Understanding Normal Numbers

Question: I am trying to understand what normal numbers are. Just for simplicity I want to talk about base 10. I understand that a number is normal in base 10 if there a probability of $\frac{1}{10
} $ such that the numbers 0-9 pop up and a probability of $\frac{1}{100}$ that the numbers $0-99$ pop up in the decimal expansion and so on...
However I am wondering, in this case when we talk about normal numbers we are only talking about irrational numbers since numbers like $2$ or $3$ don't have a decimal expansion so there is no sense in talking about them as normal numbers?
Or for example a number like $\frac{1}{3} = 0.3333..$ is not normal base 10 since it's decimal expansion only contains the number 3.
I am just wondering if a normal number has to do anything with the normal form of a number.
Comment: Normal doesn't just refer to single digits.  Yes, each digit should occur with probability $\frac 1{10}$ but each pair of digits should occur with probability $\frac 1{100}$ and so on.  See, e.g., [this](https://en.wikipedia.org/wiki/Normal_number).  But yes, normal implies irrational.
Comment: @Sasha  Yes.  But that does not imply irrational.  The rational number $.\overline {0123456789}$ is simply normal in that sense.  Proper normality is a much more interesting property.
Comment: Numbers like 2 and 3 certainly *do* have decimal expansions.  For example, $$2 = 2.000\overline{0}. $$
Comment: A normal number (even one which is only normal in base ten) must necessarily be irrational, yes. Most real numbers are normal, yet the only numbers we know to be normal are the ones we have explicitly constructed to be normal.
Comment: Actually my proof should be modified slightly to take into account the fact that the period may not start right away.  Easy to handle...suppose there are $Q$ terms before the period of length $P$ starts and replace the $2P$ in my expression by $2(P+Q)$ or such.
Comment: @Arthur Not so.  The n-digit sequences must be equiprobable.  See http://mathworld.wolfram.com/NormalNumber.html
Comment: @saulspatz You're right. I didn't know that.
Comment: @lulu He already mentioned the double digits, and the "and so on ..."
Comment: Ok so when I want to explain the definition of a normal number I need to consider every number and it's decimal expansion which is n.0000 for $n \in \mathbb{N}$. Then from there we have to look at how probable it is that certain digits pop up.
Comment: @lulu however when we are talking about simply normal we just refer to single digits?
Comment: @Arthur: [This answer discusses](https://math.stackexchange.com/questions/2353720/the-set-of-normal-numbers-is-uncountable/2354052#2354052) what you're thinking of. And for those interested in lots of links, my answer to [Normal Numbers as members of a larger set?](https://math.stackexchange.com/questions/2728446/normal-numbers-as-members-of-a-larger-set/2729156#2729156) (apparently made when I had a bit of time on my hands) will keep you busy for a while.
Comment: @lulu so when we talk about the normality of numbers even though no natural or rational number is normal almost all real numbers are normal since the set of natural and rational numbers have measure $0$?
Comment: @lulu is there a proof or theorem that says that if a number is normal it must be irrational
Comment: It's obvious.  Suppose you had a normal rational $\alpha$ .   Let $P$ denote the length of the period in the decimal expansion of $\alpha$.   Then the number $1\underbrace{000\cdots 000}_{\text {2P times}}1$  can not occur in the decimal expansion of $\alpha$.
Comment: @lulu so this is because the decimal expansion of rational numbers are periodic?
Comment: Yes, exactly.  $\quad$
Answer: As you noted a normal number ( in some basis) is necessarily irrational. We know (it was proved by E. Borel) that ''almost all'' (in the sense of measure theory) real numbers are absolutely normal normal, that is normal in all basis, but  the proof is not constructive, and it is not clear if there is some computable normal number. What we can say is that we dont know if nubers as $\pi, e, \sqrt{2}$ are normal also in base $10$ .
We know that the Champernowne number is normal in base $10$ but it is not normal in all  basis.
You  can also see  here for the problem of construction of a normal number.
Comment: It actually known that it's not normal in all bases, or just unknown whether it is?  I've always thought it was the latter, but I don't have any support for that.  If the former, do you know of a reference?
Comment: I did not verify the proof, but here (https://www.google.it/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=2ahUKEwi4r9-Xxf_eAhUFyxoKHXQJCSAQFjAAegQIABAC&url=http%3A%2F%2Fsummit.sfu.ca%2Fsystem%2Ffiles%2Firitems1%2F10167%2Fetd1934.pdf&usg=AOvVaw1t3UAeMdA6fF__ThMY0FfH ) the autors say that Champernowne's number fails to be strongly normal.
Comment: Thank you.  I'll enjoy reading this, I'm sure.

Understanding Normal Numbers


mod_security configuration issue: Error parsing actions: Unknown action: ver

Question: I am trying to install / configure mod-sec using this tutorial, which uses the OWASP ModSecurity Core Rule Set. However when I go to restart apache, I get the following error:
Syntax error on line 53 of /etc/modsecurity/base_rules/modsecurity_crs_20_protocol_violations.conf:
Error parsing actions: Unknown action: ver
Action 'configtest' failed.
The Apache error log may have more information.
...fail!

This is the block of code it is having trouble with: (specifically ver:'OWASP_CRS/2.2.9',\)
SecRule REQUEST_LINE "!^(?i:(?:[a-z]{3,10}\s+(?:\w{3,7}?://[\w\-\./]*(?::\d+)?)?/[^?#]*(?:\?[^#\s]*)?(?:#[\S]*)?|connect (?:\d{1,3}\.){3}\d{1,3}\.?(?::\d+)?|options \*)\s+[\w\./]+|get /[^?#]*(?:\?[^#\s]*)?(?:#[\S]*)?)$"\
  "msg:'Invalid HTTP Request Line',\
  severity:'4',\
  id:'960911',\
  ver:'OWASP_CRS/2.2.9',\
  rev:'2',\
  maturity:'9',\
  accuracy:'9',\
  logdata:'%{request_line}',\
  phase:1,\
  block,\
  t:none,\
  tag:'OWASP_CRS/PROTOCOL_VIOLATION/INVALID_REQ',\
  tag:'CAPEC-272',\
  setvar:'tx.msg=%{rule.msg}',\
  setvar:tx.anomaly_score=+%{tx.notice_anomaly_score},\
  setvar:'tx.%{rule.id}-OWASP_CRS/PROTOCOL_VIOLATION/INVALID_REQ-%{matched_var_name}=%{matched_var}'"

I have installed modsec Version: 2.6.3-1ubuntu0.2 so I beleve it should work with the OWASP ModSecurity Core Rule Set
Any ideas on how to get it working? Thanks in advance!
Comment: What is the version of mod_security that you have installed ?
Comment: 2.6.3-1ubuntu0.2
Answer: Googling yout error message I found this

...
Now apache fails to start:
  Sep 30 15:30:14 mydomain httpd[2377]: Syntax error on line 52 of /etc/httpd/modsecurity.d/activated_rules/modsecurity_crs_20_protocol_violations.conf:
  Sep 30 15:30:14 mydomain httpd[2377]: Error parsing actions: Unknown action: ver

and the response is

This is my bad...  CRS v2.2.6 uses some new actions from ModSecurity v2.7.0 -

ver
maturity
accuracy

It looks like the CRS that you are using is too new for the version of mod_security that you have installed. You will need to update to a later version of mod_security or find an older version of the CRS.
Comment: Thanks for your reply....Thats really strange because im using CRS v2.2.5 which should be compatible with my version of mod_sec. Do you know how I can upgrade my version of mod_sec on ubuntu 21.04? using the apt-get install libapache2-mod-security command doesn't get the latest version.
Comment: @BobFlemming: The rule you quote says `OWASP_CRS/2.2.9` and I don't use Ubuntu
Comment: ah I see. I had some old files still in the /modsecurity/base_rules/ from a previous installation attempt which are coded for version 2.0.7. After deleting these files I have managed to restart apache only to see 404 forbidden errors. Gotta love false positives!
Comment: @BobFlemming: Ah yes and now the world of pain begins ...
Answer: The OWASP rule set has been upgraded to require modsecurity >= 2.7.
There is a downgrade script in the util/rule-management folder that can automatically downgrade rulesets to be 2.6 compatible.
To downgrade your activated rules just run this comand in the rule directory (requires perl):
perl <PATH_TO_OWASP_RULESET_TGZ>/SpiderLabs-owasp-modsecurity-crs-ebe8790/util/rule-management/remove-2.7-actions.pl -t 2.6 -f .

Comment: could you explain the `-t 2.6 -f .` part?
Comment: -t: target version, -f: file or directory to convert. you can take a look here: https://github.com/SpiderLabs/owasp-modsecurity-crs/blob/master/util/rule-management/remove-2.7-actions.pl


Load two different Json dat in Odd and Even rows - ngGrid- AngularJs

Question: I am trying to load two different json data for even rows and odd rows like what we see here. I did try multiple sources as a refernce using ng-grid, but none has any solution. Kindly tell me the possibility on the same. Is it possible to do the same.
HTML

AngularJS
$scope.settings = {
    data: 'records',
    enableColumnResize: false,
    enablePaging: true,
    enableRowSelection: false,
    rowHeight: 35,
    headerRowHeight: 35,
    totalServerItems: 'totalServerItems',
    pagingOptions: {
        pageSizes: [15, 20, 50, 80, 100],
        pageSize:15,
        currentPage: 0
    },
    showFooter: true,
    footerRowHeight: 0,
    columnDefs: [
        {field: 'id', displayName: '', width: 25, cellTemplate: '' },
        {field: 'reports', displayName: 'Reports', width: 75 },
        {field: 'opportunityName', displayName: 'Opportunity', width: 250},
        {field: 'proposalId', displayName: 'Proposal ID', width: 95},
        {field: 'startDate', displayName: 'Start date', width: 90},
        {field: 'endDate', displayName: 'End date', width: 90},
        {field: 'amount', displayName: 'Amount', cellTemplate: '
{{row.entity.amount | currency:\'USD$\'}}
' },
        {field: 'alertss', displayName: 'Alerts'},
        {field: 'healths', displayName: 'Health'},
        {field: 'commentss', displayName: 'Comments' },
        {field: 'flag', displayName: 'Flag', cellTemplate: '

' }
    ]
};

Comment: Do you want `show_campaign_tasks()` to show details underneath the current row?
Comment: Yes, thats what I require.. @gidomanders
Answer: I think it would reach to mix the two data json sources in the controller, intercalate them and displaying the result using a ng-grid directive ... something like this
// main.js
var app = angular.module('myApp', ['ngGrid']);
app.controller('MyCtrl', function($scope) {
$scope.myOddData = [{name: "Moroni Odd", age: 50},
                 {name: "Tiancum Odd", age: 40},
                 {name: "Jacob Odd", age: 20},
                 {name: "Nephi Odd", age: 30},
                 {name: "Enos Odd", age: 34}];

$scope.myEvenData =   [{name: "Moroni Even", age: 51},
                 {name: "Tiancum Even", age: 43},
                 {name: "Jacob Even", age: 27},
                 {name: "Nephi Even", age: 23},
                 {name: "Enos Even", age: 34}];

 $scope.result = $scope.myOddData.reduce(function(arr, v, i) {
                          return arr.concat(v, $scope.myEvenData[i]);
                       }, []);
$scope.gridOptions = { data: 'result' };

});
Here the related Plunker
http://plnkr.co/edit/MyV5pBXK4rQEmbfbCjgL


inflexion point how to find it?

Question: Can someone explain me this part of wikipedia I don't understand it
https://en.wikipedia.org/wiki/Inflection_point#A_necessary_but_not_sufficient_condition
Comment: you must have $f''(x_0)=0$ to have an inflection point, but not all points with $f''(x_0)=0$ are inflection points
Comment: but they say: f''(x_0) exists and x_0 is an inflexion point then f''(x_0)=0, it is in the first line of the part, this do not give us the inflexion point what is it ? @J.W.Tanner
Answer: There are two kinds of POSSIBLE inflection points,(i) where $f''(x_0)=0$ and (ii)where $f''(x_0)$ does not exist.First, find all the points where $f''(x_0)=0$. At each such point, investigate whether $f''(x)$ is positive on one side of $x_0$ and negative on the other for $x$ close enough to $x_0.$ Such points are inflection points. Second, find all the points where $f''(x_0)$ does not exist.At each such point investigate whether $f''(x)$ is positive on one side of $x_0$ and negative on the other for $x$ close enough to $x_0.$ Such points are inflection points.
Comment: I am a bit surprised that you are focusing on a "necessary condition for an inflection point" but not mentioning the **definition** of an inflection point.  An "inflection point" of a curve is a point at which the curvature changes sign.  Since the curvature is proportional to the second derivative, that would be equivalent to the second derivative changing sign.  And then, **if** you are requiring that the second derivative be continuous, the second derivative must be 0 at that point.  Of course, as P. Lawrence said, it is possible for the derivative to be 0 but not then change sign.

inflexion point how to find it?


Views not saving after upgrading

Question: I am upgrading my website from Drupal 6 to Drupal 7.  In the Views module, when I attempt to save a view I now get the following error:
<code>PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column
'human_name' in 'field list': UPDATE {views_view} SET
name=:db_update_placeholder_0, description=:db_update_placeholder_1,
tag=:db_update_placeholder_2, base_table=:db_update_placeholder_3,
human_name=:db_update_placeholder_4, core=:db_update_placeholder_5
WHERE (vid = :db_condition_placeholder_0) ; Array (
[:db_update_placeholder_0] => Last_update [:db_update_placeholder_1]
=> last update [:db_update_placeholder_2] => [:db_update_placeholder_3] => node [:db_update_placeholder_4] =>
[:db_update_placeholder_5] => 0 [:db_condition_placeholder_0] => 11 )
in views_db_object->save_row() (line 2092 of
/home/yektafil/domains/dl.yektafile.info/public_html/sites/all/modules/views/includes/view.inc).
</code>
Does anyone know what's causing this?
Answer: The message states that views is missing a database column (human_name) it is expecting to exist. New fields in core or contributed modules are often added by an update process.
It looks as if you need to run update.php, because it was not run after upgrading core or the views module itself. Alternatively, if you have drush enabled, you can run 'drush updb' from a shell.

Views not saving after upgrading


Timeframe for training data in churn models vs prediction data - confused

Question: I am developing a churn model for a subscription business. The churn rate is 7% yearly for it. The training data was prepared in such a way that customer information is tracked at the start of the year where only active customers are tracked. By the end of the year, the customer tag of churned/active customer is taken. The data is also tracked till the end of the period for the active customer and till the churn period for a disconnect customer. There is good accuracy for this approach but during prediction it is poor as there is not much difference between customers who stay active vs those who churn.
Please advice on what should be changed to make better predictions!
Comment: What is unclear about this question? Why are there votes to close it for that reason?
Answer: If there is not much difference between customers who stay active and those who churn then, pretty much by definition, no method will work well.  You need to find some variable (or variables) which do distinguish the two sets.


Porque Bootstrap 4 datepicker API não funciona?

Question: Estou a criar um calendário, algures na view, precisei de um input para o utilizador inserir uma data. Como estou a usar bootstrap 4 e o bootstrap tem vários addons para datepickers, usei um deles. Relativamente ao front-end, nada a dizer, funciona lindamente. Quando ao back-end, quando uso métodos, opções ou eventos da API em jquery, eles não executam.

console.log($date = "data");
$('.datepicker').datepicker({
  format: 'dd/mm/yyyy'
}).on('changeDate', function(e) {
$date = $('.datepicker').datepicker('getDate');
  console.log($date);
});

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/css/bootstrap-datepicker.css">

  <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

   <input type="text" class="form-control" class="datepicker" data-date-format="dd/mm/yyyy" data-date-autoclose="true" data-date-today-highlight="true">

[documentação] - Tenho-me guiado pela documentação, possivelmente estarei a usar erradamente, conseguem identificar o erro?
documentação
Alguém me consegue ajudar?
Cumprimentos
[update] 2/03/2019 - Opções já executam

Segundo a documentação:
  Data API
  As with bootstrap's own plugins, datepicker provides a data-api that can be used to instantiate datepickers without the need for custom javascript. For most datepickers, simply set ´data-provide="datepicker"´ on the element you want to initialize, and it will be intialized lazily, in true bootstrap fashion. For inline datepickers, use ´data-provide="datepicker-inline"´; these will be immediately initialized on page load, and cannot be lazily loaded.

Alterei o atributo data-provide="datepicker" para data-provide="datepicker-inline", com isto esta parte do jquery já executou, contudo eventos ainda não são dispachados.
$('.datepicker').datepicker({
            format: 'dd/mm/yyyy'
    })

Answer: Olá fiz uns testes e o problema está em usar INPUT você deve usar DIV no datetimer, acho que existe uma biblioteca melhor que essa do bootstrap que você está usando, tente está aqui do jQuery.UI.
Mas de qualquer forma assim funcionou basta tentar adaptar ao visual que você deseja.

$('#datepicker').datepicker();
$('#datepicker').on('changeDate', function(e){
    $date = $('#datepicker').datepicker('getDate');
  console.log($date);
});

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/css/bootstrap-datepicker.css">

  <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

Comment: Obrigado pela ajuda. Realmente a biblioteca sugerida á primeira vista parece ter um melhor desempenho. Contudo não resolve o problema inicial. Respondi á minha pergunta e consegui solucionar parte do problema, acha que consegue melhorar a minha resposta?
Comment: O que você deseja fazer? não intendi. quer inicializar ele com uma data que vem de uma api?
Comment: Basicamente, quando altero o attributo date-provide para "datepicker-inline", o datepicker carrega aquando o carregamento da página, ou seja, deixa de ser "lazely", assim quando executo o script, ele já pode ser inicializado.
Comment: ainda não consegui intender, colocando esse atributo ele carrega mais rápido?
Comment: Sim, mas não é só isso. Alterei a resposta, o código estava errado. Conheço o termo 'lazy' em outros contextos da programação, neste não sei como funciona. Por exemplo, imagina que tens uma propriedade "altura=5cm", depois fazes setAltura(8cm), contudo se a propriedade for 'lazy' a altura continua a ser 5cm. Agora, se fizeres um getAltura(), a altura muda para o valor do último set e retorna 8cm. https://pt.wikipedia.org/wiki/Avalia%C3%A7%C3%A3o_pregui%C3%A7osa
Comment: Neste caso, o calendário sendo 'lazy', só inicia momentos antes de ser usado. Daí o script não executar nenhuma das funções. Falta-me encontrar um método/evento que disperte assim que ele for inicializado.
Answer: [Quase-Resolvido]
API de dados
Assim como os próprios plug-ins do bootstrap, o datepicker fornece uma API de dados que pode ser usada para instanciar datepickers sem a necessidade de um javascript personalizado.
Para a maioria dos datepickers, simplesmente defina data-provide = "datepicker" no elemento que você deseja inicializar, e ele será inicializado preguiçosamente, na forma de bootstrap verdadeira.
[Por resolver] - Nestes casos ainda não sei que código jquery espera pela inicialização do datepicker.
Tentei
$('.datepicker').ready(function() {
            $('.datepicker').datepicker();
            $('#sandbox-container input').datepicker({
            format: "dd/mm/yyyy"
            }).on('changeDate', function(e) {
            $date = $('.datepicker').datepicker('getDate');
            console.log($date);
            });
        });

[debbuging] - entra na função cedida em ready, mas não executa opções nem eventos.
[Revolvido] -  Para in-line, use data-provide = "datepicker-inline"; estes serão inicializados imediatamente no carregamento da página e não podem ser carregados com preguiça.
Desta forma alterando o HTML

$(document).ready(function() {
        $('#sandbox-container input').datepicker({
        format: "dd/mm/yyyy"
        }).on('changeDate', function(e) {
        console.log('Aqui');
        $date = $('.datepicker').datepicker('getDate');
        console.log($date);
        });
    });


Expected run of colored cards

Question: I came across the following question:
There are $26$ black(B) and $26$ red(R) cards in a standard deck. A run is number of blocks of consecutive cards of the same color. For example, a sequence RRRRBBBRBRB of only $11$ cards has $6$ runs; namely, RRRR, BBB, R, B, R, B. Find the expected number of runs in a shuffled deck of cards.
One way to approach the problem uses the concept of Linearity of Expectations, wherein they argue that the probability of getting a card of a different color in the first 2 runs (Red-Blue or Blue-red in the first draws) is $(26/52)\times(26/51)\times 2$ and this will be the case for all the runs. Like so, we arrive at the answer of $27$. (A more general answer of $2\times n + 1$, where $2\times n$ is the total number of cards in the deck)
However, I find it difficult to understand why this particular probability of getting $2$ different colored cards in adjacent runs is always the same throughout the runs.
Comment: I think you should simply include the original answer given to you, because your post is quite difficult to comprehend.
Comment: I cannot make sense of the sentence "The probability of getting a card of a different color in the first 2 runs is ..." Do you have any guess as to what this is supposed to mean?
Comment: He means that the first two cards are specifically either Red-Blue or Blue-Red.
Comment: See [Linearity of Expectation](https://brilliant.org/wiki/linearity-of-expectation/),
which includes a proof that the formula applies even when the events are not
independent of each other.
Answer: Let $n=26$.
Define the indicator random variable $I_k$ of the event "the cards $k$ and $k+1$ are of different color". (For $k=1, \dots, 2n-1$.) Now the number of runs is equal to $1+\sum_{k=1}^{2n-1}I_k$ because you count the first run and then there will be an additional run in every point that two adjacent cards differ.
Clearly for each $k$
$$\mathbb{E}[I_k] = \mathbb{P}(k \text{'th card is different color to the } k+1) = \frac{n}{2n-1}$$
since what ever is the color of the $k$'th card, there are $n$ cards of the opposite color versus $n-1$ cards of the same color ($2n-1$ remaining cards in total). And a random permutation is as likely to put any of the remaining cards in the $k+1$'st place.
Now using linearity we get the answer
$$1 + \sum_{k=1}^{2n-1} \frac{n}{2n-1}
= 1 + n.
$$

Expected run of colored cards


Finding a reflection that exchanges two unit vectors

Question:
Let $v$ and $u$ be two vectors in an Euclidean space, that have same length:$\|v\| = \|u\|$, but are not on a same line. Find a reflection w that commute/switch between $u$ and $v$.
Comment: What have you tried? Start by saying what's the definition of "reflection"
Comment: Did you think about it geometrically? Or do you know what the result should be but have trouble with coming up with algebraic formula for it?
Comment: @Aleks i know i can look at the plane created by v and u then look at their sum which is the vector u+v..and take a vector a that is orthogonal to the sum: u+v.knowing that S_a is the reflection that is defined by a. Then i do not see how it can be related !
Answer:
This visual aid should give you a better idea of how to achieve what you're trying to achieve. The vector perpendicular to the reflection plane is seen to be
$ \frac{u - v}{|u -v|} $
let's call this vector $\hat{r}$
Then we can write down the reflection of any vector $x$ as:
$x \rightarrow x - 2((x - \frac{u + v}{2}) \cdot\hat{r} ) \hat{r} $ , so substituting we have:
$x \rightarrow x - 2((x - \frac{u + v}{2}) \cdot   \frac{u - v}{|u -v|} ) \frac{u - v}{u-v}$
now if we substitute for $u$ for $x$ then we have
$u \rightarrow u - 2 (\frac{u-v}{2} \cdot \frac{u - v}{|u-v|} ) \frac{u-v}{|u-v|}  = u - (u - v) = v$
And similarly it follow for v -> u. Or alternatively you can notice that it is antisymmetric in u and v.
Comment: You should check it yourself if it equals that, oh and a disclaimer : $\hat{r} = \frac{r}{|r|} $
Comment: I have edited my answer -- haveing thought about it I have found an easier way with just inner products. If you need more elaborations please ask.
Comment: Why don't you try and compute it? :)
Comment: then can i substitute x = u in this function and assume that it equals to v ?
Comment: I'm trying to use the function above but don't understand how the inner product work to show that it exchanges u and v!
Comment: it isn't a problem taking a reflection not of the usual form of x---> x-2(x v) v ?
Comment: Didn't understand which one you mean, i did compute the one you suggested, it works..but with the definition I can't find a suitable reflection


How to access Weave DNS-Server from external?

Question: I use the Weave network plugin on a Docker-Swarm.
I created a docker network with a specific IP-Range, different from the default Weave Network, to which I route from my internal network.
To make the containers even better accessible I use weave to attach DNS names like containername.auto.mycompany.de. Now I want to access those from my company Network. The Problem is, that weave only allows access to the weave DNS from the local host.
Like on one of my swarm nodes i can do:
host foobar.auto.mycompany.de 172.17.0.1
Using domain server:
Name: 172.17.0.1
Address: 172.17.0.1#53
Aliases:

foobar.auto.mycompany.de has address 10.40.13.3
Host foobar.auto.mycompany.de not found: 3(NXDOMAIN)
Host foobar.auto.mycompany.de not found: 3(NXDOMAIN)

But I don't find a way to make the weave container accessible on one of the IP's from this (10.40.130/24) docker network or expose the port to the swarm node.
The only way I can think of, but don't like, is doing something like this:
iptables -t nat -A  DOCKER -p tcp --dport 53 -j DNAT --to-destination 172.17.0.1:53

(this does not work, it's just the idea)
Or tamper with the weave script to make it expose the port on start of the weave container.
Does anybody know of a better solution?
Answer: In fact setting the rules
iptables -A DOCKER -p tcp -m tcp --dport 53 -j DNAT --to-destination 172.17.0.1:53
iptables -A DOCKER -p udp -m udp --dport 53 -j DNAT --to-destination 172.17.0.1:53

does it. When I first tried that, I simply missed to see, that my request would have come from "outside" the server to work, not from inside to the loopback device.
Still not a pretty solution but it does the job. I'm looking forward to see better solutions from you guys.
(Bounty stands!)


From Basic Java Project With Web Service To Deployable Glassfish Artifacts?

Question: I am trying to learn about Web Services, Glassfish, Eclipse, etc. and the way I learn is I like to do things manually Instead of playing around with Dynamic Web Projects as many of the tutorials online ask you to do. I am starting with a basic Java project and creating the WSDLs, client stubs, etc. by hand.
I have (remarkably) come pretty far along. What I have done so far is create a web service class and used wsgen to create the WSDL and then used wsimport to create client stubs.
The part that I am stuck on is how do I deploy my service to Glassfish? I have been able to do it using Eclipse (right-click, -> Web Services -> Create Web Service) but as I stated above I want to learn how things work under the covers. So let's say I was using nothing but Notepad and a Java command line compiler how would I go from my current Web Service project to something that is deployable in Glassfish?
Thanks!
Comment: That's where creating a *Dynamic Web project* comes in handy (in Eclipse). Your Web Service needs to be archived into a WAR file so that it can be deployed to an application server.
Comment: Well I think you have started in the best way. Use an IDE may not be as good as you write it yourself. But an IDE can do the deployment tasks for you, create the WAR, etc.
Answer: You find a hell lot of examples on the Apache TomEE website. This one might fit your needs.
http://openejb.apache.org/examples-trunk/simple-webservice/
You need to package your Webservice and deploy it to the container. There is merely anything happening "under the hood". It's just bred and butter stuff for your IDE. you could also do everything "by hand" (war, http://www.openscope.net/2010/01/25/war-deployment-file-structure/ ; asadmin deploy http://docs.oracle.com/cd/E19798-01/821-1751/giobi/index.html).

M


What does the conclusion with confidence interval mean, non-statistically speaking?

Question: There is a manufacturer who told me that they tested devices in the batch based on 95% confidence level, 5% confidence interval/margin of error and 50% distribution. So from 1500 devices, they tested 110. What does it mean for me? That I can be sure that there is 95% chance that all devices will behave as the tested samples?
Answer: Under the frequentist interpretation, the confidence interval is some interval $(a,b)$ where $a,b$ are random numbers, which are determined by the sample. For a $95\%$ confidence interval for estimating some quantity $\mu$, $95\%$ of the time you will have $a<\mu<b$. Note that in a fixed sample, either $a<\mu<b$ is true or it isn't. We never really know which. But under the frequentist interpretation we can say that if we collected many confidence intervals, $95\%$ of them would contain $\mu$ and $5\%$ would not contain $\mu$.
Note that under this interpretation it is not valid to say that $\mu$ is in our single interval $(a,b)$ with probability $0.95$, which is what you would naively expect. Under the Bayesian interpretation, something like this is indeed true, but there are subtleties involved in the Bayesian interpretation which are more difficult to explain.
Comment: Well thanks but I am not a math guy, that is why I ask what does it really mean for me in the situation I described:)
Comment: @Pietross Unfortunately I have yet to see a good layman explanation of confidence intervals. Everything I've seen is either somewhat mathematically sophisticated or technically incorrect. The simplest thing I can say which is still correct is the last sentence of my first paragraph. Maybe reread that and ask what you don't understand from it.
Comment: If you could maybe interpret that on my example with hardware devices. They tested 110 based on the confiredence interval 95% etc., but what it means for me?
Comment: @Pietross In terms of absolute fact, not very much. Basically, you expect that the average behavior of all of the devices is somewhere in the confidence interval that they gave you...but it's possible that their sample was in the $5\%$ of "bad" samples, in which case the true average will not be there.
Comment: Thanks. So its really useless? I mean, they could test e.g. only 50 of them out of the batch (1500) but instead used the calculation to get this number..So I wonder why.
Comment: @Pietross With an especially small sample, the techniques used to construct confidence intervals are not reasonable. A common "rule of thumb" is that these techniques become reasonable above sample sizes of about $30$. Once the samples are large enough that these techniques are reasonable, increasing the size of the sample will tend to make the confidence interval (for a fixed level of significance) more narrow. So they probably took a sample large enough that their confidence interval was narrow enough for their purposes.
Comment: So it makes sense they used that for 1500, right? Still not really sure what to think if you say their sample could be the bad one. Out of 1500, 110 were extensively tested.
Comment: @Pietross That makes sense, yes. It's still possible that these 110 were unusually bad or unusually good devices, in which case the confidence interval will be inaccurate. But this isn't very likely.
Comment: Thanks! So can I be 95% sure of that? I still try to make something of the numbers (is there 5% chance that those were exceptionally bood or bad?)
Comment: @Pietross Yes--there is a $5\%$ chance that the sample they took consisted of much better or much worse devices than the overall group of devices.
Comment: @Pietross An idea for a layman explanation: suppose you have 1,000,000 factories broken up into 1,000 groups of 1,000 factories. You obtain $95\%$ confidence intervals for some unknown, fixed quantity that the factories need to know in order to run. Each factory uses the confidence interval for its group as some sort of internal operating parameter. If the unknown quantity is not in the confidence interval used by a given factory then the factory explodes.
Comment: @Pietross (Cont.) You do this for each group of factories (not each factory separately). Then you expect that, in 950 of the groups, none of the factories will explode, while in 50 of the groups, all of the factories will explode.


Control ASP.NET WebAPI JSON serialisation without access to source code

Question: I am using ASP.NET WebAPI to return an object from an assembly that I can't change the source code in.
I want to remove one property from the response, but I cannot simply add [JsonIgnore] to that property because I can't edit the class I am returning.
Is there a way to specify a separate property ignore list?
There serialization is happening automatically at the moment using the Ok() method:
return Ok(myObject);

Answer: You can create a custom Newtonsoft.Json.Serialization.IContractResolver to conditionally serialize properties.
For more info on Json.net's support in this space, you can take a look at the following link:
http://james.newtonking.com/json/help/index.html?topic=html/ContractResolver.htm
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new ShouldSerializeContractResolver();

public class ShouldSerializeContractResolver : System.Net.Formatting.JsonContractResolver
{
    public new static readonly ShouldSerializeContractResolver Instance = new ShouldSerializeContractResolver();

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty property = base.CreateProperty(member, memberSerialization);

        if (property.DeclaringType == typeof(Employee) && property.PropertyName == "Manager")
        {
            property.ShouldSerialize =
                instance =>
                {
                    Employee e = (Employee)instance;
                    return e.Manager != e;
                };
        }

        return property;
    }
}


The form of the residual vector in the multiple linear regression model

Question: I have 2 questions about multiple linear regression model.
Does the residual vector in the multiple linear regression model have the form $y-(X(X^T X)^{-1}  X^T)^2 y$?
And, is it true that the sample distribution for a linear combination of model parameters in the
multiple linear regression model is used in deriving the prediction interval for a future observation $x_0$?
Thanks in advance
Answer: Yes, the residual vector is correct but the expression can be simplified because: $$(X(X^TX)^{-1}X^T)^2y=X(X^TX)^{-1}(X^TX)(X^TX)^{-1}Xy=X(X^TX)^{-1}X^Ty=X\hat{\beta}=\hat{y}$$
and residuals are $r=y-\hat{y}$. You don't have to square the term in the parentheses.
Since $\hat y_0=\hat{\beta}x_0$, prediction interval will use sampling distribution of parameter estimates.
Comment: Thanks for the upvote; do you know how to accept an answer? You'll click the "tick" sign under the arrows upper left.
Comment: oh thank you so much, that was really helpful...can i do one more question? Is it true or false that the sample distribution for a linear combination of model parameters in the multiple linear regression model is used in deriving the prediction interval for a future observation x0?
Comment: yes, i tried to address that question in my last sentence.
Comment: it's a different question..idk whether its true or false
Comment: I still don't realize the difference, but ok it's true.
Comment: what explanation i can write to justify that it is true that  the sample distribution for a linear combination of model parameters in the multiple linear regression model is used in deriving the prediction interval for a future observation x0?
Comment: Because y0 depends on model parameter estimations; the with the equation I gave in the answer (last sentence).
Comment: okay thank you so much! can you check out and the question i wrote now? i really need help for that one! thank you again
Comment: your question in the comment is the same as the question in the original post. My answer for that question is both in my post and comments.
Comment: no, i mean the question i have posted after this question.. not this in the comment..
Comment: yeah of course..
Comment: yes that is what i mean..can you help me with that please?
Comment: You are welcome! can you help me with the other question?
Comment: It appears that the answer is ok for your but you haven't accepted it yet, do you know how to accept it? I've described it in my previous comment. For the other question, it's not completely appropriate for us to discuss that here in another thread because this is a community forum and people might wonder what you're referring to. This post with its question and answer is self-contained and should stay so. I'll try to look at your other post and answer/give hints if I'm *able*.
Comment: ok i have done it...can you answer and help me to the other post that i am talking about? thank you
Comment: do you know anything about  the other question to help me?
Comment: I'm afraid that seems to be slightly out of my scope of interest. However, you should first address the problems there. It was labeled as duplicate (and the duplicate is also a closed one) and it appears to be a self-study question. Obtaining direct answers without effort is discouraged in this forum.
Comment: Could you just tell me how i can compare two models to conclude to which one is better fit?
Comment: 1) That is a broad question 2) post another question with some context, your thoughts & effort to appeal others (there are very expert people specifically on regression) 3) please let's not use this comment thread as if it belongs to us only.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/101613/discussion-between-pianca-strict-and-gunes).


Rating for anonymous users plus redirection to the login page

Question: I am using the Fivestar module for product rating with Ubercart. I want to enable rating for anonymous users. At the same time, when the user rates the product, this must be redirect to login page.
Is there any possibilities for doing this?
Answer: Try the Voting Rules module.

Administrators can configure actions to occur when a user submits a
  vote, when a user deletes a vote, and when the results of a vote are
  calculated. Currently, Voting Rules supports votes on nodes, users,
  and comments.

I didn't test it, but using it is possible to achieve what you want with the the Rules module.
Comment: I have installed voting rules module. But I cannot able to find where to config that rule.


Vuex getters real time updating audio.currentTime state

Question: I want to have audio player in Vuex store to use its data for output to custom audio player in a Vue components.
In Vuex store there is a state property aplayer that plays music.
store.js code:
state: {
  aplayer: new Audio()
},
getters: {
  getCurrentTime: state => state.aplayer.currentTime
}

In the component I want to display aplayer.currentTime the current song. I'm trying to get it by using the getter getPlayer in a computed properties.
components.vue code:
getCurrentTime() {
  return this.$store.getters.getCurrentTime;
}

But when output to the template, the current time freezes to 0. However, when I press "pause", the current time is displayed correctly.
Please help.
Answer: Vue works best when observing plain objects, of which Audio is not. Vue cannot detect when the currentTime property changes.
From the docs:

The object must be plain: native objects such as browser API objects and prototype properties are ignored. A rule of thumb is that data should just be data - it is not recommended to observe objects with their own stateful behavior.

Your best solution would be to generate your own currentTime number property and synchronize its value to audio.currentTime periodically by using setInterval while the audio is playing, and clear the interval when the audio is paused.
Answer: store.js
state: {
  aplayer: new Audio()
},
getters: {
  getCurrentTime: state => state.aplayer.currentTime
}

Component.vue
<template>

{{getCurrentTime}}

</template>

Comment: Now currentTime is always 0 (even after pressing the button "pause")


Where does $rows come from in views?

Question: Let's say I have a simplest "unformated list" view.
I see that "views-view-unformatted.tpl.php" is outputting $rows in a loop.
When I open my view page on a browser, I see that the following codes are generated by $row.
test1

What template can I edit to remove anchor part?
Answer: Non need to edit template in this case.
Just edit title field and uncheck "Link this field to the original piece of content" option.

Where does $rows come from in views?


Documentation for nuget API

Question: does anyone knows a good documentation for nuget service endpoints?
I'm looking for it for both nuget v2 and v3 (v2 in priority as V3 is still in contruction).
Answer: Updating several years later: There is now official documentation for the NuGet server API over at microsoft.com.
Answer: There is no official documentation of NuGet API, but since NuGet is open source, you can take a look here: https://github.com/NuGet/NuGetGallery
The API requests handling code is located in this file:
https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery/Controllers/ApiController.cs

Documentation for nuget API


How can I find $c=d^x$ using only basic computer functions?

Question: Since this seems more like a math question than programming, I'm placing it here instead of on SO
I'm trying to find $x$ when $c$ and $d$ are known constants (user input and iteration counter, respectively) in the equation $c=d^x$ in a program I'm making. How can I find this without using complex methods? (this operation must be done several thousand times per second, at least)
Please use pseudocode for any examples.
Comment: Writing logarithm in terms of and,or,not etc. is really a programming question rather than a math question, I think.
Comment: if you can be more specific about the expected the input, it may be possible (for example) to use a look-up table.
this is really a programming question.
Comment: $x=\log c/ \log d$. You should have the $\log$ function available in your program library.
Comment: Is there any more specific information you can give about the values that $c$ and $d$ will take? Or what precision you want on $x$? For example, $c$ and $d$ might be 8-bit numbers between $0$ and $1$. If you know an upper and lower bound, we could make a rational function that approximates $\log$ to whatever degree you desire. Depending on that degree and the upper and lower bounds, this might be faster than using $\log$ directly.
Comment: I'm trying to make it more simple than that, if that's okay. Something that can be easily built into processor hardware (only using and, not, add, subt, mult, loop/goto, etc.)
Comment: I think there are math answers to this question, if you can provide more detail. Otherwise, this is a programming/hardware question. Some processors come with the $\log$ function built into the circuitry of the hardware. Generally, it will be hard to beat that with any clever math, if it is available to you.
Comment: c, d, and x are each 12-bit floating-point numbers (-4096 to 4095 with progressively decreasing fractional precision as the number approaches its upper and lower limit)
Comment: if these are floating point numbers then your programming language's log function is likely optimised more than any other suggestion you'll get here.
Answer: As the comments suggested, the direct approach is to apply log function.
If you don't want to use log function, I suggest that you write your equation as:
$f(x) = d^x - c$ where c,d are constants.
and you could apply a method of successive approximations to find the root. One such method is this: Wiki-Bisection Method (while it is not the best method, it is the only way that does not involve using log function as far as I know). The link provides an algorithm.
Answer: Log is a special function that has the property that if $c=d^x$ then $\log c=x\log d$ and thus $x=\frac{\log c}{\log d}$.  To find x in pseudocode, we simply have:
<code>float c, d, x
//assign input for c and d h
x = math.log (c)/math.log(d)  //assigns x the correct value
</code>
The log function should be in all math libraries of big programming languages.  Java has the log function in the Math class, C++ has it in the math.h library, Python has it in its math library, etc.
If you cannot find this function in a library (which is very unlikely), there are plenty of algorithmic to estimate log.  You probably do not need to use any of the numerical analysis methods for finding log as many people suggested, however.  Also, the standard log function from a math library should be sufficiently fast.
Answer: Since you need very high performance (and from that we can infer that you need interactive rates), you could perhaps benefit from modern GPUs by employing them for general purpose computing. Their parallelized SIMD nature might be able to severely flunk the time necessary to perform the operations and GPUs love chewing floating point operations. You don't even have to cheat with standard shaders or use clever math tricks to approximate, you can turn to the well established approaches like DirectCompute, OpenCL, CUDA.
If you don't wish to entangle yourself in such complexity for performance, your best bet would be to compare performance between Mark Dominus' table lookup/interpolation approach, alex.jordan's suggestion to use approximation by rational functions and simply brute forcing the log() function in a heavy usage scenario and then choose what suits your needs best. Besides that, there isn't much you can do to squeeze performance/precision. It's either the workload of coding for the GPUs or deciding between computation and memory. Trade-offs, like everything in life.
Answer: Others have observed that the function you want is $x = {\log c\over \log d}$.  So it's enough to be able to quickly calculate logs. Precompute the values of $\log t$ and store them in a table. Then use table lookup. You will not get it to run any faster and you will not find a simpler implementation.
If the table takes too much space for the accuracy you need, store a smaller table, and use table lookup followed by linear interpolation.  Linear interpolation goes like this: Suppose you want $\log x$ but
your table only has $\log a$ where $a$ is not too different from $x$.  If you know that the slope of the log function near $\log a$ is close to $m$, then $\log x\approx \log a + m\cdot(x-a)$, which is quick: you can get $\log a$ from the table and then once you have $m$ you need one multiplication and two additions.  For your particular function, $m = 1/a$, so you have $\log x\approx \log a + {x-a\over a}$.
Similarly if you want to trade off more computation for a smaller table you can use second- or third-order interpolation: $\log x\approx \log a + {x - a \over a} - {1\over 2}{(x-a)^2\over a^2}$ or $\log x\approx \log a + {x - a \over a} - {1\over 2}{(x-a)^2\over a^2} + {1\over 3}{(x-a)^3\over a^3} $.  To save operations, you'll want to calculate $z = {x-a\over a}$ and then use Horner's method to calculate the polynomial functions of $z$.
Comment: [An approximation by rational functions](http://en.wikipedia.org/wiki/Pad%C3%A9_approximation) is likely more efficient here than the Taylor approximations (by polynomials).
Comment: There are infinitely many values (working with double floats), so a precomputed table won't do.
Comment: @Supuhstar It depends on how precise you need the results to be. Double floats have a 52-bit mantissa, which is enough to represent the result to about one part in $10^{16}$. If you only needs the results accurate to one part in 100 (you didn't say) then you don't need a big table. The table size also depends on the size of the input (which you also didn't say) but at least one of those is not a float but an integer.
Comment: They each need to be accurate to the 4th decimal place. They are ALL floats.
Answer: After looking over all these answers, I've taken them into consideration and come up with the solution: send a modified version of the algorithm from Wikipedia's Binary Logarithm page to the GPU. This takes, on average, 3000ns to calculate, allowing for about 333 $1\over3$ thousand operations per second.
Comment: Funny, using the built-in log function on the CPU with no parallelism and optimization turned off, I can do 30 *million* operations per second on my machine...
Comment: fascinating... which language?
Comment: C++: `#include
int main (int argc, char **argv) {
    for (float i = 0; i < 30*1000*1000; i++)
        float j = std::log(i);
}`
Comment: I'll keep that in mind, but I was testing mine in Java. Perhaps it'd be faster when I actually write it in Assembler or make hardware to do it.


Reverse a DNA string sequence and find its complementary

Question: I am having a hard time doing C program for this. I have come up to use strrev function for reversing a string. However, in finding the complementary, it always says COMPARISON BETWEEN POINTER AND INTEGER.
Please correct my if else statement. I badly need it. Thank you.
#include<stdio.h> // define the header file
#include<string.h>
void main() {  // define the main function
    char str[100];
    char comp[100];
    printf("\nHi! \n Please input a string: ");
    scanf("%s",&str);
    printf("Reversed String: %s", strrev(str));

    if(str == 'a')
    comp=='t';
    else if(str == 't')
    comp=='a';
    else if(str == 'g')
    comp=='c';
    else if(str == 'c')
    comp=='g';

    printf("\nComplementary: %s",comp);
}

Comment: The reason it says 'comparison between pointer and integer' is that in each of the 8 lines, you compare a pointer (`str` or `comp`) with an integer (`'a'`, `'c`', `'g'`, `'t`').  Array names become pointers; you need to index into the array to get at the characters stored in the array.  And you need to do assignments, not comparisons, in the action statements after the `if` clauses.
Answer: You need to use assignment operator = to assign (not ==, which is for comparison). You need to loop over the elements of the string — for example, for (size_t i = 0; str[i] != '\0'; i++) and refer to the characters using str[i] in the body of the loop setting up the complementary string.
You might need to worry about upper-case vs lower-case letters too, I think — I've seen ACGT used more often than acgt for the DNA base molecules.  The code below identifies invalid letters, but continues anyway.
Note that while Microsoft provides the strrev() function, it is not standardized either by the C standard or by POSIX.
#include <stdio.h>
#include <string.h>

int main(void)
{
    char str[100];
    char comp[100];

    printf("\nHi!\nPlease input a DNA string (lower-case acgt): ");
    scanf("%99s", str);
    printf("Reversed String: %s\n", strrev(str));

    size_t i;
    for (i = 0; str[i] != '\0'; i++)
    {
        if (str[i] == 'a')
            comp[i] = 't';
        else if (str[i] == 't')
            comp[i] = 'a';
        else if (str[i] == 'g')
            comp[i] = 'c';
        else if (str[i] == 'c')
            comp[i] = 'g';
        else
        {
            fprintf(stderr, "Invalid DNA character '%c' at position %zu\n", str[i], i);
            comp[i] = str[i];
        }
    }
    comp[i] = '\0';  // Make sure the complementary string is null terminated

    printf("\nComplementary: %s\n", comp);
    return 0;
}


How do I create a download link from data in memory?

Question: I need to create a Controller that serves data as a download when accessed. That file is not in the file system but in memory; that's why I need a Controller instead of just serve file.
How do I create a download link from data in memory?
Answer: My approach is to use a Symfony Response obejct as explained here: The HttpFoundation Component: Serving files.
Firts setup the routing:
mymodule.download_item:
  path: '/myitems/{item_id}/download'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MyController::downloadItem'

So the controller looks like:
class MyController extends ControllerBase {
 public function downloadItem($item_id) {

    $fileContent = functionToObtainExternalContent($item_id);
    $response = new Response($fileContent);

    $disposition = $response->headers->makeDisposition(
        ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'foo.txt'
    );

    $response->headers->set('Content-Disposition', $disposition);

    return $response;
  }
}


Chord symbol and Roman numeral for naming an Augmented 6th chord

Question: While there are chord symbols & Roman numerals used to name a Neapolitan 6th chord, I haven't come across either of these for naming an Augmented 6th chord. The only names written were Italian 6th, French 6th and German 6th. The symbol for each was It.6, Fr.6 and Ger.6. Is this the only way to represent this chord?
Also, while using the Augmented 6th chord in a chord progression, I read that this chord is generally followed by chord V, or it goes to chord Ic and follows the cadential 6-4 progression i.e. ic - V - i. Are these the only possible ways of using the Augmented 6th chord, or there are others?
Comment: Closely related: [Do "augmented-six" chords always have to be bVI?](https://music.stackexchange.com/q/80684/21766)
Answer: The names It.6, Fr.6 and Ger.6 are pretty common ones. I've also seen some other names like:

IV 6# 5b for the German
IV 6# or #IV 6 for the Italian
II 6# 4 3 for the French

These are less common, but they are more "thorough" because they say on which chord they are built on and what notes are altered.
You are correct that in most cases these chords are followed by a V or I 64 chord. To be honest, I don't remember if this is a strict rule or if there are exceptions, but generally this is the case.
Here is an example of the German followed by a I 64:

And an example of the italian followed by a V:
Answer: German...
#iv6/5
French...
ii#6/4/3
In the case of the German I put the sharp in front of the Roman numeral to show the chord root is altered. Whereas in the French the chord root is not altered, but the 6th gets the sharp because it is raised chromatically from the diatonic sixth.
Of course the point here is to make clear none of the augmented sixth chord are rooted on bVI.


Where to set/keep Kadira Debug Authentication Key(Incorrect Debug Auth Key, Try again!)?

Question: My first question is where to set/keep KADIRA_DEBUG_AUTH_KEY="XXXXXXXXX" authentication key(Right now I have kept it in app/server/kadira.js). And second question is the authentication key is user defined OR app secrete key which we can get by creating app.Tried self  defined key but it is showing as "Incorrect Debug Auth Key, Try again!".
<code>  My app/server/kadira.js looks like below:

  Meteor.startup(function() {
    Kadira.connect('xxxxxxxxxxxxx', 'xxxxxxxxxxxx');
    KADIRA_DEBUG_AUTH_KEY="xxxxxxxxxxxx";
  });
</code>
Answer:
Where to keep sensitive app data - Meteor settings. They have option to have private (accessible only on server) and public settings, that will be accessible on client
Yes, secret key is obtainable, not random.
Comment: Thank you so much for your suggestion. I will work on it.
Comment: @Rashmi if it helps, then mark the answer as correct and close the question ;)


How do I use the sx prop in material UI to implement styling only when the component is selected?

Question: As shown in the code below,I have configured useState such that when a ListItem is clicked on, selected is true. When I want to do is implement specific styling when the item is selected. I would like to do this in the sx prop and not used a styled component as that would be unnecesarry for such simple styling. What I want to have is that when a ListItem is selected, the ListItemText turns blue and the ListItem turn a lighter shade of blue.
import { useState } from 'react'
import { Box, Drawer, CssBaseline, AppBar, Toolbar, Avatar, List } from '@mui/material';
import Typography from '@mui/material/Typography';
import ListItem from '@mui/material/ListItem';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import HomeOutlinedIcon from "@mui/icons-material/HomeOutlined"
import PeopleOutlinedIcon from "@mui/icons-material/PeopleOutlined"
import PersonOutlinedIcon from "@mui/icons-material/PersonOutlined"
import CalendarTodayOutlinedIcon from '@mui/icons-material/CalendarTodayOutlined';
import HelpOutlinedIcon from "@mui/icons-material/HelpOutlined"
import PieChartOutlineOutlinedIcon from "@mui/icons-material/PieChartOutlineOutlined"
import TimelineOutlinedIcon from "@mui/icons-material/TimelineOutlined"
import FolderSharedOutlinedIcon from '@mui/icons-material/FolderSharedOutlined';
import { Link as RouterLink } from 'react-router-dom'
import { useTheme } from '@mui/material'
import { ColorModeContext, tokens } from "./../theme"
import { useContext } from 'react';
import Logo from "./../assets/code2.jpg"

const SideBar = () => {
    const theme = useTheme();
    const colorMode = useContext(ColorModeContext);
    const colors = tokens(theme.palette.mode);
    const [selected, setSelected] = useState("Dashboard")

    const handleListItemClick = (text) => {
        setSelected(text)
    }

    const Item = ({ icon, text, to, selected }) => {
        console.log(selected === text);
        return (
            <ListItem key={text}
                selected={selected === text}
                disablePadding
                onClick={() => handleListItemClick(text)}
                sx={{
                    "&$selected": {
                        "& .MuiListItem.Mui-selected": {
                            backgroundColor: "blue",
                        }
                    },
                    "&$selected:hover": {
                        backgroundColor: "white",
                        '& .MuiListItem-root': {
                            color: "white"
                        }
                    }
                }}>
                <ListItemButton component={RouterLink} to={to}>
                    <ListItemIcon>
                        {icon}
                    </ListItemIcon>
                    <ListItemText selected={selected === text} primary={text}
                        sx={{
                            "&$selected": {
                                "& .MuiListItemText.Mui-selected": {
                                    color: "blue",
                                }
                            }}}                    />
                </ListItemButton>
            </ListItem>)
    }

    return (
        <Drawer sx={{
            width: 240,
            flexShrink: 0,
            '& .MuiDrawer-paper': {
                p: 2,
                width: 240,
                boxSizing: 'border-box',
                backgroundColor: `${colors.primary[500]}`,
            }
        }} variant="permanent" anchor="left">
            <Box textAlign="center" m="0 0 15px 0">
                <Typography variant="h3" color={colors.grey[100]} fontWeight="bold" sx={{ m: "10px 0 0 0" }}> ADMINIS</Typography>
            </Box>
            <Box mb="10px">
                <Box display="flex" justifyContent="center" alignItems="center">
                    <Avatar alt="logo" src={Logo} sx={{ width: 100, height: 100, cursor: "pointer"}} />
                </Box>
            </Box>
            <Box textAlign="center">
                <Typography variant="h2" color={colors.grey[100]} fontWeight="bold" sx={{ m: "10px 0 0 0" }}> Huvon Goodridge</Typography>
                <Typography variant="h5" color={colors.greenAccent[500]}>VP Fancy Admin</Typography>
            </Box>
            <List>
                <Item selected={selected} icon={<HomeOutlinedIcon />} text={"Dashboard"} to={'dashboard'} />
            </List>
            <Typography variant="h6" color={colors.grey[300]} sx={{ m: "15px 0px 0px 5px" }}>
                Data
            </Typography>
            <List>
                <Item selected={selected} icon={<PeopleOutlinedIcon />} text={"Team"} to={'team'} />
                <Item selected={selected} icon={<FolderSharedOutlinedIcon />} text={"Projects"} to={"projects"} />
            </List>
            <Typography variant="h6" color={colors.grey[300]} sx={{ m: "15px 0px 0px 5px" }}>
                Pages
            </Typography>
            <List>
                <Item selected={selected} icon={<PersonOutlinedIcon />} text={"Profile"} to={'profile'} />
                <Item selected={selected} icon={<CalendarTodayOutlinedIcon />} text={"Calendar"} to={'calendar'} />
                <Item selected={selected} icon={<HelpOutlinedIcon />} text={"FAQ"} to={'faq'} />
            </List>
            <Typography variant="h6" color={colors.grey[300]} sx={{ m: "15px 0px 0px 5px" }}>
                Charts
            </Typography>
            <List>
                <Item selected={selected} icon={<PieChartOutlineOutlinedIcon />} text={"Pie Chart"} to={'piechart'} />
                <Item selected={selected} icon={<TimelineOutlinedIcon />} text={"Timeline"} to={'timeline'} />
            </List>
        </Drawer>)
}

export default SideBar;

I have tried multiple ways to select the classes of the components that I want but to no avail. I expected this to change the backgroundColor but it did not and furthermore, it failed to change the text color. I have looked at the documentation on material ui website for this but it did not help.
Answer: For using sx prop to style the selected component, perhaps try add styles to &.Mui-selected and &.Mui-selected:hover property names.
Example: (with an over simplified live demo on: stackblitz)
<ListItemButton
  sx={{
    "&.Mui-selected": { backgroundColor: "hotpink", color: "#fff" },
    "&.Mui-selected:hover": {
      backgroundColor: "hotpink",
    },
  }}
></ListItemButton>

Comment: John Li, thank you so much. This was so annoying because there are spaces in the documentation between the "&" and the "." Its good knowing that it was so simple.
Comment: @LordEscanor Did it work? The example with a space after `&` is probably for setting the style on the parent `List`, which could also be tried. Anyways hope this will help! If it does, please consider choose to accept the answer so this post is complete. Thanks.


How do I add a customer ID field in Ubercart?

Question: I want to ask for the customer to enter his ID when he buys something.
Is it hard to add a new field apart from the default: name, phone, address, etc?
Answer: You want to add a field to the checkout process? There are two modules that do that. uc_webform_pane allows you to create webform nodes that integrate into the checkout process. uc_cck_pane allows you to integrate cck nodes into the checkout process.


Is a wind-string instrument (such as the one I will explain) acoustically possible?

Question: I've always had this concept of an instrument, but I am wondering if such an instrument is even acoustically possible.
The instrument is a tube, like most other woodwinds, but inside of the tube is a string that is stretched along the length of the tube. Air blown into this tube will somehow make the string vibrate, and the keys on the tube are like fingers on a regular string instrument, they will hold the string down so that only a certain length of the string can vibrate.
Is this possible? How could wind make a string vibrate? Are there any other complications I should be considering?
Comment: Possibly better suited to physics.se
Comment: In principle, yes. See: https://en.wikipedia.org/wiki/Aeolian_harp Your actual design may present some challenges. Note that the air has to flow perpendicular to the string, not along it, for it to work. As to the other engneering challenges, you will probably have to figure those out for yourself, assuming you're the first person to attempt this.
Comment: I think you would have better luck with a thin reed similar to that in a harmonica.  You won't be able to get a string to vibrate unless as Todd suggests the air hits it on the side. But even a very thin reed or film of any appreciable length would take a great deal of blow power to cause it to vibrate.  I am afraid the musician would pass out from hyperventilating trying to get such an instrument to emit sound - particularly when attempting to play lower notes.  Perhaps it could be powered by a CO2 cartridge like a pellet gun.  Only much larger.
Comment: @ToddWilcox Of course it won't just be a hole at the end you blow into, I was intending on there being a mouthpiece that would somehow manipulate the wind to flow through it a certain way, I just didn't know how. But now that you say it should be perpendicular to the string, now I know.
Comment: @ToddWilcox  that's not strictly true: it's  possible for turbulence effects to allow a longitudinal flow to excite vibration.   But I wouldn't go that route either :-) .
Comment: Rockin Cowboy, I agree, the required energy to induce vibration by blowing would be impossible for a human being, at least if we're considering guitar like strings strung to a similar tension. This is much aggravated if the air flow is longitudinal to the strings, not perpendicular. A possible less pyrotechnic ( :-) alternative to the CO2 cartrige, or even to a bellows, could be a rather small instrument (perhaps 10 to 20 cm) with very light and loose strings (think of office rubber bands). But this is just speculation, I wonder if the OP progressed in his quest
Answer: Yes such instrument is possible it sounds like a player activated variation of an aeolian harp. Looking at Aeolian harp designs help me to develop some ideas what such instrument and it might look like and how I could prototype my design ideas.
Below is quick image of quick prototype design trying to show major design elements are:

mouthpiece
tube
bridges for string
air outlet hole
string
stopper

My design would use a fretboard to control the pitch of the string as opposed to keys. Also worth considering is flexible mount pieces so the instrument could be played in sitting like board zither.

I highly recommend reviewing part of the book by Bart Hopkin, Musical Instrument Design - Practical Information For Instrument Making, See Sharp Press, 1996.  This where my ideas come from for this quick prototype.  The next for me would be to build one and see if works and what obstacles need to overcome and how best to handle these obstacles.
Comment: Bob, this is quite interesting, but the energy required to induce vibration in the strings by human blowing still seems to me a probable difficulty. Do you have any specific ideas regarding size, type of strings, or other issues, that help make this project viable?
Comment: I actually haven't looked back into this for quite a long time. It was a nice surprise seeing an answer here! But I've pretty much abandoned this and I've been trying to develop this instrument http://physics.stackexchange.com/questions/238187/what-would-the-physics-of-this-theoretical-instrument-be?noredirect=1#comment537991_238187 which I haven't been too successful with, especially with my minimal knowledge of acoustics. And I will definitely look into that book!
Comment: Perhaps if the mouthpiece is used to concentrate the air in one spot, you could induce vibration, though probably not much more than however hard you can blow. Maybe use multiple strings as well?


Prove $\int_{0}^\infty \mathrm{d}y\int_{0}^\infty \sin(x^2+y^2)\mathrm{d}x=\int_{0}^\infty \mathrm{d}x\int_{0}^\infty \sin(x^2+y^2)\mathrm{d}y=\pi/4$

Question: How can we prove that
\begin{aligned}
&\int_{0}^\infty \mathrm{d}y\int_{0}^\infty \sin(x^2+y^2)\mathrm{d}x\\
=&\int_{0}^\infty \mathrm{d}x\int_{0}^\infty \sin(x^2+y^2)\mathrm{d}y\\=&\cfrac{\pi}{4}
\end{aligned}
I can prove these two are integrable but how can we calculate the exact value?
Answer: I do not know if you are supposed to know this. So, if I am off-topic, please forgive me.
All the problem is around Fresnel integrals. So, using the basic definitions,$$\int_{0}^t \sin(x^2+y^2)dx=\sqrt{\frac{\pi }{2}} \left(C\left(\sqrt{\frac{2}{\pi }} t\right) \sin
   \left(y^2\right)+S\left(\sqrt{\frac{2}{\pi }} t\right) \cos
   \left(y^2\right)\right)$$ where appear sine and cosine Fresnel integrals. $$\int_{0}^\infty \sin(x^2+y^2)dx=\frac{1}{2} \sqrt{\frac{\pi }{2}} \left(\sin \left(y^2\right)+\cos
   \left(y^2\right)\right)$$ Integrating a second time,$$\frac{1}{2} \sqrt{\frac{\pi }{2}}\int_0^t \left(\sin \left(y^2\right)+\cos
   \left(y^2\right)\right)dy=\frac{\pi}{4}   \left(C\left(\sqrt{\frac{2}{\pi }}
   t\right)+S\left(\sqrt{\frac{2}{\pi }} t\right)\right)$$ $$\frac{1}{2} \sqrt{\frac{\pi }{2}}\int_0^\infty \left(\sin \left(y^2\right)+\cos
   \left(y^2\right)\right)dy=\frac{\pi}{4}  $$
Answer: Although this problem relates to Fresnel integration, if you take the following for granted then it is quite easy to show.
Given that (Fresnel integrals):
$$ \int_0^\infty \cos (x^2)dx = \int_0^\infty \sin (x^2)dx
= \sqrt{\frac{\pi}{8}} $$
Using trigonometry:
$$ \sin(x^2 + y^2) = \sin(x^2)\cos(y^2) + \cos(x^2)\sin(y^2)$$
And since both are symmetric, the original integral becomes:
$$\int_0^\infty dx \int_0^\infty dy \sin(x^2 + y^2)
= 2\int_0^\infty \sin(x^2)dx \int_0^\infty \cos(y^2)dy
= 2 \sqrt{\frac{\pi}{8}} \sqrt{\frac{\pi}{8}} = \frac{\pi}{4}$$


Where do ack-only sent packets come from (on FreeBSD)?

Question: I run the systat -tcp command on a moderately loaded system and see something like this for a 5 second window:
<code>                /0   /1   /2   /3   /4   /5   /6   /7   /8   /9   /10
 Load Average   ||||||||||||

         TCP Connections                       TCP Packets
       0 connections initiated           21062 total packets sent
     153 connections accepted            16291 - data
     153 connections established           125 - data (retransmit by dupack)
      11 connections dropped                 1 - data (retransmit by sack)
       0 - in embryonic state             4271 - ack-only
       5 - on retransmit timeout             0 - window probes
       0 - by keepalive                    217 - window updates
       0 - from listen queue                 0 - urgent data only
                                           148 - control
                                             0 - resends by PMTU discovery
         TCP Timers                      21057 total packets received
    9752 potential rtt updates           13471 - in sequence
   12437 - successful                       49 - completely duplicate
     763 delayed acks sent                  11 - with some duplicate data
     140 retransmit timeouts                14 - out-of-order
       0 persist timeouts                  225 - duplicate acks
       0 keepalive probes                12535 - acks
       0 - timeouts                          0 - window probes
                                            80 - window updates
                                             0 - bad checksum
</code>
Why is the sent ack-only number so much higher than the "delayed acks sent" number plus the dup data received numbers? What situations generate ack-only packets besides incoming data (which should go through delayed ack timer) and received dupes (immediate ack). Keepalive, I guess. But this box has no long-lived idle connections. Everything is short and furious. And there's a keepalive line item there too that says zero...
What am I missing about the tcp machine here?
Answer: You seem to be reasoning that ack-only packets should only be sent when the machine either gets a dupe, or when the timer expires, but I don't see why that would be true.  There is another category, perhaps more common and important than either of them, which is that the ack window is almost full.
If the other machine is streaming data to you and sends enough packets to get close to the ack window, the local machine will send it an ack.  In the common case that it has no other data to send back, it will send an ack-only packet.
So, why are there any delayed acks?  Because we don't want to ack every single packet the client sends: that would generate excessive back traffic.
Suppose the recv window would allow for 10 incoming packets.  The remote machine sends us one.  There is no need to ack it right away, because they know they can send us up to 9 more.  If they do in fact keep sending packets, then as we get close to filling the window, we'll acknowledge their transmissions.
On the other hand, if they send us just one packet, and then stop for a while, we do want to at least acknowledge we got that one packet, so that they know not to retransmit it and so they know the current state of the window.
The delayed ack timer distinguishes between these two cases: letting them carry on if they're sending lots of data, without letting data sit unacknowledged for too long.
Comment: +1 To summarize: most commonly when there are no other data packets to piggy-back an ack on to.
Comment: Ok, that makes sense. I think I also misunderstood delayed-ack... it only affects a solitary packet. "Ack window" is the same as "recv window" in your usage? This is the comment from the DELAY_ACK macro in tcp_input.c: "Indicate whether this ack should be delayed.  We can delay the ack if
    - there is no delayed ack timer in progress and
    - our last ack wasn't a 0-sized window.  We never want to delay
        the ack that opens up a 0-sized window"
Comment: Yes, I meant the recv window.


Print page without URL and DateTime Using Javascript

Question: I want to print the div tag content by javascript by using the following code.
var divToPrint1 = $('#PrintDoc').html();
var newWin = window.open('Share Certificate #001', '', 'width=10px,height=10px');
newWin.document.open();
newWin.document.write('' + divToPrint1 + '');
newWin.document.close();
setTimeout(function () { newWin.close(); }, 10);

And print code works fine. But now I want to remove the url, date and title from the print by using the javascript code.
Is it possible?
Can anyone help me to solve the following problem?
Answer: You cannot remove the URL and timestamp programmatically. Those options are part of the Print dialog, which cannot be controlled from JavaScript in the page. This choice is entirely up to the user.
Comment: can i write vb.net code to perform this? If yes then what is the code?
Comment: Uh, no... VB.NET runs on the server.
Answer: You are using IE? IE adds extra information to your print. Although not sure this can be changed through code...

I did find an article on the MSDN site where you can set some behavior, didn't try it out but you can give it a spin.
Answer: If you are trying in Chrome, when you click print button at the bottom of the print page there will be "Remove the Header and Footer" checkBox.
Also for other browsers go to print settings and there you will find same settings.. just un-check it
Comment: Hi, your answer does not quite answer the question; the original question was for disabling the header and footer using Javascript.


Passing a function's args straight to another function

Question: In PHP, is there a way to send a function's arguments straight to another function without having to specify them one by one? Is there a way to expand func_get_arg() so that the other function receives the individual arguments and not just a single array?
I'd like to send the arguments from foo() straight to bar() like so:
function foo($arg1, $arg2, $arg3)
{
  $args = expand_args(func_get_arg());
  bar($args);
}

Answer: yes.
function foo($arg1, $arg2, $arg3)
{
    $args = func_get_arg();

    call_user_func_array("bar",$args);

}

Answer: If you want to call it on a function belonging to an instance of an entirely seperate class, that can be done by passing the first arg to call_user_func_array as an array.
In this example, the function foo accepts whatever arguments, and passes them directly into $bar->baz->bob(), and returns the result.
public function foo(/* example arguments */)
{
    return call_user_func_array
    (
        array($bar->baz, 'bob'),
        func_get_args()
    );
}


BeautifulSoup: Find table by style

Question: Is it possible to find a specific table with unique style?
Say, given the following html:

How can I use BS to find that table?
Thanks
Comment: have a look into: http://stackoverflow.com/questions/3945750/find-a-specific-tag-with-beautifulsoup
Comment: you wish to fetch a table with unique style?
Answer: Try it:
from bs4 import BeautifulSoup
bs = BeautifulSoup(htmlcontent)
bs.find_all('table', attrs={'border': '1' ,'style':'background-color:White;font-size:10pt;border-collapse:collapse;'})

Check this link for more details.
Comment: Missing a curly bracket.
Comment: thanks, this really helped. I used the following to append to an array(list): allstateswithparks = []

for tag in soup.find_all('td', attrs={'style': 'text-align: center; width: 140px;'}):
    allstateswithparks.append(tag.get_text())
Comment: Find all WITHOUT style, is that possible?
Comment: @CodeGuru what about leaving `attrs` empty?
Answer: import requests
from bs4 import BeautifulSoup
r = requests.get("https://www.lipsum.com/")
soup =   BeautifulSoup(r.content,"lxml")
print(soup.find_all('div',style=lambda value: value and 'text-align:justify' in value))

Note: important use attrs for class !!!
Comment: You should add in value in the end.

print(soup.find_all('div',style=lambda value: value and 'text-align:justify' in value))

BeautifulSoup: Find table by style


How do I know if I can accept or reject the hypothesis?

Question: I have to test a hypothesis that religion is connected to conservatism. I have recoded my variables and I have done a cross-tab and cramer's v test. I am not sure what these values tell me about my hypothesis. Does anyone possibly know if I can accept or reject my hypothesis through these tests?
Comment: Welcome to this site! If this is homework, please add the [tag:self-study] tag and read its wiki.
Comment: Either the chi-squared test or its Yates-corrected version is a valid way to test the null hypothesis $H_0$ that your Religion and Vote categories are independent. [The 'expected counts' in the computation of the chi-squared statistic are based on H0.] The very small P-values indicate the $H_0$ is rejected at the 5% level of significance (or any reasonable smaller level down to $\approx 0).$ Such large values of the test statistic are very unlikely to occur if $H_0$ were true. // For cell counts as large as yours the Yates correction is not necessary. // In Answ. format I verify the P-values
Answer: Chi-squared test in R:
MAT = rbind(c(1097,2209), c(344,1340))
MAT
     [,1] [,2]
[1,] 1097 2209
[2,]  344 1340
chisq.test(MAT, cor=F)

        Pearson's Chi-squared test

data:  MAT
X-squared = 88.37, df = 1, p-value < 2.2e-16

If $H_0$ is true then the chi-squared statistic (X-squared in the output) has very nearly the distribution $\mathsf{Chisq}(\nu=1)$ and
hence expected value $1.$ The probability that the statistic exceeds 89.331 can be computed in R as follows $(0$ to eight or more places):
1 - pchisq(88.37, 1)
[1] 0

If the statistic exceeds $3.841$ or $6.635,$ then $H_0$ is rejected at the 5% or 1% level, respectively.
qchisq(c(.95,.99), 1)
[1] 3.841459 6.634897

Another test for such a $2\times 2$ table is Fisher's Exact
Test. It is based on a hypergeometric distribution. (Wikipedia has an extensive discussion). This test is often used when
counts in the table are too small for the chi-squared test
to give reliable P-values.  In R:
fisher.test(MAT)

        Fisher's Exact Test for Count Data

data:  MAT
p-value < 2.2e-16
alternative hypothesis:
  true odds ratio is not equal to 1
95 percent confidence interval:
 1.680566 2.229396
sample estimates:
odds ratio
  1.934191


i was developing this android apk and suddenly got errors

Question: i was trying to implement functionality and got errors for android and it works good in ios development multiple dependencies installed for push notification and all
is it any problem with reactnative version 0.70
do i need to upgrade the version of reactnative
<code>18 issues were found when checking AAR metadata:

  1.  Dependency 'androidx.work:work-runtime:2.9.0' requires libraries and applications that
      depend on it to compile against version 34 or later of the
      Android APIs.

      :app is currently compiled against android-31.

      Also, the maximum recommended compile SDK version for Android Gradle
      plugin 7.3.0 is 33.

      Recommended action: Update this project's version of the Android Gradle
      plugin to one that supports 34, then update this project to use
      compileSdkVerion of at least 34.

      Note that updating a library or application's compileSdkVersion (which
      allows newer APIs to be used) can be done separately from updating
      targetSdkVersion (which opts the app in to new runtime behavior) and
      minSdkVersion (which determines which devices the app can be installed
      on).
termines which devices the app can be installed
      on).

</code>
https://github.com/manan36chauhan/Notification_react_native/issues/1
i have tried to resolve errors for changing build.gradle and version downgrading and upgrading still not having any solution
Answer: have you tried this?
I have an app with     "react-native": "0.70.6", and it works without errors.
It'll be better if you share more code.
Comment: i tried to add more code but rejected by stackoverflow i am sharing link for all errors
https://github.com/manan36chauhan/Notification_react_native/issues/1
Comment: Hi Mana, so you've got this problem after installation of the Notification_react_native?

If this is the problem, why you don't try this package?
https://notifee.app/react-native/docs/installation
Comment: currently i am using this package for foreground notification and badges count  "@notifee/react-native": "^7.8.0",


PHP Port Scanning

Question: This may be a duplicate post, BUT I've not seen any answer that correctly resolves this.
I'm trying to find a php script that can correctly determine the state of a TCP or UDP port.
I've tried several of the ones I've found online and they all return the wrong results.
EG: On my local network I have ports 5000 UDP & 5060 TCP/UDP open and routing correctly.
If I run a test via http://www.ipfingerprints.com/portscan.php or GRC Shields Up then the correct results are returned,  but all of the PHP Scripts I've tried fail and show the ports as closed.
I'm running the php script via my hosted account and trying to scan and test my own network.
This is one of the scripts I've tried:

<?php echo "<title>Port Scanning " . $_GET['host'] . "</title>"; ?>

<?php
ini_set('display_errors', 0);

if(isset($_GET['host']) == true)
    $host = $_GET['host'];
else
{
    echo "You didn't set the host parameter";
    die();
}

if(isset($_GET['sport']) == true)
    $sport = $_GET['sport'];
else
{
    echo "You didn't set the sport parameter";
    die();
}

if(isset($_GET['eport']) == true)
    $eport = $_GET['eport'];
else
{
    echo "You didn't set the eport parameter";
    die();
}

if($sport > $eport)
{
    $sport = $eport;
}

$scanned = 0;
$openports = 0;
$maxports = 1;
$totalports = ($eport - $sport) + 1;
$mins = floor(($totalports / 10) / 60);
$secs = ($totalports / 10) - $mins * 60;

echo "Scanning " . $totalports . " ports on " . $host . ", this should take around " . $mins . " minute(s) and " . $secs . " second(s), probably more depending on local website load, hardware, and other factors.

";
flush();

do
{
    if($scanned >= $maxports && $maxports != 0)
    {
        echo "Scan limit of " . $maxports . " ports reached, scanning stopped.

Scanner written by Samo502";
        flush();
        die();
    }
    if(fsockopen($host, $sport, $errorno, $errorstr, 0.1))
    {
        echo "Port " . $sport . " is open on " . $host . "
";
        $openports++;
        flush();
    }
    else
    {
        echo "Port " . $sport . " is not open on " . $host . "
";
        flush();
    }
    $scanned++;
    $sport++;
} while($sport <= $eport);

echo "
Done, " . $openports . " out of " . $totalports . " ports are open.

Scanner written by Samo502";
die();
?>

Does anyone know of a way to do this correctly ?
Thanks
**UPDATE**
I've found this which seems to work a bit better, but it's still not detecting that port 21 is currently open on my network..
http://resources.infosecinstitute.com/php-build-your-own-mini-port-scanner-2/
Any help gratefully received. Thanks
Comment: Are you sure there's not something on your host preventing you from making outbound connections? Some hosting will prevent PHP making connections, or require the use of a proxy. Does a (limited!) version of your script work on your local machine to tell you if, say, Google has port 80 open? Also, a tenth of a second for a timeout may be a little low—what happens if you increase the connection timeout?
Comment: Looks like my host does block unless asked to open them.
I'm trying the new script and that seems to work better, but still not 100%
Answer: The best solution is to write a wrapper in PHP for nmap - seriously, you can't recode a better portscan than nmap.
If you really want to do it, you should not simply open TCP port and check wether it does connect, you should start from a lower level of sockets, raw sockets.
$mysocket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

This allows you to investigate SYN, ACK handshake flags and do stealth or simply faster scans.
You can create (non-blocking) sockets in parallel and check their buffer/connection using socket_select();, which is the fastest and most reliable way to handle several sockets in PHP. I'd probably use forks or threads or dispatch parts of the code to run a full portscan within the same time as a single port scan.
Other functions you'd like to use are socket_set_timeout() and socket_set_blocking().
shell_exec not working with nmap command
https://unix.stackexchange.com/questions/28732/fastest-way-to-port-scan-nmap
http://phpnmap.sourceforge.net/
Probably the best solution, a PEAR package nmap wrapper: http://pear.php.net/package/Net_Nmap/
Comment: @user214292 You might want to look at php.net for the description and examples of the functions and then play arround with them. I've put useful links in the answer.
Comment: Thanks for the advice. This is not something I've looked at before. Do you have any links or examples that could help ?
Comment: Updated original post with an example that works, but not 100%
Answer: Instead of
if(fsockopen($host, $sport, $errorno, $errorstr, 0.1))

Try
$connection = @fsockopen($host, $sport);
if (is_resource($connection)){
  // OK
}

Answer: I tried the same thing on my shared hosting account and it did not work. I was able to install the PEAR packages necessary for port scan and it seemed to work for internet websites like "yahoo.com" but not for any of the ports I wanted. I ended up setting up a separate Virtual machine with APACHE and PEAR packages installed and now the code works just fine. Here you can try it for yourself:
www.admin-toolkit.com/port_scan.html (dead link)
Here is the code for that.  First, assign a value to $scanhost, $port and $timeout (in seconds), then:
$status = Net_Portscan::checkPort($scanhost, $port, $timeout);

$servicename = Net_Portscan::getService($port);

if ($status == NET_PORTSCAN_SERVICE_FOUND) {
    if($servicename == null)
        echo $port.": OPEN ".PHP_EOL;
   else
        echo $port." (".$servicename .") : OPEN ".PHP_EOL;
   }
else{
   if($servicename == null)
      echo $port.": CLOSED".PHP_EOL;
   else
      echo $port." (".$servicename ."): CLOSED".PHP_EOL;
}

PHP Port Scanning


Views Megarow refresh code example

Question: I am trying to use Views Megarow to update my entities inline. My problem is how to refresh the view after I save an entity. This is important especially in a case where the view outputs the title of the node and I update the title, for instance, or in the case where I delete the node and want it removed from the view listing.
The Views Megarow readme refers me to Commerce Backoffice for an example. I see that there is a menu entry as follows:
$items['commerce_backoffice/order/%commerce_order/%'] = array(
  'title callback' => 'commerce_order_ui_order_title',
  'title arguments' => array(2),
  'page callback' => 'commerce_backoffice_order_view',
  'page arguments' => array(2, 3),
  'delivery callback' => 'ajax_deliver',
  'access callback' => 'commerce_order_access',
  'access arguments' => array('view', 2),
);

And then the callback:
function commerce_backoffice_order_view($order, $display_id) {
  $title = commerce_order_ui_order_title($order);
  $view = entity_view('commerce_order', array($order->order_id => $order), 'backoffice');
  $view = $view['commerce_order'][$order->order_id];
  $output = drupal_render($view);

  $return = views_megarow_display($title, $output, $order->order_id);
  if (!empty($view['#megarow_refresh_parent'])) {
    $return['#commands'][] = views_megarow_command_refresh_parent($order->order_id, $display_id);
  }

  return $return;
}

So the commerce order is loaded, then passed with a display id to that callback function. The entity is then created and rendered, and displayed in the megarow, and an Ajax command is returned.
What exactly is the $display_id, and how do I structure the megarow link so that jQuery does the substitution?
I would appreciate it if someone could share a working code example and a conceptual walk-through.
Comment: It's not much fun I'm afraid :) Last time I did it (a few months ago) I had to conditionally monkey patch one of the Megarow module's core JS functions to have any chance. Don't have the code on this computer but I'll try to dig it out tonight
Comment: Seems off-topic as the question asking for code.
Comment: @Beebee Totally agree - but the painful memory of cobbling this together (and banging my head against a lot of walls) fills me with sympathy for the OP, I must admit :)
Answer: I found a quiet simple solution for this "recalculate-confirm-inline-update" UI pattern in Views Megarow forms.
Implemented scenario :
Step1:

Step2:

Step3:

Custom module approach :
function some_form_alter(&$form, &$form_state, &$product) {
 ...
 $form['#submit'][] = 'some_form_submit';
 $form['#validate'][] = 'some_form_validate';
 ...
}
function some_form_validate(&$form, &$form_state) {
 ...
 $field1_changed = (!empty($form['field1']['#value']) && $form['field1']['#value'] != $form['field1']['#default_value']);
 $field2_changed = (!empty($form['field2']['#value']) && $form['field2']['#value'] != $form['field2']['#default_value']);
 if($field1_changed || $field2_changed) {
  $result = _calculate_field3();
  if($result == $form['field3']['#value']) {
   return;
  }
  $form['field3']['#value'] = $result;
  $form['field3']['#default_value'] = $result;
  form_set_error('field3', t('Field3 has been recalculated. Please confirm with [SAVE]'));
  return;
 }
}
function some_form_submit(&$form, &$form_state) {
 $product = $form_state['product'];
 //apply $product changes
 commerce_product_save($product);
}

The idea is to simulate an update confirm with form_set_error(), which will be skipped on the second validation run when calculation equals previous calculation, saved in $form['field3].
My client needed a flexible solution allowing him to either enter net sale price or have sale price determined by wholesale price + profit margin + VAT.

Views Megarow refresh code example


monitor http traffic from non-browser

Question: I want to monitor http request generated out of a exe. Is there any tool that can help me?
Actually, an exe would call my asp.net web page to register a user. The exe constructs the request with all the data in it. when the request reaches my web page, I don't see any data. I wan to monitor the Request object and the traffic to find the reality.
Any help is appreciated. Thanks. Ananth
Answer: If you want to look at the data being sent "over the wire", check out Wireshark.
Answer: I assume you're using MS IIS.
In IIS, you can enable logging in the Internet Services or IIS manager look at the website tab on website properties an enable logging. You can also customize what info gets logged. This should log HTTP requests regardless of where they originate from.
If you see browser-based requests but not traffic from your program, maybe look at debugging your program.
Comment: I have the code deployed in SI environment where I cant debug. But I was able to figure out that the same code works with UAT environment. I guess it has something to do with network. I will follow this with my network guys.
Thanks for your input. Ananth

monitor http traffic from non-browser


Angles in $\mathbb{P}^2$

Question: Do there exist a way to define angle between lines at $\mathbb{P}^2(k)$?, where $k$ is an algebraically closed field of characteristic zero.
Comment: However, such angles are not preserved by projective transformations, so it is debatable whether they ought to count as angles "in" $\mathbb P^2$.
Comment: You have that locally $\mathbb{P}^2$ is like $k^2$; if you can define angles on $k^2$ then you can do it on $\mathbb{P}^2$. For example, if $k=\mathbb{C}$, then defining angles is the same as defining an angle between two lines in $\mathbb{R}^4$, you just find the point of intersection of the two lines, and see which affine piece it is in.
Comment: That's true, I guess it depends on what properties you're looking for.
Comment: If I wanted to know this, I might look in Norman Wildberger's writings.
Answer: No and yes:
No: There is no way to define angles on $\mathbb{P}^2$ which respects all the symmetries of $\mathbb{P}^2$. Even looking at $\mathbb{RP}^2$, which is smaller than $\mathbb{CP}^2$, the symmetry group is $PGL_3$, which is sometimes called the group of projective transformations. These transformations do not preserve angles. You can see this in any perspective drawing: The windows of this building are framed with right angles, but they appear to be trapezoidal in the photo. The map which turns the position of points on the wall into positions of pixels in the image is one of these projective transforms.  (Photo courtesy of Tambako the Jaguar, Creative Commons license.)

Yes: Inside $PGL_3$ is the subgroup $PU(3)$. There is a $PU$ invariant metric on $\mathbb{CP}^2$ called the Fubini-Study metric and, once you have a metric, you can talk about angles.
Explicitly, let our lines be given by $a_1 x_1 + a_2 x_2 + a_3 x_3=0$ and $b_1 x_1+b_2 x_2 + b_3 x_3=0$. Then, I think, the angle between them should be
$$\cos^{-1} \left( \frac{a_1 \overline{b_1} + a_2 \overline{b_2} + a_3 \overline{b_3}}{\sqrt{|a_1|^2+|a_2|^2+|a_3|^2} \ \sqrt{|b_1|^2+|b_2|^2+|b_3|^2} }\right).$$ Here $\bar{z}$ is the complex conjugate.
Comment: I corrected a tiny typo (second paragraph of **Yes**). Hope you don't mind :)
Comment: Thanks! Plus some more characters.
Comment: Looks like I messed up something :). But the site is behaving somewhat strangely, so I won't make further edits here. And sorry for the trouble...

Angles in $\mathbb{P}^2$