Proof that Integral over the arc vanishes as $R\rightarrow\infty$ in Inverse Mellin Transform of $\Gamma(s)$

Question: It´s a very well know result that $$e^{-x}=\frac{1}{2\pi i}\int_{\gamma-i\infty}^{\gamma+i\infty} \Gamma(s)x^{-s}ds$$
In order to solve this integral we have to close the contour to the left and show that the integral over this path vanishes as $R\rightarrow\infty$. Unfortunately it´s not obvious to me how to proof it.
 All textbooks that I came across assume that the integral goes to zero without any proof.
What I have tried so far is the following:
I assume that we are closing this contour with a semi circle to the left, and I get the following integral:
Let $s=Re^{i\theta}$ and $ds=iRe^{i\theta}d\theta$,
$$\int_{\frac{\pi}{2}}^{\frac{3\pi}{2}} \Gamma(Re^{i\theta})x^{-Re^{i\theta}}iRe^{i\theta}d\theta$$
Using Stirling´s approximation for the Gamma function we have
$$\Gamma(Re^{i\theta})\sim\sqrt{2\pi} e^{-Re^{i\theta}}(Re^{i\theta})^{Re^{i\theta}-\frac{1}{2}}$$
and $$\int_{\frac{\pi}{2}}^{\frac{3\pi}{2}} \Gamma(Re^{i\theta})x^{-Re^{i\theta}}iRe^{i\theta}d\theta\sim\ \sqrt{2\pi} iR \int_{\frac{\pi}{2}}^{\frac{3\pi}{2}} e^{-Re^{i\theta}}(Re^{i\theta})^{Re^{i\theta}-\frac{1}{2}}x^{-Re^{i\theta}}e^{i\theta}d\theta$$
I took the modulus of the last integral and arrived in the following expression:
$$\sim \sqrt{2 \pi} \int_{\frac{\pi}{2}}^{\frac{3\pi}{2}} e^{Rcos(\theta)(log(R)-log(x)-1)}e^{\frac{1}{2}log(R)}e^{-R \theta sin(\theta)}d\theta$$
But I don´t know how to evaluate the $\lim$ as $R \to \infty$
I really appreciate if someone could show this for me.
Thank you in advance.
Comment: i think your integration interval should be $[\pi/2,3 \pi/2]$ and everything is fine  (since this induces $\cos(\theta)<0$,which will supress the $e^{\log R R\cos(\theta)}$-like contributions). This also coincides with the standard choice $\exp(i\pi)=-1$. Or am I missing something?
Comment: good question (maybe i can have a closer look tomorrow) (+1) and a minor correction it hast to be $-1/2$
Comment: @tired thank you for your interest in my question and for the upvote. I look forward for your answer. And by the way, I have fixed the -1/2
Comment: I fixed the integration limits. Than $(Re^{i\theta})^{Re^{i\theta}-\frac{1}{2}}$ may not blow up as R goes to infinity because $cos(\theta)<0$ in this interval but the other terms do, $e^{-Re^{i\theta}}x^{-Re^{i\theta}}$
Comment: but they are $o(e^{c R\log(R)})$, so who cares.. ^^
Comment: Stirling's formula can be used only if $\left| \theta  \right| \le \pi  - \delta  < \pi$.
Comment: @Gary so, how do you prove this integral representation? Any hint?
Comment: Have a look at https://istavrovatlclark.files.wordpress.com/2016/01/cmplx-gammafunction-2016.pdf (pages 4-5).
Comment: @Gary, thank you for the link, but he does not show how the integrals of the ractangles vanishes as $R\rightarrow\infty$, he states "Based on the knowledge that Γ(s) is really small deep in the left half-plane, it can be shown that
the contour integral along the three sides of the rectangular path shown in the diagram all go to $R\rightarrow\infty$". I just can´t figure this out. I really appreciate if you can show me. Thank you!
zero as
Answer: Apply Jordan's lemma:
http://mathworld.wolfram.com/JordansLemma.html
We want to bound $$I_R = \int_{\frac{\pi}{2}}^{\frac{3\pi}{2}}\Gamma(s)x^{-s}ds, \quad \textrm{ where } s=Re^{i\theta}.$$
Let $p=\displaystyle \frac{s}{i}$,
then
$$I_R = i\int_{0}^{\pi}\Gamma(ip)x^{ip}dp, \quad \textrm{ where } p=Re^{i\theta}.$$
$$I_R \sim \sqrt{2\pi} \int_{0}^\pi  (ip)^{ip-\frac{1}{2} }\exp\left[1-ip\right]\exp[i (\ln x) p] \, dp = \int_0^\pi f(p) \exp[i(\ln x-1) p] \, dp$$
but, for $x>e, \ln x >1$ and $\lim_{R\rightarrow \infty} f(R e^{i\theta}) \rightarrow 0$, so by Jordan's lemma, $$I_R \rightarrow 0.$$
For $0<x<e$, we can make a change of variables to scale the original integral to guarantee that we can apply Jordan's lemma directly, so there too, the integral along the semicircular contour goes to zero.
In fact, the inverse Mellin transform is defined for $x \in (0,\infty)$.
Another point:  You have taken a contour to be a semicircle, but $\gamma$ is required to be greater than zero and we should show that the integrals along the segment connecting $iR$ to $\gamma+iR$ and connecting $-iR$ to $\gamma-iR$ also go to zero.  This shouldn't be difficult because most textbook treatments (see for example the link @Gary gave in the comments) use a rectangular contour that contains these.
Answer:
$\Gamma(\sigma+it)$ is the Fourier transform of $e^{-e^x+\sigma x}$ which is $L^1$ with $L^1$ second derivative, thus for $\sigma\in [1/2,3/2]$, $|\Gamma(\sigma+it)|\le \frac{A}{1+|t|^2}$ where $A$ is the $\sup$ of the mentioned $L^1$ norms.
$\Gamma(s+1)=s\Gamma(s)$ gives
$$|\Gamma(1/2-N+it)|\le 2\frac{|\Gamma(1/2+it)|}{|t|^N}$$
Both facts imply that $$\int_{[1/2-iN,1/2+iN]\cup [1/2-N\pm iN,1/2-N\pm iN]} |\Gamma(s)x^{-s}|d|s|\to 0 \text{ as }  N\to \infty$$
Since $\Gamma(s)$ is analytic away from the poles at negative integers then Cauchy's integral theorem implies that
$$\int_{|s| = N-1/2, \Re(s)<1/2} |\Gamma(s)x^{-s}|d|s|\to 0 \text{ as }  N\to \infty$$
And hence

$$\frac1{2i\pi}\int_{1/2-i\infty}^{1/2+i\infty}\Gamma(s)x^{-s}ds =  \sum_{k\ge 0} Res(\Gamma(s)x^{-s},k) = e^{-x}$$
Comment: Thank you for your answer. But how did you get the following inequality: $$|\Gamma(1/2-N+it)|\le 2\frac{|\Gamma(1/2+it)|}{|t|^N}$$
Answer: I finally got the answer!
The integrand  $$\sqrt{2 \pi} \int_{\frac{\pi}{2}}^{\frac{3\pi}{2}} e^{Rcos(\theta)(log(R)-log(x)-1)}e^{\frac{1}{2}log(R)}e^{-R \theta sin(\theta)}d\theta$$
could be rewritten as follows:
$$\sim \sqrt{\frac{2\pi}{R}} \int_{\frac{\pi}{2}}^{\frac{3\pi}{2}} e^{Rcos(\theta)(log(\frac{R}{ex})}e^{-R \theta sin(\theta)}d\theta$$
Now, if we choose $R>ex$ and note that for $\frac{\pi}{2}<\theta<\frac{3\pi}{2}$,  $\cos(\theta)<0$ and $\theta\sin(\theta)>0$, in the limit $\lim{R}\rightarrow\infty$   the  integrand goes to zero.


Reusing Smarty replace modifier in multiple templates

Question: I'm finding that I'm reusing the same replace modifier in multiple places around my Smarty template files to replace some non-alphanumeric characters.
An example:
<code>{markdown text=$star.description|replace:''':'’'|replace:''':'‘'|replace:'"':'“'|replace:'"':'”'|replace:' – ':' — '|replace:' — ':' — '|replace:'…':'…'|replace:'é':'é'}
</code>
Ideally, I should keep that list of replace phrases in one place and reference that whenever I need to, but I can't find the right way to do that in Smarty.
Answer: You can create a modifier in smarty so then you can call it this way (if i.e. you named it "cleantext"):
<code>{markdown text=$star.description|cleantext}
</code>
read more about creating your own modifiers at http://www.smarty.net/docsv2/en/plugins.modifiers.tpl
Comment: Okay, I see, that's helpful thanks. I wasn't sure which avenue to pursue.


Speed of different Linux distros - why the difference?

Question: I have a piece of multi-threaded software which runs at different speeds under the latest ubuntu server, redhat enterprise and CentOS - all installed on the exact same server for comparison.
Ubuntu server was slowest, followed by CentOS and then redhat enterprise. The difference was 10-20%.
The difference between centOS and redhat might be exaplined by a newer gcc version, but at least in the last two operating systems the same version of gcc was used.
What I could see in the ubuntu run is that although the program used, say, 13 cores, the total CPU reported by "top" was about 1220%, while on redhat (and centOS) it was 1300%
Does anybody have an explanation? I prefer to work with Ubuntu (it's free), but I cannot afford the slow-down. I tried other multithreaded benchmarks which seemed to also indicate that ubuntu is somewhat slower - on the same downloaded executable, not compiled locally.
Comment: Why am I being down-voted? Please explain
Comment: Just want to point out that CentOS is free as well. Have you looked into different system parameters across the different distros? sysctl -a for a list... compare and contrast.
Comment: I don't know why this has bee downvoted/closed, it is clearly a technical question asking for a technical answer! Looks like way too keen mods just reading the title to me.
Comment: +1, seems like a perfectly good question, can't understand why it was down-voted. Possibly because the title made it look like a recommendation question, which is off topic according to the [FAQ](http://serverfault.com/faq#dontask), although reading the question it is clear that this isn't a recommendation question.
Comment: Can you give us some specifics about the type of workload you're testing. Is this RAM heavy, processor heavy, I/O? An example of the type of work would help. I assume it is a compiled c/c++ program? Does it use external libraries? Did you install the same programs on the three different distros?
Answer: This isn't a conclusive answer, just some thoughts that are too long for a comment.

Have a try with atop rather than top. It provides a much better view of what's going on. I find the output of top to be very inconsistant these days as well. I have no explanation as to why, but I've seen the same behaviour you have with multiple cores.
Are these installs within VMWare by chance? I ran some benchmarks using various tools on 5 different VMs running 5 different distros: Ubuntu, CentOS, RHEL, SUSE and Debian. I got WILDLY differing results that didn't seem to correlate with anything I could find. The advise I received when I escalated this to Red Hat was that some distributions kernels are better optimised for VMWare than others. This was several years ago though so things may have changed.
Are you able to better describe the internal benchmark you're running in your app? This question could easily end up sitting between serverfault and stackoverflow...
Comment: no, clean install, i would not trust a virtual machine
Comment: The internal benchmark is a piece of optimization software i wrote, I can't say much about it, but it's just plain OMP-based multi-threading, nothing sophisticated in the multi-threaded implementation. I also tried intel's linkpack benchmark, which also seems to indicate a faster speed for redhat.
Comment: At your suggestion I looked at sysctl. There are differences, for example in kernel.sched_domain variables, but I do not understand what these differences mean. Could different distros be differently tweaked to improve performance, and if so, could I copy the tweak to the other distro?


HTML change in A drupal site

Question: it has been suggested to me to delete this code piece from my site's files:
<link rel="shortlink" href="http://www.panchers.co.il/node/1" />

The problem is I haven't found the file which stores it... my theme is Pixture-Reloaded. thanks for your help.
Comment: It's probably module-generated, and thus never stored in files (except for cache, possibly). But we can't tell you which one, without knowing what you have enabled.
Answer: The default shortlink for the page is added by node_page_view(), but if you have Metatag enabled, it will override the default behavior.
I usually tackle things like this in a hook_html_head_alter(), eg
function MYTHEME_html_head_alter(&$head_elements) {
  // get rid of shortlink from metatag module
  unset($head_elements['metatag_shortlink']);

  // find the default shortlink from core, and zap it
  foreach ($head_elements as $key => $elements) {
    if (strpos($key, 'drupal_add_html_head_link:shortlink') === 0) {
      unset($head_elements[$key]);
    }
  }
}

The tricky part is that the element name from core doesn't have a consistent name, so you need to loop through find the right one to remove.  If that doesn't remove it, then you need to dpm($head_elements) and figure out the proper element to remove.

HTML change in A drupal site


Replaced form AJAX not working

Question: I'm facing a problem with Ajax enabled forms, so this is the scenario.
I have 2 blocks, the first one has some buttons and the other one has a form ,constructed using the Form API.
When I click any of the buttons in the first block and AJAX Request is sent to the server, then in my callback function it replaces the second's block form data with new values,
for doing this I call the drupal_get_form function, so the code for the callback is more or less like this:
$form = drupal_get_form('panorama_info_form');
print render($form);

And the elements of the form have the following style:
//Text field for title
$form['panorama_titulo'] = array(
        '#type' => 'textfield',
        '#title' => t('Nombre del panorama'),
        '#default_value' => $panorama['titulo'],
        '#description' => t('Nombre del panorama'),
        '#size' => 40,
        '#maxlenght' => 120,
        '#required' => TRUE,
        '#prefix' => '
',
        '#suffix' => '
',
        '#ajax' => array(
          'callback' => 'panorama_info_form_callback',
          'wrapper' => 'panorama_titulo_div',
          'method'  => 'replace',
          'effect' => 'fade',),);

Now, in my jQuery Http 200 success function I replace the old form  with the response data like this:
function reload_element(data){
    $("#panorama-info-form").replaceWith(data);

}
where data is the rendered form.
This works, and I can see my form with the new default values that I declared, however after the form is replaced, ajax is no longer triggered by events. What I mean is that before I replaced the form with jQuery, it used to work, the value was sent to the server and the callback function declared for the textfield was in fact getting called. However after the replacement, no more ajax request...
Why is this happening??? I guess that's because there's some kind of script that uses the form's element's classes to attach functions dynamically to it... Maybe that could be one reason.
How could I fix this???
Thanks a lot.
Answer: You don't post the code performing the actual AJAX request, so I have to assume it's directly calling an URL returning just the rendered version of the textfield wrapper with id "panorama_titulo_div".
Since this is sort of side-stepping Drupal's own AJAX functionality (which operates on a per-form basis, initiated by the "#ajax" key being present on certain elements), you'll need to perform some steps manually.
First you need to tell elements in the form that they are about to be removed using Drupal.detachBehaviors($('#panorama_titulo_div').get(0), Drupal.settings, 'unload');
Then you replace the form like you already do.
Finally, you need to re-attach all the JavaScript behaviors since any script operating on the elements in the replaced form won't have any references to the new elements.
Drupal.attachBehaviors($('#panorama_titulo_div').get(0));
This is where Drupal would normally pass the settings received together with other commands returned from an AJAX operation. We don't have that here, and it's not that important since we're not adding/removing elements or otherwise alter the DOM structure and won't introduce any new scrips.
Just to be sure every behaviors works, Drupal calls Drupal.attachBehaviors() again with the entire form as the context argument. You may want to do that too if you notice some things aren't working. It's a safe operation since all behaviors are required to keep track of whether they're already attached or not (often done using jQuery's .once() method.
Comment: Very well written answer, friend. Welcome to DSO.
Comment: Thanks! I tried to be as clear as possible, but it's difficult without full code samples.
Comment: I just got here 8 years later to say that I love you! A million thanks, could not find a good answer anywhere.
Comment: @Lia No problem :) Wish I could have been a bit more detailed or precise in the response but hard to not risk being misleading when the original question doesn't include all context.

Replaced form AJAX not working


Is there a more efficient way to write this simple SQL query?

Question: Seems like a lot of redundancy here. Is there a more efficient way, or do the unions need to be used? Also the frist inner join is there because the players table does not have the hotel information and has to be retrieved from teams.
select players.name
from players
inner join teams
on players.team = teams.name
where teams.staysat = 'Ambassador'
and teams.checkin is not null
and teams.checkin < '18-AUG-07'
and teams.checkout > '18-AUG-07'
--
union all
select officials.name
from officials
where officials.staysat = 'Ambassador'
and officials.checkin is not null
and officials.checkin < '18-AUG-07'
and officials.checkout > '18-AUG-07'
--
union all
select fans.name
from fans
where fans.staysat = 'Ambassador'
and fans.checkin is not null
and fans.checkin < '18-AUG-07'
and fans.checkout > '18-AUG-07';

Answer: Yes, because you retrieve the data from different tables (players, fans, officials) the union is necessary here, I can only imagine you could shorten this if you would provide a function that pulls the desired information from a table which you would specify as a string, but that would lead to building querys out of strings with concatenation or other headachy stuff so maybe better stick with the union select ;)
Besides, if the tables do not differ in their other columns as well you might consider putting them all into one table and distinguish them over a flag or something like that.
Answer: You have the right way to do it. The unions and the inner join are necessary.
Answer: You can use sub query or view(prefered), like this:
select * from (
select players.name as name, teams.checkin as checkin, teams.checkout as checkount, teams.staysat as staysat
from players
inner join teams
on players.team = teams.name

union all
select officials.name as name, officials.checkin as checkin, officials.checkout as checkount, officials.staysat as staysat
from officials

union all

select fans.name as name, fans.checkin as checkin, fans.checkout as checkount, fans.staysat as staysat
from fans

) as t
where t.staysat = 'Ambassador'
and t.checkin is not null
and t.checkin < '18-AUG-07'
and t.checkout > '18-AUG-07';

And move outwardly conditions, but it may be more slowly but more simple


Is constructor a static method of a class?

Question: Hi I am new in JavaScript. I am wondering if the class constructor is a special class static method. I have such an example:

class warrior {
  constructor(firstName, lastName, age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
  }
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
  sayHello() {
    return `Hello my name is ${this.fullName}`;
  }
  static createWarrior(firstName, lastName, age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    return this;
  }
}

let warrior1 = new warrior("Ashley", "Yuna", 25);
warrior1.sayHello();
let warrior2 = warrior.createWarrior("Kris", "Snow", 23);
warrior2.sayHello();

If class constructor is a kind of static method, how can I modify createWarrior static method to be able to return warrior instance?
Comment: In `static` methods, `this` refers to the class itself, not to the instance. See [How does the "this" keyword work?](/q/3127429/4642212). Why not `static createWarrior(...args){ return new this(...args); }`?
Comment: Maybe tangential to the core of your question, but can you elaborate a bit on why using a standard `constructor` doesn't meet your requirements?
Comment: I don't see any real use case but I am only curious if it is ever possible?
Answer: You can accomplish this by using the static method to return a new instance of the class itself:

class warrior {
  constructor(firstName, lastName, age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
  }
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
  sayHello() {
    return `Hello my name is ${this.fullName}`;
  }
  static createWarrior(firstName, lastName, age) {
    return new this(firstName, lastName, age);
  }
}

let warrior1 = new warrior("Ashley", "Yuna", 25);
console.log(warrior1.sayHello());
let warrior2 = warrior.createWarrior("Kris", "Snow", 23);
console.log(warrior2.sayHello());


Não consigo estilizar e centralizar o texto do menu

Question: Boa tarde, estou colocando um menu fixo no meu blog, está é a imagem.

O texto ao lado do ícone home está sem estilo, como faço para estilizar esse texto deixando ele centralizado e com espaçamento entre eles, mudar a cor da fonte e colocar hover?
O código é esse.
/*---TOP FIXED MENIU BLOGGER --------------*/
#menu_fixo {
    width: 100%;
    height: 45px;
    background-color: #ffa233;
    border: 0px;
    border-bottom: solid 1px #333;
    padding: 0;
    margin: 0;
    position: fixed;
    z-index: 10;
}
#menu_fixo #centro {
    width: 880px;
    height: 45px;
    margin:0 auto;
    border: 0px;
    padding: 0;
    display: block;
    position:relative;
}
#menu_fixo #centro li {
    text-decoration: none;
    display: inline;
    float: left;
}
#icone_home {
    background-image: url(http://2.bp.blogspot.com/-LkHsu7cfje8/U1UpThxpECI/AAAAAAAAAPc/RMSpYE-raKs/s1600/home.png);
    background-repeat: no-repeat;
    background-position: center center;
    width: 40px;
    height: 45px;
    border-left: solid 1px #FFF;
    border-right: solid 1px #FFF;
    margin: 0px;
    padding: 0px;
}
#icone_home:hover{
    background: #000 url(http://2.bp.blogspot.com/-LkHsu7cfje8/U1UpThxpECI/AAAAAAAAAPc/RMSpYE-raKs/s1600/home.png)no-repeat center center;
}
#social_fixo {
    width: 180px;
    height: 45px;
    border: solid 0px #000;
    float: right;
    margin: 0;
    padding: 0;
    display: block;
    position: relative;
    top: 0px;
}
#icone_facebook {
    background-image: url(http://2.bp.blogspot.com/-kOAGPn3Ee_0/U1UpTrO8rLI/AAAAAAAAAPk/7cdUoKYU1W4/s1600/icon_facebook.png);
    background-repeat: no-repeat;
    background-position: top center;
    width: 45px;
    height: 45px;
    margin: 0px;
    padding: 0px;
}
#icone_twitter {
    background-image: url(http://4.bp.blogspot.com/-LyeRkpB716w/U1UpUunplPI/AAAAAAAAAP4/zki33yOb9B8/s1600/icon_twitter.png);
    background-repeat: no-repeat;
    background-position: top center;
    width: 45px;
    height: 45px;
    margin: 0px;
    padding: 0px;
}
#icone_gplus {
    background-image: url(http://2.bp.blogspot.com/-E7UGiWMmy-4/U1UpTteTpmI/AAAAAAAAAPg/COkFj9AycMM/s1600/icon_google+.png);
    background-repeat: no-repeat;
    background-position: top center;
    width: 45px;
    height: 45px;
    margin: 0px;
    padding: 0px;
}
#icone_youtube {
    background-image: url(http://2.bp.blogspot.com/-YJyJLW221zE/U1UpU1Uh2VI/AAAAAAAAAQA/Pi3e-kBwm0c/s1600/icon_youtube.png);
    background-repeat: no-repeat;
    background-position: top center;
    width: 45px;
    height: 45px;
    margin: 0px;
    padding: 0px;
}
#caixa-pesquisa {
    width: 400px;
    height: 35px;
    border: solid 1px #3f3f3f;
    margin: 0;
    padding: 0;
    background-color: #fff;
    display: table;
    margin-left: 200px;
    margin-top: 0px;
    float: none;
    position: relative;
    top: 5px;
}
.campo-pesquisa {
    width: 350px;
    height: 35px;
    border: 0px;
    margin: 0;
    padding: 0;
    margin-left: 5px;
    border-style: none;
    outline: none;
    font-family: arial;
    color: #5e5e5e;
}
.botao-pesquisa {
    border: solid 0px;
    background-image: url(http://3.bp.blogspot.com/-2CosUiZa8Qo/U1UpUa6ryYI/AAAAAAAAAP0/m-e14j6j0x4/s1600/icon_search.jpg);
    float: right;
    cursor: pointer;
    height: 35px;
    width: 35px;
}
button, html input[type="button"], input[type="reset"], input[type="submit"] {
    -webkit-appearance: button;
    cursor: pointer;
}

Código html:

Sobre

loja virtual

Contato

Se puder me ajudar eu agradeço.
Comment: Coloca o HTML para saber a classe que está sendo aplicada nele.
Comment: @ricardo não entendi pois eu não manjo muito de códigos.
Comment: Para mudar o CSS de alguma tag vc precisa alterar a classe do CSS que está sendo aplicada a essa tag, se fosse uma div seria assim . Então precisamos saber qual a classe está sendo aplicada a tag que você quer alterar
Comment: Estou colocando assim:

Sobre
loja virtual
Contato
Comment: Coloca isso lá na pergunta, da para formatar, so mandar editar a pergunta.
Comment: Pronto @ricardo obrigada!!!
Answer: Bom vamos lá.
Antes de centralizar o texto, vamos criar o espaçamento entre eles. Para isso você pode usar a propriedade padding, ela irá criar um espaço interno, ou seja, dentro um espaço dentro da própria li. O valor fica a seu critério, mas o código seria assim:
#menu_fixo #centro li {
    text-decoration: none;
    display: inline;
    float: left;

    /* - código adicionado - */
    padding: 0 10px 0 10px; //valores: cima - direita - baixo - esquerda
}

Para que o texto fique todo centralizado, horizontal e verticalmente, você pode usar tanto a propriedade text-align:center que irá centralizar horizontalmente, como a propriedade vertical-align:middle que, usando junto da propriedade line:height, irá centralizar ele verticalmente. Veja:
#menu_fixo #centro li {
    text-decoration: none;
    display: inline;
    float: left;
    padding: 0 10px 0 10px; //valores: cima - direita - baixo - esquerda

    /* - código adicionado - */
    height:45px; //valor da altura do seu menu;
    line-height:45px; //mesmo valor, para que mantenha dentro da div
    vertical-align:middle; //para centralizar verticalmente
    text-align:center; //para centralizar horizontalemnte
}

Agora, se você deseja um efeito de :hover, basta aplicar as propriedades dentro dele, da seguinte maneira:
#menu_fixo #centro li:hover {
    //Seu código de manipulação aqui
}

Veja este exemplo com o seu código já funcionando: http://jsfiddle.net/k5L0gk7z/1/


Multi step form with click and state logging in Drupal 7?

Question: I need to create two separate forms flows. Essentially the one case has 3 pages (intro, questions, thank you), while the other has 4 pages (intro, questions, questions, thank you). I want to be able to:

Log the states of each "step" as the user proceeds
Keep track of where the user clicks and in what sequence

I am thinking of doing the second part with Google Analytics, as I know it has ways to do this. However, I am not sure what is the best way to go with the multi step form process.
So far it sounds like I would have to create content types for each step and use rules to "guide" the user as he creates the different content types. However, this sounds like a nightmare when it comes to "back" and 'next" functions.
Can anyone please tell me what is the best way to implement a form like this, keeping in mind how important it is that the logging works perfectly.
Answer: I can't say that this is the best way, but you can achieve that using the Webform module.
You can create multi step form using Webform module. Add Page break type to form components to split the form.

In Advanced Form Settings you can manage the multi step form actions like 'Automatically save as draft between pages and when there are validation errors' options.

In you want to provide advanced navigation bar for multi step web from you can try the Webform steps module

This module provides a navigation bar for multi-page webforms. The navigation bar is a set of buttons placed at the top of each webform page. The buttons allow free navigation between steps that have already been visited.
Answer: From a sitebuilder's perspective, look at MSNF module with the Conditional Fields module. Doing this programmatically beats the hell out of anything else. Ctools Multipart, Multistep forms is the best that I have come across to do want you are looking for. Have a look at Paul Booker's tutorial for a starter.
Comment: I think you are right. I've ended up reverse engineering this: https://github.com/davidsonjames/drupal-7-multistep-form ...
Answer: I decided to follow copy and modify this solution. It allowed me to basically create a way by which I can just add a new "survey-2.php" file, which contains the brains of the various surveys I want to do. The ordering and persistence and all that stuff happens in the main module.
Answer: I've written a tutorial about how multi step forms in Drupal works. You can read the tutorial on http://brattland.no/blog/drupal/multistep-forms-in-drupal-7
Comment: Hi @sbrattla, access to the site is blocked, it has been a link only answer before (which would count as NAA), please take the content over here.


Ubuntu 12.04 as router with 2 nic

Question: I have been trying this setup for weeks and still can not make this to work...
ubuntu 12.04 64 bit with 2 nic
nic1: eth0:192.168.2.33 -static ip with internet access (connected to modem)
nic2: eth1:192.168.1.2 -static ip connected to LAN.
enabled ip_forward on ubuntu box net_ip_forward = 1
on the LAN with ip address 192.168.1.5 specified gateway as 192.168.1.2 and able to ping gateway.But can not ping public address.What am i missing?
on router box:
route -n

Destination     Gateway         Genmask         Flags Metric Ref    Use Iface

0.0.0.0         192.168.2.1     0.0.0.0         UG    100    0        0 eth0

192.168.1.0     0.0.0.0         255.255.255.0   U     0      0        0 eth1

192.168.2.0     0.0.0.0         255.255.255.0   U     0      0        0 eth0

tried
ip route add 192.168.2.0/24 via 192.168.1.2 dev eth0

route -n   on LAN 192.168.1.5
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface

0.0.0.0         192.168.1.2     0.0.0.0         UG    100    0        0 eth0

192.168.1.0     0.0.0.0         255.255.255.0   U     0      0        0 eth0

192.168.2.0     192.168.1.2     255.255.255.0   UG    0      0        0 eth0

iptables default policy is to accept all.
tracepath 22.214.171.124 from LAN
  1:  192.168.1.5                                           0.060ms pmtu 1500

  1:  192.168.1.2                                           3.367ms

  1:  192.168.1.2                                           3.764ms

   2:  no reply

Is there a way to make this work,other than NAT ing.
Answer: 192.168.2.1 is not a public address either. What box is that? Does it know how to route traffic back to 192.168.1.5? Does it do NAT for networks other than 192.168.2.0/24?
Comment: There's your problem then.
Comment: 192.168.2.1 is a D-link router connected to a modem.It doesnt know abot 192.168.1.0/24 network.
Comment: Can u please guide me with fixing this.When i used clear os.It worked with out much effort.All i did was specified 192.168.2.1 as external in the graphical mode.But with Ubuntu i am stuck./
Comment: It's not ubuntu that needs configuring, it's the d-link router.
Comment: x2 - your D-Link needs a static route to 192.168.1.0/24 via 192.168.2.33.  Make sure your D-Link also is set to NAT both subnets.

Ubuntu 12.04 as router with 2 nic


(C#) O Código não Salva as informações no array (tabela)?

Question: Eu tenho o código abaixo. O objetivo dele é verificar se já existe na tabela SalaReservada um agendamento no mesmo dia/hora/sala. Caso exista, eu verifico a próxima sala que eu trouxe codSala, e caso também já exista com essa sala, eu retorno true erroNaReserva. Caso só tenha reserva na primeira sala, e na segunda não, posso gravar nessa tabela SalaReservada, a reserva.
Erro: Minha tabela SalaReservada sempre fica vazia. Quando vou executar a primeira reserva, fala que gravou, mas na segunda, a posição 0 está vazia.
Pergunta: Esse modo de gravar está incorreto?
salasReservadas[x] = new SalaReservada { Codigo = codSala[j], DtEntrada = dataIniReuni, DtSaida = dataFimReuni, TempoPerm = tempoReuniao };

Código em C#.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ReservaSala
{
    class SalaReservada
    {
        private int codigo;
        private DateTime dtEntrada;
        private DateTime dtSaida;
        private int tempoPerm;

        public int Codigo { get => codigo; set => codigo = value; }
        public DateTime DtEntrada { get => dtEntrada; set => dtEntrada = value; }
        public DateTime DtSaida { get => dtSaida; set => dtSaida = value; }
        public int TempoPerm { get => tempoPerm; set => tempoPerm = value; }

        public SalaReservada[] salasReservadas = new SalaReservada[10];

        public bool VerificaReservaSala(int[] codSala, DateTime dataIniReuni, DateTime dataFimReuni, int tempoReuniao)
        {
            bool[] veriNaReserva = new bool[10];
            bool erroNaReserva = false;
            int horaFinalJaMarcada = 0;
            int horaInicialSerAgendada = 0;
            int j = 0;
            int i = 0;
            int x = 0;

            while (codSala[j] != 0)
            {
                while (salasReservadas[i] != null)
                {
                    if (codSala[j] == salasReservadas[i].codigo
                            && dataIniReuni.ToShortDateString() == salasReservadas[i].dtEntrada.ToShortDateString())
                    {
                        horaFinalJaMarcada = Convert.ToDateTime(salasReservadas[i].dtSaida.ToShortTimeString()).Hour;
                        horaInicialSerAgendada = Convert.ToDateTime(dataIniReuni.ToShortTimeString()).Hour;

                        if (horaInicialSerAgendada <= horaFinalJaMarcada)
                        {
                            veriNaReserva[i] = true;
                            break;
                        }
                    }
                    i = i + 1;
                }
                Console.WriteLine(" \n\n\t ******* Reserva ate o momento :" + erroNaReserva);

                j = j + 1;
            }

            for(x = 0; x < i; x++)
            {
                if (veriNaReserva[x])
                {
                    erroNaReserva = true;
                    break;
                }
            }
            if(!erroNaReserva)
                salasReservadas[x] = new SalaReservada { Codigo = codSala[j], DtEntrada = dataIniReuni, DtSaida = dataFimReuni, TempoPerm = tempoReuniao };

            return erroNaReserva;
        }

    }
}

//-----------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ReservaSala
{
    class Program
    {
        static void Main(string[] args)
        {
            ValidDadosEntrada dadosRecebidos = new ValidDadosEntrada();
            SalasParaReserva verificaReserva = new SalasParaReserva();
            SalaReservada salasReservadas = new SalaReservada();
            int codValidaDadosEntrada = 0;
            string dtIniString = null;
            string dtFimString = null;
            string axSair = null;
            string axInternet = "N";
            string axTv = "N";
            string axWebcam = "N";
            string axLugares = null;
            string axComputador = "N";
            const int V = 12;
            int[] codSala;
            codSala = new int[V];
            bool reservaNok = false;

            do
            {
                dtIniString = null;
                dtFimString = null;
                axSair = null;
                axInternet = "N";
                axTv = "N";
                axWebcam = "N";
                axLugares = null;
                axComputador = "N";

                Console.Title = "Reservas de Sala para Reunião";

                //______________________________________________________________________Valida Data Inicial
                do
                {
                    codValidaDadosEntrada = 0;
                    Console.Clear();
                    Console.WriteLine("\n\n\tVAMOS EFETUAR A RESERVA DA SALA ");
                    Console.Write("\n\tDigite a Data do Inicio Reunião e a Hora (dd/mm/yyyy 00:00:00): ");
                    dtIniString = Console.ReadLine();

                    codValidaDadosEntrada = dadosRecebidos.validaInformacoesEntrada(dtIniString, dtFimString);

                    switch (codValidaDadosEntrada)
                    {
                        case 1:
                            Console.Clear();
                            Console.WriteLine("\n\t ***Favor verificar se a data é Válida e seu Formato!***");
                            Console.ReadLine();
                            break;
                        case 2:
                            Console.Clear();
                            Console.WriteLine("\n\t ***As reuniões devem ser agendadas com no mínimo um dia de antecedência!***");
                            Console.ReadLine();
                            break;
                        case 3:
                            Console.Clear();
                            Console.WriteLine("\n\t ***As reuniões devem ser agendadas com no máximo 40 dia de antecedência!***");
                            Console.ReadLine();
                            break;
                        case 4:
                            Console.Clear();
                            Console.WriteLine("\n\t ***As reuniões devem ser agendadas apenas para os dias úteis!***");
                            Console.ReadLine();
                            break;
                    }
                } while (codValidaDadosEntrada != 0);

                //______________________________________________________________________Valida Data Final
                do
                {
                    codValidaDadosEntrada = 0;
                    Console.Clear();
                    Console.WriteLine("\n\n\tVAMOS EFETUAR A RESERVA DA SALA ");
                    Console.WriteLine("\n\tInicio da Reunião: " + dadosRecebidos.DataIni);
                    Console.Write("\n\tDigite a Data do Fim da Reunião e a Hora (dd/mm/yyyy 00:00:00): ");
                    dtFimString = Console.ReadLine();

                    codValidaDadosEntrada = dadosRecebidos.validaInformacoesEntrada(dtIniString, dtFimString);

                    switch (codValidaDadosEntrada)
                    {
                        case 1:
                            Console.Clear();
                            Console.WriteLine("\n\t ***Favor verificar se a data é Válida e seu Formato!***");
                            Console.ReadLine();
                            break;
                        case 5:
                            Console.Clear();
                            Console.WriteLine("\n\t ***A data/hora do Fim da Reunião deve ser maior que a do Inicio!***");
                            Console.ReadLine();
                            break;
                        case 6:
                            Console.Clear();
                            Console.WriteLine("\n\t ***Reuniões não podem durar mais que 8 horas!***");
                            Console.ReadLine();
                            break;
                    }
                } while (codValidaDadosEntrada != 0);

                //______________________________________________________________________Valida informações da sala

                do
                {
                    codValidaDadosEntrada = 0;
                    Console.Clear();
                    Console.WriteLine("\n\n\tVAMOS EFETUAR A RESERVA DA SALA ");
                    Console.WriteLine("\n\tInicio da Reunião: " + dadosRecebidos.DataIni);
                    Console.WriteLine("\n\tFim da Reunião: " + dadosRecebidos.DataFim);
                    Console.WriteLine("\n\tTempo de Reunião: " + dadosRecebidos.TempoReuniao);
                    Console.Write("\n\tPRecisa de Quantos Lugares na Sala: ");
                    axLugares = Console.ReadLine();
                    Console.Write("\n\tPRecisa de Internet (S/N): ");
                    axInternet = Console.ReadLine();
                    Console.Write("\n\tPRecisa de Computador (S/N): ");
                    axComputador = Console.ReadLine();
                    Console.Write("\n\tPRecisa de TV (S/N): ");
                    axTv = Console.ReadLine();
                    Console.Write("\n\tPRecisa de Webcam (S/N): ");
                    axWebcam = Console.ReadLine();

                    codValidaDadosEntrada = dadosRecebidos.verificaInformacoesSala(axLugares, axInternet, axComputador, axTv, axWebcam);

                    if (codValidaDadosEntrada == 7)
                    {
                        Console.Clear();
                        Console.WriteLine("\n\t ***Você digitou informações inválidas!***");
                        Console.ReadLine();
                    }

                } while (codValidaDadosEntrada != 0);

                codSala = verificaReserva.Reservar(dadosRecebidos.LugaresReserva, dadosRecebidos.InternetReserva, dadosRecebidos.ComputadorReserva, dadosRecebidos.TvReserva, dadosRecebidos.WebcamReserva);

                Console.WriteLine("\n\n Sugestão de Salas ");
                codSala.ToList().ForEach(i => Console.WriteLine(i.ToString()));
                Console.ReadLine();

                if (codSala != null)
                {
                    reservaNok = salasReservadas.VerificaReservaSala(codSala, dadosRecebidos.DataIni, dadosRecebidos.DataFim, dadosRecebidos.TempoReuniao);

                    if (reservaNok)
                        Console.WriteLine("\n\tSua Reserva Não pode ser Feita, pois não há salas Disponíveis Nesse Dia/Hora");
                    else
                        Console.WriteLine("\n\tSua Reserva Foi Realizada Com Sucesso");
                }
                else
                    Console.WriteLine("\n\tSua Reserva Não pode ser Feita, pois não há salas que atendam seus critérios.");

                Console.Write("\n\tPara sair informe 'S', ou para reservar mais 'enter': ");
                axSair = Console.ReadLine();
                Console.ReadKey();

            } while (axSair != "s");
        }//Main
    } //Program
}// ReservaSala

//-------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ReservaSala
{
    class Sala
    {
        private int codigo;
        private int lugares;
        private bool internet;
        private bool computador;
        private bool tv;
        private bool webcam;

        public int Codigo { get => codigo; set => codigo = value; }
        public int Lugares { get => lugares; set => lugares = value; }
        public bool Internet { get => internet; set => internet = value; }
        public bool Tv { get => tv; set => tv = value; }
        public bool Webcam { get => webcam; set => webcam = value; }
        public bool Computador { get => computador; set => computador = value; }
    }
}

//------------------------------------------------
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace ReservaSala
{
    class ValidDadosEntrada
    {
        private DateTime dataIni;
        private DateTime dataFim;
        private int lugaresReserva;
        private bool internetReserva;
        private bool computadorReserva;
        private bool tvReserva;
        private bool webcamReserva;
        private int tempoReuniao;

        public int LugaresReserva { get => lugaresReserva; set => lugaresReserva = value; }
        public bool InternetReserva { get => internetReserva; set => internetReserva = value; }
        public bool ComputadorReserva { get => computadorReserva; set => computadorReserva = value; }
        public bool TvReserva { get => tvReserva; set => tvReserva = value; }
        public bool WebcamReserva { get => webcamReserva; set => webcamReserva = value; }
        public DateTime DataIni { get => dataIni; set => dataIni = value; }
        public DateTime DataFim { get => dataFim; set => dataFim = value; }
        public int TempoReuniao { get => tempoReuniao; set => tempoReuniao = value; }

        public int validaInformacoesEntrada(string dtIniString, string dtFimString)
        {

            bool dataOk = false;
            bool dadosOk = false;
            int codRetorno = 0;
            string diaSemana = null;
            //Feriados_Nacionais objFeriado = new Feriados_Nacionais();

            if (dtFimString == " " || dtFimString == null)
            {

                dataOk = verificaFormatoData(dtIniString); // Valida formato de Data e Hora
                if (dataOk)
                {
                    this.DataIni = Convert.ToDateTime(dtIniString);
                    dadosOk = verificaDiaAnterior(); // Valida dados Recebidos para Efetuar a reserva

                    if (dadosOk)
                    {
                        dadosOk = verificaDiaApos(); // Valida dados Recebidos para Efetuar a reserva
                        if (dadosOk)
                        {
                            diaSemana = DataIni.DayOfWeek.ToString();
                            if (diaSemana == "Saturday" || diaSemana == "Sunday")
                            {
                                codRetorno = 4;
                            }
                        }
                        else
                            codRetorno = 3;
                    }
                    else
                        codRetorno = 2;
                }
                else
                    codRetorno = 1;
            }
            else //_______________________________________________ Valida data Fim
            {

                dataOk = verificaFormatoData(dtFimString); // Valida formato de Data e Hora
                if (dataOk)
                {
                    this.DataFim = Convert.ToDateTime(dtFimString);
                    dadosOk = verificaDataFim();
                    if (dadosOk)
                    {
                        dadosOk = verificaTempoReuniao();
                        if (!dadosOk)
                            codRetorno = 6;
                    }
                    else
                        codRetorno = 5;
                }
                else
                    codRetorno = 1;
            }
            return codRetorno;
        }

        public bool verificaDiaAnterior()
        {
            DateTime dataAtual = DateTime.Now;
            bool solicitacaoOk = false;
            int result = DateTime.Compare(this.DataIni, dataAtual);

            if (result > 0)
                solicitacaoOk = true;

            return solicitacaoOk;
        }

        public bool verificaDiaApos()
        {
            DateTime dataAtual = DateTime.Now;
            bool solicitacaoOk = false;
            TimeSpan diferenca = this.DataIni.Subtract(dataAtual);
            int diferencaDias = diferenca.Days;

            if (diferencaDias < 40)
                solicitacaoOk = true;

            return solicitacaoOk;
        }

        public bool verificaFormatoData(string dataHora)
        {
            bool dataOk = false;
            DateTime dataValida;
            Regex r = new Regex(@"(\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}:\d{2})");
            dataOk = r.Match(dataHora).Success;
            if (dataOk)
            {
                if (!DateTime.TryParse(dataHora, out dataValida))
                    dataOk = false;
            }
            return dataOk;
        }

        public bool verificaDataFim()
        {
            bool tempoOk = false;
            if (this.DataFim > this.DataIni)
                tempoOk = true;

            return tempoOk;
        }

        public bool verificaTempoReuniao()
        {
            bool tempoOk = false;
            TimeSpan tempoOitoHoras = TimeSpan.Parse("08:00:00");
            TimeSpan diferenca = this.DataIni.Subtract(this.DataFim);

            int diferencaDias = diferenca.Hours;
            diferencaDias = Math.Abs(diferencaDias);
            int totalMaximoHoras = tempoOitoHoras.Hours;
            TempoReuniao = diferencaDias;

            if (diferencaDias <= totalMaximoHoras)
                tempoOk = true;

            return tempoOk;
        }

        public int verificaInformacoesSala(string axLugares, string axInternet, string axComputador, string axTv, string axWebcam)
        {
            int codigoRetorno = 0;
            axInternet = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(axInternet);
            axTv = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(axTv);
            axWebcam = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(axWebcam);
            axComputador = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(axComputador);

            try
            {
                lugaresReserva = Convert.ToInt32(axLugares);
            }
            catch (FormatException)
            {
                codigoRetorno = 7;
            }

            if (codigoRetorno == 0)
            {
                switch (axInternet)
                {
                    case "N":
                        internetReserva = false;
                        break;
                    case "S":
                        internetReserva = true;
                        break;
                    default:
                        codigoRetorno = 7;
                        break;
                }
            }

            if (codigoRetorno == 0)
            {
                switch (axComputador)
                {
                    case "N":
                        ComputadorReserva = false;
                        break;
                    case "S":
                        ComputadorReserva = true;
                        break;
                    default:
                        codigoRetorno = 7;
                        break;
                }
            }

            if (codigoRetorno == 0)
            {
                switch (axTv)
                {
                    case "N":
                        tvReserva = false;
                        break;
                    case "S":
                        tvReserva = true;
                        break;
                    default:
                        codigoRetorno = 7;
                        break;
                }
            }

            if (codigoRetorno == 0)
            {
                switch (axWebcam)
                {
                    case "N":
                        webcamReserva = false;
                        break;
                    case "S":
                        webcamReserva = true;
                        break;
                    default:
                        codigoRetorno = 7;
                        break;
                }
            }

            return codigoRetorno;
        }
    }
}

// ---------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ReservaSala
{
    class SalasParaReserva
    {
        public List<Sala> salas = new List<Sala>();

        public SalasParaReserva()
        {
            salas[0] = new Sala { Codigo = 1, Lugares = 10, Internet = true, Computador = true, Tv = true, Webcam = true };
            salas[1] = new Sala { Codigo = 2, Lugares = 10, Internet = true, Computador = true, Tv = true, Webcam = true };
            salas[2] = new Sala { Codigo = 3, Lugares = 10, Internet = true, Computador = true, Tv = true, Webcam = true };
            salas[3] = new Sala { Codigo = 4, Lugares = 10, Internet = true, Computador = true, Tv = true, Webcam = true };
            salas[4] = new Sala { Codigo = 5, Lugares = 10, Internet = true, Computador = true, Tv = true, Webcam = true };
            salas[5] = new Sala { Codigo = 6, Lugares = 10, Internet = true, Computador = false, Tv = false, Webcam = false };
            salas[6] = new Sala { Codigo = 7, Lugares = 10, Internet = true, Computador = false, Tv = false, Webcam = false };
            salas[7] = new Sala { Codigo = 8, Lugares = 3, Internet = true, Computador = true, Tv = true, Webcam = true };
            salas[8] = new Sala { Codigo = 9, Lugares = 3, Internet = true, Computador = true, Tv = true, Webcam = true };
            salas[9] = new Sala { Codigo = 10, Lugares = 3, Internet = true, Computador = true, Tv = true, Webcam = true };
            salas[10] = new Sala { Codigo = 11, Lugares = 20, Internet = false, Computador = false, Tv = false, Webcam = false };
            salas[11] = new Sala { Codigo = 12, Lugares = 20, Internet = false, Computador = false, Tv = false, Webcam = false };
        }

        public int[] Reservar(int axlugares, bool axInternet, bool axComputador, bool axTv, bool axWebcam)
        {
            int[] axCodigo = new int[12];
            int x = 0;
            bool axControle = false;
            bool axControleI = false;
            bool axControleC = false;
            bool axControleT = false;
            bool axControleW = false;

            for (int i = 0; i < 12; i++)
            {
                axControle = false;
                axControleI = false;
                axControleC = false;
                axControleT = false;
                axControleW = false;

                if (!axInternet && !axComputador && !axTv && !axWebcam)
                    axControle = true;

                if (salas[i].Internet && axInternet)
                    axControleI = true;

                if (salas[i].Computador && axComputador)
                    axControleC = true;

                if (salas[i].Tv && axTv)
                    axControleT = true;

                if (salas[i].Webcam && axWebcam)
                    axControleW = true;

                if (axControle || axControleI && axControleC && axControleT && axControleW) {
                    if (salas[i].Lugares >= axlugares)
                    {
                        axCodigo[x] = salas[i].Codigo;
                        x = x + 1;
                    }
                }

            }
            return axCodigo;
        }
    }
}

Comment: Você nao está salvando na tabela só de instanciar um novo objeto nesse código do new SalaReservada, vc tem que pegar esse novo objeto criado e inserir no seu contexto e salvar o mesmo
Comment: @AugustoVasques coloquei na pergunta, o código que recebo as informações do usuário, e chamo para verificar se a reserva pode ou não ser realizada.
Comment: @AugustoVasques Incluí todo o código (classes) do programa.
Comment: Cadê a parte do código que faz a reserva? Pergunto pois pode ser nele que se encontra o erro.
Comment: if(!erroNaReserva)
                salasReservadas[x] = new SalaReservada { Codigo = codSala[j], DtEntrada = dataIniReuni, DtSaida = dataFimReuni, TempoPerm = tempoReuniao }; // Será feito nesse trecho do código, somente após a verificação se já existe a reserva ou não.
Comment: @RebecaNonato Esse `if(!erroNaReserva) salasReservadas[x] = ...` é o código de verificação se a reserva. Eu quero o código que preenche as reservas.
Comment: @JoãoPauloAmorim O "salvar" é somente guardar as informações na tabela. Pois nesse código eu não uso BD, somente é online, o usuário durante a mesma execução, irá chamar o reserva quantas vezes quiser. E assim que ele chama, eu teria que "guardar" as informações em uma tabela online.
Comment: Entendi, o código está bem extenso com esse tanto de arrays, você nao pode transformar isso em listas? assim fica bem mais legivel, mais facil a verificação e mais facil de vc popular também esses caras.
Comment: Essas duas linhas
`ValidDadosEntrada dadosRecebidos = new ValidDadosEntrada();`
`SalasParaReserva verificaReserva = new SalasParaReserva();`
possuem referencia as classes `ValidDadosEntrada` e `SalasParaReserva`sem essas classes não consigo executar seu código.
Answer: O problema é que a instância salas é do tipo List<Sala> e estava sendo populada como se fosse uma instância do vetorSala[].
Existem duas soluções para esse problema.
A primeira solução consiste em modificar o tipo salas de uma instância de List<Sala> para uma instancia de vetorSala[]:
//É só alterar a classe de salas de List<Sala> para Sala[]
public Sala[] salas = new Sala[12];

A segunda solução, um pouco mais trabalhosa, é popular o List<Sala> usando o método List<T>.Add(T):
 public List<Sala> salas = new List<Sala>();

        public SalasParaReserva()
        {
            salas.Add(new Sala { Codigo = 1, Lugares = 10, Internet = true, Computador = true, Tv = true, Webcam = true });
            salas.Add(new Sala { Codigo = 2, Lugares = 10, Internet = true, Computador = true, Tv = true, Webcam = true });
            salas.Add(new Sala { Codigo = 3, Lugares = 10, Internet = true, Computador = true, Tv = true, Webcam = true });
            salas.Add(new Sala { Codigo = 4, Lugares = 10, Internet = true, Computador = true, Tv = true, Webcam = true });
            salas.Add(new Sala { Codigo = 5, Lugares = 10, Internet = true, Computador = true, Tv = true, Webcam = true });
            salas.Add(new Sala { Codigo = 6, Lugares = 10, Internet = true, Computador = false, Tv = false, Webcam = false });
            salas.Add(new Sala { Codigo = 7, Lugares = 10, Internet = true, Computador = false, Tv = false, Webcam = false });
            salas.Add(new Sala { Codigo = 8, Lugares = 3, Internet = true, Computador = true, Tv = true, Webcam = true });
            salas.Add(new Sala { Codigo = 9, Lugares = 3, Internet = true, Computador = true, Tv = true, Webcam = true });
            salas.Add(new Sala { Codigo = 10, Lugares = 3, Internet = true, Computador = true, Tv = true, Webcam = true });
            salas.Add(new Sala { Codigo = 11, Lugares = 20, Internet = false, Computador = false, Tv = false, Webcam = false });
            salas.Add(new Sala { Codigo = 12, Lugares = 20, Internet = false, Computador = false, Tv = false, Webcam = false });
        }


XML elements not created

Question: Im new with lionq to XML and a little rusty with it. I am trying to create the below XML and save it as HTML
<?xml version="1.0" encoding="UTF-8"?>
<customers>
<start>today</start>
<end>next week</end>
<Date>Some date</Date>
<customer>
....
.....
</customer>
</customers>

So far my code is
Dim XD As XDocument = <?xml version="1.0" encoding="UTF-8"><Customers></Customers>

For each c in mycustomers
MyXDocument.Root.Add(<Customer>.....</Customer>
Next

It gets the data and then creates the XML as required and saves it - this all works fine however i cant work out how to get these lines
<start>today</start>
<end>next week</end>
<Date>Some date</Date>

to be included in the XML with my code. I seem to be getting end tags mixed up or its just not happening. Could anyone advise?
Comment: I don't understand where the problem is. Can you explain it in a better way?
Answer: Just add the elements to your XML literal:
Dim XD As XDocument = <?xml version="1.0" encoding="UTF-8"?>
                      <Customers>
                          <start>today</start>
                          <end>next week</end>
                          <Date>Some date</Date>
                       </Customers>

Note: you're missing a ? in your XML literal's XML declaration

When running
For each c in Enumerable.Range(0, 5)
    XD.Root.Add(<Customer><%= c %></Customer>)
Next

the XML looks like
<Customers>
  <start>today</start>
  <end>next week</end>
  <Date>Some date</Date>
  <Customer>0</Customer>
  <Customer>1</Customer>
  <Customer>2</Customer>
  <Customer>3</Customer>
  <Customer>4</Customer>
</Customers>

Also note that first you use XD and later MyXDocument
Answer: You could use an XmlTextWriter in the following way:
  Dim xwriter As New XmlTextWriter(XmlFilePath, Encoding.UTF8)
        xwriter.WriteStartDocument()
        xwriter.WriteStartElement("customers")

        xwriter.WriteStartElement("start")
        xwriter.WriteString("today")
        xwriter.WriteEndElement()

        xwriter.WriteStartElement("end")
        xwriter.WriteString("next week")
        xwriter.WriteEndElement()

        xwriter.WriteStartElement("date")
        xwriter.WriteString("some date")
        xwriter.WriteEndElement()

        xwriter.WriteEndElement()
        xwriter.WriteEndDocument()
        xwriter.Close()

Not tested this - but you get the idea

XML elements not created


Should folds in k-fold CV actually be representative?

Question: I have read somewhere that the k of the k-fold CV should be picked in such a manner as to have representative validation sets (folds). This seems to me to be contradictory since the leave-one-out CV has only one sample as a fold, which clearly can't be representative of the dataset (I refer to one fold only, the whole process is perfectly fine as it is averaged). Furthermore, LOOCV is less biased than the k-fold CV due to it practically using the whole dataset for model fitting, albeit more expensive computationally. Of course, a smaller fold usually also implies a larger variance in the error, but this does not seem relevant in this instance.
Should each fold actually be representative?
Comment: You got that wrong, LOOCV trains on all except one unit, and tests on the left out unit, so LOOCV is very representative (for training the model, which is what the main concern is, prediction will be done by all the other similarly trained models and should reflect the final model predictions).
Comment: Could you refer to a place where you have read that the folds need to be 'representative'.
Comment: @bob_cart stratified CV is indeed a good example of requiring a 'representative' fold (not really requiring but it will be more efficient). But this is more about picking the folds than about picking the number $k$. Possibly they are referring to problems that might occur when data is correlated. In such case LOOCV might not work so well because training data is correlated with your test data (the left out data point is not a good representation of an independent piece of data). In such a case you probably want a larger piece/fold of data to be left out.
Comment: What do you mean by representative? That each fold should have similarly distributed data? If so then this is usually a good idea. You may also be interested in stratified CV.
Comment: A classic dataset has mobile phone accelerometer data with the aim of predicting whether somebody is sitting, standing, walking up, walking down or walking level, with many readings for several individuals.  If the aim is to make good predictions for future users rather than for existing users, there is an argument this is best done in the train-validate-test paradigm by putting all the data for some individuals in the test set, and the CV folds to be individuals, rather than other representative selections of the observations.  You might say this approach is not representative of all the data
Comment: @bob_cart but LOOCV is done with n different folds which makes it representative right? One uses an average over the k folds. It is the k folds as a whole that need to be representative and single fold doesn't need to be.
Comment: @SextusEmpiricus Yeah, I agree with your comment about LOOCV. I read it [here](https://machinelearningmastery.com/k-fold-cross-validation/) (the 'configuration of k' section). I think I've read it in other places as well, but I could be wrong and I could've misinterpreted the link I sent. That's why I posted the question, to get my facts straight. Maybe the author was referring to the training set, and the validation (test) set in terms of unbalanced datasets and the stratified CV?
Comment: Yes, representative of the underlying distribution. Similarly distributed to the rest of the dataset, in more practical terms. Why is it usually a good idea and at the same time LOOCV works fine, and it clearly doesn't have a representative fold (it's just one sample)? Stratified CV seems to be more concerned with unbalanced classification problems and does not seem to address my question, at least I think so.
Comment: My question is why should one fold/subsample (which is the validation set in one iteration of k-fold CV) be representative, not why the training set should be representative: that part is quite clear. I understand how LOOCV works.
Comment: "Of course, a larger fold usually implies a smaller variance in the error, but this doesn't seem relevant in most cases."—Why not, though? When one has to consider costs (like time or computational budget), the standard CV becomes more attractive because of the lower variance. You can't do LOOCV with all data points in a 3 million sample, billion-parameter machine translation model, for instance.
Comment: @AryaMcCarthy You're right and I agree with you. My wording could have been better, I wanted to say that it does not seem to be relevant when assessing models for the purpose of model selection, given that we have the resources to actually perform LOOCV. However, this is not my main point. What I am interested in is why should a fold be representative in k-fold CV if we are averaging the fold scores anyway, a demonstration of which is precisely the LOOCV (which clearly doesn't have representative folds).
Comment: @Henry I see, this is an interesting argument, but once again, it's a specific use case. I'm trying to get a general answer. Moreover, for your example, we could say that the folds indeed are representative, not of our data per se, but of our target.
Comment: What do you mean by 'representative'? Why is n-fold/leave-one-out cross validation not representative? (or at least you seem to suggest this with *"This seems to me to be contradictory since the leave-one-out CV is..."*)
Comment: @SextusEmpiricus LOOCV has unrepresentative folds in the sense that the one fold that is used for validation in one of the n iterations (which is just one sample), cannot possibly be representative of our dataset. The question is therefore why should a fold in k-fold CV be representative (the same kind of representative) if the one in LOOCV is clearly not?
Answer: This is a reasonable question but it might be conflating 2 things.

Should $k$ be chosen to make [something] representative?
Should the-way-we-assign-data-to-each-fold be chosen to make [something] representative?

1) Choice of $k$
In a comment the OP says "I read it here (the 'configuration of k' section)..."
And in that linked blog post, that blog's author writes:

Representative: The value for k is chosen such that each train/test group of data samples is large enough to be statistically representative of the broader dataset.

Rather than being representative of the broader dataset, it's often more useful to think about being representative of the population from which the dataset came.
That's because cross validation is less suited to answering "How well would this model perform on new data if I fit it to this dataset?" (conditional test error), and better suited to answering "How well does this model tend to perform on new data after being fit to datasets like this one?" (expected test error)
See for instance Section 7.12 of The Elements of Statistical Learning (Hastie et al., 2nd ed), or the preprint "Cross-validation: what does it estimate and how well does it do it?" (Bates et al., 2021).
Of course, often we still want to use the CV estimates to choose a model for our dataset. It's just helpful to realize that they are one step removed from directly answering that question.
For the moment let's just talk about the case when the original dataset was an iid sample from the population. No temporal correlation, group-hierarchical structure, etc.
In that spirit, if you choose $k=n$ and use LOOCV, each CV training set will be almost the same size as your full dataset. So CV will be "representative" in that it's trying to measure your model's expected performance when trained on datasets of (nearly) the same size as your full dataset. If that is indeed your goal, LOOCV is "representative" in that model performance estimates should be nearly unbiased.
By contrast, smaller $k$ such as $k=5$ might be "less representative" in that CV will try to measure your model's expected performance when trained on datasets smaller than the one you really have. Imagine you could get a plot of true expected model performance vs sample size. If this "learning curve" is still steep at sample size $n*4/5$, you'll get a pessimistic view of how well your model would tend to perform on samples of size $n$.
That's all in terms of repeated sampling: if you repeated the process of [collect an entirely new dataset of size $n$ and run CV] many times, LOOCV should have smaller bias than other values of $k$. But the standard story is that there's a bias-variance tradeoff, and LOOCV may have higher variance than others. So we often choose a moderate value like $k=10$ and hope that the learning curve is flat enough for samples of size $n*9/10$ to be "representative" but not too variable across repeated sampling.
In any case, in a complete run of $k$-fold CV (using all the folds), every observation will be in a test fold exactly once. Different values of $k$ will make those test cases more or less correlated with other observations (affecting the variance over repeated sampling)---but won't change the total number of test cases. However, if you're only doing a single train/test split, then yes, you should try to get enough data in both the training set (so you can afford to fit realistically/usefully complex models) and in the test set (so you can evaluate them with enough precision to distinguish better models from worse ones).
2) Choice of how to assign data to each fold
The OP also writes:

...should be picked in such a manner as to have representative validation sets (folds). This seems to me to be contradictory since the leave-one-out CV has only one sample as a fold, which clearly can't be representative of the dataset...

That's okay. If the dataset is iid from the population, any one test case is a "representative" sample ($n=1$) of that population. And the set of all LOOCV test cases across folds is representative of the population too.
This relates to a common misconception:
Shouldn't we try to make each fold look as similar to the full dataset as possible?
and I would answer:
No. In the spirit of conditional vs expected test error, the way each fold is sampled should be representative of how the full dataset was sampled.
Reference: "K-fold cross-validation for complex sample surveys" (Wieczorek et al., 2022).
This will help CV to estimate "How well is this model expected to perform on datasets collected the same way as this one?" Otherwise, if CV ignores something important about your sampling design, it will be a much less useful approximation to "How well might this model work on my full dataset?"
So for instance, CV for time-series data generally keeps blocks of temporally-consecutive observations together, and also ensures that we train on earlier data and test on later data. If we formed folds randomly instead, the training data might look "more representative" of the full dataset---but it wouldn't be useful for assessing our ability to make forecasts.
Reference: "Cross-validation strategies for data with temporal, spatial, hierarchical, or phylogenetic structure" (Roberts et al., 2016).
Likewise, in CV for grouped data (like in @Henry's comment), generally we want to keep entire groups together when making CV folds. If we have several observations for each subject in a study, folds should be formed subject-by-subject since this is how we sampled the data. (So $k$-fold would put $n/k$ subjects in each fold, and LOOCV would put one subject in each fold.) If the training and test sets have different subjects, this lets us honestly evaluate how well we'd make predictions for future subjects not yet in the dataset.
Reference: "The need to approximate the use-case in clinical machine learning" (Saeb et al., 2017).
Finally, since stratified CV came up in the comments: I would not usually do stratified CV unless the original data collection really was stratified. Otherwise CV may be over-optimistic. It will be estimating "this model's performance when trained on stratified data," whereas you actually want an estimate "...when trained on iid data" or whatever.
(The exception of course is a classification problem with a rare outcome category: then you might be forced to stratify on the response, because otherwise you might never see that outcome in some training sets.)
Comment: @bob_cart Thank you very much! And yes, you noticed my careful word choice about the "standard story" :)  Thanks for asking a good question!
Comment: The research I have done after posting the question confirms what you wrote here, and I agree with you. I have read conflicting opinions about LOOCV having higher variance, but I suppose that is why you wrote that it is "the standard story". The example with temporal data is great and something I have actually come by recently. Thanks a lot for providing a thorough answer!
Answer: The book The Elements of Statistical Learning considers leave-one-out cross-validation a form of k-fold cross-validation, and in this version the validation set of each fold consists of only a single example, and can for that reason not be said to be representative of the dataset. So no, the folds in k-fold cross-validation do not have to have representative validation sets.
Comment: k-fold cross-validation *can* have unrepresentative validation sets, but that doesn't answer the question whether or not it *should* have representative validation sets.
Comment: Unless $N$ is very large (in some cases $> 20000$ for binary Y, a single 10-fold CV will be imprecise/unstable.  That's why it's best to repeat the whole process 50-100 times, in which case the representativeness issue resolves itself.


If two infinite vector spaces have the same cardinality then they are isomorphic

Question: Let $F$ be a field. Suppose that $V,W$ are $F$-vector spaces with infinite cardinality. Is it true that they have the same dimension?
If it is not true, will it be true if $|V|,|W| \geq |F|$?
Comment: What am I missing here? Why isn't the answer to this "no because $\mathbb{R}^2$ and $\mathbb{R}^3$ have infinite cardinality, but not the same dimension"?
Comment: @Ovi of course your example works perfectly.
Comment: Note $\text{dim}_{\Bbb{R}}\Bbb{R}=1$, whereas  $\text{dim}_{\Bbb{R}}\Bbb{C}=2$. So not isomorphic over the scalar field $\Bbb{R}$.
Comment: @AnuragA, how can I forget about this simple example... Thank you!
Comment: @AnuragA Would you mind taking a look at my comment above please?
Comment: @AnuragA, is it true that any infinite vector spaces can be embedded into an infinite dimensional vector space?
Comment: @AnuragA, moreover, regarding my original question: If $|V|=|W| \geq |F|$, is it true that they have the same dimension?
Comment: @bbw $| \mathbb{R}^2 |= |\mathbb{R}^3| = | \mathbb{R}|$
Comment: @AnuragA Okay thanks
Comment: @Ovi, thank you!
Comment: @bbw Sure! ${}{}$
Comment: You may find this question interesting https://math.stackexchange.com/questions/541096/cardinality-of-a-vector-space-versus-the-cardinality-of-its-basis
Comment: @LucaCarai, Thank you!
Answer: As they told you in the comments, that is not true even assuming $|V|=|W| \geq |F|$. Indeed, $|\mathbb{R}|=|\mathbb{R}^2|\geq |\mathbb{R}|$ but $\mathbb{R}$ and $\mathbb{R}^2$ are not isomorphic as $\mathbb{R}$-vector spaces.
But if you assume $|V|=|W| > |F|$ then it is true.
For every non-zero $F$-vector space $V$ we have that
$$\max \{|F|, \mbox{dim}_{F}V \} \le |V| \le \max \{ \aleph_0, |F|, \mbox{dim}_{F}V \}$$
(see the answer in Cardinality of a vector space versus the cardinality of its basis).
If $|V|=|W|=1$, the claim is clearly true. Thus we can assume $V$ and $W$ to be non-zero. If $F$ is finite, then either $|V|=|W|$ is at most countable and it is easy to show that this implies $\mbox{dim}_{F}V=\mbox{dim}_{F}W$ or $|V|=|W|$ is uncountable and then $\mbox{dim}_{F}V=|V|=|W|= \mbox{dim}_{F}W$. If $F$ is infinite, then $|F| \geq \mbox{dim}_{F}V$ cannot happen because we would have $|V|=|W|=|F|$. If $F$ is infinite and $|F| < \mbox{dim}_{F}V$, then $\mbox{dim}_{F}V=|V|=|W|= \mbox{dim}_{F}W$.
In either case we have $\mbox{dim}_{F}V= \mbox{dim}_{F}W$. So $V$ and $W$ are isomorphic.
Comment: Thank you. But if this is true, I have another question. Given a field $F$, does there exists a $F$-vector space $V$ such that $|V|>|F|$?
Comment: Yes, absolutely. Take the free $F$-vector space on a set of cardinality strictly bigger than $|F|$. In this way, you can find vector spaces of arbitrarily large cardinality.
Comment: What do you mean by the "the free $F$-vector space"? My thought was, if $F$ is finite, then any infinite $F$-vector space will do. If $F$ is infinite, then $|F|$ is of the form $\aleph_{\alpha}$ for some ordinal $\alpha$. Then, for example, any set of cardinality $\aleph_{\beta}$ for $\beta > \alpha$ is bigger then $|F|$. But this is just a set, how can I get a vector space bigger than $|F|$?
Comment: For the definition of free $F$-vector space see this wikipedia page https://en.wikipedia.org/wiki/Free_module. Take the ring $R$ to be the field $F$. The free vector space on a set $X$ is a vector space with dimension $|X|$.


Degrees of freedom of a coin toss

Question: The probability of a fair coin landing heads is $p(H)=1/2$ and since there is only one other outcome we can deduce that the probability for tails is also $p(T)=1-p(H)=1/2$. Yet if we examine a distribution of coin tosses, knowing just one parameter (for example heads) is not enough to describe the distribution. We also need to know either the number of tails or the total number of coin tosses, so how come there is only one degree of freedom in a coin toss distribution?
Comment: Please see https://stats.stackexchange.com/questions/16921 for what "degrees of freedom" can mean in statistics.  (This is not one of those situations.)
Comment: Welcome to Cross Validated! It will be important to specify exactly what distribution you want to assess, as there are subtle differences between the so-called "Bernoulli" and "binomial" distributions.
Comment: The sample size (number of tosses here) is usually assumed to be known.
Comment: @Henry does that not hide the point that you need two pieces of data to know the whole distribution?
Comment: Re "two pieces:" that's not true.  One usually never knows the true distribution, no matter how much data are available.  The principal exception would be when conducting a complete census (with no measurement error) of a finite population.  And if by "know" you mean *estimate,* there are textbook examples where one observation suffices for an estimate.  (In a Bayesian setting, one observation can give an excellent estimate.)
Answer: Degrees of freedom apply to a parametrisation of a model, not to the observed outcome. We model a single coin toss by a Bernoulli($p$) distribution, which only has a single parameter, namely the $p$. "Heads" is an outcome, not a parameter, so it neither has degrees of freedom nor is to be counted in order to know the degrees of freedom. If we want to estimate the parameter $p$ from data, say $n$ coin tosses, we usually assume the tosses to be i.i.d. (independently identically distributed) according to a Bernoulli($p$)-distribution, so there still is $p$ as the only parameter, as long as $n$ is known and treated as fixed (which usually is the case). The standard estimator is the relative frequency of heads (assuming "1" corresponds to "heads"), so we need to know this in order to estimate $p$, but it's an outcome, not a parameter to be estimated, so again it doesn't count on top of the $p$ for determining the number of parameters. You need to understand that there is an essential difference between the parameter $p$ to be estimated and the observed relative frequency used to estimate $p$.

Degrees of freedom of a coin toss


Why is a matrix multiplied by its adjugate is diagonal?

Question: I'm referring to the formula $A\operatorname{adj}(A)=\det(A)I=C$. I understand why we get the determinants on the diagonal, but why does every $c_{ij}$ with $i\neq j$ is zero? I don't seem to get it intuitively and all the proofs I have seen treat it like it is obvious.
Comment: The question is: 'why is $A \ \text{adj}(A) = \text{det}(A) I$?'. The OP understands why $A \ \text{adj}(A)$ has $\text{det}(A)$'s on the diagonal, but not why it has $0$'s everywhere else.
Comment: That's the theorem of Laplace on row or column expansions, written in matrix form. The fact that $c_{ij}=0$ for $i\ne j$ is sometimes called "expansion with respect to the wrong row" or "alien cofactor".
Comment: Look for the expression $det(A)*I$. Isn't I the identity matrix? That's why every non-diagonal entry is zero
Comment: Start from A^-1=1/det(A)* adj(A)
Answer: In the matrix $A$, for two distinct indices $i,i'$ replace row $i'$ by row $i$ leaving all other rows the same, including row $i.$ Call the new matrix $B.$ Note that B has  two idenical rows. Note that along row $i'$, the matrices $A$ and $B$ have the same co-factors. Expand $\det B$ along row $i'$. Since $B$ has two identical rows, its determinant is 0. The elements of $B$ along row $i'$ are the elements of $A$ along row $i$ and the co-factors of $B$ along row $i'$ are the co-factors of $A$ along row $i'$.


Delete duplicate rows leaving recent 10 using mysql

Question: I have a table containing multiple fields but important fields (to be used in query) are
phone_number varchar(20),
entry_date datetime
This table contains records in millions and each phone_number have multiple entries. I want to delete phone_numbers having multiple entries but want to keep last 10 for each phone_number
Example:
SELECT phone_number,COUNT(*)
FROM test_table
GROUP BY phone_number
HAVING COUNT(*) > 10
ORDER BY COUNT(*) DESC;

Result:

Requirement:
I want a query that reduce all these counts to 10 but those must be recent 10 records for each phone_number
Comment: What is precise MySQL version? Do you need to delete excess rows completely from source table?
Comment: Server version: 5.6.28. Yes I want to delete all rows more than 10 for each phone_number but want to keep latest 10 based on entry_date
Answer: in addition to FaNo_FN's answer.
If the percent of rows to be deleted is high it can be faster to copy the rows to be saved into new table and replace source table with new one.
For MySQL 5.6 it can be performed with the query
INSERT INTO new_test
SELECT *
FROM ( SELECT CASE WHEN (@count := ((@phone = phone) * @count + 1)) > 3
                   THEN NULL
                   ELSE @phone := phone END new_phone,
              entry_date
       FROM test
       CROSS JOIN (SELECT @phone := 0, @count := 0) init_variables
       ORDER BY phone, entry_date DESC ) data
WHERE new_phone IS NOT NULL;

The amount of rows per phone is specified in CASE condition (in this query it is 3). The most recent rows are saved (this is defined by ORDER BY clause in the subquery).
fiddle (do not look at the MySQL version in the fiddle - the features which are specific for version 8+ are used for sample data generation only).
Answer: You have to assign row numbers on each of the phone_number entries, sort by descending entry_date. Then you'll do a query that will only return row number 1-10 for each phone_number. In this operation, you don't need COUNT(*) and GROUP BY. Something like this will probably work:
SELECT phone_number, entry_date FROM
(SELECT phone_number, entry_date,
       ROW_NUMBER() OVER (PARTITION BY phone_number ORDER BY entry_date) AS Rownum
       FROM test_table) AS subquery1
   WHERE Rownum <=10
  ORDER BY phone_number, entry_date DESC;

ROW_NUMBER() function is available on MySQL version 8+.
For older MySQL version, you can emulate ROW_NUMBER() using this method:
SELECT phone_number, entry_date FROM
(SELECT phone_number, entry_date,
    @row_number:=CASE WHEN @pn = phone_number THEN @row_number + 1
                      ELSE 1 END AS rownum,
    @pn:=phone_number PN
FROM test_table t
CROSS JOIN (SELECT @pn:=0, @row_number:=0) as n
ORDER BY entry_date) AS subquery1
       WHERE Rownum <=10
       ORDER BY phone_number, entry_date DESC;

Then simply add INSERT INTO new_table .. on top of the query for the insert process.
Demo fiddle


How to sum the values of second column if the names in the first column matches between two data frames in R?

Question: I have two dataframes which look like following:
df1:

Sample   Digit
AACF-01    6
AACG-01    7
AAKD-01    3
AAIU-01    4

df2:

Sample   Digit
AACF-01    8
AACJ-01    2
AAKD-01    4
AALO-01    5

If the names in the first column matches between two data frames sum the values in the second column.
Result should look like the following:
Sample   Digit
AACF-01    14
AACG-01     7
AACJ-01     2
AAKD-01     7
AAIU-01     4
AALO-01     5

Can anyone please tell me how to do this?
Thank you
Answer: We can bind the rows of the dataset, grouped by 'Sample', get the sum
library(dplyr)
bind_rows(df1, df2) %>%
       group_by(Sample) %>%
       summarise(Digit = sum(Digit))
# A tibble: 6 × 2
#    Sample Digit
#    <chr> <int>
#1 AACF-01    14
#2 AACG-01     7
#3 AACJ-01     2
#4 AAIU-01     4
#5 AAKD-01     7
#6 AALO-01     5

Or with data.table
library(data.table)
rbindlist(list(df1, df2))[, .(Digit = sum(Digit)), .(Sample)]
#    Sample Digit
#1: AACF-01    14
#2: AACG-01     7
#3: AAKD-01     7
#4: AAIU-01     4
#5: AACJ-01     2
#6: AALO-01     5

Or using base R to avoid
aggregate(.~Sample, rbind(df1, df2), sum)
#    Sample Digit
#1 AACF-01    14
#2 AACG-01     7
#3 AACJ-01     2
#4 AAIU-01     4
#5 AAKD-01     7
#6 AALO-01     5


Azure ExpressRoute Gateway Zone Redundant Gateway ARM Tempate

Question: I want to create a Zone-redudant ExpressRoute Gateway using ARM templates, however I always get this error below
<code>"message": "Virtual network gateway Sku specified is not valid for gateway /subscriptions/xxxxxxxx/resourceGroups/NSPRG/providers/Microsoft.Network/virtualNetworkGateways/ERGw
</code>
with DeploymentType CloudService. The allowed Skus are Standard,HighPerformance,UltraPerformance.",
The ARM template code I'm using is below...editor is VSCode
<code> {
    "apiVersion": "2020-06-01",
    "type": "Microsoft.Network/virtualNetworkGateways",
    "name": "[parameters('ERgatewayName')]",
    "location": "[parameters('location')]",
    "dependsOn": [
      "[resourceId('Microsoft.Network/publicIPAddresses/', parameters('gatewayPublicIPName'))]",
      "[resourceId('Microsoft.Network/virtualNetworks/', parameters('virtualNetworkName'))]",
    "[resourceId('Microsoft.Network/virtualNetworkGateways', parameters('gatewayName'))]",
      "[resourceId('Microsoft.Network/localNetworkGateways', parameters('localGatewayName'))]"
    ],
    "properties": {
      "ipConfigurations": [
        {
          "properties": {
            "privateIPAllocationMethod": "Dynamic",
            "subnet": {
              "id": "[variables('gatewaySubnetRef')]"
            },
            "publicIPAddress": {
              "id": "[resourceId('Microsoft.Network/publicIPAddresses',parameters('ERgatewayPublicIPName'))]"
            }
          },
          "name": "ERvnetGatewayConfig"
        }
      ],
      "gatewayType": "[parameters('ERgatewayType')]" ,
      "sku": {
          "name":"ErGw3AZ",
          "tier":"ErGw3AZ"
      }

    }
  }
</code>
Please what could be the issue here
Comment: Do you add a public IP address with a Standard PublicIpaddress SKU?  or change the SKU to one of Standard,HighPerformance,UltraPerformance?
Comment: @NancyXiong thanks the public IP was the issue
Answer: As the document stated:

Zone-redundant gateways and zonal gateways both rely on the Azure
public IP resource Standard SKU. The configuration of the Azure public
IP resource determines whether the gateway that you deploy is
zone-redundant, or zonal. If you create a public IP resource with a
Basic SKU, the gateway will not have any zone redundancy, and the
gateway resources will be regional.

for the error message, the public IP was the issue. We need to have a public IP resource Standard SKU for Zone-redundant gateways.


Learning to sing: Some songs i can sing straightforwardly other i really cant is this normal?

Question: I've been learning to sing for a year. And I noticed some great improvements but there is one thing that happens to me that is totally strange: When I listen to songs, there are songs that I can "understand" right away and then I can sing them with the right notes after practically a few plays.
There are other songs that maybe I have known for a long time, that no matter how much I listen to them I can't sing them and I can't "understand" them at all. ( i sing totally wrong)
Is this normal for a beginner?
For instance:
Passing Afternoon by iron and wine is one of the song i struggle the most.(I'm A 24yo male)
Comment: It's a good idea to learn to play an instrument at the same time - you'll have a far better understanding of how music works then.
Comment: What's the nature of the songs that you "sing totally wrong"? Do they have really fast notes? Are they atonal or at least heavily chromatic? Do they switch keys too often? Do they have prominent countermelodies you wish you could sing at the same time as the main melody?
Comment: @Tim yes i'm learning guitar too !
Comment: @Dekkadeci well i cant tell you why those are so hard for me but i can give you exemples of song i find impossible to sing: Passing afternoon by iron and wine , ghost by justin bieber i really can't sing them .   instead songs like "little things, tusk till down , yellow (coldplay) i can at least sing decently/good   ( ps if this matter i'm a 24yo male)
Comment: Could be range, but that's mentioned by other comments already. Could also be intervals - some intervals are less familiar and harder to get the hang of. Also, a song with an uncommonly fast or slow tempo might feel unusual and take longer to get the hang of.
Answer: Slightly unusual, maybe!   My experience is that when a singer learns by imitation, there's little distinction between 'hard' and 'easy' (as long as the song is in their vocal range).   It's when reading notation that a complex song becomes 'hard'.
Maybe you're trying songs that AREN'T in your vocal range.   If you're a female soprano, you might have to re-think a James Brown song!
Comment: Thanks for your answer! Well i give you some instance: i can get "little things the one written by ed sheeran for 1d " very fast, and i sing it quite well. I'm really struggling to sing "passing afternoon by iron and wine , i really can't get it no mutter how much i try!
Comment: Passing afternoon doesn't seems to be this "super high difficult" song , but for me is nearly impossible to sing.


Typed struct contains typed function that takes this typed struct as an argument

Question: Is it wrong at all and there is no way, or i have to do it somewhat else?
For example:
typedef void (*UserFunc)(Test *tx);

typedef struct{
int a;
char b;
UserFunc func;
} Test;

i get this error:
c.c:5:26: error: unknown type name 'Test'
 typedef void (*UserFunc)(Test *tx);
                          ^~~~
c.c:10:1: error: unknown type name 'UserFunc'
 UserFunc func;
 ^~~~~~~~

When i move down function typedef:
typedef struct{
int a;
char b;
UserFunc func;
} Test;

typedef void (*UserFunc)(Test *tx);

I get:
c.c:8:1: error: unknown type name 'UserFunc'
 UserFunc func;
 ^~~~~~~~

Comment: Please go through forward deceleration. I think it will help you to figure out the issue
Comment: Thank you! Will do!
Answer: You have to declare Test first, and define it later :
typedef struct Test Test;

typedef void (*UserFunc)(Test *tx);

typedef struct Test {
    int      a;
    char     b;
    UserFunc func;
} Test;


Does a closed form solution for the value $a$ exist?

Question: I'm having trouble trying to solve this algebraically for the value a, ie a = some function, where a, g and v are independent variables.  Is there a closed form solution for this?
$g$ = $ln(1+a)$ - $\frac{0.5v}{(1+a)^2}$
Answer: No, this is a transcendental equation in $a$. Have a look at Lambert W-Function.
Answer: If you make a change of variable such that, for example, $x=\frac{1}{(a+1)^2}$, the equation write  $$2g=-\log (x)-{v}{x}$$ which is probably the best candidate for a Lambert function based solution as already mentioned by Ryuky. The solution of this last equation is given by $$x=\frac{W\left(e^{-2 g} v\right)}{v}$$ where $W$ is the Lambert function. Then, from $x$, we have $a$ from the definition.


IPTables rules to Deny ALL traffic for an IP range with CRON

Question: I currently have a ClearOS gateway server in transparent proxy mode. It has a lot of great tools but I have some issues preventing me from forcing the use of the web proxy directly which would give the control over scheduling using ACLs....
Long story short. I need to find a way to block ALL traffic for specific IP addresses and IP ranges. I have studied this out and I need to do this through the firewall (IPTables). Ideally, I would like to set up a cron job to swap out the IPTables rules to start and stop all traffic for the specified IP ranges/addresses.
I saw someone who talked about doing this in a forum but they gave no details. They suggested having multiple iptable config files for the different conditions and then using cron to swap them. I am not sure if setting a cron command using an IPTables command to add/remove a rule or set of rules is possible or preffereable. In any case I am a novice at this specifically but I am saavy enough to get in and get my hands dirty....
If you have information on how to do this I thank you in advance. I am not looking for alternative methods at this point as I have looked at just about all of them. Going with the firewall and cron is my goal.
Thanks!
Answer: Summing this up for those who may come across this issue.... I was able to solve it with some help from the ClearOS forum and a couple of really helpful guys... Here is the link so I don't have to replicate the entire thread here:
http://www.clearfoundation.com/component/option,com_kunena/Itemid,232/catid,7/func,view/id,46918/


What is the smallest positive binary type number divisible by $225$.

Question: A binary type number is an integer (base $10$) with the property that all of its digits are either $0$ or $1$. What is the smallest positive binary type number divisible by $225$.
I dont have too much knowledge on binary numbers so What confuses me about this question is $225$ is not a binary number since a binary number only contains $0$ or $1$. So that binary number must be a multiple of $225$ but there arent any multiples that only contain $0$ and $1$.
So im not sure how to approach this problem. Any suggestions?
Answer: Note that $225=9\cdot 25$, so the solution must be a multiple of $9$ and a multiple of $25$.  A multiple of $9$ has digital root $9$, so in particular the solution must contain at least nine $1$'s.  Further, a solution must end in $00$, $01$, $10$, or $11$; however only $00$ gives a multiple of $25$.  The combination of these two conditions suggests trying $11111111100$, i.e. nine $1$'s followed by two $0$'s.  In fact this works, and is minimal by the two criteria above.
Answer: Yes there are multiples of $225$ (and all other numbers) that have all their digits $0$ or $1$.  One example, not the smallest, is $111111111111111111000$, which, when divided by $225$ yields $493827160493827160$ with no remainder.
To find the smallest, you need to first find out how many factors of $2$ and $5$ there are and make them equal.  Then you need to find how long a string of $1$'s is needed to deal with the rest of the factors.