Is &[T] literally an alias of Slice in rust?

Question: &[T] is confusing me.
I naively assumed that like &T, &[T] was a pointer, which is to say, a numeric pointer address.
However, I've seen some code like this, that I was rather surprised to see work fine (simplified for demonstration purposes; but you see code like this in many 'as_slice()' implementations):
extern crate core;
extern crate collections;

use self::collections::str::raw::from_utf8;
use self::core::raw::Slice;
use std::mem::transmute;

fn main() {
  let val = "Hello World";
  {
    let value:&str;
    {
      let bytes = val.as_bytes();
      let mut slice = Slice { data: &bytes[0] as *const u8, len: bytes.len() };
      unsafe {
        let array:&[u8] = transmute(slice);
        value = from_utf8(array);
      }
      // slice.len = 0;
    }
    println!("{}", value);
  }
}

So.
I initially thought that this was invalid code.
That is, the instance of Slice created inside the block scope is returned to outside the block scope (by transmute), and although the code runs, the println! is actually accessing data that is no longer valid through unsafe pointers. Bad!
...but that doesn't seem to be the case.
Consider commenting the line // slice.len = 0;
This code still runs fine (prints 'Hello World') when this happens.
So the line...
value = from_utf8(array);

If it was an invalid pointer to the 'slice' variable, the len at the println() statement would be 0, but it is not. So effectively a copy not just of a pointer value, but a full copy of the Slice structure.
Is that right?
Does that mean that in general its valid to return a &[T] as long as the actual inner data pointer is valid, regardless of the scope of the original &[T] that is being returned, because a &[T] assignment is a copy operation?
(This seems, to me, to be extremely counter intuitive... so perhaps I am misunderstanding; if I'm right, having two &[T] that point to the same data cannot be valid, because they won't sync lengths if you modify one...)
Comment: An `&[T]` assignment isn't a copy operation, and proving whether a pointer operation is or isn't valid using unsafe code… doesn't really work.
Answer: A slice &[T], as you have noticed, is "equivalent" to a structure std::raw::Slice. In fact, Slice is an internal representation of &[T] value, and yes, it is a pointer and a length of data behind that pointer. Sometimes such structure is called "fat pointer", that is, a pointer and an additional piece of information.
When you pass &[T] value around, you indeed are just copying its contents - the pointer and the length.

If it was an invalid pointer to the 'slice' variable, the len at the println() statement would be 0, but it is not. So effectively a copy not just of a pointer value, but a full copy of the Slice structure.
  Is that right?

So, yes, exactly.

Does that mean that in general its valid to return a &[T] as long as the actual inner data pointer is valid, regardless of the scope of the original &[T] that is being returned, because a &[T] assignment is a copy operation?

And this is also true. That's the whole idea of borrowed references, including slices - borrowed references are statically checked to be used as long as their referent is alive. When DST finally lands, slices and regular references will be even more unified.

(This seems, to me, to be extremely counter intuitive... so perhaps I am misunderstanding; if I'm right, having two &[T] that point to the same data cannot be valid, because they won't sync lengths if you modify one...)

And this is actually an absolutely valid concern; it is one of the problems with aliasing. However, Rust is designed exactly to prevent such bugs. There are two things which render aliasing of slices valid.
First, slices can't change length; there are no methods defined on &[T] which would allow you changing its length in place. You can create a derived slice from a slice, but it will be a new object whatsoever.
But even if slices can't change length, if the data could be mutated through them, they still could bring disaster if aliased. For example, if values in slices are enum instances, mutating a value in such an aliased slice could make a pointer to internals of enum value contained in this slice invalid. So, second, Rust aliasable slices (&[T]) are immutable. You can't change values contained in them and you can't take mutable references into them.
These two features (and compiler checks for lifetimes) make aliasing of slices absolutely safe. However, sometimes you do need to modify the data in a slice. And then you need mutable slice, called &mut [T]. You can change your data through such slice; but these slices are not aliasable. You can't create two mutable slices into the same structure (an array, for example), so you can't do anything dangerous.
Note, however, that using transmute() to transform a slice into a Slice or vice versa is an unsafe operation. &[T] is guaranteed statically to be correct if you create it using right methods, like calling as_slice() on a Vec. However, creating it manually using Slice struct and then transmuting it into &[T] is error-prone and can easily segfault your program, for example, when you assign it more length than is actually allocated.


What are some reasons why PHP would not log errors?

Question: I'm running Apache2 on Ubuntu 10.04 LTS. I've configured /etc/php5/apache2/php.ini with the following:
error_reporting = E_ALL & ~E_DEPRECATED
display_errors = Off
log_errors = On
error_log = /var/log/php_errors.log

I have a PHP application that I believe has an error in it.  With those settings and the suspected error, no php_errors.log was created.  So, I created a PHP file with syntax errors.  Still no php_errors.log.  What are some reasons why PHP would not log errors?
Could it be permissions?  I see that /var/log is owned by root:root.  I don't know what owns the php process.  I believe root starts the apache process and then a new starts a new thread using www-data:www-data for serving files.  Would that mean I need to change permissions on the /var/log folder?
Comment: Try putting the log file in the apache log directory /var/log/apache2/php_errors.log, do not change the permissions on the /var/log folder
Comment: Thanks, I changed the error log path as you suggested by I'm still seeing no errors.
Answer: The following should fix you up ;-)
touch /var/log/php_errors.log
chown www-data: /var/log/php_errors.log


How to return 204 with Nginx Ingress K8S

Question: Is it possible to configure Nginx Ingress to return 204 on a given path?
In Nginx, it would look like this:
location / {
return 204;
}
Thank you!
Answer: There is a way to do this in AWS scenarios mentioned here: https://kubernetes-sigs.github.io/aws-load-balancer-controller/v2.2/guide/ingress/annotations/#actions
nginx supports some annotations like nginx.org/location-snippets (https://docs.nginx.com/nginx-ingress-controller/configuration/ingress-resources/advanced-configuration-with-annotations/#snippets-and-custom-templates), which might allow you to pass in an nginx location in the way you describe above.
But I don't know if there is a generic way.
Comment: Thank you! You put me on the right way, in fact I had to add annotation on "server-snippet".
Answer: This is what I did:
metadata:
  annotations:
    nginx.ingress.kubernetes.io/server-snippet: |
      location /ping {
        return 204;
        }

More information here:
https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/#server-snippet
And here:
https://stackoverflow.com/questions/52782415/nginx-ingress-config-map-snippets-being-ignored-by-the-nginx-conf


Need help with my form with duplicate file and resetting form

Question: Need help with my form for uploading an image on my theme's settings. I have a form that uploads an image that can be used as a background image. I have two problems with my form: first is how to delete the uploaded file or reset the form and second is an error message appears when uploading the same file again after resetting the theme's settings.
This is my form code I'm using:
<?php function tsaudio_form_system_theme_settings_alter(&$form,&$form_state) {

$form['slideshow'] = array(
'#type' => 'fieldset',
'#title' => t('Background'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);

$bg_path = theme_get_setting('bg_path');if (file_uri_scheme($bg_path) == 'public') {
$bg_path = file_uri_target($bg_path);
}

$form['slideshow']['bg_path'] = array(
'#type' => 'textfield',
'#title' => 'Path to background image',
'#default_value' => $bg_path,
'#disabled' => FALSE,
);

$form['slideshow']['bg_upload'] = array(
'#type' => 'file',
'#title' => 'Upload background image',
'#description' => 'Upload a new image for the background.',
);
$form['reset'] = array(
'#type' => 'markup',
'#markup' => '<input type="reset" value="Reset All Values" class="form-submit">',);

$form['#submit'][] = 'tsaudio_settings_submit';}
function tsaudio_settings_submit($form, &$form_state) {
$settings = array();
// Get the previous value
$previous = 'public://' . $form['slideshow']['bg_path']['#default_value'];

$file = file_save_upload('bg_upload');
if ($file) {
$parts = pathinfo($file->filename);
$destination = 'public://' . $parts['basename'];
$file->status = FILE_STATUS_PERMANENT;

if(file_copy($file, $destination, FILE_EXISTS_REPLACE)) {
  $_POST['bg_path'] = $form_state['values']['bg_path'] = $destination;
  // If new file has a different name than the old one, delete the old
  if ($destination != $previous) {
    drupal_unlink($previous);
  }
}
} else {
// Avoid error when the form is submitted without specifying a new image
$_POST['bg_path'] = $form_state['values']['bg_path'] = $previous;}

}?>

And this is the error message I get when uploading the same file again after resetting the theme's settings to default.
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062
Duplicate entry 'temporary://ctrldailybg4_1.jpg' for key 'uri':
INSERT INTO {file_managed} (uid, filename, uri, filemime, filesize,
status, timestamp) VALUES (:db_insert_placeholder_0,
:db_insert_placeholder_1, :db_insert_placeholder_2,
:db_insert_placeholder_3, :db_insert_placeholder_4,
:db_insert_placeholder_5, :db_insert_placeholder_6); Array (
[:db_insert_placeholder_0] => 1 [:db_insert_placeholder_1] =>
ctrldailybg4.jpg [:db_insert_placeholder_2] =>
temporary://ctrldailybg4_1.jpg [:db_insert_placeholder_3] =>
image/jpeg [:db_insert_placeholder_4] => 1344028
[:db_insert_placeholder_5] => 0 [:db_insert_placeholder_6] =>
1436760809 ) in drupal_write_record() (line 7316 of /homepages
/9/d539887599/htdocs/towersignal_com/includes/common.inc).

Answer: As described in the docs file_save_upload
file_save_upload($form_field_name, $validators = array(),
$destination = FALSE, $replace = FILE_EXISTS_RENAME)

the last parameter $replace

$replace: Replace behavior when the destination file already exists:
FILE_EXISTS_REPLACE: Replace the existing file.
FILE_EXISTS_RENAME: Append _{incrementing number} until the filename is unique.
FILE_EXISTS_ERROR: Do nothing and return FALSE.


Multi Axes Voting using Fiverstar, Views, Reference

Question: I have tried several different tutorials on how to accomplish this. Most were for drupal 6, but there were few for drupal 7 but none seem to make sense to the modules being used currently that are in dev or stable. The Node Review module seems to be the closest thing to what I need but that requires some hacking to make it work for my particular use. I have several other modules that I've experimented with. Rate 7.x-1.3 Seemed to have potential.
How would I be able to make a system like the following use these modules?;

Node Reference   7.x-2.0+8-dev
Fivestar 7.x-2.0-alpha1+22-dev
Views    7.x-3.3

What I am looking for a content-type: Business. These will have several businesses that people can rate based on different criteria. Multi Axes Rating on separate page or tab. The Review can be a separate content type. Not required thou.
Comment: Hi, maybe I can't understand this concept of Multi Axes Voting. Why don't you just add several Fivestar (or Rates) to your content-type, one for each criteria?
Comment: The problem is that the users of the site will be creating reviews of businesses. So if I create the business with multiple axes built in.. Only the person that creates the business node will be able to input anything, and it would only get to be done once. What I need is 1 [business] to MANY [reviews] (one review per business per user)
Comment: @Digital Fire - did you find a solution on how to calculate the rating in a view?
Answer: You can add as many vote fields (using Rate or Fivestar) as you want to your Reviews, one vote for each criteria you want to make available.
Your Reviews can be a new Content-Type (then you would use a Relationship in the Business View) or you can use Comments (of Business) for this propose. Both Content-Type and Comments are customizable: you can add fields to them.
My first choice would be to add n Fivestar rating fields to Business's Comments. You can do that in Business Content-Type Edition, in the "Comment Fields" tab.
But if you want each user to make only one review and have more control/customizations, then a new Content-Type for Reviews can make your life easier.
Comment: This works, now am just trying to to get my views to calculate the average of votes through the reference..


Custom URL schema doesn't open app

Question: I have a problem with custom URL schema. I think I've configured it properly but it doesn't open the app if it is closed, if the app is in "background" (i.e. I can see it double tapping the home button) the app is opened when I tap on the link.
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>com.test</string>
<key>CFBundleURLSchemes</key>
<array>
<string>test</string>
<string>test1</string>
</array>
</dict>
</array>

the link is
TEST

other applications work fine but not mine.
Thanks,
Matteo
Answer: Do you return NO; anywhere in your - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation method?
I can't think of anything that would cause it to not open, aside from returning NO.
Comment: `- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    NSLog(@"%@ %@",url,sourceApplication);
    return YES;
}`

this is the code I use. I've downloaded a sample sender & receiver app and works fine...

Custom URL schema doesn't open app


If $x_n→ x$ in $\ell^2$ then $\lim_{n→\infty}f(x_n)=f(x)$ if $f$ is continous?

Question: Let $(x_n)_{n\in \mathbb N} \subset \ell^2$ with component wise limit $x \in \ell^2$. Let be $f:\ell^2→\ell^2$ is continous.
Is it true that:
$$\lim_{n→\infty}f(x_n)=f(\lim_{n→\infty} x_n)=f(x)? \tag C$$
In my opinion, it is not true since continuity claims $\lim_{n→ \infty}x_n=x$ so convergence with respect to a norm and not only component-wise.
Any help appreciated!
Comment: What do you mean by component-wise limit?
Comment: since $x_n \in \ell^2$ it is a infinite-dimensional vector. By component-wise I mean every component of his infinite-dimensional vector converges to a limit of the components of $x$.
Comment: What is the convergence on $(C)$ that you want? component-wise again?
Comment: Yes, that is what I would like to have, but I am not sure if this makes sense. So, since $f$ continuous that means for all $x \in \ell^2$, $\varepsilon >0$ and there is a $\delta >0$ such that for all $x _0\in \ell^2$ it holds $\|x-x_0\|_{\ell^2} < \delta \Rightarrow \|f(x)-f(x_0)\|_{\ell^2}<\varepsilon$.

By definition of the $\ell^2$-norm that means $\sum_{k \ge 1} |x_n^{(k)}-x^{(k)}| < \delta$ and $\sum_{k \ge 1}| (f(x_n))^{(k)}-(f(x))^{(k)}| < \varepsilon$. Thus every summand of both sum must be abritraly small so we got component wise continuiy, right?
Answer: In any metrizable topological space, sequential continuity is equivalent to topological continuity!
The space  $l_{2}$ is a normed space, hence metrizable with
$d(x,y)= \left\|x-y \right\|$. Therefore if $f$ is continuous, it is
also sequentially continuous which immediately gives the result!!
Comment: Sure you deserved it! But could you explain a bit further?
Comment: Thank you for your answer. That is an interesting result! Would you tell me how sequentially continuity is defined? Even better would be a book that treats this statement.
Comment: See the picture I edited in my answer!!
Comment: Thank you for your effort, really appreciate it! I am still not sure how we get the limit in $(\rm C)$ explicitly. Does it mean in the case of $\ell^2$ that $f=(f_1,f_2,...)$ and $f_i$ is one-dimensional and continuous?
Comment: You can thank me with an upvote my friend!!
Answer: This isn't true. For example you can use $f(x) = x$, which is continuous, and let $x_n$ be the sequence equal to $1$ in the $n$th entry and zero elsewhere. Then $x_n$ converges to the zero sequence componentwise, but not in $l^2$.
Comment: I just misread your question, sorry about that
Comment: Yes, the sequence doesn't converge to the zero sequence in the $\ell^2$ norm. Since $f$ is the identity map that is what you are looking for.
Comment: I am not sure if I get your counterexample. In your case $f:\ell^2→\mathbb R$ so I don't see how this shows that we can't component-wise continuity hence $(\rm C)$. Could elaborate on that a little bit?
Comment: This should correct it.
Comment: All good. With "but not in $\ell^2$" you mean not considering the $\ell^2$-norm right?
Comment: Thank you. I have another question if you don't mind. Is it possible t get component-wise convergence in $(\rm C)$?


Harmonising cadence points in a melody

Question: So I've started doing AMEB* Grade 4 theory, and came across this question:

Normally, I would have no problem if they gave me the bass, but in this case, I'm slightly confused. How are you supposed to go about this? Each note could have at least three possible chords, so how do I work out which one's which? Also, where are the cadence points?

*AMEB Stands for the Australian Music Examination Board. It's the standard assessment board for anyone wanting to learn an instrument in Australia.
Comment: When they stop spoon feeding you they will stop giving you a bass line to harmonise.
Answer: The vocabularly allowed for cadences in AMEB grade 4 theory are the following chords: I, ii, IV, V and vi. You are not allowed to use V7 until grade 6 theory otherwise it would be ideal for the final cadence. You are also allowed to harmonize other parts of the melody with first inversion chords but not the cadences so the chords that you are allowed to use for cadence points will look like this:
I DF#A
ii EGB
IV GBD
V AC#E
vi BDF#
You have four cadence points, one at the end the end of each phrase (the phrases are marked by the four slurs) The last cadence must be Perfect or Plagal as both these cadences indicate a final close. In this case it must be a Perfect cadence as chord IV will not fit under the second last note. As chords must be in root position, you place an A in the bass under the second last note followed by a D under the final note, then fill in the two middle voices (doubling the bottom note in each chord)
The other three cadences will be types of imperfect cadence (ie. ending on chord V). I'd suggest using ii-V at the end of the first cadence point (approaching the LN from above), IV-V for the second (make the bass rise a step and the other three fall) and I-V for the third one (which will resemble a "reverse" perfect cadence)
Remember that the best note to double is the root of each chord unless you are doing an interrupted cadence (V-vi) where you would double the middle note in chord vi.
Answer: A cadence point is, to a melody, what the punctuation is in a sentence. Cadences are "points of rest" or "points of resolution". You create cadences by completing a chord progression, often but not always ending in a I chord. When that chord progression is completed, the next one begins.
So you should look in this melody for logical places to create cadences. In this case it's mapped out for you because of the structure of the slurs. Make a cadence at the end of each slur.
For the different types of cadences, see this Wikipedia article.
Answer: It might be easiest to work backwards -- the most obvious cadence point is going to be the last few notes.  You can bet the last chord is expected to be the I, D major.  Prior to that you would expect a V(7) or occasionally the IV.  We see an E in the melody so assume V7, or A7  in our key of D.  Just before that is an F#, what might that be?  It doesn't quite fit V7 exactly, so something that normally comes before a V... well a subdominant-type chord would have a G or G#, and the F# doesn't fit that at all, but something else common does... (can you figure it out?)
Measure 4 is halfway through, and screams for a "half cadence" to V or V7.
That's how I would approach it, although it's not clear exactly how much you need to harmonize.  The long notes on the even-numbered bars are also targets for cadences ("moments of rest" as has already been stated) but at a minimum I would show cadences to bars 4 and 8.  Hope this helps.
I guess you can also do an approach chord for the note before which I would suggest as a V or a VI, making a normal perfect cadence.
Answer: Two thoughts:

Look at the linear shape of the melody. Notice implied harmonies for each measure.  Consider which notes might be important (clear chord tones) and which ones are less important (neighbor and / or passing tones).
Look at how the melody is accented agogically. Notice which notes have longer durations than others.  In a melody, longer notes are typically more important.  Notice how often the longer notes appear (every two measures for example) and plan your harmonic pacing around the agogic pacing of the melody.
Answer: Cadence points can be at the end of each line, but definitely at the end of a verse or chorus.It could, for the quoted question, be the end of each phrase, and probably is. In this case, taking the end of the first line, it's an imperfect cadence, I-V, the second line ending on a perfect cadence, V-I, probably playing the V on the last beat of bar 7.
Yes, each note in a tune could have a choice of 3 or more chords, but tunes rarely have chord changes 3 or 4 to the bar. So you look at the first note in a bar, and see if other notes in that same bar fit to a chord. Take bar 3: F#, A and D. Fits squarely into a Dmaj. chord.Bar 4 could have a Bmin., as 3 of the notes fit it.
Answer: You start by determining where the cadence points are. At a general grade 4 level it should be uncommon that the cadences would not be every 4 bars. You look at the note that they give. These notes that they give could only be in one of three chords.
At the first Cadence it look like a Imperfect Cadence with a passing chord as decoration. So for the last 3 beats leading into the I - I 6/4 - V (With the option of having the Dominant with or without its seventh.)
The second cadence looks like a plain old Perfect Cadence V - I. I hope you are comfortable with the use of the Dominant Seventh and the use of the Passing 6/4 chord progressions as this question just about begs for the use of them.

Harmonising cadence points in a melody


Como mostrar várias mensagens de erro simultaneamente em formulário?

Question: Eu estou tentando fazer com que minha pagina de registro mostre todas mensagens de campos esquecidos juntas como nesse exemplo:

Mas ela só mostra em partes:
1 - "Username already exists" e "Email already exists"
ou
2 - "Please insert a username", "Please insert a password" e "Please insert a email"
ou
3 - "Username must have less than 16 characters" e "Password must have 8 or more characters"
Tem alguma solução pra isso?
<?php
$page = "Register";
include "header.php";

if(isset($_POST["register"])){

$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];

if(!empty($username) && !empty($password) && !empty($email)){

    if(strlen($username) < 17 && strlen($password) > 7){

        $checkusername = mysql_query("SELECT `id` FROM `database`.`user` WHERE `username` = '".$username."'");
        $checkemail = mysql_query("SELECT `id` FROM `database`.`user` WHERE `email` = '".$email."'");

        if(mysql_num_rows($checkusername) == 0 && mysql_num_rows($checkemail) == 0){

            $insert = mysql_query("INSERT INTO `database`.`user`(`username`,`password`,`email`) VALUES ('".$username."','".$password."','".$email."')") or die(mysql_error());
            ?>
<?php echo "You are Registered"; ?>
<?php
        }
        else{
            if(mysql_num_rows($checkusername) > 0){
                $error[] = "Username already exists";
            }
            if(mysql_num_rows($checkemail) > 0){
                $error[] = "Email already exists";
            }
            foreach($error as $value){
                ?>
<?php echo "'".$value."'
"; ?>
<?php
            }
        }
    }
    else{
        if(strlen($username) > 16){
            $error[] = "Username must have less than 16 characters";
        }
        if(strlen($password) < 8){
            $error[] = "Password must have 8 or more characters";
        }
        foreach($error as $value){
            ?>
<?php echo "'".$value."'
"; ?>
<?php
        }
    }
}
else{

    if(empty($username)){
        $error[] = "Please insert a username";
    }
    if(empty($password)){
        $error[] = "Please insert a password";
    }
    if(empty($email)){
        $error[] = "Please insert a email";
    }
    foreach ($error as $value) {
        ?>
<?php echo "'".$value."'
"; ?>
<?php
    }
}
}
?>

    <form name="loginform" method="post">

Register

            Username:
            <input type="text" class="text" name="username">

            Password:
            <input type="password" class="text" name="password">

            Email:
            <input type="email" class="text" name="email">

            <input type="submit" class="submitbutton" name="register" value="Register" />

    </form>

<?php
include "footer.php";
?>

Answer: Você pode usar variáveis separadas para cada tipo de erro, e indicá-los nos respectivos campos.
Para que as mensagens possam aparecer simultaneamente, refatorei seu código, permitindo o tratamento de cada campo separadamente:
<?php
   $page = 'Register';
   include 'header.php';

   $user_error='';
   $mail_error='';
   $pass_error='';

   if( isset( $_POST['register'] ) ) {
      $username = $_POST['username'];
      $password = $_POST['password'];
      $email = $_POST['email'];

      // Tratamento de erros do username:

      if( empty( $username ) ) {
         $user_error = 'Please insert an username';
      } elseif ( strlen( $username ) ) > 16
         $user_error = 'Username must have less than 17 characters';
      } else {
         // Essa linha abaixo é sujeita a SQL Injection, cuidado!
         $checkusername = mysql_query("SELECT `id` FROM `database`.`user` WHERE `username` = '".$username."'");
         if(mysql_num_rows($checkusername) > 0) {
            $user_error = 'Username already exists';
         }
      }

      // Tratamento de erros da senha:

      if( empty( $password ) ) {
         $pass_error = 'Please insert a password';
      } elseif( strlen( $password ) < 8 ) {
         $pass_error = 'Password must have 8 or more characters';
      }

      // Tratamento de erros do email:

      if( empty( $email ) ) {
         $mail_error = 'Please insert an email';
      } else {
         // Essa linha abaixo é sujeita a SQL Injection, cuidado!
         $checkemail = mysql_query("SELECT `id` FROM `database`.`user` WHERE `email` = '".$email."'");
         if( mysql_num_rows( $checkemail ) > 0 ){
            $mail_error = 'Email already exists';
         }
      }
   }

   // Se não setamos nenhum erro, e o formulário foi enviado, podemos ir para o insert:
   if empty( $user_error )
   && empty( $mail_error )
   && empty( $pass_error )
   && isset( $_POST['register'] ) ) {
      $insert = mysql_query("INSERT INTO `database`.`user`(`username`,`password`,`email`) VALUES ('".$username."','".$password."','".$email."')") or die(mysql_error());
?>

You are registered!

(aqui você pode por instruçoes, ou a mensagem que quiser, no caso do sucesso)

<?php
   } else {
      // caso contrário, mostramos o form, e opcionalmente os erros encontrados:
      $user_error=empty($user_error)?'Username:' : ''.htmlEntities($user_error).'';
      $mail_error=empty($mail_error)?'Email:' : ''.htmlEntities($email_error).'';
      $pass_error=empty($pass_error)?'Password:' : ''.htmlEntities($pass_error).'';
      // O formulario está dentro deste else:
?>

   <form name="loginform" method="post">

Register

            <?php echo $user_error; ?>
            <input type="text" class="text" name="username">

            <?php echo $pass_error; ?>
            <input type="password" class="text" name="password">

            <?php echo $mail_error; ?>
            <input type="email" class="text" name="email">

            <input type="submit" class="submitbutton" name="register" value="Register" />

   </form>

<?php
   } // Fechando o else acima

   include "footer.php";
?>

Assim, cada erro será mostrado em seu próprio campo. Esta solução parece adequada para seu caso, pois só ha um erro de cada tipo sendo mostrado ao mesmo tempo no seu código (usuário, senha e email).
Caso queira, os mesmos ifs podem ser usados e adaptados para aplicar a solução do @Otto, que é boa caso você queira todos os erros apresentados em um bloco só.
Comment: muito bom @Bacco
Comment: @Lukaz11: Veja nesta resposta como usar o `mysqli` para evitar SQL Injection, e problemas com aspas nos campos: http://pt.stackoverflow.com/a/14757/70
Answer:
<?php echo "'".$value."'
"; ?>

troque por
$error =. "
".$value."

";

no final do loop echo $error;
Comment: Eu tentei esse código mas não acontece nada.


How to setup session sharing for language subdomains (URL language detection set to domain prefix)

Question: I would like to use domain prefix for language selection, like en.example.com and de.example.com. I've set up language detection to Domain here admin/config/regional/language/configure/url.
In theory everything works fine, except that session data is not shared between subdomains. If I log into the main site example.com and then visit en.example.com I have to log in again. Is this behaviour by design? Can I setup drupal to share session data between subdomains? It's the same site after all - only subdomain is different.
Answer: You need to set the variable $cookie_domain in your settings.php file to your base (default language) domain.
Just search the settings.php file for that variable, uncomment the line and replace '.example.com' with your default language domain preceded with a dot.
Source


How do I make sure insmod fails on error?

Question: I developed a peripheral driver for Linux. The .probe function performs the usual error checks like memory allocation failures, and also attempts to communicate with the hardware and in any type of error, deallocates any memory and returns an error code like -ENOMEM or -EIO.
The problem is, although the module probe function return -EIO when the hardware is unreachable, I still see the module is listed in lsmod output. Is it possible to make sure an insmod completely fails when there is a problem during initialization?
Here is my current probe function. All device specific functions return an appropriate error code on failure, usually -EIO.
static int mlx90399_probe(struct i2c_client *client,
        const struct i2c_device_id *id)
{
    int err;
    struct mlx90399_data *data;

    data = kzalloc(sizeof(*data), GFP_KERNEL);
    if (!data) {
        dev_err(&client->dev, "Memory allocation fails\n");
        err = -ENOMEM;
        goto exit;
    }
    i2c_set_clientdata(client, data);
    data->client = client;
    mutex_init(&data->lock);
    data->mode = MLX90399_MODE_OFF;

    err = mlx90399_reset(client);
    if (err < 0)
        goto exit;

    msleep(1); /* nominal 0.6ms from reset */
    err = mlx90399_write_register_defaults(client);
    if (err < 0)
        goto exit;

    err = mlx90399_update_scale(client);
    if (err < 0)
        goto exit;

    data->indio_dev = iio_allocate_device(0);
    if (data->indio_dev == NULL) {
        err = -ENOMEM;
        goto exit;
    }

    data->indio_dev->dev.parent = &client->dev;
    data->indio_dev->info = &mlx90399_info;
    data->indio_dev->dev_data = (void *)(data);
    data->indio_dev->modes = INDIO_DIRECT_MODE;

    mlx90399_setup_irq(client);

    err = iio_device_register(data->indio_dev);
    if(err < 0)
        goto exit;

    return 0;

exit:
    kfree(data);
    return err;
}

Comment: Show the module initialization function.
Comment: @CL.
static int __init mlx90399_init(void)
{
 return i2c_add_driver(&mlx90399_driver);
}
Answer: See the comment in __driver_attach():
/*
 * Lock device and try to bind to it. We drop the error
 * here and always return 0, because we need to keep trying
 * to bind to devices and some drivers will return an error
 * simply if it didn't support the device.
 *
 * driver_probe_device() will spit a warning if there
 * is an error.
 */

To make the module initialization fail, unregister the driver and return an error code from your init function.
Answer: Note that there isn't necessarily a 1:1 relationship between a module and a device. One module may be used for several devices. With the use of device trees, for example, a device tree may declare several on-board UARTs, all using one serial device kernel module. The module's probe function would be called several times, once for each device. Just because one probe call fails, that doesn't necessarily mean the module should be unloaded.


MariaDB is showing data only when I select all fields

Question: I have strange error (?) while using MariaDB command line.
When I use SELECT * FROM users; where I have current_role column (which is enum type) it shows it's value, but when I use SELECT current_role FROM users; I only get NULL. How is that possible and what I may be doing wrong? I don't have that issue with other fields.
Comment: Could that be a function too? Have you tried escaping the name?
Comment: I removed the mention of MySQL. This issue only occurs on MariaDB, it doesn't occur on MySQL even in version 8.0 which has the `current_role()` function.
Comment: I uploaded screenshots of what I'm doing just in case
Comment: Also forgot to add that `current_role` is enum type if that might matter
Comment: @watery you were right - I escaped the name with ` and it works now. This is quite strange given that other columns didn't needed that
Answer: current_role is a keywaord und you must escape to get the info from a field with the same name.
see: https://mariadb.com/kb/en/library/current_role/
Use backticks to escape the fieldname like:
SELECT `id`,`current_role` FROM YourTable;

MariaDB [(none)]> SELECT CURRENT_ROLE;
+--------------+
| CURRENT_ROLE |
+--------------+
| NULL         |
+--------------+
1 row in set (0.00 sec)

Comment: "moron" is a little harsh — it's sometimes legit to use reserved words for identifier names. That's why you can delimit identifiers, to allow you to do this. How many times have you seen a table in an e-commerce system named `order`?
Comment: The Answer from @Bill Karwin ist 100% correct. There are so many "bad" fieldnames .
Comment: So actually the guy that created that column in our database was a moron and I should rename it to the one that is not actually a keyword, am I right?
Comment: @BillKarwin sorry, you're right - that was a bit too harsh. I'm just after a long day of cleaning database from various things after previous database guy (where I'm a fullstack dev, not dba). Thanks guys - especially that it's Sunday evening today!


What does this double-treble double-bass staff mean?

Question: Half-way through Rachmaninoff's Prelude in C# minor there is this connected set of double clefs.  Can anyone tell me what to do? It was a single set of bass and treble clefs for half the piece.
I thought maybe there was a D.C. al Coda thing going on where I should perform one set and return to play the second... no idea really.
Comment: Satirical rendition of that piece: https://www.youtube.com/watch?v=ifKKlhYF53w
Answer: He was quite a good player - flamboyant, too. Looking carefully, in the double treble lines, he'd play the chord at the beginning of a bar, then the three quaver chords, come down again for the next octave on beat 3, then go back up again, and so on, all with the r.h. The l.h. is similarly played. There's so much going on, it's better to read (and write) separating the 'two parts' in each hand.And 'ffff' means give it all - no chance of playing the wrong note by mistake - everyone's going to notice!
It's virtually SATB, but for one player. Takes a bit of doing, but when it's ready, not only does it sound fantastic, but it looks spectacular.
Comment: And he had enormous hands, which is an advantage when playing his music.
Answer: All four staffs should be played simultaneously.  Both treble staffs are for the right hand, both bass staffs are for the left hand.
It's split up into double staffs just so that it doesn't get as crowded as it would be on two staffs.  This notation is fairly unusual but not exceptional, as a way to write densely-textured sections more readably.
Reference performance on YouTube, with score (double-staff passage at 2:21)
Comment: Note that starting on the next page (you can even see the marker here), the upper staff on the left hand moves up to a treble clef.  Notating this on one staff would be a pain and very confusing to read, requiring the clef to change between every other chord.  Hence why it's split up this way.
Comment: If this was for solo piano not piano four-hands, Rachmaninoff should've used two voices. Rachmaminoff should use four staves if this is really for piano four-hands.
Answer: That's a case for the sostenuto pedal (the middle pedal, not the sustain pedal) on a grand piano.  You play the chords in the 2nd and 4th system, hold the notes by downing the sostenuto pedal, then play the intermittent notes in the 1st and 3rd system (that are not held since the sostenuto pedal only holds notes that were active when it was being lowered) and release the sostenuto pedal just before playing the next long chord in the 2nd and 4th system.
Answer: You can play it all at once.  It's pretty 'bravura', but there's plenty worse in Rachmaninoff.  :-)   You could just about write it all on two staves if you wanted to.
Comment: And where do you think] the font borrowed its name from?  :-)
https://www.nationalgallery.org.uk/paintings/glossary/bravura
Comment: Why did you use 'bravura' for quality of music? [Bravura](https://www.smufl.org/fonts/) is a music font.


Inline SVG icons not displaying in viewbox

Question: This has proven too difficult for me work out, so another pair of eyes would help immensely!
I have some SVG's inline in my HTML file, but I don't know why they are not displaying. I have tried finding them by manipulating each of their viewBox attribute, but I haven't been successful yet.
Any ideas why I cant see them?

body {
  background-color: #ddd;
}
.st1 {
  fill: #FFFFFF;
}
.st15 {
  fill: #000000;
}
p {
  width: 600px;
}
span svg {
  width: 35px;
  height: 40px;
  border: 1px solid red;
  float: left;
  padding: 0;
  margin: 0;
}

<svg style=" display: none; position: absolute;"   version="1.1 " xmlns="http://www.w3.org/2000/svg " xmlns:xlink="http://www.w3.org/1999/xlink ">
        <defs>
            <symbol id="icon-plus " viewBox="0 0 40 40 " preserveAspectRatio="xMinYMin " aria-labelledby="title desc " role="img ">
                <title>plus sign</title>

    <path class="st1 " d="M342.5,21.5v2c0,0.3-0.1,0.5-0.3,0.7c-0.2,0.2-0.4,0.3-0.7,0.3h-4.4V29c0,0.3-0.1,0.5-0.3,0.7 c-0.2,0.2-0.4,0.3-0.7,0.3h-2c-0.3,0-0.5-0.1-0.7-0.3c-0.2-0.2-0.3-0.4-0.3-0.7v-4.4h-4.4c-0.3,0-0.5-0.1-0.7-0.3s-0.3-0.4-0.3-0.7 v-2c0-0.3,0.1-0.5,0.3-0.7s0.4-0.3,0.7-0.3h4.4V16c0-0.3,0.1-0.5,0.3-0.7c0.2-0.2,0.4-0.3,0.7-0.3h2c0.3,0,0.5,0.1,0.7,0.3
c0.2,0.2,0.3,0.4,0.3,0.7v4.4h4.4c0.3,0,0.5,0.1,0.7,0.3C342.4,21,342.5,21.2,342.5,21.5 "/>
   </symbol>

   <symbol id="icon-minus " viewBox="0 0 40 40 " preserveAspectRatio="xMinYMin " aria-labelledby="title desc " role="img ">
                <title>minus</title>

    <path class="st15 " d="M318.6,21.3v2.4c0,0.3-0.1,0.6-0.4,0.9c-0.2,0.2-0.5,0.4-0.9,0.4h-15.5c-0.3,0-0.6-0.1-0.9-0.4 c-0.2-0.2-0.4-0.5-0.4-0.9v-2.4c0-0.3,0.1-0.6,0.4-0.9c0.2-0.2,0.5-0.4,0.9-0.4h15.5c0.3,0,0.6,0.1,0.9,0.4 C318.5,20.7,318.6,21,318.6,21.3 "/>
   </symbol>

        </defs>
    </svg>

   <svg>
    <use xmlns:xlink="http://www.w3.org/1999/xlink " xlink:href="#icon-plus "></use>
   </svg>

   <svg>
    <use xmlns:xlink="http://www.w3.org/1999/xlink " xlink:href="#icon-minus "></use>
   </svg>

  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam convallis arcu eu ante vestibulum, non dictum felis pellentesque.
  Curabitur non risus rhoncus tellus vehicula pellentesque. Pellentesque commodo enim scelerisque quam accumsan, id fermentum augue condimentum.
  Praesent sed imperdiet quam. Cras dapibus orci maximus, aliquam turpis sed, laoreet sapien. Curabitur feugiat pulvinar orci, sit amet venenatis nibh consequat vel.
  Vivamus vehicula eget ex non semper. Donec sit amet luctus neque.
  Vestibulum aliquam elit justo, in pretium neque efficitur ac. Proin tellus diam, finibus sit amet tristique in, commodo ac metus.
  Mauris eget erat ut erat rutrum ultricies sed non leo. Duis in turpis magna.
  Praesent efficitur, odio congue venenatis tempor, sem augue sollicitudin orci, eu convallis enim diam et eros.
  Vivamus nulla odio, eleifend vitae pharetra non, lobortis at nulla.

Answer: The viewBox attribute tells the browser where in the coordinate system your SVG contents are situated.
You currently have it set to "0 0 40 40" which means from (0,0) to (40,40).  However look at the first coordinate of your <path>: (342.5, 21.5).  So you are clearly way off with your viewBox.
There are several ways forward including, but not limited to:

Load your SVG into a vector editor and move and resize your path so it fits in the 40x40 viewBox.
Load the SVG into a vector editor and determine the dimensions using the editors dimension readouts.  Use those for setting the viewBox.
Start with a viewBox in roughly the right area, and manually keep readjusting it till you iteratively shrink it to the right size.
Load it into a browser and use getBBox() to find the correct values for the viewBox.

Note also that if you choose not to use symbols positioned at or near the origin (0,0) you will probably need to also add viewBox attributes to the SVGs that have the <use> elements.
Comment: so the coordinates are in the beginning of the path?? OMG! Why hasn't this been written anywhere on the net, I have been scouring for questions as to how to find the coordinates...I will try this, Thank you for saving me, you kind sir!
Comment: LeBleau I have done the third way you suggested, and its working :)
Comment: No. I meant that the start of the path is at (342,21) so you can tell immediately that the viewBox is wrong.  But you already knew that.
Comment: Yes, with a little fiddling around, its setting perfectly now, thanks again!


Terraform variable pointing to current file name

Question: Is there some special variable available in Terraform configuration files which would point to current file name?
I'd like to use it for description fields in various resources, so that someone seeing these resources in the systems would know where is the master definition for them.
e.g.
in myinfra.tf
resource "aws_iam_policy" "my_policy" {
  name        = "something-important"
  description = "Managed by Terraform at ${HERE_I_WOULD_LIKE_TO_USE_THE_VARIABLE}"

  policy = <<EOF
[...]
EOF
}

And I would hope the description becomes:
description = "Managed by Terraform at myinfra.tf"

I tried ${path.module} but that only gives "filesystem path of the module where the expression is placed", so pragmatically speaking - everything but the file name I want.
Comment: I don't think you can do it. But then how would it work if later you would rename your files, or re-organize your infrastracture into modules? Re-deploy or change all the resources?
Comment: After renaming files / moving resources between files, the values would evaluate to something else and next `terraform apply` would see them as changed. Just like any other variable.
Comment: I'd recommend not putting that in the description but rather use tags. That way you can find those Terraform managed resources easier and you can use the description for something meaningful. And AFAIK there is no way to get the current file name. Not sure if that is really necessary though. We have tags to show a resource is managed by Terraform and a tag with the link to the projects Git repository where the Terraform is managed. So far, that was sufficient.
Comment: @Jens I guess you mean AWS specifically, but not all vendors / systems support tags.
Comment: @GrzegorzOledzki Yeah. Not sure about other public clouds. My suggestion is for AWS.
Comment: @Jens also even if narrowing to AWS specifically, my nice-to-have would be for the tag value to have name of the file, not only the Git repo we are in.
Comment: I think you would need to pre-process the TF files before plan/apply, or just have some tiny wrapper around apply/plan commands which would perform simple find-and-replace on your tf scripts to inject tf file names where needed.
Answer: Here's what I can share. Use the data external resource to call an external script that would get the directory/file name and then return it back as a string or any other type that your resources require. Obviously it's not exactly what you wanted as you'll get the dir/file name indirectly but hopefully it helps for others or even yourself for use-cases.
We use that only for azurerm and for very complex integrations that are not yet supported with the current provider versions. I have have not tested it specifically for AWS but since it's a core Terraform resource provider, I'm guessing it might work across the board.
data "external" "cwd" {
  program = ["./script.sh"]
  query = {
    cwd = "${path.cwd}"
  }
}

resource "aws_iam_policy" "my_policy" {
  name        = "something-important"
  description = "Managed by Terraform at ${data.external.dir_script.result.filename}"

  policy = <<EOF
[...]
EOF

This is how my script looks like:
#!/bin/sh

#echo '{"cwd":"for_testing"}' | ./dir_name.sh  | xargs

PIPED=`cat`
errPrint "INFO: Got PIPED data:\n$PIPED"

DIR=`jq -r .cwd <<< $PIPED`

cd $DIR
filename=`ls | grep \.tf$ | xargs`
errPrint "INFO: Returning this as STDOUT:${filename}"

echo "{\"name\":\"$filename\"}"

You need to be that the data from the script needs to return a valid JSON object.

The program must then produce a valid JSON object on stdout, which will be used to populate the result attribute exported to the rest of the Terraform configuration. This JSON object must again have all of its values as strings. On successful completion it must exit with status zero.

Unfortunately, like the others mentioned, there's no other way to get the current file name being 'applied'.
Comment: How would `dir_name.sh` get the name of the TF file from which it is called?
Comment: You're right I might have gotten ahead of myself - with what I had in mind, it would still require having a value in the file that the script can pick, like finding a string in a file.
Comment: Hi @Marcin can you verify if this could work for him? I tweaked my script to fit the scenario and also using `${path.cwd}`. I added `xargs` in the event there are more than one file... Would appreciate feedback
Comment: Nice hack. In order to fit my use-case, I guess the `script.sh` would need to do more precise grepping - as the whole point of putting the name of the `.tf` file is to point to a specific one among plenty of them.
Comment: Yes and I guess with a proper naming convention for different files, it should be possible to get it right.
Answer: I think you might benefit from using something like yor from Bridge Crew.
From the project's README:

Yor is an open-source tool that helps add informative and consistent tags across infrastructure-as-code frameworks such as Terraform, CloudFormation, and Serverless.
Yor is built to run as a GitHub Action automatically adding consistent tagging logics to your IaC. Yor can also run as a pre-commit hook and a standalone CLI.

So basically, it updates your resources tags with things like:
   tags   = {
      env                  = var.env
      yor_trace            = "912066a1-31a3-4a08-911b-0b06d9eac64e"
      git_repo             = "example"
      git_org              = "bridgecrewio"
      git_file             = "applyTag.md"
      git_commit           = "COMMITHASH"
      git_modifiers        = "bana/gandalf"
      git_last_modified_at = "2021-01-08 00:00:00"
      git_last_modified_by = "firstname.lastname@example.com"
   }

Maybe that would be good enough to provide what you're trying to do?
As far as my testimony, I have not used yor since my tagging uses a different approach.  Instead of having "raw" tags, we use a label module that builds the tags for us and then merges in local tags.
Just sharing this info FYI in case it helps.


Problema ao excluir um registro, buscar o próximo

Question: Estou tentando fazer no código, uma página editar, então o usuário nesta página de editar, ele pode excluir o registro, e se ele excluir, o sistema tem que verificar, se existir um registro próximo, ele vai para tela de editar do próximo, se não existe o id próximo, ele tenta o registro anterior, e caso não tenha nem o próximo, nem o anterior, ele retorna para a página de incluir um novo.
Segue a lógica que estou fazendo, mas nem sempre funciona.
[HttpPost]
    public ActionResult ExcluirProduto(int id)
    {
        var result = false;
        var item = db.Produtos.Find(id);

        if (item != null)
        {
            db.Produtos.Remove(item);
            db.SaveChanges();

            result = true;
        }
        var itemProx = db.Produtos.Where(e => e.Id >= id).OrderBy(e => e.Id).Skip(1).Take(1).FirstOrDefault();
        var itemAnte = db.Produtos.Where(e => e.Id <= id).OrderByDescending(e => e.Id).Skip(1).Take(1).FirstOrDefault();
        int idprox = 0;
        int idant = 0;
        try
        {
            idprox = itemProx.Id;
        }
        catch { idprox = 0; }
        try
        {
            idant = itemAnte.Id;
        }
        catch { idant = 0; }
        try
        {
            if (idprox == 0 && idant == 0)
            {
                id = 0;
            }
            else
            {
                if (idprox != 0)
                {
                    id = (itemProx.Id);

                }
                else
                {
                    id = (itemAnte.Id);
                }
            }
            return Json(new { Resultado = result, id });
        }
        catch {
            id = 0;
            return Json(new { Resultado = result, id });
        }
    }

E aqui é o meu AJAX que redireciona a página:
 function Excluir(idproduto) {
    var idproduto = document.getElementById("Id").value;
    var url = "/Produto/ExcluirProduto";
    $.ajax({
        url: url,
        data: { id: idproduto },
        datatype: "json",
        type: "POST",
        success: function (data) {
            if (data.resultado) {
                alert('Excluído com sucesso.');
                if (data.id != 0) {
                    window.location.href = "/Produto/Editar/" + (data.id);
                }
                else {
                    window.location.href = "/Produto/Novo";
                }
            }
        }
    })
}

Lembrando que utilizo MVC Core - Page Razor.
Comment: Quando não funciona?
Comment: Quando eu vou excluindo vários de uma vez, e mesmo havendo registros próximos ou anteriores, ele retorna para a página novo.
Comment: Falta detalhes do que está errado a pergunta está longa. Tente editá-la para conseguir respostas úteis.
Como contribuição, utilize `console.log` no data.resultado para verificar, provavavelmente está vindo um valor negativo (undefined, 0, null, "", etc)
Answer: A sua lógica de seleção está um pouco confusa na sua Controller e pode ser simplificada. E alterei o seu objeto de retorno Json para garantir que ele apresente o formato de propriedade e valor e respeite o case.
[HttpPost]
public ActionResult ExcluirProduto(int id)
{
    var result = false;
    var item = db.Produtos.Find(id);

    if (item != null)
    {
        db.Produtos.Remove(item);
        db.SaveChanges();

        result = true;
    }
    //Seleciona o próximo maior
    int? proximoProdutoId = db.Produtos.Select(p => p.Id)
                                        .OrderBy(p => p)
                                        .FirstOrDefault(p => p > id);

    //Se for 0, tenta selecionar o próximo menor
    if(proximoProdutoId == 0)
        proximoProdutoId = db.Produtos.Select(p => p.Id)
                                      .OrderByDescending(p => p)
                                      .FirstOrDefault(p => p < id);

    return Json(new { resultado = result, id = proximoProduto});
}

Com esses ajustes o seu javascript deve se comportar da forma correta, mas vale observar que da forma como escreveu, se o id de entrada não existir no contexto para ser excluído, o resultado será false e nada acontecerá na página.
Comment: Ele ta retornando o seguinte erro: O operador "??" não pode ser aplicado a operandos dos tipos "int" e "int".
E no returnJson, id = proximoProdutoId.
Comment: @marianac_costa, Ajustado
Comment: Fiz os testes, e o problema não ocorreu mais, obrigado.
Answer: Vejo dois erros a serem corrigidos na sua lógica:

Você não precisa usar o ".Skip(1).Take(1)", pois o comando FirstOrDefault precedido pelo OrderBy/OrderByDescending já resolve a questão de pegar o próximo ou o anterior.
Na sua chamada Ajax, se o data.resultado for 'falso', sua aplicação não vai fazer nada.

Você não deixou claro o real problema, mas talvez tenha a ver com estas duas situações.
Comment: Fiz o teste retirando o skip e o take, e nada acontece. Fiz desta forma, pois vi em uma reposta aqui no fórum que funcionava. Em questão do ajax for falso não fazer nada, é assim mesmo que deve ser.


Permanently disable Auto Preview in views?

Question: Is it possible to make views stop defaulting to Auto Preview on? It's really slowing down my workflow.
Answer: As seems to always be the case, I stumbled upon the views settings page after posting the question: On admin/structure/views/settings unselect "Automatically update preview on changes."
Comment: LIFE SAVER!!! I had some erroneous javascript that was killing me


How to supply $HOME or $COMPOSER_HOME option via salt state.apply?

Question: I'm trying to install composer via salt. Here is the composer.sls I am using:
get-composer:
 cmd.run:
    - name: 'CURL=`which curl`; $CURL -sS https://getcomposer.org/installer | php'
    - unless: test -f /usr/local/bin/composer
    - cwd: /root/

install-composer:
  cmd.wait:
    - name: mv /root/composer.phar /usr/local/bin/composer
    - cwd: /root/
    - watch:
      - cmd: get-composer

I am running it like this:
salt 'webserver' state.apply composer

The error that I am getting says (in part):
stdout:
              All settings correct for using Composer
              The HOME or COMPOSER_HOME environment variable must be set for composer to run correctly
Summary for webserver
------------
Succeeded: 0 (changed=1)
Failed:    2

Now here's what I am having trouble groking.
On the Composer Salt formula documentation page, it says:
Installed ... composer_home=u'/root'

and $COMPOSER_HOME is one of the options. How do I supply this option? I'm just not finding it on the docs.
Answer: I had the same issue and was able to fix it by defining COMPOSER_HOME under env variable like below:
get-composer:
  cmd.run:
    - name: 'CURL=`which curl`; $CURL -sS https://getcomposer.org/installer | php'
    - unless: test -f /usr/local/bin/composer
    - cwd: /var/www/
    - env:
      - COMPOSER_HOME : /var/www

install-composer:
  cmd.wait:
    - name: mv /var/www/composer.phar /usr/local/bin/composer
    - cwd: /var/www/
    - watch:
      - cmd: get-composer


Problem adding a tab to the user menu

Question: I created a panel page using the Panels module, Contact list at the path messages/contact-list.
The Privatemsg module causes several tabs (Inbox, Sent messages, All messages) to be displayed across the top of pages with path messages.  I am attempting to add an additional tab that links to my Panels page, Contact list.
Based on the code in privatemsg.module for the "Sent messages" tab:
  $items['messages/sent'] = array(
    'title'            => 'Sent messages',
    'page callback'    => 'privatemsg_list_page',
    'page arguments'   => array('sent'),
    'file'             => 'privatemsg.pages.inc',
    'file path'        => drupal_get_path('module', 'privatemsg'),
    'access callback'  => 'privatemsg_user_access',
    'type'             => MENU_LOCAL_TASK,
    'weight'           => -12,
    'menu_name'        => 'user-menu',
  );

I added this code to hook_menu() in a custom module:
  $items['messages/contact-list'] = array(
    'title'            => 'Contact List',
    'page callback'    => 'drupal_goto',
    'page arguments'    => array('messages/contact-list'),
    'access callback'  => 'privatemsg_user_access',
    'access arguments' => array('read privatemsg'),
    'type'             => MENU_LOCAL_TASK,
    'weight'           => 10,
    'menu_name'        => 'user-menu',
  );

However, although this produces no errors, even after clearing the cache multiple times no tab appears anywhere.  I tried moving the code from my custom module into the privatemsg module to no effect.  I've looked at the documentation for hook_menu() but it still isn't clear to me what I'm doing wrong.
Comment: not including `return $items;` was one thing that caused me to face this problem many times :) and I've seen better and more experienced people than me do this too, so I'd suggest that its worth a check, also suggest checking if there is an entry for `messages/contact-list` in the `menu_router` table with the respective arguments to gain some insight.
Comment: I did include `return $items`; there is an entry in the `menu_router` table with `ctools_access_menu` as the access callback and `page_manager_page_execute` as the page callback.  I don't really understand what that means though.
Answer: The reason for your problem is that page manager has already defined a menu entry for that path. Just as well, because the menu item you have created would cause an infinite chain of redirection. You would need to change the path for your panels page to be something different in order for the redirection to work.
But you can simply remove your menu entry altogether and use page manager to define the menu item for the page as a tab under Settings -> Menu. You shouldn't need any extra code to do that.
Comment: I could've swore there was a reason I avoided using the Panels UI, but I was able to do it this way without trouble.  Thanks!

Problem adding a tab to the user menu


Casting a multivariate linear model as a multiple regression

Question: Is recasting a multivariate linear regression model as a multiple linear regression entirely equivalent?  I'm not referring to simply running $t$ separate regressions.
I have read this in a few places (Bayesian Data Analysis -- Gelman et al., and Multivariate Old School -- Marden) that a multivariate linear model can easily be reparameterized as multiple regression.  However, neither source elaborates on this at all.  They essentially just mention it, then continue using the multivariate model.  Mathematically, I'll write the multivariate version first,
$$ \underset{n \times t}{\mathbf{Y}} = \underset{n \times k}{\mathbf{X}} \hspace{2mm}\underset{k \times t}{\mathbf{B}} + \underset{n \times t}{\mathbf{R}},
$$
where the bold variables are matrices with their sizes below them.  As usual, $\mathbf{Y}$ is data, $\mathbf{X}$ is the design matrix, $\mathbf{R}$ are normally distributed residuals, and $\mathbf{B}$ is what we are interested in making inferences with.
To reparameterize this as the familiar multiple linear regression, one simply rewrites the variables as:
$$ \underset{nt \times 1}{\mathbf{y}} = \underset{nt \times nk}{\mathbf{D}}  \hspace{2mm} \underset{nk \times 1}{\boldsymbol{\beta}} + \underset{nt \times 1}{\mathbf{r}},
$$
where the reparameterizations used are $\mathbf{y} = row(\mathbf{Y}) $, $\boldsymbol\beta = row(\mathbf{B})$, and $\mathbf{D} = \mathbf{X} \otimes \mathbf{I}_{n}$.  $row()$ means that the rows of the matrix are arranged end to end into a long vector, and $\otimes$ is the kronecker, or outer, product.
So, if this is so easy, why bother writing books on multivariate models, test statistics for them etc.?  It is most effective to just transform the variables first and use common univariate techniques.  I'm sure there is a good reason, I just am having a hard time thinking of one, at least in the case of a linear model.  Are there situations with the multivariate linear model and normally distributed random errors where this reparameterization does not apply, or limits the possibilities of the analysis you can undertake?
Sources I have seen this:
Marden - Multivariate Statistics: Old School.  See sections 5.3 - 5.5.  The book is available free from: http://istics.net/stat/
Gelman et al. - Bayesian Data Analysis.  I have the second edition, and in this version there is a small paragraph in Ch. 19 'Multivariate Regression Models' titled: "The equivalent univariate regression model"
Basically, can you do everything with the equivalent linear univariate regression model that you could with the multivariate model?  If so, why develop methods for multivariate linear models at all?
What about with Bayesian approaches?
Comment: What do you mean by foundations rather than structure?  Could you elaborate?
Comment: Ok, so.. its not *my* approach, I pointed out two places I have seen this.  The approach is the crux of the issue.  What is the difference between the multivariate version and the reparameterized univariate version?
Comment: It is good question. May be you could ask for more in terms of foundations rather than a structure.
Comment: May note that I learnt only two papers as part of my first and postgraduate degree long back, I do not have grooming in technical descriptions. I understand that Multivariate analysis has different assumptions when compared with a multiple linear regression or simply  linear regression model. The assumptions for Multivariate analysis are different i.e. mathematical expectation prevails upon. multiple linear regression makes certain other assumptions that result in heteroscedatisticity. The structure here I mean refers to your equations.
Comment: You should say it clearly in the title or the beginning whether you are speaking of _multivariate (general) linear model_ or about _bayesian multivariate regression_.
Comment: Oh.. I am really just talking about the model, and not so much the approach.  From my understanding, for a GLM you use point estimates which themselves have a distribution.  For a Bayesian multivariate regression, your solution is a distribution on $\mathbf{B}$.  I don't think this interpretation matters.
Comment: I didn't read your question attentively, so my comment may be a miss. But does your "reparameterization" adequately accounts for the fact that the DVs covariate? Multivarite GLM and multiple linear regression are equivalent only in case of several variables vs one variable. Then R-square = Pillai's trace.
Comment: Yes, it does account for correlations in the DVs.  This is what is confusing to me.  It is easy to verify in R or octave or whatever that if you make fake data/design matrix and then reparameterize as shown in the question.
Comment: Regardles of whether your approach is correct or not (I didn't check it, sorry) you should be aware that Multivariate GLM (such as MANOVA) is computentionally more efficient, faster than the series or reparameterized univariate multiple regressions. Also, your claim about that F is "exact" while multivariate tests are "approximations" seem to be not true.
Comment: All you have done is change the notation; you haven't changed the model one whit. (You can recover the original formulation from the rewritten version. It's not even a reparameterization: the parameters are in one-to-one correspondence and all you have done is to re-index them.) Since changing the names of terms in a model is considered to be inconsequential, *of course* these models are equivalent.  But try writing some natural multivariate models in univariate form and you'll quickly see how much more expressive the multivariate notation can be.
Comment: Yes, maybe reindex is a better word than reparameterize.  I guess I'm just having a having a hard time understanding why the univariate form is less expressive.  I've never seen things like the Wilks and Pillais trace statistics used in a univariate setting, even though the models can be equivalent.  Why is this?
Answer:
Basically, can you do everything with the equivalent linear univariate
  regression model that you could with the multivariate model?

I believe the answer is no.
If your goal is simply either to estimate the effects (parameters in $\mathbf{B}$) or to further make predictions based on the model, then yes it does not matter to adopt which model formulation between the two.
However, to make statistical inferences especially to perform the classical significance testing, the multivariate formulation seems practically irreplaceable. More specifically let me use the typical data analysis in psychology as an example. The data from $n$ subjects are expressed as
$$ \underset{n \times t}{\mathbf{Y}} = \underset{n \times k}{\mathbf{X}} \hspace{2mm}\underset{k \times t}{\mathbf{B}} + \underset{n \times t}{\mathbf{R}},
$$
where the $k-1$ between-subjects explanatory variables (factor or/and quantitative covariates) are coded as the columns in $\mathbf{X}$ while the $t$ repeated-measures (or within-subject) factor levels are represented as simultaneous variables or the columns in $\mathbf{Y}$.
With the above formulation, any general linear hypothesis can be easily expressed as
$$\mathbf{L} \mathbf{B} \mathbf{M} = \mathbf{C},$$
where $\mathbf{L}$ is composed of the weights among the between-subjects explanatory variables while $\mathbf{L}$ contains the weights among levels of the repeated-measures factors, and $\mathbf{C}$ is a constant matrix, usually $\mathbf{0}$.
The beauty of the multivariate system lies in its separation between the two types of variables, between- and within-subject. It is this separation that allows for the easy formulation for three types of significance testing under the multivariate framework: the classical multivariate testing, repeated-measures multivariate testing, and repeated-measures univariate testing. Furthermore, Mauchly testing for sphericity violation and the corresponding correction methods (Greenhouse-Geisser and Huynh-Feldt) also become natural for univariate testing in the multivariate system. This is exactly how the statistical packages implemented those tests such as car in R, GLM in IBM SPSS Statistics, and REPEATED statement in
PROC GLM of SAS.
I'm not so sure whether the formulation matters in Bayesian data analysis, but I doubt the above testing capability could be formulated and implemented under the univariate platform.
Comment: I see, this makes sense.  Thank you for the great answer.  I'd love to hear a Bayesian perspective too.
Comment: @PeterRabbit If you like the answer, please express your gratitude to bluepole by accepting his answer. He'll get points.
Comment: I will, I was just holding out a bit to see if anyone would offer a Bayesians perspective though.
Answer: Both models are equivalent if you fit appropriate variance-covariance structure. In transformed linear model we need to fit  variance-covariance matrix of error component with kronecker product which has limited availability in available computing softwares. Linear Model Theory-Univariate, Multivariate, and Mixed Models is excellent reference for this topic.
Edited
Here is another nice reference freely available.
Comment: Oh ok, so in a normal univariate model, there is no type of covariance structure "within" the DVs.  Therefore hypothesis tests concerned with that don't exist.  Thank you!  I'll see if I can pick up that book.


covariance of lognormal random variables

Question: I am trying to find the variance of b*log(x+y) - log(x), where x and y are independent and identically distributed lognormal random variables, the range for log(x) and log(y) is negative infinity to infinity, and 0<b<1. I have used the Fenton-Wilkinson (FW) approximation to find the variance of log(x+y), but I also need to find the covariance(log(x+y), log(x)) since both terms have x in common. FW doesn't seem to help me with this problem (although I may be wrong). I had assumed that covariance(log(x+y), log(x)) = variance(log(x)) but my simulations do not support this answer.
Comment: The fact that you need an approximation of $\log(X+Y)$ is revealing!  The sum of independent, nonsingular lognormal variables is never lognormal.  Although we might still hope to be able to compute moments, it doesn't look likely.  To what extent, then, would you be interested in approximations to the moments?  Over what ranges of parameters?
Comment: A slight simplification is that $\log(X+Y)-\log(X)=\log(1+Y/X)=\log(Z)$ where $Z=Y/X$ is lognormal because $(X,Y)$ is lognormal.  The range is not helpful: what matters are the values of the parameters of $Z.$ For instance, when $Z$ has a tiny geometric mean and tiny geometric SD, you can approximate $\log(1+Z)$ by $Z$ itself; and when $Z$ has a large GM and not too large GSD, $\log(Z)$ is a good approximation.
Comment: *Please* ask the question you actually face.  This makes it more likely the answers will be useful.
Comment: Please edit your question to contain the new information.
Comment: Thank you @whuber for your quick response! I actually need to find variance(log(x+y) - log(x)), where x, y are iid lognormal. I approximate x+y to be lognormal using Fenton-Wilkinson (FW). There must clearly be a covariance term because both terms have x in common. FW doesn't seem to help me with this case (I may be wrong) but I would be happy with any approximation. The range for log(x) and log(y) is negative infinity to infinity.
Comment: Thank you. I actually need to find the variance of beta*log(X+Y) - log(X), where 0<beta<1. I had simplified the problem when I stated it and you have made me realize that I over simplified it.
Comment: Yes; my apologies.
Answer: This is really a comment that is too long for the comment box, but might spur someone else to prove the result.
There appears to be a very clean exact solution, namely that, if $X \sim \text{LogNormal}(\mu,\sigma)$ is independent of $Y \sim  \text{LogNormal}(\mu,\sigma)$, then:
$$\text{Cov}[\log(X+Y), \log(X)] = \frac12  \sigma^2$$
The proof, like Ramanujan, is ...
Comment: +1 This is why I have repeatedly asked the OP to state their assumptions about the parameters: the *iid* case appears much more tractable.  (So is the more general case where the geometric means differ but the geometric SDs are the same.)  Some things can be inferred from general principles: in the *iid* case, the formula must be a function of $\sigma^2$ alone, for instance.
Comment: Thank you @wolfies!!!!! This is indeed beautifully clean and agrees with my simulations. Would you please share your intuition?
Comment: Thank you @whuber. That is a helpful insight and I appreciate your help with my problem (which has been halting progress on my research).


What is the proper way to play A-Flat scales on piano?

Question: Consider four cases:

A-flat major
A-flat (natural) minor
A-flat melodic minor
A-flat harmonic minor

I start them with the third finger on the A-flat key (both hands), but I have no idea how a professional pianist would do it.  Help!
Comment: This general fingering chart should be of use to you http://www.robertkelleyphd.com/scalfing.htm
Comment: Evenly.  :)  Seriously, all the advice is good here.  I'm one of the "some pianists" who starts this scale with 2 in the right hand.  No sense passing the thumb under the 4th finger when you can pass it under the 3rd without running out of fingers.
Answer: There's nothing wrong with starting on the third finger.  I would think most people would be taught it that way, because then it's consistent with the fingering you would use as you go up an octave (i.e., if you start on A♭4 you should play A♭5 with the third finger).
Some pianists might start with the second finger on the right hand, however.  The inconsistency is initially difficult to manage mentally, but it allows you to start with your stronger index finger.
Comment: Although there's nothing wrong with starting on the third finger (right hand), the scales books of the Associated Board of the Royal Schools of Music (ABRSM) suggest starting on the second finger - presumably so, as Matthew says, you have a stronger start.
Comment: I would certainly advise starting with the second finger in the minor keys. It is easier to be even for the passage between Cb and Db.
Answer: I think what helps instead of memorizing where each individual finger should go, is to memorize the "imprint" of your hand on the keyboard. For Ab major for instance, this would be thumb, index and middle on C, Db and Eb resp. and then thumb, index, middle and ring on F, G, Ab, and Bb resp. That is for the right hand, for the left hand, middle, index and thumb on Ab, Bb and C resp. and ring, middle, index and thumb on Db, Eb, F and G resp. Then, you can start on whatever finger you like, you just have to see that you fall back to that pattern somehow.
Answer: For Ab Major: Start with the third finger on the right hand, third finger on the left.  Play the C with your thumb, then cross over for the Db.
Ab minor: This has the same key signature as B Major, so you can use the same fingering.
Comment: Minor clarification: Abm and BM have the same *effective* key signature.
Answer: For A flat major, these are the fingerings I'd use:
Left hand ascending:
3 2 1 3 2 1 4 3
Right hand ascending:
3 4 1 2 3 1 2 3
Descending scales would have the fingers placed in the same positions on the piano as the ascending scales.  Thus, the fingerings would be the same sequence as written above, but in reverse.  Minor scales would use the same fingering.
I chose this fingering by using a method that works on all scales that use a lot of black keys.  I was taught this method by my piano teacher.
The idea is that each time you play the group of two black keys (C sharp and D sharp, or D flat and E flat) you use the second and third fingers of your hand.  And every time you play the group of three black keys (F sharp, G sharp and A sharp, or G flat, A flat and B flat) you use the second third and fourth fingers of your hand.  This applies to both the left and right hands.  Then you place your thumbs appropriately.  And if you have to use fewer than 5 black keys, you use the finger on the white key that would have been on the black key next to it.  So you can hover your hands over the groups of black keys and figure out the fingerings pretty easily.
A good scale to practice this on is G flat major, since it uses all 5 black keys.  If you master playing G flat major with this type of fingering, and think of it as a sort of default or standard pattern, then you'll be able to adjust it slightly to play other scales that use several black keys.
Advantages to fingering this way include:
1) It is easy to find where your hand position should be on the piano, and to figure out the fingering.
2) The thumbs always get played by both hands at the same time.  This means that it's easier to coordinate the hands.  Also you can more easily anticipate where the fingers cross over the thumb.
3) The thumbs never land on a black key.  This makes hand positions less awkward.
4) It switches the question from "What are the black keys I need to use?" to "What are the white keys I need to use?" This gives you fewer things to remember if the key uses a lot of black keys, and makes the black keys seem less intimidating.
5) You can keep going for several octaves, since it is easy to repeat the patterns.  The pinky finger isn't used, so the awkwardness of crossing over it is avoided.
That said, there are other ways to choose the fingering, and some of them might also count as "proper" ways to do it.
Answer: 3 4 1 2 3 1 2 (3)
Just keep crossing over with 3!
Answer: To answer your question: evenly.  :)  That's why we use the fingerings that we do, because they are generally considered "best practice" to get the scales even.
Now, I always start the Ab scales with the second finger in the right hand.  There's no technical reason to pass the thumb under the fourth finger instead of the third, and for me passing under the fourth is a little more difficult.  Most pros do this as well in my experience; I had three different piano professors in college and they all taught the same scale fingerings.  Now, Bb and Eb I always start with 2 instead of 3, for much the same reasons.  Conversely, I end Bb, Eb, and Ab with 2 in the left hand as well.
Therefore, it looks like my rule is to start black-key scale fingerings with the finger closest to the thumb that will still get the thumb on the right note to begin the  combination of 123 and 1234 (or 321 and 4321 in the other hand) that the rest of the scale uses.
Answer: Here are the fingerings I prefer for the four scales asked about, followed by some notes for general guidance.
Ab Major

     Ab   Bb   C Db Eb F G (Ab)
RH:  3(2) 4(3) 1 2  3  1 2 (3)
LH:  3    2    1 4  3  2 1 (3)

Ab (Natural) Minor

     Ab   Bb   Cb Db Eb Fb Gb (Ab)
RH:  3(2) 4(3) 1  2  3  1  2  (3)  [same fingering as Ab major and B major]
LH:  3    2    1  3  2  1  4  (3)  [same fingering as B major; different from Ab major]

Ab Melodic Minor

     Ab   Bb   Cb Db Eb F G (Ab)
RH:  3(2) 4(3) 1  2  3  1 2 (3) [same as major]
LH:  3    2    1  4  3  2 1 (3) [ascending]
                            (3)  4  1  2  3  1  2  (3) [descending]
                            (Ab) Gb Fb Eb Db Cb Bb (Ab)

Ab Harmonic Minor

     Ab   Bb   Cb Db Eb Fb G (Ab)
RH:  3(2) 4(3) 1  2  3  1  2 (3) [same as major]
LH:  3    2    1  4  3  2  1 (3) [same as major]

@user28 is correct that it's fine to use 3 and that 3 is commonly taught. I also follow both @Raskolnikov (think in groupings of 1 2 3 and 1 2 3 4) and @StrangeAttractor (2 3 on pairs of consecutive black keys; 2 3 4 on trios).
In general, there is flexibility at the bottom and top end of (black key) scales. The standard fingerings are designed to facilitate running scales through multiple octaves, but at the bottom and top, since you're not continuing through another octave, you can defer to comfort.

Because the Ab natural minor fingerings are identical to the B major scale (that is, the same fingers correspond to the [enharmonically] same pitches), there is also this related question: Why do we use the fourth finger of the left hand to start the b major scale?


how to prove unobservable subspace ($\text{null}(C, A)$) is $A$-invariant

Question: Given
$$ \begin{align*}
\dot{x} &= Ax + Bu \\
y &= Cx
\end{align*} $$
where $A \in \mathbb{R}^{n \times n}$, $B \in \mathbb{R}^{n \times m}$, $C \in \mathbb{R}^{p \times n}$.
How to prove the title?
I think I should use the matrix:
$$ \begin{bmatrix}C \\ CA \\ \vdots \\ CA^{n-1} \end{bmatrix} $$
Comment: I've taken the liberty to edit your post. Please have a look in case something is wrong.
Answer: Let
$$ \mathcal{O} = \begin{bmatrix}C \\ CA \\ \vdots \\ CA^{n-1} \end{bmatrix} $$
We need to show that if $v \in \text{Ker} \mathcal{O}$, then $Av \in \text{Ker} \mathcal{O}$. If $v \in \text{Ker} \mathcal{O}$, then
$$ \begin{bmatrix}C \\ CA \\ \vdots \\ CA^{n-1} \end{bmatrix} v = \begin{bmatrix}Cv \\ CAv \\ \vdots \\ CA^{n-1}v \end{bmatrix} = 0 $$
Now, let us look at $\mathcal{O} A v$, which is
$$ \begin{bmatrix}CA \\ CA^2 \\ \vdots \\ CA^{n} \end{bmatrix} v = \begin{bmatrix}CAv \\ CA^2v \\ \vdots \\ CA^{n}v \end{bmatrix} = \begin{bmatrix}0 \\ 0 \\ \vdots \\ CA^{n}v \end{bmatrix} $$
The last term is also $0$ because of the Cayley-Hamilton theorem.


Quebrar linhas no CSS sem usar elementos a mais

Question: Tenho 2 elementos inline e preciso fazer com que a linha seja quebrada, sem eu precisar adicionar display: block; ou se possível adicionar mas não ocupar 100% da linha:

        404

        Ops! Página não encontrada

Não foi possível localizar o link que você estava buscando.

    Ir à página inicial
    Voltar à página anterior

No caso os 2 links no final, deveriam quebrar linha, queria ver se tem alguma forma, sem a necessidade de usar elementos a mais, apenas pra quebrar a linha, sei que daria pra fazer com UL>LI.
Comment: @Marta, esse tipo de downvote injusto acaba se auto-corrigindo. Seu 1º comentário é bastante construtivo nesse sentido. Ah, sim, ++ na sua resposta, legal a técnica :)
Comment: Não entendi porque a pergunta foi downvoted.
Comment: É "normal" aparecer downvote sem justificativa. Poucos assumem o que fazem (sem ofensa a quem o fez porque não sei quem foi) e/ou justificam o motivo.
Comment: Uma pena, porque achei a pergunta bem legítima. E vi que dar downvote tira um ponto da sua reputação, então não faz muito sentido sair distribuindo.
Answer: Você pode usar o pseudo-elemento :after
a:after{content:""; display:block; clear:both}

O :after funciona a partir do IE8. Com ele você cria um elemento no CSS, então não precisa mexer no seu HTML.
Exemplo: http://jsfiddle.net/xqbyeq6k/
Comment: Obrigado!! Era isso mesmo. :D


Como abrir uma webview local cshtml no Xamarin Forms

Question: Estou com um projeto em Asp net mvc e outro em Xamarin Forms, preciso chamar no meu projeto Xamarin Forms uma WebView Local porem a pagina está como cshtml (asp net)
Comment: Você não pode abrir diretamente a View, vai precisar indicar a URL para da action no site mvc
Answer: Não vai rolar. cshtml é uma extensão de arquivo de projeto que precisa ser compilado, publicado em um servidor asp.net para que no momento da requisição web seja processado e só então a página HTML seja entregue para o cliente (no seu caso a webview).
Na melhor das hipóteses o que você vai conseguir é navegar em conteúdo html baseado em arquivos dentro do proprio aplicativo, mas é difícil dizer se isso lhe atenderia somente com as informações que foram fornecidas até o momento.
Comment: Entendi, estou utilizando agora o html, porem estou com problema para chamar a webview local em cada aplicativo utilizando Dependencia como sugerido na documentação da microsoft
Comment: https://docs.microsoft.com/pt-br/xamarin/xamarin-forms/user-interface/webview?tabs=vswin
Comment: Gravidade Código Descrição Projeto Arquivo Linha Estado de Supressão
Erro CS7036 Não há nenhum argumento fornecido que corresponde ao parâmetro formal necessário "loadHintArgument" de "DependencyAttribute.DependencyAttribute(string, LoadHint)" AppFrete.UWP
Erro CS7036 Não há nenhum argumento fornecido que corresponde ao parâmetro formal necessário "loadHintArgument" de "DependencyAttribute.DependencyAttribute(string, LoadHint)" AppFrete.iOS
Comment: Erro CS1061 "MapViewDetail.IBaseUrl" não contém uma definição para "BaseUrl" e não foi possível encontrar nenhum método de extensão "BaseUrl" que aceite um primeiro argumento do tipo "MapViewDetail.IBaseUrl" (há uma diretiva de uso ou referência de assembly ausente?) AppFrete

Print do código
https://www.dropbox.com/s/xdunfahoco6xy46/erro.PNG?dl=0
Comment: @ViniciusDantas, beleza. Abre uma outra pergunta sobre o novo erro que você está enfrentando, já que isso está fora do escopo desta thread aqui. Veremos se vamos consiguir te ajudar a partir de lá. É dificil fazê-lo sem ver o código que está utilizando.


Advice on writing a midi file from almost complete sheet music

Question: I want to convert a song to a midi file. The sheet music I've found on the internet for this song is almost complete. It's missing a few notes that I can hear when I listen to the song. I can just about make out the missing notes before the singing on the track starts. What's the best way figure out the missing notes?
For example the first bar is missing two notes that should be played at the end.
C#(g#)major C#(f)major F#major
Should be
C#(g#)major C#(f)major F#major C# A#
Any advice on transcribing songs to midi would be helpful also. Thanks.
EDIT: Using mingus to make the midi file.
Comment: Do you mean keys, notes or chords?
Comment: how are you planning on converting the sheet music to midi?  scanner, clicking it in?  please specify.
Comment: Regarding "figure out the missing [notes/chords]": Do a search on ["ear training"](http://music.stackexchange.com/search?q=ear+training) in this site and you will find questions and answers that should help you.
Comment: @StephenHazel Using Mingus http://code.google.com/p/mingus/
Comment: @DrMayhem notes
Comment: This is a little like asking "How do I convert the cliffnotes of Romeo and Juliet into a videorecording of the play?"
Answer: Very easy, use the opensource software (read free) MuseScore.
It allows you to input the sheet (imports different formats and lets you put the notes by hand), play them for you and export to pdf and MIDI files among others.
Just try a few settings for the missing notes in musescore, the playback function will tell you if it is correct or not.
You don't want to code a midi file yourself, as it is a very low level document type, written in hexadecimal code.
Answer: If you have a recording of the music
Sibelius has something called AudioScore which deals with transcribing from recording to e-notation (e.g. midi), though this solution costs.
Googling around I found http://www.rinki.net/pekka/slowmp3/ which seems to be a free alternative - I've not yet tried it out though.
If you only have sheet music
Again Sibelius offers a solution with PhotoScore, which can convert sheet music to e-notation (midi); again this costs money.
If you're just missing some chords / notes
It's generally possible to guess missing chords from understanding music theory.  Chord sequences tend to be repeated throughout a piece, so look for a matching pattern to what you have elsewhere in the piece & try grafting that over the missing section.
Comment: In case you don't want to buy Sibelius, read dorien's answer as well because it includes MuseScore (which I highly recommend). Also, you can't forget Finale (by MakeMusic)! (The full version includes a pdf-to-digital score utility, among countless other wonderful features.)
Comment: Don't waste your money on AudioScore (which attempts to convert audio to MIDI).  It's useless.  SlowMP3 attempts something quite different, and doubtless does it well.  But it helps YOU transcribe, it doesn't attempt to do the job for you.  PhotoScore (notation to MIDI, not audio to MIDI)
Answer: hmmm, I'm not familiar with Mingus I'm afraid...  Ask the developer if you're having probs with it, but I suspect you're not (kinda hard to tell:)
Your link isn't to "sheet music" - it's to a lead sheet - just listing chords and melody, not an actual arrangement of exact notes to play.
So hit google and look for other renditions of that song.  There may be one already in midi format (or not:)  If you find a midi file, it'll have all the notes that make the chords and from that you can polish off the lead sheet into a midi file of "just the chords".
Or you can google for the (actual) sheet music via...
filetype:pdf "sea diver"
good luck to ya.
Answer: I use Melody Assistant to physically write piano midis from sheet music.  BUT after I write the midi, I export it to a complete midi in my computer and import it to Notation Composer, edit it  to make sure that the softeware completely and correctly imported the song, and then print it as Notation Composer had a better printing section.


What is the best way to teach a friend to sing? (Improving hearing ability)

Question: In the past, I thought that singing (I mean hearing the notes and being able to produce the same note) was given at birth and couldn't be improved. But in a year, a friend of mine improved himself so much that I realized I was wrong. This friend I am talking about wasn't able to harmonize at all and would go off tune all the time. Couldn't even stay in the same note. But now he can very much sing and hear/produce correct notes etc.
So another friend of mine asked me to teach him. Now I am asking what is the best way to do this? Right now I am playing a note from the piano and trying to make him produce the same note one by one. If there are good tecniques I would like to hear them! Thanks!
Comment: Maybe you should refer the second friend to the first? :)
Comment: @LukeSawczak That's a good idea :) However he got professional help :)
Answer: One method could be a simplification of one I use to write large vocal parts - as even after all these years & can't just write them all down, or even sing them all one after another straight out of my head.*
First, pick a simple song, a 3- or 4-chord wonder to start with. Maybe a country-style song - something with a strong melody but nothing too 'clever' in the way of melodic structure.
Play simple chords left hand & the melody right hand - which will give the melody something to sit on, rather than being free-floating with no reference.
Emphasise which note of the chord references which melody note, then point out any that aren't part of a simple triad - pick tunes where these are more passing notes, rather than something that will to a beginner appear to just sit entirely in the cracks. Stay away from complex or chromatic structures initially. This should start to train your friend to be able to get the first note right just from the chord - a necessary skill, ongoing.
That should give them sufficient grounding eventually that you can progress to something more complex.
*I extend this method when writing so that I'm playing the existing parts, leaving me to sing the new one until I'm happy with it. I then swap which to sing & which to play until I've got them all, before I even record the first part.


If A has a finite number of distinct eigenvectors then each eigenvector must have a distinct eigenvalue. How to prove that?

Question: Preface: This is an exercise question, I have no idea how to prove this.
Question: In this question we will be exploring eigenvectors and eigenvalues. Let A ∈ R n×n. Recall that a vector
v ∈ R
n is an eigenvector of A if there exists λ ∈ R such that λv = Av, and we call λ an eigenvalue
of A, associated with the vector v. If we have some eigenvector v of A note that av is also trivially
an eigenvector for any a ∈ R. Because of this v and av are not considered different eigenvectors: i.e.
colinear eigenvectors are not considered distinct. Prove the following:
Proposition 1. If A has a finite number of distinct eigenvectors then each eigenvector must have a
distinct eigenvalue
Comment: Is this a translation from another language?
Comment: I corrected it, is it ok?
Answer: Assume two vectors $v,w$ have the same eigenvalue $\lambda$ and are not colinear (as otherwise we wouldn't count them as two).
Then also $\alpha v + \beta w$ has eigenvalue $\lambda$. Can you construct an infinite amount of pairwise non-colinear vectors in this way?
Comment: if we prove the following does it mean the same thing:

eigenvectors from different eigenvalues are linearly independent ?


Is $\mathbb{P}(S_n/n>p+a)$ a decreasing function of n?

Question: In my question, I have i.i.d random variables $X_1,...,X_n$ $\sim \text{Bern}(p)$ (Bernoulli distribution with parameter $p$).
Denote $S_n = \sum_{i=1}^{n} X_i$. Does $\mathbb{P}(S_n/n>p+a)$ decrease when $n$ increases, where $a$ is a fixed positive value?
Update: or when $n$ is big enough?
Answer: No, it does not decrease, but oscillates.
Here is a graph of the probability in question for $p=1/2, a=1/10$, for $n=1$ up to $n=100$. A rigorous proof can be achieved by analysing the probability in question, given by
$$P\{\frac{S_n}{n}>p+a\}=\sum_{k>n(p+a)}{n\choose k}p^k(1-p)^{n-k}$$
which follows from the fact that $S_n/n$ takes the value $k/n$ with probability ${n\choose k}p^k(1-p)^{n-k}$.
Answer: I'd like to add very simple observation which works for every sequence with bounded variance.
 Let $p_n = \mathbb{P}\left({S_n \over n} > p + \alpha\right)$. Let's calculate $\mathbb{D} {S_n \over n} = {1 \over n^2} \mathbf{Var} (S_n) = {1 \over n} \mathbf{Var} (X_1)$. Thus, by the Chebyshov's inequality $p_n \le {\mathbb{D} {S_n \over n} \over \alpha^2} = \mathbf{Var}(X_1) {1 \over n \alpha^2}$. Thus $p_n$ is bounded by a decreasing sequence, hence it contains a decreasing subsequence.
Answer: This probability does decrease as $n$ grows.
A heuristic justification is that as $n \rightarrow \infty$, $S_n/n \rightarrow p$, in probability. That is for any $\epsilon > 0$
$$\lim_{n\rightarrow \infty} \mathbf{P}(|S_n/n - p| > \epsilon) = 0.$$
I'm sure its possible to prove this for small $n$ using direct calculation using inequalities for binomial coefficients (I'll leave that to someone else).
Since the sum of $n$ independent Bernoulli $p$ variables has a binomial $\text{Bin}(n,p)$ distribution, an argument for the limiting case is that the De Moivre - Laplace Theorem asserts as $n \rightarrow \infty$
$$ \text{Bin}(n,p) \sim N\big(np,np(1-p) \big)$$
Therefore (using properties of expectations and variance)
$$\left( \frac{1}{n}S_n -p \right) \sim N \left( 0, \frac{p(1-p)}{n}\right).$$
So that in the limit $n \rightarrow \infty$ your question is
$$\lim_{n\rightarrow \infty} \mathbf{P}\left(  N \left( 0, \frac{p(1-p)}{n}\right) > a \right) = 0.$$
One can of course show that the probability for the normal distribution above is decreasing in $n$, though you need to be careful with the fact that the Binomial approximation to the Normal holds only in the limit.
Comment: Wrong. The probability does not decrease in general. For example, take $a=1/7$ and $p=1/2$. Then $S_2/2$ has the distribution $1$ and $0$ with probability $1/4$ each, and$1/2$ with probability $1/2$, so $P(S_2/2>1/2+1/7)=1/4$, but $S_3/3$ has the distribution $1$ and $0$ with probability $1/8$, $2/3$ and $1/3$ with probability $3/8$ each, so $P(S_3/3 > 1/2+1/7)=1/2$.
Comment: I think you're over simplyifying to start your response with  "Wrong". I agree 100% with your answer that this oscillates. As I observed in my post above, I did not address the case of finite $n$. My answer was entirely addressing the limiting case, and is clearly caveated as such. Without knowing the poster's reason for asking, it is impossible to tell whether the motivation is to literally know if this is a decreasing function (as you've shown computationally, no), or to have a justification as to why this would tend to 0 (which I've justified theoretically to be yes).
Comment: Thank both of you very much. I know $S_n/n$ will converge to $p$. My original concern is whether it will strictly decrease or converge with oscillation. I think about this question when I was dealing with my former question https://math.stackexchange.com/questions/2609205/bound-the-probability-that-one-random-variable-deviates-from-its-expected-value. I'm wondering if you can take a look at this question and give some advice. Thank you so much.
Comment: @owen88 - Thank you for your reply. Mathematics is known for its precision. The statement "the sequence $\{a_n\}_n$ is decreasing function of $n$" means precisley this: If $n_1>n_2$, then $a_{n_1}<a_{n_2}$. It does NOT mean $\lim_{n\to\infty}a_n=0$. As a result, when you write "The probability does decrease as $n$ grows", you are wrong. In other words, your statement is logically false.