Should slurs encompass tied notes from before and/or after?

Question: What are the rules when it comes to how a slur handles tied notes set at the start or end of the legato passage? I think it looks nicer when the tied notes are included in the slur, but I don't know whether it's correct.
For example, with the tied notes at the end:

Which is correct: The top staff, with the slur leaving out the tied notes; or the bottom staff, with the slur encompassing the tied notes?
In this second example, the tied notes are before the legato passage:

As above, which is correct, the top or bottom staff?
I'd appreciate any thoughts on this.
Answer: The top staves are "correct" for a slur, the bottom staves are correct for a phrasing slur.  For music like violin music, this difference is more poignant than for piano since a slur has separate technical meaning as a bowing direction instruction (which implies legato but the legato can be dissolved with tenuto or staccato marks) while a phrasing slur is basically a "play this phrase legato" instruction not focused on a particular instrument.
Because phrasing slurs may enclose slurs (the opposite would be rather strange), making slurs short with respect to tie scope helps to unclutter the score.
The slurs in the examples you quote are on the longish side regarding their compass so it is likely that they were intended as phrasing slurs in which case the bottom stave lines would do them better justice.
If they are intended primarily as a bowing or tongueing instruction, the top staves might be more correct.
Comment: @Walter the first rule of any music notation is "clarity". If you can think of a good reason *why* a slur extending over a 20-bar tied note makes your intention clearer, then write it that way. If not, don't. For example in keyboard music, the only actions the *performer* can take are at the start and end of the note. On other instruments, he/she can control the sound over the whole duration of the note. That may make a difference to what your notation needs to communicate to the player.
Comment: Thanks for the detailed reply! So if I understand you correctly, I should reserve the "shorter" slurs (that don't include all tied notes) for instrument-specific instructions (such as for strings), and use the "longer" slurs, as in the bottom staves, when I want to denote a legato passage? If so, is there a maximum length to this? For instance, what if a legato passage ends on a note that's tied for the next twenty bars or something? I just want to be clear on the rules/conventions. Thanks again.
Comment: @alephzero Yeah, I figured common sense would go into deciding how long a slur should be. I wanted to see whether there were any precise rules about their use (specifically where ties are concerned), and I think your and @user39917's replies have cleared it up. I'm gonna go ahead and mark this as resolved. Thanks.
Answer: A slur starts on the first note and ends at the end of the last note, so it makes sense to encompass the whole phrase, from beginning to the end of the last note, even when that could be several bars later.


Solving recurrence of 3 variables using generating functions

Question: This comes from another question in Wilf's generatingfunctionology book (the part highlighted in light yellow):

If I read the question right, if I do it for $n=3$ (and assuming a substring like $111$ is considered to have 3 consecutive $1$'s and something like $01010$ has 2 non-consecutive $1$'s):
\begin{array}{|c|c|}
\hline
& m & k \\ \hline
000 & 0 & 0 \\ \hline
001 & 1 & 1 \\ \hline
010 & 1 & 1 \\ \hline
011 & 2 & 0 \\ \hline
100 & 1 & 1 \\ \hline
101 & 2 & 2 \\ \hline
110 & 2  & 0 \\ \hline
111 & 3 & 0 \\ \hline
\end{array}
So this means $f(3,1,1)=3, f(3,2,0)=2$ and $f(3,3,0) = 1$ for instance.
I have then found the recurrence in the form:
$$f(n,m,k) = f(n-1,m,k) + f(n-2,m-1,k-1) + \sum_{t \geq 0} {f((n-3)-t,(m-3)+1-t,k)}$$
Where:

The first term is the case when we have $01$ at the start of the string.
The 2nd term when we have $10$ at start of string.
The 3rd term is when we have $110$, $1110$, $11110$, etc at the start of the string.

With base cases:

$f(1,0,0)=f(1,1,1)=1$, and
$f(n,n,0) =1$ if $n = 0$ or $n > 1$.

And also some other conditions, including $n,m,k\geq 0$, $n\geq m$ and $m\geq k$
This leads me to part (b) of the question where I could multiply the recursion by $x^n y^m$ and sum it, or sum for $n$ or $m$ separately by first defining $A_{m,k} = \sum _{n\geq 0} {f(n,m,k)x^n}$, for example. However, I am confused as to how to deal with the 3rd term.
I believe I may have read the question incorrectly (since there's a mentioning of $k=1,2,...$, but I'm having trouble understanding what the question is asking for otherwise), but am still curious if this recurrence could be solved and would like to ask for hints/help as to how to approach this recurrence, or if I am reading the question right.
Thank you!
Answer: For the generating function we get  more or less by inspection that it
is given by
$$F_k(x, y) = (1+x+x^2+\cdots)
\\ \times \sum_{q\ge 0} (y+y^2+\cdots+y^{k-1})^q (x+x^2+\cdots)^q
\\ \times (1+y+y^2+\cdots+y^{k-1})
\\ = (1+x+x^2+\cdots)
\\ \times \sum_{q\ge 0} x^q y^q (1+y+\cdots+y^{k-2})^q (1+x+\cdots)^q
\\ \times (1+y+y^2+\cdots+y^{k-1})
.$$
This is
$$F_k(x, y) = \frac{1}{1-x} \frac{1}{1-xy(1-y^{k-1})/(1-y)/(1-x)}
\frac{1-y^{k}}{1-y}
\\ = \frac{1-y^{k}}{(1-x)(1-y)-xy(1-y^{k-1})}
\\ = \frac{1-y^k}{1-x-y+xy^k}.$$
For the explicit formula we write
$$F_k(x, y) = \frac{1-y^k}{1-y-x(1-y^k)}
= \frac{1-y^k}{1-y} \frac{1}{1-x(1-y^k)/(1-y)}.$$
Extracting the coefficient on $x^n$ first followed by $y^m$ we get
$$[x^n] [y^m] F_k(x,y) =
[y^m] \frac{1-y^k}{1-y} \frac{(1-y^k)^n}{(1-y)^n}
= [y^m] \frac{(1-y^k)^{n+1}}{(1-y)^{n+1}}
\\ = [y^m] \frac{1}{(1-y)^{n+1}}
\sum_{q=0}^{n+1} {n+1\choose q} (-1)^q y^{kq}
\\ = \sum_{q=0}^{n+1} {n+1\choose q} (-1)^q
[y^{m-kq}] \frac{1}{(1-y)^{n+1}}
\\ = \sum_{q=0}^{\lfloor m/k \rfloor} {n+1\choose q} (-1)^q
{m+n-kq\choose n}.$$
We now  present a combinatorial  recurrence. Observe that  $f(n,m,k) -
f(n,m,k-1)$ gives the  strings where a block of $k-1$  ones appears at
least once. Now there are two cases.  The first appearance is right at
the  beginning  or   at  the  end  and  we   get  $f(n-1,m+1-k,k)$  or
$f(n-1,m+1-k,k-1)$ possibilities because the run of $k-1$ ones must be
followed / preceded by a zero.   The second is that the inital segment
before the  first appearance of  such a block  has length $p\ge  0$ to
$n+m-k-1$ followed by the $k-1$ ones surrounded by zeros followed by a
string of  length $n+m-p-(k+1)$ from  the set  that has at  most $k-1$
consecutive  ones. This  yields with  $q$ the  number of  ones in  the
prefix
$$f(n,m,k) = f(n,m,k-1) + f(n-1,m+1-k, k) + f(n-1,m+1-k,k-1) \\ +
\sum_{p=0}^{n+m-k-1}
\sum_{q=0}^m f(p-q, q, k-1) f(n-2+q-p, m+1-q-k,k).$$
There  is  some Maple  code  to  help  explore these  recurrences  and
generating functions  which also includes the  boundary conditions for
the recurrence.

with(combinat);

RL :=
proc(n, m, k)
    option remember;
    local res, iter;

    iter :=
    proc(restx, resty, d)
    local pos, cur, runlen;

        if restx = 0 and resty = 0 then
            cur := -1; pos := 1; runlen := 0;

            while pos <= m+n do
                if d[pos] <> cur then
                    cur := d[pos];
                    runlen := 1;
                else
                    runlen := runlen + 1;

                    if cur = 1 and runlen >= k then
                        break;
                    fi;
                fi;

                pos := pos + 1;
            od;

            if pos = n+m+1 then
                if cur = 0 or (cur = 1 and runlen < k)
                then
                    res := res + 1;
                fi;
            fi;
        fi;

        if restx > 0 then
            iter(restx-1, resty, [op(d), 0]);
        fi;
        if resty > 0 then
            iter(restx, resty-1, [op(d), 1]);
        fi;
    end;

    res := 0;
    iter(n, m, []);
    res;
end;

EX := (n, m, k) ->
coeftayl(coeftayl((1-y^k)/(1-x-y+x*y^k),
                  x=0, n), y=0, m);

EX2 := (n, m, k) ->
add(binomial(n+1,q)*(-1)^q*
    binomial(m+n-k*q, n), q=0..floor(m/k));

f :=
proc(n, m, k)
option remember;

    if n < 0 or m < 0 then return 0 fi;

    if n = 0 and m = 0 then return 1 fi;

    if n = 0 then
        if m <= k-1 then
            return 1
        else
            return 0
        fi;
    fi;

    if m = 0 then return 1 fi;

    if k <= 1 then return 0 fi;

    f(n,m,k-1) + f(n-1,m+1-k,k) + f(n-1, m+1-k, k-1) +
    add(add(f(p-q, q, k-1)*f(n-2+q-p, m+1-q-k, k),
            q=0..m), p=0..n+m-k-1);
end;

There   is  also   a  recurrence   that  is   algebraic  rather   than
combinatorial. We start from the observation that
$$\frac{\partial}{\partial x} F_k(x, y) = F_k^2(x, y).$$
Extracting coefficients on $[x^{n-1}] [y^m]$ yields
$$f(n, m, k) = \frac{1}{n} \sum_{p=0}^{n-1} \sum_{q=0}^m
f(p, q, k) f(n-1-p, m-q, k).$$
This is implemented below.

g :=
proc(n, m, k)
option remember;

    if n < 0 or m < 0 then return 0 fi;

    if n = 0 and m = 0 then return 1 fi;

    if n = 0 then
        if m <= k-1 then
            return 1
        else
            return 0
        fi;
    fi;

    if m = 0 then return 1 fi;

    if k <= 1 then return 0 fi;

    1/n*add(add(g(p, q, k)*g(n-1-p, m-q, k),
                q=0..m), p=0..n-1);
end;
Comment: It appears there is a much more symmetric recurrence which can be derived from the generating function. I have included this recurrence above.
Comment: Observe that the two recurrences produce the same values as the enumeration routine. The two sets that you refer to are disjoint as the first one has the first occurrence of a $k-1$ block at the beginning (followed by a sequence where blocks of one are at most $k-1$) and the second one at the end (preceded by a sequence with those blocks at most $k-2$). As the first occurrence of the $k-1$ block is in different positions there is no overlap.
Comment: Thank you for the help! I found [another answer](https://www.math.ubc.ca/~boyd/math331/Wilf.1.20.pdf) to the correct interpretation of the problem (unlike mine but like yours) which writes it as $f(n,m,k) = \sum _{q=0} ^{\lfloor m/k \rfloor} (-1)^q {n-kq\choose n-m} {n-m+1 \choose q}$. However, if I take $n:= n-m$ from your answer then it is the same. I wanted to ask if both of your answers are still equivalent then.
Comment: Oh, never mind. Your generating function treats $x$ as number of $0$'s and $y$ as total number of $1$'s, while as the other answer treats $x$ as counting both $0$'s and $1$'s.
Comment: I re-read the combinatorial recurrence, I think there is a misreading. For example (in the first case), wouldn't the $f(n-1,m+1-k,k)$ be also counting strings with $k-2$ or less consecutive 1's, which is also counted in $f(n-1,m+1-k,k-1)$? Would it just be enough to add a zero + $k-1$ ones on the right or left side only, and not consider both sides?


Should I write selectors from right to left?

Question: I was wondering since browsers parse a CSS document from right to left would it be better to write a selector like this:
a li #MainContent { }

instead of like this:
#MainContent li a { }

So that the browser can eliminate a selector that does match an element more quickly? Does this make any sense or am I misunderstanding? Thanks for any insight!
Comment: The first selector has no sense .... Read the basic of CSS selectors
Comment: I always use #id li a because it makes more sense and easy to read.
Comment: CSS is interpreted LTR, so writing RTL will cause problems.
Answer: Simply put...

It depends on the structure of your HTML (DOM)
a li #MainContent !== #MainContent li a

The first is redundant and can be simply replaced with #MainContent as id is unique. Ultimately it selects the #MainContent element. The second selects links which are children of list items which are children of #MainContent.

In modern browsers, the resolution of selectors in terms of directional performance is negligible, focus on writing concise ones instead
Answer: Usually we type to in order to show something inside the parent for example
div ul {}

this means select the ul in the div element so there won't be any point in writing it backwards order does matter for css


Are D-separation and Conditional independence equivalent?

Question: For a directed graphical model, does D-separation is equivalent to conditional independence. I have got bit confused about this concept from the following statement from this source.

if X and Y are not d-separated given Z in G, then are X and Y are
  dependent in all distributions P that factorize over G? This is false,
  because a distribution that factorizes over G may yet contain
  additional "accidental" independencies not asserted by the graph
  structure
Answer: D-seperation is not equivalent to conditional independence.  The D-seperation of $X$ and $Y$ given $Z$ implies the following conditional independence:
$$P(X,Y|Z) = P(X|Z)P(Y|Z).$$
However D-seperation is a concept that applies specifically to graphical models.  You can talk about conditional independence in any context involving random variables.
The statement is talking about something different.  What the statement is saying is that just because two nodes $X$ and $Y$ are not D-seperated given some subset of nodes $Z$, that doesn't mean there doesn't exist some probability distribution which factorizes over $G$ for which $X$ and $Y$ are conditionally independent given $Z$.  In fact there will always exist such a distribution (see the following paragraph).
Graphical models are only required to not encode any independency which doesn't actually exist in the joint probability distribution, that is to say, they are required to make no unwarranted assumptions.  However there's no requirement that they encode every independency that does in fact exist, and often times building a graphical model which captures every existing independency while at the same time avoiding the instantiation of spurious independencies is impossible (such a graph when it does exist is called a perfect I-map).  Therefore given a graphical model $G$, any mutually independent probability distribution on the nodes of $G$ trivially factorizes over $G$.


anchor (#) in url alias

Question: I want to open same page from different contents. So I need to generate link like /testimonials#group-1 for these contents. I used pathauto module for this. I made pattern for this category testimonials#[node:title]. But this URL get encoded by browser /testimonials%23group-1 and it gives me no page found error.
So how can I put anchor (#) in URL alias which can give me output like /testimonials#group-1.?
Comment: @MPD From a "this is what I'd like" point of view it does make sense, but from a practical standpoint it's not implementable. Ambidex's answer goes a good way towards explaining why that is
Comment: @MPD That would be a piece of "logics" implementation for your summary of nodes, it still is not a reference to your node itself but a position in a summary of nodes, so that should not be in a path (nor alias).
Comment: Why would you be using pathauto for this? It is not actually part of the "path", since it is only an anchor. We will be needing more info about where you are trying to implement this.
Comment: @NeverQuit Please read Ambidex's comment. Fragments are not part of the path, it doesn't make sense to add a fragment to a URL alias (and you can't do it). You should add the fragment to the end of a URL in a **link** that points to the path
Comment: @Ambidex I'm using this at one of my content->URL path settings-> URL alias = "testimonials#group-1". But browser encode '#' to %23 so it gives an error.
Comment: I can think of a few instances were having a fragment as part of the pathalias would make sense.  Like when you have nodes that never live on their own, but are always part of a view.
Comment: I've got a site where I don't want to display nodes directly. All nodes are in Views, on my site i've got search form. Search results gives me direct links to nodes, i want to modify them to point to page with View which contains searched node. I also want to move user to this node using anchor. This is my idea, You tell i can't do it this way so which way i can achieve this?
Answer: I think you are trying to add anchors to a node's alias to define multiple sections in a node, which is impossible since an anchor destination is not part of a path and therefor not part of an alias. For more information, see the W3 introduction on links in HTML.
Creating a anchor: If you would like to subsection your node's body, you should use anchors in your code:
 ...

If you're using the WYSIWYG module, make sure you've got the Anchor plugin enabled, so you can create the anchors through the nicely builtin anchor plugin's GUI, which makes it that much easier.
Linking to an anchor: After creating an anchor, you can link to that section by making a hyperlink as follows:
Link text

To build the above link in the Drupal-way:
<?php print l('Link text', 'path/to/node', array('fragment' => 'anchorOne')); ?>

Or to only build the URL including the anchor destination:
<?php print url('path/to/node', NULL, 'anchorOne'); ?>

Answer: It's called a fragment identifier, and is done with the l() function:
$options = array('fragment' => 'group-1');
l('Anchor', 'path', $options);

Answer: First of all, set the Pathauto pattens for the content type testimonial to /testimonials/[node:title]. This could later on be useful if you display one testimonial as a node, for instance if you don't include the full node in the view below.
Then create a view that lists all your testimonials, and show them as a page on the URL /testimonials. Use the style Unformatted, and make sure you include the Title in the rows class (using the "Style > Style > Settings" in views), you could be use Anchor-[title] (show you later on why the 'Anchor_'-part).
Then make a special versions of the views-view-unformatted.tpl.php (eg. views-view-unformatted--.tpl.php) and put it in your own themes folder (where it fits).
<?php foreach ($rows as $id => $row): ?>
  <div <?php if ($classes_array[$id]) { print 'class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>

<?php endforeach; ?>

Make a small PHP snippet that fetches the rows styles and then find the one class that contains the "Anchor-Title".
<?php foreach ($rows as $id => $row): ?>
  <div <?php if ($classes_array[$id]) { print 'class="' . $classes_array[$id] .'"';  } ?>>
    <?php
      if ($classes_array[$id]) {
        $classes = explode(" ", $classes_array[$id]);
        for ($i=0;$i<count();$i++) {
          if (strpos($classes[$i], "Anchor_") === 0) {
            list($tmp, $anchor) = explode("_", $classes[$i]);
    ?>
    <a name="<?php print $anchor; ?>">
    <?php
          }
        }
      }
    ?>
    <?php print $row; ?>

<?php endforeach; ?>

Perhaps the code can be optimized, but that's only something to get you started...
BTW: To create a "menu" on the top, you could add a header to the view that's containing a view that makes links out of titles. Eg.
  Link text

anchor (#) in url alias


Adding a new column to users table: db_drop_field errror

Question: I'm trying to add a column to the 'users' table. When I install my module, the column gets created and when I uninstall it gets deleted.
The issue is that after I uninstalled, I run a 'drush cc all' and I receive this error:

WD php: PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown[error]
  column 'base.firstname' in 'field list': SELECT base.uid AS uid,
  base.name AS name, base.pass AS pass, base.mail AS mail, base.theme
  AS theme, base.signature AS signature, base.signature_format AS
  signature_format, base.created AS created, base.access AS access,
  base.login AS login, base.status AS status, base.timezone AS
  timezone, base.language AS language, base.picture AS picture,
  base.init AS init, base.data AS data, base.firstname AS firstname
  FROM
  {users} base
  WHERE  (base.uid IN  (:db_condition_placeholder_0)) ; Array
  (
      [:db_condition_placeholder_0] => 0
  )
   in DrupalDefaultEntityController->load() (line 193 of
  /var/www/includes/entity.inc).

Here is my code inside the .install:
function mymodule_schema_alter(&$schema) {
  $schema['users']['fields']['firstname'] = array(
    'type' => 'varchar',
    'length' => 60,
    'not null' => FALSE,
    'default' => '',
    'description' => 'Field added by profile common module',
  );
}

function  mymodule_install() {
  $schema = drupal_get_schema('users');
  db_add_field('users', 'firstname', $schema['fields']['firstname']);
}

function  mymodule_uninstall() {
  db_drop_field('users', 'firstname');
}

Thanks.
Comment: Did you re-install the module after adding the new field? If not, you either need to do so, or put your `db_add_field()` logic in an update hook
Comment: In order to get rid of the error, I simply add the field manually with mysql and add db_drop_field('users', 'firstname'); into the hook_install and re-install the module. Could it be smthg wrong with db_drop_field() ? Or, the schema does not get updated ? If I can't solve this mystery I will create a custom table. Thanks
Answer: There is the difference between hook_schema() and hook_schema_alter(): The first is used to create a database table when a module is installed, but the second is not used to alter an existing database table when a module is installed. hook_schema_alter() is used to alter the values returned from hook_schema() to let other modules know an existing database table (created from a module) has been altered (from another module).
What you need to to is:

Implement hook_schema_alter() to make public the changes you made to a database table created from another module
Make the changes in that database table, in hook_install() or hook_update_N()

The reason you need to alter what returned from hook_schema() is that there are functions that write on the database which use the information returned from hook_schema(), in primis drupal_write_record().
  $schema = drupal_get_schema($table);
  if (empty($schema)) {
    return FALSE;
  }

  $object = (object) $record;
  $fields = array();

  // Go through the schema to determine fields to write.
  foreach ($schema ['fields'] as $field => $info) {
    if ($info ['type'] == 'serial') {
      // Skip serial types if we are updating.
      if (!empty($primary_keys)) {
        continue;
      }
      // Track serial field so we can helpfully populate them after the query.
      // NOTE: Each table should come with one serial field only.
      $serial = $field;
    }

    // …
  }

Without hook_schema_alter(), which is invoked from drupal_get_schema(), such functions would not be able to correctly write on the database tables.
Comment: As side note, the use of `hook_schema_alter()` is generally discouraged, since in most of the cases it is preferable to use an extra table. It causes less problems than more than one module trying to alter the same database table, since in such case there could be some problems when the single modules are uninstalled at different times.


Cannot delete orphaned domain with ntdsutil

Question: I have a problem deleting an orphaned subdomain from a Windows Server 2008 R2 AD. The situation is as follows:

dcpromo failed in demoting the only DC of the subdomain. The DC was therefore demoted forcefully.
No DC for the subdomain is in the AD at the moment (as shown in GUI).
If I use ntdsutil and connect to the sub domain, it says that there is no site, no server and no naming context for the domain.
The subdomain shows in AD domains and trusts, but I cannot do anything, because it cannot find a DC for the subdomain.

If I call "remove selected domain" for the subdomain, the tool asks for confirmations but then fails with error 0x2162, i. e. it tells me that there are still DCs left for the subdomain. However, I cannot delete any DCs or naming contexts using ntdsutil, because it does not show any.
Any suggestions on removing the domain are welcome.
Answer: Surely this is not the best approach but look for the orphaned DC in AD Sites and Services. If you find it there then delete it's NTDS Settings component, then delete the server, then delete the Site and Subnet for the orphaned domain (if the site and subnet is not valid for the remaining parent domain), then delete the domain from AD Domains and Trusts. You'll wind up with some DNS cleanup to do more than likely and may need to do some cleanup with ADSIEdit as well.
Comment: Unfortunately, the server of the subdomain is not in AD Sites and Services. I can only find the two DCs of our primary domain.
Comment: Btw, i cannot find the subdomain in the DNS settings any more, it is just in the AD domains and trusts.
Answer: I found the solution at http://www.winserverkb.com/Uwe/Forum.aspx/windows-2000-active-directory/10198/DsRemoveDsDomainW-error-0x2162. There was an old entry in CN=LostAndFoundConfig,CN=Configuration,... containing references to the subdomain. After removing this, I could remove the subdomain from AD domains and trusts.


Como criar tags internas no Site. Ex: HOME FAQ CONTACT etc

Question: Sou novo no grupo overflow e também em HTML. Ja tenho os conhecimentos básicos de html mas gostaria de saber como criar tags internas no meu site que facilitem o usuario acessar o Home, FAQ, Contactos etc . Por exempo: HOME FAQ CONTACT ABOUT ME. mas em tabelinhas acessíveis. Agradecia pela resposta.
Comment: Deve ser mais específico e detalhar a pergunta. Veja: http://pt.stackoverflow.com/tour
Answer: Olá!
Não sei ao certo se percebi a sua pergunta, mas creio que está a querer fazer uma barra de navegação. Se sim, a forma mais fácil é utilizar uma lista de itens:

HOME

FAQ

ABOUT ME

E depois formatar esta lista com CSS. Algo como:
    * {
      box-sizing:border-box;
    }

    nav{
      display: block;
      background-color: #eee;
      width: 100%;
    }

    a:link, a:active, a:visited{
      font-family: Arial;
      color: #000;
      text-decoration: none;
    }

    a:hover{
      background-color: #CC00FF;
    }

    .ativo_h{
      background-color: rgb(153,255,102);
      border-bottom: 5px solid rgb(102,0,153);
    }

    .n1 ul {
        list-style-type: none;
        margin: 0px;
        padding: 0px;
        overflow: hidden;
    }

    .n1 li {
      float: left;
    }

    .n1 li a {
      display: block;
      width: 100%;
      padding:20px;
    }

Obviamente, a formatação não tem que ser esta e pode ser feita de outras formas, em todo o caso, espero que ajude a responder à sua dúvida.
Comment: E isto mesmo que eu queria saber so que por ser novo nao sabia que a expressao correcta e "barra de navegacao"  mesmo assim estou grato.


Yum installation corrupts lib on Redhat Ubi8

Question: I'm working on a Redhat Ubi8-minimal Container. My goal is to install an .rpm from file together with its dependencies. Ubi8-minimal only provides microdnf which cannot install local .rpm's. So I installed yum using microdnf install yum which runs through fine. Among the output it shows that libmodulemd is being updated:
Updating: libmodulemd;2.13.0-2.fc34;x86_64;Clients_Fedora_34_Fedora_34_Updates

But with the first invocation of yum I get:
[root@7fc9c0e586b1]# yum --version
Traceback (most recent call last):
  File "/usr/bin/yum", line 57, in <module>
    from dnf.cli import main
  File "/usr/lib/python3.9/site-packages/dnf/__init__.py", line 30, in <module>
    import dnf.base
  File "/usr/lib/python3.9/site-packages/dnf/base.py", line 29, in <module>
    import libdnf.transaction
  File "/usr/lib64/python3.9/site-packages/libdnf/__init__.py", line 12, in <module>
    from . import conf
  File "/usr/lib64/python3.9/site-packages/libdnf/conf.py", line 13, in <module>
    from . import _conf
ImportError: /lib64/libmodulemd.so.2: undefined symbol: g_ptr_array_extend_and_steal

After that microdnf too has this problem and is no longer usable:
[root@7fc9c0e586b1]# microdnf --version
microdnf: symbol lookup error: /lib64/libmodulemd.so.2: undefined symbol: g_ptr_array_extend_and_steal

so I cannot manage any packages and installations anymore.
How can I fix this and get yum to work on Ubi8?
Details
Here is what I find in a fresh container after running podman --it --rm docker.io/redhat/ubi8-minimal bash
/etc/yum.repos.d/ubi.repo
Here is the contents of /etc/yum.repos.d/ubi.repo.
[ubi-8-baseos]
name = Red Hat Universal Base Image 8 (RPMs) - BaseOS
baseurl = https://cdn-ubi.redhat.com/content/public/ubi/dist/ubi8/8/$basearch/baseos/os
enabled = 1
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release
gpgcheck = 1

[ubi-8-baseos-debug]
name = Red Hat Universal Base Image 8 (Debug RPMs) - BaseOS
baseurl = https://cdn-ubi.redhat.com/content/public/ubi/dist/ubi8/8/$basearch/baseos/debug
enabled = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release
gpgcheck = 1

[ubi-8-baseos-source]
name = Red Hat Universal Base Image 8 (Source RPMs) - BaseOS
baseurl = https://cdn-ubi.redhat.com/content/public/ubi/dist/ubi8/8/$basearch/baseos/source/SRPMS
enabled = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release
gpgcheck = 1

[ubi-8-appstream]
name = Red Hat Universal Base Image 8 (RPMs) - AppStream
baseurl = https://cdn-ubi.redhat.com/content/public/ubi/dist/ubi8/8/$basearch/appstream/os
enabled = 1
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release
gpgcheck = 1

[ubi-8-appstream-debug]
name = Red Hat Universal Base Image 8 (Debug RPMs) - AppStream
baseurl = https://cdn-ubi.redhat.com/content/public/ubi/dist/ubi8/8/$basearch/appstream/debug
enabled = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release
gpgcheck = 1

[ubi-8-appstream-source]
name = Red Hat Universal Base Image 8 (Source RPMs) - AppStream
baseurl = https://cdn-ubi.redhat.com/content/public/ubi/dist/ubi8/8/$basearch/appstream/source/SRPMS
enabled = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release
gpgcheck = 1

[ubi-8-codeready-builder]
name = Red Hat Universal Base Image 8 (RPMs) - CodeReady Builder
baseurl = https://cdn-ubi.redhat.com/content/public/ubi/dist/ubi8/8/$basearch/codeready-builder/os
enabled = 1
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release
gpgcheck = 1

[ubi-8-codeready-builder-debug]
name = Red Hat Universal Base Image 8 (Debug RPMs) - CodeReady Builder
baseurl = https://cdn-ubi.redhat.com/content/public/ubi/dist/ubi8/8/$basearch/codeready-builder/debug
enabled = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release
gpgcheck = 1

[ubi-8-codeready-builder-source]
name = Red Hat Universal Base Image 8 (Source RPMs) - CodeReady Builder
baseurl = https://cdn-ubi.redhat.com/content/public/ubi/dist/ubi8/8/$basearch/codeready-builder/source/SRPMS
enabled = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release
gpgcheck = 1

This is also the only .repo file in the directory. I have not actively enabled any other repos.
microdnf repolist --enabled
Here is the output of the microdnf repolist --enabled command.
repo id                                                                                repo name
Clients_Extra-Software_Fedora                                                                      Fedora
Clients_Fedora_34_Fedora_34_Everything                                                             Fedora 34 Everything
Clients_Fedora_34_Fedora_34_Updates                                                                Fedora 34 Updates
Clients_RPM_Fusion_Fedora_34_RPM_Fusion_Free_OS                                                    RPM Fusion Free OS 34
Clients_RPM_Fusion_Fedora_34_RPM_Fusion_Free_Updates                                               RPM Fusion Free Updates 34
Clients_RPM_Fusion_Fedora_34_RPM_Fusion_Nonfree_OS                                                 RPM Fusion Nonfree OS 34
Clients_RPM_Fusion_Fedora_34_RPM_Fusion_Nonfree_Updates                                            RPM Fusion Nonfree Updates 34
Clients_Trinity_Desktop_Environment_Fedora_34_Trinity_Desktop_Environment_Fedora_34_noarch         Trinity Desktop Environment Fedora 34 noarch
Clients_Trinity_Desktop_Environment_Fedora_34_Trinity_Desktop_Environment_Fedora_34_x86_64         Trinity Desktop Environment Fedora 34 x86_64
ubi-8-appstream                                                                                Red Hat Universal Base Image 8 (RPMs) - AppStream
ubi-8-baseos                                                                                Red Hat Universal Base Image 8 (RPMs) - BaseOS
ubi-8-codeready-builder                                                                            Red Hat Universal Base Image 8 (RPMs) - CodeReady Builder

Which is quite confusing to me, as it doesn't match the contents of ubi.repo.
Comment: Of course I could use the full `ubi8` that already contains `yum` in the first place. But the question is how can I successfully install `yum` on a `ubi8-minimal`.
Answer: When any dnf command results in an undefined symbol, your package manager is badly broken. fc34 tag implies Fedora 34 based updates, which is not going to work with an el8 based distro. Find out what is using Fedora repos here.
Review documentation for hints as to how to run a full dnf command on a container. RHEL 8 on building containers makes use of yum's install into a chroot feature to do this even with micro containers.  From the host:
yum install \
    --installroot $micromount \
    --releasever 8 \
    --setopt install_weak_deps=false \
    --nodocs -y \
    httpd

Where $micromount is a mounted container root file system, --releasever 8 is the el version of the continer, and httpd is the package you want to install. Also repair your dnf install, possibly with  yum reinstall libmodulemd microdnf
Comment: Thanks, that's very interesting. I wasn't aware that you could install into containers from outside. But just starting a `docker.io/redhat/ubi8-minimal` image, the contained `/etc/yum.repos.d/ubi.repo` only contains repos pointing to `cdn-ubi.redhat.com/*/ubi8/` . Yet, issuing `microdnf install yum` lists multiple packages that have `Clients_Fedora_34_Fedora_34_*` repositories: ```Installing:    dbus-1:1.12.20-3.fc34.x86_64     Clients_Fedora_34_Fedora_34_Everything 155.1 kB
 deltarpm-3.6.2-8.fc34.x86_64     Clients_Fedora_34_Fedora_34_Everything 91.7 kB
...```. So I guess this is by design?
Comment: Please edit your question to add the contents of  `/etc/yum.repos.d/ubi.repo`  and the config for any other enabled repo (`dnf repolist --enabled`)   I have not investigated ubi repos in depth, but   in https://cdn-ubi.redhat.com/content/public/ubi/dist/ubi8/8/x86_64/baseos/os/Packages/l/  libmodulemd is tagged for el8, not fc34.
Comment: Also try starting from scratch, starting from a clean ubi base image.  Install only packages in the ubi repo (aka a subset of RHEL 8) at the beginning. Your "need to install local rpm" requirement could mean some other thing you installed broke your repos. Some instructions to install Fedora things from rpms perhaps?
Comment: I've updated the question with technical details. This is what I get starting from scratch, after doing `podman pull ubi8-minimal` a few weeks ago chosing the docker.io image, then issuing `podman run --it --rm redhat/ubi8-minimal bash`. The only installation changing command I then gave was `microdnf install yum` to produce the error, so no other package has been installed in between, and no other repo has been added manually.
Comment: Something weird is going on on my side. I've re-pulled the `ubi8-minimal` image, to make sure I'm up-to-date. Now, `/etc/yum.repos.d/` has a new file, `redhat.repo`, which contains all those `Clients_*_Fedora` repos. Strangely, all their URLs point to a host on our corporate internal network. When I edit this file, or remove it, it reappears in its original form after the next `microdnf` command. Can you manipulate an image in such a way? Is this done on an internal host of our network, when I thought I was pulling directly from `docker.io`?
Comment: Ok, things seem to clear up: It appears there is an interaction between the running ubi8 container and the `subscription-manager` on the host system. Maybe I oversaw the `redhat.repo` file at first and it was there all the time, which would explain all those `Clients_*_Fedora` repos being involved.
Answer: Thanks to hints from John Mahowald pointing at fc34 repos getting involved, a workaround solution is to exclude the Fedora repos when installing yum:
microdnf install --disablerepo="Clients_*" yum

This leads to a working yum installation:
[root@4f6b589029d5]# yum --version
4.7.0
  Installed: dnf-0:4.7.0-8.el8.noarch at Mon Aug 22 06:56:42 2022
  Built    : Red Hat, Inc. <http://bugzilla.redhat.com/bugzilla> at Fri Mar 18 15:21:28 2022

  Installed: rpm-0:4.14.3-23.el8.x86_64 at Tue Jul 26 12:26:21 2022
  Built    : Red Hat, Inc. <http://bugzilla.redhat.com/bugzilla> at Tue Apr  5 18:38:09 2022

The reason why this is necessary in the first place seems to be an interaction of the container with the subscription-manager of the host system which projects subscription information into the running container. Besides mentionings of other users and my own experience I haven't found any primary documentation on this, though.


Save tcp sessions in nodejs / redis?

Question: I'm currently learning node.js by developing a small chat application over TCP (classic case).
What I would like to do now is to extend this application to use static users:

All logic around messaging should be based on users rather than
sessions.
Each session therefore needs to be saved along with a
reference to the user (so that the application can send messages in
the correct session based on user name).
I have looked into Redis to store this data but not been successful so far.
<code>        tcpServer.on 'connection', (tcpSocket) -> tcpSocket.write "Welcome"
        redis.hmset("sessions", userid, tcpSocket)
        tcpSocket.on "data", (data) ->
            redis.hvals "sessions", (err, repl) ->
                repl.forEach (reply, y) ->
                    reply.Write("Data is written to clients!")
    tcpServer.listen 7000
</code>

Current error message: TypeError: Object [object Object] has no method 'write'
This indicates that I cannot store a tcpSocket as I'm trying to do right now. Can someone tell me if I can make minor adjustments to make this right or should I rethinkt this solution?
Answer: Redis supports very few data types: string, lists, sets, sorted lists and hash tables. That's it. Some other types, like Date, can be easily converted to/from string, so it can be used too. But socket is a complex internal object, so you most probably can't convert it into string and therefore can't store in Redis.
Answer: Since socket objects are to complex to store in Redis it seems like the way to go is to add identifier to the object according to link below.
This identifier could then of course be saved in a database to create realtions between different objects etc.
How to uniquely identify a socket with Node.js

Save tcp sessions in nodejs / redis?


Problems setting up facebook screenshot-tests-for-android

Question: I am trying to setup facebook's screenshot-tests-for-android (v0.8.0) on our android app and I get the following error:
java.lang.RuntimeException: Failed to create the directory /sdcard/screenshots/com.schibsted.peil.android.dev.test/screenshots-default for screenshots. Is your sdcard directory read-only?
at com.facebook.testing.screenshot.internal.ScreenshotDirectories.getSdcardDir(ScreenshotDirectories.java:121)
at com.facebook.testing.screenshot.internal.ScreenshotDirectories.get(ScreenshotDirectories.java:53)
at com.facebook.testing.screenshot.internal.AlbumImpl.<init>(AlbumImpl.java:44)
at com.facebook.testing.screenshot.internal.AlbumImpl.create(AlbumImpl.java:49)
at com.facebook.testing.screenshot.internal.ScreenshotImpl.create(ScreenshotImpl.java:66)
at com.facebook.testing.screenshot.internal.ScreenshotImpl.getInstance(ScreenshotImpl.java:84)
at com.facebook.testing.screenshot.Screenshot.snap(Screenshot.java:38)
at com.sample.myapp.ThirteenCardScreenshotTest.testScreenshot(ThirteenCardScreenshotTest.kt:24)

It seems something happens regarding the permissions to run the instrumented tests, on my apps AndroidManifest.xml I explicitly set the WRITE_EXTERNAL_STORAGE permission that the library needs, but it seems it's not available on the instrumentation tests? or something else?
does anyone has experience with this library? any suggestions?
my test looks like:
package com.sample.myapp

import android.widget.LinearLayout
import androidx.test.InstrumentationRegistry
import com.facebook.testing.screenshot.Screenshot
import com.facebook.testing.screenshot.ViewHelpers
import com.sample.myapp.feed.FooterStoryViewHolder
import org.junit.Test

class ThirteenCardScreenshotTest {
    @Test
    fun testScreenshot() {
        val context = InstrumentationRegistry.getInstrumentation().targetContext

        val view = LinearLayout(context)
        val viewHolder = FooterStoryViewHolder(view)
        view.addView(viewHolder.itemView)

        ViewHelpers.setupView(view)
            .setExactWidthDp(360)
            .setExactHeightDp(740)
            .layout()

        Screenshot.snap(view)
            .record()
    }
}

And the workaround proposed in https://github.com/facebook/screenshot-tests-for-android/issues/162 doesn't work for me
Comment: Also running into this issue - only on API 29 and higher.
Answer: If you have debug environment for the app add this into its manifest:
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

If not then u'll have to put it in the default app manifest
Comment: This is not the answer to the problem.


Is there any reason to practice scales over multiple octaves?

Question: I've found the following poster online https://www.amazon.co.uk/Really-Useful-Piano-Poster-Beginners/dp/B07DWD25FF/ref=sr_1_7?dchild=1&keywords=THE+REALLY+USEFUL+POSTER+COMPANY&qid=1609079047&sr=8-7. Sadly, it doesn't come with the fingering for playing the different scales in multiple octaves.
What are the advantages at becoming proficient at playing the different scales in multiple octaves?
Thanks in advance :)
Comment: If you are interested in piano only, you may tag the question accordingly. For all  instruments lacking a keyboard (maybe requiring to overblow) this is much more different.
Answer: The answer may depend on the instrument.  Every instrument works based on physics and it may be harder to play notes in certain registers.  This is especially true for brass and woodwind.  Practicing in one octave then trying to perform the same piece an octave higher without practice could be difficult. On guitar, the frets get closer together making playing in different octaves feel different.
I see from your link that this is piano related.  Even thought every octave looks (and perhaps feels) the same one thing piano players need to be able to do is shift position as they climb up and down the keyboard.  This requires some dexterity and planning.  So, unless the shift  within the octave is identical to the shift to the next octave I'd say you need to practice at least two octaves to ensure you will be able to shift smoothly.
Comment: It's probably also worth practicing both hands (and maybe the transition between the two) on a piano too.
Comment: Great point....
Answer: Basing this answer on piano - clue in question!
Playing a scale one octave only means most of the time, you'll play the highest note (r.h.) with pinky, wheras playing two, or three or more octaves necessitates 'starting again', where your thumb, usually, goes onto the tonic for the next octave each time.
So with that in mind, two octaves seem like the minimum. But why not carry on to three, or maybe four? In more advanced playing, your hands will become farther apart, so you're setting yourself up for when this happens. The arms' angles change, which means even simple scales will be played subtly differently.
From memory, I think scales on piano for exams go to three octaves in the higher grades, so that seems a reasonable target.
If, by any chance, you're considering the question relates to other instruments, there are many good reasons to play as many octaves as the instrument (and player!) are capable of.
Answer: The poster has little numbers on the keys for the RH/LH fingerings.
It's kind of sloppy in representing the fingerings. Some like C major use the 5 finger for a one octave scale. Others like Db major give a fingering that will repeat at the octave.
You should be able to replace the 5 with 1 to get things to repeat at the octave. Ex. C major RH is given as 123,1234,5 play it multi-octave as 123,1234,123,1234. (I added the comma to show how all the scales can be played as finger groupings of 123,1234 although the tonic isn't necessarily played with finger 1 or 5.)
The poster might be helpful for the visual aspect, but I would get a better resource for fingerings. Get a method book that gives fingerings for scales in all keys, chords on all roots and inversions, and scales in double notes. Some of the fingerings for these will differ slightly from one method book to another. You might be two complementary books. Better methods will explain principles for fingerings.
Comment: (I added the comma to show how all the scales can be played as finger groupings of 123,1234 although the tonic isn't necessarily played with finger 1 or 5.). That's really useful. Thanks!
Comment: Do you recommend a specific method book?
Comment: I have a few from IMSLP. This one by Knott https://imslp.org/wiki/Scale_and_Arpeggio_Manual_%28Knott,_Thomas_B.%29 has a nice visual for those 3 + 4 finger groupings and others, this other one by Cooke https://imslp.org/wiki/Mastering_the_Scales_and_Arpeggios_(Cooke%2C_James_Francis) I reference a lot too.
Answer: Playing in all octaves and using various instruments will give your ears special experience to recognize and absorb sounds and scores. Fingering is another question: you can play it in several possible patterns and change it on different octaves, if you wish.
Comment: There's multiple finger patterns for each scale?


Limiting case of of integral.

Question: Let $f(x)= \lim\limits_{n \to \infty}\dfrac{\cos x}{1+(\arctan x)^n} $ then,
Evaluate $\int_0^\infty f(x)\,dx.$
ATTEMPT:
Here $$I=\int _o^\infty \lim\limits_{n \to \infty} \frac{\cos x}{1 + (\arctan x)^n} \, dx.$$
Clearly $f(x)$ is non- integrable in this case.
I  tried the following substitution:
Let $\arctan x=t$
$dx=\sec^2t \, dt$
So $$I=\int_0^{\frac{\pi}{2}} \lim\limits_{n \to \infty} \frac{\cos(\tan t) \sec^2t}{1+t^n} \, dt.$$
But this again is non-integrable
I believe there is some other approach for this problem.
Answer: For $x>0$, we have $\arctan(x)<1$ for $0<x<\tan(1)$.  For $x>\tan(1)$, $\arctan(x)>1$.  Thus,
$$f(x)=
\begin{cases}
\cos x,& 0<x<\tan(1)\\\\
0,&x>\tan(1)
\end{cases}
$$
Therefore,
$$\int_0^{\infty}f(x) dx=\sin(\tan(1))$$
Answer: Simply compute your function $f$, and then plug it into the integral.
For $x > \tan 1$ you have $\arctan x > 1$, so $(\arctan x)^n+1 \to + \infty$.
This means that $f(x) = 0$ for $x > \tan 1$.
Clearly, for $0 < x < \tan 1$ you have the same argument, and $f(x)=\cos x$, and finally $f( \tan 1)$ does not matter for the integral.
So
$$\int_0^{\infty} f(x) dx = \int_0^{\tan 1}\cos x \ \ dx = \sin (\tan 1)$$
Comment: But the answer is $sin(tan1).$ not $\frac{1}{\sqrt2}.$
Comment: @yasir Please see my comment.
Comment: Oh, you all are right! I confused $\tan$ with $\arctan$.
Comment: @Crostul No worry.  My eyes have done worse to me.  ;-))

Limiting case of of integral.


Custom field type with imagefield

Question: I'm creating a widget with an image field. But I keep writing 0 to the database. But i need the fid to be saved. I know I can manipulate the data with hook_field_presave(). But the items array only contains image => '0'.
mymodule.module
/**
* Implements hook_field_widget_form().
*/
function mymodule_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
...
  $element['image'] = array(
    '#type' => 'managed_file',
    '#name' => 'mymodule_custom_image',
    '#title' => t('Image'),
    '#size' => 40,
    '#description' => t(""),
    '#upload_location' => 'public://',
    '#theme' => 'mymodule_custom_thumb_upload',
  );
...
}

Edit:
/**
* Implements hook_field_widget_info().
*/
function mymodule_field_widget_info() {
  return array(
    'mymodule_polygone_widget' => array(
      'label' => t('Default'),
      'field types' => array('mymodule_polygone'),
    ),
  );
}

mymodule.install
/*
* Implements hook_field_schema().
*/
function mymodule_field_schema($field) {
  $columns = array(
    'image' => array('type' => 'varchar', 'length' => 255, 'not null' => TRUE),
    'zones' => array('type' => 'text'),
  );

  return array(
    'columns' => $columns,
    'indexes' => array(),
  );
}

Comment: On your hook_field_widget_info() function what do you have as your return statement? This actually matters
Comment: Added the code :).
Comment: Well I apologize, I meant what is the return on your hook_field_widget_form not info. I'm sorry about that.
Answer: Found it: Forgot the 'input ...' in my custom theme function :).
function theme_mymodule_thumb_upload($variables) {
  $element = $variables['element'];

  if (isset($element['#file']->uri)) {
      $output = '

';
      $output .= 'uri) . '" />';
      $output .= '<input type="submit" id="edit-' . $element['#name'] . '-remove-button" name="' . $element['#name'] . '_remove_button" value="Remove" class="form-submit ajax-processed">';
      $output .= '<input type="hidden" name="' . $element['#name'] . '[fid]" value="' . $element['#file']->fid . '">';

      return $output;
  }
}

Custom field type with imagefield


Cloudformation ELB Cloudwatch Alarms InsufficientData

Question: I have setup a bunch of cloudwatch alarms for my service using cloudformation. All my alarms work except for the ELB alarms. They always just show insufficient data. I can go into the console and setup the alarms manually but I want to be able to use cloudformation templates to create everything. I must have an error somewhere in my json for the alarm. Here is one of them:
"ELBHighLatencyAlarm": {
    "Type": "AWS::CloudWatch::Alarm",
    "Properties": {
        "Namespace": "AWS/ELB",
        "AlarmName": { "Fn::Join" : ["", [ { "Ref" : "AWS::StackName"}, "-ELB-ELBHighLatencyAlarm"]]},
        "AlarmDescription":  { "Fn::Join" : ["", [ { "Ref" : "AWS::StackName"}, "-ELB-ELBHighLatencyAlarm"]]},
        "ComparisonOperator": "GreaterThanThreshold",
        "Threshold": "0.5",
        "EvaluationPeriods": "1",
        "Period": "300",
        "MetricName": "Latency",
        "Statistic": "Average",
        "OKActions": [],
        "AlarmActions": [ { "Ref": "PagerDutySNSTopicArn" } ],
        "InsufficientDataActions": [ { "Ref": "PagerDutySNSTopicArn" } ],
        "Dimensions": [ {
            "Name": "ElasticLoadBalancer",
            "Value": { "Ref": "WebServerLoadBalancer" }
        }]
    }
}

Do you see anything wrong with it?
Comment: If you still have the issue, can you share a SNS notification? I had a similar issue and fixing some auto-scaling grace time could help.å
Comment: @PatriceLaramée sorry, never found the issue
Answer: I can confirm what Dojo said above. Although the wording in the description of the dimensions block makes it seem as though it is not required and strings/values are arbitrary, there is a specific list of names that can be used for each type of service you want to create an alarm for. This list maps the service type to allowable values for in the dimensions block, which makes your alarms work correctly.
It seems to me that the dimensions block is a way of filtering events. So if you wanted to see CPUUtilization for a cluster, you would provide ClusterName. If you want the specific service of a cluster, you would provide 2 entries to the dimensions block. ClusterName and ServiceName.
http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ecs-metricscollected.html
The only difference between the two examples below is the Dimensions.Name field.
Example which will NOT work
"CPUUtilizationScaleInAlarm": {
  "Type": "AWS::CloudWatch::Alarm",
  "Properties": {
    "ActionsEnabled": true,
    "AlarmActions": [
      {
        "Ref": "ESCServiceScaleInPolicy"
      }
    ],
    "AlarmDescription": "Scale in in response to CPUUtilization being low",
    "AlarmName": "CPUUtilizationScaleIn",
    "ComparisonOperator": "LessThanOrEqualToThreshold",
    "Dimensions": [
      {
        "Name": "ECService",
        "Value": "MyAwesomeService"
    ],
    "EvaluationPeriods": 1,
    "MetricName": "CPUUtilization",
    "Namespace": "AWS/ECS",
    "Period": 60,
    "Statistic": "Average",
    "Threshold": 25,
    "Unit": "Percent"
  }
}

Example which WILL work
"CPUUtilizationScaleInAlarm": {
  "Type": "AWS::CloudWatch::Alarm",
  "Properties": {
    "ActionsEnabled": true,
    "AlarmActions": [
      {
        "Ref": "ESCServiceScaleInPolicy"
      }
    ],
    "AlarmDescription": "Scale in in response to CPUUtilization being low",
    "AlarmName": "CPUUtilizationScaleIn",
    "ComparisonOperator": "LessThanOrEqualToThreshold",
    "Dimensions": [
      {
        "Name": "ServiceName",
        "Value": "MyAwesomeService"
    ],
    "EvaluationPeriods": 1,
    "MetricName": "CPUUtilization",
    "Namespace": "AWS/ECS",
    "Period": 60,
    "Statistic": "Average",
    "Threshold": 25,
    "Unit": "Percent"
  }
}

Answer: Your "Dimensions" section is not using the proper "Name" value. If you replace:
 "Dimensions": [ {
            "Name": "ElasticLoadBalancer",
            "Value": { "Ref": "WebServerLoadBalancer" }
        }]

with
 "Dimensions": [ {
            "Name": "LoadBalancerName",
            "Value": { "Ref": "WebServerLoadBalancer" }
        }]

you should find that your alarm will work.


Sudo reboot -f hangs

Question: When I do sudo reboot -f the server reboots, but the terminal just says "rebooting" and doesnt exit out.  I have to actually press ctrl-c to have it exit.  Is there a way to get the server to exit out without me pressing ctrl-c.  Also I have to use sudo reboot -f.
Answer: When you use sudo reboot -f, the operating system performs a fast reboot: the kernel does the minimal necessary actions to shut down without severe filesystem corruption. In a fast reboot, proper termination of processes, including sshd, is considered unimportant. The scheduler just stops giving processes any more execution time as the kernel concentrates on a quick flush of the disk caches and any other kernel-level shutdown actions.
(As a result, some files may be left open. However, on modern journaling filesystems, these things are normally fixable by the quick filesystem check at boot time, as far as the filesystems are considered. But files with important internal structures, like databases, may be left in an inconsistent state. If so, they will likely need application-specific recovery actions... Lesson: Don't use reboot -f unless absolutely necessary.)
Meanwhile, your remote access client will be left hanging: from its viewpoint, the server sent one last message "Rebooting"... and then there was no response at all. No SSH connection termination, not even a TCP FIN. Just silence.
The client will follow the normal TCP retry rules. This can take several minutes, during which nothing visible happens... but all that time, the OS of your client system is trying again and again to resend any outgoing packets your remote access client may have sent after the reboot command.
If the server takes a long time to self-test and restart, the connection will eventually time out as the TCP stack of the client OS gives up trying and reports an error to the remote access application. This will typically take several minutes.
But if the server reboots quickly, when it reaches the point where it will activate its network interfaces again, the server's OS will see the incoming packets from your remote access client. Then the server will consult its freshly-initialized table of active network connections, conclude that there is no record of such a connection, and send back a TCP Reset. When your client receives that, only then it will report that the connection has been forcefully terminated.
Comment: that is an awesome answer!
Answer: Your server is running into issues during the shutdown process, check the contents of /var/log/messages and/or /var/log/syslog for more information and update your original post.
EDIT: I saw your note saying that the reboot works just fine, but you don't disconnect from the server. I'd make sure that your SSH timeout settings aren't set too high locally: https://bjornjohansen.no/ssh-timeout
Comment: no, it reboots just fine.  The issue is I have to press ctrl-c or eit out of the terminal.
Comment: Updated my answer

Sudo reboot -f hangs


How to execute select row(*) in postgres

Question: In postgres you can return a row as a single cell as in the following:
select row(date_created,created_By)
from some_table

However this does not work when you execute select row(*)
Does anybody know how to implement the row() function using asterisk so if my table changes in the future, I will not have to modify my query?
I am using Postgres version 8.4.1
Thank you.
Comment: Why don't you just use `select *`? What is the **real** problem you are trying to solve here? Also: Postgres 8.4 is no longer maintained, you should really plan an upgrade to a supported version as soon as possible (at least use the latest minor version which is 8.4.22)
Answer: You just need to prefix the * with the table-name or table-alias.
Documentation
select row(s.*)
from some_table s

Comment: Genius! Thank you.


How can I show that the following function is measurable?

Question: For $0\leq t_1<t_1<...<t_n \leq 1$, $n\in \mathbb{N}$ we define $$\pi_{t_1,...t_n}:(C[0,1],\mathbb{B}(C[0,1]))\to (\mathbb{R}^n,\mathbb{B}(\mathbb{R}^n)), \quad x\to (x(t_1),...,x(t_n)).$$
$\mathbb{B}(C[0, 1]) := \sigma(G \subseteq C[0, 1] : G \text{ is open})$
How can I show that $\pi_{t_1,...t_n}$ is measurable?
My thinking:
I know that it is enough to show measurability on the generating set $\mathbb{R^n}$. I can write $$\pi_{t_1,...t_n}^{-1}(\mathbb{R}^n)\subseteq \mathbb{B}(C[0,1]).$$ This is equivalent as $$\{x\in C[0,1]|\pi_{t_1,...t_n}(x)\in\mathbb{R}^n\}=\{x\in C[0,1]|(x(t_1),...,x(t_n))\in \mathbb{R}^n\}.$$
I would say that this set is, by definition of $x$, a subset of $C[0,1]$, therefore also a subset $\mathbb{B}(C[0,1]).$
Is this the right way of thinking and more importantly, am I even understanding it correctly? Am I missing something?
Comment: How is $\mathbb{B}(C[0,1])$ generated?
Comment: @d.k.o. It is generated as folows: $\mathbb{B}(C[0, 1]) := \sigma(G \subseteq C[0, 1] : G \text{ is open})$
Comment: Then, the coordinate maps are continuous (in the sup norm, which is typically used in these settings)...
Comment: @d.k.o. Would you please elaborate a little more on this? Thank you!
Answer: Consider the space $C[0,1]$ with the sup norm: $d(f,g):=\sup_{x\in[0,1]}|f(x)-g(x)|$ and the topology on $C[0,1]$ induced by that norm - $\mathcal{O}(C[0,1])$. The $\sigma$-algebra under question is $\mathcal{B}\equiv\sigma(\mathcal{O}(C[0,1]))$. Then every continuous function on $[0,1]$ is measurable w.r.t. $\mathcal{B}$ ($\because$ such functions belong to $\mathcal{O}(C[0,1])$). Therefore, it suffices to show that $\pi_{t_j}$, $j=1,\ldots,n$ is continuous.


Do I need to tag runner while standing on the base?

Question: I am new to baseball, really love it but for me as European the rules are bit unclear. I am confused by this video of Javy Báez. From what I understand as Javy is running back to home plate another player is running there. My question (1) is why the catcher was trying to tag the runner? Maybe so he cannot run back to 3rd base? But anyway catcher was already standing on the plate and had the ball in his glove before runner touched the plate, so I would say runners only option is to run back to 3rd base but (2) as he touches home plate referee signals that the runner is "safe". Why? Many thanks.
Answer: There's a bunch of stuff going on here. The most important distinction is between runners who are "forced" and those who are optionally running - a runner is "forced" if they are no longer entitled to the previous base. This always applies to a batter who has just hit the ball (a "batter-runner"), but also applies to runners who are required to move because the batter-runner is coming up behind them - e.g. a runner on first base when a hit is made, a runner on second when a hit is made if there is also a runner on first. A runner on second when a hit is made is not forced if there is not a runner on first as they can happily just stay on second.
A runner can always be put out by being tagged; a runner who is forced can also be put out but a fielder being in possession of the ball while touching the base they are running to.
That hopefully explains why the catcher was trying to tag the runner from third - the runner was not forced as they started on second with no runner on first.
What this doesn't explain is why the first baseman didn't simply step on first base to put Báez out and then throw home to prevent the runner advancing. There's no good answer to that - the first baseman just totally and utterly screwed up, apparently forgetting the rules of the game they play professionally.
Comment: The runner was _not_ forced so he had to be tagged out.
Comment: Thanks for the fast answer! However I am still not sure why the referee called safe the runner (from third) advancing to home plate? I mean the catcher was in possession of the ball while touching the base before the runner touched the home plate. Does not it mean that he (runner from third) is no longer entitled to reach the home plate?
Comment: So if the runner is not forced he can reach the base and be safe even if there is already standing fielder with ball in his glove? Given the fielder fail to tag the runner.
Comment: Precisely that.
Comment: IIRC, there were two outs, so if the 1B steps on first the inning is over without a need to tag the runner heading home.
Comment: @GreenMatt Fair point - but I can forgive a player forgetting how many outs there are, that's a "not uncommon" occurrence in the major leagues, forgetting how to put out a batter-runner is... odd.


Unable to ping other local subnets when connecting to VPN

Question: I have a local network of several subnets, let's call them subnet A and B.  As expected, one of my clients within subnet A can ping other clients within both subnet A and subnet B.  But as soon as I connect to a remote VPN, the client can no longer ping other clients only on subnet B (but can ping clients on subnet A).
When I use traceroute to figure out where its going, the first entry shows  its going to the IP configured for the VPN network (no big surprise there).
So I'm guessing its either a problem with my VPN settings (using Tunnelblick/OpenVPN) OR a problem with my router (using EdgeLite Router).
But how does one go about troubleshooting this?

UPDATE (Nov 15, 2017 at 2:03pm MST)
@Zoredache thanks for your answer.
I found I can use 'netstat -r' to show the routing table.  I sampled the table both w/ and w/o VPN connected, and got what I expected.  When connected to the VPN, the only difference was new destination addresses added to the utun1 network interface.  But I did notice something that was curious...
<code>$ netstat -r
Routing tables

Internet:
Destination        Gateway            Flags        Refs      Use   Netif Expire
...
10                 192.168.237.17     UGSc            2        0   utun1
...
</code>
What is '10' address here?  Is that really all destination 10.xxx... are routed to the VPN server?   How does this get into the routing table?  And how to have it removed?  Is this a VPN server-side thing?  I suspect this is my problem here.
Answer:
how does one go about troubleshooting this

You start by looking at your route table.  The route table defines where packets will be sent.  When your VPN is connected your routes are different, so packets follow different paths.  You need to make the routes that will send the traffic to through the correct gateways.


how to differentiate docker container and kubernetes pods running in the same host

Question: I was handed a kubernetes cluster to manage. But in the same node, I can see running docker containers (via docker ps) that I could not able to find/relate in the pods/deployments (via kubectl get pods/deployments).
I have tried kubectl describe and docker inspect but could not pick out any differentiating parameters.
How to differentiate which is which?
Comment: where is the issue? If there any pods then you will get it by `kubectl get pods`. You got nothing means there is no pod.
Comment: If you destroy a node and create a new one, the new node will probably only have Kubernetes-managed pods.
Comment: show example, we will explain you where from there containers go. E.g, like @coderanger mentioned, here is a bit info  about technical [pause containers](https://stackoverflow.com/questions/63020184/difference-between-kubernetes-metrics-metrics-resource-v1alpha1-and-metrics/63520661#63520661)
Answer: There will be many. At a minimum you'll see all the pod sandbox pause containers which are normally not visible. Plus possibly anything you run directly such as the control plane if not using static pods.
Comment: I'd add to this that k8s containers are labeled as a Christmas tree.


Group order notation?

Question: I'm working with Dummit and Foote's Abstract Algebra text, and I encountered some notation that confused me.
The theorem I saw it in reads as follows. Suppose $\varphi:G \rightarrow H$ is a homomorphism of groups. then ker $ \varphi \unlhd G$ and $G$/ker $\varphi$ $\cong$ $\varphi(G)$.
The corollary to the theorem reads $|G:$ ker $\varphi |=|\varphi(G)|$
What does this latter expression mean? I don't understand how to interpret  $|G:$ ker $\varphi |$.
Thanks for your help.
Answer: Perhaps you are more familiar with the notation $[G : \ker \phi]$? It means that the index of the subgroup $\ker \phi$ in $G$ is equal to the cardinality of $\phi(G)$, that is, the image of $\phi$.
You can read more on the notion of index of a subgroup here. Dummit & Foote introduce the index of a subgroup at page 90 of Chapter 3.
Comment: So it's the same as saying $|$ker$ \varphi|$, but clarifying it's in $G$?
Comment: No, the index of $H$ in $G$ (where $H$ is a subgroup of $G$) is $\dfrac{o(G)}{o(H)}$, or $\dfrac{|G|}{|H|}$ (and this is guaranteed to be integral as the order of a subgroup divides the order of a group).
Comment: So $|G:$ker $\varphi (G)|$ = $|G|/|\varphi (G)|$?, and the point of the theorem is that this is the same as the numbers of fibers of $\varphi (G)$?

Sorry if I'm being dense.
Comment: Correct. And every fiber (a coset of $\ker \phi$) has the same cardinality as $\ker \phi$.

Group order notation?


Dual Simplex Method

Question: Suppose that in a Linear Programming problem in the dual Simplex Method
there is a first element (in the first column) negative. If there are in that pivot row some negative numbers we take $\max$ from the first row and that pivot row.
But what if all the elements in the pivot row are positive, what pivot do we use, i.e. which column?
Consider this table
$$\begin{array}{|c|c|c|c|c|c|c|c|}\hline
-4& 0 & 1&5&16&0&4&0 \\ \hline
-12& 0 & 8&-1&-7&0&-3&1 \\ \hline
1& 1 & 1&1&1&1&1&1 \\ \hline
\end{array}$$
We take -3 in the second row. OTHER new initial TABLE:
$$\begin{array}{|c|c|c|c|c|c|c|c|}\hline
-4& 0 & 1&5&16&0&4&0 \\ \hline
-12& 0 & 8&1&7&0&3&1 \\ \hline
-1& 1 & 1&1&1&1&1&-1 \\ \hline
\end{array}$$
What do we take here? Note that the first and last element in the last row have
the opposite signs in compared with the previous table.
Comment: A numerical example might be helpful to answer your question. There are multiple related questions which are linked on the right side of this page.
Comment: After $254$ ($\textbf{ !}$) questions you should be able to make a table. [Here](https://math.meta.stackexchange.com/questions/4240/how-do-i-insert-a-table-when-asking-a-question/) you can find the code.
Comment: Your code has helped. Is my edited question OK now?
Comment: Great job (+1). Maybe it would be helpful if you provide the problem before you transformed  into tables. At the moment I just think:"Have she/he made all the steps right before? And what was the original problem?" But this are my thoughts.
Comment: May I suppose that I have these tables at the very beginning? I wanted to separate the first column and the first row by double line as here: = and || but I didn't succeeded.
Comment: Your tables are almost perfect. The name of the columns are missing. And as I said I would need a little more context to give a useful hint or answer.
Comment: By NEXT TABLE I do **not** mean that it is obtained by the Gaussian elimination with some pivot. Rather that they are two different initial tables. Does this help in understanding my question?
Answer: In a problem that you use dual simplex to solve it, if you have a negative RHS and all the elements in that row are non-negative, then your original problem is infeasible and your dual problem is unbounded.

Dual Simplex Method


Como se descobre o termo X da sequência de Fibonacci?

Question: Tenho que fazer um programa em C# que receba um número X que vai ser o termo da sequência e o imprima na tela.
Comment: O que você tentou?
Comment: Dê uma olhada no [tour]. Você pode aceitar uma resposta se ela resolveu seu problema. Você pode votar em todos os posts do site também. Alguma lhe ajudou mais? Precisa que algo seja melhorado?
Answer: Eu ia responder "calculando cada termo até onde você quer". Já estava pensando em em fazer uma solução recursiva e outra repetitiva. Mas aí me veio a ideia de procurar se alguém já tinha pensando em uma solução melhor. E achei isto nessa resposta no SO (e resolvi pelas formas mais tradicionais também):
using static System.Console;
using static System.Math;

public class Program {
    public static void Main() {
        for (int i = 0; i < 20; i++) WriteLine($"{Fib(i)}, {FibIte(i)}, {FibRec(i)}");
    }
    static int Fib(int n) {
        double sqrt5 = Sqrt(5);
        double p1 = (1 + sqrt5) / 2;
        double p2 = -1 * (p1 - 1);
        return (int)((Pow(p1, n) - Pow(p2, n)) / sqrt5);
    }
    static int FibIte(int n) {
        int a = 0;
        int b = 1;
        for (int i = 0; i < n; i++) {
            int temp = a;
            a = b;
            b = temp + b;
        }
        return a;
    }
    static int FibRec(int n) => n < 2 ? n : FibRec(n - 1) + FibRec(n - 2);
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Comment: +1 pela solução que aproxima o número de ouro.


Como extrair o título do link de um menu responsivo?

Question: Tenho a seguinte estrutura de um menu:

Página Inicial

Teste

         Início

Categoria 1

Categoria 2

...

No meu código, quando faço console abaixo:
console.log($('#responsiveAccordion > li .responsiveInykator').parent().children()[1]);

Ele me mostra:
Início

Gostaria de capturar o texto do link: "Início"
Tentei isso mas deu erro:
 console.log($('#responsiveAccordion > li .responsiveInykator')
            .parent()
            .children()[1].text());

Answer: Estavas a fazer mal:
É text e não text()

console.log($('#responsiveAccordion > li .responsiveInykator').parent().children()[1].text);

Página Inicial

Teste

         Início

Categoria 1

Categoria 2

Tal como o Sergio disse com razão, aproveito para complementar dizendo que neste caso funciona bem assim (também funcionaria com, .textContent ou o .innerHTML). Mas existem casos em que não funcionaria fazendo desta forma
Comment: Editado @Sergio. Obgado pela dica
Comment: Ok, erra isso mesmo, obrigado!
Comment: De nada @IvanFerrer
Comment: Miguel (e @IvanFerrer) , vale a pena referir que `.text` [só funciona em alguns elementos](https://jsfiddle.net/6gfLzcjo/1/). É parte da [API do HTML](https://www.w3.org/TR/html5/text-level-semantics.html#dom-a-text) e seria melhor usar o `.textContent` ou o `.innerHTML`.
Answer: Uma vez que esse  é sibling (elemento seguinte no mesmo nível do DOM) podes usar .next() e para usar o texto podess usar .html() ou .text();
var texto = $('#responsiveAccordion > li .responsiveInykator').next().text();
alert(texto);

jsFiddle: https://jsfiddle.net/wo01rf6x/
Comment: Entendi, obgado
Comment: Sergio porque `text()` resulta assim, e não como o Ivan fez?
Comment: @Miguel quando se usa `[1]` fica-se com o elemento do DOM, "raw", que já não é um objeto jQuery. Por isso não dá. Nesse caso `.innerHTML` ou `.textContent` seria o melhor.
Comment: Para não perder o objeto, resolvi da seguinte maneira: `$('#responsiveAccordion > li .responsiveInykator').parent().children('ul li a:eq(0)').text();`


CharSequence in Toast animation not appearing? Android

Question: I am fairly new to Android  development so here is my problem.
I have an array of buttons which I would like to display a Toast saying "This button will launch" + the button's getText value  when pressed.
EDIT
The declaration and initialization code of the buttons array.
 final Button buttons[] = new Button[6];
    buttons[0] = (Button) findViewById(R.id.button1);
    buttons[1] = (Button) findViewById(R.id.button2);
    buttons[2] = (Button) findViewById(R.id.button3);
    buttons[3] = (Button) findViewById(R.id.button4);
    buttons[4] = (Button) findViewById(R.id.button5);
    buttons[5] = (Button) findViewById(R.id.button6);

So,
    for(i = 0; i< buttons.length; i++){
        buttons[i].setOnClickListener(new View.OnClickListener() {
            public void onClick(View v){
                Log.d("test","Why is this not appearing in logcat");
                CharSequence buttonvalue = buttons[i].getText();
                Context context = getApplicationContext();
                System.out.println(buttonvalue);
                CharSequence text = "This button will launch" + buttonvalue + " App!!";
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
            }
        });
    }

The app compiles fine but crashes as soon as I pressed the buttons.And I can't seem to debug it cause both System.out.println() and Logcat is not appearing at all or I am just looking at the wrong place. Where should I find these messages then?
Component Tree:

Here is a screenshot :
Comment: Is your buttons[i] is well initialized?
Comment: Show the full code please.
Comment: try this `buttons[i].getText().toString;`
Comment: @ShaishavJogani why would that help? `getText()` returns a `CharSequence`.
Comment: @user13 It return `Editable` which implements `CharSequence` Take a look https://developer.android.com/reference/android/text/Editable.html
Comment: @ShaishavJogani As i said, `getText()` returns a `CharSeqence`: https://developer.android.com/reference/android/widget/TextView.html#getText() You're basically saying that initializing a `CharSequence` with one of its subclasses should solve this problem. Why would you think that? You're still passing a `CharSequence` to the other methods that way.
Comment: My bad. I though `Button` extends `EditText`
Answer: Try to follow my example it's more simple to implement while you dont have a LogCat:
 private static final int[] idArray = {R.id.button0, R.id.button1, R.id.button2, R.id.button3, R.id.button4, R.id.button5};

private Button[] bt = new Button[idArray.length];

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

    for (int i=0; i<idArray.length; i++) {
        final int b = i;
        bt [b] = (Button)findViewById(idArray[b]); // Fetch the view id from array
        bt [b].setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

 Toast.makeText(getApplicationContext(),"This button will launch" + bt[b].getText().toString() + " App!!";,Toast.LENGTH_LONG).show();                }
        });

    }
}

Comment: Still crashes when I pressed the buttons.Why must it be a String? also edited my question with more code .
Comment: it's really important to share your Log ! to know the problem
Comment: My log is empty when it crashed.I already shared the screenshot.I found out that the error occurs at the declaration of buttonvalue line cause if i removed it then the app works.
Comment: I've updated my answer try to follow my example it's more sample ! Sorry I can't help you enough  if you dont share you LogCat
Comment: Glad I could help :D


"ii and ii6 rarely used to harmonize 6 in the soprano" - for what reason?

Question: In my old theory book, I read that while ii and ii6 harmonize scale degrees 2 and 4, they rarely harmonize scale degree 6 in the soprano.  (I'm assuming they mean for common practice music, SATB).  What would be the reason behind this?  Are there other things to know about that might be related?  For example, I've seen advice about the "II" chord (any quality) in minor keys, due to it being "diminished", where the melodic minor had not yet been introduced, so these other possibilities were not mentioned.
Comment: I like to remind people that the 'rules' that theory dictates are not actually rules but guidelines, which are specific to a genre or an era within a genre.  One example is parallel fifths; not allowed in Classical but exist constantly in most other genres. So I might suggest that this is less a rule about scale degree 6 not being well harmonized by ii than a rule about how to make compositional choices that would align with the standards of the Romantic era. After all, if you are trying to compose a piece of Baroque music, you wouldn't use the same approach (rules) as a Romantic piece.
Comment: I tend to think of theory as an explanation for why things sound good than a set of rules, which seems to align with the great composers, who all broke the rules of their time, essentially creating new possibilities, which become rules, as a result.
Answer: This seems to me to be a strange statement.
For one thing, unless the chord is tonicised as ii, the analysis of the chord as ii is not the only possible analysis. (One way to tonicise it as ii is to precede it by V of ii.) It could also be said to be functionally IV, with 2 being either a non-harmony note or a substitute note for 1.
It seems to me that the question means "When the tune has 6, why is ii rarely used to harmonise it?" -- have I interpreted it correctly? If so, then, for another thing, I'm not sure that it is rare. (I'm analysing the chord as ii anyway, for the sake of argument.)
Mozart is certainly common practice music, so I looked for examples of ii harmonising 6 in his string quartets in major keys. Here are some:

Quartet 14 in G K387, mvt.1, b.19, 37 (3rd beat)
Quartet 17 in Bb K458, mvt.1, b.32
Quartet 18 in A K464, mvt.1, b.86. Also b.59, 63 unless the main pitch in the 1st violin is considered to be A rather than C#.
Quartet 19 in C K465, mvt.1, b.40, 42, 69
Quartet 20 in D K499, mvt.1, b.86
Quartet 22 in Bb K589, mvt.1, b.41
Quartet 23 in F K590, mvt.1, b.5 (after the appoggiatura resolves)
Answer: Without a reference to the book, or a longer quote, any answer is just a guess. "Old" theory books are often very prescriptive, when compared with what composers actually wrote.
That said, in common practice harmony ii and ii6 are often the start of the perfect cadence formula ii-V-I. If you don't want to make a cadence, IV and vi are perfectly good chords to harmonize scale degree 6.
Comment: I now have a tentative answer from someone who teaches theory. "Regarding the ii chord harmonizing the 6th scale degree, the approach I-ii with a soprano ^5-^6 would result in parallel fifths, and ii is often approached by I."  So it would not actually have to do with ii going to V, but I going to ii.
Comment: Thanks.  I've discussed this with two teachers, and all three of us came up with notes that would work, and without that great an effort.  The book is the previous edition of Sarnecki, book 1 (2002) so it's not that old, but maybe it's quoting older sources.  When I was googling it, someone out there had the same rule in ABRSM, and again without explanation.
What interests me in theory is the understanding part.  Then you also need less rules, if any.  Btw, the same book later lists 6 as one of the degrees that ii and ii6 harmonize.
Comment: In my answer "old" meant 50 years old, not 2002. But there are lots of more recent books are basically the next link in a game of Chinese Whispers. I can't find much on the web about Mark Sarnecki, except that he wrote plenty of textbooks. A textbook for a first university course on harmony might be better for "understanding," once you know the basic terminology - but the best tools for "understanding" are two ears and one brain, not textbooks.
Comment: Well, when I asked the question, it was in case anyone might have actually run into an explanation of the thinking behind this (assuming there was any).  I like your metaphor of Chinese whispers.  The theory I'm doing with my teacher veers more to Romantic and later, and it's not a 100% conventional path - here it is indeed ear etc.  To me the rule doesn't make sense because I could harmonize the 6 using ii.  A musician / teacher lulled herself to sleep making up a dozen.  Up to now, the rule doesn't make sense.
Comment: That is a general "problem situation" with *any* chord progression where the melody moves the same number of scale-steps and in parallel with the roots of the chords. The inner two parts need to move in contrary motion to avoid consecutives, and that can be difficult to achieve unless the voices are widely spaced.
Comment: In other words:
Comment: In other words
- ignore rule but keep it tucked away
- find the chord that fits best under the circumstance
- play with it if you ever run into it
- ignore the rule which isn't one
Comment: All in all, it makes me think there is no good reason for this rule.
Comment: "Before I had studied Zen for thirty years, I saw mountains as mountains, and waters as waters. When I arrived at a more intimate knowledge, I came to the point where I saw that mountains are not mountains, and waters are not waters. But now that I have got its very substance I am at rest. For it's just that I see mountains once again as mountains, and waters once again as waters." This also applies to learning harmony ;)
Comment: In a minor key where ii is diminished, it might make sense to double the third of ii or ii6, so as not to accentuate the tritone (degree VI in the scale is the fifth of chord ii).  In a major key, again doubling the fifth of chord ii might sound clumsy in some cases.
Comment: Maybe the idea is that when the 6 is in the soprano then the 4 is used as a harmony note and has the possibility of overpowering the 6 and creating an ambiguous chord quality. This is especially true in the ii6. In other words the minor ii sounds maybe more like a major IV.
Answer: Just to add AlephZero's answer the ii6 chord is the standard for the perfect cadence because it makes the big sense if you look at the bass line.
If you have the Cadential 6/4 progression you could have ii6-I6/4-V-I. That tonic chord in the second inversion is just a decoration of the dominant chord. If you look at the very important bass line you now have for C Major for instance have. F-G-G-C.
This is a standard chord progression that everyone should know for their harmony exercises.

In my old theory book, I read that while ii and ii6 harmonise scale
  degrees 2 and 4, they rarely harmonise scale degree 6 in the soprano

The supertonic is an excellent choice of chord after the Sub-Mediant chord.


is $||T|| ≤1$ imply $I-T$ is positive operator and hence imply $I-T$ is self adjoint .

Question: I deduced that in a hilbert space over complex feild $||T|| ≤1$ imply $ I-T$ is positive operator .
assume $||T|| ≤1$ then-
$( [I-T]x,x)=( x-Tx,x) = (x,x)-(Tx,x)=||x||^2-(Tx,x)$
now using Cauchy-Swartz inequality $|(Tx,x)|\le||Tx||.||x||\le||T||.||x||.||x||\le||x||^2$
i.e $I-T$ is positive operator.
and this imply I-T is self adjoint. but i think this is not true, for example in ℓ2 ,for left shift operator $||T||=1$ but $I-T$ is not self adjoint.
what am i doing wrong?
Comment: Simply having $\lVert T\rVert \le 1$ does not guarantee self-adjointness, so does not guarantee positivity. Specifically, your argument shows that the absolute value of $((I - T)x, x)$ is at least 0, but does not show that  it is real.
Comment: thank you sir..I got my mistake that $(Tx,x)$ may not be real. if this is real then result will be true
Answer: HINT.- The definition I have of $S$ positive operator in a Hilbert space $H$ is
$$(Sx,x)\ge 0 \text{ for all } x\in H$$ This definition has implicit that $(Sx,x)$ is real because the set $\mathbb C$ of complex numbers is not ordered (you have not, for example,  a sense  for $5+7i\ge 0$). It follows that the conjugate of $(Sx,x)$ is equal to $(x,Sx)=(Sx,x)$. Thus $S$ is self adjoint.
(Actually that $(Sx,x)$ is real for all $x$ is a well known equivalent definition of self adjointness in Hilbert spaces).


How to disable internet during web test selenium? WebDriver, Java

Question: I need to disable internet during web automation test using selenium webDriver, then test UI and enable connection.
I'm using selenium (PageFactory) to create scripts, maven to build project... My test case is - I need to start selenium script (open browser - login) then disconnect internet then test that error appear on web site and then connect again. I need to do it on different OS (Windows/Mac) and browsers
Thank you for any help.
Comment: Please explain in more detail what you are doing. Your setup etc etc. Everything that would be needed for someone to duplicate your problem.
Comment: Hi, I'm using selenium (PageFactory) to create scripts, maven to build project... My test case is - I need to start selenium script (open browser - login) then disconnect internet then test that error appear on web site and then connect again. I need to do it on different OS (Windows/Mac) and browsers
Comment: How is it related to the question marked as a duplicate? Aren't they totally different things? And why is the older question closed in favor of the newer one?
Answer:
Selenium can only be used to drive browsers and not any Desktop/Windows application.
Since its a simple network disable, you can run commands through Java language as below
1. To disable network in Java on Windows
    Runtime.getRuntime().exec("netsh wlan disconnect");
2. Run your selenium script.
3. Now enable using the code:
    Runtime.getRuntime().exec("netsh wlan connect name="network_name" ");
Comment: hi, what if I need to start selenium script (open browser - login) then disconnect internet then test that error appear on web site and then connect again Do you think your suggestion will work?


Monitor RBAC access

Question: I need to tighten RBAC for already deployed CRD in Kuberenets.
I am wondering can I drop all existing roles and bindings, then monitoring the forbidden access.
Unfortunately the kube-apiserver has no audit log settings, and if possible I would like to avoid modifying statically installed kube-apiserver.
So far I tried to get the information from apiserver metrics and logs.

The metrics contains only 200 and 404 requests, 403 is missing and has no information about nor the caller, nor the verb is matching with k8s terms, what is important. <code>{code="404",component="apiserver",contentType="application/json",endpoint="https",group="networking.k8s.io",instance="18.104.22.168:6443",job="apiserver",namespace="default",resource="ingresses",scope="resource",service="kubernetes",verb="GET",version="v1"}</code>
The logs seems verbose, but not much useful information. At least far from what I would expect from an http server
Answer: Droping all the roles and respective bindings is a high-risk operation thatcan  potentially lock out authorized or known users from accessing resources. It is highly recommended to proceed with caution and have a backup plan in case of unintended consequences.
You can use log server (e.g. Graylog server, Elastic stack kubernetes, etc.) to export logs and further analyze and study the behavior of your cluster.
On the other hand, you can use Falco to check your cluster's security integrity and Open Policy Agent to assist you on applying RBAC configurations. These are CNCF projects that are open-source. There can be other products you may use other than the mentioned applications that are open-source projects as well.

Monitor RBAC access


context parameter is empty on getServerSideProps when page refresh

Question: In one of my projects, I need to fill the meta keyword and the meta description by the data which is fetched from a REST API request.
so I used the getServerSideProps function, to fetch the response and pass it to the page.
Here's my getServerSideProps function
export async function getServerSideProps(context) {

    function makeParam() {
        let params = new URLSearchParams(context.params);
        let keysForDel = [];
        params.forEach((v, k) => {
            if (v === 'undefined')
                keysForDel.push(k)
        });
        keysForDel.forEach(k => {
            params.delete(k)
        });
        return params.toString()
    }

    let response = await axios.post(
        process.env.baseAddress + "getData.php",
        qs.stringify({
            data: "api/search/advance?" + makeParam()
        }),
        {
            headers: {
                'content-type': 'application/x-www-form-urlencoded'
            }
        })

    return {
        props: {
            dataFromServer: response.data,
            params: makeParam()
        },
    }
}

everything works fine in development mode (localhost), but after deploying, by refreshing the page Context parameter is an empty object.
this function was written in one of the pages that has one parameter called the city, which is shown below

I have already checked getServerSideProps props empty object.
as Ankri said

Can you please check, that you pass the pageProps to your custom Component?

here is my Component tag, which contains pageProps.
<Layout>
    <Component {...pageProps} ref={current}/>
</Layout>

Comment: How are you verifying that the context parameter is an empty object? Also, can you show us the component where you're using the `params` prop to populate the meta tags?
Answer: First make the file structure like this:
pages:
  city:
   [...slug].js

Note: city is folder!
Now you can get the first param like this:
export async function getServerSideProps(context) {
 const slug = context?.query?.slug[0] || "";
 const req = await axios.post(`${url}?advance=${slug}`)
 // ... rest of the code
}

now if url looks like this => http://localhost:300/city/japan
slug = japan


broadleaf commerce demo site login link gets redirected

Question: I have configured Broadleaf demo site to run with tomcat server directly from eclipse (not by using ant task). I tried to visit login, register and cart page but the link got redirected. Since in demosite for tomcat, login page must be at /mycompany/login when i click on login link i get redirected to /mycompany/mycompany/login.
I tried to directly hit the url http://localhost:8181/mycompany/login but it also gets redirected/changed to http://localhost:8181/mycompany/mycompany/login. This same issue repeats on clicking register and cart link also.
In LoginController i can see request mapping as "@RequestMapping("/mycompany/login")".
In logs i can see "No mapping found for HTTP request with URI [/mycompany/mycompany/login] in DispatcherServlet with name 'mycompany'" which is true as we do not have a mapping for this url.
Any pointer to where i can look for error.
Answer: I'm going to assume that you are actually seeing it redirect to https://localhost:8081 (as opposed to 8181 and http).
Those URLs specifically are marked as requiring SSL in applicationContext-security.xml:
<sec:intercept-url pattern="/register*" requires-channel="https" />
<sec:intercept-url pattern="/login*/**" requires-channel="https" />
<sec:intercept-url pattern="/account/**" access="ROLE_USER" requires-channel="https" />
<sec:intercept-url pattern="/checkout/**" requires-channel="https" />
<sec:intercept-url pattern="/null-checkout/**" requires-channel="https" />
<sec:intercept-url pattern="/null-giftcard/**" requires-channel="https" />
<sec:intercept-url pattern="/confirmation/**" requires-channel="https" />

If you comment those out (or remove them) then you will no longer see redirects. The alternative is to just configure SSL on your Tomcat instance.
Furthermore, the @RequestMapping that you mentioned on LoginController should just be @RequestMapping("/login"). There is no need to include the /mycompany part of that (which I assume is the Tomcat context) since Spring URLs ignore it.
Comment: Voila!!! Thanks for the information. I got it working by removing requires-channel attribute. Will try configuring SSL Connector on tomcat as this is something new to me. Also not sure whether i would be allowed to configure SSL connector on web hosting server like mochahost !!!
Comment: i can confirm that i am not able to see `https://localhost:8081` but `http://localhost:8181`.
Comment: Hi : phillipuniverse could you help in this question?

http://stackoverflow.com/questions/29077389/broadleaf-commerce-admin-controller-not-working


Signing $y''$ from $\log(\frac{x+y}{x})=x+y$

Question:
Suppose that $x,y>0$ are positive reals such that $y$ is defined implicitly in terms of $x$ via:
  $$
\log\left(\frac{x+y}{x}\right)=x+y.\tag{$\star$}
$$
  I would like study the sign of $y''$.

Attempt: Write ($\star$) as
$$
\log(x+y)-\log(x)=x+y.
$$
Differentiate both sides w.r.t. $x$ yields
$$
\frac{1+y'}{x+y}-\frac{1}{x}=1+y'\tag{$\star\star$}
$$
which can be solved to get
$$
1+y'=\frac{x+y}{x(1-x-y)}\cdot
$$
Differentiate both sides of ($\star\star$) w.r.t. $x$ to get
$$
\frac{(x+y)y''-(1+y')^2}{(x+y)^2}+\frac{1}{x^2}=y''
$$
which, after feeding to Mathematica while using $1+y'$ found above, gives
$$
y''=\frac{(x+y-2) (x+y)^2}{x^2 (x+y-1)^3}
$$
which can clearly take on positive and negative values depending on $x+y$. Indeed, looking back at ($\star$), we can freely vary $x+y$: to have $x+y=r>0$, simply set
$$
x=e^{-r}r,\quad y=(1-e^{-r})r.
$$
Is my attempt here reasonable to you? The reason I'm not confident is that if I feed ($\star$) directly to Mathematica, I get
$$
y=-x-\text{ProductLog}[-x]
$$
where (according to Help File) $\text{ProductLog}[z]$ gives the principal solution for $w$ in $z=we^w$. Then I plotted
$$
\partial_x(\partial_x(-x-\text{ProductLog}[-x]))
$$
and saw something that is only positive:

What is going on? Can someone please explain this seeming discrepancy?
Comment: One thing you can do is define $z(x)=y(x)+x$; then $\frac{d^2z}{dx^2}=\frac{d^2y}{dx^2}$ and the calculations are a bit simpler.
Answer: The problem is that $y$ isn't globally uniquely determined, i.e. there are multiple functions $y_i(x)$ that verify $(\star)$. In $\mathbb C$ these are infinite, while in $\mathbb R$ there are two, and you have, via Mathematica, found just one of them. The other solution can be seen here to vary in sign  as you predicted (to know that this is a solution, see this. If you want a single function, you'll have to work with a local definition of $y(x)$ in neighbourhoods of concrete solutions $(x_0,y_0)$.
If the global vs. local aspect seems confusing, take the unit circumference as an example: there is no function $y(x)$ that traverses the entire curve of solutions to $x^2+y^2 = 1$, but you can define, for every solution $(x_0,y_0)$, a function $y(x)$ that passes through $(x_0,y_0)$ and such that every $(x,y(x))$ is a solution.
I have to add that I'm not terribly familiar with the Lambert function, so if anyone notices a mistake please correct it.


Probability of words appearing at specific area in string

Question: I was linked a youtube video where the first two characters were underscores, how could I calculate the probability of that happening? 64 possible characters, 11 character long string, and only two underscores appearing twice at the beginning. Is this possible?
Comment: Probability under what distribution? It'd be impossible in a language that doesn't use it, and quite likely if it's a Morse code written using "." and "_".
Answer: If you assume that all characters are equally likely to appear at any position (not likely for any "real" language, but probably a reasonable assumption for auto-generated URLs), then the probability for an underscore at any particular position is $\frac{1}{64}$.
If you also assume that characters are independent (again see above), then the probability for two underscores is $\frac{1}{64}\times\frac{1}{64}\approx 0.0002$.
Comment: This assumption alone does not determine your answer.  You are implicitly assuming the characters are drawn *independently.* For a common application where the characters meet your initial assumption but are *not* independent, see any of our [threads about Scrabble](https://stats.stackexchange.com/search?q=scrabble).
Comment: @whuber: I write in my second paragraph that *if* we can assume independence, the result follows. Where is my error?
Comment: Sorry -- I was looking for assumptions at the outset and overlooked your clearly stated assumption in the second paragraph!  +1.


How to find partial derivative if given antiderivative

Question: In my book exercise I need to find $\frac{მz}{მx}$, if $F(xz,yz)=0$
I try to do it like that
$$ F'_{xz}(d(xz))+F'_{yz}(d(yz))=0 $$
$$ F'_{xz}(z+x\frac{მz}{მx})+F'_{yz}(z\frac{მy}{მx}+y\frac{მz}{მx})=0 $$
express from it $\frac{მz}{მx}$
$$ \frac{მz}{მx}=\frac{-F'_{xz}*z-F'_{yz}*z\frac{მy}{მx}}{F'_{xz}*x+F'_{yz}*y} $$
but answer in the end of the book don't have part with $\frac{მy}{მx}$
Answer: Write $$\frac {\partial}{\partial u}F(u,v)=F_1(u,v),\frac {\partial}{\partial v}F(u,v)=F_2(u,v).$$ The given equation defines $z$ implicitly as a function of $x$ and $y.$ By the chain rule, $$F_1(xz,yz)(z+x\frac{\partial z}{\partial x})+F_2(xz,yz)(y\frac{\partial z}{\partial x})=0.$$
$$F_1(xz,yz)z+F_1(xz,yz)x\frac{\partial z}{\partial x}+F_2(xz,yz)(y\frac{\partial z}{\partial x})=0.$$ $$(F_1(xz,yz)x+F_2(xz,yz)y)\frac{\partial z}{\partial x}=-F_1(xz,yz)z$$
$$\frac{\partial z}{\partial x}=-\frac{F_1(xz,yz)z}{F_1(xz,yz)x+F_2(xz,yz)y}$$
provided $F_1(xz,yz)x+F_2(xz,yz)y \ne 0.$
Comment: what to we apply chain rule?
Comment: @Computation: Let u=xz,v=yz.. Then, since z is a function of  x and y, both u and v are functions of x and y. Hold y fixed and take the derivative of F(u,v) with respect to x by the chain rule,