Image style URL from theme path

Question: I am trying to generate a URL for an image style, generated from an image in my theme directory:
$image_uri = drupal_get_path('theme', 'mytheme') . '/images/banners/projects-banner.jpg';
$banner_file = file_build_uri($image_uri);
$banner_url = image_style_url('my_image_style', $banner_file);

The $banner_url looks to be correct, however when I browse to it directly, I get a general Drupal error.
http://www.mysite.local/sites/default/files/styles/my_image_style/public/sites/all/themes/mytheme/images/banners/projects-banner.jpg

I had tried to pass $image_uri into image_style_url, but understand this need a URI and not a path. Can someone please point me in the right direction.
Comment: Something is amiss with your image file path. You don't usually see sites/default/files and sites/all/themes in the same URL. It looks like it's building the URL after the base URL for images in general instead of using the base URL for your installation. I'm not sure why.
Comment: The first part of the URL is correct (http://www.mysite.local/sites/default/files/styles/my_image_style/) as all other image styles work with that (if the images are from content type fields) . I think the issue is because I'm using a path for an image that isn't stored in the managed files table - basically an image field for the content type.
Answer: You're right, the image_style_* functions only work with files in the managed file system. You can get round it by using the imagecache_external module, though, which takes remote images and stores them where we need them.
It might seem a little strange to be requesting local images as if they were remote, but this ensures the integrity of the image_style system without further hackery.
$image_uri = drupal_get_path('theme', 'mytheme') . '/images/banners/projects-banner.jpg';

$absolute_image_url = url($image_uri, array('absolute' => TRUE));
$banner_file = imagecache_external_generate_path($absolute_image_url);

$banner_url = image_style_url('my_image_style', $banner_file);

Image style URL from theme path


É um padrão os endereços SMTP do provedores de e-mail serem no padrão: smtp.provedor.com?

Question:
Pode existir algum provedor de e-mail que utilize um endereço SMTP que não inicie com smtp.?
Ou existe alguma regra que não permite que sejam configurados servidores SMTP fora desse padrão.

Pois estou implementando um configurador de emails em meu projeto que permite que o usuário informe o endereço SMTP do provedor na mão por completo, sem nenhum tipo de validação na entrada do mesmo.

Então gostaria de saber se posso criar algum tipo de pré-configuração, ou bloqueio que previna que o usuário entre com algo totalmente absurdo.

Pois fazendo alguns testes aqui com a biblioteca JavaMail (em uma versão um pouco mais lite, pois minha implementação é em android) fazendo tentativas de envio de e-mail utilizando um host do tipo: gshshd.gdhfj.com,  ele demora cerca de 3 minutos para retornar a Exception para minha aplicação, o que não é uma boa experiência para o usuário. Já se tento em um host do tipo: smtp.gfdga.com, ele retorna a Exception quase que instantaneamente para minha aplicação.

Gostaria de talvez nem permitir host que não iniciam com smtp., se isso for uma regra.
Answer: Sim, podem existir servidores de email que não utilizam smtp. como prefixo - mail. sendo um dos mais utilizados.
Se você deseja saber qual é o nome do servidor de email de um dado domínio, consulte o registro MX do mesmo. O seguinte código Java (utilizando dnsJava) pode lhe obter essa informação:
private Record[] lookupMxRecords(final String domainPart) throw TextParseException
{
    final Lookup dnsLookup = new Lookup(domainPart, Type.MX);
    return dnsLookup.run();
}

Comment: então em meu caso não posso fazer uma validação e nem restrição na entrada do usuário. O que posso tentar é verificar antes no **MX** conforme você citou.
Comment: Mais existe um padrão, mesmo que seja: `smtp.` ou `.mail`, ou pode ser qualquer coisa, igual no exemplo que citei na pergunta?
Comment: Um padrão por uso, talvez - `smtp`, `mail` e similares são um exemplo. Padrão por especificação, não: um servidor chamado `patolino.looneytunes.com` pode ser uma entrada válida.
Answer: Eu creio que não seja um padrão, apenas uma prática convencional. Na RFC974 não impõe essa restrição enquanto ao endereço. :)
Answer: O nome do subdomínio ou host é indiferente.
Apenas atente-se de configurar na zona DNS adequadamente como uma zona MX.


Elements Not Sliding Back Upon Window Change

Question: I'm using an HTML/CSS template to create a web app. For some reason the elements are not sliding back on the template when I resize the window which I need them to do. For example, if I float a button on the right it would position itself to the leftmost portion of the full screen. If I then contract the window horizontally the button does not move back but is simply 'hidden by the window'. I've been looking at the template CSS code for days now and googling everywhere but I still don't know what's causing this.

Here is the CSS code for the template:
<code>body, html {
    padding:0;
    margin:0;
    font-family: BBAlpha Sans;
    font-size: 15pt;
    overflow:visible;
}

body {
    background-image: url('../images/stripes.png');
    overflow:hidden;
}

.listSeparator
{
    border-bottom: solid 1px Silver;
}

.label
{
    display:inline;
    float:left;
    line-height:40px;
    margin-left: 5px;
}

.row
{
    height: 40px;
    width:100%;
    vertical-align: middle;
}

.tab
{
    position:absolute;
    top:70px;
    padding: 10px;
}

.main-panel
{
    position:relative;
}

.panel-top-left {
    margin-right: 4px;
    height: 4px;
    background-image: url('../images/panel.png');
}
.panel-top-right {
    margin-top: -4px;
    margin-left: 4px;
    background-position: 100% 0;
    height: 4px;
    font-size: 2px;
    background-image: url('../images/panel.png');
}
.panel-bottom-left {
    margin-right: 9px;
    background-position: 0 -7px;
    height: 9px;
    font-size: 2px;
    background-image: url('../images/panel.png');
}
.panel-bottom-right {
    margin-top: -9px;
    margin-left: 9px;
    background-position: 100% -7px;
    height: 9px;
    font-size: 2px;
    background-image: url('../images/panel.png');
}
.panel-inside {
    border-left: 2px solid #D6D3D6;
    border-right: 2px solid #D6D3D6;
    background: White;
    padding-left: 0px;
    padding-right: 0px;
    overflow:auto;
}
.panel-nogap {
    margin-top: -3;
    margin-bottom: -3;
}

.panel-nogap input
{
    display:inline;
    float:left;
    font-family: BBAlpha Sans;
    font-size: 16pt;
    border: none;
    padding-top: 0px;
    width: 10px;
    margin-top: 7px;
}

.buttonPanel
{
    margin-top: 5px;
    margin-left: 8px;
    margin-bottom: 0px;
    text-align:center;
    position:relative;

}

a.tabButton {
    background: transparent url('../images/tabs/tabRight.png') no-repeat scroll top right;
    color: White;
    display: block;
    float: left;
    height: 64px;
    margin-right: 5px;
    padding-right: 10px;
    text-decoration: none;
    width: 28%;
}

a.tabButton div {
    background: url('../images/tabs/tab.png') no-repeat top left;
    display: block;
    height: 64px;
    padding: 0px 0px 0px 10px;
    line-height: 0px;
}

a.tabButton p
{
    font-size: 10pt;
    margin-top: 0px;
    padding: 0px;
}

a.tabButton img
{
    position:relative;
    height:35px;
    width:35px;
    margin-top: 5px;
    margin-bottom: 0px;
    padding: 0px;
}

.tabSeparator
{
    position: absolute;
    top:69px;
    background-color:#014EBE;
    height:5px;
    width: 100%;
    z-index: -1;
}
</code>
and what the template looks like:

If anyone knows what is causing this or at least what I should look for, any help at all would be appreciated. Thanks in advance!
Answer: How about changing the position properties... fixed would be your best bet: positioning it fixed @ 5em from the browser sides or something:
http://www.w3schools.com/cssref/pr_class_position.asp
play around on w3schools, it's a great site :)
Comment: I can`t do that because the screen dimensions are different for every blackberry device (platform I`m developing on), so moving 400px over will have it centered on one blackberry and skewed way to the left on another.
Comment: that's why I suggested __em__ units, not pixels or percentages. em is calculated by each device based on current font size: 1em === width/height of 1 character. However, I'm not an expert when it comes to mobile device design/development...
Comment: Hey sorry I got a bit confused with the em. I see what you mean now, I`ll give it a shot.
Comment: :) Wasn't trying to bash you... sorry if I came across a bit blunt. using bold markup does that sometimes. Hope my suggestion helped, would like to know if it did
Comment: Just another thought: have you tried using: `float:right; clear:right; margin-right: 2em;`? that should make it position relative to the navigator's window, I think. (not tested, just popped into my head)


Should we explain accepted answers?

Question: I posted this question on the economics.stack and I am wondering if I should explain the answer I am gonna accept. I see this as a good practice but I would like to know about your views.
Furthermore, I don't where to explain my choice. Should I do it as a comment? Or should I update my question with a specific mention?
Let me justify why I want to explain my accepted answer.

All answers are interesting and upvoted.
The most upvoted answer (the one by @Andras at this point in time) is a good one by reminding us the importance of sunk costs and the fact that the decision should be a forward-looking one. This answer also attracted very good comments. However, sunk costs are a favorite subject of economists and I was aware of the sunk cost fallacy. By the way, not all investment costs are sunk.
@luchonacho's answer on the discrete choice literature is promising and well documented.
@Ubiquitous' answer is my favorite one. I didn't know about optimal stopping problems. This answer is original, very promising, with great academic references.
Answer: I don't see any harm in posting a justification for your acceptance in the comments or by adding an edit to the end of your question. Adding a justification is useful information to other users about the kinds of answers people are looking for on this site. Comments can sometimes get messy of course. If it is a comment heavy section, it could get lost. I might go with editing your question first, but personally do not have a problem with either editing/commenting.
Answer: I would not edit the question. It might be confusing, and (fallacy) I have not seen this done elsewhere (other SE).
I would not add a comment either. In the end, the idea is to leave Q&A sites neat, without comments. But that is my understanding of neat Q&A site (I'm constantly flagging comments like "thank you blabla" to be deleted). Others might have a different opinion on the matter.
Comment: @denesp Did we? Can't remember :o
Comment: "leave Q&A sites neat, without comments"
...didn't we trade jokes in [comments](https://economics.stackexchange.com/questions/18263/von-neumann-morgenstern-utility-function-help) just yesterday...?

Should we explain accepted answers?


Using the image.palette property

Question: There seems to be quite the lack of documentation, at least that I could find, on how to use the image.palette property within Visual Basic.
This is something completely new to me, can anybody point me in the right direction? :)
Answer: You are correct, the documentation is very little for this category, Exhibit A
Like all great things, I recommend browsing YouTube for some more detailed walkthroughs on simple concepts such as this. Here and Here
Comment: Glad that I could help!

Using the image.palette property


Can't type in textarea when displayed

Question: import React, { useState } from 'react'

const FormBox = () => {

  const [name, setName] = useState("")
  const [textArea, setTextArea] = useState('')

  const handleSumbit = (e) =>{
    e.preventDefault();
    console.log(name)

  }

  return (
    <form onSubmit={handleSumbit}>
      Enter your name:
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />

      <textarea value={textArea} onChange={handleSumbit}></textarea>
      <input type="submit" />
    </form>
  )
  }

When the text box is displayed I cannot type in it.
What am I doing wrong...?
Answer: Shouldn't the onChange={handleSumbit} of the textarea be
onChange={(e) => setTextArea(e.target.value)}

Answer: import React, { useState } from 'react'

const FormBox = () => {

  const [name, setName] = useState("")
  const [textArea, setTextArea] = useState('')

  const handleSumbit = (e) =>{
    e.preventDefault();
    console.log(name)
  }

  return (

    <form onSubmit={handleSumbit}>
      Enter your name:
        <input
          type="text"
          value={name}
          onChange={(e) => setTextArea(e.target.value)}
        />

      <textarea value={textArea} onChange={handleSumbit}></textarea>
      <input type="submit" />
    </form>
  )
  }

Answer: import React, { useState } from 'react'

const FormBox = () => {

  const [name, setName] = useState('')
  const [textArea, setTextArea] = useState('')

  const handleSumbit = (e) =>{
    e.preventDefault();
    console.log(name)

  }

  return (
    <form onSubmit={handleSumbit}>
      Enter your name:
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />

      <textarea value={textArea} onChange={(e) => setTextArea(e.target.value)}></textarea>
      <input type="submit" />
    </form>
  )
  }

The textarea is a controlled input - if you are going to tie the value of the <textarea> to the textArea state variable, you need to update that state variable whenever the user changes the input.
Answer: Firstly
You implicitly set the value of your text area using the textArea variable which has an initial state of "" (an empty string).
React automatically refreshes the real DOM from the virtual DOM after every change in state. But the value of your textArea variable doesn't change with this event, so you have to update the state when a value is entered like this:
onChange={(e) => setTextArea(e.target.value)}

After reading your code, I guessed what you wanted to achieve is to prevent the submit button from submitting the form by default and instead logs the name on the console.
I believe this is the code you wanted to achieve:
import React, { useState } from 'react'

const FormBox = () => {

const [name, setName] = useState('')
const [textArea, setTextArea] = useState('')

const handleSumbit = (e) =>{
    e.preventDefault();
    console.log(name)
}

return (
    <form onSubmit={handleSumbit}>
    Enter your name:
        <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
    />

    <textarea value={textArea} onChange={(e) => setTextArea(e.target.value)}></textarea>
    <input type="submit" />
    </form>
)

Answer: You can't type here the event not written by you properly,  so, you state textarea not updated yet. just needed to change one as a similar name textbox. just replace
<textarea value={textArea} onChange={handleSumbit}></textarea>
to
<textarea value={textArea} onChange={(e) => setTextArea(e.target.value)}></textarea>
Full code here edited,
import React, { useState } from 'react'

const FormBox = () => {

const [name, setName] = useState('')
const [textArea, setTextArea] = useState('')

const handleSumbit = (e) =>{
    e.preventDefault();
   //  console here form data
}

return (
    <form onSubmit={(e)=>handleSumbit(e)}>
    Enter your name:
        <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
    />

    <textarea value={textArea} onChange={(e) => setTextArea(e.target.value)}></textarea>
    <input type="submit" value="Submit now!" />
    </form>
)

I Hope, work fine using this code
Thanks

Can't type in textarea when displayed


Configuration for multiple port SSH

Question: I need to listen to SSH on two ports: 22 for hosting admin access and 26 for regular access. I would like to disallow root login on 26 and disallow all but internal IPs for port 22. The latter can be done with iptables rules, but I don't know about the former. Any ideas?
Comment: It's entirely okay to allow root logins over ssh if you restrict them to key authentication, or even password authentication if the session is restricted to IP addresses you control.  'Never' is too strong.
Comment: root should never be able to login via ssh; period; end of story; buck stops here; never. If you need root access then you login via your normal user, then elevate with `su` or better yet `sudo`.
Comment: I'd argue that there are situations where it makes sense to have a root login (e.g. Filesystem corruption on the /home partition, precluding login as a standard user). One thing that can help is to set the sshd_config `PermitRootLogin` parameter to `without-password`. This only allows root login via ssh to occur with an ssh key. Password authentication will not work.
Comment: This article might be helpful:
http://everythingsysadmin.com/2010/09/the-most-simple-ssh-backdoor-i.html
Answer: In /etc/ssh/sshd_config, make the following change. Look for the line that says Port 22 and add a similar line under it.
Port 22
Port 26

Save the file and restart the sshd daemon.
I do this in situations where I have ssh enabled for internal users on port 22, but require external connectivity on say, port 2222. This binds the ssh daemon to both port numbers.
Comment: And how do you restrict root logins to port 22 now?
Comment: Before restarting ssh use test mode `sshd -t` to [check for any errors](https://www.cyberciti.biz/tips/checking-openssh-sshd-configuration-syntax-errors.html).
@faker use `PermitRootLogin prohibit-password` (less-ambiguous synonym of 'without-password')
Comment: @faker I've seen the use of firewall/network restrictions to only provide a whitelist of ip's access to regular port 22.
Answer: You can use the -f option to sshd to specify an alternate configuration file. In the configuration file you would need to use the
Port 26

directive to change the port that the sshd is listening on.
set
PermitRootLogin no

to disable root logins
You can then do  something like
/usr/sbin/sshd -f /etc/ssh/sshd_config_port_26

You may want to copy the standard sshd startup script and modify them so that you can start the port 26 service at startup.
Why are you doing this ?
Comment: Instead of having two whole configuration files, if you wanted the servers to be otherwise essentially similar, wouldn't it be more straightforward and appropriate to just add `-o PermitRootLogin yes -p 26`
Comment: this is really a great way if you want to have an `internal` and `external` configuration, thanks
Answer: With a single sshd service, you could also set up your /etc/ssh/sshd_config file as follows:
First, make sure listening on both ports:
Port 22
Port 26

Second, use the Match keyword to change configuration depending on the port connecting on:
Match LocalPort 22
    PermitRootLogin yes

Match LocalPort 26
    PermitRootLogin no

Note:  Match sections are typically placed at the end of /etc/ssh/sshd_config files as they override everything that comes before.
Answer: Assuming sshd will run with a command-line specific config file, then you could create a second config that runs on port 26 and execute a second start-up script that refers to that port.

Configuration for multiple port SSH


Prove that $F$ is continuous function of $t$

Question: Let $p$ and $q$ be conjugate indices and let $f\in L^p(\mathbb R)$ and $g\in L^q(\mathbb R)$. Prove that $F(t)=\int f(x+t)g(x)dx$ is a continuous function of $t$.
My attempt: For any $h \in \mathbb R$, $$|F(t+h)-F(t)|\le \int|f(x+t+h)-f(x+t)||g(x)|dx $$
$$\le \left(\int|f(x+t+h)-f(x+t)|^pdx \right)^{1/p}\left(\int|g(x)|^q dx\right)^{1/q}$$ by Holder's inequality. However, I have no idea how to prove that $ \int|f(x+t+h)-f(x+t)|^pdx=\int|f(x+h)-f(x)|^pdx$ goes to $0$ as $h\to 0$. Does anyone have ideas? I appreciate your help!
Answer: Let $\tau_h\colon\mathbb L^p\to\mathbb L^p$ be defined by $\tau_h\left(f\right)(x)=f\left(x+h\right)$. We have to show that $\left\lVert \tau_h(f)-f\right\rVert_p$ goes as $h$ goes to zero, which is done here.


CentOS How Much SWAP for 16GB of RAM?

Question: How much SWAP would you give a CentOS install on a dual Quad Core XEON with 16GB of RAM that is going to be running a php website with a mysql backend - medium/heavy load?
Answer: Not more than a gig or two -- you want a little bit of swap available, just in case and because it helps things work a bit better, but if you ever get to the point where you're heavily swapping, the machine is going to be useless -- and in a real catastrophic situation, you're actually better off with a smaller swap space, because then you'll trigger the OOM killer sooner rather than later.
Comment: And remember that you can always add more swap space later if it is needed by making some space and creating a new volume (if using LVM) or using a file as swap with something like `dd if=/dev/zero of=swap.file bs=1024 count=1048576; mkswap swap.file; swapon swap.file`
Comment: As a side note, you can control the degree of swapping by adjusting the /proc/sys/vm/swappiness value.
Comment: I'm gonna have to disagree with a few points here. . . First, disk is cheap, you might as well throw a couple of GB at it.  Secondly, OOM killer can take down your whole box if you get unlucky.  Relying on it in *any* way or considering it better to trigger the OOM killer is a Very Bad Idea.  Thinking that a potentially hosed box is better than a potential slowdown is also a bad idea.  The only time that would be reasonable is if you had a very specific setup planned around that situation.
Comment: side note, its generally preferable to set swap to a partition and not a file to avoid overheads and simplify the boot process. however using a file will work. 4GB is all any system should need, i doubt you will get much swapped anyway with 16gb of RAM
Comment: Actually according to Andrew Morton, the performance should be about the same between a swapfile and partition https://lkml.org/lkml/2005/6/29/11
Answer: I apologize for the very long answer. I've been wanting to put this stuff somewhere accessible for a while!
TLDR; Theoretically speaking, the answer would be "probably no less than the total amount of resident memory all your applications want to use"
I'll try to explain if you stay with me..
A bit about virtual memory
I feel there is a common misconception these days about what the value of swap is and what its purpose is for. It is often considered that swap is meant as a 'reserve bank' for memory when your running low on memory. Yes, this is partly true, but the kernel doesnt want to use your swap as a reserve bank. Additionally the kernel never wants to invoke the disk to get the data you are after!
In application space, theres a number of things the kernel will be keeping in memory.

Mapped file data.
tmpfs filesystems.
Raw application memory allocated at runtime.
Application code (such as stuff in the data segment of ELF formats)
Privately mmaped file data.

For the purpose of memory management, memory allocation is backed in some form or another by a supporting device.
File backed memory is memory which has come from a file and on a typical O/S makes up the vast majority of memory allocation on the system. It includes files such as shared libraries which have been loaded, files read from disk and stored in the page cache and files mmaped from disk (in fact, the kernel makes no distinction of pages between files in the page cache and files mmapped as its essentially the same thing).
The great thing about this memory from the kernels standpoint is its disposable, that is it should be possible to dump these pages if you need the memory for something else and this is exactly what the page cache does if memory suddenly is a requirement.
Anonymously backed memory is a different matter. Memory from this region is anonymous because, well there is no file on disk which actually contains this data. This is normally made up of the application stack, the heap, anything in tmpfs and mmapped data which is private and has been modified (since it cant sync this stuff back to disk). Since theres just no valid file on the filesystem to write these pages back to if they change, anonymously backed memory is backed by the swap media.
Now, the kernel knows that when memory is scarce, its far far cheaper to ditch file backed memory the anonymously mapped memory, thats because anonymous data has a much higher chance of being "dirty" than file backed data, in fact by default the kernel rates anonymously backed memory as being 80 times more valuable than file backed memory and this is actually what the swappiness modifier does on linux (see this post here if you want to know what exactly the swappiness parameter is altering).
The worst case scenario
The worst case scenario when it comes to a server going out of control and OOMing is based off of the fact that it spends far too much time handling I/O requests than honouring memory allocation requests. There are two conditions which can invoke this criteria.

Swapping anonymous memory around all the time to fetch pages in demand, or allocate more pages for an application.
Spending too much time fetching data from disk because its not in memory than you give to execute processes wanting CPU time.

The first one, is the commonly thought of problem. That is, since so much of the memory lives inside of swap, one needs to swap anonymous memory out of RAM, put it back into swap, then take something from swap and put it into real RAM. This operation is very expensive, slowing down the machine to the point where it can become an unrecoverable situation (as more stuff is queueing for page demands than what can be served from I/O).
The second one is less considered but just as important. If you allocate almost all your memory to real application data - you wont last long. Nearly every application relies on reading files from the filesystem to operate, this could be because some instructions live in a shared library or because you need to read /etc/resolv.conf for a library call, or any other purpose. Its entirely plausible to halt an operating system - yet have enough memory to fit all your applications, but since your queueing so much I/O requests up nothing has a chance to complete properly.
What the kernel wants to do with your swap
The kernel wants to use your swap to get rid of pages that are wasting memory so it can use that memory for something else.
Basically, in normal operation, the kernel loves to aggressively fill up page cache with data read from disk, this means it wont read the disk for the same data. This is good design and can massively reduce I/O. Now, it might be that you have some application sat in memory that sleeps for 3 days, wakes up, does a bunch of work then sleeps another 3 days.
What the kernel would like to do with this data is swap it out to make space for filesystem activity instead, since you have a much higher chance of actually using these pages more often than the pages you use for your application. Swapping, in this sense might be a 16kb transaction to your swap media which you should hardly feel, but in return you freed up 16kb of memory that could be used to store four files worth of data.
What the kernel doesnt want to use swap for
The kernel definitely doesnt want to use your swap to allocate more anonymous memory by swapping out some other anonymous memory, this is the situation people worry about the most and rightly so.
However, I should point out that if you have allocated so much memory that the kernel has no choice but to do this, this is a configuration problem of the system administrators, not the kernel itself -- its just trying to do the best by the options you've given it!
If you have a huge amount of swap do you increase the chance you use it?
No! If you have 1G of ram and 4G of swap, theres not a 80% chance your data gets swapped! The kernel wants to use the swap only when pages in memory can be better served doing something else!
Is it advantageous to not use swap at all
I would never do this. Swapping allows the O/S to get rid of memory you need to have but is never in use. If you have no swap, your just swallowing up memory you'll never get back, for which you might see a significant performance improvement by allowing say, the page cache to have it instead.
Whats the best swap to have
Theoretically speaking, find out how much resident memory +20% for safeties like re-entrant library calls that have to allocate memory from heap - then set your swap to that amount. This would (theoretically anyway) permit the operating system to swap all anonymous memory out if it had to to make way for something more useful.
If I get the kernel opportunity to swap out everything thats dangerous right?
Remember, the kernel isnt wanting to swap to make way for more anonymous memory allocation here, it will only ever swap out pages not in use to favour something else that will make better use of the space instead.
If your swapping anon memory out only to allocate from more anonymous memory, your doing something wrong and need more RAM or to retune your application stack anyway.
How much RAM would you need
You need to permit enough RAM to run all your applications of course, but you should probably allow an extra 2G of RAM for pagecache to fill up -- maybe more. Page cache makes your computer much much faster and your disks last longer. If your thinking of running a webserver, having even more for pagecache is a good idea due to the sheer amount of static content you can retrieve and reuse from pagecache that would get served out (if your webserver throughput is 5mb/s, you really dont want to be retrieving that 5mb/s content you generating from your disk after all!).
What to do if you really dont trust linux to swap properly
If your really concerned you can allocate more memory than you have:

Set your swap amount to be no more than you RAM
Set /proc/sys/vm/overcommit_memory to 2
Set /proc/sys/vm/overcommit_ratio to be a value which can never actually exceed physical RAM limits. See the kernel documentation to work out what that number would be to you.

Whats the best way to tune my memory for my application

Understand what swappiness actually does.
Use CGroups to allocate the correct resources per application.
Change the overcommit mode mentioned above to make the operating system enforce strict limits.
Use cgroups as above to set OOM priorites on applications you really want to keep if your out of memory and application you really want to ditch if your out of memory.

The vendor recommends a different configuration..
Listen to that instead. Some applications are written in such a way that they deliberately invoke the kernel to have their pages active over all others. This is a nasty trick to be honest but it breaks the kernels ability to seamlessly manage memory when it happens. If your vendor is giving you specifics then they likely fall into this category and listen to what they say instead.
In summary

Swap is meant to be used as a place to put wasted memory. Not as 'spare memory'
Having huge amounts of swap has no effect whatsoever on your chances of using it.
The kernel really wants to stop you accessing the disk for your data. This applies just as - if not more equally to page cache as it does to swap space.
The kernel will try its best to honour the setting you give it to the apps you run. But dont be surprised if you OOM if you have 500 apache children all taking up 32M of memory. Thats a fault of the configuration you choose, not the memory management.

The kernel usually does a very good job of managing virtual memory properly. Its almost always the case that your application is allocating more memory than you could possibly hope to work with and thats what is causing an OOM.
Swap used to be used as 'spare memory', but its not its primary purpose anymore, so dont think of using it like that. Instead, appreciate that your kernel probably knows best what it wants to use your memory for. Give it space to make those decisions and you'll benefit from an overall performance improvement.
Answer: From document "Oracle 10g Server on Red Hat® Enterprise Linux® 5 Deployment Recommendations".

Oracle provides generic
  recommendations regarding the size of
  swap in MetaLink Note 169706.1. These
  recommendations may lead to creation
  of very large swap space on systems
  with large amount of memory. The very
  large swap may cause sever system
  performance degradation and can be
  resolved by reducing swap space. Red
  Hat does not recommend allocating
  greater than 4GB for swap on Red Hat
  Enterprise Linux 5.

So for 16GB you should have no more than 4GB of swap.
PS. Also it's worth to note that invoked oom is almost always better than unusable swapped out process using whole I/O bandwidth.
Answer: Current CentOS Swap recommendations use the formula:
 M = Amount of RAM in GB, and S = Amount of swap in GB, then

If M < 2
    S = M *2
Else
    S = M + 2

So for 16G, the amount of swap should be 18G.
See http://www.centos.org/docs/5/html/Deployment_Guide-en-US/ch-swapspace.html
Answer: From what I recall from linux documentation: If your ram is greater than 2gb then you do swap = (ramSize + 2).  If it's less then you do swap = (ramSize*2)
Answer: I found this document for you, it should help you to make that decision, here it is:
What is Swap Space?, but neither of above answers are correct
Comment: The document you linked to doesn't agree with itself. Following the stated rule of "for more the 2Gb RAM amount of RAM above 2Gb" would give 1Gb swap for 3Gb RAM (3-2=1) not the 5Gb.

CentOS How Much SWAP for 16GB of RAM?


What are the other metrics that we can use in Sequential Pattern Mining, when using SPADE algorithm?

Question: I'm reading this awesome page with interest metrics used in Association Rules:
https://michael.hahsler.net/research/association_rules/measures.html
As I have sequential data, I decided to use the arulesSequences from R, which
do Sequential Pattern Mining, and create the rules using the SPADE algorithm.
Here are some rules created:
head(as(rules, 'data.frame'))
           rule                              support         confidence         lift
1    <{A}> => <{B}>                        0.026485890       0.13160987      0.8112745
2    <{D}> => <{B}>                        0.009853382       0.03726893      0.2297345
3     <{C}> => <{B}>                       0.063455778       0.10779325      0.6644632
4   <{C},{A}> => <{B}>                     0.018524358       0.24607330      1.5168542
6    <{D}> => <{E}>                        0.015607757       0.14494876      3.1703792
7    <{A}> => <{F}>                        0.011587577       0.05757932      1.2593987

I'm thinking if makes sense to calculate some other metrics, like Chi Squared test (to test the null hypothesis that Lift = 0 for a specific rule), or calculate the Standardized Lift.
And if makes sense, there's some function in this package or in another to calculate these new metrics?
I have my doubts because the cspade() function only creates rules with support, confidence and lift.
Answer: This book is one of the most useful resources I've found for pattern mining. Chapter 5 (available as a sample chapter) talks about a few properties of interest measures, such as whether the measure is invariant to inversion, scaling, and null addition. When choosing an interest measure it's worth thinking about what conditions are most important.
I'm not overly familiar with R, but the interestMeasure package looks like what you want. Otherwise the networkx package in Python contains some additional interest measures, or implementing them yourself shouldn't be too hard.
Comment: This book is really awesome, because details a lot of different measures. I think for my case I habe to use assimetric measures, because the order matters. The interestMeasure function is what I needed, but seems that only work for rules, not sequential rules.
Comment: I've used conviction and certainty factor before as asymmetric measures; both have worked well for me, and reduce some of the problems seen with confidence. Calculating them for static rules is very straightforward, they're just based off the item support and the rule support. Rule support should translate directly for sequential rules, but I'm not sure about item support in the sequential case, sorry
Comment: Having our discussion, I found this nice paper, which categorizes measures by assimetric/simetric properties etc. I found very useful: https://www.cse.msu.edu/~ptan/papers/IS.pdf
Comment: After studying the measure's properties, I decided to use `confidence`, because `confidence` is assimetric and null-invariant. If I'm not wrong, this means that 1. $conf(A \rightarrow B) \ne conf(B \rightarrow A)$ (assimetric property) and 2. $conf(A \rightarrow B)$ will not be affected by $supp(\overline{A}, \overline{B})$, where $\overline{}$ means complementary (null-invariant property).  These two measures properties matchs with my business design. By the way, thank you very much @Elenchus, because your recommended book opened my eyes to study assimetric measures!


Best way to encapsulate Animate callbacks?

Question: I'm doing an animation using raphaeljs, have an element that must be positioned in different places and at different time, the problem I made using a callback within another and the code was extensive, there's a way to improve?
 var c = Raphael("canvas", 500, 500);
    var p = c.path("m 40.008929,132.36161 0,128.5625 148.562501,0 0,-128.5625 -148.562501,0 z").attr({
        fill: '#33CCFF',
        stroke: '#000000',
        'stroke-width': 5
    });

    p.animate({
        path: "m 62.866072,140.93304 0,128.5625 148.562498,0 0,-128.5625 -148.562498,0 z"
    }, 2000, function () {

        p.animate({
            path: "m 77.151786,166.64733 0,128.5625 148.562494,0 0,-128.5625 -148.562494,0 z"
        }, 800, function () {

            p.animate({
                path: "m 71.4375,340.93304 0,128.5625 148.56249,0 0,-128.5625 -148.56249,0 z"
            }, 400, function () {

                p.animate({
                    path: "m 40.008929,132.36161 0,128.5625 148.562501,0 0,-128.5625 -148.562501,0 z"
                }, 1000);

            });

        });
    });

jsfiddle
Answer: You can create an array with the paths, and another array with the times.
then you create a function that calls p.animate with the next path and the next time, and with the same function as callback.
something like this:
var times = [2000,800,400,1000];
var paths = ["m 62.866072,140.93304 0,128.5625 148.562498,0 0,-128.5625 -148.562498,0 z",
             "m 77.151786,166.64733 0,128.5625 148.562494,0 0,-128.5625 -148.562494,0 z",
             "m 71.4375,340.93304 0,128.5625 148.56249,0 0,-128.5625 -148.56249,0 z",
             "m 40.008929,132.36161 0,128.5625 148.562501,0 0,-128.5625 -148.562501,0 z" ];
var current=0;

function nextStep(){
    if (current>paths.length)
       return;
    p.animate({
        path: paths[current]
    }, times[current++],nextStep);

}

and you first launch it just by directly calling:
nextStep();

Your code will stay simple even if the animation has a lot of diferent movements, and the data is easier to read, since all the paths are together.
Comment: Hi Carlos, Your example was perfect thanks, but messed me when I had to make the animation paths in groups http://jsfiddle.net/dxyJN/2/
the element being shown when I want to be animated, thanks.
Comment: i get lost at this point, i cannot find what is happening with the groups :(


Flatten Expression Parameter with Value

Question: I have this property in a class
public Expression<Func<T, string, bool>> FilterExp { get; set; }

I need to replace the string paramater with a value that is known at runtime and covert in into this:
Expression<Func<T, bool>>

so I can use it with IQueryable.
This is what it looks like when I set the filter:
PagingProvider<Employee> provider = new PagingProvider<Employee>(context.Employees);
provider.FilterExp = (employee, filterText) => employee.FullName.Contains(filterText);
return provider.GetResults();

What would be the best way of changing the expression?
Comment: What have you tried? https://stackoverflow.com/q/43090091/1462295
Comment: Please share more info. How do you set `FilterExp` now?
Comment: I've added an example code usage to the original post.
Answer: I came up with this and it seems to be working:
protected class ParameterReplacer : ExpressionVisitor
{
    private ParameterExpression parameterExpression;
    private string newValue;

    public ParameterReplacer(ParameterExpression parameterExpression, string newValue)
    {
        this.parameterExpression = parameterExpression;
        this.newValue = newValue;
    }

    public override Expression Visit(Expression node)
    {
        if (node == parameterExpression)
            return Expression.Constant(this.newValue);

        return base.Visit(node);
    }
}

And in my code I use it like this:
var replacer = new ParameterReplacer(FilterExp.Parameters[1], Filter);
var newBody = replacer.Visit(FilterExp.Body);
var exp = Expression.Lambda<Func<T, bool>>(newBody, FilterExp.Parameters[0]);
return SourceData.Where(exp);

Flatten Expression Parameter with Value


Libreswan IPSec IKEv2 unable to connect to multiple remote IPs

Question: I have been beating my head against this for awhile, and I'm hoping that someone can point me in the right direction.
I have a number of IPSec tunnels established, mostly from libreswan (v3.23) on CentOS to Cisco ASAs. Most are IKE v1, and in that case if I want to reach multiple hosts on the remote side I can have a formulation like this in my .conf file:
conn test1
rightsubnet=192.168.1.111/255.255.255.255
rightsourceip=192.168.1.111
also=test_common
auto=start
conn test2
rightsubnet=192.168.1.112/255.255.255.255
rightsourceip=192.168.1.112
also=test_common
auto=start

However, if I use this syntax with IKEv2 (ikev2=insist), I can start test1 and reach 192.168.1.111, but test2 will then not complete; or I can start test2 and test1 won't work.
My question is, what syntax will allow me to establish an IKEv2 tunnel which lets me reach both 192.168.1.111 & 192.168.1.112?
I have tried using:
conn test
rightsubnet=192.168.1.96/27
leftsubnet=192.168.2.2/32
also=test_common
auto=start

This formulation gets me up to the point where I see "STATE_PARENT_I2: sent v2I2, expected v2R2" but then all I get is "STATE_PARENT_I2: retransmission".
Similarly, I have tried:
conn test
rightsubnets=192.168.1.111/32,192.168.1.112/32
leftsubnet=192.168.2.2/32
also=test_common
auto=start

Using the rightsubnets directive causes the connection to not start, even if a single range is specified.
If anyone can point me in the right direction I'd be grateful.
Edit: I have discovered that I can use the rightsubnets directive; however it will only start the first tunnel. The syntax which works is:
rightsubnets={192.168.1.111/32 192.168.1.112/32}

In this example, 192.168.1.111 is reachable, but the second address gets to "STATE_V2_CREATE_I: sent IPsec Child req wait response" and never completes.
Answer: Change leftsubnet to leftsubnets
rightsubnets={192.168.1.111/32,192.168.1.112/32}
leftsubnets={192.168.2.2/32}

Also in my case this only works if right is not %any with IKEv2.


CSS property min-height causing margin issue?

Question: I am trying to make a div which has a CSS-generated triangle attached to the bottom of it. It works perfectly when the height of the div above is set using the CSS height property, but when I use min-height instead, it results in there being an unwanted gap, which I am unable to get rid of using the margin CSS properties.
Does anyone have any idea how I could get rid of the issue?

.triangle {
  width: 0;
  height: 0;
  margin-right: auto;
  margin-left: auto;
  border-style: solid;
  border-width: 17px 10.5px 0 10.5px;
}

.divider1 {
  min-height: 80px;
}

.divider2 {
  height: 80px;
}

This one doesn't work

But this one does?

Answer: It's because the h1 element's margin is collapsing in the second example. This is known as collapsing margins. To resolve this, one option would be to simply remove the h1 element's margin in the first example.
For what it's worth, the following applies:

Box Model - 8.3.1 Collapsing margins
The bottom margin of an in-flow block box with a height of auto and a min-height of zero collapses with its last in-flow block-level child's bottom margin if the box has no bottom padding and no bottom border and the child's bottom margin does not collapse with a top margin that has clearance.
A box's own margins collapse if the min-height property is zero, and it has neither top or bottom borders nor top or bottom padding, and it has a height of either 0 or auto, and it does not contain a line box, and all of its in-flow children's margins (if any) collapse.

As a side note, I'd suggest adding the triangle via a pseudo-element that is absolutely positioned relative to the parent element with a top value of 100%.
In doing so, it will work regardless of whether the parent has a height/min-height, and regardless of the element's margin.

.triangle-after {
  position: relative;
}
.triangle-after:after {
  content: '';
  width: 0; height: 0;
  position: absolute;
  top: 100%;
  left: 0; right: 0;
  margin: auto;
  border-style: solid;
  border-width: 17px 10.5px 0 10.5px;
}

.divider1 {
  min-height: 80px;
}
.divider1.triangle-after:after {
  border-color: blue transparent transparent transparent;
}
.divider2 {
  height: 80px;
}
.divider2.triangle-after:after {
  border-color: green transparent transparent transparent;
}

Both of these work now.

Both of these work now.

Answer: This is a result of margin collapsing. This should fix it:
h1 {margin-top:0;}

Margin collapsing occurs in three basic cases:

Adjacent siblings:
The margins of adjacent siblings are collapsed
  (except when the later sibling needs to be cleared past floats). For
  example:

The bottom margin of this paragraph is collapsed...

...with the top margin of this paragraph.

Parent and first/last child::
If there is no border, padding, inline
  content, or clearance to separate the margin-top of a block with the
  margin-top of its first child block, or no border, padding, inline
  content, height, min-height, or max-height to separate the
  margin-bottom of a block with the margin-bottom of its last child,
  then those margins collapse. The collapsed margin ends up outside the
  parent. :
Empty blocks:
If there is no border, padding, inline content,
  height, or min-height to separate a block's margin-top from its
  margin-bottom, then its top and bottom margins collapse.

More on developer.mozilla.com

.triangle {
    width: 0;
    height: 0;
    margin-right: auto;
    margin-left: auto;
    border-style: solid;
    border-width: 17px 10.5px 0 10.5px;
}
.divider1 {
    min-height: 80px;
    margin:0;
    padding:0;
}
h1 {
    margin:0;
}
.divider2 {
    height: 80px;
}

This one works now!

But this one does?

Comment: Thanks very much; this (`margin: 0`) does indeed fix it! Could you explain why this is the case, because using the Inspect Element in Chrome didn't seem to show the margin extending that far?
Comment: You're welcome! This is because of [margin collapsing](http://www.sitepoint.com/web-foundations/collapsing-margins/)
Comment: Basically you can avoid such unexpected results by using a CSS Reset.
Answer: In this specific case, the problem is with the h1 tag. If you were to remove the margin on the h1 it would work. You could also add padding to the .divider1 for it to work properly. Padding will be your better option since it accounts for any other elements having margin.


Como modificar o tamanho da fonte dos eixo em Python matplotlib.pyplot

Question: Boa tarde.
Gostaria de saber como posso aumentar a fonte nos eixos quando gero um gráfico utilizando matplotlib.pyplot.
Answer: plt.rcParams['xtick.labelsize'] = 16
plt.rcParams['ytick.labelsize'] = 16

Answer: Importando a biblioteca como
import matplotlib.pyplot as plt

Para alterar a fonte nos eixos do gráfico, escreva antes do seu plot
plt.rcParams['xtick.labelsize'] = 20
plt.rcParams['ytick.labelsize'] = 20

para alterar os parâmetros do tamanho da fonte em cada um dos eixos. No lugar do 20 coloque o tamanho que preferir.
Se quiser alterar o tamanho das fontes da legenda como um todo, escreva antes do seu plot
plt.rcParams.update({'font.size': 20})

Se quiser saber mais detalhes, veja em https://matplotlib.org/users/customizing.html


Show a subset is not path connected.

Question: Show that the subset $\{(x, y) \in \mathbb R^2 \mid x\neq 0\}$ of $\mathbb R^2$ is not path-connected.
I know that $X$ is path connected if any two points in $X$ are connected by a path in $X$, but unsure how to show this for this question. Could it been done by contradiction?
Comment: Yes. Assume that there is a path from left to right and consider its $x$-coordinate. What does the intermediate value theorem tell you?
Comment: This set, lets call it $X$, is $\mathbb R^2$ without the $y$-axis. So pick a point $(x_0,y_0)$ on any side of the axis and draw a circle of radius smaller than $|x_0|$. The interior of that circle is an open ball around $(x_0,y_0)$ completely contained in $X$. Therefore, each side is an open set, and together they give $X$. Hence $X$ is not just not path-connected, but not connected at all.
Answer: The space $A:=\{(x,y) \in \Bbb R^2:x\not=0\}$ is not connected as $U:=\{(x,y) \in \Bbb R^2:x>0\}$ and $V:=\{(x,y) \in \Bbb R^2:x<0\}$ are two disjoint non-empty subset of $A$ with $A=U\sqcup V$. Hence $A$ is also not pathwise-connected.
Answer: Let $A$ the set in question. Then $(-1,0), (1,0) \in A.$ Let $c=(c_1,c_2): [0,1] \to \mathbb R^2$ be a continuous path with $c(0)=(-1,0)$ and $c(1)=(1,0).$
Then: $c_1(0)=-1$ and $c_1(1)=1.$ Thus there is $\xi \in (0,1)$ such that $c_1(\xi)=0.$ But then we have that $c( \xi) \notin A.$
Comment: Typo  - $c_(0)$.

Show a subset is not path connected.


Numpy.corrcoef() for twice one object does not return matrix of 1's

Question: I'm trying to compare if two pictures are similar or close to similar. The picture is available as numpy.ndarray and contains of 28x28 pixels. It might look like the one below:

When I get the image as numpy.ndarray and calculate the corrcoef
image = data['test_dataset'][0]
matrix = np.corrcoef(image, image)

I was expecting a matrix full of 1's. Instead I get as print(matrix) something like:
[[ 1.          0.88450496  0.71112943 ...,  0.38349944  0.86398242
   0.95855052]
 [ 0.88450496  1.          0.85582039 ...,  0.60284577  0.99192916
   0.85438787]
...

Afterwards I wanted to create the .mean() of the matrix and if the value is higher than for example 0.98 the images are similar.
Can someone help me getting a matrix full of 1's instead of my strange looking output? Thanks in advance.
Answer: You cannot have a matrix full of 1's, only the diagonal will be (except if you have an image with identical rows).
From the numpy documentation of the first passed argument
x : array_like
A 1-D or 2-D array containing multiple variables and observations. Each row of x represents a variable, and each column a single observation of all those variables.
So in your result matrix, the coefficient appearing in position [0, 0] is the correlation of the first row of the image with itself (should be equal to 1, which is the case)
The coefficient appearing in position [0, 1] is the correlation between the first row and the second row of the image and cannot be equal to 1 as these rows are clearly not identical. It should however be equal to the coefficient in position [1, 0] which is the case.
So the function seems to work well. You cannot calculate the correlation of one pixel with respect to one other pixel because it doesn't make sense. You need a time-series to have variations and correlations.
Comment: Thanks for the explanation! For the idea of comparing how similar are two pictures, do you have a hint, which technique I should use instead? Maybe a tutorial or something similar, because time-series is a wide field.
Comment: Mutual information maybe? It seems that the `medpy` library has a full module called `metric.image`. `Sklearn.metric` has also some metrics implemented. Good luck with this :)


Sensitivity Analysis of Statistical Model

Question: Suppose I had built a model that predicts the likelihood of whether a sales agent will make a sale during an interaction with any given customer. The model is based on many variables, one of which is the 'friendliness' of the sales agent.
I run my model over my sales team of 100 staff, 50 of which have been considered 'friendly' staff (and 50 unfriendly), and I can predict the number of sales for the month.
If I were to fire the 50 'unfriendly' staff and hire 50 'friendly' staff (making a total team of 100 friendly staff), how I can I use my sales model to predict the uplift in my sales for the month with 100% friendly sales staff?
Would it be a matter of understanding (quantifying) the impact of the friendliness of staff and using that in a way to approximate the uplift in sales?
Comment: What type of model have you built? Logistic regression? Are you using R or Excel or something else?
Comment: Haven't built it yet. If it were GLM in R, how would you utilise the `summary()` of the GLM?
Comment: I'll write an answer.
Comment: Any recommendation on a better title for this question?
Answer: A few suggestions are below. Say we've run our GLM in R and called it fit, i.e. we've done fit <- glm(...).
predict(fit,newdata,type = "response") will get you the predicted probabilities for a new $X$ matrix, i.e. for a new workforce with attributes given by the rows of $X$.
Now we just need to decide how we're going to construct our newdata matrix.
The first 50 rows are easy -- they're just the rows corresponding to the friendly staff in our original matrix/data frame.
For the remaining 50, we need to make some (hopefully sensible) decisions.
We know that we want the friendliness column to be all 1s, but we're also going to need to provide the other attributes for these new employees. One way would be to assign the mean of each attribute from the original data frame to each new employee. This essentially means we're saying that all new employees are completely average, apart from the fact they're all friendly; i.e. we're looking at the marginal effect of making everybody friendly. We could also use the average among friendly staff if you expect some correlations between friendliness and other attributes.
Another option would be to try some sort of sampling procedure, whereby we get lots of possible outcomes corresponding to different attribute assignments, and we can look at the distribution of expected sales under the assumptions we embed in our sampling procedure.
The simplest way to do this would be bootstrapping -- sample attributes with replacement from the original matrix and use these samples to create 50 plausible new (friendly) employees. Predict the outcome using this new matrix and store the result. Rinse and repeat 500-1000 times, plot the histogram of your expected sales figures to get a sense of the possible variability/uncertainty associated with your decision to replace all unfriendly staff with friendly staff.


How do I grab individual tables in R when there are 3 or more classes?

Question: I have a data set that I am trying to find the rand index compared with another data set. One of the sets is shown below. The second set is very similar to this one. I have been trying to use the classAgreement() function to get the rand index, however I don't know how to convert the data I have into something that can be used by classAgreemeent(). If I can get a table comparing each cluster from each data I think it would help, but I feel lost.
-3  6   2
-2  7   2
-5  4   2
-4  7   2
12  10  3
11  9   3
14  11  3
13  12  3
14  18  1
15  19  1
13  20  1
15  16  1
16  18  1
17  17  1
2   10  2
14  9   3
17  6   3
-1  17  2
17  9   3
0   12  2

If you run table(mydata) you get three tables for each value of V3 (1, 2 or 3).
, , V3 = 1

    V2
V1   4 6 7 9 10 11 12 16 17 18 19 20
  -5 0 0 0 0  0  0  0  0  0  0  0  0
  -4 0 0 0 0  0  0  0  0  0  0  0  0
  -3 0 0 0 0  0  0  0  0  0  0  0  0
  -2 0 0 0 0  0  0  0  0  0  0  0  0
  -1 0 0 0 0  0  0  0  0  0  0  0  0
  0  0 0 0 0  0  0  0  0  0  0  0  0
  2  0 0 0 0  0  0  0  0  0  0  0  0
  11 0 0 0 0  0  0  0  0  0  0  0  0
  12 0 0 0 0  0  0  0  0  0  0  0  0
  13 0 0 0 0  0  0  0  0  0  0  0  1
  14 0 0 0 0  0  0  0  0  0  1  0  0
  15 0 0 0 0  0  0  0  1  0  0  1  0
  16 0 0 0 0  0  0  0  0  0  1  0  0
  17 0 0 0 0  0  0  0  0  1  0  0  0

, , V3 = 2

    V2
V1   4 6 7 9 10 11 12 16 17 18 19 20
  -5 1 0 0 0  0  0  0  0  0  0  0  0
  -4 0 0 1 0  0  0  0  0  0  0  0  0
  -3 0 1 0 0  0  0  0  0  0  0  0  0
  -2 0 0 1 0  0  0  0  0  0  0  0  0
  -1 0 0 0 0  0  0  0  0  1  0  0  0
  0  0 0 0 0  0  0  1  0  0  0  0  0
  2  0 0 0 0  1  0  0  0  0  0  0  0
  11 0 0 0 0  0  0  0  0  0  0  0  0
  12 0 0 0 0  0  0  0  0  0  0  0  0
  13 0 0 0 0  0  0  0  0  0  0  0  0
  14 0 0 0 0  0  0  0  0  0  0  0  0
  15 0 0 0 0  0  0  0  0  0  0  0  0
  16 0 0 0 0  0  0  0  0  0  0  0  0
  17 0 0 0 0  0  0  0  0  0  0  0  0

, , V3 = 3

    V2
V1   4 6 7 9 10 11 12 16 17 18 19 20
  -5 0 0 0 0  0  0  0  0  0  0  0  0
  -4 0 0 0 0  0  0  0  0  0  0  0  0
  -3 0 0 0 0  0  0  0  0  0  0  0  0
  -2 0 0 0 0  0  0  0  0  0  0  0  0
  -1 0 0 0 0  0  0  0  0  0  0  0  0
  0  0 0 0 0  0  0  0  0  0  0  0  0
  2  0 0 0 0  0  0  0  0  0  0  0  0
  11 0 0 0 1  0  0  0  0  0  0  0  0
  12 0 0 0 0  1  0  0  0  0  0  0  0
  13 0 0 0 0  0  0  1  0  0  0  0  0
  14 0 0 0 1  0  1  0  0  0  0  0  0
  15 0 0 0 0  0  0  0  0  0  0  0  0
  16 0 0 0 0  0  0  0  0  0  0  0  0
  17 0 1 0 1  0  0  0  0  0  0  0  0

How can I work on just one of those produced tables?
Answer: You can use [] to select data and provide third position for the table you want to select, for example, to select second table:
table(mydata)[,,2]
    V2
V1   4 6 7 9 10 11 12 16 17 18 19 20
  -5 1 0 0 0  0  0  0  0  0  0  0  0
  -4 0 0 1 0  0  0  0  0  0  0  0  0
  -3 0 1 0 0  0  0  0  0  0  0  0  0
  -2 0 0 1 0  0  0  0  0  0  0  0  0
  -1 0 0 0 0  0  0  0  0  1  0  0  0
  0  0 0 0 0  0  0  1  0  0  0  0  0
  2  0 0 0 0  1  0  0  0  0  0  0  0
  11 0 0 0 0  0  0  0  0  0  0  0  0
  12 0 0 0 0  0  0  0  0  0  0  0  0
  13 0 0 0 0  0  0  0  0  0  0  0  0
  14 0 0 0 0  0  0  0  0  0  0  0  0
  15 0 0 0 0  0  0  0  0  0  0  0  0
  16 0 0 0 0  0  0  0  0  0  0  0  0
  17 0 0 0 0  0  0  0  0  0  0  0  0


LUKS Header - 30kB mysteriously missing

Question: I have a disk containing (only) a LUKS encrypted volume.  That was created on a bare drive with no partition table using cryptsetup v.1.6.1.  When unlocked, I can check the size of the decrypted volume, compare it to the whole disk, and see that the difference is exactly 2MB.  When I back up the header, on the other hand, using:
cryptsetup luksHeaderBackup /dev/sda --header-backup-file <filename>

I get a file that is 30kB less than 2MB.  Using dd to dump the first 2MB of the disk and comparing it to the backed up header, I see that the 30KB is missing from the end and contains all 0's.  Oddly, I have backups of various (other) LUKS headers using cryptsetup 1.4.1 and 1.4.3, and they are all exactly 2MB.  This is consistent with section 6.2 of the cryptsetup FAQ, which says header size should be 2MB.
Could someone help me understand what this 30KB is?  (I would like to overwrite the header with random data as I've put it on a separate device, and want to make sure I know what I'm doing.)
Also as a more general issue, is there an easier/automated way, using the output of luksDump perhaps, to tell exactly where the header is located on a disk?  (Both offset and size.)  I have read the cryptsetup FAQ, but the result certainly doesn't just drop out.
And, is there a better way to overwrite the header, than using dd?
cryptsetup luksHeaderRestore <file_with_random_data>

doesn't work, because cryptsetup does some idiot checks to see if any already present header matches in master key size and offset.
Answer: It turns out the 30k is unused space, but the header data's been aligned to 1MB.  The whole 2MB were included when backing up with earlier versions of cryptsetup, but later versions leave it out.
By using the payloadOffset output of cryptsetup luksDump (a number of 512B sectors), it's possible to see the offset where the encrypted volume begins; so you can wipe manually up to there.  Or, since cryptsetup 1.6.4, you can use cryptsetup luksErase to overwrite all active keyslots.  The remaining visible header with metadata is the first 4KB of the disk, so that would have to be wiped manually.
[Thanks to Milan, one of the cryptsetup dev's, at cryptlab!]

LUKS Header - 30kB mysteriously missing


Use puppet to make changes to ip route and sysctl

Question: I have two changes to ip route & sysctl that disable tcp slow start.
Here's how I do it
ip route show

Make a note of the line starting with default.
Pick up the IP from the default line and run
sudo ip route change default via $ip_address dev eth0 initcwnd 12
sudo sysctl -w net.ipv4.tcp_slow_start_after_idle=0

How can I create a puppet script out of this? One that can be deployed to many machines of the same type – CentOS 6
Edit:
Added bounty to get a working example for
sudo ip route change default via $ip_address dev eth0 initcwnd 12

Answer: The sysctl side was covered in this post: Set sysctl.conf parameters with Puppet.
Puppet's example for networking also leverages Augeas.
Edit:
You're on CentOS, so remember that you need to make these routes persistent... Is the safer approach to make the change in a file, verify, then restart the network interface? This assumes /etc/sysconfig/network-scripts/route-ethX use since you're using via syntax. The ip route command seems to be your goal since you want to change the initial congestion window (initcwnd). I would seriously separate that into another option because setting the default gateway by itself should be handled by the OS network scripts/kickstart/build process.

Now for a totally different solution:
I like Puppet for some things. Network configs and sysctl values are not among them. With EL6 systems, you have the ability to use the tuned-adm framework to make these system changes on the fly in an easy and consistent manner. The servers I manage sometimes need 30+ sysctl and sysfs changes before going into production. I used to manage that manually, then with Puppet... but with EL6, I create a tuned profile with all of the requisite tweaks and scripts, manage the profiles and their distribution with Puppet, and control the tuned daemon with Puppet.
Given that, just move your ip script and sysctl values in a custom profile and go from there. Much cleaner.
Comment: Hard a hard time trying to figure out the networking bit. Even explored https://github.com/AbbyEdwards/puppet-iproute2facts
Can you help me with the ip route?
Comment: You're on CentOS, so remember that you need to make these routes persistent, right? Is the safer approach to make the change in a file, verify, then restart the network interface? This assumes `/etc/sysconfig/network-scripts/route-ethX` use.
Answer: If you are obtaining your internet address using DHCP (which is suggested by your question), then you can use /etc/dhcp/dhclient-exit-hooks to run shell commands after dhclient configures your interface.  You'll have access to a number of variables provided by dhclient, including $router.  You can use this to run:
ip route change default via $router dev $interface initcwnd 12

You would install this script with a normal Puppet file resource:
file { '/etc/dhcp/dhclient-exit-hooks':
owner => root,
group => root,
mode => 0755,
source => 'puppet:///.../dhclient-exit-hooks',
}

And the file contents would probably look something like:
#!/bin/sh

if [ "$interface" = eth0 ]; then
  ip route change default via ${new_routers%% *} dev $interface initcwnd 12
fi

If you're not using DHCP, you can do something similar.  The normal ifup script runs /sbin/ifup-local after configuring the interface, and you could use this to run the ip command.  In this case, you could get the address of the default gateway simply by sourcing in the interface configuration in /etc/sysconfig/network-scripts/ifcfg-eth0 (and your Puppet file resource would install /sbin/ifup-local).
Answer: Going off of larsks answer, if you have static ip addresses, place this in /sbin/ifup-local
#!/bin/sh

GATEWAY=`ip route| awk '/^def/{print $3}'`
DEFGWDEV=`ip route| awk '/^def/{print $5}'`

if [ "$1" = $DEFGWDEV ]; then
  ip route change default via $GATEWAY dev $DEFGWDEV initcwnd 12
fi


Difference between using deepcopy and substring operation

Question: I am using Python 2.7
I have a list lst = ['a','b','c']
If I need a copy if this list, I used to do lst_cpy = lst[:].
I came across a function deepcopy in the package copy which enables me to achieve the same.
import copy
lst_cpy_2 = copy.deepcopy(lst)

Can I use these two methods interchangeably or is there any difference between the two?
Thanks.
Comment: The [docs](http://docs.python.org/library/copy.html?highlight=deepcopy#module-copy) are your friend.
Answer: In the case of a simple list, they are the same.  If your list had other structures within it, for example, elements which were lists or dictionaries, they would be different.
L[:] makes a new list, and each element in the new list is a new reference to the values in the old list.  If one of those values is mutable, changes to it will be seen in the new list.  copy.deepcopy() makes a new list, and each element is itself a deep copy of the values in the old list. So nested data structures are copied at every level.
Answer: Since there is no way/need to deepcopy a string, slicing this particular list has the same effect. But normally [:] performs a shallow copy of a sequence.
Answer: I believe the difference is when one of the items in your list is a list, dict, or other mutable object. With a normal copy, the object is shared between copies:
>>> l = ['a','b',[1,2]]
>>> l2 = l[:]
>>> l2[2].append('c')
>>> l
['a', 'b', [1, 2, 'c']]

but with deepcopy(), the object is copied as well:
>>> l2 = copy.deepcopy(l)
>>> l2[2].append('d')
>>> l
['a', 'b', [1, 2, 'c']]
>>> l2
['a', 'b', [1, 2, 'c', 'd']]


Server 500 error in a View which is working perfectly outside of the admin area

Question: I have a View which is affected by several hooks ( views_pre_viewand views_query_alter, mainly). It works perfectly in the final user area, but when I am logged and go to the Views GUI, the browser displays the following error message:
 An AJAX HTTP error occurred.
 HTTP Result Code: 500
 Debugging information follows.
 Path: en/admin/structure/views/view/NAME_OF_VIEW/preview/block/ajax
 StatusText: Internal Server Error
 ResponseText:

I see no error loging in the recent log messages, the browser keeps working, I can modify the View, but I am worried that something may broke later in the final user area. How can I debug what is happening? I have no previous experience in Devel or similar.
Comment: Check if Apache error log has anything.
Comment: Any other log error which is related to views.
Comment: I have discovered the issue. In one of the hooks I was using a function which was defined in template instead of the module, so it didn't find it. The error was in the Apache logs, thanks for the suggestion.
Answer: You are going to have to access the PHP error log file to determine the cause. Drupal may not always log an error since it the error may stop it from running. I would contact your host to see if they can provide you the log.
Comment: You are going to have to access the PHP error log file to determine the cause. Drupal may not always log an error since it the error may stop it from running. I would contact your host to see if they can provide you the log.
Comment: As it is a dedicated server, I have access to the Apache log. There it was. Thanks.
Comment: I didn't mean to add my comment as an answer (couldn't figure out how to remove it) but I am glad it helped. Was there a helpful error message?
Comment: Yes, a function that did not exist, so I could trace back the error and copy/paste the function from template.php to mymodule.module.


Cacti totals graph values incorrectly

Question: I have the following graph: http://i45.tinypic.com/flar6f.jpg
I am graphing device memory usage via SNMP. It has an OID for used and free memory but not total. To graph total memory (as it is upgradable) I added the third item (total memory) with no data source and used the CDEF function "Total All Data Sources". As you can see, it hasn't worked.
Using snmpget both OIDs return Gauge32 values that are the used and free memory in bytes. Cacti seems to be automatically convertering them into Megabytes and Gigbytes so my CDEF item isn't working as expected (it says 1.06GBs of total memory).
How can I correct this, so that the total is 1.08GBs + 607.61MBs?
Comment: Just stack the graphs?  :)
Comment: What do you mean by stack them?
Answer: Add another CDEF that converts one of the values to the other value's unit ( * 1024 ).
Comment: But then if used memory drops to <1GB I would need to change the CDEF again. I plan to graph many more devices like this so I need a method of cacti doing it on it's own. This is a static solution if you catch my drift.
Comment: I agree; but then, you didn't mention the need to generalize this :)
Answer: In the end the problem was with the data source associations, on the "Graph Item Inputs" section, on my graph template. The correct data sources need to be supplying them selves to the correct graph items.

Cacti totals graph values incorrectly


Qual o problema de retornar um variável local?

Question: O que pode acontecer se eu retornar um variável local? Eu li na internet que não é uma boa ideia retornar uma variável local.
Talvez por que a variável quando sair da função é deletada?
Exemplo:
std::string StrLower(std::string str)
{
    std::transform(str.begin(), str.end(), str.begin(), tolower);
    return str;
}

Comment: Eu não vejo sentido nesta afirmação e sem você colocar o contexto de onde leu tal informação, acredito que será impossível aferir qualquer coisa.
Comment: Eu nunca ouvi isso, inclusive marquei a sua pergunta como favorita para caso alguém a responda, acredito que possa ser em caso de economia de memoria, projetos para arduino por exemplo que temos que economizar memoria já que ele tem um hardware mais limitado, porque se você passar a variável por referencia ela vai ocupar somente um espaço em memoria, e se retorna outra variável ela irá utilizar mais um espaço em memoria.
Answer: Você nunca retorna variáveis. Isso é um conceito abstrato para facilitar o entendimento do código, mas não sendo algo concreto não podemos transpor para outro local. Portanto a variável local só existe lá mesmo e não tem como sair.
Você retorna um valor. Ok, entendo que o que queria dizer era isso. Um valor criado localmente (alocado na stack) só pode ser copiado, porque esse valor vive em uma área que fica garantidamente viva enquanto a função está sendo executada, depois, para todos os efeitos, considere que esta área será destruída. Se você tentar acessar o valor em sua posição original potencialmente estará acessando lixo, algo que não deve. Copiando você transporta o valor para uma área que seguramente estará viva quando você acessá-lo.
Tipos longos possuem muitos dados para transportar e acaba ficando lento. Por isso a maioria dos tipos longos são por referência.
Alguns tipos tem semântica de referência, então em vez de você retornar o valor do objeto em si você retorna uma referência para ele, então considera-se que você moveu o objeto, assim só a referência (ponteiro) é copiado, e a referência aponta para o valor efetivo. Aí que está o problema. você retornou uma referência para um valor que será destruído no final da execução da função, oque obviamente dará problema, simplificadamente falando. É disso que o pessoal fala.
Neste caso a solução é alocar no heap (definição no link acima), ou passar o valor por referência, o que permitirá escrever no local onde o valor sendo manipulado nesta função será usado na função chamadora. Assim é garantido que o valor estará vivo quando for usar.

Talvez por que a variável quando sair da função é deletada?

Isso, embora para usar a terminologia correta eu diria que é porque o valor é potencialmente destruído ao sair da função.
Consertando os erros o código funciona perfeita (espero que seja um exemplo genérico, não acho isso uma ideia em código real):
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

string StrLower(string str) {
    transform(str.begin(), str.end(), str.begin(), [](char c) -> char { return tolower(c); });
    return str;
}
int main() {
    cout << StrLower("TESTE");
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Answer: Essa afirmação é velha e existe justamente pois os compiladores não sabiam otimizar o código bem antigamente, resultando em um executável com performance questionável (a variável é copiada, e cópias podem ter um custo alto). Hoje em dia, retornar algo local pode ser até melhor que usar parâmetros de saída. Claro, nunca confie em frases populares sobre otimizações, sempre faça os cálculos e medidas de performance do seu programa pra tirar qualquer conclusão.
Temos dois nomes para os tipos de otimizações possíveis nesse caso:

RVO: Return Value Optimization (otimização de valor de retorno em Português), e
NRVO: Named Return Value Optimization (otimização de valor de retorno com nome em Português), que basicamente é uma variação de RVO pra casos quando o valor tem um nome (i.e. é uma variável).

Essas duas técnicas de otimização estão dentro da técnica Copy Elision (elisão/omissão de cópia em Português). Em c++17, elisão de cópia faz parte da padronização. Antes, essa técnica era mencionada como permitida, mas não entrava em muitos detalhes sobre quais casos eram ou não permitidos de omitir cópias.
Com tudo isso dito, agora podemos observar os efeitos de RVO e NRVO:
Quando a técnica de otimização RVO é aplicada com sucesso, a cópia (que antes seria feita) de um objeto, que acabara de ser criado e retornado pela função, é omitida, fazendo com que a área de armazenamento desse objeto seja o mesmo do objeto que está recebendo esse valor de retorno. Pra ficar mais claro, o seguinte código:
#include <string>

std::string foo() { return "teste"; }

auto s = foo();

É transformado para o seguinte:
#include <string>

std::string s;

void foo() { s = "teste"; }

foo();

Perceba como a otimização usou o armazenamento da variável de fora s para atribuir a string literal "teste", em vez de criar uma nova std::string e copiar esse objeto pro s. Compilando com GCC 7.3 e com otimização nível 3, temos o seguinte corpo para a função std::string foo():
foo[abi:cxx11]():
  lea rdx, [rdi+16]                    # Calcula o local onde `s` está
  mov rax, rdi
  mov DWORD PTR [rdi+16], 1953719668   # Escreve "teste" no buffer de `s`.
  mov BYTE PTR [rdi+20], 101
  mov QWORD PTR [rdi+8], 5             # Escreve o tamanho da string.
  mov QWORD PTR [rdi], rdx
  mov BYTE PTR [rdi+21], 0             # Escreve o caractere nulo da string.
  ret

Em vez de criar um novo objeto de std::string, a função foo apenas assume que o local de armazenamento do objeto já existe (isto é, quem chamou a função já alocou espaço pro objeto) e faz uso dele.
A variação NRVO faz exatamente a mesma coisa, exceto que ela é estendida para variáveis. Se tivéssemos o seguinte código:
#include <string>

std::string foo()
{
    std::string s_local = "teste";
    s_local[0] = 'T';
    return s_local;
}

auto s = foo();

Teríamos exatamente a mesma saída otimizado, com a única adição de um mov BYTE PTR [rdi+16], 84 no fim, que altera o primeiro caractere da string pra um T maiúsculo. Isto é, s_local e s terão o mesmo local de armazenamento após a otimização.
Existe alguns casos em que a otimização NRVO não pode ser aplicada facilmente. Se apenas retornarmos a mesma variável local, então a aplicação da NRVO é trivial. Caso contrário, se tivermos retornos de múltiplos valores, então estamos em um caso difícil para a NRVO, e provavelmente a otimização não será efetuada. Por exemplo:
std::string foo(bool b)
{
    std::string s1 = "abc";
    std::string s2 = "def";
    return b ? s1 : s2;
}

Aqui, o compilador pode até conseguir aplicar NRVO (escrevendo "abc" ou "def" na string, dependendo do valor de b), mas assim que o código vai ficando mais complexo, as chances de NRVO ser aplicado com sucesso diminuem. Em contraste, se apenas tivermos retornos de sempre a mesma variável, a função pode ficar o quão complexa quiser, que a aplicação de NRVO será trivial independentemente.
Por fim, aqui está a saída da sua função (brevemente alterada) de alguns compiladores (compilando com c++17 em todos).
#include <string>
#include <algorithm>

std::string foo()
{
    std::string s = "teste";
    std::transform(begin(s), end(s), begin(s),
                   [](char c) { return c - 32; });
    return s;
}

Com GCC 7.3 e nível de otimização 3:
foo[abi:cxx11]():
  lea rdx, [rdi+16] # Calcula o começo da string que já existe fora da função
  mov DWORD PTR [rdi+16], 1953719668 # Escreve "teste"
  mov BYTE PTR [rdi+20], 101
  mov rax, rdi
  mov QWORD PTR [rdi+8], 5
  mov BYTE PTR [rdi+21], 0
  mov QWORD PTR [rdi], rdx
  sub BYTE PTR [rdi+16], 32 # Sequência de subtração (pra passar pra maiúsculo)
  sub BYTE PTR [rdi+17], 32 # que foi desenrolado de `std::transform`
  sub BYTE PTR [rdi+18], 32
  sub BYTE PTR [rdi+19], 32
  sub BYTE PTR [rdi+20], 32
  ret

Com Clang 6.0.0, nível de otimização 3 e também compilando com libstdc++:
foo[abi:cxx11](): # @foo[abi:cxx11]()
  lea rax, [rdi + 16]
  mov qword ptr [rdi], rax
  mov qword ptr [rdi + 8], 5
  mov dword ptr [rdi + 16], 1414743380 # Clang conseguiu remover o `std::transform`
  mov word ptr [rdi + 20], 69          # e já passou a string na versão maiúscula
  mov rax, rdi
  ret

Você pode brincar e testar com as saídas dos compiladores no Compiler Explorer Godbolt.


Why can neither GeoGebra, nor MathWay solve this simple math problem?

Question: $\frac{e^{0.75}}{-0.5^e+10000}$
This doesn't work either:
$\frac{2.72^{0.75}}{-0.5^{2.72}+10000}$
I can even solve it with a calculator.
Comment: I don't understand the problem.   Did you look up how to correctly enter mathematical expressions in those programs?  How did you try to enter them?
Comment: (e^0.75)/((-0.5)^e+10000)
Comment: And with 2.72 instead of e
Comment: http://screencast.com/t/OBW9dbURsXF http://screencast.com/t/Sv3ZzWKJYJMy A = the intersection between a and g.
Answer: First of all, $(-0.5)^e$ is not the same as $-0.5^e$.
Secondly, $x^y$ is not well defined (at least not as a real number) if $x < 0$ and $y$ is not an integer.
Comment: @50ndr33 From your reply in the comment above, you seemed confused about the difference. (You wrote one thing in the question, another in the comment.)

I don't have any of the two programs you mention available, but I know there are some programs that get the priority rules wrong, i.e. interpreting $-0.5^e$ as $(-0.5)^e$. Wolfram Alpha gets it right: http://www.wolframalpha.com/input/?i=e%5E0.75%2F%28-0.5%5Ee%2B10000%29
Comment: I know that there is a difference between (−0.5)^e and −0.5^e, none of them worked. So you are saying that they cannot solve it because of their scripts, not because the math is not supposed to work?
Answer: Mathway refuses to numerically evaluate. Geogebra Does evaluate the expression correctly
e^(.75)/(10000-.5^e)

Gives
a=0

but if you right click on a and go to object properties the value says
0.00021

which agrees with google calculator
https://www.google.com/search?q=exp%28.75%29%2F%2810000-.5^e%29
Why you would want to evaluate this in geogebra is beyond me
Comment: Why you would want to evaluate this in geogebra is beyond me: It was because I wanted to draw this as a graph. But it said undefined with values of 1 or less on the x-axis. (0.5 = x)
Comment: Then as others have stated before me the expression you typed and what you are asking geogebra to evaluate are not the same thing $-.5^e \neq (-.5)^e$. The expression $(-.5)^e$ isn't even well defined.
Comment: So the expression $x^e$ is only a well defined real number if $x \ge 0$. Your calculator may be giving you *one* of the possible complex multi-valued solutions.


VisualG - Exercício com procedimento

Question: Boa tarde galera, tudo certo?
Estou com um exercício de Algoritmos I, e tô preso numa dúvida. A questão:
- Escreva um procedimento que receba um número inteiro e o imprima na forma extensa. Por exemplo, para 1 a saída desejada é "Um". A função deve ser capaz de gerar o extenso dos números de 1 até 15, inclusive. Caso um número não compatível seja recebido o procedimento deve mostrar uma mensagem de erro. Crie também um algoritmo que leia um valor inteiro e chame o procedimento criado acima para a impressão do número extenso.
Meu código:
algoritmo "APS09"
var
   num: inteiro

procedimento FormaExtensa(n:inteiro)
var
   extenso:caracter
inicio
      escolha n
              caso "1"
                   extenso <- "Um"
              caso "2"
                   extenso <- "Dois"
              caso "3"
                   extenso <- "Três"
              caso "4"
                   extenso <- "Quatro"
              caso "5"
                   extenso <- "Cinco"
              caso "6"
                   extenso <- "Seis"
              caso "7"
                   extenso <- "Sete"
              caso "8"
                   extenso <- "Oito"
              caso "9"
                   extenso <- "Nove"
              caso "10"
                   extenso <- "Dez"
              caso "11"
                   extenso <- "Onze"
              caso "12"
                   extenso <- "Doze"
              caso "13"
                   extenso <- "Treze"
              caso "14"
                   extenso <- "Quatorze"
              caso "15"
                   extenso <- "Quinze"
              outrocaso
                   extenso <- "Número não compatível"
      fimescolha
      escreval(extenso)
fimprocedimento

inicio

      escreva("Digite um número até 15: ")
      leia(num)

      FormaExtensa(num)

fimalgoritmo

Porém, na hora de rodar, ele pede para digitar o número certinho, porém, qualquer número que eu digite, ele da um erro no caso "1" e diz que esperava um INTEIRO. Ainda não entendi aonde ele esperava um valor inteiro.
Alguém pode me ajudar nessa?
Agradeço desde já.
[RESOLUÇÃO]
Apenas removi as aspas do caso, como sugerido em resposta ao post.
caso 1
                   extenso <- "Um"
              caso 2
                   extenso <- "Dois"
              caso 3
                   extenso <- "Três"
              caso 4
                   extenso <- "Quatro"
              caso 5
                   extenso <- "Cinco"
              caso 6
                   extenso <- "Seis"
              caso 7
                   extenso <- "Sete"
              caso 8
                   extenso <- "Oito"
              caso 9
                   extenso <- "Nove"
              caso 10
                   extenso <- "Dez"
              caso 11
                   extenso <- "Onze"
              caso 12
                   extenso <- "Doze"
              caso 13
                   extenso <- "Treze"
              caso 14
                   extenso <- "Quatorze"
              caso 15
                   extenso <- "Quinze"
              outrocaso
                   extenso <- "Número não compatível"
      fimescolha

Answer: Cara vê se não é porque você colocou entres aspas duplas "", ele espera receber um número porém esta sendo comparado com uma string, no caso seria tipo assim:
escolha n:
    case 1 extenso <- "UM"
    case 2 extenso <- "DOIS"
    ...
fimescolha

Comment: Exatamente isso meu amigo... Que mole que eu marquei. hahaha
Agradeço da mesmo forma. Já até editei o post com a resolução

VisualG - Exercício com procedimento


KeyError with pandas json_normalize when opening JSON file, but not with JSON embedded in code (JSON to CSV)

Question: This works (normalize data inline):
import pandas as pd

data = [
    {
        "action_type": "add_chat_item",
        "author": {
            "id": "abcde",
            "images": [
                {
                    "id": "source",
                    "url": "https://www.example.com"
                },
                {
                    "height": 32,
                    "id": "32x32",
                    "url": "https://www.example.com",
                    "width": 32
                },
                {
                    "height": 64,
                    "id": "64x64",
                    "url": "https://www.example.com",
                    "width": 64
                }
            ],
            "name": "user1"
        },
        "message": "the first user sent this",
        "message_id": "abcde",
        "message_type": "text_message",
        "time_in_seconds": -999,
        "time_text": "-0:00",
        "timestamp": 2000
    },
    {
        "action_type": "add_chat_item",
        "author": {
            "badges": [
                {
                    "icon_name": "moderator",
                    "title": "Moderator"
                }
            ],
            "id": "abeee",
            "images": [
                {
                    "id": "source",
                    "url": "https://www.example.com"
                },
                {
                    "height": 32,
                    "id": "32x32",
                    "url": "https://www.example.com",
                    "width": 32
                },
                {
                    "height": 64,
                    "id": "64x64",
                    "url": "https://www.example.com",
                    "width": 64
                }
            ],
            "name": "user2"
        },
        "message": "message from the user two",
        "message_id": "abeedk",
        "message_type": "text_message",
        "time_in_seconds": -111,
        "time_text": "-1:11",
        "timestamp": 100003
    }
]

norm = pd.json_normalize(data)
norm.to_csv('test.csv', encoding='utf-8', index=False, columns=['timestamp','author.name','message'])

And this works, with the above data saved as file.json (read file and outputs columns including full author column, to CSV):
import pandas as pd

with open('file.json', encoding='utf-8') as inputfile:
     df = pd.read_json(inputfile)

df.to_csv('file.csv', encoding='utf-8', index=False, columns=['timestamp','author','message'])

But this doesn't work with that same file:
import pandas as pd

with open('file.json', encoding='utf-8') as inputfile:
     df = pd.read_json(inputfile)

norm = pd.json_normalize(df)
norm.to_csv('file.csv', encoding='utf-8', index=False, columns=['timestamp','author.name','message'])

I get a bunch of errors, the last lines of which are:
raise KeyError(f"None of [{key}] are in the [{axis_name}]")
KeyError: "None of [Index(['timestamp', 'author.name', 'message'], dtype='object')] are in the [columns]"

This results in the same error:
with open('file.json', encoding='utf-8') as inputfile:
     df = pd.json_normalize(inputfile)

df.to_csv('file.csv', encoding='utf-8', index=False, columns=['timestamp','author.name','message'])

This results in a successful CSV, but only with new lines:
with open('file.json', encoding='utf-8') as inputfile:
     df = pd.json_normalize(inputfile)

df.to_csv('file3.csv', encoding='utf-8', index=False)

I expected to output the author.name column in the CSV when reading from the JSON file. Instead, the code errors out when it reads the file and normalizes it.
Answer: I think you need json.load instead pd.read_json first:
import json

with open('file.json', encoding='utf-8') as inputfile:
    data = json.load(inputfile)

norm = pd.json_normalize(data)
norm.to_csv('file.csv', encoding='utf-8', index=False,
            columns=['timestamp','author.name','message'])

Details:
print (norm.head(2))
     action_type                    message message_id  message_type  \
0  add_chat_item   the first user sent this      abcde  text_message
1  add_chat_item  message from the user two     abeedk  text_message

   time_in_seconds time_text  timestamp author.id  \
0             -999     -0:00       2000     abcde
1             -111     -1:11     100003     abeee

                                       author.images author.name  \
0  [{'id': 'source', 'url': 'https://www.example....       user1
1  [{'id': 'source', 'url': 'https://www.example....       user2

                                       author.badges
0                                                NaN
1  [{'icon_name': 'moderator', 'title': 'Moderato...


What's the difference between Ramsey theory and Extremal graph theory?

Question: Wikipedia teaches us that problems in Ramsey theory typically ask a question of the form: "how many elements of some structure must there be to guarantee that a particular property will hold?"
It also teaches us that "Extremal graph theory studies extremal (maximal or minimal) graphs which satisfy a certain property". This sounds very similar. Let's take Turan's theorem (the basic example of an EGT theorem) - it gives a bound on the number of edges in a clique-free graph (for a given clique size). Put differently, it tells us how many elements (edges) of a certain structure (graph with fixed number of vertices) must be there to guarantee that a particular property (existence of a clique of a specific size) will hold.
One can argue that in EGT we try to understand the structure of the extremal objects, but I don't see why Ramsey theory should not try to do the same thing, and also I don't see how this is done in the (beautiful) Erdős–Stone theorem which is considered a fundamental theorem of EGT.
So is there a real difference or is it just a matter of taste?
Comment: I think EGT is a subset of Ramsey theory. In Ramsey theory, we are concerned with structures other then graphs as well, for example in linear equations (Rado's theorem).
Answer: I agree with Shahab's comment above. Ramsey theory is certainly more general, and is usually concerned with questions of unavoidable order contained within even the most chaotic structures. Some of these questions (and answers) can be stated (or solved) in a graph-theoretic context using the techniques of extremal graph theory.
Extremal graph theory tends to focus on graph-specific questions of minimality/maximality. Questions like how do I guarantee that every vertex in a subgraph has a given minimum degree? How many disjoint cycles must a graph of size $m$ have? Or given a $k$-regular graph what is its minimum/maximum girth? These are questions dealing with the explicit constructions and natures of the objects of graph theory. Sometimes the results that are obtained find applicability in "real" world applications, but often they simply help us to better understand the extremal nature of regular graphs.
I think that is the difference suggested at the end of your question. Extremal graph theory studies the extremal properties of regular graphs, while Ramsey theory is more concerned with the necessary (regular) properties of extremal graphs.


Como configurar uma Activity para ocupar todo o espaço da tela?

Question: Quero esconder até a barra de notificações!!
Answer: Para ocupar toda tela você tem duas opções:
1 - Por Tema
Basta usar/herdar o tema @android:style/Theme.NoTitleBar.Fullscreen. Lembrando que você não terá o ActionBar, podendo usar o Toolbar para suprir essa falta.
2 - Programaticamente
Basta fazer a requisição da remoção do título e setar as flag's de FullScreen a Window:
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);

Lembrando que é preciso executar esse trecho depois da chamada ao super.onCreate e antes do setContentView. Caso contrário irá falhar devido a presença de conteúdo.
Acredito que a primeiração opção seja mais elegante, pode ser mais suave que a segunda.


Isomorphism with affine scheme

Question: Suppose $X\rightarrow {\rm Spec}(A)$ is a morphism between a scheme and an affine scheme that
1) is a bijection topologically and
2) each scheme theoretic fiber is a single reduced point
3) both $X$ and $A$ are reduced
Then is $X$ affine?
Comment: If $f$ is an isomorphism of underlying topological spaces, $f_*$ is exact, in particular $H^i(X,F)=H^i(\operatorname{Spec} A,f_*F)=0$ for any quasi-coherent sheaf $F$ on $X$. Hence $X$ is affine. What am I missing?
Comment: Do you have a counterexample when only 1) holds?
Comment: I guess maybe the topology of $X$ is finer than that of ${\rm Spec}(A)$. But that's a good idea…I didn't think of that.
Comment: Ah ok, so maybe $f$ is only a bijection, but not a homeomorphism. That might be a problem.
Answer: Here is one example where $X$ is not affine. A similar idea would work if $A$ is reduced with infinitely many points in $\operatorname{Spec}A$, and you took the same definition for $X$ below using residue fields of points in $\operatorname{Spec}A$. A more interesting question might be if your question is true assuming $X$ is connected.
Let $k$ be a field, and consider the morphism
$$X := \coprod_{x \in \mathbf{A}^1_k} \operatorname{Spec} \kappa(x) \longrightarrow \mathbf{A}^1_k$$
where $\kappa(x)$ denotes the residue field at a point $x \in \mathbf{A}^1_k$, and the map is defined by mapping the unique point in $\operatorname{Spec} \kappa(x)$ to $x$. This is a bijection on topological spaces by construction, each scheme theoretic fiber is a spectrum of a field, hence is a single reduced point, and $X$ is reduced. On the other hand, $X$ is not quasicompact, hence $X$ cannot be affine.
Comment: Maybe one should change the wording of 1) to a set-theoretic bijection then.
Comment: @MooS Right, I guess I understood OP's replies to your comments as saying the map on underlying sets need not be a homeomorphism.

Isomorphism with affine scheme


MSE for multivariate regression

Question: I found that the code for computing mse for multivariate regression is as below in matlab:

perf = sum(sum(e.^2)) / numel(e);

where es are residuals.
That is kind of awkward for me because the more you have responses columns the more your mse error would be.
My question is that if we account for the number of responses for computing error?
something like below:

perf = sum(sum(e.^2)) / (numel(e) * m) ;

where m in the number of response columns.
Comment: [Related](https://datascience.stackexchange.com/a/109504/73930), I think
Answer: The numel function in MATLAB is the number of elements, so for a matrix it's not just the number of rows. I suspect the original expression already addresses the concerns you have.

MSE for multivariate regression