Como transformar propriedades de um link em uma classe ou id específico?

Question: Como consigo transformar as propriedades do link em uma class ou id?
a:link
a:visited
a:hover
a:active

consigo transforma-las em uma class e usar individualmente em algum elemento?
Answer: Não precisa transformar nada, basta colocar o id ou classe no lugar da tag.
Exemplo
#cancel:hover      /* não precisa por a tag "a" */
.external:visited  /* e aqui, qualquer elemento com classe "external" que
                      tenha o estado "visited" será afetado               */

Veja no snippet:

a {color:blue}         /* Vale para todos os links */
a:hover {color:green}  /* Vale para todos os links */
#b:hover {color:red}   /* Vale somente para o #b   */
Hover genérico

Hover diferente

Hover genérico

Comment: CSS é cumulativo. Se fizer numa linha #b {color:red} e na outra #b {font-size:76px} ambas as características funcionarão (leia o [link](https://pt.stackoverflow.com/a/143893/70) que passei no segundo comentário para saber a ordem de aplicação) - Ainda, #b:active e #b:hover são definições diferentes, aumentando a especificidade (conforme link já mencionado). A sugestão é você fazer experiências diversas, não se limite a tentar as coisas só quando precisar usar de fato.
Comment: Certo, entendi, a minha dúvida surgiu diante que por exemplo, eu estar criando um menu e aplicando as propriedades do "a", ele aplica de uma forma geral, e na mesma página eu tenha um botão de "whatsapp" (img+link) fixo no canto inferior da tela, ele fica com essas propriedades aplicada também,  essa é minha dúvida na aplicação "individual"
Comment: é o mesmo caso do ítem com id #b, quando especifiquei individual no CSS, ele "passou por cima" do genérico por especificidade. [Mais detalhes neste link](https://pt.stackoverflow.com/a/143893/70)
Comment: Então como fica a estrutura do #b para aplicar diferentes cores para hover e visited por exemplo?
Comment: Mesma coisa, faz um `#b:visited` tambem (e um `#b:active`, etc).
Comment: Ah, não sabia que poderia ter mais de uma id com o mesmo nome xD, obrigado!


Securely executing system commands as sudo from PHP

Question: Is it possible?
I have written a command line tool in PHP for creating new environments for our company. It creates system users, directories, databases, VHosts and restarts apache, amongst other things. These commands require sudo privileges. I thought it might be a nice idea to have a web-interface for it, to make it easier for other non-developers to use. The web app would be behind authentication.
When running from the command line I just run sudo tool.php, obviously I can't do this from a web app.
How could I do this securely? Giving the apache user sudo access seems silly, as this would means all sites hosted on the box (eg all our environments) would have sudo access. Is it possible to make this tool run under a different user? this user could have sudo privileges for only the commands I need?
How do things like plesk and cPanel do this?
Any thoughts?
Comment: What does `tool.php` do?  Are you able to edit the sudoers command list on the server that `tool.php` is hosted on?
Comment: creates system users, databases, vhosts, restarts apache, etc. Yeah I have full control of the server, I just want to write something that is safe.
Comment: While I've added an answer that should get you sorted, I'd also make sure that my `tool.php` functions atomically -- if there are 5 steps and step 3/5 fails, have operations that return the server to the original state.
Comment: Thanks - Sure, the tool logs and rolls back any unsuccessful actions.
Comment: Awesome, logging details to a remote location is a great idea.  While I'm going to leave my answer as is, keep in mind that configuration management software such as Ansible, Chef, or Puppet have web interfaces and choosing an existing solution may save you a lot of work.
Answer: While this approach lends itself to generating bad feelings, if this is a necessary evil, I'd begin by making sure that the server is segmented from the network -- either accessible only by a few hosts in a LAN or listening only to hosts that have authenticated against a VPN (or SSH tunnel).  In short, try not to let this host be low-hanging fruit.
It is possible to have a user with limited sudo-access and I would recommend doing so.
To begin, create a sudoers user that can only run tool.php and can be switched to via your www-data user (or whatever your webserving user happens to be named).  This will limit the scope of the sudo actions that can be taken on the server (however, if your tool.php is exploitable, this does not help).
You can do this by editing sudoers to contain a line like:
online_tool_user ALL=(www-data) NOPASSWD: /var/danger/tool.php
This will allow "online_tool_user" to run the command /var/danger/tool.php without entering a password. If this user tries to run any other commands (iptables, adduser, et al), it will be denied.
To make exploiting this user less fun for an attacker, look into using restricted shells or "jails."
Finally, if you're just calling exec via PHP, throw the user into the call, e.g.: exec("sudo -u online_tool_user -c 'php /var/danger/tool.php'").
Comment: Nice, thank you, this is all good information. The tool is purely for ease of use, the server is a dev server (not found on our internal network), and is used only by us internally, occasionally by clients to check out specific sites, but these are all behind `htpasswd` auth (I know this isn't particularly strong protection).
Comment: Although, thinking about it, not sure this will actually work. It's my fault trying to simplify the explanation. The tool is not just one script. It is a collection of classes and components, which would just be used in the web-app. So the web app doesn't just call the tool o the command line, it performs the actions itself.
Comment: I assume you mean that you're calling actions from PHP that require escalated privileges.  I'd have to see some of your code to offer specific suggestions.
Comment: Sure - I'll post some in the morning
Answer: One approach is to separate the web interface from the execution layer, i.e. use the web interface as the UI and to schedule actions. Then run a second job with root privileges that polls the queue, validates and executes scheduled tasks and which reports exit status back.
A slight modification to that is where instead of having the poller run independently  your web application can run that poller on-demand with sudo.
Another, less secure, approach is to run a second apache instance for your secure app that runs as root instead of apache. Last time I checked (a long long time ago) that was the approach web control panels used.
Comment: Thanks, I thought about the polling method, like using a cron to pick up the commands. This would definitely work but I like the idea of immediate feedback. I'll also check out the other approach!
Comment: Creating and modifying virtual hosts requires an Apache reload/restart which is not something you want to see happening 30 times in 5 minutes on a shared production server... And a new virtual host often requires a DNS modification as well also taking time to propagate  so letting your users wait until your system emails a task completed message may be a good idea.
Comment: It's a dev server, so none of that should happen. It will probably only be run a couple of times a week, so no massive overhead :)
Answer: What about using setuid so that the process can be run as root?
 chmod 4555 tool.php
 chown root tool.php

I think that should do it correctly.
Comment: This does not address the asker's security questions and suggests that he has to interpret web-based commands as root.
Comment: @tristan setuid is specifically designed for situations like his and it does not require you to execute the command as root. in fact, it's made so you don't run as root. however, setuid only works on shebang executables in a few *nix systems so it may or may not work for him
Comment: setuid will let you execute the command as root, but it doesn't really address his question.  It's like being asked how to make a cake and responding "baking powder can be used to make a dough more fluffy."  While a helpful tidbit, it doesn't stand on its own as an answer to the question.


How do I restore my MySQL so it can work again?

Question: Ok so this starts the other day. I tried creating an index on a large table (7million rows) and it hung. Well it went into "Repair by keycache"... which I found out wasn't so great.
Well the process got interrupted. The ALTER failed and no index was made. On further attempts to do it something happened (I don't know what or how I caused it), but the entire table became corrupted and went into "Incorrect key file for table"
So I started repairs (nothing worked) - was taking hours and bailing. So I tried restoring from a backup... this didn't go too well.
So I tried restoring from another server's .MYI and .MYD files. This didn't work either.
So I ditched the table and recreated it empty (the data wasn't an issue). All systems go, everything's running smooth. But every time I try to do an insert on the recreated table MySQL crashes. Then the next query (usually my attempt to see what's going on at the shell with SHOW PROCESSLIST\G;) boots every connection from the server and I get errors like these:
*************************** 1. row ***************************
     Id: 11
   User: debian-sys-maint
   Host: localhost
     db: NULL
Command: Query
   Time: 1
  State: Repair by sorting
   Info: products

*************************** 3. row ***************************
     Id: 71
   User: debian-sys-maint
   Host: localhost
     db: NULL
Command: Query
   Time: 0
  State: System lock
   Info: select count(*) into @discard from `creloaded`.`products_options_values_to_products_options`

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (111)
ERROR:
Can't connect to the server

And so the entire server becomes unusable... until I stop the server and delete the products table files.
So I tried recreating the entire schema containing this offending table. Gave it a different name. The table name is still the same though: products
Same problem as above as soon as I try to insert any data into it. So I'm guessing something a little more drastic is happening or there's a deeper reference to this table and/or it's indexes somewhere that MySQL feels a desperate need to repair!
Can anyone shed any light on this and perhaps some assistance?
I'm running Ubuntu Server 10.04 and MySQL 5.1.41 running on a 32-bit machine with 2GB RAM
Comment: Just to let you know, the debian-sys-maint process (PID:11 above) has been "Repair by sorting" `products` for nearly 17 hours now - bearing in mind there's nothing in this table...
Comment: Now it says it's been running for almost 2 straight days... so something interrupted it along the line and it started again
Answer: I managed to rectify the problem... although I don't really know what the cause of it is so it may happen again of course.
So basically I stopped MySQL and did a myisamchk on the products table (in it's new schema) by:

sudo su -ing
cd /var/lib/mysql/{scema_name}/
myisamchk -o -f products

I had tried this before, but it was going to take days with a full table. But because the table now had no records in it, it was done in a few seconds and this seemed to clear whatever flag MySQL sets for crashed tables.
So it has now stopped trying to repair it every time the server boots up and I have successfully written nearly 5 million rows back to the table without a hitch.
The Lesson?
Back up your table data, empty the table, do a myisamchk -o on the empty table and then re-INSERT your data
Interestingly I tried to do a myisamchk -r but I kept getting a Segmentation Fault.
Comment: just a note to anyone googling this, I got a Segmentation Fault as well when running myisamchk because I had ran out of hard drive space for the temp files. I resized my instance, tried again and it worked.


Inserting triple quotes inside of triple quotes in cson file

Question: I'm trying to write a some python snippets for the Atom text editor and I would like to have triple quotes inside of a multi-line body but for some reason Atom does not like that. I've tried <code>\\</code> to escape (as mentioned here near the page) but that does work either. I've left comments in the example below where I'd like to put triple quotes;
<code>'.source.python':
  'Main Class':
    'prefix': 'mainclass'
    'body':"""
    class ${1:NewClass}(object):
        '$2' # I'd like triple quotes here.
        def __init__(self, *args, **kwargs):
            '$3' # Here as well.
            ${4:pass}
    """
</code>
Is this even possible in cson?
Answer: This works but it doesn't totally solve the problem. So feel free to add another more correct answer.
<code>'.source.python':
  'Main Class':
    'prefix': 'mainclass'
    'body':'''
    class ${1:NewClass}(object):
        """$2"""
        def __init__(self, *args, **kwargs):
            """$3"""
            ${4:pass}
    '''
</code>
Comment: What about this is not "totally" solving the problem?
Comment: In the extremely unlikely scenario where someone would need to use triple single quotes and triple double quotes in the body element.


Allow tables in content with CK-Editor

Question: I have problems to configure my dupal 7 installation to allow entering tables.
I will add the link to the page I mean because not everytime sure that I use the right words.
I have created a type (admin/structure/types) which has four fields (admin/structure/types/manage/my-type-name/fields). The field body (admin/structure/types/manage/my-type-name/fields/body) has set filtered text as text processing. The selectbox under the CK-Editor has the value Filtered HTML. I tried to set its value to a custom clone of Filtered HTML which allows the attentional tags table, td, th and thead.
How can I allow tables for a special kind of type?
Answer: You can use Full Html to allow tr th and table but If you need to use Filtered HTMl for security reason you can use wysiwyg_filter Module that allow you to add some html tags to filtered html
about select box under ck-editor it's a permission problem that only filtered html appear
Answer: Related issue at CKEditor table td style not showing in frontend.
Check your ckeditor settings at /admin/config/content/ckeditor, had to disable "advanced content filter" (or well, reconfigure the editor), which was strapping all html tags not present in the editor features.
Comment: Thank you for your reply, but after now more then 6 years this has no relevance for me. I even forgot that I have an account on this site ;-)

Allow tables in content with CK-Editor


Change Chrome homepage for multiple PC's

Question: In our business we have about 300 PC's. What I want to achieve is to change the homepage on all browsers (IE, Chrome and Firefox). The problem is that I can't find any way to set/change the homepage on Chrome for all computers at once.
IE can be configured through GPO and in Firefox I run a batch file that does that. How can I do this on Chrome without changing it manually on each PC?
Answer: See Google's Help document Set Chrome policies for devices.  They provide Group Policy templates you can add on your Domain controller, so you can configure policies to set things like the home page.
I haven't found a updated document to confirm the current state, but in the past you needed to have the Chrome for Business and Education installed.
Answer: Here you have a place where Chrome configuration is stored:  http://www.chromium.org/user-experience/user-data-directory
There you have file named Preferences - it's a JSON file - you can find there some properties for homepage and for example parameter which is responsible for loading homepage on startup:
<code>"startup_urls": [ "http://google.pl/" ]
</code>


Box and diamond proprierties in Propositional Dynamic Logic

Question: I read that, while ⟨a⟩B implies that the program "a" will eventually come to an end, [a]B does not imply the same thing. Would anyone care to explain why?
Answer: See the Stanford Encyclopedia:

[$\dots$] If $\alpha$ is a program and $A$ is a formula then $[\alpha]A$ ("every execution of $\alpha$ from the present state leads to a state where $A$ is true") is a formula.
[$\dots$]  In addition, we abbreviate $\neg [\alpha]\neg A$ to $\langle \alpha \rangle A$ ("some execution of $\alpha$ from the present state leads to a state where $A$ is true") as in modal logic.

With this in mind, $\langle a \rangle B$ means that there does exist an execution of $a$, and that execution will lead to $B$ being true.
However, $[a]B$ simply means that if there is an execution of $a$, then $B$ will be true, but we do not know whether such an execution exists or not.
Comment: Thanks a lot! That was very helpful explanation!
Comment: @MattB in that case, an upvote and/or an accept would be appreciated.
Comment: Can't yet, mate. I still have less than 15 reps.


How to integrate FB login with my own server

Question: I'm not understanding FB is saying we can use FB login in place of my own server's login.  More like how Uber allows a user to login using FB.
How is the flow supposed to go?  Is it like this?

User clicks login using FB on my Mobile App and grants permission
User informs my server that it has logged into Facebook.
??? what happens here?  How is security handled here?

The reason I ask is because FB doesn't say how the server side is implemented.
Answer: The idea is to use information associated with facebook to create a user on your server.
So..

User clicks login using FB on mobile and grants permission
Use info that you get from FB to create a user account (username, email, token) by calling your server endpoint.
Next time user logs in, you know who they are.

FB step is just shortcut for asking there email/password. It also allows for easy sharing of your content.
Answer:
User clicks login using FB on my Mobile App and grants permission. You will get a access_token.
User informs my server that it has logged into Facebook with received token
The server requests FB via that token, and get information.
The server responds to the client success or not.
Comment: How do you solve scenarios where a user would try to create an account after, should we try to link that account to the account created using fb login?
Comment: Yes, you can link it with fb acc. But I think it complicated. I will try to let user edit their profile (fb acc), like name or adding password. Because after fetched the infos from fb, I added them to database. Then user can edit them.
Answer: Actually, The process is
User Signs in, using your facebook SDK (with your App facebook client Id linked) and then on success returns:
User Information including:

Profile Picture
Email Address
Full Name

as email address is already verified by fb, so you can trust this email address to be true.
Now you can register user in your own server for signing in directly using your sign in page, by using the response email address. Simply provide a option to set password.(better to be kept optional)
Also fb sdk return access_token, which can be used further to call graph api's by your server or app.


Fazer uma busca e subtração de datas

Question: sou novo na área e gostaria de colocar uma dificuldade que estou tendo ..
No banco mongo tenho um exemplo de tabela (retornando essse json)
{
  "_id": "5cb7652fc278309ac78dce2b",
  "status": "Teste 123",
  "accessTokenKey": "exemplo",
  "accessTokenSecret": "exemplo",
  "dateToPost": "2019-04-15T14:45:28Z",
  "dateTime": "2019-04-17T17:41:03Z",
  "isPosted": false,
  "__v": 0
}

Primeiro de tudo eu preciso fazer o seguinte...
Comparar o dateToPost com a hora atual para que se a hora atual for maior, um outro util entra em ação e envia o post (é um app para postar no twitter com agendamento, apenas para estudo), depois ele muda o estado do isPosted de false, para true
Eu empaquei aqui, se nao quiser falar a resposta me fala por gentileza como procurar já está de ótimo tamanho, desde já muito obrigado
Obs: eu consigo filtrar também com este código
Tweet.find({isPosted: false}, await function(err, tweets) {
    if (err) throw err;
    res.send(tweets);
  })
}

mas nao consigo pegar as propriedade de dateToPost para subtrair =/
Answer: Essa query compara se a propriedade (dateToPost) é menor ou igual ($lte) a data atual (new Date())
Tweet.find({isPosted: false, dateToPost: { $lte: new Date() }}, () => { ... });

Há outros comparadores, olhe na documentação

Fazer uma busca e subtração de datas


Exportar imagens Blogger para Wordpress

Question: Estou migrando meu blog do Blogger para Wordpress. Como faço com as imagens, pois irei exportá-las e depois modificar uma a uma. Eu devo fazer redirecionamento 301? Isso é possível? Como proceder nessa situação?
Vejam bem, as URLs eu tenho que fazer redirecionamento 301. As imagens devemos proceder da mesma forma, para não sermos punidos pelo google?
*Apesar de achar que o blogger não seja possível este redirecionamento, com imagens.
Comment: @abc, anota aí: quando alguém pedir esclarecimento ou quando você tem mais informação pra fornecer, **por favor**, edita sua pergunta.
Comment: Qual a dificuldade que está tendo?
Comment: Meu problema é na importação das imagens... pois elas estão em vindo com tamanho menor. Minha dúvida seria se irei perder visitantes de imagens pois irei trocá-las para minha url?... ATT
Answer: Você pode fazer a migração de diversas maneiras:
1) Migrando o conteúdo manualmente, recriando as publicações e salvando as imagens uma por uma. Nesse método você iria evitar bugs e falhas de formação, tendo em vista que ambos são diferentes. É o mais trabalhoso, mas também é o mais garantido.
2) Linkando imagens via URL. Ou seja, você recria apenas o conteúdo e as imagens você linka ela através da plataforma do Wordpress.
3) Exportando todas as publicações pelo sistema do próprio Blogger. As imagens iriam juntos também, porém podem ocorrer alguns bugs principalmente no quesito alinhamento. Caso queira seguir este método:
http://wiki.locaweb.com.br/pt-br/Transferindo_Blogspot_para_Wordpress
Comment: Eu encontrei, um plugin interessante, envia as imagens e tudo mais...  Mas o problema é que as imagens estão em tamanho menor... Ou seja, ele importa o tamanho de  e não do ... Daí irei tentar fazer um substituição para /s1600/ nas imagens.
Outra coisa que estou desenvolvendo é uma aplicação para remover essas TAgs do blogger, que cagam com as postagens...  ATT
Comment: Já tive esse mesmo problema quando tive que migrar um cliente para o Wordpress. Decidi eu mesmo fazer essa migração, para evitar dores de cabeça...
Comment: Eu fiz a migração das imagens acredito que foi com este plugin: SEO Blogger to Wordpress using 301 Redirection ...  Deu certo, mais algumas não parecem... acredito que pouco a pouco faço manualmente... deixando padronizado o site... ATT

Exportar imagens Blogger para Wordpress


Why arn't changes I am making in CSS appearing?

Question: This is weird. I've just started at a company that uses Drupal (I havent used it before) and I've been tasked with making some simple CSS changes to a site.
I find the site's theme folder and corresponding CSS and make a simple change just to test things out. Nothing happens. I clear the cache via admin and get a 500 error. Fine. So I use drush to clear CSS and JS. It says it works but still no change. I clear my browser cache too just to be sure.
I use Chrome's inspector to trace back the paths of the CSS files I'm working on - they're correct. I even check the themes .info file to see if all the .css files are linked - they are.
So...what am I missing here? What on Earth is going on?
(Edit: CSS aggregators are off)
Comment: Are you sure you are on the right server? try naming a .css file and see what happens.
Comment: Also, edit your css file and check that the changes made did save.
Answer: I'd turn off CSS aggregation temporarily to see if that makes any difference. The settings are in admin/config/development/performance
That way you can see which CSS files are being used directly. This sounds like it might be a configuration problem with the server itself and not something with Drupal.
Also, check the response headers for the CSS. That will give you more info about whether it's serving cached versions and if there's something like a reverse proxy serving old versions of the files.
Comment: Sorry, I should have mentioned: aggregators are off.
Comment: In that case, open the CSS file directly with your browser. If you still see the old version then it's not a problem with Drupal.
Answer: Turned out this was because the Theme I was working on refused to be 'activated' despite this appearing so in the UI. I don't know why Drupal was doing this.


Replace First N Occurrences in the String

Question: How can I replace first N occurrences of many whitespaces and tabs in the following string:
07/12/2017  11:01 AM             21523 filename with s p a c  e  s.js

I am expecting the following result:
07/12/2017|11:01|AM|21523|filename with s p a c  e  s.js

I know not very elegant option only via calling replace N times on the same string
.replace(/\s+/, "|").replace(/\s+/, "|").replace(/\s+/, "|");

Worth to mention that I'm going to run this on near 1,000,000 lines so performance matters.
Comment: @stealththeninja Op wants to only replace the first 4 occurrences in the strings, thus leaving the spaces in the file name intact.
Comment: `g` will replace everything. But i need to replace only first `n` occurrences
Comment: smells like you can use a loop of some sort
Answer: Probably something like this:
var txt = "07/12/2017  11:01 AM             21523 filename with s p a c  e  s.js";

var n = 0, N = 4;
newTxt = txt.replace(/\s+/g, match => n++ < N ? "|" : match);

newTxt; // "07/12/2017|11:01|AM|21523|filename with s p a c  e  s.js"

Answer: You could take a counter and decrement it.

var string = '07/12/2017  11:01 AM             21523 filename with s p a c  e  s.js',
    n = 4,
    result = string.replace(/\s+/g, s => n ? (n--, '|') : s);

console.log(result);

You could replace the ternary expression with one with logical AND and OR.

var string = '07/12/2017  11:01 AM             21523 filename with s p a c  e  s.js',
    n = 4,
    result = string.replace(/\s+/g, s => n && n-- && '|' || s);

console.log(result);
Answer: Derek and Nina provide great answers for dynamically replacing N whitespace groups. If N is static, the non-whitespace token (\S) can be used to match and keep the groups between whitespace:
.replace(/\s+(\S+)\s+(\S+)\s+/, '|$1|$2|')
Answer: Some answers here are really good already, but since you say you want speed, I'd go with a single while, like this:

var logLine = '07/12/2017  11:01 AM             21523 filename with s p a c  e  s.js';
var N = 4;
while(--N + 1){
  logLine = logLine.replace(/\s+/, '|');
}
console.log(logLine);

Here's on JSFiddle: https://jsfiddle.net/2bxpygjr/
Answer: I'd go with something like this. Though I kinda like Derek's answer so I'll look his up and understand what he/she does in it.
var mytext = "some text separated by spaces and spaces and more spaces";
var iterationCount = 4;
while(iterationCount > 0)
  {
    mytext = mytext.replace(" ", "");
    iterationCount--;
  }
return mytext;

Answer: What about recursive version of you own solution?
function repalceLeadSpaces(str, substitution, n) {
    n = n || 0;
    if (!str || n <= 0) {
        return str;
    }
    str = str.replace(/\s+/, substitution);
    return n === 1 ? str : repalceLeadSpaces(str, substitution, n - 1)
}

Answer: You could also:

split on whitespace, using a capturing group to retain the spacing;
use map to replace the first N whitespace elements with |;
join the parts back together

const str = '07/12/2017  11:01 AM             21523 filename with s p a c  e  s.js'

const N = 4
const result = str.split(/(\s+)/).map((v, i) => i % 2 == 0 || i >= 2*N ? v : '|').join('')

console.log(result)


Meaning of this definition of a system of ODE:s? (Multivariable ODE?)

Question: I always thought an ODE had one independent variable:

For a system of $n$ ODE:s, we have a vector function $f$ of one variable $t$, $f:\mathbb R\rightarrow \mathbb R^n$ and
  \begin{align}
\dot x(t)=f(t,x(t))
\end{align}

However, in Ordinary Differential Equations by Logemann and Ryan, the defintion is

Our goal is the study of systems of ordinary differential equations of the form
  $$
\dot x(t)=f(t,x(t))
$$
  Here $f:J\times G\rightarrow \mathbb R^N$ is a suitably regular function, $J\subset \mathbb R$ is an interval and $G$ is a non-empty open subset of $\mathbb R^N$.

From "$J\times G$", $f$ is now a function of $N+1$ variables: $f:\mathbb R^{N+1} \rightarrow \mathbb R^N$.
But hey, it is an ODE, $f$ should be function of one variable?
I'm stuck at this definition, I can't wrap my head around this!
I appreciate any clarification/reference. Thanks!
Comment: The function $t \mapsto f(t,x(t))$ *is* a function of one variable. But the function $(t,y) \mapsto f(t,y)$ is a function of two.
Comment: $f$ is a known function. "ODE" means that the unknown function $x$ has one argument. (Besides, even in your original example, $f$ is a function of two variables: $t$ and $x$.)
Comment: $J\times G$ is a [cartesian product](https://en.wikipedia.org/wiki/Cartesian_product).
Answer: An ODE can be a function of as many variables as you like, the point is that there are only derivatives in one variable - this variable is often denoted $t$ (for time).
E.g. $t\mapsto x(t),$ $[0,1]\to \mathbb R^3$ can be thought of as a particle satisfying some ODE $$\frac{d}{dt}x(t)=f(t,x(t)),\quad x_0=x.$$ This is an ODE, as only a time-derivative occurs -- despite the fact that $f:[0,1]\times\mathbb R^3\to \mathbb R^3$ is a function of several variables. Indeed, $f$ needs to be a function of many variables as the solution to the ODE lives in $\mathbb R^3$ and we are composing $f$ with this solution!
Comment: Thanks! When we write $f(t,x_t)$, do you mean $x_t$ is a function of $t$?. If so $f(t,x_t)$ is explicit $f(t,t_t(t))$, correct? But my problem here is that now $f$ must be a single variable function. I don't grasp how it could be a multivariable function.
Comment: Sorry I was using, $x_t =x(t)$  -- I have now changed the notation. I don't quite understand what you're saying: $x$ is a function $x:[0,1]\to\mathbb R^3$ and $f$ is a function $f:[0,1]\times\mathbb R^3\to \mathbb R^3$. So why do you think $f$ is a single-variable function?
Comment: Hmm, I will try to explain what I mean. If we forget ODEs for a moment. If I have a function $f(x,y)$, this is a function $f:\mathbb R^2 \rightarrow \mathbb R$, right? Suppose I have a another function $g(x,y(x))$, this is just a function of one variable, right?
Comment: Read Chappers' comment above -- s/he's already answered that question. $g$ is a function of many variables. The composition $x\mapsto g\circ(x,y(x))$ is a function of one variable.
Answer: Suppose you have a function
$$F(u,v) = [u^2 v,  uv, 4v]$$
This is a vector-valued function of two variables: $F : \mathbb{R}^2 \rightarrow \mathbb{R}^3$.
Now, suppose you are interested in finding a function $y:\mathbb{R}\rightarrow \mathbb{R}^3$ such that:
\begin{align*}
\dot y(t) = [t^2 y(t),\, t\cdot y(t),\, 4y(t)]
\end{align*}
You could express this problem by saying that you are looking for a function of one variable $y:\mathbb{R}\rightarrow \mathbb{R}^3$ such that for all real $t$ in an area of interest, the following equation is true:
$$\dot y (t) = F(t, y(t))$$
Evidently, both $\dot y$ and the composite function $h(t)\equiv F(t, y(t))$ are functions of a single variable. This is what makes the equation an ordinary differential equation.
$F$ has two independent variables. But the problem you've set up— find a function $y:\mathbb{R}\rightarrow \mathbb{R}^3$ such that $\dot y = F(t, y(t))$ has only single-valued functions on both sides.

Maybe another way to put this is in terms of composition: given a function $y:\mathbb{R}\rightarrow \mathbb{R}$, you can explicitly mention a function $G_{[y]}:\mathbb{R}\rightarrow \mathbb{R}^2$ where $G_{[y]}(t) \equiv \langle t,\, y(t)\rangle$.
Then $F(t, y(t))$ can more clearly be written as a composition $F\circ G_{[y]}$ which sends $$t\mapsto \langle t,\,y(t)\rangle \mapsto F(t, y(t)).$$
$F$ is a function with two free variables (named $u$ and $v$, above). In contrast, $F\circ G_{[y]}$ is a function with one free variable (named $t$).
With an ordinary differential equation, you are searching for a function $y$ such that for all real $t$ of interest,
$$\dot y = F \circ G_{[y]}$$
that is, such that $\dot y(t)$ and $F(t, y(t))$ are equal as functions of $t$.

I write the function as $G_{[y]}$ as a reminder that $G$ was defined in terms of a particular function $y:\mathbb{R}\rightarrow \mathbb{R}$. In particular, $G_{[y]}$ has a geometric interpretation: it is the graph of $y:\mathbb{R}\rightarrow \mathbb{R}$.
Comment: In your first example, what is the dimension of the values of $y$? You mix 1 and 3 quite deliberately.


How to reduce sample data to a smaller scale?

Question: In statistics let's say for a specific city (call it "City A") 1000 people die of driving related accidents annually. The city has a population of 2.7 million people. In another city, "City B" 3000 people die annually from driving related accidents but 7.3 million people live in City B. How could I provide a proper statistical comparison to prove which city has better drivers, while taking respect to the difference in population?
Answer: Don't overthink it: For A the annual car death rate is $\frac{1000}{2700000} = 0.00037$, i.e. 37 out of 100'000 anually. For city B it's $\frac{3000}{7300000} = 0.00041$, i.e. 41 out of 100'000 anually.
So purely from a car death rate perspective, city A is better (lower death rate). However, I wouldn't go as far as concluding automatically that city B drivers are worse. There could be many factors, e.g. less lights on road, more rainy weather or a thousand other things that influence the rate from above.
As long as there is not more info about city A or city B and their populations this is the best you can do.


Braid invariants resource

Question: What are some braid invariants (analogous to the idea of knot invariants) or a resource where I can find them?
Comment: Invariant up to what? Equality or conjugacy? The invariants coming from quantum groups also give braid invariants, but they aren't numbers (they're linear transformations).
Answer: For a solid reference on this topic, I would suggest either

J. S. Birman Braids, Links and Mapping Class Groups, Annals of Mathematical Studies 82, Princeton University Press, 1975.

for a classical approach to a solution for the word problem of the braid groups (contained in the first two chapters), or

V. L. Hansen, Braids and Coverings, London Mathematical Society Student Texts 18, Cambridge University Press, 1989.

for a more refined and modern approach, closely based on Birman's text.
To directly answer your question, piecewise linear (non-backtracking) braids on $n$ strands can be entirely classified up to ambient isotopy by 'solving the word problem' in the braid group $B_n$. This means that, given two words in the standard braid generators, we can tell whether these words represent ambient isotopic braids or not in an algorithmic way, as outlined in either of the above references (this amounts to writing braids in a 'standard form' which is shown to exist, and be unique, for every braid).
There are of course many other ways to classify braids. You may want to classify them up to conjugacy, because conjugate braids in $B_n$ will give the same link, up to isotopy, when taking the braid closure (although the converse does not hold. Non-conjugate braids can close to give isotopic links).
You may want to consider classifying braids up to 'homotopy'. This is where you consider two braids to be the same if you allow standard ambient isotopies to get from one to the other, but you also allow single braid strings to 'pass through themselves' (but not each other). A good reference for this concept of homotopic braids is

K. Murasugi & B. Kurpita, A Study of Braids, Kluwer Academic Publishers, 1999.

Braid invariants resource


How to solve laplace inverse using convolution

Question: The problem is find the laplace inverse of:
$Y(s) =\frac{18}{s(s-6)} + \frac{2}{s-6}$.
Are you able to solve this problem using convolution, by breaking the terms into:
$18 * \mathscr{L} (\frac{1}{s}) * \mathscr{L}(\frac{1}{s-6})$
I tried to solve it using this method, but did not get the same solution as solving through partial fractions.   Thanks in advance for the help!
The answer I found through partial fractions is: $5e^{6t}-3$
My solution is shown in the image below!
Comment: Show us your partial fractions decomposition.
Comment: This doesn't seem to be the same answer I found through partial fractions.  I have an extra $+2e^{6t}$ term!?
Comment: @Yves I've added an image of my solution!
Comment: My apologies, I only posted a portion of the question which is what confused me when the answers did not match.  I've updated the question to reflect the original problem with the added $\frac{2}{s-6}$ term upon simplification.  If you have the time - it would be amazing if you could update your convolution solution to answer the full problem!  Thanks :)  (@Yves also)
Comment: There is now far enough material on this page for you to get/check the proper answer.
Comment: I know the correct answer, but I don't understand the convolution integral with respect to this problem.
Answer: $$\frac{18}{s(s-6)} = \frac{A}{s} + \frac{B}{s-6} = \\
= \frac{A(s-6)+Bs}{s(s-6)} = \frac{s(A+B) - 6A}{s(s-6)}.$$
Then:
$$\frac{18}{s(s-6)} = \frac{s(A+B) - 6A}{s(s-6)},$$
which is satisfied when the numerators are equal. In particular, you need to pose:
$$\begin{cases}
A+B = 0\\
-6A = 18
\end{cases} \Rightarrow \begin{cases}
B = 3\\
A = -3
\end{cases}.$$
Finally:
$$Y(s) = -\frac{3}{s} + \frac{3}{s-6}.$$
This can be easily anti-transformed:
$$y(t) = (-3 + 3 e^{6t})u(t).$$
Comment: Thank you for the partial fraction solution.  My question was however, how to solve the problem using normal fraction expansion and the convolution integral by separating the terms into $\frac{1}{s} \ \ and \ \ \frac{1}{s-s}$.
Answer: Using Convolution (see Part $2$) for the first part, we have:
$$18 \left( \mathscr{L}^{-1} \left(\dfrac{1}{s}\right) * \mathscr{L}^{-1} \left (\dfrac{1}{s-6}\right)\right) = 18(1 * e^{6t}) \implies \displaystyle 18 \int_0^t 1*e^{6 v}~dv = 3(-1 + e^{6t})$$
Using Inverse Laplace Transforms for the second part:
$$\mathscr{L}^{-1} \left(\dfrac{2}{s-6} \right) = 2 e^{6t}$$
Adding the two results:
$$\mathscr{L}^{-1} \left(Y(s) \right) = \mathscr{L}^{-1} \left(\frac{18}{s(s-6)} + \frac{2}{s-6}\right) = -3 + 5e^{6t}$$


Chasing Problem

Question:
Possible Duplicate:
Four turtles/bugs puzzle

Starting from the corners of a square of side a, each bug chases the one clockwise from it. If they all start at the same time and run at the same speed, how far has each bug run by the time they all collide at the center of the square?

I know that this can be solved with or without calculus. Can anyone help me please? Thank you.
Comment: The answer is given in [this previous question](http://math.stackexchange.com/q/155254/856).
Comment: @RahulNarain:  Good on you for finding it
Answer: By symmetry, the bugs are always at corners of a square as they spiral in.  A quasi-calculus solution is to recognize that the path of one bug is (infinitessimaly) directly toward the next one, and the path of the next one is perpendicular, so the distance shortens with the speed of the bug.  The distance traveled is then the side of the square.
Answer: Let $A(t)$ and $B(t)$ be two of these bugs, $A$ chasing $B$. Note that $A$ always moves towards $B$ in a direction perpendicular to the motion of $B$. Thus, it makes no difference how $B$ is moving, as the time it takes $A$ to reach $B$ remains the same in any event.
As a result, the time it takes is the original distance between $A$ and $B$, written $|A(0) - B(0)|$, divided by the speed of bug $A$, and the distance each bug has run is $|A(0) - B(0)|$.

Chasing Problem


Why does pagination create duplicates in Google's results?

Question: I created multiple views to display different types of nodes on my site. On each of these views, I added a pagination, which creates duplicates in Google's results. Why?
I think this is bad for the SEO of my site. How can I avoid this?
Answer: This is definitely bad for SEO.
You need to set related links on the each page of the view so that google doesn't crawl all of the variations via parameters. Example:
<code><link rel="next" href="http://example.com/view?page=2">
</code>
Apparently the metatag module will help with this, or you can find some discussion about how to do it on this issue.


cloning with dd - is non-partitioned space considered the same as empty space within filesystem for resulting image size?

Question: note: all = all that i've found
All the "cloning with dd" information talks about how dd copies all the "empty space", but literally all writings seem to be responding to a situation where filesystems fill up the entire disk.
What about the situation where i have two partitions that together fill up only 10% of 160G disk. What is the image size going to be for the good ol "dd if=/dev/sda of=disk.img" run: 16G or 160G?
Unless i'm blind, Using DD for disk cloning does not have this information.
Answer: sda is the disk as a whole - 160 GB
sda1 is the first partition on that disk - 8 GB (say)
sda2 is the second partition on that disk - 8 GB (say)
If you only want to clone the 16 GB of filesystem data, use dd on sda1 and sda2.
To restore the data to a different disk you'd have to first partition that disk (ideally identically to the original disk). I expect you'd probably have to reinstall the bootloader too.
See, for example, http://www.backuphowto.info/linux-backup-hard-disk-clone-dd
Comment: yeah, if the goal is to have minimum whole-disk image size with a single dd command, you are saying there is no difference to dd whether empty space resides inside filesystem or in non-partitioned space. right?
Comment: `dd` can't tell the difference between "empty space" and space filled with data. You can minimize the image size by compressing it with `gzip` but obviously this takes time. I suppose you could minimise the size of a gzipped dd of sda by creating a new partition to occupy the remaining disk space and filling that partition with zeroes or some regular pattern. However I doubt there are many cases where this would be worthwhile.
Answer: First I want to answer to your question:

what about the situation where i have two partitions that together
  fill up only 10% of 160G disk. what is the image size going to be for
  the good ol "dd if=/dev/sda of=disk.img" run: 16G or 160G?

If you run dd on /dev/sda, i.e. the whole disk sda of 160G, then disk.img will be 160G, since dd will just copy all bits on sda one by one. It makes no difference if the space after /dev/sda1 and /dev/sda2 is partitioned or not! Unfortunately, if the hard disk ever was full of data before, even if you try to compress the disk.img, it will not really get smaller because of the fact that the "empty space" on the disk surface in reality is not empty but contains the leftover bits of the previously used file systems and data. I do not know what the case for brand new hard disks that have never been used before is, though!
Additionally to this, I want to answer to your comment that you gave to RedGrittyBrick's answer.
If your goal is to make a minimum size whole-disk image, then a possible solution is as follows

Create a third partition with the empty space, in your example:    /dev/sda3. There is no need (but also no harm) to format it with a   file system since the partition will be overwritten with zeros in the    next step, eliminating any file system formatting again
Now fill the entire partition with zeros: dd if=/dev/zero of=/dev/sda3. This will take quite a long time and dd has no    progress bar, so just be patient. At some point dd will report that  the disk is full and some time after that will exit with a final    report about the bits copied
If you do not want this partition to exist, you can delete it again now. The zeros will remain on the disk surface!
Now make the single disk image as you where planning in first place: dd if=/dev/sda of=disk.img. By the way: There is no need for any further dd-parameter whatsoever, such as conv=notrunc, etc.    as reported in many other forums. notrunc has    absolutely nothing to do with what we want to do here (clone a disk to a file) and is used for something totally different (in    short: Insert data in a file that is already existing without cutting    off [=truncating] the remains of the existing file should the newly    added data be shorter than the existing file). Do not listen to those    who write that notrunc is especially needed when cloning disks to a    file, that is 100% bollocks
The disk.img will be 160GB again, no surprise here. But the difference now to before is that if you compress the disk.img, this  time it will almost become the same size as the sum of the compressed images of /dev/sda1 and /dev/sda2 would be, since the zeros on the remaining unpartitioned disk surface will compress down to practically nothing!
There you go, now you have a single-file full disk image of the whole disk but which is almost only the size of the really used data area of /dev/sda1 and /dev/sda2
In the case that you would not have created /dev/sda1 and /dev/sda2 yet, you  could also just write zeros with dd to the entire disk /dev/sda first, or use a disk wiping tool that writes zeros to an entire disk, etc. and then just create /dev/sda1 and /dev/sda2. The result should be the same

HTH!
Best regards
An anonymous internet native on planet earth
Comment: Or you can instead truncate the data at the right place (`head -c …` for example). Then even the uncompressed image doesn't need to be 160GB; and writing back incomplete raw image is totally fine; if you really need, you can always fill with zeroes the remaining space when restoring.  The tricky part is to figure out the correct size…


Write a function that returns avg arrival delay by carrier by airport in R

Question: I have an airline delays data set with columns for carrier, origin airport, destination airport, dep delay, arr delay. How do I write a function that calculates and returns the average arrival delay for a carrier flying into the specified destination airport? This is what I have and it's not working.
avgDelay <- function(Carrier,Dest)
{
    x <- 0
    for (i in 1:dim(delays)[1])
    {
        for(j in 1:dim(delays)[1])
        {
            if(delays[i,3] == Carrier && delays[j,5] == Dest)
            {
                total <- x+(sum(delays[i,7] > 0, na.rm = TRUE))
                avg <- mean(total)
            }
        }
    }
    return(avg)
}

I want to run the function to return the average number of delays by carrier by destination airport
avgDelay("AA","LAX")

The data set looks something like this
  YEAR MONTH CARRIER ORIGIN DEST DEP_DELAY ARR_DELAY
1 2014     1      AA    JFK  LAX        14        13
2 2014     1      AA    JFK  LAX        -3         1
3 2014     1      AA    JFK  LAX        NA        NA
4 2014     1      AA    JFK  LAX        65        59
5 2014     1      AA    JFK  LAX       110       110
6 2014     1      AA    JFK  LAX        17        -8

Comment: It would help if you included a small example data set and the desired answer.  Your code should run and return an answer against which the desired answer can be compared.
Answer: This is what I was looking for
   avgDelay <- function(carrier, dest)
{
     TempTotal = 0
     TempCount = 0
     for(i in 1:dim(delays)[1])
     {
     if(delays$CARRIER[i] == carrier  & delays$ARR_DELAY[i] >0 & is.na(delays$ARR_DELAY[i]) == FALSE & delays$DEST[i] == dest)
         {
             TempTotal <-TempTotal + delays$ARR_DELAY[i]
             TempCount <-TempCount + 1 # keeps count of the number of delays
     }
 }
 return(TempTotal/TempCount)
}

avgDelay("AA", "LAX")

Answer: The above answer would take more than 30 secs to execute.
The below code would be quicker as compared to the above one
AvgDelay<-function(x,y){
  output<-AirlineFile[(grepl(x,AirlineFile$CARRIER)&(grepl(y,AirlineFile$DEST))),]
  returnValue(mean(output$ARR_DELAY[output$ARR_DELAY>0]))
}


How does feature selection work for non linear models?

Question: A model like a neural network or an SVM is called for only if the interactions between the features and the target is non-linear, otherwise we're better off using linear or logistic regression.
But all of the feature selection methods I've come across use linear criteria for determining feature importance: For example if two features are highly correlated then we can discard one and use only one of them. Same thing with LASSO or using a variance threshold. They only make sense to me if we assume a linear relationship to the output.
So how does one then perform feature selection for non linear supervised models?
Answer: Assuming non linear feature interactions, one could use something like mutual information which can capture both linear and non linear dependencies. You could check the mutual information between your features and the target variable and based on this criteria select relevant features.
There is a family of simple and famous models that captures non linear interactions, to give you the simplest one as example decision trees, which use the information gain criteria to build its splits. Once you fit a decision tree(or similar models) you gain a feature importance vector that will tell you the importance of each feature. There is this paper on Feature Selection via Regularized Trees.
In the end, regardless of the type of features interaction or nature of the model (linear vs non linear) you can always apply some type of search for feature subset selection as described here


Tiny mail server for low end box?

Question: I want to set up a mail server with as much smaller memory footprint as possible on a Centos 5 very low end machine.
Bare minimum features is enough. :)
But what are my options? I can't seem to find anything like that. Or perhaps I can stripdown one of the well know packages?
Thank you.
Comment: Which features do you require?
Comment: POP or imap (whatever is lighter) and smtp for 10 users maximum. I don't think it will be more than a few hundred mails per month as traffic.
Answer: For just SMTP I would say Postfix or Qmail. Those are quite lightweight to begin with and can be tunes easily. Postfix's modular nature allows you to disable any unused features and their processes. You can also tune Postfix to get the most out of limited resources.
If you need to add POP/IMAP then I think Dovecot is a good choice since it's uses few resources by default. A little more tuning can be done.
Answer: I run sendmail and dovecot on a very old CentOS 5 machine. Granted I don't use it for hundreds of people, but it works well enough.
Answer: My first choice would be postfix - it's compact, efficient, reliable and easy to manage. Sendmail certainly doe well in terms of reliability, and it can comfortably process huge volumes of emails but its a pig to configure and IMHO doesn't scale down as well as it scales up. I've not looked at qmail nor exim for some time, but previously did some research and found them to be not nearly as good in terms of reliability.
HTH
C.

Tiny mail server for low end box?


Calculating CPU cache hits

Question: I am struggling to understand what the process/formula is for calculating cache hits. So, if for example if we have a main memory with 16 entries and a cache memory of 4 entries and the CPU loads the memory addresses: 0, 1, 2, 8, 9, 2', how can I calculate the number of hits a) if the cache is direct-mapped and b) 2-way associative?
Answer: Assuming no prefetchers and LRU as the replacing mechanism.
a)
For direct-mapped cache, each memory entry can be only in one cache entry.
The cache will map like this (default assuming uniform distribution):
Cache 0 --> can hold 0,4,8,12 of the main memory entries.
Cache 1 --> can hold 1,5,9,13 of the main memory entries.
Cache 2 --> can hold 2,6,10,14 of the main memory entries.
Cache 3 --> can hold 3,7,11,15 of the main memory entries.

After reset, the cache is empty.
Load from 0 will be missed and will be cached in cache entry 0.
Load from 1 will be missed and will be cached in cache entry 1.
Load from 2 will be missed and will be cached in cache entry 2.
Load from 8 will be missed and will be cached in cache entry 0 (replaced load 0).
Load from 9 will be missed and will be cached in cache entry 1 (replaced load 1).
load from 2 will be hit and will be taken from cache entry 2.

so we have 1 hit and and 5 misses, the hit rate is 1/(5+1) = 1/6 = 16%
b) For 2 ways associative, you will have for each entry in the memory 2 entries in the cache to go to.
so set0 (entries 0,1 in the cache) will hold all the even main memory entries and set1 will hold all the odd entries, so if we span it we will have like this:
cache 0 (set 0) --> can hold 0,2,4,6,8,10,12,14 of the main memory entries.
cache 1 (set 0) --> can hold 0,2,4,6,8,10,12,14 of the main memory entries.
cache 2 (set 1) --> can hold 1,3,5,7,9,11,13,15 of the main memory entries.
cache 2 (set 0) --> can hold 1,3,5,7,9,11,13,15 of the main memory entries.

After reset the cache is empty.
Load from 0 will be missed and will be cached in cache entry 0.
Load from 1 will be missed and will be cached in cache entry 2.
Load from 2 will be missed and will be cached in cache entry 1.
Load from 8 will be missed and will be cached in cache entry 0 (replaced load 0 because we replace the Least Recently Used).
Load from 9 will be missed and will be cached in cache entry 3.
load from 2 will be hit and will be taken from cache entry 1.

in this case the hit rate is the same: 1/(5+1) = 1/6 = 16%

Calculating CPU cache hits


How can I add radio button and submit button in a drupal view?

Question: I want to add radio button in my drupal view ?
I need to make a table of users and set for each of them one status(present,absent,delayed,...) by use of radio buttons, and A button under the table to save these statuses.
So how can I change view?
Answer: Mohsen,
Maybe Views Bulk Operations module can help you. You can download it at http://drupal.org/project/views_bulk_operations.
Comment: Is it possible to put a form in each field, and use Views Bulk Operations module?
Comment: but VBO is not sufficient for my purpose, I don't want to edit this module.
Answer: I used embed form module to add some radio buttons in my view. and now I must implement submission.
Answer: I wish I new.
I'm currently playing with hook_views_data to create a relationship within Views between my table and a node. This works ok.
I just need to work out how to make this data submittable from within the View.
If I work it out I'll let you know.


Skip DNS query with Java if I have the IP

Question: How do I skip a DNS request if I have a list of domains and their IP address?
scans.io provides a list of domain and their IPs and I would like to use that list instead of sending a query to a DNS server.
Is it ever possible without setting up my own dns server?
Edit:
The reason is that I have a big file with a million of domain with their IP and I want to crawl them as fast as possible without getting banned from a DNS server.
Answer: If you use InetAddress.getByName(String) (javadoc) you can supply either a DNS name or the string representation of an IP address.  In the latter case, it the method won't do an unnecessary DNS lookup.

What happens when an IP has more than one site? It's possible if I remember correctly, and giving just the IP shouldn't be enough.

A website is identified by a URL, not just a DNS name or IP address.  The URL gives you the hostname or IP address, and also the protocol to use, the port number and the path.  Any one of these can cause your HTTP requests to be directed / redirected to a different "site" ... whatever that means.
Basically, the process of connecting to a "site" starts as follows:

The hostname (or IP address string) is converted to an address
The port number is figured out (from the protocol and the optional explicit port number in the URL.
The client opens a TCP connection to the IP / port determined above
The URL is sent to the server listening on the IP / port in the HTTP start line.

If there are multiple "sites" on the same IP address + port (e.g. because multiple hostnames resolve to the same IP), then the server works out which "site" should respond based on the start line (and potentially, other HTTP headers).

If your goal is to reduce DNS lookups for HTTP interactions, then your best bet is to configure client-side DNS caching.  Details are platform specific.  Google can help you find the details.
You could also turn your big file of DNS entries into "/etc/hosts" syntax, and point the local resolver at it.
Comment: I am not 100% sure about my next question..but what happens when an IP has more than one site? It's possible if I remember correctly, and giving just the IP shouldn't be enough.
Comment: Thanks for your answer. I will have a look at caching. I'm not sure it will help though, since I will connect to each site only once.
Answer: You don't explain what you want to do with this data that you think requires a DNS lookup. If you are trying to make InetAddress objects in java, you can call InetAddress.getByAddress(host, addr) to construct an InetAddress without performing a DNS lookup.
See https://docs.oracle.com/javase/7/docs/api/java/net/InetAddress.html#getByAddress(java.lang.String,%20byte[])
To convert an address into a byte[], call InetAddress.getByName(addr).getAddress() if you know it is a valid address. It will not cause a DNS lookup. If you don't trust your data, you may want to write a small function to parse the address yourself and build a byte array.
Comment: I added the reason. I crawl a huge list of domain as fast as possible (not too fast ofc) and I don't want to get ban/warnings from dns servers.
Answer: There are several possibilities.
If you are not required to limit DNS lookups from your datafile to a specific Java process, you can add the list to your system's 'hosts' file. Where to find the file is OS specific and you have to consider that all processes running on the system would get the matching IP from the hosts file if they use the OS API calls to resolve an IP from a host name.
Another option is, if supported by your Java VM, to configure the host name resolver to use other data sources than a regular DNS lookup. Oracle's Java VM offers this possibility and you can find a documentation of the configuration in the section JNDI DNS service provider settings of the network properties documentation. Perhaps a little bit outdated, but this article also gives you a complete example on how to implement your own NameService using the API in sun.net.spi.nameservice.


How to set up email address on my domain

Question: I realize this is a really elementary question but I can't seem to find a good answer to my question through googling.
I want to set up an email address on my domain, e.g. email@example.com. I think I'd like it to forward to my GMail account.
I'm on Ubuntu and I already have Postfix installed.
Answer: I'd suggest using Google apps for this and just setting up forwarding. If you insist on setting up a mail server, check out this guide: http://flurdy.com/docs/postfix/
Answer: From the content of your question, I'd suggest that instead of trying to set up a mail server of your own, that you consider setting up a Google apps account for your domain. You can configure either account to forward to the other, as you see fit.
The process is fairly straight forward. As you've already got you domain, you need to sign up to Google Apps, then create a couple of MX records in your registrar's control panel and point them at Google's servers. The whole process shouldn't take longer than a couple of days.
Answer: If you want mail for your domain, there needs to be a server handling it and you'll need to setup an MX record on the domain to point to the server's address.  If you don't personally setup a server to handle it i'm sure there will be a charge from the company you bought the domain from to add e-mail to your domain.  If you get e-mail service from the company you purchased the domain from and pay the monthly fee, there will be a place on your account to set a forward address.  Google may do all of this for free but i've never set it up.


Thread de um ponto "piscando"

Question: Ola, eu fiz um programa que voce mexe uma bolinha com as setas do teclado so que fica piscando a tela quando mexe. Eu vi outros programas nesse tipo do meu so que nao ficam piscando. Se alguem puder me ajudar...
(o fundo fica normal mas a bolinha enquanto se mexe que pisca)
codigo:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Cobrinha extends JFrame implements Runnable {

    private Thread th = new Thread(this);
    private int posEsq = 300;
    private int posTop = 300;
    private int ultTecla = 37;

    public Cobrinha() {
        super("Cobrinha");
        this.setSize(600,600);
        this.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                mover(e.getKeyCode());
            }
        });
        this.getContentPane().setBackground(Color.GREEN);
        th.start();
        this.setVisible(true);
    }
    public void mover(int tecla) {
        ultTecla = tecla;
    }
    public void run() {
        while (true) {
            switch (ultTecla) {
                case 38: posTop--; break;
                case 40: posTop++; break;
                case 37: posEsq--; break;
                case 39: posEsq++; break;
            }
            try { th.sleep(6); } catch (InterruptedException e) { }
            this.repaint();
        }
    }
    public void paint(Graphics g) {
        super.paint(g);
        g.fillOval(posEsq, posTop, 20, 20);
    }
    public static void main(String [] args) {
        new Cobrinha();
    }
}

Comment: Como você pode perceber você recebeu votos para fechar como não clara. A razão certamente é que você não explica corretamente o que é "piscada", não descreve como é a tal "bolinha" e também não oferece uma imagem de exemplo do que acontece. Se for o que eu imagino, essa piscada se chama *flickering* e ocorre porque a repintura total está acontecendo a cada quadro. Herde de `JComponent` ao invés de `JFrame` que deve ajudar por causa do *double buffering*. Dá uma lida nesta minha outra resposta (e na que ela linka) pra entender os detalhes: http://pt.stackoverflow.com/a/14283/73
Answer: Para utilizar o double buffer no Swing, você pode fazer com que sua classe herde de JPanel, e depois sobrescrever o método paintComponent. Após isso é só inserir sua classe em um JFrame:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Cobrinha extends JPanel implements Runnable {
    private static final long serialVersionUID = 1L;
    private Thread th = new Thread(this);
    private int posEsq = 300;
    private int posTop = 300;
    private int ultTecla = 37;

    public Cobrinha() {
        setSize(600, 600);
        setBackground(Color.GREEN);
        th.start();
        setVisible(true);
    }

    public void mover(int tecla) {
        ultTecla = tecla;
    }

    public void run() {
        while (true) {
            switch (ultTecla) {
            case 38: posTop--; break;
            case 40: posTop++; break;
            case 37: posEsq--; break;
            case 39: posEsq++; break;
            }
            try {
                Thread.sleep(6);
            } catch (InterruptedException e) {
            }
            repaint();
        }
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.fillOval(posEsq, posTop, 20, 20);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Cobrinha");
        Cobrinha cobrinha = new Cobrinha();

        frame.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                cobrinha.mover(e.getKeyCode());
            }
        });

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(cobrinha);
        frame.setBounds(0, 0, 600, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

Thread de um ponto "piscando"


Nmap results incorrect when connecting via VPN

Question: I am trying to determine why my nmap results are incorrect when I am connected to a VPN provider.
As you can see below nmap reports that ports are open when connecting to a VPN provider even though the host has no open ports.
Here's an example:
No VPN
root@localhost# nmap -vvv --open 126.96.36.199
Starting Nmap 7.80 ( https://nmap.org ) at 2021-05-31 11:41 EDT
Initiating Ping Scan at 11:41
Scanning 22.214.171.124 [2 ports]
Completed Ping Scan at 11:41, 3.01s elapsed (1 total hosts)
Read data files from: /usr/local/bin/../share/nmap
Note: Host seems down. If it is really up, but blocking our ping probes, try -Pn
Nmap done: 1 IP address (0 hosts up) scanned in 3.08 seconds

Windscribe VPN
Shows TCP 443 open
root@localhost# nmap -vvv --open 18.104.22.168
Starting Nmap 7.80 ( https://nmap.org ) at 2021-05-31 11:40 EDT
Initiating Ping Scan at 11:40
Scanning 18.104.22.168 [2 ports]
Completed Ping Scan at 11:40, 0.01s elapsed (1 total hosts)
Initiating Parallel DNS resolution of 1 host. at 11:40
Completed Parallel DNS resolution of 1 host. at 11:40, 0.01s elapsed
DNS resolution of 1 IPs took 0.02s. Mode: Async [#: 1, OK: 1, NX: 0, DR: 0, SF: 0, TR: 1, CN: 0]
Initiating Connect Scan at 11:40
Scanning ariel.c2b2.columbia.edu (18.104.22.168) [1000 ports]
Discovered open port 443/tcp on 188.8.131.52
Completed Connect Scan at 11:40, 4.10s elapsed (1000 total ports)
Nmap scan report for ariel.c2b2.columbia.edu (184.108.40.206)
Host is up, received syn-ack (0.014s latency).
Scanned at 2021-05-31 11:40:34 EDT for 4s
Not shown: 999 filtered ports
Reason: 999 no-responses
Some closed ports may be reported as filtered due to --defeat-rst-ratelimit
PORT    STATE SERVICE REASON
443/tcp open  https   syn-ack

Read data files from: /usr/local/bin/../share/nmap
Nmap done: 1 IP address (1 host up) scanned in 4.21 seconds

Nord VPN
Shows TCP 80,443,5060,8080 open
root@localhost# nmap -vvv --open 188.8.131.52
Starting Nmap 7.80 ( https://nmap.org ) at 2021-05-31 12:00 EDT
Initiating Ping Scan at 12:00
Scanning 22.214.171.124 [2 ports]
Completed Ping Scan at 12:00, 0.03s elapsed (1 total hosts)
Initiating Parallel DNS resolution of 1 host. at 12:00
Completed Parallel DNS resolution of 1 host. at 12:00, 0.41s elapsed
DNS resolution of 1 IPs took 0.41s. Mode: Async [#: 1, OK: 1, NX: 0, DR: 0, SF: 0, TR: 1, CN: 0]
Initiating Connect Scan at 12:00
Scanning ariel.c2b2.columbia.edu (126.96.36.199) [1000 ports]
Discovered open port 443/tcp on 22.214.171.124
Discovered open port 8080/tcp on 126.96.36.199
Discovered open port 80/tcp on 18.104.22.168
Discovered open port 5060/tcp on 188.8.131.52
Completed Connect Scan at 12:00, 4.09s elapsed (1000 total ports)
Nmap scan report for ariel.c2b2.columbia.edu (184.108.40.206)
Host is up, received syn-ack (0.028s latency).
Scanned at 2021-05-31 12:00:44 EDT for 4s
Not shown: 996 filtered ports
Reason: 996 no-responses
Some closed ports may be reported as filtered due to --defeat-rst-ratelimit
PORT     STATE SERVICE    REASON
80/tcp   open  http       syn-ack
443/tcp  open  https      syn-ack
5060/tcp open  sip        syn-ack
8080/tcp open  http-proxy syn-ack

Read data files from: /usr/local/bin/../share/nmap
Nmap done: 1 IP address (1 host up) scanned in 4.62 seconds

Comment: Could you elaborate, what exactly is this IP address, and where are you running nmap from?
Answer: I think the VPN service is proxying those connections, hence the SYN ACK.
I tested the same thing
Without VPN
nmap --version-intensity 0 -T4 -Pn -sTV 126.96.36.199 -vv -top-ports 1000
Starting Nmap 7.92 ( https://nmap.org ) at 2021-11-24 13:28 CST
NSE: Loaded 45 scripts for scanning.
Initiating Parallel DNS resolution of 1 host. at 13:28
Completed Parallel DNS resolution of 1 host. at 13:28, 0.28s elapsed
Initiating Connect Scan at 13:28
Scanning ariel.c2b2.columbia.edu (126.96.36.199) [1000 ports]
Discovered open port 995/tcp on 188.8.131.52
Discovered open port 143/tcp on 220.127.116.11
Discovered open port 110/tcp on 188.8.131.52
Discovered open port 993/tcp on 22.214.171.124
Completed Connect Scan at 13:29, 4.93s elapsed (1000 total ports)
Initiating Service scan at 13:29
Scanning 4 services on ariel.c2b2.columbia.edu (22.214.171.124)

With VPN (Nord VPN)
nmap --version-intensity 0 -T4 -Pn -sTV 18.104.22.168 -vv -top-ports 1000
Starting Nmap 7.92 ( https://nmap.org ) at 2021-11-24 15:01 CST
NSE: Loaded 45 scripts for scanning.
Initiating Parallel DNS resolution of 1 host. at 15:01
Completed Parallel DNS resolution of 1 host. at 15:01, 1.10s elapsed
Initiating Connect Scan at 15:01
Scanning ariel.c2b2.columbia.edu (126.96.36.199) [1000 ports]
Discovered open port 8080/tcp on 220.127.116.11
Discovered open port 110/tcp on 22.214.171.124
Discovered open port 80/tcp on 126.96.36.199
Discovered open port 993/tcp on 22.214.171.124
Discovered open port 443/tcp on 220.127.116.11
Discovered open port 995/tcp on 22.214.171.124
Discovered open port 143/tcp on 184.108.40.206
Discovered open port 5060/tcp on 220.127.116.11
Completed Connect Scan at 15:01, 4.83s elapsed (1000 total ports)
Initiating Service scan at 15:01
Scanning 8 services on ariel.c2b2.columbia.edu (188.8.131.52)


What is the meaning of N bit key-size

Question: I read about the Key_size in Cryptography but i don't understand exactly that what is the specific meaning of Key size?
for example in wikipedia saied:

"Triple DES has a key size of 168 bits but provides at most 112 bits
  of security, since an attack of complexity 2^112 is known"

Is this mean that if we brute force 2^112 times then we can crack all of 3DES hashes?
What is the difference between 128 bit encryption and 1024 bit encryption?
Comment: 168 bit key means DES  cipher with 168 bit
Comment: Triple DES is not a hash function so it does not generate hashes. It depends on the attack if you can simply try all 2^112 possibilities to crack the plaintext. If the plaintext is a random then you may not have anything to test the decryption result against. Finally, this question is completely off topic here as it does not specify anything to do with programming, and the quality of the answers may reflect that (and up to now probably do).
Answer: Okay. Let's take this one at a time.
Key size
In cryptography, you have three major elements.
The plaintext, the ciphertext and the key.
The key is combined with the encryption algorithm to encrypt the plaintext, and get the ciphertext. It's like the state of a function, that is:
<code> K = "This is the key".
 P = "Plaintext".
 C = Encrypt(P,K).

 // This would result in some ciphertext.
</code>
If K was not equal to "This is the key", and was equal to "This is another key", then the value of C would be different.
The keysize is the size of the key used. For example, AES256 uses a 256 bit key. That means that the key is literally 256 binary numbers long.
What is the difference between 128 bit encryption and 1024 bit encryption?
The difference is in the title. 128 bit encryption encrypts data with a 128 bit key. 1024 bit encryption encrypts with 1024 bits of data. The important thing to note here is that with 128 bits, you're usually looking at a Symmetric Key Cipher, and with 1024 bits, you're usually looking at an Asymmetric Encryption Algorithm.
Brute Force Attack
Yes. Following the AES256 example, if you perform 2^256 possible combinations of a key, you will eventually crack any and all AES256 ciphers. However, 2^256 is a massive number, and it's considered computationally unfeasible to attempt that value.
Comment: True, but OP didn't even understand the fundamental principles of encryption. Why throw in all that added detail when I'm trying to teach them the abstract principles?
Comment: So its mean the  K = "This is the key" long at most is 256 bit?
Comment: Not at most. ALWAYS. In 256 bit key encryption, the key HAS to be 256 bits long. I was just giving you an example :)
Comment: Well if it was my answer that got you there, be sure to mark it as correct :)
Comment: Is this possible to brute force the key of MD5 or MD4 ?
Comment: MD5 is whatis called a [Hashing Algorithm](http://en.wikipedia.org/wiki/Hash_function) which mean it is a one way encryption. There is no key. What you CAN do though is use a Rainbow table. [here is an example of one](http://crackstation.net/)
Comment: "There is no key" so why we said MD5 has 128 bit key-size?
Comment: MD5 has a 128 bit message digest size. Not key size. Read my link.
Comment: A key and the plain text should never be strings for modern cryptography, it is not a good idea to use strings within an example. Passwords require a password based key derivation function to turn them into keys, and plaintext should be encoded using a character encoding method.
Answer: It means that with 2112 trial encryptions, you can guarantee that you find the key that was used to encrypt something with 3DES. That, however, uses a "meet in the middle" (MITM) attack that also requires an absurd amount of memory.
Also note that 3DES only really needs 112 bits of key material. You do an encrypt/decrypt/encrypt (EDE, most common) or Decrypt/Encrypt/Decrypt (DED) cycle, but the first and last can use the same key. 168 bits means you're using a separate key for each cycle. That's fine, but not entirely necessary.
As far as what the key itself is, it's basically just a collection of bits that are known, but (by strong preference) difficult or impossible for anybody else to predict or guess. In a typical case, you don't directly use what the user has entered as a key. At the very least you run that through a cryptographic hash to get a constant-size result. Given the predictability of what user's typically enter, you often want to go a step further: generate a much more random key, and use the user's password only to allow access to that key. This means (for example) that although it may be fairly easy to recover the user's key given physical access to their computer, the data sent "over the wire" (where it's generally easier to intercept) uses a key that's much less predictable than their password itself.
A far as 128-bit vs. 1024 bit goes, the two aren't normally entirely comparable. A huge amount here depends on the difficulty of an attack. The worst case is generally a key-exhaustion attack. This basically means that you simply try every possible key until you find one that "works".
If that's the best attack known against an algorithm, then a key size around 128 bits is almost certainly adequate against almost any conceivable improvement of "conventional" technology--that is, even if we assume CPUs will continue to get a lot faster for a long time, and assume processors of tens or even hundreds of Tera-Hertz can be build, carrying out 2128 operations to exhaust the key space still remains completely impractical (like, with millions of 100 Tera-Hertz processors, you still don't finish before the heat-death of the universe).
Larger key sizes with symmetric encryption are largely intended to protect against practical quantum computers. A (working) quantum computer of sufficient capacity can carry out different types of attacks than conventional computers, and could exhaust a key space much more quickly than a conventional computer. So that's the source of things AES 256.
When you get to keys substantially larger than that, you're typically dealing with encryption like RSA, for which practical attacks are known which do not involve doing trial encryption until you find a key that "works". In the case of RSA, part of the information that needs to be publicly known can be (fairly easily) converted to a large number that's a product of two prime numbers. If you can factor that number to obtain those two primes, you can break the encryption fairly easily.
So in this case, the strength we need is based on that product being large enough that factoring it is impractical. The largest number that would be suitable to use as an RSA key that's publicly known to have been factored was 768 bits.
So, if you're interested in safety vs. a well equipped attacker, for RSA you pretty clearly need a key larger than that.
Note that the "meet in the middle" attack on 2DES, the attack on 2-key 3DES and factoring large RSA keys have some characteristics in common: that make attacking them quite different from attacking plain DES. With DES, you can easily trade off between how much you spend, and how fast you get a result. Spend (nearly) nothing, and it takes a long time to get a result, but you will eventually. The more you're willing to spend, the faster you get your result.
With the other attacks, however, you need a large amount of memory to carry out the attack at all. For these, you (mostly) can't just scale things so spending half as much gets you a result half as fast. Rather, you'd need to switch to (for example) using SSD instead of DRAM for your storage--and immediately lose a lot of speed. Alternatively, you could switch to another algorithm that's asymptotically less favorable, but doesn't have quite such a high barrier to entry. Again, for a practical attack you'll typically lose a lot very quickly this way.
Bottom line: for some attacks, you get a fairly "smooth" trade-off between time and money. With others, you get much more of a step function; in many cases, a practical attack will simply exceed most people's capacity (now and for quite a while to come, in most cases).
Comment: That would be pass phrase, there is no such thing as a key phrase. You should use a PBKDF (password based key derivation function) to turn the password input into a randomized key. Also note that 2 key triple DES has a different security margin than 3 key triple DES.
Comment: 2TDEA (3DES with K1=K3) provides 80 bits or less of effective strength, and that's not good enough. Only the 3-key version could be considered strong encryption, and that just barely.
Comment: @erickson: I'd advise that you look at how you attack 2-key 3DES. Yes, there *is* [an attack](https://crypto.stackexchange.com/a/25624/479) that (based on the block size) has a complexity *around* 2^{64}--but it also requires about 2^{60} bytes of RAM. Current worldwide DRAM production capacity is somewhere around 2^{50} bytes annually (probably a little less than that). That means (assuming Moore's law holds out) that around 10 years from now, the entire earth's production of DRAM for an entire year would be (barely) sufficient to start the attack.
Comment: @erickson: Bottom line: you're taking a *lot* for granted in saying "that's not good enough". Most people never protect anything that would justify an attack this expensive--and the few who do need to worry more about "practical cryptanalysis" (e.g., somebody kidnapping them and torturing them to get the key). That's mostly irrelevant though: the question isn't about how many bits is enough--it's about what N bits of strength *means*.
Comment: We don't know everything there is to know about cryptanalysis. Stronger encryption provides a safety margin to protect against future (or currently undisclosed) attacks. In an AES world, 80-bit encryption isn't something I want to have to defend.
Comment: @erickson: The question had nothing to do with whether 3DES is currently a good choice of encryption algorithm. It was about what "N-bit keysize" means. Nothing more and nothing less.
Answer: The wikipedia has an entry on the key size: http://en.wikipedia.org/wiki/Key_size

What is the meaning of N bit key-size


Relação One-To-Many com nome da foreign key explícito

Question: Estou realizando um mapeamento simples de one-to-many via Fluent API especificando qual é a coluna utilizada no mapeamento, porém, o EF "ignora" a configuração e continua utilizando o nome default.
Mapeamentos:
        public AtividadeMap()
        {
            HasKey(a => a.Codigo);

            ToTable("tb_atividade");

            Property(a => a.TituloAtividade).HasColumnName("titulo_atividade");
            Property(a => a.DescricaoAtividade).HasColumnName("descricao_atividade");
            Property(a => a.DataHoraInicio).HasColumnName("data_hora_inicio");
            Property(a => a.DataHoraFim).HasColumnName("data_hora_fim");
            Property(a => a.Codigo).HasColumnName("pk_atividade");
            Property(a => a.StatusAtividade.Identificador).HasColumnName("status_atividade");
            Property(a => a.EstimativaInicialAtividade).HasColumnName("estimativa_inicial_atividade");
            Property(a => a.TipoAtividade.Identificador).HasColumnName("tipo_atividade");

            HasRequired(a => a.Usuario)
           .WithMany()
           .Map(e => e.MapKey("fk_usuario"));

            HasRequired(a => a.Projeto)
           .WithMany()
           .Map(e => e.MapKey("fk_projeto"));

        }

        public ProjetoMap()
        {
            HasKey(a => a.Codigo);

            ToTable("tb_projeto");

            Property(p => p.Codigo).HasColumnName("pk_projeto");
            Property(a => a.Nome).HasColumnName("nome");
        }

Exceção:

Como observado, o SQL está realizando uma busca por CodigoProjeto e CodigoUsuario ao invés de fk_projeto e fk_usuario
Além da exceção, uma dúvida: preciso mapear este one-to-many também nas classes da agregação (Projeto e Usuario)?
Se possível, preferiria mapear apenas na classe que consome a entidade, visando o isolamento da responsabilidade apenas para esta classe.

---- EDIT : Inclusão dos models relacionados ao problema ------
    public class Atividade : ObjetoPersistente
    {
        public Atividade()
        {
            Projeto = new Projeto();
            StatusAtividade = EStatusAtividade.NaoIniciado;
            TipoAtividade = ETipoAtividade.NovaImplementacao;
            Usuario = new Usuario();
        }

        public DateTime DataHoraFim { get; set; }

        public DateTime DataHoraInicio { get; set; }

        public string DescricaoAtividade { get; set; }
        public string EstimativaInicialAtividade { get; set; }
        public Projeto Projeto { get; set; }

        public long CodigoProjeto
        {
            get
            {
                return Projeto.Codigo;
            }
            set
            {
                Projeto.Codigo = value;
            }
        }

        public string NomeProjeto
        {
            get { return Projeto.Nome; }
        }

        public Usuario Usuario { get; set; }

        public string LoginUsuario
        {
            get { return Usuario.Login; }
        }

        public long CodigoUsuario
        {
            get
            {
                if(Usuario == null) Usuario = new Usuario();
                return Usuario.Codigo;
            }
            set
            {
                Usuario.Codigo = value;
            }
        }

        public EStatusAtividade StatusAtividade { get; set; }

        public string DescricaoStatusAtividade
        {
            get { return StatusAtividade.Descricao; }
        }

        public string DescricaoTipoAtividade
        {
            get { return TipoAtividade.Descricao; }
        }

        public ETipoAtividade TipoAtividade { get; set; }
        public string TituloAtividade { get; set; }

        public override bool Equals(object obj)
        {
            return (obj is Atividade) && (obj as Atividade).Codigo.Equals(Codigo);
        }

        public override int GetHashCode()
        {
            return Codigo.GetHashCode();
        }
    }

    public class Projeto : ObjetoPersistente, IObjetoElementoOption
    {
        public string Nome { get; set; }

        public override bool Equals(object obj)
        {
            return (obj is Projeto) && (obj as Projeto).Codigo.Equals(Codigo);
        }

        public override int GetHashCode()
        {
            return Codigo.GetHashCode();
        }

        public string Valor
        {
            get { return Codigo.ToString(); }
        }

        public string Descricao
        {
            get { return Nome; }
        }
    }

    public class Usuario : ObjetoPersistente
    {
        public string Login { get; set; }
        public string Senha { get; set; }

        public override bool Equals(object obj)
        {
            return (obj is Usuario) && (obj as Usuario).Codigo.Equals(Codigo);
        }

        public override int GetHashCode()
        {
            return Codigo.GetHashCode();
        }
    }

    [Serializable]
    public abstract class ObjetoPersistente : IObjetoPersistente
    {
        public long Codigo { get; set; }

        public override bool Equals(object obj)
        {
            return (obj is ObjetoPersistente) && (obj as ObjetoPersistente).Codigo.Equals(Codigo);
        }

        public override int GetHashCode()
        {
            return Codigo.GetHashCode();
        }

        ///
        /// Obtêm lista de longos a partir dos códigos dos objetos persistentes.
        ///
        /// <param name="lista"></param>
        /// <returns></returns>
        public static List<long> ObtenhaListaDeCodigosPorListaDeObjetos<T>(List<T> lista) where T:ObjetoPersistente
        {
            var listaLongo = new List<long>();

            foreach (var objetoPersistente in lista)
            {
                listaLongo.Add(objetoPersistente.Codigo);
            }

            return listaLongo;
        }

        ///
        /// Obtêm lista de objetos do tipo genérico a partir de lista de códigos
        ///
        /// <typeparam name="T"></typeparam>
        /// <param name="listaDeCodigos"></param>
        /// <returns></returns>
        public static List<T> ObtenhaListaDeObjetoPorListaDeCodigos<T>(List<long> listaDeCodigos) where T  : ObjetoPersistente
        {
            var listaObjeto = new List<T>();

            foreach (var codigo in listaDeCodigos)
            {
                var objeto = Activator.CreateInstance<T>();
                objeto.Codigo = codigo;

                listaObjeto.Add(objeto);
            }

            return listaObjeto;
        }

        ///
        /// Obtêm objetos persistentes da lista que possuem a propriedade Código equivalente a 0.
        ///
        /// <typeparam name="T"></typeparam>
        /// <param name="objetos"></param>
        /// <returns></returns>
        public static List<T> ObtenhaObjetosComCodigoZerado<T>(List<T> objetos) where T : ObjetoPersistente
        {
            var resultado = new List<T>();

            foreach (var objeto in objetos)
            {
                if(objeto.Codigo.Equals(0))
                    resultado.Add(objeto);
            }

            return resultado;
        }

        ///
        /// Obtêm objetos persistentes da lista que possuem a propriedade Código diferente de 0.
        ///
        /// <typeparam name="T"></typeparam>
        /// <param name="objetos"></param>
        /// <returns></returns>
        public static List<T> ObtenhaObjetosComCodigoDiferenteDeZero<T>(List<T> objetos) where T : ObjetoPersistente
        {
            var resultado = new List<T>();

            foreach (var objeto in objetos)
            {
                if (!objeto.Codigo.Equals(0))
                    resultado.Add(objeto);
            }

            return resultado;
        }

        ///
        /// Compara duas listas de objetos persistentes
        ///
        /// <typeparam name="T"></typeparam>
        /// <param name="listaBase"></param>
        /// <param name="listaAnalisada"></param>
        /// <returns>Os objetos persistentes da 'listaAnalisada' que não existem na 'listaBase'</returns>
        public static List<T> ObtenhaDiferenteEntreListas<T>(List<T> listaBase, List<T> listaAnalisada)
            where T : ObjetoPersistente
        {
            var resultado = new List<T>();

            foreach (var objetoPersistente in listaAnalisada)
            {
                if(!listaBase.Contains(objetoPersistente))
                    resultado.Add(objetoPersistente);
            }

            return resultado;
        }
    }

---- EDIT2 : Detalhes sobre o momento em que a exception é disparada ----
A exception ocorre no momento que realizo um 'find' no DbSet:
_dbContext.Set<Atividade>.Find(codigoItem);

O SQL que o EF produziu foi este:
SELECT "Alias1"."status_atividade", "Alias1"."pk_atividade", "Alias1"."data_hora_fim", "Alias1"."data_hora_inicio", "Alias1"."descricao_atividade", "Alias1"."estimativa_inicial_atividade", "Alias1"."CodigoProjeto", "Alias1"."CodigoUsuario", "Alias1"."tipo_atividade", "Alias1"."titulo_atividade", "Alias1"."fk_projeto", "Alias1"."fk_usuario" FROM (SELECT "Extent1"."pk_atividade", "Extent1"."data_hora_fim", "Extent1"."data_hora_inicio", "Extent1"."descricao_atividade", "Extent1"."estimativa_inicial_atividade", "Extent1"."CodigoProjeto", "Extent1"."CodigoUsuario", "Extent1"."status_atividade", "Extent1"."tipo_atividade", "Extent1"."titulo_atividade", "Extent1"."fk_projeto", "Extent1"."fk_usuario" FROM "public"."tb_atividade" AS "Extent1" WHERE "Extent1"."pk_atividade" = ((4)) LIMIT 2) AS "Alias1"

A mensagem da exceção:
ERROR: 42703: column Extent1.CodigoProjeto does not exist

PS: Estou utilizando PostgreSQL.
Comment: Eu queria entender por que você faz questão de mudar os nomes das colunas no banco.
Comment: Existe um padrão de nomenclatura para o banco de dados, e estou trabalhando com migração de um sistema que já está em produção com ADO.NET (sql puro).
Comment: Não usar *Fluent API* é uma opção?
Comment: Não é viável. Como é uma migração, fica mais simples isolar o código que tem essa responsabilidade. Não é viável carregar os modelos com mais anotações.
Comment: Mas pq não usar Fluent API ? Ele não pode resolver essa particularide?
Comment: Pode, mas não resolve alguns casos muito bem. Vou pensar em uma resposta. Preciso dos *Models* no corpo da pergunta.
Comment: Pronto, foram incluídos. Desconsidere as propriedades de acesso, não estão sendo utilizadas (pontes para Projeto.Codigo, por exemplo). Poderia explicar mais sobre 'mas não resolve alguns casos muito bem' ? Quais são as situações?
Comment: Situações de associação direta, associação indireta, mapeamentos e nomes, enfim. Seus *Models* estão bastante fora do padrão do Entity Framework, então a chance de não funcionar é bem grande. Qual o comando usado para executar a *query* que levanta `Exception`?
Comment: Bem, estou fazendo provas de conceito em relação ao EF, para concluir sobre a viabilidade ou não de sua utilização neste projeto. Meu objetivo é utilizar um framework ORM a priore. Terei modelos das mais diversas formas possíveis, com estratégias de polimorfirsmo (interfaces) por exemplo. Estou incluindo oq você solicitou à pergunta.
Answer: Vamos começar pelo SQL gerado:
SELECT "Alias1"."status_atividade", "Alias1"."pk_atividade",
"Alias1"."data_hora_fim", "Alias1"."data_hora_inicio",
"Alias1"."descricao_atividade", "Alias1"."estimativa_inicial_atividade",
"Alias1"."CodigoProjeto", "Alias1"."CodigoUsuario",
"Alias1"."tipo_atividade", "Alias1"."titulo_atividade",
"Alias1"."fk_projeto", "Alias1"."fk_usuario" FROM
    (SELECT "Extent1"."pk_atividade", "Extent1"."data_hora_fim",
    "Extent1"."data_hora_inicio", "Extent1"."descricao_atividade",
    "Extent1"."estimativa_inicial_atividade", "Extent1"."CodigoProjeto",
    "Extent1"."CodigoUsuario", "Extent1"."status_atividade",
    "Extent1"."tipo_atividade", "Extent1"."titulo_atividade",
    "Extent1"."fk_projeto", "Extent1"."fk_usuario"
    FROM "public"."tb_atividade" AS "Extent1"
    WHERE "Extent1"."pk_atividade" = ((4)) LIMIT 2) AS "Alias1"

Repare que em nenhum momento você referencia CodigoProjeto e CodigoUsuario aqui:
    public AtividadeMap()
    {
        HasKey(a => a.Codigo);

        ToTable("tb_atividade");

        Property(a => a.TituloAtividade).HasColumnName("titulo_atividade");
        Property(a => a.DescricaoAtividade).HasColumnName("descricao_atividade");
        Property(a => a.DataHoraInicio).HasColumnName("data_hora_inicio");
        Property(a => a.DataHoraFim).HasColumnName("data_hora_fim");
        Property(a => a.Codigo).HasColumnName("pk_atividade");
        Property(a => a.StatusAtividade.Identificador).HasColumnName("status_atividade");
        Property(a => a.EstimativaInicialAtividade).HasColumnName("estimativa_inicial_atividade");
        Property(a => a.TipoAtividade.Identificador).HasColumnName("tipo_atividade");

        HasRequired(a => a.Usuario)
       .WithMany()
       .Map(e => e.MapKey("fk_usuario"));

        HasRequired(a => a.Projeto)
       .WithMany()
       .Map(e => e.MapKey("fk_projeto"));

    }

Obviamente não vai funcionar. Como as duas propriedades não fazem parte da consulta (porque não são campos de dados, e sim, propriedades de navegação que você mesmo definiu), você precisa marcar essas propriedades com [NotMapped] para retirar as colunas da consulta.
    [NotMapped]
    public long CodigoProjeto {
        get
        {
            return Projeto.Codigo;
        }
        set
        {
            Projeto.Codigo = value;
        }
    }

    [NotMapped]
    public long CodigoUsuario {
        get
        {
            if(Usuario == null) Usuario = new Usuario();
            return Usuario.Codigo;
        }
        set
        {
            Usuario.Codigo = value;
        }
    }

Comment: Irei fazer a modificação Cigano, mas dai lhe pergunto, o mapeamento no Fluent-API não tem o objetivo de explicitar quais propriedades estou trabalhando no contexto de persistência? Faltou eu definir alguma configuração no meu DBContext para orientá-lo a utilizar apenas o que está mapeado?
Comment: Realmente não analisei a fundo o SQL gerado, ele está gerando o fk_usuario e fk_projeto perfeitamente, mas está gerando também o 'CodigoUsuario' e 'CodigoProjeto'. É exatamente isso. Preciso definir então uma configuração que diga ao EF  que, só quero que ele trabalhe com o que está mapeado na classe de EntityTypeConfiguration? Irei pesquisar agora. Porque como citei, estou em processo de migração, com os modelos já implementados. Definir as propriedades que não devem ser mapeadas, uma a uma, será um retrocesso. Também posso ignorar todas as propriedades via reflexão, mas ficaria ruim.
Comment: @JoaquimMagalhães O mapeamento mais recomendado, aí falando por experiência, é o de atributos, em que você decora as propriedades do *Model* em questão. O `[NotMapped]` é um bom exemplo disso. Usar a *Fluent API* pra configurar tudo se torna um tanto prolixo num estágio mais avançado de desenvolvimento. No seu caso, as configurações já estão definidas de acordo, e o que ocorre é que o SQL gerado é um comportamento padrão do Entity Framework: ele deduz que cada propriedade existe em banco, sem necessariamente conferir a implementação delas. Você chegou a testar conforme a resposta?
Comment: Sim, funcionou. Porém fiquei decepcionado pelo fato de que, como já estou explicitando *cada* propriedade, esperasse que o EF não 'tomasse decisões por conta própria'.
Comment: Estou esperando apenas uma resposta sobre o contexto da pergunta para concluí-la: Existe uma propriedade que defina que o EF **utilize apenas as propriedades mapeadas na minha classe de configuração EntityTypeConfiguration**?
Comment: Sobre utilizar FluentAPI ou anotações, bem, acho que teria que te passar bastante detalhes sobre o projeto e iria estender bastante o assunto, talvez fugir do contexto desta pergunta. Me parece que existe um recurso de CHAT , caso esteja interessado posso lhe descrever por lá.
Comment: @JoaquimMagalhães http://chat.stackexchange.com/rooms/25342/c-asp-net-asp-net-mvc-entity-framework-etc


JS function to undo

Question:   (function() {
tinymce.create('tinymce.plugins.custom', {
    init : function(ed, url) {
        ed.addButton('custom', {
            title : 'custom',
            text: 'custom',
            icon: false,
            onclick: function() {
                ed.focus();
                ed.selection.setContent('
' + ed.selection.getContent() + '
');
            }
        });
    },
    createControl : function(n, cm) {
        return null;
    },
});
tinymce.PluginManager.add('custom', tinymce.plugins.custom);
})();

I've added a button to TinyMCE using the above JS code.
So, when user clicks the button, it wraps any highlighted words into  tags.
My question is, how do I make it so that if the highlighted words are already in  tag, then it should remove the tag?
Answer: Keep an array store of tags, remove the tag if found in array, push to array if not
var tags = [];

...

onclick: function() {
    var content = ed.selection.getContent();
    var index = tags.indexOf(content);
    ed.focus();

    if (index === -1) {
        ed.selection.setContent('
' + content + '
');
        tags.push(content);
    } else {
        ed.selection.setContent(content);
        tags.splice(index, 1);
    }
}

Comment: I have to remove the class "custom" if I click the button again. It doesn't do that now

JS function to undo