How to prevent a View from rendering via a hook?

Question: I want to prevent an attached view from running depending on some coding parameters.
I've tried using hook_views_pre_view() to prevent it from running, but I can't figure out what options to set on the view to accomplish that. Tweaking attached or rendered doesn't seem to do anything.
function ding_eresource_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'eresource_list' && $display_id == 'attachment_1') {
    // Prevent rendering if parent view has some option set.
    if (!empty($view->old_view[1]->barr)) {
      // This does not work. How can it be done?
      $view->attached = FALSE;
      $view->rendered = TRUE;
    }
  }
}

How can it be done?
Comment: In my case, the view display I wanted to conditionally prevent from showing was a block display, so I was able to use hook_block_list_alter() to pick it out and remove it at that point. That way views didn't touch it at all.
Answer: Wanted to do similar but just $view->executed = TRUE; made the query in the view still run. Looking at view::build(), I understood you need the following code, to prevent anything running further in the view (displays and query).
$view->executed = TRUE;
$view->built = TRUE;

To make it clearer, the code you should use is the following one.
function ding_eresource_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'eresource_list' && $display_id == 'attachment_1') {
    // Prevent rendering if parent view has some option set.
    if (!empty($view->old_view[1]->barr)) {
      // This does not work. How can it be done?
      $view->executed = TRUE;
      $view->built = TRUE;
    }
  }
}

Answer: $view->executed = TRUE; worked for me but I'm not sure it is a correct way to stop Views from rendering.
Comment: Hmm, that does work, after a fashion. Regrettably, it shows the View's empty text instead, but I worked around this by removing the empty text for the attached view.
Answer: Options for hook_views_pre_render:
$view->result = array();

That destroys the array, preventing any data from rendering.
Or, the plain PHP option:
die();

Comment: Sadly, this doesn't stop pagination from rendering. I'm also assuming `die()` is a joke suggestion ;)


How to abort XMLHttpRequest.upload from the external script?

Question: As a follow up to Why is $_FILES[] always empty?:
When uploading a file via AJAX with PhP, one generally does the following (I'm new to this so please tell me if there is a better way to do this):

Have one file with a form and javascript where you setup and send your XMLHttpRequest, e.g. upload_form.php
Have another, external php file to process the upload request, e.g. upload.php

My question is this:
Is it possible to abort the XMLHttpRequest from within the external upload.php file?.
The reason for wanting to do this is that if the file already exists on the server, I'd like to abort the XMLHttpRequest rather than making the user wait until the upload has completed to be informed of the failure.

Some images to illustrate the problem:
I throttled the speed in the network tab in order to exaggerate the problem.
The user uploads a file that DOES NOT exist on the server in the uploads directory:

The user uploads a file that DOES exist on the server in the uploads directory:

Some code to illustrate the problem:
upload_form.php:

<form class="form" id="upload_form" enctype="multipart/form-data" method="POST">
    <input type="file" name="file_to_upload" id="file_to_upload">

    <input class="button" type="submit" value="Upload">
</form>

upload.php:
<?php

$target_path = "uploads/".basename($_FILES["file_to_upload"]["name"]);
$uploaded_file = $_FILES['file_to_upload']['tmp_name'];

$upload_ok = true;
$errors = [];

// ================= MAIN PART OF QUESTION ==========================
// I want this to cause the abort event to fire on the XMLHttpRequest
if (file_exists($target_path)) {
  $upload_ok = false;
  array_push($errors, 'The file already exists on the server. Please rename the file and try again.');
}
// ==================================================================

if(!$upload_ok) {
  echo 'The file was not uploaded because:
';
  foreach ($errors as $err) {
    echo $err.'
';
  }
} else {
  if(move_uploaded_file($_FILES["file_to_upload"]["tmp_name"], $target_path)) {
    echo 'File uploaded successfully';
  } else {
    echo 'Something went wrong. Please try again.';
  }
}
?>

I've tried checking different combinations of readyState and status in upload_form.php but this hasn't helped.
Answer: By the time the PHP code is get to begin, the file has been fully uploaded so there is no point aborting it that way, which would be to simply return the message. Instead, you can make a prior to upload AJAX call and check if the file exists and only if it doesn't then upload the file or else message the user about it.
Create a simple exists.php with the following code
<?php

$target_path = "uploads/".$_GET['file'];
$file_exists = file_exists($target_path);

header('Content-Type: application/json');

// Return a JSON object with a single boolean property to indicate if the file exists
echo json_encode(['exists' => $file_exists]);

Create a promise to make a XHR call and get the exists.php result
function check_file_exists() {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();

    xhr.open("GET", `exists.php?file=${encodeURIComponent(file_to_upload.files[0].name)}`);
    xhr.responseType = 'json';
    xhr.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        resolve(this.response && this.response.exists);
      }
    };

    xhr.send();
  });
}

Refactor the upload_file submit function to first call the check_file_exists promise
// An element to display a message to the user
const message = document.getElementById('message');

function upload_file(e) {
  e.preventDefault();

  message.textContent = '';

  // Call the promise to check if the selected file exists on the server
  check_file_exists().then(exists => {
    if(exists) {
      // If it exists message the user about it and do nothing else
      message.textContent = `File "${file_to_upload.files[0].name} already exists`;
    } else {
      // If it does not exists upload the file
      const xhr = new XMLHttpRequest();

      xhr.open("POST", "upload.php");
      xhr.upload.addEventListener("progress", e => {
        const percent = e.lengthComputable ? (e.loaded / e.total) * 100 : 0;
        console.log(percent.toFixed(0) + "%");
      });

      xhr.onreadystatechange = function() {

        if (this.readyState == 4 && this.status == 200) {
          // update some response area here
          message.textContent = this.responseText;
        }
      };

      xhr.send(new FormData(upload_form));
    }
  });
}

Comment: Promises are very powerful and you should invest time to learn how they work and when you can make use of them. These two PHP files, not only the `exists.php` but also the `upload.php` are totally unsecure and should never be used as they are; instead, you have to create an authentication system (*or use some ready made auth systrems*) that will handle login sessions and only allow users that they have logged in and have access to upload and check only for files and folders that should have access to.
Comment: `GET` requests are totally fine when there is a backend authentication system that will check for users and access. There is nothing special that makes `POST` requests more secure than `GET` requests; there always must be a middleware auth system to check and allow/deny these requests accordingly.
Comment: Very nice answer. I've only just started to learn about `Promise` objects in javascript so it's nice to see them used in a context directly relevant to my own problem. Can you comment on whether there's any security implications with having an `exists.php` script that uses `$_GET` on your server? - e.g., could somebody snoop around for files using it?


Route values disappeare in View .Net MVC3

Question: I have simple controller:
public class TestController : Controller
    {
        public ActionResult Test(string r)
        {
            return View();
        }

    }

I have simple View Test.cshtml:

@ViewContext.RouteData.Values["r"]

        @using (Html.BeginForm("Test", "Test"))
        {
            <input type="text" name="r" />
            <button>Submit</button>
        }

I have route rule in Global.asax:
routes.MapRoute(
            null,
            "Test/{r}",
            new { action = "Test", controller = "Test",
                r = UrlParameter.Optional }
        );

I want to make such thing: user types route value in input, press submit and controller redirects him to page Test/value. But controller show just page with name Test everytime. ViewContext.RouteData.Values["r"] is empty too. I check in debug, Test action recieves user value of r correctly.
How can I realize my idea?
Thanks.
Answer: I'm super late to the party, but just wanted to post a solution for reference. Let's assume that this form has more than just a strong as it's input. Assuming there are other inputs, we can wrap up the inputs of the form into a class in our model, called TestModel whose properties maps to the id's of the form's inputs.
In our post, we redirect to the get, passing in the route values we need in the URL. Any other data can then be shuttled to the get using a TempData.
public class TestController : Controller
    {
        [HttpGet]
        public ActionResult Test(string r)
        {
            TestModel model = TempData["TestModel"] as TestModel;
            return View(model);
        }

        [HttpPost]
        public ActionResult Test(string r,TestModel model) //some strongly typed class to contain form inputs
        {
            TempData["TestModel"] = model; //pass any other form inputs to the other action
            return RedirectToAction("Test", new{r = r}); //preserve route value
        }

    }

Answer: You cannot do this without javascript. There are two types of methods that exist when submitting a <form>: GET and POST. When you use POST (which is the default), the form is POSTed to the url but all data entered in input fields is part of the POST body, so it is not part of the url. When you use GET, the input fields data is part of the query string but of the form /Test?r=somevalue.
I wouldn't recommend you trying to send user input as part of the path but if you decide to go that route you could subscribe to the submit event of the form and rewrite the url:
$('form').submit(function() {
    var data = $('input[name="r"]', this).val();
    window.location.href = this.action + '/' + encodeURIComponent(data);
    return false;
});

Comment: Oh! Sure! Thanks. I create two action methods (HttpGet and HttpPost) and use RedirectToAction from HttpPost method to HttpGet method. And it works fine. Thanks!
Answer: As far as you are saying to post the form to Html.BeginForm("Test", "Test") you will be always posted back to the same page.
A solution could be to use an explicit Redirect to the action using 'RedirectToAction' (in view) or you can use javascript to change the form's action:
<input type="text" name="r" onchange="this.parent.action = '\/Test\/'+this.value"/>


Show that $f$ is an isometry for infinite-dimensional

Question: $V$ is a real vector-space and $f: V \rightarrow V $ an automorphism. Show that $f$ is an isometry iff $f^* = f^{-1}$.
This has been explained in our textbook for finite-dimensional situations however the exam question demands proof without using the textbook explanations which has left me stumped on how to approach this. Does anyone have a tip where to start with this proof? How does the dimension affect this so dramatically?
EDIT:
For the ones asking what the course note proof is:
$\langle v, f^{*}(v) \rangle = \langle f(v), v \rangle = \langle f(v), f(f^{-1}(v))\rangle = \langle v, f^{-1}(v)\rangle$
Which implies $f^{*}=f^{-1}$
Comment: For the concept of isometry you need a distance function, a real vector space does not allow such a concept without additional structure. Are you assuming a Euclidean vector space (i.e. one with a scalar product)?
Comment: Unless we know that $V$ is finite dimensional, it is possible to have an isometry $f$ for which no inverse $f^{-1}$ exists.  See for instance [this example](https://math.stackexchange.com/a/838901/81360)
Comment: @Thomas a Euclidean vector space is a finite one and the question explicitly is forbidding me to use the assumption of a finite-dimension so I'm sadly going to say no as much as I agree with your statement. That's why I am surprised at this exam question.
Comment: If you are looking for a different approach then the one followed in your course notes, can you maybe say how it is proven in the course notes?
Comment: Edited the question to provide the course notes explanations
Answer: Assuming that $V$ is an inner product space with a norm defined by $\lVert x \rVert = \sqrt{\langle x, x\rangle}$, we can proceed as follows.
Firstly, assume $f^*=f^{-1}$. Then for any $x \in V$,
$$\lVert fx \rVert^2 = \langle fx, fx\rangle = \langle f^*fx, x\rangle = \langle x, x\rangle = \lVert x \rVert^2. $$
Secondly suppose that $f$ is an isometry. Then it preserves the inner product
(since $\langle x, y \rangle = \frac{1}{2}\left(\lVert x + y\rVert^2 - \lVert x\lVert^2 - \lVert y\lVert ^2\right)$.
Therefore,
$$\langle x,y \rangle = \langle fx, fy \rangle=\langle f^*fx,y\rangle,$$
for all $x,y \in V$, from which it follows that $f^*f = \operatorname{id}$, thus $f^*=f^{-1}$. Note that the last step assumes that $f$ we already know $f$ is invertible.
If we do not assume that $f$ was invertible, and if the vector space is infinitedimensional, we cannot conclude from $f^*f=\operatorname{id}$ that $f$ is invertible.
I don't know in what sense you could consider this proof different from your textbook proof. It's certainly longer and very similar.


PHP for each - return results "live" not when the array is completed

Question: I can't remember how I did this before, but there had been a way that I used a while loop and it returned the result after each loop, not after the entire array was looped through.
I am now using for each though, but I assume the same practice should be able to be applied to for each.
I have a multiple photo uploader that I want the photos to return as soon as each one is finished, not when all of them are done.
Comment: Not entirely sure what you're asking for; but if you want to display the content to the user as it's done, check PHP manual for flush() and ob_flush() : http://php.net/manual/en/function.ob-flush.php
Comment: can you put your code here; it will help to provide the well answer what you want
Comment: Flush is exactly what it was, thanks.
Answer: Are you searching for ob_flush ?
Will output the contents of the output buffer and can be controled in your for each array.


Is it possible to hide a field on a form without writing code?

Question: there are good instructions on hiding a field using a hook.
Is there a simpler way of doing this? I would like to hide a term reference field on a node edit form but use the default value for it.
Answer: If you simply want to hide the field and have the default value saved, you should be able to simply hide the field with CSS. Find the ID of the wrapper surrounding the field and set it to display: none;.  Here is a working example from my D6 site:
#edit-field-vendor-sort-order-0-value-wrapper {
  display: none;
}

Comment: This can be useful, but don't use CSS if the field value has security implications.  A malicious user could still change the value.
Comment: Very true, good point


Populate TextView from selected ListViewItem text

Question: I want to call setText on the TextView in the new activity every time I click on any text at the list view. For example, if I click on an item in the listView containing "Android" I want the word "Android" to appear in the new activity.
Find code below :
public class ThirdMainActivity extends ActionBarActivity {

    ListView lvCourses;
    String[] courses = { "Android", "HTML 5", "J2SE", "JavaScript", "MySQL", "PHP", "CSS", "JQuery", "C#"};

    String[] descr = { "Android Course", "HTML 5 Course", "J2SE Course", "JavaScript Course", "MySQL Course", "PHP Course", "CSS Course", "JQuery Course", "C# Course" };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_third_main);

    lvCourses = (ListView) findViewById(R.id.lvCourses);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, Android.R.layout.simple_list_item_1, courses);

    final TextView rr = (TextView)findViewById(R.id.setT);
    lvCourses.setAdapter(adapter);
    lvCourses.setOnItemClickListener(
        new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> lv, View view, int position, long id) {

                if(position == 0){
                    rr.setText(""+descr[0]);
                    Intent e = new Intent(getApplicationContext(),TeMainActivity.class);
                    startActivity(e);
                }

                if(position == 1){
                    rr.setText(""+descr[1]);
                    Intent e = new Intent(getApplicationContext(),TeMainActivity.class);
                    startActivity(e);
                }
            }
        });
    }
}

Answer: you don't need to check all position states. just do this on onItemClick()
rr.setText(descr[position]);
Intent e = new Intent(getApplicationContext(),TeMainActivity.class);
startActivity(e);

if you want to pass this data to new activity
rr.setText(descr[position]);
Intent e = new Intent(getApplicationContext(),TeMainActivity.class);
e.putExtra("desc", descr[position])
startActivity(e);

Comment: when I emulated it give me error "Unfortunately da4  stopped"


How to add the same atributes for all SVG elements

Question: I have two SVG elements:
<circle r="260.2" fill="#1ABCb6" class="" id="svg_el_obj"></circle>
<circle r="260.2" fill="#1ABCb6" class="" id="svg_el_obj"></circle>

and i want add for them the same cx and cy atributes, so i use each with jquery but i have expected response for only first element, what is wrong?
svg_el_obj.each(function(){
    $(this).attr({
        cx: svg_plain_h/2,
        cy: svg_plain_h/2
    })
});

thx for help.
Comment: how do you create svg_el_obj ? check his length, must be one if you only get the first, your error is not in the .attr code, also you not need the each => svg_el_obj.attr({});
Comment: Worth pointing out here.  You have the same id for two elements in the same document. The ids must be unique: http://www.w3.org/TR/html401/struct/global.html#h-7.5.2
Comment: Here is a fiddle with some additions to fill in the gaps between your description and getting something working.  There is an execute button to click to run the "each" function. http://jsfiddle.net/hWwub/12/
Comment: im creating them by JS, and i have two elements bc i see them in my DOM :)
Comment: i have two different ids now and it's not helps
Answer: what selector do you use to find your svg elements. Seems like you can find only first one.
You see it's incorrect to use same id for different elements anyway.


Let $G$ be a finite, abelian group, prime $p\mid |G|$ and $G$ contain $p-1$ elements order of $p$. Prove $G$ is cyclic.

Question:
If $G$ is a finite abelian group, then TFAE:

$G$ is cyclic
if $p$ divides order of $G$ then $G$ contains exactly $p-1$ elements of order $p$?

The forward direction is easy but for the other part I could not solve it without using structure theorem for finite abelian group.
Any hint will be appreciated.
Comment: It stands for, "The Following Are Equivalent", @Mike.
Comment: @Shaun thank you for editing my ans with good latex code..thanks..
Comment: Consider the Sylow subgroups of $G$.  First show that each of them must be cyclic.  Then show that $G$ is a direct product of its Sylow subgroups and that the direct product of cyclic subgroups of relatively prime order is itself cyclic.
Comment: @aschepler extremely sorry now i corrected it
Comment: What is 'TFAE'?
Comment: You're welcome, @Shrihari.
Answer: We will prove the challenging direction, that 2. as in the OP implies 1.
Lemma 1 Let $G$ be any abelian group. For each integer $p$ that divides $|G|$, let $\nu(p)$ be the largest integer that satisfies the following: There is a cyclic subgroup $H(p)=\langle \alpha \rangle$ of $G$ such that $|H(p)|$ is divisible by $p^{\nu(p)}$. Then let $p_1,\ldots, p_r$ be the distinct primes that divide $|G|$. Then there is a cyclic subgroup $H'$ such that $p_1^{\nu(p_1)}\cdots p_r^{\nu(p_r)}$ divides $|H'|$.
Indeed, to see this, for each such $p_i$, let $H'(p_i)$ be the cyclic subgroup of $H(p)$ where $|H'(p_i)|$ is precisely $p_i^{\nu(p_i)}$. Then let $\alpha_i$ be the generator of $H'(p_i)$. Then $\alpha_1\cdots \alpha_r$ has order $\prod_{i=1}^r p_i^{\nu(p_i)}$. Indeed, otherwise an equation of the form $\alpha_1^{c_1} =\prod_{i=2}^r p_i^{c_i}$ would hold for some $c_1$ such that $p_1^{\nu(p_1)}$ does not divide $c_1$; raising both sides of this to the $\prod_{i=2}^r p_i^{\nu(p_i)}$-th power would give the equation $p_1^{C_1}=e$ for some integer $C_1$ such that $p_1^{\nu(p_1)}$ does not divide $C_1$, which is impossible. $\surd$
So now, let us assume that $G$ satisfies 2. as in the OP. First, using Lemma 1, let $p_1,\ldots, p_r$ be distinct primes that divide $|G|$, and let $H'$ be a cyclic subgroup of $G$ such that $p_1^{\nu(p_1)}\cdots p_r^{\nu(p_r)}$ divides $|H'|$. Let $\alpha'$ be an element in $G$ such that $\langle \alpha' \rangle = |H'|$. For ease of notation, let $M'$ be the integer satisfying $M'=|H'|$. If $H'=G$ then we are done. So let us assume that $H'$ is a proper subgroup of $G$, and thus there is a $\beta \in G \setminus H'$. Now, as $H'$ is cyclic and it is easy to see that 1. of the OP implies 2. of the OP, there are exactly $p_i-1$ elements of $H'$ of order $p_i$, for each $i=1,\ldots, r$.  So we finish showing that 2. implies 1. in the OP by constructing from $\beta$ an element $\gamma \in G \setminus H'$ such that $\gamma^{p_1} = e$, for some prime $p_1$ that divides $|G|$.
Let $N$ be the smallest positive integer such that $\beta^N=e$; so $\langle \beta \rangle$ is a subgroup with precisely $N$ elements. Then let $k$ be the smallest positive integer such that $\beta^k \in H'$, and assume WLOG that $p_1$ divides $k$, and thus $N$ as well. Then $\beta^j$ is in $H'$ iff $k|j$, and in particular only if $p_1|j$. Thus letting $\ell$ be the largest power of $p_1$ that divides $N$, it follows that $\beta^{N/p_1^{\ell}}$ is not in $H'$, because $p_1$ does not divide $N/p_1^{\ell}$ [lest there were a larger power of $p_1$ that divides $N$]. So $\ell_1$ be the largest integer that both

$p_1^{\ell_1}$ divides $N$, and

$\beta^{N/p_1^{\ell_1}}$ is not in $H'$;

there is indeed such an integer $\ell_1$. Then it follows that $\ell_1$ must be at least $2$ lest we are done. [Indeed, $\beta^N= \beta^{N/p_1^0}=e \in H'$, and if $\beta^{N/p_1}$ is not in $H'$, then set $\gamma= \beta^{N/p_1}$. Then indeed $\gamma$ is not in $H'$ and satisfies $\gamma^{p_1}=e$.] So $\beta^{N/p_1^{\ell_1-1}}$ must be in $H'$, write $\beta^{N/p_1^{\ell_1-1}}=\alpha^c$; then as $\left(\beta^{N/p_1^{\ell_1-1}}\right)^{p_1^{\ell_1-1}} = \left(\alpha^c\right)^{p_1^{\ell_1-1}}=e$, it follows that $M'$ must divide $cp_1^{\ell_1-1}$; as $p_1^{\ell_1}$ divides $N$, by Lemma 1 it follows that $p_1^{\ell_1}$ must divide $M'=|H'|$ as well, and thus, as $M'$ divides $cp_1^{\ell_1-1}$, that $p_1$ divides $c$ as well.
Thus, consider the element $\gamma=\alpha^{(M'-c)/p_1}\beta^{N/p^{\ell_1}}$. Note that $\gamma$ is not in $H'$ because $\beta^{N/p^{\ell_1}}$ is not in $H'$, and yet,
$$\gamma^{p_1} = \alpha^{M'-c}\beta^{N/p_1^{\ell_1-1}}$$ $$ = \alpha^{M'-c}\alpha^c = \alpha^{M'}=e.$$ So here we constructed our desired element $\gamma$, as thus, there cannot be such an element $\beta$, and so it follows that $G$ must indeed be cyclic, and satisfy 1. of the OP after all.


Precise rule(s) for calling a note sharp or flat in a given scale

Question: Is there a precise rule (or set of rules) by which I can determine if a note should called sharp or flat?
Consider the two scales below. In the first C#/Db is C#, and in the second it's Db. By which rules would I be able to make this decision, given only a pitch class set like 0, 1, 2, 4, 5, 6, 7, 9, 10?
Scale 1783: "Youlan"

Scale 1715: "Harmonic Minor Inverse"
Answer: For the second, each note has its own letter name, there's no duplication, be it ♯, ♭ or ♮. that makes it easier to write - each note has its own line/space on the stave - and also easier to read, there being no need for accidentals.
That's pretty straightforward for heptatonic scales. However, when it comes to scales with more than seven notes, it can't really matter. There are two Cs and two Fs in that scale. Or, maybe, two Ds and two Gs! As a 'rule of thumb', the chromatic naming works well. Use C and C♯ when they follow each other, or D and D♭ when they follow. That saves using natural signs to cancel a previous note.
But as far as where they occur in the dots, when writing music which uses these scale notes, keeping to the same sign as much as possible seems a good idea.
Answer: For the first one, it's a forced approximation, translating a more-than-seven-notes-per-octave language to a seven-notes-per-octave language. Something gets lost in translation, and in this case something that wasn't there gets added, namely the sharp/flat aspect. I don't know what this Youlan scale is, but most likely there were no sharps and flats where it came from. And there probably was no A, B, C, D, E, F, G either.
The sharp/flat note naming system has evolved for use in a culture where scales have seven notes per octave. That's why there are seven note names: A, B, C, D, E, F, G. The Western staff notation system corresponds to this. There are seven staff positions per octave. It's a language - it naturally lends itself to expressing certain things well, but some other things, not so well.
When you try to describe scales that have more than seven notes per octave, the seven-notes-per-octave note naming and staff notation systems are not ideal. But since they are so commonly used, that's what often gets used.
There are other kinds of notation systems and "languages", for example guitar tablature. There you could write 0,1,2,4,5,6,7,9,10 without having to ask the sharp or flat question. Do you speak tab?
For the second scale, it has seven notes per octave, and you can derive it from the C major scale by making two scale degrees flat. The logic is, each letter-name should occur exactly once. You cannot have C and C# in the same scale, that would be against the whole letter naming idea. Each of the seven scale degrees can be basically in a sharp, natural or flat position. By saying "C#" you declare that "my C slot is tuned sharp". The tuning switch cannot be both natural and sharp at the same time, in that sort of way of thinking.
BUT like already said, that logic only applies to systems that can be seen as somewhat compatible with the Western seven-notes-per-scale way of thinking.
Answer: The web site cited for the scales says...

...more than you ever wanted to know about...

...apparently that doesn't include how to fit more than seven tones in the western seven tone gamut.
I wouldn't use the work "precise." A better word might be "conventional." If the tuning is equal temperament then enharmonic equivalent tones like C#/Db are precisely the same pitch. But if an instrument isn't tuned by equal temperament, then enharmonic equivalents aren't necessarily the exact same pitch. A violinist may play half steps smaller than those of equal temperament. So, C C# D and D Dd C might not be exactly the same intervals on violin.
There is a convention to write chromatic half steps using sharps for ascending steps and flats for descending steps (or the corresponding naturals/doubles.) The cited web page shows the ascending usage...

...but it doesn't show the scale descending. Following the convention of flats for a descent it would be...

If the scale has only seven tones, you should spell it with only one letter for each tone.
Answer: I would say that there can't be an unambiguous set of rules. Its more like natural language - part always depends on culture, context and what you're trying to express.  As a practical suggestion, I would say pick something and stick to it, and when you have to break your own rules try and do so in a way that's a 'gentle' deviation from the style you've established. An aesthetic choice of course but probably simpler to do than to talk about! That way the reader will come to understand your way of communicating, which is the end goal of course. (For context , I work microtonaly so my bias is I'm not a big fan of 'rules' by instinct :) )


ML Model: Stock market price prediction model

Question: I got asked this in an interview. "If you had a lot of data about a lot of stocks, how would you go about predicting the next price of a stock?" "What are advantages and disadvantages of using certain models/strategies?"
The question seemed intentionally so open-ended, but I didn't know how to approach it. With some more thinking, I feel like one approach is to break stocks up by sector, since different sectors may have different relationships. Then, I could use PCA in order to reduce the dimensionality of the data, and then use regression in order to predict prices. What do people think are other, better solutions?
Comment: You're correct that these kinds of questions are deliberately open-ended; however, the open-endedness of them does not make them great candidates for stats.SE because there is no correct answer. More information about which questions are on-topic here can be found in the [help].
Answer: I would more likely, in an interview context, give an answer of linking a stock's price to the expected performance of a sector.
For example, in the case of a pandemic, telecommunications applications would likely benefit. How has a stock in question, within this sector performed relative to the sector average?
So, based on one model of how a particular sector would likely benefit under a presumed scenario, followed by a more traditional relative performance statistical analysis at the sector level, I might be comfortable (or at least, the interviewer might feel so) so as to provide a projection of a stock price change within the time frame consistent with the first model.
The advantages of this approach are that it logically integrates current macro conditions (importantly for projecting trends) and separately makes quality decisions on stock differentiation within the sector.
Good luck on your next interview.


How to slow down application?

Question: I have some kind of automation app that is calling functions from another app (lets call it host). However, it is doing it so fast, that host gets crash. Is there any way to slow down whole app or function? Weird point is that on debug it works perfectly, when I go step-by-step, but host crash just when I press continue.
Comment: No matter how fast or slow you make your program, what you are experiencing is called a [race-condition](http://stackoverflow.com/questions/34510/what-is-a-race-condition). Often these can appear to be solved by adding pauses to slow down one contender in the race. That approach can fail when your computer is under load. The best approach here is to figure out how to get notification and only act when you are sure that the thing you're waiting for is actually finished.
Comment: @RossDrew It's a classic race. Two different apps are racing. Race conditions aren't just confined to threading. ["A race condition or race hazard is the behavior of an electronic, software or other system where the output is dependent on the sequence or timing of other uncontrollable events. It becomes a bug when events do not happen in the order the programmer intended. "](https://en.wikipedia.org/wiki/Race_condition) This question fits the definition perfectly (just, not with threads).
Comment: Provide code examples.
Comment: This isn't really a race condition if there is only one thread making calls
Comment: By that logic, denial of service attacks are race conditions though
Answer: You can tell your code to wait between statements with Thread.sleep() for example (make sure you use it correctly though)
<code>Thread.sleep(1000); //Wait for a time specified in milliseconds (1000 milliseconds=1 second)
</code>
Comment: Seems to be working, as 4 actions out of 8 were performed with sleep(200) before each step. Thanks a lot.

How to slow down application?


How to output reactive data

Question: I am using Shiny and want to output some of the data.
This is the code I am using to load data and select variables
  data.feature <-  reactive({
    # filename <- paste0("dataall_'", input$date, "'new.RData")
    filename <- paste0("dataall_new.RData")
    load(filename)
    feature.test[input$variable,]
  })

Then use the following code to download the data
 output$downloadDatar <- downloadHandler(
    filename = paste('data_summary.RData'),
    content = function(file) {
      save( data.feature, file= file)})
    }})

But when I open the saved file, and enter data.feature I got this:
reactive({
    filename <- paste0("dataall_new.RData")
    load(filename)
    feature.test[input$variable]
})

Is there any way to view the data inside?
BTW, I tried data.feature() in save function and got  object 'data.feature()' not found error
Problem solved: just use isolate function
Comment: I suggest posting an answer with your solution, this will help others having the same problem.
Answer: Problem solved: just use isolate function

How to output reactive data


How to make the UserProfile Info availlable on a block

Question: I understand how to preprocess a specific block to make some variable available for that it, but what I don't understand is where I grab these variable that I want to be available in my  block.
I have the following code:
function THEME_preprocess_block(&$variables) {
    $variables['user_profile']= $user_profile;
}

$user_profile is NULL.
So in other terms what i would like is to grab all the data entered by a user during the registration and make it available within block under for instance a user_profile variable.
Is it possible at all?

Well i tried but it doesn't seem to do anything in drupal 7. Also isn't the user variable holding data only for the current loged in user ? I would like to retrieve the data of any user in order to populate the profile page with it.
Answer: You need to use the global user object to get info about the currently logged in user, then pass that user object to profile_load_profile:
function THEME_preprocess_block(&$variables) {
    global $user;
    $user_profile = profile_load_profile($user);
    $variables['user_profile']= $user_profile;
}

(code is untested but should work)
Answer: Here is the correct snipet:
function THEME_preprocess_block(&$variables) {
    $variables['user_profile'] = menu_get_object('user');
}


What does `vec type 'AnonymousBundle(IO io in )' must be a Chisel type, not hardware` mean?

Question: The following line of code val mod_subexp_array = Vec(9, Module(new SubTaylor(fepar)).io) produces the following error:
chisel3.package$ExpectedChiselTypeException: vec type 'AnonymousBundle(IO io in SubTaylor)' must be a Chisel type, not hardware

The module SubTaylor is a module I've written, and I interface with it via an IO port. My objective is to create 9 instances of these SubTaylor modules and chain them together using their IOs. To resolve the problem above, I thought perhaps the SubTaylor module needed to be wrapped within a Wire:
val mod_subexp_array = Vec(9, Wire(Module(new SubTaylor(fepar))).io)
However, the errors message changed to wire type 'AnonymousBundle(IO io in SubTaylor)' must be a Chisel type, not hardware. As I currently understand, there are two different Wire datatypes. One wire datatype is a Chisel type, and the other is a hardware type. Is my understanding correct? And how am I supposed to define Vector as a Chisel type?
Answer: What you want to write is the following:
val mod_subexp_array = VecInit(Seq.fill(9, Module(new SubTaylor(fepar))).io))

What that error message means is that you provided a hardware value instead of a type when a type was expected. I'll explain by analogy with C:
// This is how you make an Array of 10 ints
int my_array[10];
// This is analogous to Vec(9, Wire(Module(new SubTaylor(fepar))).io)
3 my_array[10]; /*
^ An int value instead of a type
*/

I know this distinction is a little more obvious in C than in Chisel (because Chisel is a generator metaprogramming framework), but it's effectively the same thing.
Vec(<n>, <type>) is how you create a Vec type. VecInit(<values>) is how you create a Vec value.
You may wonder why we are using Seq.fill? Seq is a Scala type and we are using a factory method to stamp out 9 instances of your Module. VecInit accepts a Seq of whatever hardware type you're creating so it will take those 9 instances and turn it into a hardware value.
Comment: This answer right here needs to be part of the Chisel docs/tutorial. I spent days going in circles until I found this and everything clicked when I read it.


Rank of product of matrices (analytic proof)

Question: $A$ is (nxn) full-rank matrix. $B$ is (nxm) matrix with rank k. I want to prove analytically that $$rk(AB) = k$$
I am not sure if my answer is correct or not, but here it is:
As vector space spanned by $B$'s columns is $k$-dimensional, we can express any $k$-dimensional vector (e.g. $s$) as a linear combination of columns of B:
$$s=Bx$$ with  $s$ -> (nx1); $B$ -> (nxm); $x$ -> (mx1)
$x$ here is a (mx1) vector of coefficients of the linear combination. By notation $s$ is (nx1) vector, but it is only k-dimensional (only k entries are non-zero), as this vector is the linear combination of $B$'s columns, from which only $k$ columns are linearly independent from each other.
As matrix $A$ is (nxn) and full-rank, it hast n linearly independent columns. Then if we multiply $A$ by vector $s$, then $As$ will be a linear combination of only $k$ (out of n) linearly independent columns of $A$, as (n-k) entries of vector $s$ are zero.
Now again any k-dimensional vector can be represented by $As$.
$$As = A(Bx) = (AB)x$$
By that we prove that vector spaces generated by columns of $AB$ and by columns of $B$ arethe same. Subsequently, their dimensions are the same and that is the definition of rank, so
$$rk(B) = k = rk(AB)$$
Any help would be greatly appreciated.
Comment: Thanks a lot, it makes sense now.
Comment: I think your mistake is really "...but it is only $k$-dimensional (only $k$ entries are non-zero)...". This isn't the right condition: instead, arbitrary $s \in \mathbb{R}^n$ are representable in the way you specify if and only if $s \in \operatorname{im}B$. Now, you are right that $\operatorname{im}B$ is $k$-dimensional, but this does not mean that it consists of vectors with only $k$ entries nonzero.
Comment: In general $\operatorname{im}B$ simply has a basis consisting of $k$ vectors in $\mathbb{R}^n$, which could for example all happen to have all nonzero entries. (Recall for example that the standard basis vectors for all of $\mathbb{R}^n$ all have only one nonzero entry!)
Comment: (Here the image $\operatorname{im}B$ is the same thing as the range of $B$. Sorry, my comment had a very confusing typo so I have reposted it.)
Answer:
As vector space spanned by B's columns is k-dimensional, we can express any k-dimensional vector (e.g. s) as a linear combination of columns of B:
s=Bx

This statement doesn't make any sense. The columns of $B$ are in $R^n$. The columns span a $k$-dimensional subspace of $\mathbb{R^n}$. It doesn't make any sense to represent a "k-dimensional vector" in terms of vectors in $R^n$.


How do I play this mordent?

Question: What's the second note I play? It's in the key of C major
Comment: How to realize ornaments depends somewhat on the style, so it's better to give a fuller excerpt and the name of the work. This looks like the first Invention of J. S. Bach. See https://en.wikipedia.org/wiki/Ornament_(music)#In_Baroque_music for some ideas, but you have freedom.
Answer: Since you're in the key of C your second note will be G.
The auxiliary note is the next note in the key: a mordent goes to G, a reverse mordent to E natural.  If the composer wants a note outside the key you'll see an accidental above the mordent symbol.
Answer:
What's the second note I play? It's in the key of C major

You have to play G.
From Wikipedia,
The mordent is thought of as a rapid single alternation between an indicated note, the note above (the upper mordent) or below (the lower mordent) and the indicated note again.
The upper mordent is indicated by a short squiggle; the lower mordent is the same with a short vertical line through it:
https://en.wikipedia.org/wiki/Mordent

How do I play this mordent?


How do I match a string with the the path in React

Question: I have a React application where I wanted to render some menus depending upon the path.
I have following URL:
http://localhost:3000/Test/marks

Now from this URL I need to get the Test string only so that I can match that string with the array and then get the associated objects with that key.
I tried using the useLocation but it gives us the object and again I have to add a regex to get that name.
Is there any other way?
Comment: Have you try [that](https://stackoverflow.com/questions/47693540/get-an-active-route-with-react-router-in-reactjs)
Answer:
You can achive this using useParams hook

<Route path='/:id/marks' element={<Component/>}>

in Your component
import { useParams } from 'react-router-dom';

function Component() {
  // Get the id param from the URL.
  let { id } = useParams();
  // ...
}

Answer: You mention the useLocation hook so I'll assume you are using react-router or react-router-dom. You can use the useMatch hook to test a path pattern, and if there is a match a match object is returned. The match object has a params property that will have any path params available on it.

declare function useMatch<
  ParamKey extends ParamParseKey<Path>,
  Path extends string
>(
  pattern: PathPattern<Path> | Path
): PathMatch<ParamKey> | null;

interface PathMatch<ParamKey extends string = string> {
  params: Params<ParamKey>;
  pathname: string;
  pattern: PathPattern;
}

Example:
Test path: "/Test/marks"
import { useMatch } from 'react-router-dom';

...

const match = useMatch("/:key/marks");
console.log(match?.params?.key); // "Test"
...

If the component that needs to access that part of the URL path is already rendered as part of the normal routing, e.g. on a route rendered on path "/:key/marks", it could also just use the useParams hook directly to access the key path parameter.
Example:
<Route path="/:key/marks" element={.....} />

And in the route component on test path: "/Test/marks"
const { key } = useParams(); // "Test"


Show attribute widgets even if the Add to Cart form only represents one product

Question: I'm having problem with display option, of Product variation field as "Add to Cart form":

With that option it should show variation switcher, whenever there is one or more product variations.
But it does not:

Simply looks like "Show attribute widgets even if the Add to Cart form only represents one product." option doesn't change anything.
The above display shows teasers on the front page (I have trying manipulating default view in Manage Display as well).
I have trying clearing cache, running cron and changing my customized node--product--type.tpl.php and node--product--type--product--list.tpl.php  to oryginal ones and it does not help as well.
Comment: Do you have any attributes set up on your products? That is, fields which are marked in their field configuration as being attributes that will show up on the add to cart form?
Comment: I'm not quiet sure what you'r talking about :). I have couple of additional fields for product displays and it's variations. Hovewer I just want to show in teaser product variation switcher so it is set to display in teaser in product display and product variation display settings.
Answer: There are a few things you have to ensure you do right for this to work, as even in my little test environment to reproduce the error I screwed it up a couple different ways.

You must ensure the field you've added to your product type has checked the box to state that it should function as an attribute field on Add to Cart forms.
You must edit the field display settings using the form you've posted a screenshot of, but make sure you save the full form as the "Update" button on the expanded form doesn't actually save any changes to the database.
You must reproduce that for all relevant view modes.

With all of those things in mind, I was actually able to confirm the feature itself is working as advertised when properly configured:
Comment: It's a field setting, actually. Edit the field and look for the checkbox regarding Add to Cart form behavior.
Comment: I did 2, 3, however where do I set a variation switcher field to be an attribute field on Add to Car form?

That switcher simply does not show when there is only one product variation, in default view and any other like teaser.


Conditional probability - how to compute the intersection in the formula?

Question: Problem: a person wants to use ATM. With equal probability either $0$ or $1$ person is ahead. If there is $1$ person, the waiting time is distributed exponentially with the $\lambda$. What's the CDF of the waiting time?
Solution (by the book): I do understand the general approach:
$T$ - the waiting time, $F_{T}(t)=P\{T\leq t\} = ?$
$C$ - the number of people ahead ($0$ or $1$)
$P\{T\leq t\}=P(C=0)*P\{T\leq t|C=0\}+P(C=1)*P\{T\leq t|C=1\}$
The book says that $P\{T\leq t|C=0\}=1$. Intuitively I do understand it: If no one's using the ATM, the probability that the waiting time is less or equal to a non-negative number is $0$. However, for the sake of understanding the formula I'd like to apply the definition of conditional probability here and compute $P\{T\leq t|C=0\}$ using the general fact that $P(A|B)=P(A\cap B)/P(B)$
How to compute the $P(\{T\leq t \cap C=0\})?$ Same question for the second part: How to compute the $P(\{T\leq t \cap C=1\})?$
Comment: Don't you have to have $P(T \leq t, C = 0)=1/2$, since $P(C=0)=1/2$?
Comment: @aduh
I do, but here I'd like to know the reasoning that comes not from $1/2 : 1/2 = 1$, but from the concepts and their definition. Suppose I wasn't told that $P\{T\leq t|C=0\}=1$. How could I reason here?
Answer: Using the definition of conditional probability
$$P(T\le t \mid C=0)=\frac{P(T\le t \cap C=0)}{P(C=0)}=\frac{P(T\le t\cap C=0)}{P(C=0)}.$$
Furthermore
$$P(T\le t\cap C=0)=P(T\le t\cap C=0\cap T=0)=$$
$$=\begin{cases}P(C=0)&\text{ if } &t\ge 0\\0&\text{ otherwise}\end{cases}$$
because $\{C=0\}\subset\{T=0\}$ and, as a result $\{C=0\}\cap\{T=0\}=\{C=0\}$ and $\{T\le t\}\cap \{T=0\}\cap\{C=0\}=\{C=0\}$ if $t\ge0$ and it is $\emptyset$ otherwise.
But I would rather simply say that
$$P(T\le t\mid C=0)=\begin{cases}1&\text{ if }& t\ge 0\\0&\text{ if }& t<0\end{cases}$$
since I do know that if $C=0$ is given then the waiting time is $0$.
Also,
$$P(T\le t\mid C=1)=\begin{cases}1-e^{\lambda t}&\text{ if }& t\ge 0\\0&\text{ if }& t<0.\end{cases}$$
So,
$$F_T(t)=\begin{cases}P(C=0)+(1-e^{\lambda t})P(C=1)&\text{ if }& t\ge 0\\0&\text{ if }& t<0.\end{cases}$$
For $\lambda=1$, $P(C=0)=\frac12=P(C=1)$ we have
Comment: Why assume independence?
Comment: @adu: You are right we don't have to assume independence. I corrected my answer.
Comment: @zoli Thank you for the detailed explanation!

But can't I prove the same way that $P(T≤t∣C=1)=1$ using the fact that $\{C=1\}\subset\{T=t\}$ and $\{C=1\}\cap\{T=t\}=\{C=1\}$, which will also give me $1$ when I divide by $P\{C=1\}$?
Answer: I suppose you could reason as follows.
Fix $t \geq 0$. Clearly, $\{T \leq t \cap C=0 \} \subseteq \{C=0 \}$. Conversely, if $C=0$, then $T=0$, which implies $T \leq t$. Therefore, the events $\{T \leq t \cap C=0 \}$ and $\{C=0 \}$ are identical and must have the same probability.
Though I think the reasoning with conditional probabilities is more natural.


sample size for paired t-test with unknown standard deviation

Question: This is a straightforward question. In order to calculate a sample size needed for a paired t-test, it is required to know ahead of time the standard error of the paired differences. But what if this is unknown? Is there a crude estimation of the standard error that can be used?
Answer: The $t$ test prominently uses the standard errors. If you can't specify the standard error, you can't calculate the power for the $t$ test, and therefore, you can't calculate the sample size you need for a specified power.
Your best bet likely is to plug a range of "reasonable" standard errors (or, equivalently, effect sizes) into the formula. What is "reasonable" will depend on your domain of application, and your prior knowledge about the effect you are studying.


Change input text color on dark or light mode

Question: I create a dark/light theme switcher and the problem that I discover is when I enter any information in input field while the website in dark mode, the text inside input field appears black, how I can change it to keep black text colour on light mode and white text colour on dark mode.
Here is my CSS for light/dark mode. How I can add a different text color for dark mode?
:root {
    --primary-color: rgb(82, 80, 144);
    --secondary-color: #536390;
    --font-color: #424242;
    --bg-color: #fff;
    --heading-color: #292922;
    --color: black;
  }
  [data-theme="dark"] {
    --primary-color: rgb(107, 106, 134);
    --secondary-color: #818cab;
    --font-color: #e1e1ff;
    --bg-color: #4d5055;
    --heading-color: #63656d;
    --color: white;
  }
  body {
    background-color: var(--bg-color);
    color: var(--font-color);
  }
  h1 {
    color: var(--secondary-color);
  }

  a{
    color: var(--primary-color);
  }
input {
color: var(--color);
}

HTML part

<input type="text" id="searchquery" placeholder="Type here">

I was trying to it with this code, but it changes for both dark and light mode.
input, select, textarea{
    color: #ff0000;
}

EDITED: I add the content from answer below. It works now with only one problem, when I change to the light mode the input text color remains white, but suppose to be black color.
Comment: You could use this: `@media (prefers-color-scheme: dark) { }` to change the colour just for dark mode. See more here: https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme
Comment: As I understand right the code suppose to look like that `@media (prefers-color-scheme: dark) {
  .input-field{
    color: white;
  }
}`
But currently it doesn't work for me, where is my mistake?
Answer: In your case, you need to add the attribute data-theme="dark" in the labels or any parent for it take effect. I hope this can help you.

:root {
    --primary-color: rgb(82, 80, 144);
    --secondary-color: #536390;
    --font-color: #424242;
    --bg-color: #fff;
    --heading-color: #292922;
    --color: black;
  }
  [data-theme="dark"] {
    --primary-color: rgb(107, 106, 134);
    --secondary-color: #818cab;
    --font-color: #e1e1ff;
    --bg-color: #4d5055;
    --heading-color: #63656d;
    --color: red;
  }
  body {
    background-color: var(--bg-color);
    color: var(--font-color);
  }
  h1 {
    color: var(--secondary-color);
  }

  a{
    color: var(--primary-color);
  }

input {
    color: var(--color);
  }

Input with data-theme attribute "dark"

    <input type="text" id="searchquery" placeholder="Type here">

Input wihout data-theme attribute "dark"

    <input type="text" id="searchquery" placeholder="Type here">

Comment: Thank you for explanation, yes it works for me, the only thing that the input text color stays white even in light mode.


Docker amd64 warning on Apple M1 computer

Question: What is this warning:

I have enabled docker compose V2 and set export DOCKER_DEFAULT_PLATFORM=linux/amd64 as an env variable as I believe that this enables an emulation that allows the docker images to run on an Apple M1 chip.
I am new to docker and am wondering if this means that the emulation is working or if I have not configured something correctly?
Answer: The warning means that amd64 images have poor performance, and sometimes crashing behavior as well. This is a known issue with Docker + qemu on the Apple Silicon chips. For this reason, Docker recommends avoiding use of amd64 images when possible.
https://docs.docker.com/desktop/mac/apple-silicon/

Not all images are available for ARM64 architecture. You can add --platform linux/amd64 to run an Intel image under emulation. In particular, the mysql image is not available for ARM64. You can work around this issue by using a mariadb image.
However, attempts to run Intel-based containers on Apple silicon machines under emulation can crash as qemu sometimes fails to run the container. In addition, filesystem change notification APIs (inotify) do not work under qemu emulation. Even when the containers do run correctly under emulation, they will be slower and use more memory than the native equivalent.
In summary, running Intel-based containers on Arm-based machines should be regarded as "best effort" only. We recommend running arm64 containers on Apple silicon machines whenever possible, and encouraging container authors to produce arm64, or multi-arch, versions of their containers. We expect this issue to become less common over time, as more and more images are rebuilt supporting multiple architectures.
Comment: @Sammy65 Using multiplatform images to get the native platform is the default, so to do that, you just unset the ENV var that you have set. The thing is, not every image published on Docker Hub has an arm64 version. There's not much you can do about that; you can either try your luck with the emulator, or you can attempt to build your own arm64 version of the software if there isn't one available.
Comment: For folks compiling their own images, Docker has a useful guide for multi-platform support: https://www.docker.com/blog/faster-multi-platform-builds-dockerfile-cross-compilation-guide/
Comment: So please, I can I run the container which has multiplatform support? There isn't a simple command to do this I've found which works! Please, if you could add such a command to your answer, would be additionally helpful. Thanks!


Remover atributo disabled quando uma condição for satisfeita

Question: Boa noite.
Estou tentando fazer uma tela de registro e login para uma aplicação que vai salvar os dados em localStorage. Para evitar que o usuário se cadastre com dados incompletos desabilitei o botão de submit usando disabled.
Minha intenção é quando todos os campos forem preenchidos a propriedade disabled seja removida e o botão possa ser clicado mas não consigo remover o disabled, tentei de várias maneiras e nada. Creio que a maneira mais fácil seria essa:

var operacao = "A"; //"A"=Adição; "E"=Edição
var indice_selecionado = -1; //Índice do item selecionado na lista
var tbUsuarios;

//aqui o botão submit já está desabilitado
$(document).ready(function() {
    $('#buttonSubmitRegister').prop('disabled', true);
});

$(function () {
    tbUsuarios = localStorage.getItem("tbUsuarios");// Recupera os dados armazenados
    tbUsuarios = JSON.parse(tbUsuarios); // Converte string para objeto
    if (tbUsuarios === null) // Caso não haja conteúdo, iniciamos um vetor vazio
        tbUsuarios = [];
});

function Adicionar() {
    var usuario = JSON.stringify({
        Nome: $("#txtNome").val(),
        email: $("#txtEmail").val(),
        Senha: $("#txtSenha").val()
    });
    //aqui tentei remover o disabled quando os campos forem preenchidos
    if ($("#txtNome").val().length > 1 && $("#txtEmail").val().length > 1 && $("#txtSenha").val().length > 1){
        $(document).ready(function() {
            $('#buttonSubmitRegister').prop('disabled', false);
        });
        tbUsuarios.push(usuario);
        localStorage.setItem("tbUsuarios", JSON.stringify(tbUsuarios));
        alert("Usuário Cadastrado com Sucesso!");
        return true;
    }
}
<form id="formRegister" nome="formRegister" class="positionFormRegister">

                    <input id="txtNome" name="txtNome" type="text" class="form-control" placeholder="Crie seu nome de Usuário" autocomplete="off">

                    <input id="txtEmail" name="txtEmail" type="text" class="form-control" placeholder="Seu endereço de e-mail" autocomplete="off">

                    <input id="txtSenha" name="txtSenha" type="password" class="form-control" placeholder="Crie sua senha" autocomplete="off">

                    <input id="buttonSubmitRegister" type="submit" class="btn btn-primary btn-lg positionFormRegister" value="Cadastrar no e-Pro »" onclick="Adicionar()">

            </form>

Alguém tem alguma idéia de como resolver?
Obrigado pela ajuda.
Comment: Eu tentei também com  ' $("#txtNome").val().length != " " '. Mas não deu certo
Answer: Você quer que quando o campo tenha o numero de caracteres corretos, ele seja habilitado novamente certo? Note que o $(document).keyup(function(){}); vai fazer a verificação sempre que uma tecla for pressionada. Meu código exemplo:
$(document).keyup(function() {
    if($("#email-test").val().length > 0 && $("#password-test").val().length > 0) {
        $(document).ready(function() {
            $('#submit-test').prop('disabled', false);
        });
    }
});

Exemplo no jsfiddle:
https://jsfiddle.net/Knautiluz/L9vqatoh/2/
Tente assim com o evento fora da função adicionar, do contrário ele só vai ser computado quando a função for acionada:
var operacao = "A"; //"A"=Adição; "E"=Edição
var indice_selecionado = -1; //Índice do item selecionado na lista
var tbUsuarios;

//aqui o botão submit já está desabilitado
$(document).ready(function() {
  $('#buttonSubmitRegister').prop('disabled', true);
});

$(function() {
  tbUsuarios = localStorage.getItem("tbUsuarios"); // Recupera os dados armazenados
  tbUsuarios = JSON.parse(tbUsuarios); // Converte string para objeto
  if (tbUsuarios === null) // Caso não haja conteúdo, iniciamos um vetor vazio
    tbUsuarios = [];
});

function Adicionar() {
  var usuario = JSON.stringify({
    Nome: $("#txtNome").val(),
    email: $("#txtEmail").val(),
    Senha: $("#txtSenha").val()
  });
}

$(document).keyup(function() {
  // habilita caso o numero de caracteres seja maior que 1.
  if ($("#txtNome").val().length > 1 && $("#txtEmail").val().length > 1 && $("#txtSenha").val().length > 1) {
    $(document).ready(function() {
      $('#buttonSubmitRegister').prop('disabled', false);
    });
    tbUsuarios.push(usuario);
    localStorage.setItem("tbUsuarios", JSON.stringify(tbUsuarios));
    alert("Usuário Cadastrado com Sucesso!");
    return true;
  }
  // desabilita o campo o valor seja apagado.
  if ($("#txtNome").val().length < 1 && $("#txtEmail").val().length < 1 && $("#txtSenha").val().length < 1) {
    $(document).ready(function() {
      $('#buttonSubmitRegister').prop('disabled', true);
    });
  }
});

Não sei exatamente qual as suas necessidades, mas essa verificação pode ser facilmente removida pelo usuário, claro que vai diminuir altamente o número que cadastros feitos faltando algum dado... mas caso seja um usuário malicioso ele pode manipular isso, então é bom que exista uma verificação no lado do servidor também. Como você está desenvolvendo uma aplicação que usa o localStorage não sei se há muito que possa ser feito. Mas dou essa dica também caso no futuro alguém encontre isso e esteja desenvolvendo algo em PHP por exemplo, e ache que simplesmente isso vai resolver o problema.
Answer: Não adianta modificar o valor do atributo disabled para falso.
Os navegadores não lêem o valor do atributo. Eles apenas consideram sua presença. Se o atributo existe, o elemento que o tem está desabilitado. Se o atributo não existe, o elemento não está desabilitado.
Portanto, as quatro formas abaixo são equivalentes:
<input type="button" disabled>
<input type="button" disabled="true">
<input type="button" disabled="false">
<input type="button" disabled="Fui na Espanha buscar o meu chapéu, azul e branco da cor daquele céu">

A única forma de reabilitar o seu botão é removendo o atributo. Você pode utilizar a função removeProp do jQuery para isso. E.g.:
$("#buttonSubmitRegister").removeProp("disabled");

Se algum dia você encontrar um navegador que habilite um elemento que esteja com o valor do atributo disabled igual a false, saiba que esse navegador não segue a especificação do HTML 5:

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

"A presença de um atributo booleano em um elemento representa o valor verdadeiro e a ausência do atributo representa o valor falso".
Fonte: https://www.w3.org/TR/html5/infrastructure.html#boolean-attribute
Comment: Pelo que eu entendi desse trecho, qualquer valor dentro do `disabled` altera a condição para verdadeira, na ausência é `false` ou seja `$("#elemento").prop('disabled', "");` também voltaria a habilitar o elemento. Não seria necessário então o `removeProp("disabled")` correto?
Comment: A idéia é boa, mas tem isso:   "Also note that the .removeProp() method should not be used to set these properties to false. Once a native property is removed, it cannot be added again. See .removeProp() for more information. "
Comment: Interessante essa, mas vendo por esse lado, nenhum dos meus navegadores incluindo o Chrome e Firefox que estão atualizados seguem essa regra, o unico desatualizado é o IE, e nele também funciona.


Finding the inverse modulo . $7^{-2}\pmod {11}$ and $7^{-3}\pmod {11}$

Question: $7^{-1}\pmod{11}$
the above can be found by
$7x\pmod{11}\equiv 1$ and $x=8$
now i am confused on how to find $7^{-2}\pmod{11}$ and  $7^{-3}\pmod{11}$ .
Comment: Indeed. It took me more than it should have to verify $64\equiv 9$ mod $11$ :)
Comment: oh so its $7^{-2}\pmod {11}\equiv 9$ ?
Answer: Hint $\,\ 7^{-2} \equiv (7^{-1})^2\ $ since $\ 7x\equiv 1\,\Rightarrow\, 7^2 x^2\equiv 1.\,$
Comment: @RK Yes, $\ \color{#c00}{7^{-1}\equiv 8}\,\Rightarrow\, (\color{#c00}{7^{-1}})^2\equiv \color{#c00}8^2\ $ by the $ $  [Congruence Power Rule.](http://math.stackexchange.com/a/879262/242) $ $ Similarly for $\ 7^{-3}\ \ $
Comment: @RK Yes, done smartly by the [Congruence Product Rule.](http://math.stackexchange.com/a/879262/242)
Comment: so can i substitute like $7^{-2}\equiv (7^{-1})^2\equiv(8)^2\\\equiv 64 \equiv 9 \pmod {11}$ ?
Comment: and similarly for
$7^{-3} \equiv 7^{-2}\cdot 7^{-1}\\
\equiv 9\times 8 \equiv 72 \equiv 6 \pmod {11}$


Is the square root of a positive semi-definite matrix a unique result?

Question: I am trying to decompose a time series of $n$ observations  $\bf{\mathrm{v_c}}$ into the $n \times n$ variance-covariance structure $\sum$ and a random series $\bf{\mathrm{v}}$.
So, I can derive the variance-covariance matrix $\sum$ from the autocorrelation function of $\bf{\mathrm{v_c}}$.  This will be a Toeplitz matrix, which is positive semidefinite.  Therefore, I am able to compute a suitable matrix $\sum^{-\frac{1}{2}}$ to transform my correlated series into a random signal.
$\bf{\mathrm{v}} = \sum^{-\frac{1}{2}}\bf{\mathrm{v_c}}$
I am able to do this using the sqrt(m) function in MATLAB, but can also find a Cholesky factorisation of the variance-covariance matrix and use this to induce the correlations.  However, I get different (but somewhat similar) results for the random series using the sqrtm and Cholesky methods.
I have read through several texts to determine how I might ascertain the square root of various matrices, and have looked at eigenvalue decomposition methods and so on.  I see there are only unique solutions under certain prescribed conditions - but I presume that these unique solutions are still only one of many roots?
My question is this:  is there any way to argue that one particular square root is preferable over another.  If not, is there a way to extract all possible solutions, such that all possible random functions may be obtained?
Answer: Let a matrix $\mathbb{V}$ have "square roots" $\mathbb{A}$ and $\mathbb{B}$; that is,
$$\mathbb{V = AA^\intercal = BB^\intercal}.$$
For simplicity, suppose the original matrix  $\mathbb{V}$ is invertible (which is equivalent to being positive definite under the assumptions).  Then $\mathbb{A}$, $\mathbb{B}$, and their transposes must also be invertible because
$$ \mathbb{I} = \mathbb{V^{-1}V} = \mathbb{V^{-1}AA^\intercal} = \mathbb{(V^{-1}A)A^\intercal}$$
exhibits a left inverse for $\mathbb{A}^\intercal$, implying $\mathbb{A}$ is invertible too; the same argument applies to $\mathbb{B}$, of course.  We exploit these inverses to write
$$\mathbb{(B^{-1}A)(B^{-1}A)^\intercal = B^{-1} (A A^\intercal) B^{-1}{^\intercal} =  B^{-1} (V) B^{-1}{^\intercal}=B^{-1}(BB^\intercal)B^{-1}{^\intercal} = I\ I = I},$$
showing that $\mathbb{O=B^{-1}A}$ is an orthogonal matrix: that is, $\mathbb{OO^\intercal=I}$.  The set of such matrices forms two smooth real manifolds of dimension $n(n-1)/2$ when $\mathbb{V}$ is $n$ by $n$. Geometrically, orthogonal matrices correspond to rotations or to a reflection followed by rotations, depending upon the sign of their determinant.
Conversely, when $\mathbb{A}$ is a square root of $\mathbb{V}$, similar (but easier) calculations show that $\mathbb{AO}$ is also a square root for any orthogonal matrix $\mathbb{O}$--and it does not matter here whether $\mathbb{A}$ is invertible or not.
It is also easy to see that multiplication by an orthogonal matrix (not equal to $\mathbb{I}$) really does alter the square root of an invertible matrix. After all, $\mathbb{AO = A}$ immediately implies $\mathbb{O = A^{-1}A = I}$.  This shows that the square roots of positive-definite matrices can be put into a one-to-one correspondence with the orthogonal matrices.
This demonstrates that square roots of positive-definite matrices are determined only up to multiplication by orthogonal matrices.  For the semi-definite case, the situation is more complicated, but at a minimum, multiplication by an orthogonal matrix preserves the property of being a square root.
If you wish to apply additional criteria to your square root you might be able to identify a unique one or at least narrow down the ambiguity: that will depend on your particular preferences.
Comment: (+1) @hydrologist: As a complement to whuber's answer: One possible criterion that will lead to uniqueness is to insist on the *square-root* itself being positive semidefinite. Uniqueness of $\mathbb A$ then holds under the weaker condition that $\mathbb V$ is positive semidefinite. An instructive example to see what can "go wrong" is to look at the possible square roots of $\mathbb I$, even just the *diagonal* ones! :)
Comment: @cardinal:  Thank you for your responses, which are most helpful and very much appreciated!
Comment: This is known as *unitary freedom of square roots*
Comment: @whuber:  Thank you again for your help.  This has been most useful.


specifying random effects in an intensive longitudinal design

Question: I conducted a study where participants made 15 decisions (which could be correct or incorrect) per trial (or block). There were 10 identical trials (so the same 15 decisions were made 10 times). All participants made the same decisions across the same number of trials. Further, each decision contains a unique cue. The cues can be grouped into one of three categories. So, my data looks like this:

ID
trial
decision
cue
correct

1
1
1
A
1

1
1
2
B
0

1
1
3
C
1

1
1
4
B
1

1
2
1
A
0

1
2
2
B
0

1
2
3
C
1

1
2
4
B
1

1
3
1
A
1

1
3
2
B
0

1
3
3
C
1

1
3
4
B
0

1
4
1
A
0

1
4
2
B
0

1
4
3
C
1

1
4
4
B
1

2
1
1
A
0

2
1
2
B
0

2
1
3
C
1

2
1
4
B
0

... but with 40 participants (ID), 10 trials, and 15 decisions. I'm specifically interested in two things: (1) How do participants learn across the trials and (2) is there an interaction between cue and trial (in other words, do participants learn across trials differently based on the cue type).
Here's what I believe (though I would appreciate confirmation or corrections).

This is an example of an intensive longitudinal design (as described in this paper, which is essentially collecting repeated measures data at multiple time points.
In a hierarchical modeling framework, there are three nested levels. Specifically, decision is nested within trial which is nested within participant (ID).

I have three model specifications that I cannot choose from. I'd appreciate any help you can offer in deciphering how to best specify this model.
1)
lmer(correct ~ 1 + trial * cue + (1 | ID:trial) + (1 + trial | ID), data=df, family="binomial")
2)
lmer(correct ~ 1 + trial * cue + (1 | trial) + (1 | ID), data=df, family="binomial")
3)
lmer(correct ~ 1 + trial * cue + (1 + trial | ID), data=df, family="binomial")
My question is: What are the consequences or meaning of each specification. In other words, I believe that the first model best captures the study design, but I can't explain why. I think I understand the resulting formulas. Thus, this is not a coding question and I am not limited to using lmer or R.
Thank you in advance - I have been thinking about this problem for many more months than I care to admit.
Answer: In the first model:
correct ~ 1 + trial * cue + (1 | ID:trial) + (1 + trial | ID)

(1 | ID:trial) treats trial as a random factor that is nested within levels of ID. From the description in the question, this is not the case. Since all participants were in each trial, these would be crossed random effects, not nested. To understand the difference, see here:
Crossed vs nested random effects: how do they differ and how are they specified correctly in lme4?
However, since you are specifically interested in the fixed effect of trial (and it's interaction with cue) it does not make sense to also treat trial as a random factor.
The second model:
correct ~ 1 + trial * cue + (1 | trial) + (1 | ID), data=df

is the formulation you would use to treat ID and trial as crossed random effects, but as mentioned above, this does not make sense.
The third model:
correct ~ 1 + trial * cue + (1 + trial | ID)

does make sense, based on the description. Here we are fitting random intercepts for participants and allowing the fixed effect of trial to vary by participant. If this is what you want, then this would be a reasonable model, provided that it is supported by the data.


SQL-Alchemy reuse column definitions

Question: Is there a way to reuse the column definitions across all tables to avoid mix types between tables.
It's a common issue on DW to have the same column in many tables.
Using SqlAlchemy Core.
t_teachers = Table(
    'teachers', metadata,
    Column('teacher_uid', String(20), primary_key=True),
    Column('first_name', String(50)),
    Column('last_name', String(50)),
)

t_students = Table(
    'students', metadata,
    Column('student_uid', String(20), primary_key=True),
    Column('first_name', String(50)),
    Column('last_name', String(50)),
)

exams = Table(
    'exams', metadata,
    Column('exam_id', String(20), primary_key=True),
    Column('teacher_uid', String(20), ForeignKey('teachers.teacher_uid'), nullable=False),
    Column('student_uid', String(20), ForeignKey('students.student_uid'), nullable=False),
    Column('points', Integer),

)

exam_marts = Table(
    'exams_marts', metadata,
    Column('teacher_first_name', String(50)),
    Column('teacher_last_name', String(50)),
    Column('student_first_name', String(50)),
    Column('student_last_name', String(50)),
    Column('exam_name', String(50)),
    Column('points', Integer),
)

Comment: With proper database design, you'd probably have a `user` table and columns referring to `user.id` as a foreign key. I really don't know what you're asking in this instance.
Comment: You should'nt have 5 different tables with same column. You only should have one table, and other tables referencing this table. See https://en.wikipedia.org/wiki/Database_normalization
Comment: Maybe the user_name wasn't a good example. There are some columns that are not referable, and some tables are acting as data marts.
Comment: It still wouldn't make much sense to me. You need a [mcve] to show the actual issue you're talking about
Comment: `exam_marts` (which is probably a typo in itself) is repeating data already in `t_teachers` and `t_students`. As suggested, you should be looking at normalization
Comment: The data on the marts are summarized and not normalized on purpose.
Answer: Something like this?
def mixin_factory():
    return (sa.Column("created", sa.Date),)

tablename_table = sa.Table(
    "tablename",
    metadata,
    *mixin_factory()
)

Comment: +1 and read more on [Composing Mapped Hierarchies with Mixins](https://docs.sqlalchemy.org/en/14/orm/declarative_mixins.html#composing-mapped-hierarchies-with-mixins)

SQL-Alchemy reuse column definitions


Content notification for updates

Question: OG has a pre-installed rule "OG group content notification" for sending out notifications to group members of new posts.
Is there a similar rule for sending out notifications of updated group posts to group members?
I have read that there might be a way using Rules on How do I send notifications for followers of a group when group content is updated? but I was not allowed to post a follow-up comment there.
Answer: I realized that I did not have the Rules UI enabled. Once I enabled it, I was able to see the "OG new content notification (With Message)" rule clearly.  I only need create a copy of this and edit it to my requirements.

Content notification for updates


Need help with Jacobi symbol / quadratic nonresidues proof

Question: I've been doing a few number theory problems online for fun and I've been having a bit of trouble with proving this one successfully:

Suppose $p$ and $q$ are distinct odd primes. Prove that there is always some integer $n$ with $(n / pq) = -1$ (where $(n / m)$ means the Jacobi symbol of $n$ and $m$).

I ended up with $(p/n)(q/n)$  and tried using the prime factorization of n to try to get somewhere, but I don't think it's the correct path. I think what I need to do is prove that there is always some n that can be a quadratic non-residue modulo pq. However, I've also been having a bit of trouble trying to prove this.
Could someone give a bit of guidance to help me out? Thanks.
Comment: @EMS  It is not appropriate to delete your question as soon as it is answered.  Such behaviour is disrespectful to the person(s) who took the time to answer, constitutes vandalism of the site, and is often indicative of attempts to cheat and hide the evidence.  Please don't do this again in the future.
Comment: e.g. choose $n\equiv c\,$ nonsquare $\!\!\pmod{\!p}\,$ and $\,n\equiv 1\pmod{\!q},\,$ e.g. $\ c+p(p^{-1}(1\!-\!c)\bmod q)\ \ $
Answer: You don't need to deal with the prime factorization of $n$, apart from it being relatively prime to $pq$, but that is implicit in the equation you have. Also, instead of "$(p/n)(q/n)$", your symbols should be the reciprocal of this. In particular, rewriting your equation of Jacobi symbols in terms of Legendre symbols gives
$$\left(\frac{n}{pq}\right) = \left(\frac{n}{p}\right)\left(\frac{n}{q}\right) = -1 \tag{1}\label{eq1A}$$
This means one of the Legendre symbol values is $1$ and the other is $-1$. Since $p$ and $q$ are odd primes, there's always at least one quadratic residue and one quadratic non-residue for each. Assume the first Legendre symbol value is $1$, so let $x$ be a quadratic residue modulo $p$, and the second one is $-1$, so let $y$ be a non-quadratic residue modulo $q$. You thus have the following $2$ congruence equations to solve for $n$:
$$n \equiv x \pmod p \tag{2}\label{eq2A}$$
$$n \equiv y \pmod q \tag{3}\label{eq3A}$$
Since $\gcd(p,q) = 1$, the Chinese remainder theorem states you can solve the above $2$ equations to get a unique solution of $n$ modulo $pq$.


Get double variable when sent variable to next viewcontroller swift

Question: I create global variable just after import statement:
var kontenid = ""
var judulkonten = ""

then I sent to FreeTiles view controller (other view controller) through tableview and prepareForSegue:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    //let cell = tableView.dequeueReusableCellWithIdentifier(reuseContentFreeIdentifier, forIndexPath: indexPath) as! FreeTableViewCell
    var contentku = contents[indexPath.row] as ContentModel
    kontenid = contentku.id
    judulkonten = contentku.title
    performSegueWithIdentifier("lemparkonten", sender: self)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
    if (segue.identifier == "lemparkonten") {
        var svc = segue.destinationViewController as! FreeTiles;
        svc.idcontent = kontenid
        svc.namacontent = judulkonten
    }
}

And on FreeTiles view controller, I put this inside class:
var idcontent :String!
var namacontent :String!

But when I println on FreeTiles view controller:
println("konten id nya:\(idcontent)")
println("judul nya:\(namacontent)")

I got two log of idcontent and two log of namacontent, the first is empty and the second filled with correct idcontent and namacontent.
How to avoid get two threw variable result when sent variable between two view controller? What is the correct code to get only one result for each threw variable?
Edited:
it seems like cache on xcode log because when I change println, it show only one log.
if idcontent.isEmpty && namacontent.isEmpty {
        //println("Nothing to see here")
    }else{
        var content_id = idcontent
        var content_name = namacontent
        println("content_id:\(content_id)")
        println("content_name:\(content_name)")
    }

So, I make filter on FreeTiles (second view controller) to get the filled variable.
Regards.
Comment: When do you print your results? Show your code of the FreeTilesViewController.
Comment: if idcontent.isEmpty && namacontent.isEmpty {
            //println("Nothing to see here")
        }else{
            var content_id = idcontent
            var content_name = namacontent
            println("content_id:\(content_id)")
            println("content_name:\(content_name)")
        }
Comment: Where is that code? (ViewDidLoad?) Post your Code of your second ViewController
Comment: override func viewDidLoad() {
        super.viewDidLoad()
        println("konten id nya:\(idcontent)")
        println("judul nya:\(namacontent)")
        if idcontent.isEmpty && namacontent.isEmpty {
            //println("Nothing to see here")
        }else{
            var content_id = idcontent
            var content_name = namacontent
            println("content_id:\(content_id)")
            println("content_name:\(content_name)")
        }}
Answer: First of all, if you are declaring global variables then you need to specify it's scope. Let's say:
public var kontenid = ""
public var judulkonten = ""

Further, once you have declared global variables you can access it from anywhere and it will also reflect when you will change the value.
So, after assigning values to the variables
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    //let cell = tableView.dequeueReusableCellWithIdentifier(reuseContentFreeIdentifier, forIndexPath: indexPath) as! FreeTableViewCell
    var contentku = contents[indexPath.row] as ContentModel
    kontenid = contentku.id
    judulkonten = contentku.title
    performSegueWithIdentifier("lemparkonten", sender: self)
}

In your prepareforsegue method, you don't need to assign the values:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
    if (segue.identifier == "lemparkonten") {
        var svc = segue.destinationViewController as! FreeTiles;

    }
}

Now you can access the above global variables anywhere so you can directly use it in other class:
if idcontent.isEmpty && namacontent.isEmpty {
        //println("Nothing to see here")
    }else{
        var content_id = kontenid
        var content_name = judulkonten
        println("content_id:\(content_id)")
        println("content_name:\(content_name)")
    }
}

Let me know, if you have any issues against this code.
Comment: I think this throw variable to FreeTiles (second view controller), I tried without this it throw nil : svc.idcontent = kontenid
            svc.namacontent = judulkonten
Comment: It can't be nil, try to print the value inside tableview itself
Comment: inside tableview is not nil, but if I do not write svc.idcontent = kontenid
        and svc.namacontent = judulkonten inside prepareForSegue, it did not sent to FreeTiles (second view controller), so when I run the project it become buggy because the second view controller got nil for idcontent and namacontent.
Comment: @Sarimin As I said you need not to assign the variables, you can directly access from other class, once you have defined as a "public"
Answer: You are printing your variables 2 times out with your code:
    override func viewDidLoad() {
       super.viewDidLoad()
       println("konten id nya:(idcontent)") // first
       println("judul nya:(namacontent)")  // second
       if idcontent.isEmpty && namacontent.isEmpty { //println("Nothing to see here")
    } else {
    var content_id = idcontent var content_name = namacontent
println("content_id: (content_id)") // 3
println("content_name:(content_name)") // 4
    }}

Your Code seems doing well to send data through segues. Otherwise you could check my answer here:
Sending data with Segue with Swift


Dropping the 5th degree and counting a C♯Dom7

Question: I'm currently writing out (into a chord diagram book) all the different voicing/finger positions for the seventh chords.
Some voicings are difficult to play and I so my initial thought was "oh, the 5th note apparently is neutral so I can drop that and maybe the finger position will be a little easier to play".
The problem I'm having is being confident that the note I'm dropping is indeed the 5th degree, specifically when dealing with a chord whose notes have already been re-arranged into another voicing.

In short: I think my understanding (below) is correct and I'm just looking for confirmation from someone that there isn't some other crazy music theory concept I'm unfamiliar with that would mean I'm mistaken

So for example: A7 (dominant).
The root degrees are 1, 3, 5, ♭7 (A, C♯, E, G)
If I switch to 1st inversion I get the notes C♯, E, G, A (which are really the A7 degrees 3, 5, ♭7, 1)
If I try to play these notes in this order (C♯, E, G, A) on the guitar, I've found it to be a bit tricky for me still (that might just be my fingers not being as flexible as a long practicing guitarist, but whatever).
So if I decided I want to drop the 5th (a neutral note), which note should I drop?
I assume I'm still dropping the E note (which is the 5th as far as the root arrangement is concerned) because the new degrees (3, 5, ♭7, 1) don't actually make any sense as far as the major scale for C♯7 is concerned.
e.g. it's not like I can count the degrees like I would have done when originally calculating the notes for A7; So it wouldn't make sense to count: C♯ (1st), E (3rd), G (5th), A (♭7th) because those particular notes aren't the correct notes/order as far as C♯7 dominant chord is concerned (using the major scale). That would instead be: C♯ (1st), E♯ (3rd), G♯ (5th), B (♭7th)
So is my understanding correct?

One additional question, how do you properly count the degrees for something like C♯7?
If I do it like so...
C♯, (W) D♯, (W) F, (H) F♯, (W) G♯, (W) A♯, (W) B♯, (H) C
...then this wouldn't be correct as we A.) have two F's in the arrangement and B.) don't end on the correct note for the octave.
But if I do it like so...
C♯, (W) D♯, (W) E♯, (H) F♯, (W) G♯, (W) A♯, (W) B♯, (H) C
...then here I've just assumed that you don't count F for the half-step and just go straight to F♯ as you know that E♯ is actually just F anyway.
But this doesn't appear to be correct either, as we've ended up with the octave not being the correct note.
Comment: All the voicings mentioned in your question are close voicings. They are not very useful for playing on the guitar because most of them are hardly playable in standard tuning (the root position of a maj7 chord being an important exception). On the guitar, seventh chords are usually played in drop-2 or drop-3 voicings. These are not only much easier to play, but they also sound very good. Some information on drop-2 and drop-3 voicings can be found in [this answer](http://music.stackexchange.com/a/42527/9724).
Comment: Yes, dropping the fifth is usually OK, if it's not altered (i.e., if it's no b5 or #5).
Comment: C♯ major is C♯ (2) D♯ (2) E♯ (1) F♯ (2) G♯ (2) A♯ (2) B♯ (1) C♯ (with semitone counts between scale degrees). B♯  to C is 0 semitones - they're the same note in a tempered scale.
Comment: Oh bloody hell, of course, B♯ IS C. Sorry, I was being an idiot there
Comment: Thanks @MattL I'm aware of drop 2 and 3 voicings. Was interested to know if dropping the 5th (as I've described above) was correct/valid (although I'm aware drop voicings are generally suggested for difficult guitar voicings)
Comment: Easy way to work out the notes for C#: think key C and add a # to each and every.
Answer: The fifth of a chord can safely be dropped in any inversion. The fifth of a chord (perfect fifth) is always going to be the same note in reference to the root. Thus, root=A, means P5=E. It can't matter when there is a different voicing, as P5 will always be the same note in the same key. It has been said of a dominant chord on guitar that the 3 (C#) and b7 (G) are the most important, especially if the bass player uses the root A. Some of the shapes for A7 are tricky, in some inversions, so you could even make shapes that only use 3 strings - and they don't need to be adjacent to each other.
You ask about C#7. Be aware that the b7 in C# is B# flattened, making the dominant part actually a B note.
Answer: As an addition to Tim's answer, the two most common guitar voicings for dominant seventh chords with the fifth omitted and the root as the lowest note are (e.g., for C7, from low to high E string):
8 X 8 9 X X
and
X 3 2 3 X X
Since you mute three out of the six strings, these shapes can be shifted. They are very common in a blues and jazz context.
They allow other tensions to be added very easily. The first version allows you to add the 13th (on the b string) and the 9th (on the high e string):
8 X 8 9 10 10
Of course, you can also add the #5/b13 (9th fret b-string), or the b9 or #9 on the high e-string.
The other voicing lets you add the 9th (or the b9 / #9):
X 3 2 3 3 X (9)
X 3 2 3 2 X (b9)
X 3 2 3 4 X (#9)
These voicings finally also let you add the 5th (or an altered fifth) if you want it; you can find it on the high e-string. Some examples:
X 3 2 3 3 3 (C9 with 5th)
X 3 2 3 3 4 (C9/#5)
X 3 2 3 3 2 (C9/b5 or #11)
X 3 2 3 4 4 (C7/#5/#9 or C7/#9/b13)
Go wild finding all playable combinations ...
Comment: Thanks @MattL this was an interesting response. But as Tim answered first and confirmed specifically what I needed I'll likely mark his response as the correct answer. Hope that's OK.
Comment: @Integralist - On SE we don't really say one answer is "correct" which would imply the other answers are incorrect.  But you can "accept" only one answer.  The answer you accept should be the one that best answers your question (does not mean that the others are not also "correct").  You will find  most of the answers on SE are correct to some extent because they are generally provided by knowledgeable members.  If one is incorrect it will be downvoted.  Also, the answer you accept does not have to be based on the order the answer was posted.  Justed wanted to clarify for future reference.