How do I fix this 404 error for a button added with "url_for"

Question: I'm building a basic flask todo list web application, with main app.py and 4 html pages, add.html, edit.html, home.html, todos.html.
Everything works perfectly fine, except when "add todo" button is clicked on the main page, I have this error 404:

Here's my app.py:
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///todos.db'
db = SQLAlchemy(app)

class Todo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    description = db.Column(db.String(200), nullable=False)
    status = db.Column(db.String(20), nullable=False, default='Incomplete')

@app.route('/')
def home():
    return render_template('home.html')

@app.route('/add', methods=['GET', 'POST'])
def add_todo():
    if request.method == 'POST':
        description = request.form['description']
        new_todo = Todo(description=description)
        db.session.add(new_todo)
        db.session.commit()
        return redirect(url_for('todos'))

    return render_template('add.html')

@app.route('/todos')
def todos():
    todos = Todo.query.order_by(Todo.status, Todo.id).all()
    return render_template('todos.html', todos=todos)

@app.route('/todos/mark_complete/<int:todo_id>')
def mark_complete(todo_id):
    todo = Todo.query.get_or_404(todo_id)
    todo.status = 'Completed'
    db.session.commit()
    return redirect(url_for('todos'))

@app.route('/todos/mark_incomplete/<int:todo_id>')
def mark_incomplete(todo_id):
    todo = Todo.query.get_or_404(todo_id)
    todo.status = 'Incomplete'
    db.session.commit()
    return redirect(url_for('todos'))

@app.route('/todos/edit/<int:todo_id>', methods=['GET', 'POST'])
def edit(todo_id):
    todo = Todo.query.get_or_404(todo_id)

    if request.method == 'POST':
        todo.description = request.form['description']
        db.session.commit()
        return redirect(url_for('todos'))

    return render_template('edit.html', todo=todo)

@app.route('/todos/delete/<int:todo_id>')
def delete(todo_id):
    todo = Todo.query.get_or_404(todo_id)
    db.session.delete(todo)
    db.session.commit()
    return redirect(url_for('todos'))

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run()

And here's my add.html:
<!DOCTYPE html>

  <title>Add ToDo</title>

Add ToDo

  <form method="POST" action="{{ url_for('add_todo') }}">
    Description:
    <input type="text" id="description" name="description">
    <input type="submit" value="Add">
  </form>

Comment: [todo-tag](https://stackoverflow.com/questions/tagged/todo): "... Please do not use this for questions about creating todo list applications."
Comment: What is the URL that the button tries to navigate to?
Comment: @dsakhuria, your code is working properly for me. I did not modify your code and it is adding new todo. I have added another HTML template for `todos` and it is showing the newly added todo. One suggestion might be to use debug mode in flask : https://flask.palletsprojects.com/en/2.3.x/quickstart/#debug-mode
Answer: Upon reviewing your code, it appears that the code itself is correct and should work as expected. Therefore the issue is not related to the code itself.
Here's a working version using your code -

https://replit.com/@Om-Mishra/AdmiredPrestigiousArguments
https://admiredprestigiousarguments.om-mishra.repl.co/add

If you're encountering a 404 error when clicking the "add todo" button, it could be due to a misconfiguration in your Flask application or an issue with the server setup. To troubleshoot that try running the app in debug mode - How to debug a Flask app
Answer: problems fixed, issue was that the button itself was reffering to wrong directory, instead of path/add, it was going to path/todo/add which wasnt really existing(thats the reason of why error 404 raised), ty anyway.


How to validate such input using a regular expression?

Question: Somebody's can help with this maybe by using regex.
It is necessary for the "useInput" function to have minutes as the first parameter and seconds as the second parametr, if input can be: "1 2" (two digits - minutes seconds), "1" (just a digit - minutes), "1 minutes 2", "2 seconds 1 ".
Not so necessary but if is not too hard: seconds = sec = second = s; minutes = minute = min = m; Іnstead of "1 minutes" you can write "1 min" into "input"

const input = "   2   seconds   1   minutes   "
const regexTimer = new RegExp(/([0-9]+)\s*minutes?|([0-9]+)\s*seconds?/, 'g')

useInput(input.replace(regexTimer, '$1$2')).split(' '));//1 parameter is minute, 2 parametr is second

function useInput(minutes, seconds){...};
Answer: You could use capture groups and pass those group values to the function.
Check which group values are not empty, and based on that pass the parameters in the right order to the function useInput.
For the partial names of seconds and minutes you can use nested optional groups.
^\s*(?:(\d+)(?:\s*(\d+))?|(\d+)(?:\s+s(?:ec(?:onds?)?)?)?(?:\s+(\d+)(?:\s+m(?:in(?:utes?)?)?)?)?|(\d+)(?:\s+m(?:in(?:utes?)?)?)?(?:\s+(\d+)(?:\s+s(?:ec(?:onds?)?)?)?)?)\s*$

Regex demo

const useInput = (minutes, seconds) =>
  console.log(`minutes: ${minutes ? minutes : "n/a"} - seconds: ${seconds ? seconds : "n/a"}`);
const regex = /^\s*(?:(\d+)(?:\s*(\d+))?|(\d+)(?:\s+s(?:ec(?:onds?)?)?)?(?:\s+(\d+)(?:\s+m(?:in(?:utes?)?)?)?)?|(\d+)(?:\s+m(?:in(?:utes?)?)?)?(?:\s+(\d+)(?:\s+s(?:ec(?:onds?)?)?)?)?)\s*$/;
[
  "1",
  "1 2",
  "1 minutes 2",
  "4 seconds 3",
  "5 seconds",
  "6 minutes",
  "7 min",
  "8 sec",
  "9 s 10 m",
  "11 m 12 second",
  "20 9 sec",
  "30 s 44",
  "test"
].forEach(s => {
  let m = s.match(regex);
  if (m) {
    if (m) {
      if (undefined !== m[1]) useInput(m[1], m[2])
      if (undefined !== m[3]) useInput(m[4], m[3])
      if (undefined !== m[5]) useInput(m[5], m[6])
    }
  }
})


Como modificar o documento HTML através de uma extensão?

Question: Gostaria de fazer um botão aparecer no site que desenvolvi, mas só para quem tem a extensão.
Eu tenho os códigos CSS, HTML e Javascript pra gerar o botão. A funcionalidade do botão está pronta, só preciso fazer a extensão.
Podem me ajudar?
Comment: A extensao que voce quer identificar 'e sua ou de terceiros?
Comment: queria criar a minha própria extensão, as funcionalidades foram criadas por mim.
Comment: O que você já fez? Se vai criar a própria extensão, pode inserir o botão na página por meio da extensão.
Comment: Ja que a extensao 'e sua voce pode fazer ela se comunicar com a pagina atraves de uma troca de mensagens. Outro metodo seria voce fazer a sua extensao deixar algum rastro, como por exemplo adicionar uma classe a alguma tag usada na pagina.
Comment: já fiz todas as funcionalidades, são 2 botões com 2 input radios, todos estão funcionando. tem algum tutorial para seguir?
Answer: Extensão Chrome

Crie um diretório vazio o qual conterá os arquivos da extensão.
Crie nesse diretório o arquivo manifest.json.
Adicione ao diretório um arquivo JavaScript contendo o código que irá inserir o botão no final da página.
Adicione ao dreitório o arquivo de script do jQuery, que será usado pela extensão.

O diretório representando a extensão deverá ficar com o seguinte conteúdo:

Seu arquivo de manifesto deverá ficar da seguinte forma:
Arquivo manifest.json
{
  "manifest_version": 2,

  "name": "Adiciona Botao",
  "description": "Adiciona um botao no final da pagina",
  "version": "1.0",

  "content_scripts": [
    {
      "matches": ["http://*/*"],
      "js": ["jquery.js", "main.js"]
    }
  ]
}

No arquivo main.js você executa o código que adiciona o botão:
$(document).ready(function() {
    $("body").append("<input type='button' onclick='alert(\"Botão adicionado por uma extensão!\")' value='Botão Dinâmico' />");
});

Agora, para carregar a extensão, vá para a URL chrome://extensions/, clique em "Carregar Extensão Expandida..." e selecione a pasta da extensão.
Feito isso, basta acessar qualquer página que contenha http na URL e o botão será adicionado ao final dessa página. Clique no botão para testá-lo.
Answer: Já há uma resposta sobre o desenvolvimento para Chrome, então tentarei explicar de forma simplificada como fazer o mesmo no Firefox.
A Mozilla disponibiliza um SDK que inclui APIs para o desenvolvimento, execução e teste das extensões.
O desenvolvimento pode ser feito em qualquer editor de sua preferência, usando linguagens como Html, CSS e Javascript. Já a inicialização, execução e os testes são feitos por meio da jpm, que é uma ferramenta baseada em Node e que substituiu o uso do cfx após o Firefox 38.
Na documentação da Mozilla, há uma página voltada para a explicação de como instalar a jpm, bem como a lista dos comandos que podem ser usados como parâmetros de execução.

Iniciando
Tendo o Node e o módulo do jpm instalados, crie um diretório vazio.
Por linha de comando, navegue até o diretório que criou e execute o comando:
> jpm init

Serão perguntadas algumas informações como nome da extensão, descrição, autor... após inserir essas informações, no diretório, será criado um "esqueleto" como ponto de partida para o desenvolvimento.
Não é preciso fazer nenhuma modificação no package.json por enquanto. E nem será necessário se a única coisa que precisa fazer é modificar o Html de uma página para criar um botão.
A única coisa que você precisa verificar é se o atributo main está apontado para o arquivo index.js que foi criado no diretório, ele define qual será o primeiro arquivo a ser executado.

Criando um botão na página 'x'
Um dos módulos no SDK é o page-mod que, como o nome sugere, permite modificar páginas. Tomando como exemplo o StackOverflow, para inserir um botão na página, o index.js poderia ficar assim:
let { PageMod } = require('sdk/page-mod');

PageMod({
   include: '*.stackoverflow.com',
   contentScript: 'document.body.insertAdjacentHTML("afterbegin", "<button>Botão criado pela extensão</button>")'
});

Somente isto. Executando o comando jpm run e navegando até o site StackOverflow, o botão será exibido no topo da página:

No exemplo, o botão até herdou as regras CSS do site.
Como você disse já ter o script que controla o botão, você pode trocar o contentScript por contentScriptFile para incluir o arquivo por completo.
No diretório da extensão, crie uma pasta chamada data e em qualquer módulo da extensão é possível usar o alias ./ para obter os arquivos na pasta data.
Então, em minhaextensão/data/ você teria o seu arquivo Javascript que controla a interação com o botão. E agora seu index.js ficaria assim:
let { PageMod } = require('sdk/page-mod');

PageMod({
   include: '*.stackoverflow.com',
   contentScriptFile: './meuscript.js'
});

Se quiser importar mais de um script, também é possível:
let { PageMod } = require('sdk/page-mod');

PageMod({
   include: '*.stackoverflow.com',
   contentScriptFile: ['./jquery.min.js', './meuscript.js', './meuoutroscript.js']
});


Querying for user's whose birthday is today plus other OR conditions

Question: We have a date field attached to the user entity.  It stores values for year, month and day, in the following format (looking at the field_date_of_birth_value column in the DB): 1987-06-08T00:00:00.
We are using EFQ and wish to return users who's birthday is today OR some other conditions on another field also attached to the user entity (field_babys_date_of_birth, which doesn't necessarily have a value for every user and has is stored in the same format as the other field).
Is there a way to compare the stored month and day with the current ones using EFQ? If not, how would you approach this problem?
Pseudocode specification
  FETCH every account where:
    date_of_birth == TODAY (month and day only)  OR
    babys_date_of_birth == TODAY + 6 MONTHS OR
    babys_date_of_birth == TODAY + 3 MONTHS
  END FETCH
  FOREACH accounts as account
    // Custom logic (always the same).
  END FOREACH

Implemented code
<?php
// Fetch users whose birthday is today.
$today = new DateTime('today');
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->fieldCondition('field_date_of_birth', 'value', $today, '=');
$result = $query->execute();
$uids = array_keys($result['user']);
foreach ($uids as $uid) {
  $account = user_load($uid);
  // Custom logic (always the same).
}

// Fetch users where babys_date_of_birth == today + 3months.
$after_three_months = new DateTime('today + 3 months');
$after_three_months = $after_three_months->format('Y-m-d\T00:00:00');
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->fieldCondition('field_babys_date_of_birth', 'value', $after_three_months, '=');
$result = $query->execute();
$uids = array_keys($result['user']);
foreach ($uids as $uid) {
  $account = user_load($uid);
  // Custom logic (always the same).
}

// Fetch users where babys_date_of_birth == today + 6 months.
$after_six_months = new DateTime('today + 6 months');
$after_six_months = $after_six_months->format('Y-m-d\T00:00:00');
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->fieldCondition('field_babys_date_of_birth', 'value', $after_six_months, '=');
$result = $query->execute();
$uids = array_keys($result['user']);
foreach ($uids as $uid) {
  $account = user_load($uid);
  // Custom logic (always the same).
}
?>

Known problems with the code:

We think it should be better to have only one query to return all the accounts, as the custom logic to be executed is the same for all of them.
The first condition should only check for month and day (excluding year).

Maybe EFQ doesn't support ORed conditions, and we should use something else?
Comment: Please show the code you're using
Answer: If you want to filter in your efq, you'll have to compare strings:
   $today = new DateTime();
   $today = $today->format('Y-m-d\T00:00:00');

Then add in your query the condition
'field_date_of_birth_value', $today, '='

I can't tell more unless you show us your code.
Comment: you can do a for loop on the result set and then compare and compare the date like this. if $today->format('m-d') == substr(dategotfromdb, 5, 4);
Comment: That's what we are looking for, except that we need to compare just the month and day (we want user's who's birthday is today, so the year doesn't matter).
Comment: Arf sorry ; so you will indeed need to make a loop, as @MohammedShameem advised... But it will be after the query ! Plz show your code, we will help better.
Comment: Doesn't seem optimal at all, we would need to retrieve the entire userbase and do the check in the loop.  I've uploaded the code, maybe that helps.  Maybe we need to look beyond EFQ ?
Comment: Indeed, the problem we have here is that it can be any year... My guess would be to store 'somewhere' the day and month of birth per user, like after a hook_user_update. Call that hook, get the birth date, extract day and month from it, store that in a new hidden field or in a new table. Then your query will be easy as pie.
Comment: Smells overkill.  If EFQ doesn't do the job, any chances of using db_select or db_query to partially match that date?
Comment: db_select accepts the LIKE, but I would feel more comfortable with the CONTAINS as given in Kiamlaluno's answer :)
Answer: About using OR conditions, you can read the answers for Using OR with EntityFieldQuery.
For the code to use to check only the month, and the day, I would use the following query.
$today = new DateTime('today');
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->fieldCondition('field_babys_date_of_birth', 'value', $today->format('-m-d\T'), 'CONTAINS');

Basing on EntityFieldQuery::addFieldCondition(), the method called by EntityFieldQuery::addFieldCondition(), $operator can be one of the following: =, <, >, <=, >=, STARTS_WITH, CONTAINS, IN, NOT IN, BETWEEN.
If LIKE is supported, I would write the field condition as:
$query->entityCondition('entity_type', 'user')
  ->fieldCondition('field_babys_date_of_birth', 'value', '%' . db_like($today->format('-m-d\T')) . '%', 'LIKE');

Comment: This seems like the best approach so far.  However, messing with EFQ to workaround ORed queries scares me out :)  Given that we won't be using anything but MySql compatible DBs in the foreseeable future, how about this other option:  doing a db_select query over each field table to get all matching user entity IDs and then do a user_load_multiple and execute our custom logic on each of them.  Like that better for simplicity?
Comment: I think that the only problem would be with field storage implementations that don't use a SQL database engine, such as in the case of Mongodb; passing from MySQL to PostgreSQL should not cause any problem. The alternative solution (using `hook_query_alter()` as suggested from the answer to the other question) would probably have problems with Mongodb too.


Como executar arquivo de áudio utilizando a classe AudioTrack?

Question: Pretendo fazer um app de tocar bateria, mas, como estou começando agora a desenvolver para android, estou com dificuldade.
Eu preciso tocar um arquivo de áudio com a classe AudioTrack (pois ela tem a menor latência), porém não entendi como utilizá-la para executar um arquivo .mp3, por exemplo.
Já pesquisei, mas só encontrei exemplos da classe MediaPlayer. Alguém poderia postar um exemplo da AudioTrack?
Answer: A única forma de tocar algum áudio pela AudioTrack é um streaming PCM, como pode ser visto na documentação:

The AudioTrack class manages and plays a single audio resource for Java applications. It allows streaming of PCM audio buffers to the audio sink for playback. This is achieved by "pushing" the data to the AudioTrack object using one of the write(byte[], int, int) and write(short[], int, int) methods.

Em tradução livre:

A classe AudioTrack gerencia e toca um recurso de áudio para aplicações Java. Ela permite streaming de buffers de áudio PCM ser a fonte de áudio para reprodução. Isso pode ser alcançando através do carregamento das informações para um objeto AudioTrack usando um dos métodos: write(byte[], int, int) e wirte(short[], int, int).

Pode-se utilizar esse tutorial para descomprimir o arquivo .mp3 e carregá-lo como PCM, utilizando a biblioteca JLayer e o código abaixo:
public static byte[] decode(String path, int startMs, int maxMs)
  throws IOException, com.mindtherobot.libs.mpg.DecoderException {
  ByteArrayOutputStream outStream = new ByteArrayOutputStream(1024);

  float totalMs = 0;
  boolean seeking = true;

  File file = new File(path);
  InputStream inputStream = new BufferedInputStream(new FileInputStream(file), 8 * 1024);
  try {
    Bitstream bitstream = new Bitstream(inputStream);
    Decoder decoder = new Decoder();

    boolean done = false;
    while (! done) {
      Header frameHeader = bitstream.readFrame();
      if (frameHeader == null) {
        done = true;
      } else {
        totalMs += frameHeader.ms_per_frame();

        if (totalMs >= startMs) {
          seeking = false;
        }

        if (! seeking) {
          SampleBuffer output = (SampleBuffer) decoder.decodeFrame(frameHeader, bitstream);

          if (output.getSampleFrequency() != 44100
              || output.getChannelCount() != 2) {
            throw new com.mindtherobot.libs.mpg.DecoderException("mono or non-44100 MP3 not supported");
          }

          short[] pcm = output.getBuffer();
          for (short s : pcm) {
            outStream.write(s & 0xff);
            outStream.write((s >> 8 ) & 0xff);
          }
        }

        if (totalMs >= (startMs + maxMs)) {
          done = true;
        }
      }
      bitstream.closeFrame();
    }

    return outStream.toByteArray();
  } catch (BitstreamException e) {
    throw new IOException("Bitstream error: " + e);
  } catch (DecoderException e) {
    Log.w(TAG, "Decoder error", e);
    throw new com.mindtherobot.libs.mpg.DecoderException(e);
  } finally {
    IOUtils.safeClose(inputStream);
  }
}

Vale ressaltar que a AudioTrack não foi concebida com o intuito de carregar arquivos de áudio. O ideal para carregar arquivos comprimidos de áudio (tais como mp3 e ogg, por exemplo) seriam as classes MediaPlayer ou SoundPoll, como pode ser visto nas respostas dessa pergunta da SOen.


Simple probability confusion

Question: I have confused myself by the following argument I would love some help with.
Let $f(a,b)$ be a function that equals $1$ or $0$. Let $a \in \{1,\dots, n^4\}$ and $b \in \{1,\dots n\}$ be independent uniform random variables.  Let us say we know that $P_{a,b}(f(a,b) = 1) = p$ when $a$ and $b$ are chosen uniformly at random.  I would like to argue that therefore there exists an $i$ for which $P_{b}(f(a,b)= 1|a=i) \leq p$ when $b$ is chosen uniformly at random.
Is this correct or is there a similar statement one can make that is true?
Comment: I think your notation is somewhat confusing. Is $b$ a random variable taking values in $\lbrace 1,\dots n\rbrace$? Is $P_{a}(f(a,b) = 1)$ then the same as the conditional probability$ P(f(a, b) = 1 | b = i) $?
Comment: @user126540 Sorry for the confusion. I have attempted to fix it. You are basically right except I had the wrong subscript. $a$ and $b$ are both random variables  as you say.
Answer: Let's say $f(a, b) = 1$ when $a \in A$ and $b \in B$ where $A \subset \lbrace 1, \dots n^4 \rbrace$ and $B \subset \lbrace a, \dots n \rbrace$. Then $$P(f(a, b) = 1) = P(a \in A, b \in B) = P(a \in A)P(b \in B)$$ assuming $a$ and $b$ are independent. In the same manner $$ P(f(a, b) = 1 | a= i)= \begin{cases}0 & i \not\in A \\P(b \in B)& i \in A \end{cases} $$  So basically, the inequality holds every time $a \not\in i$ but false when $a \in A$ since
$$
p = P(a \in A)P( b \in B) \leq P(b \in B | a= i)= P(b \in B)  = P(f(a, b) = 1|a=i).
$$
Conclusion: your hypotheis is true.
Acknowledgement: I was hung over while doing this, so it might not be waterproof.

Simple probability confusion


Comunicação Serial Com PHP e Arduino

Question: Já tenho um código na IDE do arduino, no qual quando passado a letra 'l', um led será acesso, entretanto, não consigo de forma alguma acessar essa porta serial com PHP, estou utilizando Fedora 22, Arduino Uno, os códigos estão abaixo:
Código Arduino, porta utilizada /dev/ttyACM0
void setup() {
   pinMode(13, OUTPUT);
}

void loop() {
   char caracter = Serial.read();
   if(caracter == 'l'){
      digitalWrite(13, HIGH);
      delay(1000);
   }
}

Código PHP, pssando o caracter 'l'
<?php
   $porta = fopen("/dev/ttyACM0", "w");
   fwrite($porta, 'l');
   fclose($porta);
?>

Dei um var_dump na variável $porta e ela me retornou false, agradeço a ajuda de todos.
Comment: Provavelmente o executavel do PHP ou apache não tem permissões de escrever em `/dev/ttyACM0`, me parece o mais provável. Tambem não sei se seu kernel possui os drivers nescessários. Alguns arduinos "piratas" tem drivers especificos
Comment: Certeza que é permissão tive esse mesmo problema no linux, da um chmod 777 /dev/ttyACM0 que vai funcionar. !!!
Answer: então eu resolvi o problema, não consegui de forma alguma fazer a leitura e escrita dos dados da porta serial através do PHP, porém depois de muitas pesquisas, consegui fazer a leitura e escrita dos dados pelo prompt de comando (estou usando Windows) e com o php consegui fazer a leitura dos dados do prompt. A lógica é a seguinte, o PHP manda executar um script powershell com a função 'exec', este script manda um caractere para a porta serial e o arduino com este dado faz alguma coisa. Para mais informações, segue o tutorial que me ajudou bastante na parte dos scripts em powershell: PowerShell Scripts Serial Port
Answer: Amigo, eu sou muito ajudado por tutoriais e fórum, sou hobista então tudo que faço é com muito esforço e pesquisa, e fiquei uns 3 meses buscando essa solução, basicamente o código no Windows muda um pouco:
$fj = fopen("COM2", "w");
//o "w" muda de acordo com o que vc quer fazer, pode ser "w" "a" "r" no site do manual php tem mais informacoes.
$escreve = fwrite($fj, '1');
fclose($fj);

Funciona na porta COM2 e você precisará mudar as configurações na porta serial dentro de "Gerenciador de dispositivos", "portas ", "USB porta serial(COM2)", "Definições da porta" e "avançadas", "mudei o temporizador e marquei todas as opções do lado esquerdo, mas há o risco de queimar a entrada serial do Arduíno, o que provavelmente aconteceu comigo depois de algumas vezes que acendi um led.
Obs. você precisa fazer a mudança de configuração depois que enviar o código Arduíno, senão não funciona. Tentativas e erros. Não instala um tal de Firmata, só zimbra o Arduíno e não tem como tirar mais.
Answer: Use o PHP-Serial
link aqui
exemplo :

error_reporting(E_ALL);
ini_set('display_errors', '1');
include "php_serial.class.php";

$serial = new phpSerial;
$serial->deviceSet("/dev/ttyAMA0");
$serial->confBaudRate(115200);
$serial->confParity("none");
$serial->confCharacterLength(8);
$serial->confStopBits(1);
$serial->deviceOpen();
$serial->sendMessage("L");

$serial->deviceClose();

echo "comando enviado! \n\r";
Comment: Então, já tentei implementar com este script, mas também sem sucesso, o mesmo erro ocorre, acesso negado a porta. Obs: realizei testes em três máquinas diferentes, com Fedora 22, com Ubuntu 14.04 em com Windows 10, todos em máquinas distintas e sem nenhum sucesso.
Comment: nesse site tem o exemplo do php Serial em uso no linux, no final tem o comando pra porta serial funcionar.
http://www.embarcados.com.br/sistema-web-com-raspberry-pi-e-arduino/
Comment: Vou dar uma conferida assim que possível e estarei retornando o resultado.
Answer: Já tentou via socket? Segue um exemplo básico:
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($sock,"188.8.131.52", 8081); // Ip e porta que você configurou no seu arduino
socket_write($sock,'l', 1);
socket_close($sock);

Para mais funções e melhor entendimento consulte o manual do php.
Espero que ajude, abraços.

Comunicação Serial Com PHP e Arduino


Alternative to libraries_get_path() to get a JavaScript file path

Question: I was crafting the following code in order to alter the path to a JavaScript file.
function MY_MODULE_js_alter(&$javascript) {
      $sm_path = libraries_get_path('soundmanager2'). '/script/soundmanager2.js';
      $javascript['sites/all/libraries/soundmanager2/script/soundmanager2-nodebug-jsmin.js']['data'] = $sm_path;
      }

It works fine, but the only thing that bothers me is that libraries_get_path() is provided by the Libraries API module. Is there an internal Drupal 7 function to act the same way?
Answer: You can get the same data using drupal_get_library(), but it's not in a friendly format so you'll have to dig into the array yourself. For example, the following code will get the same path as your current code but in a much less less satisfying manner (in my opinion anyway):
$lib = drupal_get_library('soundmanager2', 'soundmanager2_debug');
$sm_path = array_shift(array_keys($lib['js']));

As I understand it this is actually the reason there's a need for the Libraries API to exist...so this sort of thing can be managed in a structured manner.
Comment: Definitely, this useful libraries_get_path() function should be included in Drupal core, what do you think?
Comment: Yes it would definitely be helpful, in fact there's an [open issue](http://drupal.org/node/667058) on drupal.org requesting the addition of the Libraries API in it's entirety to core for Drupal 8. Unfortunately it won't be back-ported to D7 core from what I can tell.
Comment: @onirio It will not back-ported because it is too late for adding new modules to Drupal 7 core.
Answer: drupal_get_library() returns a library that is between those libraries a module defines in its hook_library() implementation. If there isn't a module that defines that JavaScript library with hook_library(), then drupal_get_library() is not a valid alternative to libraries_get_path().
If you just want to look for a library, without requiring the Libraries module as dependency for your module, you can use libraries_get_path(), and libraries_get_libraries() code to write your own function.
I would rather make a module dependent from the Libraries module for the simple fact you don't need to maintain that code. It is up to you to decide if creating a dependency from the Libraries module is worth being done, in your case.
The alternative to make the Library module a dependency for your module, and copying the code used from the Libraries module is to hardcode the location where your module is looking for the JavaScript library. Considering that users are already used to the Libraries module, and considering that more than one module could use the same JavaScript library your code is using, I think the Libraries module is still the valid solution to your case.


Copying MySQL Blob Rows - to other rows with a different username

Question: OK - I updated from Horde Webmail 3 to Horde Webmail 4.
In that transition, the 'horde_prefs' table now shows that the 'pref_value' field is of type BLOB.  Previously, it was of type LONGTEXT.
When setting up new accounts, I want to give all of the users default preferences before the user logs in - to ensure that they all have the proper default preferences.
Before, I simply created a PHP script with all of the default values as SQL entries - and inserted them with the username.  Now, because these are BLOB entries, I cannot do so.
So in essence, the table has four fields:
pref_uid (the username)
pref_scope (the application that the preference is set for - like horde, ingo, imp, etc)
pref_name (the name of the preference - such as last_login, last_maintenance, etc)
pref_value (the BLOB entry that contains the actual preference)
So - there might be 20+ rows for one user account and all the preferences.
I'd like to copy all of the rows from one user (say firstname.lastname@example.com) to make the default preferences for the new user (say email@example.com)
Is there any way that this can be done?
Thank you!
Answer: It is possible like the following:
<code>insert into horde_prefs(pref_uid, pref_scope, pref_name, pref_value)
select 'firstname.lastname@example.com', pref_scope, pref_name, pref_value
from horde_prefs
where email@example.com'
</code>
the insert into .. select .. works with blobs too.


mention slack users in prometheus alertmanager notification

Question: So I have a common label opsteam that is supposed to bring DM in slack once alertmanager is fired. However inside slack I get usernames as pure text, not highlighted and these users are not getting any messages.
nodeSelector:
  prometheus: "true"
enabled: true
retention: "30d"
extraFlags:
  - web.enable-lifecycle
  - web.enable-admin-api
strategy:
  type: RollingUpdate
global:
  scrape_interval: 30s
  external_labels:
    env: prod
    client: client
    cluster: project-prod-eks
    opsteam: "@U0325FRAD @U01GN7KJHU"

If I change opsteam: "@U0325FRAD @U01GN7KJHU" to opsteam: "@john @jim" it does no effects either.
so this is my custom slack notification
 notifications.tmpl: |
  {{ define "__alert_silence_link" -}}
      {{ .ExternalURL }}/#/silences/new?filter=%7B
      {{- range .CommonLabels.SortedPairs -}}
          {{- if ne .Name "alertname" -}}
              {{- .Name }}%3D"{{- .Value -}}"%2C%20
          {{- end -}}
      {{- end -}}
      alertname%3D"{{- .CommonLabels.alertname -}}"%7D
  {{- end }}

  {{ define "__alert_severity" -}}
      {{- if eq .CommonLabels.severity "critical" -}}
      *Severity:* `Critical` {{ if eq .Status "firing" }}:fire:{{- else -}}:ok:{{- end -}}
      {{- else if eq .CommonLabels.severity "warning" -}}
      *Severity:* `Warning`
      {{- else if eq .CommonLabels.severity "info" -}}
      *Severity:* `Info`
      {{- else -}}
      *Severity:* :question: {{ .CommonLabels.severity }}
      {{- end }}
  {{- end }}

  {{ define "__alert_client_details" -}}
      *Env:*     {{ .CommonLabels.env }}
      *Client:*  {{ .CommonLabels.client }}
      *Cluster:* {{ .CommonLabels.cluster }}
  {{- end }}

  {{ define "slack.title" -}}
      [{{ .Status | toUpper -}}
      {{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{- end -}}
      ] {{ .CommonLabels.cluster }} - {{ .CommonLabels.alertname }}
  {{- end }}

  {{ define "slack.text" -}}
     {{ .CommonLabels.opsteam }}  <<-----------------WANT THEM TO BE User Mentions!!!!!
     {{ template "__alert_severity" . }}
     {{ template "__alert_client_details" . }}
     {{- if (index .Alerts 0).Annotations.summary }}
     {{- "\n" -}}
     *Summary:* {{ (index .Alerts 0).Annotations.summary }}
     {{- end }}

     {{ range .Alerts }}
       {{- if .Annotations.description }}
       {{ .Annotations.description }}{{- "\n" -}}
       {{- end }}
       {{- if .Annotations.message }}
       {{ .Annotations.message }}{{- "\n" -}}
       {{- end }}
     {{- end }}

  {{- end }}

  {{ define "slack.color" -}}
      {{ if eq .Status "firing" -}}
          {{ if eq .CommonLabels.severity "warning" -}}
              warning
          {{- else if eq .CommonLabels.severity "critical" -}}
              danger
          {{- else -}}
              #439FE0
          {{- end -}}
      {{ else -}}
      good
      {{- end }}
  {{- end }}

Yes my messages are just text in slack.
Answer: There is a given format to embed usernames in Slack.
https://api.slack.com/reference/surfaces/formatting#mentioning-users

<@userId>


Projections onto closed and convex sets

Question: I have to prove that if $A$ is convex and closed set, then $z=P_A(x)$ for all $z\in A$ if and only if $\langle x-z, z-y\rangle \geq 0$ for all $y\in A$
I have following proof which is not much complicated, but I don't understand few things.
If $g(\theta)=||x-((1-\theta)z+\theta y)||^2, \theta \in R, z=P_A(x), y\in A$ is quadratic function of the variable $\theta$ and it has minimum at $\theta =-\frac{\langle x-z,z-y\rangle}{||z-y||^2}$
Now there is a part that I don't understand:
For $z=P_A(x)$, from convexity of a set A, we get $g(0)\leq g(\theta)$ for  all $\theta \in [0,1]$, so $\theta_{min} \leq 0$.
I know why $g(0)\leq g(\theta)$ (I can see it by simply putting $0$ in function), but I don't know how convexity of $A$ caused that and why did we take $\theta$ from $[0,1]$.
The rest of the proof is ok.
Would anybody try to make this clear to me?
Answer: If $z$ is the projection of $x$ to $A$, then it's the closest point to $x$ in $A$.  If $y$ is any other point in $A$ and $0\leq\theta\leq 1$, then $(1-\theta)z+\theta y$ is in $A$ because $A$ is convex.  (Notice that this would not follow if $\theta$ were outside $[0,1]$.)  So the distance from $x$ to this point $(1-\theta)z+\theta y$ in $A$, must be at least the distance from $x$ to $z$.  Square both sides of that inequality (because squared distances are algebraically nicer than distances in Euclidean space), and you get $g(\theta)\geq g(0)$.  So $g(\theta)$, with $\theta$ restricted to $[0,1]$, takes its minimum value at $\theta=0$.
Comment: Ok, everything you wrote is now clear to me. But I wrote above that $\theta_{min} \leq 0$. Can it $\leq 0$ if we choose it from $[0,1]$? It's written so in the proof in the book.
Comment: As far as I can tell, $\theta_{\text{min}}$ (which isn't defined in the material you quoted) is supposed to be the value of $\theta$ where the quadratic function $g(\theta)$ has its minimum value. It need not be in $[0,1]$; in fact, the only way it could be there is if it is $0$. What's involved here is that, if a quadratic function (in your case $g$) has a lower value at $0$ than elsewhere in $[0,1]$, then its minimum (the bottom of its parabola-shaped graph) must occur at a point $\leq0$.

Projections onto closed and convex sets


Is there a symbol for the median of a population?

Question: We usually use $\mu$ for the population mean but I couldn't find a symbol the median of a population. Is it ok to use just $m$? For instance,
$H_o: \ m_{a} = m_{b}$
$H_a: \ m_{a} <> m_{b}$
is it Ok to formulate these hypotheses like that?
Comment: Personally, I like it.  But you're not just going to drop these symbols in out of nowhere, right?  You'll follow up with "where $m_a$ is the median value for population $a$"?
Comment: The world is too big, rich, and complicated to allow us to reserve our limited numbers of symbols for specific purposes.  That is why people *describe* and *define* their terminology.  That also allows you the creativity to use whatever notation you think might best convey your ideas to your audience.  Thus, hypotheses formulated as you have shown are in themselves meaningless, but when accompanied by your explanation of what $m_a$ and $m_b$ refer to, are perfectly fine.
Comment: I know $m_a$ is the median value for population $a$, but only from the context of the question.  My point is that you can use whatever symbol you want as long as you tell the reader what you're doing.  Which is @whuber's point.  And PS I like $m$ just fine.
Comment: @The Laconic, yes, $m_a$ stands for the median value for population a.
Comment: @whuber. Yes, but as there is the $\mu$ symbol for the mean, I supposed there would be some symbol for the median. Maybe the median is underused compared to the mean?
Comment: Agreeing with everyone, I'd say that sometimes it is convenient to use ``m`` for the sample mean, especially when typesetting code (shorter to write ``mx`` than ``x_bar``, ``x.bar`` or ``xbar``), and some authors do use it for consistency (as in: sigma --> s, beta --> b, mu --> m). For that reason, I'd avoid using ``m`` for the median. I would favour capital ``M`` or go for an explicit ``Med`` or ``med``. Or tilde. But either way, you must define it clearly.
Answer: I have seen a number of symbols used to denote the population median.
One I have seen quite a few times is $\tilde\mu$, but as whuber suggests in comments, you should define whatever you do use. So if you were to use this suggestion, you could say something like:

$H_0: \ \tilde{\mu}_{a} = \tilde{\mu}_{b}$
  $H_a: \ \tilde{\mu}_{a} \neq \tilde{\mu}_{b}$
$\text{where }\tilde{\mu}\text{ denotes the population median.}$

It would be okay to use $m$ for that, just as you have it in your question (as long as you define it) -- though keep in mind that conventionally population quantities are denoted by Greek symbols, which is probably why $\tilde\mu$ tends to crop up.
You'd also need to be clear (somewhere) about the meaning of the subscripts $_a$ and $_b$. (Note also the use of $\neq$ in preference to $<>$.)
Comment: There's a distinction between  $\bar{\ }$ (bar) and $\tilde{\ }$ (tilde) over something. They're not at all the same symbol. The first *is* used to denote sample means but the second is used for a variety of purposes, often as some sort of variant of a more common thing, including $\tilde{x}$ representing the sample median (akin to but distinct from $\bar{x}$ for the sample mean). It is also sometimes used to denote a population median by analogy to that use.
Comment: I've never seen $\tilde{\mu}$ as the population median, but sometimes I've seen $m$. The bar, as in $\bar{x}$ is usually used for sample mean, the tilde, I don't know. Anyway, I think you're right about population parameters written using Greek symbols. I think that $\mu$, as being the lower case for $M$ in the Greek alphabet, is ok to denote the median too. Furthermore, R language uses mu as a parameter for some statistical test Indistinctly for mean or median.
Answer: I am currently in an introduction to statistics class and the textbook says that the median of a statistic can be represented with an "M" (a capital m). And the median of a parameter can be represented with a "θ" (a theta). This is as straightforward of an answer as you are going to get, though I am sure the way you handled the situation would work just fine also.
Answer: The Greek letter Eta (η) can also be used to represent the population median. Check this from Wikipedia: In Statistics, η2 is the "partial regression coefficient". η is the symbol for the linear predictor of a generalized linear model, and can also be used to denote the median of a population, or thresholding parameter in Sparse Partial Least Squares regression.
Comment: I don't understand the value of the question but I have nothing against your answer.
Answer: You can refer to the median as $Q(a,50\%)$, i.e. the 50th percentile, and write the null hypothesis as:
$$H_0: Q(a,50\%)=Q(b,50\%)$$
This notation is longer than the other notations here, but its meaning is probably more obvious. So you probably would want to clarify that $Q$ is the quantile function, but readers might understand the reference to the median automatically.


If String Is Contained By Brackets, Remove Them

Question: I'm trying to write a function that will take input, check to see if it has "[" as the first char and "]" as the last and remove them if it does. The string may have more brackets in them, if that's the case then I need to print an error statement. Everywhere I've looked, I've seen examples of how to do this if it were just the two brackets, but I need to check if there are any more as well, and that's where I'm getting confused.
I've seen examples of using regex, and I know that if I can find a string with just the two brackets on the outside, I can use substring to trim it, but I can't figure out how to check the string for the instances of brackets without remvoing all of them.
Help would be greatly appreciated. Thanks.
Comment: `String` has a number of useful methods for checking its contents.
Comment: You could use `substring` to trim the outside brackets and then check if the trimmed string `contains` any brackets
Answer: if(str.chatAt(0) == '[' && str.charAt(str.length()-1) == ']') //str.matches("\\[.*\\]")
{
    str = str.substring(1, str.length() - 1);
}
if(str.contains("[") || str.contains("]")) //str.matches(".*[\\[\\]].*")
{
    //throw your error
}

Posted potential regex solutions beside the if statements. Warning: Not the greatest at regex, so they may not be correct.
as @Ingo pointed out in the comments, str.charAt(0) will fail on empty string.
Comment: Fails for the empty String.
Comment: @Ingo Yes, added that to the answer. The regex version should be fine I think though.
Answer: You can use String.charAt(int) for do it:
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#charAt%28int%29
Answer: Since you claim to know what you are doing to trim the leading and trailing brackets, it sounds like the missing link is the .contains() method on the String class.
if (myString.contains("]") || myString.contains("["))
    throw new Exception("myString contains invalid brackets");


Pickups and selector switch stop buzzing when touched?

Question: I just recently built a Les Paul style guitar, and, for some reason, when I touch the pickups and selector switch the guitar stops buzzing.
Why?
Answer: That is normal.
The strings are earthed so when you touch them your body becomes earthed and no longer acts as an antennae and electrical hum is reduced.
Nearly every other conductive part on a guitar should also be earthed for noise reduction reasons.
If a part isn't earthed and you touch it (while not touching something that is earthed..) the hum will generally increase.
If the hum reduction when touching the pups/selector still occurs when you are already touching the strings that would imply your strings are not earthed. Did you run a wire from one of the bridge post holes to earth?
Comment: @scrowler If you are implying that humbuckers are quieter than single coils, then I agree that is generally true, their construction cancels more EMI. If you are implying earthing issues (which the OP describes) are "not so common for humbuckers" then you are wrong. The quality of the earthing has nothing to do with the pickup type installed.
Comment: Not so common for humbuckers in fact (standard pickups with Les Pauls)... Agree when using single coil pickups.
Comment: There are very valid reasons why guitars should not have their strings (or tuners, bridges or other metallic parts) grounded. It creates a situation where the guitarist can close a loop through badly wired A/C circuits, which can cause a shock, or even death. It's better to shield the controls and possibly do what Taylor does in their electrics, and use a shunt that'll open in case of a ground-loop. Modern building codes should having wiring that won't case a problem, but old buildings, or badly wired stages, can be dangerous.
Comment: @theTinMan Your reasoning can be applied to all appliances, yet my toaster, oven and computer (and guitars of course..) all have their metallic cases earthed, and for good reason. If there is a fault and the casing becomes electrified a large current will flow via the earthing system and the mains fuse (or RCD/GFCI) will blow and the current will cease to flow, this occurs pretty much instantaneously. If the part was not earthed it will remain live until something with a viable path to earth touches it, usually the user...
Comment: As for Taylor, they still earth their strings, the only difference is that it is via a 10 mA fuse (not a 'shunt'), which  will blow under fault conditions (not simply a ground loop which in audio systems introduce noise rather than shock hazard, generally). This is a bad idea as once the earth path is disconnected by the fuse blowing the only other path for current to flow to earth is via the player...
Comment: Taylor calls it a "shunt", so I used their terminology. The strings are not grounded when the fuse/shunt blows, instead the connection to the strings is broken entirely, and, if you're holding the strings, you won't get shocked as the circuit to the strings, and hence the player, no longer exists. I've got two Taylors with them in it; One currently is blown and the guitar works fine, albeit with a bit more noise which goes away if I touch the pickup casing to ground myself.
Comment: In my youth, I played my guitar through an old tube radio.  I once bent down trying to put a slightly skewed stage panel (they had metal liners) back into position while with the other hand still grabbing the guitar by the neck.  The metal liners obviously were leading somewhere where they were grounded, and the power supply of the tube radio was not AC-decoupled enough (old transformers with lots of icky waxed paper in them and stuff) to be fun.  Since the mains was 220VAC, I probably got about half.  So I removed the ground connection for the strings (I was young and needed the money).
Answer: I saw this video

 about noise going off when touching which is a tell tale sign that there is no grounding problem (if it were the problem then noise would get louder by touching rather than going altogether, I checked it for myself by doing the continuity test myself with a DIY circuit of light bulb because I don't own a multimeter and there was no problem in grounding) There are various videos about checking continuity of ground wire and components and so do it for yourself(maybe you can find a cold solder which may occasionally touch and works). I recommend that anyone facing similar issue to watch the video I mentioned above as when I did for myself by touching grounded surface (Can be any metallic home appliance plugged into socket like fridge, CPU case, heater, etc.) other than guitar the noise seem to go away. After seeing this video searched up online and found various videos about filtering power supply from high frequency interference, and guess what, when you plug a normal speaker the noise is there too. I coincidently own a extension plug which has RF and other filters, and when I connect my amp to that then, BAM the noise just goes away. You can also purchase one from any reputed brand you know. Generally speaking such extensions are usually marketed as computer extension socket, but you ask or check specifications(RF filters and others) for yourself, or any electrician may help you with that as it is easy compared to changing house wirings.(You can watch this video

 for the same, anyone can understand basic concept shown (don't try for typical and higher concepts, if aren't from the field or aren't interested) and try to understand. Worked from me and hope other find it useful too.....
Answer: My experience is that single coil pickups are quite susceptible to this, but humbuckers much less so or not at all.
I have seen the same effect vary from guitar to guitar.. bass with single coil buzzed horribly. Strat with single coils less so. Same player, same amp (yes, I know.. bass through guitar setup .. there were reasons)
So I see that this can vary from guitar to guitar. Strats often have a bit of tin foil mounted (glued) on the inside of the scratch plate to help with this issue. As for earthing the strings : variable - sometimes yes, sometimes no, but mostly they are earthed in my own experience.
My Les Paul in the same setup as above didn't buzz at all. Humbuckers .. clue's in the name  ;-)
I'd conclude that this isn't really "normal" for a Les Paul (sorry!).
Things you could check ..

Is your lead well earthed ? Some 'look' like they are (ie all
soldered up properly) but something breaks down in the shilding in
the lead and they become noisy, sometimes giving strange results.
Does any other guitar buzz like that through the same setup ?
IYou say you just built the guitar- is it all wired up properly ? (though I bet you've checked that) I'm at the edge of my knowledge here but I gather it's possible to set what looks like one humbucker up as just two single coils so that you don't get the hum cancelling effect. That would be the wiring between the two coils of the pickup itelf
If you set it to the middle position, (both pickups), does the hum go away ? If so this hints at the pickups behaving more like single coils than humbuckers.

Hope this helps.


Cronjob can not execute smartctl?

Question: I have a cronjob installed (Ubuntu 16) that runs with the root user. So in
sudo crontab -e
I have the following entry:
10 5 * * mon /home/userA/raidchecker.sh
And the script raidchecker.sh does this:
#!/bin/sh
mail=`which mail`
rec="firstname.lastname@example.com firstname.lastname@example.com"
now=$( date +%Y%m%d-%H%M-%S )
mdstat=$( cat /proc/mdstat )
details=$( /sbin/mdadm --detail /dev/md2 )
diskusg=$( df -kh )
disk1=$( smartctl -A /dev/sda | grep Realloc | grep Sector )
disk2=$( smartctl -A /dev/sdb | grep Realloc | grep Sector )
disk1f=$( smartctl -A /dev/sda )
disk2f=$( smartctl -A /dev/sdb )
buddyinfo=$( cat /proc/buddyinfo | grep Normal )

echo "Check from $now\n\n=================\nMemory Fragmentation:\n$buddyinfo\n\nAll partitions:\n\n$mdstat\n\n=================\nData Partition:\n\n$details\n\n=================\nDisk Usage:\n$diskusg\n\n=================\nSMARTCTL:\n\nData Disk /dev/sda and sdb:\n$disk1\n$disk2\n\nFull Reports:\nDisk1:\n$disk1f\n\nDisk2:\n$disk2f" | $mail -s "Check from $now" $rec

When I execute the script manually from the shell ./raidchecker.sh the email contains all infos as expected.
When the cronjob executes the script, the parameters disk1, disk2, disk1f and disk2f are empty (do not contain any data).
Why?
Comment: Did you run the script manually with the same user as in the crontab?
Comment: sorry my bad ... Try appending `2>&1` to the cronjob https://stackoverflow.com/questions/4883069/debugging-crontab-jobs
Comment: i don't know. I run the script as root. the crontab has been setup by using the same user.
Comment: @HenrikPingel: did that, no more info in the email. In the syslog I see this : `CRON[9476]: (root) CMD (/home/userA/raidchecker.sh 2>&1)`
Comment: I think i found it out. cronjob can not find the command `smartctl`
Comment: Thank you @HenrikPingel, I added `2>&1` not only to the cronjob but also to those command lines where smartctl is used, so I now found out that cronjob (running as root) could not find the command `smartctl`, i now inserted the full path and it is working! THANKS
Answer: The solution was to use /usr/sbin/smartctl instead of smartctl in the script, only this way the cronjob could execute this command.
Answer: Using a crontab, most of the usual environment set for a regular user login is absent or reduced (unless you set it), when the script is run automatically by cron.
To be sure, it's better to either provide a relevant PATH, or give the absolute path to all commands.
Always test a crontab (setting a time a couple minutes after the current time).

If you want to receive (by email) the standard and also error output, only add  2>&1 to the command in the crontab
If you do not want to receive any of the output of the crontab command (by email), add  > /dev/null 2>&1

Cronjob can not execute smartctl?


Bash: not absolute script #! interpreter?

Question: Is it possible to say to a script to search for an interpreter not in an absolute location, but in his path?
For example, writing #!/usr/bin/php will fail if the user has php installed somewhere else.
Just writing #!php does not automatically work, of course, and I couldn't find anything about it, they just all treat this method as if it was "the way"® to do it.
So, is there a standard simple syntax to say "search for it anywhere in your path"?
Answer: Try:
#!/usr/bin/env php

Comment: Thaaaank you :D I love you for this


SVG filter can't be rendered in React

Question: I am trying to load a SVG filter (in this case <feGaussianBlur>) to the graphic element <rect> in an web application that uses React(15.0.1). The code looks something similar to this
In component1.js :
render(){
   return(
      <defs>
        <filter id='blur'>
          <feGaussianBlur stdDeviation="5" />
        </filter>
      </defs>
      <component2 />
   );
}

In component2.js:
render(){
  <rect x="some_xpos"
        y="some_ypos"
        height="some_height"
        width="some_width"
        filter="url(#blur)"
  >
  </rect>
}

All these components are to be rendered on the same html page but somehow the filter is not applied when the entire page renders. I have looked into different options:

option1 : export the svg filter to its own .svg file in a public asset folder and url() that using public url. Didn't work because of a Chrome bug link
option2 : put the <filter>  in the main (and the only one) index.html file where the entire app renders. I also put that at the very top wrapped with its own <svg> tag. Didn't work.

It seems to me the <rect> couldn't figure out where the filter is. I would appreciate any advices on how to debug this or alternative for loading svg filter.
Comment: I don't know react, but reading some issues on the github project about xmlns attributes, it seems you need `dangerouslySetInnerHTML`. https://github.com/facebook/react/issues/2250
Comment: It would be better if you show the test case that reproduces the error on some services like jsfiddle.net [ https://jsfiddle.net/pmvo81ac/ ]
Comment: thanks for the link, will try to repro it
Comment: I believe it's the lowercase `c` in ``. Works fine with a capital-C ``: https://jsfiddle.net/pmvo81ac/1/
Comment: I tried that on my app, it still didn't work. But thanks for the suggestion.
Answer: SVG elements must be created in the SVG namespace if you're going to directly create them in the DOM. And from what I can see, React does not support that. The workaround, as Kaiddo mentions in the comments is to create the elements as raw innerHTML.
Answer: the best workaround is to use "style" as follows:
<rect x="some_xpos"
        y="some_ypos"
        height="some_height"
        width="some_width"
        style={ {filter: 'url(#blur)'} }
  >

SVG filter can't be rendered in React


Views: How to sort in Table format naturally

Question:
Create view.
Select Format: Table.
Under the Table Settings toggle Sortable on.
Fields gets arranged/sorted unnaturally 1 2 3 4 40 5 50 51 6 60, etc. both ways ascending and descending.

The module Views Natural Sort does not solve the problem, it works only with fields under Sort criteria settings. And it's pretty broken in overall, the option to sort doesn't even appear in my Views.
We want to sort in normal natural way 1 2 3 4 5 6 7 8 9 10
Answer: Try to install Views_bootstrap module.
Then in views/Format select Bootstrap Table

Don't forget the Settings
Comment: Isn't this for bootstrap theme only.
Comment: Yes, if you're not using bootstrap theme then try with the settings in table Format
Check Sortable - Default order and default sort


SELECT SUM mysql

Question: I need to select a sum of data for every day where employees belong to a department, I want to be able to select a date range and have a summary of every day is this possible, at the moment i am just getting a summary of the whole date range in one field.
This is my query at the moment
select
  date,
  SUM(no_of_live_products)
from
    fulfilment
INNER JOIN
  employee
  ON  employee.employee_id = fulfilment.employee_id
where
      employee.department = 'Telecoms    Services'
  and date >= '2013-09-16'
  and date <= '2013-09-29'

Is it possible to get a summary of data for every day within that date range or not?
Comment: Seems like you should add a GROUP BY.
Comment: Ordinarily, you cannot return data that does not exist. There are some hacks for fudging this in MySQL but generally it's better to handle application level logic at the 'application level'.
Comment: cheers @X.L.Ant That worked a treat
Comment: @Strawberry I was trying to work out the logic in mysql to be able to then do it at the application level now I've fixed it cheers anyway
Answer: You can
GROUP BY `date`

to see the sum per day
Comment: you life saver! I will make your answer the accepted answer shortly
Answer: If you want to get the number of days and you have several time ranges,
First, get the number of dates for a single time range, then sum these up (needs a subselect).
Take this as an example, it's not a complete query for your situation:
SELECT SUM(x.days)
FROM (
    SELECT TIMESTAMPDIFF(DAY, startDate, endDate) AS days
    FROM fulfilment
) x
GROUP BY employee.employee_id

Comment: Thats a good query to get the difference in days thank you but not what I was after, may come in handy in the future though
Answer: why not try
SELECT
  date,
  SUM(no_of_live_products)
FROM
    fulfilment
INNER JOIN
  employee ON  employee.employee_id = fulfilment.employee_id
WHERE
      employee.department = 'Telecoms    Services'
  AND date >= '2013-09-16'
  AND date <= '2013-09-29'
GROUP BY date(date)

Comment: Cheers I have fixed this using the same method but mentioned further up. Much Appreciated

SELECT SUM mysql


Fermat's Little Theorem & Euler's Theorem

Question: Make a table showing the values of
$a, a^2, a^3, a^4, a^7, (a^3)^7$ modulo 33 for 0 ≤ a ≤ 16, expressing the entries as integers in the
interval [−16, 16]. Explain why two of the columns are the same.
I understand this question involves those two theorems but I don't know where to begin. Do I use Euler's totient function on each of the powers and find what each a is congruent to in mod 33?
Comment: Welcome to Maths SX! Using it for $\;(a^3)^7$ will be enough.
Answer: Euler's theorem states $$a^{\varphi(n)}\equiv 1\mod n$$ for $(a,n)=1$. For $n=33$ we hence have $$a^{20}\equiv 1\mod 33$$ for $(a,n)=1$ , which implies $(a^3)^7=a^{21}\equiv a\mod 33$
It remains to show that $a^{21}\equiv a\mod 33$ is true as well for $a$ not coprime to $33$.
If $a$ is divisible by $3$ , but not $11$ , we get $a^{10}\equiv 1\mod 11$ (This time Fermat's little theorem) , implying $a^{21}\equiv a\mod 11$. Because of $a^{21}\equiv a\mod 3$ and the chinese remainder theorem, we get $a^{21}\equiv a\mod 33$
If $a$ is divisible by $11$ , but not $3$, we get $a^2\equiv 1\mod 3$ implying $a^{21}\equiv a\mod 3$. Analogue to the first case, we get $a^{21}\equiv a\mod 33$.
Finally, if $a$ is divisible by both $3$ and $11$ , we get $a\equiv 0\mod 33$ immediately implying $a^{21}\equiv a\mod 33$
Hence, the first and last column must coincide.


The optimal value is continuous in the parameter

Question: Let $f:(0,\infty) \to [0,\infty)$ be a continuous function satisfying $f(1)=0$, which is strictly increasing on $[1,\infty)$, and strictly decreasing on $(0,1]$. Define
$$
F(s)=\min_{xy=s,x,y>0} f(x)+ f(y), \, \,  \, \, \text{for } \, \, s \in (0,\infty).
$$
Claim: $F$ is continuous.

I am looking for a reference for such a claim. (not that claim exactly, but perhaps a slightly more general claim which implies it , or is similar to it).

I think that it follows from a result in the book "Perturbation Analysis of Optimization Problems" by Bonnans and Shapiro, but that book phrases things in much more abstract setting than I find necessary.

BTW, here is my proof:
Suppose that $s \le 1$.
Define $g(x,y)=f(x)+f(y)$. Suppose that $s_n \to s$. Write $F(s_n)=g(x_n,y_n)$ for some $x_n,y_n \in [s_n,1]^2, x_ny_n=s_n$. By compactness we may assume that $x_{n_{k}} \to x, y_{n_{k}} \to y$. Thus
$$
F(s) \le g(x,y)=\lim_{k \to \infty} g(x_{n_k},x_{y_k})=\lim_{k \to \infty}F(s_{n_k}) \le \liminf F(s_n).
$$
On the other hand, take $(x,y) \in (0,\infty)^2$ such that $xy=s$ and $F(s)=g(x,y)$. Now take $x_n,y_n$ such that $x_ny_n=s_n$, and $(x_n,y_n) \to (x,y)$. Then
$$
F(s_n) \le g(x_n,y_n) \Rightarrow \limsup F(s_n) \le \lim_{n \to \infty}g(x_n,y_n)=g(x,y)=F(s).
$$
Comment: I am not certain. I think that it implies the result, but I am not sure since there are quite a few definitions to unpack. This makes the abstract statement less appealing to me, since I thought there should be a rather simple, concrete and easy to state claim which implies the result. (and indeed Martin R's answer provides such a thing.)
Comment: Is the book result abstract to the point of ambiguity (i.e.unclear if it entirely proves the result)?
Answer: That is a consequence of the following theorem:

If $X,Y$ are topological spaces and $Y$ is compact. Then for any continuous $f:X\times Y\to\mathbb{R}$, the function $g(x) := \inf_{y\in Y} f(x,y)$ is well-defined and continuous.

Source: Continuity of the infimum, by Willie Wong. See also Infimum is a continuous function, compact set.
In our case we have
$$
 F(s) = \inf_{x > 0} f(x) + f(s/x) \, .
$$
In order to apply the above theorem we fix $0 < s_1 < s_2$ and show that one can replace the $\inf_{x > 0}$ by an infimum over a compact set if $s$ is restricted to $[s_1, s_2]$: Let
$$
 x_1 = \min(1, s_1) \, , \, x_2 = \max(1, s_2) \, .
$$
Then, due to the given monotony conditions on $f$,
$$
 x < x_1 \implies f(x)+f(s/x) \ge f(x_1) + f(s/x_1) \\
 x > x_2 \implies f(x)+f(s/x) \ge f(x_2) + f(s/x_2)
$$
and therefore
$$
 F(s) = \inf_{x_1 \le x \le x_2} f(x) + f(s/x) \, .
$$


How does Indian and Western Musical contain Seven Notes ? Is it a Coincidence?

Question: How does Indian (sa,re,ga,ma,pa,dha,ni) and Western(c,d,e,f,g,a,b) music have seven notes ? Is it a coincidence or someone copied from other ?
Answer: In general, scales tend to have about seven notes in them, or "seven, plus/minus two". This number is believed to have to do with cognitive limitations; it would be difficult to recall more notes. On the other hand, scales with fewer notes impose more melodic and harmonic limitations.
In order to answer whether or not it is a coincidence that Indian and Western scales happen to have seven tones, one would have to know if there were cultural exchanges in the antiquity.
I don't know much about Indian theory, but they do have a different system with shrutis and all the ornaments, which probably have no direct counterpart in early Western music.
Answer: There are many, many answers to your question, and all answers come from a slightly different standpoint.
If you want a relatively recent scholarly view on scales, check out the notion of maximal evenness. Basically, it suggests that Western and non-Western scales may be constructed (both in terms of number of pitches and intervals between them) in such a way as to be spread out evenly and almost-symmetrically. (But that is a pretty gross oversimplification, beware!)


JS: For loop continues to iterate after condition is false

Question: Does anyone know what would cause my for loop to continue after the conditions are met? I would post the entire file, but it is quite large. Here are the loops:
for (var j = 0; j < depKeyArr.length; j++) {
    var directory = angular.copy(dependencies[depKeyArr[j]]),
        keyArr = angular.copy(Object.keys(directory));
    for (var i = 0; i < keyArr.length; i++) {
        var next = i + 1;

        if (keyArr[i] && !keyArr[i].includes('Params')) {
            if (keyArr[next] && keyArr[next].includes('Params')) {
                directory[keyArr[next]] = directory[keyArr[next]].split(', ') !== [''] ? directory[keyArr[next]].split(', ') : undefined
                directory[keyArr[next]].push(directory[keyArr[i]])
            }
            var paramArr = directory[keyArr[next]] ? directory[keyArr[next]] : directory[keyArr[i]]
            switch (depKeyArr[j]) {
                case 'controller':
                    angular.module('app').controller(keyArr[i], paramArr)
                    break
                case 'directive':
                    angular.module('app').directive(keyArr[i], paramArr)
                    break
                case 'factory':
                    angular.module('app').factory(keyArr[i], paramArr)
                    break
                case 'filter':
                    angular.module('app').filter(keyArr[i], paramArr)
                    break
                case 'service':
                    angular.module('app').service(keyArr[i], paramArr)
                    break

            }
        }
    }
}

So depKeyArr.length in this particular instance equals 5, and keyArr.length equals 42. Both the for loops continue to execute when those conditions are met, in spite of the fact that I would expect them to stop at 4 and 41. Any help you can offer so I can figure out why would be great.
Snippet updated above!
Also - you all mentioned i & j changing, but when I'm looking at it in the debugger, they are unchanged. I am looking at it right now - j = 5 and depKeyArr.length is 5. Similarly, i = 42 and keyArr.length is 42...and yet I'm inside both loops, specifically at the last case in the switch statement. It fails when keyArr[i] is undefined.
In response to the answer provided by OBDM, I added angular.copy() to prevent updating the array from inside the loop. It is still stepping into the loop when the boolean condition is met. What is even more perplexing is the fact that even the if condition doesn't keep it from executing the switch. It should fail to enter the following if:
if (!keyArr[i].includes('Params'))

because by then keyArr[i] is undefined.
Latest update -
It seems that I have successfully broken out of the inner loop with the latest changes, but it still continues to the switch statement and breaks on keyArr[i] even though that switch is within both loops and an if conditional which evaluates to false.
Comment: If the inner loop continues to iterate, how do you know that the outer loop does too? In regards to your outer loop, wouldn't j never get past 0?
Comment: try to use break with labels: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label
Comment: Are you sure that `i` and `j` are changing nowhere than `for`?
Comment: @JoaozitoPolo I looked into this, but I suppose I would need a conditional, because I only want to break out of the loops when the conditions are exceeded...but this bug is ignoring the conditionals within the loops and it just directs right back to the last switch statement. It's the strangest thing...
Answer: genrally speaking it is a bad practice to set the stop condition of loop with a "dynamic value" i.e a value that can be changed while iterating over the loop.
the following code generates an infinite loop:
for (var j = 0; j < depKeyArr.length; j++) {
   depKeyArr.push("whatever");
}

rather than setting the stop condition in a variable prevents from unclear behavior:
var depKeyArrLen = depKeyArr.length;

for (var j = 0; j < depKeyArrLen; j++) {
   depKeyArr.push("whatever");
}

Comment: As for your latest point about setting the length in a variable, I have never had to do that before. I'm more in favor of copying the array by value so that the array it is looping is static.
Answer: "Does anyone know what would cause my for loop to continue after the conditions are met? I would post the entire file, but it is quite large. Here are the loops:"
Im not sure what the "//blah blah more code", but in here what you need to make sure in that part is no operation involving value change of variable i and j, because usually we do a sequence loop of i, j, k, l, and so on, if you have another loop inside that bla bla more code and unconsciously put j because after i, you know what happened later..
Comment: Can you explain this a bit more? "unconsciously put j because after i, you know what happened later.." There is no loop in there, but there is a switch. I did not intentionally update `i` or `j`, but I will look for that.
Comment: what kind of switch is that? does it update i or j also?
Answer: For anyone who may come across a similar scenario, this is simply the odd behavior that happens when the program was failing to attach the final angular service in the loop.
I went over it and over it and finally had to take a big step back and question the assumptions. I was assuming that the loops completed successfully, which they did not. That was the answer.


É uma má prática verificar Auth nos components que quero travar?

Question: Eu tenho a seguinte logica de autenticação
 initAuthListener() {
    this.afAuth.authState.subscribe(user => {
        if (user) {
            this.store.dispatch(new Auth.SetAuthenticated());
            this.router.navigate(['/training']);
        } else {
            this.trainingServices.cancelSubscriptions();
                this.store.dispatch(new Auth.SetUnauthenticated());
                this.router.navigate(['/login']);
        }
    });
}

Como o app.component estava
 ngOnInit(): void {
this.authService.initAuthListener();
                 }

Toda primeira chamada na pagina ia para /login, então eu passei a verificação para o training.component, que é onde precisa ter autorização.
É uma pratica ruim? Qual seria minha alternativa?

Eu modifiquei da seguinte maneira, aparentemente está ok:
initAuthListener() {
    this.afAuth.authState.subscribe(user => {
        if (user) {
            this.store.dispatch(new Auth.SetAuthenticated());
            this.router.navigate(['/training']);
        } else {
             if((this.ROTAS_LIBERADAS.includes(this.router.url))){
                    this.trainingServices.cancelSubscriptions();
                    this.store.dispatch(new Auth.SetUnauthenticated());
                }else{
                    this.trainingServices.cancelSubscriptions();
                    this.store.dispatch(new Auth.SetUnauthenticated());
                    this.router.navigate(['/login']);
                }
        }
    });
}

Comment: melhor vc usar um router guard https://angular.io/guide/router#canload-guard-guarding-unauthorized-loading-of-feature-modules Se não vc teria que duplicar essa lógica em todo componente que precisa de autenticação
Comment: @EduardoVargas obrigado pela dica, vou dar uma lida na doc que você me passou. Eu olhei por alto e parece que é o que estou usando, mas posso estar enganado.
Comment: então respondendo sobre a má pratica eu fazia isso antes, preferi salva um token no cokkies e depois conferir ele no middle do backend axo que desgasta menos o servidor, imagina a cada click vc ter que fazer uma requisição
Answer: A pratica que uso é a descrita na doc do angular usando uma service com um metodo chamado CanActived e colocando a validação nas rotas.
Exemplo:
auth-guard.service.ts
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class AuthGuardService {

  private isAuthenticated: boolean = true;
  constructor() { }

  canActivate() {
    return this.isAuthenticated;
  }

  login(){
    return this.isAuthenticated = !this.isAuthenticated
  }
}

app.module.ts
@NgModule({
  declarations: [

  ],
  imports: [

    RouterModule.forRoot([
      { path: 'login' , component: LoginComponent },

      { path: 'welcome', canActivate: [AuthGuardService], component: WelcomeComponent }

    ])
  ],
  providers: [AuthGuardService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Comment: Eu voltei ao padrão. Na implementação do canActivate e canLoad em auth-service eu fiz a lógica que eu precisava. Verificando se a rota é liberada caso não esteja logado e verificando a Role caso logado.
Comment: Boa! É bem melhor seguir os padroes pois fica mais facil dar manutençao
Comment: Esqueci de agradecer :D Obrigado  :)


Restrict forum access based on user (user list)

Question: I need to restrict access to forums so that only selected users can access an individual forum. (The users should apply for a forum and a moderator should decide if the user should be allowed to participate in that forum or not.)
If users visit the forum listing page for the first time, they should only see all forums listed but they should not be able to see the topics.
I have used Flag module to implement a subscription system.
I have set a flag 'subscribe_forum' that allows users to flag a forum, and another flag 'approve_forum_subscription' that allows an administrator to flag a flagging, which means the subscription of the user is accepted.
What I want to do is to grant that user access only to those forums which he has subscribed to and has been approved by an administrator.
The solution you would suggest doesn't have to use this flag system. I am open to any other suggestions.
I have installed Forum Access module, however it allows me to restrict access based on roles, but I need to have a list of users for each individual forum. The only thing that is useful for my case on this module is the ability to set a moderator for individual forums.
Edit: I am also using Advanced Forum module to extend the functionality of the core Forum.
UPDATE:
I have mostly achieved my goal using Panel pages which are already provided by Advanced Forum, adding some custom selection rules.
I have added a PHP Code rule which returns TRUE if the user has flagged the forum, and a moderator accepted it (i.e. flagged the flagging of the user), and FALSE otherwise. I have also added a fallback variant which shows only an 'access denied' message in a panel pane.
I have done the same thing to the topic listing panel, as well.
Then, I have enabled the panel page that overrides node/node% and added 2 selection rules, one for checking if the content type is forum and the other one is the custom PHP.
So, I have almost what I wanted to have, but I am not yet completely sure if this method I follow is a good one. To be honest, I don't find it elegant enough.
I am still open to other suggestions. It can also be a completely different approach.
Thanks in advance.
Comment: Since your requirement is very much aligned with Organic Groups, have you considered using OG to build a forum-like site rather than using a regular forum?
Comment: It's probably possible but I think it will require some development effort. Last time I checked OG and Forum weren't integrated.
Comment: I am already using OG in this site to build some groups. But we need also a forum solution like I described, which should be moderated independent of those OG Groups. I am also using Advanced Forum module to expend the core Forum functionality. Would it be possible to create a new group type that integrates with core or Advanced Forum so that I can restrict the access to each forum to the members of this new group type?
Comment: I am going to give a try to [OG Forum D7](https://drupal.org/project/og_forum_D7) latest dev version.
Comment: I have tried it with OG Forum D7, but I couldn't create a second group type to assign it for forum users. I get an error about a database table already exists, which I guess related to OG 7.x-2.x rather than with OG Forum D7. Nevertheless, I couldn't get it work with this approach. Apart from that, the OG Forum D7 is also not very stable yet.
Answer: If you use views or panels to display the forum, you can use their access controls which are quite flexible. Doesn't look like AF has built views for everything, so I think the easiest way would be to use Panels.
Create a page and under the page settings you have access rules that can be quite elaborate within the UI. You can use a naked layout and then just had the forum entities as content to display and render the full node.
Second Look:
Take a look at the Drupal Module Flexiaccess. It looks like exactly what is needed and has a nice UI to manage the users that have access to the individual forum with out writing/maintaining custom stuff:

The Flexi Access module will provide a simple and flexible interface
to the ACL (Access Control List) module. It will let you set up and
mange ACLs naming individual users that are allowed access to a
particular node.
The module let you manage access to individual nodes. The
administrator may grant individual users the right to: View (read),
update (edit/write), and delete the node.
The main idea behind Flexi Access is to allow flexible per user access
control for nodes without the complexity (or features) of Organic
Lists, and without having to create a lot of (overlapping) roles.

I see you using Flag to set up the "subscription request" then a moderator looks at the flagged users with the Flag and if approves add em to the ACL with flexiaccess?
Comment: Hi Tom, thank you for your advice, I was also going with Panels which has integrated access rules, and I am writing some custom PHP to check if the user has flagged the forum and if the flagging is accepted by a moderator. I'll let you know about the success, if I could get it how I want it to be.
Comment: Thanks. How are you moderating the flag? A user flag puts it in the moderate queue and a second moderate flag for the forum access? Depending on the who you moderate, I bet there is an elegant way to do the access with in configuration rather than the custom code.
Comment: I have updated my post. I have 2 type of flags, one for flagging forums, and one for flagging the flaggings. Every user can flag a forum, but only administrators can flag the flaggings. I have made a view for administrators that lists all users which have flagged a forum. In this view, they can also flag this flaggings as approved.
Comment: I couldn't find in the interface any other way to check if the user has flagged the forum and it is accepted by an administrator. That's why I wrote a custom PHP to check the flaggings using Flag 3 API.
Comment: I havent done this before, but it looked like the double flag would be required. Thanks for the update on your strategy.
Answer: Maybe this is more reliable and worth trying:

Create a user list in views with the subscribed users for every forum. In this view you should use the nid of the forum type as a contextual filter.
Install and enable Rules Bonus Pack and Conditional Rules modules.
Create a rule that will trigger on the event: "When a page variant is loaded" where the page variant = the forum page
In that rule set an action "Load a user list with views" to load the above view
Add a loop through that list
Inside this loop add a conditional and then an Add if condition: uid of current user is not in that list (Data/List contains item/Negate)
Finally continue (inside the same loop) by adding an action to redirect the user to some other page and if you want, add another action for the system to send a message like: "Your subscription has not yet been approved by the admin" or something.

I understand the answer is a bit brief. In case you need more details or some help with the rule let me know.
Answer: Since you want the most granular form of permission ( per-user), without too much of investigation, I would check:
https://drupal.org/project/user_permissions
Second way (non-entirely Drupal, but working)
Or writing a custom module that does this functionality.(Gets list of users and a simple field 1 or 0, then in hook node preprocess  (php) , you can add some simple logic, to show specific thing only if the value is 1.
Also, that will involve some CRUD operations.
There might be other answers though.
Regards
Comment: Thank you for your answer. I have looked at the User Permissions module, but as far as I see it doesn't have any rules integration or something else so that I can imply it some logic. I could write a custom module as well, but I wish I knew the logic I should follow..


Permission Issues for User 1

Question: I have added pages, webform, and views to my site to customize the User profile experience. I can access mysite.org/user and it shows my user profile page as customized. I have a link on that page to Edit the user profile which is formatted as mysite.org/user/1/edit this works fine. I also have realname module installed so the Edit button on the User profile tabs has the url mysite.org/user/my-real-name/edit This link does not work. It gives an access denied when used even from the User 1 account. I have researched this over and over and over. I can't find the cause or the fix. Any ideas?
I've checked permissions, I've gone through the panel page, the view. I've disabled things and tried it and still issues. I'm at a total loss on what to do.
Comment: are you sure a url alias is being assigned using the real-name parameter?
Comment: Yes, Just checked it.
Comment: assuming you have customised the edit via panels, have you tried disabling panels entirely for that page?
Comment: I didn't customize the edit via panels. The only thing I did to the Edit was created a webform which I then used Views to create a page which rendered the webform at user/%/edit/My_Details
Answer: I don't think Real Name does what you think it does.  At least not by default.  The module is primarily for using parts of the user account other than the username when the user account is displayed (such as the by-line on an article).
You can set the edit link to send people to mysite.org/user/my-real-name/edit but unless you've done something to make that URL exist, which I'm not sure you can do with this module, it won't do anything.
Comment: Then why does `mysite.org/user/my-real-name` work? I also have [Pathauto](http://drupal.org/project/pathauto) as well as subpathauto so this should take care of creating those links
Comment: it follows the same idea that you can go to a url alias of:  /this-is-the-node-title, but by default, the edit page would be: node/12/edit - unless there is something specifically overriding that default behaviour
Comment: Geoff is right, just because `user/%` has an alias, it doesn't mean that `user/%/edit` will have a similar alias.
Comment: Although it appears subPathAuto should handle that, I would look in the settings for that module.
Comment: The subpathauto module is set to 3 depth and it works on other content with the /edit argument. It's just not working on the user node.
Comment: Perhaps SubPathAuto has a bug, or it is something to do with the known issue listed on the project page. I suggest checking the issue queue if you haven't already.
Answer: This has nothing to do with the Real Names module.
There are 2 Types of links in Drupal:

system links like /user/1 or /node/240
and alias links like /user/johndoe or /content/about (they point to system links and are generated by modules like Pathauto)

While most of the site is accessible via alias links generated by pathauto, certain admin links require arguments on the system link: /content/about/edit does not work – /node/240/edit is the correct link, because there is no alias for the edit link.
Same with the user page: You can't mix system links (accepting special arguments like /edit) with path aliases. The only way to do that would be to generate a separate alias for all argument links (e.g. an alias for /node/240/edit, /node/240/delete) – some sites actuallay do that, via Rules for example.
Comment: That's why I have the module [subpathauto](https://www.drupal.org/project/subpathauto) installed. It does this all links.
Comment: Ah, okay, that's not very common – you should mention this in your original post.

Permission Issues for User 1


Highcharts sankey diagrams multiple series

Question: I would like to have multiple series in my sankey diagram so that the legend adjusts along.

For now, I have to have to trick with an empty data series:
series: [{
  name: 'New allocations',
  keys: ['from', 'to', 'weight', 'color'],
  data: sortedData,
  centerInCategory: true,
  showInLegend: true,
  color: 'pink',
  colorByPoint: false,
  nodes,
}, {
  name: 'Current allocations',
  keys: ['from', 'to', 'weight', 'color'],
  data: [], // Only added so that it is displayed in the legend :(
  centerInCategory: true,
  showInLegend: true,
  color: 'blue',
  colorByPoint: false,
  nodes,
}]

But it doesn't feel correct for color handling, nor tooltip content.
Thanks
Comment: You mean something like in this [example](https://jsfiddle.net/BlackLabel/q0L3jdy2/)?
Comment: Thanks for getting back. Well, the example you submitted uses the same trick as I did, by not setting any data to legend series. But then, one can't hover the legend and see only related links, which would be the expected behavior. Shouldn't Highcharts merge the series at some point?
Answer: A possible solution would be to use hide() and show() methods, another thing is to set the color to transparent.
Unfortunately, I don't see an option to not have the whole date in the following series because otherwise the series is added to the whole width of the chart.
  var series = chart.series[1];
  if (series.visible) {
    series.hide();
    e.target.innerHTML = 'Show apples';
  } else {
    series.show();
    e.target.innerHTML = 'Hide apples';
  }

Demo:
https://jsfiddle.net/BlackLabel/q0L3jdy2/3/
API References:
https://api.highcharts.com/class-reference/Highcharts.Series.html#hide
https://api.highcharts.com/class-reference/Highcharts.Series.html#show


What are my options when it comes to saving and reloading data with Quill.js?

Question: I am making a note taking app and it is in the early prototyping stages, so I just want to hack together something that will work for myself.
My text editor is built using Quill, and I'm using Vue to structure the whole application. Currently, I don't have a back end, so no server.js.
I would like my application to be able to save the information that I put in the editor, and reload the information whenever I rebuild the app.
I checked out the autosave option provided by Quill here
But I'm not sure what to do with $.post and where to post it.
Can I simply post it to a local .json file?
What is the best thing to save in my case? The example was logging changes, what am I supposed to do with changes?
I apologize beforehand for the lack of clarity in my question, as I don't know exactly what I should be asking to achieve what I want.
Any advice is appreciated.
Answer: So if I understood correctly, what you're asking is how to implement quilljs' auto save feature when you have no server. But, you've already answered your own questions.

A simple way to do it would be saving the document into a local json file. But I don't know if you can do that using js.
Another way of doing it, is to save the content to the browser's local storage and loading the data every time you load the app.
var Delta = Quill.import('delta');
var quill = new Quill('#editor-container', {
  modules: {
    toolbar: true
  },
  placeholder: 'Compose an epic...',
  theme: 'snow'
});

// Store accumulated changes
var change = new Delta();
quill.on('text-change', function(delta) {
  change = change.compose(delta);
});

// Save periodically
setInterval(function() {
  if (change.length() > 0) {
    console.log('Saving changes', change);
    // Save the entire updated text to localStorage
    const data = JSON.stringify(quill.getContents())
    localStorage.setItem('storedText', data);
    change = new Delta();
  }
}, 5*1000);

// Check for unsaved data
window.onbeforeunload = function() {
  if (change.length() > 0) {
    return 'There are unsaved changes. Are you sure you want to leave?';
  }
}

Then inside your vue component's mounted(), use the following to fetch the saved data:
const data = JSON.parse(localStorage.getItem('storedText'));

Comment: Hey Stormix, im trying to understand your answer (im a noob) What do you mean with the vue components mounted?
Comment: Oh, OP was using Vue js, which has a lifecycle hook called mounted that is executed whenever the page/component are rendered. Think of it as a 'on page load' listener.
If you're not using vue js, then you can ignore that part, and just get the stored info whenever you want using that snippet.


Angular 9 route url changing but view not rendered

Question: I've made a blog app with angular where a component called blog-details containing the details of the blog is rendered on the left side and two other components of called recent blogs and categories are rendered on the right side of the component. Now, when I'm trying to change the blogs by recent blogs, the route URL is changing on the browser but the detailed view of the new blog is not getting rendered on the blog-detail component till I manually refresh the browser. In case you want, you can check my entire Github repository from here
blog-detail.component.html:

{{currentBlog.title}}

      <app-recent-blog></app-recent-blog>
      <app-blog-category></app-blog-category>

blog-detail.component.ts:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute} from '@angular/router';
import { BlogpostService } from '../blogpost.service';
import { Blogpost } from '../../models/blogpost';
import { Title } from '@angular/platform-browser';

@Component({
  selector: 'app-blog-detail',
  templateUrl: './blog-detail.component.html',
  styleUrls: ['./blog-detail.component.css']})
export class BlogDetailComponent implements OnInit {
   public currentBlog: Blogpost;
     constructor( private route: ActivatedRoute, private router: Router, private blogpostService: BlogpostService, private titleService: Title) { }
 ngOnInit() {
    console.log('blog-detail ngOnInit called')
    let myBlogId = this.route.snapshot.paramMap.get('id');
    console.log(myBlogId);
    this.blogpostService.getSingleBlogInformation(myBlogId).subscribe(
                (data: Blogpost) =>{ console.log(data); this.currentBlog = data; }
                error =>{ console.log("some error occured");}

routing-module:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { RecentBlogComponent } from '../recent-blog/recent-blog.component';
import { BlogCategoryComponent } from '../blog-category/blog-category.component';
import { BlogDetailComponent } from '../blog-detail/blog-detail.component';

const routes: Routes = [
  {path: 'blog/:id', component: BlogDetailComponent}];

@NgModule({
  declarations: [
    RecentBlogComponent,
    BlogCategoryComponent,
    BlogDetailComponent ],
imports: [
    RouterModule.forChild(routes),
    CommonModule,
    ClientRoutingModule,
    FormsModule,
    ReactiveFormsModule
  ],
  exports: [
    RouterModule,
    RecentBlogComponent,
    BlogCategoryComponent,
    BlogDetailComponent
  ]
})
export class ClientModule { }

Answer: Have to use the AsyncPipe in the HTML template to subscribe to an Observable and return the latest value it has emitted and also switchMap in the component code to send a new request each time as the param changes

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute, ParamMap} from '@angular/router';
import { switchMap } from 'rxjs/operators';
import { Observable } from 'rxjs';

public currentBlog$: Observable<any>    //take currentBlog value as an Observable

constructor(
    private route: ActivatedRoute,private blogpostService: BlogpostService,private titleService: Title) {}

ngOnInit() {
let myBlogId = this.route.snapshot.paramMap.get('blogId');
this.currentBlog$ = this.route.params.pipe(
      switchMap((params: ParamMap) =>
                    this.blogpostService.getSingleBlogInformation(params['blogId'])));}

Answer: I believe you want to update component when url is updated.
In BlogDetialsComponnt you need to change ngOnInit implementation.
add import switchMap:
import { switchMap } from 'rxjs/operators';

ngOnInit should be like:
ngOnInit() {
  const currentBlog = this.route.params.pipe(
    switchMap(params => {
      this.blogpostService.getSingleBlogInformation(params[id]);
    })
  )
}

now currentBlog will be updated every time router id param is updated
Your example is displaying changes after page refresh because component knows only first id, and every further update is ignored. So after page refresh, component is initiated with new id.


Firefox & NPAPI plugins: can they be restricted (to be only used on certain pages)?

Question: I've been reading this and I know it doesn't mention possible ways to restrict access to an installed plugin, but is there some trick one can play in order to contain the usage of a plugin?
Comment: Hope I clarified the question correctly. [Why do you want to do that though? If your plugin gives the page special permissions, it seems quite scary - e.g. a successful XSS attack on your page means the plugin can be used by the attacked. Just something you should keep in mind]
Comment: On Chrome, it is possible to restrict usage of a plugin to an extension. Thus it is conceivable to craft a plugin with special "powers" and control access to these. I am wondering if the same sort of thing can be done on Firefox.
Comment: FWIW, there are some extensions that use a plugin, e.g. cooliris. I don't know if they restrict the plugin usage to the extension somehow, might be worth checking.
Answer: You could write your plugin to query window.location and then refuse to work if it doesn't match up with what you want =]
I don't know of another way to do it, though.
Comment: hmmm... that's not exactly what I had in mind but it might be sufficient. Thanks.


Transition not showing between views in a custom UIStoryboardSegue

Question: I have written a custom UIStoryboardSegue.
The only code in my CustomSegue.m file is:
<code>-(void) perform {
    UIViewController* sourceViewController = (UIViewController *) self.sourceViewController;
    UIViewController* destinationViewController = (UIViewController *) self.destinationViewController;

    UIWindow* window = UIApplication.sharedApplication.keyWindow;
    window.rootViewController = destinationViewController;
    window.rootViewController = sourceViewController;

    [UIView transitionWithView: sourceViewController.view.window
                        duration: 0.5
                         options: UIViewAnimationOptionTransitionFlipFromLeft
                      animations: ^{window.rootViewController = destinationViewController;}
                      completion: ^(BOOL finished) {}
     ];
}
</code>
If I set up a storyboard so it just has two UIViewControllers, with a button on the first linking to the second, all works as planned: there is a flip from left transition.
But: if I place a UINavigationController before the first UIViewController, the segue now brings up the second view controller without doing a flip from left.
What is going on? Why doesn't the transition work with a navigation controller?
Thanks for your help!
(In case you're interested, the reason I'm using a custom segue is so that I can have a master-detail view appearing after some intro pages. I am inspired by this Stackoverflow answer.)
Answer: I never resolved this, but found a simple workaround. I removed the navigation controller from the front, but put one after the segue instead. I then put a simple navigation bar at the top of the source screen. The segue also triggered adding a back button to the destination view controller. My custom segue thus became a "pseudo push" segue.