Is antisemitism protected on this site?

Question: I've answered a question about the Israeli law of return, which was accepted by the OP and was upvoted by others.
However one user decided to put a derogatory remark claiming that somehow Israeli law of return is discriminatory and wouldn't exist in any other country. After rebutting that argument and showing that not only similar laws exist in other countries, including the (I think) OP's United Kingdom, I also explained that as opposed to these other laws that are based on ancestry or ethnicity, the Israeli law is based on religion that anyone can convert to.
In response I've been called "a troll", the moderators decided to school me, and the derogatory comments remained there despite my explicit request from the moderators to remove them.
According to the moderator Scott Earle I was in the wrong to stand up to antisemitism and was warned that if I do this again I'll be blocked from the site. Is antisemitism protected on this site? Am I really wrong to stand up to antisemitic remarks?
Answer: I've kind of sat back on this. I'm going to give my own opinion which is rather sideways from either of yours, but I think may be important to state given where this has headed.

Israel bases citizenship (and even residence) on religion.

Israel's policies for citizenship and residence are discrimination.

In my opinion, any sovereign nation has the explicit and unchallenged right to allow in who they want, for any reason at all or no reason at all given. They can alot citizenship accordingly and do not have to defend the basis for decision, except to say that they are sovereign - and that's the end of the discussion.
This means to me that if Israel wished to only allow Jews in for the purpose of settlement and only grant citizenship to such people, that's their business and none of the rest of ours (and none of mine), as long as they are a sovereign nation. They have that sovereign right. Period. This also means that I accept Trump disallowing people from certain Muslim countries into the United States. This also means that while I was vehemently Remain in the Brexit vote, I did think that accomodations should be allowed for countries to curb immigration temporarily until their infrastructure can support the extra numbers - the lack of such control for the UK directly had an impact on Brexit occurring. I likewise felt that countries such as Romania and Poland should have been allowed to put policies in place to curb emigration, as they were losing vast amounts of population, especially young people, to other EU countries.
If a nation cannot decide who gets to enter, who gets to reside, and who gets the priviledge of citizenship, then it cannot by definition call themselves a sovereign nation.

I don't agree with a policy of religious discrimation.

You're anti-semitic!

Sorry, I can't abide this strawman/ad-hominem/false-dilemma kind of reasoning. It's a specific policy he doesn't agree with, not a religion. There are plenty of reasons why someone might consider a policy of citizenship based on religion a kind of discrimination. It's not exactly a secret that there many Jews who do not agree with the policies and actions of Israel. Are they 'anti-semitic' if they think that Israel's policy towards citizenship should be more diverse and open to other religious and ethnic backgrounds? Indeed many countries have lots of different policies regarding citizenship that any of us might not really agree with or understand without knowing fully the history and culture. Saudi Arabia only grants citizenship if it's bestowed upon that person by the king. Malaysia doesn't allow some ethnic minority groups to ever get citizenship, even for third and fourth generation native born descendants.
If I criticize these policies, that doesn't mean I'm 'Islamaphobic' or 'anti Malaysian'. It just means I don't agee with those specific policies.

I feel that Israel's policies for citizenship and residence are discrimination.

Well sorry you feel that way. But unless Israel signs up to some sort of agreement akin to the EU or something like that, or unless some other nation is able to subjugate the nation of Israel and force them to follow their rules instead, then it's really irrelevant, and frankly kind of none of your concern what Israel decides to with their citizenship as a sovereign nation. All we are here to do is know the rules and help others know the rules and give practical advice.
The OP is obviously shopping around for a country where they can settle and never have to work or worry about housing. They heard about Israel's policies and came up with the idiotic idea that they could simply convert and they'd have their nest sorted for life. They came on here and instead got realistic practical advice. Whether any of us agree with Israel's policies or not, our job on Expats here was done the moment they got that advice and bailed. Probably they will not be seen here again unless they come with another misinterpretation or misunderstaning of some other nations' immigration/settlement rules. In which case, we'll probably straighten them out there as well.
Comment: @litteadv, Then I guess we better start with cleaning out all of the posts that ask about American visa policies, which are laced with valid criticism. Then the UK.... and so on.
Comment: Thank you for clearly explaining my point about sovereign rights. As to *why* I think the comment was antisemitic - it wasn't because "any criticism of Israel is antisemitic", but rather "criticism of Israel for something everyone does - is antisemitic". I provided examples to that person from numerous European countries, including his own (the UK), and my own (the US), both on exclusionary/preferential citizenship laws and religious intolerance, yet he chose to double down on his claims.
Comment: @littleadv, "criticism of Israel for something everyone does - is antisemitic" Sorry, but that is still just as illogical. Someone criticizing the United States for 'something everyone does' doesn't make the critic anti-American. I go back to the example of Jews who criticize Israel for some of their policies- while possibly their home country does the exact same to a far greater extreme. That person may even criticize both nations for the same exact kind of policies (as you've pointed out with your citizenship examples).
Comment: @littleadv, There is simply no logical way to extrapolate that to anti-semitic or anti-American. Not without introducing a logical fallacy or two (most easily *ad hominem* or *false dilemma*, but *strawman* is easy pickings as well).
Comment: I'm struggling explaining how I see the situation. A drive by deragotory comment specifically targeting Israeli policy as "discriminatory", denying that Israel has that sovereign right you went to such a great length explaining, and then explaining how his own country is perfectly within its right to discriminate its own citizens in its own government positions because reasons, ironically religious reasons... How is it not antisemitic?
Comment: And just to point out the obvious - there are most definitely self-hating jews, it's not news to anyone. You're trying to argue that an opinion cannot be antisemitic if you can show a jew holding it - that's just as fallacy as anything you are attributing to me. There are Jews members of the PLO, there were Jewish Nazi sympathizers early on, that doesn't remove the stink of antisemitism or justify the bigotry.
Comment: @littleadv, Let me put it like this. You've pointed out specific examples of other countries that have similar policies - the UK and the US. If somebody called you anti-American or 'Anglophobic' (sorry had to make that up) for pointing out those policies and describing them (correctly btw) as **exclusionary**, would you consider that blanket labeling valid? I'd think you'd see through that fallacy instantly and naturally reject such a label without hesitation. And you'd be right to do so. That's far beyond your criticism.
Comment: I pointed out these policies, described them as exclusionary - but **not** as discriminatory. Because as you said and as I said in that thread - each country can decide who they want to let in and its entirely their right. Traveler argued that there would be uproar, that it is impossible that his country would do that, but immediately when I pointed out he came up with the excuse "oh, but our religion", completely ignoring the fact that he negated his own argument when talking about Israel. How can't you see that?
Comment: @littleadv, I myself am borderline nationalist in my Amercanism. That doesn't mean I can't be critical of some of their bungling policies, especially with regards to the economy. And I wasn't talking about 'self-hating' Jews, which I consider an extreme. I was just referring to regular people having a diverse set of regular views and opinions that might not all be the same - who just happen to be Jewish. (Updated my previous comment to 'exclusionary').
Comment: That's beside the point. My argument that scolding me when pointing out someone's bias only emboldens the bias. Next time Traveler will spew his hatred and you folk will punish *me* for standing up to him because "I've been warned". So I'm asking again - why am I being punished when I pointed out someone's bias? You're trying to convince me that it is OK to be biased, and my question is - is it OK to be specifically biased against Jews?
Comment: @littleadv, "is it OK to be specifically biased against Jews" - To which I ask: "Is being critical of a specific on-topic-for-this-site policy such as citizenship (which c'mon, this is expats right?), the same as being -ophobic/-ist/anti-"? I'm a bit surprised you don't see the obvious conflation there. I don't necessarily agree with the criticism as I've pointedly explained, but if we can't avoid such blanket extreme generalizations, there is literally not a single nation's immigration/citizenship policies we can discuss on this site.
Comment: @littleadv, You yourself pointed out that every nation implements these kind of policies to some degree. We might as well just cease to exist because we're sure to offend somebody.
Comment: Last time I check this wasn't a discussion forum, it was a Q&A site. Personal opinions are not welcome, especially when they're factually incorrect. Personal opinions that are not answering the question are furthermore irrelevant. Am I misunderstanding this? So I ask you again: someone who *chose* and *deliberately* left degrading comment against Israel, no other country, and doubled down even when shown he's factually incorrect both about Israel and his own country is in the right and calling him out is wrong?
Comment: I'm not even talking about abusive behavior, calling me troll, and demanding that I let his abuse and bigotry left unanswered which was completely ignored by the moderators.
Comment: Why don't you? It is not relevant. I'm here to share my experience and what I've learned in the process, not to air my frustrations. Isn't that the goal?
Comment: Pinging this to show the irony of your last comment. You wrote an extensive answer here defending mods inaction against an antisemitic libel, while ironically you linked to it when you explained that my factually correct answer has to be deleted because it makes Americans feel uneasy. You have absolutely no shame whatsoever.
Answer:
Is antisemitism protected on this site?

No, just as the slandering of other users is not protected.

This whole sorry affair started with:

Which country offers citizenship based on religious conversion?" Probably none except for the example in your question, as such an approach would likely be considered discriminatory.

I disagree with this opinion (i.e. it is not likely), because religious discrimination is based in treating a person or group differently because of the particular beliefs which they hold about a religion. The Law of Return is also about ethnic background ('people with one or more Jewish grandparent').
Had you pointed this out at this point, the discussion would have probably ended.
Instead of that an immature, childish, tit for tat starts with half baked historical samples (which are factualy correct, but beside the point) that leads nowhere.
At this point, you start making unfounded claims about the other users supposed motive:

The only reason you think the Israeli law of return is discriminatory is because it is Israeli.
As I mentioned before, similar laws exist in many countries, including many countries in Europe. In fact, the UK gives preferential immigration rights to people with British ancestry as well. So I really don't understand why, other than antisemitism, you'd single out the Israeli one. But... antisemitism is a strong force for many.

Had you read the link that yourself supplied in your answer properly (The Israeli Law of Return), all of this could have been avoided.
I agree with your answer and many of your initial statements:

There are some countries with similar laws (Italy, Ireland, Germany - to name a few), but their criteria is based on ethnicity and ancestry, not religion

but disagree with your conclusion, because the  Law of Return is also about ethnicity and ancestry.
So it is your lack of knowledge that has brought about this situation, just as it was you that introduced the antisemitism sediment.

Moved to chat - sorry I didn't notice this for a couple of days
I will ask that @littleadv be nice. I have already been on the receiving end of this user to a small extent, and others have also mentioned him/her. It doesn't hurt to be nice to people
And criticising one country's policies based on religion does not make someone "anti" that religion or "anti" that country. And accusing someone of antisemitism just because that country is Israel is a very unpleasant thing to be accusing someone of
So again - I will ask @littleadv to tone it down a bit. He/she is openly arguing with people in a public forum, and doing that can get people blocked from that forum
Oh and also - @littleadv you enjoy being unkind to other people, but you flag people's comments as being unkind more often than I would expect

I agree with this.
Comment: As I commented to you in the answer, your interpretation is incorrect. Religion is crucial for Jewish identity. There are no "Christian Jews" or "Muslim Jews". There are only Jewish Jews. There are Jewish people of many ethnic backgrounds that converted into Judaism. Ivanka Trump, for example, has no Jewish ancestry, but is Jewish nevertheless. The Law of Return explicitly excludes children/grandchildren of Jews who have converted into a different religion. And while being a *practicing* Jew is not required - belonging to Judaism is very much the central part of the law.
Comment: That said, my point was not about whether the law is based on religion proper or anything else, but whether it is *discriminatory*. Whether your interpretation is correct or mine, either way - the law is in no way discriminatory. My argument is that Traveler made that comment, which we both agree was factually incorrect, for no reason other than being it about Israel. I stand by that claim, and your answer didn't provide any other insights into why Traveler would have made such a claim.

Is antisemitism protected on this site?


Can't access instrument view in Arturia Analog Lab 2

Question: I bought an Arturia KeyLab 61 hybrid synthesizer which was supplied with Analog Lab 2. I have an issue here: I can't access an instrument view.
Here is like it's supposed be:

And here's a screenshot from my version of the software:

You can clearly see, that I don't have that small third button on the right – instrument view. How can I make it to show up?
Answer: You have to buy the full instrument product from Arturia or buy the Analog Collectiom product which includes all the instruments. You have the free software that just has presets that you can play to entice you to buy the full software packages.


Pegar Id do usuário logado

Question: Como faço para pegar o Id do usuário logado no site, para depois inserir em uma outra tabela?
Tentando explicar melhor. Eu tenho uma action chamada CriarPub, que permite que o usuário escreva suas publicações no site. Na minha tabela publicações, tem o id do usuario, que é obrigatório, para eu saber quem publicou no site. A minha ideia, é na hora que o usuário clicar em criar publicações, esse campo da tabela publicações, receba o Id do usuário logado, permitindo assim, o insert.
Comment: Acredito que isso possa ajudar: http://stackoverflow.com/a/25453584/2263584 Embora .NET já esteja na versão 4.5, acho que isso ainda deve funcionar.
Comment: @TiagoSilva Estou utilizando o Membership.
Answer: Como nessa resposta no SOen: get-the-id-of-the-current-user-asp-net-membership
Para um usuário aleatório que você precise, faça assim:
MembershipUser mu = Membership.GetUser("username");
string userId = mu.ProviderUserKey.ToString();

Para um usuário logado, você pode fazer assim:
string userId = Membership.GetUser().ProviderUserKey.ToString();

Comment: Devo implementar isso no método membershipuser getuser() correto?
Comment: Entendi. Só mais uma dúvida,  um dos parâmetros desse método é o bool user online, ou algo assim. O que eu faço com ele?  É necessário a implementação dele?
Comment: Olá. Desculpe a demora para responder. Confere se é isso mesmo, por favor.   public override MembershipUser GetUser(string username, bool userIsOnline){
  string userId = Membership.GetUser().ProviderUserKey.ToString();  } Qual seria o retorno desse metodo?
Comment: Confere se ficou mais claro agora.

Pegar Id do usuário logado


capture bash output values inside perl script

Question: I have a bash script that sets two variables to values (not a STDOUT) . I want to store those variables inside a perl script.
Sorry dont have example.. but this is the requirement. any thoughts please
In shell script i am doing something like this
source


How do pro baseball (or cricket) players decide who should catch a fly ball?

Question: In baseball, it often happens that a fly ball is hit where two or more fielders would have a chance to catch it.  In that case, the fielders have to agree as to who will make the catch.  If they miscommunicate, they might collide and let the ball drop; then the batter reaches base and the fielders reach ESPN's Not Top Ten blooper reel.  This is a particular risk because the fielders will normally be watching the ball instead of each other.
Casual players seem to handle this just by yelling "I got it".  Do professional teams have a more elaborate system?  Sometimes it appears on TV that players are shouting as they go for the ball, but it's hard to tell what they are saying.  I would think there should also be some rule for what to do if both players try to call for the ball.
I suppose the same issue must arise in cricket, and I'd also be interested in that answer if it is different.
Answer: I cannot speak to cricket, but in baseball there is a system of who has precedence in a fly ball situation:

Outfielders have precedence over infielders
Infielders have precedence over the catcher and pitcher
Catchers have precedence over the pitcher

When it comes to who has precedence within the outfield, or infield it is as follows:

The center fielder has precedence over the corner outfielders
The middle infielders (SS and 2B) have precedence over the corner infielders (1B and 3B)
The short stop has precedence over the second baseman

Basically if there was a scenario where everyone could catch a fly ball, the list of precedence would be as follows:

Center fielder
Left or Right fielder
Short stop
Second baseman
First or third baseman
Catcher
Pitcher

When it comes to actually communicating, players will use different systems.  This can be a style that a coach decides on (especially at lower levels than professional) such as calling "ball" or "I got it".
If you are teaching this system to younger players it is good to teach the player to call "ball" and for the other players to either call "you" or call the players name.  This lets everyone on the field know who is catching the fly ball.
Players in the pros may speak different languages and may communicate differently.  Usually this would be something that they agree on during spring training as to how they call each other off.
Personally, in college we were taught that the infielders call "me" and the outfielders call "ball" as a way of distinguishing who can call you off.  They continue calling it until the players near by return with "you" to help avoid collisions.
Here is a reference on what I have explained
Comment: I found this answer when trying to understand why MLB outfielders often chase fly balls the outfield is in a better position to catch. The precedent system outlined here is what we teach in Little League, but something else seems to be going on in MBL.  See for example https://img.bleacherreport.net/img/images/photos/001/923/535/infield_crop_north.png?h=533&w=800&q=70&crop_x=center&crop_y=top
Comment: I guess this might have to be modified in case of defensive overshifts.  For instance, the San Diego Padres commonly play a defense with the third baseman moved to short **right** field, and it can easily happen that he goes for the same fly ball as the first baseman.  So one of them would need to have precedence over the other.
Answer: In baseball in particular, it is usually the outfielder's job to 'call off' the infielder (i.e. the infielder should listen to the outfielder). This is because the outfielder can see the entire field (including the infielder and the runner) during the play. On the other hand, the infielder has to turn his back, or else is running backwards, and in either case, is not able to see the field properly. Although I don't have personal experience at the professional level, my understanding is that the fielders are using the same "I got it"-style of communication to broadcast their intentions that little league players use. Of course, this isn't perfect, and sometimes they end up on the Not Top Ten.
Answer: The complexity above in baseball looks amusing.. I don't know much about baseball, it might really be required. But in cricket, I don't think any set of clear guidelines exist. Fielders with specific positions would be positioned accordingly and they expect to catch the ball. But yes, even in cricket there can arise a situation where two fielders are running for the same catch. A good communication system is usually practiced by teams to avoid collisions like someone calling like 'Mine' loudly.
This was one infamous incident where two fielders went for the catch with no communication and Australian captain Steve Waugh ended up with a nastily broken nose.
https://www.youtube.com/watch?v=zGu1eMhkAzc


Hierarchy of users

Question: I want to do like that one user should have multiple child users, for example team lead user and team members with proper permissions. Can i do this thing in drupal 7.26?
Comment: you can take a look on https://www.drupal.org/project/subuser
Answer: You can achieve that using the User Relationships module

Administrators are able create relationship types (friend, coworker, etc). Relationship types can be setup to be one-way or mutual. If a relationship type is one-way (subscriber) only the requester is shown as relating to the requestee. Relationship types can also be set as needing or not needing approval.
Administrators can give users the option to auto approve relationships on a per-relationship type basis.

If you want to assign a user under another user you can use References  module
you can use This project provides D7 versions of the 'node_reference' and 'user_reference' field types, that were part of the CCK package in D6, at functional parity with the D6 counterparts. See http://drupal.org/node/533222 for details.
Comment: Thanks Krishna, i have installed this module but we can't assign user to another user using this module, and if is it possible then can you please send me example or best tutorial for it? and also this module is not workingwith 7.26
Comment: @virangjethava you can use 'user reference' from that module (after installation)
Answer: Subuser module seems work for you.

This module allows users to be given the permission to create subusers. The subusers may
      then be automatically assigned a role or roles. The parent of the subusers then has the
      ability to manager the users they have created.

Customize settings links
please visit admin/settings/subuser

Hierarchy of users


Can't understand Unity3d Flight Script

Question: I'm trying to make a flight simulation in Unity3d. First I used rigidbody.addforce() but the movement did not respond good in rotation so I look forward to Unity3d samples and tried to use their code for controlling the airplane. It works just fine but I can't understand how it works. The code is this:
var newVelocity = Vector3.Lerp(rig.velocity,
                               -transform.forward * EnginePower,
                               EnginePower * Time.deltaTime);

Debug.Log("Velocity:     " + rig.velocity +
          "Forward:      " + -transform.forward * EnginePower +
          "Vector3.Lerp: " + Vector3.Lerp(rig.velocity, -transform.forward * EnginePower, EnginePower * Time.deltaTime));

rig.velocity = newVelocity;

This code is in the Update() function, I tested it and tried to set it to Start(), the airplane is moving but did not respond to rotation. I tried to debug and see what changes, the thing is there is nothing that changes so much.
I just can't understand how it works.
Answer: You should call this in your Update() function, since it's supposed to run every frame. Vector3.Lerp() does a Linear interpolation between two 3D vectors (documentation).
The first argument to the function, let's call it Vector A, rig.velocity, is the current velocity of your airplane. -transform.forward * EnginePower, Vector B, is your backwards direction scaled to your engine power - which is probably connected to a user input (gas gauge).
I'm not sure why transform.forward is reversed with -, but what lerp does is return a new vector, from Vector A to Vector B, scaled with a factor. If the factor is 0, Vector A is returned. If the factor is 1, Vector B is returned.
In your code the scale is EnginePower * Time.deltaTime, where Time.deltaTime is the time in seconds since the last frame - 0.016 seconds if you're running 60 FPS. So, you can understand, the scale becomes really small and so Lerp returns a vector very close to your current velocity, but ever so slightly towards Vector B. The next frame, it scales a bit more, and a bit more, etc. I hopes this improves your understanding.
You can use Debug.DrawLine() to draw your vectors, use it like this:
 Debug.DrawLine(transform.position, rig.velocity, Color.red);
 Debug.DrawLine(transform.position, -transform.forward * EnginePower, Color.green);

This will draw two lines representing the vectors you are passing to Lerp. These lines are gizmos so sure to have gizmos turned on in the editor window to display them (top right corner, next to the stats button).
Comment: Many thanks. for edit and help. the thing is I see the debug return from vector3.lerp it's actually the same as rigidbody.velocity most of the time. but when I increase EnginePower Value the object goes faster every thing is move good but no change to vector3.lerp come out. the thing is I can't figure out the way it's work !!!!
Comment: Oh Now I got it Many Thanks ;)
Comment: @FDM.Pro Happy to help!

Can't understand Unity3d Flight Script


user not logged in php file

Question: I want use drupal functions in php files,I did it with below code
$path = $_SERVER['DOCUMENT_ROOT'];
chdir($path);
define('DRUPAL_ROOT', getcwd()); //the most important line
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

Its ok and good fine, after this all drupal function exist,but my problem is here
when user logged in before this page when redirect to this page it not know as logged in user (it know as anonymous user ), how can have logged in user in php file ?
I try  drupal_session_regenerate() after below code but nothing happened, how can solve this problem?
Comment: possible duplicate of [Properly bootstrap drupal for standalone PHP file?](http://drupal.stackexchange.com/questions/28511/properly-bootstrap-drupal-for-standalone-php-file)
Comment: @Mołot it is not duplicate of it boy,my solution was on settings.php  ;)
Answer: This forum post on d.o explains what may be your problem.
You need to:

Set $cookie_domain='example.com'; explicitly in your settings.php file.

According to the post, Drupal keeps a long session ID string in a cookie, and without a proper cookie domain, the current user is anonymous.

user not logged in php file


Delay Ajax Submit

Question: I have a loading message and a success message that I want to fade in and fade out before the form gets submitted. I can't really get the code right to show these messages for a couple of seconds then submit the form as usual with Ajax.
I have tried to connect the submit button like this.
jQuery(document).ready(function (e) {
    jQuery( "#submitbutton" ).click(function() {
           e.preventDefault();
           jQuery('#loadingMessage').fadeIn(1000);
           jQuery('#loadingMessage').hide().delay(1000);
           jQuery('#saveMessage').show().delay(2000).fadeOut(1000);
       setTimeout( function () {
            jQuery("form[id=postorder]").submit();
        }, 4000);
    });
});

Or this, this just an example, I have tried a few.
jQuery(document).ready(function (e) {
    jQuery("form[id=postorder]").submit({
           e.preventDefault();
           jQuery('#loadingMessage').fadeIn(1000);
           jQuery('#loadingMessage').hide().delay(1000);
           jQuery('#saveMessage').show().delay(2000).fadeOut(1000);
       setTimeout( function () {
            [Submit form here]
        }, 4000);
    });
});

The messages works fine.
Grateful for any help!
Comment: please see [here](https://stackoverflow.com/questions/68485/how-to-show-loading-spinner-in-jquery)
Comment: why don't you move the settimeout to the top?
Answer: You can do something like this

jQuery(document).ready(function (e) {
    jQuery( "#submitbutton" ).click(function() {
           jQuery('#loadingMessage').fadeIn(2000, function(){
            jQuery('#loadingMessage').hide(2000, function(){
              jQuery('#saveMessage').show(2000).fadeOut(2000, function(){
                jQuery("form[id=postorder]").submit();
              });
            });
           });
    });
});

Loading Message

Save Message

<form id="postorder" action="" method="post">
  <input type="button" id="submitbutton" value="submit">
</form>

jQuery is non blocking as it is a Javascript library.
Non blocking means it will not wait for the previous line to complete it's work. It will move to the next line while the previous line code is stilling working.
So you need to use callback functions to do something sequentially in a situation like this.
Hope this helps :)
Comment: Works prefect! Smart to attach the Ajax to a button instead of a Type=Submit and then run the submit in a function after the last message. Thank you!

Delay Ajax Submit


Binomial distribution probability that the 45th student selected will be the 38th student to select yes?

Question:
I figured out part a and part b, but I cannot get my head around how to do part c. Any help, please!
Comment: Welcome to MSE! Please put the effort of typing a question. Linking pictures is strongly discouraged.
Answer: Hint: Among the first $44$ students, you must get $37$ yes's followed by a yes on the $45^{th}$.


Why use Rhino Mock Stub method?

Question: I just started using Rhino mock to set up test cases for my project. What exactly does the .Return(objToReturn:list) do ?
Its only seems to work if I initialize and populate the list then pass it to the mock stub method. I was a assuming I could used the Mock Stub method to populate a list then return that populated list.
<code>....
    private ProductRepository _productRepository;
    private IProductRepository _productRepositoryStub;

    [SetUp]
    public void SetUp()
    {
        _productRepository = new ProductRepository();

        //Testing using Rhino Mocks
        //Generate stub
         _productRepositoryStub = MockRepository.GenerateMock<IProductRepository>();
    }

    [Test]
    public void Canquerydb()
    {
        IList list = _productRepository.GetAllProducts();
        _productRepository.Stub(x=> x.GetAllProducts()).Return(list);
        _productRepositoryStub.AssertWasCalled(x => x.GetAllProducts());
    }

    /// <summary>
    /// Refaactor and use MockRhino here
    /// </summary>
    [Test]
    public void can_insert_product()
    {
        IProduct product = new Grains("Cheese Bread", "Dairy grain", 0);
        _productRepository.SaveProduct(product);
        _productRepositoryStub.Stub(x=>x.SaveProduct(product));
        _productRepositoryStub.AssertWasCalled(x => x.SaveProduct(product));

    }
</code>
Comment: In this context, I think the `objToReturn:list` part is just the C# 4+ explicit argument naming syntax and doesn't really do anything special for Rhino.
Answer: To answer the title of your question: Rhino mocks makes a distinction between Mocks and Stubs. A Mock is the only thing that can make a test fail because it is a wrapped instance of the thing you are testing - your System Under Test (SUT). You "stub" something in Rhino mocks so that you can satisfy the dependencies of your mocked object. The stub gives you visibility of the arguments you pass to it, and gives you control of the return result so that you can make assertions about the behaviour of your Mock in complete isolation.
This site has further explanation of Mocks and Stubs.
To add, Libraries like Moq do not make the distinction between Mocks and Stubs. Through the use of generics you don't have to Mock your SUT. I personally prefer this simplicity of Moq.

Why use Rhino Mock Stub method?


When is Response.IsClientConnected slow?

Question: I have a long running ASP response (actually an MVC action) that I want to cancel if the user has navigated away. I think this should be fairly simple:
if(!this.Response.IsClientConnected)
{
    Response.End();
}

However I've come across various sources starting that this method is slow.
So I ran my own tests (using MVC mini profiler, though you could use your own):
using (var step = MiniProfiler.Current.Step("Response_IsClientConnected"))
if(!this.Response.IsClientConnected)
{
    Response.End();
}

That found that every time I call it it's consistently very fast: under 1ms on my developer set up. This is whether it's true or false.
Under what circumstances is Response.IsClientConnected expected to be slow?
I have to support IIS6 - would Response.IsClientConnected be slower on that?
Does anyone know what it's doing under the covers? At a low level I'd expect the TCP/IP stack to know whether the connection is still there, so I'd expect this check to be instant, but does IIS have to do some additional work to check?
Answer: Good question but unfortunately don't have the answer, but can provide the following information. Hopefully this can be a starting point to know what's it's doing under the covers.
The Response.IsClientConnected is checking this by asking the current worker HttpWorkerRequest handling the request.
The worker request can be one of the following types and is created by the ISAPIWorkerRequest.CreateWorkerRequest(IntPtr ecb, bool useOOP) which is called by the ISAPIRuntime.ProcessRequest(IntPtr ecb, int iWRType). This is the entry point from the low level ISAPI to the ASP.NET runtime.

ISAPIWorkerRequestInProcForIIS6
ISAPIWorkerRequestInProcForIIS7 >= IIS7
ISAPIWorkerRequestInProc < IIS6
ISAPIWorkerRequestOutOfProc For out of proc requests

For all the InProc HttpWorkerRequest workers this call is then directed back to unmanaged code by calling int EcbIsClientConnected(IntPtr pECB) which is located in the webengine.dll pECB being the Extension Control Block (ECB), provides all the low level access to the ISAPI request. This reference is initially passed to the ISAPIRuntime.ProcessRequest.
Now I can't find any implementation details of the EcbIsClientConnected method. So without this it's impossible to know what it's doing under the covers and how this maybe differs for the different versions of IIS. Maybe someone else can explain this? I would like to know as well.
Comment: Cool, that's a good start, but not the answer. I'll vote it up once I have one.
Comment: I just asked for the implementation details of the EcbIsClientConnected method on the IIS.NET forums. Hope somebody there knows - http://forums.iis.net/t/1187030.aspx
Comment: Cheers, though it looks like the response is "don't mess with that!" Helpful :-|
Comment: @Keith One tiny addition I have, is from a Microsoft person I spoke on a conference. He was just thinking out loud but he could imagine that the method could be slow in cases where your client for example is a mobile device on a slow connection.


Inequality involving maximums

Question: I need some hints for proving the following fact about maximums which I know it is true for all real numbers $a$ and $b$.
Prove that $|\max\{a, b\}|\leq\max\{|a|,|b|\}$ for all real numbers $a$ and $b$. I only need hints, not answers.
Comment: This will be hard to prove. Try $a=0, b=-1$.
Comment: What copper is saying is that it's _flat-out_ false.
Comment: Yes, I tried it out with some numerical values and it seems to be true. What I need is an hint so that I approach this proof algebraically. Do you have any suggestions? I will apreciate your help. :)
Comment: Sorry, I may have gave you the wrong statement! I will edit my post so that you can see the real one.
Comment: I already editted the post. Now that's the statement I was trying to show you.
Answer: Note that $\max(a,b) \leq \max(|a|,|b|)$, and $|\max(a,b)| = sgn(\max(a,b)) \max(a,b)$. It should be easy from here on.
Answer: We have $|\max\{a, b\}|=|a|$ or $|\max\{a, b\}|=|b|$. In both cases we get the desired inequality.
Comment: What cases did you considered there?
Comment: Case 1: $|\max\{a, b\}|=|a|$. Case 2: $|\max\{a, b\}|=|b|$.

Inequality involving maximums


Game Server Colocation

Question: I am new to colocation. I am looking for a good place to host my server that would have around 5-10 Source Servers (Team Fortress 2). I am looking at maybe around 90 players at a time for now, players coming from all over the United States
Could I get more info on what I am suppose to look for exactly?
Would it be correct for me to get a 100Mb/s line and does 100Mb/s line in the following example actually be 100Mb/s upload bandwidth? Example: package 4 of FDC's services:
http://www.fdcservers.net/server_colocation.php
also I want to get something unmettered. I do not want to have to ever worry about going over some bandwidth limit or any DDOS attacks killing me.
And if anyone has any other recommendations as to what network configurations I should get or any other good colocation providers that are cheap in price, I would REALLY appreciate the help.
So my questions are:

What should I look for in colocation
for hosting about 5-10 game servers
on one box?
Is an unmetered 100Mb/s line
actually 100Mb/s upload rate?
Would a 100Mb/s line be adequate for
my use?
How could I check the latencies of
the data center before buying their
services?

Thanks, I really appreciate the help.
Comment: I would suggest Linode for this, assuming you weren't planning on buying hardware.
Comment: I need to avoid virtualization for what I am doing
Comment: Why avoid virtualization? I run ALL my game servers virtualized...
Comment: Product and service recommendations are off topic per the FAQ.
Answer: If you're running a server on the net you always have to worry about security, DDOS included.
The connections on those plans look unrestricted. You'll still be limited by the colo facility's own bandwidth (which shouldn't be a bottleneck for a proper facility).
Latency is going to be a much bigger issue for a game server than throughput. I don't know how much TF takes, but if it's like most, it's not much (like in the order of <100kbps per player).
Comment: Ya I will worry about DDOS, I just don't want to have to worry about a successful DDOS attack costing me a fortune.

How could I check the latency before I buy their service? And I heard of bad things about latency in Denver datacenters. Is there anything to that?
Answer: I answered your questions out of order as it made more sense for me to talk about the specific points in this order :)
Answer to question 2: In reality, 100mbps bandwidth at that price is unrealistic. The bandwidth on the FDC servers package is likely shared/oversubscribed. You should shop around and ask the providers who offer the bandwidth if it is dedicated or shared among a pool of users. Most providers at these prices are shared bandwidth. While there may be nothing wrong with this, it is something you should be aware of (since all the customers on this package, using all their bandwidth at the same time, is likely to cause a slowdown for everyone).
Answer to question 3: Your bandwidth usage for game servers seems a little high to me. Based on a worst case player usage of about 20kB/s (160 kilobits), 90 players would be about 14400 kilobits of outbound traffic per second. This translates to around 14 megabits of bandwidth. Check your math per player and don't get more bandwidth than you need! It would be much wiser to get quality bandwidth at 20mbit/s rather than shared bandwidth at 100mbit/s at the same price.
Answer to question 1: Get a server close to you and your target players. If you are in Denver, search for other colocation providers in Denver. Colocation and dedicated servers can vary greatly in pricing. Check providers which can build the server for you and compare costs. There are pros and cons of each type of hosting.
Answer to question 4: Ask for a IP address in the location that your server would be hosted so you can run a ping and traceroute to see latency. Generally speaking, ping under 50 is good for gaming. As an example, game ping times are about 100ms across the U.S.
Hope this information helps. Good luck!
Comment: thanks for all the information! I will do more research to see if I can get a better bandwidth for around that price. So far, what I have seen, FDC is the cheapest one available. All other services I have seen either only offer 1Mb/s or 10Mb/s

Game Server Colocation


Post pages in Wordpress 2.9

Question: I'm trying to use a posts page in Wordpress. For the uninitiated, this is a page (other than the home page) which features all your blog posts. You essentially turn on the static home page and point Wordpress at a custom index. Then you tell Wordpress to use another custom template as your "posts page"; thereafter, any post you make will wind up there.
My custom template for the 'Blog' page shows up as expected until I define it as the posts page. When I do, the template reverts to my custom index and I get no posts. When I undefine it as the posts page, it goes back to my template. What am I missing? I'm new to using this method, as it used to be done with a plugin prior to WP 2.9
Answer: So, I figured out the solution and wanted to share. Thanks for all your input, everyone.
The problem was with the name I chose for the template. I had called it "blog.php", which works fine when creating an ordinary page template. But when using a page as a posts page, Wordpress has some specific setup rules. The pertinent section of documentation, which I scoured the entire internet for using hours of my life I'll never get back, is hidden here:

Also, any Template assigned the Page will be ignored and the theme's index.php (or home.php if it exists) will control the display of the posts. (from here).

So, I named my template "home.php", since I wasn't using a home.php in this particular install, and I was off to the races. Anyway, thanks for the answers!
BTW, I think this may have been what Richard M was getting at.
Answer: Your problem might be in creating "templates" and the single post (single.php) You can create a template for any of your pages by putting this in the top of your page (after the first < ? php:
<code>/**Template Name: ****templatenamehere**** @package WordPress * @subpackage Default_Theme */
</code>
...rest of code
This allows you to create a page called "posts" which references your new template.  This way you can create a new template and then call it through a page.  If this is confusing or you have tried this let me know and I will try to give you more details if you need.  Thanks

Post pages in Wordpress 2.9


How I can determine $\dim(U)$?

Question: $$
U = \bigl\{ p(x) \in \mathbb{R}^3 \mid 3p(1) = 2p'(1) \bigr\}
$$
How I can determine the $\dim(U)$?
What I tried was an arbitrary $p$ like, $ax^3+bx^2+cx+d$ and then doing an equation with both conditions. I got to the value of constants must be: $3a+b-c-3d = 0$
Do that means that I can reduce the condition to
$U = \bigl\{ (a,b,c,d) \mid 3a+b-c-3d = 0 \bigr\}$?
If so, what is the dimension of that?
Comment: What does $p(x) \in \mathbb{R}^3$ mean? Do you mean that $p$ is a function $\mathbb{R} \to \mathbb{R}^3$? So the equation that defines the elements of the set $U$ involves vectors? If so, what is the cubic polynomial? One of its coordinates?
Comment: Hint: Think about a certain null space.
Comment: Or do you mean that $p$ belongs to the vector space of polynomials of degree at most $3$, and you're considering a subspace of this finite dimensional space? That's a pretty standard example of a vector space, sometimes denoted $P_3$ or something. Please clarify where $U$ lives!
Comment: Oh I forgot that! with p(x)∈R3 I mean it is a polynomial which maximum grade is 3
Answer: Just isolate one variable from your equations, e.g. $c$:
\begin{align*}
U &= \{ax^3+bx^2+cx+d : a,b,c,d \in \Bbb R,\, 3a+b-c-3d = 0\} \\
&= \{ax^3+bx^2+cx+d : a,b,c,d \in \Bbb R,\, c=3a+b-3d\} \\
&= \{ax^3+bx^2+(3a+b-3d)x+d : a,b,d \in \Bbb R\} \\
&= \{a(x^3+3)+b(x^2+x)+d(-3x) : a,b,d \in \Bbb R\}.
\end{align*}
This means that $x^3+3$, $x^2+x$ and $-3x$ spans $U$. If you prove that these three polynomials are linearly independent, then they form a basis for $U$. Hence, $\dim U = 3$.
Comment: Thanks man! I got it very clear
Answer: Let $U=\{p\in P_3(\mathbb{R}):3p(1)=2p'(1)\}$.
As you noted, we have $U=\{ax^3+bx^2+cx+d:3a+b-c-3d=0\}$.
We know that $P_3(\mathbb{R})$ is isomorphic to $\mathbb{R}^4$ via the map $\phi:ax^3+bx^2+cx+d\mapsto (a,b,c,d)$.
Then $\phi(U)$ is a subspace of $\mathbb{R}^4$ isomorphic to $U$.
Explicitly, we have $\phi(U)=\{(a,b,c,d)\in\mathbb{R}^4:3a+b-c-3d=0\}$,
so that
$$
\phi(U)=\ker
\begin{bmatrix}3 & 1 & -1 & -3\end{bmatrix}.
$$
We easily see that the rank of this matrix is $1$, so its kernel has dimension $3$
and hence $U$ has dimension $3$.
Answer: Note that $U = \ker A$, where $A : \mathbb{P}_3 \to \mathbb{R}$ is given by $Ap = 2p(1)-3p'(1)$. Then rank nullity gives $\dim{\cal R} A + \dim \ker A = \dim \mathbb{P}_3 = 4$, and since $A \ne 0$ we see that $\dim{\cal R} A = 1$ hence $\dim U = 3$.

How I can determine $\dim(U)$?


An Application of Urysohn's Lemma?

Question: Let $X$ be a compact Hausdorff (hence, normal) space. Let $\epsilon>0$, $x_{0}\in X$, $U\ni x_{0}$ be open, and $f\colon X\to \mathbb{R}$ be continuous.

I am trying to find a continuous function $g\colon X\to\mathbb{R}$ such that:
i) $\|g-f\|_{\infty}<\epsilon$,
ii) $g|_{U^{c}}=f|_{U^{c}}$,
iii) $g|_{V}\equiv f(x_{0})$ in some neighbourhood $V$ of $x_{0}$?

Using Urysohn's lemma, I was able to come up with a $g$ that satisfied all but condition i): I wasn't able to guarantee that $\|g_{U\setminus V}-f_{U\setminus V}\|_{\infty}<\epsilon$.
Is there a way to show the existence of such a $g$, either by Urysohn or some similar variant?
Answer: Yes.
1) Choose an open neighborhood $W$ of $x_0$ such that $W \subset U$ and $\lvert f(x) - f(x_0) \rvert < \epsilon/2$ for $x  \in W$.
2) Choose an open neighborhood $V$ of $x_0$ such that $\overline{V} \subset W$.
3) Choose a continuous $h : X \to [0,1]$ such that $h(x) = 0$ for $x \in \overline{V}$ and $h(x) = 1$ for $x  \in X \setminus W$.
Define
$$g(x) = f(x_0) + h(x)(f(x) - f(x_0)).$$
Then $g(x) = f(x)$ for $x \in X \setminus W \supset X \setminus U$ and $g(x) = f(x_0)$ for $x \in \overline{V} \supset V$. It remains to show that $\|g-f\|_{\infty}<\epsilon$, that is, $\sup_{x \in X} \lvert g(x) - f(x) \rvert = \sup_{x \in W} \lvert g(x) - f(x) \rvert < \epsilon$. But for $x  \in W$ we have
$$\lvert g(x) - f(x) \rvert = \lvert (h(x) - 1)(f(x) - f(x_0)) \rvert = \lvert h(x) - 1 \rvert \cdot \lvert f(x) - f(x_0) \rvert$$
$$\le \lvert f(x) - f(x_0) \rvert < \epsilon/2 .$$
Answer: Let $h(x) =  = mid(-\delta, g(x)-f(x), \delta)$ (i.e. the middle value) for some $0 < \delta < \epsilon$, and then replace $g$ by $f + h$ and $V$ by $f^{-1}((f(x_0)-\delta,f(x_o)+\delta)) \cap V$.

An Application of Urysohn's Lemma?


Como imprimir/exportar (pdf, xls, impressora) os gráficos do google chart?

Question: Criei uma tela com vários gráficos usando o google charts, mas estou precisando imprimir/exportar para pdf, xls, impressora, só que de tudo que eu procurei na net ainda não achei nada, será que alguém sabe de alguma forma de como eu poderia fazer isso?
A partir do exemplo mais básico, será que alguém consegue me dar uma luz?!

Comment: Você quer imprimir somente o #piechart? Já tentou "@media" e window.print?
Comment: Eu preciso imprimir tanto o #piechart quanto outros elementos que tenham como titulos e textos, mas nesse exemplo que passei seria somente o grafico gerado mesmo. E nao tentei ainda usar os @media, sera que tem algum exemplo para o caso? Valew
Answer: Você fala exportar para "impressora", realmente isto não faz sentido para mim, mas vou supor que você simplesmente quer imprimir com Ctrl + P ou que o dialogo de impressão do navegador seja chamado diretamente.
Se for realmente isto, então você pode simplesmente chamar o window.print():

google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);

function drawChart() {
    var data = google.visualization.arrayToDataTable([
        ['Task', 'Hours per Day'],
        ['Work',     11],
        ['Eat',      2],
        ['Commute',  2],
        ['Watch TV', 2],
        ['Sleep',    7]
    ]);

    var options = {
        title: 'My Daily Activities'
    };

    var chart = new google.visualization.PieChart(document.getElementById('piechart'));

    chart.draw(data, options);
}

document.getElementById("print").onclick = function() {
    window.print();
};

<button id="print">Imprimir</button>

Você também pode usar o @media para ocultar todos elementos (acaso o seu chart esteja em uma página com "várias coisas") e imprimir. Ficaria algo como:
@media print {
    body {
         visibility: hidden;
    }

    #piechart {
         visibility: visible;
    }
}

Porém também posso presumir que talvez você queira dizer outra coisa como "exportar para impressora", talvez você só queria realmente exportar com a intenção de gerar um documento como PDF, mesmo na parte que você fala de impressora, então a solução seria o jsPDF.
Para usar o jsPDF com SVG (o seu Chart é um SVG :) ) provavelmente terá que usar o plugin sillysvgrenderer (está no próprio repositório). Um exemplo de como adicionar o SVG com o plugin seria:
var doc = new jsPDF();
var chart = document.querySelector("#piechart svg");
var sourcecode = new XMLSerializer().serializeToString(chart);

//Adiciona o SVG
doc.addSVG(sourcecode, 15, 15);

//Download do arquivo
doc.save("sample-file.pdf");

Comment: Se o que você quer dizer com imprimir é exportar então `window.print` não é a resposta. A resposta é `jsPDF`.
Comment: Muito obrigado mesmo, vou dar uma olhada e ainda volto a falar se deu certo ou não e dai sinalizar como resposta válida. E quando eu digo imprimir quero dizer que se der para exportar para um pdf, excel, imagem, qualquer coisa que de para o usuário exportar já esta bom, então vou fazer uns testes, e imprimir (windown.print) não da muito certo pois se eu tiver muitos graficos ele pode quebrar algum no meio da página.


Read zone file with dnspython SOA error

Question: I am really battling to get dnspython to read a zone file, I always get stuck with SOA and I have tried combinations of different zones files and python scripts.
Zone file(From http://agiletesting.blogspot.com/2005/08/managing-dns-zone-files-with-dnspython.html):
$TTL 36000
example.com. IN      SOA     ns1.example.com. hostmaster.example.com. (
               2005081201      ; serial
               28800   ; refresh (8 hours)
               1800    ; retry (30 mins)
               2592000 ; expire (30 days)
               86400 ) ; minimum (1 day)

example.com.     86400   NS      ns1.example.com.
example.com.     86400   NS      ns2.example.com.
example.com.     86400   MX 10   mail.example.com.
example.com.     86400   MX 20   mail2.example.com.
example.com.     86400   A       192.168.10.10
ns1.example.com.        86400   A       192.168.1.10
ns2.example.com.        86400   A       192.168.1.20
mail.example.com.       86400   A       192.168.2.10
mail2.example.com.      86400   A       192.168.2.20
www2.example.com.       86400   A    192.168.10.20
www.example.com.        86400 CNAME     example.com.
ftp.example.com.        86400 CNAME     example.com.
webmail.example.com.    86400 CNAME     example.com.

Script 1(From http://agiletesting.blogspot.com/2005/08/managing-dns-zone-files-with-dnspython.html):
import dns.zone
from dns.exception import DNSException
import dns.ipv4
import os.path
import sys

zone_file = sys.argv[1]
print "Command line argument: " + str(zone_file)

domain = os.path.basename(zone_file).replace(".hosts","")
print "Domain - "+domain

try:
        zone = dns.zone.from_file(zone_file, domain)
        print "Zone origin:", zone.origin

        for name, node in zone.nodes.items():
                rdatasets = node.rdatasets
                print "\n**** BEGIN NODE ****"
                print "node name:", name
                for rdataset in rdatasets:
                        print "--- BEGIN RDATASET ---"
                        print "rdataset string representation:", rdataset
                        print "rdataset rdclass:", rdataset.rdclass
                        print "rdataset rdtype:", rdataset.rdtype
                        print "rdataset ttl:", rdataset.ttl
                        print "rdataset has following rdata:"
                        for rdata in rdataset:
                                print "-- BEGIN RDATA --"
                                print "rdata string representation:", rdata
                                if rdataset.rdtype == SOA:
                                        print "** SOA-specific rdata **"
                                        print "expire:", rdata.expire
                                        print "minimum:", rdata.minimum
                                        print "mname:", rdata.mname
                                        print "refresh:", rdata.refresh
                                        print "retry:", rdata.retry
                                        print "rname:", rdata.rname
                                        print "serial:", rdata.serial
                                if rdataset.rdtype == MX:
                                        print "** MX-specific rdata **"
                                        print "exchange:", rdata.exchange
                                        print "preference:", rdata.preference
                                if rdataset.rdtype == NS:
                                        print "** NS-specific rdata **"
                                        print "target:", rdata.target
                                if rdataset.rdtype == CNAME:
                                        print "** CNAME-specific rdata **"
                                        print "target:", rdata.target
                                if rdataset.rdtype == A:
                                        print "** A-specific rdata **"
                                        print "address:", rdata.address

except DNSException, e:
        print e.__class__, e

The Error:

python read_zonefile.py example.com.hosts
Command line argument: example.com.hosts
Domain - example.com
Zone origin: example.com.
** BEGIN NODE **
node name: @
--- BEGIN RDATASET ---
rdataset string representation: 36000 IN SOA ns1 hostmaster 2005081201 28800 1800 2592000
  86400
rdataset rdclass: 1
rdataset rdtype: 6
rdataset ttl: 36000
rdataset has following rdata:
-- BEGIN RDATA --
rdata string representation: ns1 hostmaster 2005081201 28800 1800 2592000 86400
Traceback (most recent call last):
File "read_zonefile.py", line 31, in
if rdataset.rdtype == SOA:

NameError: name 'SOA' is not defined

Script 2:
import dns.zone
import dns.ipv4
import os.path
import sys
reverse_map Olivia Munn= {}
for filename in sys.argv[1:]:
        zone = dns.zone.from_file(filename, os.path.basename(filename),relativize=False)
        for (name, ttl, rdata) in zone.iterate_rdatas('A'):
                try:
                        reverse_map[rdata.address].append(name.to_text())
                except KeyError:
                        reverse_map[rdata.address] = [name.to_text()]
keys = reverse_map.keys()
keys.sort(lambda a1, a2: cmp(dns.ipv4.inet_aton(a1), dns.ipv4.inet_aton(a2)))
for k in keys:
        v = reverse_map[k]
        v.sort()
        print k, v

Error:

python create_rev_dns.py example.com.hosts
Traceback (most recent call last):
File "create_rev_dns.py", line 7, in
zone = dns.zone.from_file(filename, os.path.basename(filename),relativize=False)

File "/usr/lib64/python2.6/site-packages/dns/zone.py", line 977, in from_file
filename, allow_include, check_origin)

File "/usr/lib64/python2.6/site-packages/dns/zone.py", line 924, in from_text
reader.read()

File "/usr/lib64/python2.6/site-packages/dns/zone.py", line 882, in read
self.zone.check_origin()

File "/usr/lib64/python2.6/site-packages/dns/zone.py", line 521, in check_origin
raise NoSOA

dns.zone.NoSOA

As for the Zone file I have downloaded a zone file from Godaddy.com, the same issue. I have taken a zone file from a PRODUCTION Bind server(Secondary Zone), same error.
So I am really stumped, any assistance will greatly be appropriated.
Answer: Concerning script 1:
I had a similar issue, since SOA is unknown - as are all the other rdata types. Either import them using the from directive, or give the full name, e.g. dns.rdatatype.SOA, ...
Concerning script 2:
The demo guesses the zone origin from the filename. If the filename is not the zone origin, replace os.path.basename(filename) by the origin of the zone.
Answer: Modify the code as follows,
if rdataset.rdtype.name == 'NS':
   print ("target:", rdata.target)

Read zone file with dnspython SOA error


Playing with an mp3 player in performance

Question: I'm getting ready to do a show where I play guitar & sing and use backing tracks I've recorded and turned into mp3s, but I don't really want to take my laptop out of the house, would rather use a portable mp3 player.
What is a good portable mp3 player for doing something like this, and would it be better to hook it up to my amp, or through the mixer/PA?
Comment: A couple of questions: Are the backing tracks in stereo? Do you need to be able to operate it from stage, or can someone just hit play on it from wherever?
Comment: To clarify, this question is obviously concerning the practice of musical performance and the logistics concerned therein.  I think other people could benefit from this question as this type of performance is becoming increasingly common.  Perhaps a change to the title of the question would help.
Comment: Buy a cheap laptop or tablet and dedicate it to performance use.
Comment: Make sure you have a monitor speaker so you hear the backing track enough. Just a tip, cause people tend to forget that.
Answer: The following pieces of equipment offer cheaper alternatives to purchasing a dedicated performance computer:

Use the house stereo (if available)
Use your smartphone (if available)
Use your dumbphone (if you still have one)
Use your tablet (if available)
Purchase a candy bar-style digital recorder and use it as your device (I do this personally and it works fine.)

Pat also brings up a good point: a stereo recording played through your amp won't do the world any good.  It's also not going to provide a very wide stereo field for people to listen to.  I'd advise you to use the house's amps whenever available and set them up wide to give you a full sound.  If you own your own PA setup, then yes, I'd lug that around if it gives your backing tracks the presence they require.
To clarify, my equipment recommendations were made with the thought that you'd be plugging an audio out into a larger set of speakers for performance.


For a service created, Local system account have not enough credentials?

Question: Somebody created a service which runs an exe (in VB6). My part was to create this exe. If I run the exe using a bat file (exeApplication parameters), my program works fine. If I execute the service and runs the exe with the same parameters, not working completely/correctly.
Somebody tells me that is a issue with credentials. I mention that the service(is a process) runs with "Local System account".
How I can change this? I tried to change on option "This account" and put the user-computer but not saving this.
Any solution?
Answer: The NT Authority\System account has the most power of any user account on the system. There is nothing that it cannot do, even if it first has to take ownership of an object or change its permissions, the System account can do it.
Your problem lies elsewhere. Maybe an environment variable or startup directory problem. When you launch a process in your own security context, that process will have different environment variables and startup/working directory than if Service Controller launches it as System.
Edit: As mfinni points out, I meant that local system has full control of the local system of course, no automatic permissions to remote computers. We don't know what your service does. If your service does use network resources, it is still possible to grant another machine's system account permissions on remote resources; it's tied to the machine's computer account in Active Directory.
Comment: 'There is nothing that it cannot do' *on the local system.* If the place where it's failing is trying to use resources on another server, it will have to run as an account that can do so -and if Marina is having problems setting that, we need to know the details there.
Comment: True of course. More detail from OP is definitely appreciated.


passing argument to boto3 e2 start script

Question: any idea how I can modify this to passing the instance id as argument instead of putting it in the script?
import boto3

def stop_instance(instance_id):
    ec2 = boto3.client("ec2", region_name="us-west-1")
    response = ec2.stop_instances(InstanceIds=[instance_id])
    print(response)

stop_instance()

Comment: Add [command line parsing](https://realpython.com/comparing-python-command-line-parsing-libraries-argparse-docopt-click/), e.g. using argparse or click.
Comment: If you are wanting to stop an instance from the command-line, you could instead use the [AWS Command-Line Interface (CLI)](http://aws.amazon.com/cli/) command: `aws ec2 stop-instances --instance-ids `
Comment: I want to use python. infact i want to have just one script to start and stop instances
Answer: If your objective if to stop all EC2 instances via Python script, you can first call the describe-instances method to dynamically build a list of all the running EC2 instances (pull id values based on the state property = running). From there you can pass that list into your function to stop them all, as the stop-instances method can handle a list of ids.
Comment: not stop all. I want to have an ad=hoc python script to stop an ec2 instance by passing the instance Id as an argument. like so python3 shutdown_ec2.py instance_id
Comment: Thanks for clarifying the endgame - use the sys module (sys.argv) to pass the instance id value into the script
Comment: i need to import sys and argparse?
Comment: Yep.. see here: https://stackoverflow.com/questions/59212110/how-can-i-use-sys-argv-in-python
Answer: like this?
import boto3
import sys
import argparse
instance_id = sys.argv[1]

def stop_instance(instance_id):
    ec2 = boto3.client("ec2", region_name="us-west-1")
    response = ec2.stop_instances(InstanceIds=[instance_id])
    print(response)

stop_instance(instance_id)

then i ran it with python3 stop_ec2.py instance-id
Comment: when i run it without arguments: it shows this.....................
Comment: python3 stop_ec2.py
Traceback (most recent call last):
  File "stop_ec2.py", line 4, in
    instance_id = sys.argv[1]
IndexError: list index out of range
Comment: is it as expected


Authentication mechanism comparison

Question: I have to start a new project where user authentication/management will be required.
A lot of websites use existing authentication mechanisms like facebook/twitter/openID/google/etc (even SO).
While I might understand that they are used to simplify some parts of this workflow can someone enumerate the pluses and minuses of using one of these authentication mechanisms vs. an usual user creation and what should I look for when I do this?
Thanks in advance!
Answer: Here are a few:
Advantages of using external auth (like openId)

For the user, fewer account names/passwords to keep track of
For you, don't have to manage password resets etc.

Disadvantages

Ties you to an external service (if google/facebook is down, so are you)
Your site is only as secure as the external site(s) you trust as id providers

Authentication mechanism comparison


Radio Button set custom drawable not working

Question: I have used the radio button and set a custom drawable for a check/uncheck
I want to this

but my current output is this

Radio button XML code
<RadioGroup
            android:id="@+id/segmented2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_margin="6dp"
            android:layout_weight="1"
            android:baselineAligned="false"
            android:orientation="horizontal">

            <RadioButton
                android:id="@+id/colorRadioButton"
                style="@style/RadioButton"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:checked="true"
                android:text="@string/color_color" />

            <RadioButton
                android:id="@+id/gradientRadioButton"
                style="@style/RadioButton"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:checked="false"
                android:text="@string/color_gradient"
                android:visibility="visible" />
        </RadioGroup>

style/RadioButton

drawable/radio_checked_unchecked.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/radio_checked" android:state_checked="true"/>
    <item android:drawable="@drawable/radio_unchecked"/>
</selector>

Comment: set button to `@null` and set the radioGroup background to the custom drawable
Comment: @MAshhal thanks you for the answer but not working
Answer: I got an idea from the given answer and I found a solution to my question
Change
<RadioButton
        android:id="@+id/colorRadioButton"
        style="@style/RadioButton"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:checked="true"
        android:text="@string/color_color" />

To
<RadioButton
            android:id="@+id/autoRadioButton"
            style="@style/RadioButton"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:checked="false"
            android:text="@string/auto"
            android:drawablePadding="@dimen/_10sdp"
            android:drawableStart="@drawable/radio_checked_unchecked"/>

set android:drawableStart to set custom drawable and set button="@null"
style

use the above code and get output like this
Answer: Firstly, you need to change the android:orientation from horizontal to vertical. You can also use fixed layout width and height if you use larger or unscalable custom drawables.
So, your updated RadioGroup codebase will be like below:
<RadioGroup
    android:id="@+id/segmented2"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_gravity="center_vertical"
    android:layout_margin="6dp"
    android:layout_weight="1"
    android:baselineAligned="false"
    android:orientation="vertical">

    <RadioButton
        android:id="@+id/colorRadioButton"
        style="@style/RadioButton"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:checked="true"
        android:text="@string/color_color" />

    <RadioButton
        android:id="@+id/gradientRadioButton"
        style="@style/RadioButton"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_marginTop="10dp"
        android:checked="false"
        android:text="@string/color_gradient"
        android:visibility="visible" />
</RadioGroup>

Also, button should be set to @null, and the radioGroup background should be your custom drawable.
So, your updated style codebase will be like below:

Comment: Thanks for your answer but not working
Answer: I think you need to use this:
<item name="android:background">@drawable/radio_checked_unchecked</item>
<item name="android:button">@null</item>

instead of this:
<item name="android:background">@null</item>
<item name="android:button">@drawable/radio_checked_unchecked</item>

in your style.
Comment: Thanks for your answer but not working


Introduction to Markov Process (Part 2): Dynamical system and Markov relationship

Question: In my previous post asked here Introduction to Markov process: How to prove that a process is Markov? Part 1, -- a process is Markovian if it follows the memoryless property. Consider, a dynamical system $x_n = f(x_{n-1})$ and a (stationary) Markov chain ${(X_n)}_{n \in \mathbb{Z}}$ in discrete time with each $X_n$ taking its values in a finite set $E$. The canonical space of the Markov chain is the product set $E^{\mathbb{Z}}$. The trajectory $X=(\ldots, X_{-1}, X_{0}, X_1, \ldots)$ of the Markov chain is a random variable taking its values in $E^{\mathbb{Z}}$. Let $\mu$ be its invariant distribution.
Question1: How does one show that a Markov Process generates (iid) random variables or is it only random variables which may not be iid?
Question2: In https://en.wikipedia.org/wiki/Subshift_of_finite_type it says that  through the shift operator $T$, a shift dynamical system is a Markov Process. So, it means that the shift dynamical system can generate iid random variables. How? A simplified version of explanation as to how a Markov Chain is a dynamical system and vice-versa (how the dynamical system can be a Markov Chain) will be helpful to clear the concept.
Links to Theorum and proof will be additionally very helpful
Comment: Did is correct.  You will likely find reliable definitions here: http://www.statslab.cam.ac.uk/~rrw1/markov/M.pdf
Comment: Q1: i.i.d. sequences are Markov chains, many Markov chains are not made of independent random variables (and the links in your comment do not say otherwise). Q2: All Markov chains are not dynamical systems. An example of dynamical system yielding i.i.d. random variables is the shift on $\{0,1\}^\mathbb Z$ with the uniform probability, then the $0$th projections of the iterates of the shift are indeed i.i.d.
Comment: Thank you for your answer. How can Markov Chains give iid sequences since the prev state is fed back to obtain the next state? It can generate random variables but where is the proof that they are iid? Can you link a proof in support of your answers esp Q2?
Comment: "the prev(ious) state is fed back to obtain the next state" There might lie a deep misconception about Markov chains. What is the precise definition you are using? Please be specific.
Comment: In the answer below, it is mentioned that Markov chains generate dependent rvs. This has confused me, all definitions (http://www.stat.yale.edu/~jtc5/251/readings/Basics%20of%20Applied%20Stochastic%20Processes_Serfozo.pdf) and in basic text books mention that Markov process is iid. I had also asked the same QUestion to the person who has put up the answer below -- whether iid or not.
Comment: The statement that I have mentioned in my comment is obtained from the article http://arxiv.org/pdf/1211.1234.pdf Section II
Comment: First reference: a book, 450 pages. Do you seriously think this is useful? Second reference: a strange assertion in a research article by two CS students. Sorry but my advice is to look up some definitions in a serious textbook about Markov chains. "in basic text books mention that Markov process is iid" Absolutely not (did you really write what you meant to write?).
Comment: In your first comment, "iid sequences are Markov chains", so does this mean that Markov process are iid. I am not sure what is the correct claim as I am finding different interpretations in different resources. In essence, if asked are iid sequences Markov chains and are Markov chains iid, then what is the answer and the corresponding reference for that? Can you please put this as an answer?
Comment: Quote: `Q1: i.i.d. sequences are Markov chains, many Markov chains are not i.i.d.` Can one be clearer?
Answer: (In answer only to Q1) ... Markov chains usually generate non-independent rv's.  That's why it's a "chain": the distribution of the next output is usually dependent on some of the previous outputs.
Comment: Thank you for your reply. But I am a bit confused because I have found in some articles (http://www.columbia.edu/~ks20/stochastic-I/stochastic-I-MCI.pdf Pg 3 Point 2) and https://ece.uwaterloo.ca/~mazum/ECE603/Lectures/chap2-Processes.pdf (conditional independence in Pg 8). Can you explain more, please?


Prove: If $f$ is bounded and uniformly continuous on $R$ and $g(x)=f(x)^2$ for all $x \in R$, then $g$ is uniformly continuous on $R$.

Question: My initial approach was to use the definition of uniform continuity and altering the epsilon since there exists $M \in R$ such that $f(x)\leq M$
I'm confused about the selection of delta in this process, if using the epsilon-delta definition of uniform continuity even is the right way of doing this.
Thank you very much!
Comment: It would be great if you could show a formal attempt so that we can highlight where you went wrong and needed assistance.
Answer: Since $f$ is uniformly continuous and bounded, we know that:
$$\exists M \in \mathbb{R} \setminus \{0\}: \forall x \in \mathbb{R}: |f(x)| \leq M$$
$$\forall \epsilon > 0: \exists \delta > 0: \forall x,y \in \mathbb{R}: |x-y| < \delta \implies |f(x)-f(y)| < \epsilon$$
Let $\epsilon > 0$ be given. Let $x,y \in \mathbb{R}$. Then:
$$|g(x)-g(y)| = |(f(x))^2-(f(y))^2| = |(f(x)-f(y))(f(x)+f(y))| = |f(x)-f(y)| \cdot |f(x)+f(y)|$$
By the triangle inequality, wee can see that:
$$|g(x)-g(y)| \leq |f(x)-f(y)| \cdot (|f(x)|+|f(y)|) \leq |f(x)-f(y)| \cdot 2M$$
Then, we know that there is a $\delta_1 > 0$ such that:
$$|x-y| < \delta \implies |f(x)-f(y)| < \frac{\epsilon}{2M}$$
Hence, let $\delta = \delta_1$. Then:
$$|x-y| < \delta \implies |g(x)-g(y)| \leq |f(x)-f(y)| \cdot 2M < \frac{\epsilon}{2M} \cdot 2M = \epsilon$$
which is exactly what we wanted. Hence, $g$ is uniformly continuous on $\mathbb{R}$. Does that make sense?


Git submodule mess: how to use git submodules with developers not familiar with git?

Question: I am really frustrated about using git's submodule feature. Either I still don't get it right or it just don't work as I am expecting this. Following project situation is given:
Project
  | .git
  | projsrc
  | source (submodule)
  | proj.sln

In this scenario source is pointing to another repository containing the common source data across all our projects. There is a lot of development happening under source as also under projsrc. Unfortunately Project points to some commit of the source submodule and not to the actual HEAD of it. This is the usual git behaviour, as far as I got it know.
I already found out that
git submodule update

just get the version of submodule which was commited together with the main Project. However, I would really like to be always up-to date with the submodules development, but do not have any real clue how to do this right. Hence my question is:
Is it possible to attach the Project to the HEAD of the submodule,
reagardless of the fact if this will break the compilation of Project or not.
I just don't want to go always into the submodule
directory and do git pull there. Since I think I could loose my changes done
in the submodule directory, because this is simple attached to a
commit and not really to any branch or so.
Please consider following constraints:

Developers in our group are not that familiar with all VCS around. We are used to use really huge svn repository before, without any external repo features at all.
We are working on Windows
A click'n'forget solution would be best, since most of project members are rather scared by using a command line interface :)
Comment: See also http://stackoverflow.com/questions/1979167/git-submodule-update/1979194#1979194 and http://stackoverflow.com/questions/3131912/why-are-git-submodules-incompatible-with-svn-externals/3132221#3132221
Comment: "I could loose my changes done in the submodule directory, because this is simple attached to a commit and not really to any branch" It's not true! There is always a branch. You never lose your changes until you commit when you're in detached head state.
Answer: The reason why a submodule points to a particular revision is important. If you point to a HEAD, builds will be unreproducible. I.e. if you checkout yesterday's a version of the Project, you would never know which exact version of source@HEAD was yesterday.
That's why it always stores particular revision sha.
To pull all submodules you could use Easy way pull latest of all submodules
Comment: I fully agree that they would break, however I am ok with that situation. I just get bothered to explain every non-git-familiar developer collaborating on my **Project** that the submodule **source** does not work as they expect it. They have always commit/push on the source on any change there. And more important, if they just do _git submodule update_ in the Project, they loose all their changes made to _source_, since they get overwritten by that particular revision.
Comment: `submodule update` doesn't delete any changes, as I know, it just checks out referred revision. The made changes are still in repo, and you could checkout them, then update **Project** to refer the revision and commit the submodule revision reference to the main project.
Comment: In deed git do delete your changes if you haven't commited and pushed them yet (as also haven't pushed the changes in the parent). Since the source/ is a submodule with detached HEAD (default behavior) git submodule updates would always bring the source/ directory in the state pointed by the parent repository. This is, in my eyes, very bad behavior of git, since it doesn't even notify me that my local changes get overwritten (git 1.7.7)
Comment: If changes are not committed, `submodule update` doesn't change anything (at least it is so on my pc). If changes are committed, they are not lost, you can checkout them even it you checked out something else. Moreover, what's for you are calling `submodule update`?
Comment: You can still cd to source and do checkout head. Moreover, if you commit changes to source, you would need to push them to origin. You should consider source as a simple git repository, nested into projsrc. It is what submodule really is. The only difference is that projsrc has information about origin of source submodule and specific commit. If you want your common source is always the same version as other projects, you should place all your projects in the same repo as common.
Answer: I am not good at Git and submodule. But I think some simple rules would be very helpful.

Commit and push from sub-directory.
Go back to root of your project, check the status if you need to commit and push again.

when Pull. can try to use script to bundle the "pull/submodule update" together. And only do it at the root of your project.
Answer: Consider this:

source is pointing to HEAD (as you would want).
you make changes to source inside you Project (you commit but not push them)
now you have two HEADs : one in your Project's source, another in  your common source.

Which one you would want to be present in your Project when you make submodule update?
The problem (and the main feature) of git in your case is that you consider commit and push as atomic operation. It isn't. Git is decentralized. There is no common HEAD. You might have multiple repositories with different HEADs.
Consider this:

you have 3 developers (A, B and C) with a git project.
they all pull a project's HEAD.
each developer has made changes to project
now each of them has 3 HEADS: A HEAD, B HEAD and C HEAD.

Which HEAD you consider "true" HEAD?
So, to answer your question: If you want common source submodule always be synchronized with central repository, git isn't your choice. And probably none of VCSs would help you with that.
You should treat git submodule as a thirdparty library which should be updated manually with these two steps:

Pull your submodule ("download thirdparty library")
Commit your project with updated submodule ("place the new version of thirdparty library to your project")

If you want to make changes to submodule you should do the same in reverse order:

Commit your submodule ("make your changes to the thirdparty library")
Push your submodule ("send your changes to the thirdparty library maintainer")
Commit your project with updated submodule ("place the new version of thirdparty library to your project")
Comment: Thanks Vanuan. Yes, I know I got the idea of git. You might be right, it might not be the right choice. The problem is, that it took for me very long time to understand what git is actually doing compared to previously used svn. I am already really afraid about explaining this to my co-developers... Nevertheless, I think I've found already my workflow using git.
Comment: Don't be afraid to explain. Git is as simple as distributed versioning can be. The one thing your co-developers have to understand is that each copy of git repo is self-contained local "svn-server". The need of synchronization between "servers" is the reason why some things are not possible with git.


Como contar valores consecutivos no Excel?

Question: Neste momento tenho esta formula que calcula valores consecutivos:
=SE(AB5=0;0;SE(OU(E(AB4>=100;AB5>=100);E(AB4<=-100;AB5<=-100));AC4+1;1))

Basicamente ela faz isto:
0           0
0           0
-110        1
-110        2
-110        3
-100        4
0           0
0           0
0           0
130         1
150         2
0           0
0           0
-100        1
0           0
0           0
0           0
0           0
-110        1
0           0
0           0
0           0
-220        1
-150        2
0           0
0           0

Mas eu pretendo que ela faça isto:
0           0
0           0
-110        0
-110        0
-110        0
-100        4
0           0
0           0
0           0
130         0
150         2
0           0
0           0
-100        1
0           0
0           0
0           0
0           0
-110        1
0           0
0           0
0           0
-220        0
-150        2
0           0
0           0

Ou isto:
0           0
0           0
-110        4
-110        0
-110        0
-100        0
0           0
0           0
0           0
130         2
150         0
0           0
0           0
-100        1
0           0
0           0
0           0
0           0
-110        1
0           0
0           0
0           0
-220        2
-150        0
0           0
0           0

Qual é a fórmula para tornar isto possível ?
Eu preferia não ter que adicionar mais colunas, pois o ficheiro já é grande...
Usar apenas uma fórmula para fazer este trabalho seria o melhor...
Obrigado pela ajuda.
Comment: Olá Fábio, esse é o site do Stackoverflow em português, traduza sua pergunta
Comment: Já traduzi a pergunta.
Comment: boa Fábio, senão ela pode ficar pendente por ser sinalizada como escrita em outra língua, agora está ok :)
Answer: Para a fórmula não ficar muito extensa você pode usar outra coluna para comparar linhas, duas a duas, como a imagem abaixo:
Comment: Thiago, eu acho que vou por esta solução mesmo. Já tentei só com uma coluna e tudo resulta em formulas muito lentas. Obrigado, gashaste um upvote, pois embora não seja bem o que está na pergunta, a tua solução resolve o problema.


Would this bass line be heard as 5/4 or 4/4?

Question: Assuming no other instruments (such as drums, in particular) are providing any clues about the time signature, would the following bass line be heard by people as 5/4 or 4/4 (all quarter notes, all same volume):
G A A A A G A A A A G A A A A G G A A A :
IOW, would it be heard as:

?
Does it depend on what the listener is accustomed to hearing (the time signature is in the ear of the beharker)? IOW, would most people hear it as 4/4?
Comment: I have voted to reopen. This isn't a matter of opinion. The change in pitch will be perceived as an accent. It's the same principle used by metronomes that use a different pitch for the downbeat than on the other beats.
Comment: @Aaron - I've heard pieces in the Musescore website that my brain has interpreted as being in 3/4 time and 6/8 time depending on what I'm thinking of the piece at the time, so yes, it is opinion-based (those were real music with real running 8ths for melody and accompaniment, so pitch changes matter surprisingly little).
Comment: Voted to reopen for the reasons stated by @Aaron - though one clarification: I am assuming you also mean that the bass instrument *itself* isn't accenting the notes differently or providing other cues either.
Comment: @Aaron - With audio that doesn't accent any notes on downbeats such as most Musescore-original pieces, the issue is always the same: whether every X notes or every Y notes should be grouped together beat-or measure-wise. With 3/4 vs. 6/8, it's every 2 vs. every 3. With 4/4 vs. 5/4, it's every 4 vs. every 5.
Comment: @AndyBonner - If you were just listening to a 4/4 - or even 3/4! - piece before listening to the sample in the question, I don't think you can force the answer "in this case, certainly not" anymore.
Comment: @Dekkadeci This question is about a specific bass line and 5/4 vs. 4/4. 3/4 vs. 6/8 is an entirely different matter, far more subjective, and the subject of many questions on this site that are open.
Comment: @Dekkadeci As I understand your comment, you're speaking of how to notate such a piece; but that isn't the question here. This is simply about perception, and the perception in this case is unambiguous. The G will be perceived as the downbeat. Since pitch is the only element of change, that moment of change — when the G is heard — will be perceived as an emphasis.
Comment: Just to point out to everyone, it might help to hear the questions in this in inverted order: "1) Can people's familiarity with a given meter override melodic cues? I.e., if common time is so darn common, can a bias for it override some of the cues that help us construe meter? And then 2) for example, what about this contrived scenario?" Perhaps too much attention is being given to the example and not to the real question. Also IMO the example is so contrived as to force the answer "in this case, certainly not," but one could come up with a less deterministic scenario...
Comment: @Dekkadeci Meh, maybe that's an argument for "opinion-based" *, but I still think not. Now, if a metric pattern had already been established *in this piece* and we flowed seamlessly into this segment, sure (though even then I think it would disrupt my existing 4/4 or 3/4). But play in 4/4, stop, turn the page, continue with this, I think I'd be in 5 by the 3rd A (or at the worst, simply confused, but not comfortably in 4 or 3). (*Though I firmly believe that opposing As on a Q do not always prove that the Q "invited opinion-based As.")
Comment: @Нетвойне: Correct; picture a robot playing the notes
Answer: In the scenario described, it would be heard as 5/4. Because there are no other contextual clues, the G would stand out from the texture and be perceived as "accented" — not in the sense of volume, but in the sense of having attention called to it by virtue of being different from the otherwise static A.
Comment: I agree with @Aaron here. When I play it straight, without accents or additional context, I hear the pitch change at regular intervals as the 1. Even if I start on one of the A notes, I end up hearing the G as the 1.
Comment: @Tim I didn't downvote without explaining, but I'm downvoting now because the question is too subjective to support such an absolute answer as this.  Whether it is heard one way or another depends on the player and, much more to the point, on the hearer.
Comment: @Tim the question is too subjective for this answer to be appropriate; it's not necessarily too subjective in an absolute sense.  If you prefer, I could rephrase the critique: this answer is too absolute to be adequate for the subjective question at hand.  Unfortunately, the people who designed SE decided early on that downvotes should not require justification, so people can and regularly do downvote without explanation.  I find it vexing, but there's not much hope that it will ever change.
Comment: Unexplained dv - again?
Comment: @phoog - so if the **question** is too subjective, **that's** what needs dving, not any answer, surely? And, listeners receive more than hearers, don't they? But, all that apart - dvers *should* be expected to validate their dvs, as I keep harping on about...
Comment: @phoog I have to disagree and side with Aaron here on the question of this question's subjectivity. Granted, the OP has created a bit of an "angels dancing on the head of a pin" thought experiment, with a naked bass line rendered with absolute equal emphasis on all notes—but given those parameters, I think the answer is simple; the melodic change is the only "landmark" to suggest a meter, and the given example is simple and repetitive enough to force us into one perception.
Comment: @AndyBonner I can only think of the conductor whose name I sadly cannot remember who, according to one of my conducting teachers in graduate school, was so unable to deal with 5/4 meter that he conducted the second movement of Tchaikovsky's 6th with the first beat of each measure twice as long as the others, turning 5/4 into 6/4.  Such a person might well hear the pattern in question as s 4- (or 6?) beat pattern with the Gs occurring at different points in the pattern.
Comment: @phoog I heard an anecdote about a conductor: "Maestro, do you find it difficult to conduct in 7?" "Certainly not—one, two, three, four, five, six, sev, en." (Though in seriousness, I would argue that the "stretch it to fit" approach is different than "willfully hear the downbeat where you want it to be." My anecdotal data would suggest that adding a beat is a natural reflexive response in 90% of kids encountering 3/4 or triplets for the first time ("One two three-ee one two three-ee")
Comment: @AndyBonner - true enough! So many students when meeting 5/4 would morph it fairly soon into either 4/4 or 6/4. Both of which are in fact more natural - having even numbers of hands and feet. Where that puts our 5 fingers/thumbs though, I'm still trying to figure...
Answer: In the absence of any emphasised notes, it's virtually impossible to say in reality.
The existence of that recurring G note, with the extra one towards the end would trend towards 5/4, with the added fact that that gives four lines to the music - a very common feature, against the five lines otherwise.
I'd really appreciate dv reasons - thanks!


Embedding not found in MainActivity.java in flutter

Question: I use method channel for using Java code in flutter but
Flutter activity (flutter.plugin , embedding and some other library's not found)
Comment: can you try to copy-paste the code and the error in your post instead of the picture?.
Answer: Looking at the screenshot, I guess you are using vs code.
In general I advise to do the Android/iOS specific parts of flutter in their respective IDEs because of these things.
VSCode does not detect the android libraries by default.


Django 1.10 or later: base.html override not working

Question: I am creating a site in Django with a custom view, and want to link to that view on the admin page. But even though I've followed the directions to override in Documentation or Youtube, but i won't show the changes in the overide file.

{% extends "admin/base.html" %}

{% block title %}{{ title }} | {{ site_title|default:_('Django site admin')    }}{% endblock %}

 {% block branding %}

Test

 {% endblock %}

 {% block nav-global %}{% endblock %}

My base.html in ratonix\templates\admin
Map tree:

└─ratonix
----└── ratonix
----------└── settings.py
----------└── views.py
----------└── urls.py
--- └── templates
-----------└── admin
- ------------  └── base.html

└── manage.py

Templates folder in the same folder as manage.py
This is my current settings.py:

"""
Django settings for ratonix project.

Generated by 'django-admin startproject' using Django 4.0.6.

For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""

import pymysql
import os
pymysql.install_as_MySQLdb()

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-SECRET SORRY!'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'ratonix',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'ratonix.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, '../templates/')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'ratonix.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'ratonix_db',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306',

    }
}

# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATICFILES_DIRS = (os.path.join(BASE_DIR, '/xampp/htdocs/ratonix/ratonix/static/'), )
STATIC_URL = 'static/'
MEDIA_URL = '/images/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

I've restarted the server, as well as used different browsers, and none of my changes show up.
Am I doing something wrong anywhere, or are the instructions given by the tutorial just plain incorrect?
Answer: The order of INSTALLED_APPS affects the override order.
If you have templates/admin/base.html in the ratonix app, then ratonix must come before django.contrib.admin in INSTALLED_APPS for that template to be used.
Since you also have DIRS in your TEMPLATES configuration, you could also use <PROJECT>/templates/admin/base.html, and that would be used; per the documentation,

If you have app and project templates directories that both contain overrides, the default Django template loader will try to load the template from the project-level directory first. In other words, DIRS is searched before APP_DIRS.

Note the preferred customization point for the admin is admin/base_site.html.
Comment: Thanks! change the order for overide and change filename did the trick!