Strange behavior of R function ecdf

Question: I have a very long vector, x, of integer values in the range [0, 1000]. I then use stats::ecdf to create
empirical cummulative distribution function (ECDF). Since the minimum value of x is 0, I expect
that ecdf(x)(0) would be equal to zero. However, this is not true
> length(x)
[1] 28694
> min(x)
[1] 0
> max(x)
[1] 1000
> summary(x)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
    0.0   576.0   762.0   720.4   977.0  1000.0
> summary(x[x<=576]) #summary of the first quantile
    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
    0.0   172.0   391.0   330.2   490.2   576.0
> f <- ecdf(x)
> f(0) # I expect 0
[1] 0.0425176
> f(-0.00000001)
[1] 0
> f(762.0) #median
[1] 0.5004879 #as expected

What may be the source of strange behaviour?
Answer: Your expectation is wrong.  Run...
mean(x==0)

... and you will see why.  (Side note:  x == 0 creates a vector of logicals where TRUE has a value of 1 and FALSE has a value of 0.  The mean of this vector of logicals tells you what proportion of your dataset has a value of 0.)  This matches f(0).  Why?  Because, per the help file for that function:

The e.c.d.f. (empirical cumulative distribution function) Fn is a step
  function with jumps i/n at observation values, where i is the number
  of tied observations at that value. Missing values are ignored.

(emphasis added).  Therefore, the ecdf at 0 matches the proportion of your vector x that has a value <= 0.
Comment: Yep, that explains it. I was sure that ecdf at 0 matched the fraction of x<0 and was also not expecting that **my** `x` would contain that much 0's. Thank you

Strange behavior of R function ecdf


What are the steps involved in organizing a new band?

Question: I would like to create a band. This seems to me a non-trivial question to implement, as it involves a lot of management, which is not particularly tied to music theory. But it has  musical specifics, and some of you may be successful bandleaders. So I'd like to ask you what your action sequence would be, if you had no friends in that field, and would like to know what you've done from scratch? Thanks.
P.S. If genre matters, I originated from '80s Metallica's Nothing Else Matters, which is kind of fingerstyle, and with bass I would like to do some funk melodies like the Red Hot Chili Peppers.
Comment: Go to shows, go to bars, go to meetups for musicians, music-oriented book clubs, whatever. Ask your non-musician friends if they have friends who are musicians. Hang out with people, find people you vibe with and want to play with, then start playing!
Comment: I think this is a great question. Answers could address finding likeminded bandmates, organizing rehearsals, paying for equipment and rehearsal space, and various levels of commitment/professional aspiration that a prospective bandleader might choose from.
Comment: You don't mention the size of the town you live in.  This is an important consideration.
Comment: At the moment, with most countries in lock-down? Dream on! When we CAN be social again, go places where bands play. Talk to the guys. Have you played in a band before? If not, consider filling a vacancy in someone else's band and learn the ropes.
Answer: There are so many considerations, it may well not be feasible, particularly right now.
Even if you have access to several good players, and you are also in that category, it can and most likely will take many months minimum to even reach the stage where you can do a gig.

Players - what instruments, what level, what style, what age range?
Equipment - who buys, owns, looks after, stores, transports what?
Rehearsals - where, who pays, who finds, who attends, is available?
Songs - who chooses, works out, arranges, decides?
Gigs (eventually) - where, frequency, size, money paid?
Publicity - how much (time, effort, cost)?
Management - needed or not? One person in charge, or a group decision on what things?
Hiring/firing - who does what, when, why?

That's just some starter questions to consider, before we get into 'can my mate come and sing? No, he hasn't even got a mic...'
There are places to advertise - schools, colleges, unis, churches, local rags, sites like 'Join my Band'.
Comment: "Yeah, but John's the only one with a bass amp, so he HAS to be the bassist!" "John can't play to save his life, what about Dave?" "Dave always appears to be playing in 5/4 to most things, & often in a different key." ad nauseum….
Comment: Keep in mind when forming a band that you're "herding cats."  The more members, the harder it is to get them all in the same place at the same time.  And if your bandmates are any good, there's a good probability that they're in other bands as well.  How do you/they set priorities when there's a conflict?
Comment: Also to add to the bullet list to consider: Union membership and licensing of the music.
Comment: @Tetsujin - been in bands like that - momentarily... It could always end up as a jazz band though!
Comment: I'm just so glad I'm not in my teens any more ;) I got lucky, 3 friends, all played different instruments, all could sing, all had parents who'd buy amps, all about the same [limited] talent. Worked well, we all learned. All still musos, nearly 50 years later.
Comment: @Duston - I was a member for many years, and it was useful on only one occasion, a gig when all the bandmembers had to be in the union. It did provide a good pro forma for bookings. Licensing - again, in a thousand gigs, we filled the form in once. Maybe country makes a difference?
Comment: @Tim I don't disagree, But even if he chooses not to decide, he still has made a choice.
Comment: It seems from the OP's post that they aren't necessarily interested in starting a *professional* band, so not all of these points will apply.
Comment: @Max - there's not much worse than a band acting in an amateur way. So even if it's never going to be a *pro* band - there's nothing wrong with approaching the whole thing in a pro way.
Comment: See also: [Who provides the p.a?](https://music.stackexchange.com/q/129896/70803).
Answer: I'd suggest that the first step in your action sequence, or rather the first intermediate goal you should set for yourself, should be to find just one other person, one other musician, with whom to get things started.
Ideally, it should be a compatible person, with similar tastes, with whom you can already start trying out some ideas. And you can already start looking for such a mate even now, during the lockdown period, why not. You can talk online, share ideas, etc. And at the first opportunity, meet somewhere and try playing together.
If you play bass, this first person could be a drummer or a guitarist. In both cases you'll already be able to get something started.
If you can get this done, you will have reached an important milestone toward eventually forming a full band.
And if you don't already have friends with those characteristics, try local ads, online ads, etc.
Again, the main principle is that you don't try to create a whole band all at once, but try instead to find one good person first, then after some time, if things gel, look for one more person that both of you will like, and so on. In this way things will always remain fairly simple and you'll gradually learn along the way whatever you need to learn.


Flink: Error while running the flink program on CLI

Question: I am trying to run a flink steaming program that uses kafka connector(latest universal connector).
The jobs runs without any problem on IntelliJ  but when I am submitting the code build into jar using sbt package is giving me below error.
java.lang.ClassNotFoundException: org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumerBase
I also used the jar built using traditional IntellIJ option but still i get the above error.
Answer: Most probably the issue is the fact that You are not including the dependencies in Your JAR file. Connector dependencies are not included in the Flink binary.
Generally, the preferred way of tackling this issue is to use the proper plugin for Your build tool like shade-plugin for Maven or assembly for sbt to create so-called fat-jar i.e. the JAR with the dependencies included.


Limit by L'hospital's rule

Question: I have to prove that:
 $$\lim \limits_{x \to \infty} \frac{{\int_x^{\infty} \exp(-t^2/2)dt}}{\exp(-x^2/2)
(1/x)}=1$$
Should I use L'hospital rule, if yes what are the derivatives?
Comment: I would say:  $d/dx (\int_x^{\infty} \exp(-t^2/2)dt)=-\exp(-x
^2/2)$
Answer: First note that
$$
\int e^{-cx^2}dx=\sqrt{\frac{\pi}{4c}}\mathrm{erf}(\sqrt{c}x)
$$
So now we have
$$
\lim_{x \to \infty} \left[\frac{\int_x^{\infty} e^{-\frac{t^2}{2}}dt}{\frac{1}{x}e^{-\frac{x^2}{2}}}\right]=\lim_{x \to \infty} \left[\frac{\lim \limits_{b\to\infty} \int_x^b e^{-\frac{t^2}{2}}dt}{\frac{1}{x}e^{-\frac{x^2}{2}}}\right]=\lim_{x \to \infty} \left[\frac{\sqrt{\frac{\pi}{2}}\lim \limits_{b\to\infty}\left[\mathrm{erf}\left(\frac{b}{\sqrt{2}}\right)-\mathrm{erf}\left(\frac{x}{\sqrt{2}}\right)\right]}{\frac{1}{x}e^{-\frac{x^2}{2}}}\right]
$$
$$
=\lim_{x \to \infty} \left[\frac{\sqrt{\frac{\pi}{2}}\left[1-\mathrm{erf}\left(\frac{x}{\sqrt{2}}\right)\right]}{\frac{1}{x}e^{-\frac{x^2}{2}}}\right]=\lim_{x \to \infty} \left[\frac{\sqrt{\frac{\pi}{2}}\mathrm{erfc}\left(\frac{x}{\sqrt{2}}\right)}{\frac{1}{x}e^{-\frac{x^2}{2}}}\right]=\sqrt{\frac{\pi}{2}}\lim_{x \to \infty} \left[\frac{\mathrm{erfc}\left(\frac{x}{\sqrt{2}}\right)}{\frac{1}{x}e^{-\frac{x^2}{2}}}\right]
$$
$$
=\sqrt{\frac{\pi}{2}}\lim_{x \to \infty} \left[\frac{\frac{d}{dx}\mathrm{erfc}\left(\frac{x}{\sqrt{2}}\right)}{\frac{d}{dx}\left[\frac{1}{x}e^{-\frac{x^2}{2}}\right]}\right]=\sqrt{\frac{\pi}{2}}\lim_{x \to \infty} \left[\frac{-\sqrt{\frac{2}{\pi}}e^{-\frac{x^2}{2}}}{-\frac{e^{-\frac{x^2}{2}}(x^2+1)}{x^2}}\right]=\sqrt{\frac{\pi}{2}}\lim_{x \to \infty} \left[\frac{\sqrt{\frac{2}{\pi}}}{\frac{(x^2+1)}{x^2}}\right]
$$
$$
=\sqrt{\frac{\pi}{2}}\lim_{x \to \infty} \left[\frac{\sqrt{\frac{2}{\pi}}}{1+\frac{1}{x^2}}\right]=\sqrt{\frac{\pi}{2}}\sqrt{\frac{2}{\pi}}=1
$$
Comment: That is certainly the long way around. I am impressed that your result agrees with the other two.
Answer: Since
$$\mathop {\lim }\limits_{x \to \infty } {{\int_x^\infty  {{e^{ - {{{t^2}} \over 2}}}} dt} \over {{e^{ - {{{x^2}} \over 2}}}}} = \mathop {\lim }\limits_{x \to \infty } {{ - {e^{ - {{{x^2}} \over 2}}}} \over { - x{e^{ - {{{x^2}} \over 2}}}}} \to 0$$
Applying L'hospital's Rule ,
$$\mathop {\lim }\limits_{x \to \infty } {{x\int_x^\infty  {{e^{ - {{{t^2}} \over 2}}}} dt} \over {{e^{ - {{{x^2}} \over 2}}}}} = \mathop {\lim }\limits_{x \to \infty } {{\int_x^\infty  {{e^{ - {{{t^2}} \over 2}}}} dt - x{e^{ - {{{x^2}} \over 2}}}} \over { - x{e^{ - {{{x^2}} \over 2}}}}} \\= \mathop {\lim }\limits_{x \to \infty } {{ - {e^{ - {{{x^2}} \over 2}}}} \over { - \left( {{e^{ - {{{x^2}} \over 2}}} - {x^2}{e^{ - {{{x^2}} \over 2}}}} \right)}} + 1 = \mathop {\lim }\limits_{x \to \infty } {1 \over {1 - {x^2}}} + 1 = 0 $$
Answer: $$x e^{x^2/2}\int_{x}^{+\infty}e^{-t^2/2}\,dt = x\int_{x}^{+\infty}e^{(x-t)(x+t)/2}\,dt=x\int_{0}^{+\infty}e^{-t(2x+t)/2}\,dt=\int_{0}^{+\infty}e^{-\frac{t^2}{2x^2}}e^{-t}\,dt$$
By the dominated convergence theorem, the limit of the ratio is so:
$$\int_{0}^{+\infty}e^{-t}\,dt = 1.$$

Limit by L'hospital's rule


Ip and Port Forward

Question: We have three computers in our scenario. Lets name them A, B and C. There is no direct connection between A and C, you must follow A-->B-->C. I want to send soap request A to C. There can be a ssh connection between A and B. But no ssh server at C and i cant touch that computer because of security reasons. I just want to send soap request to http://computerCurl:8860/webservice. How can i do this?
Thanks in advance.
Answer: Assuming that B can reach C on port 8860, and that A has no current listener on port 8860, try
<code>A% ssh B -L 8860:C:8860
</code>
and once the tunnel is built, on A try "telnet localhost 8860", and check that you're connected to C's web service.

Ip and Port Forward


Busca em DataGridView populado digitando sobre ele

Question: Possuo um DataGridView já com dados recuperados onde o usuário seleciona um item. Mas, como os itens são numerosos, gostaria de possibilitar que o usuário digite sobre o DataGrid enquanto o sistema "vai" até o item digitado.
Não sei o nome correto desse tipo de facilidade, mas é muito comum no próprio ambiente widows. Como aplico isso num DataGridView?
Obrigado.
Comment: Como se fosse um CTRL F na página?
Comment: Isso, mas sem o `CTRL` + `F`.. Hehe
Comment: Aonde a pessoa digitaria? no próprio gridview? ou em um campo busca fora?
Comment: No próprio Grid..
Answer: Adicione um campo do tipo TextBox logo acima do seu DataGridView e adicione um manipulador para o evento TextChanged e dentro deste manipulador faça como o código abaixo, levando em consideração as suas necessidades:
var termo = (sender as TextBox).Text.ToLowerInvariant();
bool semTermo = String.IsNullOrEmpty(termo);

foreach (DataGridViewRow linha in dataGridView1.Rows)
{
    if ((linha.Cells[COL_NOME.Index].Value as string).ToLowerInvariant().Contains(termo) || semTermo)
        linha.Visible = true;
    else
        linha.Visible = false;
}

Neste exemplo quando o texto do campo for alterado as linhas que contiverem o valor digitado na coluna de "Nome", COL_NOME é o nome de uma coluna, serão exibidos. Caso o termo esteja vazio, ou seja, a pessoa tenha apagado, ele exibirá todas as linhas.
Comment: A ideia é interessante, mas ao testar o código tenho o erro "Não foi possível tornar invisível a linha associada à posição do gerenciador de moeda". Tentei adicionar a linha `dataGridView1.CurrentCell = null` logo acima de `Visible = False` (solução que achei por aí), mas não funcionou
Comment: "... gerenciador de moeda" você está usando algum componente extra ou não está usando o DGV original?
Comment: Estranho o erro, não? Também não entendi.  Nada de diferente, apenas o velho e quase obsoleto DataGridView..
Comment: Poste a exception em inglês, sem tradução.
Comment: adicionei um pequeno trecho que encontrei [**AQUI**](https://social.msdn.microsoft.com/Forums/pt-BR/d18b3b16-4966-48c5-af8a-ccb528dacba6/erro-ocultando-uma-linha-no-datagridview?forum=vscsharppt) e resolveu o erro, mas o processo num todo demora tempo demais na análise das ROWs. Não haveria uma forma apenas de posicionar o Grid no dado procurado?
Comment: Teria sim, mas acredito que a demora é devido à busca em si e não a ocultação das linhas. Você quer posicionar a célula que for encontrada primeira como a célula visível é isto?
Comment: Minha ideia inicial era não deixar nenhuma `row` invisível, apenas posicionar o item buscado na tela, porém, acabei por fazer uma busca via `TextBox` que realiza uma nova `query` no banco de dados no evento `TextChanged`.


Find a Dirichlet series for $\frac{\zeta(s-1)}{\zeta(s)}$ valid for $Re(s)>2$.

Question: Find a Dirichlet series for $\frac{\zeta(s-1)}{\zeta(s)}$ valid for $Re(s)>2$.
I know that we should use absolute convergence but not sure how that applies in this case.
Comment: The $Re(s)>2$ just follows simply from the half-plane of absolute convergence of the $\zeta$ function.  Think about the abscissa of convergence of $\zeta(s)$ and what effect the transformation $s\mapsto s-1$ has.  The import of the problem is finding a nice expression for the coefficients of the Dirichlet series.
Comment: @SimplyBeautifulArt OP needs a Dirichlet Series.  More likely needs $\frac{1}{\zeta(s)}=\sum_{n=1}^{\infty} \frac{\mu(n)}{n^{-s}}$ where $\mu(n)$ is the moebius function.
Comment: Interestingly, $\displaystyle\frac1{\zeta(s)}=\prod_{k\ge1}e^{-\frac{P(kx)}k}$ where $P(x)$ is the prime zeta function.  I suppose you could then expand this via Taylor expansion of $e^x$ and then multiply the entire product out...
Comment: @sharding4 Yeah.... wait... hm... Yup, guess that solve everything
Answer: If the Dirichlet series of $f$ and $g$ converge absolutely for some $s$, then $\text{D}(f,s)\cdot \text{D}(g,s)=\text{D}(f*g,s)$.
We know that $\text{D}(\mu,s)=\frac1{\zeta(s)}$ so it suffices to find a function whose dirichlet series is $\zeta(s-1)$; one easily sees that it is the function $N(n)=n$.
Hence $\frac{\zeta(s-1)}{\zeta(s)}=\text{D}(N*\mu,s)$ for $\text{Re}(s)>2$.
Now we use Möbius inversion to find out what $N*\mu$ is. Since $N*\mu=f$ iff $N=f*u$, where $u$ is the constant $1$ function, we seek for an $f$ which satisfy $\sum\limits_{d|n}f(d)=n$. This is satisfied by Euler's totient function $\varphi$, so we get that $\frac{\zeta(s-1)}{\zeta(s)}=\text{D}(\varphi,s)$.
Comment: You mean if the two Dirichlet series converge absolutely for $\Re(s) > \sigma$, then so does their product.
Comment: If the convergence is conditional, I don't think it is true, look at $\eta(s)^2$ whose abscissa of convergence should be related with the [Dirichlet divisor problem](https://en.wikipedia.org/wiki/Divisor_summatory_function#Dirichlet.27s_divisor_problem)
Comment: Right, I corrected it. Thanks.


svchost suddenly overloading CPU on many servers

Question: it seems that on many servers (w2k8 and w2k12) in our environment suddenly svchost hosting Dhcp, EventLog, lmhosts, Wcmsvc services started to use 1 CPU core by 100%. Sometimes it is also WmiPrvSe. It all seems to have started on Saturday 7pm (CET) synchronously. I did not see any special event in eventlog by that time. What the heck can it be? Please advice where to look and what to investigate. Servers are mainly virtual and I can see clearly in vSphere CPU graph when the load started.
Comment: I'm having a similar problem.  Did you ever find a solution to this?
Comment: the problem was in an app called Wincollect. It is running on our servers and collects eventlogs and sends them to some DB. When we checked resource monitor we save the CPU load is caused by eventlog service. Devs reverted it to some older version and that seems to have helped
Comment: So I have fixed one server for like 5 minutes by stopping all these services and restarting them (actually they restarted by themselves). Now CPU load is normal. It was difficult though because of many dependencies. But after few minutes the CPU load of svchost.exe is back! :(
Comment: And now it is OK again... (why can't I edit the comment after 5 minutes? Jeez...) I don't know what was the cause of CPU load and if it does not come back eventually. Anybody knows the proper sequence of commands or has some script to restart these services easily please?
Comment: Seems like restarting eventlog service helps...
Comment: Mostly restarting eventlog is not enough but clearing Application event log seems to help. Sometimes also System or Security... It has 400MB before clearing.
Answer: No idea if this will work for you, this is something of a shot in the dark. I had a similar issue once - it was caused by wmiprvse service going nuts, and as I recall we solved it by moving WMIprvse to its own process:
<code>`sc config WMIprvse type= own`
</code>
Note space after '='. See Microsoft kb490995.
We never got to the root cause.
Comment: don't you mean Winmgmt?
Comment: More than likely yes. Above is from memory...
Comment: Sorry it did not help. Svchost still jumps from 0 to 100 every few seconds. Also I can't find kb490995. Maybe you made a typo in it
Comment: Ok sorry try bb not kb sorry. You'll need to restart services too.. Look in task manager, can you work out which process is going wrong? If they are in separate processes (svchost instances) you can at least get some idea of where problem is coming from.


The selected view is not changed when drag gestures change the view

Question: I use the following code to create a PageView:
class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  int _selectedIndex = 0;
  PageController pageController = PageController();

  void onTapped(int index) {
    setState(() {
      _selectedIndex = index;

      pageController.animateToPage(index,
          duration: const Duration(milliseconds: 300),
          curve: Curves.ease);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: null,
      body: PageView(
        controller: pageController,
        //We can add widets to each tab page
        children: [
          Container(
            color: Colors.red,
          ),
          Container(
            color: Colors.blue,
          ),
          Container(
            color: Colors.green,
          )
        ],
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
          BottomNavigationBarItem(icon: Icon(Icons.paste), label: 'Report'),
          BottomNavigationBarItem(icon: Icon(Icons.settings), label: 'Settings')
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.white,
        unselectedItemColor: Colors.grey,
        onTap: onTapped,
      ),
    );
  }
}

I can navigate through views by pressing the view icons below but when I use the drag gesture to change the view, the selected view is not changed. How can I fix it?
Answer: You can include a listener on PageController to update the navbar item.
  late PageController pageController = PageController()
    ..addListener(() {
      setState(() {
        _selectedIndex = pageController.page?.toInt() ?? 0;
      });
    });

Or onPageChanged
onPageChanged: (value) {
  _selectedIndex = value;
  setState(() {});
},

Comment: yes you can use `physics: NeverScrollableScrollPhysics(),`
Comment: Thanks. Is it possible to disable gestures in page view changing?


Why is bII 7(b5) considered a dominant?

Question: I am using Ear Master for ear training and at the Chord Progression exercises, there is an exercise called "Various dominant-tonic combinations".
These are the chord progressions that are being played:

I can understand why VIIdim7 can be played as a dominant, but why is bII 7(b5) considered dominant?
Answer: bII7(b5) is a tritone substitution of the original dominant V7. Note that the roots of the two chords are a tritone apart, and the 7th of one chord equals the 3rd of the other chord and vice versa, so they share the most important chord tones.
Answer: This is a form of tritone substitution, and is considered one of the basic substitutions in jazz. The idea is that you replace a chord (typically a dominant chord) with one a tritone away. (Recall: a tritone, TT, is 3 whole steps, which is the distance of either an augmented fourth or a diminished fifth).
The reason this substitution works lies in the symmetry of the TT - it is exactly half an octave, so it is its own inversion. This lends it to a certain ambiguity. Consider the G7 chord (G B D F). There is a TT between the B (the 3rd of the chord) and the F (the 7th of the chord). But there is also a tritone between the F and the B, so we can reimagine the F as the third of some chord, and the B as its seventh (except now we have to call the B a Cb, to reflect that it is a fifth above the F).
The chord for which F is the 3rd and Cb is the 7th is Db7 (Db F Ab Cb), so we can use that chord. Its root happens to be a TT away from our original G7.
The deal with the (b5) being used just makes it even closer to the original chord. This would replace the Ab with Abb, which is the same pitch as G. So this gives us a very ambiguous chord: It's either a G7(b5) or a Db7(b5), but it has the same pitches both ways (just "spelled" differently):
(G B Db F) vs (Db F Abb Cb)
Comment: Another motivation for this substitution is the smooth chromatic progression in the bass. Your typical jazz progression is ii7-V7-IM7, where the bass jumps from 2 to 5 to 1. But with this substitution, the bass just walks down by half steps: ii7-bII7(b5)-IM7.
Answer: Tritone substitution is the reason, but it could also resolve to a Imaj.It doesn't have to be a Imaj7, the resolution is more marked to a standard major, as the leading note is there in the TTsub. moving to the root, rather than remaining sounded.(The B/Cb stated in Caleb's answer).

Why is bII 7(b5) considered a dominant?


delete view using popup in mvc3

Question: am using jquery code to popup my view.i want to delete data through this popup...But by using the following code,only popup is coming not performing deleting action,the jquery code is shown below.
$(document).ready(function (){
$('.del').click(function (e) {
    e.preventDefault();
    custom_confirm('pleaseNote:',
        function () {
            var sel = $(this).attr('href');

            $.ajax({
                url: '/default1/Delete/',
                type: 'POST',
                data: { id: sel },
                success: function (result) {
                    $(this).remove();
                }, error: function (result) {
                    alert("error");
                }
            });
        });
});
function custom_confirm(prompt, action, title) {
      $("#confirm").dialog({
        buttons: {
            'Proceed': function () {
                $(this).dialog('close');
                $('#confirm').dialog({ modal: true });
                action();
            },
            'Cancel': function () {
                $(this).dialog('close');
            }
        }
    });
}

})
and my view code is
@Html.ActionLink("Delete","Delete",new { id = item.studentID }, new { @class="del"})

and controller action is
[HttpPost]
    public ActionResult DeleteConfirmed(int id=0)
    {
        student student = db.students.Find(id);
        if (student == null)
        {
            return HttpNotFound();
        }
        db.students.Remove(student);
        db.SaveChanges();
        return RedirectToAction("Index");

Comment: ajax url = url: `'/default1/Delete/',` but method name: `DeleteConfirmed`
Comment: Decorate the Action Method like below. `[ActionName("Delete")] public ActionResult DeleteConfirmed(int id=0)`
Comment: Don't hardcode the url like this `url: '/default1/Delete/'` it should be like `"Url.Action("ActionName", "ControllerName", new {area = "AreaName"})"`
Comment: Like @PKKG said, if you use a hardcoded url like this in a partialview  ( I assume this is partial ) your url could get mangled. It will try to access /default1/default1/Delete, which doesnt exist.
Answer: Here you are selecting the href attribute:
var sel = $(this).attr('href');

and then passing it as id parameter in the AJAX request:
data: { id: sel }

Now looking at your DeleteConfirmed controller action, it expects that the id parameter be an integer value. But the href is not an integer. That's why your controller action is never invoked.
Also $(this) inside the action is not what you think it is.
So here's how you could proceed:
custom_confirm('pleaseNote:', function () {
    var url = $('.del').attr('href');

    $.ajax({
        url: url,
        type: 'POST',
        success: function (result) {
            $(this).remove();
        }, error: function (result) {
            alert("error");
        }
    });
});

Comment: or we could say `var sel = $('.del').attr('id');` ?
Comment: No, you can't say that. `$(this)` is the dialog so this will return `confirm`.
Comment: I've already checked. Have you seen where is the `action` parameter being called? Inside the `'Proceed'` button click of the dialog. And you know what `this` is referring to in this callback? Check it out.

delete view using popup in mvc3


Are there other similar badges in football?

Question: In Italy when a team win its 10th Championship (Serie A), they can put on the shirt a star so

Juventus FC has 3 stars (31 titles)
AC Milan 1 star (18 titles)
Inter Milan 1 star (18 titles)

This is not an official recognition but it is commonly recognized.
Are there other similar badges in football?
Comment: Possible duplicate of [Stars on football players' shirts](https://sports.stackexchange.com/questions/981/stars-on-football-players-shirts)
Comment: Not sure it's what you're looking for, but in Belgium the reigning champion has a golden league badge on their sleeve, whilst others have a silver one. But nothing to the amount of titles won, but some have stars added to their logo.
Answer: Yes, such an aspect is common amongst in football on both the club and national level.  While some leagues have official rules on the matter, such as the Champions League (where a "Multiple-Winner Badge", seen below, is rewarded for any club winning the Champions League five times or three consecutive), while others are far less formal.  It's not uncommon for these rules to be loosely enforced as well; the equipment regulations for FIFA competitions, section 18.2 states:

"Those Member Associations that have won the FIFA World Cup may put a symbol on the playing shirt representing this accomplishment and the number of times won.

However, Uruguay's national team wears four stars (for their two World Cup victories and their two Olympic victories before the World Cup began, which they recognize themselves as Championships), and are allowed to get away with it.
In the end, unless there is a codified rule in place and enforced, like the Champions League badge, many of the stars are placed on uniforms by the club at their own behest, depending on what titles a team feels are significant.  Occasionally this may adhere to an accepted standard such as the one mentioned in your question, but the club or nation does not necessarily have to take into account anything other than what they want to display on their kits.
Answer: Often those things are not really sanctioned by any authority, and are decided by teams themselves. For example, Glasgow Rangers in 2003 decided they will have five stars on their shirts to represent their 50 titles, while Celtic's single star symbolises their victory in the 1967 European Cup.
In Germany, they have a Verdiente Meistervereine system, where teams get one star for 3 titles, two stars for 5titles, three stars for 10 titles, and four stars for 20 titles. So, for example, Bayern won 28 titles so they can show four stars on their shirts.
Comment: Germany even has two systems. The DFL uses the one you mentioned exclusively for Bundesliga titles and the DFB allows a star (plus the number of titles on it) for winning any top flight German domestic league, so that includes the Oberliga and titles won before 1963 as well.


Seeding problem for a 3-way bracket

Question: I apologize in advance if this is not the correct place for this question. I'm going to be running a 36-person tournament in a certain activity, with the first two rounds being 3-way competitions (36->12->4).
My question is how to fairly seed these 3-way tournaments. Before the round of 36, I'll have a good idea of player strength, and the seeds will reflect that strength. I can either decide matchups by seed or by a rough estimation of player strength.
My idea was to give the highest strength of schedule to the 36th seed, the 2nd-highest to the 35th seed, etc. Is there any good method out there for figuring out matchups so that this can happen, or is there another method which would be appropriate for seeding such matchups?
Comment: What does "strength of schedule" mean?
Comment: By "strength of schedule", I mean the strength of the opponents that a player would have to face in the first round. For instance, if I had a matchup of the 1-13-36 seeds in the first round, and each player had strength (37-seed), the 1st seed would have schedule strength (37-13)+(37-36)=25.
Comment: What matters to the players (all of them, really) is presumably their chance of winning the first round. That depends on how the strength of the other two combines into win-probability.
Comment: Re-reading your answer makes it more clear. I think the most important thing here is whether or not the top-players are more evenly matched than the bottom players. Thanks for the help!
Answer: Usually, scheduling based on seeding seems to be set up to improve the chance to retain the better players.
Here's one obvious possibility:
Going by seed, if we want to maximize the chances of keeping the top few seeds, we want the highest seed they face to be low and within that, the average seed they face to be fairly low.
One approach: Consider that the second-best player in each group is the 'main danger' to the top seeds. We can hold the average of the seedings of the 2nd and 3rd ranked player in each group constant, while keeping the lowest of the second-ranked seeds for the top seed, the second-lowest second-ranked player for the second seed and so on:
<code> 1 24 25
 2 23 26
 3 22 27
 4 21 28
 5 20 29
 6 19 30
 7 18 31
 8 17 32
 9 16 33
10 15 34
11 14 35
12 13 36
</code>
This has the advantage that the top second-ranked players also have a reasonable chance to go through (it's not that much worse being 13th seed than 12th), so the difficulty of the draw for the top 2/3 of players seems to increase relatively smoothly. It might be particularly appropriate for the top 2/3 of players if the strengths in the bottom third are more nearly even than in the top groups (though the bottom-ranked players might then argue that the schedule for 36 is easier than for 25).
You could flip the third column top to bottom, but it's not clear to me that it's better. This would make the progression from easy to hard more rapid as you go down the first column of seed (weighting it more strongly to the top few seeds):
<code> 1 24 36
 2 23 35
 3 22 34
 4 21 33
 5 20 32
 6 19 31
 7 18 30
 8 17 29
 9 16 28
10 15 27
11 14 26
12 13 25
</code>
This could be more suitable, for example, if the strength in the bottom third goes down more quickly than in the top groups (if the top seeds were more nearly evenly matched than the lowest-ranked 12 players were). If you want to focus on the task for the bottom 12 players, this makes the progression in difficulty more clear for them.
If you have some model for the chances of going through that might give you a better idea of which of those schedules will have the best chances of giving outcomes that are 'desirable'.
Comment: This is close to what I'm looking for, but it would seem unfair to the 25 seed.
Comment: I don't see how. Can you explain? Note in particular, that in the top schedule I give, the 25th seed has only a fractionally harder task than the 24th seed, so if it is unfair on 25, it presumably must also be unfair on 24.
Comment: Using the top model: If we expect the #1-#2 gap to be greater than the, say, #35-#36, I would much rather be the #36 than #25. I think we're talking about different things: for the top 2/3 both models work fantastically, while things are different for the bottom 1/3. However, I'm not sure it is possible to make a perfect schedule for the entire population of players.
Comment: On thinking about it, I can see that if the strengths flatten out more as you go down, #25 might complain that #36 has a slightly easier task. And then #24 might have a similar complaint. The second schedule might suit you better from several viewpoints.

Seeding problem for a 3-way bracket


How to compute $\gcd(d^{\large 671}\! +\! 1, d^{\large 610}\! −\!1),\ d = \gcd(51^{\large 610}\! +\! 1, 51^{\large 671}\! −\!1)$

Question: Let $(a,b)$ denote the greatest common divisor of $a$ and $b$.
With  $ \ d = (51^{\large 610}\! + 1,\, 51^{\large 671}\! −1)$
and $\ \ x \,=\, (d^{\large 671} + 1,\, \ d^{\large 610} −1 )$
find $\ X = (x\bmod 10)$
I used $y=51^{61}$ to reduce $d$ to  $d=(y^{10}+1,y^{11}-1) = (y^{10}+1,y+1)$.
What should I do now?
Comment: Were you previously taught any method to find gcds of the form $\,(a^j+1,a^k-1)$?   Does "trick" mean a method of computing said gcd $\!\bmod 10$ that is (much) simpler than computing the gcd then reducing it $\bmod 10$?
Comment: As a further hint, note that if $\ y=x^{61}\ $, then $\ x^{610}+1= y^{10}+1\ $ and $\ x^{671}-1=y^{11}-1\ $.
Comment: The reduction to the case of coprime exponents in the prior comment of @Ionza works generally, e.g. see [this answer](https://math.stackexchange.com/a/2983281/242). We can handle this problem in a very similar manner as I do there. See also [this answer](https://math.stackexchange.com/a/876013/242).
Comment: Yeah i want to know the method for computing $(a^{j}+1,a^{k}-1)$ I mean how to derive this formula @BillDubuque
Comment: And I do need to find d at first @BillDubuque
Comment: You can use the method in the answers I linked.
Comment: I have reduced the given d to $y=x^{61}$ then d reduced to this  $d=(y+1,y^{10}+1) $ what should I do know? @BillDubuque
Comment: @q123 Follow the linked answers. Recall $\,(a,b) = (a,\,b\bmod a)\,$ so $\,(y+1,f(y)) = (y+1,f(-1))\,$ by $\bmod y+1\!:\,\ y\equiv -1\,\Rightarrow\, f(y)\equiv f(-1),\,$ for any polynomial $f(y)$ with *integer* coeff's.
Comment: I posted an answer with a full proof (which uses a common theorem $\bf T1$ for both gcds).
Comment: Were any of the answers helpful?  If you need help understanding them then you can pose questions in comments on the answers.
Answer: First note: $\gcd(a^m \pm 1, a+1)=\gcd((a^{m}\pm 1)-(a^{m}+a^{m-1}),a+1) = \gcd(a^{m-1}\mp 1, a+1)$
And via induction $\gcd(a^{m}+1, a+1) = \gcd(2, a+1)$ if $m$ is even.  $\gcd(a^{m} - 1,a+1) =\gcd(0, a+1) = a+1$ if $m$ is even.  (And the opposite results if $m$ is odd).
so if we let $a= 51^{61}$.
Then $\gcd(51^{610} + 1, 51^{671} - 1)=$
$\gcd(a^{11}-1,a^{10} + 1)=$
$\gcd((a^{11} -1)-(a^{11} + a), a^{10} + 1) =$
$\gcd(a^{10} + 1, a+ 1) =  2$
...
Let $b = 2^{61}$ and so
$\gcd(2^{671}+1, 2^{610} -1)= \gcd (b^{11} + 1, b^{10} -1)=$
$\gcd((b^{11}+1)-(b^{11}-b), b^{10}-1)=\gcd(b^{10}-1,b+1)=b+1= 2^{61}+1$
Answer: As in the proofs here and here, we reduce to coprime powers then apply the $\rm\color{#90f}{Euclidean}$ algorithm.
$a = 51^{\large 61}\Rightarrow\, d = (a^{\large 11}-1,\,a^{\large 10}+1) = (a\!+\!1,2) = 2\,$ by $\,\bf T1\,$ below, with $\ s = -1$
$a\, =\, d^{\large 61}\Rightarrow\,x = (a^{\large 11}+1,\,a^{\large 10}-1) =\, a\!+\!1 = d^{\large 61}\!+1 = 2^{\large 61}\!+1\,$ by $\,\bf T1,\,$ $\,s = 1$
${\bf T1}\,\ (s,a)\! =\!1\, \Rightarrow\, (a^{\large 11}\!+s,\,a^{\large 10}-s)\, = (a\!+\!1,\,1\!-\!s).\  $ Proof: $\,\rm\color{#90f}{using}$ $\ (x,y) = (x,\, y\bmod x)$
$\begin{align} (\color{#0a0}{a^{\large 11}}\!+s,\,{a^{\large 10}}\!-s) &= (\color{#0a0}{s}(\color{#0a0} a\!+\!1),\, {a^{\large 10}}\!-s)\ \ \ \,{\rm by}\ \ \bmod a^{\large 10}\!-s\!:\,\ a^{\large 10}\!\equiv s\,\Rightarrow\, \color{#0a0}{a^{\large 11}}\!\equiv a^{\large 10}a \equiv \color{#0a0}{sa} \\[.2em]
&= \ \ \ \, (a\!+\!1,\ \,\color{#c00}{a^{\large 10}}\!-s)\ \ \ \ {\rm by}\,\ \ (s,\,a^{\large 10}\!-s) = (s,a^{\large 10})=1, \ \, {\rm by}\,\ \ (s,a) = 1\\[.2em]
&=\ \ \ \  (a\!+\!1,\ \ \  \color{#c00}1\, -\, s)  \ \ \ \ {\rm by}\ \ \bmod a+1\!:\ \ \ \  a\equiv -1\,\Rightarrow\, \color{#c00}{a^{10}}\equiv (-1)^{10}\equiv\color{#c00} 1 \\[.2em]
\end{align}$
Comment: Thus $\,X = (2^{\large 61}\!+1\bmod 10) = 3,\ $ by $\ 2^{\large 61}\! \bmod 10 = 2\big((2^{\large 4})^{\large 15} \bmod 5\big) = 2\ \ $
Answer: $$51^{671}=51^{610}\times 51^{61}-1=(51^{610}+1)51^{61}-(51^{61}+1)$$
$$(51^{61}, 51^{61}+1)=1$$
So we may write:
$$d=(51^{610}+1, 51^{671}-1)=(51^{610}+1, 51^{61}+1)$$
$$51^{61}+1=52 k=2\times 26 k$$
$$51^{610}+1=52 k_1 +2=2(26 k_1+1)$$
$$(26, 26k_1+1)=1$$
However $k$ and $26 k_1+1$ may have common divisors. If we assume $d=2$ then we have:
$$x=(2^{671}+1, 2^{610}-1) $$
$$2^{671}+1=(2^{610}-1)2^{61} +2^{61}+1$$
$(2^{61},2^{61}+1)=1$, Therefore:
$$x= 2^{61}+1$$


One note of chord not part of scale

Question: I am currently analyzing a track by Deadmau5, and am almost positive that it is written in F# minor. The melody notes are all within that scale, and pretty much all of the chords are too. However, there is one chord where the root note is not part of the scale.
Can anyone help with what's going on here? I've attached a screenshot below with a MIDI chord progression. You'll see that the 2nd chord has a root note of G, but the rest of the notes within it are from the F# minor scale.

I want to ensure that I am continuously improving my music theory knowledge. Reason being, if I was to write my own track, I would completely avoid using a chord like this, because it goes against what I know. The chord sounds great, so that's why I am confused as to why Deadmau5 chose to use G as the root note.
Comment: That picture is twisting my melon, man. The "white & black" stuff on the left isn't any  kind of keyboard & worse still, the letters on the notes don't correspond to the actual keyboard image underneath the editor area. My brain hurts!
Comment: Sorry, but that adds no additional clarity. The 'grey-blue' bars are the white notes of a piano keyboard. The 'grey-grey' bars are the black notes. The 'blue-blue' notes on top have note names in them which do not correspond to that 'keyboard' at all. The weird black & white 'keyboard' on the left is nothing I recognise as musical in any sense at all.
Comment: It's a midi keyboard in Ableton Live. The opaque blue bars are there to indicate if that piano key is in the F# minor scale. If the piano key is not, its just gray.
Comment: @Tetsujin - Huh? The black and white "keyboard" on the left is actually a pretty good attempt at a keyboard, except F# is unfortunately coloured cyan. The long cyan bars all have note names that make sense.
Comment: Could you add the name of the track to the question?
Comment: @Dekkadeci - that makes vaguely more sense… kind of, but not much. Why doesn't that then line up with the other background keyboard in the main editor?
Comment: @Tetsujin - I have to assume that the "other background keyboard" is not a representation of a keyboard at all - the cyan-grey background bars all correspond to notes in the F# Aeolian scale, while the grey background bars are all for notes not in that scale.
Comment: @Dekkadeci - idk which app it is & I cannot figure out the reasoning behind doing it that way. That first F♯ just looks like an A to me, with the rest transposed commensurately. It hurts my brain. Even now knowing the keyboard on the left has the F♯ in cyan doesn't help me read it at all as a keyboard.
Comment: @Tetsujin Imagine your right hand on the "keyboard", rather than your left (as I did first). Higher on the screen is higher notes.
Comment: @Peter. This is not new to me, honestly. I've been looking at key editors since the late 80s ;)) I've just never seen one with two conflicting keyboards, in indeed one with so little colour differentiation as to what I'm supposed to be looking at.
Answer: I'd love to find who it is spreading this 'theory' that notes need to conform to the particular key or scale a piece is in!
When learning about music theory initially - in the early stages - it makes some sense to stick to diatonic notes, those from the scale used in the key of the relevant piece. However, that 'rule' gets 'broken' fairly quickly as one advances. Chromatic notes, chords, or borrowed notes, chords abound in all kinds of music. The word chromatic means coloured, and those notes/chords add some colour to what could otherwise be quite a mundane piece.
Theory says that borrowing from other keys is one reason: keep the same root note, change from minor to major, major to minor, use the notes/chords from modes using the same root/tonic. Or introduce V/V, V/ii, V/vi etc. to add more colour.
If the key is indeed F♯ minor, having a G note would indicate the theory that the mode has changed, either using the Phrygian or Locrian mode of F♯. My money's on Phrygian. Which actually emanates from the notes of D major.
Comment: @DanZuzevich - there's only 12 notes - excluding what Blues players use! Each and every one can be used anywhere you like, (once you know what you're doing!), and jazz players use this 'loophole' all the time. But you'll find (are finding) that in every genre, the 'rules' get broken. Keep looking, they're not far away!
Comment: @LaurencePayne - I'm never saying diatonic is 'correct', I'm saying diatonic is the datum or start point. Which it is. Intervals are named using the major scale names, basically, and we rarely mention that a chord is 'major' - it's a given.
Comment: @Tim You just WON'T let go of this idea that diatonic is correct, everything else is a 'loophole' or 'breaking the rules' will you!
Comment: If you are curious, go to YouTube and type in, "Deadmau5 16th hour". Fast forward to about 2:03, this is what I am talking about. You'll hear the chords playing with some type of string, violin cello or whatever. You'll be able to hear the melody as well.
Comment: Thanks Tim. I'm still new to music production, so that's probably why I thought I needed the notes to conform to the key or scale. I guess that is my next step, where I need to find some good resources to go beyond the basics. There is a ton to learn.
Comment: @LaurencePayne - I'd love to. But it seems that folk are Hell-bent on having 'rules' that explain everything. They're not happy to just say - 'it sounds good, it works, leave it at that', so we'll keep on having all these and similar questions, and my answers are there in attempts to supply reasons. It's a Human trait to ask 'why?', but sometimes theoretical answers will remain theoretical for ever...
Comment: Some other people on here think that it is actually b minor. If it's b minor, then the G note that was causing my problem disappears, as the G is part of the b minor scale. When I check the melody that plays over the chords, all of those notes fit into the b minor scale as well.
Answer: Judging only from the notes I can see here, there are two possibilities:

Either the entire song is not F# minor, but F# phrygian.
The song is still F# minor, but the second chord is actually "borrowed" from the phrygian scale. This is a technique, which is called "borrowed chords". There, you have some chord progression, however you like it, but at one point, you go out of scale and use a chord from another scale. Same root note, but different scale.

You should look up this technique. There are multiple tutorials online. They can explain it better than me, here in few sentences.
Comment: Thanks! I checked out that scale, and indeed it contains a G note. I believe this solves my conundrum. Deadmau5 likes open chords, typically with a perfect fifth, then with the last note uses a note from the scale at a higher octave than the others.
Answer: Just from the progression this looks more like B-minor to me. The first F#-minor chord could be interpreted as a tonic cause Dmaj7 contains a F#-minor chord. Than it ends on a regular Bm chord.
Comment: I think you are right. Someone else said that it might be B-minor below as well. I checked, and indeed all of these notes fit into the scale.
Comment: Check out my last two comments posted under Tim's answer.
Answer: 'What is going on here' is that a piece of music in F♯ minor contains a chromatic note.  A normal, unremarkable, common occurrence.
As @Tim says in his answer, there is no rule that all notes/chords in a piece of music must conform to one scale.
But then @Tim's answer gets far too complicated.  As do so many answers to this topic.   And the complication seems to stem from a deep-seated conviction that, really, everything SHOULD conform to one scale and, when something doesn't, it needs to be justified as the key/mode temporarily changing, as a 'borrowing' (see the underlying assumption that we should always be conforming to SOME scale?) or as a daring 'breaking of the rules'.
Much music has a key centre.   Not all music.  Not even all rock/jazz music.  But a lot of music does.   And a lot of music uses functional harmonies - the sort that can be analysed as tonics, dominants etc.   But even when playing the tonal/functional game, CHROMATIC NOTES/CHORDS ARE FINE!
Sometimes they're just an 'in-between' transition.  Stepping on the lines between the paving stones.  Same pavement, same journey, just not hitting each slab dead centre.    Sometimes they're just a change of colour.  The classic example is the IV chord in a major key.  Often modified to iv, the same triad but minor. No excuse needed.
And sometimes a chromatic chord DOES set us off on a journey to another key, another 'home' scale.  If that iv was followed by ♭VII7 and then ♭III (starting in C major that would be Fm, B♭7, E♭) there might be some use in considering it as 'borrowed' from E♭ major.  But otherwise, let it be just a chromatic chord for goodness' sake!
Where did this misapprehension come from?  Probably Berklee, in the 1960s. The Chord=scale thing which replaced melodic composition/improvisation with a 'this chord allows this scale' approach.
To be fair, Berklee itself admits "Using the chord-scale approach gives improvisers (especially less proficient ones) greater melodic and rhythmic mobility..." (I suggest reading the whole article)
https://www.berklee.edu/berklee-today/summer-2000/Chord-Tone
They don't pretend chord-scale is the Answer to Life, The Universe and Everything.   But it's just such an easy way to present music to a beginner, particularly one who is more fluent with chord shapes than with notation, and who sees improvisation as their primary aim rather than reading and performing the repertoire (so we're largely talking about guitarists rather than band kids :-) )
OK, rant over.   But it is important to keep reminding newcomers that 'being in a key' is a framework not a restriction.
Comment: Appositely stated! I agree with all. But not tackled the question itself...
Comment: @Tim You want an 'answer' as well as a discussion?  OK, I'll add it to the top of my answer.
Comment: Indeed. Cf. Chopin, Rachmaninoff, Tatum, et al. :)
Answer: If I read the notation correctly, that seems to be the sequence F#m, G, A, Bm.
It feels more like the key is B minor to me - it's more or less a reversal of the Andalusian Cadence.
Comment: I think you are right actually.
Comment: Check out my last two comments posted under Tim's answer.
Answer: So the notes of the chords are (bottom note is doubled an 8ve down:
<code>    (This is not a series of guitar chords, please stop converting them SE!)

    A   B   C#  D
    C#  D   E   F#
    F#  G   A   B
    ----------------
    F#m G   A   Bm
</code>
Or F# minor, G major, A major and B minor.
This sounds good mainly because of the voice-leading. If you think of each part as an individual voice in a choir, (top, middle, bottom), you can see that they all smoothly connect, and none of the voices overlap.
You're correct that the piece seems to be in F# minor ... as the sequence starts on F# minor and goes to B minor - but the chords in between don't have to be strictly notes from the F# minor scale. They're just passing chords on the way to a destination.
You could use these "rules" to try different options:

Start on F# C# A, end on B F# D.
Smoothly connect the voices from one chord to the next

So any of the following options could also work (and there are many other possibilities). Although some of the harmony is quite distant from the key of F# minor, it's the smooth voice leading that makes it work musically, while also creating some interesting sounds. Try playing these examples and hear what they sound like.
<code>A   B   C   D
C#  D   F   F#
F#  G   A   B
--------------
F#m G   F   Bm

A   C     Db   D
C#  D     F    F#
F#  G     Bb   B
-----------------
F#m Gsus4 Bbm  Bm

A   B    C    D
C#  D    F#   F#
F#  F#   G#   B
-----------------
F#m Bm   G#7  Bm
</code>

One note of chord not part of scale


Erro com arrays em Java

Question: Alguém poderia me dizer o que tem de errado nesse código? O resultado é sempre o 1º número antes do espaço, mas tem que ser a soma de todos os números da array.
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
    @SuppressWarnings("resource")
    Scanner entrada = new Scanner(System.in);
    String x = entrada.next();
    String array[] = x.split (" ");
    int soma = 0;
    int resultado[] = new int[array.length];
    for (int i = 0; i < array.length; i++) {
        resultado[i] = Integer.parseInt(array[i]);
        soma = soma + resultado[i];
    }
    System.out.println (soma);
  }
}

Comment: Sempre 1? não não! acabei de fazer um teste e deu 2. Dá sempre o primeiro número da sequência.
Answer: Troque isso:
String x = entrada.next();

por isso
String x = entrada.nextLine();

O seu código não está funcionando, pois next() retorna o próximo token completo. Nesse caso, o 1o número antes do espaço. Já o nextLine() retorna todos os caracteres até o caracter de quebra de linha.
Explicação mais detalhada
Um token completo, retornado pelo next(), é um token que atenda o padrão de delimitação especificado no Scanner. Como não foi especificado nenhum padrão, então o espaço entre os números fica sendo um delimitador.
Por isso, ao digitar 1 2 3 e usar o next(), ele retorna o caracter 1, pois o espaço após o número 1 serviu de delimitador.
Já no caso no nextLine um padrão de linha é utilizado. Veja a função nextLine() retirada do código fonte da classe Scanner.
public String nextLine() {
    if (hasNextPattern == linePattern())
        return getCachedResult();
    clearCaches();

    String result = findWithinHorizon(linePattern, 0);
    if (result == null)
        throw new NoSuchElementException("No line found");
    MatchResult mr = this.match();
    String lineSep = mr.group(1);
    if (lineSep != null)
        result = result.substring(0, result.length() - lineSep.length());
    if (result == null)
        throw new NoSuchElementException();
    else
        return result;
}

Comment: +1 - Muito boa a explicação, parabéns!
Answer: O que está acontecendo é que o entrada.next(); retorna a práxima palavra, mas no contexto dessa aplicação seria entrada.nextLine();
nextLine pega tudo que foi digitado.

Erro com arrays em Java


Spring MVC cannot find JSPs when deployed into embedded Jetty 8 server

Question: I'm trying to run embedded Jetty server and deploy Spring MVC application into it, but there is a problem of resources mapping - particulary I can't map spring mvc controller so that it can find my JSPs.
Configuration:

jetty-8.1.8.v20121106
Spring 3.2

Jetty Server Configuration:
<code>    Server server = new Server();

    ServletContextHandler context = new ServletContextHandler();
   //WebAppContext context = new WebAppContext();
    context.setBaseResource(Resource.newClassPathResource("webapp"));
    context.setClassLoader(Thread.currentThread().getContextClassLoader());
    context.setContextPath("/");

    AnnotationConfigWebApplicationContext webAppContext = new AnnotationConfigWebApplicationContext();
    webAppContext.register(WebFaceSpringConfiguration.class);
    webAppContext.setServletContext(context.getServletContext());
    webAppContext.setParent(applicationContext);

    context.addServlet(new ServletHolder(new DispatcherServlet(webAppContext)), "/");

    server.setHandler(context);
    server.setConnectors(jettyConnectors);
</code>
Folder webapp is in classpath, but in such configuration I have an error Problem accessing /WEB-INF/pages/main-page.jsp (which is actually located under webapp). So controller method is invoked, but view cannot be resolved.
I tried to use WebAppContext and wildcard mapping for Spring Dispatcher Servlet (/*), but it did not help - controller mapping is ignored or JSP cannot be found.
Comment: Can you post your error?
Answer: You need to specify a viewresolver, normal way looks this in xml
<code> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/pages/" p:suffix=".jsp"/>
</code>
Comment: actually I have one. And it looks active, since my controller method returns "main-page" view name, but error contains full path to jsp file.
Comment: @viator I am not familar with jetty... sorry can;t help anymore


Multiple MongoDB instances on same server

Question: We set up a MongoDB development server on CentOS 6.3 and were able to separate different projects by using separate config files and rc scripts.  Now we're looking at setting up a MongoDB production environment.
I've read that it is not recommended to host multiple instances of MongoDB on the same server in production.  Does that mean each project will need its own production MongoDB environment?
These projects are not very "big" and so do not require a lot of resources, so it feels like we're jumping the gun by giving each its own host.  Perhaps we just need to get our heads out of the RDBMS world.
We will be monitoring our development server to see how it fares, but I'm looking for some insight and some of your own personal experience to supplement what I've read.
Answer: The reason Mongo/10Gen recommends against running multiple instances of Mongo on the same system has to do with resource availability assumptions. The mongod process assumes it's the only major tenant of the system, and running two such side-by-side will lead to overall worse performance than just running one mongod just with two databases.
Mongo is quite capable of running multiple databases under a single mongod process. These are discrete databases, just under a single master process. Each database handles its own authentication, which gives you separation.  You'd run multiple mongod processes if you need different mongo versions for your products.
I'm not enough of an RDBMS DBA to know the best-practice arguments behind separating products by discrete database-binary processes, so I can't refute/assuage/talk-down each point. But as I understand it, accepted practice in Mongo environments is to have a separate database per product.
Comment: What about mixing a config server process and an arbiter on a single machine? I'm planning out a setup with 2 replica sets, each with 2 nodes and an arbiter and don't want t separate machine for each arbiter and config server if possible.
Comment: @NicholasTolleyCottrell The [Mongo docs](http://docs.mongodb.org/manual/tutorial/add-replica-set-arbiter/) on arbiters says it right there: arbiters have minimal requirements. They can safely run along side a config server.
Comment: in my case , i had to run 3 instances on a single server , because it's recommended to have a replica set with at least 3 members , 2 real and 1 voter . So that's how we rolled for months before new servers were available to us .


Sierpinski triangle formula: How to take into account for $0^{th}$ power?

Question: The formula to count Sierpinski triangle is $3^{k-1}$ .It is good if you don't take the event when $k=0$.But how can you write a more precise formula that takes the $k=0$ into account which gives $3^{-1}$? Just to note, I did figure out the equation myself as I learned it to write a program although the equation is available online.I am doing it purely for fun and out of curiosity, no homework question.
Add-on:
I tried to draw a tree to find the relation but still the nodes start to show pattern from level 2.
Comment: What does "count the Sierpinski triangle" mean?
Comment: number of triangle.I'm making a binary tree of it and will soon upload that too.
Comment: Um, tack on the conditional that sierpinski triangle has a positive integer of degree.  Do you worry if k is fractional?  Irrational?
Comment: So that means we cannot imagine an event when we don't have any triangle?If k=0, shouldn't that be 0?The number of triangle since we are not doing any iteration?There has to be a way I believe.
Comment: It's perfectly possible that the formula is "$3^{k-1}$ when $k\ge1$ and $1$ when $k=0$". Math happens.
Comment: Yes that would be then conditional, thanks!I took it for literal sense.Give it in answer section so that I can accept.
Answer: As I understand it, you want a formula to count the number $n$ of triangles that remain at level $k$ in the standard trema construction of the Sierpinski triangle. If we say that level one is the initial triangle, then that leads to a sequence of images that looks like so:

We can then clearly see your formula: $n=3^{k-1}$. (Recall that $3^0=1$, so that $k=1$ yields the correct result.) This depends, however, on where you choose to start counting. I would personally prefer to call the initial triangle level zero but, really, this is somewhat arbitrary.
One other comment: I'm not sure why you're using an unbalanced binary tree to model this situation. It seems to me that a balanced ternary tree (where each node has three children) would be more natural.
Comment: I'm putting information in inorder binary search tree traversal that visits left child first to input information and I'm trying to draw a relationship between each level and and k.I was saying that level zero would give 3^0-1, which is 3^-1. But your explanation  is spot on though.


Dismissing the UIPicker after user is done using it in a UITextField?

Question: I have a UIPicker that would like to be shown only when a user selects a specific UITextfield. The problem I am having is this:
I have added a working picker called myPicker and a text field called field.
I have looked at several questions asking this but they are mostly about getting the picker to pop up instead of the picker, I have not come across with one with the right answer for me.
I was able to get myPicker to show up by changing the text field's inputView but now my problem is that I cannot figure out a way to add an accessory toot bar with perhaps a "Done" button.
For testing purposes I added a simple button with the action :
self.myPicker.hidden = YES;

[_field resignFirstResponder];

But this is giving me a weird, non animated look that just doesn't feel right.
Here is my code for this:
#import "ViewController.h"

@interface MixerHPViewController ()
@property (weak, nonatomic) IBOutlet UILabel *testLabel;
@property (weak, nonatomic) IBOutlet UITextField *field;
@property (weak, nonatomic) IBOutlet UIPickerView *myPicker;
@property (weak, nonatomic) IBOutlet UITextField *field2;
- (IBAction)takeButton:(id)sender;

@end

@implementation ViewController

@synthesize tempList;

// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return [tempList count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return [tempList objectAtIndex:row];
}

- (void)pickerView:(UIPickerView *)pickerView
      didSelectRow:(NSInteger)row
       inComponent:(NSInteger)component {

   CGFloat chosenValue;

    switch (row) {
        case 0:
            chosenValue = 0.0000765;
            break;
        case 1:
            chosenValue = 0.0000123;
            break;
        case 2:
            chosenValue = 0.0000982;
            break;
        case 3:
            chosenValue = 0.0000933;
            break;
        case 4:
            chosenValue = 0.0000058;
            break;
        case 5:
            chosenValue = 0.0000121;
            break;
        case 6:
            chosenValue = 0.0000132;
            break;
        default:
            chosenValue = 0;
            break;
    }

NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    formatter.minimumFractionDigits=7;

self.testLabel.text = [formatter stringFromNumber:@(chosenValue)];

}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    tempList = [[NSArray alloc] initWithObjects:@"OPTION A",@"OPTION B",@"OPTION C",@"OPTION D",@"OPTION F",@"OPTION G",@"OPTION H", nil];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {

    if( textField == self.field ) {
        self.field.inputView = _myPicker;

    }
}

- (IBAction)takeButton:(id)sender {
    self.myPicker.hidden = YES;
    [_field resignFirstResponder];
}
@end

Answer: You can dismiss it with animations:
 - (IBAction)takeButton:(id)sender {
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationDelay:1.0];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];

    //you can customize this
    self.myPicker.frame = CGRectMake(-100, -100, 100, 200);

    [UIView commitAnimations];

    [self.myPicker removeFromSuperview];
    [_field resignFirstResponder];
   }


Java Regular Expression for "mysql_free_result($myvar);" - Netbeans

Question: I'm using netbeans and I'm working on a project in php.
I need to use the find tool, looking for all the point in the project where the following string can appear
<code>  mysql_free_result($myVarName);
</code>
$myVarName can be any name allowed in php.
Then I've to replace this string with
<code>  mysql_free_result($myVarName); MyAdditionalString
</code>
To observe that $myVarName can be different for diffents points in the scripts, so the replace had to replace with correct var name.
Netbeans find tool can use a regular expression for search pattern, so what I've to write to find this points?
Comment: Is your question how you should write a regex in netbeans to refactor a variable name, that just happens to be in a PHP-file?
Comment: my question is about to write a regular expression that I can use in the search tool of netbeans.
This regular expression need to match "mysql_free_result($myVar)"
So I can use the search and replace function to append something after this instruction
Comment: That's more or less what I wrote. :) Anyway, you should remove the "PHP" tag since this question is all about regex and not PHP itself.
Comment: Yes, but instead of refactor is about to append :-)
Comment: neither is the topic about java
Answer: Search with
<code>         mysql_free_result\(\$[a-zA-Z]+\);
</code>
and replace with
<code>        $0 myAdditionalString
</code>
Thanks to @Jakumi for the suggestion
Comment: if you add an `;` at the end, OP could replace with `$0 MyAdditionalString`. however, php vars can contain numbers and underscores as well ... see http://wiki.netbeans.org/FaqEditorBackReferences
Comment: Yes it's correct but in my case no numbers and underscores appears in a variable's name


How do I replace a plugin?

Question: Let's say that I want to replace the block_content_type plugin of the core block_content module to ad some features while not having to rewrite a whole module to achieve this.
It is very easy to replace a service by providing your own service definition with the same key as the to-be-replaced service. How do I replace a plugin with another one?
Answer: To answer the general question how do you do that with plugins: Each plugin type is managed by a plugin manager. You can list all plugin manager classes with this console command:
drupal debug:plugin

Most plugin managers provide an alter hook to change the plugin definitions. Look in the plugin manager class method __construct for a line with $this->alterInfo():
public function __construct(...) {
  ...
  $this->alterInfo('example_plugin_info');

In this alter hook you can replace the class of plugins managed by this plugin manager:
function mymodule_example_plugin_info_alter(array &$info) {
  if (isset($info['foo_plugin'])) {
    $info['foo_plugin']['class'] = '\Drupal\mymodule\Plugin\ExamplePlugin\MyCustomFooPlugin';
  }
}

You can check the result by executing the same console command, now providing the plugin type as parameter, to list the plugins of this type and their classes:
drupal debug:plugin example_plugin

Entity type classes
About your specific question, the plugin manager for entities is EntityTypeManager (not listed by the console command because it doesn't use the standard service name scheme). It provides an alter hook to alter entity types as well, so if you are referring to the bundle entity type class of Block Content, then you can change it here:
/**
 * Implements hook_entity_type_alter().
 */
function mymodule_entity_type_alter(array &$entity_types) {
  $entity_types['block_content_type']->setClass('...');
}

Using Drush and Devel instead of Drupal Console to debug plugins
Devel adds some useful commands to Drush, one of them is to debug services, which you can filter to list only plugin managers:
drush devel:services plugin.manager.

After you've found the service ID of the plugin manager you can list the plugins discovered by this plugin manager:
\Drupal::service('plugin.manager.example')->getDefinitions();

Run this command from a drush php shell to get a nice output.
For the plugin manager class name look up the service ID in Devel UI (/devel/container/service).

How do I replace a plugin?


JavaScript callbacks - issues with accessing individual elements of a returned array

Question: Self-taught and struggling a little bit to understand how callbacks work.
My callback handling function cannot access individual elements of the array i.e:

"console.log(ResultsArray)" works
"console.log(ResultsArray[1])" returns "undefined"

However, "ResultsArray[1]" works perfectly fine when executed in Firefox console directly.
What am I doing wrong?

Comment: What exactly does `ResultsArray` return, does it return an array structure and are there any items in that array?
Comment: ResultsArray
[…]
0: Array [ {…}, {…}, {…}, … ]
1: Array [ {…}, {…}, {…}, … ]
2: Array [ {…}, {…}, {…}, … ]
3: Array [ {…}, {…}, {…}, … ]
length: 4
Answer:
"console.log(ResultsArray)[1])"

Should be console.log(ResultsArray[1]), bad parentheses.
Comment: console.log(ResultsArray[1]) produces  "undefined"
Answer: First, if you are going to use callbacks, use error-first callbacks like this:
const results = [];

function main(cb) {

  (function recursive(counter) {

    if (counter >= ArrayOfTickers.length) {
      return cb(null);
    }

    const url = `https://api.iextrading.com/1.0/stock/${ArrayOfTickers[counter]}/time-series`;

    fetch(url)
    .then(function (response) {
      return response.json();
    })
    .then(function (data) {
      results.push(data);
      recursive(counter + 1);
    })
    .catch(cb);

  })(0)

}

main(function (err) {
  if (err) throw err;
  console.log(results)
});

// but it might be better to use promises like so
function main() {

  const recursive = function (counter) {

    if (counter >= ArrayOfTickers.length) {
      return;
    }

    const url = `https://api.iextrading.com/1.0/stock/${ArrayOfTickers[counter]}/time-series`;

    return fetch(url)
    .then(function (response) {
      return response.json();
    })
    .then(function (data) {
      results.push(data);
      return recursive(counter + 1);
    });

  };

  return recursive(0);

}

main().then(function(){
  // check results
})
.catch(function(err){
   // handle error
});

Comment: If your ArrayOfTickers varied in length, and if it could be 0 in length, to be safe, you'd want to use `return Promise.resolve(null)` instead of just `return`, just to ensure you always return a promise.


Selection of sample on X or Y

Question: In an OLS regression where Y is the dependent variable, X the independent variable and u the error term:
Selecting our sample on Y creates a bias:
If we have a Y variable that is zero mean and we only run our regression if y>0 our bias will be E(u|u>-xBeta)
What about when we select our sample on X ?
So we have a similar zero mean X variable, and we cut at x>0.
Does it create a bias ? Why not ?
Comment: Well it depends. If Y is a linear function of that X variable, then it certainly will affect which Y are selected, for instance.
Comment: That was my initial thought as well. But if I run a simulation in which I clearly define x as a  random variable and u as a 0 mean random variable and then define y=x+u: Any regression selecting on x will yield the expected coefficient of 1, while any regression selecting on y will not.
Answer: If you select on y you will more likely drop observations with positive errors, especially if the predicted value is high. So the negative errors will  in your observed dataset be more influential when the predicted y is high, and they will pull the regression line to a flatter trajectory.
A selection on x will not prefer observations with a particular error, so no bias occurs.

Selection of sample on X or Y


Perlin Noise in Python: Noise Values Compacted, Need Help Forming Sinusoidal Pattern

Question: I'm currently working on a project involving Perlin noise generation in Python. I've implemented the Perlin noise generation using the noise library and generated different types of noise values (cave, land, hill, mountain) within a chunk using a combination of these noise types.
However, I'm facing an issue with the generated noise values. Instead of the noise values forming a smooth, sinusoidal pattern, they seem to be compacted and lacking the desired variation. As a result, the final noise representation doesn't display the expected terrain features I'm aiming for.
Here's a snippet of my code for the block_perlin_noise method:
import numpy as np
import noise
from typing import List, Dict

# ... unsolicited code

# Define a class to represent a Chunk
class Chunk:
    def __init__(self, geometry: List[int] = (16, 16, 16), position: List[int] = (0, 0, 0),
                 rotation: List[int] = (0, 0, 0)):
        # Validate the input parameters
        if not isinstance(geometry, tuple) or len(geometry) != 3 or all(value == 0 for value in geometry):
            raise TypeError("geometry must be a tuple of length 3 with non-zero values.")
        if not all(isinstance(value, int) for value in position) and all(isinstance(value, int) for value in rotation):
            raise TypeError("position must be a tuple of floats.")
        # Initialize instance variables
        self.geometry = geometry
        self.position = position
        self.rotation = rotation

    # Method to generate Perlin noise for different types of blocks in the chunk
    def block_perlin_noise(self) -> np.ndarray:
        chunk_width, chunk_height, chunk_depth = self.geometry

        # Generate noise values for different types of blocks in the chunk
        # and store them in separate 3D arrays
        cave_noise = np.zeros((chunk_width, chunk_height, chunk_depth), dtype=int)
        land_noise = np.zeros((chunk_width, chunk_height, chunk_depth), dtype=int)
        hill_noise = np.zeros((chunk_width, chunk_height, chunk_depth), dtype=int)
        mountain_noise = np.zeros((chunk_width, chunk_height, chunk_depth), dtype=int)
        # Initialize the chunk noise array
        chunk_noise = np.zeros((chunk_width, chunk_height, chunk_depth, 3), dtype=int)

        for x in range(chunk_width):
            for y in range(chunk_height):
                for z in range(chunk_depth):
                    # Generate Perlin noise for caves
                    cave_noise[x, y, z] = int(noise.pnoise3(
                        (x + self.position[0]) / chunk_width,
                        (y + self.position[1]) / chunk_height,
                        (z + self.position[2]) / chunk_depth,
                        octaves=2,
                        persistence=0.8,
                        lacunarity=1.2,
                        repeatx=chunk_width,
                        repeaty=chunk_height,
                        repeatz=chunk_depth,
                        base=1
                    ))

                    # Generate Perlin noise for land blocks
                    land_noise[x, y, z] = int(noise.pnoise3(
                        (x + self.position[0]) / chunk_width,
                        (y + self.position[1]) / chunk_height,
                        (z + self.position[2]) / chunk_depth,
                        octaves=4,
                        persistence=0.5,
                        lacunarity=1.0,
                        repeatx=chunk_width,
                        repeaty=chunk_height,
                        repeatz=chunk_depth,
                        base=0
                    ))

                    # Generate Perlin noise for hills
                    hill_noise[x, y, z] = int(noise.pnoise3(
                        (x + self.position[0]) / chunk_width,
                        (y + self.position[1]) / chunk_height,
                        (z + self.position[2]) / chunk_depth,
                        octaves=6,
                        persistence=0.5,
                        lacunarity=1.5,
                        repeatx=chunk_width,
                        repeaty=chunk_height,
                        repeatz=chunk_depth,
                        base=1
                    ))

                    # Generate Perlin noise for mountains
                    mountain_noise[x, y, z] = int(noise.pnoise3(
                        (x + self.position[0]) / chunk_width,
                        (y + self.position[1]) / chunk_height,
                        (z + self.position[2]) / chunk_depth,
                        octaves=8,
                        persistence=0.5,
                        lacunarity=2.0,
                        repeatx=chunk_width,
                        repeaty=chunk_height,
                        repeatz=chunk_depth,
                        base=1
                    ))

                    # Combine different noise types to get the final chunk noise
                    chunk_noise[x, y, z] = np.sum([
                        cave_noise[x, y, z],
                        land_noise[x, y, z],
                        hill_noise[x, y, z],
                        mountain_noise[x, y, z]
                    ])

        return chunk_noise

    # ... continuation of my previous code

    def render(self):
        figure = plt.figure()
        axes = figure.add_subplot(111, projection='3d')

        chunk_noise = self.block_perlin_noise()
        for x, y, z in np.ndindex(*self.geometry):
            block_x_value, block_y_value, block_z_value = chunk_noise[x, y, z]
            # You can adjust the size of the points based on the noise values
            axes.scatter(x + self.position[0], y + self.position[1], z + self.position[2], marker='o', s=5)

        axes.set_xlabel('X')
        axes.set_ylabel('Y')
        axes.set_zlabel('Z')
        plt.show()

I'm aiming for a Minecraft chunk terrain-like representation with gradual variations similar to a sin wave, but the noise values are not providing that smoothness and appear to be compressed into one place.
Could anyone help me understand why my noise values are compacted and not forming the expected pattern? Are there any adjustments I can make to the Perlin noise generation parameters or my approach to achieve a smoother, sinusoidal-like pattern in my terrain representation?
Answer: I made sure, this code segment encapsulates the rendering process of the chunk noise in a 3D plot using Matplotlib. When you call the render() method on an instance of the Chunk class, it will generate the noise, create the plot, and display it using Matplotlib.
    def render(self):
        import matplotlib.pyplot as plt
        from mpl_toolkits.mplot3d import Axes3D

        # Generate chunk noise
        chunk_noise = self.get_block_mapping_grid()

        # Create a meshgrid for the 3D plot
        chunk_width, chunk_height, chunk_depth = self.geometry
        X, Y = np.meshgrid(np.arange(chunk_width), np.arange(chunk_height))

        # Create a 3D figure
        fig = plt.figure()

        ax = fig.add_subplot(111, projection='3d')  # Use Axes3D
        # Plot the chunk noise as a surface
        ax.plot_surface(X, Y, chunk_noise[:, :, 0, 0], cmap='terrain')

        # Set labels and title
        ax.set_xlabel('X')
        ax.set_ylabel('Y')
        ax.set_zlabel('Noise Value')
        ax.set_title('Chunk Noise')
        plt.show()


Can I load a VMWare VM created using Fusion on VMWare Player?

Question: My primary workstation (at home) is a Mac and I am running Ubuntu on Fusion 2. Can I copy that VM onto a disk/USB flash drive and load it on a Windows machine running VMWare Player?
Comment: What happened when you tried? :-)
Answer: Yes the versions are compatible. Make sure you have the latest VMware Player and know that not all the features of your Fusion machine will not work. Other than that, I do it all the time.
Comment: could you be more specific about which features will not work?
Comment: The automatic drive mapping and printer sharing doesn't work out of the box. You will also run into Unity issues from what I have found.
Answer: I have created an XP in Fusion, which now runs under vmware player under Ubuntu 9.04.  It works well.
I found it hard to create new shared folders, and the player does not support snapshots.  Other than that I have been very pleased - even Ctrl-Alt-Del works as expected.  Note, Fusion creates a lot of helper files to allow OS X to know that the VM can handle a given file type.  Those files are not needed and may delay copying a lot.


Can Accept-Ranges Be Enabled On Ruby Cartridge

Question: I'm running Padrino on a Ruby cartridge. I have an application that serves a somewhat large mp3 file to be consumed by an in-browser player, so I need to send a Range Request. If I don't, the file stops playing and basically craps out until I make a new request, but the same thing always happens with each request.
I set up the route to explicitly return a 206 code for the file. This fixed the problem reliably on my local stack, however the Openshift server responds with this header: 'Accept-Ranges:none.' From what I have read, this means the server does not support Range Requests.
Is there any way for me to enable this? I couldn't find any information about it, although I saw that Node cartridges have had this issue.
Answer: This is a known bug in OpenShift. I suggest you add your name to the bug, and also contact Red Hat Support if you are using OpenShift Enterprise.
Comment: Thanks! I did see that bug report but thought it was just for the Node cartridge. I added my comment.


How to catch errors in multer

Question: I have read documentation for multer. But the current set up I have in my code is different and this makes difficult for me to understand how to handle errors.
It is important now because it happened (only once) that a file was not stored on the server but the code continued saving info in database as if the storing of the file had worked. But it probably did not.
const multer = require('multer');

var docPath = "path_to_disk_where_to_store_files";

var storage = multer.diskStorage({
    inMemory: true,
    destination: function (request, file, callback) {
        callback(null, docPath);
    },
    filename: function (request, file, callback) {
        //Just a function that creates an unique name with timestamp
        renamedFile = helpers.createUniqueName(file.originalname);
        callback(null, renamedFile);
    }
});

var fileFilter = function (req, file, cb) {
    var path = require('path');
    var ext = path.extname(file.originalname);
    if (file.mimetype !== 'application/pdf' || ext.toLowerCase() != '.pdf') {
        req.fileValidationError = 'goes wrong on the mimetype';
        return cb(null, false, new Error('goes wrong on the mimetype'));
    }
    cb(null, true);
};

const multerUploader = multer({storage: storage, fileFilter: fileFilter, limits: { fileSize: maxSize }});

router.post('/save_document',[multerUploader.single('file'),saveDocumentInDb]);

I dont really understand where the if-statement that will check if the upload got an error would fit.
Answer: Please refer the following for error handling when using multer:
https://github.com/expressjs/multer#error-handling
Your implementation will be something like this:
const multerUploader = multer({storage: storage, fileFilter: fileFilter, limits: { fileSize: maxSize }});
const upload = multerUploader.single('file');
router.post('/save_document', function (req, res) {
  upload(req, res, function (err) {
    if (err instanceof multer.MulterError) {
      // A Multer error occurred when uploading.
    } else if (err) {
      // An unknown error occurred when uploading.
    }

    // Everything went fine and save document in DB here.
  })
})

Comment: thank you. it's a very nice implementation.
Comment: can you tell me what is correct response error is on these two cases?

or in another word, what is the best error status in case of multer error and other error that you named it unknown error

How to catch errors in multer


Can independent variables be components of the dependent variable?

Question: I'd like to run a regression analysis but I am not sure if what I am trying to do makes sense.
My dependent variable is the total spending of a customer and my independent variables are the number of products bought that are equal to or higher than 10 USD and the number of products bought that are less than 10 USD.
I am trying to understand whether customers who buy more expensive products spend more money overall or not.
I am not even sure if this is a regression problem tho. So if you have any other suggestions on how I should approach this problem, please let me know!
Thanks,
update: would it make sense to look at the correlation between # of products >= 10 USD and total spending vs # of products < 10 USD and total spending? so the first one's correlation coeff is 0.87 and the second one's correlation coeff is 0.38.
Answer: If you want to use regression on this, one possible way to do it would be to normalise both "number of products" variables and then fit for example a linear model. You can then assess the relative importance of the 2 variables for predicting the "total spend" variable.
Comment: Thank you, Dave, for your answer. So you say that it's technically OK to use these "# of products" variables as independent variables in this case?
Comment: Yes, as long as what you mean by independent is, that they're the "independent" variables in the sense that the "total spend" variable is "dependent" because you're regressing it on the other 2. Not in the sense of "statistically independent".


How to write a variadic Rust macro that forwards to the vec! macro?

Question: In Rust 2021, I have a struct type called Intersection, and I wish to store it in a variable length list, so probably a Vec<Intersection>. I can easily construct a new container with:
#[derive(Debug)]
struct Intersection {
    t: f64,
    // ...
}

fn main () {

    let i0 = Intersection { t: 0.1 };
    let i1 = Intersection { t: 0.2 };

    let vs = vec!(i0, i1);

    for v in vs {
        println!("{:?}", v);
    }
}

Rust Playground
This makes use of the vec! macro.
What I want to do now is abstract the container type a bit, to decouple the implementation (a Vec<>) from the user of the API. For now, and to do this in the least intrusive way, I could just use a type alias to encourage decoupling:
type Intersections = Vec<Implementation>;

To complement this, I would also want to define a helper function, to create such a collection from a variable number of Intersection objects. So something that would be used like this:
fn main () {

    let i0 = Intersection { t: 0.1 };
    let i1 = Intersection { t: 0.2 };
    let i2 = Intersection { t: 0.3 };

    let vs = intersections(i0, i1, i2);  // <--- what can this be?

    for v in vs {
        println!("{:?}", v);
    }
}

To put it another way, I'm looking to forward a variadic number of arguments to the function intersections() to the vec! macro. However I understand that Rust does not support variadic arguments, so I'd need to write a macro that invokes vec! internally, perhaps call it intersections!(&i0, &i1, ...).
I've looked at the standard library's implementation of vec! and I'm not sure how I would forward the list of items to the vec! macro.
I appreciate that since I'm using a type alias so I could just call vec!(...) directly, however I want to decouple the interface from the Vector, so that if I ever change the container implementation, I can change the intersections() function or intersections! macro to suit the new implementation. This is a pretty common thing to do in C, C++, Haskell, etc, so that types can be redefined later.
Answer: You can simply write a wrapper macro that forwards to the existing rules of the vec! macro:
macro_rules! intersection {
    () => { vec![] };
    ($elem:expr; $n:expr) => { vec![$elem; $n] };
    ($($x:expr),+ $(,)?) => { vec![$($x),+] };
}

Then you can call your intersection! macro like this, for example:
let vs = intersection![i0, i1];
// requires Intersection to implement Clone
let vs = intersection![Intersection { t: 0.1} ; 2];
let vs: Intersections = intersection![];

Playground.
Comment: You can remove the first rule.
Comment: @ChayimFriedman yes, that would require us to convert `$($x:expr),+` in the last rule to `$($x:expr),*` though and subsequently the call to `vec!` in that rule to `vec![$($x),*]`. Otherwise we could not call `intersection!` without any values.
Answer: You can just re-export vec as intersections
pub use std::vec as intersections;

fn main() {
    println!("{:?}",intersections!(1,2));
}


Union of odd and even permutations forms the group $S_n$

Question: We have that $S_n$ is the group of permutations of ${1, ..., n}$ and $A_n$ is the alternating group.
If we take an element $γ∈S_n$ with a signature of -1, i.e. it is an odd permutation, and have shown already that $A_n ∩ γA_n = ∅$, how do I go about proving the following statement:
$S_n = A_n ∪ γA_n $
using the hint that for all  $σ ∈ S_n, σ = γγ ^{-1} σ$
Comment: If you have already shown that $A_n\cap \gamma A_n=\emptyset$, then a counting argument shows that the union is $S_n$.
Comment: Can you expand on that I don't understand, I haven't yet shown the cardinality of $A_n$ or $γA_n$, thats part of the following question, so I dont think it is meant to be used
Answer: Let $\sigma\in S_n$. We want to show that $\sigma\in A_n\cup \gamma A_n$.
If $\sigma\in A_n$, we are done.
Suppose $\sigma\notin A_n$, which means that $\sigma$ is odd. Note that $\sigma=\gamma(\gamma^{-1}\sigma)$. Since $\sigma$ and $\gamma^{-1}$ are both odd, $\gamma^{-1}\sigma$ must be even. So $\gamma^{-1}\sigma\in A_n$ and therefore $\sigma=\gamma(\gamma^{-1}\sigma)\in \gamma A_n$.
Hence $S_n\subseteq A_n\cup \gamma A_n$.
Since the reverse inclusion is obvious, we conclude that $S_n= A_n\cup \gamma A_n$.
Answer: Hint:
Consider the multiplicative group $\{-1,1\}$ and show the map
\begin{align}\:\text{sgn}:S_n&\longrightarrow \{-1,1\}\\
\sigma&\longmapsto \text{sgn}(\sigma)
\end{align}
is a group homomorphism.