Operator '&' cannot be applied to operands of type 'byte[]' and 'byte[]'

Question: I'm trying to process a byte array retrieving from a sensor.
In the retrieved byte array, there will be a byte-mask, xx-xx-xx-xx, that tells me which data will be in the array.
The sensor mask:
DATA_1 0x00000001
DATA_2 0x00000002
DATA_3 0x00000004
DATA_4 0x00000008
DATA_5 0x00000010
DATA_6 0x00000020
DATA_7 0x00000040
DATA_8 0x00000080
DATA_9 0x00000100
DATA_10 0x00000200
DATA_11 0x00000400

This byte-mask 43-05-00-00, for example, tells me that data_1, data_2, data_7, data_9, data_11 will be in response array. I know this by using bitwise-and in Calculator app of Windows: in hex mode, type 543, click "And" button, then type the sensor mask (1, 2, 4, 8, 10,...). If the result is the same as sensor mask (1, 2, 4, 8, 10,...), this data is included. But I don't know how to achieve this in C#.
This is my ideal but it gave me error: Operator '&' cannot be applied to operands of type 'byte[]' and 'byte[]'
int[] sensorMaskList = new int[length] {1, 2, 4, 8,... };
internal List<int> GetSelectedData(byte[] byteMask)
{
    List<int> lstDataIndex = new List<int>();
    for (int i = 0; i < sensorMaskList.Length; i++)
    {
        byte[] mask = BitConverter.GetBytes(sensorMaskList[i]);
        if (mask & byteMask == mask)
           lstDataIndex.Add(i);
     }
     return lstDataIndex;
}

Can someone give me some ideal. Thanks in advance and sorry for bad english
Comment: You are trying to use the bitwise &-operator on arrays. You cannot do that. You'll need to loop through each element in the array and use the operator on the elements themselves. I.e. use the &-operator on a `byte` not a `byte[]`.
Comment: Yes I know that, but in my case, the value is greater than value a byte can store, like 543 and 100, so I had to store it in an array. Will it be correct if I using bitwise &-operator on each byte instead of whole array ?
Comment: Yes, because bitwise operations are - as the word says - performed bit by bit without carry. `&` is not `+`!
Comment: Try this: `if (mask.Zip(byteMask, (m, bm) => (m & bm) == m).All(x => x))`
Answer: You can use BitArray class to easily perform and operation
int[] sensorMaskList = new int[length] {1, 2, 4, 8,... };
internal List<int> GetSelectedData(byte[] byteMask)
{
    BitArray byteMaskBits = new BitArray(byteMask);
    List<int> lstDataIndex = new List<int>();
    for (int i = 0; i < sensorMaskList.Length; i++)
    {
        byte[] mask = BitConverter.GetBytes(sensorMaskList[i]);
        BitArray maskBits = new BitArray(mask);
        if(maskBits.And(byteMaskBits) == maskBits)
        {
            lstDataIndex.Add(i);
        }
     }
     return lstDataIndex;
}

Answer: All the error message "Operator '&' cannot be applied to operands of type 'byte[]' and 'byte[]'" means is that you can not use the bitwise AND operator on variables of type array. You can only use them on a single integer or unsigned integer variable or two integer or unsigned integers can be bitwise ANDED together.
What you may want to do if you want to do it for the whole array is make up another array of equal size and AND each variable in the first array with each variable in the second array in the corresponding positions such that the first variable in the array 1 will be bitwise ANDED with the first variable in array 2 and so forth. Hope this helps.
Comment: sorry but i don't get your point. what I want is apply operator '&' on 2 array. So you are telling me to create a third array, basing on one of the first two array, right ?
Comment: Possibly. Depending on what you want to do. I am not telling you to make a third array. I am just saying when you bitwise logical AND two variables they must either be unsigned integer or integer and preferably of the same width bitwise. You can not logical AND on a whole array because a whole array contains many individual variables not only one and this is the reason you are getting this error. bitwise logical AND applies only to bits in two variables for example I can bitwise logical AND int x with int y but I can not bitwise logical AND a whole array with another whole array.
Comment: byte[] mask = BitConverter.GetBytes(sensorMaskList[i]);
if (mask & byteMask == mask)
Comment: The line that is producing the error is the if statement since you are trying to bitwise AND the whole of the mask array which is an array of type byte with byteMask. This is not a legal operation. I am not sure exactly what byteMask is but if it is an array, which I am assuming this from the error message you are trying to bitwise AND two arrays together. This can not happen. Instead you can bitwise AND two individual variables of two arrays so a statement like mask[0] & byteMask[0] would be perfectly legal since you are bitwise ANDING two variables of type byte not two whole arrays.
Comment: Try to break down your problem and work on individual variables so that you are bitwise logical ANDING individual variables and put the result in a third array if that is the way you want to go, for example:
Comment: Array 1 input integer; Array 2 mask integer; Array 3 result integer;
Comment: for (arrayCounter = 0; arrayCounter < length; arrayCounter++)
{
 result [arrayCounter] = input[arrayCounter] & mask[arrayCounter];
}

Simple enough is it not, since you broke the problem down and you are working on individual variables not whole arrays.
Comment: I got it now. Thanks


Possible alternative way of expressing continuity of a function?

Question: In Calculus or Real Analysis the usual form of definition of continuity of a function is $\epsilon- \delta$ def.
From a rigorous point of view, is it possible to say this way? and if so, why?:
$f(\lim_{n\rightarrow \infty} x_n)=\lim_{n\rightarrow \infty} (f(x_n))$
Thank you.
Comment: yes. If I see $\varepsilon$'s (and $\delta$'s), my first thought is "o, Cauchy is out there"
Comment: It's Heine definition of limit; Cauchy and Heine are equivalent
Comment: @Michael Galuza: Cauchy def. means $\epsilon- \delta$ def.?
Answer: Almost. The second definition is the definition of sequential continuity. It is not hard to show that if $f$ is continuous (traditional definition) then it is sequentially continuous.
Using the Axiom of Choice, we can prove that if $f$ is sequentially continuous then it is continuous. However, the result cannot be proved without invoking at least a weak form of AC.
Comment: AC is  widely (but not universally) accepted as an axiom of Set Theory. Here is a sketch of sequential continuity implies continuity. Suppose $f$ is not continuous at $a$. Then there is an $\epsilon\gt 0$ such that for every $\delta$ there is an $x\ne a$  such that $|x-a|\lt \delta$ and $|f(x)-f(a)|\ge \epsilon$. Let $\delta=1, 1/2, 1/3$ and so on. For every $1/n$, **choose** an $x_n$ such that $0\lt |x_n-a|\lt \frac{1}{n}$ but $|f(x_n)-f(a)|\ge \epsilon$. (The simultaneous choosing is where AC is used.) We have obtained a sequence $(x_n)$ that violates sequential continuity.
Comment: I didn't know about *Axiom of Choice* so in a limit knowledge I read it from wiki. However I don't know it's connection as you've stated. I would appreciate if you please explain it simply for me, and if it is not easy enough don't bother yourself (I know BSc level of maths).
Comment: It turns out there are *lots* of related questions, answers on MSE. Search the site for sequential continuity axiom of choice.
Comment: Thank you very much for introducing a new necessary concept and referring to M.SE so I found some books in [here](http://math.stackexchange.com/questions/735166/book-books-leading-up-to-the-the-axiom-of-choice), will try reading. :)
Answer: You are talking about the sequential criterion. It says:

A function $f:\Bbb R\to\Bbb R$ is continuous at $x=a$ if and only if for every sequence $a_n\to a$ we have $f(a_n)\to f(a)$.

It is essential the word 'every'. For example, take $f(x)=\sin(1/x)$. Let $a_n=1/(n\pi)$ and $b_n=1/(2n+0.5)\pi$. Both sequences tend to $0$ but $f(a_n)\to 0$ and $f(b_n)\to 1$.
Comment: This counterexample doesn't say that these two def.s are not equivalent. Non-equality occurs in your example because $\epsilon- \delta$ def of continuity is also not applicable for $f(x)=\sin(1/x)$.
Comment: My counterexaple intends to show that if $f(a_n)\to f(a)$ for some sequence, there still can be other sequences for which the condition does not hold, and then the function will not be continuous.
Comment: Yes, another example can be Dirichlet's function (by the sequential
density of the rationals and irrationals, if we choose irrational point as a limit point of a sequence of rational numbers).
Answer: The epsilon and the delta are understood to be numbers. For the epsilon-delta definition to be rigorous, there must be a meaning of the differences f(x)-f(a) and x-a as numbers. For example if there is a metric on the underlying spaces.
In more general cases the definition is: The inverse image of an open set is open,
Since open sets are necessary, the spaces must be topological. Otherwise there is no notion of continuity.


How is composer including a dependent module?

Question: I have a composer managed Drupal project based on drupal/recommended-project.
I'm installing a contrib module, domain_group, and I'm seeing that composer is auto-including a required dependency, even though it's not listed in the module's composer.json. (I'm checking some other contrib modules and it seems that this is not specific to this module, but a consistent pattern across many modules.)
I run:
composer require drupal/domain_group

and it installs domain_group and domain_site_settings.
Then when I run:
composer why drupal/domain_site_settings

and it tells me that drupal/domain_group requires it.
While the dependency is not listed in domain_group/composer.json, I do see that it is listed in domain_group.info.yml.
Is composer somehow looking to the .info.yml to check for dependencies? Is this some kind of Drupal magic? What causes this? How does it work?
Update:
It seems that it's not checking the .info.yml, at least not locally. From @Clive, in the comments:

[composer why still lists the dependency] even when [the reference to domain_site_settings] is not in domain_group's local composer.json, composer.lock is deleted, the require line in domain_group.info.yml is commented out and composer cache is cleared (just checked). Where is it getting the reference?

I'm now wondering if composer why checks the remote repositories, e.g. https://packages.drupal.org/8, and if there's something special about the d.o repository that compiles extra package dependencies from .info.yml files.
domain_group/composer.json
{
    "name": "drupal/domain_group",
    "type": "drupal-module",
    "description": "This module provides integration between Domain and Group modules",
    "homepage": "http://drupal.org/project/domain_group",
    "authors": [], // etc...
    "support": {}, // etc...
    "license": "GPL-2.0+",
    "minimum-stability": "dev",
    "require": {
        "drupal/core": "^8.8 || ^9",
        "drupal/group": "~1.0",
        "drupal/domain": "~1.0"
    }
}

domain_group/domain_group.info.yml
name: 'Domain Group'
type: module
description: 'This module provides integration between Domain and Group modules.'
core: 8.x
core_version_requirement: ^8 || ^9
package: 'Domain'
dependencies:
  - group:group
  - domain:domain
  - domain_site_settings:domain_site_settings # Is composer somehow respecting this?

Comment: The Drupal packager does do some magic with .info.yml files, but that doesn't really explain why a local `composer why` finds that package, even when it's not in domain_group's local composer.json, composer.lock is deleted, the require line in domain_group.info.yml is commented out and composer cache is cleared (just checked). Where is it getting the reference?
Comment: https://git.drupalcode.org/project/domain_group/-/blob/2.x/composer.json#L28
Comment: That's interesting.. That's not what I see after installing the module OR when I download the 2.0.0 tar.gz from the project page. Though I do see it when I download 2.x-dev version from the project page. (I guess you can see that it was committed there after the release)
Comment: `Is composer somehow looking to the .info.yml to check for dependencies?` Yes, always. `Is this some kind of Drupal magic?` You betcha.
Comment: Thanks for the additional info, Clive. I added it to the question.
Comment: _I'm now wondering if composer why checks the remote repositories_ It doesn't, still works with network connection disabled...I'm sure there's a simple explanation for this but I can't see it
Answer: I think this is what's happening:

The Drupal packager gets dependencies from domain_group.info.yml, and adds them to the dependencies for the package record that composer will use.
When composer installs the package, it downloads the current version of the module code (which doesn't have the dependency in composer.json)
Composer doesn't use that composer.json for its record keeping - it stores the dependency from the packager in composer.lock, and also in vendor/composer/installed.json
composer why seems to use composer.lock first for its info, falling back to installed.json if unavailable.

So it doesn't really matter what's in the module's composer.json as far as Composer commands are concerned - it's looking at composer.lock or installed.json, which has domain_site_settings as a requirement from the original install.
Comment: Yeah, this matches what I see. The Drupal packager must be working some magic here to mark to list the initial dependency. Thanks.
Comment: Is there any documentation out there about the "Drupal packager"? Seems rather hard to find something about it.


jQuery Auto Rotating SWFs

Question: Im trying to find a tutorial or demo of jQuery auto rotating banner images/SWFs >>>WITHOUT OVERLAYING<<< each image/SWF that slows down my browser.
I currently have an old rotating SWF banners based on javascript with transition effect (on my website) that overlays on top of each image/SWF and it is killing my computer/browser. The longer they overlay each other, it freezes the browser app and have to close/reopen it.
Something like a_banner rotates up front for few sec then the b_banner rotates next and the a_banner disappears behind it, rather than staying behind the b_banner.
I know there are tons of jQuery rotating banner, but they are not what Im looking for technically.
Thanks and appreciate it.
Comment: What code have you tried?  Any snippets we can take a look at to help you on your way?
Comment: its a old javascript and wanted something new and effective.
Answer: Well without knowing a little more, I guess an idea would be to use ajax methods to feed html content of a swf object into a div using jQuery.  A process flow would look something like...
render a placeholder where swfs will live.  have a javascript method setup to run every n seconds (using setTimeout) to call a web service that streams out html content.  The html content would be the html representation of a swf (....etc).  Then you can use jQuery to dispose of the old flash object and replace it with the new content.
How's that sound?

jQuery Auto Rotating SWFs


Create new column in data.frame based on if-else assessment of other columns

Question: I am trying to add a new column (x_new)to my dataframe that is dependent on the value given in a 'definition' column. The definition column x_definition contains on of the following record types:
- A constant number
- A string describing the operation needed
- NA
I want the resultant column, x_new, to look as follows:
- If x_definition is NA, then x_new remains NA.
- If x_definition is a string, then it requires a certain calculation. For example if it's 'equal_to_z' than the result should be z, or if its 'third_of_z', then x_new should be z/3. There are also more than just these definitions that indicate more complex functions of z are required.
- If x_definition is any number, then x_new should just be that number.
I wrote the following code which works to handle those cases, but is a cumbersome group of nested ifelse statements. I am looking for a method that
data <- data %>% mutate(x_new = ifelse(
  is.na(x_definition), NA, ifelse(
    x_definition=='equal_to_z', z, ifelse(
      x_definition=='third_of_z', z/3, NA
      )
    )
  )
)

I also considered using switch but ran into the problem where I don't know how to say "if it's a number, leave it as a number"
a <- data %>% mutate(x_new = switch(x_definition,
  'equal_to_z' = z,
  'third_of_z' = z / 3,
  <number???> = x_definition
  )
)

What would be an appropriate process for addressing this?
Answer: I think case_when is exactly what you're looking for.
data = data %>%
    mutate(x_new = case_when(is.na(x_definition) ~ NA,
                             x_definition == 'equal_to_z' ~ z,
                             x_definition == 'third_of_z' ~ z / 3,
                             !is.na(as.numeric(x_definition)) ~ as.numeric(x_definition)))

Answer: Yes, this is a very common need and it has a very good solution.
Your logic is:
If x_definition is NA, then x_new remains NA. - If x_definition is a string, then it requires a certain calculation. For example if it's 'equal_to_z' than the result should be z, or if its 'third_of_z', then x_new should be z/3. There are also more than just these definitions that indicate more complex functions of z are required. - If x_definition is any number, then x_new should just be that number.
I can rewrite it as
np.nan if row['x_definition'] is np.nan
else row['z'] if row['x_definition'] == 'equal_to_z'
else row['z']/3 if row['x_definition'] == 'third_of_z'
else row['x_definition'] if isinstance('row['x_definition'], int)
else np.nan

then you can do
df['x_new'] = df.apply(lambda row: np.nan if row['x_definition'] is np.nan
                    else row['z'] if row['x_definition'] == 'equal_to_z'
                    else row['z']/3 if row['x_definition'] == 'third_of_z'
                    else row['x_definition'] if isinstance('row['x_definition'], int)
                    else np.nan, axis=1)

or if you want to be more elegant
def logic_for_x_new(row):
 ...
 return x_new

df['x_new'] = df.apply(logic_for_x_new, axis=1)

Just be careful in how you check for nan in Pandas, I use the trick that x==x is false when x is NaN (just be careful with this)
Comment: using axis=1 in .apply() makes the function be applied row-by-row, and each row is basically a dictionary indexed by column name.


Como redirecionar para a página de login após um determinado tempo ocioso em PHP?

Question: Como o título da pergunta diz gostaria que a um tempo determinado onde o usuário se encontra ocioso, e assim o sistema destrua a sessão e redirecione automaticamente para a página de login. Eu sei que o php possui a função session_cache_expire() (http://php.net/manual/pt_BR/function.session-cache-expire.php). Porém pelo que entendi este tempo é independente do usuário estar ocioso, além do que ao terminar o tempo a sessão só ira ser destruída quando houver a requisição da página. Acredito que muitos aqui já tiveram a experiência desagradável de preencher um formulário extenso e ao enviar o submit perder os dados devido ao tempo gasto preenchendo o formulário (eu tive preenchendo os dados para inscrição do ENEM no celular). Preferiria utilizar apenas PHP, mas acho que será necessário utilizar javascrpit também. Desde já agradeço a atenção.
Comment: Esse exemplo do Enem é programação porca (e programação porca é o que mais tem, em especial na coisa pública). Um sistema decente manteria os dados do form, mesmo a sessão acabada, e te permitiria relogar pra continuar, num caso mais extremo. Pode ter algum tonto que não entenda de PHP e vai te falar pra aumentar o tempo de sessão, mas só mudaria o problema de lugar (além de não ser o jeito certo de se usar sessão). O ideal é pensar em como armazenar esse form, independente da sessão, e permitir o usuário continuar de onde parou (isso vale pra qualquer tipo de dado, não apenas para esse caso).
Comment: Em outras palavras, é muito bom que você esteja se preocupando com isso, mas não existe receita mágica que resolva com simplicidade. Sessão é pra ser uma ferramenta auxiliar. Tudo que precisa demorar bastante, pode ser gerenciado de maneiras mais complexas. Por exemplo, é muito mais limpo relogar o usuário automaticamente e de maneira transparente do que encompridar a sessão. Nesse caso o cookie avulso e o login não destrutivo (aceitar o form de qualquer jeito, mas pedir login pra prosseguir) tem menos efeitos colaterais.
Comment: Sobre usar JS, uma maneira seria um script ficar renovando a sessão junto do PHP, mas se nesse meio tempo há uma pequena falha de conexão, pode ter o problema da mesma forma. Outra idéia seria usar o JS para além de resolver o problema com PHP, você ter um cache local do form preenchido (e descartar depois de um tempo razoável sem uso, claro, seja em JS, seja em PHP). Qualquer caminho que escolher, vai precisar um pouco de raciocinio e capricho, mas afinal, programar é exatamente isso.
Answer: Eu faria da seguinte maneira,
1 - O usuário fez login
(cria-se uma tabela temporária no db, gravando um registro contendo a data e tempo)
2 - Um javascript é iniciado como objetivo de realizar requisições get a esta tabela temporaria verificando o registro de data e tempo que consta nela e confrontando com data e tempo da requisição, este javascript deve ser executado em intervalos de XX minutos.
3 - O usuário faz uma ação carrega uma pagina por ex:
(atualiza o registro regravando data e tempo) - o JavaScript continua sua rotina
4 - O usuário fica sem realizar ação por um tempo - o javascript em algum momento irá confrontar os dados e dai sim, quando o tempo de comparação for maior que o estipulado (tempo ocioso permitido), o javascript acionado um php que irá destruir a tabela temporaria e enviar o usuario a tela de login novamente.
utilizo desta forma em um sistema que desenvolvi.


Javascript sort table column on click

Question: My intention is to sort a table column (only the clicked th's column) in ascending order when th is being clicked. On further click the exact table column shall be ordered in a descending order.
What I got so far:
The table is being sorted, but on click all three columns are being sorted - I only want one column to be sorted.

function sortTable(n) {
    var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
    table = document.getElementById("table");
    switching = true;
    dir = "asc";

    while (switching) {
        switching = false;
        rows = table.rows;

        for (i = 1; i < (rows.length - 1); i++) {
            shouldSwitch = false;
            x = rows[i].getElementsByTagName("TD")[n];
            y = rows[i + 1].getElementsByTagName("TD")[n];

            if (dir == "asc") {
                if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
                    shouldSwitch = true;
                    break;
                }
            } else if (dir == "desc") {
                if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
                    shouldSwitch = true;
                    break;
                }
            }
        }
        if (shouldSwitch) {
            rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
            switching = true;
            switchcount ++;
        } else {
            if (switchcount == 0 && dir == "asc") {
                dir = "desc";
                switching = true;
            }
        }
    }
}

        Nummer
        Land
        Name

        2
        Rumänien
        Dan

        1
        Deutschland
        Aaron

        3
        USA
        Peter

Comment: Some suggestions to improve the question: You should be clear about what you expect the code to do, and what it actually does. You also should explain what you think the problem is, and why. And ideally, make the example code runnable.
Comment: @AlexMA I've updated the post, thank you.
Answer: This also looks like extreme overkill for the description. If all you want to do is sort your rows, then the code for that is a few lines:
function compareValues(a, b) {
  // return -1/0/1 based on what you "know" a and b
  // are here. Numbers, text, some custom case-insensitive
  // and natural number ordering, etc. That's up to you.
  // A typical "do whatever JS would do" is:
  return (ab) ? 1 : 0;
}

function sortTable(colnum) {
  // get all the rows in this table:
  let rows = Array.from(table.querySelectorAll(`tr`));

  // but ignore the heading row:
  rows = rows.slice(1);

  // set up the queryselector for getting the indicated
  // column from a row, so we can compare using its value:
  let qs = `td:nth-child(${colnum})`;

  // and then just... sort the rows:
  rows.sort( (r1,r2) => {
    // get each row's relevant column
    let t1 = r1.querySelector(qs);
    let t2 = r2.querySelector(qs);

    // and then effect sorting by comparing their content:
    return compareValues(t1.textContent,t2.textContent);
  });

  // and then the magic part that makes the sorting appear on-page:
  rows.forEach(row => table.appendChild(row));
}

The magic part works because DOM nodes can only exist in one place, so if you appendChild it to something, it gets moved from wherever it was in the first place. As such, we sort in JS, and then we run appendChild in that sorted order, every row is simply moved from "whereever it was" to "the end of the child list", which means after we run through every row in rows, presto: all the rows are now reordered as needed.
Of course you're still on the hook for writing compareValues(a,b) yourself. I don't know what you want to do there, because maybe you want natural text compare, or maybe you want "if the values are numbers, compare as numbers, only if they're not compare as text", etc.
But one thing you should do is not use 1998 event handling. Don't use onclick, do this properly on the JS side. So in your HTML:

  Nummer
  Land
  Name

And then on the JS side:
table.querySelectorAll(`th`).forEach((th, position) => {
  th.addEventListener(`click`, evt => sortTable(position));
});

(and better yet, use <button>Nummer</button>	 and add the event listener based on th button, because that's what it is. If you have text that can be clicked to "do something", that's a button. Use the correct markup, and then just use CSS to style it however you want, e.g. no border, background:inherit, etc)
Comment: Thank you very much! I'm new to JavaScript - you told me to not use the old event handling and showed me an alternative. But where do I use both, the function and the eventListener, how do I arrange them in my .js file (since the console tells me that `table` is not defined)?
Comment: normally anything you give an `id` attribute magically becomes a directly-usable variable on the JS side, but if that is not the case you can put `let table = document.getElementById('table')` at whatever is the most sensible "highest level" so that you can use it directly in your functions. Where you put functions is almost always irrelevant: JS "hoists" functions by reading all of them in _first_, before actually running your code. One of the lesser documented features of JS, but a super important one to know about.
Comment: I smh get another error: `Failed to execute 'querySelector' on 'Element': 'td:nth-child(undefined' is not a valid selector.` and furthermore, where do I exactly put a hook to compare the values?
Comment: That looks like a pretty obvious error? The `colnum` variable, which we know should be a number, is showing as `undefined` in the error message, so maybe you forgot to pass it in - have a look at where you're adding the event listener, and make sure you're passing in the th's position to the call to `sortTable`. As for the comparison function, it just has to live anywhere that is in scope for the `sortTable` function, so the obvious choice is "above or below it". I've updated the answer with a stub for it.
Answer: Mike 'Pomax' Kamermans' answer works very well except the sorted table will place the
s outside the
 tag, which is undesired.
This can be easily solved by changing his answer to this:
function sortTable(colnum) {
  let tbody = table.querySelector(`tbody`);
  let rows = Array.from(table.querySelectorAll(`tr`));

  // other codes...

  rows.forEach(row => tbody.appendChild(row));
}

Then the generated table should be working perfectly.
Answer: Maybe use a different approach. Store your data and sort the array before rendering.

let tblData = [{
    number: 2,
    land: 'Rumänien',
    name: 'Dan'
  },
  {
    number: 1,
    land: 'Deutschland',
    name: 'Aaron'
  },
  {
    number: 3,
    land: 'USA',
    name: 'Peter'
  }
];

const getRow = (data) => `<tr><td>${data.number}</td><td>${data.land}</td><td>${data.name}</td></tr>`;

const sortNumber = (a, b) => a.number - b.number;
const sortLand = (a, b) => (a.land === b.land) ? 0 : (a.land > b.land) ? 1 : -1;
const sortName = (a, b) => (a.name === b.name) ? 0 : (a.name > b.name) ? 1 : -1;

function buildTable(data) {
document.querySelector('tbody').innerHTML = data.map(row => getRow(row)).join('');
}

function sortTable(n) {
  let sort = sortNumber;
  switch (n) {
    case 1:
      sort = sortLand;
      break;
    case 2:
      sort = sortName;
  }
  console.log(n);
  buildTable(tblData.sort(sort));
}

buildTable(tblData);

      Nummer
      Land
      Name

Comment: No need, `appendChild` makes it really easy to sort the HTMLelements in JS, and then effect the reordering in the DOM with a `forEach`.
Answer: When running your code, I get the results that I would expect. I wonder if it seems like the results aren't correct simply because your data is setup that way.
For example, your data is:
1   Deutschland Aaron
2   Rumänien    Dan
3   USA Peter

And sorting on Number, would have Deutschland First with Aaron, and both Deutschland and Aaron are alphabetically first before the rest of the data.
So its an illusion that the other columns are being sorted, when in fact they are actually just following your data structure.

Javascript sort table column on click


For very beginning startup: home server or EC2?

Question: The micro instance of Amazon EC2 only has ram of 613MB, my laptop got 8GB. And I suppose likewise the processing power of my computer would be better than the micro instance.
My question is, what are the considerations in deciding to host yourself or on Amazon EC2, especially for a really baby startup?
For example, would network speed be a problem? My computer broadband network is 100Mbs up to 1Gbs. What would Amazon compare to this?
My site at these moment would just host some images and perform some php requests. I would probably also use cloudflare but seems it increases the dns lookup time considerably... And of course the overall  objective is to make the best user experience.
Comment: As a startup, you should not spend time to setup things that do not add business value. It will likely cost less if you pay for an external service that will manage it for you.
Comment: Related: http://serverfault.com/q/431966/7709
Answer: With very few exceptions never host from a laptop.
They're almost the diametric opposite of a server, they have little or no resilience to handle any failure whatsoever, are typically designed for battery life not performance, have slow disks usually, even their NICs aren't particularly capable.
Oh and your broadband is highly unlikely to be 100Mb-to-1Gb, that's the speed of the interface not your outgoing speed, in fact hosting via broadband is usually a very bad idea because your upstream speed is a fraction of your download speed.
We're professional sysadmins on this site (as I'm sure you read in our FAQ), we don't mess about, if you're just running a minecraft server or similar you may get away with what you have but if you care at all about your 'clients' then don't consider using a laptop or broadband link to serve them.
Comment: @StCee - AWS Micro == free for one year. No financial risk.
Comment: I can't believe this is even up for debate.  Wow.
Comment: Disagree: webserving is easy to scale horizontally, buying quality big-iron for webservers is a false economy. Look at what Google do. One of the best things you can do for performance and availability is to add a UPS - and laptops have one built-in. But as per answer elsewhere, other considerations suggest that this is not the route for StCee to follow.
Comment: I've no idea but I still think using a laptop will come back to bite you.
Comment: @symcbean what about redundant PSUs, laptop PSUs die, well they all do, what about ECC and CPUs that deal with faults better such as Xeons, what about simple disk mirroring? I'm totally fine with using low-end PCs as google do but using laptops is too far for me.
Comment: Thanks for all the answer here. One of the reason I ask the question is that I know that any body can start a web hosting business (well at least a lousy one) with a computer. So probably instead of joining some cheap shared hosting I can probably use my redundant laptop, and maybe make a high performance desktop to specialize in hosting. Is it still the case that shared hosting (like hostgator) >> hosting from your laptop/pc? In fact I do run through all the trouble (for a beginner) to set up my website on ec2. I just fear the cost would bankrupt me before I start to get profit.
Answer: If you have a business, you need real hosting, not some stuff running on your notebook. EC2 is certainly much more reliable than your notebook on a home broadband connection, and you can scale it effortless if your demands get bigger.
Also, home broadband connections are often asymmetric with a high download speed and a slow upload speed, which makes a home server impossible to begin with.
Answer: I think hosting a live website on your home laptop is a terrible idea, you have to take into account:

If you want reliability, you cannot rely on a laptop. If you have powercuts, if you laptop runs out of power, etc. your website is going to become unavailable. Using Amazon will solve this problem as there data centers will be highly disaster proof with minimum downtime.
In terms of security, how will you be allowing the outside world access to your laptop. You have to consider if the commercial router you will have is providing enough security to allow direct internet access to it.
If you're only running a small website serving up images and a few PHP requests, I do not imagine you will need more than a micro instance, it will be unlikely to be taxing the entire RAM.
Also, with your commercial broadband link, you probably have a very low amount of traffic coming down the link which could cause issues in the future.

I think your best bet will be to continue using Amazon EC2, the cost is minimal for a much better, more reliable service.
Answer: That you are asking the question implies you have limited experience / knowledge of managing a system. While it's difficult to learn how to do this without diving in and getting your feet wet, I'd strongly sugest that you look for a managed service (VPS or shared) - but do beware that the cheapest packages often offer the poorest levels of support.

For example, would network speed be a problem?

Network speed is always a problem - but usually it's latency that's the problem - not the bandwidth. Make sure your chosen provider is close to your user base.
Answer: You would face a myriad of problems hosting from home, the least of which would be your laptop. Some issues I can think of off the top of my head;

You undoubtedly have a dynamic IP given to you by your ISP, if this changes, your site goes down until you notice that it's changed, update your DNS records, and your DNS propagates.
You will (9/10 times) be violating the terms of services by hosting a service on your home ISP. In fact, port 80 and 443 might even be blocked by your ISP. Worst case scenario, your home internet service is shut off w/o warning due to hosting a website on a home connection.
Your upstream is a fraction of your ISP's package. You need to look at what package you have from your ISP, I guarantee it is not 1Gbs.
You might one day want to take your laptop out of the house with you?

I'm not clear on what you really need to host, if it's just ruby code, or php or something like that you should look at starting with heroku, which is a service based on top of AWS, which takes a lot of the management issues you face out of the picture. If you require windows (C#, etc) then you should look in to doing it yourself on AWS, or find a managed service out there that provides support for windows.
Comment: Re: #3, you can guarantee that the internet connection is not 1 Gbps as long as the asker doesn't live in a place like Hong Kong, Chattanooga, or Kansas City...
Answer: Assuming you're developing a Web/Internet based service, as of right now, your choices vary greatly: you can buy a server and put it in your own rackspace at a data center.  You could use shared/commodity hosting, get a virtual private server (VPS), or go with a cloud offering like Amazon's EC2.
The former requires expertise and a significant outlay of capital, but gives you the most control.  Shared hosting is probably the cheapest, but the service quality can vary greatly and they usually don't offer any guarantees on uptime at all and offer little in the way of control.  Virtual Private Servers are better in the quality and control department, but are more expensive and not quite up to the cloud's "theoretical" (more on that later) resiliency, uptime, and control.
As for the cloud, the promise of instant scalability and resiliency is so prevalent, but is not easily obtained without a very sound understanding of cloud principles and architecture to make that happen: an EBS-backed EC2 instance can fail unrecoverably just like any other server (happened to me last week, but thankfully I had a backup; an "old school" file level backup, but it was in-line with my uptime requirements for this not-so-important Linux instance I had running for a customer; I was up and running in a couple of hours and that suited them fine).
This is the "unknown", unfulfilled promise of the cloud that can bite a business just as badly as having a physical server with no backup can: if you don't know/understand the tools of the Amazon ecosystem and have designed your application/service with these tools in mind, your app is no more resilient than a shared hosted, VPS, or physical box somewhere.
Having said that, one cloud-based solution that may be the most appealing to you is Platform as a Service such as Microsoft Azure: you get the .NET/SQL application development stack you require, but the infrastructure is someone else's responsibility with SLAs to back it that you can mirror in your SLA to your customers.
Answer: Given that you are a startup you have absolutely minimal server requirements. Why not do what 99% of other startups do and use shared hosting? Everything is managed for you, which lets you get on with the business of conducting your business. If, and only if, you grow beyond shared hosting should you look at any of the other alternatives.
Hosting from home has so many downsides that I'm not even going to attempt to list them. Suffice to say that the worst thing for your business is to have your system down due to circumstances totally outside your control.


Exchange 2013 IPBlockListProvider blocking some (but not all) matched IPs

Question: I have configured our Exchange 2013 Edge Transport server to utilize several IPBlockListProviders including Spamhaus.  While they work great most of the time, there are still some emails which despite being matched by one of the block list providers get through.
Taking for instance an email that was received recently from IP 22.214.171.124 which is most certainly on the Spamhaus SBL as well as a few others (http://mxtoolbox.com/SuperTool.aspx?action=blacklist%3a188.8.131.52&run=toolpage) and correctly identified by the Edge server as such:
<code>[PS] C:\Users\Administrator>Test-IPBlockListProvider -Identity "Spamhaus" -IPAddress 188.8.131.52

Provider                                ProviderResult                                                          Matched
--------                                --------------                                                          -------
Spamhaus                                {127.0.0.3}                                                                True
</code>
I have verified that I'm not using any public DNS forwarders (such as Google's), so it's not an issue of all or nothing being blocked.
What's most confusing is that this configuration works for the majority of messages received which are on an SBL:
<code>[PS] C:\Program Files\Microsoft\Exchange Server\V15\Scripts>.\get-AntispamTopRBLProviders.ps1

Name                                                                                Value
----                                                                                -----
Spamhaus                                                                                4594
SpamCop                                                                                48
</code>
Interestingly, one thing that seems to have made a significant difference is modifying the priority of the transport agents such that the Connection Filtering Agent is first.  This is my current configuration in case it's pertinent:
<code>[PS] C:\Program Files\Microsoft\Exchange Server\V15\Scripts>Get-TransportAgent

Identity                                           Enabled         Priority
--------                                           -------         --------
Connection Filtering Agent                         True            1
Sender Id Agent                                    True            2
Sender Filter Agent                                True            3
Recipient Filter Agent                             True            4
Content Filter Agent                               True            5
Address Rewriting Inbound Agent                    True            6
Edge Rule Agent                                    True            7
Attachment Filtering Agent                         True            8
Address Rewriting Outbound Agent                   True            9
Protocol Analysis Agent                            True            10
</code>
I'm including the full message headers (with my server's identities redacted) of an email from an IP address that is on an SBL below.  It's clear that the inclusion of all of the SPAM filtering I have is impacting the time it takes for a message to make it through to the mailbox server (in this case, 8 seconds between submission and delivery), however it doesn't seem to be enough.
<code>X-Ms-Exchange-Organization-Network-Message-Id: 32388ce4-005a-4090-a363-08d2612d1e23
X-Ms-Exchange-Organization-Authas: Anonymous
Pm-Xs: 15766241f_7460962er.x15766241
X-Ms-Exchange-Organization-Avstamp-Enterprise: 1.0
Vr-Yhkrg: 15766241s-15766241e_i7460962
X-Ms-Exchange-Organization-Prd: heliq240.emited.work
X-Ms-Exchange-Organization-Pcl: 2
Return-Path: email@example.com
X-Ms-Exchange-Organization-Scl: 1
Mime-Version: 1.0
Ybu-Efa: c3195284488a449ed165c2c50f18376bb-ec3195284488a449ed165c2c50f18376b.u15766241
Okul-Lfp: 15766241y.15766241n_c7460962
X-Ms-Exchange-Organization-Senderidresult: None
X-Ms-Exchange-Organization-Antispam-Report: DV:3.3.14519.472;SID:SenderIDStatus None;OrigIP:184.108.40.206
Message-Id: <email@example.com>
X-Ms-Exchange-Organization-Authsource: edgeserver.mydomain.com
Content-Type: multipart/alternative; boundary="15766241"
Received-Spf: None (edgeserver.mydomain.com: firstname.lastname@example.com does not designate permitted sender hosts)
Received: from mailboxserver.mydomain.com (192.168.1.2) by mailboxserver.mydomain.com (192.168.1.2) with Microsoft SMTP Server (TLS) id 15.0.847.32 via Mailbox Transport; Wed, 20 May 2015 10:59:49 -0500
Received: from mailboxserver.mydomain.com (192.168.1.49) by mailboxserver.mydomain.com (192.168.1.49) with Microsoft SMTP Server (TLS) id 15.0.847.32; Wed, 20 May 2015 10:59:43 -0500
Received: from edgeserver.mydomain.com (192.168.1.4) by mailboxserver.mydomain.com (192.168.1.49) with Microsoft SMTP Server (TLS) id 15.0.847.32 via Frontend Transport; Wed, 20 May 2015 10:59:43 -0500
Received: from heliq240.emited.work (18.104.22.168) by edgeserver.mydomain.com (192.168.1.4) with Microsoft SMTP Server id 15.0.847.32; Wed, 20 May 2015 10:59:41 -0500
New telecommuting opportunities available today - 05/20/15
</code>
Any suggestions?
Also, this is my first post on any of the Stack Exchange sites.  I hope this question is both merited and on the correct site.  If not, please do let me know!
Comment: Are your IPBlockListProviders Enabled?  I'm not sure what a Test- would do against a disabled provider.
Comment: @blaughw Yes, they are enabled.  Using [this](http://www.crynwr.com/spam/) site to test yields expected results for all tests.
Answer: I recommend you check your AllowLists as well, as it seems you have a hard hit against a (presumably enabled) BlockList.  My hunch is that you must have a rule in the Transport flow that successfully validates the message. Since Connection Filter is highest in the list, I would think the buck stops there.
Comment: Good point, I should have said whether I use allow lists.  I don't have any allow list providers and the only allowed IPs are from known servers (not, for example, the one listed in the question).


How to use sus2/sus4/add9 in minor key to stay within the key

Question: I understand how to use sus2/sus4 and add9 inn major to keep all notes within the chosen major scale, but how can I use the same chords in a minor key and still stay in key?
Comment: Surely the same way. With su2/4 there's no clue as to major or minor, so what's the difference? With add9, the maj./min. is implicit..
Comment: Just to get an idea, could you explain your current understanding? I'm about 92% certain that everyone around here has a different understanding or guess about the question. What are you trying to do, and what kind of problems are you having in a minor key? What do you mean by "in key"?
Comment: By 'in key' i mean for C major/A minor I ONLY want to hear the notes C, D, E, F, G, A, B.
Answer: Jazz chord symbols are not relative to a key.
The are relative to a major dominant thirteenth chord. All interval numbers and modifiers work from that base chord: triads are major, sevenths are minor, ninths major, elevenths perfect, thirteenths major. Modifiers work from those defaults.
So, G7 is a G root, major triad, and minor seventh.
But, Gmin7♭5 get the modifiers min and ♭5 as changes to the defaults.
Sorry, for that tedious explanation, but it's important, because the main part of your question about suspensions is that they work the same in major and minor keys. Suspensions are dissonances over a chord root which traditionally get resolved to consonances. That's the same in major and minor keys.
The thing that changes with jazz chord symbols and major and minor keys is the specific quality of all intervals in chord symbols. It isn't limited to just the intervals of suspensions.
You can now look at your list...

sus2/sus4 and add9

...and first say...

sus2 is a major second above the root
sus4 is a perfect fourth above the root
add9 is a major ninth above the root

Now you just need to know where those are not the diatonic intervals in minor. I will just work with a minor key signature on not bother with the variable sixth and seventh scale degrees in minor...

seconds are minor between ^2/^3 and ^5/^6, a suspended second on a iio or V
fourths are augmented between ^6/^2, a suspended fourth on a ♭VI
ninths are just an octave added to seconds so the minor ninths are the same as the minor seconds between ^2/^3 and ^5/^6, a suspended second on a iio or V

If a chord deals with those intervals you need to add a flat to it to show the change that makes it diatonic in minor. You do this regardless whether the interval is a chord tone or a suspension tone.
To show how both chord tone intervals and suspension intervals change to fit a major or minor key tonality here are two examples, major first, then minor...

...I put courtesy accidentals in parenthesis to show any interval modified from the default dominant thirteenth chord. Those correspond to the jazz chord modifiers m for minor triads, sus#4, Δ7, ♭5, and ♭9.
It's tedious, but if you really want major or minor key tonality, you need to spell/label intervals correctly.
Answer: First keep in mind that minor keys actually use three different scales for melodic and harmonic purposes, the natural, harmonic and melodic minor scales. Let's just look at the diatonic chords of only the C natural minor scale. Keep in mind that using a sus2 or sus4 chord takes away the 3rd, the chord tone that makes a chord either major or minor:
The i: Cm, Csus2, Csus4, Cm(add 9)
The iio: Do (sus 2,4 and add 9 are not possible unless you use melodic minor)
The III: Eb, Ebsus2, Ebsus4, Eb(add 9)
The iv: Fm, Fsus2, Fsus4, Fm(add 9)
The v: Gm, (sus 2 and add 9 are not possible unless you use melodic minor) Gsus4,
The VI: Ab, Absus2, Ab(add 9) (sus4 would contain Db, not D natural)
The VII: Bb, Bbsus2, Bbsus4, Bb(add 9)
This is not taking into account all the other options available by using the harmonic or melodic minor scales. I would also like to add that there is no need to stay "in key" when composing unless you are challenging yourself to do so for whatever reason you might have.
Comment: I don't have enough reputation to comment on an answer, but beware that there is an issue in your favored answer. The VI cannot have sus4 and stay in the minor key because the 4 (relative to the VI) is a semitone above the root. The sus2 is ok on the VI though because the 2 (relative to the VI) is the VII of the key.
Comment: I will accept this answer as it is the most useful for my use case.
Comment: @MightyMorphism I answered this ages ago but hey, good catch! I will edit.
Answer: Chords are defined independently of the key of the surrounding music. C = CEG even if the piece itself is in, say, E major.
The definitions of the OP chords are:

Sus2 = root - M2 - P5
Sus4 = root - P4 - P5
Add9 = root - third - fifth - M9

Suppose we're in C major Csus2 = CDG. All notes are diatonic to C major. This is also true in C minor.
But consider the chord Dsus2: DEA. In C major, this chord is again diatonic, but not in C minor. To remain diatonic in C minor, the chord would be either Dsus[b2][b5] or Dsus[b2], depending on whether the context has the flat or raised sixth (minor keys allow for both, as well as both flat and raised seventh).
Similar alterations can be made to other chords. For example:

an Fsus4 (FBbC) is not diatonic to C major. For a diatonic version in C major, the chord would be altered to Fsus[#4].
in C minor, change Dadd9 to Dadd[b9] in order to include Eb in the chord instead of E.
Comment: 'Chords are defined independently of the key of the surrounding music' - then later you quote chord names diatonically. I'm confused.
Comment: @Tim Can you point out one of the chords you have in mind?
Comment: DEA - Dsus2. becomes Dsusb2 in Cm. So now is DEbA - sounding strange!
Comment: Yeah 9th's are not considered diatonic, they are just major 9ths if there's no alteration just like just 7 is not diationic, it's the minor 7th.
Comment: @Tim I'm not sure I understand your question. But agreed, DEbA is an odd sound.
Comment: I think that diatonic `D` chord in minor would be `Dsus(b2)(b5)`
Comment: @MichaelCurtis You're right; my oversight. But also brings up an Interesting point. Since minor admits both flat and raised 6 and 7, I suppose you could have it both ways. I've updated my post.
Comment: That's true and complicates this question. But I figure without more context assume `iim7b5 V7 i`, a basic minor jazz progression.
Comment: You describe my problem perfectly.


Stored procedure is not incrementing more than 10 increment

Question: Create the following stored procedure but the @tagID is not incremented for more than 10 serial from 1 - please help.
CREATE PROCEDURE [dbo].[bulk_employee]
    @active BIT,
    @FNAME NVARCHAR(50),
    @DOB DATE,
    @DOJ DATE,
    @GENDER NVARCHAR(10),
    @FATHER_NAME NVARCHAR(50) = NULL,
    @AADHAR NVARCHAR(14),
    @ESIC NVARCHAR(10) = NULL,
    @UAN NVARCHAR(10) = NULL,
    @SALARY INT,
    @BRANCH INT,
    @DIVISION INT,
    @USER INT
AS
BEGIN
    DECLARE @TagID INT;

    SELECT @TagID = COALESCE((SELECT MAX(Emp_ID) + 1 FROM EmployeeP1), 1)

    INSERT INTO EmployeeP1 (isActive, Emp_ID, FirstName, BirthDate, JoiningDate, Gender, FatherName, aadharnumber, ESIC, UAN, SalaryID, DivisionID, BranchID, AccessBy, LastUsed)
    VALUES ('0', @TagID, @FNAME, @DOB, @DOJ, @GENDER, @FATHER_NAME, @AADHAR, @ESIC, @UAN, @SALARY, @DIVISION, @BRANCH, @USER, CURRENT_TIMESTAMP)
END

EmployeeP1 structure
CREATE TABLE [dbo].[EmployeeP1]
(
    [EmployeeID] [int] IDENTITY(1,1) NOT NULL,
    [Emp_ID] [nvarchar](10) NULL,
    [isActive] [bit] NULL,
    [FirstName] [nvarchar](50) NOT NULL,
    [LastName] [nvarchar](50) NULL,
    [BirthDate] [date] NOT NULL,
    [Gender] [nvarchar](10) NOT NULL,
    [FatherName] [nvarchar](50) NOT NULL,
    [MotherName] [nvarchar](50) NULL,
    [Address1] [nvarchar](50) NULL,
    [Address2] [nvarchar](50) NULL,
    [Address3] [nvarchar](50) NULL,
    [Pin_Code] [numeric](6, 0) NULL,
    [DistrictID] [int] NULL,
    [StateID] [int] NULL,
    [Mobile] [nvarchar](10) NULL,
    [Mobile2] [nvarchar](10) NULL,
    [Email] [nvarchar](50) NULL,
    [AccountName] [nvarchar](50) NULL,
    [BankAccount] [nvarchar](30) NULL,
    [IfscCode] [nvarchar](11) NULL,
    [PermanentAccount] [nvarchar](10) NULL,
    [AadharNumber] [nvarchar](14) NULL,
    [JoiningDate] [date] NOT NULL,
    [ESIC] [nchar](12) NULL,
    [Esic_Joining_Date] [date] NULL,
    [UAN] [nchar](12) NULL,
    [UAN_Joining_Date] [date] NULL,
    [EPF_ID] [nvarchar](10) NULL,
    [SalaryID] [int] NOT NULL,
    [DivisionID] [int] NOT NULL,
    [BranchID] [int] NOT NULL,
    [AccessBy] [int] NOT NULL,
    [LastUsed] [datetime] NULL,

    PRIMARY KEY CLUSTERED ( [EmployeeID] ASC)
) ON [PRIMARY]

The input as with bulk insert is like below :

Expect the serial increment for all the record inserted with bulk import
Comment: A little unclear.  Add the create table script for `EmployeeP1`, and add example data showing what it currently does vs what you want it to do.
Comment: Thanks, that clears it up.  Looks like Mudassir has you covered.  Either modify the table to store `Emp_Id` as `int` (or another numeric data type) or change your script to `...select max(cast(emp_id as int)) + 1...`.  I'd recommend the first option assuming you can modify the table.
Comment: question updated
Comment: @AaronDietz thanks for your valuable comment and the same is working like PRO
Answer: EmpId is nvarchar, so when it's value reaches 10, the max value remains 9 as in character comparison 9 is greater than 10 so you will keep getting 9 + 1 as next value.
Also you already have Employee ID column in table with auto incrementing values so I don't think EmpId column is required.
Comment: here the Emp_ID is nvarchar but i store its value from `@tagid` value not the same empid value. as per statement the `max(emp_id)` is 10 and after increment it assign to `@tagid` and after that stored in table data.
Comment: Thanks for Reply but the other Emp_ID for manual entry by user end and EmployeeID for database auto increment
Comment: Check Aaron Deitz comment..change your query as written by him
Answer: The concept has been answered, however I am adding a "safety" condition in the where clause. (thus my new answer)
Generic Northwind example where the column is a string-column BUT has int values.
  SELECT MAX(CAST(PostalCode as INT)) + 1 as NextValue FROM dbo.Customers
    WHERE
        ISNUMERIC(PostalCode) > 0 /* protect against non int values in a string column */

Probably your query:
  SELECT MAX(CAST(Emp_Id as INT)) + 1 as NextValue FROM dbo.EmployeeP1
    WHERE
        ISNUMERIC(Emp_Id) > 0 /* protect against non int values in a string


C Compiler Warnings for Dangerous Casts

Question: With all C compilers that I'm aware of, -Wall warns about implicit casts but never warns about any explicit casts. I've been trying to find a flag (doesn't matter if it's for gcc, clang, any c compiler will do) that will cause a warning to be emitted when there is a cast that results in undefined or implementation-defined behavior. Here's an example illustrating where I would and wouldn't expect a warning:
#include <math.h>

struct person {
  int tag;
  char* name;
};

int foo(struct person* p) {
  int* tagPtr = (int*)p; // this cast is fine, cast to first member ptr is allowed
  double* badPtr = (double*)p; // this cast should cause warning
  return ((*tagPtr) + (int)(round(*badPtr)));
}

The cast to a an int* is well defined, and the cast to double* is not, but gcc does not warn me about this second cast. Is there a way to get it to do so? Or does another compiler or even a linter provide this feature?
And then there's the area in between "definitely well defined" and "definitely implementation defined" which is "could be well defined depending on context". For example, casting from a int* to a struct person* is well defined if the int* was originally formed by a cast in the other direction (implied by section 188.8.131.52p15 of C spec). The provenance of a pointer is seldom available, so a compiler or linter would not known if this cast was sound or unsound, only that it is possible that it is sound. To be useful to me, the warn-on-dangerous-cast feature would need to not warn in this situation, only in situations where the cast is guaranteed to be implementation-defined behavior.
Is there a tool that can help with this?
For context, I'm working on using C as a target for a language with tagged variants. If the variants have different sizes, casting is essential. It would be nice, however, if the compiler could help-spot check my generated code by making sure I don't do any nonsense casts. I suspect that optimizing compilers should have the information to provide this warning since this is the same information that would be needed for alias analysis. I've just not been able to figure out if any compiler bends the information to this end.
Comment: A lot of the *point* of type casts in C is to tell the compiler, "I promise I know what I'm doing, so don't complain." So I think you're unlikely to find a compile option that that tells the compiler, "Go ahead and second guess me anyway."
Comment: This is not unprecedented. Compiler options like gcc's `-Wcast-align=strict` instruct the compiler to second guess the user and warn on certain explicit casts.
Comment: For clang, the answer is no.  It has a handy `-Weverything` option that enables every warning it implements, and this gives no relevant warnings on your code.  https://godbolt.org/z/91vEPKjz3
Answer:
Is there a tool that can help with this?

Yes: The clang-cl compiler that you can (optionally) install and use in Visual Studio 2019. I copy/pasted your code without change into my VS IDE and this was clang's response:

warning : cast from 'struct person *' to 'double *' increases required
alignment from 4 to 8 [-Wcast-align]

Running a (static) code analysis added this:

warning GCC3CDF22: cast from 'struct person *' to 'double *' increases
required alignment from 4 to 8 [clang-diagnostic-cast-align]
Comment: Oops (maybe) - The warning is generated *only* when I target Win32 - not when I target x64. Seems weird.
Comment: GCC has a similar flag, and it can be used as `-Wcast-align=strict` to get this warning even when targeting x64. Unfortunately, this only catches situations where the alignment differs. It doesn't warn on incompatible struct conversions unless the structs happen to have different alignment. For the purposes in the original question, this flag causes false positives since a cast from `int*` to a 8-byte-aligned struct that starts with `int*` will lead to a warning.

C Compiler Warnings for Dangerous Casts


Let $G$ be a group and $x$ be a fixed element of $G$. Prove that $G$ is a group under the operation $*$ where $a*b=axb$

Question:
Let $G$ be a group and $x$ be a fixed element of $G$. Show that $G$ is a group under the operation $*$ where $a*b=axb$.

I need to prove this by showing the $3$ properties of a group, someone please show how to do the first and then I'll try to do the others.
Comment: It's bad form to put the main question *only* in the title. You ought to copy it to the body of the post too.
Comment: Rolled back an edit which changed the $x$ to a $\times$. It seemed... mistaken.
Comment: context... and a statement of the question in the body, to name a few things.
Comment: What is my question missing ?
Comment: @rschwieb I edited as you suggested.
Comment: Good... if you added work for the parts you were able to accomplish, I would even join in reopening.
Answer: For any bijection $\varphi: G\to G$, the binary operator
$$a*b:=\varphi^{-1}(\varphi(a)\varphi(b))$$
always makes $G$ a group with identity $\varphi^{-1}(1)$.
In this place, $\varphi: g\mapsto xg$.
Comment: This even works for any bijection $\varphi: X\to G$, where $X$ is a set and turns $X$ into a group isomorphic to $G$. This technique is called *transport of structure*.
Answer: All right. The first one is (usually) associativity. Take $a,b,c\in G$. Then\begin{align}(a*b)*c&=(axb)xc\\&=ax(bxc)\\&=a*(b*c).\end{align}
Comment: @hjx The identity element is $x^{-1}$, because $a*x^{-1}=axx^{-1}=a$ and $x^{-1}*a=x^{-1}xa=e$. FInally, the inverse of $a$ is $x^{-1}a^{-1}$. Can you prove this one?
Comment: My mistake. What I meant was $x^{-1}*a=x^{-1}xa=a$.
Comment: Could you please show the other proofs ? I tried to do the others but they are wrong according to my teacher.
Comment: Sorry for the late response. But I'm confused about $x^{-1}*a=x^{-1}xa=e$, why is this equal to e ?
Comment: How Can I prove that the inverse of a exists ?
Comment: @hjx I don't know if you can, but I can. The inverse of $a$ is $x^{-1}a^{-1}x^{-1}$.


Little finger positioning on fretting hand while playing guitar 3-notes-per-string

Question: I would like some advice on my left (fretting) hand pinkie's (little finger) orientation when I'm playing three-note-per string scales at faster tempos. I find the pinkie flattens, especially the joint closest to the fingertip. I know my other fingers are stronger, and I see that they (middle and ring finger) are often perpendicular to the fretboard during such exercises. With the pinkie, it stays perpendicular when I concentrate, or play slower, but if I forget, I see it's flat again. I also find that it is harder to target the string with the pinkie when it is perpendicular; though perhaps that's less surprising.
Here is a photo showing the flattened pinkie orientation that concerns me:

Here is a photo showing my pinkie with a more perpendicular orientation:

My question is: am I correct to believe that the flattened pinkie is indeed a weakness that may become problematic at higher tempos? If so, are there any exercises which can help improve the pinkie position, or is it simply a case of slowing down the exercises and starting a fresh effort here?
I've been playing on and off for about 30 years, but have picked the guitar up again during Covid-19 lockdown.
Answer: There's really no need to have all three fingers pressing for a 3nps scale. Only if you're pulling off to the lower two notes, which I doubt. So moving your hand slightly up/down the 'board will put any finger in a stronger, perpendicular position.
In fact, while the highest note is being played, on ascending scales, the other two fingers need to be moving to the next string up, not staying anchored where they've already done their job.
Comment: I'm not sure if I understand the answer. You normally don't want to move the hand too much for each note, that's inefficient. Indeed you don't need to press the string with all 3 fingers at the same time (or even you shouldn't), but they should be positioned just above the string, ready to press it, that is in almost the same place.
Comment: @user1079505 - a lot of folk, myself included - and maybe the OP - can't stretch that far comfortably anyway. But even if they can, playing the three notes (especially on the bottom two strings, lower frets), there's no need to keep all pressed down - although descending there may be a tiny argument *for* that. Ascending, my 2nd para. covers it.


Token based authentication http interceptor

Question: I would like your opinion in order to achieve something. I have an api and I want to restrictionate the access of the user. But short story long, in action login controller of page /login I generate the token for the user autheticated and I return it. Well, here comes one of my question/problem. It's mandatory in a action controller to return a response, and my token it's send in json format and it's displayed on browser, but I don't want this, I just want to keep in response or in something so that my angular part to take that token and to take care of it in its way. So my method login:
  public function loginAction(Request $request)
{

    $username= $this->get('security.token_storage')->getToken()->getUser()->getEmail();
    $serviceUser = $this->container->get('ubb_user_login');
    $tokenUser = $serviceUser->generateToken($username);
    $response = new JsonResponse(array('Token' => $tokenUser));

    return $response;
}

2nd problem. I do not know in angular where to extract the token. In a controller I tried something:
app.controller('loginApi', function ($scope, $http, $window){

$http.get(
    '/api/user/login'
).then(function (success) {
    $scope.token = success.data.Token;
    $window.localStorage.setItem('Token', token); // it's okay used like this localStorage?
});
});

Here, I want only to take the token from /login action, to save it in local storage, and then to display it on every request using $http request interceptor. That part works. If I send a random string in header auth it's working and it gives me access to api:
function httpInterceptor() {
return {
    request: function(config) {
        config.headers.authorization = 'jdjdnnkdkd';
        return config;
    },
    responseError: function(errorResponse) {
        switch (errorResponse.status) {
            case 403:
                window.location = '/login';
                break;
            case 401:
                window.location = '/login';
        }
        return $q.reject(errorResponse);
    }
 }
 }

So, the problems I encounter:
1) How to send the token in order for angular to take it, but to not be displayed in the browser? Let's say that I have a menu that access the api, and if the user it's not authenticated,clicking on a link unauthenticated it's sending me on the login page, and after I auth with success, to redirect me on the menu?
2) After returning the token, where exactly to use it in angular? In which controller? And how to save it?
Much appreciation, thank you.
Answer: It seems like you need a separate api resource for working with the tokens. Have you tried using FOSOAuthServeBundle? It helps a lot with setting up oauth authentication, tokens etc.
In general you need to have a separate call for the token, i.e.:

angluar app makes request to a get token resource, a token is returned and temporarily stored in the angular app
use that token for each subsequent request - check the oauth bundle config on how to set which urls have to be oauth protected, but that bundle takes care of this for you

Regarding your angular issue, look at this q/a How to store authentication bearer token in browser cookie using AngularJS
Comment: Thank you for your response, but I want to use my idea, I already implemented Auth Token and it returnes me the user by the given token, the only part is this one. How to send it angular. Can you give me some information in order for this to work?


CSS background-position 0.1s linear;

Question: What does the linear attribute mean in CSS?
 background-position 0.1s linear;

I am looking at this code and am unfamiliar with the linear attribute.  How does this change the gradient of a button?
.btn:hover {
  color: #333333;
  text-decoration: none;
  background-color: #e6e6e6;
  background-position: 0 -15px;
  -webkit-transition: background-position 0.1s linear;
  -moz-transition: background-position 0.1s linear;
  -ms-transition: background-position 0.1s linear;
  -o-transition: background-position 0.1s linear;
  transition: background-position 0.1s linear;
}

Answer: The word linear represents the easing functionality used in your css transition - this is formally known as a "transition-timing-function". In this case linear is telling the css that this element will maintain the same speed throughout the animation of this Transition.
When we specify a transition-timing-function we are defining a curve graph that represents the speed throughout the animation.
Take a look at the MDN documentation here - you can see a list of the other options
To get other interesting animation effects you can try "ease-in" or "ease-out" which represent animations that start slower and speed up or start quickly and slow down.
Using cubic-bezier(start, mid1, mid2, end) you can even define your own easing if you were so inclined.  The four values represent speed at Start MidPoint1 MidPoint2 and End of the animation.

CSS background-position 0.1s linear;


Nginx - Redirect ignoring server_name

Question: <code>#default:
server {
    listen 80 default_server;

    server_name _;

    return 404;
}

server {
    listen 443 default_server;

    server_name _;

    ssl_certificate         /etc/nginx/ssl/dummy.crt;
    ssl_certificate_key     /etc/nginx/ssl/dummy.key;

    return 404;
}

#old-domain:
server {
    listen 80;

    server_name old-domain.com;
    server_name www.old-domain.com;

    return 301 https://www.old-domain.com$request_uri;
}

server {
    listen 443;

    server_name old-domain.com;
    server_name www.old-domain.com;

    ssl_certificate         /etc/nginx/ssl/old-domain.crt;
    ssl_certificate_key     /etc/nginx/ssl/old-domain.key;

    #catch all
    return 301 https://new-domain.com;
}

#new-domain:
server {
    listen 80;

    server_name new-domain.com;
    server_name www.new-domain.com;

    return 301 https://www.new-domain.com$request_uri;
}

server {
    listen 443;

    server_name new-domain.com;
    server_name www.new-domain.com;

    ssl_certificate         /etc/nginx/ssl/new-domain.crt;
    ssl_certificate_key     /etc/nginx/ssl/new-domain.key;

    ....
}
</code>
As, requested, here is the output of curl -I for the various requests:
curl -I http://old.domain.com

HTTP/1.1 301 Moved Permanently
  Server: nginx/1.16.1
  Date: Mon, 11 Nov 2019 07:48:57 GMT
  Content-Type: text/html
  Content-Length: 169
  Connection: keep-alive
  Location: https://www.old.domain.com/

curl -I https://old.domain.com

curl: (60) SSL certificate problem: self signed certificate
  More details here: https://curl.haxx.se/docs/sslcerts.html
  curl failed to verify the legitimacy of the server and therefore could not
  establish a secure connection to it. To learn more about this situation and
  how to fix it, please visit the web page mentioned above.
Comment: I have added a more detailed example of my config.
Comment: Welcome to ServerFault. Please post an example curl request on what's happening and what's expected to happen.
Comment: I have added the curl output to the original question.
Answer: I think that the problem it's with the certificates. You need to add the ssl proper certificate to the server block that you are redirecting on the old domain. Make sure that the certificate on the old domain is correct or it won't work

Nginx - Redirect ignoring server_name


Attempt to prove the $∀d∀x∀y (d | x ∧ d | y ∧ x ≤ y → d | y- x)$ property of the "divides" relation for non-negative integers

Question: I am attempting to prove the $∀d∀x∀y (d | x ∧ d | y ∧ x ≤ y → d | y- x)$ property of the "divides" relation for non-negative integers, but am having a little difficulty and am hoping someone can help.
I have access to the standard rules of natural deduction, the following axioms:

and the following useful formulas:

Here is my attempt so far:
Comment: Not clear what you are asking... The long "list" has been produced by way of some proof assistant ? If so, the last formula (53) is what you have to prove: thus, it must be correct (if the proof assistant works correctly). If not, how do you produced it ?
Comment: @MauroALLEGRANZA The OP is using JAPE, a proof writing/checking assistant.  The ... between lines 33 and 34 means that there is still a gap in the proof.
Answer: The key formula you will have to use is:
$\forall x \forall y \forall z (z \not = 0 \rightarrow (x\cdot z \le y\cdot z \rightarrow x \le y))$
So, you will need to first consider the special case where $a=0$, but in that case you can easily show that it must be the case that $a1=0$ and $a2=0$, and it is also easy to show that $0|0-0$ so you're done.
So then you can consider $a \not = 0$, and s0 you have:

$a \not = 0$
$a|a1$
$a|a2$
$a1 \le a2$
$a1 = a3\cdot a$
$a2 = a4\cdot a$

So then using some = Elim's:

$a3\cdot a \le a4 \cdot a$

And now you use the key formula to get:

$a3\cdot a \le a4 \cdot a \rightarrow a3 \le a4$
$a3 \le a4$  (6,7)

and you already have the rest.
Comment: Thanks so much :) I managed to finish it with your steps I never thought of splitting on 0.
Comment: @Brams28 Would you be able to tell me which axioms/useful formulas I need to be using to prove $∀ d. ∀ x. (x ≠ 0 ∧ d | x → d ≤ x)$ ?
Comment: @MarkDonaghue Ah, that's great you were able to finish the proof! OK, for the other one ... I would think the key one there is one of the Peano Axioms: $\forall x \forall y x\cdot s(y) = (x \cdot y) + x$, since if $d$ devided nonzero $x$, then $x = d\cdot y$ for some nonzero $y$, hence ... Oh!  You probably need a 'predecessor' theorem that says that $\forall y (y \not = 0 \rightarrow \exists z y = s(z))$ ... anyway, if you have that, then $x = d \cdot s(z) = (d \cdot z) + d$ and hence $d \le x$.

Attempt to prove the $∀d∀x∀y (d | x ∧ d | y ∧ x ≤ y → d | y- x)$ property of the “divides” relation for non-negative integers


How to configure failover in edgerouter x 5 ports?

Question: I have connected to my edgerouter x 5 ports, 2 WAN (WAN1 to eth0 and WAN2 to eth1 in failover)
Problem: WAN1 has 10 Mbps and WAN2 Failover 8 Mbps. When WAN1 drops, but not enough (example: 1 or 0.5 Mpbs), WAN2 failover does not enter.
What I want is that when WAN1 drops to XX Mbps, WAN2 goes into operation in failover mode and returns to WAN1 when it exceeds XX Mbps, in a recovery time of XX minutes
Where XX are values that I determine manually
My edgerouter x:

I did not find the information in the ubiquiti user manuals for this router HERE, HERE or HERE
I appreciate the help.
PS: I apologize if this is not the right forum to ask this question. I searched on stackexchange but didn't find any hardware to post this question
Comment: *What* parameter do you want to trigger on? When available bandwidth is under 2Mb/s? How can you know if available BW is <2Mb/s?
Comment: The question describes the scenario. What I want to activate the failover when I want, according to my parameters and not when the router decides.
Comment: How do you determine the available bandwidth?
Comment: I suppose that it will be necessary to take them from the RX/TX (although these values do not represent reality, but it is close). But I really wouldn't know
Comment: You can't do that. You don't know why you have low speed. It can be a video feed that just happens to consume 400Kb/s, or it can be a download that is slow. The problem is simply that the router has ***no way of knowing*** the parameter you want to act upon. This is not a trivial problem; it's fundamental.
Answer: There's no such thing as Ethernet running at 2Mbps. If you have some other means of getting a bandwidth report reliably (e.g. DSL or 3G modem status page) you can incorporate this check in a bash script, save it somewhere in /config/scripts so it will survive firmware upgrades and then call it in your load-balance stanzas like in the example below.
In this example WAN2 is on eth2 and is a backup, while WAN1 is on eth1 and its the primary link. You would also need to create routing tables 10 and 20 with the appropriate defaults in each and reference them in firewall modify rules:
load-balance {
group WAN2 {
    exclude-local-dns disable
    flush-on-active disable
    gateway-update-interval 20
    interface eth1 {
        failover-only
        route {
            table 10
        }
        route-test {
            initial-delay 180
            interval 60
            type {
                script /config/scripts/pinger
            }
        }
    }
    interface eth2 {
        route {
            table 20
        }
        route-test {
            initial-delay 180
            interval 60
            type {
                script /config/scripts/pinger
            }
        }
    }
    lb-local disable
    lb-local-metric-change disable
}
group WAN1 {
    exclude-local-dns disable
    flush-on-active disable
    gateway-update-interval 20
    interface eth1 {
        route {
            table 10
        }
        route-test {
            initial-delay 180
            interval 60
            type {
                script /config/scripts/pinger
            }
        }
    }
    interface eth2 {
        failover-only
        route {
            table 20
        }
        route-test {
            initial-delay 180
            interval 60
            type {
                script /config/scripts/pinger
            }
        }
    }
    lb-local disable
    lb-local-metric-change disable
}
}

The script is called with three parameters:
#!/bin/bash
targets=(
    '192.168.10.1'
    '192.168.20.1'
    '192.168.30.1' )
if [ $# != 3 ]
then
  echo "Usages: $0 <group> <intf> <status>"
  exit 1
fi

group=$1
intf=$2
status=$3

for host in "${targets[@]}"
do
  /bin/ping -n -c 1 -W 1 -w1 -I $intf $host
  if [ $? == 0 ]
    then
      exit 0
  fi
done

# fail

exit 1

This script uses ping via interface provided by EdgeOS upon the script startup to check availability of three uplink hosts and returns 0 (ok) if at least one of them responds and 1 (failure) when no hosts respond.
You could use the same approach to implement some logic so that when the $intf has a good status according to your checks, return 0 with exit 0, otherwise return 1 with exit 1.
Comment: There's no such thing in EdgeOs in general, as far as I'm aware. Built-in functionality for load balancing is `route-test type ping` with success and failure counters triggering failure and recovery. But you can alter this with `route-test type script` as I described in my answer and implement your own logic in this script.
Comment: So, according to your answer, the "Trigger Level" and "Recovery Time" failover options do not exist in the Edgarouter-5-ports configuration.
Comment: I think you should explain how your script works and why you set those values
Comment: I have included a complete script we use here to monitor dual-wan networks on EdgeOS together with a brief explanation of the logic behind it.


A continued saga of C# interoprability with unmanaged C++

Question: After a day of banging my head against the wall both literally and metaphorically, I plead for help:
I have an unmanaged C++ project, which is compiled as a DLL. Let's call it CPP Project. It currently works in an unmanaged environment. In addition, I have created a WPF project, that shall be called WPF Project. This project is a simple and currently almost empty project. It contains a single window and I want it to use code from Project 1. For that, I have created a CLR C++ project, which shall be called Interop Project and is also compiled as a DLL.
For simplicity I will attach some basic testing code I have boiled down to the basics.
CPP Project has the following two testing files:
tester.h
#pragma once
extern "C" class __declspec(dllexport) NativeTester
{
public:
    void NativeTest();
};

tester.cpp
#include "tester.h"
    void NativeTester::NativeTest()
    {
        int i = 0;
    }

Interop Project has the following file:
InteropLib.h
#pragma once
#include <tester.h>
using namespace System;
namespace InteropLib {
    public ref class InteropProject
    {
    public:
        static void Test()
        {
            NativeTester nativeTester;
            nativeTester.NativeTest();
        }
    };
}

Lastly, WPF Project has a single window refrencing Interop Project:
MainWindow.xaml.cs
using System;
using System.Windows;
using InteropLib;
namespace AppGUI
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            InteropProject.Test();
        }
    }
}

And the XAML itself has an empty window (default created).
Once I am trying to run the WPF project, I get the following error:

System.Windows.Markup.XamlParseException: 'The invocation of the constructor on type 'AppGUI.MainWindow' that matches the specified binding constraints threw an exception.' Line number '3' and line position '9'. ---> System.IO.FileNotFoundException: Could not load file or assembly 'InteropLib.dll' or one of its dependencies. The specified module could not be found.
     at AppGUI.MainWindow..ctor()

Interestingly enough, if I do not export the class from CPP Project, I do not get this error. Say, if i change tester.h to:
#pragma once
class NativeTester
{
public:
    void NativeTest()
    {
        int i = 0;
    }
};

However, in this case I cannot use my more complex classes. If I move my implementation to a cpp file like before, I get unresolved linkage errors due to my not exporting my code. The C++ code I want to actually use is large and has many classes and is object oriented, so I can't just move all my implementation to the h files.
Please help me understand this horrific error I've been trying resolve without success.
Thanks.
Comment: Focusing on the _native_ C++ part, can you use your DLL from native code? I suspect the `__declspec(dllexport)` way of exporting... the more usual way is using preprocessor machinery and macros that expand to `__declspec(dllexport/dllimport)` basing on the context. See [this article](http://www.codeproject.com/Articles/28969/HowTo-Export-C-classes-from-a-DLL) for detailed info.
Comment: Make sure to put the interop DLL and the native DLL in the application path. VS will copy the former but not the latter.
Comment: Alexandre C. I have all of the DLLs and executable in one directory.
user1629821, I will check out the link and see if I'm missing something.
Comment: Fuslogvw (Assembly binding log viewer) may help identify what the problem is if it's complaining that it can't load a dependency.
Answer: This went wrong right from the start, your tester.h file is not correct.  The class should only have the __declspec(dllexport) attribute when you are building the tester project.  Any other project that uses the DLL must see the class with the __declspec(dllimport) attribute.  Start fixing this by using a macro in tester.h:
#undef EXPORTED
#ifdef BUILDING_DLL
#   define EXPORTED __declspec(dllexport)
#else
#   define EXPORTED __declspec(dllimport)
#endif

class EXPORTED NativeTester {
    // etc..
};

And in your tester project, use C/C++, Preprocessor, Preprocessor Definitions and add BUILDING_DLL.
Next thing is to make sure that the DLL is being stored in the right directory.  Which is what the exception is complaining about, it can't find the DLL.  The build directory for C++ projects is Debug but for WPF projects it is bin\Debug.  Fix that by changing the General + Output Directory setting, make it $(SolutionDir)$bin\(ConfigurationName).
Build the C++ project and verify that you can find the DLL back in the Solution's bin\Debug directory.  And check that you also have the .lib file, you'll need that when you build the C++/CLI project.  As an extra verification step, run Dumpbin.exe /exports foo.dll from the Visual Studio Command Prompt and check that you indeed see the class getting exported.
The C++/CLI project next, you need to change the Output Directory setting the same way.  Add the .lib file to the linker's Additional Dependencies properties.  You'll get the kind of linker errors you were talking about if you skip that step.  Build it and verify that you get the DLL in the correct bin\Debug directory again.
Repeat these changes for the Release configuration.
Set the project dependencies, the WPF project depends on the C++/CLI project.  The C++/CLI project depends on the C++ project.  This ensures the projects are getting built in the right order.
You should now have a good shot at using these DLLs in your WPF project.
Comment: I'm going to try this as soon as I can. I will update. Thanks!


Keeping JSP session alive between two applications on two tomcat servers

Question: Hi I want to keep same session between two different application which are running on 2 tomcat servers. I have one application running on one server for which one session is created while logging in . If I click a link on the application, it will be redirected to second application on another tomcat server. At that time, it should maintain the same session which is in the first server. After that if it returns to the application in the first server, it should not ask for authentication again. It should use the same session.
Is there any way to pass the session ID or details between the 2 tomcat servers in JSP.
Can anyone help.
Comment: Are the apps the same but on different servers or unrelated apps?
Answer: I think you might want a SSO (Single Sign-On) solution. So here are these which are available for free and some open source:

Open AM (previously Open SSO)
JOSSO (Java open Single Sign-On)
CAS (Central Authentication Service)

You can also build some custom security in both these web-applications using Servlet filters following the approach as mentioned here.
Note: Go for the custom solution (it would be a pain but a good learning ;-)) only if you don't want to use any of the SSO solutions; I will suggest not to Reinvent-the-wheel due to the reasons given here)
Hope this helps.
Answer: If you are using two tomcat server on the same machine then there is different ports for both the server like one has 8080 and second one 8081.
Now you can simply forward request to second application with setting attribute and remember to give full path of 2nd application jsp in url like,
http://localhost:8081/2nd_application/page.jsp

JSP has 4 scopes: Application, Session, Request, and Page.
The use of the Request scope here is the right from me.
Comment: This answer is difficult to understand- could you clarify what you are suggesting? Your comments about JSP scopes presumably refer to JSP attributes, although I can't see how is relevant to the question.
Answer: just Use  resp.encodeRedirectURL() with resp.sendRedirect().
Like this :
response.sendRedirect(response(encodeRedirectURL("outputpage.jsp"))

Hope provided the right solution.


Nice formula for $\sum\limits_{d|n}(-1)^{n/d}\Phi(d)$?

Question: How do I evaluate
$$\sum_{d|n}(-1)^{n/d}\Phi(d)?$$
$\Phi(d)$ is Euler's totient function. Thanks.
Answer: We are performing Dirichlet convolution on $(-1)^k$ and $\Phi(k)$. The corresponding Dirichlet generating functions of these two sequences are
$$\begin{align*}\frac{\zeta(s-1)}{\zeta(s)}&=\sum_{k=1}^\infty \frac{\Phi(k)}{k^s}\\(2^{1-s}-1)\zeta(s)&=\sum_{k=1}^\infty \frac{(-1)^k}{k^s}\end{align*}$$
where $\zeta(s)$ is Riemann's function.
The product of these two generating functions is the generating function of the convolution; we thus seek the Dirichlet series for $(2^{1-s}-1)\zeta(s-1)$.
We have the Dirichlet $\lambda$ function
$$\lambda(s)=\sum_{k=1}^\infty \frac{1-(-1)^k}{2k^s}=(1-2^{-s})\zeta(s)$$
and we see that our generating function is precisely $-\lambda(s-1)$. Thus, the Dirichlet convolution of $\Phi(k)$ and $(-1)^k$ is
$$-\dfrac{k(1-(-1)^k)}{2}=\begin{cases}-k&\text{odd }k\\0&\text{even }k\end{cases}$$
Comment: Thank you very much, though I have to admit, I do not know Dirichlet convolution a lot.
Comment: Have a look at the wiki article I linked to. You can ask questions here if there's anything you don't understand about them.
Answer: You can use the formula
$$\sum_{d | n} \Phi(d) = \sum_{d | n} \Phi\left(\frac{n}{d}\right)= n$$
And consider
$$\sum_{d | n} \Phi\left(\frac{n}{d}\right) + \sum_{d | n} (-1)^{d} \Phi\left(\frac{n}{d}\right) = \sum_{d | n} (1+(-1)^{d}) \, \Phi\left(\frac{n}{d}\right) = 2 \sum_{2d | n} \Phi\left(\frac{n}{2d}\right)$$
If $n$ is odd, then this is equal to $0$. Otherwise, you get
$$2 \sum_{2d | n} \Phi\left(\frac{n}{2d}\right) = 2 \sum_{d | n/2} \Phi\left(\frac{n/2}{d}\right) = n$$
So your sum is $-n$ if $n$ is odd, and $0$ otherwise. You can sum it up as
$$\sum_{d | n} (-1)^{n/d} \Phi\left(d\right) = \sum_{d | n} (-1)^{d} \Phi\left(\frac{n}{d}\right) = \frac{(-1)^n-1}{2} \cdot n$$


The prior odds were a hundred-to-one against Voldemort surviving. What is the probability of Voldemort being alive?

Question: For educational purpose, I came across a probability problem and I can't make sense of it. Can someone put me in right direction on how I can solve this.
Dumbledore is worried if Voldemort is still alive because he noticed a suspicious mark on a hand.
If Voldemort dies, the mark continuous to exist with a 20% probability.
On the other hand, if Voldemort lives on, the mark will stay with 100% chance.
The prior odds were a hundred-to-one against Voldemort surviving. What is the probability of Voldemort  being alive??
Comment: Bayes' Theorem is the thing to use here.
Comment: What have you tried? Where are you stuck?
Comment: p(A|B), A is the event that voldemort survives and B is the event that mark exits. Is that right ?
Answer: Studies have shown that people deal with proportions better than probabilities. Rewrite the question as

There 3030 fanfics. There are 100 times as many fanfics where Voldemort died as fanfics where Voldermort lived. In 100% of fanfics where Voldemort lived, the mark remained. In 20% of fanfics where Voldemort died, the mark remained. Of all the fanfics where the mark remained, in what percentage did Voldemort survive?"
Comment: You might want to make this a multiple of 5, to make the mental math easier - it's easier to see that 5000/5 = 1000 than 3000/5=600, even if the final numbers you arrive at are the same once you do the fraction cancellations.
Answer: CORRECTION: The old solution i gave is assuming that the prior odds were referring to the conditional probability of knowing the mark exists and you are calculating the overall probability of being alive. However if that is not the case and $p(A) = \frac{1}{101}$ then you can use:
$$p(A|M) = \frac{p(M|A)\times p(A)}{p(M|A)\times p(A) + p(M|D)\times p(D)}
= \frac{\frac{1}{101}}{1\times\frac{1}{101} + \frac{1}{5}\times\frac{100}{101}} = \frac{1}{1+\frac{100}{5}} = \frac{1}{21}$$
Or 20:1 odds.
OLD SOLUTION:
$$A = Alive, D= Dead, M = Mark$$
Currently we know that Voldemort has the mark (because Dumbledore noticed it). Therefore the prior becomes what we know which is the 1:100 odds.
$$p(A|M) = \frac{1}{101}$$
$$p(D|M) = \frac{100}{101}$$
We also learned the probability of the mark given that he is alive or dead:
$$p(M|A) = 1$$
$$p(M|D) = \frac{1}{5}$$
Using Bayes theorem and the fact that $p(D) = 1-p(A)$ we can solve the equation.
$$p(M|A) = \frac{p(A|M)\times p(M)}{p(A)}$$
$$p(M|D) = \frac{p(D|M)\times p(M)}{1-p(A)}$$
Keeping the fractions actually makes the math easier to do by hand. Solving for p(A) using these equations gives (Hopefully i did my math right but im getting):
$$p(a) = \frac{1}{501}$$
Which is 500:1 odds.
Comment: My understanding is that $\frac 1 {101}$ is $p(A)$, not $p(A|M)$.
Comment: Yeah im not exactly sure. Is the prior odds referring to the odds knowing that there is a mark or the odds in general? I assumed that because it was known that the mark exists it was referring to p(A|M). If it is like you said you can use the formula here: http://www.stat.yale.edu/Courses/1997-98/101/condprob.htm#:~:text=The%20conditional%20probability%20of%20an,probability%20of%20B%20given%20A. To calculate p(A|M). Im getting 20:1 odds in that case.
Comment: Fixed, thanks for the clarification @Acccumulation i think you are right.


Array Out Of Bounds exception in java net beans IDE 8.0 while connecting jTable with MySQL database

Question: I have a table with 7 columns and I'm trying to connect my database with it so as to receive data from the database and show it in the table. The code works fine when you press the button the first time but when you press it a second time, the table becomes blank and i get this error:
java.lang.ArrayIndexOutOfBoundsException: 0 >= 0

I have given my code below for the ActionPerformed method of the button.
try
{
    Class.forName("com.mysql.jdbc.Driver");
    Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/db_name","root","admin123");
    String query="SELECT * FROM tablename;";
    Statement st = con.createStatement();
    ResultSet rs= st.executeQuery(query);

    DefaultTableModel tmodel = (DefaultTableModel) jTable1.getModel();

    int rows=tmodel.getRowCount();
    while(rows>0)
    {
        tmodel.removeRow(0);
    }
    jTable1.setModel(tmodel);

while(rs.next())
{

    tmodel.addRow(new Object[] {rs.getInt("column1"),rs.getString("Column2"),rs.getString("Column3"),rs.getInt("Column4"),rs.getString("Column5"),rs.getString("Column6"),rs.getString("Column7")});
    jTable1.setModel(tmodel);
}

}
catch(Exception ex)
{
    System.out.println("Eception: "+ex);
}

Any help would be greatly appreciated.
Answer: Since you never update rows inside the loop, the while will keep going forever or until an Exception is reached...
            while(rows>0)
            {
                tmodel.removeRow(0);
            }

And of course, setRowsCount() will be way simpler and less error prone.
BTW: Helping you would be easier if you pointed which line was the one throwing the exception.
Answer: your problem is with this part although it is a relatively simple fix:
            int rows=tmodel.getRowCount();
            while(rows>0)
            {
                tmodel.removeRow(0);
            }
            jTable1.setModel(tmodel);

what you want to do is:
            while(tmodel.getRowCount()>0)
            {
                tmodel.removeRow(0);
            }
            jTable1.setModel(tmodel);

because you are setting a variable to a constant value returned by the method which means it wont be updated as you continue to delete rows


Rewriting statements into set theory notation

Question: This
$y \in \{\sqrt{x}|x \in Q\}$
turned into this
$∃x \in Q(y = \sqrt{x})$
In the second statement how would I read the stuff in the Q brackets. Q(...).
Also is there a different name for both of these statements notations used or are both of them set theory notation?
Answer: You're misreading the result. The brackets do not belong to the $\mathbb Q$ but to the entire $\exists x\in\mathbb Q$ prefix.
There are many ways to write punctuation for such quantified formulas, and the difference between them generally doesn't encode any meaning other than what the author thinks looks nicest. You can also find people would would write the same result as, for example
$$ (\exists x\in \mathbb Q) \; y=\sqrt x \\
(\exists x\in \mathbb Q)(y=\sqrt x) \\
\exists x\in \mathbb Q : y=\sqrt x \\
\exists x\in \mathbb Q. y=\sqrt x $$
All of these variants pronounced,  "There exists an $x$ in $\mathbb Q$ such that $y=\sqrt x$".
The $\exists$ symbol is called a quantifier -- more precisely, it is the existential quantifier. It is not, in particular, a "set theoretic" notation, but belongs instead to predicate logic.
Comment: got it, thanks doc
Comment: would I be right in saying that in the second statement, in the set Q, y is a free variable and x is bound?
Comment: @ZeeshanHassan: It is right that $y$ is free and $x$ is bound, but saying "in the set $\mathbb Q$" makes no sense in that context.


Is there a way to create static route to a differente subnet on Linux?

Question: From my point of view, there's no way of doing this, but maybe someone can suggest me a workaround.
I have two companies that have a VPN between them, configured on a Mikrotik router. Subnets 192.168.1.0/24 and 192.168.2.0/24 and they are working fine.
I had to create a DHCP server(192.168.2.240) on my N2 company. I kinda have a small different subnet inside the company.
What I need is that when this "different subnet" goes to the internet, they pass through the firewall on my N1 company(192.168.1.10).
I created the routing table on my N2 company, but when I try to put the gateway for this routing table, I have the error:
<code>ip route add table othernet default via 192.168.1.10  metric 100
RTNETLINK answers: Network is unreachable
</code>
That is very natural, since this DHCP server is not on the same subnet, but there is a way of doing something like this?
I know that if I configure a VPN directly between these two hosts(002-DHCP,001-Firewall) I can make this happen, but I would like to do it only with routes configured on these both Linux.
Comment: Possible duplicate of [Setting a default gateway which is on a different subnet](https://serverfault.com/questions/686451/setting-a-default-gateway-which-is-on-a-different-subnet)
Answer: Your question is broken.  You said that you have a router on each end of the VPN connection between the two sites.  The router at site two should be configured to point to the router at site one for its default gateway.  The DHCP server should be configured to point to the router for the gateway also.  If you have the router configured properly, traffic should flow and it should not matter what operating system you have and there should not need to be any static configuration in the computer.  Something isn't right either in your question or your hardware configuration.
Comment: Ok, I probably didn't explain correctly. The routes between then are OK. From my DHCP server(on N2) I can ping and connect firewall and every host from N2. But (I'll use fictional IP for explanation)...in my N1 Company I have IP 188.8.131.52, and in my N2 Company I have the IP 188.8.131.52. I want to have a static route on my DHCP server(N2), so that when I go to the internet, I use the IP 18.104.22.168(N1). In other words,I don't want to connect the firewall, I want to pass through it until the internet. The other hosts on N2 still must go to the internet with 18.104.22.168(N2).
Comment: The system that you want to send their traffic to a host on N1, set that system to have the host on N1 as the gateway address.  It will force any traffic to a non local address to go to that host to be routed.
Comment: I don't know if I understood you right. But you're saying to me set up a host on N1 as a gateway for a host on N2, right? Then, that happens:
COMMAND:     ip route add table othernet default via 192.168.1.10  metric 100
RETURN:     RTNETLINK answers: Network is unreachable