Prove if If $m \in Z^+$, $a|m$, and $b|m$, then $\mbox{lcm}(a,b) \leq m$.

Question: Let $a,b \in Z^+$. Define $\mbox{lcm}(a,b) := \frac{ab}{\gcd(a,b)}$.  Prove that $\mbox{lcm}(a,b)$ is the smallest (positive) integer that is evenly divisible by both $a$ and $b$.
I am trying to prove this using 3 conditions. I have proved the first two so far (and wrote their proofs below) but I am unsure how to prove the 3rd point.
1) $\mbox{lcm}(a,b) \in Z^+$,
2) $a| \mbox{lcm}(a,b)$ and $b|\mbox{lcm}(a,b)$, and
3) If $m \in Z^+$, $a|m$, and $b|m$, then $\mbox{lcm}(a,b) \leq m$
1) $\mbox{lcm}(a,b) \in Z^+$
It was stated that the least common multiple of $a,b$ was defined to be $\mbox{lcm}(a,b) := \frac{ab}{\gcd(a,b)}$. We know that $a, b \in \mathbb{Z^+}$, and that $gcd(a,b) \in \mathbb{Z}$, based on the definition of the greatest common denominator.
Also from the definition of the $gcd$, we know that it divides both $a$ and $b$. For this reason, we know that $\frac{ab}{\gcd(a,b)} \in \mathbb{Z}$. This is because when simplified, the denominator will cancel, and then whatever is remaining in the numerator can be written over $1$, which allows us to conclude it is an integer. Thus we have proved $\mbox{lcm}(a,b) \in Z^+$.
2) $a| \mbox{lcm}(a,b)$ and $b|\mbox{lcm}(a,b)$
As stated before, $\mbox{lcm}(a,b) := \frac{ab}{\gcd(a,b)}$. We also know that if $a|\mbox{lcm}(a,b)$ and $b|\mbox{lcm}(a,b)$, then $a \cdot k = \mbox{lcm}(a,b)$ for some $k \in Z$, and also that $b \cdot j = \mbox{lcm}(a,b)$ for some $j \in Z$.
Looking at the equation stated for $lcm$, we can say that the '$k$' to make $a| \mbox{lcm}(a,b)$  true  is $\dfrac{b}{gcd(a,b)}$, and the '$j$' to make $b|\mbox{lcm}(a,b)$ true is $\dfrac{a}{gcd(a,b)}$. Clearly since there exists values to make these claims true, we can conclude that $a| \mbox{lcm}(a,b)$ and $b|\mbox{lcm}(a,b)$.
3)   If $m \in Z^+$, $a|m$, and $b|m$, then $\mbox{lcm}(a,b) \leq m$
??
Comment: What a strange definition of lcm...
Comment: The usual way to do these things is, I believe, to deal with the case when $a,b$ are coprime first. Then you can use the fact that if a number is divisible by two coprime numbers, it is divisible by their product. It really depends on what sort of tools you're allowed to use.
Comment: $a,b\mid m\iff \text{lcm}(a,b)\mid m\implies \text{lcm}(a,b)\le m$.
Answer: Let $d=\gcd(a,b)$, and let $a=da_1$ and $b=db_1$. Note that $a_1$ and $b_1$ are relatively prime and that $\frac{ab}{\gcd(a,b)}=da_1b_1$.
It is clear that $da_1b_1$ is divisible by $a$ and $b$. We show no smaller positive integer is divisible by $a$ and $b$.
Suppose that $m$ is divisible by $a$ and $b$. Let $m=am_1=da_1m_1$. Since $m$ is divisible by $b$, $db_1$ divides $da_1m_1$, so $b_1$ divides $a_1m_1$. But $a_1$ and $b_1$ are relatively prime, so $b_1$ divides $m_1$, say $m_1=b_1m_2$.
Then $m=da_1m_1=da_1b_1m_2$, and therefore $da_1b_1$ divides $m$. This completes the proof.


Windows 2012: how to make power button work in every cases?

Question: I need some Windows 2012 servers to be shutdown properly with the power button.

If nobody is logged, the power button correctly shuts down the server
If somebody is logged without a blocking program, it's okay too

But:

if a session is locked, the power button does nothing
if somebody is logged with a blocking program (notepad with an unsaved document for example), the button does nothing too

With previous Windows versions I was used to configure the power button behaviour with the GUI and modify a registry key (HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\system\shutdownwithoutlogon) but this seems not any more relevant.
Does anyone knows the "offical" way, or a trick ?
Edit:
The system log display an event each time I press the power button. The kernel power manager has initiated a shutdown transition with event ID 109.
When the session is locked, this event is followed by nothing. And no other events in other logs.
When a program refuse to close, I have the corresponding log entry, so this will be okay soon.
Comment: Show those damn smart switches who's really smart: yank the F^&%#ing power cord out of the wall!
Answer: The fact you can't power down a 2012 server when a session is locked is probably by design. I faced a similar need and don't know any policy or registry change to allow that.
I used a simple trick: I captured the power button event which simply run my favorite shutdown.exe with the desired parameters after a timeout.
If you use the correct shutdown parameters, you won't be blocked by open programs.
To capture events, just open the task scheduler and create a task triggered on the desired event ID.
Comment: Also for reference the event in my case is a basic event with these properties Log: System, Source: Kernel-Power, Event-ID: 109
Comment: For reference, the command I use is: shutdown /s /t 10 /d p:0:0
Answer: Check out AutoEndTasks:
You can set it for all users by creating the key here vs HKCU:
HKEY_USERS.DEFAULT\Control Panel\Desktop
Additionally, there is some tuning that can be done via group policy that can be found here:
Computer Configuration>Administrative Templates>System>Shutdown Options>
Turn off automatic termination of applications that block or cancel shutdown
Additional tuning options that you may want to look into are:
WaitToKillServiceTimeout,WaitToKillAppTimeout,HungAppTimeOut
I'll also second what MarcoZink stated, check your Bios and verify there isn't any special setting configured for your power button that may be holding things up.
Comment: I would not second what MarcoZink stated about the BIOS because the question clearly states "If nobody is logged, the power button correctly shuts down the server"


Simplification of proof for $\exists c>0$ such that $|x+y|\leq c(1+\sqrt{x^2+y^2})$

Question: Question: Consider function $f(x,y)=|x+y|$ for $x,y\in \mathbb{R}$. Show that $\exists c>0$ such that $|x+y|\leq c(1+\sqrt{x^2+y^2})$.
My proof:
i) if $|x|,|y|\leq 1$, then $|x+y|\leq 2\leq 2(1+\sqrt{x^2+y^2})$;
ii): if $|x|\leq 1$ and $|y|\geq 1$, then $|x+y|\leq 1+|y|\leq 1+\sqrt{x^2+y^2}$;
iii): if $|x|,|y|\geq 1$ such that $|x|\geq |y|$, then $|x+y|\leq2|x|\leq2(1+\sqrt{x^2})\leq 2(1+\sqrt{x^2+y^2})$.
Hence, we conclude, and $c=2$ works for the claim.
However, I feel like there should be a simpler proof which does not prove in a case-by-case way like I did.
Answer: Notice that
$$|x|=\sqrt{x^2}\leq\sqrt{x^2+y^2}\quad\text{and}\quad|y|=\sqrt{y^2}\leq\sqrt{x^2+y^2}$$
and so
$$|x+y|\leq|x|+|y|\leq 2\sqrt{x^2+y^2}<2\left(1+\sqrt{x^2+y^2}\right)$$
Answer: $|x+y|\leq |x|+|y|\leq 2\sqrt {x^2+y^2}\leq2\sqrt {1+x^2+y^2}$
Answer: Write $x=r\cos\phi$, $\>y= r\sin\phi$, assuming $r>0$ (the case $r=0$ is trivial). Then it is about the inequality
$$r(\cos\phi+\sin\phi)\leq c(1+r)\ ,$$
or
$$\cos\phi+\sin\phi\leq c{1+r\over r}\ .$$It is well known that here the LHS is $\leq\sqrt{2}$, and the given value is reached for $\phi={\pi\over4}$. Therefore we have to make sure that
$$c{1+r\over r}\geq\sqrt{2}$$
for all $r>0$. Now ${1+r\over r}>1$, and $\lim_{r\to\infty}{1+r\over r}=1$. It follows that the smallest $c$ for which the given inequality holds throughout is $c=\sqrt{2}$.


std::vector to boost::python::list without copy the data

Question: My question is basically the same as std::vector to boost::python::list. The difference is that I only need to read data from C++ in python side.
Naively, I could build a new C++ class holding a pointer and forward all the required attributes and then expose this new class to python. Is there a better(simpler or systematic) way to get a python 'list' (not really a list since setter is not allowed) without copy the underlying data?
Answer: If you do not want to convert std::vector to boost::python::list. Then it can be possible if you pass the size of vector to python side and iterate the function with argument as index to get the element of vector to python side.
in cpp:
class vc
{
    private:
        vector <int> vec ;
    public:
        vc(){};
        void set_vector();
        int vector_size();
        int vector_iterator(int index);
        ~vc(){};
}

void vc::set_vector()
{
    for(int i=0;i<10;i++)
        this->vec.push_back(i);
}

int vc::vector_size()
{
    return this->vec.size();
}

int vc::vector_iterator(int index)
{
    if(this->vec.size()> index)
        return  this->vec[index];
    return 0;
}

BOOST_PYTHON_MODULE(vector_imp)
{
    class_<vc>("vc", init<>())
        .def("set_vector",&vc::set_vector)
        .def("vector_size",&vc::vector_size)
        .def("vector_iterator",&vc::vector_iterator)
    ;
}

in python:
import vector_imp as vect
    vc_obj = vect.vc()
    vc_obj.set_vector()
    v_size = vc_obj.vector_size()
    for i in range(0,v_size):
        element = vc_obj.vector_iterator(i)
        print element


How do you normally structure your Menus?

Question: I am using the Sitemap module, and in order to display the pages available on the site, I need to enable which Menus are displayed. It then lists them in sections, with a Menu title above each section.
I have 5 menus at the moment, so the sitemap generated looks very messy. What is the best way around this? How do you structure your Menus so it all looks neat in the Sitemap, but is also functional?
Also, do you  normally rename the Main and Navigation menus to Primary links and secondary links, or do you leave them as they are? Do you  hide the Menu headings from being displayed in the Sitemap?
Comment: You have a number of things in here that there is no difinitive answer for so you might find it hard to get concrete answers. For example, "do you normally rename the Main and Navigation menus to Primary links and secondary links, or do you leave them as they are?" and "Do you hide the Menu headings from being displayed in the Sitemap?" etc. have no right or wrong answer, but only subjective answers based on what you want for the current website.
Answer: One option you have is to leave your menus as they are and use CSS to style the page so it appears nicer.
You can do things like reduce the amount of space between menus.
Another way (this depends on your sites menu requirements - it may not fit with what you need), is to have primary links be your sitemap.
Add everything you want in your site map to the primary links, going in as many levels deep as you need.
Then don't actually display all the levels in your menu (unless you want to and have deep drop down menus).
Then have the site map just display the primary links menu.
This will give you a nicer looking site map.
In my opinion, site maps are something drupal does not do well (short of doing something more custom). I have never seen a satisfactory result (to my standards) from using the site_map module.
Another option would be to use the menu_block module, which would allow you to create a bunch of menu blocks for specific menus (and levels of those menus), which you could then position on your site map page in a grid (or whatever layout you prefer).
This allows you to be very specific with what is displayed on the sitemap and how it is displayed.
Menu blocks also means you can customise the heading specifically for that block, without changing the name of the menu.
You could assign the blocks to a node page that has some introduction text for the body, of you could use something like the empty_page module to add a non-node sitemap page to assign your blocks to.
You can call your menus whatever you prefer, but I would not rename them to primary and secondary links. It is better to use more semantic names.
This is important in cases where you want the menu title displayed with the menu, and also when the menu title is there but hidden, to give screen readers better context, for accessibility.
Whether or not to display the manu titles in the site map also depends on your site setup and what you want to achieve.
If your menus are for distinct sections of the site it might be useful to have those sections stated in the sitemap, however if the title is not really relevant, for example "Main manu", "Navigation", "Footer links" etc., then it would likely be best to not show them.
Comment: If this answer does not contain enough detail you might have to mention what you would like further clarification on, because I addressed all your questions.
There is no definitive answer to most of your questions as they are subjective. For example, you ask whether or not to hide the titles, but that depends on what you want for your site, there is no right or wrong answer.
Comment: Thank you @rooby

Did it work? As in the points? I clicked it but it still looks greyed out to me ...


PGP Encryption in U-SQL and/or Azure Data Lake Store

Question: Without spinning up a VM instance, is it possible to add PGP encryption to data already in Azure Lake Lake Store? Theoretically, it seems this should be possible with a registered c# binary (dll) in U-SQL but theoretically this would require treating files as blobs (or as text), and I'm not sure how one would do that from U-SQL?
The use case is to take data from the lake, encrypt it as PGP/GPG using a public key, and then land the data into an ADLS location for pickup by an external team (subsequent egress from ADLS).
Any ideas?
Comment: Possibly relates to: https://stackoverflow.com/questions/4192296 (C#+PGP)
Answer: You can write a custom extractor and outputter that can then do the decryption/encryption. This would most likely look something like this (at the abstract level):

Extractor:
AtomicFileProcessing=true
d = decrypt(input.baseStream)
for each row in d.Split do outputrow end // or whatever the right processing is

Outputter:
AtomicFileProcessing=true
serialize rows into outputstream
encrypt outputstream and write to output

Note that there are some examples on the example section in our U-SQL GitHub page that show how to operate on data at the basestream level.
You will want to avoid having to load more than 500MB of data into main memory though if you can. So it would be good if the encrypt/decrypt could be done in a streaming way.


Como salvar arquivo em PDF de uma página embutida?

Question: Eu preciso de fazer o download ou salvar o arquivo PDF de uma página embutida.
Porém, ao acessar a página de download o seletor "#download" não é encontrado, devido estar embutido. Este seletor é o botão para download.
Segue o código que estou usando
<code>const puppeteer = require ('puppeteer'); //biblioteca puppeteer

async function getdados ()  {

    const inscricao = '015440380448440' //número da inscrição consultada

    const browser = await puppeteer.launch({ headless: false }); //abre o browser
    const page = await browser.newPage(); //abre nova aba

    await page.goto('https://emissao.cuiaba.mt.gov.br/portal/'); //acessa a primeira página
    await page.waitForSelector('body');    //aguarda carregar.
    await page.waitForSelector('#form1');   //aguarda carregar.
    await page.goto('https://emissao.cuiaba.mt.gov.br/portal/EmissaoGuia.aspx');  //acessa a segunda página
    await page.type('#ctl00_ContentPlaceHolder1_txt_inscricao', inscricao, {delay: 100}); //clica na barra e digita a inscrição
    await page.click('#ctl00_ContentPlaceHolder1_BtnContinuar'); //clica no botão continuar

    page.on('dialog', async dialog => {
        await dialog.accept();
    }); //aceita caixa de alerta se houver

    await page.waitForSelector('#ctl00_ContentPlaceHolder1_ASPxGrdVwPadrao_cell0_0_chk'); //aguarda carregar a 1º caixa de guia.
    await page.click('#ctl00_ContentPlaceHolder1_ASPxGrdVwPadrao_cell0_0_chk')//clica na 1º caixa de guia.
    await page.click('#ctl00_ContentPlaceHolder1_BtnContinuar')//clica em gerar guia

    await page.waitForSelector('body > embed'); //aguarda carregar a página da guia.

    const url = page.url() //captiura a url atual
    console.log(url) // verifica se a url refere-se a url da guia.

    await page.click('body > embed'); //clica no corpo da página

    const download = await page.evaluate(() => {
        const uiElement = document.querySelector('#download');
        return uiElement
      }); //Procura o selector "#download"

    await page.click(download); //clicka no botão de download.

};

getdados ()
</code>
Comment: Para fazer a ação de salvar o PDF seria necessário um biblioteca para maniputação de PDF? Digo isso porque ao tentar utilizar o comando Ctrl+S não funcionou. Este comando faria abrir a pasta para salvar o arquivo.
Answer: eu ja tive um problema parecido. No chrome, quando vamos abrir um pdf o robo nao consegue clicar nos indicadores dos pdf (download, imprimir etc...). Mas, ao rodar o robo com o 'headless=true' o puppeteer baixa o pdf quando clica no botão que abre ele no navegador.


Run a service after the phone has been unlocked for a variable amount of time

Question: I'm looking for a method to run a service after a certain amount of time. However, I cannot use the standard AlarmManager for this problem as I don't want to rely on my app being running all the time, and AlarmManager takes into account the time when the phone is locked.
Basically, the goal is for a service to run after the user has been using their phone for a set amount of time, such as one hour. This timer should allow for breaks in the time when the phone is locked or turned off.
Comment: `AlarmManager` does not require your "app being running all the time". In fact, it is specifically designed so that your app should not be "running all the time".
Comment: When my app is force stopped by the user or the system, all alarms associated with my app no longer function. However, my app is ordinarily only stopped for at most a couple of seconds, so this generally isn't a problem. It is a problem for figuring out how long the phone has been in use however, as I cannot just keep a running process keeping track of the time elapsed, as this will be reset when my application is stopped for a short amount of time.
Comment: "When my app is force stopped by the user or the system, all alarms associated with my app no longer function" -- and on Android 3.1+, your whole app will no longer work, until something runs one of your components manually (e.g., user launches one of your activities from the home screen).
Answer: After a bunch of research, I found that the best way to do this was the following:

Create a service that is run every 10 seconds by the setRepeating method for an AlarmManager.
If the app that creates the AlarmManager is ever stopped, once the app restarts, just restart the repeating alarm as well.
When the service runs every 10 seconds, check if the phone is locked using the following code:
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
boolean locked = keyguardManager.inKeyguardRestrictedInputMode();
If the phone isn't locked, then have the service increment a database variable that keeps track of time by 10 seconds.
Also have the service check after it updates the database whether or not the total unlocked time is more than the maximum time. If so, then activate whatever event.

If anyone comes up with a better (cleaner) method, I'll accept that answer.


Max number of query steps in Laravel

Question: I am having some trouble querying some data in Laravel.
I start my query doing the following:
$query = User::whereRole('advertiser');

When I query for example $usersall = $query->whereHave_pics('1')->get();
Then I also get users that have 0 in have_pics
The $query can consist of a long string of where queries that are dynamic depending on the users choices. Some of these where queries, the users that have 0 in have_pics do qualify for, but when I end the query with whereHave_pics('1'), shouldn't I only get the users that have '1' in Have_pics?
What I am wondering, is, if there is a max number of steps that laravel can handle in the query builder?
For example, if I but whereHave_pics('1') at the beginning of the query, like this:
$query = User::whereRole('advertiser')->whereHave_pics('1');
   /* More queries are added */
$usersall = $query->get();

Then it completely ignores the whereHave_pics but not the whereRole...
If I do it at the end of the query, like this:
$query = User::whereRole('advertiser');
   /* More queries are added */
$usersall = $query->whereHave_pics('1')->get();

Then it is dependent on the users choices that also creates queries.
I have been trying a ton of different work arounds, like changing the query model, e.g. instead of whereHave_pics('1') I have done where('have_pics', '1') or where('have_pics', true) etc.
I have no idea what to try next.

This is the complete function, that queries the users
public function search_adv(Request $request, $locale = 'dk') {

    App::setLocale($locale);

    $hair_queries = [
    ['input' => 'blonde', 'operator' => '=', 'field' => 'haircolor'],
    ['input' => 'brown', 'operator' => '=', 'field' => 'haircolor'],
    ['input' => 'red', 'operator' => '=', 'field' => 'haircolor'],
    ['input' => 'dark', 'operator' => '=', 'field' => 'haircolor'],
    ];

    $eye_queries = [
    ['input' => 'green', 'operator' => '=', 'field' => 'eyecolor'],
    ['input' => 'brown', 'operator' => '=', 'field' => 'eyecolor'],
    ['input' => 'blue', 'operator' => '=', 'field' => 'eyecolor'],
    ['input' => 'hazel', 'operator' => '=', 'field' => 'eyecolor'],
    ['input' => 'silver', 'operator' => '=', 'field' => 'eyecolor'],
    ['input' => 'amber', 'operator' => '=', 'field' => 'eyecolor'],
    ];

    $query = User::whereRole('advertiser');

    /* HAIRCOLOR */
    $hair = 0;
    foreach($hair_queries as $filter) {
        if($hair == 0) {
        if(!empty($request->input($filter['input']))) {
            $query = $query->where(
                $filter['field'],
                $filter['operator'],
                $filter['input']
            );
        }
        }
        if(!empty($request->input($filter['input']))) {
            $hair++;
        }
    }

    if ($hair >= 2) {
    foreach($hair_queries as $filter){
        if(!empty(request()->input($filter['input']))){
            $query = $query->orWhere(
                $filter['field'],
                $filter['operator'],
                $filter['input']
            );
        }
    }
    }
    /* END HAIR COLOR */

    /* EYECOLOR */
    $eye = 0;
    foreach($eye_queries as $filter) {
        if($eye == 0) {
        if(!empty($request->input($filter['input']))) {
            $query = $query->where(
                $filter['field'],
                $filter['operator'],
                $filter['input']
            );
        }
        }
        if(!empty($request->input($filter['input']))) {
            $eye++;
        }
    }

    if ($eye >= 2) {
    foreach($eye_queries as $filter){
        if(!empty(request()->input($filter['input']))){
            $query = $query->orWhere(
                $filter['field'],
                $filter['operator'],
                $filter['input']
            );
        }
    }
    }
    /* END EYE COLOR */

    $usersall = $query->whereHave_pics('1')->get();

    return view('search', compact('usersall'));
}

Answer: The problem is you need to understand how where chaining and orWhere chaining works in Laravel.
When you say $query->where(..a..)->orWhere(..b..)->where(..c..)->orWhere(..d..) it will evaluate to: (a || (b && c) || d). Where you may have intended ((a || b) && (c || d)) or you may have intended ((a && c) || b || d). This is why when you need advanced where clauses, use where closures and parameter grouping
Comment: Okay, I see. Do you have a source for the where closures? a quick google search didn't come up with anything
Comment: Click on the parameter grouping link in my post
Comment: Okay, I saw that but I thought it was to different things -- where closures Or parameter grouping :)

Max number of query steps in Laravel


problemas com php, json, javascript e mysql

Question: Estou tentando buscar dados do mysql para exibir no html com php utilizando json, mas esta dando errado, ele traz os dados mas não exibe, se eu aperto o f12 ele mostra os dados do banco mas não exibe os dados.
segue o codigo:
 index.html

<!DOCTYPE html>

 Home

Read Database (JSON)

getDados.php
<?php

function conectar(){

define('HOST','localhost');
define('USER','root');
define('PASS','');
define('BASE','db');

try{
    $conexao = 'mysql:host='.HOST.';dbname='.BASE;
        $conexao = new PDO($conexao, USER, PASS);
        $conexao->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        // echo 'Conectado com sucesso';
} catch (PDOException $erro){
    echo $erro->getMessage();
}

return $conexao;
}
?>

ajax.php
<?php
header('Content-Type:' . "text/plain");
include_once "getDados.php";
$pdo = conectar();

    $listar = $pdo->query("select * from cad_cliente");
    $listar->execute();

echo json_encode($listar->fetch(PDO::FETCH_OBJ));

?>

Comment: Coloque na pergunta qual é o resultado do ajax...
Comment: Ele mostra os dados no console.log?
Answer: Se mostra o retorno no console talvez não esteja retornando um objeto... tente  ver que tipo de elemento esta retornando.
console.log(typeof result);

Se for do tipo string e estiver no formato de JSON é só fazer o parse com JSON.parse e depois usar ex:
 var result = JSON.parse(result);

Isto vai converter uma string no formato JSON para um objeto javascript dai pode proceder normalmente.


Giving permissions to a node to multiple accounts without creating a new role

Question: I've built a site where all of the content is essentially private. All the relevant content types are Unpublished and my users (role=Owner) only have permissions to view/edit/delete their own Content. This is working just fine.
However, requirements have changed and I'm trying to figure out what to do. The new requirement is that an Owner can give permission to another user (role=OwnerAssistant) to view/edit/delete their data. I'll refer to the group of users that all administer the same dataset as an OwnerGroup.
It will not be feasible to create a Role for each of these groups because each new customer would need a separate role and we're hopefully going to have 50,000+ customers.
How can I control the permissions on a node so that a specific list of users can view/edit/delete that content? I'm ok with maintaining my own DB table that tracks the mapping of OwnerAssistants to Owners so that I have a way of determine if an OwnerAssistant is allowed to access content created by the Owner. However, I don't know how to let drupal know that uids 234, 894, and 1029 have x,y,z permissions to node 24590.
I will likely be integrating this with the Field Permissions module because I want to hide certain fields from OwnerAssistants.
Any help is appreciated!
Answer: How about using Entity Reference to designate non-owner users that may edit the node?
You could make your own module with a function to handle permission checks, i.e. "return TRUE if user is referenced on node".
Then use other hooks (hook_form_alter() for instance) to show/hide edit buttons and override edit privileges on nodes.
You can secure it by making the entity reference field only accessible by the content owner.
Comment: I was under the impression that hook_permission() is only for permissions that my module defines. I'm not defining any custom permissions, I'm just using drupal's normal permissions per content type ("MyContentType: Edit own Content").
Comment: Ah yes, true, you needn't use hook_permission.  Just create a handler instead.  The rest should still work.  Changed answer to reflect.
Comment: I need to actually control permissions though, not just override forms, because I need want content listings to exclude things they don't have permissions to access.
Comment: Ah right, fun.  Looks like Señor Reynolds has the right idea =)
Answer: Try module Node access user reference

Gives content access permissions to users for content that references
  the users with User reference or Entity reference.
This is great if you want your content authors to be able to choose
  additional authors, or choose who can view their content, as well as
  being able to display the list of authors or viewers within your
  content, or in views displays.
Comment: I'll read through the docs for that module tomorrow. Do you happen to know if those permissions need to be set on each node, or can they be set on the User entity? For example, could I add a User Reference on the Owner's user entity that lists the extra users (OwnerAssistants) and then that will be used for access permissions on all of the Owner's content?
Comment: I doubt that, but you could code around that or even use Rules to set/unset the user reference on a node automatically (when referencing user from a user, or creating new content). In code would probably be better.


Generating XML Documents from XML Schemas in C++

Question: Is there any easy way to create at least a template XML file using XML Schema? My main interest is bounded by C++, but discussions of other programming languages are also welcome.By the way I also use QT framework.
Comment: http://stackoverflow.com/questions/307616/xml-instance-generation-from-xml-schema-xsd
Comment: Check this one... https://stackoverflow.com/questions/17106/how-to-generate-sample-xml-documents-from-their-dtd-or-xsd.. It has accepted answer too and lot other suggestions..
Answer: You may have to write this yourself. There is no one way of getting an XML file from a Schema. If you can make domain-specific assumptions (e.g. how to populate data items, which items to choose in case of a choice, how often to insert domain-specific elements) then you will get a better instance document.
If you are working with C++, note that Xerces C++ allows you to load a schema and access its model (i.e. access it properly, not just load the schema as an XML document). I suggest you download it an check out the SCMPrint Sample. It will show you how to traverse a schema. You can then modify that to print out a sample XML file instead.
Answer: In Qt 4.5 the XML support has been extended by an XSLT implementation, that allows you to easily convert documents from one XML dialect into another or generating source code from a XML description
W3C XML Schema validation with Qt
Example:
<code>    #include <QtXmlPatterns/QXmlSchema>
    #include <QtXmlPatterns/QXmlSchemaValidator>

    QXmlSchema schema;
    schema.load( QUrl("file:///home/jordenysp/example.xsd") );

    if ( schema.isValid() ) {
        QXmlSchemaValidator validator( schema );
        if ( validator.validate( QUrl("file:///home/jordenysp/result.xml") ) ) {
            qDebug() < < "Is valid";
        } else {
            qDebug() << "Is invalid";
        }
    } else {
        qDebug() << "Is invalid";
    }
</code>
Comment: Your example is a validation example, not a transformation of XML.


Cauchy criteria at infinity

Question: i couldn't find the definition for Cauchy for functions as $x$ approaches infinity. I wrote it myself and i wanted to know if someone can correct me.
Let $f(x)$ be a function defined on all the real numbers. for every $ε>0$ there is an $M$ such that if $x,y>M$ so $|f(x)-f(y)|<ε$
thank you for your help!
Comment: It appears correct. It's like cauchy for a sequence indexed by $\mathbb R$
Comment: It isn't very clear what you are trying to define.  Maybe that $f(x)$ has an asymptote ?
Answer: If your goal is to define a criterion similar to the Cauchy criterion for sequences (that is, a sequence converges if and only if it is a Cauchy sequence), then you're right: $\lim_{x\to+\infty}f(x)$ exists (in $\mathbb R$) if and only if $f$ satisfies your condition.

Cauchy criteria at infinity


How does horizontally autoscaling an application work on compute engine?

Question: I wrote a web application model with Flask and deployed it to a VM instance on Google compute engine. The backend is a machine learning model. I can access this application by the external IP. But if two or more users try to predict something using this app, it will crash. I think the solution is to horizontally scale the vm instances so more users can access.
I looked at google doc and the link below to get a general idea of this steps.
Use existent VM Instace (bitnami) for Autoscale Group of Instances
But I am still confused about how this autoscale works.

The vm instance template does not contain the files and virtual environment, how to custom these information to template, or is it impossible?
If I deploy the app to one of the automatically generated vm instance, when more people use the app, the new generated instances will also be exactly the same (containing all the files of the web app) as the first one?
Answer: First, the main issue you are having is the crashing of your app when two or more users are using it. And the reason you come up with an Autoscale solution is because the root cause might be the VM does not have enough resources. I would recommend to try to test it first on a high resource VM and see if it is really a resource issue. Or more preferably, check the error logs on your application to see clues why it is crashing.
To answer your questions on Autoscaling

You will create your Instance template based from the disk image of your application, that information can also be found in the answers of the post on your question.
You will need to deploy the app to the instance template and it will automatically replicate itself based on the needed resources.

How do I configure managed instance group and autoscaling in Google Cloud Platform
Comment: Thank you. I tried with a custom image, the new instances did contain all the necessary files.


Can you legally use the gutter to pick up a split?

Question: If I were to bowl the bowling ball into the corner of the gutter to pick up a split (usually 7-10 split applies here), is it still legal if it goes in the gutter completely, comes out of the gutter, and hits the pin(s) ?
Answer: No, it would not be legal.  If the ball goes into the gutter before reaching the pins, any pinfall that happen after the ball hits the gutter is not legal pinfall, therefore the pins either need to be stood back up(if on the first ball of the frame) or the shot counts as 0(if on the 2nd ball of the frame).
Rule 6b - Illegal Pinfall

6b. Illegal Pinfall
When any of the following occur, the delivery counts but the resulting pinfall does not:
A ball leaves the lane before reaching the pins.

Reference
Rulebook Page 13


Why are multiples of 11 palindromes?

Question: One thing I noticed is that for any integer $-10<a<10$, $11a$ is always a palindrome. I'm assuming this is because 11 is the first row of Pascal's triangle. For that same reason, for any nonnegative integer $n<5$, $(11a)^n$ is a palindrome.
Is there a proof for this? Is there a proper formula that proves that multiples of 11 are palindromes?
Comment: It is true, however, that all palindromes with an even number of digits are divisible by $11$.
Comment: $11a$ is not always a palindrome. e.g. $11 \cdot 10 = 110$
Comment: But that's not true: put $a=15$, e.g.  Then $11\cdot 15 = 165$
Comment: $\;11\cdot132=1452\;$ ...doesn't look too palindromic to me...
Comment: You're correct - let me update this.
Comment: For which multiples?  Aside from $1$ to $9$, for which integer $n$ is $11n$ a palindrome?
Comment: @Dr.MV $11\cdot 11$ is a palindrome.  As is $11^3$ and $11^4$.
Comment: @DWiggles Yes, I know.  My point was to find all of them.
Comment: @Dr.MV Like I said in the question - (11a)^n for -10<a<10 and -1<n<5.
Comment: @MarcusStuhr 121 doesn't contain an even number of digits. Neither does 14641.
Comment: @drmv Is -121 not a palindrome?
Comment: @DonielF Sometimes a palindrome with an odd number of digits can be divisible by $11$, but not all of them. My claim was that all palindromes with an even length are divisible by $11$.
Answer: Since $11 = 10 + 1$, the binomial theorem gives
$$
11^{n} = (10 + 1)^{n} = \sum_{k=0}^{n} \binom{n}{k} 10^{n - k}.
$$
If $0 \leq n < 5$, then $\binom{n}{k} < 10$, i.e., is represented base $10$ by a single digit. Concretely,
\begin{align*}
  11^{2} &= 121, \\
  11^{3} &= 1331, \\
  11^{4} &= 14641, \\
  11^{5} &= 161051.
\end{align*}
(At the fifth power, there's carrying from $\binom{5}{2} = \binom{5}{3} = 10$.)
The question about $11a$ is similar but trivial: If $0 < a < 10$ is a single digit base $10$, then $11a = 10a + a$ has decimal representation $aa$.
It's not true that $(11a)^{n}$ is a palindrome, e.g., $22^{5} = 5153632$.

Why are multiples of 11 palindromes?


How to sample clustering to estimate precision and recall?

Question: There is a system containing $N$ clusters and in each cluster there are some elements. The clusters' sizes varies dramatically and most of the clusters are singletons.
I need to know the precision and recall of this system, but since I need to check it manually it is impossible to check too many units.
My question is: if I draw samples, the sampling unit should be cluster or element?
Also, precision is a kind of easy to check (given I know the definition of each cluster), but how could I check the recall? I need to check in the scope of sample only, or I need to search from the entire population?
Is there anything else I need to know?
Thanks a lot!
Comment: Why do you have to check manually? Plus P&R make direct sense only in case of binary classification, how do you want to generalize into many clusters?
Comment: @user6397: Please clarify what kind of clusters you have. Are you talking about classifier validation with clustered (hierarchical) structure of the samples or are you talking about validation of cluster analysis results?
Answer: For cluster algorithm evaluation you have to create small manual clusters and check how well they distributed among resulted clusters. Check this article http://nlp.stanford.edu/IR-book/html/htmledition/evaluation-of-clustering-1.html
Answer: Drawing Validation Samples with Clustered Data Structure
You need to draw samples from a structural level where samples are statistically independent.
So if I have several patients (= your clusters?) and varying numbers of (e.g. repeated) measurements per patient (= your elements?) then I draw test patients. That is, unless I can show that the variance between patients is negligible compared to the variance between measurements of one patient.
Validation of Cluster Analysis
I'd use someting like cluster purity and/or the number of clusters samples of a given group are assigned to.
Precision, Recall & Co. don't seem quite appropriate: Think of a very bad classifier that always assigns B to class A samples and vice versa. That would be 0 precision and recall. But cluster analysis doesn't claim that the cluster where it assigns all B samples is actually class B. You'd need to assume something like the cluster with highest B predictions is actually B. So you'd always get at least $\frac{1}{n_{classes}}$ correct assignments due to this assumption.
Generalization of Precision & Recall
I use the following generalizations. I derived them from the medical diagnostics meaning, where the binary case disease X vs. not disease X (often called healthy in every day language)
(see p. 12 of http://softclassval.r-forge.r-project.org/Beleites2011b.pdf for an illustration)

recall = sensitivity = How good does the classifier recognize class C samples? = fraction of cases where reference says it is class C that is (correctly) assigned to class C,
specificity = How good does the classifer recognize that a sample does not come from class C? = fraction of cases where reference says it is not class C that is (correctly) not assigned to class C.
precision = positive predictive value = If the classifier says it is C, what is the probability that this is correct? = fraction of cases with reference C of predicted class C cases.
negative predictive value = Given the classifier said it is not class C, what is the probability this is correct? = fraction of cases with reference not C of cases predicted to be something else than C.


Are effects pedals overkill for acoustic instruments?

Question: When I play acoustic instruments (ukulele/harp/acoustic guitar) I like to add reverb and other various effects to them, even if I'm just playing. None of my instruments have any kind of line-out, so I need to use a microphone. I'm currently using my iphone with an app that has a realtime effects generator and it uses the iphone's microphone. So I put the iphone right next to the instrument, then plug in an aux cable from my iphone to a usb rechargeable speaker (ue boom 2) to get the sound out.
This works good but I was wondering what is traditionally used for this in the music realm, hardware wise. I'm curious because I saw there's so many pedals for this and they have a ton of effects.
But the problem is they seem overkill. First they're not battery powered so I need to get an external battery. Second, they don't have a mic so I need to get a microphone for them and somehow power it too, and also they have a pedal. Why is a pedal important? I just want to get sound out of it.
Upon further investigation I saw people do this with pedal boards. So they'll have an external battery connected to various pedals. But it seems overkill and weighs alot and is not as portable compared to my iphone setup. Which is important because sometimes I play outside. Is there any reason to go hardware though? maybe I'm missing something.
Comment: There are acoustic guitars with built-in reverb and delay. Sorry don't know the brand.
Answer: Just about everything sounds better with some reverb on it.
For steel strings you can get magnetic pickups that require no power to function. For nylon strings you can get a piezo pickup but the output will be very low compared to magnetic pickups unless you have a preamp or other signal boost on it.
For other instruments, just about anything that vibrates (ie. any musical instrument) can be fitted with a piezo to work as a transducer.
One other thing to be aware of: if you do get a piezo with a preamp, the output level may be very high compared to the output from a magnetic pickup. So always switch things on with the preamp volume very low or off and turn it up to produce a clear signal.
Comment: Strongly disagree with the first sentence.
Comment: @leftaroundabout "Some" doesn't have to mean "lots". :)
Comment: I also disagree strongly with that sentence.
Comment: @leftaroundabout probably not for all instruments as it can muddy the sound. but think of playing in a cave with a ton of reverb, versus playing on a football field. I'd probably choose the cave most times.
Comment: can you two please show me examples where no reverb at all sounds good?
Answer: As Laurence says, adding reverb is more generally done at the mixing desk. The problem is that you (on stage) can't hear what sounds good for an audience. It may sound great to you, but awful out front, which is why performers have foldback speakers (also known as monitors) with a different mix.
One reason things sound better with reverb is that you can't distinguish pitch quite as clearly, so it can cover up for less able singers. The downside of this is that singers need to be able to hear their own voice accurately to pitch notes properly, so the sound in the monitors must have no reverb whatsoever.
All that said, some singers do want to manipulate their voices in the mix. As well as typical guitar FX pedals which take a line-in signal, you can also get FX pedals designed for singers which have an XLR microphone input. This would be more suitable for what you're doing.
You do then need to add a mic, of course. These FX pedals don't generally provide phantom power so you're limited to dynamic mics, but that's generally not a great hardship. Shure SM57 are the classic instrument mic, but Sennheiser drum mics are recommended too (just detach the drum clip), or the Sennheiser MD421 (and derivatives) if you've got a lot of money.
Answer: You can put a pickup on a ukulele if you want, and run it through all the effects a guitarist might use.  A multi-effects setup will often include one or more pedals for volume and wah-wah.  A single effect box normally uses an internal battery, with the option of an external power supply.
More typically, a uke is just miced and put through the PA.  Maybe some reverb will be added at the mixing board.
Sounds like your lash-up is working fine though.  Carry on!
Answer: If what you're doing works fine for your particular situation, keep doing it.
However your iPhone mic will be picking up all sorts of other sounds from your environment and applying the onboard effects to those sounds as well. Your current solution will let you down badly as soon as you want to perform with other people, or if you were playing through somebody else's amplification system. You must also need to stand/sit extremely still to keep your iPhone mic at the correct position to pick sound up, which will hamper any form of performance.
Why pedals? They're built for stage use, you can turn effects on and off by stamping on them (which of course will also work with your iPhone, but only exactly once), and they give far superior sound quality. There are also loads of single and multi-effect pedals that work off battery power, so that's an erroneous objection.
Answer: If all you want is reverb and you're just playing at home, try a different room or facing the wall. Try the bathroom or entry hall.
Answer: Before you ask this question, you need to ask whether you are helping things by being amplified in the first place. After all, most halls already have reverb that occurs naturally - the electronics is a simulation of that. Why add a simulated version of something that is already there?
It depends hugely on context - style of music, the venue, the acoustics, the quality of the PA and the competence of the sound engineer (for the style of music). Also note that if you, on stage, do not hear more or less what the audience hears, your chance of giving a quality performance takes a nosedive. So the quality of the monitoring is also a big factor.
I think that acoustic performances are often over amplified. I saw Lincoln Centre Jazz Orchestra in a hall for maybe 10000 people - only two mics on stage, one for flute, one for vocal. They sounded great. I have also seen another big band (who shall rename nameless but also well known and respected) in a 2000 seater hall, with about 20 mics on stage and it was awful.
I posit that music was almost always performed acoustically until aroun 1940, and widespread use of amplification didn't start until the 60s. Now we have a situation where (outside of the classical and operatic world) many performers feel insulted if asked to perform without a sophisticated and powerful sound system, even in small venues. In some cases, use of a mic/PA becomes a prop for poor technique or musicianship. (Although I do accept that the mic has become an integral part of the singers sound in popular music.)
While a good sound system can be a an asset to a performance, it is not always necessary, and is never going to be better than the engineer behind the desk. So my approach is 0 "use with discretion". (And I speak as someone with both musical and technical know-how and real-world experience.)
Comment: OP is most likely a bedroom player (when he's not outside!). Not quite into performing to a crowded auditorium. (Ask him!)
Comment: Ok, but anyone at all can be reading.
Comment: @dmb I agree, but I think that battle has been lost in a lot of performance situations
Answer: I think they are generally overkill on an acoustic instrument generally, unless very subtle.
I did once try a Boss "Psycho acoustic processor" which added to the steel string sound, and perhaps a tiny bit of chorus with modulation for an occasional "different" sound. However generally, I wouldn't bother
Answer: There are no written laws for music and musical sounds... If it sound better: do it. Haters will be haters, but even if would be the only person in the world to use a reverb (or any other effect) on an accoustic guitar and you think it sounds good: use it!
On a side note... I have an expensive martin guitar with line out and everything that has a built in reverb... So yes: it's very acceptable to use one
Answer: I think every effect I've ever come across for musical applications has the ability to become overkill in it's use, however they can usually be dialed back to become complimentary to the music being performed. It is up to the performer to determine the level of the chosen effect and the audience can accept or reject the results according to their own individual preferences. As far as I know, that's pretty much how things work in general when it comes to music.


Quando devo usar cada nível de log no Android Studio?

Question: Existem diferentes níveis de log no Android Studio, que talvez, digo talvez, não seja muito diferente em outras IDE's. Basicamente são as maneira diferentes de como posso gravar uma mensagem no logcat. Os tipos são VERBOSE,DEBUG, INFO, WARN, ERROR e ASSERT.
O que significa cada um desses? Em quais situações devo usa-los?
Comment: aqui nesse link que abri pressionando a ajuda do android studio:
https://developer.android.com/studio/debug/am-logcat.html
Comment: feito, @Ack Lay, se quiser, seria interessante para min (rerere) marcar a resposta como correta.
Answer: Segundo o site oficial de ajuda do android studio, https://developer.android.com/studio/debug/am-logcat.html, segue traduzido:
No menu Nível de registro, selecione um dos seguintes valores:

Verbose - Mostra todas as mensagens de log (o padrão).
Debug - Mostra mensagens de log de depuração que são úteis apenas durante o desenvolvimento, bem como os níveis de mensagem mais baixos nesta lista.
Info - Mostra as mensagens de log esperadas para uso regular, bem como os níveis de mensagem mais baixos nesta lista.
Avisar - Mostra possíveis problemas que ainda não são erros, bem como os níveis de mensagem inferior nesta lista.
Erro - Mostra problemas que causaram erros, bem como o nível de mensagem inferior nesta lista.
Assert - Mostra problemas que o desenvolvedor espera que nunca aconteçam.

é isso...


What technique is used for the opening of this Soundgarden song?

Question: The song Loud Love by Soundgarden opens with several single notes on the guitar.  They sound almost like bowed notes on a cello.
I'm not sure if maybe Kim Thayil is working the volume knob, or if this is accomplished with a volume pedal, or even more effects.
Does anyone know?

Video above for reference.
Comment: I'm only hearing the volume rise on the first note. The rest sounds to me like hammer-on, at levels high enough for feedback to keep the sustain. [Pure guesswork, so can't post an answer]
Comment: Wikipedia says feedback: https://en.wikipedia.org/wiki/Loud_Love http://web.stargate.net/soundgarden/articles/gschool_5-94.shtml
Comment: @user1079505 excellent find.  Fashion that into an answer and the cred is yours.
Comment: Not sure if the question is on topic and @Aaron wants to dv answers to off-topic questions
Answer: I don't agree that this sounds anything like bowed cello notes, but it does sound a lot like an EBow. That's a device which generates feedback similar to what you can get by having the amp vibrate the guitar, but without the loudspeaker – instead, it directly vibrates the strings magnetically.
However, as per the article that Wikipedia and user1079505 linked to, Kim Thayil actually used amp feedback, not an EBow. That requires cranking the amp very loud (in particular, high gain) and standing close to it with the guitar. Even then it's quite difficult to control which notes / partials actually get sustained. So if you want to play this intro reliably, I would anyway recommend trying an EBow.
In addition to feedback, the guitar has a lot of distortion and a lot of reverb on it.


Allow users to see own content only

Question: I have two content types, provider and products.
The providers is a list of titles filtered by logged in user (each user can only see the providers he enterd). By clicking the provider the user is taken to a page that contains a table with all the provider products.
the provider and the products content type are linked via a unite content field using contextual filter (the mutual field called lpid).
In the products page the path is provider/%/products while the wildcard represents the lpid field.
Everything works great, what I am trying to do is to prevent from users to see other users content.
Is there a way to pass the wildcard via $_POST so the user will not be able manualy change the url?
TNX
Answer: "Allow users to see own content only", You can achieve this using contextual filter and relationships in advance settings in views module, Given by you already set the contextual filter set filter to login user,
1.) In Advanced settings add field Content:author in relationships.
2.) Then in Contextual Filters add User: Uid and choose provide default value and set Provide default value Type User ID from logged in user.
Comment: Hey, Thank you for your detailed answer, I did what you suggested in the `provider` content type, what I was asking is if there is a way to show the `products` items  to the users who inserted the `provider`. for example: one of my provider is `shoes store`.  the id of the `shoes store` is `227` in that provider i have products, the products are inserted by an external form and inserted as `products` content type items. now,  when i click the `shoes store` i am redirected to `provider/227/products` there i see all the products related. the problem is that if I write a different id in the...
Comment: ...URL  let's say `228` i wiil see all the products belong to the 228 provider which was created by other user. is there a way to prevent that? lets say pass the id variable in $_POST method?
Comment: can you provide current settings of your views so that I can use that as a reference? I will update my answer base on your current settings
Comment: also the id of the provider is that the user id of the provider?
Comment: [THIS IS THE PROVIDER VIEW](http://nimb.ws/nm1WYg)  .       [THIS IS THE PRODUCTS VIEW](http://nimb.ws/usT3bN)
Comment: the `unique` in `provider` equals` lpid` in `products`
Comment: I see have you tried to add relationships in product view to content:Content Author and also set the uid in contextual filter? and set it Provide default value Type User ID from logged in user.
Comment: I tried that in provider to product. exactley ass you suggested
Comment: is there a way to pass the id var in $_POST? so it will not be visieble?

Allow users to see own content only


Make a column NULL for insert and NOT NULL for update

Question: This is something that I stumbled across multiple projects, and I feel I'm reinventing the wheel every time:
I have a table that stores user data. Whenever the user is created, I create one row on the table. This row has several NULL fields on creation, because the user just informed some critical information (and other non-critical info is going to be filled later).
But, when the user completes the filling of the data, I want to enforce this cols to be NOT NULL.
Is there any way to make a column NULL for INSERT, but NOT NULL for UPDATE that does not involves triggers? Or any other clever solution?
Thank you
Comment: Maybe you would like to share us what you have done so far?
Answer: CREATE TABLE users ( regular_column SOMETYPE NOT NULL,
                     smart_column SOMETYPE NULL,
                     completed ENUM('no', 'yes') NOT NULL DEFAULT 'no',
                     CHECK ((completed = 'no') OR (smart_column IS NOT NULL)) );

This row has several NULL fields on creation, because the user just informed some critical information (and other non-critical info is going to be filled later).

In this moment completed = 'no', CHECK constraint is TRUE, smart_column may be NULL.

when the user completes the filling of the data, I want to enforce this cols to be NOT NULL.

In this moment completed = 'yes', and CHECK constraint does not allow NULL value in smart_column.
I.e. setting completed column to 'yes' fixes smart_column - you may alter it but cannot set it to NULL. And you cannot set completed to 'yes' until smart_column is set to a value.
Comment: Special thanks for the CHECK statement that makes very easy to add new columns to it!
Answer: If you use column options in your CREATE TABLE statement, there's no way a column can be both NULLable and NOT NULL. There's no way to distinguish between inserts and updates.
The alternative could be to let the column be nullable, but add a trigger on UPDATE that throws an exception (called a SIGNAL in MySQL terminology) if the column is still NULL after the update.
Here's a quick demo:
mysql> create table mytable (id int primary key, x int);
Query OK, 0 rows affected (0.05 sec)

mysql> delimiter //

mysql> create trigger notnullonupdate before update on mytable
    -> for each row
    -> begin
    -> if NEW.x IS NULL then
    -> signal sqlstate '45000'
    -> set message_text = 'x must be updated to non-NULL value';
    -> end if;
    -> end//

mysql> delimiter ;

mysql> insert into mytable set id = 42, x = null;
Query OK, 1 row affected (0.03 sec)

mysql> update mytable set id = 42;
ERROR 1644 (45000): x must be updated to non-NULL value

Even though this is possible, it's kind of a lot of work.
Most developers would just handle this by writing application code to ensure the value is not null before executing an update. Of course the risk of that is if you forget one of the cases in your app that does an update, or if someone does an ad hoc update in the mysql client, it could cause your data to be in an invalid state and you wouldn't know it.
Comment: Thanks Bill! I'm currently writing application code for the validation, as you said. But I think this is the wrong solution in the long term. Your trigger answer does work as intended, but I'm marking @Akina as correct because it does this on table creation syntax


How to add "load more" link to comments?

Question: I am trying to style my comments list to be similar to Facebook comments, so that user can load more comments by clicking on a link to load more. If there is a big number of comments then he should be able to load more and more comments.
Any suggestions how to start this?
Answer: Views Infinite Scroll and many similar modules allows you just that.

Views Infinite Scroll provides a Pluggable pager that enables views infinite scrolling ( autopaging, depaging, endless pages ...you name it) by using jquery.autopager plugin. using this module with views page display will load another page whenever the user reaches bottom of the page.

Views Load More is other example.

Yes, this is indeed, Yet another load more pager for views.

And you can show anything with Views. Comments too.
Comment: This can be used with views .. but how to use it with comments
Comment: Create a view displaying comments? Or google for similar module that works on them natively? Most people write things like that for views, as you can show anything with views - so you can use their creations on anything and they don't need to bother.
Answer: This module does a similar thing, More Comments

More Comments module replaces the default pager of comments with a
  button that loads the next page of comments using ajax.
Comment: Thanks a lot.. it's very useful ,, any idea how to make it load the previous comments not the recent.. bcs this module shows the old comments and hides the previous
Comment: check this post http://drupal.stackexchange.com/questions/2444/drupal-7-change-blog-comments-display-order and this talk and modules http://drupal.org/project/comment_goodness, http://drupal.org/project/sort_comments you will get suitable one


"For all $\epsilon>0$, if $a+\epsilon>b$, then $a>b$" vs "If, for all $\epsilon>0$, $a+\epsilon>b$, then $a>b$".

Question: Peter asked:

If $a + \epsilon > b$ for each $\epsilon > 0$, can we conclude that $a > b$?

Micah commented

Be careful: [$\Large{1.}$] "for every $ϵ>0$, if $a+ϵ>b$, then $a>b$" is a different statement than
[$\Large{2.}$] "if, for every $ϵ>0, a+ϵ>b$, then $a>b$."
One of them is a lot closer to being true than the other.

Brian M. Scott expounded on why conditional statement #1 is false. But my difficulty is grislier! As English isn't my first language, I can't even distinguish between the two conditionals, which mean the same to me! What's the simplest way to distinguish between them?
As both share the same apodosis ("then $a> b$"), I only pay attention to the protasis. I spot only one difference: the placement of $\color{limegreen}{\text{"if"}}$. The protasis of 1 is

for every $ϵ>0, \color{limegreen}{\text{if }} a+ϵ>b$

The protasis of 2 is

$\color{limegreen}{\text{if}}$, for every $ϵ>0, a+ϵ>b$
Answer: In statement 2's protasis, there is actually an if-then statement. It is "if 'if $\epsilon > 0$, then $a+\epsilon > b$'".
This is clunky to say in plain English, so people use the "for every" quantifier instead.
So statement 2 actually says:
"if

'if $\epsilon > 0$, then $a+\epsilon > b$'

,
then $a>b$".
On the other hand, statement 1 is:
"if $\epsilon > 0$, then

'if $a+\epsilon > b$, then $a>b$'

."
So which one is true?
Looking at it this way, it is clear that statement 2 is not true (because try letting $a=b=1$), but in some sense "close to being true", because changing the conclusion to $a\ge b$ makes it true.
However, statement 1 is "nowhere near being true", because try letting $\epsilon = 10$ and $a=1,b=2$.
Answer: Since your issue is a linguistic one, I'll write down the two statements in logical notation. Pay close attention to the placement of the brackets.
Statement 1:
$$ (\forall a \in \mathbb R)\bigg[(\forall b \in \mathbb R)\bigg[(\forall \epsilon \in \mathbb R^+) \bigg[ (a + \epsilon > b) \implies (a > b) \bigg]\bigg]\bigg]$$
Statement 2:
$$ (\forall a \in \mathbb R)\bigg[(\forall b \in \mathbb R)\bigg[(\forall \epsilon \in \mathbb R^+) \bigg[ (a + \epsilon > b)  \bigg] \implies  (a > b)\bigg]\bigg]$$
Comment: Thanks. I see merely one difference: the placement of ]. Statement 1 ends with 3 ]'s. Statement 2 ends with 2 ]'s, because you placed one ] before $\Longrightarrow$. But how does this answer my question? I still befuddled!
Comment: @user1147844 I thought your question is about how to translate the English sentences into logical statements?
Comment: Yes, that's the first part. But I want to distinguish, and intuit, these logical statements too!


For discrete random variables $X,Y,Z$, what conditions normally might cause $P(Y\mid X,Z) > P(Y \mid Z)$ or vice versa?

Question: For discrete random variables $X,Y,Z$, I am wondering what conditions normally might cause
$$
P(Y\mid X=x,Z=z) > P(Y \mid Z=z)
$$
at $X=x,Z=z$. Is there a connection with correlation? I know generally that if $Y \perp X \mid Z$, then it holds with equality. However, more generally do there exists paradigms to think about it?
Answer: The key idea is that any conditional distribution is itself a distribution.  I.e. if everything is conditioned on $Z$, you might as well consider $Z$ to be your entire sample space.  And if you don't know / can't say anything special about $Z$, then there is no restriction whatsoever on the conditional distribution.
So you're effectively asking: under what conditions $P(Y | X) > P(Y)$?  Well, they are "positively correlated" in a sense, but really, that's not a good answer but merely re-stating the requirement but in a way that is less formal / rigorous.


Importar csv com pandas. Valores da coluna com ponto e vírgula. O que fazer?

Question: Estou importando arquivos csv com o pandas para fazer uma limpeza nos dados.
E estou encontrando um problema.
Alguns valores tem ';' .
Por exemplo: df[0][1] = "RUA A ; "
Importo o csv através de:
df = pd.read_csv('GUAXUPE.csv', header = None, sep = ',', encoding = 'utf-8')
E apesar de ter colocado o separador como a vírgula, o pandas reconhece o ' ; ' como um separador e acrescenta um campo aonde não devia, desregulando parte da tabela.
Já pesquisei na internet, li a parte da documentação do pandas que fala do read_csv() e não encontrei resposta. Alguém tem uma idéia ?
Answer: Uma forma de contornar é unir a coluna com a informação à esquerda do ";" com a coluna contendo a informação à direita do ";".
Ficaria algo assim:
df['dados_esquerda']+=";"+df['dados_direita']

Caso não queria nomear as colunas, acredito que esse poderia ser feito assim:
df.loc[:,1]+=";"+df.loc[:,2]

No exemplo acima, assumi que a segunda coluna contenha os dados à esquerda do ";" e a terceira coluna os dados à direita do ";".
Posteriormente, você pode apagar a coluna indesejada com o comando del:
del df[2] #ou del df['dados_direita']

Comment: Mas o problema é que é um dataframe gigantesco. Na verdade escrevi um script para tratar vários arquivos csv. importei os dados de cnpj , cnae , do site da receita federal ; e estou tratando-os.  E para fazer isso , que você sugeriu , eu precisaria saber exatamente quais linhas e quais colunas, o problema acontece.
Comment: O problema é na hora da importação do CSV  pelo panda. quando passo o read_csv() ele reconhece o ponto e virgula , mesmo entre aspas , como um separador.
Comment: Eu cheguei a importar usando o módulo csv do python , e depois transformando  o dicionario em um dataframe. Ficou melhor . Mas ainda gera um problema de formatação das colunas...
Comment: Eu tive o mesmo problema quando gerei um dicionário com todas as CNAES e seus significados, e fiz a substituições da mesma na coluna CNAE .   O dicionário tinha espaçamento com o TAB . E quando fazia a substituição na coluna, o pandas lia o TAB como um separador . Isso foi fácil de resolver. Usei o VScode com crl shift seta pra baixo e eliminei todos espaçamentos tab de uma vez.
Comment: Na verdade precisaria saber somente em quais colunas o problema acontece.
Você poderia colar uma linha do csv aqui para eu poder entender melhor como ele é?
Comment: "00317713000183","1","WANDERLEIA SABBAG DUARTE","PRIVILEGIUS MULTI-MARCAS","04","20190124","63","","","","2135","19941129","4781400","AVENIDA","CONDE RIBEIRO DO VALLE","1243","LETRA: A;","IRMAOS RICCIARDI","37800000","MG","4573","GUAXUPE","35","35514071","","","","","email@example.com","50","0.0","01","6","20070701","20121231","N","",""
"00317713000183","1","WANDERLEIA SABBAG DUARTE","PRIVILEGIUS MULTI-MARCAS","04","20190124","63","","","","2135","19941129","4781400","AVENIDA","CONDE RIBEIRO DO VALLE","1243","LETRA: A;","IRMAOS RICCIARDI","37800000","MG","4573"
Comment: Essa é uma das linhas de um dos csv  que dá problema . Veja que um dos valores é "LETRA:A;"
Comment: Mas não são todos valores da coluna que isso acontece. Nesse csv tem umas 10 linhas  apenas que tem um valor com ponto e virgula,entre as 25000 .
Comment: É um csv para cada município do Brasil . No total , 26 GB.
Comment: Pelo visto, todos os campos possuem aspas duplas no início e no final do valor.
Nesse caso, faça um teste usando como separador "," aos invés da vírgula simples. Se não funcionar, tente usar sep='["]*,["]*'
Outra alternativa é importar o csv usando nova linha como separador. Aí na linha gigante que será criada, rodar um script para remover os ";". Salvar o CSV novamente e então reimportar.
Comment: Tentei, e não deu certo. O pandas insiste em reconhecer o ponto e vírgula como um separador, mesmo recebendo a vírgula ou qualquer outro elemento como separador. Ele reconhece também o espaçamento TAB como um separador. Tive um problema no passado com ele. Mas esse foi fácil de resolver. Era um dicionário com todos códigos CNAES e seu significado. Cortei todos espaçamentos de uma vez.
Answer: No comando engine acrescente o parametro engine, ficaria assim:
df = pd.read_csv('GUAXUPE.csv', header = None, sep = ',', encoding = 'utf-8',engine='c')

Na documentação do read_csv diz que a engine do Python reconhece separadores automaticamente, a engine do C não. Acredito que pode uncionar.
segue a doc: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html
Comment: Eu tentei. Não deu certo. Continua reconhecendo o ponto e vírgula como separador.
Comment: Estou tentando usar o módulo CSV do python também.  A função que converte o csv para um dicionário acaba excluindo duas colunas onde aparecem esses caracteres que estão interferindo na formação da tabela.  De um lado, resolve , mas de outro não,pois preciso dessas informações,
Answer: Resolvi o mistério!
O problema não era no pandas. Mas sim a maneira que estava fazendo a supervisão das tabelas geradas. Quando abria o arquivo .csv no libre office, o programa pedia inicialmente pra escolher quais caracteres seriam considerados como separador. E automaticamente, o ponto e vírgula estava selecionado.
Fiz a supervisão das tabelas pelo jupyter notebook, e está tudo certo !


Formatar Hora utilizando initBinder

Question: Eu preciso pegar a hora com a formatação "hh:mm" porém não está funcionando, segue o erro também para melhor especificar:

Whitelabel Error Page This application has no explicit mapping for
  /error, so you are seeing this as a fallback.

Tue Dec 18 13:56:56 BRST 2018
There was an unexpected error (type=Bad Request, status=400).
Validation failed for object='cartelas'. Error count: 1
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'cartelas' on field 'final_time': rejected value [17:20]; codes [typeMismatch.cartelas.final_time,typeMismatch.final_time,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [cartelas.final_time,final_time]; arguments []; default message [final_time]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'final_time'; nested exception is java.lang.IllegalArgumentException: Could not parse date: Unparseable date: "17:20"]
    at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:164)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:126)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:166)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:791)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

Minha classe:
package br.com.sky.iTvMC.modelo;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.springframework.format.annotation.DateTimeFormat;

@Table(name = "CARTELAS_NEW_CHANNEL_HD")
@Entity
public class Cartelas {
@SequenceGenerator(name = "seqCart", sequenceName =
"SEQ_CARTELAS_NEW_CHANNEL_HD", allocationSize = 1)
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seqCart")
private Long id;
private static final String server_folder = "C:'\'Projetos";

@DateTimeFormat(pattern = "dd/MM/yyyy")
@Temporal(TemporalType.DATE)
private Date initial_date;

@DateTimeFormat(pattern = "dd/MM/yyyy")
@Temporal(TemporalType.DATE)
private Date final_date;

@DateTimeFormat(pattern = "hh:mm")
@Temporal(TemporalType.TIME)
private Date initial_time;

@DateTimeFormat(pattern = "hh:mm")
@Temporal(TemporalType.TIME)
private Date final_time;

@Enumerated(EnumType.STRING)
private CelulasCartela celulas;

private String who;

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public static String getServerFolder() {
    return server_folder;
}

public Date getInitial_date() {
    return initial_date;
}

public Date getFinal_date() {
    return final_date;
}

public Date getInitial_time() {
    return initial_time;
}

public Date getFinal_time() {
    return final_time;
}

public CelulasCartela getCelulas() {
    return celulas;
}

public void setFinal_time(Date final_time) {
    this.final_time = final_time;
}

public void setInitial_time(Date initial_time) {
    this.initial_time = initial_time;
}

public void setInitial_date(Date initial_date) {
    this.initial_date = initial_date;
}

public void setFinal_date(Date final_date) {
    this.final_date = final_date;
}

public void setCelulas(CelulasCartela celulas) {
    this.celulas = celulas;
}

public String getWho() {
    return who;
}

public void setWho(String who) {
    this.who = who;
}

}

Controller
package br.com.sky.iTvMC.controller;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import br.com.sky.iTvMC.modelo.Cartelas;
import br.com.sky.iTvMC.modelo.CelulasCartela;
import br.com.sky.iTvMC.repository.CartelasRepository;

@Controller
@RequestMapping("/cartelas")
public class ClientChannelController {

@Autowired
CartelasRepository cartelaRepository;

@RequestMapping("/novo")
public ModelAndView novo() {
    ModelAndView mv = new ModelAndView("cadastrarCartela");
    return mv;
}

@InitBinder
public void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm"); //yyyy-MM-
dd'T'HH:mm:ssZ example
    dateFormat.setLenient(false);
   // System.out.println("init binder");
    binder.registerCustomEditor(Date.class, "initial_time", new
CustomDateEditor(dateFormat, true));
    binder.registerCustomEditor(Date.class, "final_time", new
CustomDateEditor(dateFormat, true));
}

@RequestMapping(method = RequestMethod.POST)
public ModelAndView salvar(Cartelas cartela) {
    System.out.println("Data inicial: "+ cartela.getInitial_date());
    System.out.println("Data final: "+ cartela.getFinal_date());
    System.out.println("celula: "+ cartela.getCelulas());
    System.out.println("hora incial: "+ cartela.getInitial_time());
    System.out.println("hora final: "+ cartela.getFinal_time());
    cartelaRepository.save(cartela);
    ModelAndView mv = new ModelAndView("cadastrarCartela");
    mv.addObject("mensagem", "Cartela cadastrada com sucesso!");
    return mv;
}

@ModelAttribute("todasCelulas")
public List<CelulasCartela> todasCelulas(){
    return Arrays.asList(CelulasCartela.values());
}

}

A página do formulário

      Data Inicio

        <input type="text" class="form-control" data-provide="datepicker" data-date-orientation="bottom" data-date-format="dd/mm/yyyy" data-date-language="pt-BR" data-date-autoclose="true" data-date-today-highlight="true" autocomplete="off" name="initial_date"
          placeholder="dd/mm/yyyy">

      Hora Inicio

          <input type="text" class="form-control" name="initial_time" placeholder="00:00" autocomplete="off">

      Data Final

        <input type="text" class="form-control" data-provide="datepicker" data-date-orientation="bottom" data-date-format="dd/mm/yyyy" data-date-language="pt-BR" data-date-autoclose="true" data-date-today-highlight="true" autocomplete="off" name="final_date"
          placeholder="dd/mm/yyyy">

      Hora Final

          <input type="text" class="form-control" name="final_time" placeholder="00:00" autocomplete="off">

Answer: De acordo com a mensagem de erro:

... [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'final_time'; nested exception is java.lang.IllegalArgumentException: Could not parse date: Unparseable date: "17:20"

Isso quer dizer que a String com o valor "17:20" foi passada para o SimpleDateFormat que você criou, mas não foi possível fazer o parsing.
Considerando o SimpleDateFormat criado no seu método initBinder:
// SimpleDateFormat que você criou
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm");
dateFormat.setLenient(false);

// tenta fazer o parsing de 17:20
Date date = dateFormat.parse("17:20");

Este código lança uma exceção:

java.text.ParseException: Unparseable date: "17:20"

Isso acontece porque hh corresponde ao campo Hour in am/pm, com valores entre 1 e 12 (por exemplo, o valor 5 pode ser tanto 5 da manhã quanto 5 da tarde).
Este SimpleDateFormat até aceitaria valores maiores que 12 para as horas, mas como você usou setLenient(false), isso faz com que somente valores entre 1 e 12 sejam aceitos, e qualquer outro lance exceção.
Como você está recebendo valores maiores que 12, use HH (maiúsculo) para que sejam aceitos valores entre 0 e 23 (5 é 5 da manhã e 17 é 5 da tarde):
// usar HH para as horas (em vez de hh)
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
dateFormat.setLenient(false);
// agora sim faz o parsing sem lançar exceção
Date date = dateFormat.parse("17:20");

Use o campo correto
Por padrão, SimpleDateFormat é leniente, o que significa que aceita quaisquer valores e tenta dar um jeito de ajustá-los (o que pode gerar alguns resultados bem estranhos se você não tomar cuidado).
Usando setLenient(false), este modo permissivo é desligado e a classe se torna mais restritiva, aceitando somente valores dentro do intervalo permitido para cada campo. E se você olhar na documentação, verá que existem 4 campos para a hora, cada um representado por uma letra diferente e com um intervalo específico de valores:
Letra   Nome do campo/valores
H       Hour in day (0-23)
k       Hour in day (1-24)
K       Hour in am/pm (0-11)
h       Hour in am/pm (1-12)

Como você estava usando hh (minúsculo), só são permitidos valores entre 1 e 12. Ao tentar fazer o parsing de "17:20", ocorre a exceção, já que 17 está fora do intervalo de valores válidos para o campo h.
Repare que no seu caso você pode usar HH (maiúsculo) ou kk (minúsculo): o primeiro aceita meia-noite como o valor zero, e o segundo, como o valor 24. Verifique nos seus casos de uso como você recebe este valor e use o campo que for mais adequado.

Formatar Hora utilizando initBinder


How can I read numbers from an file and use them in an array?

Question: I am making a program that asked the user to open and existing txt file. The program should read the numbers from the file and storing them into arrays. I am supposed to create different functions with those numbers in the array, such as getting the largest number, the lowest number, the sum, and the average. I have done the functions already but I do not know how to extract the numbers from the array.
Here is an example of numbers but instead of being separated by space, they're separated by a new line.
53
22
87
103
-3
75
220
1
64
543
98
44
int getLowest(int num[], int size);
int getHighest(int num[], int size);
int getSum(int num[], int size);
int getAverage(int num[], int size);

int main()
{
    string fileName;
    ifstream inputFile;
    const int ARRAY_SIZE = 12;
    int numbers[ARRAY_SIZE];

    cout << "Enter the name of imput file: ";
    cin >> fileName;

    inputFile.open(fileName);

    if (inputFile)
    {

            cout << " numbers read from input file.\n"
                << "The lowest value is " << getLowest(numbers, ARRAY_SIZE) << endl;
    }
    else
    {
        //Display error message
        cout << "Error, this file does not exist.";
    }
    system("pause");
}

int getLowest(int num[], int size)
{
    int temp = num[0];

    for (int i = 0; i < size; i++)
    {
        if (temp < num[i])
        {
            temp = num[i];
        }
    }
    return temp;
}

int getHighest(int num[], int size)
{
    int temp = num[0];

    for (int i = 0; i > size; i++)
    {
        if (temp > num[i])
        {
            temp = num[i];
        }
    }
    return temp;
}

int getSum(int num[], int size)
{
    int sum = 0;

    for (int i = 0; i < size; i++)
    {
        sum += num[i];
    }
    return sum;
}

double getAverage(int num[], int size)
{
    int sum = 0;
    double average;

    for (int i = 0; i < size; i++)
    {
        sum += num[i];
    }

    average = sum / size;

    return average;
}

When I open the file with the numbers shown above, the result I get does not work. I get:
010FFCE0 numbers read from input file.
The lowest value is 1968178332
Where it says "010FFCE0" i would like to get something that says the numbers of values, and the lowest value I would like it to be the actual lowest value.
Comment: If you have trouble with a basic fundamental of the language such as reading data from a file, you should write a very simple 3 to 5 line program doing or attempting to do just that -- read from a file.  All of these things with average and sums are not important.  Also all C++ books discuss how to read from a file Hint -- you're reading from a file already in your program -- `cin >> fileName` reads from a "file", that file being the keyboard.  Reading from a file uses the exact same syntax, using `>>`.
Comment: FYI, getAverage() is simply `return getSum(num, size) / (double)size;`.  One thing you should be aware of is to reuse the code you already wrote.
Comment: Also, you are calling `getLowest` before you read anything from the file.  Programs run top-down, a line at a time.  Seems as if you should review how to read data from a file.  All you did was open the file.
Comment: A key to [debugging programs](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/) is to make sure each step works. Before worrying about the highest/lowest/etc. functions, you should verify that you have in fact "read the numbers from the file and storing them into arrays". Have you done that yet?
Comment: @PaulMcKenzie I am aware of that. I have fixed that in another IDE I am using. Also How do I read the data from the file. That is my question. Thank you.
Comment: @JaMiT Well, that is what I am struggling with, I am not sure how to do that. I am a beginner and kind of have issues with files and arrays so using both is kind of my issue.
Comment: @LLC You should ask about what you are struggling with, not about the next steps you plan to take. Otherwise your question will likely be unclear and the answers likely unhelpful.
Answer: Here is an example of reading numbers from a file into std::vector<int>:
int number = 0;
std::vector<int>    database;
while (inputFile >> number)
{
  database.push_back(number);
}

The std::vector is a good choice here because it expands dynamically as necessary (performing dynamic memory allocation as necessary).
However, you don't need to store the numbers in order to determine the highest, lowest and average:
int sum = 0;
int highest;
int lowest;
inputFile >> highest;
lowest = highest;
sum = highest;
int number;
int quantity = 1;
while (inputFile >> number)
{
  if (number > highest)
  {
    highest = number;
  }
  if (number < lowest)
  {
    lowest = number;
  }
  sum += number;
  ++quantity;
}
double average = (sum * 1.0) / quantity;


Oracle SQL PLS-00103 error INSERT NEW ROW

Question: This will be a long one and I am sorry if the question is not so interesting. I am just a beginner with Oracle SQL.
I am kind of new with Oracle and for now I try to make a script to add a new line in a table T_USER.
This is my code:
SET SERVEROUTPUT ON; --- IT WAS OFF BY DEFAULT

--- declare the variable

DECLARE

TUSERID NUMBER(38,0);
TORGID  NUMBER(38,0) := 'Write-the-Org-ID-Here';
TROLE   NUMBER(38,0) := 'Write-the-role-Here';
TQDL    NUMBER(38,0) := null;
TFIRSTNAME  VARCHAR2(255 BYTE)  := 'Write-the-First-Name-Here';
TLASTNAME   VARCHAR2(255 BYTE) := 'Write-the-Last-Name-Here';
TEMAIL  VARCHAR2(255 BYTE) := 'Write-the-email-Here';
TEMAILSUBSCRIPTION  NUMBER(1,0) := null;
TDIVISION   VARCHAR2(255 BYTE) := 'Write-the-division-Here';
TQNUMBER    VARCHAR2(255 BYTE) := 'Write-the-QNumber-for-the-user-Here';
TACTIVE NUMBER(1,0) := 1;
TCREATOR    NUMBER(38,0);
TCREATED    TIMESTAMP(6);
TEDITOR NUMBER(38,0);
TEDITED TIMESTAMP(6);
TISDELETED  NUMBER(1,0)  := 0;
TLOGIN  VARCHAR2(255 BYTE) := 'Write-the-QNumber-for-the-user-Here';
TSETTINGS   CLOB := null;
TDEFAULTINBOX   NUMBER(38,0) := null;
TACCESSTOPST    NUMBER(38,0) := null;
TTIME_ZONE  VARCHAR2(100 CHAR) := 'Write-the-Time-Zone-Here';
TLIMITEDACCESS  NUMBER(1,0) := null;
TVALID_UNTIL    TIMESTAMP(6);
TCOMMENTS   VARCHAR2(255 CHAR) := null; --- I think you can insert the number of the Incident here
TAFTERSALESACCESS   NUMBER(38,0) := null;
TSOURCE VARCHAR2(5 BYTE) := 'QCAT';

---- BEGIN

BEGIN

SELECT COUNT(USERID) + 1
INTO TUSERID
FROM T_USER;
--------
SELECT USERID
INTO TCREATOR
FROM T_USER
WHERE LOGIN = 'Your-Q-number';
-------
SELECT  systimestamp
INTO TCREATED
FROM dual;
---
SELECT USERID
INTO TEDITOR
FROM T_USER
WHERE LOGIN = 'Your-Q-number';
 ----
SELECT systimestamp
INTO TEDITED
FROM dual;
-----
SELECT TO_CHAR
((select add_months((SELECT systimestamp FROM dual),1 *12) from dual), 'MM-DD-YYYY HH24:MI:SS') ----"TODAY" ?????
INTO TVALID_UNTIL
FROM DUAL; ---- ADD one year to the currrent date

END

----INSERT INTO

INSERT INTO T_USER (USERID,
ORGID,
ROLE,
QDL,
FIRSTNAME,
LASTNAME,
EMAIL,
EMAILSUBSCRIPTION,
DIVISION,
QNUMBER,
ACTIVE,
CREATOR,
CREATED,
EDITOR,
EDITED,
ISDELETED,
LOGIN,
SETTINGS,
DEFAULTINBOX,
ACCESSTOPST,
TIME_ZONE,
LIMITEDACCESS,
VALID_UNTIL,
COMMENTS,
AFTERSALESACCESS,
SOURCE)
VALUES(TUSERID,
TORGID,
TROLE,
TQDL,
TFIRSTNAME,
TLASTNAME,
TEMAIL,
TEMAILSUBSCRIPTION,
TDIVISION,
TQNUMBER,
TACTIVE,
TCREATOR,
TCREATED,
TEDITOR,
TEDITED,
TISDELETED,
TLOGIN,
TSETTINGS,
TDEFAULTINBOX,
TACCESSTOPST,
TTIME_ZONE,
TLIMITEDACCESS,
TVALID_UNTIL,
TCOMMENTS,
TAFTERSALESACCESS,
TSOURCE);

I get the following error(s):
Error starting at line : 5 in command -
DECLARE

TUSERID NUMBER(38,0);
TORGID  NUMBER(38,0) := 'Write-the-Org-ID-Here';
TROLE   NUMBER(38,0) := 'Write-the-role-Here';
TQDL    NUMBER(38,0) := null;
TFIRSTNAME  VARCHAR2(255 BYTE)  := 'Write-the-First-Name-Here';
TLASTNAME   VARCHAR2(255 BYTE) := 'Write-the-Last-Name-Here';
TEMAIL  VARCHAR2(255 BYTE) := 'Write-the-email-Here';
TEMAILSUBSCRIPTION  NUMBER(1,0) := null;
TDIVISION   VARCHAR2(255 BYTE) := 'Write-the-division-Here';
TQNUMBER    VARCHAR2(255 BYTE) := 'Write-the-QNumber-for-the-user-Here';
TACTIVE NUMBER(1,0) := 1;
TCREATOR    NUMBER(38,0);
TCREATED    TIMESTAMP(6);
TEDITOR NUMBER(38,0);
TEDITED TIMESTAMP(6);
TISDELETED  NUMBER(1,0)  := 0;
TLOGIN  VARCHAR2(255 BYTE) := 'Write-the-QNumber-for-the-user-Here';
TSETTINGS   CLOB := null;
TDEFAULTINBOX   NUMBER(38,0) := null;
TACCESSTOPST    NUMBER(38,0) := null;
TTIME_ZONE  VARCHAR2(100 CHAR) := 'Write-the-Time-Zone-Here';
TLIMITEDACCESS  NUMBER(1,0) := null;
TVALID_UNTIL    TIMESTAMP(6);
TCOMMENTS   VARCHAR2(255 CHAR) := null; --- I think you can insert the number of the Incident here
TAFTERSALESACCESS   NUMBER(38,0) := null;
TSOURCE VARCHAR2(5 BYTE) := 'QCAT';

---- BEGIN

BEGIN

SELECT COUNT(USERID) + 1
INTO TUSERID
FROM T_USER;
--------
SELECT USERID
INTO TCREATOR
FROM T_USER
WHERE LOGIN = 'Your-Q-number';
-------
SELECT  systimestamp
INTO TCREATED
FROM dual;
---
SELECT USERID
INTO TEDITOR
FROM T_USER
WHERE LOGIN = 'Your-Q-number';
 ----
SELECT systimestamp
INTO TEDITED
FROM dual;
-----
SELECT TO_CHAR
((select add_months((SELECT systimestamp FROM dual),1 *12) from dual), 'MM-DD-YYYY HH24:MI:SS') ----"TODAY" ?????
INTO TVALID_UNTIL
FROM DUAL; ---- ADD one year to the currrent date

END

----INSERT INTO

INSERT INTO T_USER (USERID,
ORGID,
ROLE,
QDL,
FIRSTNAME,
LASTNAME,
EMAIL,
EMAILSUBSCRIPTION,
DIVISION,
QNUMBER,
ACTIVE,
CREATOR,
CREATED,
EDITOR,
EDITED,
ISDELETED,
LOGIN,
SETTINGS,
DEFAULTINBOX,
ACCESSTOPST,
TIME_ZONE,
LIMITEDACCESS,
VALID_UNTIL,
COMMENTS,
AFTERSALESACCESS,
SOURCE)
VALUES(TUSERID,
TORGID,
TROLE,
TQDL,
TFIRSTNAME,
TLASTNAME,
TEMAIL,
TEMAILSUBSCRIPTION,
TDIVISION,
TQNUMBER,
TACTIVE,
TCREATOR,
TCREATED,
TEDITOR,
TEDITED,
TISDELETED,
TLOGIN,
TSETTINGS,
TDEFAULTINBOX,
TACCESSTOPST,
TTIME_ZONE,
TLIMITEDACCESS,
TVALID_UNTIL,
TCOMMENTS,
TAFTERSALESACCESS,
TSOURCE);
Error report -
ORA-06550: line 65, column 1:
PLS-00103: Encountered the symbol "INSERT" when expecting one of the following:

   ; <an identifier>
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:

Thank you in advance for your help. I spend hours and this is the final result I was able to wrote, I can't understand what I do wrong.
Comment: Why did you tag an Oracle question with MySQL and SQL Server?
Answer: Try putting a semicolon right after END.
Answer: Your END is the wrong place. A unit in PL/SQL starts with begin and finishes with END. You can have more units, but in your case as you have only one BEGIN, so the last command must be an END;
declare
-- declarantion of variables and cursors
begin
-- processing
end;

So, in your code
DECLARE

TUSERID NUMBER(38,0);
TORGID  NUMBER(38,0) := 'Write-the-Org-ID-Here';
TROLE   NUMBER(38,0) := 'Write-the-role-Here';
TQDL    NUMBER(38,0) := null;
TFIRSTNAME  VARCHAR2(255 BYTE)  := 'Write-the-First-Name-Here';
TLASTNAME   VARCHAR2(255 BYTE) := 'Write-the-Last-Name-Here';
TEMAIL  VARCHAR2(255 BYTE) := 'Write-the-email-Here';
TEMAILSUBSCRIPTION  NUMBER(1,0) := null;
TDIVISION   VARCHAR2(255 BYTE) := 'Write-the-division-Here';
TQNUMBER    VARCHAR2(255 BYTE) := 'Write-the-QNumber-for-the-user-Here';
TACTIVE NUMBER(1,0) := 1;
TCREATOR    NUMBER(38,0);
TCREATED    TIMESTAMP(6);
TEDITOR NUMBER(38,0);
TEDITED TIMESTAMP(6);
TISDELETED  NUMBER(1,0)  := 0;
TLOGIN  VARCHAR2(255 BYTE) := 'Write-the-QNumber-for-the-user-Here';
TSETTINGS   CLOB := null;
TDEFAULTINBOX   NUMBER(38,0) := null;
TACCESSTOPST    NUMBER(38,0) := null;
TTIME_ZONE  VARCHAR2(100 CHAR) := 'Write-the-Time-Zone-Here';
TLIMITEDACCESS  NUMBER(1,0) := null;
TVALID_UNTIL    TIMESTAMP(6);
TCOMMENTS   VARCHAR2(255 CHAR) := null; --- I think you can insert the number of the Incident here
TAFTERSALESACCESS   NUMBER(38,0) := null;
TSOURCE VARCHAR2(5 BYTE) := 'QCAT';

---- BEGIN

BEGIN

SELECT COUNT(USERID) + 1
INTO TUSERID
FROM T_USER;
--------
SELECT USERID
INTO TCREATOR
FROM T_USER
WHERE LOGIN = 'Your-Q-number';
-------
SELECT  systimestamp
INTO TCREATED
FROM dual;
---
SELECT USERID
INTO TEDITOR
FROM T_USER
WHERE LOGIN = 'Your-Q-number';
 ----
SELECT systimestamp
INTO TEDITED
FROM dual;
-----
SELECT TO_CHAR
((select add_months((SELECT systimestamp FROM dual),1 *12) from dual), 'MM-DD-YYYY HH24:MI:SS') ----"TODAY" ?????
INTO TVALID_UNTIL
FROM DUAL; ---- ADD one year to the currrent date

    ----INSERT INTO

INSERT INTO T_USER (USERID,
ORGID,
ROLE,
QDL,
FIRSTNAME,
LASTNAME,
EMAIL,
EMAILSUBSCRIPTION,
DIVISION,
QNUMBER,
ACTIVE,
CREATOR,
CREATED,
EDITOR,
EDITED,
ISDELETED,
LOGIN,
SETTINGS,
DEFAULTINBOX,
ACCESSTOPST,
TIME_ZONE,
LIMITEDACCESS,
VALID_UNTIL,
COMMENTS,
AFTERSALESACCESS,
SOURCE)
VALUES(TUSERID,
TORGID,
TROLE,
TQDL,
TFIRSTNAME,
TLASTNAME,
TEMAIL,
TEMAILSUBSCRIPTION,
TDIVISION,
TQNUMBER,
TACTIVE,
TCREATOR,
TCREATED,
TEDITOR,
TEDITED,
TISDELETED,
TLOGIN,
TSETTINGS,
TDEFAULTINBOX,
TACCESSTOPST,
TTIME_ZONE,
TLIMITEDACCESS,
TVALID_UNTIL,
TCOMMENTS,
TAFTERSALESACCESS,
TSOURCE);

COMMIT;

END;


Can a defender legally carry a receiver out of bounds?

Question: If a receiver makes a jumping sideline catch, I take it, it's legal for a defender to push him out of bounds, once the catch is made.
What if the defender catches the receiver before he got both feet on the ground and carries him a few yards to drop him out of bounds. Where would the boundary be for this to be illegal?
Comment: I am relatively sure a rule exists against this. Vaguely speaking, you can move an opponent ball-carrier in a tackle as a part of natural momentum, but you can't force them to move if they have the option of stopping.
Answer: It is legal to catch/carry a receiver out-of-bounds, in the sense that no flag is thrown for a foul, however the pass would be considered completed (or intercepted in the case for the defence).
This is covered in the NFL Rulebook under Rule 8 - Section 1 - Article 3

ARTICLE 3. COMPLETED OR INTERCEPTED PASS
[...]
Notes:

If a player, who is in possession of the ball, is held up and carried out of bounds by an opponent before both feet or any part of his body other than his hands touches the ground inbounds, it is a completed or intercepted pass. It is not necessary for the player to maintain control of the ball when he lands out of bounds.
Comment: Wow, they really have rules for everything...