Execute linux command through PHP

Question: I am using the tool for language analysis called Freeling. For language identification I use the analyzer command in the Linux console:
analyzer -f /usr/share/freeling/config/ident.cfg --outlv ident --fidn /usr/share/freeling/common/lang_ident/ident.dat

When I execute this command, its wait for the text entries (sentences) and determine what language they are in.
When I write a line of text in Spanish: "la casa es azul" and I press the enter key returns ES which means that it is written in Spanish. If I write "the house is blue" it returns EN, for the English language. To interrupt its execution press Ctrl + C.
When I execute this command in the Linux console the first sentence takes some time to respond and the other times responds quickly.
I use this code to execute this php command but it takes many seconds to return the result:
<?php
$cmd = "analyzer -f /usr/share/freeling/config/ident.cfg --outlv ident --fidn /usr/share/freeling/common/lang_ident/ident.dat";

$descriptorspec = array(
    0 => array("pipe", "r"),
    1 => array("pipe", "w"),
    2 => array("pipe", "w"),
);

$process = proc_open($cmd, $descriptorspec, $pipes);

$oracion[0]="we are the word";
$oracion[1]="somos el mundo";

if (is_resource($process)) {

    fwrite($pipes[0], $oracion[0]);
    fwrite($pipes[0], $oracion[1]);
    fclose($pipes[0]);

    while($pdf_content = fgets($pipes[1]))
    {
    echo $pdf_content . "
";
    }
    fclose($pipes[1]);
    $return_value = proc_close($process);

}
?>

How can I improve the response time?
Comment: Shouldn't you at least send a newline with each sentence? And read the language response right after each? (Instead of senting two sentences first. Isn't that how it works on the command line?)
Comment: Try profiling execution or at least print time difference on each significant line to know where the bottleneck is.
Comment: Mario, you are right in what he says of the new line (\n) at the end of the sentence. I already did it and it continues slow.
I also tried to send the senetnces and then read the result and the execution is still very slow.
Answer: When you run the program, it needs to load the statistical models for all languages. That's why the first sentence takes longer.
The "analyzer" program provided with FreeLing is just a demo. The best way to use the library is to write your own program, as shown in FreLing tutorial  https://talp-upc.gitbooks.io/freeling-tutorial/content/
If you want to call FreeLing from PHP, there is no API, so you should probably resort to "server mode", where freeling is loaded once, and then it will accept requests.
You'll find more information in FreeLing user manual https://talp-upc.gitbooks.io/freeling-4-1-user-manual/content/
Comment: The first thing I tried was to execute the language identification in the server mode.

I tried with the configuration file of the Spanish language

analyzer -f /usr/share/freeling/config/es.cfg --outlv ident --fidn /usr/share/freeling/common/lang_ident/ident.dat --server --port 12345

when I query the server with:

analyzer_client 12345 <texto.txt

the result is:

Server not ready?
Comment: If I tried with the language identification configuration file:

analyzer -f /usr/share/freeling/config/ident.cfg --outlv ident --fidn /usr/share/freeling/common/lang_ident/ident.dat --server --port 12345

analyzer_client 12345 <texto.txt

The result is always:

Server not ready?
Comment: Uhm you are right, there seems to be a bug in the analyzer that causes that the server does not work for lang ident.
Comment: I just fixed the bug.  If you download the file src/main/sample_analyzer/main.cc from gitHub and rebuild freeling, you'll have a server working for lang_ident.

You were lucky I checked SO just the day after you posted this. If you post this kind of questions in FreeLing forum, I will be able to answer sooner.
Comment: Thank you very much for your response!!! I will try what it says.
About a week ago, try to subscribe to the freeling forum. After filling out the form I received the message that will await the approval of my request. I did not receive anything in my email .
Comment: Today I tried again to subscribe to the forum with the same name username and email and it gives me the error that has already been used. Then I receive for the first time in my mail:
Thank you for registering at FreeLing Home Page. Your application for an account is currently pending approval. Once it has been approved, you will receive another e-mail containing information about how to log in, set your password, and other details.
Comment: I hope that another email arrives with the approval. I would like very much to be able to write any questions directly in the freeling forum.
Comment: I just approved your registration. You should be getting the email now.
Comment: After downloading the files: main.cc and analyzer_client.cc and compiling the freeling works perfectly well. Thank you very much Lluis Padro !!

Execute linux command through PHP


Which interface do I have to implement for an item collection

Question: Class: Episode with properties string name, uint orderNumber and timespan length.
Class: TVserie with episodes[] property.

How do I make something like this:
TVseries breakingBad = new TVseries();
breakingBad.episodes.add(511, "Confessions", 30.00);

Which Interface provides the 'add' and other collection functionality to my custom classes?
==============================
Edit: thanks! I changed it to:
List<Episode> breakingBadSeason5 = new List<Episode>();
Episode episode = new Episode();
episode.Name = "confessions";
breakingBadSeason5.Add(episode);

Comment: 1) `add` should be uppercase 2) See [`ICollection.Add` Method](http://msdn.microsoft.com/en-us/library/63ywd54z.aspx) on MSDN
Comment: `uint` is not in the CLS; use `int` or `long`. Or consider using a string for an order number. It's not like you're going to be doing math on it.
Answer: You don't want an Episodes[] property - since arrays are non resizable.
Use a List<Episodes> instead. Then you can add all you like.
To answer your question however, the interface is ICollection<T>
Full answer:
public class TVSerie
{
public List<Episode> Episodes{get;set;}

public TVSerie ()
{
   this.Episodes = new List<Episode>
}

}

TVserie breakingBad = new TVserie();
Episode episode = new Episode();
episode.Foo = "Foo";
episode.Bar = "Bar";
breakingBad.Episodes.Add(episode);

Comment: Arrays are *not resizable* is I think what you meant to say.
Comment: Your link is to `IList`, not to `ICollection`, and I think you meant `ICollection`.
Comment: Ah, SO filtered out the triangular brackets because they look like html markup. Better now.


How to calculate the average Fivestar rating correctly?

Question: The anonymous visitors and registered users on my website can rate nodes through a comment with a Fivestar field. I display the average rating on the node's page. While testing this mechanism, I found out that the average isn't calculated correctly when multiple anonymous users vote with a comment. I suspect that only the last vote of a certain uid is taken into account: since all anonymous users have a uid equal to 0 - even if their name in the comment is different - they are considered as the same person.
In order to solve this problem, I did some research to how Fivestar calculates averages. All comments and corresponding votes of anonymous users are stored seperately in the database, so I can certainly use all the available information. I think that I also located the function in fivestar.module (lines 45-59) that calculates the average:
function fivestar_microdata_suggestions() {
  $mappings = array();

  // Add the review mapping for Schema.org
  $mappings['fields']['fivestar']['schema.org'] = array(
    '#itemprop' => array('aggregateRating'),
    '#is_item' => TRUE,
    '#itemtype' => array('http://schema.org/AggregateRating'),
    'average_rating' => array(
      '#itemprop' => array('ratingValue'),
    ),
    'rating_count' => array(
      '#itemprop' => array('ratingCount'),
    ),
  );

  return $mappings;
}

My situation is as follows: I use the average rating of a node in Rules and Views too, so I'm looking for an easy solution. Surely, I expect that I can calculate the correct average with Views or Computed Field, but implementing the usage of this average elsewhere could require quite a lot of adaptations.
Therefore, I would first like to ask you whether you have faced this problem as well. If so, how did you solve it? Is it possible to somehow "overwrite" the way Fivestar calculates averages programatically? I'm not familiar with how one uses schema.org or what information that website provides...
Answer: According to me, the insufficient support for anonymous voting is due to an underdeveloped Voting API (see my comment on this issue on drupal.org). Since I am not a professional programmer, I am not able to solve this matter on my own, so I looked for a workaround, using the Rules, Views and Computed Field modules. These are the main steps to solve the problem:

Create a comment View with all the comments on a node which have a non-zero voting field. Compute the average vote with aggregation.
Add a new computed field for nodes, which stores the result of the previously created View. The safest option is to add the code in a custom module (see the module's documentation).
In order to update the computed field from step 2, it is necessary to save the corresponding node again. To do that, I created a simple Rule which launches after a comment is edited or deleted.
Additionaly, if you want users to be allowed to vote only once, you can create a node Flag Reacted and Rules which (un)flag a node when (a comment is deleted) it receives a comment. Next, use HOOK_form_comment_form_alter() in your custom module to hide the voting field in the comment form when the current user has already flagged the actual node with Reacted.


Create content programmatically

Question: In Drupal 8, how can I create content programmatically ?
From the "Drupal 8" administration, I created a new type "House" (contain a description, an image, a reference field to users ...). How can I create a entity type "House" from a custom module ?
In my custom module, I have a form file (contain a class who extends FormBase). In the submit callback, I want create a new "house" and set values and save the new Entity.
I don't find examples on the web, in core...
Comment: Your second question "How can I create a entity type 'House'?" is a little confusing. I think the question is "How can I create a node of the node type "House" from a custom module?" The ambiguity stems from the use of "entity type" which has a very specific meaning in Drupal and the question could be "How can I create a custom entity type called 'House' from a custom module?" or "How can I create a custom entity which uses the bundle 'House'"?
Answer: The following code creates a node in Drupal 8.
$data = [
  'type' => 'article',
  'title' => 'My new title',
  'uid' => 1
];
$node = Drupal::entityTypeManager()
  ->getStorage('node')
  ->create($data);
$node->save();

For testing code snippets like this, drush core-cli works great.
Comment: Before the save, with the entityManager, is it possible to know for each field : what type of data must be set ? (text for text field, fid for file etc...)
Comment: The only way I know at the moment is to use another deprecated method, EntityManager::getDefinitions(), but I think if you instantiate an EntityDataDefinition via the static create method you can call getPropertyDefinitions(). Both will return definitions for each property such as title or a field.

There is also the getFieldStorageDefinitions() which returns the same thing, but from storage entity (see getStorage('node') above). However this may not be available for non-SQL drivers.
Answer: As of Drupal 8 nodes are now treated as entities. You can simple create a node by the following code
$new_page_values = array();
$new_page_values['type'] = 'my_content_type';
$new_page_values['title'] = $form_state['values']['page_title'];
$new_page_values['path'] = $new_page_path;

$new_page = entity_create('node', $new_page_values);
$new_page->save();

Comment: entity_create() is a deprecated method that we should avoid using. Injecting the EntityManager into the Form class or using \Drupal::entityManager are the standard ways of managing entities.

Create content programmatically


Copy multiple csv files to multiple sheets of an excel using azure data factory

Question: I am trying to copy my CSV files test1.csv and test2.csv to a single excel workbook in multiple sheets means sheet1 should have data from test1.csv and sheet2 data should have data from test2.csv.
As excel is not supported as sink so I am not able to do this . Also if I am going through binary option then I am not able to use sheet option.
Answer: Unfortunately Excel as a Sink functionality is yet not available in ADF.
And Binary dataset is used when you want to move a file as is without changing its properties  (you cannot use it for file changes)
In order for you to achieve your use case, you would have to write your won custom logic via databricks, batch ,Azure function etc


Obter próximo registro em um foreach agrupado

Question: Como eu poderia estar selecionando o próximo registro dentro de um foreach agrupado antes de ele terminar, sem avançar nesse loop?
O ponto aonde penso que poderia estar obtendo essa informação é onde está escrito OBTER O PRÓXIMO ID DESSE FOREACH no código abaixo:
decimal? valor = 0;
@foreach (var item in Model.Lista.GroupBy(d => d.Nome)
                              .Select(
                               g => new
                               {
                                 key = g.Key,
                                 Id = g.First().Id,
                                 NomeFantasia = g.First().NomeFantasia,
                                 ValorTotal = g.Sum(s => s.ValorTotal) }))
{

     Id
     Nome
     Valor

   valor += item.Valor;

   <!- **OBTER O PRÓXIMO ID DESSE FOREACH** -->

}

     @Valor

Comment: Não sei se entendi o que deseja, mas no fim do laço virá o próximo `id`. VoCê quer o próximo antes de terminar? Não seria melhor colocar o LINQ no *controller*, na *view* deveria ter só código estritamente necessário para gerar a *view*, esse código de LINQ é regras de sistema, ou mesmo eu diria regra de negócio, que deveria estar no *model*.
Comment: Exato. eu gostaria de obter o próximo antes de terminar. sim. concordo e deve o LINQ estar no controller, porém surgiu um problema e tive que implementar assim.
Answer: Você não pode usar o for each quando quer controlar o índice, por isso existe o for:
var valor = 0M;
@foreach (var i = 0; i < model.Count(); i++) {

        Id
        Nome
        Valor

    valor += model[i].Valor;
    var proximoID = model[i + 1].Id;
}

Coloquei no GitHub para referência futura.
Comment: qual o tipo desse model ? setei o model pra List<>. porém não tá vindo o length :
Comment: ao invés de utilizar o model.length, usei o model.Count(); ai funcionou. Muito Obrigado.
Comment: É o que você fez eu só evitei de colocar aí, e eu errei nisso mesmo vou consertar :)
Answer: Você pode usar um contador para ser o índice das iterações e usar o valor i+1 para acessar a sua lista.
@{int i = 0;}
@foreach(...)
{
    @i+1

    i++;
}

Edit:
var lista = Model.Lista.GroupBy(d => d.Nome)
                          .Select(
                           g => new
                           {
                             key = g.Key,
                             Id = g.First().Id,
                             NomeFantasia = g.First().NomeFantasia,
                             ValorTotal = g.Sum(s => s.ValorTotal) });

@{decimal? valor = 0;int i = 0;}
@foreach (var item in )
{

     Id
     Nome
     Valor

   valor += item.Valor;

   <!- **OBTER O PRÓXIMO ID DESSE FOREACH** -->
   lista[i++].Id
}

Comment: não é isso não. eu gostaria de obter o próximo antes de terminar o foreach
Comment: Você tem o índice atual, o proxímo elemento vai ser o Lista[i+1] ... Sendo que `Lista` é a variavel que você vai atribuir o seu `GroupBy` e depois da rforeach nessa mesma variável. Lamentável o downvote.


how to show that integral depending on a parameter are continuously differentiable

Question: I'm trying to solve this exercise
Let $f:[0,1]\to \mathbb{R} \space$ an integrable function, show:
$$g(z):=\int_{0}^1\frac{f(x)}{x-z}dx$$
is a continuous differentiable function on $\mathbb R \backslash[0,1]$.
This is what I've done: we have seen two theorems in class. One allows me to see whether an integral is differentiable and calculate its derivative, while the other one allows me to see whether the integral is continuous (If you need them I can post them). Therefore I've decided to check first whether the integral was differentiable and after that whether the derivative of the integral was continuous. To check whether the integral is differentiable I've to check 1) the function inside the integral is in $L^1$, 2) that she is differentiable with derivative $\frac {\delta f(x,z)}{\delta z}$, where $f(x,z):=\frac{f(x)}{x-z}$. 3) I have to check whether the derivative has a dominating function. Here are my calculation:
1) I was unsure about this point. I've considered the fact that $z \in (-\infty,\epsilon) \cup (1+\epsilon, +\infty)$ where $\epsilon \gt0$ and that $x \in [0,1]$ to point out that the denominator must be bounded by some constant $C\gt0$ (is this true? Can I do it?). If I do like this I get that the denominator is never 0 and this implies that the function $\frac{f(x)}{x-z}$ is integrable.
2)I've calculated the derivative (since the derivative exist by the previous point at every point z)
$$\frac {\delta f(x,z)}{\delta z}= \frac {\delta}{\delta z} \frac{f(x)}{x-z}=\frac {f(x)}{(x-z)^2}$$
3) by doing the same reasoning as in 1) I've thought that the denominator can't vanish and hence there exist a dominating function which is in $L^1$ The derivative of g(z) will be
$$g(z)'= \int_{0}^1 \frac {f(x)}{(x-z)^2}dx$$
Now what I've done is to check that this function is continuous on $\mathbb {R}\backslash [0,1]$ (I have to check 1') the function inside the integrale is measurable, 2') she is continuous for x fixed and 3') there exist a dominating function of the function inside the integrale)
1) the function $\frac {f(x)}{(x-z)^2}$is measurable since $f(x)$ measurable and $(x-z)^2$ measurable (since is never 0 and never $\infty$, hence is a number, hence is continuous)
2) the function is continuous since composition of continuous functions (same argument as above)
3) same argument as above with dominating function h defined as:
$$h(x) =\begin{cases}
f(x) & \text{if } (x-z)\le 1 \\
   (\frac {1}{C}+\epsilon)      & \text{if } (x-z)\lt 1
  \end{cases}$$
where $C = (x-z)$ and $\epsilon \gt 0$
Did I do everything wrong? Is there a simple way to see if an integral depending on a parameter is continuous / differentiable / continuously differentiable?
Answer: I see that you know some measure theory, because you talk about "measurable" functions. Assuming that, this is much easier. For example, first argue that
$$
       g(z)=\int_{0}^{1}\frac{f(x)}{(x-z)^{2}}dx
$$
is continuous on $\mathbb{R}\setminus[0,1]$. This is where the dominated convergence theorem comes in handy. Suppose first that $a$ and $z$ are in $(0,\infty)$. Then Fubini's theorem allows you to interchange orders of integration to obtain:
$$
\begin{align}
     \int_{a}^{z}g(z')dz'
    & =\int_{a}^{z}\left(\int_{0}^{1}\frac{f(x)}{(x-z')^{2}}dx\right)\,dz'\\
    & =\int_{0}^{1}f(x)\left(\int_{a}^{z}\frac{1}{(x-z')^{2}}\,dz'\right)\,dx \\
    & =\int_{0}^{1}\frac{f(x)}{x-z}dx-\int_{0}^{1}\frac{f(x)}{x-a}\,dx.
\end{align}
$$
The left side is a continuously differentible function of $z\in(0,\infty)$ because $g$ was argued to be continuous. So the right side must be continuously differentiable in $z$ (and you don't have to check). Furthermore, the derivative of the left side with respect to $z$ is $g$ because $g$ is continuous. Therefore,
$$
               g(z) = \frac{d}{dz}\int_{0}^{1}\frac{f(x)}{x-z}\,dx,
$$
which is what you wanted to show.
Comment: @Ale: Your proof of direct differentiability takes some work because of having to find uniform bounds on the fractions leading to the partial derivatives. You can avoid that work by starting with what you know to be the derivative then integrating instead. You only have to demonstrate continuity for one function, which is an easier problem when it comes to bounding expressions.
Comment: The point is exactly this: how can you say that you can apply Fubini? The function is not positive, hence she has to be in $L^1$ fi you want to apply Fubini, but I'm not shure if the proof that I made allows me to say that $f \in L^1$. If my proof is wrong then how can I find a dominating function of $f(x,z)$, respectively $\frac {\delta}{\delta z} \frac {f(x)}{(x-z)^2}$?
Comment: @Ale: Integrable normally means $L^{1}$ (i.e., absolutely integrable.) You can apply Fubini's theorem because you're integrating over a region where the denominator is non-zero. That is, if $f$ is measurable, then $f(x)/(x-z')^{2}$ is jointly measurable and absolutely integrable on $(x,z') \in [0,1]\times [a,x]$ (or $[0,1]\times [x,a]$ depending on $a < x$ or $x \le a$.)


Cant figure out how to implement a 3 strike feature in Javascript game

Question: I need to allow the user to make 2 mistakes before they lose the game. I need to:
-Create a global variable to track the number of mistakes
-Initialize that variable during startGame
-Edit the guess function so that it updates the mistake counter when the user makes and mistake, and adds a check of that variable before calling the loseGame function
Im having trouble implementing this into the JS file. How can I do it?
JS File:
const cluePauseTime = 333; //how long to pause in between clues
const nextClueWaitTime = 1000; //how long to wait before starting playback of the clue sequence

//Global variables
var clueHoldTime = 200; //how long to hold each clue's light/sound
// var pattern = [2, 3, 1, 4, 6, 1, 2, 4, 3, 5];
var pattern = [];
var clueLength = 10;
///////////////////////////////
var progress = 0;
var gamePlaying = false;
var tonePlaying = false;
var volume = 0.5;
var guessCounter = 0;

function startGame() {
  progress = 0;

  pattern = []; // reset so array doesn't get longer then 10 if we restart game
  for (var i = 0; i < clueLength; i++) {
    pattern.push(getRandomInt(5));
  }
  console.log("pattern: " + pattern);

  gamePlaying = true;

  document.getElementById("startBtn").classList.add("hidden");
  document.getElementById("stopBtn").classList.remove("hidden");

  playClueSequence();
}

function stopGame() {
  gamePlaying = false;

  document.getElementById("startBtn").classList.remove("hidden");
  document.getElementById("stopBtn").classList.add("hidden");
}

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max) + 1);
}

function lightButton(btn) {
  document.getElementById("button" + btn).classList.add("lit");
}
function clearButton(btn) {
  document.getElementById("button" + btn).classList.remove("lit");
}

function playSingleClue(btn) {
  if (gamePlaying) {
    lightButton(btn);
    playTone(btn, clueHoldTime);
    setTimeout(clearButton, clueHoldTime, btn);
  }
}

function playClueSequence() {
  guessCounter = 0;
  let delay = nextClueWaitTime; //set delay to initial wait time
  for (let i = 0; i <= progress; i++) {
    // for each clue that is revealed so far
    console.log("play single clue: " + pattern[i] + " in " + delay + "ms");
    setTimeout(playSingleClue, delay, pattern[i]); // set a timeout to play that clue
    delay += clueHoldTime;
    delay += cluePauseTime;
  }
}

function loseGame() {
  stopGame();
  alert("Game Over. You lost.");
}
function winGame() {
  stopGame();
  alert("Yayyyyy, you win!!");
}

function guess(btn) {
  console.log("user guessed: " + btn);
  if (!gamePlaying) {
    return;
  }
  if (pattern[guessCounter] == btn) {
    if (guessCounter == progress) {
      if (progress == pattern.length - 1) {
        winGame();
      } else {
        progress++;
        playClueSequence();
      }
    } else {
      guessCounter++;
    }
    //guessCounter++;
  } else {
    loseGame();
  }
}
// Sound Synthesis Functions
const freqMap = {
  1: 261.6,
  2: 329.6,
  3: 392,
  4: 466.2,
  5: 432.8,
  6: 336.2
};
function playTone(btn, len) {
  o.frequency.value = freqMap[btn];
  g.gain.setTargetAtTime(volume, context.currentTime + 0.05, 0.025);
  tonePlaying = true;
  setTimeout(function() {
    stopTone();
  }, len);
}
function startTone(btn) {
  if (!tonePlaying) {
    o.frequency.value = freqMap[btn];
    g.gain.setTargetAtTime(volume, context.currentTime + 0.05, 0.025);
    tonePlaying = true;
  }
}
function stopTone() {
  g.gain.setTargetAtTime(0, context.currentTime + 0.05, 0.025);
  tonePlaying = false;
}

//Page Initialization
// Init Sound Synthesizer
var context = new AudioContext();
var o = context.createOscillator();
var g = context.createGain();
g.connect(context.destination);
g.gain.setValueAtTime(0, context.currentTime);
o.connect(g);
o.start(0);

HTML:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <title>Hello!</title>

    <link rel="stylesheet" href="/style.css" />

Memory Game

      Welcome to the game that will test your memory!

    <button id="startBtn" onclick="startGame()">
      Start
    </button>
    <button id="stopBtn" class="hidden" onclick="stopGame()">
      Stop
    </button>

      <button
        id="button1"
        onclick="guess(1)"
        onmousedown="startTone(1)"
        onmouseup="stopTone()"
      ></button>
      <button
        id="button2"
        onclick="guess(2)"
        onmousedown="startTone(2)"
        onmouseup="stopTone()"
      ></button>
      <button
        id="button3"
        onclick="guess(3)"
        onmousedown="startTone(3)"
        onmouseup="stopTone()"
      ></button>
      <button
        id="button4"
        onclick="guess(4)"
        onmousedown="startTone(4)"
        onmouseup="stopTone()"
      ></button>
      <button
        id="button5"
        onclick="guess(5)"
        onmousedown="startTone(5)"
        onmouseup="stopTone()"
      ></button>
      <button
        id="button6"
        onclick="guess(6)"
        onmousedown="startTone(6)"
        onmouseup="stopTone()"
      ></button>

CSS:
body {
  font-family: helvetica, arial, sans-serif;
  margin: 2em;
  background-color: slategrey;
  color: white;
}

h1 {
  font-family: verdana, arial, sans-serif;
  color: yellow;
}

button {
  padding: 15px;
  border-radius: 15px;
}

#gameButtonArea > button {
  width: 200px;
  height: 200px;
  margin: 2px;
}

.hidden {
  display: none;
}

#button1 {
  background: lightgreen;
}
#button1:active,
#button1.lit {
  background: green;
}

#button2 {
  background: lightblue;
}
#button2:active,
#button2.lit {
  background: blue;
}

#button3 {
  background: pink;
}
#button3:active,
#button3.lit {
  background: red;
}

#button4 {
  background: lightyellow;
}
#button4:active,
#button4.lit {
  background: yellow;
}

#button5 {
  background: lightgray;
}
#button5:active,
#button5.lit {
  background: black;
}

#button6 {
  background: white;
}
#button6:active,
#button6.lit {
  background: purple;
}

Comment: What is your actual question/problem? You've told us what you need, but not what you are having trouble with.
Answer:
Add a variable let lostCount = 0;.

Change guess else block to:

else {
    if (lostCount < 2) lostCount++;
    else loseGame();
 }

const cluePauseTime = 333; //how long to pause in between clues
const nextClueWaitTime = 1000; //how long to wait before starting playback of the clue sequence

//Global variables
var clueHoldTime = 200; //how long to hold each clue's light/sound
// var pattern = [2, 3, 1, 4, 6, 1, 2, 4, 3, 5];
var pattern = [];
var clueLength = 10;
///////////////////////////////
var progress = 0;
var gamePlaying = false;
var tonePlaying = false;
var volume = 0.5;
var guessCounter = 0;

let lostCount = 0;

function startGame() {
  progress = 0;

  pattern = []; // reset so array doesn't get longer then 10 if we restart game
  for (var i = 0; i < clueLength; i++) {
    pattern.push(getRandomInt(5));
  }
  console.log("pattern: " + pattern);

  gamePlaying = true;

  document.getElementById("startBtn").classList.add("hidden");
  document.getElementById("stopBtn").classList.remove("hidden");

  playClueSequence();
}

function stopGame() {
  gamePlaying = false;

  document.getElementById("startBtn").classList.remove("hidden");
  document.getElementById("stopBtn").classList.add("hidden");
}

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max) + 1);
}

function lightButton(btn) {
  document.getElementById("button" + btn).classList.add("lit");
}
function clearButton(btn) {
  document.getElementById("button" + btn).classList.remove("lit");
}

function playSingleClue(btn) {
  if (gamePlaying) {
    lightButton(btn);
    playTone(btn, clueHoldTime);
    setTimeout(clearButton, clueHoldTime, btn);
  }
}

function playClueSequence() {
  guessCounter = 0;
  let delay = nextClueWaitTime; //set delay to initial wait time
  for (let i = 0; i <= progress; i++) {
    // for each clue that is revealed so far
    console.log("play single clue: " + pattern[i] + " in " + delay + "ms");
    setTimeout(playSingleClue, delay, pattern[i]); // set a timeout to play that clue
    delay += clueHoldTime;
    delay += cluePauseTime;
  }
}

function loseGame() {
  stopGame();
  alert("Game Over. You lost.");
}
function winGame() {
  stopGame();
  alert("Yayyyyy, you win!!");
}

function guess(btn) {
  console.log("user guessed: " + btn);
  if (!gamePlaying) {
    return;
  }
  if (pattern[guessCounter] == btn) {
    if (guessCounter == progress) {
      if (progress == pattern.length - 1) {
        winGame();
      } else {
        progress++;
        playClueSequence();
      }
    } else {
      guessCounter++;
    }
    //guessCounter++;
  } else {
    if (lostCount < 2) lostCount++;
    else loseGame();
  }
}
// Sound Synthesis Functions
const freqMap = {
  1: 261.6,
  2: 329.6,
  3: 392,
  4: 466.2,
  5: 432.8,
  6: 336.2,
};
function playTone(btn, len) {
  o.frequency.value = freqMap[btn];
  g.gain.setTargetAtTime(volume, context.currentTime + 0.05, 0.025);
  tonePlaying = true;
  setTimeout(function () {
    stopTone();
  }, len);
}
function startTone(btn) {
  if (!tonePlaying) {
    o.frequency.value = freqMap[btn];
    g.gain.setTargetAtTime(volume, context.currentTime + 0.05, 0.025);
    tonePlaying = true;
  }
}
function stopTone() {
  g.gain.setTargetAtTime(0, context.currentTime + 0.05, 0.025);
  tonePlaying = false;
}

//Page Initialization
// Init Sound Synthesizer
var context = new AudioContext();
var o = context.createOscillator();
var g = context.createGain();
g.connect(context.destination);
g.gain.setValueAtTime(0, context.currentTime);
o.connect(g);
o.start(0);

Comment: I understand what you did but when incorporating it into the code, it works the first round but after pressing start multiple times after for multiple rounds, the game doesn't use the 2 strikes.
Comment: Are you resetting `lostCount` inside the function that restarts the game?


Autolayout invalid related to hidden navigationbar in xib

Question: I am working on an problem related to navigation bar in xib file. The problem is as follows:
I add a xib file, and manually put a UINavigationBar on top of it, and use constraints to make it stays on top of the screen. Then I add a UILabel below it, and also use constraints to make it just below the navigation bar. That is, let label.top equals navigationbar.bottom. Then I need to add a fullscreen function. I add a button and after pressing it, I hide the navigation bar by code like this:
self.navbar.hidden = YES;

The navbar is hidden, but the label is somehow still keeping its position, and doesn't move to the top of the screen, which is what I expected to see.
So the question is:

Is this effect normal? Because now the navbar is hidden, the constraints should make the label move to top.
What should I do to achieve the effect I want if it's normal/abnormal.

Thank you guys! Any idea can help!
And pardon me for my English, for it's not my native language.
Comment: hiding the nav bar won't change it's position and so still label.top equals navigationbar.bottom even on hiding it.... you can add another constraint to the top with low priority... then on hiding navbar, change it's priority so it is now larger than the priority of constraint label.top equals navigationbar.bottom
Comment: Then should I manually set the label frame to make it top? Is there any automatic way? For in real project there are more than a label below it, and moving each control is too much work to do.
Comment: You can make a view to contain all those views, that way you only need to change one constraint... For navbar you don't have any automatic way.... for labels you have sizeToFit which can be used
Comment: create outlet of topspace constraint for label and change that constraint constant value when navigationbar hidden otherwise put as it is
Answer: As you are just adding a navigation bar, not a navigation controller, so hiding wont work. You have to set height constraint on your navigation bar, and make its outlet in your controller, then where you want to hide the bar you have to set your constraint.constant to zero.
Answer: you hide the navigation bar & set the frame of lable .
if(self.navbar.hidden){

   // set frame of lable on top aas you required ..

}

hope it help you.
Comment: Is there any automatic way? There may be other controls related to it, and I don't want to move each of them, the layout maybe very complex to manually calculate.
Comment: I think no because you just hide the navigation bar but bar is still present there so you set it manually .
Answer: Create outlets of topspace constraint and height constraint for label and change that constraint constant value when navigationbar hidden  otherwise put as it is previously.
Example:
@property (strong, nonatomic) NSLayoutConstraint *lblTopSpaceConstraintValue;

@property (strong, nonatomic) NSLayoutConstraint *lblHeightConstraintValue;
and write condition

if(self.navigationBar.hidden)
{

lblTopSpaceConstraintValue.constant = 0;
lblHeightConstraintValue.constant = 0;

}

else

{

lblTopSpaceConstraintValue.constant = 10;//label topspaceconstraint value which you have given previously
lblHeightConstraintValue.constant = 21; //label height constraint value which you have given previously

}

Comment: Thank you for your advice, I know exactly what should I do!
Answer: Thank you all! I set the height constraint of the navbar to zero, and it works fine! You guys just taught me a lot about the constraints, Thanks again!
Answer: Create IBIOutlet of label top Constraint with navbar.

    IBOutlet NSLayoutConstraint* _lblTopNavBarConstraint;

and set value as per the condition.

- (IBAction) move:(id)sender
{
    _navBar.hidden = !_navBar.hidden;
    _lblTopNavBarConstraint.constant = (_navBar.hidden) ? -20 : 20;
}


Why does this form helper generate two inputs?

Question: On a model, I have attr_accessor: :email_settings.
In a view, I have:
<%= form_for some_model do |f| %>
    <%= f.fields_for :email_settings do |email_settings| %>
        <%= email_settings.label :general, _("General updates") %>
        <%= email_settings.check_box :general %>
        General site updates
    <% end %>
<% end %>

But in the HTML, this does not create one input for some_model[email_settings][general], it creates two. One hidden and one a checkbox:
General updates
<input name="user[email_settings][general]" type="hidden" value="0">
<input id="user_email_settings_general" name="user[email_settings][general]" type="checkbox" value="1">
General site updates

What's going on here? Why is there a hidden input and a checkbox for the same value, when I only want a checkbox?
Also in the controller action that the form is submitted to, I do this:
def update
    puts "email_params: #{email_params}"
end

def email_params
  params.require(:user).permit(:email_settings)
end

Which outputs:
Unpermitted parameters: email_settings
email_params: {}

Not sure how email_settings is being interpreted as "unpermitted" when I'm explicitly permitting it.
Comment: What is the output of `params.inspect` ?
Comment: I had to change `def email_params` to: `params.require(:user).permit(email_settings: [:general])`
Answer: From the browser should always send a response.
If you do not select the box, will send the hidden field to understand that something has been sent.
In this way the rails will always receive an indication that the box was selected or not.
similar answer is here: Why does the check_box form helper generate two checkboxes, one hidden?
Comment: But this doesn't work as intended because *two* values are specified instead of one, making `user[email_settings][general]` itself be interpreted as an array of `[0,1]` instead of just `0` or `1`.
Comment: Correction. The above comment of mine is wrong. But there is another issue and I will update the main post.
Comment: email_setings is an array.
Try to put in your model
`serialize :email_setings, Array`
and your controller `params.require(:user).permit!` to see if it passes


Upstart service is not killing processes on stop

Question: I have an upstart service that maintains a number of instances of workers.
pm-all-workers.conf:
start on runlevel [2345]
stop on runlevel [!2345]

env NUM_WORKERS=25

pre-start script
for i in `seq 1 $NUM_WORKERS`
  do
    start pm-worker N=$i
  done
end script

pm-worker.conf:
start on runlevel [2345]
stop on stopping pm-all-workers

instance $N
respawn
respawn limit 10 5
umask 022

exec su - someuser -c "/home/someuser/bin/worker.bin"

This has been working fine, but recently some of the worker processes keep hanging around even if the service is stopped. My understanding is upstart will send SIGTERM to the processes on stop and then after a few seconds SIGKILL, if the process is still up.
How is it possible that some processes don't get killed? I can kill the processes fine manually with pkill -9 worker.bin.
Answer: Perhaps Upstart is sending su the SIGTERM/KILL, instead of your worker.bin. Try using the setuid stanza of upstart and remove the su bit.
Comment: Good point, will try this.


What are DOM levels?

Question: I've heard DOM level 2 and DOM level 3 mentioned in previous posts.  Are these abstract constructs like the ISO OSI model which has layers 1-7 but are only loosely followed?
Comment: So they are just versions...should be called DOM versions ( If life made sense )...as levels imply some sort of abstraction and hierarchy.
Answer: DOM Levels are the versions of the specification for defining how the Document Object Model should work, similarly to how we have HTML4, HTML5, and CSS2.1 specifications.
As of 2020, the most recent spec is DOM Level 4, published in November 2015.
Additionally, there are pieces of the DOM spec that vendors can choose to implement, such as Core, HTML, and XML, as well as the event model. Depending on what is being built (a DOM parser, web browser layout engine, or javascript engine), the vendor may choose to implement some or all of the spec. Most modern web browsers implement all of the Level 3 spec.
Answer: DOM Levels are essentially versions.
DOM Level 1 defines the core elements of the Document Object Model.
DOM Level 2 extends those elements and adds events.
DOM Level 3 extends DOM lvl 2 and adds more elements and events.
Each new level of the DOM adds or changes specific sets of features. When browsers are said to be DOM Level X compliant developers can (hopefully) assume that the browser correctly handles the specified DOM api calls.
Answer: I know this question is old, but I'm adding this data for any people coming across this post.
The DOM used to be written as a set of levels. That is no longer the case.
These days it is maintained as the DOM Living Standard
See also the DOM Reference for more recent web-developer-focused information.
Source: Here
Answer: Looking for levels of DOM? (MDN reference can be found here, W3 reference also is here)
Alternatively, this could be referencing hierarchy of elements within the DOM.  e.g.

Hello, World!

 being level 1,  level 2.
Answer: According to wiki

Beginning with the publication of DOM Level 4 in 2015, the W3C creates new recommendations based on snapshots of the WHATWG standard.

DOM Level 1 provided a complete model for an entire HTML or XML document, including the means to change any portion of the document.
DOM Level 2 was published in late 2000. It introduced the getElementById function as well as an event model and support for XML namespaces and CSS.
DOM Level 3, published in April 2004, added support for XPath and keyboard event handling, as well as an interface for serializing documents as XML.
DOM Level 4 was published in 2015. It is a snapshot of the WHATWG living standard.[7]
Answer: DOM, "Document Object Model" in world wide Web W3C defines a standard for accessing documents
The W3C DOM standard is separated into 3 different parts:
Core DOM - standard model for all document types
XML DOM - standard model for XML documents
HTML DOM - standard model for HTML documents
You taking about JavaScript thus You need to know the HTML DOM.
The HTML DOM is a standard object model and programming interface for HTML. It defines:
The HTML elements as objects
The properties of all HTML elements
The methods to access all HTML elements
The events for all HTML elements
In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements that is displayed in that window (Web Page). It has various properties that refer to other objects which allow access to and modification of document or webpage content with e.g.javascript
For example: An HTML page has a button with an id="txr1".
So how will you get the "txt1" value in JavaScript?
document.getElementById('txt1');
In above example, I am getting element with id="btn1″ in javascript with the help of document element which is a DOM element.
There are many other DOM elements which you can use in JavaScript to get and change elements of an HTML document.

What are DOM levels?


Infinite-dimensional translation-invariant measure

Question: Why is there no translation-invariant measure on an infinite-dimensional Euclidean space? Is there a reasonably short, insightful proof?
I am interested in an infinite-dimensional space with a definite inner product but not necessarily complete in the corresponding topology. Thus it need not be a Hilbert space.
Comment: And the same proof works.  Any ball of your inner-product space contains infinitely many disjoint balls of the same (smaller) radius which are all translates of each other.
Comment: @Henning: I think so. Nate's answer works just as well in any Hausdorff (separable) topological vector space as he points out in an exercise immediately following theorem 1.1 in his notes.
Comment: @t.b.: Okay -- but the theorem _as quoted in the answer_ did include an explicit requirement that it was a Banach space. I see that the question is tagged (hilbert-spaces), but that tag didn't come from the OP.
Comment: See also problem 18 in Halmos's [Hilbert space problem book](http://books.google.com/books?id=S57XLkgbf0oC&pg=PA10)
Comment: Is the asserted duplicate really a duplicate? It is about Hilbert space, whereas this one might be on $\mathbb R^\omega$ (i.e. the space of functions $\mathbb N\to\mathbb R$ with _finite_ support). The answer to the existing question depends on the space being Banach, which $\mathbb R^\omega$ isn't.
Comment: I am interested in an infinite-dimensional space with a definite inner product but not necessarily closed in the corresponding topology. Thus it need not be a Hilbert space.
Comment: Some remarks: [this MO answer](http://mathoverflow.net/questions/61610/measures-on-infinite-dimensional-banach-spaces/65982#65982) gives some answers in the non-Borel and non-separable cases. And stealing a link from Michael Greinecker from MO, [this paper](http://www.ams.org/journals/bull/1992-27-02/S0273-0979-1992-00328-2/S0273-0979-1992-00328-2.pdf) gives several references to the statement that "any $\sigma$-finite quasiinvariant Borel measure on a infinite dim LCTVS must be zero".
Comment: @Henning: ah, I hadn't noticed that the hilbert-space tag didn't come from the op.
Answer: The statement in the question "Why is there no translation-invariant measure on an infinite-dimensional Euclidean space?" is not correct.
(i) A counting measure defined in infinite-dimensional Euclidean space is  an example of such measure which  is translation-invariant.
(ii)There does not exist a translation-invariant Borel measure  in an infinite-dimensional Euclidean space $\ell_2$ which gets the value 1 on the unit ball.  Indeed, assume the contrary  and let $\mu$ be such a measure. let $(e_k)_{k \in N}$ be a standard basis with $||e_k||=1$ for $k \in N$. Let $B_k$ be an open ball with center at $\frac{e_k}{2}$ and with radius $r$ less than $\frac{\sqrt{2}}{4}$. Then $(B_k)_{k \in N}$ is a family of pairwise disjoint open balls with radius $r$. On the one hand, $\mu$ measure of $B_k$ must be zero because in other case the $\mu$ measure of the unit ball will be $+\infty$. On the other hand, since $\ell_2$ is separable, $\ell_2$ can be covered by countably many translations of $B_1$ which together with an invariance of $\mu$ implies that $\mu$ measure of $\ell_2$ is zero. This is a contradiction and assertion (ii) is proved.
(iii) There exists  a translation-invariant measure  on an infinite-dimensional Euclidean space $\ell_2$ which gets the value 1 on the parallelepiped $P$ defined by $P=\{x : x \in \ell_2 ~\&~ |<x,e_k>|\le \frac{1}{2^k}\}$.
Let $\lambda$ be infinite-dimensional  Lebesgue measure in $R^{\infty}$ (see, Baker R., ``Lebesgue measure" on~$\mathbb{R}^{\infty}$,Proc. Amer. Math. Soc., vol. 113, no. 4, 1991,
pp.1023--1029).  We set
$$
(\forall X)(X \in {\cal{B}}(\ell_2) \rightarrow \mu(X)=\lambda(T(X)))
$$
where ${\cal{B}}(\ell_2)$  denotes the $\sigma$-algebra of  Borel subsets of $\ell_2$
and the mapping  $T : \ell_2 \to R^{\infty} $ is defined by: $T(\sum_{k \in N}a_ke_k)=(2^{k-1}a_k)_{k \in N}$.
Then  $\mu$ satisfies all conditions participated in (iii).
P.S. There exist many interesting translation-invariant non-sigma finite Borel measures in infinite-dimensional separable Banach spaces(see, for example,  G.Pantsulaia , On generators of shy sets on  Polish topological vector spaces, New  York   J.  Math.,14 ( 2008) ,  235 – 261)


getting error callback is not a function in one condition

Question: I have two functions like this
$("body").on("click", "#btnEdit", function (e) {
    TransactionId = $(this).closest("div").find('#SearchItemID').text();

    EditorDuplicate(TransactionId);
});

$("body").on("click", "#btnDuplicate", function (e) {
    TransactionId = $(this).closest("div").find('#SearchItemID').text();

    EditorDuplicate(TransactionId);
    GetnextItemCode();
})

As you can see in my first function I am calling only the EditorDuplicate function, but in the secont one i am calling another function after excecuting of first completes.
But to load the GetnextItemCode function after EditorDuplicate function I added callback function. Now it looks like this:
$("body").on("click", "#btnTransactionEdit", function (e) {
    TransactionId = $(this).closest("div").find('#SearchItemID').text();
    EditorDuplicate(TransactionId);
});

$("body").on("click", "#btnDuplicate", function (e) {
    TransactionId = $(this).closest("div").find('#SearchItemID').text();

    EditorDuplicate(TransactionId, function () {
        GetnextItemCode();
    });

    //EditorDuplicate(TransactionId);
    //GetnextItemCode();
})

EditorDuplicate function:
function EditorDuplicate(TransactionId, callback) {

    // other codes

    callback();
}

Now clicking #btnDuplicate works well, but when clicking #btnEdit I get the error

Uncaught TypeError: callback is not a function

Why is that? and how do I correct this?
Note :
And function is still not running one after another, GetnextItemCode executed before the other completes. EditorDuplicate function got several lines of codes, where GetnextItemCode function has only few lines.
Please see the error in the snippet

// edit button
$("body").on("click", "#btnEdit", function () {
    var TransactionId = $('#SearchItemID').text();
    EditorDuplicate(TransactionId);
});

// duplicate button
$("body").on("click", "#btnDuplicate", function () {
    var TransactionId = $('#SearchItemID').text();
     EditorDuplicate(TransactionId, function () {
        GetnextItemCode();
    });
});

function EditorDuplicate(TransactionId, callback) {

    alert("EditorDuplicate");
    // other codes

    callback();
}

function GetnextItemCode(){
    alert("GetnextItemCode")
}

<input type="button" id="btnEdit" value="edit"/>
<input type="button" id="btnDuplicate" value="duplicate"/>

Search Id :
2
Comment: You can show us your HTML code, or much better give us a sample output using SO snippet
Comment: @alimbaronia please see the snippet added
Answer: In your function, you first need to check if callback is actually a function:
function EditorDuplicate(TransactionId, callback) {
    // your code

    if (typeof callback === 'function') {
      callback();
    }
}

This is because callback becomes undefined when it is not passed in this call:
EditorDuplicate(TransactionId);

And trying to call undefined will throw an error.
Answer: function EditorDuplicate(TransactionId, callback) {
    // your code
if (callback) {
  callback();
}

}


Compare fits of model to transformed and untransformed response

Question: I want to compare data that proportions among three different groups e.g.:
<code> ID Group Prop.Nitrogen
 1    A     0.89
 2    A     0.85
 3    B     0.92
 4    B     0.97
</code>
Following Wharton and Hui (doi:10.1890/10-0340.11)
 I though I'd see if these data would be better dealt with using a logit transformed.
When I look at diagnostic plots for linear models on the transformed and un-transformed data they look very similar with no obvious problems, and there are only small differences in estimated parameters. However, I'd still like to be able to say something about how well the model fits the transformed and untransformed versions of the data - I know I can't compare AIC values directly. Is there a correction and I can make to examine this? Or should I be taking a different approach?
Comment: You might want to try a Box-Cox transformation (`boxcox()` in the MASS library), although I'm not sure whether it can deal with logit transforms.
Comment: @Marius: to clarify, are you suggesting `boxcox()` on the raw data, or on the transformed data?
Comment: What about transforming the data and the fitted values to the subject-matter-relevant scale (so you will have a unified scale) and then calculating AIC for all the competing models you have? You would have to calculate AIC values manually for models that were originally fit on a different scale but I don't think this could be a problem.
Answer: My experience with transformed data suggests that the correlation improves after transformation as well as the homoscedasticity and/or normality, although they are not necessarily all optimal for any single transformation. One simple answer may be to calculate correlation coefficients between the two models and their respective data sets. One can even test for the significance of difference of correlated correlation coefficients. Tests for homoscedasticity and density function type of residuals can also offer a means to evaluate them.


How to split string from column to create long format dataframe

Question: If I have the dataframe shown below, how do I make a long format dataframe (I.e. one term per gene per row).
I guess I will have to apply or map a split(",") to the Term column, but what do I do after that?
import pandas as pd
from StringIO import StringIO

df = pd.read_table(StringIO("""Gene    Terms
Mt-nd1  GO:0005739,GO:0005743,GO:0016021,GO:0030425,GO:0043025,GO:0070469,GO:0005623,GO:0005622,GO:0005737
Madd    GO:0016021,GO:0045202,GO:0005886
Zmiz1   GO:0005654,GO:0043231
Cdca7   GO:0005622,GO:0005623,GO:0005737,GO:0005634,GO:0005654"""), sep="\s+")

Ps. the table above is simplified, the actual df will have many more columns.
Psps. In case I was unclear, I want to end up with something like:
Mt-nd1  GO:0005739
Mt-nd1  GO:0005743
Mt-nd1  GO:0016021
...
Cdca7   GO:0005634
Cdca7   GO:0005654

Answer: You can use str.split to do the splitting (instead of apply and split approach, but similar):
In [6]: splitted = df['Terms'].str.split(',', expand=True)

In [7]: splitted
Out[7]:
            0           1           2           3           4           5  \
0  GO:0005739  GO:0005743  GO:0016021  GO:0030425  GO:0043025  GO:0070469
1  GO:0016021  GO:0045202  GO:0005886         NaN         NaN         NaN
2  GO:0005654  GO:0043231         NaN         NaN         NaN         NaN
3  GO:0005622  GO:0005623  GO:0005737  GO:0005634  GO:0005654         NaN

            6           7           8
0  GO:0005623  GO:0005622  GO:0005737
1         NaN         NaN         NaN
2         NaN         NaN         NaN
3         NaN         NaN         NaN

To turn it into columns (instead of a list), you can use expand=True keyword to split, or for older pandas versions you can do df['Terms'].str.split(',').apply(pd.Series) to obtain the same.
Now, to obtain your desired output we have to stack these columns, but first merge it with the genes column to have this information in the stacked frame:
In [14]: stacked = pd.concat([df['Gene'], splitted],axis=1).set_index('Gene').stack()
In [15]: stacked
Out[15]:
Gene
Mt-nd1  0    GO:0005739
        1    GO:0005743
        2    GO:0016021
        3    GO:0030425
        4    GO:0043025
        5    GO:0070469
        6    GO:0005623
        7    GO:0005622
        8    GO:0005737
Madd    0    GO:0016021
        1    GO:0045202
        2    GO:0005886
Zmiz1   0    GO:0005654
        1    GO:0043231
Cdca7   0    GO:0005622
        1    GO:0005623
        2    GO:0005737
        3    GO:0005634
        4    GO:0005654
dtype: object

From here, we can reset the index, rename our column with terms, and drop the integer column (from the automatically generated column names) we don't need anymore:
In [19]: stacked.rename(columns={0:'Term'}).drop('level_1', axis=1)
Out[19]:
      Gene        Term
0   Mt-nd1  GO:0005739
1   Mt-nd1  GO:0005743
2   Mt-nd1  GO:0016021
3   Mt-nd1  GO:0030425
4   Mt-nd1  GO:0043025
5   Mt-nd1  GO:0070469
6   Mt-nd1  GO:0005623
7   Mt-nd1  GO:0005622
8   Mt-nd1  GO:0005737
9     Madd  GO:0016021
10    Madd  GO:0045202
11    Madd  GO:0005886
12   Zmiz1  GO:0005654
13   Zmiz1  GO:0043231
14   Cdca7  GO:0005622
15   Cdca7  GO:0005623
16   Cdca7  GO:0005737
17   Cdca7  GO:0005634
18   Cdca7  GO:0005654

How this can be combined or merged with the other columns you have, will depend on what you exactly want to do with it.
Comment: @joris In 16.2 this answer does not work! Getting `rename got an unexpected argument columns`.  It is the last command that does not work.
Comment: The fix was just `stacked.reset_index().rename(columns={0:'Term'}).drop('level_1', axis=1)` - that is, add `reset_index()` to last command!


Prove that either $a$ is even or $b$ is even?

Question: Prove that if $a$, $b$, and $c$ are all positive integers such that $a^2$ + $b^2$ = $c^2$ then $a$ or $b$ must be even.
One way I was taught to handle implications with an or statement was to prove that if the first part is false, then the second part must be true. What I mean by this is that I can prove this implication to be correct if I can show that if $a$ is odd, then $b$ must be even. My problem is that I don't have much to work with. If $a$ is odd, then I could split the proof into 2 cases, one where $c$ is odd and the other where $c$ is even. I couldn't seem to get anywhere with that though.
Comment: Have you tried assuming that both of them are odd and seeing if it leads to a contradiction? (I'm not sure it will work)
Comment: The "proof verification" tag means "Here's my proof. Is it right?" Since you don't have a proof, that doesn't apply.
Comment: My fault, sorry.
Answer: Suppose they are both odd. Then we get, for some integral $m,n$, $4m^2 + 4m + 4n^2 + 4n + 2 = c^2$. $c$ must thus be even, and hence it can be expressed as $c=2b$ for integral $b$. So we get
$4m^2 + 4m + 4n^2 + 4n + 2 = 4b^2$ for some $b$. Dividing both sides by four, we see $b^2$ is not integral, which implies $b$ is not integral. This is a contradiction.
Comment: Alternatively, $2=4b^2-4m^2-4m-4n^2-4n$ shows that $4$ divides $2$, a contradiction. This is the same proof as user218931's, but without using modular arithmetic notation/terminology explicitly.
Answer: If $a=2n+1$ and $b=2m+1$ are odd, then
$$
a^2 = 4n^2+4n+1 = 4n(n+1)+1 \equiv 1 \mod 8
$$
because either $n$ or $n+1$ must be even. Similarly, $b^2\equiv 1\mod 8$. Now
\begin{align*}
a^2 + b^2 = 4n^2+4n+1 + 4m^2+4m+1 \equiv 2 \mod 8.
\end{align*}
But $2$ is not a square modulo $8$. Hence, there exists no $c$ such that $a^2+b^2=c^2$.
Answer: The general parametrized solution to this diophantine equation is: $a = 2pq, b = p^2-q^2, c = p^2+q^2$. This shows that $a$ is even.
Comment: Showing that this parametrization is the _full_ solution is harder than solving the problem directly, I would say.
Answer: We can understand that what we want to prove is that
$ (odd)^2 + (odd)^2 $ will not equal to $(even)^2$
(Sum of odd numbers will only be even)
Perfect odd squares are in the form
$4n + 1$
Therefore the above expression (sum of two odd  square numbers) comes down to
$ 4n + 4m + 2$
It can be proven that this will never be an even pefect square which is always a multiple of 4.
If it is, then
$(4n + 4m + 2)/4 $
will be an integer, but it is not, as it becomes
$ m + n + 0.5$


What is the marginal posterior distribution?

Question: Based on this question: How to build a Bayesian regression model of a response that is a Gaussian mixture
Consider the mixture of normal,
$$y_j\sim  (N(0,\sigma_1))^{\pi}(N(0, \sigma_2))^{1-\pi}, j=1,2,3,4.$$
My question is what is the conditional distribution of $y_j|\sigma_1^2, \sigma_2^2, z$.
Comment: If I understand you correctly, then there is something wrong if H is four dimensional while Y is 100 dimensional.
Comment: @BenjaminChristoffersen Sorry, that is 100.
Answer: Note: In this simplified linear model, the OLS estimator $\hat\beta(y)$ is a sufficient statistic, meaning that the posterior on the parameters is the same given $y$ and given $\hat\beta(y)$.

Left graph is a (directed acyclic) graph representing the dependence structure in the model. Right graph is the so-called moral graph associated with it (where parents are linked). It is most useful to find conditional dependencies for building a Gibbs sampler, as a node is independent of everything else given its neighbours, i.e. parents and children. For instance, $\beta$ only depends on $y$, $z$, $X$, and $\sigma=(\sigma_1,\sigma_2)$, but not on $\pi$.
$$
\beta| z, \sigma_1, \sigma_2, y\sim f(\beta| z, \sigma_1, \sigma_2,y)\propto f(\beta| z, \sigma_1, \sigma_2)\times f(y|,\beta,X)
$$
Similarly, $z$ only depends on $\pi$, $\sigma$, and $\beta$, and not on $y$. And at last $\pi$ solely depends on $z$,$$f(\pi|z,\ldots,y)=f(\pi|z)$$
When considering the full conditional of one component of $\beta$, like $\beta_1$, the density satisfies
$$f(\beta_1|\beta_{-1},z, \sigma_1, \sigma_2, y)\sim f(\beta_1| z, \sigma_1, \sigma_2,y)\propto f(\beta| z, \sigma_1, \sigma_2,y)$$
which only depends on $z_1$ (and not $z_2,z_3,z_4$):
$$f(\beta_1|\beta_{-1},z, \sigma_1, \sigma_2, y)\sim f(\beta_1| z, \sigma_1, \sigma_2,y)\propto f(\beta_1| z_1, \sigma_1, \sigma_2)\times f(y|X,\beta)$$
Although this should be considered as a separate question, here are the details when running a full conditional Gibbs sampler on $\beta$:
At step 0, start with an arbitrary vector $\beta^{(0)}$ (for instance, the OLS $\hat\beta(y)$, and $\pi^{(0)}$, and generate $z^{(0)}$ from its full conditional distribution.
At step t, given the current state $\beta^{(t)},\sigma^{(t)},z^{(t)},\pi^{(t)}$ of the parameter, do

update $\beta_1^{(t)}$ into $\beta_1^{(t+1)}$ by simulating from
$$f(\beta_1|\beta_2^{(t)},\beta_3^{(t)},\beta_4^{(t)}, z^{(t)}, \sigma^{(t)},y)\propto f(\beta_1|z_1^{(t)}, \sigma^{(t)})\times
f(y|\beta_1,\beta_2^{(t)},\beta_3^{(t)},\beta_4^{(t)})$$
update $\beta_2^{(t)}$ into $\beta_2^{(t+1)}$ by simulating from
$$f(\beta_2|\beta_1^{(t+1)},\beta_3^{(t)},\beta_4^{(t)}, z^{(t)}, \sigma^{(t)},y)\propto f(\beta_2|z_2^{(t)}, \sigma^{(t)})\times
f(y|\beta_1^{(t+1)},\beta_2,\beta_3^{(t)},\beta_4^{(t)})$$
update $\beta_3^{(t)}$ into $\beta_3^{(t+1)}$ by simulating from
$$f(\beta_3|\beta_1^{(t+1)},\beta_2^{(t+1)},\beta_4^{(t)}, z^{(t)}, \sigma^{(t)},y)\propto f(\beta_3|z_3^{(t)}, \sigma^{(t)})\times
f(y|\beta_1^{(t+1)},\beta_2^{(t+1)},\beta_3,\beta_4^{(t)})$$
update $\beta_4^{(t)}$ into $\beta_4^{(t+1)}$ by simulating from
$$f(\beta_4|\beta_1^{(t+1)},\beta_2^{(t+1)},\beta_3^{(t+1)}, z^{(t)}, \sigma^{(t)},y)\propto f(\beta_4|z_4^{(t)}, \sigma^{(t)})\times
f(y|\beta_1^{(t+1)},\beta_2^{(t+1)},\beta_3^{(t+1)},\beta_4)$$
Comment: Thank you very much!


Julia: Passing arguments for a function into a function

Question: I was wondering if Julia has an easily already built in capability to pass arguments meant for a function in a function?
For example,
I'm working with Gadfly but I want to create a function that makes a specific plot, let's say one that does a line graph with the plots pointed already.
So for a working example
using Gadfly, Random
Random.seed!(50)
x = randn(10)
y = 10 * x .+ 2 .+ randn(10)/10
function dummy1(x, y; plotOptionsToPass...)
    plot(x = x, y = y, Geom.point, Geom.line; plotOptionsToPass...)
end

And I want to be able to pass in all different types of Gadfly plot options such as
dummy1(x, y; Theme(panel_fill = nothing))

so that it makes the dummy1 function turn into something like
plot(x = x, y = y, Geom.point, Geom.line; Theme(panel_fill = nothing))

without me having to actually prespecify all of the types of options Gadfly allows plot() to take.
Answer: Not sure what you are after, but maybe it helps to see that you can define a new function inside dummy1 and return it. The retruned fucntion will use less arguments. dummy1 becomes a drawing function 'constructor'.
function dummy1(;plotOptionsToPass...)
    function foo(x, y)
        plot(x = x, y = y, Geom.point, Geom.line; plotOptionsToPass...)
    end
    return foo
end

# create new drawing function
new_artist = dummy1(Theme(panel_fill = nothing))
# draw something
new_artist(x, y)

Comment: Let me try the functionality on desktop and get back with an update.
Comment: Hi @EPo, thanks for the answer. I tried using your syntax above and got the following error. `ERROR: MethodError: no method matching dummy1(::Theme)
Closest candidates are: dummy1(; plotOptionsToPass...) at REPL[5]:2
Stacktrace: [1] top-level scope at none:0`. Maybe to clarify, I am just trying to create a function that makes a scatter plot with lines connecting the dots, but also lets me specify any other plot functions/arguments that `plot()` takes in Gadfly.


Perform object recognition based on colour

Question: I have captured each frame of a video .Then I have used background subtraction to eliminate the background .Now I have the people with their bounding boxes.I have to compare the colour features of this person with the features of the same person in another video. The person will be wearing the same dress in every video.
I am developing this in opencv 2.4 and python 2.7
Here it the background subtraction code I have used:
<code>import numpy as np
import cv2
cap = cv2.VideoCapture('test.mp4')
fgbg = cv2.BackgroundSubtractorMOG()
j=0
count = int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT))
while j<count:
    ret, frame = cap.read()
    cmask = fgbg.apply(frame)
    fgmask = cmask.copy()
    floodfill =cmask.copy()

    (cnts, _) = cv2.findContours(cmask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cnts = sorted(cnts, key = cv2.contourArea, reverse = True)
    if(len(cnts)!=0):
        h, w = floodfill.shape[:2]
        mask = np.zeros((h+2, w+2), np.uint8)
        cv2.floodFill(floodfill, mask, (0,0), 255)
        floodfill_inv = cv2.bitwise_not(floodfill)
        fgmask=fgmask|floodfill_inv

    # screenCnt = None
    print "K="+str(j)
    j+=1
    for cnt in cnts:
        x,y,w,h = cv2.boundingRect(cnt)
        cv2.rectangle(fgmask,(x,y),(x+w,y+h),255,4)
    if(len(cnts)!=0):
        cv2.imshow('frame',fgmask)

    k = cv2.waitKey(30) & 0xff

    if k == 27:
        break
cap.release()
cv2.destroyAllWindows()
</code>
Is there any method for comparing objects based on the colour?
I have not used face recognition because I don't have pictures of the people in the video
Any help would be appreciated
Comment: Have you seen [this](http://docs.opencv.org/2.4/modules/features2d/doc/common_interfaces_of_descriptor_extractors.html#opponentcolordescriptorextractor)?
Comment: Additionally, if you have the color from one frame and you want to match that with same color in another frame, isn't it straight forward?
Answer: What you want is Swain and Ballard's Color Indexing technique.
Basically, you create a color histogram to represent the object/person. Using the information in the histogram, you can create a probability mass function of another image that represents the probability of an object being at a certain point.
Here's a python/opencv tutorial that explains how to do the back projection.
The peak of the probability mass function is the most likely location of your object/person.
You probably may not need to do the back projection if you are just trying to compare two known objects.  Here's a previous question about ways to compare color histograms that will give you some options.
If your video has significant lighting changes, you probably won't get the results you need with this technique alone, but someone else came up with a way to introduce color constancy to the method. Instead of using a histogram of colors, you use a histogram of color ratios.
Comment: I think histogram intersection is the best choice for comparing the histograms. It's both simple and effective for this case. See http://blog.datadive.net/histogram-intersection-for-change-detection/
Answer: You could try to extract the 'average' color of an image, since the dress will have a large impact on the color shade of the entire image (since you extracted it, it makes up most of the image).
However, depending on lighting conditions and the way you extract the persons from the image, the values can change from time to time. It's therefore most likely not the most secure method, especially not when these persons have similar colors of clothing. But you could give it a try.
You can use the following code to extract the average color of an image (you can apply this to the extracted image you have):
<code># Get the average color values of each row in an array
average_row_color = numpy.average(input_img, axis=0)
# Now get the average of that array to get the overall average image color
average_image_color = numpy.average(average_row_color, axis=0)
# Convert it to uint8 to get your 3 channel color values, like [100, 150, 200]
average_color_uint8 = numpy.uint8(average_image_color)
</code>
You can then compare your results and see how close they are to colors you found in other videos and match the colors that are closest.
Answer: I'd consider to match using template matching on color images.
Another option, if applicable, is to extract and match features using feature based methods (SIFT, ect). best option.
Another option (sort of a shortcut) would be to calculate the histogram between the blobs, find the most common color, than match the colors on HSV color space.
Good luck


External load balancer solutions between EC2 and Rackspace

Question: I have a website primarily hosted on EC2 with the backends (MySql) replicated async to a Rackspace store. I am also planning to have a suite of web server, cache & db on standby at Rackspace in the eventuality that Amazon has an outage.
With this is perspective, is there a solution that will allow me to switch between EC2 and Rackspace depending on availability?
Answer: We use dnsmadeeasy for exact same thing. DNS monitoring and failover would help you with this. For mysql, you can setup 2 way or one way replication; two-way replication is better as you don't have to worry about replicating data back when you switch back. And everything can be completely automated failrly easily.
Comment: DNSMadeeasy is the easiest  and very cost effective option. Link: http://www.dnsmadeeasy.com/enterprise-dns/dns-failover/
Answer: If you're just looking to have it on "stand-by" I suppose you can accomplish this well enough (depending on what your uptime requirements are) using DNS.  Simply point the domain to a new IP when the change is required.  But I know this is manual.
Barring that, enterprise level load balancers exist that can do the same, I've seen some in a few client environments, but never for failover, mostly it's geographical or performance-based decisions per user on which datacenter will service said user.  That said, I know you can configure load balancing per host to work in many different ways on most devices, including active/passive (failover) so I'm sure the same can be done but in terms of what site instead of what host.  I'm purposely avoiding recommending any one/some brands due to potential perception of conflict of interest at work.
An alternative would be to use a CDN, if the budget exists for it.  I can't speak for others, but I've worked with Akamai for joint clients and they have a site failover service which you may find useful.  Check out http://www.akamai.com/html/technology/products/site_failover.html for an example
Answer: You can prop up another box using Heartbeat as a load balancer. If you really want you could host redundant heartbeat boxes on Amazon and Rackspace, that would ensure that your load balancer is up even if one of the services goes down. You can easily configure Heartbeat to direct all of the traffic to Amazon unless the servers there are down.
Answer: You would need a combination of a ping service (or whatever you need to judge outage) and then an short lived DNS entries and a API to change DNS.


Polynomial of Degree $n$ over a field has at most $n$ zeros, counting multiplicity

Question: Proof : We proceed by induction on $n$
If $f$ is constant, clearly $f$ has no zero.
Suppose for all $f$ with degree $n-1$ holds the statement
Let $g$ with degree $n$ and $a$ is a zero of $g$
then $g(x)=(x-a)^kq(x)$ and $q(a)$ is not zero

From now, my book add some logic , but I don't understand why author add this part to show the statement. Subsequent proof is as follow : If $g$ has no zeros other than $a$, we are done. On the other hand, if $b$ is not equal to $a$ and $b$ is a zero of $f$, then $0=g(b)=(b-a)^kq(b)$, so that $b$ is also a zero of $q(x)$ with multiplicity as it has for $f(x)$.

Since, deg $g$=$k$+deg $q$, deg $q$ = $n-k$
By induction hypothesis, $q$ has at most $n-k$ zeros ,counting multiplicity
Thus $g$ has at most $k+n-k=n$ zeros, considering multiplicity.
Answer: Hint: Given $f(x)\in{\Bbb K}[x]$ and $a\in{\Bbb K}$. Then
$$f(a) = 0 \Longleftrightarrow \exists g\in{\Bbb K}[x]: f(x) = g(x) \cdot (x-a).$$
Prove this by using the usual division algorithm.
Iterating this gives
$$f(x) = (x-a_1)^{k_1}\cdots (x-a_m)^{k_m} g(x)$$
where $a_1,\ldots,a_m\in{\Bbb K}$, $k_1,\ldots,k_m\geq 1$, and $g(x)$ has no root in ${\Bbb K}$.
Comment: Based on your hint, my curious part shows that $q(x)$ has at least one zeros in given field. If $q(x)$ doesn't have zero in given field, we can't apply induction hypothesis. right??
Comment: For instance, $x^2+1$ has no zero in ${\Bbb R}$. In my last equation, $f=g$.


Determine compression % of gzip file?

Question: Is there an easy way to determine the compression % of a .gz file?
Comment: http://superuser.com/questions/139253/what-is-the-maxiumum-compression-ratio-for-gzip-algorythm
Comment: Ah crap didnt mean to post this on SF. Migrate or close if necessary. Thanks
Answer: from man gzip:
-l, --list
This option displays information about the file's compressed and uncompressed size, ratio, uncompressed name.  With the -v option, it also displays the compression method, CRC, date and time embedded in the file.

Determine compression % of gzip file?


Is there a problem defining a View using a path alias? Or did I just miss something?

Question: CONDENSED SUMMARY OF ISSUE:
I have a view with a path of /taxonomy/term/%/something that responds to a URL alias of /spec/ID/ so entering /Spec/ID or /Spec/ID/Something displays what is in the View.  If I clone the View and change the paths from /taxonomy/term/%/something to /Spec/%/Something entering a URL of /specs/ID will no longer display the view.
ADDITIONAL INFO:
I have created a View (D7 Views3) with several pages each with the path /taxonomy/term/%/sub-category where subcategory is a label for a subgroup of content for the specified term. A filter in each page limits the content to match the subcategory label.
I have created an alias for a vocabulary /specs/[term:field_specno]. The field, attached to the term, provides a unique ID for the terms relating to a client's set of standards.
If I enter a URL for /specs/term1, the view will display the correct content for term1 on a page display, with operating Menu Tabs I have defined for each page in the view. It works great except that if I select another Menu Tab, the URL changes to taxonomy/term/%/subcategory format used in the view.  This would be confusing if a user uses the URL and gets the cryptic tid instead of his ID system.  It I clone the view and change the paths to spec/[term:field_specno]/sub-categories, the view no longer displays the pages and tabs correctly.
Is there a fundamental problem in Drupal doing this or have I screwed up somehow?  Has anyone done something similar successfully?
Comment: There are to many parts of the problem, I can't quite grasp where things to wrong for you. Can you try to shorten down the question? :)
Comment: You're right, I boiled it down in the added first paragraph.
Answer: It could be, that I'm still having difficulties understanding your question, but I have no idea why you would expect that to work?
/path/to/%term contains an argument, and as such there is essentially an infinite number of variations that could "fit" into that path.
A path alias "/pageone" to "/path/to/aterm", does not match "/path/to/otherterm", nor any other path in the system.
Each path alias must point to a specific path, and there is to my knowledge no way to automatically "Create all possible path-aliases to for a path /path/with/%arg". There is a feature request for such a tool though.
Comment: OK let me try and clarify.  My views are defined with % wildcards for the tid in View1-/Taxonomy/term/% or for a custom ID (CID) held in a field for View2-specs/% path. Both work in preview, the only difference between them is the path and the contextual filter setting.  If I enable View1 and enter a URL using the path alias for the term/specs/CID, View1 works.  If I disable view1 and enable view2 and enter the same URL, View2 fails.
Comment: If I "get it" now, that does sound like it should work on.
Comment: Letharion +1 and Check.  Letharion & I discussed this in a chat to clarify the information and I will explain the results as an answer.
Answer: Letharion's answer:

Drupal translates the URL alias to the actual URL very early in the
  request sequence so it cannot find the View defined with an alias
  path.

Path Auto creates an alias for a URL and Drupal translates the alias into its true path and then executes the URL action.  In the example in the question, the URL contains /specs/ID which Drupal changes to /taxonomy/term/[tid].  Since the view path is defined as /taxonomy/term/%, the view is called and works as designed. In the second case, the view path has been changed to /specs/% and Drupal, having already changed the URL request from /specs/[ID] to taxonomy/term/[tid] does not associate the view definition with the URL request, so the View is never called.
My reason for attempting this was so that the alias URL would be visible after the view is called and a user could use the URL alias to change to another view in addition to a special menu.  Unfortunately, when the view is called, the url for the view is displayed (/taxonomy/term/[tid]).  I do not see any work around for this at this time.
Answer: For those, who still searching issue... Creating path alias for your term-related view seems good idea. You can do it in hook_node_presave().
For Example:
I have page view with path node/%/tours and menu tab "Tours"
for node 123 i have alias: node/123 -> country/Greece. When opening country/Greece, we can see "Tours" tab with node/123/tours link. After adding alias node/123/tours -> country/Greece/tours tab link will be country/Greece/tours
Just found: Extended path aliases module.
Answer: So the way I understand this questions is such:
You created a view, with a path that has an argument. Then you created aliases for each variance?
Like, if my View path was /animals/% you would just make aliases for /animals/cats to just /cats, /animals/dogs to /dogs.
Then you went and changed the view path from /animals/% to /creatures/% and you wonder why your aliases no longer work?
If that's the case it's because aliases are static and don't know when the thing they are aliasing changes. You'd have to go back and correct your aliases so they now point to /creatures/% since that's now the path your view is operating on as /animals/% no longer exists.
Comment: No, I did not create a variance for each view possibility.  Using your example, 'animals' is a vocabulary and dogs & cats are terms.  The alias for the term 'dog' may be animals/dog, but the actual path is taxonomy/term/a-term-number-for-dog. My answer on this question should help clarify what I was doing and why it doesn't work in Drupal.


Prove if $E$ is a Lebesgue measurable set, there exists a continuous function $f$ differing from $\chi_{E}$ on a set of measure $< \epsilon$?

Question: I am reviewing my analysis notes, and I don't really understand the proof given by my professor.  He first proved if $E$ is a Lebesgue measurable set and $\epsilon > 0$, then there is an open set $O$ such that $m(O) - m(E) < \epsilon$, which makes perfect sense.  Then, using that fact, he proved that, given $\epsilon > 0$, $\exists$ a continuous function $f$ such that $m (\{ x \mid f(x) \neq \chi_{E}(x) \} ) < \epsilon$.  Anyone know how to construct the function $f$?
Answer: Let $O \subseteq \mathbb{R}$ be an open set and define
$$O_n := \left\{x \in \mathbb{R}; d(x,\mathbb{R} \backslash O) \geq \frac{1}{n} \right\}.$$
It is not difficult to show that $O_n$ is closed and $O_n \uparrow O$. Now choose $n$ sufficiently large such that $m(O \backslash O_n)<\varepsilon$. It is not difficult to show that there exists a continuous functions $f_n$ such that $0 \leq f_n \leq 1$ and
$$f_n|_{O_n}=1 \qquad \qquad f_n|_{\mathbb{R} \backslash O} = 0;$$
this follows from Urysohn's Lemma. In particular, $$m(\{x; f(x) \neq 1_{O}(x)\})< \varepsilon.$$ Using that $m(O \backslash E)<\varepsilon$, the claim follows.
Comment: @saz Note: it is not true that $m(O \backslash O_n)<\varepsilon$ for large enough $n$, as that measure could be always infinite.  The result can be salvaged by considering $G_m = O\cap(m,m+1)$ for each integer $m$ and taking a closed subset $F_m$ of that with $m(G_m \backslash F_m) < \varepsilon/2^k$ and then taking the union of the all the $F_m$, etc
Comment: Why is $f_{n}$ continuous?  What is $f$?  Is it the limit of the $f_{n}$'s?
Comment: @user46944 No, for each $n$ there exists a continuous functions $f_n$ such that $f_n|_{O_n}=1$ and $f_n|_{\mathbb{R} \backslash O}=0$. Now $f=f_n$ for some (fixed) $n$ sufficiently large.
Comment: So, if it is not difficult to show that there exists a continuous function $f_{n}$ for each $n$, can you show it?  I realize this must be some obvious fact, but I don't see it.  If we are drawing pictures, do you just mean you connect 0 and 1 "continuously" on $O \setminus O_{n}$?
Comment: @user46944 Basically that's the idea, yes. More precisely, $$f_n(x) := \frac{d(x,\mathbb{R} \backslash O)}{d(x,\mathbb{R} \backslash O)+d(x,O_n)}$$ does the job.
Comment: @PatrickR Yes, you are right.


npm install -D tailwindcss postcss autoprefixer error next.js

Question: npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: email@example.com
npm ERR! Found: firstname.lastname@example.com
npm ERR! node_modules/react
npm ERR!   peer react@">=16.8.0" from @firstname.lastname@example.com
npm ERR!   node_modules/@react-oauth/google
npm ERR!     @react-oauth/google@"^0.2.6" from the root project
npm ERR!   peer react@"^17.0.2 || ^18.0.0-0" from firstname.lastname@example.com
npm ERR!   node_modules/next
npm ERR!     next@"12.1.6" from the root project
npm ERR!   6 more (react-dom, react-icons, styled-jsx, ...)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16 || ^17" from firstname.lastname@example.com
npm ERR! node_modules/react-google-login
npm ERR!   react-google-login@"^5.2.2" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: email@example.com
npm ERR! node_modules/react
npm ERR!   peer react@"^16 || ^17" from firstname.lastname@example.com
npm ERR!   node_modules/react-google-login
npm ERR!     react-google-login@"^5.2.2" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\Mr. Aka\AppData\Local\npm-cache\eresolve-report.txt for a full report.
npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Mr. Aka\AppData\Local\npm-cache_logs\2022-08-10T19_35_56_488Z-debug-0.log
Answer: Try using npm cache verify and after npm cache clean --force. It may then ask you to run another command to permanently solve the issue which is caused by older versions of npm, run that command and it should be solved (worked for me).


how to create multiple list with different set of values in a loop in python?

Question: I'm struggle to create multiple lists with different sets of values. I try to read a csv using pandas and then for every 100 records I want to set it in a list, and then until it reach the bottom of the csv.
The csv file example:
number
1
2
...
100

here is my code so far
import pandas as pd

df = pd.read_csv('test.csv', delimiter=',')

n = 10
m = 0

mylist = []

while n < 25:

    for i in range(m, n):
        test = df.iloc[i]['number']
        mylist.append(test)
    print(mylist)

    print('finish 10 records')

    m += 10
    n += 10

    if n >= 25:

        for i in range(m, n):
            test = df.iloc[i]['number']
            mylist.append(test)
        print(mylist)
        print('finished')
        break

as you can see the code create this output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
finish 10 records
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
finish 10 records
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
finish 10 records

what I want to achieve is this output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
finish 10 records
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
finish 10 records
[21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
finish 10 records

is that possible to achieve that please?
thank you
Answer: Right now, you're appending those values to the existing mylist variable and printing it as-is. You need to make sure you clear that list upon every iteration so that it starts empty, like this:
...

mylist = []
while n < 25:
    for i in range(m, n):
        ...

    print(mylist)
    mylist = []

    ...

Or, you could create a new list every iteration:
while n < 25:
    l = []

    for i in range(m, n):
        ...
        l.append(...)

    print(l)


how to run openCV related app , without using OpenCV manager in android

Question: In my android application, i use static loading of OpenCV library
i.e
OpenCVLoader.initDebug()

it will return true when run on emulator, but return false when run on (mobile) device.
if i use
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_3, this, mLoaderCallback)

if OpenCV manager .apk alredy installed,then above code work fine in emulator and device.
 here i want run openCV realted app, with out intall OpenCV manager.apk.
please help me. thanks in advance.
Comment: possible duplicate of [How to integrate OpenCV Manager in Android App](http://stackoverflow.com/questions/20259309/how-to-integrate-opencv-manager-in-android-app)
Comment: Alternate answer: http://stackoverflow.com/a/35135495/5611377
Answer: Ok what you are talking is Static initialization of the OpenCV library.
See this Official Opencv help regarding this matter.
Also have a look at these StackOverflow topic and try compiling your code.
Cheers.
Comment: OpenCV related app is working fine with OpoenCV manager .apk , but i want without OpenCVmanager.apk. i said that **"without OpenCVManager.apk , my app is running fine in emulator, but in the device it gives 'forceclose error'"**.
Comment: @sathishkumar.challa did you read the [Link1](http://docs.opencv.org/doc/tutorials/introduction/android_binary_package/dev_with_OCV_on_Android.html#application-development-with-static-initialization) completely ? Please do read every line; your answer is within that doc. ie.- w/o using Opencv manager.
Comment: Thank you very much, i got the solution (i.e in previous i did not copy the libs all files from native folder).
Answer: For the Android Studio users out there, I made a blog post detailing what I did to get around the OpenCV Manager App Installation prompt:
http://usefuljavanotes.weebly.com/blog/how-to-use-opencv-without-opencv-manager
Here is a GitHub repo that includes the code I implemented in the blog post. Feel free to download it and test it on your system:
https://github.com/JamieLee629/OpenCVTest
The other OpenCV parts of the code not mentioned in the blog post were courtesy of Code Onion Blog:
http://blog.codeonion.com/2016/04/09/show-camera-on-android-app-using-opencv-for-android/
I compiled this answer using these sources: https://stackoverflow.com/a/45684065/6030520, https://stackoverflow.com/a/35135495/6030520, https://stackoverflow.com/a/20259621/6030520


Selector de ListView e ImageButton não funciona

Question: Tanto o botão quando a ListView não sofrem modificações quando clicados, mas as definições de quando o item não é pressionado funcionam.
ListView:
<ListView
        android:id="@+id/listaListas"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:divider="#FFECECEC"
        android:dividerHeight="2sp"
        android:layout_alignParentEnd="true"
        android:layout_above="@+id/novalista"
        android:background="@drawable/layout_item_listview">
    </ListView>

layout_item_listview:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:state_selected="true"
        android:drawable="@drawable/layout_item_selecionado" />
    <item android:state_pressed="false" android:state_selected="false"
        android:drawable="@drawable/layout_item_normal" />
</selector>

layout_item_selecionado:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/item_selecionado"/>
</shape>

layout_item_normal:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/vermelho"/>
</shape>

Botao:
<ImageButton
            android:layout_width="70dp"
            android:layout_height="80dp"
            android:background="@color/amarelo"
            android:src="@drawable/img_estrelabotao"
            android:id="@+id/btnfavorito"
            android:layout_alignParentTop="true"
            android:layout_alignParentEnd="true"
            android:visibility="visible"
            style="@style/estiloBotaoFavorito"/>

estiloBotaoFavorito:

layout_botao_favorito:
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="true" android:drawable="@drawable/layout_botao_favorito_pressionado"/>
    <item android:state_pressed="false" android:drawable="@drawable/layout_botao_favorito_normal"/>
</selector>

layout_botao_favorito_pressionado:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle">
    <solid
        android:drawable="@drawable/nine_patch_retangulo"
        android:color="@color/amarelo_escuro"
        android:elevation="8dp"/>
</shape>

layout_botao_favorito_normal:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle">
    <solid
        android:drawable="@drawable/nine_patch_retangulo"
        android:color="@color/amarelo"
        android:elevation="8dp"/>
</shape>

Outra dúvida que tenho é se dentro do shape do botão eu posso definir elevation e o drawable? Como não acusou erro eu deixei assim
Answer: A ordem como são declarados os estados tem importância na forma como são aplicados, o que nem sempre é óbvio.
A melhor forma de evitar essas situações é declarar o menor número de estados possíveis e fazê-lo em itens separados.
Altere os selectores assim:
layout_item_listview:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
        android:drawable="@drawable/layout_item_selecionado" />
    <item android:state_selected="true"
        android:drawable="@drawable/layout_item_selecionado" />
    <item android:state_activated="true"
        android:drawable="@drawable/layout_item_selecionado"/>
    <item android:drawable="@drawable/layout_item_normal" />
</selector>

Para que a selecção fique activada é necessário acrescentar android:state_activated="true" e que seja declarado, na ListView, o atributo android:choiceMode com um modo diferente de none.
Nota: Este selector deve ser atribuído ao background do layout do item da lista e não ao da ListView.
layout_botao_favorito:
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="true"
        android:drawable="@drawable/layout_botao_favorito_pressionado"/>
    <item android:drawable="@drawable/layout_botao_favorito_normal"/>
</selector>

O último <item>, aquele que não tem estado definido, será aplicado por padrão(quando nenhum dos anteriores se verificar).
Em relação à outra dúvida, a documentação apenas indica o atributo android:color a poder ser usado no elemento <solid>.
Comment: Deu certo! Os Buttons não estavam funcionando pq além do style eu tinha definido um background. Tirei o background e funcionou direitinho! Obrigada :)
Comment: fiz o que você falou e coloquei o choiceMode como singleChoice e continuou não funcionando
Comment: Editei a resposta, faltava o estado `state_activated`. Tenha atenção à nota que adicionei.
Comment: Eu estou com o mesmo problema, o meu codigo esta do jeito que vc falou ramaral, porem somente qdo clico no imagebutton ele faz algo, agora quando clico no item do listview ele não seleciona aparentemente ele nem clama a função onClick (se eu tiro o button funciona normalmente), o meu choiceMode é multipleChoice.
Comment: @JoãoCarlos sem ver o código fica difícil de saber a razão. Veja se está a fazer tudo o que é descrito na resposta. Se não resolver, abra um nova pergunta.
Comment: Eu fiz uma pergunta da uma olhadinha la pra mim.https://pt.stackoverflow.com/questions/237218/ao-adicionar-imagebutton-selector-de-listview-para-de-funcionar?noredirect=1#comment485869_237218
Comment: Vi-a pouco depois de ter comentado. Não vejo nada de errado em relação ao problema que indica.


ARToolkit Unity - Camera blank (only black) when Playing

Question:
I want to create Augmented Reality using Unity and ARToolkit but when done then play the camera was blank. I follow this tutorial from Youtube
Answer: Alternatively, you can use one of the example scenes that come with the ARToolKit Unity package as a starting point.
Those scenes should work fine and you can check the differences with yours.
Comment: i've using the example scene and its doesnt work also
Comment: Then the problem must be in the camera and the access to it.
Comment: Hi @shalafi . I have problem with unity3d blank scene when open project? Can you help me? Here is the link to the question: http://stackoverflow.com/q/39952401/5241603


Como criar um sistema notificações em tempo real semelhante ao Stack Overflow?

Question: Estou desenvolvendo um sistema Help Desk, e gostaria de algumas idéias de como criar um sistema de notificação semelhante ao próprio Stack Overflow, sempre que algum novo suporte for cadastrado.
Pretendo utilizar PHP, MySQL e jQuery apenas.
Devo utilizar o window.setTimeout para verificar no banco de tempos em tempos se um novo chamado for registrado?
Comment: O Stack Overflow usa websockets para notificações em tempo real.
Comment: Alguma das respostas lhe ajudou? Ou há problemas nelas? Comente informando ao autor qual a duvida em tentar usar a solução proposta. Se alguma das respostas lhe resolveu o problema, marque-a como correta clicando em ✓
Answer: Acabei de responder uma pergunta parecida, só que falava sobre um chat.
As opções que têm são as seguintes:
Para implementar o chat:

a opção que vai te dar a maior abrangência em termos de browseres, é chamada de long-polling, mas também é a que vai dar mais trabalho. Veja mais sobre a técnica: long-polling
um outra opção que vai ser mais fácil, é usar websocket, e criar uma conexão com servidor, que vai poder enviar mensagens quando algum evento do chat ocorrer... tipo enviar uma mensagem, mas nesse caso o servidor terá de ser capaz de receber a conexão do cliente via websocket (terá de ser capaz de esperar por conexões... basta buscar por "php websocket" no google que aparecem algumas bibliotecas).
Answer: Cara, NÃO utilize ajax com setInterval.
Veja, imagine que de 1 em 1 minuto o sistema irá fazer uma requisição ao servidor e retornar uma resposta ao browser, mesmo que não haja mudanças na conversa.
Se houver vários clientes, irá sobrecarregar o sistema com requisições em ajax, o que seria desperdício de recursos.
Procure sobre PHP+LONG POLLING.
Long Polling funciona diferente do ajax, a conexão fica aberta aguardando uma resposta do servidor.
O ideal mesmo seria implementar essa parte em nodejs, uma vez que é mais adequando para aplicações real time.
Answer: Você já pensou em utilizar algum tipo de sistema de Pusher notification como por exemplo o Pusher ou o PubNub ?
Você utilizar timeout você vai estar fazendo Long Polling e esse tipo de atualização utiliza muito mais recurso.
Minha sugestão para você seria você dar uma olhada na melhor opção:

www.meteor.com
socket.io
pusher.com
www.pubnub.com
Comment: Os dois fornecem um serviço de Push notification baseado em WebSocket. A vantagem de usar esses dois é que eles diversos tipos de API para integração no seu sistema. A base é que você vai criar um canal e quando esse canal for invocado ele vai executar um handler.
Comment: o que fazem o `Pusher` e o `PubNub` exatamente?
Comment: Exemplo: http://pubnub.github.io/backbone/


date format in database of quiz module

Question: I make a quiz with quiz module and the start date is 1/8/2013 4:30 and the close time is 10/8/2013 4:30.
In the database it stored as this=>
1375315200(quiz open)
1376092800(quiz close)

which one is year, month and day?
Answer: Use PHP's date() function.
Example:
echo date('m/d/Y', 1299446702);

Check Unix Timestamp Conversion Tools online
Comment: can you give me a code that convert this timestamps?
Comment: try `echo date('m/d/Y', "Your Timestamp");`
Comment: not working!and I want to convert unix timestamp to human time stamp like YYMMDD
Comment: It shows 01/01/1970
Comment: we can use this function

    function unix_timestamp_to_human ($timestamp = "", $format = 'Ymd- H:i:s')
    {
        if (empty($timestamp) || ! is_numeric($timestamp)) $timestamp = time();
        return ($timestamp) ? date($format, $timestamp) : date($format, $timestamp);
    }

date format in database of quiz module


Question in Proof of Proposition 3.16 in AM

Question:
Proposition 3.16. Let $A\to B$ be a ring homomorphism and let $\mathfrak{p}$ be a prime ideal of $A$. Then $\mathfrak{p}$ is the contraction of a prime ideal of $B$ if and only if $\mathfrak{p}^{ec} = \mathfrak{p}$.

$(\Leftarrow)$ Let $S$ be the image of $A-\mathfrak{p}$ in $B$. Then $\mathfrak{p}^e$ does not meet $S$, therefore by $(3,11)$ its extension in $S^{-1}B$ is a proper ideal and hence is contained in a maximal ideal $\mathfrak{m}$ of $S^{-1}B$. If $\mathfrak{q}$ is the contraction of $\mathfrak{m}$ in $B$, then $\mathfrak{q}$ is prime, $\mathfrak{q}\supseteq \mathfrak{p}^e$ and $\mathfrak{q}\cap S=\emptyset$. Hence, $\mathfrak{q}^c = \mathfrak{p}$.
In the last part, why $\mathfrak{q}^c\subset\mathfrak{p}$ holds?
Answer: Let $f$ denote the map $A\to B$. If $x\in {\frak q}^c\setminus {\frak p}$, then $f(x)\in {\frak q}$ and $f(x)\in f(A\setminus {\frak p})=S$ which contradicts ${\frak q}\cap S=\emptyset$.