$(".class").val() is returning undefined value

Question: I'm hooking into the Trello API and creating a  with the Lists from a Board. I'm then attempting to list all the Cards from each List. When getting the ListID from the  value attribute, it's returning "undefined". Why is this?
I'm printing it out with document.getElementById("demo").innerHTML = $(".board").val();
//HTML
Choose from a List of Boards

Display Cards Below for Board Selected

//Javascript
    var $boards = $("<select>")
            .attr("id", "boards")
        .text("Loading Boards...")
        .appendTo("#output");

    Trello.get("/boards/BOARD_ID/lists", function(boards) {
        $boards.empty();
        $.each(boards, function(ix, board) {
            $("<option>")
            .attr({href: board.url, target: "trello", value : board.id, name : board.id, id : board.id})
            .addClass("board")
            .text(board.name)
            .appendTo($boards);
        });
    });

    var $cards = $("
")
        .text("Loading Cards...")
        .appendTo("#outputCards")
        .appendTo("#demo");

    // This is where I'm trying to return the value
    document.getElementById("demo").innerHTML = $(".board").val();

    var resource = "lists/LIST_ID/cards";
    Trello.get(resource, function(cards) {
        $cards.empty();
        $.each(cards, function(ix, card) {
            $("")
            .attr({href: card.url, target: "trello"})
            .addClass("card")
            .text(card.name)
            .appendTo($cards);
        });
    });

The HTML is outputting like this:
Choose from a List of Boards

        <select id="boards">
            <option target="trello" value="LIST_ID" name="LIST_ID" id="LIST_ID" class="board">
                List One
            </option>
            ...
        </select>

Display Cards Below for Board Selected

undefined

Comment: I don't know what `Trello` is, but I'm guessing `Trello.get()` does an asynchronous operation, so the `".board"` element will not yet have been created by the time your `$(".board").val()` line runs. And `.val()` will return `undefined` if `$(".board")` didn't match any elements. Any code that relies on the result of the `.get()` needs to be in that callback function, or in some other function called from there.
Answer: I think the main problem here is that the board class is only being added to elements in the Trello.get callback.
As this code is executed asynchronously, it's likely that you are executing $(".board").val() before the code in the callback has been executed, meaning `$(".board") returned no elements.
I would consider something like this
Trello.get("/boards/BOARD_ID/lists", function(boards) {
        $boards.empty();
        $.each(boards, function(ix, board) {
            $("<option>")
            .attr({href: board.url, target: "trello", value : board.id, name : board.id, id : board.id})
            .addClass("board")
            .text(board.name)
            .appendTo($boards);
        });
        // This is where I'm trying to return the value

        $('#board').change(function () {
            document.getElementById("demo").innerHTML = $(".board:selected").val();
        });
    });

Comment: Thanks that fixed it! But... now it's pulling in the ID for the first list (that loads by default), but doesn't update when I choose a new option from the . Any ideas how to fix that?
Comment: @user994585 I've updated the code with a fix (haven't tested it but I think it should work). You bind the `change` function to the `select` so that when the selected option changes, it updates the `demo` element with the selected value.


Interpret the clustering results of Weka to measure the performance

Question: I'm having the Boston dataset, where it's class variable in the housing price. So I think regression is more suitable for this dataset, so we can predictions.
I'm using Weka for this. I used several regression algorithms and could evaluate the performance of regression.
I just wanted to check whether clustering works with my data set. These are the results I obtained.
<code>=== Run information ===

Scheme:       weka.clusterers.SimpleKMeans -init 0 -max-candidates 100 -periodic-pruning 10000 -min-density 2.0 -t1 -1.25 -t2 -1.0 -N 2 -A "weka.core.EuclideanDistance -R first-last" -I 500 -num-slots 1 -S 10
Relation:     housing-weka.filters.unsupervised.attribute.InterquartileRange-Rfirst-last-O3.0-E6.0-weka.filters.unsupervised.instance.RemoveWithValues-S0.0-C15-Llast-weka.filters.unsupervised.attribute.Remove-R15-16-weka.filters.unsupervised.attribute.Remove-R4,8-9
Instances:    438
Attributes:   11
              CRIM
              ZN
              INDUS
              NOX
              RM
              AGE
              TAX
              PTRATIO
              B
              LSTAT
              class
Test mode:    split 66% train, remainder test

=== Clustering model (full training set) ===

kMeans
======

Number of iterations: 6
Within cluster sum of squared errors: 144.78333527946944

Initial starting points (random):

Cluster 0: 0.15445,25,5.13,0.453,6.145,29.2,284,19.7,390.68,6.86,23.3
Cluster 1: 7.83932,0,18.1,0.655,6.209,65.4,666,20.2,396.9,13.22,21.4

Missing values globally replaced with mean/mode

Final cluster centroids:
                         Cluster#
Attribute    Full Data          0          1
               (438.0)    (286.0)    (152.0)
============================================
CRIM            3.1711     0.2599     8.6489
ZN              7.3459      11.25          0
INDUS          11.3185     7.2142    19.0411
NOX             0.5579     0.4941     0.6781
RM              6.3063     6.4543     6.0279
AGE            69.9447     58.979    90.5776
TAX           400.7694   298.4685   593.2566
PTRATIO        18.4845    17.9395    19.5099
B             358.3076   389.1012    300.367
LSTAT          12.4776      9.714    17.6776
class          22.8628    25.8227    17.2934

Time taken to build model (full training data) : 0.01 seconds

=== Model and evaluation on test split ===

kMeans
======

Number of iterations: 3
Within cluster sum of squared errors: 101.20987958357911

Initial starting points (random):

Cluster 0: 5.73116,0,18.1,0.532,7.061,77,666,20.2,395.28,7.01,25
Cluster 1: 0.18159,0,7.38,0.493,6.376,54.3,287,19.6,396.9,6.87,23.1

Missing values globally replaced with mean/mode

Final cluster centroids:
                         Cluster#
Attribute    Full Data          0          1
               (289.0)     (99.0)    (190.0)
============================================
CRIM            3.4497     9.5404     0.2762
ZN              7.7699          0    11.8184
INDUS          11.4102    19.1316      7.387
NOX              0.557     0.6773     0.4943
RM              6.2967     5.9688     6.4676
AGE             70.274    90.6424    59.6611
TAX            397.391   587.0505   298.5684
PTRATIO        18.5235    19.4384    18.0468
B             357.8081    300.728   387.5498
LSTAT          12.7507    17.9897    10.0209
class             22.9    16.9687    25.9905

Time taken to build model (percentage split) : 0 seconds

Clustered Instances

0       52 ( 35%)
1       97 ( 65%)
</code>
I used 2 clusters. What I need to know is, how can I interpret these results and how to evaluate the performance, since I do not have a class variable. Kindly give your input to understand this
Answer: The interpretation of your results depends on what you want to achieve. What do you cant to achieve by clustering your data? If you want to make predictions of house prices you should use regression models, as you already mentioned yourself.
In general, the performance of a clustering algorithm can be measured for instance by inter- and intra-cluster similarities, i.e. whether the points that belong to the same cluster are similar to each other and different to points in another cluster.


probability with two variables - Taking balls out of the basket

Question: There's 3 balls in the basket - White, red and black. Three people chose one ball after the other with return.
$X$ is the various colors that got chosen.
$Y$ is the number of people that chose white.
I need to calculate $P(X+Y≤3|X-Y≥1)$.
So I got that I need to start from that getting each ball is probability of $1/3$, since it's with return.
I'm getting confused with how Can I compute Y? Can I say it's sort of uniform distribution and maybe to try by that? Meaning, that the expected value is $(a-b)/2$?
Comment: You should not compute $Y$. It is a random number taking on the values $0,1,2,3$. And you can easily compute the probability of each of these 4 values.
Comment: 'various colors that got chosen' - do you mean a list of unique colors, e.g. (W) if everyone selected white?
Comment: @Alex I would assume it is the number of colors chosen at least once.
Answer: We can make a probability table of joint outcomes of $(X, Y)$.  Note $X \in \{1, 2, 3\}$, and $Y \in \{0, 1, 2, 3\}$.  For $X = 1$, there are only the three outcomes $$(w,w,w), (r,r,r), (b,b,b).$$  For $X = 2$, we have $\binom{3}{2}(2^3 - 2) = 18$ outcomes:
$$(r, r, w), (r, r, b), (r, w, r), (r, w, w), (r, b, r), (r, b, b), \\
  (w, r, r), (w, r, w), (w, w, r), (w, w, b), (w, b, w), (w, b, b), \\
  (b, r, r), (b, r, b), (b, w, w), (b, w, b), (b, b, r), (b, b, w).$$
For $X = 3$, we have $3! = 6$ outcomes, which are the permutations of $r, b, w$ in some order.  The total is $3^3 = 27$.
When $X = 1$, we have either $Y = 3$ with probability $1/3$ or $Y = 0$ with probability $2/3$.
When $X = 2$, we have $Y = 0$, $Y = 1$, $Y = 2$ each with probability $1/3$.
When $X = 3$, we have $Y = 1$ with probability $1$.
So we have
$$\begin{array}{c|cccc}
\Pr[X = x, Y = y] & 0 & 1 & 2 & 3 \\
\hline
1 & \frac{2}{27} & 0 & 0 & \frac{1}{27} \\
2 & \frac{2}{9} & \frac{2}{9} & \frac{2}{9} & 0 \\
3 & 0 & \frac{2}{9} & 0 & 0
\end{array}$$
The rest is simply conditioning.  Select those outcomes for which $X - Y \ge 1$, and among those, tabulate the probabilities for which $X + Y \le 3$.  then divide by the sum of the probabilities that you considered.
Comment: Thanks, That was very helpful. So if I got it right I should get $0.7$ in the end right?
Comment: @JustEquvilant Yes that is correct.
Answer: There's a total of $3^3$ ways of selecting 3 balls (all balls and all ppl are different).
Given that $X$ is at most $3$ and $Y$ is at most $3$, $X-Y \geq1$ can mean two cases:
$$
1)  X-Y=1
$$
if either 2 colors/1 white  (WR, WB) or 1 color/0 white (R,B) were chosen.
$$
2) X-Y=2
$$
if either 3 colors/one white (WRB) or 2 colors/0 white (RB). The difference can't be 3, because you can't have all 3 colors selected without selecting white.
For $X+Y$, you have 3 cases:
$$
1)X+Y=1
$$
if (R,B) were chosen
$$
2)X+Y=2
$$
if either one white (W) or (R,B) were chosen and
$$
3)X+Y=3
$$
if either (W,B) or (W,R) were chosen.
Can you put together these cases assuming all sampling was independent and withe replacement?


In how many ways can a board of five people that includes the male Head of School be formed if it must include at least two men and two women?

Question: An appointments board must consist of the Head of School and exactly 4 other
members of the School chosen from a group consisting of 3 men and 4 women. If
the overall board of 5 people must include at least 2 women and at least 2 men and
the Head of School is male, how many different makeups are possible?
I have attempted this question and I got 2 different makeups is possible- two men (including Head of School) & three women and three men (including Head of School) & two women? Could someone tell me if I'm correct or if I'm taking too simple an approach to this question?
Comment: People are distinguishable.
Comment: The groups that include Bob have different make-ups from those that do not.
Comment: But they have the same positions available to them so does it matter that they're distinguishable?
Answer:
I have attempted this question and I got 2 different makeups is possible- two men (including Head of School) & three women and three men (including Head of School) & two women? Could someone tell me if I'm correct or if I'm taking too simple an approach to this question?

You are correct so far.   However, remember that people are distinguishable objects.   Now count how many distinct ways there are to select those combinations from the head of school, 3 other men, and 4 women.


What does "Base key" mean?

Question: I have come across lyrics and chord sheets that show "Base key : (A, B, C etc)". What does it mean?

Passion
Planetshakers, Legacy
Base key: A

Intro
Fm   Ab/C   Db
Fm   Ab/C   Db   Ab

Verse
   Fm         Eb            Ab
This passion deep within my soul
Answer: I expect you're looking at this page:
https://www.psalmnote.com/song/passion-chords-planetshakers
The page has a transposition feature.  With 'A' selected at the top of the page, the song is shown in F minor/Ab major.   Press 'A#', it goes up a semitone into F# minor/A major.  And so on, for the other possible selections.  You can also use the Transpose Higher/Lower buttons.  Press them and see what happens.
The choice of 'A' as the 'base key' seems arbritary, unconnected with the actual key of the song.   They might just as well have labelled the buttons  '+1', '+2' etc.
Here's a song on the same site where, with 'C' as 'base key', the song actually IS in C, and therefore the 'base key' switch makes more sense.
https://www.psalmnote.com/song/dia-lahir-untuk-kami-chords-victor-hutabarat?is_randomize=1&is_praise=1&is_worship=0
Just a case of sloppy website design, I think.
Answer: Usually refers to the key the guitar is tuned to.
Standard guitar tuning is A (hence base A). But it can be tuned to any key - as far as I'm aware.
D is a very common key to tune a guitar to in rock music.
Comment: I think you've misunderstood  'Drop D' tuning, where just the bottom (E) string is tuned down to D.   It would be most unusual to tune EVERY string down - and certainly not as far down as a fifth, A down to D.  So downvote, I'm afraid.
Comment: 'Standard guitar tuning is A'  - what's that? And D isn't that common, and in any case, the guitar is probably not *tuned* to anything apart from standard, maybe Eb, or sometimes 'drop D'.

What does "Base key" mean?


Restricted mean residual life: Survival analysis: Discrete

Question: I am hoping someone can help with this - perhaps trivial question of interpreting the formula below. It is the mean residual lifetime (restricted to the window of data) for the case of discrete time.
Restricted Mean Residual Life

Remaining time until event or upper bound--whichever comes first

$$\mu_{[\gamma]}(t|\mathbf{x})=E\left(\min(T, t+\gamma+1)-t|T\ge t, \mathbf{x}\right)=\sum_{j=t}^{t+\gamma}\prod_{k=t}^{j}\left(1-h(k|\mathbf{x})\right)$$
My question is how do you interpret the sigma and product? $t$ is the current time (e.g. "5") and $\gamma$ is the upper bound from my understanding. How do you compute this?
Answer: $\left(1-h(k|\mathbf{x})\right)$ is the probability of surviving past date $k$ given you survived to the start of date $k$
$\prod_{k=t}^{j}\left(1-h(k|\mathbf{x})\right)$ is the probability of surviving past date $j$ given you survived to the start of date $t$.
Add up these latter probabilities and you get your remaining expectation restricted to the $\gamma+1$ dates starting from the start of date $t$.  I would draw a graph where the sum is represented by vertical rectangles, while the expectation can be seen as horizontal rectangles (sum of probabilities of surviving exactly that long multiplied by time survived), something like this
Comment: I think I understand @Henry. So, gamma here is max time minus t. So, if I have discrete time by month (up to 24) and we are at t=5, then $\gamma$ is 19. Any way you could post an example using the notation given in the question? I am not completely clear on it (with t and j being the same...)
Comment: It seems $t+\gamma+1$ is the maximum time [see $\min(T, t+\gamma+1)$ in your formula] while $t$ is the minimum time.  $t$ and $j$ are not the same: in the diagram $j$ is the horizontal axis and cannot take a value less than $t$.


How do I persist data in a local html file meme award webpage to allow the counter to persist permanently?

Question: I have recently made a website that uses basic javascript to make a counter (as well as html and CSS to make graphics) and now I want to include a component that allows the counter to go up even if the page is refreshed. This is a big project that will allow people to vote on memes in the free code camp earth facebook group and will prevent people from flooding the site with memes all the time - it's part of the Free code Camp Sunday Funnies community initiative.
Currently, when the page is refreshed, the counter goes back to zero.
Here is the context that is vital so that you can see how different my specific questions are than other ones!
Firstly, here is my code (again, all you need to do is post this in notepad, I prefer visual code editor because it autoformats):
#Fbanner1 {
  position: absolute;
  top: 0;
  right: 0%

  }
  #Fbanner2 {
      position: absolute;
      top: 0;
      left: 0%;

  }
    #banner {
       position: absolute;
      top: 0%;
       left:0%;

}

        #hook {
            font-family: 'VT323', monospace;
            font-size: 30px;
            text-align: center;
            font-variant: small-caps;
            border-style: double solid;
            border-color:black;
            background-color:blue;
            transform: translateX(425px);

        }
        h1 {
            font-family: 'Nova Mono', monospace;
            font-size: 50px;
            text-align: center;
            transform: translateX(-5px);
        }

        body {
            background-color: green;

        }

        section {
            display: flex;
            flex-direction: row;
        }

        #main {
            font-family: 'Nova Mono', monospace;
            display: flex;
            flex-direction: row;
            flex-wrap: wrap;
            justify-content: space-around;
            text-align: center;
            position: absolute;
            top: 8px;
            transform:translateY(45px);
        }

    </style>

        <title>Free Code Camp Sunday Meme Award</title>

!click to choose the meme of legend!

 Sunday Funnies Meme Award

 1st place

0

 Alert: dank meme found!

 2nd place

0

 Getting warmer....

 3rd place

0

 A small ripple effect...

 Honorable Mention

0

 Worth an eyebrow raise...

 Hononorable Mention

0

 Worth an eyebrow raise...

I have done intensive research on different ways to do this:
How to use local storage I
how to use local storage"> How to use local storage II
conflicting information on using cookies
Here is a similar method described in stack overflow, but I don't know how to apply it to my specific situation that involves a counter:
Stack overflow research
 confusing one about cookies in addition (or instead of?) using local storage)
Here is an example of using local storage and an example that works! (see below, but you will have to copy and paste the info into notepad)
step-by-step example
MDN local storage instruction doe snot make sense in this context:
 MDN
Now that you have the context above, also how this is dealing with a counter variable and not a bunch of numbers, and
I thought this is what I would do but I do not know how to set the item when it starts at zero and will change in the future. Here is the code, as described step by step, by Tod Motto:
   <textarea class="localstorage"></textarea>
    <button class="clear">Clear localStorage</button>
    <button class="empty">Empty localStorage</button>

SKIP TO HERE IF YOU WANT TO SEE THE BRIEF VERSION OF THE EXPLANATION TO  THE QUESTION
I understand that I need to set and get info and I assume that this info would be the counter, but
A. I dont know if that is possible (if I need to use cookies also); there is mixed reviews online about the different methods...
B. If I need to use WAMP (I am not asking how to use WAMP, just if I do...based on my research it seems like this is not neccesary)
C.If I can do this with a counter (maybe I cannot...and in that case anyone that is working with a popular meme site probably would like to know also to not try and do this)
D. Just as important, what do I set in situations like this with a counter (I am trying to build my skill base by doing projects, so I can use up less of your time.
My own example would be something like this:
localstorage.setitem(0, ++)
(I assume this because you are adding a value each time..also this is a snip it out of context but hopefully can be inserted in the Tod Mottos code above.
Comment: the MDN website for local storage is not showing up as a link and I do not know why so here is the link: https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage       This comment helps clarify my links above.
Comment: You should clean up the code block and only show the parts relevant to the question. (ie the javascript). Most people would just tldr
Comment: I've made it bold so you can look at what is relevant and skim over what is not, as I know everyone is very busy already. All the info is needed in the context, otherwise I am told that I am not being specific enough.
Answer: If the data you want to save has to be shared between users of the site then it isn't possible without some type of server-side technology. Easiest to learn and set up would probably be PHP (although I dislike it). There are other options too but set up and learning the language might be hard.
IF the counter data is unique to each user you can use either cookies or localstorage but it can easily be tampered with by the user. Cookie data is simpler to set and get and can be easily done with the following code:
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

The code above is from here where you can learn more about cookies.
Comment: Exactly this. If you want all users to see the exact same counter with its count shared amongst all user, you would need to use a server side programming language and store the count in some database. If not, you can use the localStorage.
Comment: Would you reccomend using a local developer environment such as WAMP?  and then I would be able to use cookies?
Comment: Here is the link for WAMP so you can have more info: http://www.wampserver.com/ (more context of what I am possibly gonna work with)
Comment: Wamp is a web server that can do stuff like compile PHP but cookies is something that is built into browsers so you can use cookies without WAMP or any web server. Personally if I was doing a small site like this I wouldn't use Wamp and access just via file if I didn't have access to a server side technology.


Random Background Music Loop PHP

Question: on a particular website I currently have a script that randomises the background music that is played each time the website is accessed. It grabs the file randomly from a sound folder and plays. Everything works great.
PHP
$songs = glob('snd/*.*');

HTML
<embed src="swf/player.swf" id="radioplayer" name="radioplayer" quality="medium" allowScriptAccess="always" width="1" height="1" type="application/x-shockwave-flash" FlashVars="file=<?php echo $song; ?>&volume=10&start=0&duration=0&autostart=true&controlbar=none&dock=false&icons=false&loop=1">

However, I would like to expand this a little more.
It is used as a loading screen for a gameserver which requires custom files to be downloaded to the client. Once the song finishes, it's just silence. I'm wondering: is it possible that when the song is finished a new song is selected randomly, like how it was the first time, and then played? The only thing is, even though I want the selection to be random I do not want it to play the song that was just played.
Hopefully this is possible and thanks in advance.
Note
It uses a flash player to play the songs, as you can see. If this is not a viable method of playing the songs with my request above I'm welcome to alternative methods, provided I can control the volume of the audio that plays.
Edit
To try and kill two birds with one stone, the webpage's background image also changes depending on which map the server is currently using. I do not have images for each map I add as I add more all the time, would it be possible to set the background to a default image instead of it just being blank?
Comment: Use a different flash player that supports playlist?
Answer: Im doing this in javacript, you could just add the song as a string creating the Audio object!
    Example
 var titleTheme = new Audio("PUT_RANDOM_SONG_HERE");

Real World
The magic and what you are looking for is to add an event listener too the event "ended".
var titleTheme = new Audio("AUDIO/tmnt.mp3");

//Start up with this
titleTheme.play();

// Events _________________________________________________
// BIND TITLE THEME ENDED
titleTheme.addEventListener('ended',endings);
function endings()
{
 titleTheme.play();
}

Things to know, not all browsers play all the fileformats. So you will have to be able to supply audio as per browser.
Comment: @JakeGriffin You said you could take an alternative solution, the one I provided is in javascript. Ok so what i do first is I create an Audio in this case titleTheme the object I feed this just like you feed the flash player with a song(path_to_one). Then I use the play method which the audio object has. The music will start to play, next thing is that I set an eventlistener to the titletheme object which listens for when the song has ended. this will start the song all over again, using the play method that the object has.
Comment: Could you elaborate a little more here?
Comment: @JakeGriffin okay I have added an example! remember I did my implentation in javascript. As an alternative method. Got it? Added the eventbinding thing also.
Comment: I apologise but I don't quite follow. I am not that knowledgeable on the subject. (Sorry to sound like an idiot.)
Comment: @Chris The only thing is when the first song finishes it plays the same song when it ends - I want it to randomly choose another song to play when it's done, is that possible?
Comment: @Chris Yes you could load an array with your songs fill the array with your audio objects. Inside the function that goes of when the songs ends, create a random number not higher than your arraylength. Then load that.

Random Background Music Loop PHP


Gerar uma unica página com todos os registro

Question: Tenho uma consulta que me retorna uma lista com objetos. Dessa lista, eu percorro cada posição, defino alguns parâmetros do objetos e retorno para uma view.
O que estou tentando fazer é:
Percorrer todas posições dessa lista e gerar uma unica view. Porém, o acontece é que quando executo o método, minha view só carrega o primeiro objeto da lista.
<code> public async Task<IHttpActionResult> Get(string cnpj, int numero, string chave)
     {
         var notaDb = await DbContext.GetNotaAsync(cnpj, numero, chave);

         var notas = DbContext.ObterTodasNotas(notaDb.Prestador.Id);

         var items = new List<NotaFiscalViewModel>();

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

         foreach (var nota_ in notas)
         {
              var nota = await GetNotaAsync(nota_);
             var cidade = await DbContext.GetMunicipioNomeAsync(notaDb.CodigoTributacaoMunicipio);
             nota.CodigoTributacaoMunicipio = cidade.Descricao + " - " + cidade.Estado.UF;

             var prefeitura = await DbContext.GetPrefeituraAsync();
             nota.Imagem = prefeitura.Imagem;
             nota.Prefeitura = await ContribuinteController.GetContribuinteViewModelAsync(prefeitura);
             var cnpjPrefeitura = await DbContext.GetConfiguracaoAsync();
             nota.Prefeitura.CpfCnpj = cnpjPrefeitura.CnpjPrefeitura;

             return Ok<NotaFiscalViewModel>(nota);
         }
         return Ok();
    }
</code>
Answer: Acredito que deseje retornar a lista de todas notas alteras, sendo assim, pode fazer da seguinte forma:
<code>public async Task<IHttpActionResult> Get(string cnpj, int numero, string chave)
{
     var notaDb = await DbContext.GetNotaAsync(cnpj, numero, chave);

     var notas = DbContext.ObterTodasNotas(notaDb.Prestador.Id);

     var items = new List<NotaFiscalViewModel>();

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

     //Lista de notas
     List<NotaFiscalViewModel> viewModels = new List<NotaFiscalViewModel>();

     foreach (var nota_ in notas)
     {
          var nota = await GetNotaAsync(nota_);
         var cidade = await DbContext.GetMunicipioNomeAsync(notaDb.CodigoTributacaoMunicipio);
         nota.CodigoTributacaoMunicipio = cidade.Descricao + " - " + cidade.Estado.UF;

         var prefeitura = await DbContext.GetPrefeituraAsync();
         nota.Imagem = prefeitura.Imagem;
         nota.Prefeitura = await ContribuinteController.GetContribuinteViewModelAsync(prefeitura);
         var cnpjPrefeitura = await DbContext.GetConfiguracaoAsync();
         nota.Prefeitura.CpfCnpj = cnpjPrefeitura.CnpjPrefeitura;

        //Adiciona notas na lista
         viewModels.Add(nota);
     }
     //Retorna todas notas com as cinfigurações efetuadas
     return Ok<List<NotaFiscalViewModel>>(viewModels);
}
</code>
Comment: Opa, cheguei a corrigir isso. Porém, ele só retorna o ultimo item da lista.
Comment: E pra vc passar 'nota' fora do foreach, precisa declara-lo antes. Dessa forma que está seu método jamais vai compilar.
Comment: @ViniciusMatos verdade, não prestei atenção nisso; você deseja retornar a lista de notas?


[Android]How to get item number(position) from a String[]

Question: I have a String[] that contains number of strings, what I'm trying to do is set a ProgressBar's progress according to which string is used.
For example, I have already determined number of strings and set max progress of progress bar accordingly; here is the list:
 "zero one two three four five six seven eight nine...."

..
 String[] cpu0freqslist = cpu0freqs.split("\\s");
 countcpu0 = cpu0freqslist.length;

..
 ProgressBar cpu0progbar = (ProgressBar)findViewById(R.id.progressBar1);
 cpu0progbar.setMax(countcpu0);

But now I need to set the progress of progressbar according to the item that is used, and I don't know how to get item position.
So if I want to set a progress bar to the position of item five (in this case it would be 6) how can I do that - how can I get the position of item five?
Comment: The "cpu0freqslist" variable is an array. So you can simple access that array with "cpu0freqslist[4]" for the fifth element.
Answer: essentially what you're looking for is a indexOf(...) ...
since arrays don't have it, you'll have to search thru it to find the desired string. so something like this (feel free to optimize)
 public int indexOfString(String searchString, String[] domain)
 {
     for(int i = 0; i < domain.length; i++)
        if(searchString.equals(domain[i]))
           return i;

     return -1;
 }

Then again, if you dynamically fetch your String[] data, it would be wiser to use an ArrayList and just invoke list.indexOf(myString);
Answer: You can use the Arrays utility class:
List<String> list = Arrays.asList(new String[] {"First", "Second", "Third"});
int index = list.indexOf("Second"); // 1

Answer: cpu0freqslist[5]
Does this help you?
Answer: Ok let me break your query into parts...
String[] arr = {"First","Second","Third"};   // String array with 3 elements

for(int i=0 ; i<arr.length ; i++){

    int j = i ;                          // Position of the element

    String s = a[i] ;                    // Element Itself

   System.out.println("The "+i+" element is  "+s);

  }


When is the preimage a sub manifold?

Question: I am working on the following exercise : we consider the function $f(x, y) = 2x^3 - 5xy + 3y^2$ from $\Bbb R^2$ to $\Bbb R$ and would like to find the values $c \in \Bbb R$ such that the set $f^{-1}(c)$ is a submanifold of $\Bbb R^2$.
I have only one theorem in my lecture notes about that and it tells :

Let  $f : U \subset \Bbb R^m \to \Bbb R^n$ a $C^k$ function
of constant rank $=r$ then for each point $q \in \Bbb R^n$, the preimage
$M = f ^{-1}(q) \subset U$ is a differentiable submanifold
of dimension $m - r$.

The solution of the exercise uses the following result : if $f : U \subset \Bbb R^n \to \Bbb R$ is $C^k$ and if $df_p \neq 0$ for all $p$ such that $f(p) = c$, then $f^{−1}(c)$ is a $C^1$ submanifold. To me, that is not the same theorem we stated. In fact the function $f$ is not of constant rank on the whole $\Bbb R^2$, there are a couple of points where the gradient is $0$ so we cannot use the theorem. So the result they are using is something different, it is a corollary from the theorem ? Did I misunderstand the theorem ?
Comment: What I think is that since $df_p$ is continuous, we can find an open set $U_p$ around $p \in f^{-1}(c)$ such that the gradient is not $0$. Then by taking $X=\bigcup_{p \in f^{-1}(c)} U_p$ we can now use the theorem on $f:X \to \Bbb R$
Answer: Define a family of subsets of $\mathbb R^2$, given by
$$M_c:=\{(x,y)\in\mathbb R^2 | f(x,y)=c\}.$$
We want to find the values of $c$ such that $M_c$ defines a submanifold of $\mathbb R^2$.
First, we have to find the regular values of the smooth map $f:\mathbb R^2\to\mathbb R$, where $f(x,y)=2x^3-5xy+3y^2$ (observe that $x,y$ are the global coordinates of the real plane).
A regular value is a point $q\in f(\mathbb R^2)$ such that $\forall p\in f^{-1}(\{q\})$, the map $f_{*p}:T_p\mathbb R^2\to T_{f(p)}\mathbb R$ is surjective.
The differential map $f_{*p}$ is linear and its matrix representation is given by $$\nabla f(x,y)\vert_p=(6x^2-5y,-5x+6y)\vert _p$$
whose rank is less than one iff $\begin{cases}6x^2-5y=0\\-5x+6y=0 \end{cases}\iff \begin{cases}6x^2-5y=0\\ x=(6/5)y\end{cases}\iff 6(6y/5)^2-5y=0$.
Now you can find the solutions for the system to see for which $c\in\mathbb R$, the set $M_c$ is a $2-1$-dimensional submanifold of $\mathbb R^2$.

When is the preimage a sub manifold?


Poisson Distribution: P(exceeds certain number)

Question: A professor plans to schedule an open lab in order to provide answers and additional
help to students in the hour before homework is due. The number of students who will
come to open lab will vary from week to week, and the professor assumes the count in
a particular week will follow a Poisson(15) distribution.
The professor is offered a room for the open lab, but is concerned that the room
capacity of 23 won't be sufficient. Compute the probability that the number of
students who come to open lab in a particular week will exceed the room capacity.

I get that λ=15, but how do you find P(X > 23)? Would it be 1-P(0 < X ≤ 23)? That would take ages to calculate...
Answer: Depending on what you have learned in class so far, your professor may want you to consider
1) Writing a program to sum up $p=\sum_{k=0}^{23} P(X=k)$ and then to compute $1-p$.
2) Noting that for $\lambda$ large, $\mathrm{Poisson}(\lambda) \approx N(\lambda,\lambda)$, i.e. you can use a normal approximation to your Poisson.
Comment: @wad11656: you can directly use $1-ppois(23,15)$ in R.
Comment: They recommend we use the program "R" in the class. If I wrote a program for your notation in 1), that would give me the probability of the number of students NOT exceeding the room capacity, correct? So would I then do 1-(result)?
Comment: Thank you, gents. I haven't been using R the whole semester, but this is a situation where I really needed a program to do the calculations. Cheers!
Answer: Hint
Since $\lambda>10$, you can approximate using Normal distribution, $N(\mu, \sigma^2)$ with $\mu=\lambda$ and $\sigma^2=\lambda$
Using this information, we need to find $\Pr(X>23)=1-\Pr(X\le 23).$ We can convert this to standard normal and then look it up on the standard normal distribution table. We have
$$Z=\frac{X-\mu}{\sigma}=\frac{23-15}{\sqrt{15}}=\frac{8}{\sqrt{15}}=2.07$$
Now, you need to find $1-\Pr(Z<2.07)$
Comment: This has already been pointed out in the answer below. Unless you add more context, I shall regretfully downvote this answer.
Comment: @voldemort Added more context.
Comment: Downvote retracted with pleasure.


NSURLConnection error 1100 while running ionic app on iOS

Question: I have build an app with ionic 4 and cordova. On android the app runs like a charm but on iOS I just get some strange problems... like others do (Ionic IOS app NSURLConnection error 1100, ionic 4 app shows white screen on ios with error code 1100).
The app ionic build runs fine without any errors and just a few warnings of unused imports. Also the xcode build is fast and successfull. But when the app is running on a real device or simulator, I just get a blank white screen. In the console I get this with addional debugging:
I found like mentioned some similar issues and also added the environment variable (CFNETWORK_DIAGNOSTICS = 1) for advanced network logging to get more infos in the console (whole file: https://pastebin.com/yecJ5Vzy) or some snippets here:
2019-05-03 10:59:49.788736+0200 MyNiceApp[3426:1312031] CFNetwork Diagnostics [1:1] 10:59:49.787 {
DiskCookieStorage Construction: Binary{ Disk Cookies: { /private/var/mobile/Containers/Data/Application/23CCB045-0976-4DD0-A19B-0BD8CB6825FD/Library/Cookies/Cookies.binarycookies, <0 cookies in 0 domains> clean not writing } }
                     Accessing: <CFURL 0x282db3c60 [0x1bda5d610]>{string = file:///private/var/mobile/Containers/Data/Application/13371337-0976-4DD0-A19B-0BD8CXYZAS/Library/Cookies/Cookies.binarycookies, encoding = 13371337, base = (null)}
                          Path: /private/var/mobile/Containers/Data/Application/13371337-0976-4DD0-A19B-0BD8CXYZAS/Library/Cookies/Cookies.binarycookies
                Read from disk: <0 cookies in 0 domains>
                         Dirty: NO
                       Writing: NO
                        Policy: 0
} [1:1]
2019-05-03 10:59:49.788845+0200 MyNiceApp[3426:1312031] CFNetwork Diagnostics [1:2] 10:59:49.788 {
DiskCookieStorage Journaling On: Binary{ Disk Cookies: { /private/var/mobile/Containers/Data/Application/13371337-0976-4DD0-A19B-0BD8CXYZAS/Library/Cookies/Cookies.binarycookies, <0 cookies in 0 domains> clean not writing } }
                           File: <CFURL 0x282db3c60 [0x1bda5d610]>{string = file:///private/var/mobile/Containers/Data/Application/13371337-0976-4DD0-A19B-0BD8CXYZAS/Library/Cookies/Cookies.binarycookies, encoding = 13371337, base = (null)}
} [1:2]
2019-05-03 10:59:49.879254+0200 MyNiceApp[3426:1312031] Apache Cordova native platform version 5.0.0 is starting.
2019-05-03 10:59:49.879772+0200 MyNiceApp[3426:1312031] Multi-tasking -> Device: YES, App: YES
2019-05-03 10:59:49.901704+0200 MyNiceApp[3426:1312031] Using UIWebView
2019-05-03 10:59:49.904145+0200 MyNiceApp[3426:1312031] [CDVTimer][console] 0.041008ms
2019-05-03 10:59:49.904228+0200 MyNiceApp[3426:1312031] [CDVTimer][handleopenurl] 0.049949ms
2019-05-03 10:59:49.905236+0200 MyNiceApp[3426:1312031] Unlimited access to network resources
2019-05-03 10:59:49.905271+0200 MyNiceApp[3426:1312031] [CDVTimer][intentandnavigationfilter] 1.001954ms
2019-05-03 10:59:49.905338+0200 MyNiceApp[3426:1312031] [CDVTimer][gesturehandler] 0.050068ms
2019-05-03 10:59:49.905379+0200 MyNiceApp[3426:1312031] [CDVTimer][backgroundfetch] 0.025034ms
2019-05-03 10:59:49.905397+0200 MyNiceApp[3426:1312031] [CDVTimer][TotalPluginStartup] 1.327991ms
2019-05-03 10:59:50.139954+0200 MyNiceApp[3426:1312031] Resetting plugins due to page load.
2019-05-03 10:59:50.158278+0200 MyNiceApp[3426:1312115] CFNetwork Diagnostics [1:3] 10:59:50.158 {
LoaderWhatToDo: (null)
       Request: <CFURL 0x282db7c00 [0x1bda5d610]>{string = file:///var/containers/Bundle/Application/13371337-0976-4DD0-A19B-0BD8CXYZAS/MyNiceApp.app/www/index.html, encoding = 13371337, base = (null)}
   CachePolicy: 0
      WhatToDo: originload
   CreateToNow: 0.00069s
} [1:3]
2019-05-03 10:59:50.161705+0200 MyNiceApp[3426:1312031] Failed to load webpage with error: The operation couldn't be completed. (NSURLErrorDomain error -999.)
2019-05-03 10:59:50.162212+0200 MyNiceApp[3426:1312031] Resetting plugins due to page load.
2019-05-03 10:59:50.162894+0200 MyNiceApp[3426:1312115] CFNetwork Diagnostics [1:4] 10:59:50.162 {
LoaderWhatToDo: (null)
       Request: <CFURL 0x282d94060 [0x1bda5d610]>{string = file:///var/containers/Bundle/Application/13371337-0976-4DD0-A19B-0BD8CXYZAS/MyNiceApp.app/www/index.html, encoding = 13371337, base = (null)}
   CachePolicy: 0
      WhatToDo: originload
   CreateToNow: 0.00030s
} [1:4]

And a bit later in the console log:
2019-05-03 10:59:50.278000+0200 MyNiceApp[3426:1312114] NSURLConnection finished with error - code -1100
2019-05-03 10:59:50.278024+0200 MyNiceApp[3426:1312114] NSURLConnection finished with error - code -1100

It seems like the app can't load its own files.. since the error -1100 means NSURLErrorFileDoesNotExist
Answer: Had the same issue and after quite a bit struggle and R&D this is what worked for me.
Seems like relative path is taken by IOS so in your src -> index.html please change this
base href="/"
to
base href="./" (note dot at the beginning of the /)
this will load all the relevant js files (cordova.js, polyfill.js etc.)
the 1100 errors are files not being found due to absolute path.
Comment: This worked for me, it fixed the issue, however it brought some weird behaviour such as images not being found and app name for plugins with permissions
Comment: Icons and images are not loaded correctly :/ @JoseGeorges did you found a solution?
Comment: @JanMoritz I rebuilt the app with Flutter
Answer: After researching a lot a trying a lot of stuff, my solution was to execute this command:
ionic cordova plugin add cordova-plugin-ionic-webview --save
Comment: This one here does solve the issue as well, however for people using location services it will break those for them. from experience


pound conf file location osx brew

Question: Where is the pound configuration file location on os x when installed from brew?
I have been looking at /
find / -name "pound.cfg" * 2>/dev/null
Found nothing
Thanks
Answer: I found out mysql after all
/usr/local/etc/pound.cfg

pound conf file location osx brew


Fórmula para retornar a data apenas com dias úteis

Question: Existe alguma fórmula que eu possa utilizar para a célula retornar a data correspondente ao prazo?
Se insiro a data 03/01/2020 na célula, queria que outra célula ao lado retornasse a data com o cálculo de 5 dias úteis.
Seria assim:
03/01/2020
A célula ao lado retornaria 10/01/2020 automaticamente considerando apenas dias úteis.
Posto que já tipifiquei as células como data, uma simples soma resolveria o caso. Supondo que o valor de A1 é 03/01/2020
<code>=A1+5
</code>
Ele me retorna 08/01/2020 quando na verdade deveria ser 10/01/2020. O problema é que ele não considera apenas os dias úteis.
Comment: @KALIBBAN: creio que você confundiu a função DIATRABALHOTOTAL com a função DIATRABALHO.
Comment: Posta o código que você já tentou fazer,e você já deu uma olhada nisso https://pt.stackoverflow.com/questions/23537/f%c3%b3rmula-para-calcular-intervalos-num%c3%a9ricos-no-excel?rq=1 ?
Comment: Não entendi como a fórmula `SE` poderia ajudar neste caso. Mesmo se aplicasse condições, não retornaria a data.
Comment: Então poste a parte do código que você esta com problemas
Comment: Pronto, Kalibban, inseri minha tentativa fracassada.
Comment: De fato ele ira te retornar 08/01/2020 pelo fato de você estar fazendo uma soma.
Comment: Exatamente, eu queria saber se há alguma forma de configurar a contagem apenas com os dias úteis, mas não deve existir, eu acho.
Comment: A função DIATRABALHO faz exatamente isso. https://support.office.com/pt-br/article/diatrabalho-fun%C3%A7%C3%A3o-diatrabalho-f764a5b7-05fc-4494-9486-60d494efbf33
Comment: @anonimo a função DIATRABALHO precisa ser passado as 2 datas como parâmetro,e pelo que eu entendi ele vai dar a entrada numa data qualquer e informar 5 dias,para que a partir dai ocorra o retorno da data contabilizando 5 dias uteis.
Comment: @anonimo realmente eu confundi,mas mesmo assim ambas precisam ter 2 datas como parâmetro,e o que ele esta tentando fazer e passar uma data e uma quantidade de dias.
Answer: Cheguei a solução atraves da função

DIATRABALHO.INTL

Você passa os parâmetros para a função e ela te trara a data corretamente
<code>=TEXTO(DIATRABALHO.INTL(DATA(2020;1;3);5;1);"dd/m/aaaa")
</code>
Utilizei a data 03/01/2020 como base de parâmetro e ele me retornou a data 10/01/2020
Usei essa fonte de pesquisa https://www.tudoexcel.com.br/planilhas/funcao-diatrabalho-intl-do-excel-3784.html
Comment: Se: `A1 = 03/01/2020`, `A2 = 5` e em C1 tenho o feriado 20/01/2020, a fórmula: `=DIATRABALHO(A1;A2;C1)` dará como resultado: `10/01/2010`.
Se: `A1 = 16/01/2020`, `A2 = 5` e em C1 tenho o feriado 20/01/2020, a fórmula: `=DIATRABALHO(A1;A2;C1)` dará como resultado: `24/01/2010`.
Considerando os fins de semana como sendo sábados e domingos não há necessidade de utilizar a função `DIATRABALHO.INTL`.
Comment: @anonimo dessa forma você obriga a pessoa a informar uma data para feriado em C1,isso tambem e possivel com a função `DIATRABALHO.INTL`,onde ele so precisa informar a data inicial e tendo a opção de calcular feriados ou fins de semana,então eu acho válido utiliza-la.


Prove that $A$ is a compact subset of $M_3(\Bbb R) \cong \Bbb R^9$.

Question: Consider the set $A ⊂ M_3(\Bbb R)$ of $3 × 3$ real matrices with characteristic polynomial
$x^3 − 3x^2 + 2x − 1$.  Then $A$ is a compact subset of $M_3(\Bbb R) \cong \Bbb R^9$.
Now this polynomial is irreducible over rationals and it is equivalent to the companion matrix $$
    \begin{pmatrix}
    0 & 0 & 1 \\
    1& 0 & -2 \\
    0 & 1 & 3 \\
    \end{pmatrix}.
$$
Now am I missing any important theorems or details?
Comment: Could you please tell what metric you are using? The answer heavily depends on that.
Answer: The statement is false. If $m\in\mathbb N$, then the characteristic polynomial of the matrix$$\begin{bmatrix}0&0&m\\\frac1{m^2}&0&-\frac2m\\0&m&3\end{bmatrix}$$is also $x^3-3x^2+2x-1$. Therefore, your set is unbounded. In particular, it is not compact.
Comment: Sure. But it is clear that the metric here is $d\left((a_{ij})_{1\leqslant i,j\leqslant3},(b_{ij})_{1\leqslant i,j\leqslant3})\right)=\sqrt{\sum_{i,j=1}^3a_{i,j}^2}.$
Comment: Well, the 'bounded' part depends on the metric.
Answer: Let $B$ be your matrix and $V_t=\operatorname{diag}\{ t,1,1\}$.
Then $V_t B V_t^{-1}= \begin{bmatrix}0 & 0 & t \\
{1 \over t} & 0 & -2 \\ 0 & 1 & 3\end{bmatrix} \in A$ for all $t \neq 0$.


Prove the Series Converges or Diverges: $\sum_{n=1}^\infty \frac{5+2n}{(1+2n^2)^2}$

Question: $$\sum_{n=1}^\infty \frac{5+2n}{(1+2n^2)^2}$$
How would I even do this to find if this converges or diverges? I tried doing the Telescoping series test but it just got really confusing.
I got as far as this using partial fraction decomposition:
$$\sum_{n=1}^\infty \frac{5}{1+n^2} + \frac{2n-5n^2}{(1+2n^2)^2}$$
$$Sequence: (\frac{5}{2}-\frac{1}{3}),(1-\frac{16}{81}),(\frac{1}{2}
-\frac{29}{361}),...$$
I could really use some step by step instructions on how to do this one. Nothing seems to cancel out at all so I felt like I did it wrong. Did I even pick the right test to do it? This was on a quiz I took today so a thorough explanation wouldn't get me any points.
Answer: You may observe that, as $n \to \infty$,
$$
\frac{5+2n}{(1+2n^2)^2} \sim \frac{1}{2n^3}
$$ then use the comparison test.
Comment: @England The numerator is equivalent to $2n$ ($5$ becomes negligible compared to $2n$ when $n\rightarrow\infty$) The denominator is equivalent to $(2n^2)^2$
Comment: @England You have, as $n$ tends to $\infty$, $$ \frac{5+2n}{(1+2n^2)^2}\sim \frac{2n}{(2n^2)^2}=\frac{1}{2n^3}$$
Comment: So as a rule of thumb you can ignore the number being added to the 2n (or a variation of it) as long as it doesn't have an exponent or anything?
Comment: @England Exactely!
Comment: @England It's not just a rule of thumb. There are ways to formalize it and it makes dealing with sequences and series much easier.
Comment: @OlivierOloa Thank you for the help!
Comment: How did you choose the $$\frac{1}{n^3}$$?
Comment: @Farnight Thanks for the help!
Answer: We have $$\sum_{n\geq1}\frac{5+2n}{\left(1+2n^{2}\right)^{2}}\leq\frac{5}{4}\sum_{n\geq1}\frac{1}{n^{4}}+\frac{1}{2}\sum_{n\geq1}\frac{1}{n^{3}}=\frac{5}{4}\zeta\left(4\right)+\frac{1}{2}\zeta\left(3\right)\approx1.9534.
 $$
Comment: @wallyk It's the Riemann Zeta function http://mathworld.wolfram.com/RiemannZetaFunction.html
Comment: Solid answer!  +1 ...
Comment: What does the symbol `ζ` mean?
Answer: $g(n)=(5+2n)/(1+2n^2)^2=n^{-3}(2+5n^{-1})/(2+n^{-2})^2=n^{-3}f(n)$  where $\lim_{n\to \infty}f(n)=1/2$. So for all sufficiently large $n$ we have  $0<g(n)<n^{-3}$. There are many ways to show that $\sum_nn^{-s}$ converges for $s>1$ : e.g. Integral test, or Cauchy condensation test. And so $\sum_ng(n)$ converges by the comparison test.


Exchange Server with DC questions

Question: I have a Windows Server 2003 (no Service Packs installed). It functions as a DC but has also an older Exchange Server installed.
I've set up a Windows Server 2008 R2 in hyper-v to move the DC to that new server (transitioning).
I know it is not good but Exchange Server 2010 will also be installed on that new 2008 R2 server.
I've already run the adprep.exe commands on the Windows Server 2003.
My question now:
Should Exchange Server 2010 be installed first on the new 2008 R2 before I run dcpromo or is it better to install that Exhange Server after making the 2008 R2 server a DC?
(+ do you have some good resources on how to migrate Exchange Server 2003(?) to Exchange Server 2010?)
Answer: Microsoft supports, but doesn't recommends installing Exchange 2010 on DC. Follow this article to migrate AD and this to migrate Exchange.
Answer: You should never install Exchange server on a DC. Since you are already in the process of using Hyper-V, there is absolutely no excuse for not installing Exchange into its own VM.
Comment: I'll disagree.  I agree you don't WANT to install Exchange on a DC if you have the choice, but it IS a supported configuration.  You should understand that doing so can cause lengthy shutdown times, among other issues, but again, Exchange on a DC *IS* a supported configuration.  And there is absolutely an excuse - $$$ - as juFo pointed out, you would need an extra server license which is not cheap.
Comment: the current hyper-v host doesn't have any more room for another Hyper-V, there is no budget for extra hardware and server licenses atm.

Exchange Server with DC questions


blow up time for function $G(t)$

Question: given
$G:[0,\infty)\rightarrow \mathbb R$
$$
G'(t)\geq -\lambda G(t)+ f(G(t))
$$
where $\lambda >0$ and $f$ is a convex function. $G(0)>0$ is also given.
Show that $G$ blows up at finite time $t>0$.
I can see that in case of $f(x)=x^p$ for $p>1$.  Please help me in generalizing it to any convex function.
Answer: First of all, $G(0)>0$ is not enough to guarantee finite time blow up. If $G(u)=u^p$, $p>1$, you need $G(0)>\lambda^{1/(p-1)}$.
Secondly, convexity does not guarantee blow up in finite time. Consider $G(u)=u\log(1+u)$. It is convex, but all solutions are global.
Comment: Sir , Can you help me with this problem . http://math.stackexchange.com/questions/1144091/second-variation-of-the-domain-functionals . I will remove this comment after some time. I would be glad if i could get your attention.

blow up time for function $G(t)$


Command Line Argument adding an extra parameter

Question: I am trying to explore command line argument in C++ in Visual Studio 2010. It is working fine but it is adding one extra parameter at args[0] any reason why?
Here is the snapshot of how I am setting my arguments

the main method is as follows
int main(int argc, char *argv[])
{
    cout<< endl << "total args passed in the command line - " << argc << endl;
    for(int i = 0; i < argc; i++){
    cout << i+1<< " argument  - " << argv[i] << endl;
    }

return 0;
}

The output on cmd is looking like this

As you can see that I am adding only two arguments but it is showing the count as 3.
Comment: _"enter image description here"_ is an instruction; please follow it.
Answer: The first entry in the list is the program name; that's how it's designed to work.
Answer: args[0] contains the name of your program and argc includes this in the count aswell.
If you would like to exclude this, try this:
int main(int argc, char *argv[])
{
    cout<< endl << "total args passed in the command line - " << argc - 1 << endl;
    for(int i = 1; i < argc; i++){
        cout << i << " argument  - " << argv[i] << endl;
    }

    return 0;
}


set slope to 1 in linear regression in r

Question: In R, lm(y~x) will get the linear regression in terms of y=a+bx, giving the estimates of both slope and intercept. Now I want to set the slope to 1, and do the regression, which means the form of the regression should be y=a+x (since b is forced to be one), and the estimate of intercept will be generated. How can I achieve that in R? And how can I compare the regression of the slope 1 with regression of the estimated slope b?
Comment: Questions solely about 'how to do ____ in R' are off topic here. However, note that if you look at the documentation [?lm](https://stat.ethz.ch/R-manual/R-devel/library/stats/html/lm.html), you will see there is an `offset` argument which will do what you want.
Answer: Assuming $b=1$ then,
$$y=a+x \rightarrow (y-x)=a$$
then $\hat a=mean(y-x)$
For comparing you can compare residuals.
maybe it is useful : http://stattrek.com/regression/slope-test.aspx?Tutorial=AP


Number of partitions of a set into even classes

Question: Suppose I have a set containing $n$ elements and I consider the number of partitions of it in which all the constituent classes are even. I let $R_n$ denote this number ($R_0=1$) and proceed as follows to obtain the exponential generating function for $R_n$.
Since $$R_n=\sum_{k=1}^{\lfloor n/2\rfloor}(\text{No. of such partitions where n lies in a class containing 2k elements})$$ so $R_n=\sum_{k=1}^{\lfloor n/2\rfloor}\binom{n-1}{2k-1}R_{n-2k}$. Now let $r(x)$ be the exponential generating function of $R_n$. Then
$\begin{align}r'(x)&=\sum_{n=1}^\infty\frac{R_nx^{n-1}}{(n-1)!}\\&=\sum_{n=1}^\infty\sum_{k=1}^{\lfloor n/2\rfloor}\frac{R_{n-2k}x^{n-1}}{(n-2k)!(2k-1)!}\\&=\sum_{k=1}^\infty\sum_{n=2k}^\infty \frac{R_{n-2k}x^{n-1}}{(n-2k)!(2k-1)!}\\&=\sum_{k=1}^\infty\frac{x^{2k-1}}{(2k-1)!}\sum_{n=2k}^\infty \frac{x^{n-2k}R_{n-2k}}{(n-2k)!}\\&=\sum_{k=1}^\infty\frac{x^{2k-1}}{(2k-1)!}\sum_{n=0}^\infty \frac{x^nR_n}{n!}\\&=r(x)\sum_{k=1}^\infty \frac{x^{2k-1}}{(2k-1)!}\end{align}$.
This shows that $r'(x)=r(x)\sinh x$. This differential equation has the solution $r(x)=e^{\cosh x+c}$. The boundary condition yields $r(x)=e^{\cosh x}$.
My doubt is that in my book the answer is provided as $r(x)=e^{\cosh x-1}$. I simply want to know whether it is a misprint in the book or if I am wrong, where have I gone wrong.
The reference cited is : Alfred Renyi, New methods and results in combinatorial analysis, I, II,
MTA III. Osztaly Kozlemenyei, 16(1966), 77-105, 159-177. English summary
on p.177 (paper is in Hungarian), note esp. pp.78-91. I do not have access to it.
Answer: It is easiest to approach this problem using symbolic combinatorics as formalized by Flajolet and Sedgewick. Let $\mathcal{R}$ be the combinatorial class in question. Then we have straightforwardly the following combinatorial class equation
$$\mathcal{R} =
\mathfrak{P}(\mathfrak{P}_2(\mathcal{Z}) + \mathfrak{P}_4(\mathcal{Z}) +\mathfrak{P}_6(\mathcal{Z})+\cdots),$$
where $\mathcal{Z}$ is the singleton class.
Translating this into generating functions we obtain for the exponential generating function $R(z)$ that
$$ R(z) = \exp\left(\frac{z^2}{2!} + \frac{z^4}{4!} + \frac{z^6}{6!} + \cdots\right) =
\exp\left(-1 + \frac{z^0}{0!} + \frac{z^2}{2!} + \frac{z^4}{4!} + \frac{z^6}{6!} + \cdots\right)\\=
\exp\left(-1 + \frac{1}{2}\exp(z) + \frac{1}{2}\exp(-z)\right) =
\exp(-1 + \cosh(z)).$$
This shows from a modern perspective that there is no misprint in the book.
Comment: Can you please take a look at my updated post and tell me where have I gone wrong. Thanks.
Comment: Never mind. I figured it out. It was just a careless mistake on my part. This Flajolet-Sedgewick approach sounds interesting. Where can one learn more about it?
Comment: @Shabab Get started [here](http://en.wikipedia.org/wiki/Analytic_combinatorics).
Comment: @Shahab, a somewhat easier starting point is Sedgewick and Flajolet's ["An Introduction to the Analysis of Algorithms"](http://aofa.cs.princeton.edu/home), Flajolet and Sedgewick's ["Analytic Combinatorics"](http://ac.cs.princeton.edu) is more mathematically oriented. Both available on line, I bought them both anyway...
Answer: The problem is that the empty set can't be partitioned, i.e., $R_0 = 0$. Your boundary condition is off.
Comment: Not really. The generating function is $r(x)=e^{ch (x)+c}$ which doesn't makes sense for $R_0=0$.
Comment: The solution has $R_0 = 0$...
Comment: What do you mean? The generating function is $r(x)=e^{ch(x)-1}$. So $R_0=r(0)=1$.


PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function Kit\core::__construct() on PDO class

Question: I am currently looking at improving my PHP knowledge and creating websites to a better extent by using classes and such but I've ran into an issue when trying to allow other classes in separate files to access the PDO connection that I've sent up. I've tried hundreds of resolutions which have been inputted onto this site but can't seem to figure it out at all and can't seem to understand where I'm going wrong.
I'm being met with the following error:

    [16-Sep-2022 11:05:02 UTC] PHP Fatal error:  Uncaught ArgumentCountError: Too few arguments to function Kit\core::__construct(), 0 passed in /home/liamapri/public_html/kit/global.php on line 24 and exactly 1 expected in /home/liamapri/public_html/kit/app/class.core.php:11
    Stack trace:
    #0 /home/liamapri/public_html/kit/global.php(24): Kit\core->__construct()
    #1 /home/liamapri/public_html/index.php(3): include_once('/home/liamapri/...')
    #2 {main}
      thrown in /home/liamapri/public_html/kit/app/class.core.php on line 11

I have a global.php file which will be added to each individually page such as /home /index etc, it references all the files that I'll need and starts the session from it, see below:

    error_reporting(E_ALL ^ E_NOTICE);

    define('C', $_SERVER["DOCUMENT_ROOT"].'/kit/conf/');
    define('A', $_SERVER["DOCUMENT_ROOT"].'/kit/app/');
    define('I', 'interfaces/');

    // Management
    require_once C . 'config.php';

    // Interfaces
    require_once A . I . 'interface.engine.php';
    require_once A . I . 'interface.core.php';
    require_once A . I . 'interface.template.php';

    // Classes
    require_once A . 'class.engine.php';
    require_once A . 'class.core.php';
    require_once A . 'class.template.php';

    // OBJ
    $engine = new Kit\engine();
    $core = new Kit\core();
    $template = new Kit\template();

    // Start
    session_start();

    $template->Initiate();

This references the class.engine.php first which is where I have created the database connection class, as shown below:

    namespace Kit;

    use PDO;

    if(!defined('IN_INDEX')) { die('Sorry, this file cannot be viewed.'); }

    class engine
    {
        public $pdo;

        public function __construct()
        {
            global $_CONFIG;
            $dsn = "mysql:host=".$_CONFIG['mysql']['hostname'].";dbname=".$_CONFIG['mysql']['database'].";charset=".$_CONFIG['mysql']['charset'].";port=".$_CONFIG['mysql']['port'].";";
            $options = [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES   => false,
            ];
            try {
                $this->pdo = new PDO($dsn, $_CONFIG['mysql']['username'], $_CONFIG['mysql']['password'], $options);
            } catch (\PDOException $e) {
                print "An error has occurred whilst connecting to the database:
" . $e->getMessage() . "";
                die();
            }
        }
    }

    $connection = new engine();

I'm then trying to run a PDO query on another class (class.core.php) and keep getting met with either a PDO can't be found error or the one described above.
See the file below:

    namespace Kit;

    if(!defined('IN_INDEX')) { die('Sorry, this file cannot be viewed.'); }

    class core implements iCore
    {
        public $connection;

        public function __construct($connection)
        {
            $this->connection = $connection;
        }

        public function website_settings()
        {
            $qry = $this->connection->pdo->prepare("SELECT `website_name` FROM `kit_system_settings`");
            $qry->execute([]);
            if ($qry->rowCount() == 1) { while($row = $qry->fetch()) { return $row; } }
        }
    }

Sorry if this is a simple fix but I really can't see where I'm going wrong.
Answer: Look in your global .php on Line 24 (its probably this line: $core = new Kit\core();)
In your class.core.php you tell the constructor that it will get a connection, but in your global.php you dont give constructor (when you initialize a class) any argument.
That's what this error is telling you
PHP Fatal error:  Uncaught ArgumentCountError: Too few arguments to function Kit\core::__construct(), 0 passed

Just guessing, but i think
$core = new Kit\core($engine->pdo);

will fix your issue.
Comment: I see it now, you also have code in your database connection class, called engine. Thats a bad way to do it!  A class file should only contain the class, nothing else. No "normal" php code in there.

If i see your code correct it should be like this:

`$engine = new Kit\engine();$core = new Kit\core($engine);`


Curve in $\mathbb R^2$ with conditions on distance and normal vector

Question:
Let $\gamma$ be a curve in $\mathbb R^2$. Lets denote $Y_0(x,y)$ an intesrction point of the normal line of the curve in point $(x, y)$ and coordinate line $OY$. For every point $a$ on $\gamma$ it is true that $||a||=||Y_0(a)||$ (see fig. 1). Find $\gamma$ as a graph of some function $y(x)$.

Let $y(x)$ be such function. Normal vector at $(x, y)$ equals $(-y', 1)$. Then $(x, y) + \frac{x}{y'}(-y', 1) =(0, Y_0(x,y))$. Thus $Y_0(x, y) = \frac{x}{y'} + y$.
Distance to $(x, y)$ is equal to $\sqrt{x^2 + y^2}$
So we got differential equation: $(\frac{x}{y'} + y)^2 = y^2 + x^2$.
I have two questions here: is my reasoning about calculating $Y_0(x, y)$ correct and how can we solve differential equation?
Thanks!
Answer: Your differential equation is correct:
$$
{x\over y'}+y=\sqrt{x^2+y^2}
$$
and can be written as follows:
$$
y'={x+yy'\over\sqrt{x^2+y^2}}={d\over dx}\sqrt{x^2+y^2},
$$
whence $y=\sqrt{x^2+y^2}+k$, where $k$ is a constant.
The result is then a parabola, having its focus $F$ at $(0,0)$. Note that $||a||=||Y_0(a)||$ is a well-known property of such parabolas, because normal $PQ$ at point $P$, in a parabola, is the bisector of the angle formed by $PF$ with the parallel to the axis passing through $P$.


How to describe the derivative of matlab symbolic variable?

Question: For example, I named the variables x(t), xdot(t) about time: syms t x(t) xdot(t);, and the derivative of x about time is xdot, xdot=diff(x,t).
But when I calculate diff (x, t), the result is not xdot. How can I set the display of diff (x, t) in the calculation result to xdot?
In addition, the time variable in the calculation result is displayed in the form of variable(t). How to set the result to display only variable?
syms t x(t) xdot(t);
xdot=diff(x,t);
y=diff(x,t);
y

the result of y is displayed as  , however, I want it to be xdot
Comment: Shows us the code, its not entirely clear (to me) what you mean
Comment: As Ander mentioned, it is hard to provide a great answer.

Consider,
assignin('base', 'xdot', simplify(diff(x, t)))
Answer: Consider the following code:
a = 3;
b = 3;
b

It appears to me, you would like this to display b = a, instead of b = 3. This is not how MATLAB works. Both a and b are equal to 3, but that doesn't mean a is b.
The same is true for the code:
a = 3;
b = a;
b

This gives b = 3, not b = a. I won't go into details about why this is the case (and why it has to be the case in MATLAB). It's enough to know that this is how it works.
You have assigned diff(x,t) to two different variables, xdot and y. This means that, while xdot and y have the same value, xdot is not y.
If you do xdot = 3 after your code, then y would still be dx/dt.
Side note: Why do you want this behaviour? Are you sure it's necessary? You can always print the result however you like:
fprintf('xdot = %s', y(t))
xdot = diff(x(t), t)

Ugly workaround to do something I don't understand why you would do:
Create a function:
function res = xdot(t)
   syms x(t) res;
   res = diff(x,t);
end

And then define y as a function handle:
y = @xdot
y = function_handle with value:
  @xdot

Now y(t) will still give dx/dt, but y will give xdot
I strongly recommend you don't do this.
Comment: I want to do this for the reason that I want to use these symbolic variables to deduce the formula, not calculate the result, like this:. And I don't know other tools for deriving formulas besides the symbol toolbox.

How to describe the derivative of matlab symbolic variable？


Fitting splines to famous curves programmatically

Question: this may be a bit of a naive question.  I am looking for a way to input a Cartesian description of a famous curve and map that to some spline say NURBS to make spline paths.  Is this at all possible?
Examples of curves in question:
http://www-history.mcs.st-and.ac.uk/Curves/Curves.html
Ideally I would like to input the equation describing the curve and fit a spline over a given range
Answer: In many cases, it won't be possible to represent the given curve exactly in NURBS form. But you can certainly construct NURBS approximations that are as accurate as you want.
The easiest way to create an approximation is to construct a spline curve that interpolates a sequence of points lying on the given curve. So, how do you get this sequence of points? If the given curve has known parametric equations, this is easy: you just take a sequence of parameter values $t_1, t_2, \ldots$, and calculate points $P_i = \left( x(t_i), y(t_i) \right)$. If you have only an implicit equation for the given curve, then things are more difficult. This paper outlines one possible approach: https://www.sciencedirect.com/science/article/pii/S0377042703004114
Comment: Thanks for your reply.  I am aware the NURBS can be used to create these types of curves, http://www.dm.unibo.it/~casciola/html/papers/giulio.pdf  however I am having trouble wrapping my head around constructing them using their function equations.  I would like to be able to construct an algorithm that takes an equation over a range and creates a spline that approximates it.  Are you aware of any resources that might get me started on tackling this?
Answer: In theory, as long as you can evaluate points on these curves, you can fit a spline to any range of these curves. There are tons of curve fitting techniques (interpolation vs approximation) over the internet that you can search for and therefore I won't elaborate here.
However, there is one issue you need to pay attention to: some of these famous curves have $C^1$ discontinuities (e.g., Astroid and Cardioid). If the range of curve you would like to fit a spline to contains such $C^1$ discontinuities, you need to know where these $C^1$ discontinuities occur so that they will be handled properly during curve fitting. On the other hand, depending on what your original purpose is, it will be easier for you to simply approximate the curve by a polyline and you do not need to be concerned with the $C^1$ discontinuities issue.
PS: Some curves listed in the "Famous Curve Index" page only have implicit representation (e.g., Bicorn, Cartesian Oval). It will be much harder to evaluate points on these curves and this is probably the reason that they do not show up on the "Famous Curve Applet Index" page (the page pointed to by a link in the "Famous Curve Index" page).
Comment: thanks for your response!  My intent is to create a series of interpolated flight patterns for a game I am developing.


How hard is composing a song like ancient Greek music today?

Question: And by this question I mean a song that sounds like an actual ancient Greek song, with ancient Greek instruments (lyre, kithara, salpinx, etc.) being used.
Answer: It's effectively impossible, because we only know indirectly what their music might have sounded like, and there are almost no surviving working instruments.
We know quite a lot about the music theory the Greeks developed — there are a number of excellent posts on this site in that regard — but the actual sound of the music is, in essence, guesswork — though guesswork backed up a some outstanding and detailed research.
Comment: Has anyone tried to make those instruments, which could emulate the sounds?
Comment: @Tim yes, though the accuracy is debated, and still doesn't inform the overall sound of the music, such as rhythm.
Comment: @Tim making the instruments is the easy part.  Consider the similarity between e.g. the [oud](https://en.wikipedia.org/wiki/Oud) and the [lute](https://en.wikipedia.org/wiki/Lute) and the differences between traditional North African music and the music of Renaissance Europe.  Or compare the many widely disparate styles of music one can play on a keyboard tuned in 12-tone equal temperament (and the even greater variety one can achieve by varying the tuning).
Comment: Sting's *When We Dance* is in [Lydian](https://en.wikipedia.org/wiki/Lydian_mode). Sounds wack. Unlike REM's *Man On the Moon*, presumably because he can "actually maintain a harmony rigorously fixed on" the mode.
Comment: @Mazura The modern Lydian mode has nothing to do with the ancient Greek musical system except for millenia-later music theorists choosing a Greek name.


Accessing specific member of an ArrayList using Javascript

Question: So, I have a table in a jsp page which shows the data fetched from a database via an ArrayList forwarded to the page. Each row of the table has a radio button corressponding to it. Now, I would like to access the elements in the row (the ArrayList's members on the selection of the corresponding radio button and then click of an 'edit' button)
Any thoughts as to how to achieve this would be very much appreciated. Here's my code for a bit intro.
<%
   ArrayList<requestbean> reqjsp = new ArrayList<requestbean>();
   reqjsp = (ArrayList<requestbean>) (request.getAttribute("reqdb"));
%>

<input type="button" name="edireq" id="edireq" onclick="x()" value="Edit Request">

These are a few columns in my table.
<%
 for ( int i = 0; i < reqjsp.size(); i++ ) {
%>

     <input type="radio" name="reqradio" id="req<%=(i+1) %>">
    <%= reqjsp.get(i).getRequestid() %>
    <%= reqjsp.get(i).getRequestor() %>
    <%= reqjsp.get(i).getApprover() %>

<%} %>

Answer: You could generate a JavaScript array with JSP code and then access this generated variable in your JavaScript. But you would not be able to change anything in the underlying Java object this way:

The JSP code will generate this kind of code:


How can I export Image Crop configuration with an Image Style for custom module?

Question: I have a custom module I'm re-using on other projects and I want to include an image style with an image crop configuration.
Under the configuration menu, I export a single crop item:
langcode: en
status: true
dependencies: {  }
label: 'Head Shot Crop'
id: head_shot_crop
description: 'Cropping for image head shot.'
aspect_ratio: '1:1'
soft_limit_width: null
soft_limit_height: null
hard_limit_width: null
hard_limit_height: null

I strip out the UUID value for that to be set on new installs.  However, for the image style export:
langcode: en
status: true
dependencies:
  config:
    - crop.type.head_shot_crop
  module:
    - crop
name: head_shot
label: 'Head Shot'
effects:
  ce7f0752-c37c-4ff6-945d-96c298663365:
    uuid: ce7f0752-c37c-4ff6-945d-96c298663365
    id: crop_crop
    weight: 1
    data:
      crop_type: head_shot_crop

I strip out the UUID value as well, but the associated crop configuration seems to be tied to the image style via UUID under the effects key, which also has a UUID value.
How can I pair an image style configuration with a crop configuration configuration so they exist on new module installs?
Answer: Please see: https://www.drupal.org/project/drupal/issues/2247257
The uuid under the effects array is used as a "unique ID" for the effect.
Seems technically it "works as designed", but as you can see from the linked project task, there is talk about if it's designed correctly.
Fortunately, the uuid under the effects array is scoped to that effects namespace, so it is safe to have the same uuid under any effects array you have regardless of the image style.
Example:
langcode: en
status: true
dependencies: {  }
name: 136x91
label: '(35mm Film 96dpi) 136 x 91'
effects:
  42cf8d4f-246c-4a6d-835f-868e5bcea297:
    uuid: 1cfec298-8620-4749-b100-ccb6c4500779 // <- could be any uuid value
    id: image_scale_and_crop
    weight: 35
    data:
      width: 136
      height: 91
      anchor: center-center

Just note that if you have two effects in one image style, they will each need a unique uuid key.
Example:
langcode: en
status: true
dependencies: {  }
name: teaser_290x163
label: 'Teaser Image 290 x 163'
effects:
  bdd99645-b55a-47b4-9337-89453c12658e:
    uuid: 1cfec298-8620-4749-b100-ccb6c4500779 // <- same as above
    id: image_scale_and_crop
    weight: 1
    data:
      width: 290
      height: 163
  4f4a1ff4-f127-4693-af57-d8f0cf3c9de0:
    uuid: 1cfec298-8620-4749-b100-ccb6c4500780 // <- needs to be unique
    id: image_resize
    weight: 2
    data:
      width: 290
      height: 163

So remove the uuid from the first line for the image style itself, but leave the uuid under the effects array when you export.


Ler formato Json Angular 9

Question: minha api retorna um formato de json da seguinte forma
{
  "Errors": [],
  "Result": [
    {
      "CompanyName": "teste inicio",
      "FantasyName": "inicio"
    },
    {
      "CompanyName": "teste meio",
      "FantasyName": "meio"
    },
    {
      "CompanyName": "teste final",
      "FantasyName": "fim"
    }
  ],
  "Message": "Solicitação atendida com sucesso!"
}

até aqui tranquilo, usando Angular 9 meu serviço que faz o consumo em minha API
 read(): Observable<Restaurant[]>{
 return this.http.get<Restaurant[]>(this.baseUrl);

meu arquivo do componente.ts onde faz a consulta em meu serviço
ngOnInit(): void {
this.restaurantService.read().subscribe(restaurants => {
  this.restaurants = restaurants
  console.log(restaurants)
})

no console do navegador ele exibe tranquilamente o retorno da API conforme já exemplificado no início, quando vou exibir em tela os dados retornados em "Result:" ou mostrar o valor em "Message", retoma a seguinte mensagem
error TS2339: Property 'Result' does not exist on type 'Restaurant[]'

Segue o código HTML

    {{ item.restaurants }}

Tanto colocando o "Result" no .html quando no .ts do componete o erro é o mesmo.
Comment: Sim, vai dar erro mesmo! Na hora que o Html é renderizado o retorno da Api pode ainda não ter sido resolvido (por estar acessando dados de uma api o retorno é assíncrono) logo o erro.
Comment: Alguma sugestão de como resolver, apesar do erro mostrado ele acaba mostrando em tela os dados quando coloco o  "Result" direto no ngFor
Comment: Poderia postar a declaração da variável **restaurants**?
Comment: Sim, restaurants: Restaurant[]
Comment: Removi a resposta, pq achava que era um problema, mas, pelo visto aí deve estar acontecendo outro problema, e como não dá para testar creio não saber como ajudar.
Answer: Essa mensagem é porquê não foi definido o 'Result' no restaurants.
Tente fazer essa forma:
ngOnInit(): void {
    this.restaurantService.read().subscribe((restaurants:any) => {
         this.restaurants = restaurants.Result
    })
}

Ler formato Json Angular 9


Expected an indented block error(Protein Sequence Count)

Question: The code:
def find_orf_lengths(dna,frame,cutoff):
    orfs_lengths = []

    for i in range(0,len(dna),3):
        if(dna[i:i+3] == "ATG"):
            orfs_lenghts[i] += 1
            elif(dna[i:i+3] == "TGA"|"TAA"|"TAG"):
                if(orfs_lenghts[i] >= cutoff):
                    orfs_lengths.append(100)
                    elif(orfs_lenghts[i] < cutoff):
                        continue

    return orfs_lengths

I was working on a protein sequence project and the problem is, whatever I do I can't get past the "Expected an indented block" error which is given like this:
             File "lab6hw.py", line 27
               if(dna[i:i+3] == "ATG"):
            IndentationError: expected an indented block

Comment: `elif`'s should be indented the same as their associated `if`'s.
Comment: You've mixed spaces and tabs, among other indentation problems.
Comment: This may be helpful to you: https://stackoverflow.com/questions/45621722/im-getting-an-indentationerror-how-do-i-fix-it
Answer: Put elif at same indent level as if:
def find_orf_lengths(dna,frame,cutoff):
    orfs_lengths = []
    for i in range(0, len(dna), 3):
        if(dna[i:i + 3] == "ATG"):
            orfs_lenghts[i] += 1
        elif(dna[i:i + 3] == "TGA" | "TAA" | "TAG"):
            if(orfs_lenghts[i] >= cutoff):
                orfs_lengths.append(100)
            elif(orfs_lenghts[i] < cutoff):
                continue

    return orfs_lengths

Answer: An elif has to be at the same indentation level as an if above it. You probably meant something like this:
def find_orf_lengths(dna,frame,cutoff):
    orfs_lengths = []

    for i in range(0,len(dna),3):
        if(dna[i:i+3] == "ATG"):
            orfs_lenghts[i] += 1
        elif(dna[i:i+3] == "TGA"|"TAA"|"TAG"):
            if(orfs_lenghts[i] >= cutoff):
                orfs_lengths.append(100)
            elif(orfs_lenghts[i] < cutoff):
                continue

    return orfs_lengths

Though I can't test your code without knowing the inputs.


DropBox: Form submit file directly to DropBox

Question: I was looking for a way to submit a file directly to DrobBox from a simple form passing the oauth but I  did not find anything so I am almost convinced that I will have to send the file to my server and then send it to dropbox.
Anyone knows if there is a way to submit a file directly to DrobBox from a simple form, actually is there a service in dropbox which accepts it?
THks
Answer: Looks like you should use the official Dropbox API which you can find here https://www.dropbox.com/developers
Comment: I already read the api and I am talking with dropbox using ruby. I guess It is not possible to send a file directly from my form, sure maybe using an iframe to post to dropbox but how will I get the datafile?
Comment: There is a dropbox API for Ruby here https://github.com/riscfuture/dropbox
does that not do what you need, if not I think you need to explain more.....
Comment: I am using that api, it works fine but I want a service like as3 does: http://doc.s3.amazonaws.com/proposals/post.html to post a file directly to dropbox without touch in my server.


Pandas: Extracting just the Calendar Year from Datetime column

Question: I have a Dataframe with a column alike the following column:
df['Schedule'] =
...
2012-12-31
2013-01-01
2013-01-02
2013-01-03
2013-01-04
2013-01-05
2013-01-06
2013-01-07
2013-01-08
2013-01-09

And so on from 1981 to 2015. The elements of the column are pandas.tslib.Timestamp.
I needed to create another column where I had to extract only the year.
So I did the following command:
df['Year'] = df['Schedule'].dt.year

It partially worked because I need the years to match with the date from calendar year (my dataset is composed of matchups of a NBA season)/
To be clear instead of:
2012-12-31    2012
2013-01-01    2013

I need:
2012-12-31    2013
2013-01-01    2013
...
2013-09-27    2014
...
2014-04-06    2014

Does anyone have an efficient way to solve this problem?
Comment: How do months map to the season?
Comment: My observations (inputs) are all matchups from 1981 to 2015. The beginning of each season is around October and the regular season (before the playoffs) ends in mid-April. So the concerning months are the following: 09,10,11,12,01,02,03,04. Hope it helps you
Answer: From what you're saying, it seems like September is the breakpoint for NBA season year.  If so, your best bet would be to apply a custom lambda, like this one:
df["year"] = df["schedule"].apply (lambda x : x.year if x.month < 9 else x.year + 1)

If you give me more info on NBA season months I can clean this up.
Here's a test program yielding correct outputs for your sample:
import dateutil

df = DataFrame ({
    "schedule" :
    Series ([
        "2012-12-31",
        "2013-01-01",
        "2013-09-27",
        "2014-04-06"
    ]).apply(dateutil.parser.parse)
})
df["year"] = df["schedule"].apply (lambda x : x.year if x.month < 9 else x.year + 1)
df

Here is one of the places where the pandas documentation first begins to introduce using lambda functions with apply.
Comment: To give you more information, my dataset is composed of the regular season schedule (from October to mid-April). Your code sounds pretty good but why does ".apply(dateutil.parser.parse)"?
Comment: Thx for accepting.  The `.apply(dateutil.parser.parse)` was just to set up the sample data to make the `schedule` column into a `datetime` type, which I assume was the type of your original dataset column too.
Comment: Yes! Thx for your help.


i am getting permission denied after writing rules in firebase

Question:     import React, { useReducer, useState ,re} from 'react';
import uuid from 'react-uuid';
import { useDispatch } from 'react-redux';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import database from '../firebase/firebase';
import snapshot from '../firebase/firebase';
import '../App.css';
import { auth } from 'firebase';

const AddTasks = () => {

    const dispatch = useDispatch();
    const newLocal = null;
    const [selectedDate, setSelectedDate] = useState(newLocal);
    const [task, setTask] = useState('');
    const date = new Date()

here i want to add task with user but gettin permission issue want to set users=> task but it gives me getState is not a function so i tried
eturn (dispatch, getState) but its do nothing

    const addTask = () => {
//  return (dispatch, getState) => {
//       const uid =  getState().auth.uid
         console.log(selectedDate);
        const payload = { id: uuid(), text: task, completed: false, addedAt: JSON.stringify(selectedDate)}
        console.log(payload)

i tried ref(users/${uid}/tasks) but not working

const dbtasksWrapper = database.ref().child('tasks');
            return dbtasksWrapper.child(payload.id).update(payload).then(() => {
                    dispatch({ type: "ADD_TASKS", payload })
                 })
            setTask('');
            setSelectedDate(null);
        //  }
     }

return (
    <form onSubmit={e => {
        e.preventDefault(e.target.value);
        addTask();
    } }>
        <input className="input-group-prepend" value={task} placeholder="Enter your Task" onChange={e => setTask(e.target.value)} />
        <DatePicker className="input-group-prepend" placeholderText="Enter task date " selected={selectedDate} onChange={(date) => setSelectedDate(date)} showTimeSelect timeFormat="HH:mm" timeIntervals={15} timeCaption="time" dateFormat="MMMM d, yyyy H:mm aa" minDate={date} />

        <input className="btn btn-primary" type='submit' value='Submit' />

    </form>
);

};

export default AddTasks;

i have edit rules for my task want to set for Auth user but its not working      PERMISSION_DENIED: Permission denied
 "rules": {

      "users":{
        "$user_id":{
          ".read": "$user_id === auth.uid",
            ".write": "$user_id === auth.uid ",
          "tasks": {
            "$task_id": {

i think the issue is here in "newData.hasChildren but dont know whats wrong??
              ".validate": "newData.hasChildren(['task', 'addedAt', 'complete'])",

                "task":{
                  ".validate": "newData.isString() && newData.val().length > 0 "
                },
                "addedAt":{
                  ".validate": "newData.isString()"
                },
                "complete":{
                  ".validate": "newData.isBoolean()"
                },

                "$other": {
                ".validate": false
            }
            }
          },

        }
      }

  }
}

Comment: Please edit the question to show the code of the query that's failing.  Security rules don't have much meaning without also queries that they must allow or deny.
Comment: Your rules check for a child named `task`, but your code adds a child named `text`. That seems like a typo that would explain why the write fails.
Comment: The code needs to be in the question itself so that it will be helpful in the future in case your repo goes away.
Comment: @DougStevenson i have edited now kindly check
Comment: tried that too @FrankvanPuffelen same in rules playground its Simulated set denied on.       ".validate": "newData.hasChildren(['text', 'addedAt', 'complete'])",
Comment: This was definitely a cause of the error you got. But I also see you're writing to `database.ref().child('tasks');`, while the rules apply to `/users`/$uid/tasks`. There's just a lot going on with these rules and the code, which makes it hard to pinpoint the exact problems. I recommend isolating the problem in fewer rules, and simpler code. At worst that will make it more likely one of us can help, but actually also often means that you'll find the problem yourself while isolating the problem.
Answer: const AddTasks = () => {

    const dispatch = useDispatch();
    const newLocal = null;
    const [selectedDate, setSelectedDate] = useState(newLocal);
    const [task, setTask] = useState('');
    const date = new Date()

useSelector for uid as following

const userId = useSelector(state => state.auth.uid);

    const addTask = () => {
        console.log(userId);
        const payload = { id: uuid(), text: task, completed: false, addedAt: JSON.stringify(selectedDate)}

then add child userId and its done

const dbtasksWrapper = database.ref().child(userId).child('tasks');
            return dbtasksWrapper.child(payload.id).update(payload).then(() => {
                setTask('');
                setSelectedDate(null);
                dispatch({ type: "ADD_TASKS", payload })
            })
         }


If $\theta\in\mathbb{Q}$, is it true that $(\cos \theta + i \sin \theta)^\alpha = \cos(\alpha\theta) + i \sin(\alpha\theta)$?

Question: Is the following true if $\theta\in\mathbb{Q}$?
$$(\cos \theta + i \sin \theta)^\alpha = \cos(\alpha\theta) + i \sin(\alpha\theta)$$
Is it true if $\alpha\in\mathbb{R}$? In each case, prove or give a counterexample, whichever is applicable.
I am not able to guess except about the de Moivre's theorem.
Comment: Do you mean "if $\alpha \in \Bbb{Q}$"?
Answer: It is not true in general.
$$
(\cos \theta + i \sin \theta)^\frac 12 = \left [ \begin{array}{l}
\cos \frac \theta 2 + i \sin \frac \theta 2 \\
\cos \left ( \frac \theta 2 + \pi \right ) + i \sin \left ( \frac \theta 2 + \pi \right )
\end{array}\right .
$$
Comment: @DanZimm There's no such a rule in complex analysis. I could've taken cubic root, which one would you prefer to take in that case?
Comment: Hrm, if we were to consider $(\cos \theta + i \sin \theta)^{\alpha}$ a function then would we only take the positive square root?
Comment: ah good point ok
Answer: The problem with this question is that this is not so much about being true as about being well defined (except in the cases where $\alpha\in\Bbb Z$, for which there is no problem and the formula holds).
Raising complex numbers to non-integral powers is not well defined; the best stab at a definition is $z^\alpha=\exp(\alpha\ln z)$ which shows that the necessary branch cut of the complex logarithm makes it impossible to define $z\mapsto z^\alpha$ as a (single-valued) continuous function on all of$~\Bbb C$, or even on a neighbourhood of$~0$, unless $\alpha\in\Bbb Z$. Therefore the left hand side $\def\i{\mathbf i}(\cos θ + \i \sin \theta)^\alpha$ of your proposed equality has these kind of definitional problems, whereas the right hand side $\cos(\alpha\theta) + \i\sin(\alpha\theta)=\exp(\i\alpha\theta)$ is a perfectly well defined (even for $\theta\in\Bbb C$ of which it defines a holomorphic function).
As you can easily check you can make the formula hold for a given $\theta$ by choosing $\ln(\cos θ + \i\sin \theta)=\i\theta$ in defining the LHS, which then becomes $\exp(\alpha\mathbf i\theta)$ in accordance with the RHS. However, to get the formula to still work after adding $2\pi$ to $\theta$ would require using a different logarithm for the same complex number $\cos θ + \i\sin\theta$; no single-valued choice for defining complex exponentiation can have it both ways. In a sense the position that makes the equation $(\cos\theta + \i\sin\theta)^\alpha = \cos(\alpha\theta) + \i\sin(\alpha\theta)$ "as true as possible" for $\alpha\notin\Bbb Z$, is to interpret the left hand side as a multi-valued expression (finitely many if $\alpha\in\Bbb Q$, infinitely many otherwise), one of whose values coincides with the single-values right hand side. However working with multi-valued expressions is not what one does normally in mathematics, it is therefore a tricky business, and I think it tends to obscure rather than to solve fundamental difficulties, so one is better off not doing this.
Comment: Yes, I have noticed that the right hand side is not well-defined. However, a similar calculation can be applied for finding n-roots of $1$ for example: $1^\frac{1}{n} = (e^{2\pi i})^\frac{1}{n} = e^{2\pi i \frac{1}{n}} = e^{i\frac{2\pi}{n}}$, that gives n roots, that are on the unit circle.
Comment: Oh, you meant the question.
Answer: Not for every $\alpha \in \mathbb{R}$, but for the left hand side of your equation you can calculate
\begin{eqnarray}
(\cos(\theta) + i \sin(\theta))^\alpha & = & (e^{i\theta})^\alpha = (e^{i\theta + 2\pi i k})^\alpha = e^{(i\theta + 2\pi i k)\alpha} = e^{i\theta\alpha + 2\pi i k \alpha} \\
& = & e^{i\theta \alpha} e^{2\pi i k \alpha} = e^{2\pi ik \alpha} e^{i \theta \alpha} = e^{i \pi 2 k \alpha} e^{i \alpha \theta} \\
& = & e^{i \pi 2k \alpha} (\cos(\alpha \theta) + i \sin(\alpha\theta))
\end{eqnarray}
for $k \in \mathbb{Z}$ so the left hand side is not necessarily unique, but at least one of its values has the value of the right hand side. It is found by choosing $k = 0$. A counterexample is found by choosing $k = 1$ and $\alpha = \frac{1}{2}$ as in Kaster's answer.


What does (1-) mean in the context of probability mass functions?

Question: I am checking over some work I'm doing, and I noticed the following formula:
$P(X=i) $
$= P(X\le i) - P(X < i)$
$ = F(1) - F(1^-)$
I understand the concept of the second line, but I don't understand the 3rd line.
Answer: $F(1^-)$ is shorthand for
$$
\lim_{x\to1^-}F(x)
$$
which is to say, the limit of $F(x)$ as $x$ approaches $1$ from below.
Comment: Honestly, if you know what the second line means, and what $F(1)$ means, then in my opinion it shouldn't be too hard to guess what $F(1^-)$ means from the context. True, guessing is not the same as knowing, but you can get pretty far that way most of the time.


How to find a standard deviation determined by a Normal distribution probability?

Question: The question is

A liquid drug is marketed in phials containing a nominal 1.5ml but the amounts can vary slightly. The volume in each phial may be modeled by a normal distribution with the mean 1.55ml and standard deviation $\sigma$ ml. The phials are sold in packs of 5 randomly chosen phials . It is required that in less than 0.5% of the packs will the total volume of the drug be less than 7.5ml. Find the greatest possible value of $\sigma$.

I need to find the greatest possible value of the standard deviation ($\sigma$).
I worked out the following:
$$\mu= 1.55*5 = 7.75.$$
We are asked to find value of $\sigma$ such that probability of (total volume of $5$ packs $\lt 7.5)\lt0.5\%$
$$P(X\lt7.5)\lt0.005.$$
After standardizing,
$$P(X\le\frac{7.5-7.75}{\sigma/5})<0.005$$ and I found $\sigma=0.2170.$ However, the answer provided is $0.0434.$
Please assist.
Comment: what's CTL? ... ... Also please check the details of the question, it looks like you may have a mistake somewhere. Where did the 7.75 in your working come from? Please show more detail/explanation of what you're doing. (As far as possible your responses should result in edits to your question)
Comment: Please add the `self-study` tag, read its [tag-wiki](http://stats.stackexchange.com/tags/self-study/info), and indicate the specific help you need at the point you struck difficulty.
Comment: How have you approached/engaged it so far?  Any partly successful paths?  Where else have you looked for answers?
Comment: Interestingly, neither answer is correct.
Answer: Among the objectives of good introductory statistics courses is learning how to think about the Normal distribution.  This question provides a nice example.
The key is to use units of measurement that are adapted to the distribution.  That is, let the mean be the zero point and let the standard deviation be one unit.  This is what a "Z score" measures.
In light of this, let's parse the question.  To do so, I will use two fundamental facts: expectations add ("linearity of expectation") and variances of independent variables also add:

The mean volume of one pack is 1.55 ml, whence the mean volume of five packs must be five times as large, or 7.75 ml: this is the zero point.
Since the unknown variance of a single pack is $\sigma^2,$ the variance of the sum of five independent packs is $5\sigma^2.$  Therefore the standard deviation of the sum--the unit of measurement we must adopt--is $\sqrt{5\sigma^2} = \sigma\sqrt{5}.$

The question stipulates that in less than 0.5% of cases should the total be less than 7.5 ml.  For the (standard) Normal distribution we remember (or can compute) that exactly 0.5% of cases are $2.57\ldots$ or more less than the mean.  An example of this computation is
qnorm(0.5/100)

in R or
=NORMSINV(0.5/100)

in Excel, for instance.
One aim of the introductory course is to help you reach the point where such considerations are automatic: you can do them in your head correctly, apart (perhaps) from the arithmetical calculations.

This preliminary work enables us to rephrase the question like this:

What unit of measurement, given by $\sigma\sqrt{5}$ for a five-pack of drugs, will re-express an amount of $7.5$ ml as being $2.57$ less than $7.75$ ml?

The solution obviously is
$$\sigma\sqrt{5} = (7.75 - 7.5)/2.57\ldots = 0.097\ldots,$$
implying
$$\sigma = \frac{0.097\ldots}{\sqrt{5}} = 0.0433797\ldots$$

Comparing this result to the question shows that the work in the question was entirely correct up to the point where "$\sigma/5$" appeared: the square root was lost.  This suggests remembering to think in terms of variances rather than standard deviations.
Comparing this result to the older answers that were posted also shows how they were basically moving in the correct direction but made mistakes along the way, too.  Because arithmetical mistakes are easy to make, when one has the chance it's a good idea to check probabilistic calculations with simulations.  For instance, the following R statement generates a large number of five-packs of drugs as described in the question (using the answer I obtained) and, to check my answer, computes the fraction with totals less than 7.5 ml:
mean(colSums(matrix(rnorm(5*1e6, 1.55, -0.25/qnorm(0.5/100) / sqrt(5)), nrow=5)) < 7.5)

(You can see all the data from the question embedded in this expression, along with the value 1e6 giving the number of five-packs to simulate.)  When I run and re-run this code (which takes less than a second each time), I consistently obtain results between 0.0048 (0.48%) and 0.0052 (0.52%), in satisfactory agreement with the intended 0.5% target.
Answer: I think your understanding of the variance of the sum is mistaken. The variance of the 5-pack sum is 25 times the variance of the single pack.
Comment: The only way you could justify the factor of $25$ is to suppose the five packs are perfectly correlated.  Assuming, as is more likely the intent, that the five-pack sum can be modeled as the total of five *independent* Normal variables $X_1+\cdots+X_5$, its variance will be $$\operatorname{Var}(X_1+\cdots+X_5)=\sigma^2 +\cdots+\sigma^2=5\sigma^2.$$  Consequently its standard deviation will be $\sigma\sqrt{5}$, which (by following the path outlined in the question) leads directly to the correct answer.
Answer: \begin{align}
5\times 1.55 &= 7.75  \\
5\times SD   &= 5SD
\end{align}
Problem statement: $P(X<7.5)<0.005$
\begin{align}
\frac{(7.5-7.75)}{(5SD^2)^{1/2}}  &< 0.005  \\[8pt]
\frac{-0.25}{2.576} &= (5SD^2)^{1/2}  \\[5pt]
&-0.0970 / 5^{(1/2)}
\end{align}
$0.0434$ as the standard deviation can never me negative, take the mod value.
Comment: Welcome to Stats.SE. You may give hints but please do not give the full answer. Furthermore, can you please edit your post and explain the key steps in the solution and use [MathJax](https://math.meta.stackexchange.com/q/5020) in the formulas?