What should a beginner be aware of when choosing a Xun?

Question: I want to buy a Xun (an ancient flute from China). From what I have read, they are made of clay or ceramic. Image below from Wikipedia:

What is the difference between the two? Should that be a selection criterion? What other criteria should I be aware of?
Comment: From your link "Frequently, the raw materials of modern ceramics do not include clays".
It's called ceramic when baked at high temperature.
Comment: I didn't say ceramic is clay, I said clay is ceramic. One is a sub-set of the other.
Comment: Clay **is** ceramic. https://en.wikipedia.org/wiki/Ceramic
Comment: @JSFDude "Ancient" flutes were not made from "modern" ceramic materials, most of which would be completely impractical for making musical instruments.
Comment: Of course. The Xun is an ancient instrument, but I don't want to buy a 4000 years old flute. It's just that some Xun look really different. They seem to come in all sorts of shapes and materials. When you listen to Xun on youtube you can hear that the sound is not always the same. I also suspect that some of them are easier to use. For those reasons,  I would like to have feedback from a specialist.
Answer: This is an old thread, but in case somebody stumbles upon it...
I have been making many xun, experimenting with design parameters.  I am not an expert at playing them, but I suppose I'm decent.  Here are my findings:
1) width/height ratio is very important.  Taller and skinnier gives increased high range, but decreased sound quality (weak, airy sound).  shorter and fatter gives the inverse.  W:H of 1:1 gives awesome fat solid sound, but you will struggle to get an octave-and-a-third range.  W:H of 1:2 and above will give you octave-and-a-fifth or sixth range but sound quality will be terrible, with screeching and slurping feedback.  This is the purpose of 2-chambered xun: the baffle inside eliminates feedback, but does nothing to improve tone.  The middle-ground sweet spot?  .67:1.  This gives reasonably good tone with a reasonably good range (octave and a fourth).  This, by the way, is a standard 9-hole xun.
2)  Blowhole design is critical.  Any xun with a plain hole for a blowhole is garbage.  The blowhole must have some sort of bevel cut into the front side of the hole, whether this be a flat or scalloped bevel (scalloped is my preference)  This bevel drastically improves sonic response and range.  Also, the xun must display some method of allowing the player's bottom lip to come in as close as possible to the blowhole.  Some high-quality wheel-thrown xun have a thin vertical lip that forms the blowhole.  I build by hand, so I simply cut a scalloped groove behind the blowhole, thinning that portion of the clay body considerably.  Getting your bottom lip in close like this allows better sonic response and density of sound.
3) Body composition: I have experimented with low-fire clay and low-fire clay with sand added.  Sand-added clay bodies provide a more focused tone.  I mix 25% sand with dry clay powder by weight.
4) Body tuning: I have not done extensive testing with body wall thickness, however, I am under the impression that a moderately thick wall (about 1/4 inch or so) is a good thing, provided that it is tuned by thinning a belt around the middle of the bottom half of the body.  This thinning removes less than 1/8 inch of thickness but allows the body to vibrate freely, making the xun's sound much more free.
5) Corners kill sound.  The body's shape should be as bulbous and organic as possible.  This gives a freer and pleasantly windy sound quality.
I hope this benefits somebody.
Edit: after further experimentation, I have learned the huge importance of another variable...
6) Blowhole diameter: The larger the blowhole (and as a consequence, the rest of the finger holes) the more powerful and pure the tone and the greater the volume.  The counter-consideration is that the larger the holes, the more difficult it becomes to hit the high range.  I feel that a 1/2" diameter blowhole on a 5" tall xun is about right.  This produces an addictive power and clarity of tone though it takes some skill and practice to hit the high note on, particularly on the attack.
Answer: For starters, this site has a varying selection of the Xun. Prices ranging from $23 to $79 US. http://www.redmusicshop.com/Xun
From looking there, other criteria includes the hole count. From reading the wiki and other articles, the first Xun had only one hole but, I assume you don't want to go that traditional? :P The standards today are 8 hole and 10 hole Xuns; the 10 hole Xun also coming with the monikers, professional and concert-grade.
Be sure that the Xun, specifically, is what you are after.

Traditional Chinese musical instruments were classified into eight groups (bayin) according to their materials: gourd, earthenware, hide, wood, stone, bronze, silk and bamboo. It is said that there were more than 70 different musical instruments, but many of them have been lost or are obsolete today.
  https://en.wikipedia.org/wiki/Chinese_orchestra#The_ancient_Chinese_orchestra

So, it is only a Xun if it is made of earth. As Tetsujin mentions, clay is a form of earth from which ceramic can be made...
Interestingly:

Like all members of the ocarina family of wind instruments, its shape has almost no effect on its sound, which has lead to many different forms of the instrument. Some are spherical, while others are egg shaped, flattened or elliptical. Other have the form of a fish or a pear, which is the most popular today and resembles a modern ocarina. https://ocarinaforest.com/ocarinas/chinese-xun/

With this being the case, I speculate that it seems unlikely that the actual earth used to make the vessel would have any effect on the overall tone. You're looking at size and thickness for differences in tone; smaller for higher tones, larger for lower tones.
Also if anything in the composition of the instrument might effect the timbre, it's whether or not the earthenware has been glazed. The glazing itself may effect tone versus a non-glazed instrument. But, glazing is a delicate process in and of itself. Two Xuns of equal size and thickness may sound different due to their respective glazings alone...


MySQL Auto Increment failing

Question: I am having a table with one column of primary key and auto increment of int(11) data type.
When I am trying to insert into that table, I am getting following error.
Failed to read auto-increment value from storage engine Query
When I restart MySQL service, it is working fine.
I am sure that this is not problem with "Auto Increment Number Exceeded", as when I try to insert from outside it is getting inserted properly.
Is this problem with Auto Increment or some other one.
Answer: I saw the same error message on a table with a bigint(20) key and looking at the output of
mysql>show table status like 'my_big_table';

It showed:
Auto_increment: 0

when it should have been:
Auto_increment: 2157452851

(as the last row inserted had a key value of 2157452850)
There was no explanation of why the Auto_increment went to a value of 0 but it blocked inserts by our application.
I tried to do the ALTER TABLE to change the Auto_increment value, but it was apparent that the entire table was going to be rebuilt, which on a table this size would have taken many hours, so I canceled the alter.
The solution I found was to explicitly add a row with the next key value:
mysql> INSERT INTO `my_big_table` VALUES (2157452851,22808084,71,36376,'2013-03-16 15:09:55','2013-03-16 15:07:18','2013-03-16 15:09:55','Sent',NULL,7426);
Query OK, 1 row affected (0.03 sec)

This corrected the Auto_index value.
mysql> show table status like 'my_big_table'\G
Auto_increment: 2157452852

Hopefully this will help someone else.
Answer: Basically this is a bug in MySQL that causes the problem but a work around is simple. The problem happens when the Auto-Increment value of a table grows beyond the limit.
Just run this SQL query in MySQL to fix the bug.
ALTER TABLE table_name  AUTO_INCREMENT =1
Table_name is the name of the table where you found the error while inserting data into. Don't bother about the Auto_Increment value even if you have records in your table.
Answer:
When I am trying to insert into that
  table, I am getting following error.
  Failed to read auto-increment value
  from storage engine Query

This could be a MySQL Bug(#35602,#42566). Try this workaround.
Answer: On wamp where mysql version is 5.1.30 running on windows 7 64bit, it did not work.
By running alter table it happens something (I see altered rows), but value does not fix, so after refresh it comes back to null. Mysteriously removing auto_increment from key and setting it back, auto_increment value returned. Probably, it 64 bit issues, but hope someone will save hours solving this issue by resetting ID key to non auto_increment and setting back!

MySQL Auto Increment failing


Optimal allocation between loans

Question: I have a two part problem. The first asks whether I can optimally determine how I should split my weekly paycheck towards two loan payments to ensure the shortest total time to payoff my loans. The second, if possible, asks how to allocate funds if I also split funds into an investment account that grows at some rate. I have changed numbers from my real world use case.
Question 1
Given two loans, the first at \$2,000 compounded daily with an annual rate of 6% and the second at \$4,000 compounded daily with an annual rate of 7%, and I save \$10 a day. How can I optimally split my \$10 between the loans each day, to ensure I payoff the loans in the shortest time possible?
I have come up with three equations that I need to solve for.
$$f_\alpha(t) : \mathbb{N} \rightarrow \mathbb{R} $$
The domain is whole numbers representing each day and the co-domain is a range [0,1] that represents the percent of funds that are added to each loan daily. So if $f_\alpha(1) = 0.2$ then on the first day $t_1$, I would add \$2 to loan1 and \$8 to loan2. Then there are the recursive equations representing the daily loan amounts over time.
$$loan_1(t) = loan_1(t-1)*(1 + \frac {0.06}{365}) + 10*f_\alpha(t) \mid \ loan_1(0) = -2000 $$
$$loan_2(t) = loan_2(t-1)*(1 + \frac {0.07}{365}) + 10*(1-f_\alpha(t)) \mid \ loan_2(0) = -4000 $$
The loan amount on each day is the previous day's loan total multiplied by the fixed rate compounded daily plus the dollar amount added to each loan.
Is there a way for me to solve $f_\alpha(t)$ to minimize the time it takes to get $loan_1(t) + loan_2(t) = 0$? Because $f_\alpha(t)$ has a discrete input, that makes this problem non-differentiable. So I don't think I've defined the problem properly to do this with calculus but I'd be happy to change the problem statement so that $f_\alpha(t) : \mathbb{R} \rightarrow \mathbb{R}$ with your suggestion and a modification to $loan_1(t)$ and $loan_2(t)$ that isn't recursive.
Question 2
Bonus points for adding in a fourth function that represents gains in the stock market with an annual percent yield of 7%. The updated functions would look like this:
$$f_\alpha(t) : \mathbb{Z} \rightarrow \mathbb{R^3} $$
mapped from the the integer domain representing days, to a vector $v_\alpha = [v_1,v_2,v_3]$ where $v_1+v_2+v_3=1.0$ and each value is constricted to the range [0,1]. Each value in the vector represents the percent of funds that are added to each loan/investment daily. So $f_\alpha(1) = [0.1,0.3,0.6]$ would have me insert \$1 into loan1, \$3 into loan2, and \$6 into my investment account, namely the function invest3.
$$loan_1(t) = loan_1(t-1)*(1 + \frac {0.06}{365}) + 10*f_\alpha(t)[1] \mid \ loan_1(0) = -2000 $$
$$loan_2(t) = loan_2(t-1)*(1 + \frac {0.07}{365}) + 10*f_\alpha(t)[2] \mid \ loan_2(0) = -4000 $$
$$invest_3(t) = invest_3(t-1)*(1 + \frac {0.07}{365}) + 10*f_\alpha(t)[3] \mid \ invest_3(0) = 1000 $$
I'm also curious to find out if, for varying market gains, if these functions even converge. Is the problem even constrained enough? For example do I need to set a 5 year limit, and simply try to maximize wealth by paying off loans and investing over a 5 year period? I do not know, but I believe answering Question 1 will help in my quest.
Conclusion
I am a first time user so please point out any mistakes in my line of reasoning. Solving this answer will help me in the real world because the true loan amounts are much much larger. I'm an American student who paid on the order of $100,000 for tuition, so solving atleast Question 1 will help me tremendously!
Answer: The simple answer is to look at what allocation helps your net worth tomorrow the most.  When looking at loans, pay the high interest one first.  Probably each loan has a minimum payment that if you don't pay it generates a fee that is effectively a higher interest rate.  In that case, make the minimum payment on the $6\%$ loan and put all the rest toward the $7\%$ loan until it is paid off.  You may hear of a "snowball" strategy, which says to pay the maximum on the smallest loan.  The justification is psychological, in that getting a loan paid off is rewarding and will help you stay on course.  The difference in interest is often small and if the encouragement is valuable to you it can be worthwhile.  That is a nonmathematical question.  If you are interested, I suggest making a spreadsheet that shows the balance each month based on how you make your payments.  With these numbers, I think you will find the difference is tiny, so encouragement may be worth the small cost, but that is up to you.
When you look at investments, until taxes intervene you are better off borrowing if the investment returns more than the interest cost of the loan.  If you borrow a dollar at $7\%$ to invest in something that returns $7\%$ after a year you have an investment worth $1.07$ and owe $1.07$ for a wash.  If you can deduct the interest but not pay taxes on the profit (unlikely), you are ahead.  If you pay taxes on the profit but cannot deduct the interest (more likely), you are behind.

Optimal allocation between loans


How do I change a view pager submit from GET to POST?

Question: Currently when I have a view pager at my site and I want to click on another site the pager gives me a link similar to "base_url/?page=0"
How can I change that so that the link just shows me the "base_url"?
In my understanding thats because the pager submit handles requests via GET.
Answer: You can't POST a link, it's a link; by definition clicking it will send a GET for the target href. The best you could do is hijack the click to POST via JS, set something in the session, then reload the page. Or wrap the View in a form and convert the pager to use submit buttons (possibly styled like links)
But that's very awkward, and would be more than a trivial amount of effort to achieve. Plus you'll need to write a custom Views pager for either method, and you lose the ability to link directly to a certain page, destroying navigation and SEO.
I would just leave it as it is (ie the same as every pager you're likely to find), or install Views Load More or something, if it's the UI you're concerned about.


Install Commerce 2.x project template windows using composer and got HTTP 500 error

Question: I want to install Drupal Commerce 2.x in Drupal 8.x in Windows. I followed as in  Commerce 2.x project template in Github. I installed composer and from my cmd window, I ran command: composer create-project drupalcommerce/project-base mystore1 --stability dev --no-interaction
All was going fine. It loaded many components like phpunit 4.8.27. Then it displayed messages like commerceguys/addressing suggests installing sysfony/intl ... and like these. Then Writing lock file ,  Generating autoload file, Downloading file:100%, Downloading file:100%,
Then I got Downloading file:Failed
Composer/Downloader/TransportException
The "http://cgit.drupalcode.org/drupal/plain/.eslintignore?h-8.2.0-rc1: file could not be downloaded (HTTP/1.1 500 Internal Server Error)
I also searched if it had created some folder somerwhere in my C:\xampp\htdocs or somewhere, I could not get anywhere. Please help me install it completely and access drupal from browser.
I have attached screenshot. The errors are seen in lower section:
Answer: Retry ! It solves download issues.
Then find project location in C:\Users\current_user\project_name
Copy inside htdocs and browse localhost\project_name\web and continue installation.


Dúvida em select com group by e count?

Question: Estou fazendo um SQL em 2 tabelas no Oracle e gostaria de agrupar as informações de acordo com o código do cargo e também contar quantas pessoas estão nesse cargo.
Estou usando o seguinte SQL:
select f.numemp, f.numcad, f.nomfun, f.codcar, c.titcar, count(*) from R034fun f
join R024car c
on f.codcar = c.codcar
where f.codcar in ('0001157','800739','800852') and f.sitafa <> 7
group by f.codcar

Porem Recebo o seguinte erro:

ORA-00979: não é uma expressão GROUP BY
  00979. 00000 -  "not a GROUP BY expression"
  Cause:Action:
  Erro na linha: 1 Coluna: 8

Alguém pode me ajudar dizendo o que está errado em meu código?
Answer: No Oracle o "group by" tem de ser o mesmo do "select"
select f.numemp, f.numcad, f.nomfun, f.codcar, c.titcar, count(*) from R034fun f
join R024car c
on f.codcar = c.codcar
where f.codcar in ('0001157','800739','800852') and f.sitafa <> 7
group by f.numemp, f.numcad, f.nomfun, f.codcar, c.titcar

Dúvida em select com group by e count?


controlling multiple cc2541 modules

Question: can 5 or more ble modules (cc2241), each with an rgb led, be simultaneously controlled at same time from one app.I want to choose and control, at the same time,the rgb led blinking patterns from an ios/android app, so if i press a color on app, all the ble modules will respond at same time
Comment: Welcome to Stack Overflow! Welcome to Stackoverflow! Can you please elaborate your question having your effort like code or something so that people could get your problem early and help you? Thanks!
Comment: the main question is .. can multple ble modules be cotrolled at the same ti me
Answer: At the exact same time is not possible: your central only has one radio PHY, it can only talk to one peripheral at the same time. Connection events with peripherals are scheduled by the Central PHY in a round-robin manner.
If you accept some delay between deliveries of updates to the 5 modules, this is doable.
Let's suppose the 5 modules are connected with equivalent connection parameters, when your application writes the characteristic for each device, phy actually has to wait for the next connection event to actually deliver the packet, in turn for each connection.
In an ideal environment, you could assume worst case latency is (ConnectionInterval * (SlaveLatency + 1)), with some packet loss, this can easily be multiplied by 2 to 5.  ConnectionInterval and SlaveLatency are parameters set by your device.
Let's say all modules should be updated within 200ms allowing one connection event to be lost, you should have a connectionInterval under 100ms and slaveLatency = 0. This is reasonable.
Comment: Thank you, 200ms is no prob. i was not expecting for instant response
Comment: would the response be the same if it was an rf remote control system instead of ble?
Comment: If you mean custom protocol, it could be different: you could design this protocol to broadcast a single packet to control the 5 modules. You'll still need some sort of acknowledgement to work around radio glitches.
Answer: It is possible if you are using Broadcast/Observer connectionless model.
This is exactly the same way how Apple iBeacon works.
In this mode all data is transmitted in advertisement packet of broadcasting device. If you take look on TI CC254x examples you will find few implementations that uses it.
Depending of your application this could be perfectly OK way to go.

controlling multiple cc2541 modules


MySQL count "IN" statement matches

Question: In a query like this:
SELECT ID FROM table
WHERE field
IN (SELECT field2 FROM table2 WHERE condition)

How I can order the returned rows by the number of records matching in the IN statement ?
Comment: You need to clarify what you mean.  The number of records matching in the `IN ()` subquery is a scalar value, and so ordering by it does not make sense. Post a sample recordset and a sample expected output if possible.
Answer: I am going to assume that you mean by the number of distinct values in table 2 that match.
select t.ID, count(t2.field2)
from table t left outer join
     (select distinct field2
      from table2
      where condition
     ) t2
     on t.field = t2.field2
group by t.id
order by count(t2.field2) desc;

Why is it structured like this?  The left outer join ensures that all rows from table are in the result set.  The distinct ensures that duplicate rows in table2 do not result in duplicate rows in the output.  count(t2.field2) counts the number of matches in the second table, so it will be 0 when there is no match (as opposed to count(*) which would be 1 in that case).
This is assuming that id is unique in table.
Answer: try JOIN-ing ON where those fields are equal and then do a COUNT() like below, then you can ORDER BY that COUNT() (representing occurences of field = field2)
SELECT table.ID,COUNT(*) as occurrence
FROM table INNER JOIN table2
ON table.field = table2.field2
WHERE condition
GROUP BY table.ID
ORDER BY occurrence

MySQL count "IN" statement matches


Add css from a block

Question: I am building a custom magento module and i try to add a custom css file to my block. I wrote :
<?php
class Wise_InteractiveSlider_Block_Slider extends Mage_Core_Block_Template
{
   protected function _prepareLayout()
   {
      $this->getLayout()->getBlock('head')->addCss('css/mycompany/mymodule/stylesheet.css');
      return parent::_prepareLayout();
   }

 }

but it doesn't work, my css file is not loaded, any idea?
Thank you.
Comment: Does a link element for your CSS get added to the page when your block is loaded?  It's narrows down the problem area if it is not.
Answer: My alternative solution was to add this in my xml layout :
<default>
  <reference name="head">
      <action method="addCss"></action>
  </reference>
</default>

Thank you for your help
Answer: All the CSS & Images are normally available in the "skin" folder. It should be:-
"skin" folder
   -> Package Name (like "base" or "default")
      -> Theme Name (like "modern" or "mycompany")
         -> "css" folder
            -> "mymodule" folder
               -> "stylesheet.css" file

So I suppose that you have been following this above-mentioned basic structure, which is considered as one of the best practices.
Coming back to your question, I suppose that you have mentioned the correct block class in your module's layout file "layout.xml". So the above code should be, according to the above folder structure:-
<?php
class Wise_InteractiveSlider_Block_Slider extends Mage_Core_Block_Template
{
   protected function _prepareLayout()
   {
      $this->getLayout()->getBlock('head')->addCss('css/mymodule/stylesheet.css');
      return parent::_prepareLayout();
   }
}

Lastly, please make sure that you have uploaded your CSS file "stylesheet.css" in the correct folder.
Hope it helps.
Comment: I used it but it doesn't work in my case. I give my solution in the answer bellow.
Answer: You can only use the _prepareLayout() method if the block is defined in the layout XML. If you 'inline' the block inside a CMS page via the {{block type... method, the layout is already prepared by the time the block is rendered

Add css from a block


How pcregrep force to return first match of regexp

Question: I have ci-pipelines and there are a lot of before_scripts sections. I would like to make a multiline regexp. I export all before script to my-ci-jobs.txt with python script.
pcregrep -M 'before_script.*\n.*' my-ci-jobs.txt
"before_script": [
    "yarn install"
"before_script": [
    "yarn install"
"before_script": [
    "yarn install"
"before_script": [
    "yarn install"
"before_script": [
    "yarn install"
"before_script": [
    "yarn install"
"before_script": [
    "yarn install"
"before_script": [
    "yarn install"
"before_script": [
    "yarn install"
"before_script": [
    "yarn install"
"before_script": [
    "yarn install"

This works fine, but sometimes, there are more lines in before script, so I would like to make regular that catch everything between before_script and first match of ],. But when I implement it, it will catch the longest match. This is my command (I will not past here the result, it is the whole file till the last ],):
pcregrep -M 'before_script.*(\n|.)*],' my-ci-jobs.txt

How can I make regexp to match first match? Is there a better way how to do a multiline regexp?
Comment: Does [this](https://regex101.com/r/mmNTu7/4) help?I edited the regex. It'll help if you provide the expected result of the above input. Perhaps you can create a small sample of your file and paste.
Comment: I think you just need `pcregrep -M 'before_script[^]]*]' file`. If you need the first match only, add `| head -1`
Comment: Thank you for replay. This does not work. It returns nothing.
Comment: Thats works, thank you. Could you explain the reqexp and Answer my question?
Comment: I needed first match of `before_script` something `],` but basically I need  all  `before_scripts` and then check the diffs. Your first reqular works perfectly as I needed.
Answer: You almost never need (.|\n)  in a regular expression, there are better means to match any chars including line break chars.
To match any zero or more chars but ] you may use [^]]* pattern:
pcregrep -M 'before_script[^]]*]' file

If you need the first match only, add | head -1:
pcregrep -M 'before_script[^]]*]' file | head -1

Pattern details

before_script - some literal text
[^]]* - a negated bracket expression that matches any chars but a ] char, 0 or more times, as many as possible (since * is a greedy quantifier) (it matches line break chars, too, because you pass an -M option to pcregrep)
] - a literal ] char (no need to escape it because ] outside a character class is not special).


Probabilistic Cauchy-Schwarz

Question: Let $Y\geq 0$ be a random variable with $v=\mathbb{E}(Y^2)<\infty$. Show that for any $0\leq a \leq  \mathbb{E}(Y)$,
$$P(Y>a)\geq \frac{(\mathbb{E}(Y)-a)^2}{\mathbb{E}(Y^2)}.$$
I started by trying to apply the Cauchy-Schwarz inequality to the random variable $Y\mathbb{I}_{Y>a}$ (where $\mathbb{I}$ is an indicator random variable). The inequality gives us that
$$\mathbb{E}(Y\mathbb{I}_{Y>a})\leq \sqrt{\mathbb{E}(Y^2)}\cdot\sqrt{\mathbb{E}(\mathbb{I}_{Y>a})}=\sqrt{\mathbb{E}(Y^2)}\sqrt{P(Y>a)}.$$
This gets almost what I need, as we can square the inequality and divide by $\mathbb{E}(Y^2)$, provided I show either $\mathbb{E}(Y\mathbb{I}_{Y>a})=\mathbb{E}(Y)-a$ or that $\mathbb{E}(Y\mathbb{I}_{Y>a})$ is at most $\mathbb{E}(Y)-a$.
As a subsequent part of the question, I need to show that $(\mathbb{E}(|Y^2-v|))^2\leq 4v(v-(\mathbb{E}(Y))^2)$. For this, I can recognize the last term is Var$(Y)$, and I attempted to use the inequality from the beginning of the problem, but my manipulations were only valid when $\mathbb{E}(Y^2)\geq \frac{1}{4}$.
Comment: This is the [Paley–Zygmund inequality](https://en.m.wikipedia.org/wiki/Paley%E2%80%93Zygmund_inequality), and you are on the right track. Just check that $$Y\mathbb{I}_{\{Y>a\}}\geq Y-a\qquad\text{and}\qquad \mathbb{E}[Y-a]=\mathbb{E}[Y]-a\geq 0.$$
Comment: Also, by replacing $Y$ by $Y/\sqrt{\mathbb{E}[Y^2]}$ if necessary, you can assume $v = 1$. So, if you have already checked the inequality for $v \geq \frac{1}{4}$, then you are good to go.
Answer: Here is a solution:
1. If $0 \leq a \leq \mathbb{E}[Y]$, then taking expectation to both sides of the inequality $ Y \mathbf{1}_{\{Y > a\}} \geq Y - a $, we get
$$ \mathbf{E}[Y \mathbf{1}_{\{Y > a\}}] \geq \mathbf{E}[Y - a] = \mathbf{E}[Y] - a \geq 0. $$
So it follows that
$$ (\mathbf{E}[Y] - a)^2 \leq \mathbf{E}[Y \mathbf{1}_{\{Y > a\}}]^2 \leq \mathbf{E}[Y^2]\mathbf{E}[\mathbf{1}_{\{Y > a\}}] = \mathbf{E}[Y^2] \mathbf{P}(Y > a). $$
Rearranging this yiels the Paley–Zygmund inequality as required.
2. By the Cauchy–Schwarz inequality,
\begin{align*}
\mathbf{E}[|Y^2 - v|]^2
&= \mathbf{E}[|Y - \sqrt{v}|\cdot|Y + \sqrt{v}|]^2 \\
&\leq \mathbf{E}[(Y - \sqrt{v})^2]\mathbf{E}[(Y + \sqrt{v})^2] \\
&= (2v - 2\sqrt{v}\mathbf{E}[Y])(2v + 2\sqrt{v}\mathbf{E}[Y]) \\
&= 4v(v - \mathbf{E}[Y]^2)
\end{align*}
as expected.

Probabilistic Cauchy-Schwarz


A question in functional equation of Gamma Function

Question: I have a question in Tom M Apostol ( Mathematical Analysis) Example on Page 278.

I beg for every one's pardon, by mistake a different image was added. I am really sorry for wastage of other people's time.

It's image is ->

I understood the example completely, but I want to ask:  Is the functional equation derived valid only when $a$ is small positive and $b$ tends to $\infty$?
I think I have seen the function equation for any $a, b$ satisfying $0<a< b$.
Comment: What functional equation?  There's no functional equation in the snippet you included.
Comment: @RobertIsrael I think the op means $F(x) = xF(x-1)$
Comment: Maybe, but there are other function equations for the Gamma function.  And what are $a$ and $b$?
Comment: @RobertIsrael Exactly the functionality equation which jacopo wrote.
Comment: @RobertIsrael by mistake a different image was added. I am really sorry.
Comment: @jacopoburelli by mistake a different image was added, I am really sorry.
Answer: The functional equation, $\Gamma(y+1)=y\Gamma(y)$, involves integrals from $0$ to $\infty$ on both sides of the equation; there are no $a$ and $b$. (Indeed, the Gamma function has other definitions as well, not involving integrals, and this functional equation of course applies to equivalent definitions as well.)
If you wanted to consider an incomplete Gamma function with endpoints at $a>0$ and $b<\infty$, that is a perfectly valid function, and its value at $y+1$ is related to its value at $y$, by exactly the equation in the OP. Notice that they are not exactly equal though, so I would hesitate to call this a "functional equation" for this incomplete Gamma function.
Basically, the introduction of $a$ and $b$ is a tool for the proof of the functional equation for the (complete) Gamma function, used because the definition of $\Gamma(y)$ is a doubly improper integral. The numbers $a$ and $b$ are not part of the definition of $\Gamma(y)$.


Atualizar tabela DataTables depois de requisição AJax

Question: Na minha página tenho o seguinte:
$(document).ready( function () {
            buscaProdutos();
        } );

Quando a página é carregada ele faz uma busca dos produtos para listar na tabela. Dentro dessa função buscaProdutos tenho o seguinte:
    function buscaProdutos() {
            $.get('buscaProdutos.php',
                function(e){
                    e = $.parseJSON(e);
                    $.each(e, function(indice, produto){
                        $("#produtos").append('' +
                            '
'+
                                ''+produto.codigo+'	'+
                                ''+produto.nome+'	'+
                                ''+produto.data_vencimento+'	'+
                                ''+produto.valor+'	'+
                                ''+produto.status+'	'+
                                'Excluir	'+
                            '
');
                    });

                    tabela = $('#example').DataTable({
                        "language": {
                            "url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Portuguese-Brasil.json"
                        }
                    });
           });
}

Dentro da função que exclui produtos, depois que ela faz a requisição para excluir eu chamo a função buscaProdutos() porém tenho o seguinte erro:

warning cannot reinitialise datatable

Vi algumas soluções que utilizam o proprio draw do DataTables para montar as tabelas mas não queria ter que refazer isso tudo já que uso dessa forma em diversas partes do sistema.
Da primeira vez que chamo a função buscaProdutos não dá erro algum. Mas daí em diante ele fica dando esse erro que não pode reinicializar a tabela.
Então minha dúvida é como eu posso chamar o DataTables depois de cada busca sem dar esse erro?
Comment: Creio que isso pode te ajudar: https://datatables.net/reference/api/ajax.reload()
Comment: Se sua tabela foi configurada  com ajax, você pode usar a forma que o colega acima falou, dando o reload. Mas caso ela não seja uma tabela ajax, a única forma que eu encontrei de contornar esse problema (que é meio gambiarra, admito) é limpar toda a div que envolve a tabela, montar ela inteira de novo e chamar .DataTable pra iniciar a tabela novamente.
Comment: Fiz isso Renato, exclui a div inteira, esqueci de colocar a solução aqui. Depois vou colocar!!!
Comment: tenta desta forma: tabela = $('#example').DataTable({ "language": { "url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Portuguese-Brasil.json" }, destroy: true
});
Answer: Ao invés de chamar a atualização da tabela assim:
$(document).ready( function () {
    buscaProdutos(); }
);

Use assim:
$('#table').DataTable().ajax.reload()// onde #table é o id da tua tabela

Fonte: https://datatables.net/reference/api/ajax.reload()
Answer: O aviso "Cannot reinitialize DataTable" ocorre quando você tenta inicializar novamente a tabela DataTables em um elemento HTML que já possui uma tabela DataTables associada a ele.
Para resolver esse problema, você pode verificar se a tabela já foi inicializada antes de tentar recriá-la. Uma maneira de fazer isso é verificar se a tabela já possui a classe 'dataTable' aplicada a ela.
Aqui está um exemplo de como fazer isso:
var tabela;

$(document).ready(function () {
  tabela = $('#example').DataTable({
    "language": {
      "url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Portuguese-Brasil.json"
    }
  });

  buscaProdutos();
});

function buscaProdutos() {
  $.get('buscaProdutos.php', function (e) {
    e = $.parseJSON(e);

    if (tabela && tabela instanceof $.fn.dataTable.Api) {
      // Se a tabela já foi inicializada, destrua-a antes de recriá-la
      tabela.destroy();
    }

    $('#produtos').empty(); // Limpa o conteúdo da tabela

    $.each(e, function (indice, produto) {
      $("#produtos").append('' +
        '
' +
        '' + produto.codigo + '	' +
        '' + produto.nome + '	' +
        '' + produto.data_vencimento + '	' +
        '' + produto.valor + '	' +
        '' + produto.status + '	' +
        'Excluir	' +
        '
');
    });

    tabela = $('#example').DataTable({
      "language": {
        "url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Portuguese-Brasil.json"
      }
    });
  });
}

Neste exemplo, primeiro verificamos se 'tabela' já está definida e se é uma instância válida de '$.fn.dataTable.Api'. Se sim, chamamos o método 'destroy()' para remover a tabela DataTables existente.
Em seguida, usamos '$('#produtos').empty()' para limpar o conteúdo da tabela no HTML.
Depois disso, iteramos sobre os dados obtidos na requisição AJAX e adicionamos as linhas à tabela usando o método 'append()'.
Finalmente, inicializamos a tabela DataTables novamente com os novos dados.
Dessa forma, você evita o erro de recriar a tabela DataTables quando ela já foi inicializada anteriormente.


Error ITMS-90062: The value for key CFBundleShortVersionString must contain a higher version than that of the previously approved version

Question: I am trying to update my app for the first time and ran into this issue. I searched a lot but none of the solutions worked for me.

App Store Connect Operation Error
ERROR ITMS-90062: "This bundle is invalid. The value for key CFBundleShortVersionString [2020.0] in the Info.plist file must contain a higher version than that of the previously approved version [2020.0]. Please find more information about CFBundleShortVersionString at https://developer.apple.com/documentation/bundleresources/information_property_list/cfbundleshortversionstring"

And my info.plist file is :

General Window:
Comment: can this be the issue ? http://stackoverflow.com/a/37048170/569789
Answer: TL;DR: If you have an app version that was approved for the official app store, you cannot upload a build with the same version to TestFlight.  You have to remove the app from official app store submission, or increase your TestFlight version #.
I figured out why this happened to me.

I have an app in the app store with version 2010.
I have been running an external beta test with version 2020, and build numbers in the range of 400-410
In order to discover if my app would get rejected in the app store once I'm ready to actually release it in a few weeks, I submitted version 2020, build 407 for official app store review.  I expected it to be rejected for various reasons.  It was approved!  However, i'm not ready to release it since I still have more fixes I want to implement.  So, I let it sit there, waiting for me to do something with it.
Then, I wanted to upload a newer build for my External beta, still version 2020, build 410, and I received this error.
Thanks to user462990's answer, I realized that the error could be due to the fact that I have version 2020 currently approved and waiting to be launched into the official app store, so iTC didn't allow me to submit the same build # for a TestFlight external beta.

So, I selected "cancel this release" of the official approved version, and Viola!  I can now upload a build with the same build #.
Comment: In Xcode 9.2:
`CFBundleShortVersionString
n.n.n.`, in `Info.plist`
Appears in UI as: "Bundle Versions string, short"
Answer: I think it was some issue on Apple's side. It resolved itself automatically after few hours.
Comment: Thx for mentioning that. After a year, I've learned that the service leaks a lot of errors that go away. Mentioning specific examples helps. For me, when you are trying to meet a deadline and you get an error, you want as much relevant info as possible.
Answer: What worked for me is to change it from 1.0 (.6) to 1.1 (.0) It's not really a new "Version" but incremental improvements and corrections. One thought is that when an app is accepted into the iTunes store then next upload must be to a higher VERSION.
Comment: Thanks for this answer, this totally baffled me!
Answer: You must always increase the version number when uploading updates, so change it from 1.0 to 1.1.
Comment: I have as you can see in .plist file
Comment: @Bilal What shows in the Xcode's target *General* window?
Comment: @Bilal OK, I don't understand that.
Comment: Changing the "Version Number" (CFBundleShortVersionString) might solve the problem by over-kill, but the error seems to be more specific.
Answer: I'm having a similar issue today. I uploaded a new build a couple days ago with no issues. I found someone who posted a similar issue here: https://discussions.apple.com/thread/7297092. They were able to resolve it by changing the Info.plist values in their sub-projects, however, I tried doing that, and I still ran into the same issue.
I cannot find any information on why this is occurring or when this started, but I know that I uploaded a prerelease build to TestFlight with all of the same projects 5 days ago.
I currently increment my prerelease builds this:
1.10 (1) -> CFBundleVersionShortString (CFBundleVersion)
1.10 (2)
...
I was up to 1.10 (7), which I deployed 5 days ago. Now, I can't get anything to work 1.10 (8), 1.10 (9), 1.10 (1.10), etc. They all say "CFBundleShortVersionString [1.0] must be greater than previously approved version [1.3]"
1.3 is correct as the previous version available in the store, but clearly, 1.0 as the Bundle version is not.
Comment: As interesting and insightful (and therefore useful) as this is, it's a comment, not an answer. I think you should simply add that it's a temporary issue with the Apple submission process, to turn it into an answer.
Comment: I posted the answer, but will comment here. Apple does not treat the version as a decimal number. They treat it as integers separated by periods.  In your case, your previous build is 1.10, which they interpret as major version 1, minor version 10.  Your new version is 1.3, which is major version 1, minor version 3. Since the existing minor version 10 is greater than 3 it will not meet their criteria. Try a new version of 1.30, or switch to their scheme and make your new version 1.11 (followed next by 1.12, etc).
Answer: For anyone else dealing with this. My scenario was similar as follows:
NOTE: For my builds the version number is in the form of a.b.c (1.4.6 in this case) and the build number is just an integer (1555 in this case). Also, in general I use Fastlane to upload builds and I am writing my apps in Flutter.
I used Fastlane to upload a build of my app (1.4.6 1553) and submitted it for review. It was approved. In the mean time I found a bug so I rejected the release and removed it as per instructions above. Then I used Fastlane to upload another build (1.4.6 1555). This build was rejected with the ITMS-90062 error. So, I tried 1.4.7 1555, still rejected. So, I tried 1.5.0 1555, still rejected. Same error (ITMS-90062) every time.
The solution for me was to create an archive (1.4.7 1555) and upload it using XCode. Going this route was successful. ...and following on from there I can now also successfully upload using Fastlane again.
For some reason a Fastlane upload after a rejection (I assume either developer rejected OR apple rejected) will not work; you'll need to do an upload from within XCode to "fix" the issue and THEN Fastlane uploads will work again.
Comment: This is the only way how I was able to work around the ITMS-90062 issue and fastline. I have not uploaded using Xcode but rather I have used this command:

`xcrun altool --upload-app --type ios --file  --username  --password `
Answer: I ran into this issue when going from version 1.141 to version 1.15.  Apple does not treat the version as a decimal number - they treat it as multiple integers separated by periods.  Thus in my case Apple considered 1.141 to be Major version 1, Minor version 141 and then my new version was Major version 1, Minor version 15.  Since 141 > 15 it fails.
Two options to deal with this:

Use Apple's interpretation of version numbers, so you always increment the minor version by 1: 1.1, 1.2, ... 1.9, 1.10, 1.11.
If you wish to use "hundreds" or "thousands" places (I do, as I try to encode the scope of the build in the precision - I use the thousands place for minor bug fix releases), then always pad them out with zeros: 1.10, 1.11, 1.20, 1.30

So in my case I went from 1.141 to 1.150 and I was able to upload.


NAS as (direct) datastore for esxi host

Question: I'm using a NAS box as a datastore for my esxi host. The NAS and esxi host are connected to each other via a switch.
I want to experiment a little and was thinking of ways to connect the NAS box to the host directly, and was wandering if it even possible and what effect(s) it will have
(1) if the NAS box and esxi host have another, spare ethernet port, can I connect them to each other directly? Instead of through a network? Would this have much of a performance gain?
(2) USB 3.0. Can I connect the NAS box to the esxi via usb 3.0 cables so that the NAS appears as a mass storage device? Given the performance of USB 3.0, would this be beneficial?
Answer: This depends on your NAS unit. You can attach the NAS as a datastore either via NFS or preferably iSCSI if that is a supported option.
Whether connecting them directly has a performance benefit depends on your network topology and how much traffic your VMs produce. If your VMs do not produce too much traffic and both the hypervisor and the NAS are attached to the same switch, the performance gain would be rather small. But if both units have a spare port anyway, there isn't really a reason not to.
Using USB as a datastore is not supported in ESXi, so I wouldn't do it. But it is possible and might be faster again depending on the exact hardware of both machines.
Another solution would be to connect both machines via 10 GbE or eSATA. eSATA is also not officially supported but it is better than USB.
Comment: Ah yes I think I have an eSATA port on both! Thanks.
Answer: 1) Yes. Performance gain due to eliminating the switch: Effectively zero. It still can help (potentially a lot) if the other network port has other traffic on it, as the direct connection is exclusive for the NAS traffic.
2) As far as you are asking if you can use USB block storage to format it with VMFS: Effectively no. It's still not official supported to my knowledge, and while there exist posts on the internet that explain how to do it anyway, I believe this is bad practice.
Answer:
Yes, it will work. The performance will will be negligible, unless your switch is completely overloaded or super duper crappy.
Possible, yet. Supported, no. You will have to test to see if it's faster.

NAS as (direct) datastore for esxi host


Homophony vs Polyphony

Question: Would I be correct if I were to define homophony vs polyphony as chords vs lines? If homophony is defined as a single melody with chordal accompaniment, and polyphony as several melodies with equal importance, then would homophony be limited to
To be honest applying this concept in most of the modern music lowkey baffles me. I can identify when a song has many layers that are formed by different motions in the instruments (e.g. vocal + a constantly moving bassline + thrumming beats with certain pattern), but the 'equal importance' criteria of polyphony is what blurs the line for me. For example, in a rock song, even if there is an independent melody developing in the electric guitar playing at the same time as the vocal, wouldn't the guitar melody still take a backseat to the vocal? Is this polyphonic?
Also one extra question : would the addition of simple melodic pattern still be homophonic? e.g that xylophone part from Somebody That I Used to Know
Answer: Homophony and Polyphony are not absolute, mutually exclusive terms.
A melody with strummed guitar chords is pretty much homophonic.  Add a bass line that does anything more interesting than just stick on I, IV or V and we're beginning to get an element of polyphony.   Add the idea that it's effective to have the bass rise where the melody falls, that a long note in the melody works well against a little run in the bass and there's even more.
Let's start from the other direction.  A Bach fugue is basically polyphonic.   But every now and again there'll be a bit that could have come straight out of a traditional hymn book.  A bit of homophony.
Don't suffer over whether a particular piece of music is Homophony or Polyphony.   Just look for homophonic and polyphonic elements in it.   You'll generally find both.
Also, be clear over your definition of 'polyphony'.  It doesn't always mean several INDEPENDENT voices.   A homophonic SATB  note-for-note harmonisation of a hymn tune could be called polyphonic - it has 4 voices! A one-oscillator synth is monophonic, a 2,4,20... oscillator one can be 2, 4 20... -voice polyphonic.   Better perhaps to talk of Monophony and Counterpoint.
Comment: Nice explanation, clarifying that music can have elements of both. Suggest two small changes to the final paragraph: 1) OP mentioned polyphony containing voices of "equal importance", but the key element is not "importance", but "independence", as you point out — seems worth amplifying. Also 2) polyphony does mean "independent" voices; calling an SATB hymn polyphonic is too wide a definition — it would make even a singer with chordal guitar accompaniment polyphonic, the guitar playing multiple voices simultaneously.
Comment: @Aaron thanks for pointing this out! After doing some futher research, I agree that it's the independence of the lines that matters most to polyphonic texture. I'm still a bit ambivalent about the 'equal importance' trait though. The literatures that I read are pretty conflicting, in the sense that some only attributed the equal importance trait specifically to couterpoint or fugue, while other says that 'equal importance' in general is a must-have for any polyphonic texture. Can anyone clarify this?
Comment: @Anastasia Celine   You're trying to make a hard distinction between homophony and polyphony/counterpoint.    There isn't one.  Counterpoint starts the moment that any voice shows independence from the melody.  It doesn't have to be complete independence, and it doesn't have to have equal musical interest to the melody.  Fugue is, indeed, an extreme manifestation of counterpoint.   But less intense counterpoint is still counterpoint!
Answer:
Would I be correct if I were to define homophony vs polyphony as chords vs lines?

Yes, this is correct. Mind that a) homophony and  b) polyphony are just 2 different aspects of composing or analyzing a set of voicings:
a) is prioritizing the vertical aspect, as you say the chords, b) is concerning the horizontal aspect of the voicing: the lines. The more 2 or more voices are independent, leading their own way  or imitating each other, the more we are speaking about polyphony, while a setting of voices, that are streaming together horizontally in equal rhythm accompanying a tune we have a homophonic setting.

For example, in a rock song, even if there is an independent melody developing in the electric guitar playing at the same time as the vocal, wouldn't the guitar melody still take a backseat to the vocal? Is this polyphonic?

I agree, that some styles are difficult to categorize as one of these 2 types. How about the early organum with parallels of 5ths? Hindemith says, this was not real polyphony, just a simple preliminary stage of it.
Comment: @LaurencePayne "Polyphony" means multiple independent voices. The independence is part of the definition.
Comment: @LaurencePayne That's insulting. And I made a point of looking up the definition in a variety of different sources. All agreed.
Comment: I have never heard of a note-for-note hymn-tune harmonization referred to as "polyphonic." I agree with Aaron and Albrecht that voice independence is a vital aspect of polyphony.
Comment: Be careful.  There's the Monophonic/Polyphonic distinction where Polyphonic merely means 'more than one voice'.  In this sense a note-for note harmonisation of a hymn tune could be said to be 'polyphonic'.   This is rather different to the Homophonic/Polyphonic distinction, where 'Polyphony' might better be called 'counterpoint'.
Comment: @Aaron Yes, that's what Wikipedia says.  There are other, looser definitions!
Comment: "Polyphony, in music, the simultaneous combination of two or more tones or melodic lines (the term derives from the Greek word for "many sounds"). Thus, even a single interval made up of two simultaneous tones or a chord of three simultaneous tones is rudimentarily polyphonic. Usually, however, polyphony is associated with counterpoint, the combination of distinct melodic lines."   https://www.britannica.com/art/polyphony-music
Comment: There is a further definition of Polyphony in the world of electronic music.  "Polyphony refers to the maximum number of notes that a keyboard or sound module can produce at one time. For instance, if you were to play a 3-note chord with a 1-note melody, you'd need at a keyboard capable of at least 4-note polyphony. "  https://usa.yamaha.com/support/faq/music_production/7255.html
Answer: From my understanding polyphonics are a single instruments ability to play two or more notes concurrently (at the same time).  Therefore a singer's voice is considered monophonic and not polyphonic because the singer can only reproduce one audible voice at a time.  More examples of monophonic instruments include trumpet or a trombone.  Many synthesizers are only capable of monophonic playback being able to play sound from only one depressed key on the keyboard at a time and at any given point in time regardless of how many keys are depressed at the same given point in time.  If a voice is to be reproduced synthetically with the sampler on a polyphonic synthesizer, it then can support multiple playback of the audible voice.
Now a grand piano is considered polyphonic because you can play multiple notes at the same time like playing a cord or triad.  Stringed instruments would be considered polyphonic to a degree because a musician are capable of playing two strings at the same time with one bow.  Guitars are also polyphonic capable.  Many other synthesizer keyboards support polyphonic playback so that capable of playing multiple audible notes at the same time mimicking an analog piano's polyphonic abilities.
As far as homophonics are concerned , YourDictionary describes -

The definition of homophonic is having one sound or line of melody at a time that >is played by multiple instruments at the same time, or two words that are >pronounced the same but differ in their meanings.

An example of something homophonic is a piece of music with chords, where two >instruments play the same line of melody in the same rhythm; however, one >instrument plays one note and a second instrument places a note in harmony.

An example of homophonic words are pair and pear.

I'll quickly summaries that homophonics are the act of an instrument playing in unison or harmony with another or other instruments.
Another example of the latter definition of homophony are the difference of the two words won, and one.   – they both are words that mean two different things, but, homo-phonetically audibly sound the same as if they were the same word.
Therefore two or more polyphonic or monophonic instruments vs. a homophonic instrument or instruments can be played in homophonetic unison and in harmony.  These instruments playing in unison are not exactly considered to be playing in polyphony.
These answers should satisfy the initial question even if whatever notes being played sound out of tune or out of harmony.  :)
Comment: I must be confusing polyphony as it relates to heterophonics instead of homophony.  I learned something new. Thank you.  There is a lot to learn from a good question like the one that is asked.  I enjoyed reading all of the great and interesting answers.
Comment: These are different usages of these words than what is being asked about. The question regards the musical textures known as polyphony and homophony rather than the terms as used in describing the capabilities of instruments.

Homophony vs Polyphony


PHP upgrading to 5.3.3 - what should I be aware of?

Question: I have a VPS that's hosting half a dozen PHP-based sites. All is OK on php5.2.10 but I want to upgrade to 5.3.3.
I have tested the functionality of the sites on my local dev machine running 5.3.1 and all is well.
Having never done a PHP upgrade, and not wanting to disrupt the service of the live sites, are there any precautions you can give me that I should be considereing before I do this?
Thanks.
Answer: Testing on another computer is a good way to start, but to have the best result try to test with 5.3.3 and on a computer that look like as much as possible the server configuration.
A virtual machine is a good way to duplicate server setup and test an upgrade.
You also want to read http://www.php.net/manual/en/migration53.php to understand change between 5.2 and 5.3 so that you will see if you can have any potential issue.


How to prevent escape characters in MySQL varchar inserted by PHP PDO via jQuery AJAX

Question: I think it's strange that I can't find anything on this, but that's the case.
On my site, I allow users to enter text to be stored in my database.  I use PDO to keep it safe, but then all of the dangerous characters have "\"s in front of them.
Is there an easy way to get rid of all that?  Should I be using a different datatype in MySQL?
Thanks in advance!
No double escaping.  Laziness prevented it
I read that just doing straight PDO made it so you didn't have to worry about escaping, sanitizing, bleaching, scrubbing, etc...
I do the standard PDO INSERT like so How do I insert into PDO (sqllite3)?
The data is transmitted by jQuery ajax.  Is that the source of the problem?  If so, how do I reverse it?
Thanks for your help!
Specifics on problem
I have "\"s in front of quotes and double quotes only.  Thanks!
Versions
PHP 5.3 for Zend Guard compatibility.  MySQL 5.5.  Apache 2.2.2.  jQuery 1.8.3
+1 for reversal
I'll give as many +1s as answers on how to reverse these /'s.  Thanks!
Magic Quotes
was the answer.  Anyone want to lengthen their answer for check?
Still looking for a SQL statement to reverse previous escaping.  Thanks!
Comment: Is it possible you're using an older version of PHP with [magic quotes](http://www.php.net/manual/en/security.magicquotes.what.php) enabled?
Comment: `phpinfo()` should tell you whether it's enabled. I think the only way to control `magic_quotes_gpc` (the most likely culprit) is in your php.ini.
Comment: If you've verified with `phpinfo` that magic quotes is the problem, you can give this link to whoever has access to the php.ini file on your server: http://www.php.net/manual/en/security.magicquotes.disabling.php Note that if other code on that box relies on magic quotes to escape user input, it may cause errors or security holes.
Comment: how do danagerous character looked like? :D
Comment: big bad "'"s and """s.  They're so sharp.  They cut my database to shreds.  LOL  Thanks for looking!
Comment: Are the extra characters `/` or  \
Comment: Yeah, PHP ~5.3 for Zend Guard compatibility.  If you think that's the problem, can you give details on how to shut off, so I can give you the check?  Thanks!
Comment: You should have a look at how your data's coming in. It is probably escaped before it hits PDO.
Comment: I swear I'm doing nothing but taking data from HTML input type text and textboxes, transmitting by POST via jQuery AJAX, and inserting into MySQL with PHP PDO.
Comment: Can you guys tell me how to turn it off?  I have security up the ying yang, and someone else does the server stuff.  Thanks!
Answer: This can be caused by having magic quotes enabled on the server. In particular, it's probably the magic_quotes_gpc directive, which can be set in php.ini, .htaccess, etc, but not at runtime with ini_set.
First, double-check the output of phpinfo() to be sure this is the problem. If you find that magic quotes is enabled, you'll need somebody with access to the server to disable it in your php.ini or .htaccess file. The php manual explains the process here: http://www.php.net/manual/en/security.magicquotes.disabling.php
Do be careful with this, though: If there is code running on the server that relies on magic quotes, disabling it could leave those sites vulnerable to attacks like sql injection.
Comment: For those who cannot edit php.ini, try adding to .htaccess: php_flag magic_quotes_gpc off
Answer: You've obviously got some other escaping going on in your application before it hits the PDO layer. Look for addslashes or escape_string type method calls to see if you've got that going on.
What you're seeing is a sign of double escaping.


Using a JavaScript var in a link

Question: I found the JavaScript to break up the queryString of a page and pull a variable from it.  I needed to do this so that I could create a new link that would put the website into a facebook app I am trying.  Basically, we upload pages to our server which generates a long value (k).  So, the URL is always www.oursite.com/webhost/login.asp?k=12342342334 etc.
Here is what I have so far:
function querySt(ji) {
    hu = window.location.search.substring(1);
    gy = hu.split("&");
    for (i=0;i<gy.length;i++) {
        ft = gy[i].split("=");
        if (ft[0] == ji) {
            return ft[1];
        }
    }
    var SurveyKey = querySt("k");
    var url = "http://apps.facebook.com/appname/k=" + SurveyKey;
    window.location = url;
}

So, I have a var called "url" which should give the correct URL for what I need it to do (basically just sets the page in a facebook canvas).  I seem to be lost on how to make create a link for this.
It needs to be a button that someone clicks and it just opens a new window with the var url.  What am I missing here?  I tried
document.write="<a href="url...

but I can't reference that variable.
Answer: document.write="<a href="url...

… isn't valid syntax. If you want to use document.write to pass your url variable out to a web page as a link, you should do something like this:
document.write("YOUR LINK TEXT");

Answer: You can do this with jQuery:
$('#someDiv').append('click here');

Or without it:
document.getElementById('someDiv').innerHTML = 'click here';

Answer: You create a link in the page and hook up a javascript function to the click event on that link.  In the JS handler for the click event, you can run whatever Javascript code you want, construct the link you want, use window.open to open a new window with that link.
Using jQuery:
HTML:
Click here

JS:
$('#myLink').click(function() {
  alert('Handler for .click() called.');
});

jsfiddle here to see it in action or play with it: http://jsfiddle.net/jfriend00/AKuXG/
Or, if you can compute the desired link just once and set it forever, you can do that with this plain JS after the page has loaded:
document.getElementById("myLink").href = whatever javascript expression you want

Answer: Why not use PHP for it instead of Javascript? If you extract the variable from the URL in PHP you can just make the link:
<a href="www.oursite.com/webhost/login.asp?k=<?=$your_key?>">test

If you want to do it in javascript:
var url;
function querySt(ji) {
    hu = window.location.search.substring(1);
    gy = hu.split("&");
    for (i=0;i<gy.length;i++) {
        ft = gy[i].split("=");
        if (ft[0] == ji) {
            return ft[1];
        }
    }
    var SurveyKey = querySt("k");
    url = "http://apps.facebook.com/appname/k=" + SurveyKey;

    insertInPage();
}

function insertInPage() {
    var content = "link"
    document.write(content);
    // or:   document.getElementById("your_id").innerHtml = content;
}

Something along those lines at least.

Using a JavaScript var in a link


Interpretation of interaction b/w two dummy variables and purpose of it

Question: Suppose we have the model:

Y = a + bX + cZ

where X and Z both are dummy variables, and a, b & c are coefficients. What might be the purpose of adding an interaction term between both dummy variables (shown below)? Do you add it if you suspect or know that the dummy variables X and Z are correlated?
What is the interpretation of the interaction term if, let's say, d>0?

Y = a + bX + cZ + dXZ
Answer: Say that the average drop in glucose levels in blood when the patient takes vitamin Z is 10 mg/dL, so that when the random variable $I_\text{vitZ}=1$, the overall intercept drops 10 units. Now if you give that overly-advertised drug MegaFarmaXXX to patients, the drop with respect to the intercept if the indicator variable $I_\text{XXX}=1$ is a whooping 30 units. The amazing thing, though is that if both are present, where $I_\text{interaction}=I_\text{vitZ}\times I_\text{XXX}=1$, the drop is not 40 units, but rather 60 units because of the interaction between the vitamin supplement and the drug from the pharmacy- the interaction brings the intercept down 20 units.
If just one of the variables is continuous, there will be, instead a possible change in the estimated slope. The mathematical expression is:
$Y=\hat \beta_0+\hat \beta_1\,X_1+\hat\beta_2X_2+\hat \beta_3X_1\times X_2+\varepsilon$
So if we take my favorite dataset mtcars{datasets} in R, and we carry out the following regression:
(fit <- lm(mpg ~ wt * am, mtcars))

Call:
lm(formula = mpg ~ wt * am, data = mtcars)

Coefficients:
(Intercept)           wt           am        wt:am
     31.416       -3.786       14.878       -5.298

am, which dummy-codes for the type of transmission in the car am Transmission (0 = automatic, 1 = manual) will give us an intercept of 31.416 for manual (0), and 31.416 + 14.878 = 46.294 for automatic (1). The slope for weight is -3.786. And for the interaction, when am is 1 (automatic), the regression expression will have the added term, −5.298 ∗ 1 ∗ weight, which will add to −3.786 ∗ weight, resulting in a slope of −9.084∗weight. So we are changing the slope with the interaction.
But let me use the same dataset to actually illustrate your initial question about two categorical variables. Let's look at the effect on miles-per-gallon of automatic engines (as opposed to manual) - the variable am as above - and the effect of the a "V" shaped engine in the car (as opposed to a straight engine) - the variable vs, first without interaction:
> fit=lm(mpg ~ as.factor(am) + as.factor(vs), mtcars)
> fit

Call:
lm(formula = mpg ~ as.factor(am) + as.factor(vs), data = mtcars)

Coefficients:
   (Intercept)  as.factor(am)1  as.factor(vs)1
        14.594           6.067           6.929

Clearly, there is less gas consumption the fancier you get: you pay less at the pump with automatic transmission, and you pay even less if instead you splurge in a nice "V"-shaped engine.
But what if you get an automatic car with a "V"-shaped engine:
> fit2=lm(mpg ~ as.factor(am) *  as.factor(vs), mtcars)
> fit2

Call:
lm(formula = mpg ~ as.factor(am) * as.factor(vs), data = mtcars)

Coefficients:
                  (Intercept)                 as.factor(am)1
                       15.050                          4.700
               as.factor(vs)1  as.factor(am)1:as.factor(vs)1
                        5.693                          2.929

Now you can see that what actually happens is that part of the variability in the gas consumptions is "absorbed" be the interaction of enjoying both luxuries, which brings the mpg up. Notice that the initial explanation was oversimplified: in reality, the coefficients for the isolated variables change when the interaction is included, because that part of the variability that was included in the isolated variables is now included in the interaction term.


How to find out if lvm mirror write is asynchronous or synchronous?

Question: I am using redhat 5.8 with an lvm mirror, created with the following command:
 lvcreate -m1 --mirrorlog mirrored -n mirrorvol -L 10G myvg /dev/vdb /dev/vdc

I would like to know, when I write, do I need to wait the write is given to both devices, or just one?
From what i understood lvm mirror is synchronous:
[root@02srv004x9 ~]# dmsetup ls
mpath2  (253, 2)
foo (253, 3)
vgmirror-oracle_BD2_mirrorlogAvol   (253, 4)
VolGroup00-LogVol01 (253, 1)
VolGroup00-LogVol00 (253, 0)
vgmirror-oracle_BD2_mirrorlogAvol_mimage_1  (253, 6)
vgmirror-oracle_BD2_mirrorlogAvol_mimage_0  (253, 5)
dmsetup suspend /dev/mapper/vgmirror-oracle_BD2_mirrorlogAvol_mimage_1
Name:              vgmirror-oracle_BD2_mirrorlogAvol_mimage_1
State:             SUSPENDED
Read Ahead:        256
Tables present:    LIVE
Open count:        1
Event number:      0
Major, minor:      253, 6
Number of targets: 1
UUID: LVM-c8xfdstj4tTpfV3LSIYat0wbKXpfb7kDefFId05lIJR2QV1ws7CBfkbC0Oc813d9

Now I have a secondary image in suspend state, and I will try to mount the filesystem:
 mount /dev/mapper/vgmirror-oracle_BD2_mirrorlogAvol /mnt

Here the mount command locks, and remains in state D.
Answer: If you write, write will happen into the block cache in your ram. From there it will be synced out, when it is optimal.
If you do a sync command or an fsync() system call, it will write out the whole write cache. Next to that, the ext2-3-4 filesystems try to write the write cache nearly as often as it is possible, other filesystems have better heuristics.
Journaling filesystem also execute partial syncs regularly.
If a write happens to the mirrorvol, it will passed over two write operations to the logical sub-volumes on vdb and vdc. There is no guarantee they will be actually executed in the same time, except if somebody says them so (which can be periodic write cache sync, journaling or the ext2-3-4 filesystems wonderful sync feature).

Suspension is not for emulating errors in a LVM physical volume. Suspension is to do non-atomic changes which seems atomic for the actual users. During suspension, every command using the given logical volume, will be in D status, but it don't have to do anything with the write caching, it is an LVM feature.
If you want to emulate a hardware error in a mirrored LVM volume, you have to find alternative solutions. The first which I think working if you power off the physical hard disk with SMART.
Comment: if i use O_DIRECT to bypass the OS cache?
Comment: @c4f4t0r As I read here ( https://stackoverflow.com/questions/19440041/o-direct-vs-o-sync-on-linux-freebsd ) it will be probably ok.
Comment: if you look my last update, if i suspended the second image of the mirror, i cannot mount the fs.
Comment: @c4f4t0r O.k., I extended my answer too.
Comment: any idea how to make the mirroring asynchronous or how to throttle it down? the question is [here](http://unix.stackexchange.com/questions/306827/lvm-mirror-creates-high-load-from-time-to-time-how-to-lower-these-effects)
Comment: @AquariusPower It is asynchronous. How to trottle is down: give c3 io priority to the synchronizing kernel thread.


Telegram for Android, confusing NDK error

Question: So I have downloaded Telegram messenger source from GitHub, and I am trying to get it to run on Android Studio for the first time. Now the error is as below:
The build failed message is:

Error:error: CreateProcess: No such file or directory

The detailed log in Gradle Console is:

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':TMessagesProj:externalNativeBuildArmv7Debug'.

Build command failed.
  Error while executing process D:\AndroidStudio\sdk\ndk-bundle\ndk-build.cmd with arguments {NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=C:\TMessagesProj\jni\Android.mk NDK_APPLICATION_MK=C:\TMessagesProj\jni\Application.mk APP_ABI=armeabi-v7a NDK_ALL_ABIS=armeabi-v7a NDK_DEBUG=1 APP_PLATFORM=android-14 NDK_OUT=C:/TMessagesProj/build/intermediates/ndkBuild/armv7/debug/obj NDK_LIBS_OUT=C:\TMessagesProj\build\intermediates\ndkBuild\armv7\debug\lib NDK_APPLICATION_MK:=jni/Application.mk APP_PLATFORM:=android-14 C:/TMessagesProj/build/intermediates/ndkBuild/armv7/debug/obj/local/armeabi-v7a/libtmessages.26.so}
  [armeabi-v7a] SharedLibrary  : libtmessages.26.so
  arm-linux-androideabi-g++: error: CreateProcess: No such file or directory
  make: *** [C:/TMessagesProj/build/intermediates/ndkBuild/armv7/debug/obj/local/armeabi-v7a/libtmessages.26.so] Error 1

When I check the directory addressed in the log, I don't find a file named libtmessages.26.so. I don't know what is wrong. I don't know much about C++ and GCC so I appreciate any detailed helps.
Good to mention that prior to this error, I had a "redefinition in struct" error. When I focused, I found out there were repetitive definitions of two classes in two link.h files, one in the project and another in my sdk\ndk-bundle directory. So I commented the conflicts in link.h in my sdk, and I faced the above error. But weird was when I uncommented those parts, I expected to see the redefinition error again, but surprisingly nothing changed and I still got the above error.
Anyway, any help is appreciated. Thanks in advance.
Comment: Which version of NDK do you have? Try running **ndk-build** from command line: go to `C:\TMessagesProj` and run `D:\AndroidStudio\sdk\ndk-bundle\ndk-build.cmd APP_ABI=armeabi-v7a APP_PLATFORM=android-14`
Comment: It's latest version of NDK, which is 15th revision (r-15)
Comment: Try to explicitly set `ANDROID_DEPRECATED_HEADERS=true`. What does your command-line build say?
Comment: Thanks! where should I exactly put the line of code? If in Gradle, then where in Gradle?
Comment: Add it to the [**arguments** setting](https://github.com/DrKLO/Telegram/blob/master/TMessagesProj/build.gradle#L167) in **build.gardle**.
Comment: but have you tried command-line build?
Comment: Try moving your project to a shorter path. NDK will fail with same error if you have a long path for your project.
Comment: Yes, moving the project to a shorter path works for me. I am working in the windows environment. I suspect it's either the length of path or directory in the path with space or both that are causing the problem for windows.
Answer: Add below line at the first of your Android.mk file that is in JNI folder.
LOCAL_SHORT_COMMANDS := true

And then add following line at the first of your Application.mk file that is in JNI folder too.
APP_SHORT_COMMANDS := true

If this could not solved your problem and you have some errors yet, then try to use MULTIDEX in your build process. You can find many tutorials out there about how to enable it.


How to install reviewboard with nginx?

Question: Does anyone how to install reviewboard with nginx? It currently only has docs for apache and lighty.
Thanks
Comment: It's important to understand the server software you're using.  When you have an idea of how to construct virtualhosts in Nginx, the answer to this question will become clear.

Read the documentation for Nginx, and reviewboard, and read the Apache and Lighttpd instructions.  Then experiment, and see if you can get it right.
Answer: http://rramsden.ca/blog/2011/09/26/nginx-reviewboard/
I had issue with that setup, replaced "root" with "alias" and works fine for me.
Answer: This module is not compiled by default and must be specified using the
--with-http_stub_status_module
You can check your binary (packaged or not) with
<code>nginx -V
</code>
I would suggest doing something like this in your server config
<code> location /server-status {
      stub_status on;
      access_log off;
      allow 10.0.0.0/24;
      deny all;
    }
</code>
Hope this helps :D
Answer: ReviewBoard is a Django based application that can be used through WSGI. With nginx this usually means running ReviewBoard with an WSGI server (for example see here for a list), and proxying it with nginx.
You can find generic instructions about running a Django application behind nginx in the official documentation
Here, I found a gist with example configurations for running ReviewBoard with uwsgi e nginx.

How to install reviewboard with nginx?


Instalador reconhecido como vírus

Question: Olá, criei um programa em python 3.6 e criei o executável dele para Windows com Cx Freeze, depois criei um instalador para ele utilizando o Inno Setup 5.6.
Quando compartilhei com meus amigos para eles testarem, o windows impedia de abrir o instalador, dizendo q n era um programa reconhecido e poderia causar danos ao computador.
Como posso fazer meu programa se tornar reconhecido para o windows?
Comment: Provavelmente é porque o Windows não consegue garantir que a fonte do programa é segura através do certificado digital. Não entendo muito do processo, mas [nesse site](http://www.techracket.com/windows-cannot-access-the-specified-device-path-or-file/) tem um tutorial de como exportar e instalar a chave do seu computador em outros, tornando-o uma fonte confiável.
Answer: O seu vírus não foi reconhecido como vírus. Ele foi marcado como um programa de uma fonte não reconhecida pela Microsoft, o que é muito diferente.
Todo "menino do computador" sabe que parente leigo com acesso de administrador + Windows = ninho de malwares a procriar e evoluir. Tem sido assim desde o Windows 95, talvez até mais cedo. Em uma tentativa de limpar a reputação do Windows de sistema vulnerável e colocar a culpa no usuário, a Microsoft de vez em quando lança alguma iniciativa como o User Account Control, que é o que você viu.
Funciona assim: toda vez que o usuário tentar instalar ou executar algo que pode danificar o computador, ele dá um aviso: "olha, se você rodar essa coisa você pode me f... lascar, e a culpa vai ser só sua, viu?". Obviamente, o usuário dá a esse pequeno aviso o mesmo tratamento que costuma dar aos acordos de licença.
Então, você tem duas formas de lidar com isso:

Desativar o UAC: deixo a seu critério pesquisar como fazer isso. Infelizmente, é uma alteração que tem que ser feita máquina a máquina, localmente, e afeta não apenas a sua aplicação. Custoso e discutivelmente antiético.
Comprar uma licença do Authenticode e assinar digitalmente o seu aplicativo. Fica a seu critério também estudar o que é uma assinatura digital, e como ela garante a autenticidade do que é assinado dessa forma. Isso não garante que alguém não usará a assinatura em um vírus, mas é caro, burocrático e eles vão saber onde você mora.
Comment: Agora está pior ainda, porque além desse aviso, o windows 10 também exibe uma janela bonitinha ao melhor estilo "google" avisando que a aplicação não está na loja dela, portanto, não é possivel garantir segurança na instalação(quando é um aplicativo win32). Mesmo ignorando, essa janela aparece em seguida. Proteção adicional, pena que quase ninguem se importa com ela, mas depois que detona o sistema, a culpa é do "Rwindows" e não do *BIOS*.

Instalador reconhecido como vírus


How to configure snmp for snmp trap forwarding

Question: I have tried adding the following to snmpd.conf:
trapcommunity public
trapsink finalsnmptrapdestserver public

I thought this should allow traps to be recieved with the community string public
and send any traps to finalsnmptrapdestserver with community string public. But traps do not seem to make it to my final destination.
Answer: Apparently snmptrapd needs to be used.
I created /etc/snmp/snmptrapd.conf with the following contents. Its not secure in any way but it did what I was wanting, though the problem I was originally trying to solve was not fixed. So back to the drawing board for me. But for anyone else wanting to proxy snmp traps a simple config.
authCommunity net public
forward default finalsnmptrapdestserver public

This will accept traps for forwarding with the community string public and forward all traps to finalsnmptrapdestserver with community string public.


manually install npm packages?

Question: I'm experimenting with protractor and following tuturial on github. NPM was already present on my system, I succesfully downloaded protractor and now I'm proceeding with
webdriver-manager update

Which fails with
downloading http://selenium-release.storage.googleapis.com/2.42/selenium-server-standalone-2.42.2.jar...
Error: Got error Error: getaddrinfo ENOTFOUND from http://selenium-release.storage.googleapis.com/2.42/selenium-server-standalone-2.42.2.jar
Updating chromedriver
Error: Got error Error: getaddrinfo ENOTFOUND from https://chromedriver.storage.googleapis.com/2.10/chromedriver_win32.zip
downloading https://chromedriver.storage.googleapis.com/2.10/chromedriver_win32.zip...

Per earlier answered equal questions I double checked my npm proxy settings, all fine for http and https. Also I can see the username:password@proxy definition in .npmrc in my userprofile directory (c:/Users/my-name), the files are also present on the internet. Also the npm install action of protractor worked well. Now is it possible to manually (via browser download the relevant files and have them exploded and installed in the designated places?
I'm on windows 7 SP 1, 32 bit.
Answer: Yes you can manually install the webdriver-manager file in "node_modules\protractor\bin".
By the way , the error message really looks like you have a trouble to access internet.
Did you try to set these variables before launching your npm command:
set HTTP_PROXY=http://'your http proxy ip':'your proxy port'
set HTTPS_PROXY=http://'your https proxy ip':'your proxy port'
Comment: dr jerry , you replied yourself below with the answer I gave.I do not think this is a good behavior.Do you ?
Comment: Sorry did not notice I think. Referenced your answer.
Answer: To answer my own question:
As Yannick mentioned: I only set the proxy configuration with npm config ... For this you also need to set the environment variables
set PROXY=http://<username>:<password>@proxyserver
set HTTP_PROXY=%PROXY%
set HTTPS_PROXY=%PROXY%

manually install npm packages?


Prove the convergence of the sequence using the definition

Question: I started learning sequences today and my teacher made an introduction to sequences and convergence of sequences. Not long after the beginning of the class, the teacher wrote and explained the definition of the limit of a sequence:
$(a\in\mathbb{R})$ is the limit of a sequence if:
$$(\forall\epsilon>0)(\exists n_0\in\mathbb{N})(\forall n>n_0)|a_n-a|<\epsilon$$

I understand the definition, but, I don't quite understand the proof by the definition that some number is the limit of the sequence.

For example:
Show that $a=0$ is the limit of the sequence:
$$b_n=\frac{2n+4}{n^2+3n-1}$$
Here's what the teacher did:

If we go with the definition, then we have:
$$|b_n-0|=\Bigg|\frac{2n+4}{n^2+3n-1}\Bigg|=\frac{2n+4}{n^2+3n-1}$$
since $n\in\mathbb{N}$

then we have:
$$\frac{2n+4}{n^2+3n-1}=\frac{2(n+2)}{n(n+2)+n-1}\leq\frac{2(n+2)}{n(n+2)}=$$
$$=\frac{2}{n}<\epsilon$$
$$n>\frac{2}{\epsilon}$$
$$n_0=\bigg\lfloor{\frac{2}{\epsilon}}\bigg\rfloor$$
What bothers me is why we couldn't, for example, do this like this:
$$\frac{2n+4}{n^2+3n-1}=\frac{2(n+2)}{2(n+2)+n-1}\leq\frac{2(n+2)}{2(n+2)}$$
which leads us to something indefinite, I guess. (typo)

Or, let's look at this example (we have to prove that $c_n$ converges to $1$):
$c_n=\frac{3n^2+1}{3n^2+2n+1}$
$$|c_n-1|=\bigg|\frac{3n^2+1}{3n^2+2n+1}-1\bigg|=\bigg|\frac{-2n}{3n^2+2n+1}\bigg|=\frac{2n}{3n^2+2n+1}=$$
$$=\frac{2n}{2n(\frac{3n}{2}+1)+1}\leq\frac{2n}{2n(\frac{3n}{2}+1)}=\frac{2}{3n+2}<\frac{2}{3n}<\epsilon$$
$$3n>\frac{2}{\epsilon}$$
$$n>\frac{2}{3 \epsilon}$$
$$n_0=\bigg\lfloor{\frac{2}{3 \epsilon}}\bigg\rfloor$$

I did the second example, but I still don't understand the proof by definition.

Edit: I made some typos which made me not understand this. But, even though everything looks logical now, I'm still a bit confused by these proofs.
Comment: You have some typos in the steps. In the first example, the $2(n+2)$ in the denominator should be $n(n+2)$, then you wouldn't have that question. Your second example looks correct except that the $\epsilon$ should be in the denominator. So where did you not understand?
Comment: To prove that a sequence $a_n$ does _not_ converge to a given number $a$ you can find a particular $\epsilon$ such that $|a-a_n|>\epsilon$ for infinitely many values of $n$. For your $c_n$, $|c_n - 0|>\frac13$ for all $n > 0$, which is infinitely many, so $c_n$ does not converge to $0$. Of course, finding that $c_n$ converges to $1$ is also a perfectly good proof that it doesn't converge to $0$.
Comment: @KittyL Could you please post an answer where you try to prove by definition that the sequence $c_n$ converges to 0 and how you would come to a contradiction that it doesn't?
Comment: Maybe you didnt quite understand the definition. If you are given a sequence $cn$ which converges to $a$ then you need to find an $n_o$ so that for every $n>n_o$ $| c_n-a |$<$\epsilon$.
Answer: If I understand you correctly, you want an example to show that a sequence does not converge to a number, say, $a$, or to show that a sequence does not converge.
I will use the example $c_n=\cos(\pi n)$. We will show that it does not converge to $0$ as $n\rightarrow\infty$.
We pick $k=2,4,6,...$. Then the subsequence $|c_k-0|=1>\epsilon$ for any $0<\epsilon<1$. So the limit of $c_n$ is not $0$.
To show that it has no limit, we pick two subsequences, $k=2, 4, 6, ...$, $m=1, 3, 5, ...$. We see that the two subsequences $c_k$ and $c_m$ converge to $1$ and $-1$, respectively. So $c_n$ has no limit.