Basis of a subspace (What does it mean for vectors to span a subspace?)

Question: How is the basis of this subspace the answer below?
I know for a basis, there are two conditions:

The set is linearly independent.
The set spans H.

I thought in order for the vectors to span H, there has to be a pivot in each row, but there are three rows and only two pivots. I know that the set is linearly independent, but I don't understand how the set spans H.
Here is the subspace:
$$\left\{\begin{bmatrix} s-2t \\ s+t \\ 3t \end{bmatrix} : s,t \in \mathbb{R} \right\}$$
Here is the solution (finding the basis):

This subspace is $H=\mathrm{Span}\{\mathbf{v}_1,\mathbf{v}_2\}$, where $\mathbf{v}_1=\begin{bmatrix} 1 \\ 1 \\ 0 \end{bmatrix}$ and $\mathbf{v}_2=\begin{bmatrix} -2 \\ 1 \\ 3 \end{bmatrix}$.  Since $\mathbf{v}_1$ and $\mathbf{v}_2$ are not multiples of each other, $\{\mathbf{v}_1,\mathbf{v}_2\}$ is linearly independent and thus is a basis for $H$.  Hence the dimension of $H$ is $2$.
Comment: $$\begin{bmatrix}s-2t\\s+t \\ 3t\end{bmatrix} = s\mathbf{v}_1 + t\mathbf{v}_2$$so the parametrisation and the two given basis vectors span the same space.
Comment: Who do you mean by a "pivot?"
Answer: The space has dimension $d$ at most $2$, since it is the image of a linear mapping from $\mathbb{R}^2$ to $\mathbb{R}^3$:
$$\ell\colon (s,t)\mapsto (s-2t,s+t,3t)$$
Thus, any set of $2$ independent vectors has to be a basis, since a basis is a set of $d$ linearly independent vectors.
Answer: Span means that your set of vectors generates the whole space. More rigorously, if $V$ is a vector space over a field $K$, the span of a set of vectors $S$, $\operatorname{Span}(S)$, is defined to be $\{a_1 v_1 +a_2 v_2 + \cdots + a_n v_n : v_i\in S, a_i \in K\}$.
With matrices and whatnot this can be rephrased as you indicated in terms of how many pivots there are. It would be an excellent exercise to work this out!
In terms of your particular example anyway, you want to show that every vector $v$ in $H$ can be written as $v=a_1v_1+a_2v_2$ for $a_1,a_2\in \Bbb{R}$. But of course by definition of $H$, if $v\in H$,
$$v=\pmatrix{s-2t \\ s+t\\3t}=s\pmatrix{1\\1\\0}+t\pmatrix{-2\\1\\3}=sv_1+tv_2.$$
Therefore $v_1$ and $v_2$ span $H$.


Title over an image using Display:Table Cell

Question: I am trying to get a title to display over an image and have it center horizontally and vertically using display:table-cell.
A specific example is http://ollymoss.com - how, on hover, the title of each poster comes up and is centered vertically/horizontally. I inspected element and saw they were using Display: Table-cell but I can't replicate it.
If anyone happens to know a way to make this work, that would be great!
This is the page in question: http://sathyaram.com/graphic
I'm trying to get those titles for each tile to appear ON the tile, centered vertically/horizontally.
If there's a better method than display:table-cell, I would love to know! I know you can use position:absolutes/relatives, but I would like it to be responsive and I'm not sure how that'd work!
I'm trying to do this specifically within CSS - not sure how to use jQuery!
Thank you very much!
Comment: You should include a [mcve] _in your question_; simply linking to off-site code, especially a web site you INTEND to change, will not help anyone in the future.
Answer: If you want to display the title centered horizontally and vertically, you can make this in css I think :
<code>.yourTitleWrap {
    text-align: center;
    width: 100%;
    height: 50px /* with 50px for example ... */
    position: absolute;
    top: calc(50% - 25px);
}
</code>
For the top value, 25px represents height / 2, normally it should work and center your title in the center of the parent's div.


Removing duplicates before train test split

Question: Let's say you have a dataset generated from real world sampling which has lots of duplicates (the dependent and independent variables are identical) and you want to train a classifier to predict the dependent variable in future samples from the real world. If you were to take a train test split from this dataset you'd inevitably have records which appear in both the train and the test dataset, so to avoid this you would deduplicate the original before doing a train test split.
My question is - is it the right thing to deduplicate and train on deduplicated data and test on totally unseen data, or is it the right thing to train and test from the original distribution coming from the real world, and accept that we would do well on previously seen examples anyway?
Comment: I would treat the duplicates as one entity, that is they are either all in the training set or all in the test set, but not both.
Answer: Interesting question.
The effect of duplicates in training data is slightly different than the effect of duplicates in the test data.
If an element is duplicated in the training data, it is effectively the same as having its 'weight' doubled. That element becomes twice as important when the classifier is fitting your data, and the classifier becomes biased towards correctly classifying that particular scenario over others.
It's up to you whether that's a good or bad thing. If the duplicates are real (that is, if the duplicates are generated through a process you want to take into account), then I'd probably advise against removing them, especially if you're doing logistic regression. There are other questions about dealing with oversampled and undersampled datasets on this SE. When it comes to neural networks and the like, other people may be able to answer better whether it is necessary to worry about this.
If your dataset is, for example, tweets, and you are trying to train a natural language processor, I would advise removing duplicate sentences (mainly retweets) as that doesn't really help to train the model for general language use.
Duplicated elements in the test data serve no real purpose. You've tested the model on that particular problem once, why would you do it again, when you'd expect the exact same answer? If there is a high proportion of the same duplicated entries in the test set as are in the training set, you'll get an inflated sense of how well the model performs overall, because the rarer scenarios are less well represented, and the classifier's poor performance with them will contribute less to the overall test score.
If you are going to remove duplicates, I'd recommend doing it before splitting the dataset between train and test.
Comment: I don't agree with the statement that "duplicated elements in the test data serve no real purpose". It all depends what the population is of interest that you're trying to test / predict upon.  If you're trying to say:
A) How does it perform on a representative sample of the data (and duplicates will continue to occur in the production setting) -- then keeping duplicates in makes sense
B) How does it perform on new data its never seen -- then removing duplicates makes sense. Depends what is actually relevant to your application / what the population of interest is.  Both may be interesting
Comment: Do you know of any Python packages that do a train-test split with duplicate records, but then pull those out of the test set that are also in train?
Comment: You wrote, and I agree, that duplicates might be meaningful in the training dataset, but they are unnecessary in the testing dataset. And then, in the end you recommend removing them from both datasets. I think the end clashes with your previous reasoning.
Comment: @helen no it doesn't
Answer: I'd like to add 2 points to @Ingolifs nice answer:

The main idea behind recommending to deduplicate or not is to think what that amounts to wrt. your application. Both have their point, but wrt. testing a slightly different kind of generalization ability:

If you want to test the ability to correctly predict new (say, future) cases, there's nothing that would guarantee statistically independent future cases not to have independents that your model encountered during training. So deduplication here would lead to a bias in your sample distribution. Which may or may not influence your model and if it does have an influence on the model, that influence may or may not be what you actually want.
On the other hand, it may still be of interest how your model peforms for cases where the independent variable vector is unknown in the sense that it has not been encountered during training. Note that while this means a constraint in splitting so that no equal independent vectors can appear in both training and test sets, it does not imply deduplication.
I'm analytical chemist and I do something similar when I test performance for concentrations that are (slightly) different matrix* composition.

The second point is that if your original sample is representative for your population, then the dedupicated sample will be biased. In other words, do the duplicates occur naturally or  were they produced artificially?

In the former case, I'd say you need very good argumentation why you want to change your sample distribution.
You can still deduplicate, but it is up to you to correctly account for that treatment. As @Ingolifs said already, you may be able to save computation by replacing duplicates with appropriate weights. That holds for testing as well.
For deduplicated test sets, you'll have to be particularly careful about the conclusions you draw. I'm thinking of the somewhat related issue of reporting predictive values that can be seriously wrong if they do not take into account the actual class distributions - see Buchen: Cancer: Missing the mark, Nature 471, 428-432 (2011). for a famous example.

* in analytical chemistry matrix is the stuff surrounding the analyte you're interested in. Say I'm looking at ethanol in wine, then the water, acids and all other substances except the ethanol form the matrix.


Passing parameter to a function reached via a buffer overflow

Question: I have written this simple main that I compiled with the flag -fno-stack-protector.
#include <stdio.h>
int pos;
char c = 0;

void
bof(unsigned int i)
{
   fprintf(stderr, "BOF %u\n", i);
}

void
foo()
{
   unsigned char buf[3];
   while(c != 'X') {
    scanf(" %c", &c);
    buf[pos++] = c;
  }
}

int
main() {
  fprintf(stderr, "%p\n", bof);
  foo();
  return 0;
}

I'm trying to pass 0 to the input variable of the bof function, and to be sure I surrounded the address of the bof function with zeros.
(note that I use ubuntu 12.04 v. 64 bit):
perl -e 'print "\x00"x24  . "\xa4\x05\x40\x00\x00\x00\x00\x00" . "\x00"x8 . "X"'
The problem is that executing the program with this buffer the printed result is not zero (it is not even constant), but when I try to debug the program:
perl -e 'print "\x00"x24  . "\xa4\x05\x40\x00\x00\x00\x00\x00" . "\x00"x8 . "X"' > file
(gdb) b 19
Breakpoint 4 at 0x40061b: file main.c, line 19.
(gdb) r < file
The program being debugged has been started already.

Start it from the beginning? (y or n) y
Starting program: /home/badnack/Documents/Code/stuff/bof/bof < file
0x4005a4

Breakpoint 4, foo () at main.c:19
19  }
(gdb) l
14    unsigned char buf[3];
15    while(c != 'X') {
16      scanf(" %c", &c);
17      buf[pos++] = c;
18    }
19  }
20
21  int
22  main() {
23    fprintf(stderr, "%p\n", bof);
(gdb) l
24    foo();
25    return 0;
26  }
(gdb) disass
Dump of assembler code for function foo:
   0x00000000004005d0 <+0>: push   %rbp
   0x00000000004005d1 <+1>: mov    %rsp,%rbp
   0x00000000004005d4 <+4>: sub    $0x10,%rsp
   0x00000000004005d8 <+8>: jmp    0x400610 <foo+64>
   0x00000000004005da <+10>:    mov    $0x400755,%eax
   0x00000000004005df <+15>:    mov    $0x601040,%esi
   0x00000000004005e4 <+20>:    mov    %rax,%rdi
   0x00000000004005e7 <+23>:    mov    $0x0,%eax
   0x00000000004005ec <+28>:    callq  0x4004b0 <__isoc99_scanf@plt>
   0x00000000004005f1 <+33>:    mov    0x200a4d(%rip),%eax        # 0x601044 <pos>
   0x00000000004005f7 <+39>:    movzbl 0x200a42(%rip),%edx        # 0x601040 <c>
   0x00000000004005fe <+46>:    mov    %edx,%ecx
   0x0000000000400600 <+48>:    movslq %eax,%rdx
   0x0000000000400603 <+51>:    mov    %cl,-0x10(%rbp,%rdx,1)
   0x0000000000400607 <+55>:    add    $0x1,%eax
   0x000000000040060a <+58>:    mov    %eax,0x200a34(%rip)        # 0x601044 <pos>
   0x0000000000400610 <+64>:    movzbl 0x200a29(%rip),%eax        # 0x601040 <c>
   0x0000000000400617 <+71>:    cmp    $0x58,%al
   0x0000000000400619 <+73>:    jne    0x4005da <foo+10>
=> 0x000000000040061b <+75>:    leaveq
   0x000000000040061c <+76>:    retq
End of assembler dump.
(gdb) ni
0x000000000040061c  19  }
(gdb) x/10xg $rsp
0x7fffffffe278: 0x00000000004005a4  0x0000000000000000
0x7fffffffe288: 0x00007ffff7a3b758  0x0000000000000000
0x7fffffffe298: 0x00007fffffffe368  0x0000000100000000
0x7fffffffe2a8: 0x000000000040061d  0x0000000000000000
0x7fffffffe2b8: 0xbc2b8a4223791ede  0x00000000004004c0
(gdb) n
bof (i=0) at main.c:7
7   {
(gdb) x/10xg $rsp
0x7fffffffe280: 0x0000000000000000  0x00007ffff7a3b758
0x7fffffffe290: 0x0000000000000000  0x00007fffffffe368
0x7fffffffe2a0: 0x0000000100000000  0x000000000040061d
0x7fffffffe2b0: 0x0000000000000000  0xbc2b8a4223791ede
0x7fffffffe2c0: 0x00000000004004c0  0x00007fffffffe360
(gdb) n
8     fprintf(stderr, "BOF %u\n", i);
(gdb) n
BOF 4158473024
9   }
(gdb) x/10xg $rsp
0x7fffffffe268: 0x0000000000000000  0xf7dd434000000000
0x7fffffffe278: 0x0000000000000000  0x0000000000000000
0x7fffffffe288: 0x00007ffff7a3b758  0x0000000000000000
0x7fffffffe298: 0x00007fffffffe368  0x0000000100000000
0x7fffffffe2a8: 0x000000000040061d  0x0000000000000000
(gdb)

The i variable seems to receive the correct value, but then another value is printed (which is exactly the decimal representation of 0xf7dd434000000000. What is happening? Why this cell of memory is not present also before?
Answer: To know exactly what is happening, we would have to look at the assembler code for function bof. Anyway, an oversight in your approach is that you did not write the parameter value onto the stack; the 8-byte return address "\xa4\x05\x40\x00\x00\x00\x00\x00" is popped off the stack by the retq in foo - we see this from the difference between before
0x7fffffffe278: 0x00000000004005a4  0x0000000000000000
0x7fffffffe288: 0x00007ffff7a3b758

and after the retq
0x7fffffffe280: 0x0000000000000000  0x00007ffff7a3b758

(now in bof). The "\x00"x8 is now in place of the return address from bof, which would have been pushed on top of stack if bof were called regularly by callq.
Moreover, the calling convention used seems to be System V Application Binary Interface, where the 1st (and in this case only) argument to function bof is passed in register %rdi, not on the stack.


High note =high energy?

Question: Does a higher note always needs more energy to sing than a lower note? Is it possible for a singer to sing a higher note using same energy used to sing a lower note?
Answer: No, a higher note does not necessarily require more energy to sing. A simple example is the use of falsetto which can be done with very little effort—certainly less than the same singer singing the same pitch using their modal voice.
Comment: @ David Vogel, Yes,that answers my question.We can use this information while producing electronic sound.
Comment: No problem. Does that answer your question?

High note =high energy?


Web scraping. First page data duplicated

Question: Here is code using Bs4 and pandas dataframe to scrape two websites' data . second page successfully scraped but instead of showing second page data first page's data duplicated .

@app.route('/')
def index():
    try:
        webpage1 = requests.get('https://bekorganics.myshopify.com/collections/nuts')
        sp1 = BeautifulSoup(webpage1.content, 'html.parser')
        webpage2 = requests.get('https://perfectorganics.myshopify.com/collections/nuts-1')
        sp2 = BeautifulSoup(webpage2.content, 'html.parser')
    except Exception as e:
        # Handle the exception here, e.g. log the error, display an error message to the user, etc.
            print(f"An error occurred: {e}")
            return "Sorry, we could not process your request at this time. Please try again later."

    data1 = []
    for i in range(1, 3):
        #Extracting data from first website

        url = f'https://bekorganics.myshopify.com/collections/nuts?page={i}'
        webpage = requests.get(url)
        sp = BeautifulSoup(webpage.content, 'html.parser')
        title1 = sp.find_all('div', 'card__information')
        sellprice1 = sp.find_all('span', 'price-item price-item--regular')
        for title0, sellprice0 in zip(title1, sellprice1):
            title_text = title0.find('a').text
            price_text= sellprice0.text
            if title_text and price_text:
                product = {'Name of Product': title_text.strip(), 'Selling Price': re.sub(r'\s+', ' ', price_text.strip())}
                data1.append(product)
        next_page = sp.find('a', {'class': 'page-link', 'rel': 'next'})

two websites scraped data
First page data keep repeating and i am trying to avoid data repeating and trying to scrape next page data
Comment: I haven't solved your problem but just an FYI you can add "/products.json" to the end of the url to get pretty json back instead of having to parse html   https://perfectorganics.myshopify.com/collections/nuts-1/products.json & https://bekorganics.myshopify.com/collections/nuts/products.json
Answer: Mis-aligned data is a common issue that crops up when you zip lists together without checking whether they are actually aligned with each other.

but instead of showing second page data first page's data duplicated

It's not just the first page data - names from all pages are duplicate (not the prices though). Add print(len(title1), 'titles and', len(sellprice1), 'prices from', url) just before the for title0, sellprice0 ... loop and you'll see that there are always twice as many items in title1 as there are in sellprice1 (view screenshot).

Rather than zipping different ResultSets together, it would be better to loop through a single ResultSet of elements that contain all the data you might want in a row. Something like
        for product in sp.find_all('li', class_='grid__item'):
            title = product.find('div', class_='card__information')
            if title: title = title.find('a')
            price = product.find('span', class_='price-item price-item--regular')
            if title and title:
                data1.append({
                    'Name of Product': title.text.strip(),
                    'Selling Price': re.sub(r'\s+', ' ', price.text.strip())
                })

or with .select and list comprehension:
        title_sel,price_sel = 'div.card__information a','span.price-item.price-item--regular'
        product_sel = f'li.grid__item:has({title_sel}):has({price_sel})'

        data1 += [{
            'Name of Product': product.select_one(title_sel).text.strip(),
            'Selling Price': re.sub(r'\s+', ' ', product.select_one(price_sel).text.strip())
        } for product in sp.select(product_sel)]

        next_page = sp.find('a', {'class': 'page-link', 'rel': 'next'})

If you fix this (.find('a', {'href':True, 'aria-label':"Next page"})), you can change to a while loop:
    max_pg = None # 2 # 10 # set any limit
    url = f'https://bekorganics.myshopify.com/collections/nuts'

    data1, cur_pg = [], 0
    title_sel,price_sel = 'div.card__information a','span.price-item.price-item--regular'
    product_sel = f'li.grid__item:has({title_sel}):has({price_sel})'
    while url and (cur_pg:=cur_pg+1)<=(max_pg if max_pg is not None else cur_pg):
        sp = BeautifulSoup((webpage:=requests.get(url)).content, 'html.parser')

        data1 += [{
          'Name of Product': product.select_one(title_sel).text.strip(),
          'Selling Price': re.sub(r'\s+', ' ', product.select_one(price_sel).text.strip())
        } for product in sp.select(product_sel)]

        nextPg = sp.find('a', {'href':True, 'aria-label':"Next page"})
        url = 'https://bekorganics.myshopify.com'+nextPg['href'] if nextPg else None

"...FYI you can add "/products.json" to the end of the url to get pretty json back instead of having to parse html..." - comment by childnick

Then you don't have to bother with looping through pagination at all.
json_url = 'https://bekorganics.myshopify.com/collections/nuts/products.json'
json_data = requests.get(json_url).json()
data1 = [{
    'Name of Product': p['title'], 'Selling Price': f"£{p['variants'][0]['price']}"
} for p in json_data['products']]

With any of the above suggestions, the output should look like:


How to get all CheckBoxes using C#?

Question: In Asp.net. how can I access every checkbox exists in the page using C# code ?
Comment: You can access checkboxes via their IDs if they are server-control.
Answer: This gets you every Checkbox on the page. You can change the form1 to whatever control you want to search inside of.
foreach (Control ctl in form1.Controls)
{
    if (ctl is CheckBox)
    {

    }
}

Alternatively if you know the ID of the control:
form1.FindControl("id");

How to get all CheckBoxes using C#?


How to determine experiment sample size for a target CI width?

Question: I'm working on an experiment to measure property $X$ of some pieces of equipment. Assuming there is an excess of equipment available for testing, and barring any funding restrictions, what is the best procedure for choosing how many measurements to make, so that I have a set confidence interval width?
Valid values for property $X$ are strictly positive, but their range is quite wide; typical values can reasonably be as little as $0.01$ and as large as $3000$. For this particular test, I expect the measurements to fall in the $3-20$ range.
Answer: I am hardly a good statistician, but I'll try to contribute. Can't comment for now (not enough Reputation) so directly as an answer. Assuming you want a CI at 95% and normal distribution of your measurements, CI definition is
$CI= 1.96* (sd /\sqrt{N})$
with sd the standard deviation and N the number of samples.
Your measurements will be between $3-20$, so you might assume worst-case-scenario with large sd.  Based on thin air I assumed a sd of $15$ but very simple (and perhaps unnecessary) R simulations showed sd to be between $4$ and $6.5$ for an expected range of $3-20$. A sd of $6.5$ may then help choose a "cautious" (i.e, quite large) sample size.
EDIT: simulations for sd estimation
<code># Ranges for outcomes
widest_range=seq(from=0,to=3000,by=1)
likely_range=seq(from=3,to=20,by=1)

# matrix to store the results
nb_sims=30
Mat_Results=matrix(0,ncol=2,nrow=nb_sims)
colnames(Mat_Results)=c("Widest_range","Likely_range")

# sims
for (i in (1:nb_sims)) {
  # sampling assuming 10 measures (EDIT: uniform distribution)
  measures_widest=sample(widest_range, 10, replace = FALSE, prob = NULL)
  measures_likely=sample(likely_range, 10, replace = FALSE, prob = NULL)
  # sd
  Mat_Results[i,1]=sd(measures_widest)
  Mat_Results[i,2]=sd(measures_likely)
}

x11()
par(mfrow=c(1,2))
boxplot(Mat_Results[,1],main="SD with widest range")
boxplot(Mat_Results[,2],main="SD with likely range")
</code>
Comment: Hey, thanks! Assuming normal distribution for my measurements and a $95\%$ CI, a range of $3-20$ for them would yield an SD of about $5$, no?
Comment: Definitely not standard, but I don't mind! Again assuming normality, the mean of a sample whose range is $3-20$ is $11.5$. Assuming that range represents a $95\%$ CI (which is more of a leap than the normality assumption), $\sigma_{sample} = \frac{20-11.5}{1.96} = 4.34$.
Comment: Yes, you're right. I don't know whether there's a mathemical rule behind that, but I tried a very quick simulation on R and I get a mean sd of $5.5$ out of 30 simulations (for $n=10$ measurements per simulation). $95$% simulated sd between $4$ and $6.5$. For the range of $0$ to $3000$ (I simplified the max. range that you were talking about), mean sd of $850$!
Comment: That $0-3000$ range refers to acceptable values for this particular property (for any pieces of equipment). Measurement will narrow that down considerably, I hope.
Comment: I hope so too. I just did it for fun. Within your likely range of values, highest sd to be expected seems $6.5$. You could determine your sample size based on that value (kind of an expect-the-worse approach).
Comment: Apart from simulations, do you know a rule for sd estimation based on expected range? (yes, I am asking you a question in your thread - perhaps not standard).
Comment: Ok, nice. Many thanks. This formula/trick may be useful to others (as it is for me), so you should perhaps include it somewhere? Thanks again.
Comment: I'm not sure where that'd be, though. It's not really an answer, and it doesn't really make sense in the question...
Answer: In my experience, taking a small sample (less than 10, or 5% of the overall number of equipments) doing several measurements gives an indication of how many measurements need to be done to have a good CI.
For instance,
if I have 50 pieces, I am going to take 5 pieces, do several measurements until I find a balance for each of the 5 pieces, ranging from 3 measurements to 10 first. If I don't find a balance, I'll redo the measurements, but this time 11 to 20 times (and so on). Once I have a smoothed average of measurements, I'll deploy the method to the overall pieces.
This will give you an estimated standard deviation.
Based on that and your level of confidence, you can, then, build your CI with the formula I assume you already know.
Comment: That helps, thanks. In my case, though, the individual measurements destroys the piece of equipment, so I can't really do more than one measurement on each piece. Also, I assume this initial procedure is to get a feel for the sample standard deviation, correct? What should I do with it subsequently?
Comment: Yes, it is. Once you have an estimation of your standard deviation, you can choose the level of confidence of your interval (85, 90, 95, 99%). Then you can calculate the CI, check if it falls within your expected range. - How many measurement can you do?
Comment: I'd say it would be ideal to keep the number of measurements under 20 (seeing as each one takes a good 8 hours), but I guess it would depend on how tight I'd want the CI to be, which I don't know yet. Assuming the errors are normally distributed, I'm wondering if using a straight normal distribution for the sample mean is appropriate (as opposed to, say, a Student-t to correct for the low number of samples).
Comment: Given your expected range, do you have an expected mean or `SD`? - if the distribution is gaussian, then using a gaussian distribution seems appropriate, the low number of the sample only intervenes if the distribution is not gaussian, over 30 gaussian and student give both more or less the same intervals. I would start on 6 measurements to test the waters (so to speak)
Comment: I have an estimate of the SD, by assuming normality and that the range represents a $95\%$ CI. Since I was expecting to do something like 10-15 samples, I though that assuming normality would be folly. Anyway, that sounds like a good strategy. Thanks again!


Creating different brush patterns in c#

Question: I'm trying to make something similar to paint. I'm trying to figure out how make different brush styles. Like in Paint 3D you get a certain line fills when using the pen tool vs using the paint brush tool.

I have no idea where to even start. I've spent a good portion of the day looking through documentations, and watching YouTube videos. I'm more lost than when I started. The closest thing I came across was line caps, but that's definitely not what I'm looking for.
Comment: https://learn.microsoft.com/en-us/dotnet/framework/winforms/advanced/how-to-fill-a-shape-with-an-image-texture
Comment: Do have a look at my update, which abandons the idea of TextureBrush altogether..
Comment: one of [those](https://stackoverflow.com/search?q=user%3A3152130+floodfill) may help for filling with solid colors..
Answer: !!See the UPDATE below!!
Hans' link should point you in the right direction, namely toward TextureBrushes.
To help you further here a few points to observe:

TextureBrush is a brush, not a pen. So you can't follow a path, like the mouse movements to draw along that curve. Instead, you need to find an area to fill with the brush.
This also implies that you need to decide how and when to trigger the drawing; basic options are by time and/or by distance. Usually, the user can set parameters for these often called 'flow' and 'distance'..
Instead of filling a simple shape and drawing many of those,  you can keep adding the shapes to a GraphicsPath and fill that path.
To create a TextureBrush  you need a pattern file that has transparency. You can either make some or download them from the web where loads of them are around, many for free.
Most are in the Photoshop Brush format 'abr'; if they are not too recent (<=CS5) you can use abrMate to convert them to png files.
You can load a set of brushes to an ImageList, set up for large enough size (max 256x256) and 32bpp to allow alpha.
Most patterns are black with alpha, so if you want color you need to create a colored version of the current brush image (maybe using a ColorMatrix).
You may also want to change its transparency (best also with the ColorMatrix).
And you will want to change the size to the current brush size.

Update
After doing a few tests I have to retract the original assumption that a TextureBrush is a suitable tool for drawing with textured tips.
It is OK for filling areas, but for drawing free-hand style it will not work properly. There are several reasons..:

one is that the TextureBrush will always tile the pattern in some way, flipped or not and this will always look like you are revealing one big underlying pattern instead of piling paint with several strokes.
Another is that finding the area to fill is rather problematic.
Also, tips may or may not be square but unless you fill with a rectangle there will be gaps.

See here for an example of what you don't want at work.
The solution is really simple and much of the above still applies:

What you do is pretty much regular drawing but in the end, you do a DrawImage with the prepared 'brush' pattern.

Regular drawing involves:

A List<List<Point>> curves that hold all the finished mouse paths
A List<Point> curentCurve for the current path

In the Paint event you draw all the curves and, if it has any points, also the current path.
For drawing with a pattern, it is necessary to also know when to draw which pattern version.
If we make sure not to leak them we can cache the brush patterns..:
Bitmap brushPattern = null;
List<Tuple<Bitmap,List<Point>>> curves = new List<Tuple<Bitmap,List<Point>>>();
Tuple<Bitmap, List<Point>> curCurve = null;

This is a simple/simplistic caching method. For better efficiency you could use a  Dictionary<string, Bitmap> with a naming scheme that produces a string from the pattern index, size, color, alpha and maybe a rotation angle; this way each pattern would be stored only once.
Here is an example at work:

A few notes:
In the MouseDown we create a new current curve:
curCurve = new Tuple<Bitmap, List<Point>>(brushPattern, new List<Point>());
curCurve.Item2.Add(e.Location);

In the MouseUp I add the current curve to the curves list:
 curves.Add(new Tuple<Bitmap, List<Point>>(curCurve.Item1, curCurve.Item2.ToList()));

Since we want to clear the current curve, we need to copy its points list; this is achieved by the ToList() call!
In the MouseMove we simply add a new point to it:
if (e.Button == MouseButtons.Left)
{
    curCurve.Item2.Add(e.Location);
    panel1.Invalidate();
}

The Paint goes over all curves including the current one:
for (int c = 0; c < curves.Count; c++)
{
    e.Graphics.TranslateTransform(-curves[c].Item1.Width / 2, -curves[c].Item1.Height / 2);
    foreach (var p in curves[c].Item2)
        e.Graphics.DrawImage(curves[c].Item1, p);
    e.Graphics.ResetTransform();
}
if (curCurve != null && curCurve.Item2.Count > 0)
{
    e.Graphics.TranslateTransform(-curCurve.Item1.Width / 2, -curCurve.Item1.Height / 2);

    foreach (var p in curCurve.Item2)
        e.Graphics.DrawImage(curCurve.Item1, p);
    e.Graphics.ResetTransform();
}

It makes sure the patterns are drawn centered.
The ListView is set to SmallIcons and its SmallImageList points to a smaller copy of the original ImageList.
It is important to make the Panel Doublebuffered! to avoid flicker!

Update: Instead of a Panel, which is a Container control and not really meant to draw onto you can use a Picturebox or a Label (with Autosize=false); both have the DoubleBuffered property turned on out of the box and support drawing better than Panels do.
Btw: The above quick and dirty example has only 200 (uncommented) lines. Adding brush rotation, preview, a stepping distance, a save button and implementing the brushes cache takes it to 300 lines.
Comment: oh damn that's niftier than texture brushes!
Comment: @TaW Sorry, I didn't get the part with the ColorMatrix. I scrolled through the doc. of [`QBrush`](http://doc.qt.io/qt-5/qbrush.html) but I couldn't find anything related. This arised in a follow-up question [SO: QPainter how draw texture with special color](https://stackoverflow.com/q/51940533/7478597). I would be happy if you could elaborate this a bit (to enlight us).
Comment: A ColorMatrix is a quick and simple way to change images. See [here](https://docs.rainmeter.net/tips/colormatrix-guide/) for a great guide. - See [here](https://stackoverflow.com/questions/51526858/c-sharp-color-an-image-with-shadows/51533537?s=1|42.5328#51533537) for more coloring an image it. - See [here](https://stackoverflow.com/questions/44749869/picturebox-slider-control-transparency/44758640?s=4|28.6410#44758640) for more on changing alpha (ie transparency.
Comment: @TaW , hello! Can you provide source codes of this project? I was try to reproduce, but it's very ugly. As I understand, you make this example for WinForms? I need an WPF version, but if you don't have wpf, please, give your winForms full example? Update your answer with URL (source code), please?

Creating different brush patterns in c#


A missing or empty content type header was found when trying to read a message. The content type header is required

Question: I am using a SAP odata service and I added it as a web reference in visual studio 2012.
 Uri serviceUri = new Uri("http://zbc.net:4521/sap/opu/odata/sap/Emp/", UriKind.Absolute);
            Emp context = new Emp(serviceUri);

            context.Credentials = new System.Net.NetworkCredential("loginanme", "pass");

            var query = from b in context.Employees
                        where b.Role == "Admin"
                        select b;

            foreach (var myObject in query)
            {
                Console.WriteLine("\n name: {0} | role: {1}", myObject.name, myObject.Role);

            }

When I execute the code above, I get the following error:
"An error occurred while processing this request."

InnerException: "A missing or empty content type header was found when trying to read a message. The content type header is required."

this is the query that VS2012 produces:

Query: {http://zbc.net:4521/sap/opu/odata/sap/Emp/Employees()?$filter=Role eq 'Admin'}

StackTrace:

   at Microsoft.Data.OData.ODataMessageReader.GetContentTypeHeader()
   at Microsoft.Data.OData.ODataMessageReader.TryGetSinglePayloadKindResultFromContentType(IEnumerable`1& payloadKindResults, MediaType& contentType, Encoding& contentEncoding)
   at Microsoft.Data.OData.ODataMessageReader.DetectPayloadKind()
   at System.Data.Services.Client.Materialization.ODataMaterializer.CreateODataMessageReader(IODataResponseMessage responseMessage, ResponseInfo responseInfo, Boolean projectionQuery, ODataPayloadKind& payloadKind)
   at System.Data.Services.Client.Materialization.ODataMaterializer.CreateMaterializerForMessage(IODataResponseMessage responseMessage, ResponseInfo responseInfo, Type materializerType, QueryComponents queryComponents, ProjectionPlan plan, ODataPayloadKind payloadKind)
   at System.Data.Services.Client.MaterializeAtom..ctor(ResponseInfo responseInfo, QueryComponents queryComponents, ProjectionPlan plan, IODataResponseMessage responseMessage, ODataPayloadKind payloadKind)
   at System.Data.Services.Client.QueryResult.CreateMaterializer(ProjectionPlan plan, ODataPayloadKind payloadKind)
   at System.Data.Services.Client.QueryResult.ProcessResult[TElement](ProjectionPlan plan)
   at System.Data.Services.Client.DataServiceRequest.Execute[TElement](DataServiceContext context, QueryComponents queryComponents)

Response from RESTClient (firefox add-on)
Status Code: 200 OK
Content-Encoding: gzip
Content-Length: 566
Content-Type: application/xml
Last-Modified: Tue, 09 Jul 2013 13:03:22 GMT
Server: SAP NetWeaver Application Server / ABAP 731
dataserviceversion: 2.0

Response body
<?xml version="1.0" encoding="utf-8"?>
    <edmx:Edmx Version="1.0" xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx"
    xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"
    xmlns:sap="http://www.sap.com/Protocols/SAPData">
    <edmx:DataServices m:DataServiceVersion="2.0">
    <Schema Namespace="Emp" xml:lang="en" xmlns="http://schemas.microsoft.com/ado/2008/09/edm">
    <EntityType Name="Bank" sap:content-version="1">
    <Key>
        <PropertyRef Name="Admin"/>
    </Key>
     <Property Name="Name" Type="Edm.String" MaxLength="35" sap:label="Name"/>
    <Property Name="street" Type="Edm.String" MaxLength="35" sap:label="Street"/>
    <Property Name="Role" Type="Edm.String" MaxLength="35" sap:label="Role"/>
    <Property Name="Region" Type="Edm.String" MaxLength="3" sap:label="Region"/>
    </EntityType>
    <EntityContainer Name="Emp" m:IsDefaultEntityContainer="true">
    <EntitySet Name="Employees" EntityType="Emp.Employee" sap:deletable="false" sap:content-version="1"/>
    </EntityContainer>
    <atom:link rel="self" href="http://zbc.net:4521/sap/opu/odata/sap/Emp/$metadata" xmlns:atom="http://www.w3.org/2005/Atom"/>
    <atom:link rel="latest-version" href="http://zbc.net:4521/sap/opu/odata/sap/Emp/$metadata"
    xmlns:atom="http://www.w3.org/2005/Atom"/>
    </Schema>
    </edmx:DataServices>
    </edmx:Edmx>

From Fiddler I get the following response:
HTTP/1.1 401 Unauthorized
www-authenticate: Basic realm="SAP NetWeaver Application Server [SVD/800]"
content-length: 2180
content-type: text/html; charset=utf-8
server: SAP NetWeaver Application Server / ABAP 731

How come in fiddler I get a 401? How can I provide a login and pass in Fiddler so that I don't get a 401?
Comment: Can you include the HTTP headers and payload of the response from the server that's causing this exception (using a tool like Fiddler)?
Comment: Can you try installing the latest WCF Data Services from NuGet?http://blogs.msdn.com/b/astoriateam/archive/2013/05/30/wcf-data-services-5-5-0-release.aspx. The early releases of ODataLib where case sensitive on HTTP header names (which is technically correct, but some services don't work well with that).
Comment: I haven't added the WCF Data Services 5.5.0. yet. I have to download and install it in offline mode since we don't have access to internet in our dev machines
Comment: anyone has got any idea how to include the header in my calling code?
Comment: Are you sure those HTTP traces are coming from the right request?  The response xml you included is the kind of response you'd get from requesting $metadata, not `http://zbc.net:4521/sap/opu/odata/sap/Emp/Employees()`.  Also, did you get a chance to download the latest WCF Data Service client? I bet that will solve your problem.
Comment: (And it doesn't seem like this is a problem with the headers in the calling code, but rather the headers coming back from the server. I think SAP is returning a lowercase "content-type" header and the client doesn't recognize it.)
Comment: Hi Jen S, when I use http://zbc.net:4521/sap/opu/odata/sap/Emp/Employees() I get the data, but that is via the browser.

the server administrator has installed Nuget Package Manager: Version 2.6.40627.9000. So I thing, WCF 5.5 should be there.
Answer: Thanks Vitek Karas MSFT for your suggestion. The issue is sovled by installing the latest version of WCF Data Services 5.6.0. and thanks to Maikel who tried in on our dev and was able to solve the issue.


Why the space of skew-symmetric tensors $\Lambda^{n}V$ is a one dimensional if $dim(V)=n$

Question: While reading Liviu Nicolaescu  Lectures on the geometry of manifolds, I came accross the notion of "determinant line":
Definition: Lev $V$ be an n-dimensional R-vector space. The one dimensional vector space $\Lambda^{n}V$ is called the determinant line. Here, $\Lambda^{n}V$ is a space of skew-symmetric (a.k.a. antisymmetric) tensors.
My question is why $\Lambda^{n}V$ is a one-dimensional vector space? I think that this has something to do with the fact that the degrees of the tensors in that spaces is equal to the dimension of $V$, i.e. $n=dim V$. But I cann't figure this one out. Any guidance would be very appreciated.
Answer: Using a basis $e_i$ of the vector space $V$, one can show that $Λ^kV$ has a basis composed of
$$e_{i_1}\wedge e_{i_2}\wedge\dots\wedge e_{i_k}\text{ where }1\le i_1<i_2<\dots<i_k\le n,$$
so $\dim Λ^kV=\binom nk$. Thus $Λ^nV$ has exactly one basis element and so dimension $1$.
Comment: Indeed, if $v_1, \dotsc, v_n \in V$, then
$$
 v_1 \wedge \cdots \wedge v_n = \det(v_{ij}) e_1 \wedge \cdots \wedge e_n,
$$
where for each $j$,
$$
 v_j = \sum_{i} v_{ij} e_i.
$$


Notation for multilevel modeling

Question: The formula one needs to specify for training a multilevel model (using lmer from lme4 R library) always gets me. I have read countless textbooks and tutorials, but never properly understood it.
So here's an example from this tutorial that I would like to see formulated in an equation. We are trying to model voice frequency as a function of gender (females have higher pitched voice than males in general) and attitude of the person (whether he/she answered in a polite or informal manner) in different scenarios. Also, as you can see from the subject column, each person was subjected to measurements several times.
> head(politeness, n=20)
   subject gender scenario attitude frequency
1       F1      F        1      pol     213.3
2       F1      F        1      inf     204.5
3       F1      F        2      pol     285.1
4       F1      F        2      inf     259.7
5       F1      F        3      pol     203.9
6       F1      F        3      inf     286.9
7       F1      F        4      pol     250.8
8       F1      F        4      inf     276.8
9       F1      F        5      pol     231.9
10      F1      F        5      inf     252.4
11      F1      F        6      pol     181.2
12      F1      F        6      inf     230.7
13      F1      F        7      inf     216.5
14      F1      F        7      pol     154.8
15      F3      F        1      pol     229.7
16      F3      F        1      inf     237.3
17      F3      F        2      pol     236.8
18      F3      F        2      inf     251.0
19      F3      F        3      pol     267.0
20      F3      F        3      inf     266.0

subject, gender and attitude are factors (with informal and female considered as base levels for attitude and gender in equations below). Now, one idea is to train a model with differing intercepts for each subject and scenario:
politeness.model=lmer(frequency ~ attitude + gender +
 (1|subject) + (1|scenario), data=politeness)

If my understanding of the notation is correct, this corresponds to:
$y_i=a^1_{j[i]}+a^2_{k[i]}+\beta\cdot$ attitude$_{\text{pol}_i} + \gamma\cdot$ gender$_{\text{male}_i}$
where $i$ denotes $i^{th}$ data point, $j[i]$ denotes group level for subject and $k[i]$ denotes group level for scenario for $i^{th}$ data point. attitude$_\text{pol}$ and gender$_\text{male}$ are an binary indicators.
To introduce random slopes for attitude, we can write:
politeness.model = lmer(frequency ~ attitude + gender +
 (1+attitude|subject) + (1+attitude|scenario), data=politeness)

Again, if my understanding is clear, this corresponds to:
$y_i = a^1_{j[i]} + a^2_{k[i]} + (\beta^1_{j[i]} + \beta^2_{k[i]})\cdot$ attitude$_{\text{pol}_i} + \gamma\cdot$ gender$_{\text{male}_i}$
Now, what equation does the following R command correspond to?
politeness.null = lmer(frequency ~ gender +
 (1+attitude|subject) +  (1+attitude|scenario), data=politeness)

Comment: not a very sensible one; the population average slope with respect to attitude is assumed to be zero  ...
Comment: @BenBolker: Hey, can you please write it in an equation form? Are my previous equations correct? In the last model, I still see `attitude` being conditioned on `subject` and `scenario`.
Answer: I would write
~ attitude + gender + (1|subject) + (1|scenario)

as
$$
y_i \sim \beta_0 + \beta_1 \cdot I(\textrm{attitude}=\textrm{pol}) + \beta_2 I(\textrm{gender}=\textrm{male}) + b_{1,j[i]} + b_{2,k[i]} + \epsilon_i \\
b_1 \sim N(0,\sigma^2_1) \\
b_2 \sim N(0,\sigma^2_2) \\
\epsilon \sim N(0,\sigma^2_r)
$$
where $\beta$ indicates a fixed-effect coefficient, $b$ indicates a random variable, $I$ is an indicator function (this is basically the same as what you said above, just slightly different notation).
~ attitude + gender + (1+attitude|subject) + (1+attitude|scenario)

adds among-subject variation in response to attitude and scenario (we could equivalently write the random-effects part as (attitude|subject) + (attitude|scenario), i.e. leaving the intercept implicit; this is a matter of taste). Now
$$
y_i \sim \beta_0 + \beta_1 \cdot I(\textrm{attitude}=\textrm{pol}) + \beta_2 I(\textrm{gender}=\textrm{male}) + \\
  b_{1,j[i]} + b_{3,j[i]} I(\textrm{attitude}=\textrm{pol}) +
  b_{2,k[i]} + b_{4,k[i]} I(\textrm{attitude}=\textrm{pol}) + \epsilon_i
\\
\{b_1,b_3\} \sim \textrm{MVN}({\mathbf 0},\Sigma_1) \\
\{b_2,b_4\} \sim \textrm{MVN}({\mathbf 0},\Sigma_2)  \\
\epsilon \sim N(0,\sigma^2_r)
$$
where $\Sigma_1$ and $\Sigma_2$ are unstructured variance-covariance matrices, i.e. they are symmetric and positive (semi)definite but have no other constraints:
$$
\Sigma_1 = \left( \begin{array}{cc} \sigma^2_1 & \sigma_{13} \\
              \sigma_{13} & \sigma^2_3 \end{array} \right)
$$
and similarly for $\Sigma_2$.
It might be instructive to group terms as follows:
$$
y_i \sim (\beta_0 + b_{1,j[i]} + b_{2,k[i]}) + \\
    ( \beta_1 + b_{3,j[i]} + b_{4,k[i]}) \cdot I(\textrm{attitude}=\textrm{pol}) + \beta_2 I(\textrm{gender}=\textrm{male}) + \epsilon_i
$$
so you can see which random effects are affecting the intercept and which are affecting the response to attitude.
Now if you leave out the fixed-effect attitude term (i.e. set $\beta_1=0$, or drop the attitude term from the formula) you can see (without rewriting everything) that, because the random effects are assumed to have zero mean, we will be assuming that the average response to attitude across subjects and scenarios will be exactly zero, while there is still variation among subjects and scenarios.  I won't say this never makes sense from a statistical point of view, but it rarely does.  There are discussions of this issue on the email@example.com mailing list from time to time ... (or it may be discussed on StackExchange somewhere -- if not, it would make a good follow-up SE question ...)

Notation for multilevel modeling


Read Input till quit statement prolog

Question: So I'm coding a chat Bot and I need to keep taking input from the user as long as they don't type 'quit.', but if they do I must do a certain recap of what the user asked and then return true , I'm having trouble with the predicate that will keep reading the input till quit is typed , Can anyone help me?
Thanks
Comment: What have you tried so far? Show the code you've been working on.
Comment: @lurker I have tried to use repeat but it caused a lot of problems , so I have to find another way , keeping in mind that I want to keep a set of all the inputs.
Answer: The question is worded rather generally, so here's a description of how to make it work in Prolog semi-pseudo-code:
user_input :-
    repeat,
    read_a_line(Line),
    (   Line = quit  % You might have another way to check this depending...
    ->  write('Finished'), nl,
        !, true
    ;   do_something_with(Line),
        fail
    ).

The way the repeat-fail loop works is that you want to fail to continue to do your loop. Then for exiting the loop, you want to succeed with a cut.

Read Input till quit statement prolog


What is the difference between an Epoch and an Episode?

Question: I am working on DQN and have confused myself with Epoch and Episode. I have gone through this answer but the confusion is increased.
I will explain my scenario and would like to understand the difference through it if anyone could guide me better.
Here is my scenario:
I have written a DQN Agent with the following properties:
class DQNAgent(nn.Module):
    def __init__(self, state_size, action_size):
        super().__init__()
        self.state_size = state_size
        self.action_size = action_size
        self.memory = deque(maxlen=2000)
        # print(f"self.memory {type(self.memory)}")
        self.gamma = 0.95  # discount rate
        self.epsilon = 1.0  # exploration rate
        self.epsilon_min = 0.01
        self.epsilon_decay = 0.995
        self.learning_rate = 0.001
        self.model = self._build_model()

    def _build_model(self):
        # Neural Net for Deep-Q learning Model
        model = Sequential()
        model.add(Dense(24, input_dim=4, activation='relu'))
        model.add(Dense(24, activation='relu'))
        model.add(Dense(self.action_size, activation='linear'))
        model.compile(loss='mse',
                      optimizer=Adam(lr=self.learning_rate))
        print(model.summary())

        return model

    def memorize(self, state, action, reward, next_state, done):
        self.memory.append((state, action, reward, next_state, done))
        print(f" action {action} reward {reward}")

    def act(self, state):
        if np.random.rand() <= self.epsilon:
            return random.randrange(self.action_size)
        act_values = self.model.predict(state)
        return np.argmax(act_values[0])  # returns action

    def replay(self, batch_size):
        minibatch = random.sample(self.memory, batch_size, )

        for state, action, reward, next_state, done in minibatch:
            target = reward
            if not done:
                target = (reward + self.gamma *
                          np.amax(self.model.predict(next_state)[0]))
            target_f = self.model.predict(state)
            target_f[0][action] = target
            self.model.fit(state, target_f, epochs=1, verbose=0)

        if self.epsilon > self.epsilon_min:
            self.epsilon *= self.epsilon_decay

Here is the way I am calling the Environment class:
for episode in range(100):
    for time in range(500):
        call step function of gym.Env class

         if len(agent.memory) > batch_size:
            agent.replay(batch_size)

memory_size=2000
batch_size=1024
I am confused with the epoch, time, and episode in my scenario.
What I am getting is as follows:
1 Episode = 500-time slots
So, 1 epoch will train on the data stored in replay memory after the completion of episode 1.
When Episode 2 completes, it will train on the entire data it has stored inside the memory this time. And until the forward propagation and backward propagation does not complete on the data, it will keep iterating?
Am I getting it right? I am just confused with the episode, time and epoch concept here.
Answer: Time (timestep) is a concept from Markov Decision Processes. It is the way how the evolution of an MDP is indexed. For example, steps in a game.
Episode is a concept from Markov Decision Processes. It is a run of given MDP with a given policy. For example, when the game is over. In your code, you restrict the length of your episode to 500 timesteps.
Epoch is a concept from Deep Learning.

The number of epochs is a hyperparameter that defines the number times that the learning algorithm will work through the entire training dataset. https://machinelearningmastery.com/difference-between-a-batch-and-an-epoch/

The fact that epochs=1 in your code means that an update of the weights happens with the given data set only once. From the RL context, it makes sense because of an online nature of your learning.
Comment: thanks. it makes sense to me now.


Replicated filesystem and EC2 MySQL

Question: I'm currently investigating migrating our infrastructure over to run on Amazon's EC2 and am trying to figure out the best way to set up a MySQL service.  I'm leaning towards running our own MySQL instances, rather than going with Amazon's RDS, but am still considering the best approach for performance and cost on the instance itself.
In order to have persistent data, the MySQL data needs to be on an EBS volume (with some form of striped RAID, e.g. RAID0 or RAID10) to improve persistence.  However, EBS IO is limited by the network interface (gigabit, so a theoretical maximum of 128 MB/s), while the ephemeral volumes have no such problem.
I did see a suggestion for running two MySQL servers on an instance, with a master running on the ephemeral disk (which we would also RAID) and a slave storing changes to an EBS volume, but this has some additional overhead and complexity (two servers).
What I was imagining is using some form of replicated file system such that I could have

a filesystem on top of a RAID0 of ephemeral volumes to maximise performance
all changes from the above immediately replicated to another RAID1 volume backed by multiple EBS volumes to ensure no data loss

The advantages of this would be

best possible IO performance for the DB server; no network delay in IO
decreased IO on EBS volumes (as all read IO will be done on the ephemeral volumes) so decreased cost
good data security, as it's backed onto redundant EBS volumes

However, I haven't seen an appropriate system to replicate all changes from one volume to the other; is there a filesystem, or any other approach, which will do this?  The distributed file systems, e.g. GlusterFS, DRBD etc seem to focus on replicating disks between servers, can they be set up to do what I'm interested in here?
I also haven't seen anything about other's taking this approach.  Do I have a solution in need of a problem here (i.e. is performance good enough, so this whole idea is redundant)?  Is there some flaw in the plan?
Answer: In the absence of any better answers, it looks like we can use RAID1 to pull this off by creating a RAID1 array on top of the RAID0 of ephemeral drives and the EBS drive; with reads mainly occurring on the ephemeral RAID0 performance should be good, while we still have writes going to persistent storage as well as ephemeral.

Replicated filesystem and EC2 MySQL


How to make that sound effect

Question: How to make that sound effect on this music video and singing after 1:50

 I listen aoutotune pitch change but only voice sounds different and not like autotune, i mettin more music tracks with that effect. Thats sounds like voice mixed with synth not real human voice and i cant found vst oar anothe softare to do it that effect please help me fully. More exaple videos for
I listen pitch change again like on autotune but voice sounds diferent like robo voice or takbox

Sing on begin
Comment: Could it be a vocoder? Have you looked into those?
Comment: I think its two or more voices but not real human, sounds like robo voice or talk like
Answer: It sounds like a combination of two effects. The first is a delay effect with increased high and low-pass filtering on each repeat (like a tape delay plugin). There also seems to be increasing pitch glitches with each repeat. Maybe the autotune effect, the second effect heard here, is being run after the delay effect, and struggles to pitch-correct the repeats as they are lower fidelity?
The fundamental frequencies of the male human voice are roughly 85 to 180 Hz. If the delays are being high-pass filtered at, say, 250 Hz then the second echo won't contain any fundamental for the autotune to correct, so it is likely to have a harder time correctly re-tuning the incoming audio, giving the glitch effect on the recording.
Comment: "The fundamental frequencies of the male human voice are roughly 85 to 180 Hz." Do you mean "in the OP's recordings?" Anybody who seriously claims they are a tenor should be able to sing up to 440 Hz without using falsetto. A professional classical tenor should get to at least 520 Hz.
Comment: I'm referring to a normal male speaking voice, rather than any operatic performance. For OP's first recording this sounds about right.
Comment: No i need a software actually vst effect plugin or other programs for that

How to make that sound effect


How to show $f'(0)$ exist and is equal to $1$?

Question: Assume that $f$ be continuous on $\mathbb{R}$, $f'(x)$ exists for all $x\neq 0$, and $\lim_{x\rightarrow 0} f'(x)=1$. We need to show $f'(0)$ exist and is equal to $1$.
$f'(0)=\lim_{x\rightarrow 0}\frac{f(x)-f(0)}{x}$, $\lim_{x\rightarrow 0}f'(x)=1\Rightarrow\lim_{x\rightarrow 0}\lim_{h\rightarrow 0}\frac{f(x+h)-f(x)}{h}=1$...am I going in the right direction? Please help.
Comment: You are on the right track. You need to apply the Mean Value Theorem if you have seen that.
Comment: [Here](http://math.stackexchange.com/questions/257907/prove-that-fa-lim-x-rightarrow-afx/257936) is a related post.
Answer: Apply l'Hopital's rule to your quotient
$$
\frac{f(x)-f(0)}{x}.
$$
Comment: l'Hopital rule is itself proved using Mean Value theorem. Using mean value theorem it is possible to show that if a function is continuous then its derivative can not have jump discontinuity.
Answer: Let $x>0$. By the Mean Value Theorem in $[0,x]$,
$$\exists \xi_x\in (0,x):f'(\xi_x)=\frac{f(x)-f(0)}{x}$$
Let $\epsilon>0$. We have that
$$\exists \delta>0: \ \forall y\in (0,\delta)\ \left|f'(y)-1\right|<\epsilon\implies \left|f'(\xi_x)-1\right|<\epsilon\implies \left|\frac{f(x)-f(0)}{x}-1\right|<\epsilon $$
for $0<x<\delta$. Thus $f'_+(0)=1$. Similarly deal with the case $x<0$
Answer: Yes, as Julien's answer says, you can apply L'Hopital. Alternatively, you can use the Mean value theorem directly, which is really how L'Hopital's theorem is proved.
For any $h \neq 0,$ we have $\frac{f(x+h)- f(x)}{h} = f^{\prime}(\alpha_{h})$ for some $\alpha_{h} \in (x+h,x)$ for $h <0$, or in $(x,x+h)$ if $h >0.$ Now as $h \to 0,$ we must have $\alpha_{h} \to 0.$ But you are told that $f^{\prime}(\alpha_{h}) \to 1$ as $\alpha_{h} \to 0,$ so you are done
Answer: If $\displaystyle\lim_{x\to0}f'(x)=1$ and $f'(0) \not= 1$ then $f'$ has a simple discontinuity at $x=0$ but since $f$ is continuous $f'$ cannot have simple discontinuities then $f'(0)=1$


Subtracting characters in a loop

Question: I need the output of the program to be ten "*" symbols and then each following line is one less star until there is only one. I need to do this using a loop.
I am able to add stars but not subtract them. Please take a look at my program and see if you can help.
public static void main(String[] args)
{
    int count;
    String stars;
    stars = "**********";
    String star = "*";
    System.out.println(stars);

    for (count = 10;  0 < count;)
    {
        stars = (stars - star);
        System.out.println(stars);
        count--;
    }
}

Comment: try the substring method
Comment: Welcome on StackOverflow. When you are creating question you can see preview of how it will look like with your current formatting, so before you decide to post it take your time and format it properly.
Answer: You can't do String - String. You may use String.substring
 stars = stars .substring(0, stars .length() - 1);
 System.out.println(stars);

Note that the correct way to write for loop is:
for(initialization; Boolean_expression; update)
{
   //Statements
}

So you should write your for loop as:
for (count = 10;  0 < count; count--)
{
    stars = stars .substring(0, stars .length() - 1);
    System.out.println(stars);
}

Answer: Try this,
stars = (stars.replaceFirst("\\*", ""));

instead of
stars = (stars - star);

Answer: for(int i =10;i>0;i--){

    for(int j=i;j>0;j--)
        System.out.print('*');
    System.out.print('\n');//exit main loop

 }

Comment: Couple of quick pointers we would typically use final char '*' single quotes because its a literal, Also keep in mind how many variables you used and how many i used solving these small problems with little to no use of memory will come in handy if your interested in larger programs that require serious concern of memory usage. I also noticed your usage of decrement at the end, you may notice i put mine with the loop parameter body to stay organized
Answer: One approach could be to print the asterisks in a loop for each line, without maintaining a string throughtout the process:
for (count = 10;  0 < count; --count) {
    for (int i = 0; i < count; ++i) {
        System.out.print("*");
    }
    System.out.println();
}

If you're adamant about preserving the string throughout the program's execution, I'd suggest not using a String, but a mutable StringBuilder:
StringBuilder stars = new StringBuilder("**********");
while (stars.length() > 0) {
    System.out.println(stars);
    stars.setLength(stars.length() - 1);
}

Subtracting characters in a loop


How should I "store" my guitars?

Question: I have a bunch of guitars of varying quality from unplayable to quite nice. I intend to hang some (or all) of them on walls for decoration, but I'm not sure if this is good for the guitars, so perhaps I should do something else with the better ones?
I assume that lying down in a hard case will be the best, but that takes space, and also means the guitars aren't easily accessible for use (or making the apartment look nice).
Are guitar stands better or worse than all hanging? Are there other things to think about? What are the general guidelines when storing a collectors, very nice guitar (special woods, etc.), or one you value greatly? You will find humidity control systems in place at stores with "acoustic guitar rooms" for example.  Is is good to store a guitar in a case for very long?  Should some sort of moisture control be added to any case that is intended to sit for very long or be in a less than ideal environment?
Answer: This answer has been copied, pasted, and updated based on a related question that I answered.
I will answer your question related to hanging your guitars on the wall after I give some basic context on how to properly store a guitar in general. I think it's worthwhile to provide some context in which to answer your question. In essence, when it comes to guitars, you want to control a couple of main factors: temperature, humidity (relative), light, and outside damage. This applies to both "artwork" guitars and your average everyday player. How rigorous you are with this will affect the outcome of how well kept your guitar is.
Temperature & Humidity
A guitar is an organic instrument. It is made from wood, and wood has some interesting properties. First off, it's hygroscopic; this means it absorbs water. That makes sense based on what we know about trees :D. A guitar, despite the fact that most are sealed by either a polyurethane or a nitrocellulose finish, will absorb water from its surroundings and consequently move around a bit. Luckily, most designers and luthiers already know this--so it's highly unlikely that your instrument will warp to an unusable state just because you don't have a perfectly controlled environment. However it is recommended that you attempt to avoid extreme changes in environment--which includes both temperature and relative humidity--as these kinds of radical shifts can damage finishes of all types, cause bindings to pop loose, and all kinds of other nasties.
Typically both acoustic and electric guitars like to live at anywhere from 30% to 50% relative humidity--which is good, because we humans like that range too (at least I do). Any wetter than 50% and things start to mold, and any drier than 30% and you could potentially see the finish checking or even cracking in extreme cases. Grab yourself a hygrometer, many places sell them, and at minimum be aware of the room parameters where you keep your nice guitar. No real need to be paranoid about it. I have a 1930's Kay (not worth much, but old as the hills and sounds divine with a slide) and I keep it in the same room I keep my R8, Telecaster, and Firebird.
Light
As with any fine piece of artwork, the constant abuse of photons on a surface can cause some wear and tear over many, many years. You can search the internet for pictures of 50's Les Pauls that used to be tobacco burst, but are now very much approaching an iced tea burst. Years of direct light can cause finishes to fade and check. Although this is highly unlikely to be a problem in most cases, if you plan on keeping a guitar for many years then place it in its case when you aren't using it and do your best to keep it out of direct sunlight.
Outside Damage
This is the likely reason any guitar would be damaged. Kids playing, cats being curious, or dogs being rowdy--your guitar will get a ding. The only way you can prevent this is to lock it away in a safe, or a sealed glass case. The only advice I have here is don't be super paranoid about it, and make sure to place the guitar in its case when the relatives come over. If you are truly using an expensive guitar as a piece of art--something along the lines of the PRS private stock line--and never have plans on playing it, I would recommend a glass display case. This would reduce outside sources of damage but allow you, your family, and everyone else to enjoy the beauty of the piece. If you are simply worried about your 1958 reissue getting a ding then I think a glass case or safe is likely overkill; the guitar's case will protect it adequately. Safes are useful to store very valuable guitars for future generations to enjoy, but for anything outside an original 1950's Les Paul, Stratocaster, or Telecaster/Nocaster it's not really worth the investment in my opinion. Additionally I think that you should enjoy it anyway--we all eventually take a dirt nap. If you spent a ton of money or time procuring or building "your" special guitar then you should enjoy it before you pass it on to the next lucky owner.
Should I hang my guitars on the wall?
Well, you can--but do so with caution. Some finishes dislike the cushioning that wall mounts use and it can cause some issues. Additionally, there's a chance that your guitar might be knocked off the wall--which certainly would cause more damage than storing it in its case or keeping it on a stand. I wouldn't recommend hanging very expensive guitars without researching some sturdy, finish friendly mounts, of which I have found none. Some stands can also damage the finish of your guitar when left in contact for long periods of time, but placing an old used T-Shirt over the cushions can fix that issue (this also works on wall hangers if you go that route). In general I would recommend placing an unused guitar safely in its case or on a protected stand if you plan to play it frequently. I think that a well placed guitar can improve the aesthetics of a room quite nicely--or maybe I'm just lucky because my wife doesn't seem to mind at all :).
Answer: If you tend to walk in the dark near your guitars, then hanging them is much better than leaving them on a stand and kicking them accidentally in the dark. I prefer to hang mine, but as you mention you are renting an apartment, your landlord will almost certainly disapprove of what needs to be done to hang them from the walls.
I'm fortunate in that my apartment will be remodeled when I move out, so I'm allowed to do anything that doesn't cause structural damage.
Answer: Whether it's good for them or not, I've been hanging a few of my guitars on the wall for a few years now, and I haven't noticed any difference in their condition vs. the ones I keep in a case in the closet, other than the normal wear & tear. Of course, YMMV, but I've also made sure that the room they hang in stays a reasonable temperature, and that the places they hang doesn't leave them in direct sunlight, and that probably helps as well.
Comment: I don't really recommend hanging guitars on the wall, especially very valuable ones ;).
Comment: @Jduv - perhaps true, but keeping a guitar in reach trumps keeping it in perfect condition for many people. (Mine are hanging on the wall in the dining room, away from direct sunlight.)
Comment: @neilfein - That's exactly why I keep them on the wall. I'm much more likely to play more often if I just have to pull a guitar off of the wall, than I would if I had to open a case. I'm lazy that way.
Answer: I recently read in a magazine (Guitar World or something) that a glass of water just sitting in a room would suffice ( not sure if this is true or not ). Also storing a guitar in its case is probably a good idea, it will make the strings last longer and prevent it from recieving any damages. If it's not going to be used for a long time, I'd take off the strings, clean it very well, and then restring it. Not sure how much this will help but I tried at least =p
Comment: A single glass of water won't really raise the relative humidity in a room by anything noticeable. You'd need something with greater surface area such that the water evaporates into the room atmosphere at a greater volume--like a 3 gallon bucket, or a very, very wide rimmed tupperware (cool whip containers work great here in the states).
Comment: How much water you'd need would depend on the relative humidity in the room, its size (size of the room that is), temperature, airflow in and out, etc. etc.
Stating any given volume will do is irresponsible.
Comment: If a glass of water won't make you happy buy a humidifier. And I didnt say I knew everything about the 'glass of water', i said I read it in a magazine. If you were that interested in that method you could find the magazine and check out the article.
Answer: I hang mine in a climate controlled space, i use guitar cleaning cloths over the hanger's foam padding to prevent marring the finish.  I believe hanging guitars encourages one to play them more often, the necks stay straight and there is more air for the guitar to breathe.  I had a really nice Guild D-40 that suffered marring on the neck where the case lining was touching the neck.  The neck itself was a bit bowed as well from lying flat on its back.  Now if i case a guitar I put a polishing cloth where the neck meets the case.
Answer: Regarding hanging guitars on walls....
I 'inherited' an old Epiphone semi-hollow electric guitar that was left behind by a former roommate.  The guitar was unplayable; the strings were nearly an inch from the fretboard.  I meant to get it set up, but in the interim I hung it on my wall with a guitar hanger.
After about 2 years I still hadn't brought the guitar in to be fixed so when I grabbed it next I was shocked to learn that over time the neck had straightened itself out! Its still hanging on a wall and it been good ever since.  It seems that there is a positive effect to hanging guitars.
Answer: After reading all the advice on storing/displaying guitars ive found out first hand a hanger that fits the neck well and using a cotton t shirt material for a cusion works.i stored a very old bass guitar in a hard shell case and where the neck rested in the case I got a large knot.i would assume if the case was custom made for that specific guitar it would be fine.just make shure it's hanging on a strong good fitting hanger and it is on a inside wall .one more thing DO NOT STORE YOUR CASE ON A CONCRETE FLOOR.It will mess with the case and the guitar In it.
Comment: Two questions: A) what exactly happens to a guitar that is inside a case sitting on a concrete floor? B) How do you control the humidity of the guitars you have out on hangers?
Answer: I got this off the Gibson site. I was thinking of wall hanging as well.  I agree that it looks great and I think you would be inclined to play them more, but I didn't think about all the stuff floating around in the air that could eventually cause some problems.

Store properly: Don't leave a guitar on a rack for months without picking it up and expect it to play properly. Store your guitars in cases or gig bags to keep dust and other airborne contaminants — like household cooking smoke — off their vitals, and for protection from falls or other accidents. Even if your guitars are in cases check them every few months to be sure there's no warping or other weather related damage at play. A few twists of a truss rod now could prevent a neck replacement later.

Source: Gibson, 10 Things To Keep Your Guitar In Top Condition (Accessed Feb 11 2019)
Answer: I was told by my local guitar shop that you shouldn't leave your guitars in their cases as they sweat over time - I don't live in a humid climate either. It happens as the case and outside air change too much and therefore the wood can warp/sweat and strings rust. Interestingly I have stored one of my guitars stored this way - a German silver resonator. After talking to the guitar shop guys I checked the guitar and it had started to pit and strings started to oxidize quite badly. Now I store it on a hanger - I live in a dryer climate but one that changes temp from high to low quickly - not hot humid though. Its hard to know which advice to follow sometimes.
Comment: This is the opposite of correct. Guitar woods, including open wood fingerboards on electric guitars, are seasoned to a certain relative humidity. Normally this is around 40% - 50%, which can be high for many homes and studios, especially if heating is on in the winter. Keeping a guitar in its case helps keep the guitar in a more stable relative humidity. Even then it's good to keep an eye on humidity, especially for solid wood acoustic guitars, which should have regular humidity checks and humidity management. If strings get corroded they should be replaced.
Comment: This is subjective. I have probably 30+ guitar cases, and some will allow the ambient air to permeate, whilst others I would happily throw into water, knowing the guitar will come out afterwards completely dry. Thus in its own little atmosphere. A gigbag is also considered to be a case, but leaving a guitar in that would be about the same as leaving it on a hook - apart from lack of dust!

How should I "store" my guitars?


No STARTTLS with Dovecot and Postfix

Question: I have done a lot of searching and am not finding a solution.
I had to reload Mageia 6 on my email server.  I am using dovecot-2.2.34-1.mga6 and postfix-3.1.6-1.mga6.  Openssl is openssl-1.0.2o-1.mga6.
I can send and receive email from Postbox (based on Thunderbird)with password and no encryption but when trying STARTTLS from a telnet to 587 or 465 I get:
454 4.7.0 TLS not available due to local problem
This was working before the filesystem got corrupt and I had to reinstall Mageia.  The old config files do not work with the new install.
From telnet:
Escape character is '^]'.
220 robob.robob.com ESMTP Postfix (3.1.6) (Linux)
EHLO robob.robob.com
250-robob.robob.com
250-PIPELINING
250-SIZE 252400000
250-VRFY
250-ETRN
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN
STARTTLS
454 4.7.0 TLS not available due to local problem

Dovecot is supposed to be doing the auth.
# 2.2.34 (874deae): /etc/dovecot/dovecot.conf
# Pigeonhole version 0.4.18 (29cc74d)
# OS: Linux 4.14.65-desktop-1.mga6 i686 Mageia 6
# Hostname: robob.robob.com
auth_debug = yes
auth_mechanisms = plain login
disable_plaintext_auth = no
listen = *
mail_access_groups = mail
mail_location = mbox:~/mail:INBOX=/var/spool/mail/%u
managesieve_notify_capability = mailto
managesieve_sieve_capability = fileinto reject envelope encoded-              character vacation subaddress comparator-i;ascii-numeric relational regex imap4flags copy include variables body enotify environment mailbox date index ihave duplicate mime foreverypart extracttext
mbox_write_locks = fcntl
passdb {
driver = pam
}
protocols = imap pop3
service auth {
unix_listener /var/spool/postfix/private/auth {
group = postfix
mode = 0660
user = postfix
 }
vsz_limit = 512 M
}
service imap-login {
process_min_avail = 10
service_count = 1
vsz_limit = 2 G
}
service imap {
vsz_limit = 640 M
}
service managesieve-login {
process_min_avail = 10
}
service managesieve {
vsz_limit = 640 M
}
service pop3-login {
process_min_avail = 10
}

    service pop3 {
    vsz_limit = 640 M
}

ssl_cert = </etc/pki/tls/certs/dovecot.pem
ssl_key =  # hidden, use -P to show it

userdb {
driver = passwd
}

protocol lda {
postmaster_address = firstname.lastname@example.com
}

Help would be greatly appreciated as I have been working on this for about 30 hours with very little sleep.  I have a few users and would not want them to connect insecurely.
Thanks,
Robert

        # Please be sure to read the /usr/share/doc/postfix/README.MDK file
# to learn about differences from stock postfix to Mandriva package.
# This file contains only the parameters changed from a default install
# see /etc/postfix/main.cf.dist for a commented, fuller version of this file.

# These are changed by postfix install script
readme_directory = /usr/share/doc/postfix/README_FILES
html_directory = /usr/share/doc/postfix/html
sendmail_path = /usr/sbin/sendmail.postfix
setgid_group = postdrop
command_directory = /usr/sbin
manpage_directory = /usr/share/man
daemon_directory = /usr/libexec/postfix
newaliases_path = /usr/bin/newaliases
mailq_path = /usr/bin/mailq
queue_directory = /var/spool/postfix
mail_owner = postfix

# User configurable parameters

mydomain = robob.com
mydestination = $myhostname, localhost.$mydomain, $mydomain, eoberjr.com
#inet_interfaces = localhost
#mynetworks_style = host
#delay_warning_time = 4h
smtpd_banner = $myhostname ESMTP $mail_name ($mail_version) (Linux)
unknown_local_recipient_reject_code = 450
smtp-filter_destination_concurrency_limit = 2
lmtp-filter_destination_concurrency_limit = 2
data_directory = /var/lib/postfix
mailbox_size_limit = 2000000000
message_size_limit = 252400000
#mailbox_command = /usr/bin/procmail  -a "$EXTENSION"
local_recipient_maps = proxy:unix:passwd.byname $alias_maps
mail_spool_directory = /var/spool/mail
relay_domains = $mydestination /etc/postfix/relay_domains
mynetworks = 126.96.36.199/29, 127.0.0.1
canonical_maps = hash:/etc/postfix/canonical
virtual_maps = hash:/etc/postfix/virtual
alias_maps = hash:/etc/postfix/aliases
alias_database = hash:/etc/postfix/aliases
maps_rbl_domains = blackholes.mail-abuse.org
smtpd_sasl_auth_enable = yes
ssl_cert = /etc/pki/tls/certs/dovecot.pem
ssl_key = /etc/pki/tls/private/dovecot.pem
smtp_tls_cert_file = /etc/pki/tls/certs/dovecot.pem
ssl_key = /etc/pki/tls/private/dovecot.pem
smtpd_sasl_type = dovecot
#smtpd_sasl_path = smtpd
smtpd_sasl_path = private/auth
smtpd_sasl_local_domain = robob.com
smtpd_sasl_security_options = noanonymous
smtpd_client_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_rbl_client zen.spamhaus.org, reject_rbl_client bl.spamcop.net, reject_rbl_client 22.214.171.124.b.barracudacentral.org
smtpd_sender_restrictions = permit_mynetworks, permit_sasl_authenticated
smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, check_relay_domains, reject_unauth_destinationa, reject_rbl_client bl.spamcop.net
broken_sasl_auth_clients = yes
inet_protocols = ipv4

I have tried it a number of ways.  The current config is supposed to let Dovecot do the auth.  I appreciate the clarification.  So, Dovecot does the auth and then Postfix negotiates the encryption?  I tried cyrus sasl earlier and that did not work either so I removed it.
Thanks
Comment: What's in the log, then?
Comment: postfix/smtpd[406]: warning: No server certs available. TLS won't be enabled
Comment: While Dovecot is able to perform SASL authentication for Postfix, it has nothing to do with Postfix `STARTTLS`. What's in your Postfix `main.cf`?
Comment: Thanks for the clarification.  So, Postfix negotiates the crypto type?
Comment: Added the main.cf.
Answer: You have what appears to be a typo in your Postfix configuration.
smtp_tls_cert_file = /etc/pki/tls/certs/dovecot.pem

Directives starting with smtp_ are used when Postfix makes outgoing SMTP connections to other servers. In particular, this directive is used only when Postfix is meant to authenticate to another SMTP server with client certificates. This is an extremely rare situation, and is not the situation you are in.
You probably meant to type smtpd_tls_cert_file. Directives starting with smtpd_ apply to incoming SMTP connections.
You also need to provide the private key corresponding to the certificate, in the smtpd_tls_key_file directive.
And you may need yet other configuration changes. Read the relevant Postfix documentation carefully.
Comment: The typo correction on smtp_tls_cert_file and adding the line for the key file fixed it at least for STARTTLS.  Postbox doesn't like the SSL setting so I will test that on my iPhone.  MUCH appreciated.

No STARTTLS with Dovecot and Postfix


fadeIn de divs num loop?

Question: Eu tenho o seguinte código que gostava que fizesse fadeIn e fadeOut passados 3 segundos. Pensei em usar setInterval para fazer o loop e depois usar um setTimeout para dar o tempo que cada div estava visível. Existe alguma forma de fazer o que desejo? Tenho algo mal no meu código?
setInterval(function(){
    setTimeout(function(){
        $(".emer3").fadeOut("fast");
        $(".emer1").fadeIn("fast");
    }, 3000);

    setTimeout(function(){
        $(".emer1").fadeOut("fast");
        $(".emer2").fadeIn("fast");
    }, 3000);

    setTimeout(function(){
        $(".emer2").fadeOut("fast");
        $(".emer3").fadeIn("fast");
    }, 3000);
}, 9000);

    252 252 252

    252 252 252

    252 252 252

Exemplo neste JSFIDDLE
Comment: Mas qual é o problema com esse código ? Está funcionando, se não for esse o efeito, explica um pouco melhor, ficou meio confuso o que você quer fazer.
Comment: @AnthraxisBR https://jsfiddle.net/nek7xugw/1/ Veja aqui o exemplo
Comment: Qual é a ideia do `setInterval`? Queres voltar a esconder depois?
Comment: @Sergio O `setInterval` é suposto funcionar como um lopp infinito mas não está a resultar como esperado
Comment: Mas queres mostrar e depois esconder? O setTimeout corre 1 vez, e porque o queres correr de novo?
Comment: Porque são divs diferentes, cada uma com uma classe, e com esses setTimeout define o tempo que cada uma fica.
Comment: Voce quer fazer um pisca pisca?
Comment: @HudsonPH Não, quero que a div apareça, se mantenha por 3 segundos, desapareça e apareça a próxima
Comment: Os fades de jquery suportam *complete callbacks* para encadear animações. É isso que pretende fazer?
Comment: @Isac Não entendi bem o que disse
Comment: Estou a perguntar se a ideia era os 3 setTimeouts correrem um de cada vez em sequência? Ou se os 3 ao mesmo tempo?
Comment: @Isac Sequência
Answer: No seu código o problema é que todos os setTimeout começam ao mesmo tempo, logo as esperas terminam simultâneo.
Quando quer encadear animações em Jquery deve utilizar a função de complete, que é um callback, desta maneira:
$(".umaclass").fadeIn("fast", function(){
    //aqui vem o código a executar quando esta animação acaba
});

Se não o fizer dessa forma então todos os fades para elementos diferentes correm em simultâneo.
Para o seu problema em concreto de animar divs em sequencia sugiro outra abordagem, que até é mais escalavel, construindo um array de divs a animar e animar em sequencia com base na posição em que vai.
Exemplo:

const divs = [$(".emer1"), $(".emer2"),$(".emer3")]; //divs a animar
let i = 0; //div corrente

function animar(){
  divs[i].fadeOut("fast"); //fadeout do corrente
  i = (i+1>=divs.length)?0:i+1; //descobrir o proximo
  divs[i].fadeIn("fast", function(){ //fadein do proximo
    setTimeout(() => { animar() } ,3000); //esperar 3 segundos e repetir o processo
  });
}

setTimeout(()=>animar(), 3000); //iniciar tudo em 3 segundos
.emer1 {
  background-color:cyan;
}

.emer2 {
  background-color:yellow;
}

.emer3 {
  background-color:green;
}

    252 252 251

    252 252 252

    252 252 253

Documentação do fadeIn e do fadeOut
Nota: coloquei umas cores nos divs para que o efeito fosse mais evidente.
Comment: Muito Obrigado! Resultou na perfeição

fadeIn de divs num loop?


Mensagem de Segurança sobre controle ActiveX

Question: Sistema: Windows 8 e Microsoft Office 2013
Estou tendo problemas com uma tela de alerta sobre controle ActiveX que vem me perturbando a algum tempo:
Antes de abrir o Form onde está o controle Windows Media Player, aparece uma tela de advertência com o seguinte texto:
"Este aplicativo está prestes a inicializar controles ActiveX que podem não ser seguros. Se você confia na origem deste arquivo, selecione OK e os controles serão inicializados usando as configurações atuais do espaço de trabalho."
Esta mensagem somente aparece uma única vez, antes da abertura do UserForm
Projetos sem o controle Windows Media Player a citada tela de advertência não aparece.
Em mais de uma oportunidade, realizei exaustiva pesquisa sobre o assunto na internet mas;, nada encontrei para resolver o problema.
Confesso que já tentei de tudo para sumir com ela, mas esgotei as possibilidades

Já alterei de diversas formas a Segurança de Macros sem sucesso
  Ja alterei alguns registros em  < regedit - HKEY_CURRENT_USER e também em HKEY_LOCAL_MACHINE, seguindo orientações encontradas em sites, também sem sucesso
  Na verdade, pesquisando na internet, até se encontra alguma coisa sobre o assunto, mas baseado em versões do windows/office mais antigas

Conto com a atenção da comunidade para a solução do problema
Comment: [Esta resposta](http://pt.stackoverflow.com/questions/49103/internet-explorer-restringiu-execu%C3%A7%C3%A3o-de-scripts/49160#49160) fala de ActiveX no browser, mas traz informações úteis. Talvez não haja como controlar isso.
Answer: Criei um exemplo aqui (excel 2013, windows 8), e em um form coloquei o mesmo controle "WindowsMediaPlayer" e alterei os registro conforme a terceira resposta deste exemplo e a mensagem não aparece mais.
Obs: No link de exemplo fiz somente os 16 primeiros passos (ActiveX), pois os demais eram sobre macros e assinatura)
Answer: Este questionamento também foi postado em:
social.msdn.microsoft.com/Forums/pt-BR/53fa380d-464f-44f2-bb74-d82a860c996c/mensagem-de-segurana-sobre-controle-activex?forum=vbapt&prof=required
e felizmente foi respondido pelo Felipe Costa Gualberto, que postou a seguinte solução:
Crie uma Chave em HKEY_CURRENT_USER\SOFTWARE\Microsoft\VBA\ chamada Security
Em Security, crie um registro DWORD chamado LoadControlsInForms e como valor coloque 4.
Isto foi testado por mim e funcionou perfeitamente.
Espero igualmente ter colaborado com a comunidade.
Valmor


Prove all 4 axioms of "less than" are necessary (for real numbers)

Question: One way to define an ordered field is as a field $F$ with a relation $<$ that satisfies:

For all $x,y \in F$, exactly one of $x<y$, $x=y$, $y<x$ holds.
For all $x,y,z \in F$, if $x<y$ and $y<z$, then $x<z$.
For all $x,y,z \in F$, if $x<y$, then $x+z < y+z$.
For all $x,y,z \in F$, if $x<y$ and $0<z$, then $x \cdot z < y \cdot z$.

When $F$ is the real numbers $\mathbb R$, the usual "less than" is the only relation that satisfies all four axioms. I expect that all four axioms are necessary to know this: if we drop one of them, then other relations may "sneak in". There are easy constructions for two of the axioms:

If we drop axiom 1, then we can declare that $x<y$ for all $x,y \in \mathbb R$: this satisfies the other three axioms.
If we drop axiom 4, then we can declare that $x<y$ when $x$ is greater than $y$ in the usual sense: this satisfies the other three axioms.

Are there easy constructions showing that the other two axioms are necessary?
(Again, I want to stick with the real numbers. There are interesting examples over finite fields; for example, when $F = \mathbb F_3$, let $x<y$ exactly when $y=x+1$, and axioms 1,3,4 hold (but not 2). I am not interested in these right now.)
Comment: What if all the rationals (with their usual order) are less than all the irrationals (with their usual order)?
Comment: @amWhy I looked at that question, but it's a very broad one only tangentially related to what I wanted. I was only interested in the order axioms for the reals, I had a specific set of axioms in mind, and I didn't need an explanation of how we prove an axiom is necessary, just in the constructions. (Which Eric's provided.)
Comment: I feel like there might be something weird you could do on disjoint copies of $\mathbb{Q}$ with one or both of 2/3 missing?
Comment: @EthanBolker Then axiom 4 is also violated: if $\sqrt2 < \sqrt3$, and we multiply on both sides by $\sqrt3$, it implies $\sqrt6 < 3$.
Comment: Axiom 4 "if x<y and 0<z, then x⋅z<y⋅z" ;;;; Claiming "let x<y exactly when y=x+1, and axioms 1,3,4 hold" :::: I think this is not true; if x<y then y=x+1, then we will get zy=zx+z which is not zy=zx+1 hence we are not proving x⋅z<y⋅z ....
Comment: @Prem In $\mathbb F_3$, with that definition of $<$, the only $z$ that satisfies $0<z$ is $z=1$. Thus, $zy = zx+z$ is the same as $zy = zx+1$.
Comment: Oh, I see the F3 now; got it, thanks !
Comment: Does this answer your question? [How do we decide which axioms are necessary?](https://math.stackexchange.com/questions/717821/how-do-we-decide-which-axioms-are-necessary)
Answer: Axioms 1 and 3 are equivalent to saying that you have a set $P$ of "positive" numbers such that $\mathbb{R}$ is partitioned into $P,\{0\},$ and $-P$, and then we say $x<y$ iff $y-x\in P$.  Adding axiom 4 is then eqivalent to saying $P$ is closed under multiplication.  So to satisfy axioms 1, 3, and 4, you just need a set $P\subset\mathbb{R}\setminus\{0\}$ closed under multiplication such that for all nonzero $x$, exactly one of $x$ and $-x$ is in $P$.  The multiplicative group $\mathbb{R}\setminus\{0\}$ splits as a direct sum of $\{1,-1\}$ and $\mathbb{R}_+$, and $P$ just needs to be some other direct sum complement to $\{1,-1\}$.  (Note that $P$ is automatically closed under multiplicative inverses: if $x\in P$ and $1/x\not\in P$ then $-1/x\in P$ so $x\cdot(-1/x)=-1\in P$ so $(-1)^2=1\in P$ which is a contradiction.)  In particular, if we take a basis for $\mathbb{R}_+$ as a vector space over $\mathbb{Q}$, we could replace one basis element with its negative to get a different complement, and thus a relation that satisfies axioms 1, 3, and 4 but which has a different set of "positive" numbers.
(This is quite arguably not an "easy" construction.  However, there is not really any easier option: we are asking for a group-homomorphism $\mathbb{R}_+\to\mathbb{R}\setminus\{0\}$, and any such homomorphism that is at all "nice" (e.g., measurable) is automatically continuous and so could only be the standard choice if it is to split the projection map.  In particular, for instance, it is consistent with ZF that no such counterexample exists so axioms 1, 3, and 4 suffice.)
For axioms 1, 2, and 4, just take any total order on $\mathbb{R}$ for which $0$ is the greatest element.  Then axiom 4 holds vacuously.
Comment: Thank you! That answers all my questions. Goal #1: satisfy my curiosity is satisfied, even if goal #2: be able to explain this to my students in an intro proofs course is perhaps 25% out of reach.


Calculate possible permutations/combinations of a set of unique values without repetition or reflection

Question: Let's say I have a set of five unique values: {1, 2, 3, 4, 5}
I want to calculate the number of possible combinations of these values without allowing any of the values to be repeated, which I understand is easily calculated as 5! = 120.
However, I also want the calculation to exclude "reflected" combinations of these values - e.g., 1,2,3,4,5 is effectively the same as 5,4,3,2,1, and 2,4,5,3,1 is a reflection of 1,3,5,4,2.
Is there a "simple" formula to expresses this?
Answer: Yes.  Simply divide the result you obtained by two.  Notice that every outcome you are wanting to count was counted twice (once with a smaller number in front and once with a larger number in front)
More formally, you can explain this by way of either the Shepherd's Principle (to count # of sheep in a field but can't make out bodies from one another since they are too fuzzy, instead count the legs and divide by four) or if you want to get fancy you can use Pólya Enumeration Theorem or you can use The Lemma which is not Burnside's.
Comment: Thank you for that. I had a *feeling* it was that simple, but I kept going in circles arguing with myself.


Let $O$ be an open set in a topological space $X$ and $p\in O,q\in X-\bar{O}$. Does every continuous curve from $p$ to $q$ pass trough $\partial O$?

Question: Suppose that $X$ is a topological space and $O\neq \emptyset$ is an open subset of $X$. Let $c:[0,1]\to X$ be a continuous curve from $p\in O$ to $q\in X\setminus\overline{O}$. Is it then true that $c$ passes trough $\partial O$, i.e. $c([0,1])\cap \partial O\neq \emptyset$?
My idea: We have $c(0)=p$ and $c(1)=q$. If $c(0.5)\in \partial O$, we are done. If $c(0.5)\in O$ or $c(0.5)\in  X\setminus \overline{O}$, we restrict ourselves to the interval $[0.5,1]$ or $[0,0.5]$ and continue. In this way, by using the Cantor intersection theorem, we can find $t_0\in [0,1]$ and sequences $x_n,y_n\in [0,1]$ with $x_n,y_n\to t_0$ such that $c(x_n)$ lies in $O$ and $c(y_n)$ lies in $X\setminus \overline{O}$.
Now let $M$ be any open set which contains $c(t_0)$. Then $c^{-1}(M)$ is an open set around $t_0$ . Since $x_n,y_n$ converge to $t_0$, it follows that $M$ contains points from $O$ and $X\setminus \overline{O}$ which shows that $c(t_0)$ is a boundary point of $O$.
This question is based on Lemma 6.2. on page 94 of Lee's "Riemannian Manifolds" (the part after (6.1); I have replaced the manifold $M$/the geodesic ball with an arbitrary topological space/open set, so the statement might not be correct.)
Lee argues that $X\setminus \partial O$ is disconnected so $c$ has to pass trough $\partial O$ since $p$ and $q$ lie in different components. However I don't really understand his argument.
Answer: Let $c:[0,1]\to X$ be continuous with $c(0)=p$ and $c(0)=q$. Suppose, for a contradiction, that $c([0,1])\subseteq O \cup (X\setminus \bar{O})$. Set $A = c^{-1}(O)$ and $B=c^{-1}(X \setminus \bar{O})$. We have that $A,B$ is a partition of $[0,1]$ into non-empty open sets, contradicting the fact that $[0,1]$ is connected.
Comment: This is probably what Lee had in mind. Thank you!
Answer: Your argument seems fine. I would consider the number $s=\sup\left\{t\in[0,1]\,\middle|\,c(t)\in O\right\}$. Since $0\in\left\{t\in[0,1]\,\middle|\,c(t)\in O\right\}$ and since $\left\{t\in[0,1]\,\middle|\,c(t)\in O\right\}\subset[0,1]$, the definition of $s$ makes sense. And it follows from the definition of $s$ that there are points $x\in[0,1]$ arbitrarily close to $s$ such that $c(x)\in O$. So, $c(x)\in\overline O$. But you cannot have $c(x)\in O$, because otherwise there would be a $\varepsilon>0$ such that $(s-\varepsilon,s+\varepsilon)\subset[0,1]$ and that $c\bigl((s-\varepsilon,s+\varepsilon)\bigr)\subset O$, and then$$\overbrace{c+\frac\varepsilon2}^{\phantom O\in O}>s=\sup\left\{t\in[0,1]\,\middle|\,c(t)\in O\right\}.$$So, $c(x)\in\overline O\setminus O=\partial O$.