What is the scoring system in sailing?

Question: After watching the Olympics and seeing that Australia had fewer points than other teams but was guaranteed a gold or silver medal in the Laser class. We were confused as to how sailing is scored.
Answer: The Low point scoring system is used. The winner is the boat with the lowest score at the end of the event or series of races.
The first boat across the line gets 1 point, the second 2 points, the third gets 3 and so on. For boats who are entered but did not start (cross the start line legally)(DNS), Did not finish (DNF) or were disqualified (DSQ), they will be given scores equal to the number of boats entered - (minus) 1, 2 or 3. Often DNF has a slightly lower score than DNS and DSQ.
In a longer series it is common for one or more result to be "discardable". Most sailing scoring software will automatically discard each competitor's worst result.
So, across a series of 5 races each with ten boats, a boat which one every race would be given 5 points. If they missed a race (and weren't able to discard the result), they might get 1 + 1 + 1 + 1 + 11 = 15 points.
In the case of points ties, the later results are usually given more weight (as in the case of the Olympic medal race).
The advantages of this system are as follows:

Boats can skip a race and still compete in the rest (especially if it is discarded).
It easily handles variable numbers of entrants in different races. A first is still worth as much, even if many boats didn't show up.
Applying penalties is straightforward.

Details of the scoring can be found on the USA Sailing site or the UK's RYA.
Comment: As a side effect of that, the margin of victory in a single race does not matter. If you are 1 sec ahead of your next competitor, you still get the same score as if you were 10 mins ahead.
Comment: Interesting. When I was racing, it was 0.75 for first, then 2, 3, ...
Answer: Scoring system in sailing works on negative points , for winning you need to score the least points..

The fleet racing is run on a low points scoring system - the boat at
  the end of the competiton who has the least number of points wins.
All of the events finish their competition with a Medal Race, before
  that they are scheduled to sail 10 races, except the 49er which will
  sail 15 races. The boat who finishes first in a race scores one point,
  second place scores two points, third place scores three point and so
  on. Sailors are allowed to exclude their worst score in the first 10
  (15) races.
After completing 10 (15) races, the top ten boats with the lowest
  score go on to compete in the Medal Race.  The points scored in the
  Medal Race cannot be excluded and are worth double.

Source

What is the scoring system in sailing?


nginx dynamic ssl for SaaS application

Question: my SaaS application create subdomain for each customer customer.myapp.com. in my nginx i configured wildcard ssl certificate. (*.myapp.com) and it works.
how can I allow my customer to connect their own domain to their subdomain with ssl?
i.e customer.com => customer.myapp.com
I don't want to manually add certificate each customer. I want it to be automatically.
how could it have done with nginx?
Answer: like with all things it depends on your configuration.
You sure are right, a wildcard certificate (*.myapp.com) can be used for all subdomains.
This means that for each customer you want to give a subdomain to, you can use the same wildcard certificate.
But as for how to implement it:
Show us how your configuration looks now, and we may help you automate it.

nginx dynamic ssl for SaaS application


Connect SSH Tunnel with the Java Desktop program (.jar) to remote server

Question: I developed a JavaFx Desktop program the employees of the company. Now, they want to use the program in their houses with their own personal computers. The program has MySQL and FTP services.
I need to use SSH Tunnel or VPN so that the program can connect from outside to the remote server in the office(port forwarding for FTP and MySQL).
If I want to use SSH Tunnel I have to install(or copy/paste) the certificates in the own employees' computers and I think that this option is dangerous because of the certificates can be engaged to attacks of their computers.
Sometimes I have thought to create one certificate for each employee (100 people) to control better who is connected in each time, but it's too much laborious to maintain.
I would like to use SSH Tunnel but I don't know if the best option in this situation.
What other options can I use to connect my program to remote server securely?
Answer: There aren't a lot of protocol choices - whatever you choose needs to be:

Auditable - no sharing of credentials
Secured - to limit risk of traffic interception/MitM
Manageable - if you've 100+ employees.

You could use SSH, but setting up a VPN is what most business do (in my experience). You can then only allow VPN connections through the firewall and nothing else needs to change.
Your best bet is to look into a small business VPN device. A quick search here brings up lots of (off-topic) posts asking for recommendations.
Long story short, whatever you use you're going to have to create and issue a cert or key to every employee. The only sensible way to do this is using script or management tool.
Comment: Thank you so much for your answer. I have been thinking  about do it with split tunneling with OpenVPN because I only need to use 2 ports. I don't want that all the traffic of the employees is sent throutgh the VPN. I hope it isn't a problem have to install the VPN certificate on personal employees computers (I will use password to connect the VPN as well)
https://openvpn.net/for/split-tunneling-with-access-server/
Comment: This sounds sensible. Ideally it would be good to use a more enterprise solution that uses the employees LDAP/AD Accounts for authentication - the first point I made is that it's auditable so no sharing of credentials!
Comment: I don't have knowledge about use LDAP/AD accounts. I'm going to search information so that I can use it. Thanks!
Answer: As you mentioned I would authorize the employees with the private key from the generated public/private rsa key pair for ssh connection to the office server. You can store the public key in ~/.ssh/authorized_keys and secure the private key with passphrase so that the employee can connect to server. But you must open the ssh port in the firewall for outside.
Comment: This is terrible security practice! Remote access is a big can of worms and should be done securely or not at all, as the risks to the business are way too high!


Display loading icon and then redirect to new page

Question: Lets say I have one page "page1" which consist of some info and a button named "Add".
When I click on this button, it opens a popup modal window that consists of a form with around 10 fields and submit button. Once I click on this button, I used ajax post to submit the form and at the server side it does insert and update operation and return success or failure result.
During this ajax process, I am displaying a loading image. What I am trying is just  after this loading image it should  redirect to new page. Lets say "page2". But in my code, i see after this loading stops , I see the modal window and "page1" for about 2-3 seconds and then only it redirects to "page2".
I am not sure if my question is logical or not but still if there is any method to stop it.
Below I have ajax processing code.
Thank you.
   $.ajax({
        type: 'POST',
        url: 'page2.php',
        data: {
            'data': form_data
        },
        success: function(response)
        {
            var arr = JSON.parse(response);
            if(arr.success == true) {
                window.location.href = 'page3.php';
            }
            else {
                alert('There are some error while saving record.');
            }
        },
        beforeSend: function()
        {
            $('.loader').show().delay(9000);
        },
        complete: function(){
            $.fancybox.close();
            $('.loader').hide();
        }
    });

Comment: Did you try moving `$('.loader').hide();` to last row inside `success`?
Comment: If you're redirecting on success why even have `$('.loader').hide();` in the complete, the image will go because you've been redirected to a different page. The only place you would need it is where your `alert` is.
Comment: @George Thank you. Now i understand
Answer: $.ajax({
     success: function(response)
     {
        ...
        if(arr.success == true) {
            ...
        }
        else {
            ...
            $('.loader').hide();
        }
     },
     ...
     complete: function(){
         $.fancybox.close();
     }
});

Don't hide the loader after ajax request is done.
Comment: Might be worth adding they will need to add it on the `else` block of `if(arr.success == true)`
Comment: yes, you're right. There should be hidden the popup because no redirects.
Comment: @AndreiTodorut Thank you very much


Logo não aparece no flutter dentro do container Gradient

Question: Estou tentando colocar minha logo na pagina de login do meu app, mas não estou conseguindo.
Obs.: Sou iniciante na linguagem e estou me adaptando ainda aos widgets.
<code>return Scaffold(
  body: Center(
    child: Container(
      decoration: BoxDecoration(
          gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [
              Color(0xFF01ECFD),
              Color(0xFF009AFA),
          ])),
      child: Padding(
        padding: const EdgeInsets.all(36.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            SizedBox(
              height: 155.0,
              child: Image.asset(
                "assets/logo.png",
                fit: BoxFit.contain,
              ),
            ),
            SizedBox(height: 45.0),
            emailField,
            SizedBox(height: 25.0),
            passwordField,
            SizedBox(
              height: 35.0,
            ),
            loginButton,
            SizedBox(
              height: 15.0,
            ),
          ],
        ),
      ),
    ),
  ),
);
</code>
Comment: Tem alguma imagem de como deveria ficar? Ou alguma do que esse código gera pra você? Seja mais especifico na sua pergunta se você deseja obter alguma resposta, [Que tipos de perguntas devo evitar fazer?](https://pt.stackoverflow.com/help/dont-ask)
Answer: Voce configurou esse caminho de Assets no sey Yaml? Fiz um teste aqui com seu código e funcionou.. Usei uma imagem qualquer aqui do meu pc.

Toda foto, fonte, pacote, que você precisa adicionar no seu projeto, você precisa adicionar no seu arquivo, YAML. O próprio arquivo yaml vem comentado diversas coisas prontas de examplo para você seguir... dá uma olhada nele :)
Ex:

Adicionando o caminho do asset no seu yaml, provavelmente deve funcionar.
Luz no nosso caminho!
Comment: Vale mencionar que é necessário rodar ```flutter pub get``` direto do terminal ou usar o botão correspondente na IDE (caso ela possua).


Goldbach Conjecture Counterexample

Question: My professor introduced the Goldbach Conjecture to me a couple months ago, and I've been intrigued by it ever since. The Goldbach Conjecture states that every even number greater than 4 can be written as the sum of two primes.
If we look at the number $2m$, where we let $m$ be the number containing every prime greater than $2$, then $2m$ = $2\cdot3\cdot5\cdot7\cdot11\cdot13\cdot17\cdots$
Then every number less than $2m -1$ will be contained in $2m$, so no matter what number $x$ you subtract from $2m$, you get
$2m - x = x\cdot\left(\frac{2m}{x}-1\right)$ which is composite, so this even number can't be written as sum of two primes.
I'm assuming this is not a valid counter-example, but why not?
Comment: Lol, nice try.${}{}{}$
Comment: Can you clarify about the construction of $m$? It's not clear if an infinite number of primes is involved or not. In the former case, $m$ is not a real number because the product diverges, as there are infinitely many primes (the first proof of this fact, credited to Euclid, is really slick).
Comment: The bracketed expression (2m/x – 1) won't always be an integer, e.g. when x = 5^2 (as will also be the case for any other x comprising multiple powers of the prime factors in 2m which still satisfies x < 2m - 1). If x is always an integer but (2m/x – 1) isn't, then one cannot say that x.(2m/x – 1) is always a composite - have I missed something here?
Answer: $m$ doesn't exist, since there are infinitely many primes.

In a little more detail: the product of infinitely many natural numbers is not, in general, a natural number. Similarly, the sum of infinitely many natural numbers is not, in general, a natural number: for example, $$1+1+1+1+...$$ is not a natural number. The Goldbach conjecture is a statement about natural numbers, so looking to infinite products for a counterexample isn't going to work.
There are contexts where we can make sense of an infinite expression like the above (see e.g. Why does $1+2+3+\cdots = -\frac{1}{12}$?), but it's something that takes serious work to make precise - and often results in surprising properties, or the failure of properties we usually take for granted.

Addressing rubik's comments: what if we only use finitely many primes in the construction of $m$?
Well, then the whole shebang breaks down! Suppose $$m=3\cdot 5\cdot . . . \cdot p_k$$ is the product of the first $(k-1)$-many primes bigger than $2$. Then their may be a prime which is $<2m-1$, but which is not a factor of $2m$ - namely, $p_{k+1}$! So we can't conclude that $2m$ is a counterexample to Goldbach.
Comment: well, maybe with the OP's first definition $m=0$ works.(an integer containing all primes $>2$)
Comment: $m=0{}{}{}{}{}$
Comment: @CarryonSmiling Um, what? The OP has defined $m$ as $3\cdot 5\cdot 7\cdot . . .$ - how on earth is that $0$?
Comment: @rubik I disagree, I don't see that in the question at all. Their argument crucially relies on the assumption that $m$ is divisible by every prime; until they weigh in otherwise, I think my answer addresses their question.
Comment: @NoahSchweber Thank you for your answer, it was very clear and I understand now why it's not valid.
Comment: your definition of the goldbach conjecture is incorrect. every even number >2 is prime. you forgot 4=2+2
Answer: There are infinitely many primes, so $m$ doesn't exist.
Pretend like $m$ could exist i.e. there are finitely many primes.  Then clearly $m+1$ has a prime factor, say $q$.  Since $m$ is the product of all primes, $q$ must be a prime factor of $m$ as well.  Thus, $q$ must be a prime factor of $m+1-m=1$ as well, yet $1$ has no prime factors.  Therefore, $m$ cannot exist, so there must be infinitely many primes.
Answer: Apart from the concern about the nature of $ m $ as mentioned by others,  your claim that every number less than $2m - 1$ is contained in $2m $ is not true. For example consider number 4; then for $ x=4$ you do not conclude anything.

Goldbach Conjecture Counterexample


How do you tune a piano?

Question: Ok so I am visiting my grandparents and I am going to practice piano at their house for about a month. But, when I started playing it, I noticed that the piano was out of tune buy a full QUARTER tone. So, obviously, I need to tune it. But, because of COVID, no piano tuner is coming over.
So, I must take matters into my own hands. How do I tune a piano?
Comment: "So I must take matters into my own hands."  No, no, you definitely must NOT.
Comment: ["If you can imagine an entire book that answers your question, you're asking too much."](https://music.stackexchange.com/help/dont-ask)
Comment: Hey, easier than trying to tunafish
Comment: Is it basically in tune with itself and sounding OK? Or has it gone honkey-tonk?
Comment: Sometimes tuners leave instruments flat deliberately because it's not clear that the instrument can withstand the increased tension needed to bring it to A=440 Hz.  I would not try raising the pitch of a piano as my first piano tuning project.
Comment: "So, obviously, I need to tune it": From what you've written, this is not at all obvious.
Comment: First rule "do no harm". A piano brought up to pitch may fall out of tune (inconsistently) after a short time (days or less). Strings may break due to the increase in tension - this is less likely if it is done in stages. Is it playable? Safer not to try it.
Comment: Did you ever try this? And if yes, what kind of results did you get?
Comment: @Aaron Nah man, might try it though. That piano I was talking about, is still out of tune lol
Comment: @CarlWitthoft the tunafish has more scales.
Answer: The short answer is, "you don't". Without proper training, it's very easy to damage the instrument.
With that significant caveat ...
A search for "how to tune a piano yourself" will turn up a variety of instructional videos. Here's one that seems especially promising to me.
You'll need the right tools for the job, also. Again, a search for "tools for piano tuning" will give you the results you need.
Comment: While there may be "instructional videos,"  there is a huge risk of a random untrained and unskilled person totally borking the piano.   IMNSHO the correct answer is "Don't do it"
Comment: @CarlWitthoft Thanks, Carl. I don't know why I didn't edit my post earlier to include your essential cautionary note.
Answer: It might be obvious to one who has absolute pitch. But if the whole piano is out by that quarter tone, the majority of people would not notice. Unless they played along to a recording that was at concert pitch. It may have been tuned thus on purpose. If it's only certain notes, or one string out or two/three, then it's a different matter. But if it's in tune with itself, let sleeping dogs lie.
You will need certain tools, the hammer being crucial - use the wrong size, and you could end up wrecking the pegs. You won't be able to use a tuner, like you would with a guitar. It's often a few hours for an experienced tuner to pull up a piano, so I believe it's a bad idea for you to attempt this.
If it was my piano, I wouldn't let you near the inside, and would question the mindset of grandparents who are happy for you to experiment on their pride and joy.
Comment: If it's their pride and joy, I assume they'd keep it in tune. Source: Have grandparents with badly-tuned piano that hasn't been used in decades. (Not that I'm disagreeing with anything else in your answer.)

How do you tune a piano?


Recurrence relation for $I_n=\int (\sin x+\cos x)^n \,\Bbb dx$

Question: We can obtain a recurrence relation for
$$I_n=\int (\sin x+\cos x)^n \,\Bbb dx$$
as $$nI_n= (\sin x+ \cos x)^{n-1} (\sin x- \cos x)+2(n-1)I_{n-2} \tag{$\ast$}$$
By writing $I_n=2^{n/2}J_n$, where $J_n=\int \sin^n (x+a) \,\Bbb dx=\int \sin ^n t \,\Bbb dt$
\begin{align} J_n&=\int \sin ^{n-2} t (1-\cos^2t) \,\Bbb dt \\ &=J_{n-2}-\int \cos t ~ \sin^{n-2}t ~\cos t \,\Bbb dt \end{align}
Integration by parts yields
$$J_n=J_{n-2}-\cos t~ \frac{\sin^{n-1} t}{n-1}-\frac{1}{n-1}J_n\implies nJ_n=(n-1)J_n-\cos t ~\sin^{n-1} t.$$
The question is: How else can one prove/get $(\ast)$?
Comment: You are missing a factor of $1/n$ in your recurrence.
Comment: Oh! yes, thanks, corrected it
Answer: You can write
$$I_n = \int (\sin x + \cos x)^n \,dx = \int (\sin x + \cos x)^{n-1}(\sin x - \cos x)'\,dx$$
and integrate by parts to get
$$I_n = (\sin x + \cos x)^{n-1}(\sin x - \cos x) + (n-1)\int(1-2\sin x \cos x)(\sin x + \cos x)^{n-2}\,dx$$
Now write
$$1-2\sin x \cos x = 2 - (\sin x + \cos x)^2$$
and substitute that into the last expression to get
$$n I_n = (\sin x + \cos x)^{n-1}(\sin x - \cos x) +2(n-1)I_{n-2}$$
Answer: Multiplying both sides of the identity
$$(\sin x +\cos x)^2=-(\sin x-\cos x)^2+2$$
with $n(\sin x+\cos x)^{n-2}$ we have
$$n(\sin x +\cos x)^n=
-n(\sin x+\cos x)^{n-2}(\sin x-\cos x)^2+2n(\sin x+\cos x)^{n-2}.$$
Arranging the right hand side we have
$$(nI_n)'=\color{blue}{(-n+1)(\sin x+\cos x)^{n-2}(\sin x-\cos x)^2}\color{red}{-(\sin x+\cos x)^{n-2}(\sin x-\cos x)^2
+2(\sin x+\cos x)^{n-2}}+2(n-1)(\sin x+\cos x)^{n-2}$$
and
$$(nI_n)'=\color{blue}{(n-1)(\sin x+\cos x)^{n-2}(\cos x-\sin x)(\sin x-\cos x)}+\color{red}{(\sin x+\cos x)^{n-1}(\cos x +\sin x)}+(2(n-1)I_{n-2})'$$
and
$$(nI_n)'=(\color{purple}{(\sin x+\cos x)^{n-1}(\sin x-\cos x)})'+(2(n-1)I_{n-2})'.$$
Finally integrating we obtain the recurrence relation
$$nI_n=(\sin x+\cos x)^{n-1}(\sin x-\cos x)+2(n-1)I_{n-2}.$$
Comment: Whenever you get a pen, kindly work on letting OP know how you disproved his answer because right now it is not (atleast for me) clearly understandable how you would proceed using this and how you even got this.
Comment: Recurrence relations are generally obtained by using integration by parts as stated in previous answers or in the question, do not use differentiation in such cases because that will yield nothing and for finding the final recurrence relation, you will have to integrate which will be  rather more difficult.
Comment: It disproved the formula given.
Comment: Mathematically you may be correct, I have not checked your relation becaause you did not even explain how you got it, but moreover it does not actualy answer OP's question. If you disproved the given formula, kindly show your solution and present the formula you feel to be correct
Comment: I could disprove it before the accepted answer if I had a pen, actually I uploaded my answer before.
Comment: Why ARE there so many downvotes here? I dont get it.
Comment: I think you should try explaining some of the steps, like using what formula/property and how you simplified stuff because I am kind of a beginner in this so without atleast some explanation of the property used in the steps/simplification, I do not understand this stuff


Parsing XML with Jquery

Question: Hi I am new to Jquery and struggling with parsing XML.
I have a search box in my form that returns the results of a sql search when the user has entered the first few letters . this string is then searched with a php file and the results are returned in the form of an xml file. The problem is that I need to uniquely identify each name and id returned and then to be able to access a specific name/id set. so that this one item is shown on my form.
The code (I thought) would return a list of all the the names but this seems to be in just one string. Can anybody please help me with accessing individual xml elements . I have included the xml file at the bottom , thanks for any help
        // JQ - ajax
         $(document).ready(function(){
             $.ajax({
                      type: "GET",
                      url: "search_action.php?" + string ,
                      dataType: "xml",
                      success: disxml ,

                 });

        })
        }

         function disxml(data){

        $(data).find('results').each(function() {

        var name      = $(this).find('name').text();
        var cus_id    = $(this).find('id').text();

        })

The XML File
      <results>

      <name>
      The porter grp
      </name>
      <id>
      548930
      </id>

      <name>
      ADI UK
      </name>
      <id>
      986565
      </id>

      <name>
      Fireled
      </name>
      <id>
      549899
      </id>

      <name>
      JCK Rec LTD
      </name>
      <id>
      548442
      </id>

      </results>

Answer: It may help to change the XML schema to include a result node containing the name and id elements.
<results>
  <result>
      <name>
      The porter grp
      </name>
      <id>
      548930
      </id>
  </result>
  <result>
      <name>
      ADI UK
      </name>
      <id>
      986565
      </id>
  </result>

</results>

Your jQuery code should then do something like
function disxml(data){

        $(data).find('result').each(function() {

        var name      = $(this).find('name').text();
        var cus_id    = $(this).find('id').text();

        })

Regards
Answer: Have you ever heard of json?
Javascript can handle json beautifully. So my suggestion is that you serialize your data to json instead of XML and feed this to javascript.
Looky here for the how.

Parsing XML with Jquery


how to separate the output given below

Question: 530b214119510

HEADLINE 1

one

one

one

one

Click here

above is output of $value
<?php
if(isset($_POST['partner_1'])) {

                if (!empty($_POST['editor1']))
{
    foreach ( $_POST as $key => $value )
    {
        if ( ( !is_string($value) && !is_numeric($value) ) || !is_string($key) )
            continue;

        if ( get_magic_quotes_gpc() ){
            $value = htmlspecialchars( stripslashes((string)$value) );
        } else {
            $value = htmlspecialchars( (string)$value );
        }
            echo "
";
            print_r($value);
            echo "
";
}   }
}
?>

Now I want to insert the above value in the db but the problem is that I have different columns for 530b214119510    and div.... . $value has all the value , its not in the
array . So how to separate the value without disturbing the html content and id.
Comment: 530b214119510 means what?
Comment: @PHP_USER1 is 530b214119510 in the html code ?
Comment: @Tabby I am using foreach for all the post , so I am getting two values from my form ie uniq_id and htlm content
Comment: how does `$value` prints that string ?
Comment: @PHP_USER1 how did the uniq_id generate ?
Answer: Try to use
    if ( get_magic_quotes_gpc() ){
        array_push($value, htmlspecialchars( stripslashes((string)$value) ));
    } else {
        array_push($value, htmlspecialchars( (string)$value ));
    }

instead of
    if ( get_magic_quotes_gpc() ){
        $value = htmlspecialchars( stripslashes((string)$value) );
    } else {
        $value = htmlspecialchars( (string)$value );
    }

Comment: Note that if you answer such questions, which doesn't fit the quality standards, you support them.
Comment: Fatal error: Cannot use [] for reading in D:\xampp\htdocs\relg_n2\admin\check2.php on line 17    and   my line 17 is $value[] = htmlspecialchars( (string)$value );
Comment: I modified my answer :)
Comment: No i can't use it ,
Warning: array_push() expects parameter 1 to be array, string given in D:\xampp\htdocs\relg_n2\admin\check2.php on line 17

HEADLINE 1

one

one

one

one

Click here

Warning: array_push() expects parameter 1 to be array, string given in D:\xampp\htdocs\relg_n2\admin\check2.php on line 17
SUBMIT
Answer: Use preg_match() to extract the value from the html and store it in another variable. You can also use DOMDOCUMENT to extract the value from the html code. These methods wont alter you html code.
Comment: please can you tell how to do it

how to separate the output given below


How to show cart with number of items in Ubercart?

Question: For his cart, my client wants a cart icon with the number of items in it. Not a list of all items. I searched around a little bit but didn't find anything.
Answer: As for D8 latest version, it looks like uc_cart_get_contents is not working anymore.  So here is how I managed to do it :
/** @var \Drupal\uc_cart\CartManager $cartManager */
$cartManager = \Drupal::service('uc_cart.manager');
$items = $cartManager->get()->getContents();
$variables['nbr_cart_items'] = count($items);

Answer: The code supplied works "OK" as a quick fix, but it actually counts the number of distinct products in the shopping cart, not the number of items.
Here's a snippet that counts the number of items using a different Ubercart function than the one employed above:  uc_cart_get_total_qty()
if (module_exists('uc_cart')) {
  $cart_item_count = uc_cart_get_total_qty();
  print $cart_item_count;
}

Answer: Assuming the ubercart core 'shopping cart' block doesn't work for what you need:

Then you'll need to output it in your theme or create it as your own custom block.
Use the uc_cart_get_contents() function. This loads an array of all the items in their cart, which allows you to get a quick count() on to get your number. From there it is trivial to overlay this output on to your cart icon.
// Load the current shopping cart.
$items = uc_cart_get_contents();

// Display a message if the cart has more than 5 products.
$item_count = count($items);

print "$item_count";

Comment: Thanks. One more thing... If i want the block to display only if there's one or more items in it?
Comment: use count() again but wrap it in an if statement, ex. if (count($items)) then print the cart, otherwise do nothing.
Comment: sorry i'm not very good with php. I did the following but it didn't work:

Panier d'achat  $item_count";

?>


How to storage large data in React Native

Question: I have to get a 5MB json file from an API (https://api.sleeper.app/v1/players/nfl), but because of his size the fetch take a while, but I just need to get this file once a day. So, my question is: theres a way to storage this file inside my app and get some piece when I have to? I've tried Async Storage and some others packages that uses the same logic, but the async request takes as long as the fetch function.
What I want is some way to manipulate this data in a fast way than if a have to fetch every single time that I need some piece.
Right now I'm using an API made by my own which takes this 5MB file and return the specific piece that I need (https://teste-draft.netlify.app/.netlify/functions/getplayersdata?name=167). But the problem with this temporary solution is when I have to get a lot of players (like 20 or even more), because it's so many requests that the app ends up taking a long time to display the data.
Comment: You can try realm db https://www.mongodb.com/docs/realm/sdk/react-native/
Comment: @Craques You mean that I have to save each player in a database?
Answer: I solved this by creating a Context to store all the 5 MB data, to be fetched when the user open the app. It was not exactly what I wanted, because the fetch run every time when the user close the entire app, but worked...
<code>import { useState, createContext, useEffect } from "react"

export const AllPlayersContext = createContext()

export const AllPlayersContextProvider = ({children}) => {
    const [allPlayers, setAllPlayers] = useState(null)

    const getAllPlayers = () => {
        console.log('Getting players...')
        const URL = `https://api.sleeper.app/v1/players/nfl`;
        fetch(URL)
        .then(response => response.json())
        .then(data => {
            setAllPlayers(data)
        }).catch((e) => {
            console.log('Error:', e)
        })
    }

    useEffect(() => {
        getAllPlayers()
    },[])

    if(!allPlayers){
        return (
          <Loading />
        )
      }

    return (
        <AllPlayersContext.Provider value={{allPlayers}}>
        {children}
        </AllPlayersContext.Provider>
     );
}

</code>


When to use a dot or a tie in music notation?

Question: Let's say I have the following piece in 4/4, Should it be notated as:

or

Are there any specific rules? From my previous experience, I believe the second one is the correct notation since it shows all the beats in 4/4, am I correct?
Comment: And while we're at readability... does it really make sense to notate a guitar in (octave-) violin clef, if it's tuned down that low? I'd prefer bass clef, those ledger lines are a nightmare.
Comment: Both are acceptable, but the second is usually preferred because it's usually easier to read.
Comment: BTW, what's with this strange C-C♯-C♮ combination? Are you sure the notes shouldn't rather be simply C-C-C-E♭-C-C-D♭-C, e.g. with a key signature of 5 ♭s?
Comment: @leftaroundabout Yes I should have notated it as C-Db-C. Haven't got time to fix it in Guitar Pro. I agree I should have used the bass clef, but since guitarists mainly read tabs (and read the standard notation for precise rhythms), it doesn't make too much of a difference. Thanks for your input anyway!
Comment: The first example is definitely NOT acceptable.  I was going to say 'except in exceptional circumstances', but they would have to be VERY exceptional!  It obscures the pattern of 4 beats in the bar and is therefore hard to read.
Answer: Yep, the second one is far better for precisely the reason you say. A general rule is that you shouldn't have dotted-notes that start on an off beat and carry through the next beat. There are exceptions even to this rule, but showing the underlying beat structure of the meter is paramount in the vast majority of situations.
Elliott Carter is an example of a composer that often violates this notational rule (sometimes using four beamed dotted notes, occasionally even crossing the barline), but this is for the specific purpose of notating multiple simultaneous tempos. Even with that reason, an argument could be made that it isn't worth it due to the difficulty with reading it.
Comment: In 4/4 time, I'd say it's fine for a dotted quarter note to start on the "and" of beat one or three, since a dotted quarter note is expected to carry on through the next beat; no form of quarter note should generally cross from beat 2 to 3, however.  Any quarter note which starts in the first half of a measure should fit entirely within it; likewise any quarter note that starts in the second half.  As for having four beamed dotted notes, that would seem a little odd except in something like 6/8 or 12/8 time, and even there a duple bracket might be better.
Comment: +1 for "...showing the underlying beat structure of the meter is paramount...", though I wouldn't even qualify it as much as you did.
Comment: @supercat Yeah, that was the primary exception I had in mind. Carter's beamed dotted notes aren't (generally) in compound time, but I still think there's a strong argument for them. They are generally used in a part that is playing a passage that sounds like it's metered but at a slightly slower tempo than the other instruments. There's a decision to be made about whether to show the groupings of the slower tempo's meter or risk making something look syncopated that should sound regular. He tends to choose the former, but I think a good argument exists for both choices.
Comment: I disagree with calling it a rule, because it simply isn't. It's just that it's usually easier to read if you use a tie - so coincidentally, a _pattern_ emerged, not a rule -, but some rhythms are really a lot more  readable with dots than ties even if off-beat. Example: 4 notes in a 3/4 measure. I'd notate that with dots, not ties, because with dots, it is very clear all notes are of the same length, with ties not at all.
Comment: I'm with @11684 here, with my typography hat on. There are only very little _rules_ in typography in general. Mostly it's _conventions_. Whether an author/typesetter decides to stick to the convention or not is up to him. For instance, if you get loads and loads of these notes that break the pattern, then you probably use the dotted notation, since the reader very likely won't get the pattern anyway during the first reading, and you lessen the amount of things to read. But again, that's just my opinion and another typesetter will have a different opinion.
Answer: If you are referring strictly to music written obeying to traditional rhythmic conventions (with rational time signatures and regular/even division), then your second example is more suitable. Please keep in mind that the first example is not wrong, but the second will make sight-reading much easier, as our own expectations when seeing a piece in 4/4 make us search for known beat patterns.
One possible exception is the dotted quarter, which can be exchanged with a quarter tied to an eighth. For example, the following fragment

is orthodox regarding to rhythmic division, but

is easy enough to read and can be more straightforward for those who are used to this kind of rhythmic figure.
This exchange can be especially useful in 3/4 meter, when you want to avoid a 6/8 feeling. For example, in this fragment

the continuous repetition of the pattern can lead, by assimilation, to that feeling of 6/8 (counting "1, 2" instead of "1, 2, 3"), as the dotted quarter is the time unit for such compound meter. Using, instead,

will highlight the first, second and third beats, visually aiding the reader to not assimilate the beat pattern to a binary compound meter (well, I know it has also to do with beaming of the notes, but I think you got what I mean).
As Pat Muchmore said, you can "break" these rules when working with unusual/irrational time signatures, free meter or other ingenious procedures (as is common with Elliot Carter's metric modulation, for instance). In such cases, you are the judge of what is more suitable or appealing to what you are trying to accomplish.
Comment: that 3/4 example, to me comes out as a 6/8 feel, regardless of what I do to it. Help !!  I guess the first quaver would be slightly quieter in 3/4 time compared with it written in 6/8 ?
Comment: yes, it happens a lot, but can have nasty consequences; the truth is that 6/8 and 3/4 are unrelated (6/8 is not 'abnormal' 3/4). It is a **binary** meter; its compound signature is a way to circumvent an awkward irrational time signature like "2/3", as there is no standard undotted figure which express one and a half time on its own right. This way, you have a binary meter (similar to 2/4), but you have to fit three eights instead of two into each pulse. It should sound identically to a 2/4 meter filled with triplets (which is different from a ternary meter).
Comment: @Tim: For a concrete example where that rhythm is primary throughout the piece, but it's still clearly (at least to my ear) in 3/4, check out "This little Babe" from Britten's *Ceremony of Carols*.
Comment: @Tim, the 3/4 should be counted (in eights) "ONE two THREE four FIVE six", or "ONE & TWO & THREE". 6/8 should be counted "ONE two three FOUR five six", or "ONE & & TWO & &". Please refer to [this](http://a5.tf/Gh8) example to illustrate what I mean.
Comment: thanks, yes, I appreciate that, but to me it still feels the same, either way.I'd have probably written it 6/8, 'cos that's the final outcome (for me). Unless the rest of the piece is 'normal' 3/4.
Comment: @Tim Yes, in an example like the one given, the rest of the piece (or at least the measures immediately surrounding the given phrase) would almost certainly be in what you call "normal" 3/4 time; this is typically called a hemiola. To get more of a 3/4-time feel (and less of a hemiola feel), try emphasizing the first eighth-note on beat three of measures one and three.
Comment: @Tim 3/4 has natural slight accents on each downbeat. So does 6/8, if you say 1 and 4 are the down beats. So the 6/8 example is **1** **4**-5-6 | **1** **4** | **1** **4**-5-6 | **1** **4** ||, while the 3/4 example is **1** &-**3**-& | **1** ***&*** | **1** &-**3**-& | **1** ***&*** ||. (The up beat is emphasized due to being syncopated).
Comment: @Tim, actually, the more I think about it, it seems the main difference is just that the first eighth note in the 6/8 version is emphasized, while the first eighth note in 3/4 version is deemphasized a bit and the second one is emphasized. Though, honestly, the easiest way to do them differently is just to have the beat under you in some way, maybe tapping along, or having a metronome.
Comment: You miss a good option here. In LilyPond notation: `f4. f8 f[ f]` (i.e., the first of the 8th notes having a flag and the other two being connected by a beam). That's what I would do if I wanted to clearly indcate a `4 4 4` rhythm.
Answer: Here's a common chart showing how the notes break down:

Notice how each row is a full measure in 4/4.  The general rule is that a note can span its direct children, or one of its children and one of its nephews.  That is, a quarter note can span the 2nd and 3rd eighth notes, but not the 4th and 5th.  A dotted note can only borrow from its sibling, not its cousin, so a quarter note can span eights 1-2-3 or 2-3-4, but not 3-4-5.
Your first example has the 3rd eighth note of the bar borrowing from its cousin, the 2nd eighth note.  So this is "bad".  The second way would be the proper way to write it.
Note that there are always exceptions to every rule, but it's good to follow the rules unless you have a really good reason not to.
Answer: The ideal is to keep each beat self-contained, so the second is preferrable.In 4/4 it's certainly best to keep each half of the bar separate, so anything which goes between beats 2 and 3 are shown as tied.It's easier to read, and the ties actually make you aware that the tune is syncopated.The same thing should happen in 6/8 too, which is effectively two halves of each bar. Some more modern composers and re-writers don't feel the need to do this. Change will happen slowly, but for now, at least, let's keep it easy to read - and probably easier to write (longhand at least).
It's good to see the dots alongside tab, so the rhythm can be followed, not guessed !
Answer: Correct.  There is a subjective component to this decision, but you generally want to keep the placement of the beat as clear as possible.
The rule of thumb is that when a note doesn't begin on a beat, it should not cross into another beat without a tie, unless the notation is simple enough (e.g. quarter, half, quarter) that there is no ambiguity in how the rhythm lines up with the beat.
Answer: It is a question of style.  The music of the last centuries is not subtle regarding its rhythmic stresses.  However, Renaissance and also some Baroque music does not have the same forced substructures of today's rigid meters as well as a central beat, so the "helpfulness" of substituting more complex note constructions for a rhythmically shifted variant of a straightforward melody is limited and sacrifices the self-consistency of the melody for adherence to a metronomic meter that may not even be dominant in the other voices.
The notation impacts the performance.  While percussive instruments like pianos and drums are not really in much danger here, continuous sound instruments like vocals, bowed strings, and wind instruments have a tendency of putting additional stress on the on-beat parts of syncopated notes.  Which sort of defeats the whole point of syncopation.
Renaissance music consequently often tends to be notated using "floating barlines" between the staves where not even a barline is sufficient grounds for subdividing a note value into an off- and on-beat part.
While the same is no longer customary in Baroque music, the execution of syncopated passages is still very much expected to be indistinguishable from a shifted version of the original melodic fragment.
This kind of non-syncopated syncopation stops being feasible when "swinging" meters come into play where the central rhythmic framework is so rigid that time can be warped around it and on-beat notes have different lengths from off-beat notes.
Basically these days, every music piece is what was previously considered a dance regarding the prevalence of a real or imaginary driving beat.  In that context, not burying an on-beat in the middle of a note makes perfect sense, notationally giving the central meter priority over the inner melodic logic of a voice.
Answer: As others said, the second form is probably more common, but I'd like to put in my own opinion.
Since the 3:3:2 rhythm is common in music I deal with, I prefer to notate it additively (like your first option, with the first three notes all beamed together). This option also looks cleaner, at the cost of being difficult to recognise for people unfamiliar with the rhythm.
Answer: At the end of the day it's really a matter of preference to the composer. Most of the responses that I've read claim the second example is 'right' or 'easier to read' but those are truly opinions. It is my opinion that the first example is preferable, and that's the one I'd use.
It has to do as much with how I was taught to read sheet music as it does the music itself. I would only use a tie as a slur between two different notes, and it's mathematically more complicated for me to read it in the second example. The dotted eighth in the first measure represents 3/16th of a beat. The tie in the second measure demands that I add 1/16th & 1/8th together, leading to extra math and at the very least a more difficult sightread.
While it is a purposeful goal to make the music you annotate or compose legible and understandable, there is no real right or wrong here.
Comment: Writing music is a form of communication. It's not just a matter of preference, you have to take into account a lot of conventions and the like so that the message gets through. In this case it's better to not only express the mathematical length of the note but also its relation to the underlying meter or beat structure if you like; that facilitates playing together. Furthermore, a tie and a slur may look similar but they have very different meaning.


debian ssh connection refused after update reboot

Question: Locked out with SSH from server after a Debian Jessie update and reboot(connection refused).
No websites came backup after reboot but can ping the server.
Can get to the server with host's Ubuntu Rescue via SSH, however at a loss what to do after mounting the boot disk. Logs don't appear to show anything, but am still looking.
There was an SSL certs problem after the updates, which was trying to fix before the server went dead and I decided to reboot.
Any docs or pointers as to what to check to get server back by using the Rescue mode?
Comment: Assuming you use VMware, hyperV or any other virtualization thingy: What does the Console tell you?
Comment: Not using any virtualisation thingy, and no logs since the original reboot.
Comment: So you are able to access the server?
Comment: Yes with Ubuntu Rescue OS, have mounted the boot disk searched logs, etc... in /mnt/
Comment: But are you able to boot the system?
Comment: Nope looks like boot config is broken as zero logs get written
Comment: You should change the question and the title to match the problem
Answer: As no error logs had been written since the original reboot after software upgrades using the Rescue OS was pretty useless in diagnosing a problem.
By getting access to KVM and watching the reboot from the console seeing that it failed at a network issue, bypassing and continuing with the boot.
Although the problem of why the network error occurred on reboot is yet to be found, brought the server back up online from the KVM console by checking 'ip a' to show the network interfaces and address, then brought it up with 'ifup eth0' and was able to access by SSH, and all sites came back.
Comment: "Nope looks like boot config is broken as zero logs get written – tjcham 18 hours ago"


Page flip effect same as FlipBoard app?

Question: I want to make the pages flip effect same as FlipBoard app (here).
Here is same post but I can't use this answer (the github link died!).
Below is some screen shoot:

Answer: Check out AFKPageFlipper on GitHub

Page flip effect same as FlipBoard app?


Writing to a .txt file (UTF-8), python

Question: I want to save the output (contents) to a file (saving it in UTF-8). The file shouldn't be overwritten, it should be saved as a new file - e.g. file2.txt
So, I fists open a file.txt, encode it in UTF-8, do some stuff and then wanna save it to file2.txt in UTF-8. How do I do this?
import codecs
def openfile(filename):
    with codecs.open(filename, encoding="UTF-8") as F:
        contents = F.read()
        ...

Comment: "The file shouldn't be overwritten".  Why is there only one open if you are reading one file and writing a new file?
Comment: because this is an unfinished code. ...
Comment: "because this is an unfinished code"?  What?  "unfinished" isn't a good explanation for the mismatch between your requirements and your code.  Why is there only one open?  Please fix your code to match your requirements a little better.
Answer: The short way:
file('file2.txt','w').write( file('file.txt').read().encode('utf-8') )

The long way:
data = file('file.txt').read()
... process data ...
data = data.encode('utf-8')
file('file2.txt','w').write( data )

And using 'codecs' explicitly:
codecs.getwriter('utf-8')(file('/tmp/bla3','w')).write(data)

Comment: the file 'file2.txt' when opened in notepad isn't utf-8 encoded, probably because I decoded the data using codecs (import codecs) and when saving it to a file a use a different way as you suggested (using encode method). THe question is how do I encode it using codecs?
Comment: @Gusto - I added a separate method, although it's completely equivalent. How can you see in notepad that a file is not utf-8 encoded? notepad actually does the decoding for you.
Comment: I can see it because the Cyrillic characters are not properly   displayed, I have to decode it manually using the notepad encoder.
P.S. Using Notepad ++
Answer: I like to separate concerns in situations like this - I think it really makes the code cleaner, easier to maintain, and can be more efficient.
Here you've 3 concerns: reading a UTF-8 file, processing the lines, and writing a UTF-8 file. Assuming your processing is line-based, this works perfectly in Python, since opening and iterating over lines of a file is built in to the language. As well as being clearer, this is more efficient too since it allows you process huge files that don't fit into memory. Finally, it gives you a great way to test your code - because processing is separated from file io it lets you write unit tests, or even just run the processing code on example text and manually review the output without fiddling around with files.
I'm converting the lines to upper case for the purposes of example - presumably your processing will be more interesting. I like using yield here - it makes it easy for the processing to remove or insert extra lines although that's not being used in my trivial example.
def process(lines):
    for line in lines:
        yield line.upper()

with codecs.open(file1, 'r', 'utf-8') as infile:
    with codecs.open(file2, 'w', 'utf-8') as outfile:
        for line in process(infile):
            outfile.write(line)

Answer: Open a second file. Use contextlib.nested() if need be. Use shutil.copyfileobj() to copy the contents.

Writing to a .txt file (UTF-8), python


Constrained Optimization

Question: I am taking an intro real analysis course and we just covered constrained optimization.I remember the Lagrange multiplier method from multi variable calc, but I want to understand the reasoning behind the theorem a bit more.  As an example, in Multi-variable, a problem such as optimize
$f(x,y)=x-y$ subject to $x^2-y^2=2$ was considered a degenerate case. This is because if you actually use Lagrange multipliers, you get
$1=2\lambda x$, $-1=-2\lambda y$ which gives $x=y$. Obviously, with the constraint, this is not useful. I was trying to understand why the theory broke down here, and it occurred to me that the hyperbola $x^2-y^2=2$ is not compact! I believe the theory breaks down when the constraint is not compact (Heine Borell applies here and this curve is unbounded). So, I believe the maximum is $(x,y)=(\sqrt{2}, 0)$ but I see no obvious way to find the min (assuming their is one!)
Can someone give me some intuition as to why this theorem is breaking down?
Answer: There is no "breakdown", nor a "degenerate case" here. Lagrange's method has truly reported that the given objective function $f(x,y):=x-y$ has no conditionally stationary point on the hyperbola $\gamma: \ x^2-y^2=2$. (The geometric reason behind this is that $\gamma$  has no points where the tangent is parallel to the level lines of $f$.)
Of course the question remains whether $f$ assumes  global extrema on $\gamma$. Now it is easily seen that in the points $\bigl(x,-\sqrt{x^2-2}\bigr)\in\gamma$ the function $f$ assumes arbitrarily large values  when $x\to\infty$. It follows that a global maximum does not exist, and by symmetry a global minimum does not exist either. As $\gamma$ is not compact we should not be too surprised.

Constrained Optimization


Como usar o laço para(for) em Portugol?

Question: Estou aprendendo algoritmo, mas fiquei na dúvida quanto ao uso de Laço para (for). Sei que é uma pergunta tola, mas infelizmente tenho pouco acesso a internet. Eu tenho o livro mas a duvida é essa!
Comment: Qual é a linguagem? O laço `for` costuma ser bem parecido de linguagem pra linguagem, mas ainda assim seria bom especificar. E não entendi bem sua pergunta: você disse que ficou na dúvida, mas em relação a que? Sua sintaxe, semântica, outra coisa... Se puder [edit] acrescentando mais detalhes seria muito bem vindo!
Comment: em portugol mesmo.
Comment: Relacionado: ["não consigo aprender sintaxe for"](http://pt.stackoverflow.com/q/33674/215)
Answer: O laço "para" é uma das formas de desvio condicional, ou seja, teste se uma determinada condição é satisfeita, e dependendo do resultado, desvie para uma instrução diferente ou siga pra próxima. Ela é composta de quatro partes:
para ( iniciação ; condição ; passo )
    corpo
fimpara

próxima instrução

A iniciação é simplesmente um código que executa antes de iniciar o laço; dependendo da linguagem, qualquer variável definida ali somente existirá dentro do código desse laço. Em outras, ela continua existindo fora dele.
A condição é um teste para verificar se deve continuar dentro do laço ou sair fora dele. Tipicamente ela é testada após a iniciação, de modo que se não for satisfeita ele sai do laço imediatamente - sem executar o corpo e o passo nenhuma vez - e segue para a próxima instrução.
Se a condição for verdadeira, ele executa o corpo, depois o passo, e em seguida testa a condição novamente, para ver se ela continua verdadeira. Se continuar, repete essa etapa de novo e de novo. Apenas quando a condição se tornar falsa é que ele sai do laço, indo para a próxima instrução depois dele.
O corpo é o trecho principal de código, que será repetido zero ou mais vezes. Ele tem acesso às variáveis da iniciação e condição, e pode manipulá-las ou não. Também pode executar comandos que "forçam" a quebra do laço (break) ou que continuam a partir do passo (continue) antes de chegar ao final do corpo. Se esses comandos não forem utilizados, o corpo segue até o final, antes de passar pra próxima etapa.
O passo é simplesmente um código pequeno que executa após o corpo, mas antes de testar novamente a condição. Em geral, sua função é manipular a(s) variável(is) que compõe(m) a condição, de modo a dar-lhe a chance de sair do laço.

Um exemplo completo seria:
para ( seja i igual a 1 ; enquanto i for menor ou igual a 10 ; incremente i em 1 )
    imprima i vezes i, enter
fimpara
imprima "Fim"

Saída:
1
4
9
16
25
36
49
64
81
100
Fim

Todas as partes, exceto a condição, são opcionais. Se você omitir a iniciação e o passo, o resultado é o mesmo que um laço enquanto (while):
para ( ; teste() ; )
    faça algo()
fimpara

enquanto ( teste() )
    faça algo()
fimenquanto

A sintaxe mais comum para o laço "para" é aquela da família do C (inclui Java, JavaScript e outras):
for ( int i = 1 ; i <= 10 ; i++ ) {
    printf("%d\n", i*i);
}

Algumas linguagens, como Python e Ruby, não possuem esse laço, apenas um de nome parecido - o for..in, usado para percorrer os elementos de uma lista (real ou abstrata). Muitas vezes esses laços são referidos como simplesmente for, mas sua construção é diferente.
Em portugol, o laço "para" com uma única variável fica mais ou menos assim (não tenho certeza da sintaxe exata):
para ( i de 1 a 10 passo 1 ) faca
    escreva(i*i)
fimpara

Answer: O para .. faca (faça) é uma estrutura de repetição do portugol com variáveis de controle, e serve para que você execute um determinado bloco de código interno por n vezes.
Um exemplo simples:
algoritmo "contador"
    var
    C: inteiro
inicio
      Para C <- 1 ate 10 faca
      Escreva (C)
      Fimpara
fimalgoritmo

A saída deste algoritmo no Visualg será:

1  2  3  4  5  6  7  8  9  10
* Fim da execução.
  * Feche esta janela para retornar ao Visualg.

Além da utilização do Visualg em seus estudos, aconselho também que você assista esta aula, e consulte este manual.
Bons estudos.
Answer: Em outras palavras a função irá fazer a mesma tarefa um certo número de vezes
Exemplo numa corrida:
Irá começar com a volta 0 // int x = 0; (no modelo do Lucas Henrique)
Terá 100 voltas // x <= 100; (no modelo do Lucas Henrique)
Para cada volta completada acrescente +1 //  x++; (no modelo do Lucas Henrique)
Abaixo desta declaração você informa o que o programa irá fazer, no caso da corrida iria executar a função correr até completar as 100 voltas.
Espero ter ajudado
Comment: valeu.. ajudou muito
Comment: Então se puder, vote na questão, no lado esquero da minha resposta, sabe fazer isso?
Comment: O AP ainda não tem reputação suficiente para votar (precisa de 10). A propósito, `for ( int i = 0 ; i <= 100 ; i++ )` vai executar `101` vezes, não `100`.
Comment: Verdade mgibsonbr 101 vezes, ;)
Answer: for(int x = 0; x <= 10; x++)
{
   //código que irá ser incrementado
}
sendo que int x = 0 => está criando uma variável inteira x que recebe 0, que é o ponto de partida do seu laço de repetição. Ou seja, ele vai começar em 0.
x<= 10 => ele vai executar até que a condição seja menor ou igual a 10.
x++ => é a incrementação do seu laço. Nesse caso, representa que ele vai somar o valor inicial a cada iteração.
Comment: "vai executar até que a condição seja" acho que você quis dizer "enquanto a condição seja", certo? (ou até que a condição seja falsa...)
Answer: O for costuma ser usado para fazer iterações (definidas pela linguagem ou por um recurso da linguagem) ou também como um loop condicional definido da seguinte maneira:

Valor da variável de escopo a ser criada
Condição de existência do loop
Função incondicional do loop

Em relação às duas possibilidades, tomo Python e C. Iteradores:
for x in range(0,100):
    # faça o que quiser aqui com "x"

E com a condição:
for(int x = 0; x <= 100; x++)

Comment: opa valeu ai!!!
Comment: @LeonardoSales Seja bem vindo ao StackOverflow, você deve escolher uma resposta, faça um tour para entender como funciona o : http://pt.stackoverflow.com/tour

Como usar o laço para(for) em Portugol?


When I change theme, I can't see my sidebars

Question: I am a total n00b, just trying to set up my first site.
I got something nice with the Bartik theme, then realized that I wanted drop-down menus on the main menu, so decided to try another theme.
I tried both Corolla and Martinelli, but when I set them as default theme I can't see my sidebars or footers.
The are still set up as they were for Bartik and if I switch back to that then I see them again.
Obviously, this is just some stupid n00b thing, like not knowing to rebuild the front page or something. Can anyone tell me what I am doing wrong? Thanks.
Comment: I have the exact same problem. No matter which themes I activate, under "admin/structure/block" only the BARTIK and SEVEN tabs are showing up. Even if I disable BARTIK, it's shown. I can't configure the blocks for my theme
Answer: Because themes haven't the same region names, after changing your theme you must go to admin/structure/block and re-assign blocks to regions.
Comment: @Mawg: First clear cache from here: admin/config/development/performance
Comment: I thought it must be something like that. But when I go there I only see tabs for Bartik and Seven, not for either of the two themes which I added. Any idea how I administer Martinelli or Coralla?  They do appear to be installed correctly, as they are in the list of themes under admin/appearance and if I set one as default, the site layout changes - but I can't see those blocks and I can't see how to administer them.  Heeeeeelp
Comment: +1 thanks. Hope you can help further withmy comment above
Comment: +1 Thnaks. Another good tip, but unfrotunaely it did not work. Can it be that I have the themes "half installed? That is - modules won't install without their dependancis, but maybe themes will? Maybe I should read the relaease notes agin, just to be sure
Comment: Strange!! I had given up on this and just went back to that page a week or two later and saw that it now works. Maybe some of the updates, or disabling a few modules to try to speed it up, or updating drupal core? In any case, it suddenly works and I don't know why.  Thanks for all your help
Answer: Go to Admin/structure/blocks. The tabs at the upper right of the form allow you to select your theme.  arranging the blocks in one them does not change them in every theme so you must Verify their location in the new themes. You should find the missing blocks at the bottom of the form in the 'Disabled' category.
Comment: If your themes are enabled on the admin/appearance form they should show up in block tabs.  Where in the site directory do you have them?  Each should be in a subdirectory under sites/all/themes/...
Comment: I'm GMT-5. What is RTFM?
Comment: +1 Thanks for taking the time to reply. I will try that later and get back to you. Pelase check this question anagin in 8 hours or so. Thanks.
Comment: My problem seems to be that I can see tabs at the top of Admin/structure/blocks for Bartik and Seven, but not for Corolla or Martinalli.  Coudl it be that they are not completely and correctly installed? Although they do show up in the list of themes under admin/appearance
Comment: +1 sorry about the delay. I think we are in very different time zones (I am GMT +8).  Since I installed them both by giving the URL of the initial release I would not expect problems (just my bad luck, I suppose). Yes, I can confirm that there are directories named for the themes where you think they should be. And, yes, the themes are enabled.    I will go and RTFM again
Comment: so, we are almost opposite each other on the clock.   RTFM == read the "friendly" manual. And I still can't see those themes in the tabs of Admin/structure/blocks - even though they are installed (from the URL) and enabled


RxJava, How to update views at different states of Observables call chain?

Question: I need to perform one task using one Observable, obtaining the emitted data, then using another Observable to do another query.
Normally I would use a flatmap to chain the two Observables and just caring about the final piece of data emitted.
Now there's a need to update the view during the process. Say when the first Observable emit data, I should show a text line on the UI.
I know I can break it down to two call times, calling the 2nd Observable inside onNext() of the first one, but that's cumbersome.
How can I achieve what I described above without going down that path?
Thanks
Answer: Here is an example from ny old project with doOnNext():
API.getVideoListObservable()
                .doOnError(t -> t.printStackTrace())
                .map(r -> r.getObjects())
                .doOnNext(l -> VideoActivity.this.runOnUiThread(() -> fragment.updateVideoList(l)))
                .doOnNext(l -> kalturaVideoList.addAll(l))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe();

Pay attention to the .doOnNext(l -> VideoActivity.this.runOnUiThread(() -> fragment.updateVideoList(l))) - after it you can use flatmap() any times, and doOnNext() will be executed before flatmap()
Good explanation of doOnNext() by Simon Baslé here:

doOnNext is for side-effects: you want to react (eg. log) to item
  emissions in an intermediate step of your stream, for example before
  the stream is filtered, for transverse behavior like logging, but you
  still want the value to propagate down the stream.
onNext is more final, it consumes the value.


Child element appearing AFTER as opposed to IN the element when appended using jQuery

Question: I am appending the following using jQuery:
var dateWrapper = '
'+kendo.format('{0:dd MMMM yyyy}',new Date(date))+'

'
$('.wrapper').append(dateWrapper)

I want the triangle to appear inline or inline-block with the date. Once appended the DIV is placed after the P, and not inside. Cannot fathom why this would happen.
Comment: From the given code, others will have a tough time fathoming it too. Please provide more code, especially your `date` and `triangle` classes. Also, `div` is by default `position:block`, so set it to `inline-block` if you haven't already.
Answer: You can not put div inside p tag. It will automatically put it outside the p tag. You should use..
var dateWrapper = '
'+kendo.format('{0:dd MMMM yyyy}',new Date(date))+'
';
$('.wrapper').append(dateWrapper);

In css
.triangle{
display:inline;
}

Comment: `Span` elements are already `display: inline` by default, no need for extra CSS.
Answer: According to the HTML5 documentation ( and as far as i know it's the same for older versions ) , p accepts as children only pharsing content
p element
Pharsing content means plain text or pharsing elements which include ,, etc. but not

pharsing content
So a structure like

 is not a valid HTML5 structure, so it is automatically converted into

 .
In conclusion you CAN NOT nest div inside p and that's why you don't get the desired result. I suggest, in your case, change the triangle from div to span


How to aggregate time-series data?

Question: I have two types of short length time series data (from day1-day5) as follows.
Type1 (Temperature at location1):
sensor1, 38, 38, 35, 33, 32
sensor2, 33, 32, 35, 36, 32
and so on ....

Type2 (Temperature at location2):
sensor1, 18, 18, 12, 11, 09
sensor2, 13, 12, 15, 16, 12
and so on ....

Since, the sensor that we use in both locations are same, I am just wondering if it is correct to aggregate the two time-series as follows and anaylyse the pattrens.
Aggregation of Type1 and Type2:
sensor1, 38, 38, 35, 33, 32, 18, 18, 12, 11, 09
sensor2, 33, 32, 35, 36, 32, 13, 12, 15, 16, 12
and so on ....

The reason why I thought to aggregate the data is that I thought it would give me more patterns than analysing them alone.
Please let me know your thoughts.
I am happy to provide more details if needed.
Comment: If you paste them columnwise, you are pretending `sensor1:location1` is the same as `sensor1:location2`. You would also be ignoring the temporal structure, unless all measurements at `location2` were performed after those at `location1`, which would be an unfortunate study design. You should probably read into spatiotemporal autocorrelation using mixed models, or maybe vector autoregression, but it is hard to say as you've provided no clear research question or goal other than to find patterns.
Answer: Adding to the first comment, I would recommend you to have it as channels. i.e. whole data becomes 3 dimensional, which can be still processed by deep learning models.
Let me put it clear,
Dimension 1 - rows
Dimension 2 - Sensors
Dimension 3 - Location
so your data will look something like this
[[[38, 38, 35, 33, 32],
  [18, 18, 12, 11, 09]],
 [[33, 32, 35, 36, 32],
  [13, 12, 15, 16, 12]]]

This way it will make more sense to the model as well.
Comment: how you have your data ? Do you have in csv, text files or consuming from an API ?
Comment: okay. Hope you are using python. You can ignore the text containing sensor, and read the data as whole. Hopefully the number of values from each sensor are same. You can reshape them using numpy.

for example, if it is like a=[1,2,3,4] and if you use numpy reshape function to make it a multi dimensional array as [[1,2][3,4]]  by using np.reshape(a,(2,-1))
Comment: Hi, I looked at the other question, if you are planning to use LSTM, then the data can't have multiple channels. So you dont need to reshape. So basically your data will become of shape (num_samples, timesteps, features)  where features is 10 now, 5+5. Since yours is a binary classification, i dont think there will be a problem in giving them as a single sequence.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/96238/discussion-between-venkat-krishnan-and-emj).
Comment: thanks a lot for the answer. I am new to deep learning. It would be really great if you could show me how I can insert such data to a deep-learning based binary classification problem :)
Comment: I have my data in a csv file as `sensor1, 38, 38, 35, 33, 32
sensor2, 33, 32, 35, 36, 32` :)
Comment: please let me know your thoughts on this question: https://datascience.stackexchange.com/questions/55752/how-to-input-data-to-lstmautoencoder
Comment: please check the chat. thank you :)

How to aggregate time-series data?


laravel:image file, unlink( public_path() ) not working and show permission denied

Question: My code is here:
<code> if(Input::hasFile('image'))
    {

        if (File::exists(public_path("user_images/{$users[0]->image}")))
        {
          // delete image from folder
          unlink(public_path("user_images/{$users[0]->image}"));
        }
        $file = Input::file('image');
        $name = time(). '_' . str_random(20). '_' . $file->getClientOriginalName();
        $file = $file->move(('user_images'), $name);
        $uUpdate = User::updUserProImg($userId,$name);
    }
</code>
Error :

unlink(E:\xampp\htdocs\o2schools\public\user_images/): Permission
  denied

How can I solve it?
Comment: Make sure you have the proper delete permissions enabled on the folder you wish to delete from.
Comment: But I use windows , is here need folder permission?
Comment: yes. Also make sure to apply the permission to the correct user or users.
Comment: Did u get ever resolve this? If yes, kindly explain your solution
Answer: You can use Storage::delete($filePath)


Running multiple background Java processes on Linux

Question: I have a jar file that runs continuously and acts on various events.  I need to create multiple instances of this jar, passing parameters to it on start up, and have it continue to run between shell sessions, reboots, etc.  I'm planning to write an init.d script that has the command for each instance I need, passing in the appropriate parameters for each, and having it execute on boot.  Does this sound like the correct approach?
It's possible that one of these instances can get stuck or crash, and I'll need to go in and restart it manually.  I'm also wondering if there's a way that I can name each process that gets created, so when I look at top I can determine which process is which?
Answer: init script sounds fine. You should parameterise it via some config in /etc/, though.
You can get the PID of each of the java processes after starting them and then permanetly check if all are still running, and if not, restart.
It is better to use an application level monitoring (depending on what the processes do) and act based on that. Just because the process is still there it doesn't mean it is doing what it should.
Comment: Good point.  I could create a simple web page displaying the status of each.


Prediction interval vs. confidence interval in linear regression analysis

Question: I know such a problem is explained many times, but I have still a problem with the concept and interpretation:
I would like to estimate export weight for 2016

The red point is estimated point
red lines are  prediction interval
blue lines are confidence interval

As I understand the actual export weight for 2016 is between the red lines with probability 0.95 (95% prediction interval)
and the parameter of fitted model: (here $\beta_0$ and $\beta_1$)
$$\mathit{Y}=\beta_0+\beta_1X_1+\varepsilon$$
are between both blue lines confidence interval. That means possible green lines are between both blue lines (confidence interval)
My Question:
If all possible green lines are between confidence interval, then there is not possible to have the estimated point outside the confidence interval. But we have determined, it is possible to have an estimated point between red line or prediction interval.
How can I interpret it correctly
Comment: Your interpretation "all possible green lines are between confidence interval," is not correct
Comment: To make it more confusing, the prediction interval is only 95% correct when the assumptions are 100% correct. To me, it looks like the assumptions are not correct, or at least not very useful. So the 95% prediction interval is (in practice) not really a 95% prediction interval.
Answer: The blue lines don't matter for your prediction. You can see what happen with your data, because it's the same you can expect to happen with your predictions. Please notice that some past observations fall outside of the blue lines, but most of all (about 95%) fall between red lines. That is what we should expect to happen with your predictions: although you have a single red point, the real (future observed) value is expected to fall anywhere between red lines 95% of times.
If we return to your model we can see better what both colours of lines mean. Your model is:
$$\mathit{Y}=\beta_0+\beta_1X_1+\varepsilon$$
Where $\beta_0$ and $\beta_1$ are unknown parameters we only can estimate and $\varepsilon$ is a random variable.
The blue lines are confidence intervals for $\beta_0+\beta_1X_1$, that is, intervals for the green line, but please notice that that is not the future observation (that is just your point estimation of it). Your future observation will include an $\varepsilon$ term which will cause more variability, and the red lines account for that extra variability.
Edit:
It was asked (and answered) in comments what are the blue lines useful for. For completeness, this is the answer:
If you are predicting future observations, confidence intervals (blue lines) don't have a direct use. However they can be useful sometimes. I give a couple of examples:

When epsilon stands for an error of measurement, we are usually more interested in predicting means than in predicting observations. Then, blue lines are more useful than red ones.
Blue lines show how much can we improve predictions by increasing sample size. If blue lines are nearly as apart as red lines, we could improve a lot our predictions with a larger sample; in the opposite case there is very little to gain.
Comment: If you are predicting future observations, confidence intervals (blue lines) don't have a direct use. However they can be useful sometimes. I give a couple of examples: 1) When epsilon stands for an error of measurement, we are usually more interested in predicting means than in predicting observations. Then, blue lines are more useful than red ones. 2) Blue lines show how much can we improve predictions by increasing sample size. If blue lines are nearly as apart  as red lines, we could improve a lot our predictions with a larger sample; in the opposite case there is very little to gain.
Comment: Thanks Pere, then I can say, that the Confidence intervals doesn't play any roll in the quality of prediction point. I cant steel understand, how does confidence interval help us? and why we need confidence interval in prediction
Comment: Why does the red line also not expand out like the blue line?  I would imagine that it should also.
Comment: @confused - That might be another good question.
Comment: @confused, it does, but the range of x is too small for it to be immediately visible.


Ocultar uma div e mostrar outra

Question: Boa tarde! Tô tentando resolver um probleminha (creio eu ser simples).
Fiz um script para mostrar/ocultar as divs porém não estou conseguindo fazer com que quando eu aperte no botão 2, ele oculte a div do botão 1 (ou todas as outras caso tenha mais de 2 divs).
A idéia é sempre ficar mostrando apenas uma div na tela, independente de quantas tenham.
Exemplo:

    function mostrar(id) {
      if (document.getElementById(id).style.display == 'block') {
        document.getElementById(id).style.display = 'none';
      } else {
        document.getElementById(id).style.display = 'block';
      }
    }
<!DOCTYPE html>

Botão 1

 1- texto que eu quero ocultar/mostrar

Botão 2

 2- texto que eu quero ocultar/mostrar

Answer: Você pode ocultar todos os elementos efetuando um loop pelo nome classe, após isso mostrar somente a div pelo id.

function mostrar(id) {
  if (document.getElementById(id).style.display !== "none") {
    document.getElementById(id).style.display = "none";
    return;
  }
  Array.from(document.getElementsByClassName("hidden")).forEach(
    div => (div.style.display = "none")
  );
  document.getElementById(id).style.display = "block";
}
.hidden {
  display: none;
}

Botão 1

 1- texto que eu quero ocultar/mostrar

Botão 2

 2- texto que eu quero ocultar/mostrar

Comment: esse código falha se clicar duas vezes no mesmo botão, uma exibe, depois não oculta
Comment: Obrigado pela dica Wellington, em partes o problema foi resolvido, já me ajudou à mostrar sempre apenas uma div, porém como o Ricardo falou realmente ele não oculta se apertar no botão novamente, mesmo com esse outro código que você citou abaixo. Teria outra forma de corrigir isso?
Comment: Alterei o código para ocultar. Abraços!
Answer: Um jeito simples seria esconder todos os divs que deseja e depois tratar só o que foi clicado.
Tem várias maneiras de fazer isso, mas para deixar o código mais próximo do seu e ficar fácil de entender, esse exemplo faz o seguinte:

salva o display atual do elemento que passou o id;
esconde todos;
exibe/esconde o que foi passado o id:

function mostrar(id) {
    // salva o display atual, pois abaixo irá esconder todos os divs
    var display = document.getElementById(id).style.display;

    // pego todos os div. Esse é só um exemplo, seria melhor usar um seletor mais acertivo, senão todos os divs da pagina irão sumir
    var divs = document.querySelectorAll("div");
    // esconde cada div
    divs.forEach((div) => {
        div.style.display = 'none';
    });

    // aqui, a lógica que tinha feito
    if (display == 'block') {
        document.getElementById(id).style.display = 'none';
    } else {
        document.getElementById(id).style.display = 'block';
    }
}
.hidden {
   display: none;
 }

Botão 1

 1- texto que eu quero ocultar/mostrar

Botão 2

 2- texto que eu quero ocultar/mostrar

Answer: Mais ou menos assim

function toggleDiv() {
  if(document.getElementById("exemplo1").style.display == 'none') {
    document.getElementById("exemplo1").style.display = 'block';
    document.getElementById("exemplo2").style.display = 'none';
  } else {
    document.getElementById("exemplo1").style.display = 'none';
    document.getElementById("exemplo2").style.display = 'block';
  }

}
#exemplo1 {
width:100px;
height:100px;
background-color:#FF0000;
}

#exemplo2 {
width:100px;
height:100px;
background-color:#00FF00;
}

<button onclick="toggleDiv()">Sumir uma div e aparecer outra</button>

Ocultar uma div e mostrar outra


Criar um data frame separando termos de uma string em colunas

Question: Como faço para criar um data.frame separando cada termo ligado por _ em colunas
"WZ_311205_20131007_20131008113131_RUA_RAMAL_FARIA_TEMP_DATA_ _AVENIDA_DADOS_PORTO_9.xml"
"WZ_311205_20131007_20131008113131_RUA_RAMAL_FARIA_TEMP_DATA_ _AVENIDA_DADOS_PORTO_10.xml"

Answer: Para fazer isso, tu pode utilizar a função stringr::str_split_fixed:
df <- structure(list(V1 = c("WZ_311205_20131007_20131008113131_RUA_RAMAL_FARIA_TEMP_DATA_ _AVENIDA_DADOS_PORTO_9.xml",
"WZ_311205_20131007_20131008113131_RUA_RAMAL_FARIA_TEMP_DATA_ _AVENIDA_DADOS_PORTO_10.xml"
)), class = "data.frame", row.names = c(NA, -2L)) # Leitura da base de dados

ncols <- max(apply(df, 1, function(x) str_count(x, "_")))+1 # Número de colunas a serem criadas + 1

stringr::str_split_fixed(df$V1, "_", n=ncols)


What is a Cminor chord in the key of Aminor?

Question: Let's say the part of the progression in question is Cm, Am, Cm Am but before this there is a sequence of chords that are clearly in Aminor. This Cm chord sounds great and dark but it is not part of Aminor and it is not from Amajor either so where does it come from? Is there any key that has this progression?
Comment: While there may not be a key where that progression commonly exists, all of the notes in question (`A C D#/Eb E G`) exist in the E Harmonic Minor scale (`E F# G A B C D# E`).
Comment: Check out my comment on Tim's answer; should clear up any misconceptions.
Answer: No, there is not a key which has this progression. We all seem obsessed that every different chord sequence, etc., must have a theoretical explanation - it comes up weekly.
Theory is put into place by us, as a way to explain what is happening. Here, the usual theory is the use of borrowed chords, here from the parallel key.
In reality it's not much of an explanation, but it gets us by. After the seven chords which are most often used in a key - the diatonic ones - it appears that the next lot that get used are from the parallel key. That of the same name, but major or minor. Am comes from the key C major, so it sounds reasonable to use chords from its parallel C minor, exactly what is happening here. The same sort of sequence starts 'Light my Fire'.
Comment: Not parallel, it would be "relative" here. Also, this would fit under the umbrella of "modal mixture". Lastly, we do actually have a term for this, the relationship between the two chords is called a "chromatic mediant".
Comment: @jjmusicnotes  - seems to me parallel and relative.
Comment: It can be one or the other but not both. Parallel would be altering the pitch collection while keeping the tonal center (eg - A maj vs A minor). C and A are relative to one another, tonally speaking.
Comment: Light my fire goes to F#m not Cmin but I like the sound of this too. So Would the F#min come from the relative Amajor scale here?
Comment: 'Light my fire goes Am>F#m, which is the same idea as Cm>Am, isn't it? So, assuming the key of Am, parallel A maj., relative min = F#m. A bit complicated, but surely merely the fact that it works is sufficient. Isn't it..?
Answer: Of course there can't be a single key with that progression because the A minor chord has the note E, whereas a C minor chord has an Eb. Note that the keys of A minor and C major are relative keys, i.e., they share the same notes. So moving from A minor to C minor is like moving from C major to C minor (the parallel key). This is something you see quite frequently. So the movement can be compared with the movement from major to minor (hence dark).


Adding disabled option in codeigniter form_dropdown

Question: I'm trying to figure out how to add a disabled option in my dropdown, using codeIgniter. New to CI, and I've tried googling it a bit, but couldn't find an answer.
My code for a dropdown looks like this:
    echo form_dropdown('category', array('0' => 'Choose a category...')  + $categories, '0');

This gives me a dropdown with all my options from the variable $categories, with "Choose a category..." (value 0) at top. Now how to I make the first one disabled? I know how to make it select a specific one, which I've set it to do here.
Can anyone help me? Thanks
Answer: I know this is an old post, but in the current version of CI, I can do a little (sql-injection-like) trick by appending " disabled="disabled to the keys of the option I would like to disable.
$categories['0'] = '(Select Category)';
$categories['1'] = 'Category 1';
$categories['2" disabled="disabled'] = 'Restricted Category';
$categories['3'] = 'Category 3';

echo form_dropdown('category', $categories, '0');

I am not sure if this is a bug of CI's form_helper, since it does not do any escaping or sanitizing function for the dropdown key/values. For the mean time, to be safe, just make sure your keys and values wont be coming from any user-based input.
Comment: Will not work in CI 3.1.9, as $ key will be escaped.
Answer: If you still want to use form_helper, you always can extends helper file and make 'disable' tag available. Create MY_Form_helper.php and put that under helper directory, then define function form_dropdown in that custom helper, then it will overide the form helper behaviour.
Answer: If you have a few static options only the $options variable can be a simple string too, containing the options in html format, like this:
$options = "
<option value=0 disabled>Select Category</option>
<option value=1>Category 1</option>
<option value=2>Category 2</option>";

echo form_dropdown('category', $options, '0');

Answer: Just add the fourth param $extra to your dropdown as a string like this 'disabled=disabled' as explained in CI Docs at https://codeigniter.com/user_guide/helpers/form_helper.html#available-functions
echo form_dropdown('category', array('0' => 'Choose a category...')  + $categories, '0', 'disabled=disabled');

Comment: This makes the `` disabled and not just a particular `` as the OP specified.
Answer:
<?php echo validation_errors(); ?>
<?php echo form_open(''); ?>

<?php echo form_label('Gender:'); ?>
<?php echo form_dropdown(array('id'=>'selectinform', 'name'=>'gender', 'options'=>array('1'=>'Select', '2'=>'2','3'=>'3'), 'selected'=>'1')); ?>

<?php echo form_submit(array('id'=>'submit', 'value'=>'submit')); ?>
<?php echo form_close(); ?>

Result - IMG
Comment: Using js should be a last resort.  This answer is missing its educational explanation.
Answer: This works because codeigniter pass the key as full string:
<?php
$field['select'] = array(
    'blah" disabled="disabled"' => 'Select some',
    '0' => 'Never',
    '1' => 'Daily',
    '7' => 'Weekly',
    '14' => 'Every 14 days',
    '30' => 'Monthly',
);
?>

<?php echo form_dropdown($field['name'], $field['select'], (!empty($field['value'])) ? $field['value'] : 'blah" disabled="disabled"', 'id="' . $field['name'] . '" class="form-control"' . $field['extra']);?>

Answer: From the CI user guide at http://codeigniter.com/user_guide/helpers/form_helper.html:

If you would like the opening  to contain additional data, like an id attribute or JavaScript, you can pass it as a string in the fourth parameter:

So you code becomes:
    echo form_dropdown('category', array('0' => 'Choose a category...')  + $categories, '0', 'disabled="disabled"');

However, unless you are a PHP fanatic or are using CSRF protection through the form helper I would just type out your form html yourself. It is the same amount of text and you are using less functions.
Comment: Thanks for the reply. By adding 'disabled="disabled"' to the end, the whole select list becomes disabled. I just want the first option (value 0) to become disabled, so that you cannot choose the "Choose a category..." option. Yes, maybe I should type out the form myself then, unless there is a solution to this.
Comment: I do the following: I don't give the first option a value '' and use the form validation library to make the select a required field.
Comment: Try option groups, however, they are not visible when the select is not open: http://www.w3schools.com/tags/tag_optgroup.asp
Answer: Solution:
Change the 437th string of form_helper.php:
from
.(in_array($key, $selected) ? ' selected="selected"' : '').'>'

to
.(in_array($key, $selected) ? ' disabled="disabled"' : '').'>'

and use selected feature as disabled. Looks like an lifehack, but it works
Comment: Rather than modify the core code, it could be better to inject html or use javascript on the front-end.

$('select[name=yourname]').prepend('Your choice');


Invoke appClip from specific URL endpoint

Question: we've configure Associated Domain with appclips:<domain> in app and AASA file at that domain. configure meta tag as well for Card display. App clip card is working fine.
now question is, can we make it as it will display only at some specific URL endpoints. for ex. display appClip card only for <domain>/someEndpoint.
let's say domain is example.com, then it should show appClip card only for example.com/someEndpoint.
Answer: solve it by only applying meta tag to that specific end point.
as per apple documentation for banner link

To add a Smart App Banner to your website, include the following meta tag in the head element of each page where you'd like the banner to appear:


Github pages missing submodule?

Question: I followed the exact instructions (more than once) to make a github pages site, and I got an e-mail with this error
The page build failed with the following error:

The submodule `msgBored` was not properly initialized with a `.gitmodules` file.

The page it linked me to told me absolutely nothing about how to fix this, I am very new to Github, this is my first time attempting it. Thanks!
Comment: please see the answer  http://stackoverflow.com/questions/17441904/git-submodules-in-gitmodules-not-initialized
Comment: Thanks, but that doesn't really tell me much. I already found that answer when doing my own searching. That answer is 3 years old and doesn't appear to work, as the answer doesn't really specify how to use the submodule add command.
Comment: @Treedot hopefully, I might still be of assistance 3 years after my old answer.
Comment: Ha, I didn't realize that was you. I ended up just upgrading to a real host rather than fooling around with Github. It may be good for some people, but it is really not user-friendly for beginners.
Answer: This is mentioned in "Page build failed: Missing submodule".
You can see if the submodule initializes with:
cd /path/to/main/repo
git submodule init
git submodule update

But if you don't have any .gitmodules, then it actually is a nested git repo, and you would need to remove that entry before (if you really need it), add it as a proper submodule
 cd /path/to/main/repo
 git rm mysubmodule # no trailing slash
 git submodule add -- /url/to/submodule/remote/repo

Github pages missing submodule?


Proof of Well Ordering Principle

Question: Please help me in Validating the below proof for Well Ordering Principle.
Theorem:
Every non-empty set S of non-negative integers contains a least element.
Proof:
Let $W=\{0,1,2,3,4,5, \ldots\}$ and $S$ be a non-empty subset of $W$.
Let us assume that $S$ has no least member.
Hence if some $a$ belongs to $S$, $a\leq b$, for some $b$, belongs to $S$, then there exist an $M$ in $S$, such that $M\leq a$.
(I.e I can always find an $M$ in $S$ for every $a$ in $S$ such that $a\leq b$ and $M \leq a$ for some $b \in S$).
So we have $M_n$ for every $a_n \in S$ such that $a_n \leq b$ some $b \in S$.($M_1$ for $a_1 \leq b$,
$M_2$ for $a_2 \leq b \ldots$ So on till some $M_n$)
With the sequence of $M_n$'s such that satisfying below statement :
$M_1 < M_2 < \ldots < M_n$.
Above sequence will have  lower bound of $0$, that is the least value of $\{M_n\}$ sequence as the $S$ is subset of $W$.
Thus there will an $M$ in $S$ such that it will be minimum of all $\{M_n\}$.
Hence our assumption was wrong that $S$ have no least element, as we have a bound on $M$ in $S$ such that it belongs to $W$ and $S$ both.
Please help me to pinpoint where I am wrong and what step will rectify the error.
Comment: Where did you find this *Theorem*? This is a property of the set $\mathbb N$, which is a consequence of the way $\mathbb N$ is defined via the *Axiom of Infinity*.
Comment: Confused. How do you arrive at "if some $a$ belongs to $S$, $a\le b$ for some $b$ ..."?
Comment: You may want to try a proof by induction ... Assume $S\subseteq \Bbb N$ has no minimal element and show $n\notin S$ for all $n\in\Bbb N$.
Comment: The problem is the casual "and so on" that should be a formal proof by induction. Related: https://matheducators.stackexchange.com/questions/10021/why-are-induction-proofs-so-challenging-for-students/10057#10057
Comment: @HagenvonEitzen I want to give a alternative proof... Can this be alternative proof if we correct the errors here?
Comment: @HagenvonEitzen I am elaborating the contrary assumption that S have no least element into Mathematical way. It means that if I say that there is a in S such that a<=b then there exists M such that M<a.
Comment: You could formalize it a little by picking a fixed element $b$ of $S$ by non-empty, and then argue that the successive "pick a smaller element of $S$" steps can only be done at most $b$ many times which contradicts that you can keep doing it forever (which in turn implies a minimal element). It's still really an induction proof, but the fixed bound on the number of steps makes it a little clearer (maybe ).
Answer: It looks that your proof is a bit unclear, but actually if you clear it up I think there's no actual error as such in the proof or idea. If I understood you right.
Basically you note that you can since $S$ is non empty it has an element $b$ and the set $S_b = \{x\in S| x\le b\}$ is both non-empty and finite and therefore has a minimal element. That element is also the minimum of $S$.
But what you're missing is pointing out that $S_b$ has these properties, especially finiteness. You just point out "and so on" until $M_n$...
Also it's a bit overelaborate as you actually doesn't need $M_n$ to work it. You just need the finite sequence $a_n \in S_b$. Also calling the set of natural numbers $W$ instead of $\mathbb N$ makes the proof just a bit less straight forward to read.
Also the use of reductio ad absurdum is formally correct, but redundant as the assumption of no least argument arrives at the contradiction that it in fact has, but you never actually used the assumption and you would arrive at that fact nevertheless and having a direct proof.
Comment: I assumed that S have no least element and then I elaborated it mathematically.
Comment: Thanks for pointing out where I am unclear and rectifying step.
Comment: I used W as a set of Whole Numbers since the set of Natural number does not have zero in it.

Proof of Well Ordering Principle


Apache  correct syntax/load config only if find a specified file

Question: I'm trying a condition in my httpd.conf to load some options only if find a specific file. But it is not working :(
<IfModule mod_fcgid.c> #check if php fast-cgi is loaded
    <Files /cgi-bin/php.fcgi> #check if php.fcgi exists in document root folder
        AddHandler php5-fastcgi .php
        Action php5-fastcgi /cgi-bin/php.fcgi
    </Files>
</IfModule>

I want this to not to be obliged to create this file in every vhost that I made. If I load the module without this file, the site doesn't work.
Answer: You can't. AddHandler and Action directive can be only appear in: server config, virtual host, directory and .htaccess context:

http://httpd.apache.org/docs/2.0/mod/mod_mime.html#addhandler
http://httpd.apache.org/docs/2.0/mod/mod_actions.html#action


C definition of: static void (*var_name)();

Question: I download a code example written in C, but don't understand one instruction. And besides, w
hen i try to compile the code the compiler throws me an error just in the line that i don't understand.
Code:
<code>// Global vars
static int getting_text = 0;
static char *the_text;  // Definition Part
static void (*text_entered)();  // Definition Part 2

// method
int add_text(unsigned char key)
{
  char msg[] = "x";
  int len;

  if(!getting_text) return 0;
  if(key==8) /* backspace */
  {
    len = strlen(the_text);
    the_text[len-1] = '\0';
  }
  else if(key==13 || key==9) // cr or tab ends
  {
    getting_text = 0;
    text_entered(the_text); // Execution Part
  }
  else
  {
    msg[0] = key;
    strcat(the_text, msg);
  }

  glutPostRedisplay();

  return 1;
}
</code>
The compiler throws me an error about there are too many arguments in the method's calling. But i don't if it's a method the static void (*xxx)() or if other thing.
Thanks in advance.
Comment: Please don't add asterisks to indicate sections of interest. Use something like `// comment` next to the lines to show what the problem is
Comment: Did you really use a C compiler? Or did you use a C++ compiler?
Comment: I use first a C++ compiler and after that I try with the C compiler. But i think the best option to compile the code is use the C++ one.
Comment: @JorgeVegaSánchez: No, the best option is to use a C compiler because this is valid C code. It compiles with `gcc -std=c99 -pedantic` (admittedly with warnings).
Answer: EDIT: The following only applies to C++. Did you use g++ or some other C++ compiler instead of a C compiler?
text_entered is a function pointer to a function that doesn't take any arguments, hence the error, because you're passing it a character pointer. I assume it should change to,
<code>static void (*text_entered)(char*);
</code>
This is of course assuming text_enterered actually gets set to a function that takes a char* argument and it isn't just being called wrong.
Comment: No, it's not. It's a function pointer to a function that takes any arguments. In C. That's why I asked about C++ - there it's is a function pointer to a function that doesn't take any arguments.
Comment: Oops, Sebastian appears to be correct. Edited post to note that it's only valid if he used a C++ compiler instead of a C one.
Comment: Thanks for the answer. Know works fine and i understand what the function do.


Spring Security session-management setting and IllegalStateException

Question: I'm trying to add <session-management> in my Spring Security namespace configuration so that I can provide a different message than the login page when the session times out.  As soon as I add it to my configuration it starts throwing "IllegalStateException: Cannot create a session after the response has been committed" when I access the app.
I'm using Spring Security 3 and Tomcat 6.  Here's my configuration:
<http>
    <intercept-url pattern="/go.htm" access="ROLE_RESPONDENT" />
    <intercept-url pattern="/complete.htm" access="ROLE_RESPONDENT" />
    <intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
    <form-login login-processing-url="/j_spring_security_check"
                login-page="/login.htm"
                authentication-failure-url="/login.htm?error=true"
                default-target-url="/go.htm"
    />
    <anonymous/>
    <logout logout-success-url="/logout_message.htm"/>
    <session-management invalid-session-url="/login.htm" />

</http>

Everything works great until I add in the <session-management> line. What am I missing?
Answer: You are probably hitting this bug:
https://jira.springsource.org/browse/SEC-1346
Try using the up-to-date version (3.0.2.RELEASE).
Answer: Maybe including the auto-config="true" attribute in the <http> tag helps, you might be missing some required filters or settings.
Answer: This works for me
<session-management invalid-session-url="/taac/login">
    <concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
</session-management>