Need confirmation on layer 2 security question

Question: I need confirmation on a question regarding layer 2 security. I've been doing research and I just need to know that I understand it correctly.
Basically, if you have a LAN with a few machines connected to a switch, and those machines are broadcasting LLDP or ARP or something like that, is it true that those broadcasted packets will never escape the LAN (sans faulty software in the switch or machines and things of that nature)?
I know this is a basic question, but I haven't been able to find a direct answer to it and am hoping someone could just give a really brief one. Thanks!
Answer: Well, for the most part you are right. Under proper configuration/normal operation all layer two traffic should not be able to "escape" the VLAN where it is generated.
There are some scenarios (VLAN hopping and DTP negotiation comes to my mind) were the traffic can leak to other VLANs without going first through a layer 3 device (a.k.a. router).
With "VLAN hopping" if the native VLAN ID of a trunk is the same as the VLAN ID assigned to the switch port where the host that is generating the traffic is located, then he or she can double 802.1q-tag it's traffic and then this traffic "appear" at the other end of a trunk on a VLAN different from where it originated.
This is the reason why a good operational procedure is to never use VLAN 1 for your access ports (by default the native VLAN of a trunk is 1). Another good operational procedure is to assign a unique native VLAN ID for trunks and then configure each an every trunk on your organization with this unique-trunk-only VLAN ID.
You may want to take a look at this article
Comment: Where's all this talk about VLANs coming from? I'm fairly sure the OP is just talking about a standard LAN and a standard switch with no VLANs. (for the record, your answer is still correct though)
Comment: Well my reading of the question was that if OP is talking about traffic "escaping" out of the "LAN" (VLAN) then there has to be another "LAN" (VLAN) where the traffic is leaked to. So now having two VLANs my reasoning was to give an scenario where the traffic between to VLANs could leak, then trunking, 802.1q, double-tagging et al. And for the record there is no such thing as a switch with no VLAN, if we are talking of a switch there should be at least one VLAN (with ID 1).
Answer: Agreed, with a secure configuration and no software on the hosts relaying such traffic, broadcast traffic should be confined within a VLAN on a switched network.
Another good reference on layer 2 security issues and mitigation techniques:
SAFE Layer 2 Security In-Depth (Cisco White Paper)


Getting the pretty url for a node if it's a term

Question: I'm using 'pretty urls' with autopath for my nodes so example.com/node-name but I'm having trouble getting that in the context of a term page.
So on the node template itself I'm doing:
 if ( arg(1) == 'term') {
      //do stuff
 }

To get the link to the nodes page:
<a href="<?php echo $base_url . '/node/' . $node->nid; ?>" class="btn btn-primary" role="button">View details »

But this takes me to the node number url so example.com/node/23 or something like that. I would like the nice url. When I var_dump $node all I can get to build a url is the id, any ideas? Preferably something in the code, I like controlling stuff in the templates if I can.
Answer: Figured it out, using drupal_get_path_alias. So something like in the node:
$url = drupal_get_path_alias('node/' . $node->nid);


Print custom field in user edit form in block

Question: Following code prints user edit form in block:
function notifikacie_custom_block_info() {
 $blocks['user_profile'] = array(
   'info' => t('User profile edit'),
   'cache' => DRUPAL_NO_CACHE,
 );

 return $blocks;
}

function notifikacie_custom_block_view($delta = '') {
  $block = array();

      global $user;
      module_load_include('inc', 'user', 'user.pages');
      $block['subject'] = t('Fill your profile');
      $block['content'] = drupal_get_form('user_profile_form', $user);

  return $block;
}

But it does not print custom fields created in admin/config/people/accounts/fields. How do I print those custom fields?
Comment: from `admin/config/people/accounts/display` manage your filed, make sure that your fields not `hidden` .
Comment: It is visible, I mean, I am trying to print edit form, not print the fields itself.
Answer: I've just run your code and it works fine. Maybe it is permission related problem.
<?php
function user_profile_block_info() {
 $blocks['user_profile'] = array(
   'info' => t('User profile edit'),
   'cache' => DRUPAL_NO_CACHE,
 );

 return $blocks;
}

function user_profile_block_view($delta = '') {
  $block = array();

      global $user;
      module_load_include('inc', 'user', 'user.pages');
      $block['subject'] = t('Fill your profile');
      $block['content'] = drupal_get_form('user_profile_form', $user);

  return $block;
}

Output/result:
Here Birth Date is custom field, created form admin/config/people/accounts/fields.


Verification of a proof that the ring of continuous functions on $[0,1]$ is not noetherian

Question:
My problem is to show that the ring of continuous real-valued functions on the interval $[0, 1]$ is non-noetherian.

I'd like to know if this argument holds:
Let $I$ be the set of functions such that for every $f \in I$, there exists an open neighborhood $[0, t)$ of $0$ such that $f(x) = 0$ whenever $x \lt t$. Let's call the largest such neighborhood the zero neighborhood of $f$.
This set is an abelian group, since the zero function obviously has such a neighborhood, and given any pair of function $f$ and $g$, we can intersect their zero neighborhoods to get the zero neighborhood of the sum. Lastly, this set is closed under multiplication in $\mathbb{R}$: scaling by $0$ gives you the zero function, and scaling by anything else preserves the zero neighborhood.
Then, to prove our ring non-noetherian, we must show this ideal cannot be finitely generated. Suppose it was, $I = (f_1, f_2, ... ,f_k)$ with each $f_i$ having a zero neighborhood of $[0, x_i)$. We will find a function $f$ which cannot be written as a finite linear combination of these $f_i$.
We noted above that closure under addition and under scaling may only affect the zero neighborhood in certain ways. Addition of two nonzero functions with zero neighborhoods $[0, x_1)$ and $[0, x_2)$ will leave you with a function whose zero neighborhood is $[0, \min_{ x_1, x_2} )$. Scaling by a nonzero real will preserve the zero neighborhood. This means that the linear combination of $f_i$ must necessarily either have $[0, 1]$ as its zero neighborhood, or else it must have $[0, x_i)$ for some $i$.
To construct a counterexample, we define $\widetilde{x}$ to be the midpoint between $\max {x_i}$ and $1$. Then we let $f(x)$ be uniformly zero until $x_i$, then let it grow linearly from there on out.
Wordy, but hopefully clear. There are some subtle points I'm missing. For one, I know that I would need to exclude the zero function from the final $\max {x_i}$ calculation. I also need to show that if a continuous function is zero on $[0, 1)$, it is the zero function. These two guarantee the choice at the end is legitimate.
Does this seem like a legitimate approach? Or did I miss anything?
Comment: You likely want to let $\tilde x$ to be the midpoint of min $x_i$ and 0. You can certainly have large neighborhoods that vanish in your ideal, the trick is constructing a small one. Also note that personally I think it is MUCH MUCH easier to just create a non-terminating chain of ideals though I don't see any reason why your proof wouldn't work.
Comment: You're making the problem much harder than it is. Why don't you consider the chain

$$(\sqrt{x}) \subseteq (x^{\frac{1}{4}}) \subseteq (x^{\frac{1}{8}})\ldots?$$
Comment: For the last point, about such a function being the zero function or not, the inverse image of a closed set is closed. If $[0, 1) \subseteq f^{-1}(\{0\})$, then the closure of $[0, 1)$ must also be contained in $f^{-1}(\{0\})$. Also, I think it's easier to show that there exists an infinite, strictly increasing chain of ideals, for instance
$$
(f_1) \subseteq (f_1, f_2) \subseteq  (f_1, f_2, f_3) \subseteq \cdots
$$
where $f_n$ is some function which is zero on $[0, \frac{1}{n}]$ and non-zero otherwise.
Comment: Addition of two non-zero functions with zero neighborhoods $[0,x_1)$ and $[0, x_2)$ won't necessarily give a function with zero neighborhood $[0, \min(x_1,x_2))$. The zero neighborhood of the sum may be larger: just think of the case where you're adding a function $f$ and its negation $-f$.
Comment: @Peter Oops. Yes. That is an issue, isn't it?
Answer: Denote your ring by $R$. You actually started out being pretty close to a very simple approach.
Hint: Show that $I_{ab}=\{f\in R\mid f([a,b])=\{0\}\}$ is an ideal of $R$ for any subinterval $[a,b]$ of $[0,1]$. Notice that if $[c,d]\subseteq [a,b]$, then $I_{cd}\supseteq I_{ab}$. Show that if $[c,d]$ is properly inside $[a,b]$ then the associated ideals are properly contained too.
Can you imagine how one might use this to construct a chain of ideals?


A knot invariant which highlights the unknot

Question: Is there a knot (link) invariant, or a combination of them which discern the unknot (unlink) from any other knot (link)?
Answer: Yes, however they are not known to be computable in polynomial time.  A quick an incomplete survey:

The Seifert genus of a knot is $0$ if and only if it is unknotted.
The fundamental group of the knot complement (the knot group) is isomorphic to $\mathbb{Z}$ if and only if the knot is unknotted.
The A-polynomial (not to be confused with the Alexander polynomial), which has to do with homomorphisms of the knot group to $\mathrm{SL}_2\mathbb{C}$.
Both knot Floer homology and Khovanov homology detect unknots.
For knots with 10 or fewer crossings, the Alexander polynomial suffices.

The unknotting problem is known to be in NP and coNP.  That means, given a knot presented in some manner, someone can give you a proof that the knot is either knotted or unknotted that takes polynomial time to verify.
Wikipedia has a list of unknotting algorithms.  Approaches include:

enumerating Seifert surfaces to find a disk that bounds the knot.
exhaustively trying all sequences of Reidemeister moves of a diagram up to a certain polynomial number of steps.
exhaustively trying all sequences of Pachner moves of a triangulation of the knot complement up to a certain polynomial number of steps, until it is obviously an unknot triangulation.
use Dynnikov's result that arc presentations (grid diagrams) for an unknot can be monotonically simplified, so try all monotonic simplifications.

There are also a number of invariants where whether it can detect unknots is an open question, such as the Jones polynomial, the HOMFLY polynomial, and finite-type (Vassiliev) invariants.


Imprimir mesagem quando arquivo csv carregado for maior ou menor do que 9 colunas

Question: Minha aplicação lê um arquivo csv e converter para pdf. Para isso tenho o frontend em html para carregar o arquivo. Gostaria de saber como faço para mostrar ao usuário uma mensagem informando que o arquivo é inválido. O arquivo será inválido quando o número de colunas do arquivo csv carregado for maior ou menor do que 9.
<!DOCTYPE html>

    </style>
    <meta charset="UTF-8">
    <title>Site Report</title>

 Site Report

<form action="" method="post" enctype="multipart/form-data">

    Choose CSV file:

    <input type="file" accept="text/csv" name="userfile"/>

    <input type="submit" name="action" value="Upload"/>

</form>

    <?php
    if(isset($_POST['action']) && $_POST['action']=='Upload'):
    $userFile=$_FILES['userfile'];
    $name = $userFile['name'];
    $tmp = $userFile ['tmp_name'];

    $extension=explode('.', $name);
    $ext=end($extension);

    $newName =md5($name).'.'.$ext;

    $newName= str_replace(' $name ','$name','uploadFile').'.'.$ext;
    $userMessage="File uploaded successfuly  ";

    if(empty($userFile)):
           echo 'Select an file to upload';
    else:
    if(move_uploaded_file($tmp, 'uploads/'.$newName)):

             echo $userMessage;
            else:
            echo 'Error';
            endif;
          endif;
      endif;

    ?>

<form action="download.php" method="post">

<input type="submit" name="submit" value="Download PDF File" />

</form>

Comment: Já tentou dentro do lado do servidor fazer uma contagem das colunas do arquivo e se forem no seu requisito **igual 9** passar a conversão para pdf?
Answer: Acredito que arquivos csv façam indexalização da seguinte forma:
Email;Nome
firstname.lastname@example.com;Teste1
email@example.com;Teste2
firstname.lastname@example.com;Teste3
email@example.com;Teste4

Nas linhas ele põe os nome dos campos divididos por ; (ponto e virgula), então tudo que você precisa fazer é colocar a primeira linha dentro de um array e contar o lenght desse array assim você tem o número de colunas ai você pode verificar se o mesmo é igual a 9 se for verdadeiro converter se não retornar mensagem de invalido
OBS: Deve haver uma maneira mais fácil de verificar colunas / campos nos arquivos csv, só estou dando uma sugestão do que pode ser feito


Black Ball: Can a player win a game by first hitting an opponents ball on a free shot?

Question: In a game where where player 1 is on black and player 2 still has balls remaining on the table. Given the scenarios where player 2 commits a foul giving player 1 a free shot, then on that free shot player 1 first hits one of player 2's remaining balls before sinking the black on the same shot. Does player 1 win in this case? If not, what is the correct flow of play following this?
The WPA rule book states that the "Wrong Ball First" rule is suspended on free shots. However, does this still apply on the black given that you are essentially winning off a foul shot?
Using this version of the rule book for reference: http://wpapool.co.za/wp-content/uploads/2017/03/WPA_New_Rules.pdf
Answer: The shooter wins the rack if they sink the black ball, and do not commit a foul under the rules.
As it is a free shot, the shooter cannot be called foul under 6.2 Wrong Ball First.
They may of course shoot the cue ball into the opponent ball, so that it contacts the black ball and sinks it.
As this meets the conditions of the introduction to part 5 for winning the rack, they have won, subject to not making an illegal shot and breaching rule 5.14, part (a) for a Loss of Rack foul.
Answer: You lose as shot was not called in that manner, i.e. white off opponent's ball first, if called that way is all good. Must call black pocket and if not obvious and easy, how as well, especially if hitting opponent's ball first.
Imagine my black over hole being covered with opponent's ball and I have ball in hand. I must call opponent's ball to pot black for win as unable to hit black directly with white.
Comment: the OP posted the rules. Can you point which rules apply in this situation?
Comment: The rules **do not** require calling the method of the shot or any details **at all**. This answer is completely wrong.
Answer: Player 1 loses in this game. Why?:

8-ball made on an illegal shot: As player 1 has called 8-ball and the pocket, he cannot make contact with any other ball first.
Comment: This is not correct. No shot needs to be called, and it is legal to hit the opponent's object ball first if taking a free shot.
Comment: any reference to support it?
Comment: They're literally the rules of the game. Blackball is not a called shot game, so even saying "called 8-ball" makes the answer wrong. The full rules of blackball are provided in the question itself, see section **5 Blackball**.


Dynamics CRM Online Business Rules for child grids

Question: Can you create business rules based on child grids?
When creating an Opportunity there is a grid called "Sales Team" and a field called "Identify Sales Team".
I would like to create the following business rules when creating an Opportunity or moving it between stages in the workflow Process.

User must enter at least one row in the Sales Team grid.
The Identify Sales Team value is set to "Mark Complete" when no rows. If one or more rows are added then the Identify Sales Team value is set to "Complete".

How can this be done?
Answer: Not using business rules as far as I know.
You can use JavaScript to count the number of records in a sub grid, then set the field conditionally in JavaScript.
<code>var count = Xrm.Page.getControl("sales_team_grid").getGrid().getTotalRecordCount();

if(count > 0) {
... set your field value
}
</code>
Comment: Thanks. I just discovered how to use JavaScript in Web Resources. This looks like it will work for me. It would be nice if Business Rules could be used as they are not reliant on the UI.


Solving the inhomogeneous wave equation in polar coordinates?

Question: Imagine you have the following wave equation, with an excitation term $\mu/r^2$:
$$
\frac{1}{c^2}\frac{\partial^2 \psi}{\partial t^2} - \Delta \psi = \frac{\mu}{r^2}
$$
$$
\frac{1}{c^2}\frac{\partial^2 \psi}{\partial t^2} - \frac{\partial^2 \psi}{\partial r^2} - \frac{1}{r}\frac{\partial \psi}{\partial r} - \frac{1}{r^2} \frac{\partial^2  \psi}{\partial \theta^2} = \frac{\mu}{r^2}
$$
Using separation of variables: $\psi(r, \theta, t) = \phi(r, \theta)  T(r)$:
$$
\frac{d^2T}{dt^2} = - k^2
c^2 T\\ \; \\
\frac{\partial^2 \phi}{\partial r^2} + \frac{1}{r}\frac{\partial \phi}{\partial r} + \frac{1}{r^2} \frac{\partial^2  \phi}{\partial \theta^2} - \frac{\mu}{r^2} =-k^2\phi
$$
The first equation is simply harmonic motion:
$$
T(t) \propto e^{ikc t}
$$
The second one is a little bit trickier. Because of the linearity of the equation I started solving the homogeneous equation:
$$
\frac{\partial^2 \phi}{\partial r^2} + \frac{1}{r}\frac{\partial \phi}{\partial r} + \frac{1}{r^2} \frac{\partial^2  \phi}{\partial \theta^2} = -k^2\phi \\ \; \\
\phi(r, \theta) \propto J_m(kr)e^{im\theta}
$$
Where $J_m(x)$, is the Bessel Function of first kind.
Then I assumed a particular solution would look like:
$$
\phi(r, \theta) = u(r, \theta) J_m(kr)e^{im\theta}
$$
And my problem would be reduced to find $u(r, \theta)$. But, I cannot continue. Could someone help? What I'm doing wrong? Any hint?
Answer: If you have in inhomogenous term only dependent on $r$, you should definitly do a seperation of variables for $r$ and not $t$. In fact, as @naturallyInconsistent has already pointed out, you can even do a seperation of variables for all three of them. I don't know if this is what you want, or if you want to keep it more general by using $\phi(r,\vartheta)$, but just in case I have written down the calculations for seperating all three variables:
With $\psi(t,r,\vartheta)=T(t)R(r)\Theta(\vartheta)$ you get:
$$\frac{\mathrm{d}^2T}{\mathrm{d}t^2}
=-k^2c^2T$$
$$\frac{\mathrm{d}^2R}{\mathrm{d}r^2}
+\frac{1}{r}\frac{\mathrm{d}R}{\mathrm{d}r}
=\frac{1}{r}\frac{\mathrm{d}}{\mathrm{d}r}\left(r\frac{\mathrm{d}R}{\mathrm{d}r}\right)
=-\left(\frac{C}{r^2}+k^2\right)R$$
$$\frac{\mathrm{d}^2\Theta}{\mathrm{d}\vartheta^2}+\mu
=C\Theta$$
with a constant $C\in\mathbb{R}$. (Keep in mind here, that from your second equation to your forth equation, the sign in front of $\mu$ has switched. I kept the upper sign.) If you now multiply the first equation with $R\Theta$ and divide by $c^2$, multiply the second equation with $T\Theta$ and multiply the third equation with $TR$ and divide by $r^2$ and then substract the second and the third equation from the first, you get exactly your wave equation.

The equation for $T$ can be solved quite easily with the exponential function as you have already explained. The solution is $T(t)=e^{ikct}$.
The equation for $\Theta$ can be simplified, when replacing $\Theta$
with $\widetilde\Theta=\Theta-\frac{\mu}{C}$ to get $\frac{\mathrm{d}^2\widetilde\Theta}{\mathrm{d}\vartheta^2}
=C\widetilde\Theta$. Since $\Theta$ (and therefore $\widetilde\Theta$) is periodic with $\Theta(\vartheta+2\pi)=\Theta(\vartheta)$ (or $\widetilde\Theta(\vartheta+2\pi)=\widetilde\Theta(\vartheta)$), a suitable choice for $C$ is $-n^2$ with a natural $n$, so that $\Theta(\vartheta)=a\sin(n\vartheta)+b\cos(n\vartheta)+\frac{\mu}{n^2}$ with constants $a,b\in\mathbb{R}$.
Answer: You have quite a few mistakes. You have sign mistakes.
And then it is weird that you knew how to do separation of variables to get the time dependence out. Why do you not see that angle dependence is also the same? Then you would have an equation purely for the radial dependence, and the solution should look like Bessel too, just with some alteration. You have to be consistent in how to apply the mathematical machinery.


How to reduce dimensionality of audio data that comes in form of matrices and vectors?

Question: I'm working on a project involved with identifying different types of sounds (such as screams, singing, and bangs) from each other.  We've got our data a reasonable number of different transformations (e.g.: spectrograms, chromagrams, MFCCs, etc.), but since most of our features are 2-dimensional matrices (some are actually 1-dimensional vectors), we'd like to reduce this information in some way, so that the machine learning we're hoping to do takes a "feasible" amount of time. However, I don't quite know enough about math and statistics to make an educated decision on this.
Our data consists of small sound files from ~1-10 seconds long.  There are recordings of screams, singing, bangs (and other man-made noises), and birds (and other natural noises).  We are hoping to be able to differentiate and identify each source type from the others.  See https://github.com/BenSandeen/surveillance_sound_classifier/blob/master/Project.ipynb for the different plots we have made to guide our selection of features to use.  Focus mainly on the 3x3 plots, as that's where the comparisons are being made.  These plots are primarily time vs. frequency, with amplitude represented by color.
I was thinking that maybe we could "collapse" each matrix down to a vector by somehow choosing some representative frequency/amplitude-related feature at each time slice (we're using Short Time Fourier Transforms to analyze the sounds) and then get a vector of some length, containing a bunch of scalars.  Although this could make accounting for different lengths of sounds difficult.  Would it be reasonable to just set the shorter sounds' vectors to be filled in with zeros if they have no useful data?  That would effectively make these sounds a projection onto some lower-dimensional space.  Then, maybe we could just use dot products to compare the vectors; if they're parallel, they'll have a large for product, but of they're nearly perpendicular, they'll have a dot product near zero.
Alternatively, I was thinking that something like a trace of our matrices, or finding their characteristic polynomial, might be useful direction to pursue.  I've read a bit about PCA, but I'm not quite understanding it enough to know if this may be what I'm looking for.
Can anyone think of any other ways of handling and reducing this data?  For what it's worth, we're currently planning on using Sci-Kit Learn (sorry that I can't use more than 2 links yet) to perform our machine learning.
Comment: Define a 2D basis and project them there. Commonly people concatenate matrices in vectors (eg. when using [eigenfaces](https://en.wikipedia.org/wiki/Eigenface) but 2DPCA implementation exists too (eg. [here](http://www.dtic.upf.edu/~afrangi/articles/pami2004.pdf) and [here](http://www.cis.pku.edu.cn/faculty/vision/wangliwei/pdf/Equivalence_2DPCA.pdf)). As for the different lengths: 1. Either define a utterance time 2. segment them accordingly.
Comment: Cool. Sorry I am having a deadline approach like a freight train, I will write something more extensive soon.
Answer: Looking at the task described I think you are dealing with a somewhat classical problem of classifying images albeit in more abstract form. In your case you want to classify spectrograms rather than standard images. I would suggest you look at image classification or spectrogram classification tutorials online.
Having said this general advice: A standard way to reduce your data would be to use principal component analysis. I think you tried to do somewhat gave up half-way in the notebook you attach. In any case, you would do something like this:

Transform your matrix dataset  into vectors. (ie. if you have 100 50$ \times$ 50 matrices, you will now have 100 2500-element vectors; see here for more information on the equivalence of two-dimensional PCA to line-based PCA)
Use PCA to derive the principal components $\phi$ (You will possibly deal with a $n << p$ situation, see here and here for some first steps).
Use $\phi$ to get the principal component scores $\xi$ (the projected data essentially).
Use $\xi$ as surrogate data for your original sample, ie. you classify your sample using these. (I would personally suggesting using a logistic regression first before moving to more exotic beasts (eg. decision trees, boosting, etc.))

The only real restriction you must take care of is  the need for the matrices holding your spectrograms to be of the same sizes. You can achieve that in multiple ways; you need to either define a representative  utterance time (so you practically interpolate all your sample onto a common time-grid) or you segment your utterance accordingly. Both options are slightly messy because you will need to do quite a bit of data wrangling. I have worked with human utterances in the past and that was somewhat "easy" because there is the concept of a word (usually) but the principal is the same; you want the space over your data are recorded to be the same for all data and if possible to have a physical interpretation.
You may want to consider using 2D Wavelets as a basis instead of the principal components suggested by PCA. 2D wavelets are localised on time and frequency so that should give you a more informative representation than say a Fourier polynomial basis that is focusing on frequency only. I am not a frequent Python user but Python seems to have some implementation on this matter already (eg. pywavelets) if you want to experiment on this.
Additional points:

Check the noise in your sample. Usually statistical samples are assumed to have the same amount of "noise" in them (by noise I mean unstructured variance). Recording almost always do not have this luxury. Different recording environments, different equipment, etc. can lead to a lot heteroskedasticity. You will probably need to denoise your data first.
Check your sample for frequency artefacts. Sound recording are finite representations of a infinite process (a wave). A large diverse sample usually has recording on different sampling frequencies. Before starting you want all your sampling frequencies to be similar because otherwise you risk aliasing artefacts.


How to ping UDP in php

Question: I have a question about pinging certain game servers to see if they are alive or not, most work fine with just your standard PHP ping but others are from steam... and steam is making it more difficult for me to just send a ping to see if it is alive or not, i tried Steam Condenser but... have no idea how to use it since there is no documentation.
my question
how can i ping UDP game servers such as Arma 2, Arma 3, etc. this is what i tried:
<code>        $host = '184.108.40.206';
        $port =  1234;
        $waitTimeoutInSeconds = 7;
        if($fp = fsockopen("udp://".$host,$port,$errCode,$errStr))
        {
           echo 'Online';
        }
        else
        {
           echo 'Offline';
        }
</code>
the problem with that is that i always get "true" returned no matter what IP or port i use, how can i make this work?
EDIT
I also tried
<code>        $host = '220.127.116.11';
        $port = 1234;
        $waitTimeoutInSeconds = 7;
        if($fp = fsockopen("udp://".$host,$port,$errCode,$errStr))
        {
            $write = fwrite($fp,"x00");
            if (!$write)
            {
            echo 'offline';
            }
            else
            {
                echo 'online';
            }
        }
        else
        {
           echo 'offline';
        }
        fclose($fp);
</code>
however with this one i get error code 0 which seems to be a problem with the initializing of the socket?
Answer: What about using the OS's ping utility, execute terminal ping command using PHP. You can read it here : http://php.net/manual/en/function.shell-exec.php
Comment: The ping utility does not allow you to ping specific port on you remote server
Answer: I tried this one, by removing the "udp://" :
<code> $host = '184.108.40.206';
 $port =  1234;
 $waitTimeoutInSeconds = 7;
 if($fp = fsockopen($host,$port,$errCode,$errStr))
 {
    echo 'Online';
 }
 else
 {
    echo 'Offline';
 }
</code>
And it works. Here is the return text :
Warning: fsockopen(): unable to connect to 184.108.40.206:1234 (A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. ) in C:\xampp\htdocs\test.php on line 6
Offline
It don't think you should put the "udp://" because just using the port number is enough.
Comment: But that is how you tell it is UDP or else it defaults to TCP.

How to ping UDP in php


RaspberryPi HLS streaming with nginx and ffmpeg; v4l2 error: ioctl(VIDIOC_STREAMON): Protocol error

Question: I'm trying to realize a baby monitoring with a Raspberry Pi (Model 4B, 4GB RAM) and an ordinary Webcam (with integrated Mic).
I followed this Tutorial: https://github.com/DeTeam/webcam-stream/blob/master/Tutorial.md
Shortly described:

I installed and configured an nginx server with rtmp module enabled.
I installed ffmpeg with this configuration --enable-gpl --enable-nonfree --enable-mmal --enable-omx-rpi
I tried to stream ;)

The configuration of nginx seems to be working (sometimes streaming works, the server starts without any complication and when the server is up and running, the webpage is displayed).
The configuration of ffmpeg seems to be fine as well, since streaming sometimes works...
I was trying a couple of different ffmpeg-commands; all of them are sometimes working and sometimes resulting in an error.
The command looks like following:
ffmpeg -re
-f v4l2
-i /dev/video0
-f alsa
-ac 1
-thread_queue_size 4096
-i hw:CARD=Camera,DEV=0
-profile:v high
-level:v 4.1
-vcodec h264_omx
-r 10
-b:v 512k
-s 640x360
-acodec aac
-strict
-2
-ac 2
-ab 32k
-ar 44100
-f flv
rtmp://localhost/show/stream;

Note: I rearranged the code to make it easier to read. In the terminal, it is all in one line.
Note: There is no difference when using -f video4linux2 instead of -f v4l2
The camera is recognized by the system:
pi@raspberrypi:~ $ v4l2-ctl --list-devices
bcm2835-codec-decode (platform:bcm2835-codec):
    /dev/video10
    /dev/video11
    /dev/video12

bcm2835-isp (platform:bcm2835-isp):
    /dev/video13
    /dev/video14
    /dev/video15
    /dev/video16

HD Web Camera: HD Web Camera (usb-0000:01:00.0-1.2):
    /dev/video0
    /dev/video1

When only using -i /dev/video0, audio transmission never worked.
The output of arecord -L was:
pi@raspberrypi:~ $ arecord -L
default
    Playback/recording through the PulseAudio sound server
null
    Discard all samples (playback) or generate zero samples (capture)
jack
    JACK Audio Connection Kit
pulse
    PulseAudio Sound Server
usbstream:CARD=Headphones
    bcm2835 Headphones
    USB Stream Output
sysdefault:CARD=Camera
    HD Web Camera, USB Audio
    Default Audio Device
front:CARD=Camera,DEV=0
    HD Web Camera, USB Audio
    Front speakers
surround21:CARD=Camera,DEV=0
    HD Web Camera, USB Audio
    2.1 Surround output to Front and Subwoofer speakers
surround40:CARD=Camera,DEV=0
    HD Web Camera, USB Audio
    4.0 Surround output to Front and Rear speakers
surround41:CARD=Camera,DEV=0
    HD Web Camera, USB Audio
    4.1 Surround output to Front, Rear and Subwoofer speakers
surround50:CARD=Camera,DEV=0
    HD Web Camera, USB Audio
    5.0 Surround output to Front, Center and Rear speakers
surround51:CARD=Camera,DEV=0
    HD Web Camera, USB Audio
    5.1 Surround output to Front, Center, Rear and Subwoofer speakers
surround71:CARD=Camera,DEV=0
    HD Web Camera, USB Audio
    7.1 Surround output to Front, Center, Side, Rear and Woofer speakers
iec958:CARD=Camera,DEV=0
    HD Web Camera, USB Audio
    IEC958 (S/PDIF) Digital Audio Output
dmix:CARD=Camera,DEV=0
    HD Web Camera, USB Audio
    Direct sample mixing device
dsnoop:CARD=Camera,DEV=0
    HD Web Camera, USB Audio
    Direct sample snooping device
hw:CARD=Camera,DEV=0
    HD Web Camera, USB Audio
    Direct hardware device without any conversions
plughw:CARD=Camera,DEV=0
    HD Web Camera, USB Audio
    Hardware device with all software conversions
usbstream:CARD=Camera
    HD Web Camera
    USB Stream Output

that's why i added -i hw:CARD=Camera,DEV=0.
As mentioned above, it worked very well a couple of times with this configuration and commands.
But very often, i get the following error message when starting to stream:
pi@raspberrypi:~ $ ffmpeg -re -f video4linux2 -i /dev/video0 -f alsa -ac 1 -thread_queue_size 4096 -i hw:CARD=Camera,DEV=0 -profile:v high -level:v 4.1 -vcodec h264_omx -r 10 -b:v 512k -s 640x360 -acodec aac -strict -2 -ac 2 -ab 32k -ar 44100 -f flv rtmp://localhost/show/stream
ffmpeg version N-100673-g553eb07737 Copyright (c) 2000-2021 the FFmpeg developers
  built with gcc 8 (Raspbian 8.3.0-6+rpi1)
  configuration: --enable-gpl --enable-nonfree --enable-mmal --enable-omx-rpi --extra-ldflags=-latomic
  libavutil      56. 63.101 / 56. 63.101
  libavcodec     58.117.101 / 58.117.101
  libavformat    58. 65.101 / 58. 65.101
  libavdevice    58. 11.103 / 58. 11.103
  libavfilter     7. 96.100 /  7. 96.100
  libswscale      5.  8.100 /  5.  8.100
  libswresample   3.  8.100 /  3.  8.100
  libpostproc    55.  8.100 / 55.  8.100
[video4linux2,v4l2 @ 0x2ea4600] ioctl(VIDIOC_STREAMON): Protocol error
/dev/video0: Protocol error

And when I'm swithing to /dev/video1 (since this was also an output for v4l2-ctl --list-devices), I get the following error message:
pi@raspberrypi:~ $ ffmpeg -re -f v4l2 -i /dev/video1 -f alsa -ac 1 -thread_queue_size 4096 -i hw:CARD=Camera,DEV=0 -profile:v high -level:v 4.1 -vcodec h264_omx -r 10 -b:v 512k -s 640x360 -acodec aac -strict -2 -ac 2 -ab 32k -ar 44100 -f flv rtmp://localhost/show/stream
ffmpeg version N-100673-g553eb07737 Copyright (c) 2000-2021 the FFmpeg developers
  built with gcc 8 (Raspbian 8.3.0-6+rpi1)
  configuration: --enable-gpl --enable-nonfree --enable-mmal --enable-omx-rpi --extra-ldflags=-latomic
  libavutil      56. 63.101 / 56. 63.101
  libavcodec     58.117.101 / 58.117.101
  libavformat    58. 65.101 / 58. 65.101
  libavdevice    58. 11.103 / 58. 11.103
  libavfilter     7. 96.100 /  7. 96.100
  libswscale      5.  8.100 /  5.  8.100
  libswresample   3.  8.100 /  3.  8.100
  libpostproc    55.  8.100 / 55.  8.100
[video4linux2,v4l2 @ 0x1aa4610] ioctl(VIDIOC_G_INPUT): Inappropriate ioctl for device
/dev/video1: Inappropriate ioctl for device

When using the video0 input, the webcam's LED that recognizes an access is constantly on. When using video1not.
After hours and days of googling and tears and whiskey, for the sake of my liver, my marriage and my physical and mental health, I'm very sincerly asking for your help...
What the f**k is happening and what can I do to make it work???
Thanks everybody :)
UPDATE 1:

using the full path to ffmpeg does not change anything...
/dev/video0 and /dev/video1 have access rights for everybody
sudo ffmpeg ... does not change anything as well
the problem seems to be at an "early stage". Stripping the command down to ffmpeg -i /dev/video0 results in the same problem

UPDATE 2:
It seems that everything is working when I first start another Application that needs access to the webcam and then ffmpeg...
Might be some driver issue, but when I'm looking for loaded modules with lsmod, there is absolutely no change before and after I started the application...
Any help still appreciated...
UPDATE 3:
I was checking the output of dmesg.
When I started the first application I received this message:
uvcvideo: Failed to query (GET_DEF) UVC control 12 on unit 2: -32 (exp. 4).
And when I started ffmpeg, nothing happend but everything worked...
Answer: I got the same issue, noticed your UPDATE 2 and did the following (python):
for i in range(3):
    cam1 = cv2.VideoCapture(0)
    ret, frame = cam1.read()
    cam1.release()
cam1 = cv2.VideoCapture(0)

Now I still get the error message (only once), but the camera works fine.
No idea why or how, but... this is the way (apparently)
Comment: Any more context for this code, like a library import? I get "NameError: name 'cv2' is not defined"


Random variables and co-variance, Statistics 318

Question: For the given example in the book

John E. Freund's Mathematical Statistics with Applications, 8th edition, by Miller and Miller. ISBN: 9780321807090

I've highlighted using colors what numbers corespond with what is given (Blue, Green, and Yellow).
What I don't understand is where the highlighted red numbers come from.

The example states it uses "Theorem 15" I'm just confused on how.
"The following is another important theorem about linear combinations of random
variables; it concerns the covariance of two linear combinations of n random
variables."
Comment: You´ve comprehended the answer of parsaid within 5 seconds. Congrats.
Comment: @callculus well to be fair I continued to work through the problem and I figured it out on my own and as I was working through it I saw the answer was posted, and the answer goes along with what I figured out so I figured I would select it as answered to help others out and since it is correct. So not quite 5 seconds haha but thanks!
Comment: I was just wondering. Thanks for your reply.
Answer: Hint: Define $X_{1}=X$, $X_{2}=Y$, and $X_{3}=Z$.
Also define $a_{1}=1$, $a_{2}=4$, $a_{3}=2$, $b_{1}=3$, $b_{2}=-1$, and $b_{3}=-1$. Then,
$$
\text{cov}(X+4Y+2Z,3X-Y-Z)
=\text{cov}(\underbrace{a_{1}X_{1}+a_{2}X_{2}+a_{3}X_{3}}_{Y_1},\underbrace{b_{1}X_{1}+b_{2}X_{2}+b_{3}X_{3}}_{Y_2}).
$$
The above now looks like the expression in Theorem 15. Can you finish?


Systems of equations question

Question: \begin{align*}a^a\cdot b^b\cdot c^c\cdot d^d&=\frac12\\a+b+c+d&=1\end{align*}
How can we find solutions for this system of equations given that $a, b, c, d > 0$ ?
Comment: If you try $a = 0.97, b =c=d= 0.01$, you get [0.845...](http://www.wolframalpha.com/input/?i=0.97%5E0.97+*+%5B0.01%5E0.01%5D%5E3). If you try $ a = 0.7, b=c=d=0.1$, you get [0.390...](http://www.wolframalpha.com/input/?i=0.7%5E0.7+*+%5B0.1%5E0.1%5D%5E3). There has to be a solution in the line between the two. Slight perturbations would also yield a solution.
Comment: Must the values be positive?
Comment: There seems to be infinitely many solutions, with one of the values quite close to 1. I don't think you can find a simple description of the solution set.
Answer: The system you described is a system of 2 equations with 4 unknowns. To obtain a unique solution you need 4 independent equations. Since you have two, it means you have two free variables. You need to assume values for those two free variables and solve for the other two using the given equations.
Since it is a condition that all numbers are greater than zero and their summation is 1. The values of the assumed free variables has to be between zero and one

Systems of equations question


Anonymise Webform submission in database

Question: I am asked to modify the behavior of some webforms on a Drupal 8 instance; data who could identify a user submitting a form should not be stored in the database. Submissions must be sent by email though.
Webforms do have a "Disable saving of submissions" option, however, some of the forms have file fields; files that must be sent as attachements to the mail I mentionned, and those forms cannot work if I activate the option.
I tried creating my own Webform handler but I couldn't find a way to successfully alter submission there. I managed to alter data by using a custom validation class but as I suspected, the data is altered before it gets emailed.
Drupal 'Cron' tasks won't do it either. The legal team asks that the data does not persist in database longer than the time required by the processing of the form.
I may be blind, but am running out of ideas and cannot find a relevant documentation for my problem.
TL;DR: On webforms with file fields, how can I prevent storage of specific fields in the database or rewrite them while still sending the original data by email
Answer: I would intercept on the redirect/thank you page after form submission assuming the mail is send directly (is it).
See modules/webform/src/EventSubscriber/WebformSubscriber.php where <code>$webform_submission = WebformSubmission::load($route_parameters['webform_submission']);
</code>.
You probably need to override the service webform.event_subscriber defined in webform.services.yml


How to get iOS device MAC address programmatically

Question: How do I get an iOS device's MAC code programmatically in my app?
Comment: Once check this link http://stackoverflow.com/questions/677530/how-can-i-programmatically-get-the-mac-address-of-an-iphone
Comment: Also this link http://developer.apple.com/library/mac/#samplecode/GetPrimaryMACAddress/Introduction/Intro.html
Answer: Now  iOS 7 devices – are always returning a MAC address of 02:00:00:00:00:00.
So better use [UIDevice identifierForVendor]
so better to call this method to get app specific unique key
Category will more suitable
#import "UIDevice+Identifier.h"

- (NSString *) identifierForVendor1
{
    if ([[UIDevice currentDevice] respondsToSelector:@selector(identifierForVendor)]) {
        return [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    }
    return @"";
}

Now call above method to get unique address
NSString *like_UDID=[NSString stringWithFormat:@"%@",
                [[UIDevice currentDevice] identifierForVendor1]];

NSLog(@"%@",like_UDID);

Answer: You can get the MAC Adress using the following function:
+(NSString *)getMacAddress
{
    int                 mgmtInfoBase[6];
    char                *msgBuffer = NULL;
    NSString            *errorFlag = NULL;
    size_t              length;

    // Setup the management Information Base (mib)
    mgmtInfoBase[0] = CTL_NET;        // Request network subsystem
    mgmtInfoBase[1] = AF_ROUTE;       // Routing table info
    mgmtInfoBase[2] = 0;
    mgmtInfoBase[3] = AF_LINK;        // Request link layer information
    mgmtInfoBase[4] = NET_RT_IFLIST;  // Request all configured interfaces

    // With all configured interfaces requested, get handle index
    if ((mgmtInfoBase[5] = if_nametoindex("en0")) == 0)
        errorFlag = @"if_nametoindex failure";
    // Get the size of the data available (store in len)
    else if (sysctl(mgmtInfoBase, 6, NULL, &length, NULL, 0) < 0)
        errorFlag = @"sysctl mgmtInfoBase failure";
    // Alloc memory based on above call
    else if ((msgBuffer = malloc(length)) == NULL)
        errorFlag = @"buffer allocation failure";
    // Get system information, store in buffer
    else if (sysctl(mgmtInfoBase, 6, msgBuffer, &length, NULL, 0) < 0)
    {
        free(msgBuffer);
        errorFlag = @"sysctl msgBuffer failure";
    }
    else
    {
        // Map msgbuffer to interface message structure
        struct if_msghdr *interfaceMsgStruct = (struct if_msghdr *) msgBuffer;

        // Map to link-level socket structure
        struct sockaddr_dl *socketStruct = (struct sockaddr_dl *) (interfaceMsgStruct + 1);

        // Copy link layer address data in socket structure to an array
        unsigned char macAddress[6];
        memcpy(&macAddress, socketStruct->sdl_data + socketStruct->sdl_nlen, 6);

        // Read from char array into a string object, into traditional Mac address format
        NSString *macAddressString = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",
                                      macAddress[0], macAddress[1], macAddress[2], macAddress[3], macAddress[4], macAddress[5]];
        if(IsDEBUG) NSLog(@"Mac Address: %@", macAddressString);

        // Release the buffer memory
        free(msgBuffer);

        return macAddressString;
    }

    // Error...
    if(IsDEBUG) NSLog(@"Error: %@", errorFlag);

    return errorFlag;
}

But as he said #Randomclik, mac address is unavailable from ios 7 and up.
form apple:
In iOS 7 and later, if you ask for the MAC address of an iOS device, the system returns the value 02:00:00:00:00:00. If you need to identify the device, use the identifierForVendor property of UIDevice instead. (Apps that need an identifier for their own advertising purposes should consider using the advertisingIdentifier property of ASIdentifierManager instead.)
link:
https://developer.apple.com/library/prerelease/ios/releasenotes/General/WhatsNewIniOS/Articles/iOS7.html#//apple_ref/doc/uid/TP40013162-SW1
Conversation about MAC Address:
How can I programmatically get the MAC address of an iphone
Answer: It seems that in iOS 7 and later get MAC addres will not work. Look at What's new on iOS document from Apple. (Deprecated APIs section.)
Answer: everybody is good advised to use the offical ios 7 way and use [UIDevice identifierForVendor]
http://developer.apple.com/library/ios/#documentation/uikit/reference/UIDevice_Class/Reference/UIDevice.html
And also think about the migration from some older assumptions.
Answer: You can get it by combining the following two answers i guess.
First, find ip of the device by using the following:
https://stackoverflow.com/a/30754194/1089206
Second, find the MAC of that address, by using the following:
https://stackoverflow.com/a/31246085/1089206
I'll be trying it out now and will let you know how it goes.
Comment: please avoid using links. Yes, even in SO. Please change the links to a short summary of what it says there. There is no problem to add the link as an addition, but this is not an easy way to understand the answer.
Answer: Actually it seems possible to get macaddr even on iOS >= 7 the information comes from this blog and the solution is based on ipV6.
I have tested on iPhone12 running under 15.5 and it works fine.
Here is the interesting code:
func GetMACAddress(){
    let address = getAddress()
    macAddressLabel = GetMACAddressFromIPv6(ip: address ?? "")
    print(macAddressLabel)
}

func GetMACAddressFromIPv6(ip: String) -> String{
    let IPStruct = IPv6Address(ip)
    if(IPStruct == nil){
        return ""
    }
    let extractedMAC = [
        (IPStruct?.rawValue[8])! ^ 0b00000010,
        IPStruct?.rawValue[9],
        IPStruct?.rawValue[10],
        IPStruct?.rawValue[13],
        IPStruct?.rawValue[14],
        IPStruct?.rawValue[15]
    ]
    let str = String(format: "%02x:%02x:%02x:%02x:%02x:%02x", extractedMAC[0] ?? 00,
        extractedMAC[1] ?? 00,
        extractedMAC[2] ?? 00,
        extractedMAC[3] ?? 00,
        extractedMAC[4] ?? 00,
        extractedMAC[5] ?? 00)
    return str
}

// this function was taken from
// https://stackoverflow.com/a/30754194/3508517
//and is slightly modified:
func getAddress() -> String? {
    var address: String?

    // Get list of all interfaces on the local machine:
    var ifaddr: UnsafeMutablePointer<ifaddrs>?
    guard getifaddrs(&ifaddr) == 0 else { return nil }
    guard let firstAddr = ifaddr else { return nil }

    // For each interface ...
    for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
        let interface = ifptr.pointee

        // Check IPv6 interface:
        let addrFamily = interface.ifa_addr.pointee.sa_family
        if addrFamily == UInt8(AF_INET6) {
            // Check interface name:
            let name = String(cString: interface.ifa_name)
            if name.contains("ipsec") {

                // Convert interface address to a human readable string:
                var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.pointee.sa_len),
                            &hostname, socklen_t(hostname.count),
                            nil, socklen_t(0), NI_NUMERICHOST)
                address = String(cString: hostname)
                let ipv6addr = IPv6Address(address ?? "::")
                if(ipv6addr?.isLinkLocal ?? false){
                    return address
                }
            }
        }
    }
    freeifaddrs(ifaddr)

    return address
}


Umbraco add custom Document Type

Question: Is it possible to add a custom control to the Document Type? Suppose i couldn't create a multiselect or just a simple textfield control. How could i create a custom one and use that from the Document Type page in Umbraco?
If this is possible, then what steps need to be taken? Because i can add all sorts of config information in the Document Type controls that currently exist in there. Like, when i add a textfield i can gvie it a name, an alias and a validation message (and it has some others options).
Do i have to build the custom Document Type control in a specific way? And how is it saved to the database? How does Umbraco handle that?
Any information on this matter is more than welcome!
Answer: Since adding custom document types is native to Umbraco, and judging by the description in your question, I'm going to assume that you are talking about adding custom data types with user controls.
If so, check some of the following links on the subject, it's actually fairly simple:

Creating custom datatypes using the umbraco usercontrol wrapper (I personally used this one)
Custom DataTypes in Umbraco
Creating a custom datatype using the usercontrol wrapper (Video tutorial)

Umbraco add custom Document Type


Como colocar uma variável de php em uma query do mysql?

Question: Por exemplo:
$query = "INSERT INTO tabela (data, assunto, destino, elaborado) VALUES('{$data}', '{$assunto}', '{$destino}', '{$elaborado}')";

Onde está tabela, eu quero colocar uma variável no lugar, pois dependendo do que o usuário escolher, vai usar uma tabela diferente.
Já tentei com aspas, com ponto, com chaves...
Comment: Isto responde à sua pergunta? [Como prevenir injeção de código SQL no meu código PHP?](https://pt.stackoverflow.com/questions/3864/como-prevenir-inje%c3%a7%c3%a3o-de-c%c3%b3digo-sql-no-meu-c%c3%b3digo-php)
Answer: No PHP quando você tem uma string envolvida com aspas duplas. O interpretador PHP irá percorrer a mesma e verificar se não tem nenhuma variável para ser substituída.
<?php
$tabela = 'Tabela1';
$data = '2018-06-20';
$assunto = 'Assunto';
$destino = 'Destino';
$elaborado = 'Elaborado';

$query = "INSERT INTO $tabela (data, assunto, destino, elaborado)
VALUES('$data', '$assunto', '$destino', '$elaborado')";

echo $query;

O trecho echo $query; irá imprimir INSERT INTO Tabela1 (data, assunto, destino, elaborado) VALUES('2018-06-20', 'Assunto', 'Destino', 'Elaborado')
Answer: A resposta do Thiagosilr está correta, basta colocar os nomes das variáveis dentro da string com aspas duplas. Entretanto, sugiro não utilizar esse método para formar queries a serem executadas no seu banco, pois o torna vulnerável  a ataques de injeção de SQL.
Por exemplo, se o usuário tem controle do conteúdo da variável $assunto através de um formulário, poderia preenchê-lo como '1'); DROP DATABASE ... e tentar destruir seu banco só de pirraça.
Uma forma de executar esse mesmo INSERT garantindo que as variáveis de entrada não causem estrago é utilizando prepared statements, como demonstrado nas respostas para esta pergunta do SOE.
Assim, se estiver usando MySQLi, você instancia um objeto de statement usando o método prepare() de seu objeto de conexão, especificando as lacunas para parâmetros de bind usando pontos de interrogação, depois passa os parâmetros em ordem no método bind_param() do statement por fim o executa:
//cria o statement
$statement = $dbConnection->prepare("INSERT INTO $tabela (data, assunto, destino, elaborado) VALUES(?, ?, ?, ?)");

//passa as  variáveis para preencher os pontos de interrogação
//o parametro 's' significa que você está passando uma string. É como um printf...
$statement->bind_param('s', $data);
$statement->bind_param('s', $assunto);
$statement->bind_param('s', $destino);
$statement->bind_param('s', $elaborado);

//executa o statement
$stmt->execute();

Note que um prepared statement só suporta que sejam parametrizados os valores de uma query. Assim, a variável de nome da tabela deve ser passada com concatenação de string simples como na resposta do Thiago. Imagino que seja algo pouco provável que tal variável seja um vetor de ataque, uma vez que é algo pouco usual permitir que o usuário de uma aplicação decida sobre qual tabela do sistema pretende consultar.
Answer: Uma forma é usar da seguinte forma:
$query = "INSERT INTO tabela (data, assunto, destino, elaborado) VALUES({$data}, {$assunto}, {$destino}, {$elaborado})";

Sem as aspas simples.
Comment: Você fez exatamente o mesmo da pergunta, só que piorou, porque removeu os apóstrofos, logo provavelmente vai ter erro de sintaxe na hora de executar. Tem 2 respostas já na pergunta, mas aparentemente você não se deu ao trabalho de ler elas e saiu presumindo uma "solução", recomendo que leia, estudo e depois tente sugerir algo, porque se não você vai ensinar os seus erros para pessoas que estão aqui para aprender.
Comment: Sem as aspas simples, o MySQL não irá considerar os valores como strings; sem contar que desta forma abre espaço para SQL injection como comentado na resposta do nunks.


MODIFY_PHONE_STATE permission required for endCall on Oreo

Question: I made an app to block some incoming calls. The app seems running well and done the job.
But recently I tried on an android 8.0 phone and crashed.
java.lang.SecurityException: MODIFY_PHONE_STATE permission required.
at android.os.Parcel.readException(Parcel.java:2005)
at android.os.Parcel.readException(Parcel.java:1951)
at com.android.internal.telephony.ITelephony$Stub$Proxy.endCall(ITelephony.java:2027)
at java.lang.reflect.Method.invoke(Native Method)
at anywheresoftware.b4a.agraham.reflection.Reflection.runmethod(Reflection.java:216)
at anywheresoftware.b4a.agraham.reflection.Reflection.RunMethod(Reflection.java:802)

So seems the MODIFY_PHONE_STATE permission is required on android 8.0.
I tried to add the permission on the manifest or asking on runtime. No luck.
@Override
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:
                    numberGlobal = incomingNumber;

                    //Turn ON the mute in case we have to block the call)
                    AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
                    audioManager.setStreamMute(AudioManager.STREAM_RING, true);

                    if (hasToBeBlocked()) {
                        try {
                            Method method =  telephonyManager.getClass().getDeclaredMethod("getITelephony");
                            method.setAccessible(true);   // true

                            telephonyService = (ITelephony) method.invoke(telephonyManager);
                            telephonyService.silenceRinger();
                            telephonyService.endCall();  // Crashes here only on android 8.0
                            showToast("Ending Call");
                        } catch (Exception e) {
                                     Toast.makeText(context, "AQUI: " + e.toString(), Toast.LENGTH_LONG).show();
                        }
                    }

                    //Turn OFF the mute
                    audioManager.setStreamMute(AudioManager.STREAM_RING, false);

                    break;
                case PhoneStateListener.LISTEN_CALL_STATE:
                    break;
            }
            super.onCallStateChanged(state, incomingNumber);
        }

So what can I do to end a call on android 8.0 (and up)?
Answer: As per the MODIFY_PHONE_STATE documentation:

Not for use by third-party applications.

Therefore your app cannot receive this permission.
As per the endCall documentation:

Companion apps for wearable devices should use the InCallService API instead. Apps performing call screening should use the CallScreeningService API instead.

As per this question, these were both limited to only the default dialer app until Android Q, where now third party apps can request that role.
Comment: You can get it for a personal app if you're willing to root your device and make your app a system app.  It just won't work as a play store app


UITableviewCell with RemoveButton

Question: I have a one Tableview in that i added a UIButton to each Tableviewcell named it as Remove
when i click the remove button the appropriate cell data will be remove from the tableview
and i added UIButton programmatically
now i want to perform remove option.
Thanks in Advance....
Answer: try this one:
<code>    - (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *s = @"cell";

        UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:s];
        AsyncImageView *asyncImage;
        UIButton *button = nil;
        if ( cell == nil ) {
            cell = [[[UITableViewCell alloc]initWithReuseIdentifier:s] autorelease];
            UIButton *removeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [button addTarget:self
                       action:@selector(remove:)
             forControlEvents:UIControlEventTouchUpInside];
            ….
            [cell addSubview:button];
        }

        …..

        return cell;
    }

    -(void)remove:(UIButton*)btn{
        UITableViewCell *cell = (UITableViewCell *)btn.superview;
        NSIndexPath* index = [self.tableView indexPathForCell:cell];
        [peopleList removeObjectAtIndex:index.row];
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:index]
                      withRowAnimation:UITableViewRowAnimationRight];
}
</code>

UITableviewCell with RemoveButton


User defined function export multiple data frames into global environment

Question: I have created a function, which computes the statistics on various patients data, and as well as outputting plots, it generates data frames containing summary statistics for each patient.
If i copy and run the function within R, the outputs are available to me. However, I am now calling the function from a separate R script, and the data frames are no longer available.
Is there any way to correct this?
For example,
test=function(a){
  A=a
  B=2*a
  C=3*a
  D=4*a
  DF=data.frame(A,B,C,D)
}

a=c(1,2,3,4)
test(a)

This does not return DF, yet if I were to type:
  a=c(1,2,3,4)
  A=a
  B=2*a
  C=3*a
  D=4*a
  DF=data.frame(A,B,C,D)

Then clearly DF is returned. Is there a simple way to fix this so that DF becomes available from the test function?
Comment: If `test(a)` is not returning the DF, maybe you should add a line like `return(DF)` inside the function. (Not sure if that's what you mean.)
Comment: That's not exactly what I meant, but i can see how it came across that way. I would like `DF` to be stored in the global environment as opposed to displayed in the console.
Comment: If you add `return(DF)` inside the function and use the function like `DF = test(a)`, it should do as you expect. That's the idiomatic way to do things in R, rather than having functions create objects as side-effects. If you really want to do as you describe, there's the `<<-` assignment operator that might work, but it's usually discouraged. Related: http://stackoverflow.com/q/9726705/1191259
Answer: Try:
test=function(a){
  A=a
  B=2*a
  C=3*a
  D=4*a
  DF=data.frame(A,B,C,D)
}

a=c(1,2,3,4)
df<-test(a)
print(df)

By assigning the function's returned value to a new variable it is now accessible in the global space.
Answer: If you want to assign an object from within a function to the global environment for easy retrieval then your operators are "<<-" or "->>" for more info see:
?assignOps() i.e.
test <- function(a)
       A=a
       B=2*a
       C=3*a
       D=4*a
       DF <<- data.frame(A,B,C,D)
}

# trial your dummy data
a=c(1,2,3,4)
test(a)
DF

Hey presto ... it works! Writing return(DF) within the function will not deliver your data frame to the global environment.


The difference between our sample estimate and the true population value is known as:

Question: The difference between our sample estimate and the true population value is known as:
A. Mean Value
B. Standard Deviation
C. Standard Error
D. Variance
With explanation please
Answer: None of your four options describes the difference between a single sample statistic and the population parameter. Population parameters are typically unknown (that is why we draw samples to calculate estimates and draw inferences) and so it doesn't make sense to think about the difference between a single sample statistic and an unknown quantity. Instead, perhaps you are thinking about the amount of uncertainty in a sample statistic due to sampling? In that case, the standard error is the closest answer - this is the standard deviation of the sampling distribution of your statistic. As your sample size increases, this value decreases.
Can you provide some more information about what you are trying to understand?
Comment: danCloney is right. I'd add that if the sample estimate is, say, the sample mean (rather than the median or any other sample credible estimate), then the difference between the sample mean and the population mean is $z ~se = z~\sigma/\sqrt{n}$ when the variance is known or $t~se= t~s/\sqrt{n}$ when the variance has to be estimated from the data.
Answer: Given

true value is $\theta$
sample estimate is $\hat \theta$

then

Variance, $ \sigma^2 = \mathbb E[ (\hat \theta - \theta)^2 ] $
Standard Deviation, $\sigma = \sqrt(\text{Variance}) $

Accordingly, an estimate of the difference might be B. Standard Deviation
Comment: @JuhoKokkala I apologize for the hasty Answer. I've added the previously omitted use of Expectation($\mathbb E$)
Comment: How does this relate to the  definition of variance given e.g. in https://stats.stackexchange.com/tags/variance/info?


How to use field.tpl for rendered node in views3

Question: i have set up a view (drupal 7) with a field that rendered the full node (node referenced field), and i want to get rid off the extra classes and tags wrapped around the fields.
i have copied field.tpl to my templates dir, and no matter what i name it it doesn't effect anything. I have selected that in the field settings in views. and yes, cleared the cache always.
would i name it after the content type. or the view.  i even left it at just field.tpl and still nothing.
Answer: If you want to override the views field template, the correct template file name would be views-view-fields.tpl.php.
You need to copy the template sites/all/modules/views/theme/views-view-field.tpl.php to your current enabled theme folder. Then update the file as you need.
Rescan template files in your view theming information. The file views-view-field.tpl.php should be highlighted with bold. You may need to fluch the cache. It is a view template to all the fields as a row.

If you want to theme a specific field, you could use views-view-field--[field_name].tpl.php. It is the most specific view template.
You can check more in Views theming.
Comment: @user10580, If you edit your view, you will see **Advanced** in the right most panel and then find **Other > Theme: Information** under it.
Comment: thank you, perfect! one thing, where is that panel you are showing above??
Answer: The easiest way to find out what the templates should be is to use hook_preprocess_field() in your themes template file.
<code>/**
 * Implements template_preprocess_field().
 */
function THEME_preprocess_field(&$vars) {

  // Check for template suggestions
  var_dump($vars['theme_hook_suggestions']);

  // Add a less verbose field name class: .field-NAME
  $vars['classes_array'][] = drupal_html_class($vars['element']['#field_name']);

  // Use .field-body instead of .body
  if ($vars['element']['#field_name'] == 'body') {
    $vars['classes_array'][] = 'field-body';
  }

  // Remove some classes from the wrapper <div>.
  $classes_to_remove = array(
    'field',
    'field-label-' . drupal_html_class($vars['element']['#label_display']),
    'field-type-' . drupal_html_class($vars['element']['#field_type']),
    'field-name-' . drupal_html_class($vars['element']['#field_name']),
    'body',
    'clearfix',
  );
  $vars['classes_array'] = array_diff($vars['classes_array'], $classes_to_remove);
}
</code>
The following has the information you want...
<code>$vars['theme_hook_suggestions']
</code>
See: http://drupal.org/node/1089656
Theres a few examples above to edit/remove classes. You can then remove any wrappers divs and extra markup from the template.


Pull all articles as JSON

Question: I am trying to pull all articles from my site in form of JSON.
I know it can be done by either Services, RESTful Web Services or Views Datasource but I don't know how to do it. I am a complete n00b in Drupal.
Could you specify me, with an example hopefully, that how can I pull all articles in a JSON and show that JSON through a URL?
Comment: Which version of Drupal are you dealing with?
Comment: Drupal Version 7
Answer: Judging by its description Views Datasource might be the way to go, but it seems to be still not ready for production. There is no even beta version as far as I can tell. But your task can be easily achieved by creating your own custom module.
Create your own module (you can read more about this process here).
And in your module do the following:
//Your implementation of hook_menu, create url endpoints here
function YOURMODULENAME_menu() {
    $items = array();
    $items['path/where/i/want/your/json/to/be'] = array(
        'title' => t('list of articles'), // can actually be arbitrary text here
        'type' => MENU_NORMAL_ITEM,
        'page callback' => 'your_function_name',
        'access callback' => TRUE,
    );
    return $items;
}

//Page callback function that renders the json endpoint
function your_function_name() {
    $query = "SELECT * FROM {node} n WHERE n.type = :type";
    $result = db_query($query, array(':type' => 'article'));
    $json_data = array();
    foreach ($result as $record) {
        $node = node_load($record->nid);
        $json_data[] = array('nid' => $node->nid, 'title' => $node->title, 'body' -> $node->body['und'][0]['value']);
    }
    print drupal_json_encode($json_data);
    exit;
}

I didn't test this code and you might have more fields in article datatype, but I think you should get the idea how this can be done. Just query the database for the list of nodes of specific type, compose an array of data and output json.
Answer: Thanks Alex, Thanks Sibiraj,
I was able to do it through Services + REST.
I created a view named content and configured it to show all the Published Articles.
This is what generated for me:-
http://myurl.com/views/content.json

Could I ask one more question, that how can I control how many articles could be shown. I am implementing Dynamic scrolling in my app and I want to show 10 Articles at a time. When a user scrolls till the bottom end, I want to show next 10 articles.
The problem with this URL is that it shows all the articles. Could I say append a variable with it, let's say through which it can control the start and end of article index?
http://myurl.com/views/content.json?/start_article=0&end_article=10

Many Thanks.
Answer: You can try some module like feeds or services or views_data_export or node_export

Pull all articles as JSON


How to apply Chosen on AJAX load

Question: I have a custom form within my module that is AJAX-enabled.  The form contains a fieldset with a number of fields, and the user can click 'add more' to add another fieldset.
One of the fields within the fieldset is a select list, and all select lists on the site are replaced with a Chosen widget via the Chosen jQuery plugin contained in the Chosen module.  The problem is, when AJAX refreshes the page, all Chosen widgets on the page revert back to select lists.
I already have an issue on drupal.org for the Chosen module, but there have been no responses yet--I was hoping somebody here knew of a way to use Chosen with an AJAX form.
I would assume that Chosen would be dynamically loaded on AJAX content by the Drupal behavior within the Chosen module, but apparently it doesn't work this way.  Maybe I need to load it manually?
function manual_import_menu() {
  $items['manual_import'] = array(
    'title' => 'Manual Import',
    'description' => 'Manual import form.',
    'page callback' => 'manual_import_page',
    'access callback' => TRUE,
  );
  $items['admin/config/manual_import'] = array(
    'title' => 'Configure Manual Import',
    'description' => 'Select which taxonomy terms will be used in the
      manual import form.',
    'page callback' => '',
    'access arguments' => TRUE,
    );
  return $items;
}

function manual_import_page() {
  $build = array(
    'header_text' => array(
      '#type' => 'markup',
      '#markup' => '

' . t('Manually import content into Repair Central.  Content
        is imported in a group, which is assigned an import scenario,
        which determines the tasks created for the items.') . '

',
    ),
    'manual_import_form' => drupal_get_form('manual_import_form'),
  );
  return $build;
}

function manual_import_form($form, &$form_state) {
  //set up options for select list
  $task_options = get_task_options();
  $location_options = get_location_options();
  $model_options = get_model_options();

  $form['#attached'] = array(
    'css' => array(
      'type' => 'file',
      'data' => drupal_get_path('module','manual_import') . '/manual_import.css',
    ),
    'js' => array(
      'type' => 'file',
      'data' => drupal_get_path('module','manual_import') . '/manual_import.js',
    ),
  );
  $form['#tree'] = TRUE;
  $form['scenario'] = array(
    '#type' => 'select',
    '#title' => t('Import Scenario'),
    '#options' => array(
      'shipment' => t('Shipment'),
      'location' => t('Location'),
      'manual' => t('Manual'),
      ),
    '#prefix' => '
',
    '#suffix' => '
',
    '#default_value' => 'shipment',
  );
  $form['scenario_shipment'] = array(
    '#type' => 'fieldset',
    '#title' => t('Associate Group To Shipment'),
    '#description' => t('Associate a group of items to a shipment, and auto-generate tasks'),
    '#states' => array(
      'visible' => array(
        ':input[name="scenario"]' => array('value' => 'shipment'),
      ),
    ),
    '#prefix' => '
',
    '#suffix' => '
',
    '#collapsible' => TRUE,
    '#collasped' => FALSE,
  );
  $form['scenario_shipment']['shipping_list_number'] = array(
    '#type' => 'textfield',
    '#title' => t('Shipping List'),
    '#prefix' => '
',
    '#suffix' => '
',
  );
  $form['scenario_shipment']['shipping_from'] = array(
    '#type' => 'select',
    '#title' => t('Shipping From'),
    '#options' => $location_options,
    '#default_value' => 283,
  );
  $form['scenario_shipment']['shipping_to'] = array(
    '#type' => 'select',
    '#title' => t('Shipping To'),
    '#options' => $location_options,
    '#default_value' => 283,
  );

  $form['scenario_location'] = array(
    '#type' => 'fieldset',
    '#title' => t('Associate Group To Location'),
    '#description' => t('Associate a group of items to a location, and auto-generate tasks'),
    '#states' => array(
      'visible' => array(
        ':input[name="scenario"]' => array('value' => 'location'),
      ),
    ),
    '#prefix' => '
',
    '#suffix' => '
',
    '#collapsible' => TRUE,
    '#collasped' => FALSE,
  );
  $form['scenario_location']['location'] = array(
    '#type' => 'select',
    '#title' => t('Location'),
    '#options' => $location_options,
    '#default_value' => 283,
  );
  $form['scenario_manual'] = array(
    '#type' => 'fieldset',
    '#title' => t('Manually Create Tasks'),
    '#description' => t('Manually select the tasks to be created for the items in the group.'),
    '#states' => array(
      'visible' => array(
        ':input[name="scenario"]' => array('value' => 'manual'),
      ),
    ),
    '#prefix' => '
',
    '#suffix' => '
',
    '#collapsible' => TRUE,
    '#collasped' => FALSE,
  );
  $form['scenario_manual']['task'] = array(
    '#type' => 'select',
    '#title' => t('Task Type'),
    '#options' => $task_options,
  );
  $form['import_items'] = array(
    '#type' => 'container',
    '#prefix' => '
',
    '#suffix' => '
',
  );
  if (empty($form_state['import_item_quantity'])) {
    $form_state['import_item_quantity'] = 1;
  }
  for ($i = 1; $i <= $form_state['import_item_quantity']; $i++) {
    $form['import_items'][$i] = array(
      '#type' => 'fieldset',
      '#title' => t('Import Item @item', array('@item' => $i)),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
    );
    if ($i == $form_state['import_item_quantity']) {
      $form['import_items'][$i]['#prefix'] =
        '
';
      $form['import_items'][$i]['#suffix'] =
        '
';
    }
    $form['import_items'][$i]['ticket_number'] = array(
      '#type' => 'textfield',
      '#maxlength' => 32,
      '#title' => t('Ticket Number'),
      '#class' => 'manual-import-item-field',
      '#prefix' => '
',
      '#suffix' => '
',
    );
    $form['import_items'][$i]['device_id'] = array(
      '#type' => 'textfield',
      '#maxlength' => 32,
      '#title' => t('Device ID'),
      '#prefix' => '
',
      '#suffix' => '
',
    );
    $form['import_items'][$i]['device_model'] = array(
      '#type' => 'select',
      '#title' => t('Make/Model'),
      '#options' => $model_options,
      '#prefix' => '
',
      '#suffix' => '
',
    );
    if ($i == $form_state['import_item_quantity']) {
      $form['import_items'][$i]['device_model']['#prefix'] =
        '
';
    }
  }
  $form['import_items']['item_add'] = array(
    '#type' => 'submit',
    '#value' => 'Add another!',
    '#ajax' => array(
      'callback' => 'manual_import_item_ajax_callback',
      'wrapper' => 'import_items',
    ),
    '#submit' => array('manual_import_item_add'),
  );
  return $form;
}
function manual_import_item_ajax_callback($form, $form_state) {
  return $form['import_items'];
}

function manual_import_item_add($form, &$form_state) {
  $form_state['import_item_quantity']++;
  $form_state['rebuild'] = TRUE;
}

Answer: You can add the class chosen-widget directly to the form element like this:
$form['your_form_field']['#attributes']['class'] = array('chosen-widget');

And an example for your code would be:
$form['import_items'][$i]['device_model'] = array(
  '#type' => 'select',
  '#title' => t('Make/Model'),
  '#options' => $model_options,
  '#prefix' => '
',
  '#suffix' => '
',
  '#attributes' => array(
    'class' => array('chosen-widget'),
  ),
);

How to apply Chosen on AJAX load


Show that if $X\sim$ uniform$(-\theta, \theta)$ then $|X|\sim$ uniform$(0, \theta)$.

Question: I am trying to show that if $X\sim$  Uniform$(-\theta, \theta)$ then $|X|\sim$  Uniform$(0, \theta)$. I start by using the Jacobian but I end up with $$ f(y)=\left|\frac{\partial x}{\partial y} \right|f(x) = \frac{y}{2\theta|y|}$$ but I do not think this is correct. Can some one help me?
Comment: Repost of https://math.stackexchange.com/q/4083619/321264.
Answer: Why make it so complicated? This can be done without thinking about Jacobians.
For $0<a<b<\theta$ we have
\begin{align}
& \Pr(a<|X|<b) = \Pr(a<X<b) + \Pr(a<-X<b) \\[8pt]
= {} & \frac{b-a}{2\theta} + \frac{b-a}{2\theta} = \frac{b-a}\theta.
\end{align}
Also, note that $\dfrac y{|y|} = 1$ when $y>0,$ so what you did is correct.
Answer: Hint:
$Y= |X| $ is not one to one transformation. So
$$f_Y(y)=\left| \frac{d}{dy} (-y) \right| f_X(-y)+\left| \frac{d}{dy} (y) \right| f_X(y) $$
Answer: The distribution function of Unif$(-a,a)$ is the following:
$$F_X(x)= \frac{1}{2a} x+ \frac{1}{2}$$
for $x \in [-a, a]$ which we can get by integrating the density function (which is constant with value $\frac{1}{2a}$ on $[-a,a]$). Now we know by definition of the distribution function:
$$F_{|X|}(x)= P(|X| \leq x) = P(-x \leq X \leq x) = F_X(x)-F_X(-x) = \frac{x} {a}$$
for $x \in [0,a]$ because negative values don't make sense here. The absolute value can never be negative. The distribution with the density function $F_{|X|}(x)= \frac{x} {a}$ on $[0,a]$ is precisely Unif$(0,a)$. (which we could again check by differentiating and getting the constant function $\frac{1}{a}$ on $[0, a]$ which is the density function of Unif$(0,a)$).


Notating Octatonic Music in MuseScore

Question: I'm trying to do something with MuseScore that I'm not sure is possible, and I'd appreciate some help trying to figure out a creative way to do this.
So I'm trying to write in an octatonic mode with eight distinct pitches, whose frequency values I provide. The eight pitches are unrelated to pitches in 12-TET. The pitches are defined by ratios to a fundamental/tonic, but I imagine that it would be a lot easier for me to input absolute frequencies than ratios.
Here is functionality I am looking for: (I'm aware that not all of this might be possible)

Some way to define the pitches that I'm looking for
The octave (nonave?) is nine units wide on the staff, not eight
Can I bind "H" to the note above G and below A in this scale?
Some way to play back the music I write in this mode
I don't particularly care about accidentals; I don't intend to use them.
Cool but not strictly necessary: a custom clef

Some options I have considered:

I saw there is a "Tuning" plugin, but it doesn't seem powerful enough to do what I'm trying to do (or maybe it is, and I just haven't figured it out yet?)
Maybe I could define a new instrument somehow that can do what I want, similarly to how the drum set staff doesn't mean the same thing as the standard 5-line staff?

I tried asking this question on MuseScore's support forum, but got no response. I'm using MuseScore 4.0.2, but I could switch back to 3.x if there are plugins written for an earlier version that have this functionality. If this is impossible, but it can be done using a different free software, feel free to include that, but I'm primarily looking for answers that use MuseScore.
Here's an example screenshot of what this could look like (created using MuseScore, but none of the features relating to pitch are implemented)
Answer: I'm quite unsure about what you're actual question is, as clearly you've already found a way to notate such, and clearly you may extend the note names however you like.
A custom clef will not be really possible in MuseScore unless you create you own Notation font file that substitutes an existing clef with what you want.
Regarding playback: Simply create a small MuseScore plugin like this:
<code>import MuseScore 3.0
import QtQuick 2.2
import QtQuick.Controls 1.1
import QtQuick.Controls.Styles 1.3
import QtQuick.Layouts 1.1
import QtQuick.Dialogs 1.1

MuseScore {
    version: "3.0.5"
    title: "To Nonic"
    pluginType: "dialog"
    categoryCode: "playback"

    property var offsetTextWidth: 200;
    property var offsetLabelAlignment: 0x02 | 0x80;

    property var offset: [ 0, 150, 300, 450, 600, 750, 900, 1050 ];

    onRun: {
        if (!curScore) {
            error("No score open.\nThis plugin requires an open score to run.\n")
            quit()
        }
    }

    function applyTemperament()
    {
        var selection = new scoreSelection()
        curScore.startCmd()
        selection.map(filterNotes, reTune(getFinalTuning()))
        curScore.endCmd()
        return true
    }

    function filterNotes(element)
    {
        return element.type == Element.CHORD
    }

    function reTune(tuning) {
        return function(chord, cursor) {
            for (var i = 0; i < chord.notes.length; i++) {
                var note = chord.notes[i]
                note.tuning = tuning(note)
            }
        }
    }

    function scoreSelection() {
        const SCORE_START = 0
        const SELECTION_START = 1
        const SELECTION_END = 2
        var fullScore
        var startStaff
        var endStaff
        var endTick
        var inRange
        var rewind
        var cursor = curScore.newCursor()
        cursor.rewind(SELECTION_START)
        if (cursor.segment) {
            startStaff = cursor.staffIdx
            cursor.rewind(SELECTION_END)
            endStaff = cursor.staffIdx;
            endTick = 0 // unused
            if (cursor.tick === 0) {
               endTick = curScore.lastSegment.tick + 1;
            } else {
               endTick = cursor.tick;
            }
            inRange = function() {
                return cursor.segment && cursor.tick < endTick
            }
            rewind = function (voice, staff) {
                // no idea why, but if there is a selection then
                // we need to rewind the cursor *before* setting
                // the voice and staff index.
                cursor.rewind(SELECTION_START)
                cursor.voice = voice
                cursor.staffIdx = staff
            }
        } else {
            startStaff = 0
            endStaff  = curScore.nstaves - 1
            inRange = function () {
                return cursor.segment
            }
            rewind = function (voice, staff) {
                // no idea why, but if there's no selection then
                // we need to rewind the cursor *after* setting
                // the voice and staff index.
                cursor.voice = voice
                cursor.staffIdx = staff
                cursor.rewind(SCORE_START)
            }
        }

        this.map = function(filter, process) {
            for (var staff = startStaff; staff <= endStaff; staff++) {
                for (var voice = 0; voice < 4; voice++) {
                    rewind(voice, staff)
                    while (inRange()) {
                        if (cursor.element && filter(cursor.element)) {
                            process(cursor.element, cursor)
                        }
                        cursor.next()
                    }
                }
            }
        }
    }

    function error(errorMessage) {
        errorDialog.text = qsTr(errorMessage)
        errorDialog.open()
    }

    function getFinalTuning() {
        return function(note) {

            var tpc = note.tpc; // Pitch class = circle of fifths position with C == 14
            var refpc = (((tpc - 13) % 7) + 7) % 7; // f = 0, c = 1, ..., b = 6
            var alt = (tpc - 13 - refpc) / 7; // 0 = nat, -1 = flat, 1 = sharp, ...
            var refpc2 = ((4 * refpc) + 3) % 7; // c = 0, d = 1, ...
            var pitch = note.pitch; // midi pitch, C4 = 60
            var refpitch = pitch - alt; // e.g. Dbb4 = 60, refpitch = D = 62
            var octave = (refpitch - (refpitch % 12) - 60) / 12; // Octave from C4 (note: Cbbbbbbbbbbbb5 is still an octave up!)

            var nonpc = (((refpc2 - octave) % 8) + 8) % 8; // c4, ..., a4, b4 -> c4, ..., h4, a4, then c5 -> b4, c6 -> a4, ... . Also c3 -> d3, ...
            var deltanonave = (refpc2 - octave - nonpc) / 8;
            var nonave = octave + deltanonave;

            var tuning_refpc = 200 * refpc2 + 1200 * octave;
            if (refpc2 > 2) {
                  tuning_refpc = tuning_refpc - 100;
            }

            var tuning = getOffset(nonpc) + 1200 * nonave;

            return tuning - tuning_refpc;
        }
    }

    function getOffsetS(id) {
        switch (id) {
              case 0:
                    return final_c.text
              case 1:
                    return final_d.text
              case 2:
                    return final_e.text
              case 3:
                    return final_f.text
              case 4:
                    return final_g.text
              case 5:
                    return final_h.text
              case 6:
                    return final_a.text
              case 7:
                    return final_b.text
        }
    }

    function getOffset(id) {
          return parseFloat(getOffsetS(id))
    }

    Rectangle {
        color: "transparent"
        anchors.fill: parent

        ColumnLayout {

            ColumnLayout {
                ColumnLayout {

                    Label {
                        text: "C"
                        Layout.alignment: offsetLabelAlignment
                    }
                    TextField {
                        Layout.maximumWidth: offsetTextWidth
                        id: final_c
                        text: offset[0]
                        readOnly: false
                        validator: DoubleValidator { bottom: -99.9; decimals: 1; notation: DoubleValidator.StandardNotation; top: 99.9 }
                    }

                    Label {
                        text: "D"
                        Layout.alignment: offsetLabelAlignment
                    }
                    TextField {
                        Layout.maximumWidth: offsetTextWidth
                        id: final_d
                        text: offset[1]
                        readOnly: false
                        validator: DoubleValidator { bottom: -99.9; decimals: 1; notation: DoubleValidator.StandardNotation; top: 99.9 }
                    }

                    Label {
                        text: "E"
                        Layout.alignment: offsetLabelAlignment
                    }
                    TextField {
                        Layout.maximumWidth: offsetTextWidth
                        id: final_e
                        text: offset[2]
                        readOnly: false
                        validator: DoubleValidator { bottom: -99.9; decimals: 1; notation: DoubleValidator.StandardNotation; top: 99.9 }
                    }

                    Label {
                        text: "F"
                        Layout.alignment: offsetLabelAlignment
                    }
                    TextField {
                        Layout.maximumWidth: offsetTextWidth
                        id: final_f
                        text: offset[3]
                        readOnly: false
                        validator: DoubleValidator { bottom: -99.9; decimals: 1; notation: DoubleValidator.StandardNotation; top: 99.9 }
                    }

                    Label {
                        text: "G"
                        Layout.alignment: offsetLabelAlignment
                    }
                    TextField {
                        Layout.maximumWidth: offsetTextWidth
                        id: final_g
                        text: offset[4]
                        readOnly: false
                        validator: DoubleValidator { bottom: -99.9; decimals: 1; notation: DoubleValidator.StandardNotation; top: 99.9 }
                    }

                    Label {
                        text: "H"
                        Layout.alignment: offsetLabelAlignment
                    }
                    TextField {
                        Layout.maximumWidth: offsetTextWidth
                        id: final_h
                        text: offset[5]
                        readOnly: false
                        validator: DoubleValidator { bottom: -99.9; decimals: 1; notation: DoubleValidator.StandardNotation; top: 99.9 }
                    }

                    Label {
                        text: "A"
                        Layout.alignment: offsetLabelAlignment
                    }
                    TextField {
                        Layout.maximumWidth: offsetTextWidth
                        id: final_a
                        text: offset[6]
                        readOnly: false
                        validator: DoubleValidator { bottom: -99.9; decimals: 1; notation: DoubleValidator.StandardNotation; top: 99.9 }
                    }

                    Label {
                        text: "B"
                        Layout.alignment: offsetLabelAlignment
                    }
                    TextField {
                        Layout.maximumWidth: offsetTextWidth
                        id: final_b
                        text: offset[7]
                        readOnly: false
                        validator: DoubleValidator { bottom: -99.9; decimals: 1; notation: DoubleValidator.StandardNotation; top: 99.9 }
                    }

                }

                RowLayout {
                    Button {
                        id: applyButton
                        text: qsTranslate("PrefsDialogBase", "Apply")
                        onClicked: {
                            if (applyTemperament()) {
                                quit()
                            }
                        }
                    }
                    Button {
                        id: cancelButton
                        text: qsTranslate("PrefsDialogBase", "Cancel")
                        onClicked: {
                            quit()
                        }
                    }
                }
            }
        }
    }

    MessageDialog {
        id: errorDialog
        title: "Error"
        text: ""
        onAccepted: {
            errorDialog.close()
        }
    }
}
</code>
This will then allow you to quickly tune each note to  the desired value. This plugin takes C4 as base point.
Comment: Worked like a charm, thank you for your help!

Notating Octatonic Music in MuseScore


Div to fit parent div height - where child is display:table

Question: I am trying to make a responsive table for my products.

                Coverage:

                24sqm/Litre per coat

    ...

And this is the CSS
.desc-table{border:1px solid #4a4a4a;margin-bottom:5px;}
.desc-table .span6 {display:table;}
.desc-table span {display:table-cell;vertical-align:middle;}
.desc-table > .row-fluid > .span6 {padding:0px 5px 0px 5px;margin-left:0px;}
.desc-title {font-weight: bold;}
.desc-title-table {background-color:#4a4a4a; color:#fff;}

The problem I am having is if the content in one div spills onto more than one line, the sibling div (span6) does not expand to the same height.
I have tried:

height:100%;
height: 100%; position: absolute; right: 0; top: 0;

The div is display:table so i can vertically align the text within it.
Image of my problem
My website is a Joomla! and Virtuemart website if that helps.
Comment: You need to make the ROW ``display:table` and the inner columns `display:table-cell`.
Answer: Although your question is not clear as to what it is you're trying to accomplish, my guess is that you want the .desc-title div to take up the same height as the corresponding description div .desc-text.
In other words, you want to imitate the display of vertically aligned table cells, where both cells take up the same height as one another.
You're on the right track; you just need to refine your styles a bit.

body {
  background: orange;
}
.wrapper {
  max-width: 500px;
  margin: 20px auto;
  background: green;
  display: table;
}
.desc-title {
  color: #fff;
}
.desc-table .row-fluid {
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  display: table;
  width: 100%;
}
.desc-table .row-fluid > .span6 {
  width: 50%;
  padding: 10px;
  display: table-cell;
  vertical-align: middle;
  box-sizing: border-box;
}
.row-fluid > .span6:first-child {
  background: #4a4a4a;
}
.row-fluid > .span6:last-child {
  background: #fff;
}

          Coverage:

          24sqm/Litre per coat

          Drying Time:

          Approx. 8 – 10 hours in normal conditions.

Comment: Didn't work for my page. This is the page with my original code. http://www.flooringsales.co.uk/finishes/polyx-hardwax-oil-matt-sample-5ml-detail
Comment: @FlooringSales Here is what you need to get your stuff fixed, make sure it's appended after all other styles: http://pastebin.com/HzCbfcSN
Comment: @FlooringSales How did it go?
Comment: Haven't had a chance to try it yet, when I do I shall post my results.
Answer: Actually sibling div will not expand automatically, to do that either you need to use JS or style="white-space:no-wrap" with the label/span to avoid wrapping.