Boa tarde, precisava de ajuda para uma calculadora em c++

Question: Fiz este programa para calcular áreas e perímetros de formas geométricas, mas quando pressiono "a", "b" ou "c" para escolher se queres fazer áreas ou perímetros o programa apenas fecha. Segue o código:
#include <iostream>
#include <cmath>
#include <locale>
#include <stdlib.h>
using namespace std;

    double PerimetroQuadrado (double Lado) {
        return 4 * Lado;
    }
    double AreaQuadrado (double Lado) {
        return Lado * Lado;
    }
    double PerimetroRetangulo (double Comprimento, double Altura) {
        return Comprimento*2 + Altura*2;
    }
    double AreaRetangulo (double Comprimento, double Altura) {
        return Comprimento * Altura;
    }
    double PerimetroCirculo (double Raio) {
        return 2 * M_PI * Raio;
    }
    double AreaCirculo (double Raio) {
        return M_PI * pow(Raio,2);
    }
    double PerimetroTriangulo (double Base, double Altura) {
        double hipotenusa = hypot(Base , Altura);
        return Base + Altura + hipotenusa;
    }
    double AreaTriangulo (double Base, double Altura) {
        return Base * Altura / 2;
    }
    double PerimetroTrapezio (double BaseMaior, double BaseMenor, double Altura) {
        double Hipotenusa = hypot((BaseMaior - BaseMenor) / 2 , Altura);
        return BaseMenor + BaseMaior + 2 * Hipotenusa;
    }
    double AreaTrapezio (double BaseMaior, double BaseMenor, double Altura) {
        return (BaseMenor + BaseMaior) * Altura / 2;
    }

    int main (){
        setlocale(LC_ALL, "");

        cout << "Cálculo de Perímetros e Áreas. \n";
        cout << "Escolha uma das seguintes opcões: \n";
        cout << "\t a- Perímetro \n";
        cout << "\t b- Área \n";
        cout << "\t c- Sair \n";

        int num1 , num2 , num3;
        char op;
        cin >> op;
        char pr;
        char ar;
        switch(op){
             case 'a':
             case 'A':
             break;
             cout << "Cálculo de Perímetros e Áreas. \n";
             cout << "Escolha uma das seguintes opcões: \n";
             cout << "\t 1- Quadrado \n";
             cout << "\t 2- Retângulo \n";
             cout << "\t 3- Círculo \n";
             cout << "\t 4- Triângulo Retângulo \n";
             cout << "\t 5- Trapézio \n";
             cout << "\t 6- Voltar \n";
             cout << "\t 7- Sair \n";
             cin >> pr;
                switch(pr) {
                case '1': cout << "Introduza o Valor do Lado do Quadrado:";
                          cin >> num1;
                          cout << PerimetroQuadrado(num1);
                          break;
                case '2': cout << "Introduza o Valor do Comprimento do Retângulo:";
                          cin >> num1;
                          cout << "Introduza o Valor da Altura do Retângulo:";
                          cin >> num2;
                          cout << PerimetroRetangulo(num1, num2);
                          break;
                case '3': cout << "Introduza o Valor do Raio do Círculo:";
                          cin >> num1;
                          cout << PerimetroCirculo(num1);
                          break;
                case '4': cout << "Introduza o Valor da Base do Triângulo:";
                          cin >> num1;
                          cout << "Introduza o Valor da Altura do Triângulo:";
                          cin >> num2;
                          cout << PerimetroTriangulo(num1, num2);
                          break;
                case '5': cout << "Introduza o Valor da Base Maior do Trapézio:";
                          cin >> num1;
                          cout << "Introduza o Valor da Base Menor do Trapézio:";
                          cin >> num2;
                          cout << "Introduza o Valor da Altura do Trapézio:";
                          cin >> num3;
                          cout << PerimetroTrapezio(num1, num2 , num3);
                          break;
                case '6':
                break;
                }

             case 'b':
             case 'B':
             break;
             cout << "Cálculo de Perímetros e Áreas. \n";
             cout << "Escolha uma das seguintes opcões: \n";
             cout << "\t 1- Quadrado \n";
             cout << "\t 2- Retângulo \n";
             cout << "\t 3- Círculo \n";
             cout << "\t 4- Triângulo Retângulo \n";
             cout << "\t 5- Trapézio \n";
             cout << "\t 6- Voltar \n";
             cout << "\t 7- Sair \n";
             cin >> ar;
              switch(ar) {
              case '1': cout << "Introduza o Valor do Lado do Quadrado:";
                          cin >> num1;
                          cout << AreaQuadrado(num1);
                          break;
                case '2': cout << "Introduza o Valor do Comprimento do Retângulo:";
                          cin >> num1;
                          cout << "Introduza o Valor da Altura do Retângulo:";
                          cin >> num2;
                          cout << AreaRetangulo(num1, num2);
                          break;
                case '3': cout << "Introduza o Valor do Raio do Círculo:";
                          cin >> num1;
                          cout << AreaCirculo(num1);
                          break;
                case '4': cout << "Introduza o Valor da Base do Triângulo:";
                          cin >> num1;
                          cout << "Introduza o Valor da Altura do Triângulo:";
                          cin >> num2;
                          cout << AreaTriangulo(num1, num2);
                          break;
                case '5': cout << "Introduza o Valor da Base Maior do Trapézio:";
                          cin >> num1;
                          cout << "Introduza o Valor da Base Menor do Trapézio:";
                          cin >> num2;
                          cout << "Introduza o Valor da Altura do Trapézio:";
                          cin >> num3;
                          cout << AreaTrapezio(num1, num2 , num3);
                          break;
                case '7': exit (0);
                break;

              case 'c':
              case 'C': exit (0);
              break;
              default: cout << "Inválido";
              break;
              }

        }
        return 0;
    }

Comment: Você está fazendo `break` logo ao entrar nas condições `a`/`A` e `b`/`B` do switch. Isso interrompe a execução do switch de imediato, antes de rodar a sua lógica.
Answer: O problema está ocorrendo pois logo após entrar nas condições do seu switch case você está dando um break:
...
switch(op){
             case 'a':
             case 'A':
        >>>  break;
...

A função do break é justamente sair de uma instrução (no seu caso, o switch case) e ir para outra. Como seu código não tem mais nenhuma instrução após o switch case (um for, ou um while, ou até mesmo outro switch, etc) ele é encerrado.
Para resolver o problema basta retirar estes breaks que estão logo após as condições do switch (tanto do case a quanto do b).


How to make a purchase in visionOS?'purchase(options:)' is unavailable in visionOS

Question: the code I had fully functional in production is not working for the visionOS, what the heck? I get this error
'purchase(options:)' is unavailable in visionOS: Use @Environment(.purchase) to get a PurchaseAction value to call. If your app uses UIKit, use purchase(confirmIn:options:).
how can I change my code to please visionos demands?
    func purchase(_ product: Product) async throws -> Transaction? {

        let result = try await product.purchase() //TEMPORARY JAN-23

        switch result {
        case .success(let verification):
            // Successful purchase

                //Check whether the transaction is verified. If it isn't,
                //this function rethrows the verification error.
                let transaction = try checkVerified(verification)

                //The transaction is verified. Deliver content to the user.
                await updateCustomerProductStatus()

UPDATE: I REALIZED i need to do purchase the ios17 way, but they ios16 purchase style cannot coexist with ios17 style!! wth!!
I cannot do this
struct PaymentViewVoice: View {
    @Environment(\.presentationMode) var presentationMode
    @EnvironmentObject private var store: Store
    @Environment(\.purchase) var purchase // For iOS 17 payments

error: 'purchase' is only available in iOS 17.0 or newer
and I cannot do this
struct PaymentViewVoice: View {
    @Environment(\.presentationMode) var presentationMode
    @EnvironmentObject private var store: Store //for ios6 payments
    @available(iOS 17.0, *)
    @Environment(\.purchase) var purchase // For iOS 17 payments

error: Stored properties cannot be marked potentially unavailable with '@available'
Comment: The error tells you what to use instead. Is your app based on SwiftUI or UIKit? Use one of the two suggestions based on the answer to that question.
Comment: swiftui, I am starting to implement the @Environment(\.purchase) var purchase for ios17, but I am not able to make io16 payment coexist with ios17 style payments, what a freaking mess, I am really close to give 1% of my revenue to the cat revenue
Comment: @available(iOS 17.0, *)
    @Environment(\.purchase) var purchase //for ios17

Stored properties cannot be marked potentially unavailable with '@available'

so I cannot coexist payments for ios16 and ios17
Answer: visionOS requires SwiftUI code that is only available with iOS 17.0+. Your iOS app supports iOS 16.0+. One solution is to use compiler directives so that the SwiftUI/iOS 17+ code is only built for the visionOS version of the app and the "older", non-SwiftUI, StoreKit APIs are used for the iOS version of the app.
Something like the following:
struct PaymentViewVoice: View {
    @Environment(\.presentationMode) var presentationMode
    @EnvironmentObject private var store: Store
#if os(visionOS)
    @Environment(\.purchase) var purchase // For iOS 17 payments
#endif

If you have any code that is only for the SwiftUI/iOS 17+/visionOS version, wrap that code in:
#if os(visionOS)
#endif

If you have any code that is only for the iOS version (both iOS 16 or iOS 17), wrap that code in:
#if os(iOS)
#endif

If you have a section where there is code for both, wrap the code in:
#if os(visionOS)
    // visionOS specific code
#else
    // iOS specific code
#endif

One simplified example might be in a button handler:
Button {
    Task {
        let purchaseResult: Product.PurchaseResult
#if os(visionOS)
        // visionOS specific code
        purchaseResult = try await purchase(product)
#else
        // iOS specific code
        purchaseResult = try await product.purchase()
#endif
        // Process the purchase result.
        switch purchaseResult {
        }
    }
} label: {
    Text("Purchase")
}

Comment: Note: I do not have an Apple Silicon Mac so I can't actually test this code for visionOS. If anyone has an issue with this code, please let me know so I can update the answer as needed.
Comment: thanks, let me try, I already use #if os for tvos, let's see it compiles
Comment: yes, it was an xcode thing that was pointing me to the wrong path. thanks!!
Comment: so all the purchase code remains the same as storekit2? (updatetransactions etc) i couldn't find anything on wwdc that refers to the new@Environment(\.purchase) var purchase
Comment: This works good! Just don't forget to import StoreKit.
Comment: @swiftyboi why doesn't it make sense? StoreKit is the framework for working with app purchases.


What is the relationship between the cofinality and well orders?

Question: Suppose $A$ is an infinite linear order with cardinality $\kappa$, and take the family $\langle A_{\alpha}: \alpha < \kappa \rangle$, define like this:
$$A=\bigcup_{\alpha < \kappa} A_{\alpha}$$
for all $\alpha < \beta < \kappa$, $A_{\alpha} \subseteq A_{\beta}$. and for all $\alpha < \kappa$, $A_{\alpha}$ is a well order. I need to prove that if $cf \kappa > \omega$ then A is a well order.
I have tried to develop the fact that a well order is a linear order with no infinite descending chains, but I don't know what else to do, if someone could help me or guide me i would really appreciate it.
Answer: Suppose $A$ is not a well order. Then we can find an infinite descending sequence $a_1 > a_2 > \dots$ in $A$. Each $a_n$ belongs to some $A_{\alpha_n}$ for some $\alpha_n < \kappa$. Since $\kappa$ has uncountable cofinality, there is some $\beta < \kappa$ such that $\alpha_n < \beta$ for every $n$. But now, each $a_n$ belongs to $A_{\beta}$ contradicting the fact that $A_{\beta}$ is well ordered.


Can a function nontrivially have this uniform zero-integral property?

Question: I am looking for a function $f:[0\;\pmb,\;1]\to\Bbb R\setminus\{0\}$ such that$$\int_a^bf(x)\;\mathrm dx=0\quad\text{for all }a,b\in[0\;\pmb,\;1].$$
Clearly such a function cannot be Riemann-integrable. But is there one under a more-general (e.g. Lebesgue) type of integration? The more I look at it, the more I doubt it. But I can't prove that there is no such function.
Comment: If $f$ is Lebesgue integrable then you must have $f(x)= 0$ ae.
Comment: @copper.hat : Thank you. Do you have a link to a proof of this?
Comment: It follows from the fundamental theorem of calculus applied to $t \mapsto \int_a^t  f(x)dx$.
Comment: @copper.hat : Sorry, I don't get it. The fundamental theorem of calculus applied to your function $t\mapsto0$ is not relevant. The (first or second) fundamental theorem cannot be applied to $f$ itself, because $f$ is not assumed to be Riemann-integrable or have an antiderivative. If it were so, the question would be trivial.
Comment: Look at https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus#Generalizations
Comment: @copper.hat : I read that before I posted my comment.
Comment: The function I mentioned above is diferentiable ae. and so $f(x) = 0$ ae. which contradicts your assumption. Hence no such function can exist.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/102042/discussion-between-john-bentin-and-copper-hat).
Answer: As copper.hat stated in a comment, if $f$ is Lebesgue integrable and satisfies your condition, then $f(x)=0$ almost everywhere.
Now if $f$ additionally is continous, then $f(x)=0$ everywhere.
If on the other hand $f$ is not continuous, this doesn't need to be true. For example $f(1/2)=1$ and $f(x)=0$ otherwise is Lebesgue integrable and satisfies your condition.
Comment: (1) Why is your first statement true? (2) Regarding the second statement: Yes, this is easily proved; but it doesn't address the question. (3) Your example (which is even Riemann-integrable) violates the condition that $f(x)$ is nowhere zero; please read the first line of the question.


Distribution of N objects into C bins that are then sorted?

Question: Let's say we have $C$ bins and $N$ indistinguishable objects. For each object we choose one bin at random where each bin is equally likely (with probability $1/C$). Let $B_k$ be the number of objects in the $k$-th bin after all objects have been distributed. It seems that all $B_k$ individually must be Bernoulli-distributed, but if you consider $B = (B_1,B_2,\ldots,B_C)$ as a multivariate random variable, then I think we have a multinomial distribution, that is
$$P(B = \vec t) = \begin{cases} \binom{N}{t_1,t_2,\ldots,t_N} \frac{1}{C^N} & \text{ if } \sum_k t_k = N \\ 0 & \text{ otherwise } \end{cases}$$
Now consider a new random variable $G = sort(B)$, which means for every $G$ that has a positive probability we have $G_1 \leq G_2 \leq \ldots \leq G_C$ (and obviously $\sum_i G_i = N$).
Is it possible to find the distribution of $G$ explicitly? Or at least an explicit formula for the expectation $E[G]$?
The reason I'm asking is that it seems that (if you choose $C$ and $N$ large enough) the distribution will converge to some curve. Here is a plot of a sample that was computed with $C=100$ and $N=10000$ and you can already see a nice reverse-s shaped curve to which this distribution seems to converge to. I'd like to find out whether this is actually the case and if possible find a formula for this curve (by computing $E[G]$).

Just for reference, here is the snipped used to generate this plot:
<code>import matplotlib.pyplot as plt
import numpy as np
C=100
N=10000
a = np.random.random(N)
a = np.round(a*C)
b = plt.hist(a, bins=C)
c = b[0]
c.sort()
plt.clf()
plt.bar(list(range(1,C+1)), c)
plt.show()
</code>
Answer: The multinomial distribution can be approximated by independent binomial distributions, and when the numbers are large those will be approximately normal distributed variables (with mean $N/C$ and variance $N/C (1-1/C)$).
Then the value of $B_i$ will be approximately the $i/N$-th quantile of that normal distribution. (more precisely it will follow some joint order statistic, but with growing numbers the approximation becomes better)
So you are looking at something that resembles the quantile function of the normal distribution.


Prove that ¬ is an equivalence relation

Question: Let $¬$ be a relation on $\mathbb{R}$ defined by $x¬y$ if $$y-x\in\mathbb{Z}$$
Prove that $¬$ is an equivalence relation on $\mathbb{R}$.
How would one go about doing this? My gut instinct tells me to use the definition of an equivalence relation which in my book is that it's reflexive, symmetric and transitive. Thing is, how would I show any of those to be true?
I have a proposed solution here to this:

$\underline{\textbf{Reflexivity}}$

Let $y\in\mathbb{R}$. Then $y-y=0$ and $0 \in\mathbb{Z}$, so $y¬y$.

$\underline{\textbf{Symmetry}}$

Let $a,b \in \mathbb{R}$ and $m\in\mathbb{Z}$. Suppose $a¬b$, then $a-b \in \mathbb{Z}$. Say $a-b=m$ implying $b-a=-(-a-b)=-m$ and $-m\in\mathbb{Z}$. Thus, $b¬a$.

$\underline{\textbf{Transitivity}}$

Let $a,b,c\in\mathbb{R}$ and $m,n\in\mathbb{Z}$. Suppose $a¬b$ and $b¬c$ meaning $a-b$ and $b-c$ are both in $\mathbb{Z}$. Also suppose that $a-b=m$ and $b-c=n$. Then $a-c=(a-b)+(b-c)=m+n$. Now, $m+n\in\mathbb{Z}$; that is, $a-c\in\mathbb{Z}$. Therefore, $a¬c$.
Any improvements would be welcome. Got an exam tomorrow!
Comment: Well done.  The idea of problems like this is to verify all the pieces of the definition
Comment: Note that if you define f(x) = x-n, where n is the largest integer less than or equal to x, then x¬y is equivalent to f(x) = f(y). Any relation that can be put in the form "x and y get sent to the same output" for some function is an equivalence relation.
Comment: Looks perfect to me; except for transitivity (and reflexivity), you may first suppose that $a¬b$ and $b¬c$ ($y¬y$), followed by the definition.
Comment: @poyea I'll change it to reflect that. Thanks!
Comment: You proof is just fine.  It might be interesting to realize that this realation is "have the same fractional part" or "$x - \lfloor x\rfloor = y - \lfloor y\rfloor$" or: if $n \le x < n+1$ and $m \le y < m+1$ where $m$ and $n$ are integers then $x¬y$ means $x -n = y -m$
Answer: Your proof is correct and well-presented. Good job!

Mostly posting this so this question can be finally considered to have an answer and thus be removed from the unanswered queue. Made it Community Wiki since I have nothing much of substance to add.

Prove that ¬ is an equivalence relation


Javascript switch statement not working?

Question: function decinumber(y){
var x = document.getElementById("areafield").value;
  if (x == 0){  alert(x);
   switch(y){
   case "one": x = 1; break;
   case "two": x = 2; break;
   case "three": x = 3; break;
   case "four": x = 4; break;
   case "five": x = 5; break;
   case "six": x = 6; break;
   case "seven": x = 7; break;
   case "eight": x = 8; break;
   case "nine": x = 9; break;
   case "zero": x = 0; break;
    }
   }
 }

The varible y in this function is an id, which the function gets from the button clicked in the HTML. The switch statement is not being accessible because when I put the alert statement within the switch braces it doesn't work, but when it is within the if braces it works.
Comment: so x is obviously zero, but y is not in range you listed in switch
Comment: I hate these type of questions: _"Switch is not working"_... of course it is. `switch` works just fine, the issue isn't `switch` is how you use it. Never blame the tool for what it does in the hands of an even bigger tool. I don't mean this cruelly, but check the value of `y`, and I bet you'll find the issue is not `switch`, it's the rest of your code
Comment: You can't have an alert inside the `switch` braces, you can only have `case` and `default` statements there.
Comment: @AdrianToma: Read the question: *"when I put the alert statement within the switch braces it doesn't work, but when it is within the if braces it works"*
Comment: @Guffa his alert is before the switch statement, look closer
Comment: Also, you most likely don't want to use `x == 0` as this also returns true if e.g. x is an empty string. It is almost always safer to use `x === 0`
Comment: @Guffa right, OP says alert works *outside* switch, but inside if, and doesn't work *within the switch braces*
Comment: you could try to alert y , or maybe y == "one" for exemple
Comment: @guffa you are right :)
Comment: So, switch is probably works. OP just need to check `x` is altered *after* whole switch statement.
Comment: Are you sure `y` doesn't contain leading or following spaces?
`var x = 'zero|one|two|three|four|five|six|seven|eight|nine'.split('|').indexOf(y.toLowerCase().trim());` -- no ungly switch statement.
Answer: It works Well here is the Fiddle
Fiddle
function decinumber(y){
var x = 0;
if (x == 0){  alert(x);
switch(y){
case "one":{ x = 1;alert(1); break;}
case "two": x = 2; break;
case "three": x = 3; break;
case "four": x = 4; break;
case "five": x = 5; break;
case "six": x = 6; break;
case "seven": x = 7; break;
case "eight": x = 8; break;
case "nine": x = 9; break;
case "zero": x = 0; break;
 }
 }
 }

decinumber('one');

Answer: I copy/paste you code and adapted it for jsfiddle... It's working for me :-)
You must check your x variable, it should be set to 0. And you must be sure that your y values are === the switch expression thats it :-)
EDIT : Add some code here after
By the way, I prefer this syntax instead of Switch ... case one
function decinumber(y) {
    var hash = {
        'zero'  : 0,
        'one'   : 1,
        'two'   : 2,
        'three' : 3,
        'four'  : 4,
        'five'  : 5,
        'six'   : 6,
        'seven' : 7,
        'eight' : 8,
        'nine'  : 9
    }

    // carefull, I'am replacing the value of the x input value, instead of just putting x
    var x = document.getElementById("areafield");
    if (x.value == 0 || x.value == '') {
      x.value = hash[y.toLowerCase()];
    }
 }

Comment: The variable y in this function is an id. I am not sure if that makes a difference.
Comment: If the ID is a string it's OK, you must check the case too because === is case sensitive :-)
Maybe you can add a jsfiddle if the real code slightly differ ;-)


What is the subscription stanza should be sent from my .net app to get XMPP notification from GAE app

Question: Quick question: What is the subscripiton stanza should sent from my .net app to GAE app.
Background is :
I want to have a google app engine app act as a Web end point which receives notifications from Google Mirror SDK by JSON over HTTP and relays notification back to the subscribed XMPP clients. From Google App Engine, it sends invitation and sends messages that can be seen from Google Talk client on my windows system. I want to make my .net app similar to Google talk client, i'm trying with agXMPP library, after sending subscription stanza, it throws exception and disconnects the connection.
What is the correct subscription stanza i should send?
I'm sending:
<code> <iq to="email@example.com" id="agsXMPP_1" type="set">
   <subscribe xmlns="google:push">
   <item from="test_appid.appspot.com" channel="test_appid.appspot.com" />
   </subscribe>
 </iq>
</code>
Thanks
Answer: I tried myself and figure it out. Just accept the invitation and send IQ object like this after opening the connection:
            IQ iq = new IQ();
            Jid jid = new Jid("email@example.com");
<code>        iq.To = jid;
        iq.From = _bareJid;
        XmppCon.Send(iq);
</code>
It worked.


Sound of my voice seems to have changed!

Question: as a singer, i have been struggling with a problem for almost a year now.
The sound of my voice has changed. Quite suddenly, after a laryngitis in Feb 2016.
It used to be a warm, slightly breathy sound that i liked. Now it takes a lot of effort to get the same sound, especially when singing more powerfully and in a higher pitch. Additionally i suffer from severe vocal fatigue (burning pain around the larynx after only a couple minutes of talking or even singing a line or two).
It feels as if there is less space in the larynx area. I always had to force my muscles there a bit to get rid of a mildly twangy sound, but now the twangy sound is much worse. I have to force my muscles in a certain way to create more space and find the old sound of my voice. This is very fatiguing. I have a lump in my throat sensation, too.
ENT saw nothing wrong with my voice  or throat after the laryngitis had healed but the symtoms stayed.
Vocal therapist gave up when i told her even the lax/vox exercise caused pain and fatigue.
Manual / crafta therapist noticed a lot of tension in my neck / throat / upper back but after a couple sessions loosening this up, the vocal fatigue or the changed sound are still there.
Anyone any thoughts on this?
I am heartbroken over this. I have not been able to sing almost a year (and i am a singer songwriter) and still have not found out what causes this or how to tackle this problem that has been affecting every area of my life.
I am a 32 y/o woman. Could it just be my voice getting older / changing sound and do i have to live with it? Could it be caused by a mourning process i am going through at the moment?
Answer: The answer to almost all of your questions is "yes, probably."  It may take a long time for your vokes to fully recover from laryngitis; the stress of mourning can affect stuff, and so on.
It's always a good idea to consult a specialist (medical,  not just a general ENT person but one who regularly works with pro singers) if for no other reason than to rule out physical damage to your vocal cords.
You didn't state specifically whether you've stopped singing, so I'll point out the obvious: try no singing, no humming, and as little talking as possible for a month or two and see if some healing occurs.
Comment: I agree with your conclusion. It seems like a classic "Doctor! It hurts when I do this!" scenario.
Comment: Thank you so much for your response Carl! I have been to a different ENT doctors and one was also a vocal therapist. Several times they've looked at my vocal chords with a camera through my nose as they asked me to make sounds. They could see nothing wrong. No nodules or whatsoever. They also vibrated fine. The manual therapist checked my gag reflex which looked normal which proved there's no vocal paralysis either. The last option was muscle issues, tension whatever. I really hoped the manual therapist could help. Now i can't think of anything that could be the cause of my change of voice.
Comment: And yes, i have stopped singing because it sounds bad and it hurts, so i can't enjoy it anymore. I try every once in a while whether it's getting any better. Sometimes it sounds and feels better. But most of the time, the same issues..
Answer: An interesting question, and I can understand your frustration. To answer your question, I feel the need to explain a few things of which you may or may not be aware. Through reading each of them, I think you'll find the answer to your question.

Aging
As you age, your vocal folds relax (losing their initial elasticity). As a result, not only will your voice continue to get lower in range, but you'll have to continue training your voice to compensate. Your voice will continue to change throughout your life and this is normal for everyone.
Breathy (Aspirate) Singing
"Breathy" singing, while popular (and emphasized with editing), may have been something you could control when you were younger, the production of this sound is especially difficult the higher / louder you try to sing (you're asking your voice to do opposite things here). Breathy is easier when you're singing quiet and lower. Trying to sing high, loud, and breathy is asking for trouble.
Vocal Fatigue
You should rest for a while. A week at least with little or no talking. Professional vocalists, when they go on "vocal rest" don't talk at all. If you're serious about your voice, you need a completely silent vocal rest for at least a week. Drink tons of water to help your voice repair and hydrate the folds.
Given that your illness caused a lot of swelling / damage, I think it would be best if you re-started from the beginning; pretending that you're a new singer. When you do sing again, sing for a few minutes only, and as you re-learn proper technique / production, you can gradually increasing your time spent singing as your stamina and technique improves.
Singing songs you wrote in your early 20's that really high / out of your range will cause fatigue very quickly. You will find throughout your life that you will likely need to change the keys of your songs to accommodate your voice as your voice ages and matures.
Good luck.


How to quantify correlation stability?

Question: In many financial models we are interested in measuring the correlation between variables, returns etc. However, research shows that during crises times we observe "Correlation Breaks" where previously un-correlated variables become correlated.
What is the best way to quantify "stability of correlation" by examining the historic time series of the variables on which I am interested?
Would some kind of bootstrapping be a good way to start examining the sample distribution of the correlation? Is there any other method that I could apply?
Comment: A useful literature to start at is the financial contagion literature. Take a look at Forbes & Rigobon (2002) in the `Journal of Finance` and the papers that this research has spawned. (This is dedicated research into whether correlations change during crisis events).
Comment: Vaguely along the lines of your bootstrapping comment, you could consider partitioning the data set and looking at the cross correlation in each partition and see if there is a trend
Comment: Thanks Macro. Partitioning of the data is I assume a very specific variation of bootstrapping where although my data are partitioned in smaller samples, every sample consists of observations of consecutive days. Do you think that it would be good practice to pick up samples from non-consecutive days for financial data (where time plays a role) and examine the correlation?
Answer: You might want to compare constant conditional correlation with dynamic conditional correlation. In R, the ccgarch package will be helpful. In Matlab, Kevin Sheppard has an implementation of DCC.
Comment: ProbablePattern thanks a lot! Would it be possible to elaborate a bit more on the concepts of Constant Conditional Correlation and DCC? My understanding is that for DCC we calculate the current correlation between variables as a function of their past correlations and their past volatilities by using similar methodology to GARCH models, am I correct? Also by CCC do you mean the commonly used correlation coefficient(ρ)?
Comment: DCC is a two step process. The first step is to run a GARCH model. This model can use any appropriate lag but usually a GARCH 1,1 model is sufficient. The second step is to fit the covariance matrix to the residuals of the GARCH model. The paper by Engle (2002) explains the mathematics and both Matlab and R packages automate the entire process. The CCC is the common correlation coefficient.
Comment: One way to use these is to use the CCC to construct a confidence interval and determine if the DCC ever violates either the high or low edge of the interval for any pair of variables. You could also use log likelihoods of both models for testing but I don't know enough of the math to explain the process. At the very least, if you decide to use either CCC or DCC, you should show that DCC is either warranted or not. If you have a few variables, I like the pair method that I described because it can easily be shown graphically.
Answer: You could start with a simple 'rolling' analysis of the correlation to see how stable it is over time.  Here is an example in R:
<code>#Get Data
require(quantmod)
getSymbols(c('SPY','EEM'))

#Rolling Correlation (30 days)
require(PerformanceAnalytics)
chart.RollingCorrelation(Cl(SPY), Cl(EEM), width=30)
</code>
Comment: Thanks Zach, that looks as a possible simple way to check evolution of Correlation over time. I assume to quantify, I would have to measure the St.Deviation of the observations and accept or reject the hypothesis of stable correlation. This is similar to the bootstrapping method that I was mentioning above. Do you think that taking non-consecutive samples would be acceptable for financial data? (e.g. returns on stocks?)
Comment: Sure,  you could use some kind of statistical test to quantify how far from the mean there series gets during 'events.'  In the case of EEM vs SPY it's pretty obvious from the graph... Your re-sampling method sounds like 'blocked-bootstrap' re-sampling, and I think there's R packages to implement that method on time series data.  It's certainly more appropriate than using regular bootstrap re-sampling, but your milage may vary.

How to quantify correlation stability?


shortest path or route algorithm

Question: There are pre-defined routes.
Route1 [Edirne (1)-Kırklareli (2)-Istanbul (3)]
Route2 [Istanbul (3) - Sakarya (4) - Zonguldak (5)]
Route3 [Istanbul (3) - Kutahya (6) - Afyon(7)]
Route4 [Afyon(7) - Isparta (8) - Anatlya(9)]

Every route has a vehicle which traverses on it.
For example, if some goods will be sent from Edirne(1) to Antalya(9) Route1-Route3-Route4 must be chosen.
If the case is Zonguldak to Edirne Route1-Route2 must be choosen.
etc..
Shortest path algorithms based on distances between steps and find the "shortest path" not route. Because my locations are in routes, shortest path algorithms are not the correct method for me for this situation. Any ideas on how to solve this problem, || Does anyone have a suggestion?
Answer: Shortest Path still applies; you just need to change your thinking. Rather than include edges between every city on your route, translate Route 1 into Vertices at Edirne and Istanbul and a single edge between them (weighted to your route length). Ignore the fact that it goes through Kirklareli.
Do the same for your other routes and you'll have something like
Edirne--1--Istanbul--2--Zonguldak
               |
               3
               |
             Afyon--4--Anatlya

Then you can apply a shortest path and you'll find that Edirne to Anatlya is 1-3-4, which you then translate back into the full route (Edirne - Kırklareli - Istanbul - Isparta - Anatlya)
Comment: i need a touch to change my thinking you did this, thanks. Absolutely the solution is shortest path algorithm.

shortest path or route algorithm


Scala "illegal start of simple expression" when defining a function

Question: I am getting the following error on Scala:
scala> :pas
// Entering paste mode (ctrl-D to finish)

// sum takes a function that takes an integer and returns an integer then
// returns a function that takes two integers and returns an integer
def sum(f: Int => Int): (Int, Int) => Int =
  def sumf(a: Int, b: Int): Int = f(a) + f(b)
  sumf

// Exiting paste mode, now interpreting.

<pastie>:4: error: illegal start of simple expression
  def sumf(a: Int, b: Int): Int = f(a) + f(b)
  ^

I am not understanding why def is an illegal start of simple expression. I am simply trying to declare a function. Am I violating any syntax requirements in the declaration? Thank you.
UPDATE: This is my version of Scala:
sbt:jaime> console
[info] Starting scala interpreter...
Welcome to Scala 2.12.10 (OpenJDK 64-Bit Server VM, Java 11.0.14).
Type in expressions for evaluation. Or try :help.

scala>

Comment: I would guess you need braces for declaring a nested method. Although, in this, you don't need to do that, you can just define a function directly: `(a, b) => f(a) + f(b)`
Comment: Running on Scala 3.0.0, the nested function is accepted as-is. It's possible you were looking at some example code intended for Scala 3 but are running it in Scala 2, which doesn't do indentation-sensitivity.
Comment: It works using `def sum(f: Int => Int): (Int, Int) => Int = (a, b) => f(a) + f(b)` as you said @LuisMiguelMejíaSuárez. Please write it as an answer to mark this question as solved. Thank you! It also works using curly braces as you said by the way.
Comment: True @SilvioMayolo. I am running Scala 2.12.10 and most likely the example code I was trying to run was intended for Scala 3. That makes sense. Thank you!
Answer: Two ways to make it work, as Luis Miguel Mejía Suárez mentioned in the comment to this question.
scala> :pas
// Entering paste mode (ctrl-D to finish)

def sum(f: Int => Int): (Int, Int) => Int = {
  def sumf(a: Int, b: Int): Int = f(a) + f(b)
  sumf
}

// Exiting paste mode, now interpreting.

sum: (f: Int => Int)(Int, Int) => Int

scala> :pas
// Entering paste mode (ctrl-D to finish)

def sum(f: Int => Int): (Int, Int) => Int = (a, b) => f(a) + f(b)

// Exiting paste mode, now interpreting.

sum: (f: Int => Int)(Int, Int) => Int

scala>


How do you display the IPv6 NDISC cache in Linux?

Question: Suppose you've configured IPv6 proxy NDP on one of your Linux systems like so:
ip -6 neighbor add proxy 2001:db8:1234::5 dev eth1

How do you verify that the configuration took? ip -6 neighbor show doesn't appear to show proxy entries and ip -6 neighbor show proxy isn't a supported command.
Comment: Maybe `ip -6 neighbor show nud all`?
Comment: That shows more addresses (e.g. `:: dev lo`) but not the proxies.
Answer: I think the ip tool just doesn't print the NTF_PROXY flag. In ip/ipneigh.c, after the NTF_ROUTER block, try adding
   if (r->ndm_flags & NTF_PROXY) {
            fprintf(fp, " proxy");
    }

I don't have an NDP proxy installation, so I can't test it. From reading the kernel sources, however, it appears that the entries will all get returned and the flag should be set for proxy entries.
Comment: That didn't work, unfortunately. I also tried adding "fprintf(fp, " flags: %02x\n", r->ndm_flags);" to the beginning of print_neigh and none of the entries had the NTF_PROXY flag set.
Answer: have you tried ip ntable ?
Comment: It gives me lots of useful information about the NDISC cache, but not the entries themselves. I'm beginning to think these are write-only values, at least for my kernel version.
Answer: For the sake of completeness:
 shell> ip -6 neigh del proxy 2001:db8:1234::1234:5678 dev eth1
 shell> ip -6 maddr show dev eth1
 3:      eth1
         inet6 ff02::1:ff34:5678
 ...

It's just the last 6 nibbles but that's often all you need.


Access value in JsonConverter.CanConvert()

Question: Is it possible to convert a string to a TimeSpan object using a custom JsonConverter, but have it only convert when the string is in the format "hh:mm:ss"?
I've looked at building a custom JsonConverter but the CanConvert() method only accepts a Type object, so there's no way to return false if the string is not in the "hh:mm:ss" format.
Comment: And what would you want to happen when the string is *not* in the format `hh:mm:ss`?
Comment: It should not apply the conversion.
Comment: I don't understand sorry.
Answer: You're correct that CanConvert only deals with Types and so you cannot make the converter conditional on specific JSON values.  However, you said that your desired behavior is that the conversion from string to TimeSpan is not performed if the format does not exactly match hh:mm:ss, which I take to mean that you would expect the TimeSpan in your deserialized object to have a default value of zero, correct?  In that case, you could just make the ReadJson method in the converter do the same thing, i.e. return a default TimeSpan if the format does not exactly match:
public class TimeSpanConverter : JsonConverter<TimeSpan>
{
    public string TimeSpanFormat { get; set; } = @"hh\:mm\:ss";
    public TimeSpan DefaultTimeSpan { get; set; } = TimeSpan.Zero;

    public override TimeSpan Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        string timeString = reader.GetString();
        if (TimeSpan.TryParseExact(timeString, TimeSpanFormat, CultureInfo.InvariantCulture, out TimeSpan timeSpan))
        {
            return timeSpan;
        }
        return DefaultTimeSpan;
    }

    public override void Write(Utf8JsonWriter writer, TimeSpan value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToString(TimeSpanFormat));
    }
}

Here's a short program to demonstrate usage:
public static void Main(string[] args)
{
    string json = @"
    {
      ""TimeSpan1"": ""15:46:03"",
      ""TimeSpan2"": ""3:04""
    }";

    var options = new JsonSerializerOptions();
    options.Converters.Add(new TimeSpanConverter());
    var foo = JsonSerializer.Deserialize<Foo>(json, options);
    Console.WriteLine(foo.TimeSpan1.ToString(@"hh\:mm\:ss"));
    Console.WriteLine(foo.TimeSpan2.ToString(@"hh\:mm\:ss"));
}

public class Foo
{
    public TimeSpan TimeSpan1 { get; set; }
    public TimeSpan TimeSpan2 { get; set; }
}

Output:
15:46:03
00:00:00

Comment: But I only want the conversion to happen if the string is in the required format. If it's not, then the conversion should not happen at all ie. no default value. A string not in the required format should just stay a string.
Comment: How would you represent that property in your class then?  `TimeSpan` and `string` are not compatible.  Would you declare the property as `object`?
Comment: yeah it would be object.


Finding the level of recursion call in python

Question: I have a function which is called recursively and I want to know the current level of recursion. Below code shows the method that I am using to calculate it, but it is not giving the expected results.
E.g. : To find the recursion level for a system path:
    import os
    funccount = 0

    def reccount(src):
        global funccount
        print "Function level of %s is %d" %(src, funccount)

    def runrec(src):
        global funccount
        funccount = funccount + 1
        lists = os.listdir(src)
        if((len(lists) == 0)):
            funccount = funccount - 1
        reccount(src)
        for x in lists:
             srcname = os.path.join(src, x)
             if((len(lists) - 1) == lists.index(x)):
                  if (not(os.path.isdir(srcname))):
                       funccount = funccount - 1
             if os.path.isdir(srcname):
                runrec(srcname)

    runrec(C:\test)

Problem : Given a directory path, print the level of recursion for directory
Directory Structure is :
In my directory structure, i will call the function "reccount(Test)" (Function will be called with path to MainFolder). I want to know the level of recursion call for each folder. (Directory only)
Test:
   |----------doc
   |----------share
                |----------doc
                            |----------file1
   |----------bin
                |----------common
                             |----------doc
   |----------extras
   |----------file2

When i call the procedure, i get the following result:
    Function level of C:\test is 1
    Function level of C:\test\bin is 2
    Function level of C:\test\bin\common is 3
    Function level of C:\test\bin\common\doc is 3
    Function level of C:\test\doc is 3
    Function level of C:\test\extras is 3
    Function level of C:\test\share is 4
    Function level of C:\test\share\doc is 5

As you can see, when it prints results for bin/common/doc, it prints 3 instead of 4 and all subsequent results are wrong
Comment: I think the title should be "Specifying a level of recursion in a function". I found this looking for "finding the level of recursion of the function" (without modifying the function). Something like the deep of the stack trace, in order to detect deep calls.
Comment: The most straightforward / least-effort solution is at https://stackoverflow.com/questions/34115298/how-do-i-get-the-current-depth-of-the-python-interpreter-stack — use `len(inspect.stack(0))` after `import inspect`. (There's also another answer on that question that is faster, but if speed is an issue then manually passing the depth around should be even faster.)
Answer: def some_method(data, level=0):

    some_method(..., level=level+1)

if __name__ == '__main__':
    some_method(my_data)

Comment: Does it work with variable number of arguments?
Answer: from inspect import getouterframes, currentframe
import os

def runrec(src):
    level = len(getouterframes(currentframe(1)))
    print("Function level of {} is {}".format(src, level))
    for x in os.listdir(src):
        srcname = os.path.join(src, x)
        if os.path.isdir(srcname):
            runrec(srcname)

runrec('C:\\test')

Function level of C:\test is 1
Function level of C:\test\bin is 2
Function level of C:\test\bin\common is 3
Function level of C:\test\bin\common\doc is 4
Function level of C:\test\doc is 2
Function level of C:\test\extras is 2
Function level of C:\test\share is 2
Function level of C:\test\share\doc is 3

Comment: Although Andreas's answer is the obvious choice for the OP, +1 for a solution that doesn't require the extra parameter. Extremely useful for printing nested debug info from a recursive function without the hassle of the extra param.
Comment: if you call this function from another function, the numbers will increase, while recursion depth will remain the same, and parameter based approach lacks this flaw.
Comment: Just a question.. how is the use of getouterframes and currenteframe different from using inspect.stack() ?
Answer: Why don't you store the recursion level in a parameter?
def runrec(src, level=1):
  # ...
  runrec(new_src, level + 1)

That way, you don't need a global variable:
def reccount(src, level):
    print "Function count of {} is {}".format(src, level)


How to programatically update existing user profile field in drupal 7

Question: We are using Drupal 7 and the Profile2 module.
We create and add a value to a field in the profile using this code:
$profile = profile_create(array('type' => 'main', 'uid' => $account->uid));
$lang = LANGUAGE_NONE;
$profile->field_headline[$lang][0]['value'] = 'Software Engg';
profile2_save($profile);

How can we programtically update the user profile field 'field_headline'?
Please advice us.
Answer: You just need to load the user using drupal function
profile2_load_by_user($account->uid, $type_name = NULL)

$account->uid => user id
$type_name => one of the profile types of profile 2 if any otherwise NULL
   $profile =  profile2_load_by_user($account, $type_name = NULL)
   $profile->field_headline[$lang][0]['value'] = 'update Software Engg';
   profile2_save($profile);

For more information Click Here
Hope it will work for you!
Comment: It is not working when i use for term refrence.
Comment: How would you change the profile2 type to something else?
Comment: This solution will not work in Drupal hooks such as hook_user_update().
Answer: Update specific value of user
$user_fields = user_load($user->uid);
$user_fields->field_points['und'][0]['value'] = $points;

user_save($user_fields);


get status info Windows Media Player (stand-alone application)

Question: I want to write an application which gets the status information about a running WMP thread, like playing/paused, shuffle mode on/off, repeat on/off, song title or media file path.
I was using the P/Invoke SendMessage-function to "simulate" a click on the play/pause/stop etc. buttons, but I'm unable read the values of labels/text boxes inside the WMP application with WM_GETTEXT.
I used Spy++ to get the handles of certain text fields - but they (obviously) change their handle after restarting the WMP.
Does somebody know a answer to this Problem?
It could be anything - P/Invoke or SendKeys - but not this AxWindowsMediaPlayer, because my application is a console app and I want the status information of the external process - not of my own.
Thanks
Comment: Did you try the supported way to automate an application, UI Automation?
Comment: @David Heffernan: no - I didn't try it and I haven't got any experiences in this field. I will gooogle it and look, if I find a way to achieve the effect I want.
Answer: I will mark this thread as 'answered'.
I have solved this problem a few months ago, but lost the source code.
The aim of this application is to control the WMP via sshd or telnet.
You can download the binaries here if you want to:
WMP.rar (27 KB)
https://mega.co.nz/#!ug5DySRR!rQlI9OZZ8wYq7yAqaH-KYsmCl9LSaBjNdvqX0g_WDtI
The application is executed via console. You can see the commands by typing >wmp help


How to compare two different Data frames on simile column values and put values to other data frame

Question: I need to automate the validations performed on text file. I have two text files and I need to check if the row in one file having unique combination of two columns is present in other text file having same combination of columns then the new column in text file two needs to be written in text file one.
The text file 1 has thousands of records and text file 2 is considered as reference to text file 1.
As of now I have written the following code. Please help me to solve this.
import pandas as pd

data=pd.read_csv("C:\\Users\\hp\\Desktop\\py\\sample2.txt",delimiter=',')
df=pd.DataFrame(data)
print(df)

# uniquecal=df[['vehicle_Brought_City','Vehicle_Brand']]
# print(uniquecal)

data1=pd.read_csv("C:\\Users\\hp\\Desktop\\py\\sample1.txt",delimiter=',')
df1=pd.DataFrame(data1)
print(df1)

# uniquecal1=df1[['vehicle_Brought_City','Vehicle_Brand']]
# print(uniquecal1

How can I put the vehicle price in dataframe one and save it to text file1?
Below is my sample dataset:
File1:
   fname lname vehicle_Brought_City Vehicle_Brand  Vehicle_price
0   aaa   xxx                 pune         honda            NaN
1   aaa   yyy               mumbai           tvs            NaN
2   aaa   xxx                  hyd        maruti            NaN
3   bbb   xxx                 pune         honda            NaN
4   bbb   aaa               mumbai           tvs            NaN

File2:
  vehicle_Brought_City Vehicle_Brand  Vehicle_price
0                 pune         honda          50000
1               mumbai           tvs          40000
2                  hyd        maruti          45000

Comment: can you explain your problem by giving example?
Comment: As I mentioned in my data set ,I have two text files. One having fname, lname, vehical_brought_city, Vehical Brand ,Vehicle Price.First text file dont have the values for vehicle price .And other text file has vehical brought city,vehicle brand nad vehical price.So what I need to do depending upon the combination of vehical brought city and vehical brand as a combination vehical price need to enter in text file 1 .Like in row 0 I want price as 5000 and for row 4 want price value as 4000.
Comment: ok i got your problem
Comment: Possible duplicate of [Merge two DataFrames based on multiple keys in pandas](https://stackoverflow.com/questions/32277473/merge-two-dataframes-based-on-multiple-keys-in-pandas)
Comment: In my actual data set file 1 has thousands of record and file 2 has only 30 records.Both file  has vehical_brought_city and Vehical_Brand Basically we can say file 2 is reference file. so depending upon the combination of vehical_brought_city and Vehical_Brand I need to put value of Vehical_Price in file 1. I created a dataframe for that but I am stuck how I can iterate through different dataframe?   is merge works in this case too?
Answer: del df['Vehicle_price']
print(df)

dd = pd.merge(df, df1, on=['vehicle_Brought_City', 'Vehicle_Brand'])
print(dd)

output:
  fname lname vehicle_Brought_City Vehicle_Brand  Vehicle_price
0   aaa   xxx                 pune         honda          50000
1   aaa   yyy               mumbai           tvs          40000
2   bbb   aaa               mumbai           tvs          40000
3   aaa   xxx                  hyd        maruti          45000


How to set default value for entity reference programmatically in a form?

Question: I have a custom form that I created programmatically.
    $target_type = 'node';
    $selection_handler = 'default';

    $selection_settings = ['page'];
    $data = serialize($selection_settings) . $target_type . $selection_handler;
    $selection_settings_key = Crypt::hmacBase64($data, Settings::getHashSalt());

    $key_value_storage = \Drupal::keyValue('entity_autocomplete');
    if (!$key_value_storage->has($selection_settings_key)) {
      $key_value_storage->set($selection_settings_key, $selection_settings);
    }

    $form['terms_default_node'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Terms of Business - default page'),
      '#autocomplete_route_name' => 'system.entity_autocomplete',
      '#autocomplete_route_parameters' => [
        'target_type' => $target_type,
        'selection_handler' => $selection_handler,
        'selection_settings_key' => $selection_settings_key,
      ],
      '#default_value' =>  \Drupal\node\Entity\Node::load(1)->value, // What do I put here?
    ];

I don't get how to make the default value of the field be "Terms of Business (1)".
Autocomplete works, saving works, but I don't know how to recall that saved value again and make it as default_value when I open this form again.
This field doesn't have any widgets, etc. And I can't find anything in Google
Comment: Does this help? https://drupal.stackexchange.com/questions/203559/how-to-set-default-value-for-entity-reference-field-in-hook-form-alter
Comment: @cilefen I think this is some weird bug that I have encountered. Today I used a different approach and it worked out.
Answer: This whole approach of entity autocomplete is not okay. Here is the correct way, and also it accepts Node Object as the default value well.
    $form['terms_default_node'] = [
      '#title' => $this->t('Terms of Business - default page'),
      '#type' => 'entity_autocomplete',
      '#target_type' => 'node',
      '#selection_handler' => 'default',
      '#selection_settings' => [
        'target_bundles' => ['article', 'page'],
      ],
      '#default_value' => $this->entityTypeManager->getStorage('node')->load($id), // Dependency injection.
    ];


How can I change the hight of the left and right border of the block quote and connect the border to another div?

Question: Block Quote Example
I'm trying to make my blockquote look like the image attached. I have the top and bottom gradients down, but I'm stuck on the left and right borders and I'm not sure how to round the quotations more. Also, I was wondering how to make a line to the right that connects to the picture. Thanks for the help!
Here's what I have so far

/*-------Testimonial Section Styles---------*/

section#testimonial-section {
  height: 300px;
  margin-top: 100px;
  width: 100%;
}

/*------Block Quote Sttyles-------*/

.testimonial-paragraph-wrapper {
  width: 100%;
  padding: 20px;
  margin: 10px auto;
  text-align: center;
}

.testimonial-border {
  display: inline;
  margin-left: 117px;
  float: left;
}

blockquote {
  width: 100%;
  padding: 36px 50px;
  position: relative;
  background: transparent;
  margin-bottom: 0px;
  /* gradient shining border */
  background-image: linear-gradient(to left, rgba(108, 178, 61, 1) 100%, rgba(108, 178, 61, 1) 100%, rgba(108, 178, 61, 1) 100%), linear-gradient(to left, rgba(108, 178, 61, 1) 100%, rgba(108, 178, 61, 1) 100%, rgba(108, 178, 61, 1) 100%);
  background-size: 90% 5px;
  background-position: 100% 0%, -510% 100%;
  background-repeat: no-repeat;
  border-left: 5px solid rgba(108, 178, 61, 1);
  border-right: 5px solid rgba(108, 178, 61, 1);
}

cite {
  font-style: normal;
  text-align: right;
  float: right;
  padding-right: 100px;
  padding-top: 20px;
}

blockquote::before,
article blockquote::after {
  top: 0;
  bottom: 0;
  width: 25px;
  content: '';
  position: absolute;
  background: #61a036;
  -webkit-box-shadow: 0 2px rgba(0, 0, 0, 0.25);
  box-shadow: 0 2px rgba(0, 0, 0, 0.25);
}

blockquote::before {
  right: 100%;
}

blockquote::after {
  left: 100%;
}

blockquote p {
  font-size: 20px;
  line-height: 1.5em;
  margin-bottom: 28px;
  color: #61a036;
  padding-left: 40px;
  padding-right: 40px;
}

blockquote p::before {
  top: 0;
  left: -33px;
  color: #61a036;
  content: '"';
  font-size: 10em;
  position: absolute;
  text-shadow: -3px 0 #000;
  padding-top: 0px;
}

blockquote p::after {
  right: 16px;
  color: #61a036;
  content: '"';
  bottom: -32px;
  font-size: 10em;
  position: absolute;
  text-shadow: 3px 0 #000;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />

My son had to go to the doctor's office and my insurance didn't pay for some of it, and rent was due ... then I looked at the calendar...I was going to be getting a big payment from FusionCash in only 3 more days, straight to my PayPal®
                account!

              - John Hughes of Grants Pass, OR

Comment: For the left and right borders, I would import a better looking quotation image icon with white background https://thenounproject.com/search/?q=quotation&i=1247733 , place it above the corners of the box to hide the left/right borders. To connect the quote and the image you could absolute position a `` element. And then your baby image would need a border and some padding to match your reference image. This is ofcourse only my suggestion depends on if you need responsiveness or how dyanamic this layout would be~
Answer: The connecting line can easily be done with flexbox, just use a pseudo element on your container and adjust the position with order.
(I took the bootstrap out of the equation, to simplify things... adapt as needed)

/*-------Testimonial Section Styles---------*/
#testimonial-section{
  margin:20px;
  display:flex;
  align-items:center;
  position:relative;
}

#testimonial-section:before{
  content:"";
  height:4px;
  flex:1 1 10%;
  background:#61a036;
}
.testimonial-img{
  flex:1 1 20%;
  border:4px solid #61a036;
  border-radius:50%; padding:10px;
  display:inline-block;
  height:100%;
}

#testimonial-section blockquote{
  margin:0;
  border:4px solid #61a036;
  flex:1 1 70%;
  position:relative;
  color: #61a036;
  font-size:1.5em;
  font-family:sans-serif;
  order:-1;
}

#testimonial-section blockquote:before, #testimonial-section blockquote:after{
  text-align:center;
  background:white;
  position:absolute;
  font-size:8rem;
  width:4rem; height:5rem;
}
#testimonial-section blockquote:before{
  content:""";
  top:-2rem;
  left:-2rem;
}
#testimonial-section blockquote:after{
  content:""";
  bottom:-2rem;
  right:-2rem;
}

.blockquote-text{
  padding:1em;
}

cite{
  font-size:1rem;
  position:relative;
  top:0.5rem;
  background:white;
  float:right;
}

My son had to go to the doctor's office and my insurance didn't pay for some of it, and rent was due ... then I looked at the calendar...I was going to be getting a big payment from FusionCash in only 3 more days, straight to my PayPal® account!

    - John Hughes of Grants Pass, OR

The rest should be just positioning.


Duvida em porcentagem em C

Question: O usuário tem que dar um valor que seria o preço do produto
e um valor que seria o desconto
Na hora de dar o valor final eu não consigo
já tentei algumas coisas
#include <stdio.h>

int main ()
{
    float preco, desc, end;
    printf("Qual o valor da compra? ");
    scanf("%f", &preco);

    printf("Qual o valor do desconto? ");
    scanf("%f", &desc);

    end = preco / desc;
    printf("O valor final e: %f", end);
}

Answer: O cálculo correto do valor com desconto é:
end = preco - ( preco * desc / 100 );

considerando que desc é o valor do desconto (em porcento) entre 0 e 100.
Answer: Sua fórmula para o calculo de desconto está errada, nesse caso, como você quer descontar o valor você precisa subtrair o preço pela multiplicação do preço pelo valor da porcentagem.
Nesse caso o seu código ficará assim:
int main ()
{
    float preco, desc;
    printf("Qual o valor da compra? ");
    scanf("%f", &preco);

    printf("Qual o valor do desconto? ");
    scanf("%f", &desc);

    printf("O valor final e: %.2f", preco - (preco * desc/100));
}

A saída ficará assim:
Qual o valor da compra? 10
Qual o valor do desconto? 5
O valor final e: 9.50

Note que retirei a variável end pois voce não precisa dela. Espero ter ajudado :)
Answer: Você pode fazer da seguinte maneira.
Descontando 10% no valor de R$30,00 temos:
30 * 0,90 = R$27,00
end = preco * porcentagem_do_desconto;
para acréscimos basta que o valor da porcentagem esteja dessa maneira "30 * 1.10"

Duvida em porcentagem em C


Quiz results/score are over 100 points

Question: I have a quiz with 5 questions of 10 points each one. When I score them, some exams save the result of the quiz with more than 100 points.

As you can see, I have an exam with 112 but if I open:

Look that the total score is 92% (but his score is 112).
In the other hand, the user with 100 scores is right.
So, as summary of this, I've got users with right total score but some of them have a wrong final score.
The module that I'm using is Quiz drupal.org/project/quiz version 7.x-5.0-alpha9.
Any idea?
Thanks!
Comment: I'm voting to close this question as off-topic because it looks like a bugreport to whatever module you are using. And even if bugreports weren't defined off-topic here, you didn't post relevant data - link to module you are using, definition of your quiz, information on debug steps you already did, and so on.
Comment: The module that I'm using is Quiz https://www.drupal.org/project/quiz version 7.x-5.0-alpha9. Maybe it can be a common error of the module. I haven't just found about it.
Comment: Alpha versions are known to have bugs. They are early tests, before beta ("I hope there are no bugs") and release candidate ("I believe there are no bugs, but let's test one last time")
Comment: @Mołot ... You're mostly right, except when there are alfa versions used in like 30K sites, such as https://www.drupal.org/project/usage/conditional_fields ... A sample of "versions" that are not correctly named anymore I think, would you agree that most of these 30K sites just ASSUME there are no bugs?
Comment: @Pierre.Vriens nope. All we know is that they assume quality level they are willing to accept. Apart from that, it's either a bug report or question lacks data needed to answer, version number on module changes nothing.
Comment: @Mołot: agree with your last comment. But my prior comment was only to point out that for some modules those alfa, beta, rc indications are not correctly named (because mostly the maintainer never "called it a real release" so far). You don't want a dozen (of dozens ...) of similar modules with a similar release qualifier, do you?
Comment: @Pierre.Vriens if maintainer don't care enough to bump version to rc or stable, I think it should be a reason to be cautious and have development manhours available... Because actual big fixes take even more time and effort, so if he missed easy tasks, he just might missed harder ones, too.
Comment: @Mołot : that might be true, but know that often it is not a matter of "don't care", but rather "whenever such maintainer has time to do so" ... Which is especially true for those thousands of maintainers who "contribute" part of their spare time to develop, maintain (and support ...) their module(s). But maybe those "development manhours available" that you mean could be implemented by "sponsoring" (or "donating to")  those spare time contributors (so that they can make their living from it some day also ...). Back to the original question maybe?
Answer: Thanks everyone for your answer. Finally, I've achived to solve the problem. At first, this bug comes from last versions.
If you create in this module a Long Question which max score is 0, it creates an inconsistency because you cannot divide by 0.
Some months ago, I found a patch to solve it:
https://www.drupal.org/node/2394759
But it's incomplete, because the module save the scores of each question in database and then it updates the total score adding the score of each one.
So, the way to solve that is changing the next lines in the same file that the patch file (../question_types/long_answer/long_answer.module):
db_update('quiz_node_results_answer')
  ->fields(array(
     'points_awarded' => $points_awarded,
     'is_correct' => $is_correct,
))

to
db_update('quiz_node_results_answer')
  ->fields(array(
     'points_awarded' => $calculated_score,
     'is_correct' => $is_correct,
))

To note the change is the variable $points_awarded for the variable calculated in the patch: $calculated_score.
With these changes, the patch is complete and everything is working.

Quiz results/score are over 100 points


How should i bind array with multi select options from dropdown in Angular-2

Question: I am trying to bind the array object with multi select dropdown so I can pass the selected values to model to save with other model details.
Here I am using change event to receive the selcted options value but the function is not working here is my code:
HTML Code:
label class="col-md-3 form-control-label text-right">Customer Name

             <select  multiple="multiple" class="js-example-basic-multiple form-control selectsizing" (change)="oncustomerSelect($event.target.value)" name="customer_name" [(ngModel)]="customer_name.customer" #customer_name="ngModel" [ngClass]="{ 'is-invalid': f.submitted && customer_name.invalid }"  required>
              <option></option>
              <option [value]="customernames.Business_name" *ngFor="let customernames of model_customername">{{customernames.Business_name}}</option>
     </select>

On select any values for dropdown the function oncustomerSelect() should be called which is described in component.ts, but this function call can not be done.
Here is my Component.ts:
 customer_name:any={
    customer:[]
};
model:any={
product_type:"in stock",
item_code:"ASD34",
customer_name:[]=[]
}

oncustomerSelect(value){
console.log("customer select::"+JSON.stringify(value));
var i=0;
this.model.customer_name[i]=value;
i++;
console.log("model customer::"+JSON.stringify(this.model.customer_name));
}

Please help me, how the function can be called in multiple select and how should I bind array with selected values?
Thank You!
Comment: create small demo on stackblitz
Answer: Check for the reference ! in given link you can see you will get the drop-down selected value ,you may can add multi select property and get this done
angular5-select-option-dropdown
Comment: Sir ,This answer is correct for selecting single value from dropdown but i need the selection of multiple values from dropdown and then bind them in a array. please help me in this  @AmitGolhar
Comment: @naincyjain you can use multiple attributes for your selection option, it will work !
Comment: @AmitGolhar Thank You Sir! This one is working ,there was a problem of Bootstrap Class in my code.


Why does Scanner use Scanner#ioException() instead of throwing the exception?

Question: Is there any benefits/downfalls to this?
Usually, you would throw an exception when reading from a stream:
try {
    inputStream.read();
}catch(IOException e) {
    e.printStackTrace();
}

But when using a Scanner, you are not forced to handle the exception. Instead, if one is thrown, you would use Scanner#ioException().
I know Scanner isn't a stream, rather than a tokenizer that parses data if needed, but why does it handle it's exceptions unlike other actions involving IO? When should I handle exceptions in this manner?
Answer: The explanation is given by the class documentation for java.util.Scanner.

A scanner can read text from any object which implements the Readable interface. If an invocation of the underlying readable's Readable.read(java.nio.CharBuffer) method throws an IOException then the scanner assumes that the end of the input has been reached. The most recent IOException thrown by the underlying readable can be retrieved via the ioException() method.

The Scanner is a higher level consumer of the lower level I/O reader and handles the exception itself.  The ioException() method makes that exception available if you want/need it.  Outside of certain constructors, the behavior of the Scanner API is well-defined without requiring the caller to catch any I/O-related exceptions.
The benefit is that the caller need not write try/catch blocks or make their own methods throw the checked IOException type.  This is possible because the Scanner implementation is already handling those edge cases in a way that doesn't require exceptions as flow control.
If instead the Scanner methods were to throw a checked exception, you as the caller should only write a catch block if you have a reasonable way of recovering from the exceptional case.  Indeed, you'd be forced to write it or, if you didn't catch it, now your class API becomes "polluted" by declaring its methods to throw checked exceptions merely because of an implementation detail (because you happen to use the Scanner class).
On the other hand, the lower-level Readable interface, and its implementations, have no way of handling exceptional cases and are forced to throw them to the caller; they have no way of knowing what the "correct" means of recovery is, or if any suitable means exists.  Throwing checked exceptions can be necessary, but good APIs will try to avoid it where possible.


Cannot do a `composer install` even though my minimum stability is listed as dev

Question: I am trying to build the master branch in my project after updating to 8.5.0, but am being met with an error from composer (which I did not get on my develop branch):

The requested package drupal/focal_point 1.0.0-beta6 is satisfiable by
  drupal/focal_point[1.0.0-beta6] but these conflict with your
  requirements or minimum-stability.

In my composer file, I have:
"drupal/focal_point": "^1.0",

as well as:
"minimum-stability": "dev",

How can I fix this so TravisCI gets unstuck? It worked fine for the develop branch, and the master is now updated with it.
Comment: Have you tried ```composer prohibits drupal/focal_point```?
Comment: The only output is `acquia/blt-project  dev-master  requires  drupal/focal_point (^1.0)` where `acquia/blt-project` is the name in my main composer.json file.
Comment: Indeed it seems a problem with minimum stability. Make sure there're no stability requirements per package, like said in Composer doc (```Note that you can also specify stability requirements on a per-package basis using stability flags in the version constraints that you specify in a require block (see package links for more details```). See https://getcomposer.org/doc/04-schema.md#minimum-stability. I have no other ideas :(
Answer: This may be incorrect per information in comments and because it contradicts Installing an alpha dev version with composer.
I think the issue here is that the beta6 is not ^1.0. If you updated the requirement to be "drupal/focal_point": "^1.0@beta", this would work fine.
Alternatively, you could call composer require drupal/focal_point with no version specified and it would install the beta6 version just fine. I believe this is where minimum stability is checked, but that would add a  require line in your composer.json different from what is specified in your question.
Comment: I also just added the specific version. Develop builds fine, master is still broken with the same error. I will try this.
Comment: This is interesting. I don't think your develop branch should not be building with the information you provided above. This sounds like an issue where develop is building something it shouldn't and master is acting appropriately.
Comment: Yeah its weird because it was working a week ago, I haven't changed anything about my process. On Friday I updated to Drupal 8.5.0, Drush 9, and BLT 9. Develop still worked, no problem. Now I am merging into master and thats what I see.
Comment: So I went the nuclear route, deleted the master branch, created a new one, and pushed it. Travis/Composer did not have an error at all. Very weird. The codebases are/were identical.
Comment: @Kevin - As sonfd said plus delete vendor and then reinstall.
Comment: I had done that, same result. Vendor is not committed, so the CI server is building from scratch on every commit to main branches.


Sequence that converges to the limit inferior of a function

Question: Let $f:\mathbb R^n\to \mathbb R\cup\{+\infty,-\infty\}$. The limit inferior of $f$ at $x_0 \in \mathbb R^n$ is defined as
\begin{equation}
\liminf_{x\to x_0}f(x) = \lim_{\varepsilon \downarrow 0}\left(\inf\{f(x)\mid x \in (x_0 + \varepsilon B_n)\setminus\{x_0\}\}\right)
\end{equation}
where $B_n$ is the closed unit ball. I am trying to prove or disprove the following conjecture:

There exists a sequence $\{x_k\}$ of $\mathbb R^n$ such that $x_k \to x_0$ and $f(x_k) \to \liminf_{x\to x_0} f(x)$ as $k \to \infty$.

My first trial was as follows:

Define $U_k = (x_0 + \varepsilon_k B_n)\setminus\{x_0\}$ and $m_k = \inf\{f(x)\mid x \in U_k\}$ with $\varepsilon_1 > \varepsilon_2 > \cdots$ and $\varepsilon_k \to 0$. Then, $m_1 \le m_2 \le \cdots$ and $m_k \to \liminf_{x\to x_0}f(x)$. If we pick a point $x_k$ from a set $V_k = \{x\in U_k\mid m_k \le f(x) \le m_{k+1}\}$, then $x_k \to x_0$ and $f(x_k) \to \liminf_{x\to x_0}f(x)$.

However, if $\liminf_{x\to x_0}f(x) = \inf\{f(x)\mid x \in U_1\}$ and $\liminf_{x\to x_0}f(x) \notin f(U_1)$, then $V_k = \emptyset$ and the proof does not work. Would you give me any hint or reference?
===================================================================
Edit:
I have corrected the proof thanks to Martin Argerami's answer.

Define $U(\varepsilon) = (x_0 + \varepsilon B_n)\setminus\{x_0\}$ and $m(\varepsilon) = \inf\{f(x)\mid x \in U(\varepsilon)\}$. Then, $m(\varepsilon) \to m_0 = \liminf_{x \to x_0}f(x)$ as $\varepsilon \to 0$.
1) If there exists $\varepsilon > 0$ such that $m(\varepsilon) = +\infty$, then $f(x) = +\infty$ for every $x \in U(\varepsilon)$, so $f(x_k) \to m_0 = +\infty$ for every sequence $\{x_k\}$ that converges to $x_0$.
Suppose $m(\varepsilon) < +\infty$ for all $\varepsilon >0$.
2) If there exists $\varepsilon_1 >0$ such that $m(\varepsilon) = -\infty$ for every $0 < \varepsilon \le \varepsilon_1$, then let $\varepsilon_1 > \varepsilon_2 > \cdots$ such that $\varepsilon_k \to 0$.
2-1) If $-\infty \in f(U(\varepsilon_k))$, let $x_k \in U(\varepsilon_k)$ such that $f(x_k) = -\infty$.
2-2) If $-\infty \notin f(U(\varepsilon_k))$, let $x_k \in U(\varepsilon_k)$ such that $f(x_k) < -k$; such $x_k$ exists by the definition of the infimum.
Then $x_k \to x_0$ and $f(x_k) \to m_0 = -\infty$ as $k \to \infty$ because $f(x_k) < -k$.
3) If there exists $\varepsilon_1 >0$ such that $-\infty < m(\varepsilon_1) < +\infty$, then $-\infty < m(\varepsilon) < +\infty$ for every $0 <\varepsilon \le \varepsilon_1$. Let $\varepsilon_1 > \varepsilon_2 > \cdots$ such that $\varepsilon_k \to 0$. By the definition of the infimum, there exists $x_k \in U(\varepsilon_k)$ with $|f(x_k) - m(\varepsilon_k)| < 1/k$. Then $x_k \to x_0$ and
  \begin{equation}
\lim_{k\to\infty}f(x_k) = \lim_{k\to\infty}m(\varepsilon_k) = m_0.
\end{equation}
Comment: In the $-\infty$ argument, you cannot say that $f(x_k)=-\infty$; you can say that $f(x_k)$ is very negative, but it doesn't have to be infinite.
Comment: @Martin Argerami Would you explain a little bit more why $f(x_k) = -\infty$ is not possible when $f:\mathbb{R}^n\to\mathbb{R}\cup\{-\infty,+\infty\}$? I guess that if both $+\infty$ and $-\infty$ are in the range of $f$, then $\infty - \infty$ could happen but I am not sure if it is the reason.
Comment: It is not that it is not possible; it is not certain. For instance consider $f(t)=1/t$ and $f(0)=0$. With the definition you gave, $\liminf_{t\to0} f(t)=-\infty$, but there is no $t$ with $f(t)=-\infty$.
Comment: @MartinArgerami It will be handled by the case 2-2).
Answer: By definition of inf, for each $k $ there exists $x_k\in U_k $ with $|m_k-f (x_k)|<1/k $. Then
$$
\liminf_{x\to x_0}f (x)=\lim_{k\to\infty}m_k=\lim_{k\to\infty}f (x_k).
$$
You need to deal with the $\pm\infty $ case on its own, but the spirit is the same.
Comment: Great! Thanks a lot.
Comment: I have corrected the proof by your answer.


Having trouble understanding this question propositional logic (substitution) discrete mathematics

Question: I am not understanding how to solve substitution instances, could someone please explain how it works?

Which of the following propositional formulas are substitution instances of the formula P → (Q → P)?

If a formula is indeed a substitution instance, give the formulas substituted for P,Q.
(i) ¬R → (R → ¬R)
(ii) ¬R → (¬R → ¬R)
(iii) ¬R → (¬R → R)
(iv) (P ∧ Q → P) → ((Q → P) → (P ∧ Q → P))
(v) ((P → P) → P) → ((P → (P → (P → P))))?
Answer: (i) is a substitution instance of $P \rightarrow (Q \rightarrow P)$ because we can obtain (i) by substituting $\neg R$ for $P$ and $R$ for $Q$.
Likewise, (ii) is a substitution instance of $P \rightarrow (Q \rightarrow P)$, by substituting $\neg R$ for both $P$ and $Q$.
(iii) is, however, not a substitution instance of $P \rightarrow (Q \rightarrow P)$.
Can you do the rest from here?
Comment: I am really struggling to understand this question, would you be able to show me how ¬R substitutes for p and R for Q for (I)? just so I can see an example please?
Comment: no worries I have figured it out, thanks so much for this help.


is it possible to disable ckeditor for private messages?

Question: I've ckeditor through out the site.But i don't need it for private messages(privatemsg module).Is their any way to disable CKeditor only for private messages?
Comment: check from settings or input formates
Comment: I've changed form's input format.It's working fine.Thank you.
Comment: How/where did you change the privatemsg form's input format? I cannot find that setting.
Answer: check from settings or input formates


Writing a Distribution Function in terms of $F$

Question: If you have a distribution function, $F(x)$, of a random variable $X$, how would you write this $\mathbb{P}(X =i )$ in terms of $F$?
Keep in mind that $F(x) = \mathbb{P}(X\leq x)$ and $X$ will take on one value of $1,2,3$.
I can't figure out where to begin. Is it simply just writing an equation or is it a lot more challenging?
Answer: $$
\Pr(X=i) = F(i) - \lim_{x\uparrow i} F(x).
$$
This is sometimes denoted $F(i) - F(i-)$.
Proof:  In the first place, if $x<i$ then
\begin{align}
F(i) = \Pr( X\le i) & = \Pr\Big( X\le x \text{ or } x < X \le x \Big) \\[10pt]
& = \Pr(X\le x) + \Pr(x<X\le i) = F(x) + \Pr(x<X\le i);
\end{align}
and therefore
$$
\Pr(x<X\le i) = F(i) - F(x),
$$
and so we have
$$
\Pr(X=i) \le F(i) - F(x). \tag 1
$$
Next notice that if $x<y$ then $F(x) = \Pr(X\le x) \le \Pr(X\le y) = F(y)$, so $F(x)$ gets bigger or at least stays the same as $x$ gets bigger.  Therefore $F(i)-F(x)$ gets smaller or stays the same as $x$ gets bigger.  Hence $\lim_{x\uparrow i} (F(i) - F(x))$ exists, and since $(1)$ is true of all $x\le i$, we have
$$
\Pr(X=i) \le \lim_{x\uparrow i} (F(i) - F(x)).
$$
But could $\Pr(X=i)$ be less that the limit?
\begin{align}
\Pr(X\le i) & = \Pr(X=i) + \Pr(X<i) \\[10pt]
& = \Pr(X=i) \\[10pt]
& {}\qquad{} + \underbrace{\Pr(X\le i-1) + \Pr(i-1<X\le i-\tfrac 1 2) + \Pr(i-\tfrac 1 2 < X\le i - \tfrac 1 3) + \cdots}
\end{align}
Here the thing to notice is that the series over the $\underbrace{\text{underbrace}}$ adds up to $\lim\limits_{x\uparrow i} F(x)$.
Answer: If $X$ is continuous, for every $i \in \mathbb{R}$, $\mathbb{P}(X = i) = 0$.
Now if $X$ is discrete, say over the nonnegative integers $\{0, 1, \dots\}$, let's denote $\mathbb{P}\left(X = k\right) = p_k$, $k \in \{0, 1, \dots\}$.
Then $\displaystyle F(x) = \mathbb{P}\left(X \leq x\right) = \sum\limits_{i=0}^{x}p_k$, assuming $x$ is a nonnegative integer.
Hint. What is $F(x)-F(x-1), x \geq 1$?
Comment: That makes a lot more sense. the constant k is where I'm running into some problems.
Comment: So I have sum(i=1 to infiniti) P(x i) = 1.


Quicker way to solve 10! congruent to x (mod 11)

Question: I am new to modular arithmetic and solving congruences and the way I went about this was to write out $10\cdot 9\cdot 8\cdot 7\cdot 6\cdot 5\cdot 4\cdot 3\cdot2$, then multiply numbers until I get a number greater than $11$, replace it with a smaller number in its congruence class and repeat.  Is there a quicker way to go about this?  The next question I must solve is $100!\equiv x \pmod {101}$.
Answer: Wilson's Theorem states that for any prime number $n$, you get $$(n-1)! \equiv -1 (mod\ n).$$
$10!$ makes $n = 11$, which is prime, so $10! \equiv -1 (mod\ 11) \equiv 10 (mod\ 11)$
Likewise, $100!$ makes $n = 101$, which is prime, so $100! \equiv -1 (mod\ 101) \equiv 100 (mod\ 101)$.
Comment: http://en.wikipedia.org/wiki/Wilson's_theorem
Comment: Very good way of solving the problem. On an aside Wilson's theorem is an "if and only if" statement which implies that for any $n$ such that the above is true, then $n$ is prime.
Comment: @Juan If $n$ is composite and $n>4$, then $(n-1)! \equiv 0 \pmod{n}$.
Comment: What about the case when n is not prime?
Comment: say 101! (mod 102)
Comment: Ooh, can't really help you there, buddy. It's not as nice for non-prime numbers. Umm... just plug it into Wolfram Alpha? :P
Comment: no calculators allowed in this class.
Comment: Aww man. Well I'd say your best hope then is to pray to whichever higher being you believe in (if you do) that your teacher isn't evil enough to ask something like that.
Answer: We can pair numbers, since $$10 \equiv -1 \pmod{11}$$ $$9 \equiv -2 \pmod{11}$$
and so on. So your product is the same as
$$(-1) (-2 \cdot 2)(-3 \cdot 3)(-4 \cdot 4)(-5 \cdot 5) \pmod{11}$$
or after dealing with signs,
$$-2^2 \cdot 3^2 \cdot 4^2 \cdot 5^2 \pmod{11}$$
Now $2^2 \equiv 4$, $3^2 \equiv -2$, $4^2 \equiv 5$ and $5^2 \equiv 3$, so this can be written as
$$-(4)(-2)(5)(3) \pmod{11}$$
or $$8 \cdot 5 \cdot 3 \pmod{11}$$
Now $40 \equiv 7$ and $21 \equiv -1$ leads to
$$\boxed{-1 \pmod{11}}$$
Answer: If you don't know Wilson's theorem you might stumble upon its idea tackling this problem using elementary facts and being lazy.
The non-zero elements in $\displaystyle \mathbb {Z} /11\mathbb {Z}$ form a group and each element has a unique inverse. OK, listing the elements,
$\tag 1 {\overline {1}},{\overline {2}},{\overline {3}},{\overline {4}},{\overline {5}},{\overline {6}},{\overline {7}},{\overline {8}},{\overline {9}},{\overline {10}}$
and you get a little excited since $10!$ modulo $11$ boils down to multiplying them all together.
So an easy first step for the lazy mathematician is to replace the list with
$\tag 2 {\overline {2}},{\overline {3}},{\overline {4}},{\overline {5}},{\overline {6}},{\overline {7}},{\overline {8}},{\overline {9}},{\overline {-1}}$
Looking for pairs of elements, each the multiplicative inverse of the other, you wonder if you can multiply two representative numbers  together and get $12$. Yup, $2 \times 6 = 12$ and $3 \times 4 = 12$. Great, now looking at
$\tag 3 {\overline {5}},{\overline {7}},{\overline {8}},{\overline {9}},{\overline {-1}}$
How about 'multiplying out' to $23 = 12 + 11$. Nope.
How about 'multiplying out' to $34 = 23 + 11$. Nope.
How about 'multiplying out' to $45 = 34 + 11$. Yup, $5 \times 9 = 45$. New list
$\tag 4 {\overline {7}},{\overline {8}},{\overline {-1}}$
How about 'multiplying out' to $56 = 45 + 11$. Yup, $7 \times 8 = 56$.
ANS: $10! \equiv -1 \pmod{11}$

Note: If $p$ is a prime the solutions to $x^2 \equiv 1 \pmod{p}$ are $x \in \{1,-1\}$. So with $p \ge 5$ the elements in the non-empty set
$\quad \displaystyle \mathbb {Z} /p\mathbb {Z} \setminus \{{\overline {0}},{\overline {1}}, {\overline {-1}}\}$
can be always be '$a\text{-}b$ paired off' with
$\quad \displaystyle ab \equiv 1 (\text{mod } p) \land a \ne b$


how to put a string value from one Application Db Context to another?

Question: I'v declared a var to select elements from db context named BUGS(Table).
i set it to include all the columns, there is a foreign key named ProjectsPId.
It can return the id (The foreign key), but it returns "null" if we call projects.name for example.
So, i declared a var ("BUGS1" = context.bugs) this give me the value of project.name with no problems.
How i can put the "Project Name" value from the var bugs1 to the var bugs.
i'v tried to do this:
bugs.Where(b => b.Projects.PName) = bugs1.Where(c => c.Projects.PName);
this give me an error
    public async Task<IActionResult> Index(int? id, string sortOrder, string searchString)
        {
            var bugs1 = _context.BugsSummary;
             var bugs = from b in _context.BugsSummary
                       select b;
            {

                if (!String.IsNullOrEmpty(searchString))
                {
                    bugs = bugs.Where(b => b.Projects.PName.Contains(searchString)
                                           || b.Bug.Contains(searchString));
                }

                switch (sortOrder)
                {

                    case "name_desc":
                        bugs = bugs.OrderByDescending(b => b.Projects.PName);
                        break;
                    case "Date":
                        bugs = bugs.OrderBy(b => b.PublicationDate);
                        break;
                    case "date_desc":
                        bugs = bugs.OrderByDescending(b => b.PublicationDate);
                        break;
                    default:
                        bugs = bugs.OrderBy(b => b.Projects.PName);
                        break;

                }

                if (id > 0)
                {
                    bugs.Include(b => b.User).Include(b => b.Projects)

                        .Where(b => b.ProjectsPId == id)
                        ;
                }
                else
                {
                    bugs.Include(b => b.User).Include(b => b.Projects);
                }

                ViewData["DateSortParm"] = sortOrder == "Date" ? "date_desc" : "Date";
                ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
                ViewData["CurrentFilter"] = searchString;
            }

            bugs.Where(b => b.Projects.PName) = bugs1.Where(c => c.Projects.PName);

            return View(await bugs.AsNoTracking().ToListAsync());
    }

Comment: Sorry, my friend. But I don't know why you need the bug1?
Comment: bug1 can give me the value of the string "project.name".

bug have "Null" value with project.name, i'm trying to put the bug1 project name in the bug "project name"
Comment: As I see, both bug and bug1 get the data from BugsSummary. Maybe bug return null data cause you are searching the project name.
Comment: no it's null becuase of something else, i don't know why bugs1 project.name is not null and bugs project name is null.
Answer: When you set the initial value of the query, you need to use Include method to load related data like below :
 var bugs = from b in _context.BugsSummary.Include(b=>b.Projects)
            select b;

Then you don't need bug1 to pass the value of the string "project.name" to bugs
Comment: @YakaGgFa, I am glad to help you .Could you mark my reply as the answer ? This may help others who face the same or similar issue to find the answer quickly. Thanks!


Standardized residuals in R's lm output

Question: If I plot the diagnostic plots to an R regression, a couple of them have "Standardized Residuals" as their y-axis such as in this plot:

What are the residuals standardized over? That is, let us assume that in my model, there are 100 predicted values; hence 100 residuals.

Standardized residual $e_i$ is defined as $(e_i - \bar e)/s_e$(realized residual - mean of all 100 realized residuals)/(standard deviation of all 100 realized residuals)?
Since each residual $e_i$ is itself a realized value out of a distribution of possible realizations for this single residual $e_i$, is this residual $e_i$ normalized by its own mean $\bar e_i$ and variance $\text{Var}(e_i)$ (as opposed to the mean and variance from all other values 1 to 100 as described above)?

I tried finding documentation clarifying this distinction but could not find any that was beyond doubt.
Answer: If you look at the code for plot.lm (by typing stats:::plot.lm), you see these snippets in there (the comments are mine; they're not in the original):
r <- residuals(x)                                # <---  r contains residuals

...

if (any(show[2L:6L])) {
    s <- if (inherits(x, "rlm"))
        x$s
    else if (isGlm)
        sqrt(summary(x)$dispersion)
    else sqrt(deviance(x)/df.residual(x))        #<---- value of s
    hii <- lm.influence(x, do.coef = FALSE)$hat  #<---- value of hii

...

    r.w <- if (is.null(w))
        r                                        #<-- r.w  for unweighted regression
    else sqrt(w) * r
    rs <- dropInf(r.w/(s * sqrt(1 - hii)), hii)  # <-- std. residual in plots

So - if you don't use weights - the code clearly defines its standardized residuals to be the internally studentized residuals defined here:
http://en.wikipedia.org/wiki/Studentized_residual#How_to_studentize
which is to say:
$${\widehat{\varepsilon}_i\over \widehat{\sigma} \sqrt{1-h_{ii}\  }}$$
(where $\widehat{\sigma}^2={1 \over n-m}\sum_{j=1}^n \widehat{\varepsilon}_j^{\,2}$, and $m$ is the column dimension of $X$).
Comment: the term 'standardized residual' is not a standardized term. Different people use it to mean somewhat different things. The meaning used in plot.lm would be - easily - the most common one in regression packages, though). Note that in regression with an intercept, $\bar{e}$ is 0.
Comment: Internally studentized residual as defined in the formula I gave, yes. If you're unconvinced, you could compute an internally studentized residual from the available regression information directly and compare.
Comment: Thanks for the explanation. Some clarification because I am so surprised: so that means that standardized residuals are actually _just_ studentized residuals? Not $(e_i - \bar e)/s_e$? It is surprising to me because of the confusion incurred by naming it "standardized" instead of "studentized" - or maybe this is common practice?
Comment: haha, the irony! thank you so much. so just to confirm, the standardized residual shown in the plot is just a studentized residual - as the code shows?
Answer: standardized (or studentized) residuals are the residuals divided by their standard deviations.  Standard deviation for residuals in a regression model can vary by a great deal from point to point, so it often makes sense to standardized them by their standard deviation in order to make comparisons more meaningful.

Standardized residuals in R's lm output


Images.xcassets: error: Failed to find a suitable device for the type SimDeviceType

Question: When I tried to run the app in simulators, I hold Xcode 8.3.2 and Xcode 9 beta 1 and my project was running in Xcode 8.3.2. I got the below errors.
Images.xcassets: error: Failed to find a suitable device for the type SimDeviceType : com.apple.dt.Xcode.IBSimDeviceType.iPad-2x with runtime SimRuntime : 10.3 (14E269) - com.apple.CoreSimulator.SimRuntime.iOS-10-3
    Failure Reason: Failed to create SimDeviceSet at path /Users/Mac/Library/Developer/Xcode/UserData/IB Support/Simulator Devices. You'll want to check the logs in ~/Library/Logs/CoreSimulator to see why creating the SimDeviceSet failed.
    Underlying Errors:
        Description: Failed to initialize simulator device set.
        Failure Reason: Failed to subscribe to notifications from CoreSimulatorService.
        Underlying Errors:
            Description: Error returned in reply to notification request: Connection invalid
            Failure Reason: Software caused connection abort
/* com.apple.actool.document.notices */

Comment: I'm facing the same issue on Xcode 8.3.3 - did you find any working solution for this issue?
Comment: @AkashThakkar as of now I didn't get any solution for this.
Answer: For me it did not help cleaning. I had to run sudo killall -9 com.apple.CoreSimulator.CoreSimulatorService and then I was able to start the app via the Simulator
Comment: Thank you! Cleaning the project wasn't enough for me... I had to run the command you recommended :)
Comment: Cleaning was not enough for me either.  I must have had other issues.  Restarted my mac, cleaned my build folder and it worked fine.
Answer: I had this error and solved it by just opening Simulator from the Xcode menu.
Xcode -> Open Developer Tool -> Simulator
Once the simulator was open and finished booting, I cleaned and rebuilt the project.
Comment: I had this too, turned out I had the Xcode 8 simulator open in the background while using Xcode 9.2... Closing it and opening the correct one fixed it :)
Answer: Try and Clean the Project and then Run thats what I did
Goto Product > Clean, then run


Check if current node meets conditions, then alter a block's contents?

Question: In Drupal 7, how would I check whether the current node being viewed meets certain conditions, and then based on that check alter a block's contents?
To give a specific example, I want to check if the current node on my site is a blog post (like http://www.givingwhatwecan.org/blog/2012-10-04/giving-to-charity-%E2%80%93-a-pain-in-the-eye - the conditions here are being tagged with the 'Blog' taxonomy term, or being of type 'story'). If it is, I want to add the class 'active-trail' to the 'Blog' heading in the menu block atop the page.
If need be, I'm happy to use jQuery, though I'd be interested to know the general 'Drupal way' of doing this.
Answer: You can check the content type of current node via preprocessing functions in your theme, but there might be another (simpler) way to do what you want: Drupal adds various information about the current page in the body classes, so you have more options for theming.
To select a specific menu link on all nodes of blog content type you can use the following CSS class: body.node-type-blog and a unique menu link ID (#menu-1000-1).
Add that line to the place where you define the active state of menu items. In your case this will be (in your superfish CSS file):
body.node-type-blog #menu-1000-1 a,
a.sf-depth-1.active, .active-trail a.sf-depth-1 {

Another quick solution would be using jQuery:
if ($("body").hasClass("node-type-blog")) {
  $("#menu-1000-1").addClass("active-trail");
}

Check also Context module for more complex use cases where you need to define a section on your website and apply certain theming/functional changes.


Crond Inactive Every Other Minute

Question: I have a problem with crond (dated 13Feb21) on my Slackware 14.2 x86_64 (Linux version 5.12.10) server.
I have a script that crond runs every minute that accesses an external device for current data and logs it to a file.  I will call the script Script1, and it runs fine.
I also have anther script that runs every minute and it processes a file that is larger in size each time the script runs.  As result the script takes longer to run each time as well.  This script also runs fine, and I will call it Script2.  The two scripts are not related and there are no files shared between the two scripts.
Recently I noted Script1 was only logging the data to the data file every other minute instead of every minute.  I finally traced the problem and I am not sure if is a real solvable problem, or a misconception on my part on how crond works.
When the file being processed by Script2 becomes large enough, the script takes more than a minute to run.  Using "crond –l debug" to monitor what crond was doing, it appears that if Script2 is still running at the beginning of the next minute, it does not start Script1, so no data is logged.  Even stranger however, is that there are several other scripts that should run every minute and they do not start as well.
I was under the impression that crond looked at what is scheduled to run at the present moment in time and disregarded any past scheduled tasks.  What appears to be happening now is that if a script is still running at the next minute, it does not do anything for that whole next minute.   When crond is running in debug mode, the cron log shows absolutely no activity for the entire subsequent minute.  It is only at the next following minute when Script2 is no longer running, that crond activity returns to normal.
Can someone enlighten me as to what is going on?
Thanks
Comment: W/o the scripts we can't do much. Unfortunately the crystal ball is on dry cleaning.
Answer: After many hours of searching, I came across a post where a user had a problem that was solved by using "#!/bin/bash" as the shebang instead of "#!/bin/sh".  Not knowing for sure which one I had used, and grasping for straws, I checked my script that was causing the problem. What I found was that in one of my last edits I must have inadvertently hit the space bar at some point because my shebang read "#! /bin/bash".  It didn't affect the way the script ran, but it sure messed with crond.  All is well now, but it won't be a lesson I will soon forget. Perhaps this will save another user from similar grief down the road.
Comment: Questions seeking installation, configuration or diagnostic help must include the desired end state, the specific problem or error, sufficient information about the configuration and environment to reproduce it, and attempted solutions. Questions without a clear problem statement are not useful to other readers and are unlikely to get good answers Moreover without the script it's not a useful question atm imho

Crond Inactive Every Other Minute


What are spatial functions?

Question: I was reading Einstein's paper 'Concerning an Heuristic Point of View Toward
the Emission and Transformation of Light' and read came across this segment:
"While we consider the state of a body to be completely determined by the positions and velocities of a very large, yet finite, number of atoms and electrons, we make use of continuous SPATIAL FUNCTIONS to describe the electromagnetic state of a given volume,and a finite number of parameters cannot be regarded as sufficient for the complete determination of such a
state."
What are they? And what does it mean in the context above?
Answer: The above context is described in the book "Einstein: His Life and Universe" by Walter Isaacson (Page 97).
By spatial continous functions he refers to electromagnetic fields of the wave theory of light. He also states that theories of particles (like kinetic theory of gases) involve velocities and positions of finite number of particles and a wave theory cannot give this information.
Above text emphasize differences between wave-particle approaches.

What are spatial functions?