How to interpret these conflicting results on normality of the residuals?

Question: I ran a VAR(1) model and got some results. I then moved to "diagnostic tests". The problem is that these tests seem to be conflicting (at least from the way I read them).
The ARCH test shows no sign of heteroskedasticity:
ARCH (multivariate)

data:  Residuals of VAR object VAR_before
Chi-squared = 505.47, df = 500, p-value = 0.4233

And also no sign of serial correlation:
Portmanteau Test (adjusted)

data:  Residuals of VAR object VAR_before
Chi-squared = 258.76, df = 240, p-value = 0.1934

Yet, a normality test (normality.test in R) doesn't seem to agree:

$JB

    JB-Test (multivariate)

data:  Residuals of VAR object VAR_before
Chi-squared = 27.793, df = 8, p-value = 0.0005152

$Skewness

    Skewness only (multivariate)

data:  Residuals of VAR object VAR_before
Chi-squared = 5.9398, df = 4, p-value = 0.2037

$Kurtosis

    Kurtosis only (multivariate)

data:  Residuals of VAR object VAR_before
Chi-squared = 21.853, df = 4, p-value = 0.0002143

How would you combine these findings?
Answer: Autoregressive conditional heteroskedasticity, serial correlation and lack of normality are all different things (apples and oranges). It is not surprising if some of them are present while others are not.
Regarding the apparent disagreement within the Jarque-Bera test of normality, you see a strong indication of kurtosis that is unlike that of a normal distribution but no strong indication of skewness. Still, it is enough to have one of these moments (skewness, kurtosis) unlike that of a normal distribution to have an indication that the distribution is not normal. And this is indeed what you see: the p-value associated with kurtosis is low and so is the overall p-value, even though the p-value associated with skewness is not low. So there is no paradox.
Comment: @Rollo99, normality is probably the least important assumption for regression models such as VAR. You need it for finite sample confidence intervals and hypothesis tests on coefficients, but under nonnormality you can just use bootstrap for that.
Comment: Thanks for this. I implied that having homoskedasticity and no autocorellation, I had to have iid errors distributed normally. Would you try other specifications if you were me or these results are pretty good and I shouldn't worry too much?


Is there any change in Xcode 12.0 that changes ButtonType from roundedRect to system?

Question: I recently update Xcode from V11.x to V12.0, and had to fix App that just added outlet property to text field but the storyboard got changed buttonType from 'roundedRect' to 'system'. Attached below screen image.
Answer: There are no rounded rect  buttons on iOS. They ended several years ago. A system button was used instead. So now they've stopped using the name too.
Comment: Does that also mean behaviour/UI remains unchanged on App?
Comment: FYI - indeed there was impact on text fields background colour tuned to screen colour by default. I had to recompile on 11.7v to get it right(white). Alternatively I could have change background colour for all the text fields across app to white and compile on 12v.


PHP e JS - Como criar um form com sub selects

Question: O meu plano é criar um formulário onde tenha 2 selects. No select #1 terá nomes transferidos através do MySQL. Ao escolher o nome pretendido do select 1#, automaticamente mostra dados do nome pretendido.
Exemplo
<code>#1 select: joao, ruben
Selecionado: joao

#2 select:
Caso escolha o #1 joao: giro, feio, gordo etc
Caso escolha o #1 ruben: - gordinho, inteligente, lalalal
</code>
Existe alguma forma criada por ai?
Comment: Outra: [Como selecionar uma opção em um  e carregar dados relacionados em outro?](https://pt.stackoverflow.com/q/14646/5878)
Answer: Você pode criar dois selects: o primeiro para o nome da pessoa, o segundo para as características. O segundo começa invisível (display: none(no css) ou .hide()(no function() do jquery))
Quando o val() do primeiro existir, o segundo aparece (.show()). A função que vai dar esse .show(), terá um if para identificar o valor do primeiro select. Dependendo de qual for, o segundo receberá as características corretas adicionadas na forma: $("#primeiroInput").html('blablabla')


python adding variables to imported modules

Question: I wasn't looking what I had previously written on the line so I accidently declared a variable in ipython as:
np.zerosn=10

Surprisingly this was allowed. So I thought that maybe it was because you can name use periods in your variable names, but that is not the case. So I'm wondering what is actually happening. Is this adding a new variable to the numpy module?
Answer: Yes.
In general, (most/many) python objects have dynamic attribute spaces, and you can stick whatever you want onto them whenever you want. And modules are just objects. Their attribute space is essentially the same as their global scope.
Pure python functions are another (perhaps surprising) example of something onto which you can stick arbitrary attributes, though these are not associated with the function's local scope.
Most 'builtin' types (i.e. those which are implemented in extension modules, rather than those that are found in the __builtins__ module) and their instances, do not have dynamic attribute spaces. Neither do pure python types with __slots__.
Comment: FWIW, I posted some examples of (ab)using function attributes [here](http://stackoverflow.com/questions/26096328/list-comprehension-example-with-different-statements/26102444#26102444).


Is a feedback system with an unstable component and the other component being zero internally stable?

Question: So let's consider a system like I described, say looking like such:

Where $K, P_{1}$ and $P_{2}$ are all multivariable transfer function matrices. In this case technically it could be presented as interconnection of two systems, $K$ and $(P_{1}-P_{2})$.
As far as I know, the internal stability then occurs as long as $||K(P_{1}-P_{2})||_{\infty} < 1$ (please correct me if I'm wrong). What happens then if $K$ is unstable but also $P_{1} = P_{2}$ are stable? Is the internal stability criterion fulfilled then?
Answer: Internal stability means that all the closed-loop transfer functions are stable. In the above diagram you have not defined the external inputs (references, disturbances, measurement noise)  and outputs. Typically, in the plant output $P_1-P_2$ there will be some measurement noise $\eta$ that will be added as external input into your system. So you want (among others) the  transfer function from $\eta$ to $u$ (the controller's $K$ output) to be stable i.e.
$$[I+K(P_2-P_1)]^{-1}K$$
to be stable. When $P_1=P_2$ this transfer function is unstable for unstable $K$.


How to Remove Space Additionally to the Special Chars?

Question: in my functions.php if have this code:
echo ''.urldecode($search).'';

this removes the special chars..
but how can i additonally add remove space and replace it with - and remove "
so, if someone types in "yo! here" i want yo-here
Answer: Try:
<?php

$str = '"yo! here"';

$str = preg_replace( array('/[^\s\w]/','/\s/'),array('','-'),$str);

var_dump($str); // prints yo-here

?>

Answer: If you want to replace a run of unwanted characters with a single dash, then you can use something like this:
preg_replace('/\W+/', '-', $search);

To remove surrounding quotes, and then replace any other junk with dashes, try this:
$no_quotes = preg_replace('/^"|"$/', '', $search);
$no_junk = preg_replace('/\W+/', '-', $no_quotes);

Comment: For the OP's input: '"yo! here"' this will produce '-yo-here-'
Answer: This will replace multiple spaces / "special" chars with a single hyphen. If you don't want that, remove the "+".
You might want to trim off any trailing hyphens, should something end with an exclamation point / other.
<?php
preg_replace("/\W+/", "-", "yo! here   check this out");
?>
Answer: You can remove any non-words:
preg_replace('/\W/', '-', $search);


Where Column Y Is Empty Fill In The Value From Column X

Question: I'm new at this so thank you for your help and your patience.
Example: I have a shared spreadsheet with a protected range 'Y:Y' where colleagues update line items. One line item we want to flag when they change it is in column 'X:X'.
My desire is to set up a trigger that runs every 24 hours and it copies the values in column 'X:X' and pastes them into empty or blank values in column 'Y:Y'.
Then a simple DAX formula would compare X to Y. This would simplify a script I'm currently using that runs every time there's an edit.
function OnEdit() {
var s = SpreadsheetApp.getActiveSheet();
if( s.getName() == "PTL" ) { //checks that we're on PTL or not
if( s.getActiveCell().getColumn() == 7 ) { //checks that the cell being edited is in column G
var modify = s.getActiveCell().offset(0, 7);
modify.setValue(new Date());
var baseline = s.getActiveCell().offset(0, 6);
if( baseline.getValue() === '' ) //checks if the adjacent cell is empty or not?
baseline.setValue(new Date());
}
}
}

Answer: Try it this way:
function OnEdit(e) {
  var sh = e.range.getSheet();
  if (sh.getName() == "PTL" && e.range.columnStart == 7) {
    e.range.offset(0,7).setValue(new Date());
    if (e.range.offset(0, 6).getValue() == '')
      e.range.offset(0,6).setValue(new Date());
  }
}

function notsurewhatyouwant() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('PTL');
  const xy = sh.getRange(1, 24, sh.getLastRow(), 2).getValues();
  xy.forEach((r, i) => {
    if (r[1] == null) {
      sh.getRange(i+1,25).setValue(r[0]);
    }
  });
}

function createTrigger() {
  if(ScriptApp.getProjectTriggers().filter(t => t.getHandlerFunction() == "notsurewhatyouwant").length == 0) {
    ScriptApp.newTrigger('notsurewhatyouwant').timeBased().everyDays(1).atHour(0).create();
  }
}

Comment: I don't understand your last comment. Perhaps you can make the example clearer by posting in your question. But yes providing examples of input and desired out would be helpful.


pip install pywin32 fails on mac machine

Question: How can i download pip install pywin32 on mac machine. my requirement to convert pdf to docs file using below code
<code>import glob
import win32com.client
import os

word = win32com.client.Dispatch("Word.Application")
word.visible = 0

pdfs_path = "C:\\Users\\bthakur4\\Downloads\\pdf\\"
for i, doc in enumerate(glob.iglob(pdfs_path +"inputfiles\\" +"*[A-Za-z0-9 _].pdf")):
    #print(doc)
    filename = doc.split('\\')[-1]
    in_file = os.path.abspath(doc)
    print("\n")
    print("converting file: ",in_file)
    wb = word.Documents.Open(in_file)
    out_file = os.path.abspath(pdfs_path + "outputfiles\\" +filename[0:-4]+ ".docx".format(i))
    wb.SaveAs2(out_file, FileFormat=16)
    print("success...")
    print("output file: ",out_file)
    wb.Close()

word.Quit()
</code>
. or any other way to do so ???
Answer: You simply can't. pywin32 is a Windows Python wrapper for windows API calls
Comment: right, thanks , any help please for permission denied error on installing
Comment: Try to use "sudo" ?


fabric traceback: ImportError: cannot import name cd

Question: Hello I am trying to learn fabric thought it may be useful and so I was following along the test script I should say or test fab command in the book "The Hitchhiker's Guide to Python!" might be a little out of date since it asked me to do 'from fabric.api" but I fixed that problem now I am getting a import error which I dont understand why could be something with new version of fabric perhaps but the error is a trace back
<code>Traceback (most recent call last):
  File "main.py", line 2, in <module>
    from fabric import cd,env,prefix,run,task
ImportError: cannot import name 'cd'
</code>
here is the code, cut and pasted from notepad++
also you will see the r by  with cd(r'blah blah b;ah')
that was because I was getting a unicode error and a google search said that was the fix
in any case I hope you can help ,me or direct me to somewhere that can
<code>#import fabric
from fabric.api import cd,env,prefix,run,task

#where you are running the data on
env.host = [' 192.168.6.29']

#first fab task will be checking all free memory in linux
@task
def memory_usage():
    run('Get-WmiObject Win32_OperatingSystem | fl *')

#second task will deploy this making it a fab file
@task
def deploy():
    with cd(r'C:\Users\JayBhatt'):
        with prefix('.../bin/activate'):
            run('git pull')
            run('touch app-wsgi')
</code>
Comment: Probably a `bytes` object would be better: either `.encode('utf-8')` or `b'some_string'`.
Comment: I will consider that going forward I was just following the example in the book to get a feel of fabric
Answer: from fabric import * fixed this issue


Volume of Rectangular solid from surface area

Question: I have a cuboid whose surface area is:
$S=73.16 cm^2$.
Also, I have the separate surface areas for the specific sides of the cuboid:

$ab=8.41 cm^2$
$ac=12.96 cm^2$
$bc=15.21 cm^2$

How can one calculate the Volume of this cuboid?
Comment: The volume is $abc$. What is the product of the $3$ separate surface areas?
Answer: If you divide the first two you can solve the result for $b$, then plug into the last, giving you $c$ and you are on your way.  You have three equations in three unknowns.
Comment: I don't understand the 'If you divide first two' part
Comment: I was suggesting dividing the first two equations.  That eliminates $a$ from the result and leaves you with two equations in the unknowns $b,c$.
Comment: $b = \sqrt{{ab \over ac}\,bc}$.
Comment: There is a much, much shorter way to find the volume. See my comment above.
Comment: @Jean-ClaudeArbaut:  good point.  I didn't think of it.


Remover parte String JavaScript Informando o Fim

Question: Tenho a seguinte função javascript:
var opts = document.getElementById('id_endereco'); //localiza select
var str = opts.options[opts.selectedIndex].innerText; //Pega text do option

Preciso remover parte do conteúdo do select, 'str', este valor é variavel, mas, possuo uma palavra fixa em todos os options, a palavra á 'Endereço: '. Preciso remover esta palavra incluindo tudo o que vem antes dela.
Tentei:
var resultado_str = str.replace(0, str.indexOf("Endereço: ") + 1, "");
document.getElementById('endereco_correto').value = resultado_str;

Mas, não funcionou.
Answer: Fiz uma combinação de substring com o indexOf, eu pego qual o índice que começa o "Endereço: " e somo a esse índice a quantidade de caracteres que esse texto possui, no caso 10.
var str = "texto antes Endereço: Da minha casa";
var textoReplace = "Endereço: ";
var resultado_str = str.substring(str.indexOf(textoReplace) + textoReplace.length); // essa soma da 22

"Da minha casa"

O seu problema em usar indexOf é que ele vai retornar a primeira posição do texto informado e não o último conforme você está esperando.
Seu código final será:
var textoReplace = "Endereço: ";
var opts = document.getElementById('id_endereco'); //localiza select
var str = opts.options[opts.selectedIndex].innerText; //Pega text do option

var resultado_str = str.substring(str.indexOf(textoReplace) + textoReplace.length);
document.getElementById('endereco_correto').value = resultado_str;

Comment: A questão é que preciso limpar as palavras que vem antes do 'Endereço: ', e manter o restante.
Comment: @sNniffer Entendi seu problema, atualizei a resposta com a nova solução.
Comment: Show de bola, funcionou muito bem, obrigado


Problems with parsing xml with namespaces

Question: I need to parse xml file and retrieve some information. But
Simple_XML_string function returning not all content of xml.
Here the following xml.
    <entry xmlns="http://www.w3.org/2005/Atom" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xml:base="URL">
    <id>
   URL(UserId='',UserType='')
    </id>
    <title type="text">RecommendationScenarios(UserId='',UserType='')</title>
    <updated>2017-02-10T05:08:15Z</updated>
    <category term="PROD_RECO_RUNTIME_SRV.RecommendationScenario" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"/>
    <link href="RecommendationScenarios(UserId='',UserType='')" rel="self" title="RecommendationScenario"/>
    <link href="RecommendationScenarios(UserId='',UserType='')/Scenarios" rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/Scenarios" type="application/atom+xml;type=feed" title="Scenarios">
    <m:inline/>
    </link>
    <link href="RecommendationScenarios(UserId='',UserType='')/ContextParams" rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/ContextParams" type="application/atom+xml;type=feed" title="ContextParams">
    <m:inline/>
    </link>
    <link href="RecommendationScenarios(UserId='',UserType='')/ResultObjects" rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/ResultObjects" type="application/atom+xml;type=feed" title="ResultObjects">
    <m:inline>
    <feed xml:base="URL">
    <id>
    URL(UserId='',UserType='')/ResultObjects
    </id>
    <title type="text">ResultObject</title>
    <updated>2017-02-10T05:08:15Z</updated>
    <author>
    <name/>
    </author>
    <link href="RecommendationScenarios(UserId='',UserType='')/ResultObjects" rel="self" title="ResultObject"/>
    <entry>
    <id>
    URL(ScenarioId='SAP_TOP_SELLER_HOME_PAGE',ResultObjectType='SAP_HYBRIS_PRODUCT',ResultObjectId='37511')
    </id>
    <title type="text">
    ResultObject(ScenarioId='SAP_TOP_SELLER_HOME_PAGE',ResultObjectType='SAP_HYBRIS_PRODUCT',ResultObjectId='37511')
    </title>
    <updated>2017-02-10T05:08:15Z</updated>
    <category term="PROD_RECO_RUNTIME_SRV.ResultObject" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"/>
    <link href="ResultObject(ScenarioId='SAP_TOP_SELLER_HOME_PAGE',ResultObjectType='SAP_HYBRIS_PRODUCT',ResultObjectId='37511')" rel="self" title="ResultObject"/>
    <content type="application/xml">
    <m:properties>
    <d:ScenarioId>SAP_TOP_SELLER_HOME_PAGE</d:ScenarioId>
    <d:ResultObjectType>SAP_HYBRIS_PRODUCT</d:ResultObjectType>
    <d:ResultObjectId>37511</d:ResultObjectId>
    <d:ResultObjectScore>1.00000</d:ResultObjectScore>
    </m:properties>
    </content>
    </entry>

    </feed>
    </m:inline>
    </link>
    <content type="application/xml">
    <m:properties>
    <d:UserId/>
    <d:UserType/>
    </m:properties>
    </content>
    </entry>

I need to get information from content type=application and i need to retrieve
<m:properties>
<d:ScenarioId>SAP_TOP_SELLER_HOME_PAGE</d:ScenarioId>
<d:ResultObjectType>SAP_HYBRIS_PRODUCT</d:ResultObjectType>
<d:ResultObjectId>4934</d:ResultObjectId>
<d:ResultObjectScore>0.49999</d:ResultObjectScore>
</m:properties>

I'm trying to parse using php (simple_xml_string function).
Any ideas?
Answer: I've solved my problem using xpath and namespaceRegister.
$xml = new SimpleXMLElement($content);
  $xml->registerXPathNamespace('m', 'http://schemas.microsoft.com/ado/2007/08/dataservices/metadata');

  $products = [];
  foreach($xml->xpath('//m:properties') as $key=>$event) {
      $products[] = strval($event->xpath('d:ResultObjectId')[0]);
  };


Commerce Kickstart 2 Display color as visual colour

Question: In the 'Tops' Content type/Product Variation, the color selection in the 'catalog' shows up as multiple color blocks below the 'From $00.00' price information.
I've made up a new Content type and Product Variation, also with color. How do I get all the available product variation colors to show up as blocks of color below the price instead of just a single link to the first variations colour?
Answer: Go to Store setting -> Product settings -> Variation types -> your content type -> manage fields -> edit color(term reference)
enable the settings under "ATTRIBUTE FIELD SETTINGS"
Comment: The "Rendered term" option isn't available on mine. I installed CK2 without the sample store and data. I had to add the color taxonomy. In my new Product Variation field of color, how do I get this option to show?
Comment: I figured it out. No, your method is actually not the way to do this. You go into the Content Type and in the "Manage Display" -> "Product List" mode, you add a Field Extractor to get the color field and use view mode of 'Add to cart form' for view mode
Answer: You go into the Content Type and in the "Manage Display" -> "Product List" mode, you add a Field Extractor to get the color field and use view mode of 'Add to cart form' for view mode
Answer: Navigate: Content > Content types
Click Link: (your type) > Manage display
Select Button: Manage display > Product list
If it's not there, be sure to add it to the visible area:
Product variations
Select: < Hidden >
Select: Field Extractor
Click Button: Settings
Enter the following:
Field: field_color
Formatter: Rendered entity
View mode: Add to Cart form - Attribute
Click Button: Update
Click Button: Save


What is an illustrative example of a Finsler manifold?

Question: I've attempted to get a bead on Finsler manifolds before attending an upcoming seminar that involves them. I've done some reading in the literature and think I understand that they are similar to Riemannian manifolds, but that the metric tensor need not be a quadratic differential and need not be isotropic. Also, the "sphere" of unit tangent vectors at a point in a Finsler manifold need not be symmetric although it does have to be convex.
I'd love to hear a nice, illustrative, concrete example of a Finsler manifold, especially if it could involve a picture and an explanation of why it's interesting to you.
Thanks!
Answer: This is more about Finsler norms/metrics but hopefully it is still interesting.
An interesting one appears in the medical imaging literature, specifically for streamline tracking in the brain using diffusion imaging.
Essentially, the goal is to discern the paths of the neural tracts in the brain. One is given a (noisy) tensor field describing the local diffusion properties at each point in the tissue.
A Finsler norm is defined based on a high order diffusion tensor $D$:
$$
F(x,y) = \sqrt[n]{D_{i_1,\ldots,i_n}(x) y^{i_1} \ldots y^{i_n} }
$$
Then the Finsler metric tensor is related to its Hessian:
$$
g_{ij}(x,y) = \frac{1}{2}\frac{\partial F^2(x,y)}{\partial y^i \partial y^j}
$$
The fact that the norm can depend on both orientation and spatial position is important here because streamlines can cross in the brain, making the use of a Riemannian metric alone unable to capture all the relevant information.
See Finsler Streamline Tracking with Single Tensor Orientation Distribution Function for High Angular Resolution Diffusion Imaging and
Finsler Geometry on Higher Order Tensor Fields and Applications to High Angular Resolution Diffusion Imaging by Astola et al.


Can I prevent RestKit+CoreData from overriding local entity changes?

Question: I've configured a RKObjectMappingProvider subclass with a series of object mappings that map a variety of service endpoints to my local Core Data entities & persistent store. Let's say I have a service endpoint /api/workorders and I use loadObjectsAtResourcePath:usingBlock: to fetch a list of X workorders and persist to Core Data. Next, the user modifies 2 of those entities using the app but doesn't push the changes back to the service.
If the user again calls /api/workorders to fetch the latest workorders, is there a way to not have RestKit automatically override the local modifications to the changed entities?
Answer: The short answer is no, you have to do it yourself and it gets nasty quickly.
You would need to override the setter of a custom managed object class.
This kind of thing.
You would need a property to know it has been updated. You will need to create it and set it when the entity gets updated. I would do this at the row level,
and then check the property and only update if the flag is not set.
Of course you then need to handle the case if the user wants to update the value again :)
Restkit is wonderful, but does not handle full syncing for you.
Comment: Ah I was afraid of this. I'm thinking a potential solution would be to add a isModifiedAttribute property similar to primaryKeyAttribute and work with that.


Group array php and count

Question: <code>$data = [
     [
       id: '1',
       date_created: '2021-11-14T23:22:53.558225+00:00',
     ],
     [
       id: '2',
       date_created: '2021-11-14T23:22:00.558225+00:00',
     ],
     [
       id: '3',
       date_created: '2021-11-15T11:22:53.558225+00:00',
     ],
]
</code>
Help to get a new array, you need to group by date and count the number of resulting arrays starting from the first day.Here is an example of a new array
<code>$new_array = [0,0,0,0,0,0,0,0,0,0,0,0,0,2,1]
</code>
Comment: what you have tried for that? Please share your code.
Comment: unfortunately, I don't even have any thoughts, I tried using group_by
Comment: Can you explain what you want from the data?
Comment: I need to get an array like in the example $new_array
Answer: I suppose it can be done with a loop
<code><?php
$data = [
     [
       'id' => '1',
       'date_created' => '2021-11-14T23:22:53.558225+00:00',
     ],
     [
       'id' => '2',
       'date_created' => '2021-11-14T23:22:00.558225+00:00',
     ],
     [
       'id' => '3',
       'date_created' => '2021-11-15T11:22:53.558225+00:00',
     ],
];

$res = array();
foreach($data as $row) {
    if(!isset($res[gmdate('d', strtotime($row['date_created']))]))
        $res[gmdate('d', strtotime($row['date_created']))] = 0;
    // array index, (current date of month) gmdate('d', strtotime($row['date_created']))
    $res[gmdate('d', strtotime($row['date_created']))]++;
}
print_r($res);
</code>

Group array php and count


Criar o código para preencher o vetor - Javascript/Lógica

Question: estou com um problema em um exercício sobre arrays. A questão é a seguinte:
Criar o código para preencher o array com os seguintes valores:
  3 4 7 12 19 28 39 52 67 84
Já fiz os outros exercícicios dessa lista, meu problema com esse é na lógica. Não estou conseguindo pensar em como incrementar o contador de forma que ele adicione o próximo número ímpar. Até tentei elaborar da seguinte forma:
if((i+1)%2==0)
{
     numero = numero+i;
     contador= i;
}
else {
     numero= numero+2;
     contador =  i;
}

Mas não rodou. Any help???
Comment: Acho que falta explicar melhor o que deseja e colocar o código completo. Por exemplo, qual seria o valor inicial de `i`? Onde está o array? Vc quer inserir apenas ímpares no array?
Comment: Sam, não tem código, tirei de uma lista de exercícios. Tenho que criar um código que crie o array lista= [3, 4, 7, 12, 19, 28, 39, 52, 67, 84], usando laços.  No caso entendi que o contador é incrementado em 1 no começo e vai sendo incrementado com o próximo número ímpar (1, depois 3, depois 5, ...), mas não consigo fazer isso rodar...
Comment: Certo, mas qual o valor máximo a ser adicionado?
Comment: O último incremento é no valor de 17, entre os elementos 67 e 84!
Answer: Resolução:

let n = 3;
let i = 1;
let a = [];

while(n <= 84){
    a.push(n);
    n += i;
    i += 2;
}

console.log(a);
Comment: Demais!!! Obrigada!


Mysql function error - unable to figure it out

Question: Please help me with Mysql Function. Code:
DELIMITER $$

CREATE FUNCTION `media`.`Return_Next_Season`(
        season VARCHAR(200) )
    RETURNS VARCHAR
    DECLARE _ids INT ;
    DECLARE _bsk VARCHAR(200);

SELECT id INTO _ids  FROM media._broadcast_seasons WHERE broadcast_season_key = '20132014_Fall';

SELECT broadcast_season_key INTO bsk FROM media._broadcast_seasons WHERE id  = ids;

    RETURN bsk;
    BEGIN

    END$$

DELIMITER ;

Comment: what is the error stack?
Comment: Can you show your table(s) schema? Your two selects don't make any sense. And you don't use `season` parameter.
Answer: Do you think it's a good idea having that BEGIN after all the code that does something useful? :-) Or, in less obtuse language, move the BEGIN to just after the RETURNS VARCHAR, something like (select statements broken up for readability but you may have to recombine them):
DELIMITER $$
CREATE FUNCTION `media`.`Return_Next_Season`(
    season VARCHAR(200) )
    RETURNS VARCHAR(200)
    BEGIN
        DECLARE _ids INT ;
        DECLARE _bsk VARCHAR(200);
        SELECT id INTO _ids  FROM media._broadcast_seasons
            WHERE broadcast_season_key = '20132014_Fall';
        SELECT broadcast_season_key INTO bsk FROM media._broadcast_seasons
            WHERE id  = ids;
        RETURN bsk;
    END$$
DELIMITER ;

You'll notice I've also changed the return type to give it a size since I believe that's necessary as well.
Comment: tried this.. doesnt work..

Error Code : 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'BEGIN DECLARE _ids INT ; DECLARE _bsk VARCHAR(200); SELE' at line 4

share|edit|delete|flag
Comment: @user3128161, I think that's to do with the return type missing an upper size length. Try it with the updated code, `returns varchar(200)`.


Forward real requestor IP in K3S NGINX ingress

Question: I've set up a K3S Kubernetes Environment in my private Home-Lab on Raspberry PIs in order to teach myself some Kubernetes (Noob-Alert), using NGINX as Ingress Controller and I'm kind of stuck at passing the real IP of requests to the target Pods, in my case a Nextcloud instance. The Version of K3S is v1.22.5+k3s1.
The K3S was set up using Docker as container runtime and with the --no-deploy traefik option.
After that I deployed the NGINX Ingress Controller using
kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.1.0/deploy/static/provider/baremetal/deploy.yaml

Then, after deploying the Nextcloud pods, I deployed the Ingress:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: nginx-ingress
  annotations:
    nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
spec:
  tls:
  - hosts:
    - my.own-dns.org
    secretName: very-secret-ssl-secret
  ingressClassName: nginx
  rules:
  - host: my.own-dns.org
    http:
      paths:
        - path: /somepath
          pathType: Prefix
          backend:
            service:
              name: someservice-service
              port:
                number: 8081
        - path: /
          pathType: Prefix
          backend:
            service:
              name: nextcloud-service
              port:
                number: 80

In the deployment of the IngressController, I added the following entries in the ConfigMap:
apiVersion: v1
kind: ConfigMap
metadata:
  labels:
    helm.sh/chart: ingress-nginx-4.0.10
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/version: 1.1.0
    app.kubernetes.io/managed-by: Helm
    app.kubernetes.io/component: controller
  name: ingress-nginx-controller
  namespace: ingress-nginx
data:
  allow-snippet-annotations: 'true'
  compute-full-forwarded-for: 'true'
  use-forwarded-headers: 'true'
  enable-real-ip: 'true'
  proxy-add-original-uri-header: 'true'
  forwarded-for-header: 'X-Forwarded-For'

and changed the ServiceType from the http service to LoadBalancer, so my Service of the IngressController looks like this:
apiVersion: v1
kind: Service
metadata:
  annotations:
  labels:
    helm.sh/chart: ingress-nginx-4.0.10
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/version: 1.1.0
    app.kubernetes.io/managed-by: Helm
    app.kubernetes.io/component: controller
  name: ingress-nginx-controller
  namespace: ingress-nginx
spec:
  type: LoadBalancer
  ipFamilyPolicy: SingleStack
  ipFamilies:
    - IPv4
  ports:
    - name: http
      port: 80
      protocol: TCP
      targetPort: http
      appProtocol: http
    - name: https
      port: 443
      protocol: TCP
      targetPort: https
      appProtocol: https
  selector:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/component: controller

So far so good, accessing the Nextcloud Instance from the Internet working great, including redirection to https, etc. But the Nextcloud Audit Log is only getting an internal Cluster IP as Source IP (surprisingly no IP from any Service I am running inside the Cluster), not the real from the outer world.
So what am I missing? I tried setting use-proxy-protocol to true, but this results in a ERR_CONNECTION_RESET.
Answer: Have you tried setting the spec.externalTrafficPolicy to local? Have a look at kubernetes documentatio  about the implications.


WPF. How to stop data trigger animation through binding?

Question: In WPF toolkit datagrid I have a data trigger bound to opacity of cell element.
When UpVisibility changes to 1 the path become visible and the animation starts to fade it to 0. Which works.
However my problem now - if I need to prematurely stop/cancel the fading and am setting UpVisibility to 0 the Path is still visible and fading as nothing happened....
How to drop opacity to 0 instantly using MyValue object ?
<Path Data="M 5,0 0,10 10,10" Height="10" Width="10" Fill="Green" Opacity="{Binding MyValue[0].UpVisibility}" Margin="5,0,5,0">
    <Path.Style>

        </Style>
    </Path.Style>
</Path>

Answer: Storyboards can also be stopped using the ExitAction on a DataTrigger, which is called when the bound value changes out of the target state. Just give your BeginStoryboard a name, and reference it in a StopStoryboard action, like so:
<DataTrigger.EnterActions>
    <BeginStoryboard Name="your_storyboard_name">
        ...
    </BeginStoryboard>
</DataTrigger.EnterActions>

<DataTrigger.ExitActions>
    <StopStoryboard BeginStoryboardName="your_storyboard_name" />
</DataTrigger.ExitActions>

This may be more appropriate than starting a second storyboard to stop or mask a different storyboard.
Comment: This is what I was looking for because my storyboard is running forever so I needed to stop it. Thanks !
Answer: Have you tried something like this (untested example):
<Path Data="M 5,0 0,10 10,10" Height="10" Width="10" Fill="Green" Opacity="{Binding MyValue[0].UpVisibility}" Margin="5,0,5,0">
    <Path.Style>

        </Style>
    </Path.Style>
</Path>

I set the animation duration to 0 to be instant. And if you don't define the From property you are instructing WPF to start in the current DependencyProperty value, so it will transition smoothly.
Answer: If you need to reset animation in code behind you usually do such call:
 MyControl.BeginAnimation(OpacityProperty, null);

But how to do it in XAML according to MVVM? Answer is:

</Style>

To call animation in ViewModel we can do:
Vanishing = true;
await Task.Delay(500);
Vanishing = false;

Also make sure that binding property (Vanishing in my case) calls INotifyPropertyChanged to notify view about new value


Link url paths change from within the 'user' area

Question: I have made a block for a footer which contains 2 simple links. The html code is as follows:

PRIVACY-POLICY   TERMS & CONDITIONS

The links work fine as long as i click on them while being anywhere on the website BESIDES the user profile. BUT, as soon as i try to click the links while in my user profile, instead of the URL pointing to "/privacy" or "/terms", the system appends a "/user/" path before the link. So the link becomes as follows: "/user/privacy" and "/user/terms". If i try to access it i get a Access denied.
I cannot for the life of me! figure out why this is happening.....
What am i missing?
Drupal 7
Thanks for your help!!
Answer: Modify your href from

and

to

and

Notice the slash. That means the path is relative to your base url instead of being relative to your current path.
Answer: Use href value like this
<a href="<?php echo url('terms');?>">TERMS & CONDITIONS

It will work everywhere.


$\lim\limits_{m\to 0}\dfrac{{}_1F_2\left(-\frac 12;\frac 12,\frac m2;x\right)}{\Gamma(m)}$

Question: What is the limit for following expression
$$f(x)=\lim_{m\to 0}\frac{{}_1F_2\left(-\dfrac 12;\dfrac 12,\dfrac m2;x\right)}{\Gamma(m)}\quad \text{with}\quad x\in\mathbb{R},$$
where ${}_1F_2$ is the hypergeometric series and $\Gamma$ the gamma function? Single values are
$$f(-1) \approx 1.69809, \qquad f(0)=0, \qquad f(1) \approx-2.36873$$
Comment: So it is ${}_1 F_2$ and not ${}_2 F_1$? Also, hypergeometric functions are usually not defined on the whole real line.
Comment: it is ${}_1F_2$
Answer: First we write out the function with the Pochhammer symbol:
$$\lim_{m\to0}\frac{\,_1\text F_2\left(-\frac12;\frac12,\frac m2,x\right)}{\Gamma(m)}=\lim_{m\to0}\sum_{n=0}^\infty \frac{\left(-\frac12\right)_nx^n}{\left(\frac12\right)_n\left(\frac m2\right)_n\Gamma(m)n!}$$
A limit gives:
$$f(x)=\lim_{m\to0}\sum_{n=0}^\infty \frac{\left(-\frac12\right)_nx^n}{\left(\frac12\right)_n\left(\frac m2\right)_n\Gamma(m)n!}=\sum_{n=0}^\infty\frac{2\left(-\frac12\right)_nx^n}{n!\Gamma(n)\left(\frac12\right)_n}=-2x\,_1\text F_2\left(\frac12;\frac32,2;x\right) $$
It is a combination of Struve L and Bessel I functions:
$$\lim_{m\to0}\frac{\,_1\text F_2\left(-\frac12;\frac12,\frac m2,x\right)}{\Gamma(m)}=2\text I_1\left(2\sqrt x\right)\left(\pi x\text L_0\left(2\sqrt x\right)+\sqrt x\right)-2x\text I_0 \left(2\sqrt x\right) \left(\pi \text L_1 \left(2\sqrt x\right)+2\right)$$
When evaluating, Bessel J and Struve H appear because of the imaginary unit. Single values include
$$f(-1)=2\text J_1(2)(\pi\text H_0(2)-1)-2\text J_0(2)(\pi \text H_1(2)-2)= 1.69809097088030636354471441251561 \\f(1)=2\text I_1(2)(\pi\text L_0(2)+1)-2\text I_0(2)(\pi\text L_1(2)+2)= -2.36873010158184893306470337240… $$
Comment: Do you get the same values regardless of what phase of $-1$ you are using?
Comment: @Gary You look interested in this math problem. If you mean using $\sqrt{-1}\to -i$, then [yes](https://www.wolframalpha.com/input?i=2+BesselI%5B1%2C+-2+Sqrt%5Bx%5D%5D+%28-Sqrt%5Bx%5D+%2B+x+Pi+StruveL%5B0%2C+-2+Sqrt%5Bx%5D%5D%29+-+2+BesselI%5B0%2C+-2+Sqrt%5Bx%5D%5D+%282+x+%2B+x+Pi+StruveL%5B1%2C+-2+Sqrt%5Bx%5D%5D%29%2Cx%3D-1).


How can I create more buttons of the same appearance (C#)

Question: Please, can you help me how can I create more buttons of the same appearance. I have graphics structure for buttons in a separate class. A function for creating buttons I have in windows form.
Step 1)
Class for graphic button structure:
class GraphicClassStructure : GraphicPosition
{
    public Button resetTree = new Button();

    public void CreateClassButtons()
    {
        // Reset tree
        resetTree.BackColor = Color.Transparent;
        resetTree.BackgroundImage = BuildResource.reset;
        resetTree.BackgroundImageLayout = ImageLayout.Stretch;
        resetTree.FlatAppearance.BorderSize = 0;
        resetTree.FlatAppearance.MouseDownBackColor = Color.Transparent;
        resetTree.FlatAppearance.MouseOverBackColor = Color.Transparent;
        resetTree.FlatStyle = FlatStyle.Flat;
        resetTree.Name = "resetTree";
        resetTree.Size = Size[0][5];
        resetTree.UseVisualStyleBackColor = false;
    }
}

Win forms function for control buttons.
private void classMenu_Click(object sender, EventArgs e)
{
    classStructure.ClassAllButtonsVisible();
    classStructure.CreateClassButtons();
    this.Controls.Add(classStructure.classBackround);

    for (int i = 0; i < 3; i++)
    {
        switch (i)
        {
            case 0:
                classStructure.resetTree.Location = classStructure.Location[0][2];
                break;
            case 1:
                classStructure.resetTree.Location = classStructure.Location[0][3];
                break;
            case 2:
                classStructure.resetTree.Location = classStructure.Location[0][4];
                break;
        }
        classStructure.resetTree.Click += new EventHandler(resetTreeOneEvent_Click);
        classStructure.resetTree.MouseEnter += new EventHandler(resetTree_MouseEnter);
        classStructure.resetTree.MouseLeave += new EventHandler(resetTree_MouseLeave);
        classStructure.resetTree.Tag = i;
        this.Controls.Add(classStructure.resetTree);
    }
}

The current problem is that the creation of the buttons is in the class "GraphicStructure" but in class it creates only one button. Although I can embed into windows form to the function, but I'd like to have graphic buttons and functions separately. Can you help me please?.
Control:
private void resetTreeOneEvent_Click(object sender, EventArgs e)
{
    Button button = sender as Button;
    if (button != null)
    {
        switch ((int)button.Tag)
        {
            case 0:
                // First Button Clicked
                break;
            case 1:
                // Second Button Clicked
                break;
            case 2:
                // Third Button Clicked
                break;
        }
    }
}

Or second idea. I have created a button that does nothing, but has a graphical Structure. Then create three additional buttons that are already doing something, but again have no graphics and just need to get those buttons to do something cloned from graphic button that does nothing.
I try use this but i still saw only one button:
private void classMenu_Click(object sender, EventArgs e)
{
    classStructure.ClassAllButtonsVisible();
    classStructure.CreateClassButtons();
    this.Controls.Add(classStructure.classBackround);

    for (int i = 0; i < 3; i++)
    {
        Button button = new Button();
        button = classStructure.resetTree;
        switch (i)
        {
            case 0:
                button.Location = classStructure.Location[0][2];
                break;
            case 1:
                button.Location = classStructure.Location[0][3];
                break;
            case 2:
                button.Location = classStructure.Location[0][4];
                break;
        }
        button.Click += new EventHandler(resetTreeOneEvent_Click);
        button.MouseEnter += new EventHandler(resetTree_MouseEnter);
        button.MouseLeave += new EventHandler(resetTree_MouseLeave);
        button.Tag = i;
        this.Controls.Add(button);
    }
}

Second idea work (i saw three buttons) if i commented this:
button = classStructure.resetTree;

But if i commented this part code so all three button is again without graphic structure.
Answer: If you need buttons with same appearance, then create your custom button inherited from Button and use it instead of standard Button:
public class TreeButton : Button
{
    public TreeButton()
    {
        BackColor = Color.Transparent;
        BackgroundImage = /* set some image  */
        BackgroundImageLayout = ImageLayout.Stretch;
        FlatAppearance.BorderSize = 0;
        FlatAppearance.MouseDownBackColor = Color.Transparent;
        FlatAppearance.MouseOverBackColor = Color.Transparent;
        FlatStyle = FlatStyle.Flat;
        Size = /* set size */
        UseVisualStyleBackColor = false;
    }
}

If you want buttons to behave differently, then assign different click event handlers to different buttons.
Comment: Your solution is correct, but I need a little different solutions. I have created a button that does nothing, but has a graphical Structure. Then create three additional buttons that are already doing something, but again have no graphics and just need to get those buttons to do something cloned from graphic button that does nothing.
Comment: @RadekTarant sorry, didn't get you. Buttons usually don't have logic - they just raise events which invoke handlers


Is there a hook that could manipulate the list of field items before the field is built?

Question: I am currently porting a custom field module from Drupal 7 to 8. The field (Topic Access) has 3 select fields, typically about 10 to 20 items per field, and uses a custom widget. When the form is loaded, I typically insert several "inherited" items to the field before displaying it. When saving, only the items that vary from the inherited ones are actually saved to the database.
In Drupal 7, I used hook_field_load() to add these "inherited" items to the form. As explained on Dynamic/Virtual field values using computed field property classes, that hook has been removed from Drupal 8 in favor of computed field properties.
I can't see an elegant way to manipulate the list of items. I could use hook_form_alter() on the forms that contain the field to update $form['field_topic_access']['widget']. However, it would end up duplicating code from the widget and have to specifically pick out the fields by name.
Is there a hook that could manipulate the list of field items before the field is built?
Comment: In Drupal 8, the hooks to alter entity fields are only to alter fields implemented by other modules. The module implementing an entity field should not use them.
Comment: Thanks for the reply kiamlaluno. So in short, if not using hooks then, how do I programmatically modify the list of items in a form field?

The instances of the field belong to a "tree shaped" taxonomy. The list of items in an instance of my custom field are programmatically generated from not just the field items explicitly stored in the DB against that term, but also "inherited" field items from "ancestor" terms. So, if a parent field item is changed then the "default" for that field item automatically filters thru to descendants unless the descendant has overwritten the the defaults.
Comment: I was referring to the hooks for altering fields, for example [`hook_field_widget_form_alter()`](https://api.drupal.org/api/drupal/core%21modules%21field%21field.api.php/function/hook_field_widget_form_alter/8.9.x). From where are the inherited values taken from?
Answer: What about hook_entity_prepare_form()? This simple example loaded an extra item into the form.
function mymodule_entity_prepare_form($entity, $operation, $form_state){
  if ($entity->bundle() == 'domain_groups') {
    $items = $entity->get('field_topic_access')->getValue();
    //just a hardcoded item for test purposes
    $demo_item=['topic_tid'=>'74','available_to_group'=>'1', 'publish_to_group'=>'0'];
    $items[] = $demo_item;
    $entity->set('field_topic_access', $items);
  }
}

There may be a more elegant solution but I could use this hook to show my inherited items and hook_entity_presave()  to remove inherited values before saving.


Is there an app/script I can deploy to enable my users to change their own LDAP passwords?

Question: I've recently enabled LDAP based authentication on my domain. This has allowed us to use a single set of credentials to administer the blog, the forum and the wiki.
Unfortunately, this has come at the cost of users being able to change their own passwords.
Ideally, users would be able to visit a page (i.e. mydomain.com/account), authenticate and then change their password.
Does anyone know of a script or app that will allow me to do this quickly and easily? I guess it wouldn't be hard to write in PHP, but I'd prefer not to have the hassle.
Comment: Cross posted: http://webmasters.stackexchange.com/questions/2975/is-there-an-app-script-i-can-deploy-to-enable-my-users-to-change-their-own-ldap-p
Answer: I you might be interested in phpLdapPassword.

phpLdapPasswd is a system that allows certain password management functions to be initiated from a standard web browser. As the name suggests, phpLdapPasswd is designed to integrate with an LDAP directory. The core functionality includes password changes and password resets. Templates, CSS directives and external functions allow for a high degree of flexibility in how phpLdapPasswd looks and acts. However, quick deployments are also possible by using the included default files and settings.
Comment: Hmmm... first item in the webpage: "NOTE: phpLdapPasswd is NO LONGER being maintained or supported"
Answer: I found phpLdapPasswd the most flexible solution.
As the original site of phpLdapPasswd is down and Karyl discontinued development, I added a separate github project: https://github.com/koppor/phpLdapPasswd
Answer: I've coded one a little while ago and blogged about it. It enforces a 6 characters password with a minimum of 1 special character.
The blog post is in french, but the code is commented in english.
blog post: http://jve.linuxwall.info/blog/index.php?post/2009/03/15/Changer-un-mot-de-passe-LDAP
tar with the php: http://jve.linuxwall.info/ressources/code/ldapchangepasswd.tar
Feel free to contact me if some of the functions are unclear
Answer: What you need to do is bind as the user's DN, with the old password, and then modify: userPassword with the new password value.
Pretty much any script that does that should work.
Comment: This doesn't help so much with expired passwords (if your LDAP system has date-based expirations), but the general approach is the classic one for building password-change scripts.


Can a team in the NFL make the playoffs with only three wins?

Question: It's impossible for all the teams in a division to have losing records in their divisional games--every time someone loses a game, someone else in the division wins it. But the home team could win every game, and everyone would be 3-3 in divisional play. But as far as I can tell there's no reason why the teams in this unhappy division couldn't lose all ten of their other games. Is this true--is it mathematically possible for a three win team to go to the playoffs?
Naturally, this question is motivated by the fact that there's serious talk of a six win team representing the NFC South.
Comment: For this unlikely scenario to be resolved, it likely would be the fifth tie breaker to break the logjam. - Strength of victory. http://www.nfl.com/standings/tiebreakingprocedures
Answer: Technically yes. One of those 3-3 teams will win the division by tie-breaker and, strangely enough, get a home game as the #4 seed against the top wild card team.
Answer: I suppose in theory a team could get to the playoffs without winning a regular season game.
If all divisional games finish as ties, and all teams lose every other game, they'll all end up with 0-10-6 records. Whoever comes on top after the tiebreakers will win the division and get the #4 seed.
In practice having 12 ties for the divisional games is highly unlikely of course, so is each team losing their other 10 games.
Answer: Yes. The Division champion will make it to the playoffs no matter what the team's record is and will host a wildcard team (which will have a better record!). That being said, it sounds extremely unlikely to have a team holding the best record in a division with only 3 wins.


Spectrum of the Fourier Transform operator

Question: I am asked to find the spectrum of the Fourier transform operator $\mathcal F:L^2(\mathbb R)\to L^2(\mathbb R)$, where $\mathcal Fu(\omega)=\int_\mathbb R \frac 1{\sqrt{2\pi}}u(x)e^{-ix\omega} dx$. I know that $\mathcal F^4=\mathrm{Id}$, and I read this thread already Two questions in spectral theory: the spectrum of the Fourier transform and the Hamiltonian of the hydrogen atom.. I'm lost in the last passage, how do I show that there is no residual spectrum?
Answer: Because $\mathcal{F}^4=I$, it follows that
$$
         (\mathcal{F}-zI)^{-1}=\frac{1}{1-z^4}(\mathcal{F}^3+z\mathcal{F}^2+z^2\mathcal{F}+z^3I),\;\;\;\; z \notin \{1,i,-1,-i\}.
$$
The operator on the right is bounded on $L^2$. So the spectrum $\sigma(\mathcal{F})$ satisfies $\sigma(\mathcal{F})\subseteq\{1,i,-1,-i\}$. Conversely, every point of $\{ 1,i,-1,-i\}$ is in the point spectrum; for example, $i$ is in the point spectrum because
\begin{align}
    (\mathcal{F}-iI)(\mathcal{F}+I)(\mathcal{F}+iI)(\mathcal{F}-I)=0,\\
           (\mathcal{F}+I)(\mathcal{F}+iI)(\mathcal{F}-I) \ne 0.
\end{align}
All spectrum of $\mathcal{F}$ is, therefore, point spectrum. There is no residual or continuous spectrum. This is generally true of any bounded operator with an annihilating polynomial.


ASP.NET Core MVC: return a method in another model

Question: I get a NullReferenceException when I try to create a new Contract when executing my program. I get the error at the method where I want to return the model. But I don't know why and I can't find out because I'm a bit new to programming.
This is my model where I want to return the calculated price from the CarList model
public class Contract
{
    public int Id { get; set; }
    public int CustomerId { get; set; }
    public Customer Customer { get; set; }
    public int CarListId{get;set;}
    public  CarList CarList { get; set; }
    [DataType(DataType.Date)]
    public DateTime AusleihDatum{ get; set; }

    [DataType(DataType.Date)]
    public DateTime AbgabeDatum { get; set; }

    public int KilometerstandAnfang { get; set; }
    public int KilometerstandEnde { get; set; }

    public double GesamtPreis
    {
        get
        {
            return CarList.GesamtPreis();
        }
    }
}

This is the CarList model:
namespace MvcCar2.Models
{
    public class CarList
    {
        public int Id { get; set; }

        public string Hersteller { get; set; }
        public string Modell { get; set; }
        public string Kennzeichen { get; set; }
        public string Farbe { get; set; }

        public int Kilometerstand { get; set; }

        public int CarGroupId { get; set; }
        public CarGroup CarGroup { get; set; }

        [NotMapped]
        public int ContractId { get; set; }
        public Contract Contract { get; set; }

        public double GesamtPreis()
        {
            if (Contract.AbgabeDatum < Contract.AusleihDatum)
            {
                throw new InvalidOperationException("Return date is before rental date");
            }

            TimeSpan differenz = Contract.AbgabeDatum - Contract.AusleihDatum;
            int ausleihzeit = (int)differenz.TotalDays;
            double gesamtPreis1 = ausleihzeit * CarGroup.PreisTag;

            return gesamtPreis1;
        }
    }
}

My ContractsController:
namespace MvcCar2.Controllers
{
    public class ContractsController : Controller
    {
        private readonly MvcCar2Context _context;

        public ContractsController(MvcCar2Context context)
        {
            _context = context;
        }

        // GET: Contracts
        public async Task<IActionResult> Index()
        {
            var mvcCar2Context = _context.Contract
                                         .Include(c => c.CarList)
                                         .Include(c => c.Customer)
                                         .Include(c => c.CarList.CarGroup);
            return View(await mvcCar2Context.ToListAsync());
        }

        // GET: Contracts/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null || _context.Contract == null)
            {
                return NotFound();
            }

            var contract = await _context.Contract
                .Include(c => c.CarList)
                .Include(c => c.Customer)
                .Include(c=> c.CarList.CarGroup)
                .FirstOrDefaultAsync(m => m.Id == id);

            if (contract == null)
            {
                return NotFound();
            }

            return View(contract);
        }

        // GET: Contracts/Create
        public IActionResult Create()
        {
            var CarListfromDB = _context.Car.ToList();

            var CarListList = CarListfromDB.Select(Car => new
            {
                Id = Car.Id,
                DisplayText1 =
                $"{Car.Hersteller}-{Car.Modell}-{Car.Farbe}-{Car.Kennzeichen}-{Car.CarGroupId}"
            });

            ViewData["CarListId"] = new SelectList(CarListList, "Id", "DisplayText1");

            var CustomerfromDB = _context.Customer.ToList();

            var CustomerList = CustomerfromDB.Select(Customer => new
            {
                Id =Customer.Id,
                DisplayText2 =
                $"{Customer.Name}-{Customer.Vorname}-{Customer.EMail}-{Customer.AdressId}"
            });

            ViewData["CustomerId"] = new SelectList(CustomerList, "Id", "DisplayText2");
            return View();
        }

        // POST: Contracts/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(int id, [Bind("Id,CustomerId,CarListId,AusleihDatum,AbgabeDatum,GesamtPreis,KilometerstandAnfang,KilometerstandEnde")] Contract contract)
        {
            //if (ModelState.IsValid)
            //{
                _context.Add(contract);
                await _context.SaveChangesAsync();

                return RedirectToAction(nameof(Index));
            //}

            var CarListfromDB = _context.Car.ToList();
            var CarListList = CarListfromDB.Select(Car => new
            {
                Id = Car.Id,
                DisplayText1 =
                $"{Car.Hersteller}---{Car.Modell}---{Car.CarGroupId}---{Car.Kennzeichen}---{Car.Farbe}"
            });

            ViewData["CarListId"] = new SelectList(CarListList, "Id", "DisplayText1");
            var CustomerfromDB = _context.Customer.ToList();

            var CustomerList = CustomerfromDB.Select(Customer => new
            {
                Id = Customer.Id,
                DisplayText2 =
                $"{Customer.Name}---{Customer.Vorname}---{Customer.EMail}---{Customer.AdressId}"
            });

            ViewData["CustomerId"] = new SelectList(CustomerList, "Id", "DisplayText2");

            return View(contract);
        }

        // GET: Contracts/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null || _context.Contract == null)
            {
                return NotFound();
            }

            var contract = await _context.Contract.FindAsync(id);

            if (contract == null)
            {
                return NotFound();
            }

            var CarListfromDB = _context.Car.ToList();

            var CarListList = CarListfromDB.Select(Car => new
            {
                Id = Car.Id,
                DisplayText1 =
                $"{Car.Hersteller}---{Car.Modell}---{Car.CarGroupId}---{Car.Kennzeichen}---{Car.Farbe}"
            });

            ViewData["CarListId"] = new SelectList(CarListList, "Id", "DisplayText1", contract.CarListId);
            var CustomerfromDB = _context.Customer.ToList();

            var CustomerList = CustomerfromDB.Select(Customer => new
            {
                Id = Customer.Id,
                DisplayText2 =
                $"{Customer.Name}---{Customer.Vorname}---{Customer.EMail}---{Customer.AdressId}"
            });

            ViewData["CustomerId"] = new SelectList(CustomerList, "Id", "DisplayText2", contract.CustomerId);

            return View(contract);
        }

        // POST: Contracts/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("Id,CustomerId,CarListId,AusleihDatum,AbgabeDatum,GesamtPreis,KilometerstandAnfang,KilometerstandEnde")] Contract contract)
        {
            if (id != contract.Id)
            {
                return NotFound();
            }

            //if (ModelState.IsValid)
            //{
                try
                {
                    _context.Update(contract);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ContractExists(contract.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }

                return RedirectToAction(nameof(Index));
            //}
            var CarListfromDB = _context.Car.ToList();

            var CarListList = CarListfromDB.Select(Car => new
            {
                Id = Car.Id,
                DisplayText1 =
                $"{Car.Hersteller}---{Car.Modell}---{Car.CarGroupId}---{Car.Kennzeichen}---{Car.Farbe}"
            });

            ViewData["CarListId"] = new SelectList(CarListList, "Id", "DisplayText1", contract.CarListId);
            var CustomerfromDB = _context.Customer.ToList();

            var CustomerList = CustomerfromDB.Select(Customer => new
            {
                Id = Customer.Id,
                DisplayText2 =
                $"{Customer.Name}---{Customer.Vorname}---{Customer.EMail}---{Customer.AdressId}"
            });

            ViewData["CustomerId"] = new SelectList(CustomerList, "Id", "DisplayText2", contract.CustomerId);
            return View(contract);
        }

        // GET: Contracts/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null || _context.Contract == null)
            {
                return NotFound();
            }

            var contract = await _context.Contract
                .Include(c => c.CarList)
                .Include(c => c.Customer)
                .Include (c => c.CarList.CarGroup)
                .FirstOrDefaultAsync(m => m.Id == id);

            if (contract == null)
            {
                return NotFound();
            }

            return View(contract);
        }

        // POST: Contracts/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            if (_context.Contract == null)
            {
                return Problem("Entity set 'MvcCar2Context.Contract'  is null.");
            }

            var contract = await _context.Contract.FindAsync(id);

            if (contract != null)
            {
                _context.Contract.Remove(contract);
            }

            await _context.SaveChangesAsync();

            return RedirectToAction(nameof(Index));
        }

        private bool ContractExists(int id)
        {
            return (_context.Contract?.Any(e => e.Id == id)).GetValueOrDefault();
        }
    }
}

My CarListController:
namespace MvcCar2.Controllers
{
    public class CarListsController : Controller
    {
        private readonly MvcCar2Context _context;

        public CarListsController(MvcCar2Context context)
        {
            _context = context;
        }

        // GET: CarLists
        public async Task<IActionResult> Index()
        {
            var mvcCar2Context = _context.Car.Include(c => c.CarGroup);
            return View(await mvcCar2Context.ToListAsync());
        }

        // GET: CarLists/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null || _context.Car == null)
            {
                return NotFound();
            }

            var carList = await _context.Car
                .Include(c => c.CarGroup)
                .FirstOrDefaultAsync(m => m.Id == id);

            if (carList == null)
            {
                return NotFound();
            }

            return View(carList);
        }

        // GET: CarLists/Create
        public IActionResult Create()
        {
           var CarGroupfromDB = _context.CarGroup.ToList();

            var CarGroupList = CarGroupfromDB.Select(CarGroup => new
            {
                Id = CarGroup.Id,
                DisplayText = $"{CarGroup.Klasse}-{CarGroup.PreisTag}"
            });

            ViewData["CarGroupId"] = new SelectList(CarGroupList, "Id", "DisplayText");

            return View();
        }

        // POST: CarLists/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,Hersteller,Modell,Kennzeichen,Farbe,Kilometerstand,CarGroupId")] CarList carList)
        {
            //if (ModelState.IsValid)
            //{
                _context.Add(carList);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            //}

            var CarGroupfromDB = _context.CarGroup.ToList();

            var CarGroupList = CarGroupfromDB.Select(CarGroup => new
            {
                Id = CarGroup.Id,
                DisplayText =
             $"{CarGroup.Klasse}-{CarGroup.PreisTag}"
            });

            ViewData["CarGroupId"] = new SelectList(CarGroupList, "Id", "DisplayText");

            return View(carList);
        }

        // GET: CarLists/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null || _context.Car == null)
            {
                return NotFound();
            }

            var carList = await _context.Car.FindAsync(id);

            if (carList == null)
            {
                return NotFound();
            }

            var CarGroupfromDB = _context.CarGroup.ToList();

            var CarGroupList = CarGroupfromDB.Select(CarGroup => new
            {
                Id = CarGroup.Id,
                DisplayText =
             $"{CarGroup.Klasse}-{CarGroup.PreisTag}"
            });

            ViewData["CarGroupId"] = new SelectList(CarGroupList, "Id", "DisplayText", carList.CarGroupId);

            return View(carList);
        }

        // POST: CarLists/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("Id,Hersteller,Modell,Kennzeichen,Farbe,Kilometerstand,CarGroupId")] CarList carList)
        {
            if (id != carList.Id)
            {
                return NotFound();
            }

            //if (ModelState.IsValid)
            //{
                try
                {
                    _context.Update(carList);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!CarListExists(carList.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            //}
            var CarGroupfromDB = _context.CarGroup.ToList();

            var CarGroupList = CarGroupfromDB.Select(CarGroup => new
            {
                Id = CarGroup.Id,
                DisplayText =
             $"{CarGroup.Klasse}-{CarGroup.PreisTag}"
            });

            ViewData["CarGroupId"] = new SelectList(CarGroupList, "Id", "DisplayText", carList.CarGroupId);

            return View(carList);
        }

        // GET: CarLists/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null || _context.Car == null)
            {
                return NotFound();
            }

            var carList = await _context.Car
                .Include(c => c.CarGroup)
                .FirstOrDefaultAsync(m => m.Id == id);

            if (carList == null)
            {
                return NotFound();
            }

            return View(carList);
        }

        // POST: CarLists/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            if (_context.Car == null)
            {
                return Problem("Entity set 'MvcCar2Context.Car'  is null.");
            }

            var carList = await _context.Car.FindAsync(id);

            if (carList != null)
            {
                _context.Car.Remove(carList);
            }

            await _context.SaveChangesAsync();

            return RedirectToAction(nameof(Index));
        }

        private bool CarListExists(int id)
        {
          return (_context.Car?.Any(e => e.Id == id)).GetValueOrDefault();
        }
    }
}

And the CarGroup model where I get the price from:
namespace MvcCar2.Models
{
    public class CarGroup
    {
        public int Id { get; set; }
        public string Klasse { get; set; }

        public double PreisTag { get; set; }
    }
}

So what I want to do is calculate the price in the CarList model. The model takes the price from the Cargroup model based on the CarGroup and then this calculated price is returned in the ContractController so it will be shown in the table of the ContractsController.
Comment: I tested with your code, the carlist is null in your model contract, that causes the NullReferenceException. Your GesamtPreis in the contract only get but not set, which will surely make it null. I suggest you query on the GesamtPreis in your Create post action to get the value and move the GesamtPreis out of contract.
Comment: Could you please set the breakpoint and provide more debug details?
Comment: @Ronaldoz I think its because i have to load the data from the carList Database but i dont know how yet. Like How i connect the models
Answer: Since there is no debug details, I can give you one possible cause.
The contract model calls carlist for the price property, but when creating, the model haven't bound the carlist, that's why it will always throw the NullReferenceException. You can follow my sample to check.

Your contract references the customer and carlist, set the property to be nullable. And check the price.

Contract.cs

using System.ComponentModel.DataAnnotations;

namespace YourNamespace.Models
{
    public class Contract
    {
        public int Id { get; set; }

         //1.to be nullable
        public int CustomerId { get; set; }
        public Customer? Customer { get; set; }
        public int CarListId { get; set; }
        public CarList? CarList { get; set; }

        [DataType(DataType.Date)]
        public DateTime AusleihDatum { get; set; }

        [DataType(DataType.Date)]
        public DateTime AbgabeDatum { get; set; }

        public int KilometerstandAnfang { get; set; }
        public int KilometerstandEnde { get; set; }

        public double GesamtPreis
        {
            get
            {
                   //2.add the logic to avoid nullreference
                return CarList != null ? CarList.GesamtPreis() : 0;
            }
        }
    }
}

Your Create action should bind price no more

ContractsController
// POST: Contracts/Create
// To protect from overposting attacks, enable the specific properties you want to bind to.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(int id, [Bind("Id,CustomerId,CarListId,AusleihDatum,AbgabeDatum,KilometerstandAnfang,KilometerstandEnde")] Contract contract)
{
    // 1.The modelstate will be invalid if the customer and carlist are not nullable
    if (ModelState.IsValid)
    {
        _context.Add(contract);
        await _context.SaveChangesAsync();

         //2.Here you can get the price and it will be bound to model
         //3.Include will connect the reference model in efcore
        var SavedContract = await _context.Contract
        .Include(c => c.CarList)
        .Include(c => c.Customer)
        .Include(c => c.CarList.CarGroup)
        .FirstOrDefaultAsync(C => C.CarListId == contract.CarListId);
        var gesamtPreis = SavedContract.GesamtPreis;

        return RedirectToAction(nameof(Index));
    }

    var CarListfromDB = _context.Car.ToList();
    var CarListList = CarListfromDB.Select(Car => new
    {
        Id = Car.Id,
        DisplayText1 =
        $"{Car.Hersteller}---{Car.Modell}---{Car.CarGroupId}---{Car.Kennzeichen}---{Car.Farbe}"
    });

    ViewData["CarListId"] = new SelectList(CarListList, "Id", "DisplayText1");
    var CustomerfromDB = _context.Customer.ToList();

    var CustomerList = CustomerfromDB.Select(Customer => new
    {
        Id = Customer.Id,
        DisplayText2 =
        $"{Customer.Name}---{Customer.Vorname}---{Customer.EMail}---{Customer.AdressId}"
    });

    ViewData["CustomerId"] = new SelectList(CustomerList, "Id", "DisplayText2");

    return View(contract);
}

3.Since you don't offer the Customer, make sure the reference is correct

Customer.cs

namespace YourNamespace.Models
{
    public class Customer
    {
        public int Id { get; set; }
        public string? Vorname { get; set; }
        public string? Name { get; set; }
        public string? EMail { get; set; }
        public int AdressId { get; set; }
        public Contract? Contract { get; set; }
    }
}

Now the price will be provided.
Test


Will this section be playable by a professional pianist and a professional violinist?

Question: So I am composing a piece for a competition, and it has a strict criteria about the song being playable. I am looking for reviews for a section in my piece for playability.
The piano part , 16th notes repeating both hands playing and at 140 bpm : quarter note, 4/4 time signature, same for the violin part
Will it be playable ? If not, how could I change it to have the same effect ?
Thanks !
Comment: I'm voting to close this question because this type of discussion better fits "The Auditorium" chat room rather than as a Q&A on the main site.
Comment: "strict criteria about the song being playable" - In my experience, if you have to ask whether something is playable, then the best thing for you to do is make it easier. The only time musicians or audiences complain about music being too easy is when it's also music they don't like.
Comment: I'm commenting instead of answering because I'm not a technically skilled pianist. Keep in mind that certain instruments can play rapid repeated notes fairly effortlessly. Piano is not one of them. It can be done but repeated notes require more advanced techniques to accomplish. Also, the word, "professional" does not guarantee a very specific level of ability. Whatever the pianist is doing with the other hand may be relevant so you should edit and include the bass clef of the passage as well.
Comment: @DevJ Well, ironically, repeated notes are no problem for the violin. You could swap the parts and it would be not terribly challenging for either instrument.
Comment: @DevJ If that is all a pianist had to do with both hands then it wouldn't be impossible but not easy either. There could potentially be a limit to how fast the actual keyboard can respond though. As for other instruments, orchestral strings can play very fast repeated notes as can fretted instruments, percussionists and even some wind and brass instruments.
Comment: I'd be happy to give violin tips in the chat room! As it stands, the violin part is fine for an intermediate player.
Comment: Oh sorry, I see that you edited to mention the violin part as well in the body of the question. It would still help if you posted the actual guidelines you're working with, since "professional" and "playable" are both pretty ambiguous (*how* easily playable? Sight-readable? doable with months of practice and some luck?).
Comment: @JohnBelzaguy There is nothing in the bass clef for the pianist. What I meant by "both hands" was that playing the repeated 16th notes with both hands instead of just using one. I am refering to professional as someone who has experience playing piano as their main instrument 10+ years and who perform on stages , events etc. Also what according to you would be a good instrument that could play such a melody effortlesslsy?
Comment: @AndyBonner From what feedback I have received for the piano part, most of it suggests that I should probably change it because it is too hard to play, but I have received virtually no feedback for the violin part. Is the violin line playable ? I am sorry I could not make that out from your response.
Comment: I'm voting to close this question for a combination of lack of clarity and broad, open-ended nature.
Answer: Your score calls for 9.33 repeated notes per second (140 x 4 / 60).
With piano, you have one additional problem: fast repeated notes are lot harder to execute in upright pianos due to the inherent limitation of the hammer actions (also possibly in some digital pianos / keyboards) unless the manufacturer designs the action to facilitate repetition (such as Sauter R2 Double Repetition System used in their upright models such as this one).  Comments from @ToddWilcox: "Quality digital pianos have actions as fast as the fastest grands."
As for the fastest repeated notes called for by a major classical piano piece:

Schubert's Erlkönig's piano accompaniment calls for about 160bpm (see sample performance here), so about 8 repeated notes per second.  But then, the notes relatively stay the same longer, unlike yours that changes every beat.
Ravel's Alborada del gracioso measures 42-57 which calls for about 87 bpm (260 beats per 8th note) (see sample performance here), so about 13 repeated G# per second!  Again, having it fixed at the same note (G# throughout all those measures) make it a lot easier.  Also, this piece is for concert pianists, not for accompanists.  This Piano Library difficulty rating website, rates this piece at the highest level.

So I would say your piano part would be very hard to play even for professional pianist.  I personally cannot play that passage easily (especially on black keys), even with switching fingers; maybe one day I can but I need to spend considerable effort.  Comment from @ToddWilcox:

"I don't find switching fingers on the black keys much harder than on the white ones. I would probably play this 4-3-2-1 except C to E which I might do 2-1 then 3-4. That said I cannot play this at tempo."

This thread in PianoWorld forum has responders say their maximum speed between 6 to 10.  Maybe you can post your playability question there as well.
I suggest making them 8th notes instead of 16th notes, or to maintain 16th notes but alternating with another note of the implicit harmony.  But composition suggestion questions are better asked at The Auditorium chatroom.
Comment: Even Boston uprights do not have very fast actions. Good grands can likely do this. Quality digital pianos have actions as fast as the fastest grands. I don't find switching fingers on the black keys much harder than on the white ones. I would probably play this 4-3-2-1 except C to E which I might do 2-1 then 3-4. That said I cannot play this at tempo.
Comment: I don't know how you play the piano, but I find repeating *the same* key extremely fast is incomparably harder to get right than repeating short scale fragments like this.
Comment: I am trying to get the same effect on 8th notes but I am not able to achieve something like this, maybe I will try putting the left hand to use and play 8th notes on the right hand with accompanying left hand playing something filler to have somewhat the same effect.
Comment: @DevJ As AndyBonner suggests, for composition tips, the [Auditorium chatroom](https://chat.stackexchange.com/rooms/126233/the-auditorium) is more appropriate.  I myself is a high enough level classical pianist who can play *Erlkonig*'s accompaniment just fine, but far from being able to play Ravel's *Alborada del gracioso*.
Comment: @DevJ I make this a wiki answer so a violinist can edit this answer to add input for the violin part's playability.  One fast violin with extended 16th notes is this Paganini's [*Caprice No. 24* Variation 2](https://www.youtube.com/watch?v=UcL0IsklM3M&t=49s), played at 130bpm, slightly slower than yours.
Answer: To address the violin part: This should be quite reasonable for a professional or even advanced non-professional. I think I could play it correctly even without any practice if I turned the page and happened on it at 120 bpm, and could get it up to 140 with a few minutes of practice. To go much faster than that would start to make it a virtuosic passage, but could be conceivable. Hilary Hahn's recording of the last movement of the Barber violin concerto is around 600 notes per minute, and this is only 560 and is much more straightforward.
That said, there are definitely players who could not play this. This passage would require the player to be comfortable in second and third position (maybe fourth?) and have a good sautillé or spiccato bow stroke. While you might find this in an advanced student, it would be very surprising to find it in someone younger than their teens or who had been studying for less than 4 or so years.
For the benefit of other "how fast can a violin play" questioners, let's talk about what makes this passage harder and what makes it easier. In general, the hardest thing for playing fast is moving the bow to a different string; the second hardest is moving the left hand fingers especially in unpredictable patterns or stretches; and the least hard is simply changing the bow, up bow to down bow. Notes at this speed would be easier (or at least accessible to less experienced students) in first position. Although these pitches are lower than B5 and therefore can be played in first position, the player would be using their fourth (weakest, slowest) finger a lot in the first measure, and forced to change between D and A strings in the second. Most advanced players would opt for second position in the first measure so they can use fingers 1, 2, and 3, and perhaps move to fourth position for the Abs, Bbs, and Cs (I'm not quite sure about the easiest way to make that shift). The passage is much easier than it could be because the pattern is a simple repeating one. Although each beat looks different, it's just three notes being repeated. Also, they're mostly adjacent, step-wise notes. The very fastest thing a string player can play is a scale.
So all that is to say: Things that could render this not playable at 140 would include shuffling the order of the notes in a way that was harder to intuitively grasp, or choosing notes that could not be played on a single string no matter what position one chose. (In fact, if the player had to cross from one string to a non-adjacent one, e.g. D to E, that would quickly lower the maximum possible tempo by a lot.)
Or to boil it down even simpler: the "fastest a violin can play" isn't determined simply by the tempo and rhythm, but by how the notes lie on the instrument.
Meanwhile, I think it's clear that the piano part can not be considered reasonably "playable" at this tempo. Ironically, the piano part would be quite easy on the violin. While it's challenging for piano to repeat the same key rapidly, it's quite easy to change the bow while playing a single note. That passage wouldn't even require shifting above first position. I could imagine a good middle school orchestra playing it at 140, with plenty of practice.


Why do we even need a PBX software like Asterisk?

Question: I am starting out with VOIP and configuring softphones. When we sign up to a SIP provider like FlowRoute we get the credentials for a SIP Proxy. Can't we just use the SIP registration details in a softphone like Zoiper ?
Why would we want to setup a PBX? I am talking for setting up a simple system to make calls from a desktop.
Why must there be a PBX in the middle ? Why setup a PBX and add the SIP details there and configure the softphone with Asterisk ? Why not add the SIP details in the softphone directly ?
Answer: The PBX is going to handle all of your endpoints, your hunt groups, your schedules, your auto-attendant, call flows/trees, recordings, etc.. Your SIP provider gives you phone lines. The PBX allows you to use those phone lines. A lot of SIP providers can also provide hosted PBX services, so they handle everything.
You could set up a PBX in your office for internal communication between your employees. But if you want to attach public phone numbers and allow incoming/outgoing phone calls, you'll need to add a SIP provider.
Answer: If you just want a simple phone, a VoIP equivalent of just renting a single phone line and plugging a dumb phone into it, you don't need the PBX, just a Sip Trunk.
If you want the features that the PBX brings to a traditional phone line on your VoIP line, you need a PBX for that too. Some Sip Trunk provides provide a few of these features at the host end but unless you take a "Hosted PBX" type service, (in which case you still HAVE the pbx, it's just at the host end!) you won't get most of them.

Hunt groups
Call Forwarding
Voicemail
Conference calls
Call Recording
to pick on just a few of the more common...

If you don't fancy Asterisk, and you don't want to pay, check out the "free" version of 3CX, windows based soft-PBX.
Answer: You absolutely can do this. Whether it's appropriate for your situation is a different matter.
Essentially, SIP trunks are like POTS lines or T1/PRI trunks. They are just dial tone. They can be used (and combined) in various ways depending on the business application.
Using that analogy: You could run a individual POTS lines to each desktop (i.e. associate your softphones with raw SIP trunks). This would get you phone service at that desktop / workstation.
If you have more than one desktop, you may want to call between them, transfer calls between them, or have them ring sequential in a hunt group when an inbound call to your company (or a specific department, maybe on an extension) comes in. This is where a PBX needs to exist somewhere.
The PBX can either be on-premise (e.g. Asterisk, Avaya IP Manager, etc.) or off-premise (e.g. hosted by your SIP provider).
Some SIP providers just provide the equivalent of "dialtone" -- just trunks. These can be connected directly to endpoint devices like hardware phones, soft phones, or on-premise PBXes.
Some SIP providers also provide hosted PBX offerings. In these cases the customer doesn't have an on-premise PBX, and their endpoints are configured to point at the provider's PBX.
Comment: So if I register to a SIP provider like Flowroute and only want to make calls to the PSTN via flowroute there is not need for the PBX right ? I can just download something like Zoiper and add a SIP account and make calls right ? Am I correct ?
Comment: I don't know about FlowRoute specifically, but yes generally ...at least for one endpoint device.
Answer: If your looking at VoIP line to replace a personal line you could use this as a very basic phone line, possible for a home. You would need to see if your provider could provide voicemail or call waiting.
For a office situation you will want the free inter-PBX calling. If everyone is registering to a 3rd party that 3rd party my charge you for those interoffice calls.
Their are several providers which can provide a whole PBX managed offsite, however if your office has a large concurrent call requirement you will need to make sure your location can meet the bandwidth requirements. The biggest benefit of a off site PBX would be if you have a large remote/home office user base.  If a majority of your users are in one office a on site PBX may be beneficial.
If you looking to convert to VoIP also check what e911 regulation may govern your organization, and confirm your provider can comply with these.


Can't determine whether problem involves the binomial distribution or not

Question: The question is basic: If it's sunny an average of 5 days a week, what's the probability that it'll be rainy 2 days out of 3? Assume unrealistically that the weather on a given day is independent of the other days.
I'm having a major mental block and can't see through this problem. Does the binomial distribution apply; i.e.
$\dbinom{3}{2} \left(\frac{2}{7} \right)^2 \left(\frac{5}{7} \right)^1$
or is it a simple selection without replacement:
$\frac{\dbinom{2}{2}\dbinom{5}{1}}{\dbinom{7}{3}}$
I can't convince myself one way or the other; so I solicite your advice.
Answer: Is it a homework? (then you should include the appropriate tag).
Hint: Can you come up with the probability that it rains 0 days ($P_0$), 1 day ($P_1$), and 3 days ($P_3$) for your two approaches and then check whether $$\sum_{n=0}^3 P_n =1,$$
which will give you a good indication which approach is correct...
Comment: This was really helpful--thank you.
Answer: I believe it's the first - binomial distribution.
What's happening is that you're repeating the same experiment (whether a day will be rainy or not) three times in a row, independently. In general, when repeating an experiment n times independently with a success rate of p, the probability of success is exactly
$\dbinom{n}{m} p^{m}(1-p)^{n-m}$
Here n=3, m=2, and $p=\frac{5}{7}$ so it should be:
$\dbinom{3}{2} \left(\frac{2}{7} \right)^2 \left(\frac{5}{7} \right)^1$
Selection without replacement implies that the experiments are dependent, which doesn't make sense here since we've assumed the weather of each day doesn't depend on the others.
Answer: You are right to have some hesitancy.
If the statement about "sunny" is a general statement, meaning that the probability of sunny is $5/7$, then the binomial distribution (your first choice) is the relevant one.
But if the statement is interpreted as meaning that in a PARTICULAR week it was sunny $5$ days out of $7$, and we ask for the probability that for some given $3$ days that week it rained for exactly $2$, then the hypergeometric distribution (your second choice) is the appropriate one.
My slightly preferred interpretation of the problem would be the first (binomial) one, but it really is a matter of interpretation, and there is a good case to be made, on meteorological grounds, for the second interpretation.  It is unfortunate that, in attempts at "relevance", you are asked to thrust an overly simplified probability model on a complex situation.
Too bad that the question did not say.  "It rained $5$ days out of $7$ during my week-long Spring break.  What is the probability that out of $3$ randomly chosen days that week, it rained on exactly $2$?" Then everything would be clear, the second interpretation would be correct.
Comment: Did you miss "an average of"?  That should tell you it's not talking about a particular week.
Comment: Thank you for that beautiful response. You've convinced me and taught me something. I wish you a great week.
Answer: The binomial distribution apply if the experiments satisfy these criteria:

The experiments are independent.
Each experiment has two outcomes: success/failure.
The probability for success in each experiment is the same.
Comment: For a Bernoulli trial, all that you need is (2).  If you also have (1) and (3), then you have iid Bernoulli trials.
Comment: @Robert: You're right. Sorry.


Operador "?" em PHP, para que serve?

Question: Estou estudando php, peguei um código para mexer e não estou achando referencia para o sinal de interrogação no php, que serve no exemplo abaixo, para o que serve.
<code>$dinheiro = $debito <= 1 ? FALSE : TRUE;
</code>
Comment: É o operador ternário, dá uma olhada no link que o rray postou que tem ótimas respostas.
Answer: Chama-se Operador Ternário.
Isso significa: se o valor de $debito for menor ou igual a um, a variável $dinheiro fica com o valor de FALSE, senão fica com o valor de True.
Isto pode ser comparado com:
<code>if($debito<=1)
{
   $dinheiro = false;
}
else
{
   $dinheiro = true;
}
</code>

Operador "?" em PHP, para que serve?


Configure domain name in CentOS

Question: How do I configure domain names in Cent OS?
I am actually connecting to the servers via SSH remote terminal and I also have root credentials. Does configuring the /etc/sysconfig/network and /etc/hosts suffice? Would be great to have some steps or configuration guides..
Answer: Four things to do:

Add the hostname entry to /etc/hosts. Use the format detailed here.
If your hostname is "your_hostname", type hostname your_hostname at a command prompt to make the change effective.
Define the hostname in /etc/sysconfig/network to make this setting persist across reboots.
Reboot the system or restart services that depend on hostname (cups, syslog, apache, sendmail, etc.)
Answer: If by domain name you mean domain suffix, then /etc/resolv.conf is where the domain goes. Just add a line domain yourdomain.com
Then to set your server's hostname, there's only one good place for it, and it's /etc/sysconfig/network. Add a line HOSTNAME=yourhostname, and don't put the domain suffix in the hostname, as it will take it from /etc/resolv.conf.
You do not need to add anything (and shouldn't) in /etc/hosts to define your hostname. This is the wrong way to do it.
To test your setup, use the hostname command:

Use hostname -s to get the short name (should reflect what you have in /etc/sysconfig/network
Use the hostname -d command to test your domain (should reflect what you have in /etc/resolv.conf)
To test it all together, you can use hostname -f or hostname -A for the very long version.
Comment: In CentOS 7 `HOSTNAME` in `/etc/sysconfig/network` no longer works.
Answer: The way to do it now is hostnamectl hostname.domainname
Comment: `hostnamectrl set-hostname ` you should not use the FQDN here

Configure domain name in CentOS


HI, I am not able to call redshift stored procedure in SSIS ExecuteSqltask

Question: I am getting this error, while calling  stored procedure of Redshift. we are using oledb connection
Error: 0xC002F210 at Execute SQL Task 1, Execute SQL Task: Executing the query "call dev.proc_test" failed with the following error: "Undefined procedure proc_test". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
Task failed: Execute SQL Task 1
I have  set result set as none because my procedure is not returning any value.
I have called the procedure with db name.
In my Redshift db procedure is saving under functions tab.
Is that the  reason for my error? why my procedure is saving under the functions, how to rectify this
Comment: You may need to append the DB name to the SP  EXEC DBName.dbo.proc_test.
Answer: I have called the  procedure with the DB name ,It is working fine
[image]
[1]: https://i.stack.imgur.com/2hWpl.png
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Finite volume method of Laplace equation

Question: I'm having some trouble understanding the finite volume method in 2 dimensions. I want to solve
$$
\Delta u(\mathbf{x}) = 0
$$
for $\mathbf{x}$ on a rectangular grid $[0,1]\times[0,1]$. I have homogeneous Dirichlet boundary conditions.
If $\Omega_{ij}$ is a (square, equidistant) control volume, using the divergence theorem we get
$$
\int_{\Omega_{ij}} \Delta u d\Omega = \int_{\partial\Omega_{ij}}\nabla u \cdot n \ d(\partial\Omega).
$$
I do not understand how to proceed from here. It is however given that I need to use the central scheme for the fluxes, but my main goal at the moment is to go write the integral in terms of the flux.
Comment: Maybe you could add a reference to the text you are using (if any)?
Comment: @YuriyS I unfortunately do not have any. A lot of people in my course had some numerical analysis, so it is somewhat assumed. I'm learning it on my own at the moment.
Comment: Sorry to hear that. Unfortunately, I'm not familiar with the method. Though I had zero numerical analysis as well, all I know I had to learn on my own. I would recommend a thorough search for literature on the method
Answer: 1) You define a basis for each of your volumes. The basis should be chosen to be some useful set of functions, but for the start you can choose a polynomial basis $u = a + bx + cy + dx^2 + ey^2 + fxy + ...$.
As can be seen later, a more useful choice of basis are so called edge elements, that allow to share degrees of freedom across several elements, thus saving on matrix size. Also. you have to compromise between the size of your basis and the size of your mesh. In general, basis converges faster than mesh, but then you get dense matrices, so there is generally a good compromise.
2) For each little volume, you will find the gradients $\nabla u$ of your basis with respect to each boundary.
3) You can solve the equation using the testing function approach. To do that the original equation is relaxed to hold in an integral sense, when tested by each testing function
$\int_{\Omega} t_i(r) \Delta u(r)dr = \int_{\Omega} t_i(r) \nabla \cdot \nabla u(r)dr = \int_{\Omega} \nabla \cdot (t_i(r) \nabla u(r))dr - \int_{\Omega} \nabla t_i(r) \cdot \nabla u(r)dr = \int_{\partial \Omega_{j}} t_i(r) \vec{n}_j(r) \cdot \nabla u_j(r) dr - \int_{\Omega_j} \nabla t_i(r) \cdot \nabla u_j(r)dr = 0$
Notice that first equation goes over all boundaries between elements, domain boudaries and interior boundaries. For domain boundaries, you can simply substitute your boundary condition in the place of $u(x)$, obtaining
$F_i = \int_{\partial \Omega} t_i(r) \vec{n}_i \cdot \nabla f(r) dr$
where $f(r) = u(r)$ at the boundary. Note that this equation only has 1 index, so it will be a vector. It will go to the right hand side of the equation. The equation for each interior boundary will be a sum of the contributions from two neighbouring cells. It is necessary to insure the relaxed continuity of $u(r)$ in the interior of the domain
$\int_{\partial \Omega_{+-}} t_i(r) \vec{n}_+(r) \cdot (\nabla u_+(r) - \nabla u_-(r)) dr$
where $+$ and $-$ denote the neighboring element indices. Since there are two pairs of indices $(i,+)$ and $(i,-)$, each of the summands will enter the corresponding diagonal and off-diagonal blocks of the final matrix. Finally, the volume equation will enter the diagonal blocks
$- \int_{\Omega_j} \nabla t_i(r) \cdot \nabla u_j(r)dr$
4) The last step is to plug the basis expansions for $t_i$ and $u_j$. Using Galerkin's approach, one can assume that a good choice for the testing functions are exactly the basis functions selected for the finite elements. This way, since the basis functions are only supported inside each element and do not intersect, all integrals can be completely reduced to the integrals inside individual elements and their boundaries
$t_i(r) = \sum_m \alpha^i_m b^i_m(r)$
$u_j(r) = \sum_n \alpha^j_n b^j_n(r)$
Note that indices $i,j$ go over elements, whereas $m,n$ go over individual basis functions. The latter will correspond to the rows and the columns of the matrix. Also note that all elements of your matrix will be a sum of multiple terms, for example for the elements on the boundary will have a domain boundary term, interior boundary term and a volume term, but elements on the interior will only have interior boundary and volume terms.
Finally, you will have to solve a linear system
$\sum_n M_{mn} \alpha_n = -F_m$
EDIT
I highly recommend a classical text of J. Volakis,
https://www.wiley.com/WileyCDA/WileyTitle/productCd-0780334256,miniSiteCd-IEEE2.html
I have learned using it and multiple other resources, and it is really good and concise. It is also very expensive, so it is best that you first look for paperback or electronic versions from your library
EDIT 2 I am very sorry, because of the way you wrote your first integral, I completely forgot about the most important part of this analysis - the testing functions. Please see the appropriate changes above.
Comment: Thanks, I know of the discretization process as I'm a little familiar with finite differences. I'm trying to obtain a stencil.
Comment: A stencil will depend on the basis functions chosen. I have written a recipe for you. Consider every finite volume, every boundary between 2 elements, and every domain boundary. For each consider all equations that are applicable, and fill them in. There will not be a very simple expression for this