SEO is off topic?

Question: I recently noticed that in post closing SEO has become an option as an off topic question.
SEO is an important part of the Magento system with a lot of built in features. I myself have asked questions on the topic of SEO and my posts were never closed.
I'm just curious as to why SEO has been added as "off topic"?
Comment: What do you mean? I can not see this option.
Comment: @Alex it looks like it was for a single question as a suggested closing reason.
Answer: You see reasons in the "off topic" list that others have been used on the same question:

So it's not an official reason, just a single opinion on a single question.
Comment: Ah okay I feel silly now, thanks for clarifying!
Answer: I think SEO has two sides here.

Problems or questions arising from built in Magento SEO features or even extensions (although extensions might be considered off-topic too)
General SEO questions/problems about optimization, indexing, Google results/ranking etc..

IMO number one definitely belongs on the Magento SE, number 2 does not. I think questions in category number 2 have a better chance on a fast and good answer on other SE's.
Answer: I think general SEO questions should be off topic, whereas questions pertaining to the use of magento or magento extensions in regards to SEO is ok.
Answer: to cite a different answer on a similar question

SEO questions should be asked on Webmasters, tagged with seo.

https://meta.stackoverflow.com/a/281382/716029
Reason: the whole area of SEO is as big as Magento as a whole. With a difference, that there is only a very small overlap of SEO with Magento Developers.
Doing SEO in a professional manner requires access to a few hundred websites at the lowest, the right connections to other expert People in the Field (like we Magento people are good connected to other Magento people) and reading a lot of news and books and so on.
If you want the best possible SEO answer, you should go where the experts are. They will not be here in the Magento Stackexchange

SEO is off topic?


Generate a unique number that is formed from 2 numbers and vice versa?

Question: I am not sure if this is possible but,
I have 2 numbers, a 32-bit int x and a 64-bit long y.
Given that 'y' is ALWAYS unique.
Given these numbers, I want to generate a unique identifier which is a 32-bit int.
I should also be able to construct the individual numbers back from the unique identifier.
Is this possible? I apologize if this is the wrong forum to ask, but this is related to C# programming on a project i am working on.
Basically, 'x' refers to a categoryID and 'y' refers to a unique 'categoryItemId' in my database, a single category can have a million of catalogItems.
Thanks!
Comment: So you have a unique 64bit key, and you want to turn that into a unique 32bit key? You're bound to get colisions, according to the [Pigeonhole principle](http://en.wikipedia.org/wiki/Pigeonhole_principle)
Comment: Do you know what the range would be for your unique 64-bit long 'y'? If they are going to be above Int32.MaxValue (2,147,483,647) or/and below Int32.MinValue (-2,147,483,647) you're going to find this tricky to say the least.
Comment: What is this for? Is this to create a unique id in another table or something like that?
Comment: @theOne : define unique (in this context).
Comment: "a single category can have a million of catalogItems." at most? So If you have no more than say 214 categories, you could do `(int)((categoryID *10000000) + categoryItemId)`. If you can be sure to always have less than a million, you could handle up to 2147 categories. If you either have more categories or more items per category, see Wai Ha Lees answer.
Comment: hi @sr28 yes, it is to create a unique id in another....
Comment: Is it SQL Server? If so this isn't a good way to manage relationships between tables. You should create a unique id automatically as part of adding an entry into the new table and then use Foreign Keys to define your relationship with your other tables.
Answer: To sum up:

You have 96 (== 32 + 64) bits of possible inputs.
You want a unique 32 bit value regardless of the input values.
32 < 96

It's not possible. The entropy of your inputs is larger than the entropy of the output.
Comment: Only fractions of those ranges are used. And when Y is unique, you can simply drop X. When the number of Categories is <= 1000 the required space is 10+20, 2 bits to spare.


Number of binary numbers with two consecutive zeros

Question: This is an unsolved question in my textbook (so full answers are ok too). We are asked to count the number of binary numbers of length 15, beginning with '1', that have a total of ten 1s, five 0s, and two consecutive zeros.
My thoughts are, we can begin by ordering the 10 1s: $1 1 1 1 1 1 1 1 1 1$. The answer is the number of ways to put the 0s between them, which is like the number of integer solutions to $x_1+x_2+...+x_{10}=5$ with at least one $x_i>=2$. However, I don't know how to count that...
Thanks for your help.
Comment: Andre: I'll give it a shot. We have $00000$ zeros to put in 1s between. We want at least 1 between every 0, so it's the number of positive integer solutions for $x_1+...+x_4=10$. This I know how to count: it's $C(10-1,4-1)=84$. So the answer would be $C(14,9)-84=1918$? It kind of feels too big to me...
Comment: Your idea will work nicely for **no two** consecutive $0$s. Find that, subtract from total.  For no two consecutive $0$, we need to **choose** five "gaps" to put the $0$s in. (I am assuming two means at least two.)
Comment: Listing: I get $10*C(12,3)=2200$ (10 ways to place the double-zeros and 3 ways to place the remaining 0s, but this doesn't quite make sense since without the double-zero restriction the total number of binary numbers would be $C(14,9)=2002$ (number of ways to place the 1s)... can you clarify what you mean?
Comment: Nevermind, I think I was mistaken :-], maybe there is something i overlooked I am not good at this things.
Comment: why break the head, the soluction is only a simple fibonacci :)
Answer: The problem is somewhat ambiguous. There are several interpretations: (a) at least two consecutive $0$'s; (b) exactly one occurrence of two consecutive $0$'s; (c) at least one occurrence of two consecutive $0$'s, and nowhere $3$ consecutive $0$'s; (d) maybe others.
We solve (a).  We first count the ways to have no two consecutive $0$'s. Put the ten $1$'s in a row as in the post. There are $10$ "gaps" immediately to the right of a $1$, including the gap at the right end. We must choose $5$ of these gaps for the $0$'s. This can be done in $\binom{10}{5}$ ways.
Next we count the total number of binary numbers with $5$ $0$'s, $10$ $1$'s, that start with a $1$. From the $14$ positions left to be filled, we must choose $5$ for the $0$'s. This can be done in $\binom{14}{5}$ ways.
So the number of binary strings with at least two consecutive $0$'s is
$$\binom{14}{5}-\binom{10}{5}.$$
With the interpretation (b), things are simpler. We have the $10$ gaps as before. We must choose one of these gaps to have the $00$. This can be done in $\binom{10}{1}$ ways. For each way, there are $9$ gaps left for the remaining three "single" $0$'s. They can be filled in $\binom{9}{3}$ ways, for a total of $\binom{10}{1}\binom{9}{3}$.
Comments: $1.$  The number of strings with at least two consecutive $0$'s turns out to be $1750$, and the total number of strings is $2002$, so if a string is randomly chosen, the probability it will have at least two consecutive $0$'s is roughly $0.874$.  This is may be substantially higher than one would guess.  In this kind of situation, it is easy for intuition to fail. We kind of see the 0's as being all separated, but most of the time there will be at least some clumping. There is a similar phenomenon with a baseball batter. If he gets two hits in a row, the announcer says he's got a hot bat. But "streaks," even in a purely random setting, are more frequent than intuition suggests.
$2.$ We can attack interpretation (a) in other ways. One approach is to list the types of ways we could have one or more consecutive $0$'s, count, and add.  We could have $5$ consecutive $0$'s; r we could have $4$ and a singleton; or we could have a $3$ and a $2$; or $3$ and two singletons; or two $2$'s and a singleton; or one $2$ and three singletons; or all singletons. The number of strings of each type is easily counted. But this is kind of tedious, and would get out of control if the numbers were much larger.
Comment: Thanks. This makes sense, but can you explain what went wrong in my solution? (In the comments to the original question)
We counted the total number of ways the same way ($C(14,5)=C(14,9)$), so it looks like my next step was the wrong one.
Comment: Wait! I got it. You don't need to place all 1s between the 0s, just 4...
Comment: I take it you now see the $\binom{10}{5}$ in terms of solutions of an equation. It can be done that way, but it is not automatic, since accounting for $0$ after the initial $1$, or at the end, is slightly tricky in terms of equations.
Comment: Yeah, I found out how to correct my initial answer and got to the same (10,5) ... thanks again. :)
Answer: Number of binary numbers with 2 consecutive zeroes is Fibonacci(n) (where n is the nr\umber of bits).
If you just take it step by step, from numbers with 1 digits to more, and check how many possibilities there are, you can calculate it based on previous ones, and you will notice that the recurrence is actually Fibonacci's sequence.
Here's a nice link with an explanation https://stackoverflow.com/questions/11948007/number-of-possible-binary-strings-of-length-k
Answer: All of these numbers can be computed in GAP.  We begin with:

2002:  The number of binary numbers with 10 ones and 5 zeroes.  Computed by the following:
<code>T:=Filtered(PermutationsList([1,1,1,1,1,1,1,1,1,1,0,0,0,0,0]),L->L[1]=1);;
Size(T);
</code>
1750:  The number of binary numbers with 10 ones and 5 zeroes with two consecutive zeroes somewhere.  Computed by the following:
<code> S:=Filtered(T,L->ForAny([1..14],i->L[i]=0 and L[i+1]=0));;
 Size(S);
</code>
1200:  The number of binary numbers with 10 ones and 5 zeroes with two consecutive zeroes somewhere, and no three consecutive zeroes.  Computed by the following:
<code> R:=Filtered(S,L->not ForAny([1..13],i->L[i]=0 and L[i+1]=0 and L[i+2]=0));;
 Size(R);
</code>
840:  The number of binary numbers 10 with ones and 5 zeroes with exactly one occurence of two consecutive zeroes.  Computed by the following:
<code> Q:=Filtered(T,L->Size(Filtered([1..14],i->L[i]=0 and L[i+1]=0))=1);;
 Size(Q);
</code>

We can repeat this computation for the number of (0,1)-sequences.

3003:  The number of (0,1)-sequences with 10 ones and 5 zeroes.  Computed by the following:
<code> T2:=PermutationsList([1,1,1,1,1,1,1,1,1,1,0,0,0,0,0]);;
 Size(T2);
</code>
2541:  The number of (0,1)-sequences with 10 ones and 5 zeroes with two consecutive zeroes somewhere.  Computed by the following:
<code> S2:=Filtered(T2,L->ForAny([1..14],i->L[i]=0 and L[i+1]=0));;
 Size(S2);
</code>
1815:  The number of (0,1)-sequences with 10 ones and 5 zeroes with two consecutive zeroes somewhere, and no three consecutive zeroes.  Computed by the following:
<code> R2:=Filtered(S2,L->not ForAny([1..13],i->L[i]=0 and L[i+1]=0 and L[i+2]=0));;
 Size(R2);
</code>
1320:  The number of (0,1)-sequences with 10 ones and 5 zeroes with exactly one occurence of two consecutive zeroes.  Computed by the following:
<code> Q2:=Filtered(T2,L->Size(Filtered([1..14],i->L[i]=0 and L[i+1]=0))=1);;
 Size(Q2);
</code>

While it's a good idea to understand the material, the computer can provide a handy check of one's argument (and a means of coming up with the argument in the first place; and a means of pinpointing a flaw, if one's argument is invalid).  Moreover, the code can usually be quickly modified for other slightly different applications.
Comment: To one not versed in GAP, this looks like more work than André Nicolas' hand solution.  It is nice to have a check.
Comment: That's why I often give computational answers -- to encourage people to become familiar with GAP's features (or other computer algebra systems; but I prefer GAP since it's free and open source).


Grouped-By DataFrame: Use column-values in current and previous row in Function

Question: I've got a dataframe with this kind of structure:
import pandas as pd
from geopy.distance import vincenty

data = {'id': [1, 2, 3, 1, 2 , 3],
        'coord': [[10.1, 30.3], [10.5, 32.3], [11.1, 31.3],
                  [10.1, 30.3], [10.5, 32.3], [61, 29.1]],
       }
df = pd.DataFrame(data)

This is how it looks:
           coord    id
0   [10.1, 30.3]    1
1   [10.5, 32.3]    2
2   [11.1, 31.3]    3
3   [10.1, 30.3]    1
4   [10.5, 32.3]    2
5   [61, 29.1]      3

Now, I want to group by id. Then, I want to use the current and previous row of coords. These should be used in a function to compute the distance between the two coordinates:
This is what I've tried:
df.groupby('id')['coord'].apply(lambda x: vincenty(x, x.shift(1)))

vincenty(x,y) expects x like (10, 20) and the same for y and returns a float.
Obviously, this does not work. The function receives two Series objects instead of the two lists. So probably using x.values.tolist() should be the next step. However, my understanding of things ends here. Hence, I'd appreciate any ideas on how to tackle this!
Answer: I think you need shift column per group and then apply function with filter out NaNs rows:
def vincenty(x, y):
    print (x,y)
    return x + y

df['new'] = df.groupby('id')['coord'].shift()

m = df['new'].notnull()
df.loc[m, 'out'] = df.loc[m, :].apply(lambda x: vincenty(x['coord'], x['new']), axis=1)
print (df)
          coord  id           new                       out
0  [10.1, 30.3]   1           NaN                       NaN
1  [10.5, 32.3]   2           NaN                       NaN
2  [11.1, 31.3]   3           NaN                       NaN
3  [10.1, 30.3]   1  [10.1, 30.3]  [10.1, 30.3, 10.1, 30.3]
4  [10.5, 32.3]   2  [10.5, 32.3]  [10.5, 32.3, 10.5, 32.3]
5    [61, 29.1]   3  [11.1, 31.3]    [61, 29.1, 11.1, 31.3]

Comment: Those don't work: indexing with str will only return the first value of the coordinates. But two lists of two values are expected by the function. Maybe this was not clear from my original description. I've edited it to clarify.
Comment: I get it. But what happends for first NaNs?
Comment: Those can be skipped / be NaNs. These are the starting points. So it doesn't make sense to calculate a distance for them yet.
Comment: Thanks a lot. That solves it for me!
I'm wondering if there is a simpler / one line solution.
Comment: Hard question, I have no idea. But with `vincenty` function I find only this. `NaN`s complicated it a lot.


Dimension of "Riemann Roch Spaces" for higher dimensions

Question: Suppose $X$ is a variety of dimension $n$ and $D$ is a divisor on $X$. Is there straightforward way to compute the dimension of $H^0(X,D)$? If $X$ is a curve, we can easily do this with Riemann-Roch. I know there is a version of Riemann-Roch for surfaces, but you are still left with an $H^1$ even after using Serre Duality (and this is still only for dimension $2$).
Comment: Positivity and vanishing theorems are very useful in this kind of situation. See Lazarsfeld's "Positivity in Algebraic Geometry I" for a collection of these kinds of results. For example, see [my answer here](https://math.stackexchange.com/questions/4704774/asymptotic-riemann-roch-formula-with-exceptional-divisor-involved/4704781#4704781) for the situation when $D$ is nef.
Comment: There is no straightforward way in general (I am assuming your divisor D is effective)
Answer: The higher-dimensional Riemann-Roch is telling you something about the Euler characteristic of the line bundle. Serre duality only implicates two of these cohomology groups. So as soon as more than three cohomology groups are involved, you're not going to get something clean about $H^0$ that's not also talking about other $H^i$ in some way. [deleting wrong remark about eliminating the $H^1$ term for surfaces]
Comment: So is there another way to get info about $H^0$? Or $H^0(nD)$ for some $n$ in the general case? Can you elaborate on your last sentence?
Comment: Sorry, just saw your request! For $H^0$, or $H^0(nD)$, in general this is very hard but @Daniel in the comments makes the excellent point that what you often want is a nice vanishing theorem to control the higher cohomology.
Comment: As to your second question, I cannot elaborate it because it is wrong :-) erasing it.


Add Nested  List into $form

Question: I have something like this. How can I make $upload_items be a nested
 list under Upload examples
Something like

 Upload Ex

 YAY

What I have now
$upload_items = array(
  'PDF',
  'Video',
  'PNG, GIF, JPG, JPEG',
);
 $step_items = array(
    'Upload Examples',
    implode('

',$upload_items),
    'Describe The Project',
    'Assign Tags',
    'School/Company',
  );
 $form['step_list'] = array(
    '#prefix' => '

',
    '#markup' => implode('

', $step_items),
    '#suffix' => '

',
   );

Also, what is an easy way to add ids to these

Answer: Using #markup is ok, you want to use theme_item_list to easily build your list and add html attributes to it:
https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_item_list/7

Add Nested  List into $form


Quadratic inequalities 1

Question: The question is : $2x^2-3x-1 \leq 0$
I've got the answers but I keep getting them wrong.
If someone could write out the steps it would be greatly appreciated.
Answer: The quadratic polynomial $2x^2 - 3x - 1$ has zeroes at $$x=\frac {3±\sqrt{17}}{4}$$
and is concave up. Hence $2x^2 - 3x - 1 \leq 0 \Longleftrightarrow\frac {3-\sqrt{17}}{4} \leq x \leq \frac {3+\sqrt{17}}{4}  $
Comment: I'm having troubles with coming up with the x. Would you be able to show me how you got it?
Comment: This is done by the quadratic formula, which you should have been taught. Otherwise, I refer you here: http://math.stackexchange.com/questions/49229/why-can-all-quadratic-equations-be-solved-by-the-quadratic-formula One word of advice: sometimes, it's difficult to determine whether or not a given quadratic equation may be factored easily. What you must do is determine whether or not the discriminant, $b^2 - 4ac$, is a perfect square. If it is, it may be possible to factor the expression nicely.

Quadratic inequalities 1


Let $X\subseteq \mathbb R_{>0}$ be uncountable. Prove there is a countable subset $S$ of$ X$, such that $\sum_{x\in S} x=\infty$

Question: In other words:
Suppose that there is uncountable subset $X$ of the positive Real numers.
Prove that there is countable subset $S$ of $X$ that the sum of elements in $S$  is infinite.
The only thing I thought about was the Natural number but they don't have to be a subset of $X$ if $X$ is only real number without natural number.
Comment: Sums have organs?  Hint:  consider the buckets $[1,\infty), [\frac 12, 1), [\frac 13, \frac 12), \cdots$.  One of these must contain infinitely many of your set.
Comment: You have a set of positive numbers.  Each of those numbers has to be in exactly one of my buckets.  If there were only finitely many of your elements in each bucket then there would be finite or countably many elements in your set (why?).  It follows that at least one of my buckets has infinitely many of your elements and that gives you your set $S$ (why?)
Comment: This is very hard to read.
Comment: I tried to write it in words that's better?
Comment: the sum of all the x1,x2,...,xn in the countable subset of X
Comment: Yes.  Is my hint clear?
Comment: No, I don't understand the context to my question
Answer: For $n \in \Bbb N$, consider the sets $A_n := [\frac 1 n , \frac 1 {n-1})$, with $\frac 1 0 := \infty$.
Then suppose $A_n \cap X$ is finite for every $n\in\Bbb N$. Observe that $\bigcup_{n=1}^\infty A_n = \Bbb R _{>0}$. So,
$$X = \bigcup_{n=1}^\infty A_n\cap X$$
would be an countable set as countable union of finite sets. Contradiction.
Thus there exists an $m\in \Bbb N$ such that $A_m\cap X$ is infinite. Now take some infinite countable subset $S$ of $A_m\cap X$, for example take successively different elements of $A_m\cap X$. Obviously $S\subseteq X$, and since for every $s\in S $ holds  $s > \frac 1 m > 0$
$$\sum_{s\in S} s \geq \sum_{s\in S} \frac 1 m = \infty$$
Comment: Close, but your specific construction fails.  $A_m\cap X\cap \mathbb Q$ could certainly be empty  (suppose $X$ is the set of positive irrationals).
Comment: Ah, of course you are right. Then we have to choose elements of $A_m \cap X$ successively. Thank god, we have the axiom of choice :)
Comment: Exactly so.  (+1)


Remove Items From End Of Container With JQuery

Question: I have a feed of items coming into a list using the prepend method. I've been searching but can't find a method to remove X number of items from the end - to prevent it overflowing.
How do I remove the last 3 elements from this list using jquery?

Answer: You could use the .slice() method to remove the last three elements from the jQuery object:
$('#feed li').slice(-3).remove();

Snippet:

$('#feed li').slice(-3).remove();

1

2

3

4

5

6

Alternatively, you could also use the jQuery :gt() selector and specify a negative number for the index. Keep in mind that the index for this selector is zero-based, which means that -4 would be used to remove the last three elements.
$('#feed li:gt(-4)').remove();

Snippet:

$('#feed li:gt(-4)').remove();

1

2

3

4

5

6

Comment: If you can only have so many in the list, you could do `$('#feed > ul > li:gt(4)').remove();` instead to keep the same number of items in the list (and remove any after the fifth index, for instance). Of course, no idea if that's relevant for the OP, but it works: https://jsfiddle.net/rewn0o5y/
Comment: $( "li" ).slice(-3).remove(); it work great i create a jsfiddle ; https://jsfiddle.net/f0cuocmg/
Comment: @AbderrahimSoubaiElidrissi - Yep, I included example snippets above.


How to create a list of file fields with checkboxes selector?

Question: We all know that by default drupal allows the users to create Lists consists of (float, integer, decimal and text) field types that can be useful for webforms element,
but this kind of list can't be very useful and haven't enough efficiency in content type (of course this is my personal opinion only) However,
I think this kind of list can be more flexible and powerful if combine with other types of field like Link and especially in the case of Files.
Because these kind of fields (Link & File) consists of two components Title (can be equal to field label For more convenience) that can be Stable and Value that can be Unstable.
for example I have a predefined, stable and limited list of title, List(text) and against of it there is a list of unstable and changeable of file fields in my custom content type, for this reason I decide to combine the power of lists (like default drupal list(text)) with file upload fields and create new and more powerful field type like List(file) something like below:

Advantages of this field:

Not have to change the Description (Title or label of the link) of file field eachtime that you want to upload or update a new file
Not have to change ugly file names like '102-32.exe' to something
can be more human readable.(If you want to use generic display format)
Get rid of any change or add more complexity to template files.
Comment: Nice to see you too Mr Reyhani, I think what you want is : user checks "Win 64Bit" so a file field shows up and user can upload his/her "win 64Bit" file using that, is it true?
Comment: And one more question : "there are only "Win 64,Win 32,Deb 64,Deb 32" or you want a solutions which leads to unlimited titles for fields? I mean are these titles fixed or they can be change?
Comment: Hi Mojtaba, using FIeld API you can add new widget and formatter for your fields.
sometimes more details about scenario helps better understanding of your question
Comment: @Alireza Tabatabaeian: Yes, that's right.
Comment: @Alireza Tabatabaeian: Yes, they are limited to that restricted Item only.
Answer: Add 4 file fields to your content type with desired labels (ex. "Win 64bit"),
Then you will have this 4 fields in your add content form.
Now it's time to make them optional, first of all using hook_form_alter you can add 4 new elements of class "checkbox" to your form like this:
<code>$form['dependent']['win64'] = array(
  '#type' => 'checkbox',
  '#title' => t('Win 64bit'),
);
</code>
and then for your fields add a <code>#states</code> like below :
<code>$form["win 64 file field"]= array(
  '#states' => array(
    'visible' => array(
      ':input[name="dependent[win64]"]' => array('checked' => TRUE),
  ),
);
</code>
Comment: Did u create a custom module to implement form alter
Comment: Hi Mr.Reyhani , as @Sherya Shetty mentioned, you need to create a custom module, and don't forget to include proper using in head of your .module file
Comment: good solution based on Drupal's API. vote up
Comment: @Alireza Tabatabaeian: Thanks for taking the time to help out and reply- I appreciate it greatly, but whatever I try I cant get any result. can you explain a bit more?
Comment: @Alireza Tabatabaeian: Thanks Reza, my problem was solved.
Comment: Good to hear that Mojtaba , Hope your project goes well.


Using DD to clone a 600GB drive using SSH to remote location with only 60 GB of allocated data [server migration]

Question: Please, excuse my horrible english. I'm triyng to find the way to clone a HDD server to a remote destination location, using SSH and, if possible, compress data on-the-fly to minimize unnecessary data transmission between them. The main objective is a server migration between physical & VPS appliances.
Broadband is approx 50 - 60 MB/s (transfers at 6-8 MB/s). Running a full-dd-copy estimate a 28 hours copy time. I want reduce that time as much as possible without reduce partition size in source server (i want source as-is).
Origin & destination servers are in offline status (both initiated in rescue mode).
Data on original server are 60 GB. Rest of partition is filled with zeros.
There is a way to archive that?
Until now i cloning entire disks (but not so large) with this command:
dd if=/dev/sda status=progress bs=10M conv=fsync | ssh user@ip dd of=/dev/sda

That works, but this time i'm trying to do it with too much data...
Any ideas?...
Thank you very much in advance to all. Best regards!
D.
Comment: aslong as you don't describe the network and other related things, it will only opinion based things possible
Comment: Hi, djdomi... What things do you need to complete the question?... Source & destination servers are In different data centers from same enterprise. Have root access in both servers...
Comment: hm, why not use nc for that job, it will pipe the raw data without the hazzle of encryption, second option is use a temporary space to dump the file
Comment: I was thinking about it, but SSH is better because data encryption. Precise, i don have so much space to temporary dump data, and time factor is something important in this scenario...because of that i thinking sending data with -C flag in ssh, compressing data on-the-fly... but also i'm unsure about conv=fsync in DD... or perhaps conv=sync?... my doubts are in copy of "assigned blank space" more efficiently in network...
Comment: What is the file system? I mean, using tools like `e2fsimage` might reduce the transfer to only used data blocks. But those tools are, of course, file system dependent.
Comment: So are you ultimately asking for compression? If so you can just use `gzip -c` and `zcat` in addition to / instead of `dd`. (Certainly you can use any other compression utilities that compresses even better and works with piping.) Just make sure you quote the whole comnand line for the remote host, i.e. `'zcat | dd of=/dev/sda bs=4k'` / `'zcat > /dev/sda'`.
Comment: Does this answer your question? [What is fastest way to copy a sparse file? What method results in the smallest file?](https://serverfault.com/questions/665335/what-is-fastest-way-to-copy-a-sparse-file-what-method-results-in-the-smallest-f)
Comment: Try `dd if=/dev/zero bs=1M count=100 conv=sparse 2>/dev/null | wc -c`. `conv=sparse` "suppresses" *writing*, not reading. (*What has been read* determines whether that should actually be written.)
Comment: File system is ext4. Thanks guys... I'll try Tom Yan's suggestions and come back with an update shortly... Thank you very much & Regards!
Answer: Ok, guys... finally, server migration was executed with status SUCCESS! Data copy time was aprox 5hs 30Min. Command & total time:
dd if=/dev/sda bs=5M conv=fsync status=progress | gzip -c -9 | ssh user@DestinationIP 'gzip -d | dd of=/dev/sda bs=5M'
751593062400 bytes (752 GB, 700GiB) copied, 19185.8 s, 39.2 MB/s

I want to thanks to all for your comments, specially Tom Yan. Hope this help someone else! Best regards!
Answer: Ok Guys. I return with new findings. Finally, I think i got it. Thanks to Tom Yan's directions, i realized that piping gzip -c at source side, and gzip -d at destination side did the trick.
I tried -C flag in ssh connection, with relatively no impact in speed.
So, after several tests this was the command that resolved my problem:
dd if=/dev/sda bs=4MiB conv=sync status=progress | gzip -c -9 | ssh user@DestinationIP 'gzip -d | dd of=/dev/sda bs=4MiB'

As Tom Yan's post, firstly (my bad) i not quote whole command line for the remote host and the the result not changed... so, i don't understand the reason of that quotes... of course, finally i put them... but not understand why...
Comment: Oh! Excellent explanation! Thank you very much! Tomorrow night will executed real job (hope successfully). Thanks again & come back with final results! Regards! D.
Comment: If you do not quote the command line for the remote side, the local shell will interpret the `|` in it, which means you would be piping the output of `ssh user@DestinationIP gzip -d` to `dd of=/dev/sda bs=4MiB` run on the local host. (Luckily the source and destination are both `/dev/sda`, so hopefully that didn't cause you any unexpected data loss...)
Comment: Instead of quoting, you can also use ```\``` to escape any `|` or `>` (that are after `ssh user@DestinationIP`). In that case the command line for the remote shell will remain being passed as multiple arguments (instead of one single argument) to `ssh`. (I'm not that familiar with `ssh` to tell whether it could make a difference in certain cases.)


Add button to UITableViewCell

Question: I want to add a button in a UITableViewCell. This is my code: `
if (indexPath.row==2) {
    UIButton *scanQRCodeButton = [[UIButton alloc]init];

    scanQRCodeButton.frame = CGRectMake(0.0f, 5.0f, 320.0f, 44.0f);
    scanQRCodeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    scanQRCodeButton.backgroundColor = [UIColor redColor];
    [scanQRCodeButton setTitle:@"Hello" forState:UIControlStateNormal];

    [cell addSubview:scanQRCodeButton];
}`

Now, when I run the app, I see only a blank row ! Any ideas ?
Comment: After adding `[cell.contentView addSubview:scanQRCodeButton];` you can also release the button `[scanQRCodeButton release];`
Answer: While it's natural to put it in the contentView of the cell, I'm fairly certain that is not the problem (actually, in the past, I've never had subviews displayed correctly in the contentView, so I've always used the cell).
Anyway, the problem involves the first three lines of when you start creating your button. The first two lines are fine, but the code stops working with:
scanQRCodeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];

buttonWithType: is actually a convenience method to create a button (it's like a compact alloc-init). Therefore, it actually "nullifies" your past two lines (you basically created the button twice). You can only use either init or buttonWithType: for the same button, but not both.
UIButton *scanQRCodeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
scanQRCodeButton.frame = CGRectMake(0.0f, 5.0f, 320.0f, 44.0f);
scanQRCodeButton.backgroundColor = [UIColor redColor];
[scanQRCodeButton setTitle:@"Hello" forState:UIControlStateNormal];
[cell addSubview:scanQRCodeButton];

This will work (note that you can use cell.contentView if you wanted). In case you're not using Automatic Reference Counting (ARC), I would like to mention that you don't have to do anything in term of memory management, because buttonWithType: returns an autoreleased button.
Comment: Yup. That was the problem. Thanks a lot.
Answer:     UIButton *deletebtn=[[UIButton alloc]init];
            deletebtn.frame=CGRectMake(50, 10, 20, 20);
            deletebtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            [deletebtn setImage:[UIImage imageNamed:@"log_delete_touch.png"] forState:UIControlStateNormal];
            [deletebtn addTarget:self action:@selector(DeleteRow:) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:deletebtn];

or
// Download class and import in your project UIButton+EventBlocks
UIButton *deletebtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[deletebtn setFrame:CGRectMake(170,5, 25, 25)];
deletebtn.tag=indexPath.row;
[deletebtn setImage:[UIImage imageNamed:@"log_delete_touch.png"] forState:UIControlStateNormal];
[deletebtn setOnTouchUpInside:^(id sender, UIEvent *event) {

  //Your action here
}];
[cell addSubview:deletebtn];

Answer: You want to add any custom UI elements to the cell's contentView.
So, instead of [cell addSubview:scanQRCodeButton];
do [cell.contentView addSubview:scanQRCodeButton];
Answer: Try adding [cell.contentView addSubview:scanQRCodeButton]; or if you want the button to the left side look at my question at the answer, to move the textLabel to the side. If you want the button to the right then just set it as your accesoryView like this cell.accesoryView = scanQRCodeButton;.
Comment: I added it in contentview also, but it did not work. I think Kevin Low gave the solution. Let me try it.
Answer: Method setTitle does not work in my code,  so I have set by using
[UIButton.titleLabel setText:@""]

instead of using setTitle method.
Please try again with following code:
[scanQRCodeButton.titleLabel setText:@"Hello"];

Then it would work well.

Add button to UITableViewCell


How to find stolon version

Question: Hi I am new to infra related work.
I am asked to copy 0.14.0 version of stolon binary files like stolonctl, stolon-keeper, stolon-proxy and stolon-sentinal to our postgresHa docker-container.
I created a new container using the files in git hub and got those binaries and used them for my purpose.
Now when I try to find the version by using:
stolon-keeper --version.
I get stolon-keeper version 1beee94295d009c171d89f644c854d464d7b77c8
I copied the files from  0.14.0 only.
But now I need to give my docker image to QA people.
How can I find the exact version from the above statement?
Answer: The binary files are generated by the CI uppon new releases.
You need to download the available ones directly from the release page assets (e.g., stolon-v0.14.0-linux-amd64.tar.gz from v0.14.0), then the versions should be right:
$ stolon-keeper --version
stolon-keeper version v0.14.0

How to find stolon version


Cut text in mysql

Question: I have table:
Names
id | name    | text
1  | Mr Paul | aaaa
2  | Mr Marc | bbb
3  | Mr John | ccc

How can i  remove prefix "Mr " with SQL?
Comment: Do you want it to be invisible in a selection query, or do you want to update your table?
Comment: i want update my table
Answer: You can use REPLACE() function.
 SELECT REPLACE(name, 'Mr ', '' ) FROM Names;

In order to update table do:
 UPDATE Names set name = REPLACE(name, 'Mr ', '' );

Little comment on optimization of this task: as stated in other answer, you can achieve that with SUBSTRING function - this approach might be faster if you know that every row starts with Mr - DB engine does not have to look for Mr string (which consumes some time) but arbitrary cuts first 4 letters.
Combo solution (matches only Mr at the beginning but uses faster SUBSTRING instead of REPLACE):
UPDATE Names SET name = SUBSTRING(name FROM 4) WHERE name LIKE 'Mr %';

Comment: How about `name=Mr BlahMr Blah`?
Comment: you have to put `WHERE` condition in the query, otherwise things will happen like @Amir said. check my answer.
Answer: You can use REPLACE, although note that it will find instances ANYWHERE in the field, and not just at the beginning.
e.g.
select replace(x.Name, 'Mr ', '')
from
(select 'Mr Smith' as name
union select 'Mr Jones') as x;

Answer: Here is your answer,
MySQL REPLACE function do the task
UPDATE table
   SET name = REPLACE(name, 'Mr ', '')
WHERE name LIKE 'Mr %'

It updates all names which begins with Mr suffix
Answer: SELECT SUBSTRING(name FROM 4) AS newname;

Cut text in mysql


UIAccessibilityPostNotification in background

Question: A blind tester of mine suggested the use of simple vocal notifications instead of the full blown ones, totally useless to them and just wasting battery life. So I thought of employing:
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification,"string")

for that. Too bad the string is not read while the app is in background as I could test by executing the app in the remote fetch target. Is there some way to trigger just voice notification even in background for VoiceOver users?
Comment: i believe uiaccessibility will only reads the elements visible to the user, but not when the app is in background. Did u try posting the notification in the app delegate app enter background method ?
Comment: Yes, of course and I also checked the command was executed. In fact I was of that idea too, yet my blind tester told me other apps provided voice notifications without showing any alert and I may think of no the way to attain that, short of recording the message and delivering it as a sound.
Answer: Use the AVSpeechSynthesizer in background mode to get your vocal notification and check if VoiceOver is running if it's just for this kind of users.


configuring linux console email client to check attachments

Question: I need to configure a IMAP4 capable (console-based) email client to
- check and edit the name of an attachment ("contains umlauts?" -> change character ä to ae)
- delete emails that don't fit certain requirements (not PDF, DOC,... not from domain xyz.com)
Whether the client can do everything by itself or can just trigger a script on incoming mail doesn't matter.
Anyone have an idea with mail client would be suitable for such a task?
Answer: After doing some more research I found a good program which can solve my problem with only a little LUA scripting.
http://imapfilter.hellug.gr/
Answer: That's better done at the mail server level, attempting to do it at the client end just opens up race conditions.
Filtering attachments can easily be done with something like Anomy Sanitizer:
http://mailtools.anomy.net/


Jira issues in JSON format (Need to know thw classes and functions called by I am trying to use the REST API "api/2.0.alpha1/issue/{issueKey}"

Question: I am trying to use the REST API  api/2.0.alpha1/issue/{issueKey}  .
Reference: http://docs.atlassian.com/jira/REST/4.4.3/#id2413591

I would get all issue id's from rest/api/2.0.alpha1/search
Using these issue IDs get all issues in JSON format.

But as I am using localhost (local Machine) I do not want to make network calls and increase network traffic. Hence I wanted to know which class in JAVA does these URIs call so that I can directly call these classes to get the issues in JSON format.
Basically I want all the issues in JSON format without network calls.
OR
I also have all the issue retrieved in issues object but not in JSON format. How can I convert that into JSON format?

I have found the following code from JIRA:

@GET
@Path ("/{issueKey}")
public Response getIssue(@PathParam ("issueKey") final String issueKey)
{
    final Issue issue = getIssueObject(issueKey);
    final IssueBean bean = createIssue(issue);
    return Response.ok(bean).cacheControl(never()).build();
}

Answer: You could search the source code for the @GET references or use the REST API browser (https://developer.atlassian.com/display/RAB/Overview+of+the+Atlassian+REST+API+Browser)
but accessing the classes from Java probably means that you need to be running in the same class loader as JIRA or using a plugin.
Have you measured the overhead of the calls to make sure that you are not optimizing prematurely?
Comment: Yes I a using a plugin from where I have to use these classes .
Comment: I have found the following code : (Pasted in the question )

But did not find where does it convert to JSON format .. I have also found a comment above this code : "@response.representation.200.doc
     *      Returns a full representation of a JIRA issue in JSON format."


Setup a local bridged connection using VirtualBox

Question: I'm trying to forward/masquarade some trafic from my guest CentOS6 (virtualbox with bridged connection). Host is OSX Lion. Here is my network layout:
  en1 - host iface
  address: 78.251.xx.yy
  alias: 10.0.2.1

  eth0 - guest iface
  address: 10.0.2.2

Now the connection between the guest and the host is working. Only if I could make the guest to talk to the internet my job would be done.
So I tried this ipfw rule (actually made the things worse - the guest can't talk to host):
ipfw add divert natd all from 10.0.2.2/32 to any via en1

I also tried to enable ip forwarding using this command:
sysctl -w net.inet.ip.forwarding=1

Still no luck.
Comment: Try add nat to all subnet 10.0.2.0/24
Comment: `00100 divert 8668 ip from 10.0.2.0/24 to any via en1` - same effect.
Comment: Is `iptables` enabled?
Comment: iptables is a frontend tool for Linux's netfilter => no iptables in OSX
Answer: If you have a bridged connection, you do not need to forward traffic. All you need to do is configure the virtual network adapter with a valid IP address on the same subnet as the host, or let it request one via DHCP.
If you really want the host to be responsible for forwarding traffic from the guest machine and you want to configure this forwarding manually, you first need to set the virtual machine to use a "host-only" or "internal" network. Then work from there. This would be a highly unconventional approach.
The two most common options for configuring virtual machine network adapters to communicate with your LAN and/or the Internet are as follows:

Workstation (virtual machine that is strictly a client): set the virtual network adapter to NAT, let the VM's operating system obtain an IP address using DHCP, and forget about it. Your VM will be able to make outbound connections to any LAN or internet IP address, but it will not accept inbound connections from other computers on your network. Note that this may be undesirable if the host has a private IP address due to "double-NAT" issues.
Server or Peer (virtual machine that offers network services of any kind): bridge the virtual network adapter to a physical network card. Give the virtual machine a valid IP address on the host's subnet either via static assignment or via DHCP. Your VM will function exactly like a physical computer on the host's LAN subnet.

Of course, if a host has multiple network adapters, you also have the option of bridging the virtual adapter to a different card which could be connected to a different LAN, DMZ, etc.
Comment: I can't get another ip from the hosts subnet and still get internet to the guest. My ISP doesn't allow that. This is why I tried to create an internal subnet with the bridged connection.When I select host-only adapter is gives me an error: Invalid settings detected (very verbose, right?)
Comment: If you have access to only one IP address on the host's subnet, just use the default "NAT" setting for the guest machine's network adapter. Log into the guest OS and configure it to obtain an IP address using DHCP.


Exchange 2013 running on 2012R2 changes time to about 5 hours ahead for a short time

Question: I have an Exchange 2013 Server running Cu11 on 2012R2 OS. Twice now, it has randomly changed its system time, to about 5 hours ahead for a duration of about a couple minutes, then changed back to correct time. This freaks out the transport services and requires them to be restarted. After the services are restarted, time stamps on the messages are all the same time. the only way I've found to get the time stamp to sync is to move the affected user to another database.
Logs show that Updates were downloaded just before this happens, but doesn't show that anything installed...
Has anyone seen this before?
Thanks,
Travis
Answer: Find out what the source of your time server is
from an elevated powershell ....shell
<code>w32tm /query /computer:localhost /source
</code>
make sure you timezone is correct - your NTP server might jump ahead 5 hours because your local settings might be the wrong zone
from Powershell
<code>[System.TimeZone]::CurrentTimeZone
</code>
at least knowing those two variables might point you in the right direction.
hope that helps.
Comment: Its not a VM. I've also seen VMs do funky time things.
Comment: @Sembee I don't think its the time server, if it was then I would have seen the time change on the DC as well, in the Event Log.
Comment: they sync from the hypervisor
Comment: @Rob-d, yep but its not a VM so there is no HV.
Comment: Is there anything logged at all to indicate a cause? It isn't something I have heard of. Are you in one of those locations that keeps changing their time zone configuration? (Although a five hour change is a bit much).
Comment: Nothing that tells me what cause the time change, just "The system time has changed" I'm in Eastern Time and we haven't changed zones as far as I can remember. We do daylight savings, but thats only an hour and happend a month or so ago. It seems to change to zulu/GMT when it happens.
Comment: you should do a malware scan - another thing that can change the time is the system battery (CMOS), but this is very unlikely to drop only a few hours, it would drop all the way back to the BIOS birthday - like 2002 or something ;-)
Comment: I sure hope there aren't any NTP implementations that use/affected by time zones.
Comment: I forgot to add, the exchange server is set to one of our DCs, which is our NTP. That is synced with time.windows.com. Teh DC does not display the same symptoms.
Comment: time.windows.com is about the most unreliable time source I know. Set it to use pool.ntp.org - check their web site for the address for your location.

Is this a virtual machine by any chance? I have seen this happen loads of times with VMs.
Comment: Greg - there aren't don't worry - but you know, if you want you computer to display the right time it's helpful to configure this.


Expectation of nonnegative random variable when passed through nonnegative increasing differentiable function

Question: I am having trouble proving the following result:
Let $X$ be a nonnegative random variable and $g:\mathbb{R}\rightarrow\mathbb{R}$ a nonnegative strictly increasing differentiable function. Then
$$\mathbb{E}g(X)=g(0)+\int_{0}^{\infty}g^{\prime}(x)\mathbb{P}(X>x)dx$$
I know that it should follow using integration by parts, but using integration by parts in the more abstract setting of probability is a bit confusing to me. Details would be appreciated.
Answer: $\mathbb E[g(X)] = \mathbb E[\int_0^{g(X)}dt] =  \mathbb E[\int_{g(0)}^{g(X)}dt + \int_0^{g(0)} dt ] = \mathbb E[\int_{g(0)}^{g(X)}dt ] + \mathbb E[g(0)] = \mathbb E[\int_{g(0)}^{g(X)}dt ] + g(0) $
Now using the definition of expectation, we get:
\begin{align*}
\mathbb E\left[\int_{g(0)}^{g(X)}dt \right] &= \int_\Omega \int_{g(0)}^{g(X)}dt d\mathbb P(\omega) = \int_\Omega \int_0^\infty \chi_{(g(0),g(X(\omega))}(t)dtd\mathbb P(\omega)\\& =  \int_0^\infty \int_\Omega \chi_{(g(0),g(X(\omega))}(t)d\mathbb P(\omega) dt =\int_0^\infty \mathbb P( g(0) < t <g(X)) dt \\&= \int_{g(0)}^\infty \mathbb P( g(0) < t <g(X)) dt
\end{align*}
Use of Fubini due to all things being nonnegative (so we can swap order of integration).
Now, last thing $\mathbb P( t \in (g(0),g(X)) = \mathbb P( 0 <g^{-1}(t) < X) $
So, we get $\int_{g(0)}^\infty \mathbb P( g(0) < t <g(X)) dt = \int_{g(0)}^\infty \mathbb P(0 < g^{-1}(t) < X)dt = \int_0^\infty g'(s)\mathbb P( s < X) ds$
And we get $\mathbb E[g(X)] = g(0) + \int_0^\infty g'(s)\mathbb P(X>s)ds$
Comment: (+1)Nice answer using the change of variable in the last step to produce the derivative of $g$.
Comment: @RobertThingum Yes. It is the subsitution $s=g^{-1}(t)$. Then $t=g(s)$.
Comment: @RobertThingum Yes, sorry. Maybe I should have explained more. $g^{-1}$ exists, cause $g$ is stricly monotone. If $c = \sup\{X(\omega) : \omega \in \Omega\}$, then $\int_{g(0)}^{\infty} \mathbb P( g^{-1}(t) \in (0,X) )dt = \int_{g(0)}^{g(c)} \mathbb P(g^{-1}(t) \in (0,X)) dt$. Now after substitution $t = g(s)$, we get $dt = g'(s)ds$ and limits of integral from $0$ to $c$, so $\int_0^c g'(s)\mathbb P( s \in (0,X))ds$. But $s>0$, so it's the same as $ \int_0^c g'(s) \mathbb P(s < X) ds$. As $c = \sup\{X(\omega) : \omega \in \Omega\}$, it holds that for $x>c: \mathbb P(x<X)=0$.Hencelimit $\infty$
Comment: I am with until this line:

$\int_{g(0)}^{\infty}\mathbb{P}(0<g^{-1}(t)<X)dt=\int_{0}^{\infty}g^{\prime}(s)\mathbb{P}(s<X)ds$

There is a substitution happening here, but I don't see how you are getting from a preimage to a derivative.
Comment: Is the substitution $s=g^{-1}(t)$?
Comment: @FengShao Care to explain the substitution step?
Comment: That is very clear. I understand now, thank you.
Answer: The general result is:
Claim: Let $g$ be differentiable. If $g$ and $g'$ are bounded, then
$$ \bbox[5px,border:2px solid red]
{E[g(X)]=g(0) +\int_0^\infty g'(x)P(X>x)\,dx-\int_{-\infty}^0 g'(x)P(X\le x)\, dx.}$$ The result also holds if $g$ is monotonic, provided the RHS is not $\infty-\infty$.
Proof:  First suppose that $X$ is nonnegative. Write
$$ g(X)-g(0)\stackrel{(1)}=\int_0^X g'(t)\,dt\stackrel{(2)}=\int_0^\infty g'(t) I_{X>t}\,dt.$$ Equality (1) is the fundamental theorem of calculus (remember $g$ is differentiable), while (2) is valid because the indicator random variable $I_{X>t}$ has value $1$ when $t<X$, and equals zero otherwise. Take expectation: $$ E[g(X)-g(0)]=E\left[\int_0^\infty g'(t) I_{X>t}\,dt\right]\stackrel{(3)}=\int_0^\infty g'(t)E[I_{X>t}]\,dt\stackrel{(4)}=\int_0^\infty g'(t)P(X>t)\,dt.$$ Identity (3) is the result of Fubini's theorem. In (4) we recognize that the expectation of the indicator of an event is the probability of the event.
Next, suppose $X$ is nonpositive. A similar argument shows
$$E[g(X)-g(0)] = -\int_{-\infty}^0 g'(t)P(X\le t)\,dt.$$
For general $X$, write $$g(X)-g(0) = g(X^+)-g(0)+g(-X^-)-g(0)$$ where $X^+ := XI(X>0)$ is the positive part of $X$ and $X^-:=-XI(X<0)$ is the negative part.  Apply the previous special cases to obtain
$$ E[g(X^+) -g(0)]= \int_0^\infty g'(t)P(X^+>t)\,dt$$ and
$$ E[g(-X^-)-g(0)]=-\int_{-\infty}^0 g'(t)P(-X^- \le t)\,dt.$$  To conclude, note that $\{X^+>t\}=\{X>t\}$ when $t>0$, and $\{-X^-\le t\} = \{X\le t\}$ when $t<0$.


Replicação Base de Dados MySQL

Question: Estou esboçando um projeto online e preciso de tirar uma dúvida referente a criação do banco de dados.
Terei um banco de dados EMPRESAS contendo a referência com nome e um código.
A partir deste banco EMPRESAS vou querer gerar uma estrutura nova do banco de dados, mas não vou querer ter que criar manualmente toda vez que cadastrar uma nova empresa fazer a criação do banco na unha, existe uma função que posso fazer para replicar esta estrutura ao cadastrar uma nova empresa?
Answer: Você pode utilizar o dump default desse banco alterando o nome do banco para uma slug da empresa nova.
Aonde assim que cadastrada sera upado esse dump no mysql.
ps.: Não sei se ficou prático a explicação mas posso tentar melhorar um pouco caso necessario
Comment: Mas eu conseguiria fazer o upload do dump ao realizar um cadastro na tabela EMPRESA? Somente usando o gerenciador do banco de dados MySQL.
Comment: Interessante mas existe algum requisito para que se possa dar um CREATE DATABASE de fora pra dentro porque eu nunca tentei isso, crio todos os bancos através do gerenciador de banco de dados ou phpmyadmin.
Comment: você simplesmente separa um dump default e quando efetua o cadastro pela aplicação você abre esse dump pela aplicação trocando o create database pelo nome que quiser e realiza o import. No cadastro direto no cadastro, você pode utilizar uma trigger ou store procedure para isto.

Replicação Base de Dados MySQL


How to correctly interpret the results of Power Analysis?

Question:
Attached is the result of Power Analysis comparing the means of two independent samples.
I am having hard time interpreting the "interpretations" as it is quite convoluted.
Does it say the risk of failure to reject the null hypothesis is not significant? So it says the two means are significantly different from each other? Kindly help.
Answer: If the means and standard deviations in each group really were as you've entered, and you were to randomly sample 20 observations from group 1 and 9 observations from group 2, you would obtain a significant difference between the groups (a p-value < $\alpha$, where you've set $\alpha$ to 0.05) 98.7% of the time.
Note that power analyses must be conducted before data collection. It looks like you might have entered the details of the data you actually have here - what's called post-hoc power calculation. That would be a big mistake.
Comment: Thank you @Eoin. Originally, I have no intention to perform Power Analysis. I calculated the significant difference in the mean values of the two groups and found significant difference in the mean values. Then I was eventually asked to confirm if the small sample size in Group 2 would affect the significance. Can I conclude that the sample size of Group 2 does not affect its significant difference from Group 1? Or did I perform the correct analysis to confirm that sample size does not really make a difference in the significant difference of the mean values of the two groups?


How does boost.pool achieve re-use of allocated memory?

Question: Background
My previous question about boost.pool led me to investigate boost.pool in detail, and now I have a supplementary question to finalize my understanding.
Prelude
This reference states the following about the object pool pattern:

The object pool pattern is a software creational design pattern that
  uses a set of initialized objects kept ready to use, rather than
  allocating and destroying them on demand.

From what I can tell, boost.pool (simplified) implements the object pool pattern by means of memory allocation and management mostly based on the size of an element_type, and returns a simple pointer to an allocated object:
element_type * malloc();
void free(element_type * p);

A simple boost example also shows that it is not necessary to explicitly free the acquired  element:
X * const t = p.malloc();
... // Do something with t; don't take the time to free() it.

Question
I understand that the allocated memory will be safely freed on destruction of the pool object, but how does the pool know when a block of memory acquired by a client has been released back into the pool and is reusable if its interface hands back a direct pointer to element_type, yet a call to free() is still not required?  i.e. How can the boost pool re-use this memory if it cannot be certain that the memory is not still in use?  And if it does not re-use this memory, is this even considered the same pattern as the one explained by the wiki reference?
Answer:
How can the boost pool re-use this memory if it cannot be certain that
  the memory is not still in use?

It can't. In fact it won't reuse that memory. It only guarantee that you will have no leaks when the pool is destroyed.

And if it does not re-use this memory, is this even considered the same pattern as the one explained by the wiki reference?

The article you linked says:  Object pooling can offer a significant performance boost in situations where the cost of initializing a class instance is high
While from Boost pool introduction: Pools are generally used when there is a lot of allocation and deallocation of small objects.
So no, they are not the same pattern. One is meant to re-use objects which are expensive to construct (threads, opengl resources, etc.). The other is meant to manage a lot of small objects, giving you more control than the standard allocator gives.
As you pointed out, there are two ways of using pools:

As an allocator, calling malloc()/free() when appropriate. This is the basic pool-allocator usage, it helps to reduce memory fragmentation
Construct a ton of temporary objects and don't bother to delete them.

Example for the second case: imagine you have a graph class, where each node stores its neighbors using pointers. Now you have to make a deep copy of your graph. You will allocate a bunch of new nodes and copy the data from the old ones to the new ones, but now you have to initialize neighbors pointers, so you need a map from old pointers to new pointers:
std::map<node*,node*> old_ptr_to_new_ptr;

This is a good example where pool allocators are useful (I won't go into detail about how to use pool allocators with std containers): a lot of small objects (map nodes) which are going to be deleted all together.
Comment: Thanks for the comparison between the two patterns, this answers my question exactly.
Answer: The boost pool library provides STL allocators that are more efficient when allocating objects of the same type (as opposed to std::allocator which simply uses new and delete). This is what Stroustrup or Alexandrescu would call a small-object allocator.
As any custom allocator class, it works with essentially four separate functions: allocate, deallocate, construct, and destroy. I think their names are self-explanatory (unless you are confused about allocation vs. construction). To obtain a new object from the pool, you first call allocate(1) to get a pointer and then you call construct( ptr, value ) on that pointer ptr to get it constructed as a copy of value (or moved). And you do the reverse when you want the delete that object. These are the mechanism that all STL containers use under-the-hood to allocate-construct-destroy-deallocate their objects.
You shouldn't trust the wikipedia article that you referred to (and not in general either), it is very poorly phrased, uses very vague and inaccurate language, and takes somewhat narrow view on the object-pool pattern. And btw, quoting wikipedia is worthless, you don't who wrote it, have no reason to trust it, always go to the source.
The pattern described in the wiki (and especially in the source article) has a very different objective from what the boost pool allocators try to accomplish. As described in the wiki, the emphasis is on reusing the objects without really destroying them (e.g., a thread-pool is a good example because it would be expensive to create and destroy threads frequently, and the source article is interested in pooling database service providers for similar reasons). In boost pool allocators, the emphasis is on avoiding invoking the heap (freestore) to allocate many small objects, a task that the heap cannot perform very efficiently and will cause it to become fragmented. It maybe should have been called "small-object allocators" instead, to avoid any confusion.

how does the pool know when a block of memory acquired by a client has been released back into the pool and is reusable if its interface hands back a direct pointer to element_type, yet a call to free() is still not required?

I don't think that it can. I believe that the story goes like this. You can choose to just allocate a bunch of objects from the pool, without ever deallocating them, and that is still safe in the sense that when you destroy the pool-allocator, all its memory is flushed with it, including all the objects that you left lingering in the pool. That's what they mean by "it is not required to free the objects", simply that your application will not leak memory beyond the life-time of the pool-allocator object if you forget to free all the objects from the pool.
But, if you don't tell the pool-allocator to deallocate the objects that you no longer need (and thus, can be reused) it will not be able to reuse those memory slots, that's just impossible (given that the allocators don't deliver any kind of special smart-pointer that would be able to track the allocated objects).

How can the boost pool re-use this memory if it cannot be certain that the memory is not still in use?

If it cannot be certain that the memory is not still in use, then there is no way that it can re-use the memory. Any piece of code that would make such a reckless thing as to "assume that an object is no longer needed without being sure" would be a worthless piece of code as it would obviously have undefined behavior and no programmer could possibly use it, ever.

And if it does not re-use this memory, is this even considered the same pattern as the one explained by the wiki reference?

No, it does not implement what is explained in the wiki. You'll have to get used to the fact that terminology sometimes clash in unfortunate ways. It is more common to refer to what boost pool implements either as a "memory pool" or as a "small object allocator". This is a structure optimized for somewhat small objects that are fairly cheap to construct and to copy. Because the heap (freestore) is tailored for larger blocks of memory and tends to deal poorly with trying to find a place for small objects, using it for that purpose is not a great idea, and can lead to heap fragmentation. So, pool-allocators essentially replace the heap with something that is more efficient at allocating many small objects of the same type. It doesn't re-use objects, but it can re-use memory that has been freed, just like the heap does. And it generally allocates its memory (that it allocates away) from the heap as a large contiguous block (e.g., with std::vector). There are many other performance benefits to using a small-object allocator when appropriate. But what boost pool implements is in fact very different from what is described in the wiki. Here is the implementer's description of what pool-allocators are good for:

A good place to use a Pool is in situations where many (noncontiguous) small objects may be allocated on the heap, or if allocation and deallocation of the same-sized objects happens repeatedly.
Comment: I agree that there seems a bit of a name clash in the terminology between the two patterns.  But you are right, an understanding of a pattern should be based on its purpose and not what it is called.


test the integral $\int_{0}^{\infty} \frac {x}{3x^4 + 5x^2 +1}dx$ for convergence

Question: test the integral $\int_{0}^{\infty} \frac {x}{3x^4 + 5x^2 +1}dx$ for convergence.
My thought
Can I compare it with 1/(3x^4)?
Any hints for the solution are appreciated!
Comment: you can try $$\frac{x}{3x^4+5x^2+1}\leq \frac{1}{x^3},\,\,\,x\geq 0$$
Comment: This can be easily seen:$\forall x\geq0,  \frac x{3x^4+5x^2+1}\leq\frac x{3x^4}\leq\frac x{x^4} \because$ the terms we ignore in the denominator are all positive. By ignoring them, we make the denominator smaller and thus the value of the ratio larger.
Comment: Is $3x^4+5x^2+1>x^4$?
Comment: @Lau  but I have to prove this fact first ....... is it proved here on math stack ?
Comment: I am not speaking about this @Lau I am speaking about proving the convergence of an integral that is different from the required one (the initial point differes)
Answer: $I=\int_0^\infty \frac x{3x^4 + 5x^2 +1}dx$
$\forall x>0, 0\leq\frac x{3x^4 + 5x^2 +1}\leq\frac x{x^4}=\frac1{x^3}$
$\implies 0\leq I=\int_0^1 \frac x{3x^4 + 5x^2 +1}dx+\int_1^\infty \frac x{3x^4 + 5x^2 +1}dx\\\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \leq\int_0^1 \frac x{3x^4 + 5x^2 +1}dx+\int_1^\infty \frac 1{x^3}dx\\\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ =\int_0^1 \frac x{3x^4 + 5x^2 +1}dx+\int_1^\infty \frac 1{x^3}dx\\\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ =\int_0^1 \frac x{3x^4 + 5x^2 +1}dx+\frac12$
Since $\frac x{3x^4 + 5x^2 +1}$ is continuous on $[0,1]$ (the denominator has no real zeroes), it is bounded there and so is the proper integral $\int_0^1 \frac x{3x^4 + 5x^2 +1}dx$.


How to show NextImage in ImageView when User SwipeLeft in ImageView through UISwipeGestureRecognizer in iOS?

Question: i am Newbie in iOS Development. i want to make an application in my application i make one UIScrollview and in this UIScrollView i add an UIImageview. when viewDidAppear i set imageview image like as
<code>-(void)viewDidAppear:(BOOL)animated
{
NSDictionary *dict=[self.imagesa objectAtIndex:0];
NSString *imagelink=[dict valueForKey:@"link"];
NSLog(@"imageLink %@",imagelink);
[self.bigImage sd_setImageWithURL:[NSURL URLWithString:imagelink] placeholderImage:[UIImage imageNamed:@"1.png"]];
}
</code>
And a code to add a Gesture for my Imageview and Scrollvie like as
<code> UISwipeGestureRecognizer *swipeGestureLeftdirection=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(slideToLeftWithGestureRecognizer:)];
swipeGestureLeftdirection.delegate=self;
swipeGestureLeftdirection.direction=UISwipeGestureRecognizerDirectionLeft;
[self.bigImage addGestureRecognizer:swipeGestureLeftdirection];
[self.bigScrollview addGestureRecognizer:swipeGestureLeftdirection];

 UISwipeGestureRecognizer *swipeGestureRightdirection=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(slideToRighttWithGestureRecognizer:)];
swipeGestureRightdirection.delegate=self;
swipeGestureRightdirection.direction=UISwipeGestureRecognizerDirectionRight;
[self.bigImage addGestureRecognizer:swipeGestureRightdirection];
[self.bigScrollview addGestureRecognizer:swipeGestureRightdirection];
</code>
Here Self.bigimage is my UIImageview and self.bigScrollview is my UIScrollView.
Now i want when User Swipe left then i want UIImageview image as self.imagesa next index and when swipe right then i want UIImageVIew image back index image how it possible. Please give me Solution for it.
Comment: show your UISwipeGestureRecognizer action
Comment: @Sport UISwipeGestureRecognizer action
    -(void)slideToLeftWithGestureRecognizer:(UISwipeGestureRecognizer *)gestureRecognizer
    {
    for(index=0;index<[self.imagesa count];index++)
    {
        self.bigImage.image=[self.imagesa objectAtIndex:index+1];
    }
    }
Answer: do no use loop inside, slideToLeftWithGestureRecognizer:
write code like this
<code> -(void)slideToLeftWithGestureRecognizer:(UISwipeGestureRecognizer *)gestureRecognizer
{
     if(index<[self.imagesa count])
     {
         NSDictionary *dict=[self.imagesa objectAtIndex:index];
        NSString *imagelink=[dict valueForKey:@"link"];
        NSLog(@"imageLink %@",imagelink);
       [self.bigImage sd_setImageWithURL:[NSURL URLWithString:imagelink] placeholderImage:        [UIImage imageNamed:@"1.png"]];

    index++;
   }
 }
</code>
make index as global vairable, on viewDidLoad initailize with 0.
<code>  -(void)slideToRighttWithGestureRecognizer:(UISwipeGestureRecognizer *)gestureRecognizer
   {
      if(index>0)
     {
        index--;
        NSDictionary *dict=[self.imagesa objectAtIndex:index];
        NSString *imagelink=[dict valueForKey:@"link"];
        NSLog(@"imageLink %@",imagelink);
       [self.bigImage sd_setImageWithURL:[NSURL URLWithString:imagelink] placeholderImage:        [UIImage imageNamed:@"1.png"]];

    }
 }
</code>
Comment: But bro here my array is Contain Image URL Link.so i write like as
   NSDictionary *dict=[self.imagesa objectAtIndex:index];
    NSString *imagelink=[dict valueForKey:@"link"];
    NSLog(@"imageLink %@",imagelink);
    [self.bigImage sd_setImageWithURL:[NSURL URLWithString:imagelink] placeholderImage:[UIImage imageNamed:@"1.png"]];
    index++;
But it shows error in line   NSDictionary *dict=[self.imagesa objectAtIndex:index];
Comment: bro , i have modified my answer, see once more, if this could help you.
Comment: Here my imageview is inside my Scrollview so i add a SWipeGesture to my Imageview but your code is not work can i add a Swipegesture to my Scrollview then it is work?
Comment: can you post the code of, adding gesture on scrollview
Comment: you scrollview having one image at a time or multiple images ?
Comment: Only One image at a time.
Comment: same code is working at my pc. please see if, IBOutlet is set for bigImage
Comment: initially i set index int variable and i set its value is 0 it is right or wrong?
Comment: i got it your code is right but Sorry for take your time.


What are the differences in sweeping between the two sweepers in the curling?

Question: Mainly the skip asks the sweepers do both sweep actions, but sometimes the skip asks a single player to do action.
What is the difference between the sweeping to choose one rather than another sweeper?
Answer: It's affecting the curl of the stone.

One sweeper enhances the curl away from the sweeper.
A second sweeper on the other side of the stone would cause the same effect in the opposite direction, which would cancel or reduce the curl (depending on who sweeps more/better).

So depending on who sweeps (or sweeps more than the other sweeper) you can basically steer the stone by giving it more or less curl... so if you need a lot of curling only one sweeper takes action until the stone is on its designated track, while with two sweepers working equally the stone just goes more straight forward.


Finiteness of expected values for independent random variables

Question: Show that if the random variables X and Y are independent and for some $p > 0$: $E(|X+Y|^p)<\infty$, then $E(|X|^p)<\infty$ and $E(|Y|^p)<\infty$.  I'd share thoughts or working out, but unfortunately I have none worth sharing.
Comment: Use fubini to show $\mathbb E \vert X + y \vert^p < \infty$ for almost every y
Comment: I remember this problem from Chung's book.  You can write this with joint distributions.  $\mathbb E \vert X + Y \vert^p < = \int \int \vert x + y \vert^P d \mu(x) d\mu(y) = \int (\int \vert x + y \vert^P d \mu(x))d\mu(y) < \infty$.  Since the integral is finite, the integrand must be finite for a.e. y. For any such y $\int \vert x + y \vert^P d \mu(x) = \mathbb E  \vert X + y \vert^p < \infty$.
Comment: Sorry, but I don't understand this.
Comment: @mike $X$ and $Y$ doesn't necessarily share the same distribution, but the proof is also ok.
Comment: Does $\mathbb{E}(|X+y|^p) < \infty$ immediately imply that $\mathbb{E}(|X|^p)<\infty$?
Answer: Prove that for every $t> 0$ and $\epsilon > 0$, one has $P(|X+Y| > t) \ge P(|X| > t + \epsilon) P(|Y| \le \epsilon)$.
Then use the formula which gives absolute moments of a random variable $Z$ in terms of an integral of the distribution function $P(|Z| > t)$ : that is $E|Z|^p = \int_0^{\infty} p t^{p-1} P(|Z| >t)dt$.
EDIT : Further hints
For the first part, you just have to show that $\{|X| > t+ \epsilon, |Y| \le \epsilon \} \subset \{|X+Y| > t\}$ and then use independance.
For the second part, use the recalled formula to prove that $E|X|^p$ is finite, using the majoration $P(|X|>t) \le \frac{P(|X+Y| > t- \epsilon)}{P(|Y| \le \epsilon)}$, valid for all $t > \epsilon$.
(you can choose once for all $\epsilon > 0$ such that $P(|Y| \le \epsilon) > 0$ (why ?))
Comment: +1. One could take $\epsilon=1$, to emphasize that this is merely a fixed value--but this is a matter of taste.
Comment: @did No, one has to choose an $\epsilon$ such that $P(|Y| \le \epsilon) > 0$.
Comment: Right. I was sloppy. Thanks.
Comment: I appreciate your help, but I still don't get it. Sorry.
Comment: @Hargrove I gave further details. Hard to guess exactly where you need help. Did you understand the main lines of the proof ? Are you only stucked on technical details ?
Comment: I can prove that $P(|X+Y|>t)\geq P(|X|>t+\epsilon)P(|Y|\leq \epsilon)$, but I can't put it all together. I'm having an abnormally difficult time understanding probability theory.


Trigonometric problem : Eliminate $\theta$ and $\phi$ from the relation and find relation between p and q

Question: Question :
Eliminate $\theta$ and $\phi$ from the relation
$$\begin{align}
p \cot^2\theta + q \cot^2\phi &= 1 &(1)\\
p \cos^2\theta + q \cos^2\phi &= 1 &(2)\\
p \sin\theta  &= q\sin\phi &(3)
\end{align}$$
Also find relation between $p$ and $q$.
I have tried different ways but unable to eliminate $\theta$ and $\phi$.
One method: If I subtract equations $(1)$ and $(2)$  then I got:
$$p\frac{\cos^4\theta}{\sin^2\theta} +q \frac{\cos^4\phi}{\sin^2\phi}=0$$
Please guide how to solve this.. thanks..
Comment: I edited to improve the formatting, and to remove the redundant equations. Please check my changes for errors.
Comment: @Blue, nice alignment! specially getting the equation tags, so neat.
Comment: @Arjang: The tag alignment comes with just an extra `&` in the `align` environment. I agree: it's a neat trick. :)
Answer: HINT:
$$p\sin\theta=q\sin\phi\implies p^2\sin^2\theta=q^2\sin^2\phi$$
$$\implies p^2\cos^2\theta-q^2\cos^2\phi=p^2-q^2\ \ \ \ (4)$$
Use $(2),(4)$ to solve for $\cos^2\phi,\cos^2\theta$
If $\cos^2\phi=y, \cot^2\phi=\frac{\cos^2\phi}{1-\cos^2\phi}=\frac y{1-y}$
Put the values of $\cot^2\phi,\cot^2\theta$ in $(1)$


PHP Error log level control: htaccess vs php.ini vs code and virtualhost

Question: I have a virtual host in my WAMP local server, where I set my log file.
I wanted to change my PHP log error level to only warnings and errors.
The best way should be .htaccess, I tried this solution:
How to disable notice and warning in PHP within .htaccess file?
Dind't work (tried others also).
At the end went to php.ini file, however is the less flexible options.
1) Which are the priority of this level error instructions? (php.ini vs htaccess vs  code)
I guess that order?
2) Why is not working in .htaccess?
I just set it on top of .htaccess, and did't work.
Comment: Whether you can set this stuff in .htaccess first of all depends on how you are using PHP with your web server, whether as an Apache module (only then it will work), or in some other way ...
Comment: "Why is not working in .htacess?" - `.htaccess` has 2 `c`'s. (At first I thought that was just a typo, but all 5 instances are spelt the same - wrong - way?!)
Comment: @MrWhite Fixed it. I thought something looked strange before but couldn't put finger on it Too consistently wrong
Comment: @ficuscr, (not native spelling hahah) :-D
Comment: @ficuscr Curious, I thought you were the OP when you said you'd "fixed it"!? If the OP had spelt it wrong (not the first time) then that could well have been the cause of this problem. (?)
Answer: My recommendation would be to use an httpd environment variable.
This can act as a flag to inform your web application about the environment. Say you had a white label product, there it can be useful for example in setting what configuration should be used with a specific vhost.
<VirtualHost *:80>
  DocumentRoot "/srv/www/foo/public"
  ServerName foo.com

  <Directory /srv/www/foo/public>

    # production | development | staging
    SetEnv APPLICATION_ENV development
    ...

And then in your PHP code you would access it like:
<?php
define('APPLICATION_ENV_LOCAL', 'local');
define('APPLICATION_ENV_DEVELOPMENT', 'development');
define('APPLICATION_ENV_STAGING', 'staging');
define('APPLICATION_ENV_PRODUCTION', 'production');

$app_env = (getenv('APPLICATION_ENV')) ? getenv('APPLICATION_ENV') : false;
if (empty($app_env) || ! in_array($app_env, array(APPLICATION_ENV_LOCAL, APPLICATION_ENV_DEVELOPMENT, APPLICATION_ENV_STAGING, APPLICATION_ENV_PRODUCTION))) {
    throw new Exception("APPLICATION ENV IS NOT SPECIFIED OR IS INVALID.");
}

What I'd do is have totally separate config / INI type files that I  include based on the environment. Those could determine error reporting behavior, maintain distinct database connections, anything else dependent on the application environment.
Comment: `AllowOverride`? Not sure. For one I that only works with mod_php, not *CGI. Not sure on your setup. Anyway, just not a good approach. You should entirely avoid use of .htaccess! Too much overhead, and there are alternatives. (Google a [blog](https://www.eschrade.com/page/why-you-should-not-use-htaccess-allowoverride-all-in-production/) post on the topic)
Comment: Thanks, it answered another implicit question that I have.
But, why the solution in the link didn't work for me?
Any idea?
Answer:

Why is not working in .htaccess?

Whether you can set PHP flags in .htaccess is dependent on how PHP is installed on your server. PHP would need to be installed as an Apache module.
However, since PHP 5.3, per-directory PHP config files are supported in the form of .user.ini files (note the dot prefix). These take the same form as php.ini files, but work on a per-directory basis in userland code.
For example:
; All errors and warnings only
error_reporting=E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED

Which are the priority of this level error instructions? (php.ini vs htaccess vs code) I guess that order?

Yes, that order (.htaccess or .user.ini). Except that some settings can only be set higher up the chain, eg. in php.ini.


Getting the current folder path when trying to get ProgramFilesX86 on server 2003

Question: When I'm trying to call this method from windows server 2003 SP2 Enterprise Edition KN x86:
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)

I am getting the current directory rather than the program files directory, for example, my application is installed in this location:
C:\Program Files\Company\ApplocationName\SomeApp.exe
When calling:
string x = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);

x value will be: C:\Program Files\Company\ApplocationName
Is it a known issue? is there any ideas about this?
Comment: I am not sure if I understand your question, You are saying "for example, my application is installed in this location: C:\Program Files\Company\ApplocationName\SomeApp.exe" and you are getting "C:\Program Files\Company\ApplocationName" so what is the issue ?
Comment: What do you have in `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir(x86)`?
Answer: Copied from MSDN

"On an x86 system, passing the ProgramFilesX86 member to the Environment.GetFolderPath method returns String.Empty; use the ProgramFiles member instead. You can determine whether Windows is a 32-bit operating system by calling the Environment.Is64BitOperatingSystem property."

So you should use
string x = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);

Comment: Here is the MSDN article link: http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx


Pointer to a reference parameter

Question:
Possible Duplicate:
Function argument type followed by *&

I am looking at someone else's code right now and saw an unusual (atleast for me) function declaration syntax. Is the following valid C++ syntax?
bool Foo::Bar(Frame *&ptoframe, int msToBlock)
{
    ....
}

I think the developer is trying to declare a pointer to a reference.
thanks for the help
Comment: Look up the spiral rule. It greatly aids in reading type declarations. That is, in fact, a reference to a pointer.
Comment: Types are read from right to left.
Answer: Yes, it's valid. Read the syntax from right to left: it's read reference to a pointer. This is important if you wish to change the pointer being passed to the function. The pointer is effectively passed by reference just like any other parameter.
Here's a pretty example:
void no_change(int * ptr) {
    ptr = 0;
}

void change_ptr(int *& ptr) {
    ptr = 0;
}

int main() {

    int *x;

    change_ptr(x);

}

The value of any pointer passed to change_ptr will be changed because we are passing it by reference.
Note, however that the value of the object to which a pointer points can still be changed through the no_change function (i.e *ptr = new int). This syntax is applying only to the actual pointer, not its pointed-to object.
Comment: Did you mean `right to left` and not `left to right`?
Answer: No, the first function parameter is a reference to a pointer. Sometimes you want to change someone else's pointer... To wit:
void change_my_char(char & c)    { c = 'x';     }

void pimp_my_pointer(void * & p) { p = nullptr; }

int main() {
  char x;
  void * y;
  change_my_char(x);
  pimp_my_pointer(y);
}

Comment: Is it sad that I read `pimp_my_pointer` as `p-imp my pointer` (as in p-impl)?
Comment: @chris: It might be quite in-character, so don't feel too bad :-)
Answer: It's a pointer that's being passed by reference. This allows the callee to change the value of a caller's pointer.

Pointer to a reference parameter


Setar valor do $scope de um Controller a partir de uma Directive Angular

Question: Estou tentando fazer com que a partir de um evento em uma Directive, seja chamado um método pertencente a um Controller, a chamada do método do Controller já está correta, só que parece que o $scope, dentro desse método está errado, pois se seto o $scope.file.data a partir da chamado do evento da Directive ele até seta o valor, mas não atualiza a View, já se seto o $scope.file.data a partir do evento do ng-click na div do Controller, tudo ocorre como o esperado.
O que estou tentando é o seguinte:

var app = angular.module('myApp', []);

app.controller('myController', function($scope) {
  $scope.file = {
    data: "nada!"
  };
  $scope.setExternal = function(data) {
    console.log(data);
    $scope.file.data = data;
  };
});

app.directive('myDirective', function() {
  return {
    restrict: 'A',
    scope: {
      setOnClick: '&'
    },
    link: function(scope, element, attrs) {
      element.on("click", function() {
        scope.setOnClick({
          param: "Clicou na directive!"
        });
      });
    }
  };
});
body {
  margin: 0px;
}
.box {
  padding: 25px 0px;
  border: 2px dashed #bbb;
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
  border-radius: 5px;
  text-align: center;
  font: 20pt bold'Vollkorn';
  color: #bbb;
  margin: 10px 0px;
}

    {{file.data}}

      Está é uma Div do controller. Clique aqui!

      Está é a Directive. Clique aqui!

Exemplo também no jsFiddle.
O que posso está deixando de fazer para que a chamada a partir da Directive:
element.on("click", function() {
    scope.setOnClick({
        param : "Clicou na directive!"
    });
});

tenha um $scope válido como o ng-click da div?

Obs: no meu caso real o evento na Directive não é um simples click, e sim um processo um pouco mais complexo. Utilizei um exemplo com click para fins didáticos e práticos.
Answer: Basta adicionar scope.$apply();:
element.on("click", function() {
    scope.setOnClick({
        param : "Clicou na directive!"
    });
    scope.$apply();
});

Fiddle atualizado
Dica: utilize $scope apenas para passagem de dados entre directives. No Angular 2, $scope será completamente modificado pois muitos desenvolvedores usam $scope para tudo, e acabam criando problemas que não existiriam se utilizassem os controllers corretamente (lembre-se que directive's possuem controllers).
Outra vantagem, é ser muito mais difícil ocorrerem conflitos de nomes e prover melhor re-usabilidade de código.
Comment: Sim, faltou apenas o `$apply`. Por alguma razão o Angular não fazendo o dirty check. Utilizando `$apply`, a gente força isso. Note que o Angular não permite chamadas aninhadas a `$apply` e que o próprio Angular utiliza `$apply` para realizar o dirty check. Sobre o uso do `$scope`, na sua diretriz esta correto, mas no seu controller, o correto seria utilizar `this.file = ...` e `this.setExternal = ...`, por exemplo. É necessário alterar as chamadas na sua view, para que funcione, e é necessário dar um apelido ao controller (`ng-controller='myController as apelido'`).
Comment: Não se preocupe, a doc do Angular não é muito clara com relação a isso. Na versão 2, estão deixando explícito o modo se deve utilizar `$scope`, inclusive com a possibilidade de deixar de existir e ser manipulada automaticamente pelo Angular (a versão 2 ainda não foi se quer definida completamente sua arquitetura, mas não será nem um pouco compatível com a versão 1).
Comment: Uhm, então o scope, está certo? O que acontece é que ele não está aplicando as alterações no View e o `$apply()` faz isso. Certo? Interessante mas estranho =(. E a respeito da dica: como não conheço muito bem angular, não entendi se o que estou fazendo está correto, ou está errado, partindo de sua dica? Parece-me está correto, pois estou utilizando `$scope` apenas para passagem de dados.


How to grant create and update permissions to a custom role?

Question: I have a new role as "Publisher". I want to grant Publisher 'create' and 'update' permission using code.
My .permissions.yml file looks like this :
'delete contact entity':
  title: Delete entity content.
'add contact entity':
  title: Add entity content
'view contact entity':
  title: View entity content
'edit contact entity':
  title: Edit entity content
'administer contact entity':
  title: Administer settings
'publisher contact entity':
  title: Publisher settings

I've used 2 functions to allow permissions.
The functions are:
 protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
// Check the admin_permission as defined in your @ContentEntityType
// annotation.
$publisher_permission = $this->entityType->getPublisherPermission();
if ($account->hasPermission($publisher_permission)) {
  return AccessResult::allowed();
}
switch ($operation) {
  case 'edit':
    return AccessResult::allowedIfHasPermission($account, 'edit contact entity');

  case 'update':
    return AccessResult::allowedIfHasPermission($account, 'update contact entity');
}
return AccessResult::neutral();  }

protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {
// Check the publisher_permission as defined in your @ContentEntityType
// annotation.
$publisher_permission = $this->entityType->getPublisherPermission();
if ($account->hasPermission($publisher_permission)) {
  return AccessResult::allowed();
}
return AccessResult::allowedIfHasPermission($account, 'edit contact entity');   }

Now, If check sitename/admin/people/permissions, the role is created by it doesn't have a tick in the checkbox for edit contact entity.
PS: In @ContentEntityType, I've defined publisher permission as:
publisher_permission = "publisher contact entity"

Comment: Are you looking for `$role->grantPermission()`? See https://drupal.stackexchange.com/questions/267623/grant-permission-for-custom-role-from-hook-install-programmatically
Answer: You may grant your permissions on install time of your module with a simple config in config/install/user.role.publisher.yml (about this):
langcode: en
status: true
dependencies: {  }
id: publisher
label: Publisher
weight: 3
is_admin: null
permissions:
  - 'add contact entity'
  - 'edit contect entity'

Your code above is not a "grant", it's a runtime-check of users permissions.


PostSharp injecting dependency to aspect

Question: Is it possible to inject dependency into PostSharp aspect?
I'd like to create NavigateBackAspect - something like that:
<code>[PSerializable]
class NavigateBackAspect : OnMethodBoundaryAspect
{
    private readonly INavigationService _navigationService;

    public NavigateBackAspect(INavigationService navigationService)
    {
        _navigationService = navigationService;
    }

    public override void OnExit(MethodExecutionArgs args)
    {
        base.OnExit(args);
        var viewModel = args.Instance as Shared.ViewModel.ViewModel;

        if (viewModel != null)
        {
            viewModel.Dispose();
            _navigationService.GoBack();
        }
    }
}
</code>
However I've read that constructor/parameter injection is not possible because constructor is called just once after compilation. Are there any workarounds?
Comment: An answer to this question has been given here: http://stackoverflow.com/a/23535219/74435
Comment: @GaelFraiteur That has nothing to do with this question. However, fex, you should probably reword the question without using the phrase 'dependency injection' because that usually refers to various IoC frameworks.
Comment: Correct. Mental conflicts -- I just happened to review this response. But what about that: http://doc.postsharp.net/##consuming-dependencies
Answer: This kind of thing is not possible mainly because attributes in general and aspects in particular can only have constant expressions in the constructor.
The constructor is called once per aspected target during compilation time. After this happens, the aspect is serialized (along with any internal data it may contain). It is deserialized during runtime, which means the constructor is not called at all. But there is no reason for it to be called; attribute constructors can only contain constant data that isn't liable to change. See about aspect lifetime here.
However, every aspected target still has its own instance of the aspect. This means you can do this during runtime initialization. You have a few options:

Supply a string key parameter to the constructor, and then during runtime look up the appropriate object using the key (from a shared dictionary).
Rely on the aspected type to have a property or field containing the object, and access it through reflection. It's recommended you do this during runtime initialization because reflection can cause performance problems.


how to find finite union of closed sets which can approximate a compact separable metric space?

Question: I have falled into a confusion when i read a book. Its statement is
Let $S$ is a complete separable metric space,Given $\epsilon > 0$, by separability, for each $n$, there exists a finite collection $\{F_{n,k}\}^{k_n}_{k=1}$ of closed sets of diameter not exceeding $n^{-1}$ and such that $\mu(\cup_{k=1}^{k_n}F_{n,k})^c < \epsilon/2^n$.where $\mu$ is a Borel probability measure on $S$.
Please help me to fill this gap.
Thanks for you help in advance!
Comment: This is not true. You have written union instead of intersection.
Comment: @geetha290krm sorry, I find i make some typing mistakes. It is $\mu(\cup_{k=1}^{k_n}F_{n,k})^c$ instead of $\mu(\cup_{k=1}^{k_n}F_{n,k}^c)$.
Answer: By definition of separability, there exists a countable dense set $A=\{a_i:i\in\mathbb{N}\}\subset S$. By density, for each natural number $n$, the collection $\bigcup_{i\in\mathbb{N}}B(a_i,n^{-1})$ equals $S$, here $B(a_i,n^{-1})$ denotes the closed ball of radius $n^{-1}$ centered around $a_i$. By the fact that $\mu$ is a probability measure we have
\begin{align*}
1&=\mu(S)\\
&=\mu\left(\bigcup_{i\in\mathbb{N}}B(a_i,n^{-1})\right)\\
&=\lim_{k\to\infty}\mu\left(\bigcup_{i=0}^kB(a_i,n^{-1})\right).
\end{align*}
So, in particular, there exists a $k_n$ such that $\mu\left(\bigcup_{i=0}^{k_n}B(a_i,n^{-1})\right)>1-\frac{\epsilon}{2^n}$; showing that
$$\mu\left((\bigcup_{i=0}^{k_n}B(a_i,n^{-1}))^c\right)<\frac{\epsilon}{2^n}.$$
If we pick $F_{n,k}=\{B(a_i,n^{-1})\,:i\in\{1,\dots k_n\}\}$ then the job is done.
Comment: awesome! Thanks for your help.
Answer: Let $(x_i)$ be  a countable dense set in $S$. Then $S=\bigcup_i \overline B (x_i,\frac 1 {2n})$ where $\overline B (x,r)=\{y\in S: d(y,x) \leq r\}$. Now $\bigcup_{i=1}^{m} \overline B (x_i,\frac 1 {2n})$ increases to $S$ so $1=\mu (S)=\lim_{m \to \infty} \mu (\bigcup_{i=1}^{m} \overline B (x_i,\frac 1 {2n})$. Hence, there exist $k_n$ such that $\mu (\bigcup_{i=1}^{m} \overline B (x_i,\frac 1 {2n})>1-\epsilon/2^{n} $. Now take $F_{i,n}=B (x_i,\frac 1 {2n})$.
Comment: awesome, Thanks for your help!


SQL Server "Finish" - what does it do?

Question: I'm working with some legacy code and have found this:
DROP TABLE #Temp
--========================================--
FINISH:
--========================================--
SET @SqlString = 'blah blah blah'

It's part of a fairly heavy stored procedure, and when I research via the interwebs the word "finish" is used pretty commonly where people are running jobs that aren't completing, so I am not having a lot of luck finding what this might be for.  It seems to me, at a glance, that the SQL should run just fine without that "FINISH:" bit being in there, but it's blue like other SQL keywords so it's obviously used for something.
Answer: It's a label used for control-of-flow jumps (e.g. GOTO).
See the documentation on MSDN for more information.
Comment: Ah, so "Finish" isn't itself a keyword, but by adding a colon at the end it becomes a label?

SQL Server "Finish" - what does it do?


Dimension of $\text{Hom}_\bar{\mathbb{C}}(V,W)$ as a vector space

Question: Let $V,W$ be two complex vector spaces. Then we define $\text{Hom}_\bar{\mathbb{C}}(V,W)=\{f:V \longrightarrow W | f \text{ is antilinear}\}$, where antilinear means that:

$f(x+y)=f(x)+f(y)$
$f(\lambda x)=\bar{\lambda}f(x)$

For every $x,y \in V, \lambda \in \mathbb{C}$. I want to calculate the dimension of this space (that it seems to be $\dim V \cdot \dim W$ as in the linear case).
I tried to generalise the one dimensional case where $V=W=\mathbb{C}$. In this setting is easy to see that $\text{Hom}_\bar{\mathbb{C}}(V,W)$ is generated by the complex conjugate $a+bi \longmapsto a-bi$ (because $f(a+bi)=f(a)-if(b)=af(1)-if(1)=f(1)(a-ib)$). I was trying to do the same thing for two generic $V,W$ using the same property, but I don't know how to proceed.
Answer: You can just define new linear space $(W', +, *)$ where multiplication defined as $\lambda*w = \overline{\lambda}w,$ $w \in W'.$ As a set $W'=W.$ It is easy to check that $W$ and $W'$ has the same dimensions. You should consider a basis in $W$ and show that it is also a basis in $W'.$  Now all antilinear functions are linear functions from $V \to W'.$ Thus we get natural isomorphism $\text{Hom}_{\overline{\mathbb{C}}}(V,W) \cong \text{Hom}_{\mathbb{C}}(V,W').$ So they has equal dimensions.


clearInterval não para a função setInterval

Question: Estou estudando as função de temporização no Javascript e não estou conseguindo fazer o setInterval() parar por meio do clearInterval()
var timer = function(){
    setInterval(() => {
        console.log(count);
        count++
        }, 200)}

var stop = function(){
    setTimeout(() => {
        clearInterval(timer)
        console.log('executei');
            }, 2000)
    }
timer()
stop()

No console da pra ver que a função stop aparentemente tá executando, mas o timer continua a rodar.
index.js:5 1
        index.js:5 2
        index.js:5 3
        index.js:5 4
        index.js:5 5
        index.js:5 6
        index.js:5 7
        index.js:5 8
        index.js:5 9
        index.js:14 executei
        index.js:5 10
        index.js:5 11
        index.js:5 12
        index.js:5 13
        index.js:5 14
        index.js:5 15
        index.js:5 16
        index.js:5 17

Comment: var timer tem que receber setInterval, mas está recebendo function.
Answer: A função clearInterval deve receber o retorno da função setInterval, porém como você encapsulou a setInterval, acabou passando a função timer como parâmetro, logo seu setInterval vai continuar a ser executado.

Você pode criar uma variável para guardar o retorno do setInterval, com isso será possível passar a mesma como parâmetro para a clearInterval:

let intervalo = null;

var timer = function(){
    let count = 0;
    intervalo = setInterval(() => {
        console.log(count);
        count++
        }, 200)}

var stop = function(){
    setTimeout(() => {
        clearInterval(intervalo)
        console.log('executei');
            }, 2000)
    }

timer();
stop();

Também é possível alterar a função timer para retornar o intervalo e a função stop para receber o intervalo por parâmetro:

var timer = function(){
    let count = 0;

    const intervalo = setInterval(() => {
        console.log(count);
        count++
        }, 200);

    return intervalo;
}

var stop = function(intervalo){
    setTimeout(() => {
        clearInterval(intervalo);
        console.log('executei');
            }, 2000);
}

let intervalo = timer();
stop(intervalo);

Documentações:
https://developer.mozilla.org/pt-BR/docs/Web/API/WindowOrWorkerGlobalScope/setInterval
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval
Answer: O valor de timer não é um "ID" do return do setInterval, é um uma função anonima que você setou:
var timer = function(){

Não tem como clearInterval adivinhar o que tem dentro da função, você tem que pegar o retorno de setInterval e expor em uma variável, algo como:

var interval, count = 0;

var timer = function(){
    interval = setInterval(() => {
        console.log(count);
        count++
     }, 200)
};

var stop = function(){
    setTimeout(() => {
        clearInterval(interval)
        console.log('executei');
    }, 2000)
};

timer()
stop()

Na verdade nem precisa ficar declarando uma série de funções, seria melhor jogar em funções diretas:

var interval, count = 0;

function timer(){
    interval = setInterval(() => {
        console.log(count);
        count++
     }, 200)
}

function stop() {
    setTimeout(() => {
        clearInterval(interval)
        console.log('executei');
    }, 2000)
}

timer()
stop()

Veja aqui a diferença de var funcao = function e function funcao()


SeriLog fileSizeLimitBytes attributes asp.net Core

Question: We are using asp.net Core 1.1 and are using SeriLog to create log file within the application.
Now to control size of log file, I added attribute fileSizeLimitBytes
<code>"Serilog": {
  "MinimumLevel": "Debug",
  "WriteTo": [
    {
      "Name": "RollingFile",
      "Args": {
        "pathFormat": "Logs/LogFileConf-{Date}-test.Log",
        "fileSizeLimitBytes": 500000
      }
    }
  ],
  "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
  "Properties": {
    "Application": "Sample",
    "Environment": "Test"
  }
},
</code>
In this case, writing to log file stopped and when I removed above attributes, writing to log file again started working
So I have added as follows
    "pathFormat": "Logs/LogFileConf-{Date}-test.Log",
    "fileSizeLimitBytes": 500000
I am not sure what I am missing here.
<code>Project.json contains following reference.
"Serilog.Extensions.Logging": "1.2.0",
"Serilog.Sinks.RollingFile": "3.0.1",
"Serilog.Settings.Configuration": "2.1.0"
</code>
Can anybody help here to solve this issue?
Comment: It would help if you can include your configuration directly in the question - cheers!
Comment: I have added configuration details
Answer: Is your log file already > 500,000 bytes? That's not a high limit, so chances are the logging stops because the file is already above it.
See Serilog.Sinks.File 4.0+ if you are looking for roll-on-file-size.
Comment: We added Seilog.Sinks.File in appsettings.json file, and included rolling file attribute as mentioned in question, but now it does not write anything in log file, can you please share example for the same? It seems i am missing something here