Error in try catch while converting VC6 to VS2008

Question: When I opened a VC6 project in VS2008 and tried building it , initially I got the error:

fatal error C1083: Cannot open include file: 'iostream.h': No such file or directory
error C2259: 'CException' : cannot instantiate abstract class
error BK1506 : cannot open file '.\Debug\SClientDlg.sbr': No such file or directory    BSCMAKE SClient

Now I have changed #include"iostream.h" to #include"iostream"  and now getting 7errors ( as I have used  try and catch 7 places) saying:

error C2259: 'CException' : cannot instantiate abstract class

Below is the snippet from that code:
void SClientDlg::ProcessDomainName(int *m_pDlg,char* strDomainName,int iLen)
{
    try
    {
    //Do Something

    }
    catch(CException ex)
    {
        printf("Exception: %d",GetLastError());
    }

}

Answer: You likely need to do this:
catch(CException& ex) // const& might be better

Since CException is abstract, you cannot instantiate it, but you can reference a non-abstract object that derives from it.
Comment: Solved the error, but curious to know why it was not throwing any error in VC6
Comment: @Subhen: Not a clue. :) Probably had the same semantics, but VC6 was pre-standard and I haven't put much effort into learning it.


Galois principle for ideals

Question: Let $L/K$ be a finite Galois extension of number fields with Galois group $G$. Determine a necessary and sufficient condition on $L/K$ to
ensure that
$$\{I\in \text{Id}_L,\text{ such that }\sigma (I)=I, \forall \sigma \in G\}=\text{Id}_K$$
where $\text{Id}_K$ is seen as a subgroup of $\text{Id}_L$ through the extension
map $I\rightarrow IO_{L}$.
So here is my argument. One can show that if ${Q_i}\subset O_L$ are all the primes lying over a prime $P\subset O_K$, then $\forall \sigma \in G$, we have $\sigma (Q_i)$ is one of the $Q_j$'s. Now we know that there must exist a prime ideal $P$ which ramifies in $O_L$, say $\displaystyle P=\prod Q_i^{e}$, where $e>1$. Then I can take $I=\prod Q_i$ which clearly is fixed by every automorphism and not in $\text{Id}_K$, and thus nothing else besides $L=K$ works.
However, because of the way the question is asked I have suspicions that the above is not completely true. Any help?
EDIT: I already see where this failed, thanks to Mathmo123, but I guess I will leave it here if someone wants to show how this is done.
Comment: What is $\mathrm{Id}_K$? I don't think it's standard notation. Is it the set of ideals of $\mathcal O_K$?
Comment: Yes, those are the fractional ideals in $O_K$.
Answer: Your mistake is this:

It's not true that there must exist a prime ideal of $\mathcal O_K$ which ramifies in $\mathcal O_L$.

For example, the extension $\mathbb Q({\sqrt{-5}},i)/\mathbb Q(\sqrt{-5})$ is unramified at all primes. Note that the class group of $\mathbb Q({\sqrt{-5}})$ is cyclic of order $2$.
In general, one of the key results of class field theory is that there is a maximal extension $L$ of a number field $K$ that is unramified at all primes, such that $\mathrm{Gal}(L/K)$ is isomorphic to the (narrow) class group of $K$. In particular, if $K=\mathbb Q$, you are correct that we must have $L=\mathbb Q$.
Therefore a necessary condition is that $L$ must be unramified at all primes.
To see why this is sufficient, let $I$ be any fractional ideal of $L$ and write
$$I=\mathfrak{p}_1^{a_1}\cdots\mathfrak{ p}_k^{a^k}$$where the $a_i$ are non-zero integers and the $\mathfrak p_i$ are primes. Suppose that $\sigma(I)=I$ for all $\sigma\in G=\mathrm{Gal}(L/K)$.
Since the $G$ acts transitively on the primes above any prime of $K$ and $L/K$ is unramified at all primes,  we deduce that if $\mathfrak p^{a}\mid I$, then $\mathfrak q^a\mid I$, where $\mathfrak q = (\mathfrak p\cap \mathcal O_K)\mathcal O_L=\prod_{\text{primes $\mathfrak p'$ above }\mathfrak p\cap\mathcal O_L}\mathfrak p'$.
Answer: As a complement to Matmo123's answer, I would like to take a cohomological approach, not for the sake of « abstract non sense », but in order to show that your problem is just an introduction the so called « genus theory » for class groups. Notations : $L/K$ is finite Galois with group $G$, $I_K$ and $I_L$ are the respective groups of fractional ideals. There are two canonical maps relating $I_K$ and $I_L$ , the extension map $\epsilon : I_K -->I_L^{G}$ and the norm map $\nu : I_L-->I_L^G$. In the Galois situation, they are defined as follows on prime ideals :
1). If $P$ is a prime ideal of $K$, $\epsilon (P)$ is the product of the powers $Q^{e_P}$ for all the primes $Q$ of $L$ above $P$ . Note that $G$ permutes transitively all the $Q$'s, and the ramification index $e_P$ depends only on $P$
2). If $Q$ is a prime ideal of $L$ above $P$, $\nu (Q)$ is the product of all the $Q$'s
Let us first determine $I_L^G /\epsilon (I_K)$ . The key point is that by definition $I_L$ is a free $\mathbf Z [G]$-module over the prime ideals of $L$, which implies that its Tate cohomology vanishes, in particular $\hat H^0(G, I_L) = 0 $ (see e.g. Serre's « Local Fields », chapter 8). This means exactly that $I_L^{G} = \nu (I_L)$, and this gives immediately that $ I_L^{G}/\epsilon (I_K) = \nu (I_L) / \epsilon (I_K) = \Sigma  {\mathbf Z / e_P \mathbf Z}$ (the latter sum makes sense  because almost all ${e_P}$ are 1). In particular, $ I_L^{G} = \epsilon (I_K)$ iff $L/K$ is unramified.
Now let us tackle a much more interesting problem concerning the class groups $C_K$ and $C_L$, more specifically the determination of the kernel and cokernel, denoted resp. $Cap(L/K)$ and $Cocap(L/K)$, of the natural map $C_K --> C_L^{G}$ induced by $\epsilon$. Starting from the definition of the class groups and manipulating cohomology, we can get an exact sequence  $1 -->Cap(L/K)--> Pr_L^{G}/Pr_K--> I_L^{G}/\epsilon (I_K)--> Cocap (L/K)-->H^1(G, Pr_L)-->1$, where Pr(.) is the group of principal ideals. In particular cases the calculations can be pushed further : if $L/K$ is unramified, $Cap (L/K) = H^1(G, U_L)$, where $U (.)$ is the group of units ; if $G$ is cyclic, one can express the quotient #$ C_L^{G}$/#$C_K$ in normic terms (this is Chevalley's « ambiguous class formula »), etc.

Galois principle for ideals


Show Office 365 alias email as recepient in e-mail client

Question: When creating a new (shared)mailbox to Office 365 with a primary email address, you have the option to add multiple alias email addresses too.
When sending an email to one of these alias addresses, the recepient will always see the primary email address as the address the mail was sent to in his email client (for example Outlook).
If you want to see to which alias the email was actually sent, you have to look into the email header.
So the question is: is there a way to show the alias instead of the primary email address for incoming mails in the email client?
Comment: That's pretty much how it is with Exchange servers. One option with Outlook is to add filters that moves messages to different folders based on the original recipient address.
Answer: Find the following similar cases for your reference:
Exchange 2010 - Retaining the 'alias' in the 'To:' field after the message is delivered (for rules, routing, etc.)
emails sent internally to alias address doesn't have proper To: address


How to import Amazon Lex intent and use it in Botium convo directly for testing

Question: How to import Amazon lex intent and use it in boitum convo directly for testing?
https://github.com/codeforequity-at/botium-connector-lex
Comment: We are currently working on the Botium Lex connector to add such features. Basic importer feature is available in pending PR (https://github.com/codeforequity-at/botium-connector-lex/pull/4). I will post a response here with instructions as soon as this is part of a release.
Answer: See this tutorial how to do this in Botium Box: Tutorial: Using Paraphrasing to Increase Conversational AI Test Coverage.
You can also use the Botium Connector Lex CLI:
<code>npx botium-connector-lex-cli import --buildconvos --buildentities --output spec/convo
</code>

Bot intents and user examples are mapped to utterances in BotiumScript
Slots in user examples are either filled with enumeration values (for enumeration slot types) or with samples values from the official documentation
Convos are using the utterances as input and attach an INTENT asserter
If using the --buildentities switch, the utterances are separated by slot names and an additional ENTITIES asserter is attached


Can't play Bass F & G with Treble E

Question: I bought YamahaOrgue and started taking lessons online and as an intermediate step i downloaded (EOP, everyone piano), Now in the recent lesson the teacher played simple version of the (Irish Woman Washer), in this piece she pressed (Bass F and G together with Treble E), i grow to like midi more than the physical orgue/piano but when trying to press them together it did not work on my laptop!, so i tried couple of other programs but the problem persist, does anyone know how to resolve it ?!
I am sorry if i said wrong names, bcz i am newbie in the realm of playing music.
Comment: Are you saying that you're trying to play using the *text keyboard* of your laptop?
Comment: Taking a wild guess from rather limited information, your issue is one of [keyboard rollover](https://en.wikipedia.org/wiki/Rollover_\(key\)) for which there is no fix except buy a keyboard with a higher rollover count… or indeed an actual musical keyboard.
Comment: @Tetsujin my thought indeed... I have an answer already, I'm just waiting for a confirmation, as I strongly hope that the OP is really not trying to learn music by using the computer keyboard, especially with alphabetic keys.
Comment: @musicamante yes, the laptop keyboard but it is not working
Comment: @Tetsujin but it work fine When playing Bass F & G with Treble G for instance
Comment: See musicamante's answer below - it can often depend on how closely-grouped the keys are; but you will never achieve any sort of musical proficiency trying to play a computer keyboard.
Answer: tl;dr: Just don't.
Really, please.
You cannot learn to play music by using your computer keyboard. It's like trying to learn cooking using an excavator. Or to drive a car with your chin.
What you're experiencing is due to the rollover limitation of common computer keyboards: they can handle only few keys pressed together. It's not just a matter of the number of pressed keys, but their position in the keyboard matrix: except from modifier keys (like Ctrl or Alt), there are only many (close) keys that can be kept pressed and correctly recognized as such at the same time, and the order of press events also matters.
Consumer keyboards usually can get up to 2-4 keys at maximum, depending on their position: the more they're close, the less you can press together.
There are some high-end "n-key rollover" keyboards, usually aimed for gamers, but their price is usually high (80-100$ at least), which makes it even more useless for this matter: playing with a computer keyboard (especially if using alphabetic notation) has really very limited benefits - if any. Besides the above problem, computer keyboards have layouts that don't follow "musical" requirements, so in the end trying to play with them is just uncomfortable, pointless and with great limitations.
I strongly suggest you to buy an actual keyboard: even a cheap and small one would be hundreds times better (for example, the M-Audio Keystation Mini).
You may not be used to that (and then believe that using your laptop's keyboard is better), but it's just a matter of habit, and in the long run (actually, not that long) you'll only see benefits.

Can't play Bass F & G with Treble E


Rails 4 + -jquery-datatable + ajax-datatable - Erro 406 Http e ActionController::UnknownFormat format json

Question: Estava estudando rails e seguindo o tutorial https://github.com/antillas21/ajax-datatables-rails.
OS passos do tutorial eram os seguintes, criar uma datatable que realizaria uma requisiçao via json, ao controller que responderia com os dados e a data table seria populada.
No momento do teste recebi o seguinte erro do servidor: 406 Not Acceptable, e detalhando o erro pelo chrome na aba network, é exibido o erro abaixo:
ActionController::UnknownFormat at /categories.json%20

ActionController::UnknownFormat

app/controllers/categories_controller.rb, line 8
``` ruby
    3     before_action :set_category, only: [:show, :edit, :update, :destroy]
    4
    5     # GET /categories
    6     # GET /categories.json
    7     def index

8       respond_to do |format|
      9         format.html
     10         format.json { render json: CategoryDatatable.new(view_context)}
     11       end
     12      end
     13
  ```

Pesquisei porém não consegui chegar ou encontrar uma solução.
Segue abaixo passo a passo do código caso alguem possa me ajudar ficarei agradecido:
View:

Coffe: Responsavel por atualizar a datatable quando chamada pela view

Controller - método index:

Erro browser : Aba Network:

Erro browser detalhado:

Ou seja o servidor pelo que entendi não aceita a chamada via json, porém não descobri como faze-lo aceitar. Os tutoriais ou erros parecidos que encontrei estão da mesma forma e segundo os autores funcionam.
Se eu faço a requisição direto no browser http://localhost:3000/categories.json é exibido o arquivo sem problemas:
{"draw":0,"recordsTotal":3,"recordsFiltered":3,"data":[[1,"Teste1","Erro","Sim"],[2,"Teste2","Melhoria","Sim"],[4,"Teste3","Erro Usuario","Não"]]}
Se alguem puder me ajudar ficarei agradecido.
Answer: O erro está indicando que o rails não reconhece o formato utilizado na requisição.
Na view o valor do atributo data-source possui um espaço após a url, portanto a requisição realizada pelo DataTable é http://localhost:3000/categories.jsonespaço e o rails está tentando renderizar o formato .jsonespaço
Basta você remover o espaço ao final do valor do data-source.
Comment: Vlw amigo muito obrigado...nem acredito nisso..um espaço... e achando que o erro era coisa de outro mundo...


What is the simplest way to return a ROW as well as loop through the ROWS with PDO?

Question: If I am doing an old query to return a row I would do something like this:
$sql = 'SELECT id FROM table WHERE email="' . mysql_real_escape_string($email) . '" LIMIT 1';
$res = mysql_query($sql);
$row = mysql_fetch_array($res);

echo $row['id'];

How do I do that with a Prepared Statement? I can get this far...
 $stmt = $dbh->prepare("SELECT id FROM table WHERE email = ? LIMIT 1");
 if ($stmt->execute(array($_POST['email']))) {

    // what goes in here to pull out this one row?

 }

Secondly, if I have multiple rows I would do it like this:
$sql = 'SELECT id FROM table WHERE email="' . mysql_real_escape_string($email) . '" ';
$res = mysql_query($sql);
while($row = mysql_fetch_array($res)) {

   echo $row['id'];

}

Likewise, with PDO I get to a similar place...
 $stmt = $dbh->prepare("SELECT id FROM table WHERE email = ? ");
 if ($stmt->execute(array($_POST['email']))) {

    // what goes in here to loop through the rows??
    //
    // something like this...?
    //
    while ($row = $stmt->fetch()) {
       echo $row['id'];
    }

 }

Answer: Assuming you're connected to the DB and $dbh is your PDO object.
<?php

$email = 'firstname.lastname@example.com';

$stmt = $dbh->prepare("SELECT `id` FROM `table` WHERE `email` = ?");

$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->bindParam(1, $email, PDO::PARAM_STR);

$stmt->execute();

/* One row. */
$result = $stmt->fetch();

if ($result !== FALSE) {
    $stmt->closeCursor();

    echo $result['id'];
}

/* Multiple rows. */
$result = $stmt->fetchAll();

if ($result !== FALSE) {
    foreach ($result as $row) {
        echo $row['id'];
    }
}

?>

Answer: Here is what I use:
For more info on PDO see: http://php.net/manual/en/book.pdo.php
How to use:
    //create connection
$connection = new Connection($settings,true);
$conn = $connection->conn;

    //query
   $sql = "SELECT StateName as State, StateAbbr as Abb FROM State";
    $values = array(":Abbr" => "AL");
    $query = new Query($conn);
    $testArr = $query->getArrayFromQuery($sql, $values);

CONNECTION: (Connection.php)
class Connection
{

    public $conn = null;

    /**
     * Creates PDO Database Connection
     *
     * @param array $params             Connection Data (host,database,username,password)
     * @param bool $useErrorReporting   True to Show Errors (optional)
     * @sets Database Connection
     * @access public
     */
    public function __construct($params,$useErrorReporting=false)
    {
        try
        {
            $host = "";
            $database = "";
            $username = "";
            $password = "";

            if(isset($params) && is_array($params))
            {
                $host = $params['database_connection']['host'];
                $database = $params['database_connection']['database'];
                $username = $params['database_connection']['username'];
                $password = $params['database_connection']['password'];

                $dsn = 'mysql:dbname='.$database.';host='.$host;
                $dbh = new PDO($dsn, $username, $password, array(PDO::ATTR_PERSISTENT => true));

                //display errors if true
                if($useErrorReporting)
                {
                    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                }
            }
            else
            {
                $dbh = null;
            }

        }
        catch (PDOException $e)
        {
            throw new Exception('Connection Failed: '.$e->getMessage());
        }

        $this->conn = $dbh;
    }

QUERY: Query.php
Class Query
{
    private $conn = null;

    /**
     * sets query properties
     *
     * @param object $conn      pdo connection object
     * @return void
     * @access public
     */
    public function __construct($conn)
    {
        $this->conn = $conn;
    }

    /**
     * getArrayFromQuery
     * gets array from given query
     *
     * @param string $sql       sql statement
     * @param array $values     array values to replace (":value" => 2)
     * @return array
     * @access public
     */
    public function getArrayFromQuery($sql, $values)
    {
        $retValue = array();
        $conn = $this->conn;
        $statement = "";

        try
        {
            //prepare sql statement
            $statement = $conn->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));

            //add values
            if(isset($values) && is_array($values))
            {
                $statement->execute($values);
            }

            //set return array to result array
            $retValue = $statement->fetchAll();

        }
        catch (PDOException $e)
        {
            throw new Exception("PDO Query Error: ".$e->getMessage());
        }
        catch(Exception $e)
        {
            throw new Exception("Process Query Error: ". $e->getMessage());
        }

        return $retValue;
    }

}


Are 10+ year contracts discouraged or prohibited in the NBA?

Question: In 2019, Mike Trout signed a 12-year, $430 million contract. This is on the heels of Bryce Harper signing a 13-year, $330 million contract. There have been several 10-year contracts signed by baseball players.
The longest contracts in the NBA during the 2018-2019 season are 5-6 years in length. The longest contracts in the NBA during the 2000s were 7 years in length.
Are 10+ year contracts discouraged or prohibited in the NBA? If discouraged, why?
Answer: As always, you want the fantastic CBA FAQ, in this case, Question 53 "Is there a limit to the length of a contract?":

The maximum years and raises depend on the type of contract, however the "standard" maximum length is four seasons [...] The following are exceptions to the standard:
[ ...a number of exceptions, but the longest is: ]
Extensions (Designated Veterans)  6 [years]

"Why?" is a more complicated question. The maximum contract length was introduced in order to prevent teams crippling their teams for multiple years by being tied into a high-priced contract with a veteran who is years past their prime - see e.g. Rick DiPietro for what happens if this kind of restriction doesn't exist.
While the contract length restriction has accomplished that aim, it's also had the effect of moving a lot of power to the players as teams can't lock up their legitimate superstars for long contracts - see in particular LeBron James's multiple moves, and Kevin Durant's move to the Warriors (and his potential leaving).
Comment: Part of limiting contract length may also come from salary caps. Allowing a 20 year contract when a player will never play the length of it distorts the valuations on an annual basis, bypassing cap limits. Any deferred payments need to be accounted for accurately.
Comment: @JonCuster The CBA pretty much covers this with the [Over 38 Rule](http://www.cbafaq.com/salarycap.htm#Q56) - in short, this assumes the players won't play past age 38 and pushes the cap hit into any years before that, no matter how long the actual contract is.
Comment: Fun fact: Magic Johnson signed a 25 year deal with the Lakers in 1981. I've heard it likened to a *de facto* ownership stake. https://www.nytimes.com/1981/06/26/sports/magic-johnson-signs-25-million-contract.html


Singing well: mind or muscle?

Question: When I sing, it sounds absolutely nothing like Idina Menzel. Which is probably why she's a world-renowned singer, and I'm not.
But now what I'm wondering is... if you could somehow remove my brain and put hers into my skull instead, would she be able to make my voice sound amazing? (Obviously my voice won't sound like hers — no two voices sound identical. But would it sound good?)
In particular, is learning to sing well simply a matter of learning how to do it correctly? Or does it require a physical increase in actual muscle strength? Because a brain transplant would obviously deliver knowledge, but wouldn't have any effect on muscle strength.
Comment: Renown is not the judge of a good singer. There are plenty of excellent singers in the world who are not famous.
Comment: (And some famous ones who are not excellent...)
Comment: She sounds screechy to me. Try to sound like you, not like anyone else.
Comment: Can you define "Sing well" ? do you mean accurately (always hit the note), or after the style of someone whose vocals you enjoy ? I ask because for example Bob geldof isn't a great singer but his delivery is full of character and good things
Answer: Like most things (I think), it's both.
You have to have the physical strength and agility to sing well. Arpeggios require quick movement of vocal chords, and sustain requires strength of the diaphragm as well as breath control.
However, knowledge of how these things work, the best practices involved in singing, knowledge of how your particular body works, and knowledge of your particular range is also very important.
All of these things - physical and mental - come with training and practice. Speaking from personal experience, my range used to be much larger than it is now, and that's because I didn't exercise my voice and my vocal knowledge - I quit singing for years.
So, to answer the specific question, I think Ms. Menzel's brain would probably make your voice sound better (after a little experimentation), but if the muscles involved in singing are out of shape, there's a limit.
Comment: This raises several additional questions... which I will post as new questions, once I figure out how to pose them clearly.
Answer: The separation of mind and body is a fanciful idea, a myth.
The brain is connected to a nervous system that has more neurons in it than the brains of most animals. In fact, the human hand has more neurons in it than the brains of most animals. If you touch a hot stove with your hand, your hand itself will decide to pull back from the hot stove. It won't wait for your brain to weigh in on whether to pull back or not. When you learn to play the piano, that learning is taking place in your entire body, not just in your brain. Your hands are learning, your arms, your legs, and so on. It's the same with singing. Just a little less obvious. Idina Menzel's entire body has learned to sing like Idina Menzel, not just her mind or her larynx or her diaphragm.
We each have unique vocal instruments. Some of us have a lot of resonance in our voices, and some don't. The shape of our sinuses, larynx, windpipe, diaphragm, and so on all contribute to the way we sound. But even if you could somehow use my vocal instrument to sing, you wouldn't sound like me. The way we know this is that you can setup a single drumkit and have 2 drummers play it and they sound nothing like each other. Not just in the patterns or rhythms they play, but they will literally make the same snare drum sound like it is 2 different snare drums. There are famous stories about nobody being able to play John Bonham's drums but him, and nobody being able to play Jimi Hendrix' guitar setup but him.
So when you sing, it is your entire body that is singing.
Answer: I think the answer is yes on both counts. Singing is an athletic, muscular activity, but it involves rather tiny muscles in the larynx, throat, face, head, mouth, tongue, you name it. Breath support in the chest and abdominal muscles, which are larger and more powerful, also comes into play.
However, when you learn to sing, you don't approach it from the standpoint of building up muscle strength. Rather, you get a good vocal coach who teaches you how to make good sounds, and as you go about it and practice every day, everything else falls into place, including your muscle control.
But like any athletic endeavor, unless you practice and work out a little every day, you don't maintain your control over your body. If you go for days or weeks without singing, it's going to take some careful daily warming-up and conditioning exercises to get your full ability back.
Not to get too personal, but if you are a teenager, there is only so much you can achieve with singing lessons, as your body (which is your instrument) is still rapidly growing. As you become an adult and as you age, your body matures. If you start study singing around the age of 18 and after, your vocal abilities will increase accordingly. This is just a general observation; it varies with the individual.

Singing well: mind or muscle?


How reasonable is the idea to start learning drums from solo playing?

Question: I have an idea to learn drums in addition to my main instrument, piano. I do not plan to become exactly a drummer, just want to improve my understanding about the rhythm, maybe significantly. Some say I play all notes same duration at times that is a total shame.
I feel not ready for a complete drumset that I used to see, because of the space constrains (as piano is already using up some). Most likely playing only during the lesson itself will not work either. After some thinking I come to conclusion it may work to buy a single smaller size drum and try to learn soloing on it instead.
Would it be possible to ask how popular/known this approach would be, and is it a reasonable approach in general? I do not have the previous experience with drums.
Comment: I think it is a great idea. Concentrating on rhythm by using a drum would help the timing on the piano significantly.
Comment: By "soloing" do you mean "using only one drum" (as opposed to a full kit)?
Answer: For just practicing drumming basics (sticking, rudiments, etc) without involving your feet, a good practice pad like the RealFeel pads do an excellent job. They give great stickfeel (best of any practice pad I've tried) and are very quiet. The two different sides means you can practice in two different regimes. The softer side is quieter and gives a more generous stick bounce, but it's also more forgiving and masks mistakes. The harder side gives a more distinct "tap" from the stick, so it's easier to hear exactly what you're playing and how. It also doesn't give a high energy stick bounce so it requires more work (builds stronger chops) and requires better technique. These pads, in the 12" size, are a little more expensive than your average pad, but, after 10 years, mine's still going strong unlike the other pads I've owned. And the more realistic feel I think is easily worth a little extra money.
If you're willing to spend a bit more (and have a practice space where you won't disturb people) nothing beats the feel of a real drum. The stickfeel and sound of the drum changes with where you play on the drum and with how hard you play. You also need a real drum (with a real rim) to do rimshots. But buying a full kit is probably overkill. I'd recommend just buying a snare drum to start. It's your sort of most fundamental and technical drum because it's the most diverse in terms of the sounds it can make. The great thing about buying the 12" RealFeel pad is that it fits very nicely right on top of a 14" snare drum. So you can play your snare drum when it's convenient, and when you need to make less noise (or you just want to take your earplugs out for a little while), you can plop the pad down and keep practicing with the same setup, same positioning, etc. I think that makes the 12" pad easily worth the price delta over their 7" pad (although the 7" pad is more portable. I actually own both but the 12" is more of my "go-to" pad so it's the one I generally recommended as a first pad to my students).
As far as 4-limb integrated practicing is concerned, there are not so many good solutions. There are practice sets like this or this that are cheaper, take up less space than a full kit, and make less noise than a full kit, or you could just buy an electronic drum kit if you wanted as well, but I don't really care for these solutions. You don't really need to practice hitting toms. They usually aren't essential to the beat or style you're trying to learn. There are really only 4 main pieces - snare drum, bass drum, hi-hat, and ride cymbal - 4 pieces for 4 limbs. With these pieces you can play almost any type of music. I don't have a good link for it but Jojo Mayer, in his "Secret Weapons for the Modern Drummer" dvd (which is incredible btw), he has little transitions that feature him playing super diverse grooves on the same 4 pieces. There are just bass practice pads, which are pretty good if you've got a bass pedal. But the hi-hats and ride cymbals are very diverse and complex instruments. The cymbal practice pads you'll find in that Pearl practice kit or in most electronic drum sets are nothing at all like the real thing. They simulate playing real cymbals worse than a cheap keyboard with non-weighted keys simulates playing a real piano. So personally, the ideal practice setup for 4-limb integration with space and budgetary constraints is 1) a RealFeel pad either on top of a snare or in a snare basket, 2) a real bass drum pedal attached to a bass drum practice pad, 3) a real pair of hi-hat cymbals on a real hi-hat stand, and 4) a real ride cymbal. The cymbals don't have to be expensive. They just have to be real metal that really vibrates so you can get a sense of what playing a real cymbal actually feels like. EDIT: As far as making your real cymbals quiet when/if you need to, pads like these work alright. I don't love that they don't go all the way around the cymbal, because they move the center of gravity off center (where the mount is) so they don't sit at the same angle they would without the pads on. They also don't give the best stick bounce recovery energy, so you're not going to be practicing your 220+ bpm be-bop ride patterns on them. But they do a good job keeping things quiet, so when that really matters, you do what you gotta do. END EDIT
So that's my purist/snobbish advice. Real drums are hard to beat but they can be reasonably well simulated. Real cymbals cannot. And the subtleties matter when it comes to making a groove sound like a proper groove. But this is coming from a guy that used to make a living playing and teaching drums and percussion, so of course I'm going to be a little purist. But no, I wouldn't recommend going out and buying a full drum set. They're big and loud and heavy and expensive and 90% of the time those 4 main pieces alone would suffice. And probably at least 50% of the time the snare drum or practice pad alone will suffice. Gotta hit 'dem rudiments.
Comment: Excellent, in-depth answer with personal experience. Do you have any advice for muting cymbals if you need to keep the noise down? With that, I think this would be a perfect answer.
Answer: If the only purpose is to educate yourself about rhythm, hands, feet and knees are the only thing you need. If you want to use sticks, use a practice pad (phone books is a low cost alternative).
Comment: "hands, feet and knees" and a metronome ;)
Comment: +1 for this one and Sheldon's answer, a practice pad covers a wide range of what a drummer need to know about sticking. The simplest will only help for rhythmic purposes where more advanced ones will do the job for feeling, sound and even performance with a practice mode (for electronic ones).
Comment: "Phone books"?  Do those still exist?  I think you just outed yourself as my age.  :)
Answer: I have thought about the exact same thing and also have insufficient space to place a whole drum.
My purpose is to have a drum to be able to record some things to have a basic rhythm drum.
However, what I came across is a nice small and handy tool that works well enough for me.
The cajón is a box that has some parts of a whole drum in one box (snare, kick, ...).


How to return specific data type from PowerShell function i.e. DataTable

Question: I've been trying to write a utility function that will return initialized [System.Data.DataTable] object data type.
I am aware of the annoying PowerShell functions return behavior where it tries to "unroll" everything into a [System.Array] return type.
Previously I have always managed to get around that problem.
Usually using the "comma trick" to return your own array @(,$result) aways worked - however this time this does not seem to make a difference and I've run out of options...
Another trick I normally use is the $null assignments within the Process block (see my code bellow) - this way I fool the pipeline there is nothing to "unroll" on the output...
I am not taking impossible for an answer, so far based on my experience nothing is impossible in PowerShell :)
Here is my code:
function Get-SourceDataTable
{
    [OutputType([System.Data.DataTable])]
    [cmdletbinding()]
    param(
        [parameter(Mandatory=$true, Position=0)]
        [System.Data.SqlClient.SqlBulkCopy] $Destination,
        [parameter(Mandatory=$true, Position=1)]
        [System.Collections.Specialized.OrderedDictionary] $ColumnDefinition,
        [parameter(Mandatory=$false, Position=2)]
        [int]$ColumnStartIndex = 0
    )
    BEGIN{
        $datatable = New-Object System.Data.DataTable
        $colIndex = $ColumnStartIndex
    }
    PROCESS{
        $ColumnDefinition.Keys |
        foreach {
            $null = $datatable.Columns.Add($_, $ColumnDefinition[$_])   # define each column name and data type
            $null = $Destination.ColumnMappings.Add($_, $colIndex) # map column to destination table
            $colIndex++
        }
    }
    END{
        return ,$datatable
    }
}

I hope someone can get this code working...
Comment: Have you tried just casting the output as a DataTable? `[system.data.datatable]$MyVar = Get-SourceDataTable $Dest $ColDef`
Comment: Yes, I tried a casting it does not seem to have an effect on the output type
Comment: I've had the same problem. This is ridiculous to have to jump through all these hoops to get a function to return the data type you're already telling it to return. A function should ALWAYS return the data type specified, not a different type of object. If I wanted to return an array then I would write my function to return an array.
Answer: Rather than return use Write-Output -NoEnumerate.    For example:
function New-DataTable {
   $datatable = New-Object System.Data.DataTable
   $null = $datatable.Columns.Add("x",[int])
   $null = $datatable.Columns.Add("y",[int])
   $null = $datatable.Rows.Add(@(1,2))
   $null = $dataTable.Rows.Add(@(3,4))
   Write-Output -NoEnumerate $datatable
}

New-DataTable | Get-Member

Note however that if you just type New-DataTable, it might look like enumberated rows, but Get-Member tells you the actual type returned.
Comment: Good question and good answer. After I up-voted the question and the answer many months ago, I encountered the issue again, since I forgot the answer, my google result took me back here again. Really wish I could up-vote it again. :-)
Comment: Thanks, I had fun answering it too.
Answer: I got the function from the question to return DataTable type when I used LoadWithPartialName to load the assembly containing the type and pipe it out with Out-Null.
Don't ask me why, but feel free to comment if you know the reason.
The working function code is below. Note the return statement is not necessary I only use it to improve code readability:
function Get-SourceDataTable
{
    [OutputType([System.Data.DataTable])]
    [cmdletbinding()]
    param(
        [parameter(Mandatory=$true, Position=0)]
        [System.Data.SqlClient.SqlBulkCopy] $Destination,
        [parameter(Mandatory=$true, Position=1)]
        [System.Collections.Specialized.OrderedDictionary] $ColumnDefinition,
        [parameter(Mandatory=$false, Position=2)]
        [int]$ColumnStartIndex = 0
    )
    BEGIN{
        [System.Reflection.Assembly]::LoadWithPartialName("System.Data") | Out-Null
        $datatable = New-Object System.Data.DataTable
        $colIndex = $ColumnStartIndex
    }
    PROCESS{
        $ColumnDefinition.Keys |
        foreach {
            $null = $datatable.Columns.Add($_, $ColumnDefinition[$_])   # define each column name and data type
            $null = $Destination.ColumnMappings.Add($_, $colIndex) # map column to destination table
            $colIndex++
        }
    }
    END{
        return ,$datatable
    }
}

To summarize all known possible solutions to the problem of forcing PowerShell function to return specific data type:

use $null assignments
use comma to return an array ,$variable
use LoadWithPartialName("Assembly.Name") | Out-Null
use Write-Output -NoEnumerate $variable to return the type - credit goes to Burt_Harris

Finally, after the input from Burt_Harris (THANKS Burt!) the final working version of the function from this question is this:
function Get-SourceDataTable
{
    [OutputType([System.Data.DataTable])]
    [cmdletbinding()]
    param(
        [parameter(Mandatory=$true, Position=0)]
        [System.Data.SqlClient.SqlBulkCopy] $Destination,
        [parameter(Mandatory=$true, Position=1)]
        [System.Collections.Specialized.OrderedDictionary] $ColumnDefinition,
        [parameter(Mandatory=$false, Position=2)]
        [int]$ColumnStartIndex = 0
    )
    BEGIN{
        #[System.Reflection.Assembly]::LoadWithPartialName("System.Data") | Out-Null
        $datatable = New-Object System.Data.DataTable
        $colIndex = $ColumnStartIndex
    }
    PROCESS{
        $ColumnDefinition.Keys |
        foreach {
            $null = $datatable.Columns.Add($_, $ColumnDefinition[$_])   # define each column name and data type
            $null = $Destination.ColumnMappings.Add($_, $colIndex) # map column to destination table
            $colIndex++
        }
    }
    END{
        #return ,$datatable
        Write-Output -NoEnumerate $datatable
    }
}


Should I remove all CSS while sending HTML emails in Django?

Question: I have a Django-powered WebApp that occasionally needs to send pretty HTML emails to my users.
I'm learning how to send HTML emails using Django. Here are the instructions I'm following. They are quite simple and good: http://www.djangofoo.com/250/sending-html-email
By following these instructions I'm able to send HTML emails. However, the emails I want to send should share the styles and look-and-feel of my webApp of course. Each Django template on my website includes a bunch of CSS at the top that ensures a consistent look. However, when I simply send that template as and HTML emails, the styles do not kick in in the email. Does CSS not work while sending HTML emails through Django?? Do I need to manually and explicitly set the fonts, colors, bold, italics, of each element in the HTML template I would like to use for the email? How do other people do this?
Answer: CSS is very difficult to get right with html emails... The general rule is to use inline styles and try to stay as basic as possible.
This SO question has some good resources in it for guidance on designing html emails.
Answer: Instead of manually setting all styles in the email, I tend to use the same CSS styles as the site if I want emails that should be pretty. However, emails need the styles inlined, and for that I use the inlinestyler module, which will take the HTML and the CSS files and set the relevant styles inline before sending the email.
There are still some things to think about, if you are careless you get gigantic emails because you use big style settings everywhere, and many email clients will not do positioning correctly etc. so you may have to make custom CSS styles for your emails anyway. But even if you do, inlinestyler is useful, as you get much more maintainable emails with the CSS and the HTML separate.
Answer: CSS is supported by some email clients, and not supported by others. Some clients support inline styles and others do not. You can see a fairly verbose list here. Most of what can be done with HTML/CSS can be done with inline styles and (gasp) table layouts, but some of it is simply impossible. Tools like the one @Lennart mentioned are invaluable, but "just inline everything" doesn't accommodate for a number of issues. (Pseudo classes comes to mind as a major point (a:hover is supported by Outlook, while .classname:hover is not), as does background image (there is a hack to make that work though)).
I guess that my basic point is that you can try to shortcut the process by using inlinestyler or similar, but you are going to need to keep a separate set of files, and you'll definitely be doing a series of manual tweaks.
Answer: I think you will find that email clients will not retrieve the css.
Instead, in your email, put the contents of your CSS files directly into the email, with  around it.


Como funciona o ataque meet-in-the-middle?

Question: Estava procurando sobre o antigo 3DES e resolvi pesquisar porque não existe 2DES, encontrei poucas informações, até porque não "existiu" de fato 2DES.
Apesar ser abreviado também como MITM, ele não tem relação com o Man-in-the-middle, comumente abreviado de mesma maneira, pelo que procurei ele é aplicável sempre que se faz:
E(K, E(K, M))

Por isso o 3DES utiliza o formato no minimo o formato de E(K1, D(K2, E(K1, M))), usando ao menos duas chaves (K1 e K2) de 56 bits, pode utilizar também três chaves distintas. Porém pesquisando ele ainda seria vulnerável a este ataque de Meet-in-the-middle, porém com um custo maior do que o "2DES", que faria na época ser seguro o suficiente.
Considerando que E seja encriptação, D seja decriptação, K seja chave, M seja a mensagem.
Afinal o que é meet-in-the-middle?
Comment: Dahora, cara. Gosto muito de ver esse tipo de pergunta por aqui.
Answer: A matemática por trás do ataque é mais complexa do que o que eu vou por aqui na resposta, mas o princípio no qual se baseia é simples.
Algoritmos como o "Double DES" e o Triple DES possuem múltiplas etapas de criptografia, com chaves distintas. Isso aumenta a segurança porque o elemento criminoso que for querer quebrar sua criptografia tem que brutalizar mais de uma chave.
Vamos fazer uma conta simples: se existem n chaves em uma única etapa, eu tenho que testar n combinações possíveis para quebrar uma chave na força bruta. Mas se existem n chaves em uma etapa e m em outra, o meu esforço é de testar n * m combinações, o que pode ser um número muito maior.
Só que matematicamente, se chamarmos:

os dados originais de D;
os dados criptografados de C;
a função de encriptação de ENC;
a função de decriptação de DEC;
e as chaves usadas de m e n;

Temos que:

C = ENCm(ENCn(D))

A malandragem está em usar álgebra para brincar com a equação acima:

DECm(C) = DECm(ENCm(ENCn(D)))
  (primeira equação, decripta ambos os lados com m)

E logo em seguida:

DECm(C) = ENCn(D)
  (Corta uma encriptação com m seguida por uma decriptação com m do lado direito)

Fez sentido até aqui? Você não precisa testar m * n combinações, você só precisa testar m + n... O que é muito menor. Na verdade, quanto mais m e n crescem, maior é a diferença entre as duas formas.
Se ainda não deu pra perceber, lembre-se, você não precisa entender o resultado da encriptação/decriptação intermediária pra saber que um par de chaves deu certo ;)
Não preciso nem dizer o que acontece se a mesma chave for usada nas duas etapas, né? :D
E é por isso que o nome do ataque é encontro no meio. Você ataca o algoritmo de um lado (com a cifra) e do outro (com os dados originais), e no meio você encontra o tesouro.
Agora você pode dizer "ah, mas o atacante pode não ter os meus dados originais, afinal eu encriptei". Bom, isso é um caso de uso. Mas pense no caso em que o atacante obtém uma amostra de um texto plano e do resultado de encriptação com as suas chaves. Ele agora pode adivinhar as chaves e decriptar tudo mais que você tiver encriptado com essas chaves.
E por fim, é por isso que a indústria foi direto do DES para o DES triplo. Quando estavam por fazer um novo algoritmo perceberam que o DES duplo seria muito vulnerável a esse tipo de ataque. O triplo também é, mas é menos vulnerável (adicione mais uma etapa de encriptação) - a ponto de ter sido aceito por um tempo como um bom padrão. Não sei como está hoje.
Crédito onde é merecido, tirei várias informações da wikipdia.


AngularJS - Use ng-style to set color of radio button label when checked

Question: I know how to set the color of a radio button label with ng-style, like this:
ng-style="{'background-color': buttonColor}"

But how can I change the color of the radio button label when it is checked using the ng-style directive?  In css it is like this:
.radio-button:checked+label {
    background-color: #52b6db;
    border: 1px solid #52b6db;
}

EDIT: Basically, how do I tap into the :checked+label style property through ng-style?
Comment: Could you post a codepen?
Comment: you can use ng-class as well..
Comment: ngstyle uses inline style so it is not possible. Use ng-class instead
Answer: Basically call a function in your controller for ng-style and return the appropriate style object based on the value of the button.
ng-style="$ctrl.getStyle()"

function getStyle() {
if (some condition) {
    return {
        background-color: #52b6db;
        border: 1px solid #52b6db;
} else {
    return {...}
}

OK, this is a little bit out there, but you can do this. If on your index.html page you've loaded your app at the document level (on the html tag), you can actually have a  section with a controller on it and define css using controller references, so you could dynamically set colors for radio-button:checked+label this way.
Comment: I am wondering tho how to tap into the `:checked+label` style property through `ng-style`?
Comment: I don't think you need ng-style at all for this. It seems like something that you should just be able to do with straight css. I wouldn't try to mix ng-style with css classes. Seems like just going with ng-class would be much more straightforward.
Comment: but the thing is that with straight css classes I cannot make the color dynamic, whereas with `ng-style` I can
Comment: OK. Not sure you can tie into :checked+label there, but using a controller method should give you the same result.
Comment: Updated the answer. I did something like this on an app before I started using Angular Material.


My discord bot won't stop spamming a respond to my command

Question: I added a //search command to my bot. But when I tried running it, it gave me the options on where to search, but after a while, it starts spamming messages, and every time I type in the channel, it responds to that too. I haven't even answered the question yet and it immediately starts replying and giving me coins. Is there a way I can fix this? I've scanned the code multiple times and found no typos or errors; in fact, there are no errors logging into my console either.

If the code is needed, here:
const profileModel = require("../models/profileSchema");

module.exports = {
  name: "search",
  aliases: [],
  permissions: [],
  cooldowns: 30,
  description: "Search for some coin!",
  async execute(message, args, cmd, client, Discord, profileData) {
    const locations = [
      "Dragonspine",
      "Windrise",
      "Qingyun Peak",
      "Mt. Hulao",
      "Mondstadt City",
      "Springvale",
      "Kamisato Estate",
      "Guyun Stone Forest",
      "Fort Mumei",
      "Watatsumi Island",
    ];

    const chosenLocations = locations
      .sort(() => Math.random() - Math.random())
      .slice(0, 3);

    const filter = ({ author, content }) =>
      message.author == author &&
      chosenLocations.some(
        (location) => location.toLowerCase() == content.toLowerCase()
      );

    const collector = message.channel.createMessageCollector(filter, {
      max: 1,
      time: 30000,
    });

    const earnings = Math.floor(Math.random() * (1000 - 100 + 1)) + 100;

    collector.on("collect", async (m) => {
      message.channel.send(`You found ${earnings} primogems !`);

      await profileModel.findOneAndUpdate(
        {
          userID: message.author.id,
        },
        {
          $inc: {
            primogems: earnings,
          },
        }
      );
    });

    collector.on("end", (collected, reason) => {
      if (reason == "time") {
        message.channel.send("You ran out of time!");
      }
    });

    message.channel.send(
      `<@${
        message.author.id
      }> **Which location would you like to search?\n** Type the location in this channel\n \`${chosenLocations.join(
        "` `"
      )}\``
    );
  },
};

Answer: Super easy fix! The thing is you're creating a message collector on your TextChannel and then sending your message, of which location then user would want to pick, what you simply have to do is that move the collector to the Message object instead of TextChannel after sending the message.


Called function instance must depend on parameter

Question: I would like to make the function call depend on the parameter, that is, what version of the function is being called. I'm looking for a way to make the following code work, without making enum_value v a template argument. The goal is that if v==enum_value::A, the first instance is called. If v==enum_value::B the second instance must be called.
enum class enum_value { A, B, C };

auto foo(enum_value v) -> std::enable_if_t<v==enum_value::A>
{}

auto foo(enum_value v) -> std::enable_if_t<v==enum_value::B>
{}

Feel free to ask if I need to elaborate.
Comment: I call XY-problem -- what's your use case? You can't do that directly, since overload resolution and template instantiations are compile-time processes, while your value comes up at runtime. But there's probably a solution to the actual problem you've encountered.
Comment: I was creating multiple solutions for a certain problem. I was just wondering whether this was a way too. Thank you for your help!
Answer:
I'm looking for a way to make the following code work, without making enum_value v a template argument

I don't think it's possible what do you want.
As pointed by Quentin, if the enum value is a function argument, it is known (potentially) only run-time. But the compiler have to select the function compile-time.
You can think that make foo() constexpr, passing a constexpr value as arguments, permit a compile time selection of the right function. But this doesn't works because a constexpr function can be executed compile-time, but can also be executed run-time. So the compiler give error because must consider the run-time case.
The best I can imagine (non a great solution, I know) is pass through a select function; something as
enum class enum_value { A, B, C };

void foo_A ()
 { }

void foo_B ()
 { }

// ....

void select_foo (enum_value v)
 {
   switch (v)
    {
      case A: foo_A(); break;
      case B: foo_B(); break;
      // ...
      default: break;
    }
 }


isGooglePlayServicesAvailable always returns false

Question: I want to get the location using Google Play Services, but everytime I use the following code:
resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

I will get false back only as a result. Of course when I want to initialize a new location client (I know it s absolete) by
mLocationClient = new LocationClient(this, this, this);

I get false back only as well.
Where is my mistake? Does Google Play Services need to be updated on the phone? I already checked for system updates, there is the newest one on it. It is a Galaxy S5 mini if that might help.
Answer: The method isGooglePlayServicesAvailable returns 0 when succeeds, as you can see here:
https://developers.google.com/android/reference/com/google/android/gms/common/ConnectionResult#SERVICE_SUCCESS
So, 0 = false...
Answer: There are several possibilities that you are getting that error

Services are outdated
Services are disabled/removed
Another Samsung related bug

I have used this function to check if the services are new enough, otherwise I they will get a dialog and redirected to google play to update them
private boolean checkPlayServices() {
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS) {
        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
            GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show();
        }
        else {
            finish();
        }
        return false;
    }
    return true;
}

It will display the error.


Balanced categories and conservative functors.

Question: If $\mathbf{C}$ is a balanced category, then every faithful functor out of $\mathbf{C}$ is conservative.
Proof. Suppose $\mathbf{C}$ is a balanced category and let $F$ denote a faithful functor out of $\mathbf{C}.$ Suppose $\varphi$ is an arrow of $\mathbf{C}$ such that $F(\varphi)$ is an isomorphism. Then $F(\varphi)$ is both monic and epic. By faithfulness, this means that $\varphi$ is both monic and epic. By balancedness, this means that $\varphi$ is an isomorphism. Hence $F$ is conservative.

Question. Does the converse hold?
I.e. if every faithful functor out of $\mathbf{C}$ is conservative, is $\mathbf{C}$ necessarily balanced?
Answer: Following Qiaochu's suggestion, we can obtain a result of the kind you are looking for.
Say a morphism in $\mathcal{C}$ is a weak equivalence if it is both monic and epic. Then:

The following are equivalent:

$\mathcal{C}$ is a balanced category.
Every faithful functor $\mathcal{C} \to \mathcal{D}$ is conservative, and the weak equivalences in $\mathcal{C}$ satisfy the right Ore condition, i.e. for every morphism $f : X \to Y$ in $\mathcal{C}$ and every weak equivalence $y : Y' \to Y$ in $\mathcal{C}$, there is a commutative square of the form below,
  $$\require{AMScd}
\begin{CD}
X' @>{x}>> X \\
@V{f'}VV @VV{f}V \\
Y' @>>{y}> Y
\end{CD}$$
  where $x : X' \to X$ is also a weak equivalence in $\mathcal{C}$.

The downward implication is straightforward, so assume the second set of hypotheses. Since weak equivalences in $\mathcal{C}$ are monomorphisms, the right Ore condition suffices to establish a calculus of right fractions. Concretely, that means we have the following construction of the localisation of $\mathcal{C}$ with respect to weak equivalences:

The objects are as in $\mathcal{C}$.
The morphisms $X \to Y$ are equivalence classes zigzags of the form below,
$$\begin{CD}
X @<<< \bullet @>>> Y
\end{CD}$$
where the leftward-pointing arrow is a weak equivalence in $\mathcal{C}$, and given any commutative diagram in $\mathcal{C}$ of the form below,
$$\begin{CD}
X @<<< \bullet @>>> Y \\
@| @AAA @| \\
X @<<< \bullet @>>> Y \\
@| @VVV @| \\
X @<<< \bullet @>>> Y
\end{CD}$$
where all the leftward-pointing arrows are weak equivalences in $\mathcal{C}$, we define the top row and bottom row to be equivalent zigzags.

Call this category $\mathcal{D}$. There is an evident functor $\mathcal{C} \to \mathcal{D}$ and it is faithful: indeed, given a commutative diagram of the form below,
$$\begin{CD}
X @= X @>>> Y \\
@| @AAA @| \\
X @<<< X' @>>> Y \\
@| @VVV @| \\
X @= X @>>> Y
\end{CD}$$
where $X' \to X$ is an epimorphism, the two arrows $X \to Y$ must be equal.
Thus, under the hypothesis that every faithful functor $\mathcal{C} \to \mathcal{D}$ is conservative, every weak equivalence in $\mathcal{C}$ is already an isomorphism, i.e. $\mathcal{C}$ is balanced.
It may be worth noting that there is a non-balanced category $\mathcal{C}$ for which the above right Ore condition is satisfied, namely $\mathbf{Top}$. But there is an obvious faithful non-conservative functor $\mathbf{Top} \to \mathbf{Set}$, so we haven't learned much.
Comment: If we take $X'$ to be the pullback, I guess it suffices for weak equivalences to be stable under pullback. Pullbacks of monos are monos, so we're done if pullbacks of epis are epis.
Comment: Indeed. This is precisely what happens for $\mathbf{Top}$.
Answer: If this is true, the following seems to me like the only proof strategy that could work. Suppose $f : c \to d$ is monic and epic. Then you should try to show that the localization functor $C \to C[f^{-1}]$ is faithful (presumably using the fact that $f$ is both left and right cancellative). If that's true, then by hypothesis it's conservative, so since $f$ is an iso in this localization, it was already an iso in $C$.
Unfortunately I'm not sure how to show this off the top of my head.


Replace fabric.js resize and rotate controls with custom images?

Question: I'm looking for example on how to replace fabric.js resize and rotate rectangles with custom images.... has anyone done this?
Thanks.
Comment: This question is from 2012, if you've arrived here via google you may also want to check out this more recent answer: http://stackoverflow.com/a/24533063/29182
Comment: This is not very easy at the moment, except by changing source code or showing images on top of each control similar to this demo — http://fabricjs.com/interaction-with-objects-outside-canvas/
Answer: You can do it by overriding the prototype like this:
<code>var topLeftImage = new Image();
topLeftImage.src = 'images/tl.png';

var topRightImage = new Image();
topRightImage.src = 'images/tr.png';

var bottomRightImage = new Image();
bottomRightImage.src = 'images/br.png';

//Warning I modified some other things here as well, please copy this from the sources and modify it then
fabric.Object.prototype.drawCorners = function(ctx) {
  if (!this.hasControls) return;

  var size = this.cornersize,
      size2 = size / 2,
      strokeWidth2 = this.strokeWidth / 2,
      left = -(this.width / 2),
      top = -(this.height / 2),
      _left,
      _top,
      sizeX = size / this.scaleX,
      sizeY = size / this.scaleY,
      paddingX = this.padding / this.scaleX,
      paddingY = this.padding / this.scaleY,
      scaleOffsetY = size2 / this.scaleY,
      scaleOffsetX = size2 / this.scaleX,
      scaleOffsetSizeX = (size2 - size) / this.scaleX,
      scaleOffsetSizeY = (size2 - size) / this.scaleY,
      height = this.height,
      width = this.width;

  ctx.save();

  ctx.lineWidth = 1 / Math.max(this.scaleX, this.scaleY);

  ctx.globalAlpha = 1; //this.isMoving ? this.borderOpacityWhenMoving : 1;
  ctx.strokeStyle = ctx.fillStyle = '#333333';

  // top-left
  _left = left - scaleOffsetX - strokeWidth2 - paddingX;
  _top = top - scaleOffsetY - strokeWidth2 - paddingY;

  ctx.clearRect(_left, _top, sizeX, sizeY);
  ctx.drawImage(topLeftImage, _left, _top, sizeX, sizeY);

  // top-right
  _left = left + width - scaleOffsetX + strokeWidth2 + paddingX;
  _top = top - scaleOffsetY - strokeWidth2 - paddingY;

  ctx.clearRect(_left, _top, sizeX, sizeY);
  ctx.drawImage(topRightImage, _left, _top, sizeX, sizeY);

  // bottom-left
  _left = left - scaleOffsetX - strokeWidth2 - paddingX;
  _top = top + height + scaleOffsetSizeY + strokeWidth2 + paddingY;

  ctx.clearRect(_left, _top, sizeX, sizeY);
  ctx.strokeRect(_left, _top, sizeX, sizeY);

  // bottom-right
  _left = left + width + scaleOffsetSizeX + strokeWidth2 + paddingX;
  _top = top + height + scaleOffsetSizeY + strokeWidth2 + paddingY;

  ctx.clearRect(_left, _top, sizeX, sizeY);
  ctx.drawImage(bottomRightImage, _left, _top, sizeX, sizeY);

  ctx.restore();

  return this;
};
</code>
Comment: Hi @Alexander Kludt can you please explain your code more, where to add this code or to override it on in fabrics library..? please advise


Uma função que faça o contrário de uma adição mod 2³²

Question: def mod_2to32sub1(x):
    s = 0 # the sum

    while x > 0: # get the digits
        s += x & (2**32-1)
        x >>= 32

    if s > 2**32-1:
        return mod_2to32sub1(s)
    elif s == 2**32-1:
        return 0
    else:
        return s

Essa função acima faz o 'adition mod 2^32'.
Por que do código?
Bem, gostaria de pedir vossa ajuda para criar uma função que faça o contrário dessa função, mas tenho dificuldades. Me ajudem a entender como posso estar fazendo isso.
Pra exemplificar melhor, tenho o seguinte número, 554900798. Ele é '9144835390', antes de realizar a adição do modulo 2³². Bem, gostaria de transformar o '554900798' para '9144835390' novamente. Espero que tenha ficado claro.
O que posso estar fazendo?
Obrigado desde já.
Comment: Como ele faz a "adição" de a definição de adição prevê dois operandos e um resultado? Aí somente um operando está sendo passado
Comment: Um seria x e outro 0. A função é equivalente a '>>> 0' do Javascript. Só que eu queria entender se posso criar uma função inversa(<<<). Me pediram isso no curso
Answer: Módulo (restante de divisão) não é uma operação reversível.
Consideremos o caso mais simples com o operador %:
In [1]: 9144835390 % 2**32
Out[1]: 554900798

Aqui observamos que a operação é a mesma, baseado no seu exemplo.
Pra visualizarmos melhor a questão, imagine o seguinte exemplo: Queremos o restante da divisão de 7 por 3.
In [2]: 7 % 3
Out[2]: 1

O resultado é 1. Mas e o restante da divisão de 10 por 3?
In [3]: 10 % 3
Out[3]: 1

Também é 1. O mesmo acontece pra 13, 16, etc.
Quer dizer, existem infinitos números que resultam no mesmo restante pra qualquer dado divisor. Não é possível reverter a operação, porque informação é perdida no processo.
Se você quiser números que se encaixem nesse perfil, é possível encontrá-los:
def gerar_nums(resto, divisor):
    i = 1
    while True:
        yield i * divisor + resto
        i += 1

gerador = gerar_nums(1, 3)
for i, num in enumerate(gerador):
    print(num, end=', ')
    if i == 5:
        break

# 4, 7, 10, 13, 16, 19,

Comment: Entendi. Muito obrigado. Me ajudou muito.


Programmatically creating VS solution/project files

Question: I have a C project with a very nice rake build system in place. Unit test runners, mocks, as well as some boilerplate code, are generated.
The requirement is for the pc based stuff to be available in VS. I know the VS .sln and .proj formats are undocumented.
I also know that cmake can generate VS solution files as long as it's own files are up-to-date so my fallback solution is to create the cmake file structure/lists and use it to create the VS solutions.
Since my fallback reeks of duplication, I am looking for pointers to any other tools, templates or documentation that would allow me to create VS project and solution files.
Thanks for all the help
Answer: Actually, .vcproj file format is documented and you can find it on the MSDN website:
http://msdn.microsoft.com/en-us/library/2208a1f2(v=VS.100).aspx
And here is the Solution file documentation:
http://msdn.microsoft.com/en-us/library/bb165951(VS.80).aspx
I'm sure you can find more useful information on MSDN.


Orthonormal columns implies orthonormal rows

Question: I find it non-intuitive if I impose that all of a square matrix's columns are normalized and mutually orthogonal, then all its rows are also normalized and mutually orthogonal. Any intuitive explanation for this? Also if I relax the conditions to be only mutually orthogonal without being normalized, is this still true? And why so?
Comment: It appears unintuitive because it is unintuitive. The said property is a consequence of the fact that [$AB=I$ iff $BA=I$](https://math.stackexchange.com/questions/3852/if-ab-i-then-ba-i) for square matrices $A$ and $B$. It relies on the finiteness of the dimension of the vector space and has little to do with inner products or geometry. In an infinite-dimensional inner product space, it can happen that $A^\ast A=I$ but $AA^\ast\ne I$ (e.g. when $A$ is the right-shift operator in $\ell^2$ and $A^\ast$ is the left shift).
Comment: I'm doubling down on user1551's comment: It is critical that A have a finite size, and that A be square for the result to hold.
Comment: What? I think there is the word "rows" missing a few times.
Comment: Sorry I have corrected the typo.
Comment: @ArturoMagidin I already corrected the title so perhaps u can uncomment already?
Answer: I assume you mean orthonormal coulmn implies orthonormal rows. If so, than:
Let $Q$ be a square matrix with orthonormal columns. Therefore we know:
$$Q'Q=I \implies Q'=q^{-1}$$
$$(Q')'Q'=QQ'=I$$
Therefore, we have that the rows are also orthonormal.
Comment: Yes, when I write $Q'$ I mean transpose of matrix.
Comment: Yea the math looks neat but is there some intuition? Also if the columns are not normalized is it still true?
Comment: The derivation above is incorrect. $Q'Q=I$ which follows $(Q'Q)'=I'$ $=>Q'Q=I$ which does not prove the point raised in question. To say that $Q'Q=I$ implies $(Q')'Q'=I$ is strictly incorrect.
Answer: The derivation done by @eminem is mathematically incorrect. ′=  does not imply (′)′′=. Below is a solution that could answer the question
$Q^\top Q=I => (Q^\top Q)^{-1}=I^{-1} => Q^{-1}Q^{\top -1}=I => QQ^{-1}Q^{\top -1}=Q => QQ^{-1}Q^{\top -1}Q^\top =QQ^\top => I=QQ^\top$
This means that orthonormal rows/columns imply orthonormal columns/rows. Of course, here I assume that $Q$ is a full rank square matrix. This conclusion is not always true for rectangle matrices.
Comment: "mathematically incorrect" - I disagree. The logic in @eminem's proof is fine although it could have used a few words of explanation. $Q'Q = I$, therefore $Q'$ is a left inverse of $Q$. Since $Q$ is square, this implies that $Q'$ is the two-sided inverse of $Q$, and therefore $QQ' = I$.
Comment: @Bungo What you have written is absolutely correct. But (′)′′ written by eminem is misleading.
Comment: I agree that it could have been stated more clearly.
Answer: For a matrix $Q$ with normalized orthogonal columns, $Q^TQ=I,$ then $Q^T=Q^{-1}$ and $QQ^T=Q Q^{-1}=I.$ $Q$ also has normalized orthogonal rows.
$A=\begin{bmatrix}1&0&2\\
1&-1&-1\\
1&1&-1\end{bmatrix}$ clearly is a matrix with orthogonal columns, but without orthogonal rows.
Assume $A^TA=D,$ $D$ is an invertible diagonal matrix. Let $AP=B,$ $P$ is a diagonal matrix which normalized columns. So $B$ is an orthogonal matrix. Let's see how $AP$'s rows are also normalized, i.e. $AP=B=QA,$ how $Q$ looks like?
$$PDP=P^TA^TAP=B^TB=I\Rightarrow P^2=D^{-1}\quad (\text{normalization, of course})$$
$$QAA^TQ^T=BB^T=I \Rightarrow Q^TQ=(AA^T)^{-1}$$
So $Q$ may not be a diagonal matrix. Otherwise $AA^T$ is also diagonal for sure, which contradicts our counter-example. This means when we normalize our column spaces, row basis may change during the operation.
I don't know what we can get further. I remember that when I study linear algebra, I don't find strong connection between row spaces and column spaces, especially geometrical meaning. I hope someone has learned matrix theory can answer this question deeply.


Black boxes over HTML5 video tag, only in Safari 7 (OSX Mavericks)

Question: I have a gallery setup with multiple videos. These play perfectly on every browser I'm targeting (chrome/ie/firefox), except safari; but only on Safari 7/OSX Mavericks (other versions of safari are working fine): It displays black boxes over the videos, even when they are shown to be playing/loaded (a finished video will trigger its videoended() function, as intended, behind its black background).
The black boxes occur on the videos even when they are pulled outside the gallery, with nothing else affecting them. Sometimes not all videos get a black cover when refreshing; rarely none will.
This is a sample of one of the video tags:
<video id="video-1a" width="958px" onended="videoEnded()">
    <source src="/assets/video/product-1a.mp4" type="video/mp4" />
    <source src="/assets/video/product-1a.webm" type="video/webm" />
</video>

Comment: try to add "autoplay" option:  and/or even "controls" for your users.
Comment: Thanks for the suggestions. I attempted autoplay, as well enabling the preload option. Those still give the same issue. However, enabling controls did fix the black box issue entirely. Unfortunately; for this setup/client I cannot use controls; the videos have to play by link clicks, and automatically when a previous video finishes.
Answer: I ran into the same problem with Safari 7.x on Mac OS X 10.9.x "Mavericks — a black box would appear in Safari in place of an HTML5 video.
The previous comment of adding video controls does seem to address the problem, but has the potential downside of not being able to hide the controls in other browsers.
<video preload="auto" loop="loop" controls="controls">
    <source src="/path/to/video.mp4" type="video/mp4" />
    <source src="/path/to/video.webm" type="video/webm" />
    <source src="/path/to/video.ogv" type="video/ogg" />
</video>

We can use the Shadow DOM to hide the controls in browsers that support the property (Chrome 25+, Opera 15+), but have no choice in browsers that don't support it (Safari 3-7, IE 6-11).
video::-webkit-media-controls-panel {
    display: none !important;
}

You can style the native video controls to some extent by addressing the Shadow DOM, using browser vendor specific pseudo element selectors, but these controls differ between browsers.
There is some interesting discussion on CSS-Tricks about hiding native HTML5 video controls in full-screen mode, and cites OzPlayer as an example.
If full screen video is not what you're after or if having the controls visible is a deal-breaker, it would seem there isn't a solution (unless you do some browser detection — though browser sniffing is bad!).
Alas, it seems like this behavior may be a bug in Safari (7.0) on Mavericks (10.9) since it didn't exist on Mountain Lion (10.8).
Comment: Good job on the investigation. I reported this problem to Apple and referenced this question and answer.
Answer: Voted @rjb up on diagnosing the issue.
Another way to solve it is to use setTimeout and remove the controls after a short period (40 ms):
setTimeout(function(){
    $('#targetvid').removeAttr('controls');
}, 40);

I found that I could also not use controls and instead just alter the display property after 40 ms:
setTimeout(function(){
    $('#targetvid').css('display','block');
}, 40);

If you want to restore it to its original display property (ours was inline-block), you could do that after 80 ms:
setTimeout(function(){
    $('#targetvid').css('display','block');
}, 40);
setTimeout(function(){
    $('#targetvid').css('display','inline-block');
}, 80);

It's not a pretty JS hack but it works for this Safari bug.


libcurl.so.4 no version information available

Question: curl: /usr/local/lib/libcurl.so.4: no version information available (required by curl)
This is the error I am getting. This error has not stopped any scripts or apps from running or preforming their tasks, however I do get an email from the system also anytime curl is used.
I have cron jobs that run often. Some every few minutes, others longer and I get emails that will have that error line in it. I have googled the hell out of the string and variations of it. However, I am unable to find anything useful.
What I have done:
Deleted the file /usr/local/lib/libcurl.so.4, this makes the error go away and curl still works with no issues. After about 24-48 hours, the file will come back, pop back up in to the folder and I will have to re-delete it. I know this is not the right thing to do, but I am not sure what else to do.

Contents of /usr/local/lib/
libcurl.a
libgcrypt.la
libgpg-error.la
libruby-static.a
python2.7/
weechat/
libcurl.la
libgcrypt.so
libgpg-error.so
node_modules/
python3.4/
libcurl.so
libgcrypt.so.20
libgpg-error.so.0
pkgconfig/
ruby/
libcurl.so.4.3.0
libgcrypt.so.20.0.3
libgpg-error.so.0.15.0
postsrsd/
site_ruby/

Installed Packages:
$ apt --installed list | grep 'curl'
curl/trusty-updates,trusty-security,now 7.35.0-1ubuntu2.5 amd64 [installed]
libcurl3/trusty-updates,trusty-security,now 7.35.0-1ubuntu2.5 amd64 [installed]
libcurl3-gnutls/trusty-updates,trusty-security,now 7.35.0-1ubuntu2.5 amd64 [installed]
libcurl4-openssl-dev/trusty-updates,trusty-security,now 7.35.0-1ubuntu2.5 amd64 [installed]
php5-curl/trusty-updates,trusty-security,now 5.5.9+dfsg-1ubuntu4.9 amd64 [installed]
python-pycurl/trusty,now 7.19.3-0ubuntu3 amd64 [installed,automatic]
python3-pycurl/trusty,now 7.19.3-0ubuntu3 amd64 [installed]

$ lsb_release -a
Distributor ID: Ubuntu
Description:    Ubuntu 14.04.2 LTS
Release:        14.04
Codename:       trusty

Anything to point me in the right direction would be much appreciated.
Edit #1 (more info)
The link is aways made at 8:00:01am just after the daily cron job runs.
celestia@Canterlot:/usr/local/lib# ls -hal
drwxr-xr-x 10 celestia root  4.0K Jun 11 07:58 .
drwxr-xr-x 11 celestia root  4.0K Jun 23  2014 ..
-rw-r--r--  1 celestia root  805K May  2 00:16 libcurl.a
-rwxr-xr-x  1 celestia root   953 May  2 00:16 libcurl.la
lrwxrwxrwx  1 celestia root    16 May  2 00:16 libcurl.so -> libcurl.so.4.3.0
lrwxrwxrwx  1 celestia root    16 Jun 11 07:58 libcurl.so.4 -> libcurl.so.4.3.0
-rwxr-xr-x  1 celestia root  424K May  2 00:16 libcurl.so.4.3.0
-rwxr-xr-x  1 celestia root   987 May  2 00:20 libgcrypt.la
lrwxrwxrwx  1 celestia root    19 May  2 00:20 libgcrypt.so -> libgcrypt.so.20.0.3
lrwxrwxrwx  1 celestia root    19 May  2 00:20 libgcrypt.so.20 -> libgcrypt.so.20.0.3
-rwxr-xr-x  1 celestia root  3.5M May  2 00:20 libgcrypt.so.20.0.3
-rwxr-xr-x  1 celestia root   956 May  2 00:13 libgpg-error.la
lrwxrwxrwx  1 celestia root    22 May  2 00:13 libgpg-error.so -> libgpg-error.so.0.15.0
lrwxrwxrwx  1 celestia root    22 May  2 00:13 libgpg-error.so.0 -> libgpg-error.so.0.15.0
-rwxr-xr-x  1 celestia root  336K May  2 00:13 libgpg-error.so.0.15.0
celestia@Canterlot:/usr/local/lib# stat libcurl.so.4
  File: 'libcurl.so.4' -> 'libcurl.so.4.3.0'
  Size: 16              Blocks: 0          IO Block: 4096   symbolic link
Device: fc00h/64512d    Inode: 30939991    Links: 1
Access: (0777/lrwxrwxrwx)  Uid: (    0/celestia)   Gid: (    0/    root)
Access: 2015-06-11 08:00:01.983201467 -0400
Modify: 2015-06-11 07:58:17.551455525 -0400
Change: 2015-06-11 07:58:17.551455525 -0400
 Birth: -

celestia@Canterlot:/usr/local/lib# apt-file search libcurl.so.4
libcurl3: /usr/lib/x86_64-linux-gnu/libcurl.so.4
libcurl3: /usr/lib/x86_64-linux-gnu/libcurl.so.4.3.0

celestia@Canterlot:/usr/local/lib# ldd libcurl.so.4
linux-vdso.so.1 =>  (0x00007fff1cdfe000)
libssl.so.1.0.0 => /lib/x86_64-linux-gnu/libssl.so.1.0.0 (0x00007fb2e75f1000)
libcrypto.so.1.0.0 => /lib/x86_64-linux-gnu/libcrypto.so.1.0.0 (0x00007fb2e7216000)
libz.so.1 => /lib/x86_64-linux-gnu/libz.so.1 (0x00007fb2e6ffc000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fb2e6c37000)
libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007fb2e6a33000)
/lib64/ld-linux-x86-64.so.2 (0x00007fb2e7ad2000)

Comment: Your system is probably compromised.
Comment: Files don't just appear, except on compromised systems. Try running `checkrootkit`.
Comment: That could be, though I have looked into that and have not seen anything running that I have not put in place or anything else weird. I know this is a possibility, but I would think it is more likely to be another app, or curl, or something that would cause this. If I could find what is making the file, it would be start, but I am not able to. I do know the file is remade most mornings at 8am when the cron.daily is run.
Comment: @Wouter Verhelst Ran, nothing found/not infected
Comment: Do you cron automatic security updates? Do you have any custom packages either from a third party repository, or one you compiled yourself? Have you installed any software from source?
Comment: I have the same problem as @Dasoren ... and in my case its a standalone box (not in any network) so I am sure its not compromised. So any fresh ideas?
Comment: @xkcd I found my issue, though I forgot to reply to this with my answer.
Comment: check and past this command output $ldd curl
Answer: The issue turned out to be I had 2 installs of curl on the system. An apt-get install curl and a curl build from source. I ended up removing the curl built from source and everything works fine now. I also tried later removing the apt-get one and rebuilding curl from source again and all was good. But when I reinstalled the curl from apt-get with the source one still installed, the same issue started again. So I removed the apt-get one again.
In short do not have curl on the system twice, issues happen then.
Sorry if this is not well written, I just got up.
Comment: How did you remove one?
Answer: I also had such problem in installing CMAKE, I type cmake, the output is:
cmake: /usr/local/lib/libcurl.so.4: no version information available     (required by cmake)
Segmentation fault (core dumped)`

Something like yours.I fixed it like this:
sudo ln -fs /usr/lib/libcurl.so.4 /usr/local/lib/

Then, I type cmake -version, and the result is
cmake version 3.2.2

CMake suite maintained and supported by Kitware (kitware.com/cmake).

Answer: before that check this  $ldd curl for any missing linked libraries if found missing then add this line "/usr/local/lib" in /etc/ld.so.conf and run $sudo ldconfig -v the check $ldconfig -p then curl must be able to use missing lib from this directory


Are high schools dumbing down their exams? I don't know. How can we find out?

Question: I have a large-ish longitudinal dataset of high school and college course registration and grades. I want to test the assertion that high schools are "dumbing down" their courses to meet graduation quotas, resulting in "poorly prepared" college students.
The dataset includes course info and numerical grade (%) for every student registration in high school and college.

What could we observe in the data that would increase / decrease the probability of the assertion being true? What methodology could allow us to observe that?
What if the college professors are also dumbing down their own exams as a result of the students being unprepared for higher education? Could we still detect a possible inflation of high school grades then?
Comment: You have to address confounding with different teachers (among other things).  Depending on the particulars of your dataset, if you did find some difference in grades over time, how would you know if this is the result of some potential "dumbing down" versus a different set of teachers with different teaching philosophy?  Are you controlling for teacher in some meaningful way?  In addition, how can you rule out improvements or degradation in curriculum as implemented by state or national standards?
Comment: You could try to correlate high school success to college success as a trend over time. The concern that colleges also vary in both selectiveness and difficulty over time is well founded. You could never overcome such a bias without having a standardized (age invariant) aptitude test that could be administered to people of varying educational cohorts.
Answer: The data you have is enough to examine how high-school and college grades vary over time, but not to distinguish changes in student ability from changes in test difficulty. To do that, you'd need some other measure of student ability or test difficulty. You may be interested in reading studies of the Flynn effect, which is the finding that humans in general have gotten smarter over the last century or so.
Comment: More precisely, the Flynn effect is the secular increase of test *scores*. There is much discussion in the psychometric literature whether this also means that people actually have gotten *smarter*. Many argue they have not (e.g by arguing that the increase is not on *g*).


How to schedule an event in Mysql on table update?

Question: I want to initiate an action after 7 days from the day a specific field in my database table is updated.
I can use trigger to trigger an event on update of field in the database table. But how can I make it wait for 7 days. I was looking for scheduling an Event but that can only be scheduled for specific  time. Is there any way to dynamically set the schedule time?
Answer: There are 2 ways to do it:

You store in a timestamp field when the record was last updated. You schedule a regular event to be run every couple of hours. The event's code scans the table in question and does whatever needs to be done for those records those timestamp is between the lust run of the even and the current time.

If you have lots of records you need to handle such events, then this is the recommended approach. The drawback is that timing of the event may not be fully accurate, depending on how often you schedule this event to run.

Every time you update the record you create an event specifically for that record in a trigger or stored procedure that triggers in 7 days time.

This approach gives you absolute accuracy over when an event is triggered, however, if you have a large number of changes, then this solution does not scale well.
An alternative solution could be to record the time when the change was done, but instead of event triggering base your code on user interaction. So, if the user, whose data has been updated logs on then you notify him about what you want regarding those updates that were done more than 7 days ago and the events were not seen by the user.


What does $U_i$ mean in $U_iA_i \in \mathcal{F}$

Question: I am a fourth-year math student, so I understand that $\cup$ means union of sets. However, I got stuck reading Probability: Theory and Examples by Durrett. Considering that I don't know what $\cup_i$ means, can someone please recommend me what field to read about to understand this textbook?
Comment: $i$ is an index variable for the sets $A_i$.   For example, if $i\in\{1,2,3,4,5\}$ then $\cup_i A_i=A_1\cup A_2\cup A_3\cup A_4\cup A_5$.  Similarly $\Sigma_i x_i=x_1+x_2+x_3+x_4+x_5$
Comment: Set theory (DeMorgan's law)
Comment: Yes, it means union of all sets $A_i$.  It should be made clear in the context whether $i$ ranges over a finite set or an infinite set
Comment: Oh... so $\cup_iA_i$ means union of all sets $A_i$? In other words, $\cup_iA_i = A_1 \cup A_2 \cup ... \cup A_n$?
Comment: Thanks! I also see in the book this: $\cap_iA_i = (\cup_i A^c_i)^c$. What field/textbook of Mathematics can I see the proof?
Answer: $\cup_i A_i$ indicates the union of all sets $A_i$.  $i$ is an index variable for the sets $A_i$.  It should be made clear in the context whether $i$ ranges over a finite set or an infinite set.  For example, if $i\in\{1,2,\dots n\}$, then $\cup_i A_i=A_1\cup A_2 \cup\dots\cup A_n$.  You could read about this and more in a textbook of elementary set theory.


Is conditioning always increase the probability of some event

Question: Is conditioning always increase the probability of some event ?
My answer is, since by conditioning we are reducing the sample space probability must increase.
Am I correct??? If not please explain me
Answer: Of course not, for example $P(A|A')$ is $0$; because given that $A$ did not happen, it'll be impossible for $A$ to happen.


How to find the characteristic number of a given integral equation?

Question: How to find the characteristic number of the following integral equation?
$$y(x)= \lambda \int_{0}^{1} (3x-2)ty(t)dt$$
Comment: It has NO characteristic number
Answer: $y(x)=\lambda (3x-2)C$ where , $\displaystyle C=\int_0^1ty(t)\,dt$. Then , $$C=\int_0^1t\lambda  C(3t-2)\,dt=\lambda C(1-1)=0.$$Then , $y=0$ is the only trivial solution and so the equation has NO characteristic number.
Comment: yes... thank u @S.panja. and Jesse P Francis.
Comment: **Why** is $y(x)$ a constant multiple of $(3x-2)$?
Comment: @ Mariano Suárez-Alvarez) Because the integration is on $[0,1]$.
Comment: Thank you @ S.Panja. if C is non zero then how to find the characteristic number. If you have any ref. bk or meterial related to this question pls give me....
Comment: @DeepaRavi, I guess searching for solution to Fredholm integral equations with separable kernal will give you some idea about it. (I'm no expert in it; even I learned it last day digging in those lines). Also, I found [this](http://gauravtiwari.org/portfolio/elements-of-integral-equations/) PDF quite useful in getting a basic idea about IEs.
Comment: What is actually meant by the characteristic number of an integral equation?
Comment: Also, for it to have a non-zero characteristic number, how can we tweak the given statement?


Possible to install a 3rd party RPM locally? So as not to interfere with the system RPM?

Question: This is a CentOS 5 system, x64, using yum/rpm for package management. The libxml2 is a bit dated, and the Perl XML library I'd like to install (from CPAN) requires a more up-to-date version of the C libxml2 library.
Now I could download the source and build and install into /usr/local.
But they also provide RPMs at ftp://xmlsoft.org/libxml2/. Is it possible to install the RPM in such a way as not to interfere with the system-provided RPM, which I don't want to change or upgrade?
I tried the following:
package-cleanup --problems libxml2-2.7.8-1.x86_64.rpm

But the output appears to indicate that it will replace the system RPM, which is not what I want.
Marking libxml2-2.7.8-1.x86_64.rpm as an update to libxml2-2.6.26-2.1.12.el5_7.2.i386

In addition, when continuing, the command fails with errors.
--> Finished Dependency Resolution
eel2-2.16.1-1.el5.i386 from installed has depsolving problems
  --> Missing Dependency: libxml2.so.2 is needed by package eel2-2.16.1-1.el5.i386 (installed)
libxml2-python-2.6.26-2.1.12.el5_7.2.x86_64 from installed has depsolving problems
  --> Missing Dependency: libxml2 = 2.6.26 is needed by package libxml2-python-2.6.26-2.1.12.el5_7.2.x86_64 (installed)
...

So back to compiling from source? Or is there a way to use the RPM?
Update
What I'm interested here is side-by-side installation of an RPM into something like /opt or /usr/local or whatever is your --prefix du jour. The RPM should just check that its dependencies are met by the system, but it should under no circumstances attempt to replace or amend anything at all in the system.
Answer: You can get the srpm or the sources.  Most packages will allow you to build them to install to a target under your /home (./configure --prefix=/home/foo).  Never built a RPM to do this, but it should also be possible.  However, you may need to frig the dependency metadata in the rpm and the name so it doesn't fool RPM's internal database into thinking you've replaced the actual package.
Comment: Thanks, Tunbridge. I remember having had to change trains there on the way from London to East Grinstead. Or maybe it was where they came to pick me up. Anyway, it sounds like an RPM cannot be installed out-of-the-box into your `--prefix` of choice? Because if it cannot, compiling from source is likely easier as then you don't have to deal with the RPM mechanics.
Comment: More likely where they picked you up from.  Although they're quite close the train route from Tunbridge Wells to East Grinstead is kind of convoluted - across to Edenbridge, walk to Edenbridge Town station then to Hurst Green and back out to East Grinstead.
Comment: Well, it was 20 years ago, or even more. Went to see London, and my aunt lives in East Grinstead with her family. I'm from Hamburg. So plus one for Tunbridge and let's call it a day with the boring RPMs. :)
Answer: It depends how you want manage your system in future.
You can go on with source compilation but this approach produces a lot of garbage in the system makes in hardly manageable after some time.
If you try to install the RPM, you run into so called "dependency hell". In your case, there two packages that are dependent on old libxml2 library:
libxml2-python
eel2
There 2 ways to proceed in this situation:

Install newer libxml2 package with --nodeps option:

rpm -Uvh libxml2-2.7.8-1.x86_64.rpm --nodeps
However, note that the dependent software may be incompatible with this new version.

Download new SRC-RPMS for libxml2-python and eel2 and rebuild them against newer version of libxml2. However, I'm not able guarantee that the compilation will succeed.
Comment: Roman, thanks. There are dozen or two packages depending on the old system-provided libxml2 (attempted to indicate this by ...). That must all stay as it is, I don't want to meddle with it, I have the distinct feeling that things will go awry if I do. I'd like to know if there's a way to install an RPM like you'd install a built in `/usr/local` or `/opt` or `/what/ever` using `--prefix` as with `autoconf`?


Calculate change in radius for some change in electrostatic potential energy.

Question:
A sphere of radius $R$ has a charge $Q$ distributed uniformly over its surface. How large will a sphere that contains $90\ \%$ of energy stored in electrostatic field of this charge distribution.

Since, $$U = {1\over 8\pi}\int_{\text{Entire} \\ \text{Field}} \vec E\cdot \vec E\ \  dv$$
I assume that a sphere with charge only surface would behave like a spherical shell with charge, then $E = 4\pi \sigma$, where $\sigma$ is the surface charge density.
From the integral I got,
$$8\pi\Delta U = \vec E\cdot \vec E \times \Delta v$$
For which I get, $-8\pi(0.1)U = 16\pi^2\sigma^2 \Delta v$.
Everything seems fine here except that I don't the value of $U$. I can't solve two unknown in one equation.
I also tried just to use $\displaystyle U = {Q^2 \over R}$.
$$\begin{align} \Delta U &= -(0.1)U_i \\{Q^2 \over R^\prime} - {Q^2 \over R} &= -(0.1){Q^2 \over R} \\ \frac{10}9 R &= R^\prime \end{align}$$.
The given answer is $10R$.
I think I am missing something very silly. Any hints are welcomed.
Comment: Can you clarify the initial question a bit more? I'm assuming we're trying to solve for a sphere radius, but what the parameters are to figure that out are fuzzy to me: "contains $90\%$ of energy". I don't know what that means. Are we envisioning another sphere of charge placed somewhere around this first sphere and considering the potential energy between them?
Comment: @WB-man There is a shell kept somewhere. It has some electric potential energy associated to it. Now we need to find some other shell which has same amount charge distributed over it but has 90% the energy that original sphere has. There is no interaction between those two shells.
Answer: I was too with this puzzling problem. We've been assuming that there are two spherical distributions of charge to compare, but no, there is only one and not comparing anything. In a classical language it can be explained so: Consider all imaginary spheres surrounding the material one. By other side, we can think of the field as carrying some amount of energy at every point where it is not zero. With this idea, every region of the space contains some amount of energy and the entire space the total energy of the field. So, each of those spheres contains some amount of the total energy. We want to find the sphere that contains a 90% of the total energy.
First, for a some region, $U =\displaystyle\dfrac{1}{8\pi}\int_{\text{Region}} \vec E\cdot \vec E\ \  dv$.
For the distribution, being $R_0$ the radius of the spheric distribution, $E=\vert\vec E\vert=\dfrac{Q}{r^2}$ and $E=0$ in the sphere's interior.
$\displaystyle U_{R_0}=U_{total}=\dfrac{1}{8\pi}\int_{R_0}^{+\infty}\int_\Omega\vert\vec E\vert^2r^2d\Omega dr=\dfrac{Q^2}{2}\int_{R_0}^{+\infty}\dfrac{dr}{r^2}=$
$\displaystyle U_{R_0}=\dfrac{Q^2}{2}\dfrac{1}{R_0}$
Now, we calculate the energy for the region out of the sphere of radius $R_1$
$U_{R_1}=\dfrac{Q^2}{2}\dfrac{1}{R_1}$
At last,
$U_{R_0}-U_{R_1}=90\%U_{R_0}\implies \dfrac{1}{R_0}-\dfrac{1}{R_1}=\dfrac{90\%}{R_0}\implies R_1=10R_0$
Comment: $$\dfrac{1}{8\pi}\int_{R_0}^{+\infty}\int_\Omega\vert E\vert^2r^2d\Omega dr$$

What is omega here ? I am not similiar with this notation. Is it surface charge density ?
Comment: It's the solid angle $d\Omega=\sin\theta d\theta d\phi$, $\int_\Omega d\Omega=4\pi$
Comment: You converted it to spherical coordinates ?
Comment: Yes. The angular part is a constant and we can check the radius directly.
Comment: $$\dfrac{1}{8\pi}\int_{R_0}^{+\infty}\color{red}{\int_\Omega\vert E\vert^2r^2d\Omega }dr$$

One last thing. As I understood, the first integral (red one) calculates the energy over the surface and the second integral calculates the energy over the whole space ?
Comment: No, $r^2d\Omega dr=dv$ is the infinitesimal volume element in spherical coordinates. If you need it I can write the whole thing, but anyway, as the problem doesn't depend on $\theta,\phi$, the integral is always $4\pi$ for the spheres we are considering.
Comment: Thank you, I understand now.
Comment: You are welcome :)


Why is the boundary of a set in the closure of the set?

Question: The definition of the closure of a set $S$ is the intersection of all the closed subsets of the topological space $X$ which contain $S$ as a subset.
The definition of boundary of $S$ is $\text{Comp}\{\text{Int}(S) \cup \text{Ext}(S)\}$.
Since the boundary of $S$ does not contain $\text{Int}(S)$ as a subset, it is not a closed set that contains $S$, so the boundary of $S$ is not in the closure of $S$, but apparently it is. Why is this?
Comment: What is $\operatorname{Comp}$?
Comment: $\text{Comp}(S)$ is the complement of the set $S$
Answer: The argument in the last paragraph of the post is wrong. If it were true, you would be able to apply it and prove that no point lies in the closure.
Now let $p\in\partial S$. Then $p\not\in\mathrm{Ext} S$, and so any open neighborhood of $p$ intersects $S$. It follows that $p$ lies in any closed set which contains $S$, i.e. $p$ is in the closure.
Comment: How do you know that any open neighborhood of $p$ intersects $S$?
Comment: @ᴇʏᴇs otherwise, by definition we have $p\in\mathrm{Ext}S$.
Comment: Sorry, which definition are you using? Our definition of $\text{Ext}S$ is $\text{Int}(\text{Comp}S)$, and our definition of neighborhood of $p$ is a subset of the topological space that contains an open set such that $p$ is contained in the open set
Comment: @ᴇʏᴇs ... and the definition of *open* neighbourhood of $p$ should be: an open set containing $p$.