sitefinity view cshtml accordion list

Question: I am returning a list object within a list object and wanted to have the sub list in accordion list. Do I need to do this in JS or jquery? Or is this something within sitefinity controls that will be faster and better to use?
Answer: I do something like this
https://github.com/sitefinitysteve/RandomSiteControlsMVC/blob/master/RandomSiteControlsMVC/MVC/Views/DocumentTree/Simple.cshtml
(Try here https://rscdemo.sitefinitysteve.com/components/document-treelist)
If you have bootstrap on there, just add the collapse attributes to your elements
https://getbootstrap.com/docs/4.3/components/collapse/
Comment: the bootstrap is great, can I use a variable in the href `` like something like this <a data-toggle="collapse" href="@string.Format("#collapseExample_{0},id)
Comment: No, if it's because you're needing unique names, my view handles that... but there's methods and stuff too in the docs https://getbootstrap.com/docs/4.3/components/collapse/#methods

sitefinity view cshtml accordion list


PayPal login button: close popup after login and reload / redirect parent window

Question: What I want to do
Implement PayPal login button to use customer information from PayPal (name, adress...). After login (or cancel) login popup should be closed and parent window should be reloaded / redirected.
Current progress
PayPal button works as expected, user informations can be requested.
Current problem
Login popup does not close after login; redirect is done in popup window.
What I tried
The only solution for this problem I found is to add JS code in redirect-page on popup to close popup and reload parent window, see eg. Log in with PayPal: Closing the login window to return to main site
All solutions are mostly identical; solution should be something like this in the page called after successful login (redirect url):
<code>window.opener.location.href = window.location.href;
window.close()
</code>
I tried with Firefox, Chrome and Edge; all browser do close popup, but no action in parent window is done because window.opener is null; also window.parent.opener or top.window.opener. Some threads say this is because of security reasons and popup windows with different url than parent window could not access parent window. Is that correct or is there some other way to close PayPal popup? There are many pages that use PayPal login and work as expected, so there must be a solution. Maybe I did something wrong when implementing in my script?
Answer:
Some threads say this is because of security reasons and popup windows with different url than parent window could not access parent window.

Do not have it be different.
After login completes, its return within the popup should be to the same domain (and protocol+port) as the opener/parent window.
Comment: Yes, but opener is still null. Popup called in www.mydomain.com/login; after login, popup redirects to www.mydomain.com/paypal and window.opener is null. Is it null because of first url called in Popup is PayPal url?
Comment: use www.mydomain.com/login
Comment: Same behaviour unfortunately...
Comment: Try a different domain/localhost for the top opener window and review your HTTP headers and HTML META equivalents
Comment: Plain script works as expected. Same code in my project does not. But I think I got it: I'm using mod_rewrite for seo; maybe this is the reason for this problem. mydomain.com/login is rewritten to index.php?option=login so I have to find out how to get it working in this environment...
Comment: Preston PHX: I could not get a solution for this. Maybe you can help me? In my example script it works fine (with all url params as in Joomla), but if I put same code in Joomla it does not. In Joomla I disabled seo and mod_rewrite and use non-seo paths like option=com_mycomponent&view=login. I use a component template and output html code is same as in my example - also in paypal popup. But popup keeps open... Any ideas?
Comment: Got it. CSP was the key... Thanks Preston for your help!


How do I go about playing 32nd notes?

Question: I'm an intermediate alto saxophone player and I'm currently learning to play Milhaud's Scaramouche, III - Brazileira. The problem is the last sequence of 16th and 32nd notes which are extremely hard for me to get down. I can do them clean at around 138 for an eighth note but it's hard to go any faster without making my hands fly everywhere and sounding uneven and wrong. Here are the relevant measures (circled in pencil):

My target tempo is around 168 for an eighth note. What are some tips to getting it clean and especially getting my posture correct so I don't have my hands flying everywhere?
Answer: I'm going to suggest two primary techniques for working up a line of fast passagework like this, but in the end I would suggest combining the two processes into one. Also, I'm changing the 32nd notes to sixteenth notes in my examples, because it makes them easier to read and, at first when you're practicing at slower tempos, it indicates the feel.
Technique #1
My cello teacher called this technique "making it harder at first, so that the actual line becomes easier." The basic idea is that you'll practice the line at a much slower tempo, but change the rhythm from straight sixteenths to dotted-sixteenth/thirty-second note pairs, like this:

Initially, play the passage in this rhythm at a much slower tempo, until it's perfect (probably in conjunction with the second technique I describe below). The idea is that the slower tempo is giving your brain more time to internalize the large-scale connections, but your fingers are still getting practice in the faster connections between every other note. Of course, the problem here is that you're only practicing the quicker connection between the even and odd notes this way. That's why, before moving the tempo up, you should also practice the inverse, "Scottish snap" version of the rhythm, like this:
Now you're practicing the faster finger connection between the odd and even notes, in the context of an overall slower tempo.
Once you have both patterns perfect at the tempo, play everything as straight sixteenths a couple of times. This should feel insanely slow and easy after using the off-kilter rhythm, but it's important to synthesize everything. Now bump the tempo up a bit, and start over.
Technique #2
I can't emphasize enough the extent to which these techniques are best combined with each other. The idea with the second technique is to build up your finger speed (and finger calmness) within the beats, while still giving your brain time to breathe. The idea is to slowly build up a larger span in your playing. Begin by separating every "beat" (by which I mean every eighth note in the original notation) by playing all the notes up to the next beat and inserting a rest. After the rest, begin with the last note you played and finish out that beat, overlapping with the first note of the next beat. That sounds more complicated than it is, here's what I mean:
It's imperative that you maintain the overlap as shown in the example. You are practicing from beat to beat, but inserting a rest into the pattern to give yourself time to internalize everything. Obviously, this is very choppy, and you need to make sure you start building up larger-scale connections, so, once you've got this version down at the current practice tempo, expand everything by one beat:
Now you're having to get more notes in before you take a break, and it will take several attempts before you feel comfortable with it. When you are, double the length again and again until you're playing the whole passage without artificial interruption. Then, finally, bump the tempo up a titch, and start over.
One thing that will initially be complicated by both of the techniques is the overall tonguing of the pattern. Try to incorporate the actual tonguing as much as possible, especially once you get to larger spans of music. Make sure you have played everything exactly as written at one tempo before you even think about moving on to a faster tempo. This final consolidation phase should always feel almost painfully easy after the more complex versions you've practiced.
In my experience, this tends to be a frustrating process the first time I'm working on a passage. It will feel like I'm taking one step forward, only to take two steps back. However, when I come back to the same passage the next day, I'm usually shocked by how much more easily the pattern falls under my fingers. I do the whole routine again, but it's usually far easier. After a few more days, my fingers know the passage, and I can't remember why it ever seemed so difficult.
I hope this helps!
Comment: Pat, did you ever find it disruptive to the learning process to practice incorrect rhythms? Does this approach have any advantage over practicing slowly in the true rhythm and gradually speeding up the metronome?
Comment: @jdjazz Well, first of all, this process I described *always* is a build-up to restoring the correct rhythm then moving on to any faster tempos, so it's in addition to, not a replacement to, practicing slowly in the true rhythm. Further, I think "incorrect" rhythm is an exaggeration, it's more like proper rhythm but with a sort of start/stop flow. It's important to note that, when you're at half speed, the faster notes are actually essentially practicing the proper speed rhythm, just in smaller chunks. The advantage is that you're practing the fastest connection, just piecemeal.
Comment: Yes--I meant incorrect in the sense that it's different from the true rhythm at tempo. In terms of practice time required, I wonder how this approach compares to playing the full piece slowly and gradually increasing the metronome (e.g., starting at 120 bpm and increasing by 2 bpm up to the desired speed). Maybe the approach you've described takes less time to reach a certain level of technical capability with the piece. Have you ever practiced the other way--starting the metronome very slowly and gradually increasing till you reach the desired speed? If so, how do the two approaches compare?
Comment: This practice method applies to pretty much every musical instrument and is widely advocated by educators and professionals who play the respective instruments. For instance, I've watched a Nahre Sol (a pianist) video (How to Practice Arpeggios or something like that) where she talks about this way of practicing.
Answer: Just the usual.  Practice the tricky section SLOWLY making sure there are no fluffs and fumbles.  REALLY no fluffs and fumbles, even if that means going REALLY slowly.  Resist the temptation to 'take a run at it' and get it ALMOST right.   Speed will come.  I promise!
Comment: I found that splitting it off and getting everything perfect and slowly incrementing the tempo was the best. Thanks for the advice!
Comment: Good!   Don't focus too much on increasing the tempo.  Rather, practice it at the slow speed until you COULDN'T put a finger wrong.  The tempo will come.
Comment: I agree completely with this approach. I would start embarrassingly slow, so that the 32nd notes fall on the beats when the metronome is set to 200 bpm. I would repeat at this tempo until I can play every note *exactly* on the correct beat 2-3 x in a row. Once I achieved that goal, I would increase the metronome to 210 bpm and repeat the exercise. I would continue increasing by 10 bpm until I reached the desired speed. This might take ~4 hours, but you'll be clean as any recording you can find. (At certain points you'd have to change the metronome from playing 32nd notes to 16th notes, etc.)
Comment: It can be frightening how, at a very slow tempo, you STILL make mistakes!
Answer: Practise in sections, so maybe divide it up into beats, and practise it until you get it perfect before moving to the next beat. Also once you have a couple down, practise joining them together.
Comment: Yeah, I decided to go with splitting them off into three sections and getting them perfect at least three times in a row. Then putting two together and repeating, then all three sections. I've pretty much got it now, thanks for the advice!
Answer: Take a metronome and go through each section, gradually speeding it up. You should also subdivide the rhythm with the metronome.
As for your fingers, now's the perfect time to focus on them. Here are two things to focus on:
- Movement
- Pressure
Your fingers should be moving as little as possible. That means keeping your fingers resting on the pearls and only moving as much as you need to (for example, bottom pinkie work on both hands for low notes).
Also, you should only be pressing on the keys as much as you need to. Take a few moments to really think about how much you need to press in order to close the pad sufficiently -- don't press harder than that.
Think of both of these factors as you do this, and your fingers will be able to stay more relaxed as you go to faster tempos.

How do I go about playing 32nd notes?


How to analyze the frequency of correct/ non-correct answers

Question: I have a question about how to analyze some data. It involves the performance of two equally sized groups in a questionary with 30 arithmetic questions that I scored with two possible outcomes (correct/ incorrect) plus possible omissions (unsolved question). My first approach to these data has been to calculate each subjects' frequency of correct, incorrect and non-solved questions which I aimed to compare by means of a chi-square association test (plus an a posteriori inspection of the standardized residuals).
On a second step, as I do not expect differences between groups, I would like to observe whether participants (regardless of the group) provided more/ less correct answers depending on the type of arithmetic operation involved (addition, subtraction, multiplication or division). I intended to ascertain this question by means of chi-square goodness of fit and, again, an a posteriori inspection of the standardized residuals
However, I have been told that my approach might be incorrect because I should treat correct, incorrect and non-solved questions as interval variables. Therefore, I am quite puzzled at the moment and I would appreciate expert advice on the correct approach to deal with this two experimental situations.
(I am using SPSS, just in case this information might be relevant here)
Answer:
However, I have been told that my approach might be incorrect because I should treat correct, incorrect and non-solved questions as interval variables.

I do not understand this advice, you should ask for clarification. One way to interpret it is that the three categories correct/ incorrect, unsolved question can be ordered, but then, how?
Maybe you could try multinomial logistic regression, or, use a chi-square test.


Missing Application-Name manifest attribute for:

Question: I have an application with some external jars I created. With the new java policy I had to sign my application and all jars. I buyed a certificate and signed my jar application and all other jars. Then I got a error "missing permissions attribute in jar manifest". I added Permissions: all-permissions to the manifest of my jar (not the other external jars). And now I have the error Missing Application-Name manifest attribute for:... But I don't know what I have to put as application-name. Is that the name of my jar?
I tried to add to the manifest of all other jars "Permissions: all-permissions" but then my application doesn't work at all.
thanks for the answers
Comment: `Application-Name` is the name of your application. Did you sign all of your jars?
Comment: yes I signed all jars. The problem is that I don't know what the name is of my application. I didn't write the application, I just got it from someone else. And now I have to do the maintenant on it. Where can I find the name of the program. Is that the name of the jar?
Answer: This is what helps me out:
How do I fix "missing Codebase, Permissions, and Application-Name manifest attribute" in my JNLP app?
I just had to put THREE extra attributes in the manifest of ALL jars.
Comment: Read article and wanna ask: Could I just edit someone's jnlp file as end-user to prevent these popups?

Also tried to edit `/etc/icedtea-web/javaws.policy` file (with codebase from jnlp) and include this file on javaws run to no avail.
Answer: I had this problem and I was also getting security warnings similar to this post
It was a quick fix by making sure then when exporting the jar file I had  "Export Java source files and resources" ticked. Didn't even need to adjust the manifest file in the end.


Counting array occurrences in an array

Question: Hi I have a 2d array like this
<code>[[0 2]
 [0 1]
 [1 2]
 [1 2]
 [0 1]
 [1 2]
 [0 1]
 [0 1]
 [1 3]
 [2 3]]
</code>
I need to count the occurrences of each array for example [0, 1] = 4, [0,2] = 1, etc. Preferably using numpy.
and then extract the max values.
Thanks in advance.
Answer: np.unique() will do for you
<code>unique_arr, num = np.unique(arr, axis=0, return_counts=True)
</code>

Counting array occurrences in an array


Cannot create bar plot with pandas

Question: I am trying to create a bar plot using pandas. I have the following code:
import pandas as pd

indexes = ['Strongly agree', 'Agree', 'Neutral', 'Disagree', 'Strongly disagree']

df = pd.DataFrame({'Q7': [10, 11, 1, 0, 0]}, index=indexes)
df.plot.bar(indexes, df['Q7'].values)

By my reckoning this should work but I get a weird KeyError: 'Strongly agree' thrown at me. I can't figure out why this won't work.
Comment: `df.plot(kind='bar')` or `df.plot.bar()`
Comment: Isn't `plot.bar` just an alias for the same?
Answer: By invoking plot as a Pandas method, you're referring to the data structures of df to make your plot.
The way you have it set up, with index=indexes, your bar plot's x values are stored in df.index.  That's why Wen's suggestion in the comments to just use df.plot.bar() will work, as Pandas automatically looks to use df.index as the x-axis in this case.
Alternately, you can specify column names for x and y.  In this case, you can move indexes into a column with reset_index() and then call the new index column explicitly:
df.reset_index().plot.bar(x="index", y="Q7")

Either approach will yield the correct plot:
Comment: Ok thanks. And if I want to colour each bar differently?
Comment: Pandas isn't designed to support multiple colors for a single column.  (And in general it's often unnecessary, and even confusing, to encode color as a redundant dimension for a categorical axis.)  Still, there's a workaround here, if you really need it: https://stackoverflow.com/a/44495136/2799941.

Cannot create bar plot with pandas


in Matlab, find the distance for every matrix element

Question: Suppose I have a zero matrix of 75x50 where every zero will be replaced by the distance from some reference index in the matrix, such as every element having a pair of indexes (i, j) tells me the Euclidean distance from the reference point. So if the reference point is at (i = 25, j= 44), I need to compute the distance from every other 'i' and 'j' to this point. I could do this with a pair of loops but since my matrix is in reality much larger, I was wondering wether and how I can make this faster.
Thanks
Answer: One way to do this would be to use bsxfun with the hypot function. Like so:
rows = 75;
cols = 50;
i=25;
j=44;
bsxfun(@hypot, (1:rows)' - i, (1:cols) - j);

Essentially what this is doing is generating two matrices. One like this:
1  2  3  ...  50
1  2  3  ...  50
...

and the other like this:
1  1  1 ...
2  2  2
...
75 75 75

You can think of these as vector coordinates . We then subtract i and j from them so that the point  equals zero, and every other point gives the distance from them in vector space (e.g. <-2,3>). @hypot then calculates the length of said vector (so, for instance, <-2,3> would become 4.0). It does this for every element of the matrix, which then becomes your matrix of euclidean distances.
Note that this is probably not what is actually happening behind the scenes, but I find it's a useful way of thinking about it.
Comment: Thanks indeed. I hadn't even got my morning coffee before the answer was provided :)


How can I cd to an alias directory in the Mac OSX terminal

Question: Is there a way to get into an alias directory from shell with the command "cd" ? It always returns that "htdocs" isn't a directory.
Edit: I made the shortcut with the OS GUI -> rightclicked the htdocs directory and chose "Alias..." (i'm using a german OS if it's not alias maybe it's called shortcut in english?) then i moved it to my home directory (because my terminal starts from there when i open it).
All i want is to open my terminal and type "cd htdocs" so that i can work from there.
Answer: you can make symbolic link to it.
ln -s EXISTING_PATH LINK_NAME

e.g.
ln -s ~/Documents/books ~/Desktop/

Reference
Enter into a directory through an alias in Mac OS X terminal
Comment: It works but I feel like it defeats the purpose of an alias. What then is the advantage of using an alias vs a symbolic link? @jaepage
Comment: Note subtle distinction between `ln -s ~/Documents/books ~/Desktop` (which would try to create a symlink called ~/Destop and fail) vs `ln -s ~/Documents/books ~/Desktop/` with trailing slash, creating a symlink _under_ ~/Desktop/ — a shorthand for `ln -s ~/Documents/books ~/Desktop/books`.
Comment: I like this approach better. Thanks.
Comment: Didn't want to repost your solution after finding it myself. It's much more useful and linux-y!
Comment: So what do have to call afterwards?
Answer:
All i want is to open my terminal and type cd htdocs so that i can work from there.

The easier approach is probably to ignore the links and add the parent directory of your htdocs directory to the CDPATH environment variable. bash(1) will check the contents of the CDPATH environment variable when you type cd foo to find the foo directory in one of the directories listed. This will work no matter what your current working directory is, and it'll be easier than setting symbolic links.
If the path to your htdocs is located /srv/www/htdocs/, then you could use CDPATH=/srv/www. Then, cd foo would first look for /srv/www/foo/ and change to it if it exists; if not, then it would look for foo in the current working directory and change to it if it exists. (This might get confusing if you have multiple htdocs directories on your system; in that case, CDPATH=.:/srv/www would let you change into a child directory easily but still use the /srv/www/htdocs/ version if no ./htdocs directory is present.)
You can add the CDPATH=/srv/www line to your ~/.bashrc file so it works every time you start a terminal.
Comment: An FYI: an OS X `alias` file is not a symbolic link, although it functions like a combination of hard link and symbolic link.  It is something supported primarily by the OS X Finder and its origins are way back in the early days of Classic Mac OS.  It's not trivial to use `alias` files in shell programming.  OS X also supports standard symbolic links and hard links.
Comment: This answer is better than mine as it allows for full path auto completion ie. cd htdocs/another/directory.  My answer would require that you know which sub directory you want (no auto complete).
Comment: @Ned, excellent, thanks; I've removed my completely wrong paragraph. I hadn't expected Apple to use a mechanism above the filesystem layer...
Comment: @Gibron, but there is some nice simplicity in a variable, something I completely overlooked. :)
Comment: Very elegant solution, the only downside to this is when you cd from anywhere you get completion on that path you added. Personally I use cd with first letters and wait for autocomplete to finish for me so I've found the solution a bit annoying.
Answer: I personally use this to quickly work in the directory which is present deep inside one of my Volumes in my Mac.
Open your ~/.bash_profile, create an alias to the directory by adding this:
alias cdh="cd /Volumes/Haiku/haiku/src/apps/superprefs"

Save it, restart your terminal. Now on typing cdh in your terminal should change the working directory to the one mentioned as the alias.
Comment: may need to `source ~/.bash_profile` or `. ~/.bash_profile`. Need to do that in the ubuntu and now need to test it on the actual OSX.
Answer: I am not sure how OSX exposes Alias links but since you are using bash you can just create a variable in your .bashrc file.
On its own line put:
htdocs=YourDirectoryPath/

Once you have restarted bash you can just type cd $htdocs
Comment: I found this to be the least confusing method. Thanks!
Answer: There is a old hint on macworld to do this in a way that is integrated with BASH: Enable 'cd' into directory aliases from the Terminal
Plus, here is an answer that uses this solution on superuser.
Comment: The link you provided looks like it may do the trick, but it's a lot of work.  How about an explanation?
Comment: @ScottBiggs look at the second link for a shorter explanation.
Answer: You may be able to use osascript to do this -- this command seems to work:

cd "`osascript -e "on run aFile" -e "set aFile to POSIX file aFile as alias" -e "tell application "\""Finder"\"" to return POSIX path of ( ( original item of aFile ) as text ) " -e "end run" path_to_my_Finder_alias 2>/dev/null`"

Basically this command is running an AppleScript that finds the destination path of the argument (path_to_my_Finder_alias) in a subshell, then wraps it in double quotes, and changes the directory to it.
Maybe someone with a little more bash expertise can turn it into a bash alias or function.
Answer: try:
alias cdgo=`echo cd /root/go/`

cdgo will run, then get command "cd /root/go/" and enter, and it will change your directory in current terminal process
It works on my centos, no test with osx


Displaying the Drupal administration interface in the main content area

Question: How would I go about displaying the Drupal administration interface in the main content area, instead of it taking up the whole page when the overlay module is disabled...
Answer: If I understand you correctly you are using the Drupal core Seven theme as the administration theme, and you would like to use the active theme instead.
You can change this by going to Appearance. At the bottom of that page you have a select for Administration theme. Choose Default theme to use your site's active theme as the admin theme.


Paginação de um grande array em reactJS

Question: Estou puxando um array com um tamanho de mais ou menos 20.000.
Porém, na hora da paginação, todas as páginas disponíveis aparecem no meu campo de paginação.

Porém queria limitar, pra que aparecessem apenas 3 números e tipo,
1 2 3 ... 10
  render({
    const indexOfLastUser = currentPage * usersPerPage
    const indexOfFirstUser = indexOfLastUser - usersPerPage
    const currentUsers = users.slice(indexOfFirstUser, indexOfLastUser)

    const pageNumbers = []
    for (let i = 1; i <= Math.ceil(users.length / usersPerPage); i++) {
      pageNumbers.push(i)
    }

    const renderPageNumbers =

              «

          {pageNumbers.map(number => {
            return (

{number}

            )
          })}

              »

     return(
      {renderPageNumbers}
     )}

Answer: Bom, eu consegui da seguinte forma
import React, { Component } from 'react'
import ReactPaginate from 'react-paginate'

const users = [
    {
        name: 'DD'
    },
    {
        name: 'Ruan'
    },
    {
        name: 'Reginaldo'
    },
    {
        name: 'Renan'
    },
    {
        name: 'DD'
    },
    {
        name: 'Ruan'
    },
    {
        name: 'Reginaldo'
    },
    {
        name: 'Renan'
    },
    {
        name: 'DD'
    },
    {
        name: 'Ruan'
    },
    {
        name: 'Reginaldo'
    },
    {
        name: 'Renan'
    },
    {
        name: 'DD'
    },
    {
        name: 'Ruan'
    },
    {
        name: 'Reginaldo'
    },
    {
        name: 'Renan'
    },
]

export default class Teste2 extends Component {
    constructor(props) {
        super(props);
        this.state = {
            offset: 0,
            users: users,
            elements: [],
            perPage: 2,
            currentPage: 0,
        };
    }

    componentDidMount() {
        this.receivedData()
    }

    setElementsForCurrentpage() {
        let elements = this.state.users
            .slice(this.state.offset, this.state.offset + this.state.perPage)
            .map((users, index) => {
                return (

{users.name}

                )
            })
        this.setState({ elements: elements })
    }

    handlePageClick = (users) => {
        const selectedPage = users.selected;
        const offset = selectedPage * this.state.perPage;
        this.setState({
            currentPage: selectedPage,
            offset: offset
        }, () => {
            this.setElementsForCurrentpage()
        })
    }

    receivedData() {
        this.setState({
            users: this.state.users,
            pageCount: Math.ceil(this.state.users.length / this.state.perPage)
        }, () => this.setElementsForCurrentpage())
    }

    render() {
        let paginationElement
        if (this.state.pageCount > 1) {
            paginationElement = (
                <ReactPaginate
                    previousLabel={"← Previous"}
                    nextLabel={"Next →"}
                    breakLabel={...}
                    pageCount={this.state.pageCount}
                    onPageChange={this.handlePageClick}
                    forcePage={this.state.currentPage}
                    containerClassName={"pagination"}
                    previousLinkClassName={"previous_page"}
                    nextLinkClassName={"next_page"}
                    disabledClassName={"disabled"}
                    activeClassName={"active"}
                />
            );
        }
        return (

Teste

                {paginationElement}
                {this.state.elements}
                {paginationElement}

        )
    }
}

Paginação de um grande array em reactJS


To prove that irrational powers of 1 is equal to 1

Question: It is easy to prove that if 1 is raised
to any power of a rational number ( say $x$), then :
$(1)^x = (1)^{p/q}$
(because $x$ can be expressed as $p/q$ where $p$ and $q$ are integers except $q≠0$). And,
$(1)^{(p/q)} = (1)^p/(1)^q = 1/1 = 1$
But I am stuck in proving following :
a)   $1^π = 1$
b)   $1^e = 1$
c)   $1^{\sqrt3} = 1$
Or in general, how to prove $1^{y}$ = 1 , where $y$ is an irrational number.
I would appreciate any help in proving above things .
Comment: Perhaps show $\log(1^x)=0$ for all real $x$ and so $1^x=1$
Comment: What is your definition of real powers?
Comment: See [Exponentiation: real exponents](https://en.wikipedia.org/wiki/Exponentiation#Real_exponents): "For positive real numbers, exponentiation to real powers can be defined in two equivalent ways..."
Comment: You have to use definitions: the def for integer exponents, based on "repeated" multiplication, does **not** work for *real* exponents. You have to find a suitable def that - for the case of exponents that are integers - fits with the already available one. This is the way math works...
Comment: What does $a^b$ mean when $a>0$ and $b$ is real?  My calculator says $2^\pi \approx 8.825$ but what is it calculating? What is your fundamental definition?
Comment: You can define irrational powers using continuity or monotonicity between rational powers, or using logarithms and antilogarithms, or using something else.  But you need to tell us your definition, and your choice affects how difficult the proof is.
Comment: How about show that $a^0=1$ for $a\in \mathbb{R}$ and $a \neq 0 $. Then use that to establish for $x \in \mathbb{R}$, $1^x=(a^0)^x=a^0=1.$
Comment: @Shiva Keep fair. We did not know what you are allowed to use , in this case that the exponential laws hold also for real exponents as long as the base is positive. Strictly speaking , it requires high math to justify those laws.
Comment: Do you know "logarithm "
Comment: @Shiva yes, but how do you define it?
Comment: @Shiva Forgive my harsh criticism, but your request is, as JMoravitz pointed out, unfair, and hypocritical, not to mention illogical. You said "definitions are off-topic for this question." **No, they are not.** Definitions are at the foundation of all mathematics. There are no mathematics without definitions. You cannot prove any statements without definitions. If you want me to prove "The sky is blue," you first need to give me definitions of the words "sky" and "blue." Otherwise, the sentence is incoherent. I vote this question be closed.
Comment: @BasantaRajPahari That would be an invalid proof, since it is necessarily circular. You cannot assert $(a^b)^c=a^{bc}$ without proof. To prove it, you need to accept a definition to begin with.
Comment: I am sorry everyone for the dumb things I did in past. I had edited to make it more focused and removed un-necessary things.Also , I accept the definitions of laws of exponents to be valid.
Answer: You first need to understand what $1^x$ means when $x$ is irrational. If $x$ is rational, then it can be written as $x=p/q$ in reduced form. Then, for any real number $a$, the definition of $a^x$ is
$$
\sqrt[q]{a^p},
$$
where $a^p=a\cdot a\cdots a$ when $p>0$, and $a^p=(1/a)\cdot (1/a)\cdots (1/a)$ when $p<0$ (both repeated $|p|$ times).
This does not work when $x$ is irrational, so what to we do? The idea is to approximate $x$ by rational numbers. For example, to compute $a^\pi$, you could look at the sequence of numbers
$$
a^3,\;a^{3.1},\;a^{3.14},\;a^{3.141},\dots
$$
Each of these makes sense since any terminating decimal can be written as a fraction. As the exponents get closer and closer to $\pi$, it turns out that the list of numbers will converge to some number. We call the number they converge to $a^{\pi}$. To make all this precise, you need to understand what the limit of a sequence means.
To prove that $1^{\pi}=1$, you just have to note that $1^{\pi}$ is defined as the limit of the sequence $1^{3},1^{3.1},1^{3.14},\dots$, and these numbers are all $1$ because of the rules you stated in your question. Since the limit of a sequence of $1$'s is just $1$, we conclude $1^\pi=1$. The same applies to any irrational number $x$; it is always true that $1^x=1$.
Comment: So, lim(x tends to π) 1^(x) = 1^(π) . I have been taught that limits calculate limiting values and not actual values?
Comment: Hi, I asked for actual values and not limiting values. We can find only limiting values and not actual values because actual values are indeterminable? Thanks


A limit with determinants

Question: I'd be thankful if some could explain to me why the second equality is true...
I just can't figure it out. Maybe it's something really simple I am missing?

$\displaystyle\lim_{\epsilon\to0}\frac{\det(Id+\epsilon H)-\det(Id)}{\epsilon}=\displaystyle\lim_{\epsilon\to0}\frac{1}{\epsilon}\left[\det  \begin{pmatrix}
        1+\epsilon h_{11} & \epsilon h_{12} &\cdots & \epsilon h_{1n} \\
        \epsilon h_{21} & 1+\epsilon h_{22} &\cdots \\
        \vdots &  & \ddots \\
        \epsilon h_{n1} & & &1+\epsilon h_{nn}
        \end{pmatrix}-1\right]$
$\qquad\qquad\qquad\qquad\qquad\qquad=\displaystyle\sum_{i=1}^nh_{ii}=\text{trace}(H)$
Comment: One possible approach: Group terms in the expansion of the determinant by powers of $\varepsilon$. You can show that the determinant is $$1+\varepsilon \sum_{i=1}^n h_{ii} + O(\varepsilon^2),$$ which is exactly what you need.
Comment: (specifically, use the [Leibniz expansion](https://en.wikipedia.org/wiki/Leibniz_formula_for_determinants)).
Comment: @angryavian: A bit confusing but $Id$ is short for Identity.
Comment: Relevant post from [Terrence Tao's blog](https://terrytao.wordpress.com/2013/01/13/matrix-identities-as-derivatives-of-determinant-identities/)
Comment: @Omnomnomnom, I went ahead and posted it. There are a couple of details missing, but I think it has enough included in order to expand it into a rigorous proof rather easily if needed.
Comment: I suppose you don't really mean the *last* equality?
Comment: oh oops, the one before it
Comment: Another - less good? - approach: put $H$ into Jordan canonical form (over the algebraic closure).
Comment: @NicholasStull if you have the time/patience, you should put that up as an answer
Comment: @peterag less good as far as I'm concerned, at the very least, since we now must invoke complex numbers for a real derivative.  Also, it takes us a step further away from $\sum h_{ii}$ since we have to say that it coincides with the sum of the eigenvalues.
Comment: @Omnomnomnom  - I entirely agree, and I shouldn't have put the question mark after the 'less good.' On the other hand, the equality is obvious for upper triangular  matrices...
Answer: Here is a conceptual proof that avoids expanding a complicated determinant:
The determinant of a linear operator (or of a square matrix) is the product of the eigenvalues, counting multiplicity. The trace of a linear operator (or of a square matrix) is the sum of the eigenvalues, counting multiplicity.
Now suppose that $\lambda_1, \dots, \lambda_n$ are the eigenvalues of $H$, counting multiplicity. Then the eigenvalues of $I + \epsilon H$ are
$$
1 + \epsilon \lambda_1, \dots, 1 + \epsilon \lambda_n,
$$
counting multiplicity. Thus
$$
\det(1 + \epsilon H) = (1 + \epsilon \lambda_1) \cdots (1 + \epsilon \lambda_n).
$$
It is now clear that
\begin{align*}
\lim_{\epsilon\to 0} \frac{ \det(1 + \epsilon H) - 1}{\epsilon} &= \lambda_1 + \dots + \lambda_n\\
&= \text{trace } H,
\end{align*}
as desired.
Comment: My proof above does not require $H$ to be diagonalizable because each operator (or square matrix) on an $n$-dimensional complex vector space has exactly $n$ eigenvalues, counting multiplicity.
Comment: A very nice alternative approach to this question (and much easier to express rigorously than using the Leibniz Expansion in retrospect).
Comment: Thank you, this is indeed a nice approach, but H doesn't have to be a diagnolizable matrix
Answer: As I suggested in my comment, we proceed by expanding
$$|Id + \varepsilon H| = |A| = \left| \begin{array}{cccc}
1+\varepsilon h_{11} & \varepsilon h_{12} & \cdots & \varepsilon h_{1n}\\
\varepsilon h_{21} & 1+\varepsilon h_{22} & \cdots & \ \\
\vdots & \ & \ddots & \ &\\
\varepsilon h_{n1} & \ & \ & 1+\varepsilon h_{nn}
\end{array} \right|$$
in powers of $\varepsilon$. First, we have:
$$|A| = (1+\varepsilon h_{11}) \left| \begin{array}{cccc}
1+\varepsilon h_{22} & \varepsilon h_{23} & \cdots & \varepsilon h_{2n}\\
\varepsilon h_{32} & 1+\varepsilon h_{33} & \cdots & \ \\
\vdots & \ & \ddots & \ &\\
\varepsilon h_{n2} & \ & \ & 1+\varepsilon h_{nn}
\end{array} \right| + \varepsilon\sum_{j=2}^n (-1)^{1+j} h_{1j} \det(A_{1j})$$
where $\det(A_{1j}) = O(\varepsilon)$ (here, I am using the usual notation $A_{1j}$ to be the matrix obtained by deleting the first row and $j$th column from $A$).
Justification of this part: The minimal power of $\varepsilon$ would occur when the maximal number of diagonal terms is included. In this case (dealing with $(n-1)\times (n-1)$ minors, this would mean $n-2$ diagonal terms, since all terms of the cofactor expansion along the first row (with the exception of the first one, which I am separating from the rest of the computation) would exclude the $1+\varepsilon h_{11}$, as well as the diagonal entry that sits in the $j$th column. Finally, if there are $n-2$ diagonal terms multiplied together (in the minimal case), then there must be one off-diagonal term, introducing the (claimed) factor of $\varepsilon$.
We hence conclude that $$|A| = (1+\varepsilon h_{11}) \left| \begin{array}{cccc}
1+\varepsilon h_{22} & \varepsilon h_{23} & \cdots & \varepsilon h_{2n}\\
\varepsilon h_{32} & 1+\varepsilon h_{33} & \cdots & \ \\
\vdots & \ & \ddots & \ &\\
\varepsilon h_{n2} & \ & \ & 1+\varepsilon h_{nn}
\end{array} \right| + O(\varepsilon^2)$$
Continuing (inductively) to expand the determinant in this manner, we see that
\begin{align}
|A| &= \prod_{j=1}^n (1+\varepsilon h_{jj}) + O(\varepsilon^2)\\
&= 1+\varepsilon \sum_{j=1}^n h_{jj} + O(\varepsilon^2)
\end{align}
which exactly yields the desired equality, since this immediately says
$$|A|-1 = \varepsilon \sum_{j=1}^n h_{jj} + O(\varepsilon^2),$$
hence
\begin{align}
\lim_{\varepsilon \to 0} \frac{1}{\varepsilon}(|A|-1) &= \lim_{\varepsilon\to 0} \frac{1}{\varepsilon} \left( \varepsilon \sum_{j=1}^n h_{jj} + O(\varepsilon^2) \right)\\
&= \lim_{\varepsilon\to 0} \left( \sum_{j=1}^n h_{jj} + O(\varepsilon) \right)\\
&= \sum_{j=1}^n h_{jj} = \text{Trace}(H)
\end{align}
Comment: Thank you very much! Exacly what I was looking for
Answer: Hint:
$$\left|\begin{matrix}
1+\epsilon h_{11}&\epsilon h_{12}\\
\epsilon h_{21}&1+\epsilon h_{22}\\
\end{matrix}\right|=1+\epsilon h_{11}+\epsilon h_{22}+\epsilon^2\left(h_{11}h_{22}-h_{12}h_{21}\right).$$
Only the main diagonal generates terms in $\epsilon$. This generalizes to higher order, for instance using the expansion by minors.
Answer: actually, you're trying to calculate the differential $\phi$ of the function $\det : M_n(\mathbb{R}) \rightarrow \mathbb{R}$ at $I_n$, which is defined as
$$\forall H \in M_n(\mathbb{R}), \phi(H) = \lim\limits_{t \to 0} \dfrac{\det(I_n+tH)-\det(I_n)}{t}=
\dfrac{d}{dt}_{t=0} \det(I_n+tH)
$$
First, since $\det$ is a polynomial, it is differentiable at any point and $\phi$ is a linear form on $M_n(\mathbb{R})$. Therefore, it suffices to calculate its value on the canonical basis of $M_n(\mathbb{R})$.

For $H=E_{i,i}$,  $\det(I_n+tE_{i,i})=1+t$, so $\phi(E_{i,i})=1$.
For $H=E_{i,j},$ where $i \neq j, \det(I_n+tE_{i,j})=1$, so $\phi(E_{i,j})=0$.

So, $\phi=\textrm{Trace}$, since these two linear forms coincide on a basis of $M_n(\mathbb{R})$.
Comment: Maybe I'm misunderstanding but, how did you conclude $\phi$ is a linear form? The determinant is multilinear in columns. It just so happens that the answer is indeed linear.
Answer: Late comments.

This is a special case of Jacobi's formula.
One way to prove the problem statement using Laplace/cofactor expansion, but easier to understand than other similar approaches and without creating a mess, is to use total derivative. Let
$$
g(t_{11},t_{12},\ldots,t_{nn})=\det\pmatrix{
1+t_{11}h_{11}&t_{12}h_{12}&\cdots&t_{1n}h_{1n}\\
t_{21}h_{21}&1+t_{22}h_{22}&\cdots&t_{2n}h_{2n}\\
\vdots&&\ddots&\vdots\\
t_{n1}h_{n1}&t_{n2}h_{n2}&\cdots&1+t_{nn}h_{nn}},
$$
where each $t_{ij}=t_{ij}(\epsilon)=\epsilon$ (yes, here each $t_{ij}$s is actually identical to $\epsilon$, but we'd like to view it as a function of $\epsilon$). Let also $f(\epsilon)=g\left(t_{11}(\epsilon),t_{12}(\epsilon),\ldots,t_{nn}(\epsilon)\right)$. Then
$$
f'(\epsilon)=\sum_{i,j}\frac{\partial g}{\partial t_{ij}}\frac{\partial t_{ij}}{\partial \epsilon}=\sum_{i,j}\frac{\partial g}{\partial t_{ij}}
$$
and in turn
$$
f'(0)=\sum_{i,j}\left.\frac{\partial g}{\partial t_{ij}}\right|_{t_{ij}=0}.
$$
However, to evaluate $\left.\frac{\partial g}{\partial t_{ij}}\right|_{t_{ij}=0}$, all other $t_{rs}$ are treated as zero and we are effectively finding the derivative of $g$ with respect to a single variable $t_{ij}$. By Laplace expansion along the $i$-row, we see that
$$
\left.\frac{\partial g}{\partial t_{ij}}\right|_{t_{ij}=0}=
\begin{cases}
h_{ii}&\text{ if } i=j,\\
0&\text{ otherwise}.
\end{cases}
$$
Therefore $f'(0)=\sum_i h_{ii}=\operatorname{trace}(H)$.

A limit with determinants


Do contemporary singers sound "wrong" without a microphone?

Question: When I play guitar and sing, it isn't very loud because I mix my head voice with falsetto. It's impossible for me to know what this sounds like without recording my voice- but the only way to record is with a microphone, and it sounds exactly like I want it to. However, I'm nervous to sing around people because I don't feel like the recording is a true representation of what someone would actually hear.
For example, usually in a pop or rock chorus the singer will sound like they're yelling or shouting, and when I record with my mouth closer to the mic and the guitar farther away, I can replicate that sound and it's as powerful as the original. But I know that I'm manipulating my falsetto and pretending that I'm yelling, when it's actually no louder than speech level singing.
I did find this article about microphones, but I've never heard this information from any YouTube videos or singing websites. It says:

When you listen to the vocal in a sound recording, you don't actually hear the singer. Usually what you hear is a loudspeaker illusion of the vocal, one so compelling that you think you know the voice of your favorite singers. But it's likely that they would sound very different singing to you in your living room or in your car. In fact, they might sound wrong. The discipline of pop music production includes the creation of sounds that are better than those in real life— exaggerated, unmistakable, and often unforgettable. And although that's true for all the members of a band, the vocalists get special attention.

I understand that pop and rock singers must use microphones to be heard, and that effects are added to live shows. I also understand that a microphone automatically makes our voices much louder and fuller. What I'm having trouble understanding is what a few friends in a singer's living room would hear if they sing without a microphone- using the same techniques they use to practice and record.
Would it sound weak and would their "shouts" sound artificial?
Would their voices project towards their audience better than in their own ears, so that the audience hears the same sounds that a recording in a smartphone would provide?
Or should singers sacrifice range and "emotion" for volume if they don't have access to a microphone.
Or maybe I have it all wrong and don't make any sense lol.
Here is an example of Bruno Mars singing Count on Me in front of an audience without a microphone. He doesn't sing the bridge, and I think the reason why is because he traded range for volume. Not that he couldn't hit that C5 (you'll always have my shoulder when you cryyyyy) with volume, but that it would come out like a heavy metal scream instead of a controlled, soft rasp. Hopefully that makes sense.
By microphone, I basically mean a recording device that would be used for practice. Does the conversion of natural(?) sound to electronical allow for unconventional singing techniques that would sound "wrong" if sung in a completely acoustic setting?
Answer: The proximity of a mic to a singer will have a profound difference in the sound captured. Good vocalists use this phenomenon a lot - you'll see someone holding a mic at various distances from the mouth - to vary volume and to an extent tone. Add that to the almost infinite variation of tone and volume naturally, and there's a heck of a range.
On a personal note, I like my mic's volume to be fairly high. This is because I'm usually playing an instrument at the same time, and the mic's on a stand, so I have to move to and from the mic to get effects I want. And, yes, it's switched off when I'm not singing!
Listening  to one's own voice singing in a room will sound 'nothing like you'. One of the reasons is that we partially hear our own voice through sympathetic vibrations of the bones in our head. That's one of the reasons most of us are surprised (pleasantly or not...) when we first hear our own recorded voice.
One way to alleviate the problem is to use a mic away from the singer, so he's not singing directly into it, or anywhere near. That eliminates the proximity effect. But at the same time, it includes any coloration the room may give - soft furnishings, curtains will make it sound quite different from no carpet, stark walls and a couple of wooden chairs.
Another factor is that during recording in a studio, a myriad of effects is available to improve and/or change the singer's voice. Hope this answers at least part of your question.
Comment: I think it's fair to say a microphone is an instrument too - you need to learn how to play it to best effect. I like my mic on stage loud too - gives the greatest potential for intentional variation.
Comment: @Tetsujin - what really gets me is when some 'expert' sorts all the mics out on stage before the gig. He has one voice, and all the mics are adjusted to that. He hasn't realised that  each mic will be used by someone who has a voice probably very different from his!
Comment: In a word, yes!
Comment: @gidds - Having done thousands of sound checks - both for a band I was playing with at the time, and as sound man, I'm amazed at the differences used. A four piece band taking 45 mins to 'get the sound right' (when the place is empty?!) to big bands which merely check each mic is working, and subtly balance through the first number. And generally the better sounding ones were those who didn't spend (waste?) much time. Many's the time when there's no opportunity to sound check, and professionalism has to do the job. Experience usually wins through. Still stand by answer and comments.
Comment: All walks of life are densely populated with 'egg-spurts'. I don't think there's anything we can [legally] do about them ;)
Comment: @Tetsujin - or - 'all walks of life are populated by dense egg-spurts'?
Comment: The proximity effect is definitely the correct answer. You recommend moving the mic farther away to alleviate the effect, but I'm wondering if pop singers move the mic closer, and use a different technique that is dependent on it. In other words, does the proximity effect add a "chest voice" sound to give the illusion that a singer is doing more than they actually are?
Comment: @Tim One of the purposes of a sound-check is to ensure each mic is set up (physically and sonically) for the person/instrument using it.  A sound tech may well do some initial checks to ensure that each mic is connected to the right channel &c and the levels are ballpark, but I've never heard of that being the _only_ check — not even in a 2-man church band!
Answer: For a historical perspective:
Before the use of vocal microphones, singers needed to be heard , unaided, at the back of the hall.  In classical music, for example, the development of opera-singing technique was partly due to the need to be heard over progressively larger and louder orchestras and choirs!  In popular music, too, singers needed a very loud style to be heard over a band.
When sound started to be broadcast over radio and recorded, microphones allowed singers to be heard even when singing quietly, and crooning developed, as popularised by singers like Bing Crosby.  This allowed singers to use a much more personal, intimate style that suited more sentimental music, even when backed by a full orchestra or band.
Of course, a microphone doesn't require such a style; by adjusting placement and amplification, it can still be used with louder, more forceful singing too.  So we now have a wide range of singing styles and levels, all suitable for concerts and broadcasting and recording.
As for what a singer would sound like without amplification, it depends.  If they kept the amplified backing, but still sang in an intimate style, then they probably wouldn't be heard over it.  However, in a relatively small space, if the backing was quieter and 'unplugged' to suit the song, it could still work very well.  Alternatively, the singer could sing louder to be heard over the backing — how this sounded would depend upon how much their singing changed as a result (which would in turn depend upon how much louder they needed to be, the style of music, their ability and technique, &c), so it's hard to generalise.  Certainly few singers could maintain an intimate, gentle style while singing very loudly — though some could approximate it better than others.
And if you want to find out what you sound like, I'd suggest getting a 'distant' mic (capacitor/condenser, or even just a smartphone), setting it up across the room, recording yourself singing and playing, and then listening to the results.  (Yes, it's always painful listening to yourself, but it's the only way!)
Comment: :-)  That's from personal experience, of course…  I studied singing for several years, and was advised to tape-record the lessons.  After a few years, I could just about bear listening to myself — that's when I knew I'd got good!
Comment: I've been practicing singing for a few months and I always record myself. It's a bit painful, but it seems like the only way to actually know what you sound like and get 'honest' feedback.
Comment: Great point about quiet singing, crooning, being reproduced at higher than natural volume through electronic amplification. It's hugely important in modern pop recording, but probably unnoticed by the average listener, where you can hear whisper level vocals balanced over overdriven guitars and strong drumming.
Answer: Yes, 'popular' singers generally use a microphone, if we define 'popular' as pop, rock, jazz etc.   And they use it close, as part of their performance, which is rather different to placing a mic further away to capture a recording of an acoustic performance.
(Opera singers don't close-mic, and might still be popular of course.)
But this is really the 'I don't like the sound of my own voice when amplified' question, isn't it!  Don't worry so much about the sound of your voice, concentrate on communicating the song.  Don't be frightened of hearing it coming back at you through a speaker LOUD!
Perhaps your voice is 'big' enough to perform unamplified in a smaller room.  Try.   It's not that long since that was the only way to do it!
Comment: Thanks for the answer. My question is actually a little different. I'm satisfied with the sound of my voice *loud* through a microphone, or at any volume from a recorded device. My concern is what I sound like to other people *without* a mic. Basically I'm wondering if I play my guitar very quietly in a very quiet room, using the technique I use when I record (singing no louder than falsetto), will my voice project to my listener just as powerfully as the recording sounds, or will it sound weak and strange?
Comment: @anonymouswho - 'falsetto' isn't really a volume for the voice, although it's often quieter than head voice, which again can be 'turned down'. The difference is more of quality of sound.
Comment: @Tim I think "speech level singing" is what I'm referring to. Your answer is correct and provides a lot of great information, but I'm trying to figure out if I should sing this way around friends, or if I should sacrifice some range and "emotion" for more volume and power. I feel like if I sing this way in front of people, they will think it's weak and strange sounding. It seems if my technique is correct, then popular artist would also experience this if they sang without a mic. That's why I think Bruno Mars is singing with more "chest voice" and ends the song very early in the link above.
Comment: @anonymouswho - Every song is different, and must be sung in a different way. It would be folly to try to sing every song using the same volume, power and tone. The point of recognising the different facets one's voice is capable of is that one can vary the way one sings. Keep it varied, according to the song and type of song.
Answer: Yes.  Current popular singers are called popular because they usually have large audiences, which requires microphones for recording and amplification, either for remote playback (mp3, etc.) or large concert venues.  A sound, audio or recording engineer usually designs microphone placement(s) and audio processing to create a sound representing an artistic (or marketing) intent, which may or may not be "realistic".  The final result can be quite different from the far field sound into the ear of a listener at some distance from a voice in a strictly acoustic venue.  To hear what one sounds like acoustically, the industry makes special microphones (look up binaural head microphones) that can record more closely what a listener might hear at a given distance in a room.  You would have to record your voice in the actual venue, as each room can transmit a different sound to a listener's ears due to room acoustics.
Answer: An amplified voice is a product that includes capture, processing, equalization and projection, just like the sound of an electric (and even amplified acoustics and half-acoustics) guitar.  The amount of processing and equalization done is variable and depends on the voice you start with.
For a classically trained voice (see this example from Nina Hagen in 1978), you will find that a living room performance will end up less consistent in volume and tone but essentially quite similar.
For singer where the amplification has been an essential part of their "instrument" for a long time, the amount of processing is a lot harder to guess and the likelihood of an unamplified performance being hard to recognize higher.
This goes particularly for techniques like growling, vocal fry, rasping and so on which tend to rely on amplification for useful volume and processing for tonal signature.
There are also processors like "autotune" that create a boost in overall quality for singers with a less than perfect grasp on pitch.
However, while there is a lot you can do with processing, competition is heavy and so signature acts rather than fly-by-nights tend to have pretty solid basics after all, since with lot of competition, getting close may not be enough.  Or you need to stand out differently like Bob Dylan who competes on the quality of his songwriting skills.  He won't sound all that much different than when singing in his living room but then he doesn't need to.

Do contemporary singers sound “wrong” without a microphone?


how to add gradient color to vector image in android and to use in bottom navigation view

Question: how to achieve this bottom navigation view in android with gradient color effect.
Answer: Incase you dont have gradient drawable, here is the example of primary_gradient.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:startColor="@color/white"
        android:endColor="@color/colorPrimary"
        android:angle="90" />
</shape>

You need to make a selector for it, lets call it nav_item_background_state.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/primary_gradient" android:state_checked="true" />
    <item android:drawable="@color/white" android:state_checked="false" />
</selector>

Then you can add code below to your bottom navigation

app:itemBackground="@drawable/nav_item_background_state"
Comment: Thanks Erwin Kurniawan i was able to achieve gradient overlay color but how to get gradient color vector icon and that top gradient color selected line??
Answer: you can use gradient color in vector but drawable is not allowed
for using gradient color you have to create a file inside res/color folder
<?xml version="1.0" encoding="utf-8"?>
<gradient xmlns:android="http://schemas.android.com/apk/res/android"
    android:startColor="#FFFFFF"
    android:centerColor="#0000FF"
    android:endColor="#00FFFF"
    android:angle="145"
    android:startX="30"
    android:endX="70"
    android:startY="30"
    android:endY="70"
    android:type="linear"/>

and inside vector file use it as a normal color


jQuery logic for unclicked paragraphs

Question: i have following html structure.

Computer and Laptop Repairs

content

Softrware and Hardware

content2

So i have repetetion of content1 content2 content3 etc. I am writting a toggle function so that when i click on first paragraph first content div expands. When i click on second paragraph second expands but all other open content collapses.
Can somebody help.
Answer: $('.expandableContent').click(function() {
    $('.services').hide();
    $('.services', this).show();
});

Also add these to your html:

....

content

Answer: You can do it without modifying your HTML too.
$(document).ready(function() {
    $('.services').hide();
    $('.expandableContent').click(function() {
        $('.services:visible').toggle();
        $(this).nextAll('.services:first').toggle();
    });
});

The code should be mostly self-explanatory. By selecting only the visible .services, I can toggle them to hidden. I then used the nextAll() to find all following siblings with the class, .services, but only take the first. (I can't use next() as it only takes the immediately following sibling and then filters it by class. Not what we want.) I then toggle this between visible and hidden. You can find a working example at http://jsfiddle.net/Lv2mW/.
Answer: This should do the trick for you:
$(function() {
    $('.expandableContent').click(function() {
        $('.services').hide();
        $(this).nextAll('.services:first').show();
    });
});

First, you'll hide all .services divs, then select the next one after the paragraph that was clicked, and expand it.
Here's a demo of that in action: http://jsfiddle.net/Ender/5nYpT/

jQuery logic for unclicked paragraphs


Escrevi esse código no Dev C++, ele compilou mas não realiza a operação

Question: Quando executo e digito um número ele não faz a multiplicação, só exibe a mensagem " Preço:" e não o resultado da multiplicação.
<code>#include<stdio.h>
main()

{

int quantidade;
double valor;
scanf("%d", &quantidade);

        if(quantidade<12)
        {
          printf ("Preço:");
          valor=quantidade*1.3;

        }
        else
        {
         printf ("Preço:");
         valor=quantidade*1.0;

        }
</code>
Comment: Ele está fazendo exatamente o que você mandou fazer. Inclusive ele faz a multiplicação. Mas por alguma razão parece que não é o que deseja, por isso precisaria escrever na pergunta o que deveria ter acontecido na sua concepção.
Comment: Ele não exibe o resultado na execução, só aparece "Preço:".
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo
Answer: O maior problema é que não está mandando imprimir o resultado. Tudo o que quer que o código faça você tem que dizer. E não precisa dizer nada que seja desnecessário. Esse código poderia ser simplificado já que o objetivo dele parece ser apenas ler um número e dependendo dele gerar outro número baseado nele multiplicado por um fator predeterminado. Então só precisa ter uma variável para armazenar o dado pedido para digitar, pedir para digitar e mandar imprimir o cálculo, que pode ser feita em uma expressão condicional simples. Reforço, se não mandar imprimir o resultado ele não será impresso, nada acontece como mágica no código. E compilar é uma preocupação desnecessária, o que importa é o código estar certo, ter compilado não é medida de algo certo.
<code>#include <stdio.h>

int main(void) {
    int quantidade;
    scanf("%d", &quantidade);
    printf("Preço: %lf", quantidade * (quantidade < 12 ? 1.3 : 1.0));
}
</code>
Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
A pergunta fala em C++, mas esse código é C e não C++, mesmo que ele compile em C++, é bom ter em mente que não é C++. E eu não usaria este IDE, ele é bastante criticado.


What happened with the answer ratio?

Question: This morning the answer questions percentage was at 88%.
Not it's 82%. .
I doubt that in one day were added about 450+ unanswered questions that would represent 6% of the total number of questions (about 8k).
Comment: I've been asking a *lot* of questions in meta lately :P
Comment: Bug, bug, bug :-(

http://meta.stackexchange.com/questions/233979/how-are-beta-site-statistics-calculated
Comment: @Tim. So which one is the correct value: 82 or 88? By my calculations it should be around 90%.
Comment: We will see soon.
Answer: Oddly I think it is correct, unless my basic maths failed again. I wonder if something happened to a lot of our questions.
We currently have:
<code>8010: total questions
1433: question without an up voted answer
</code>
I blame Ben for actually advertising the website ;)
Comment: Hmmm. I thought "unanswered questions" were calculated differently. for me "unanswered questions" means "questions without an answer". But I guess you are right....Oh...and I also blame Ben for everything also. :)
Comment: @Marius think that a big part of the massive drop was because we have gone from around 20 questions per day to over 40....again this is all Ben's fault ;)

What happened with the answer ratio?


Is $\mathcal{D}_k(k[x])$ generated by $\partial_1,\partial_p,\partial_{p^2},\ldots$ and multiplication maps?

Question: Let $k$ be a field of characteristic $p>0$, and let $\mathcal{D}=\mathcal{D}_k(k[x])$ be the ring of differential operators on $k[x]$. That is, we define
$$
\mathcal{D}_{\leq -1}:=\{0\}\subseteq\operatorname{End}_k(k[x])\\
\text{for }n\in\mathbb{Z}_{\geq 0}:\quad\mathcal{D}_{\leq n}:=\{D\in\operatorname{End}_k(k[x])\ |\ \forall f\in k[x]:\ [D,\mu_f]\in\mathcal{D}_{\leq n-1}\}\\
\mathcal{D}:=\bigcup_{n\geq -1}\mathcal{D}_{n}
$$
where $\mu_\bullet$ denotes multiplication by the element in the subscript, and $[\bullet,\bullet]$ is the Lie-bracket (i.e. $[f,g]=f\circ g-g\circ f$).
Now for $n\in\mathbb{Z}_{\geq 0}$, let $\partial_n:k[x]\to k[x]$ be defined by $\partial_n(x^m):=\binom{m}{n}x^{m-n}$, extended by $k$-linearity; it is not hard to verify that $\partial_n\in\mathcal{D}_{\leq n}$. Then is it true that $\mathcal{D}$ is generated as a $k$-algebra by $\{\partial_1,\partial_p,\partial_{p^2},\ldots\}\cup\mathcal{D}_{\leq 0}$?
Playing around a bit I think that every $\partial_n$ can be expressed in terms of $\{\partial_{p^i}\}_{i\geq 0}$, so the question reduces to whether $\{\partial_n\}_{n\geq 0}\cup\mathcal{D}_{\leq 0}$ generates $\mathcal{D}$. Is that the case?
This question is motivatet by trying to understand the ring of differential operators in positive characteristic. Note that in characteristic zero, $\mathcal{D}$ is generated by $\mathcal{D}_{\leq 1}$ and can then be described fairly concretely.
Answer: Note that $f \partial_n \in D_{\leq n}$ kills $x^0, \dots, x^{n-1}$ and sends $x^n$ to $f$. Given $D \in D_{\leq n}$, we can therefore adjust $D$ by an element of $k[x] + k[x] \partial_1 + \cdots + k[x] \partial_n$ so that $D x^i = 0$ for $i \leq n$. It therefore suffices to prove that the following claim.
Claim: If $D \in \mathcal{D}_{\leq n}$ and $D x^i = 0$ for $i \leq n$ then $D = 0$.
Proof: We will prove $D x^k = 0$ by induction on $n$ and $k$. We may assume $n \geq 0$ and $k > n$. Now
$$ D x^k = x D x^{k-1} + [D, x] x^{k-1}.$$
By induction on $k$, $D x^{k-1} = 0$. Since $[D, x] x^i = 0$ for $i \leq n-1$, $[D, x] x^{k-1} = 0$ by induction on $n$. Hence $D x^k = 0$.


Finding the error probability of an optimal bayes classifier analytically

Question: I have two classes $\omega_1,\omega_2$ with equal prior probability $P(\omega_1)=P(\omega_2)=0.5$.
And the points in 2D are distributed $\mathcal{N}(\mu_i,\Sigma), \mu_1=(0,0)^T, \mu_1=(4,4)^T, \Sigma=\biggl(\begin{matrix}2&-1\\-1&2\end{matrix}\biggr)$.
I got that the optimal bayes classifier is: $f(x_1,x_2)=\begin{cases}\omega_1&x_1+x_2\leq4\\\omega_2&else\end{cases}$
I want to calculate the error probability of that classifier analytically, I want to express it as a function of the cumulative distribution function of the standard normal distribution $\mathcal{N}(0,1)$.
There's a clue given in the question to turn the problem into a one-dimensional one using a rotation of the axis.
can someone tell me how can that be done?
Comment: I think I made a mistake with the classifier, I think this is the naive bayes classifier, and not the optimal one, in this case how do I find the optimal classifier?
Comment: I think you mean distributed and not "distrusted".  If you have the two densities you have integrate the posterior distribution with the lower density since the rule would pick the class with the higher posterior density. Note that this will change when the densities cross.
Comment: In the case of the normal distributions with the same variance the boundary of equal density is a line. Since you are integrating normal densities doing this analytically means doing it numerically.  In your case if you did it right the line x1+x2=4 is that boundary.
Comment: I know that I need to integrate the posterior distributions with the lower density, but the question I'm trying to solve wanted me to right down a closed formula using the CDF of a standard normal distribution. that's what I'm having difficulty with.
If what I found is correct, what does a naive bayes classifier look like? what's the difference?
Comment: I meant to say that in general integrating a normal distribution over a range of values does not yield a closed form expression.  So I don't think it is possible unless your definition of closed form is different from mine.  Do you consider an infinite eries a closed form?
Comment: Ok, "closed form" might not be the most successful word to use here. I want to find an expression for the probability of error using the CDF of a standard normal distribution, for example: P(error)=1-phi(0.9)
So in a sense I suppose that is a numerical calculation (or however phi is usually calculated). but all I need to is to express P(error) in terms of phi.
Answer: Let $(X,Y)$ denote the observation, and suppose that the conditional distribution of $(X,Y)$ is bivariate normal: specifically if $(X,Y)$ is from Class I, then $(X,Y) \sim \mathcal N((0,0), \Sigma)$ while if if $(X,Y)$ is from Class II, then $(X,Y) \sim \mathcal N((4,4), \Sigma)$, where the covariance matrix $\Sigma$ is $\begin{bmatrix}2&-1\\-1&2\end{bmatrix}$.Both classes are equally likely, and so we don't have to worry about the prior probabilities of the two classes mucking up the comparisons of the conditional posterior distributions of $(X,Y)$ for the two classes to determine which is larger.  Put another way. the optimal Bayes classifier compares the likelihood ratio $\frac{f_2}{f_1}$ to $\frac{\pi_1}{\pi_2}$ to determine the decision, but since $\frac{\pi_1}{\pi_2} = 1$, the optimal Bayes classifier is the same as the maximum-likelihood classifier.
The Naive Bayes classifier treats $X$ and $Y$ as independent random variables (even though they aren't in this instance) in which case the decision boundary is just the line $x+y=4$ in the $x$-$y$ plane. The classification is announced to be Class II if the point $(X,Y)$ lies above this line and Class I if $(X,Y)$ lies below this line.
The Optimal (nonNaive or Sophisticated?) Bayes classifier looks at the likelihood ratio
\begin{align}\Lambda(x,y) = \frac{f_2}{f_1}
&= \frac{\mathcal N((4,4), \Sigma)}{\mathcal N((0,0), \Sigma)}\\
&= \frac{\exp\left[-\frac 23\left(\frac{(x-4)^2}{2}+ \frac{(y-4)^2}{2}+\frac{(x-4)(y-4)}{2}\right)\right]}{\exp\left[-\frac 23\left(\frac{x^2}{2}+ \frac{y^2}{2}+\frac{xy}{2}\right)\right]}\\
&= \exp\left[-\frac 13\left(-8x+16-8y + 16 -4y-4x+16\right)\right]\\
&= \exp[4x+4y-16]
\end{align}
to determine for which values of $(x,y)$ does $\Lambda(x,y)$ exceed $1$ and arrives at the same conclusion as the Naive Bayes classifier and the maximum likelihood classifier:

If $(X,Y)$ lies above the line $x+y=4$, then announce that the observation $(X,Y)$ belongs to Class II; else announce that $(X,Y)$ belongs to Class I.

Finally, turning to the calculation of the error probability, note that  when $(X,Y)$ is actually in Class I, an error occurs whenever $(X,Y)$ lies above the line $x+y = 4$.  Now, when the observation actually belongs to Class I, $X+Y$ is a $\mathcal N(0,2+2-2) = \mathcal N(0,2)$ random variable and so $$P(X+Y>4\mid \text{I}) = 1 - P(X+Y \leq 4 \mid \text{I}) = 1 - \Phi\left(\frac{4}{\sqrt{2}}\right).$$
Similarly, $(X,Y)$ is actually in Class II, an error occurs whenever $(X,Y)$ lies below the line $x+y = 4$.  Now, when the observation actually belongs to Class II, $X+Y$ is a $\mathcal N(8,2+2-2) = \mathcal N(8,2)$ random variable and so $$P(X+Y\leq 4 \mid \text{II}) =  \Phi\left(\frac{4-8}{\sqrt{2}}\right) = \Phi\left(\frac{-4}{\sqrt{2}}\right).$$
While the two calculations seem to give different results, both these error probabilities are in fact the same (proof of this is left as an exercise for the bemused reader) and the unconditional or average error probability is also equal to $\Phi\left(\frac{-4}{\sqrt{2}}\right).$
Note that if your naïveté extends to computing the error probability of the Naive Bayes classifier while continuing to use the assumption that $X$ and $Y$ are independent normal random variables, then $X+Y$ would be a normal random variable of variance $4$ instead of variance $2$ and the error probability would work out to be $\Phi\left(\frac{-4}{2}\right) = \Phi(-2) > \Phi\left(\frac{-4}{\sqrt{2}}\right) = \Phi(-2.828\ldots).$


SetState in ternary operator

Question: I want to change the color of the text displaying the scheduled time, if the scheduled time is past the current time then it should change to red and if its in the future then it wont change. This works properly but it only changes state when I click on another button. I am using a ternary operator like this:
color: (run(todoController.todos[index].date,
            todoController.todos[index].time)
            .compareTo(tz.TZDateTime.now(tz.local))>0)
            ? Theme.of(context).hintColor
            : Colors.redAccent,

How do you add setState in a ternary operator? Thanks
Answer: I think the neater solution would be moving the logic of the comparison of time in a separate function which will be called each 2/5 second depending on your app. In that function, you can change the state and make sure to use color depending on the state.
The code for checking the future time each minute
var cron = new Cron();
cron.schedule(new Schedule.parse('*/3 * * * *'), () async {
  if(run(todoController.todos[index].date,
        todoController.todos[index].time)
        .compareTo(tz.TZDateTime.now(tz.local))>0){
    setState(() {
      isFutureTime = true;
    });
  }
});

I have used corn. CORN documentation
Your Widget color code would look like this.
isFutureTime == false? Theme.of(context).hintColor : Colors.redAccent,

isFutureTime is the state boolean variable. You can follow this StackOverflow answer on changing the state periodically.
Comment: Can you also add the isFutureTime function?
Comment: @RohithNambiar I have added the function code using CORN. Let me know if it works.
Comment: I tried it, but it didn't work and also there were no errors shown in the debug console, I am using Getx, so any way to set state in getx?

SetState in ternary operator


How can I print the list of directory and sub-directory along with files inside sub-directory

Question: Please see the following code which I have tried.
echo scanDirectoryImages("Images");

function scanDirectoryImages($directory, array $exts = array('jpeg', 'jpg',
'gif', 'png'))
{

$html = '';
if (
    is_readable($directory)
    && (file_exists($directory) || is_dir($directory))
) {
    $directoryList = opendir($directory);
    while($file = readdir($directoryList)) {
        if ($file != '.' && $file != '..') {
            $path = $directory . '/' . $file;
            if (is_readable($path)) {
                if (is_dir($path)) {
                    return scanDirectoryImages($path, $exts);
                }
                if (
                    is_file($path)
                    && in_array(end(explode('.', end(explode('/', $path)))),
$exts)
                ) {
                    $html .= '<img src="' . $path
                        . '" style="max-height:200px;max-width:200px"
value="<?php echo basename($path)"/>  ';
                }
            }
        }
    }
    closedir($directoryList);
}
return $html;
}

It is returning only the images from my sub directories but not the path of sub-directories what i actually want.
Also,I'am working on a server and not localhost which is creating a problem to set $path.
please help!!!
Comment: This is a recursive function. And sure it only lists the images if you call the function with the parameter ('jpeg','jpg','png','gif').
What you need to do is not just copy pasting code but instead understand it and modify it so that it fits your needs.
`if (is_dir($path)) {
                    return scanDirectoryImages($path, $exts);
                }` is a point of interest for you. Just to point you in the right direction
Answer: I'd like to show you a really easy way to get all of the files with a particular extension from a directory.
This makes use of various Iterators and filters
the FilterIterator::accept() is the rule to which files are included in the iteration.
class ImagesOnlyFilterIterator extends FilterIterator
{
  function accept()
  {
    return in_array( strtolower( $this->current()->getExtension() ), array( 'jpeg', 'jpg', 'gif', 'png', 'bmp', 'tif', 'tiff' ), true );
  }
}

$path = '/foo/bar/whatever';

foreach( new ImagesOnlyFilterIterator( new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path ) ) ) as $image )
{
  echo $image . PHP_EOL;
}

$image will actually be a SplFileInfo object, and will contain other various properties for you to use.
Comment: use strict mode for in_array.  https://eval.in/89008  / https://www.reddit.com/r/lolphp/comments/1v7ek6/in_which_in_array_does_crazy_stuff/
Comment: @hanshenrik May not be an issue here as getExtension wrapped in strtolower can only return strings. But happy to add it.


What is my nginx + php server bottleneck?

Question: I am running some siege tests on my nginx server. The bottleneck doesn't seem to be cpu or memory so what is it?
I try to do this on my macbook:
sudo siege -t 10s -c 500 server_ip/test.php

The response time goes to 10 seconds, I get errors and siege aborts before completing.
But I if run the above on my server
siege -t 10s -c 500 localhost/test.php

I get:
Transactions:               6555 hits
Availability:              95.14 %
Elapsed time:               9.51 secs
Data transferred:         117.30 MB
Response time:              0.18 secs
Transaction rate:         689.27 trans/sec
Throughput:            12.33 MB/sec
Concurrency:              127.11
Successful transactions:        6555
Failed transactions:             335
Longest transaction:            1.31
Shortest transaction:           0.00

I also noticed for lower concurrent figures, I get vastly improved transaction rate on localhost compared to externally.
But when the above is running on localhost the CPU usage is low, memory usage is low on HTOP. So I'm confused how I can boost performance because I can't see a bottleneck.
ulimit returns 50000 because I've increased it. There are 4 nginx worker processes which is 2 times my cpu cores. Here are my other settings
worker_rlimit_nofile 40000;

events {
        worker_connections 20000;
        # multi_accept on;
}

  tcp_nopush on;
  tcp_nodelay on;
  keepalive_timeout 65;
  types_hash_max_size 2048;

The test.php is just a echo phpinfo() script, nothing else. No database connections.
The machine is an AWS m3 large, 2 cpu cores and about 7gb of ram I believe.
Here is the contents of my server block:
      listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;

        root /var/www/sitename;
        index index.php index.html index.htm;

        # Make site accessible from http://localhost/
        server_name localhost;

        location / {
                try_files $uri $uri.html $uri/ @extensionless-php;
        }

location @extensionless-php {
    rewrite ^(.*)$ $1.php last;
}

        error_page 404 /404.html;

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
                root /usr/share/nginx/html;
        }

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
        }

My php-fpm settings:
 pm = dynamic

; The number of child processes to be created when pm is set to 'static' and the
; maximum number of child processes when pm is set to 'dynamic' or 'ondemand'.
; This value sets the limit on the number of simultaneous requests that will be
; served. Equivalent to the ApacheMaxClients directive with mpm_prefork.
; Equivalent to the PHP_FCGI_CHILDREN environment variable in the original PHP
; CGI. The below defaults are based on a server without much resources. Don't
; forget to tweak pm.* to fit your needs.
; Note: Used when pm is set to 'static', 'dynamic' or 'ondemand'
; Note: This value is mandatory.
pm.max_children = 40

; The number of child processes created on startup.
; Note: Used only when pm is set to 'dynamic'
; Default Value: min_spare_servers + (max_spare_servers - min_spare_servers) / 2
pm.start_servers = 30

; The desired minimum number of idle server processes.
; Note: Used only when pm is set to 'dynamic'
; Note: Mandatory when pm is set to 'dynamic'
pm.min_spare_servers = 20

; The desired maximum number of idle server processes.
; Note: Used only when pm is set to 'dynamic'
; Note: Mandatory when pm is set to 'dynamic'
pm.max_spare_servers = 35

; The number of seconds after which an idle process will be killed.
; Note: Used only when pm is set to 'ondemand'
; Default Value: 10s
;pm.process_idle_timeout = 10s;

; The number of requests each child process should execute before respawning.
; This can be useful to work around memory leaks in 3rd party libraries. For
; endless request processing specify '0'. Equivalent to PHP_FCGI_MAX_REQUESTS.
; Default Value: 0
;pm.max_requests = 500

Comment: What are the exact error messages that you get from the mac ?
Comment: Could you post your PHP-FPM settings? Sounds like your php process pool is starving due to high connection concurrency.
Comment: What is "server_ip"?  On a private network?

Is there any reverse DNS lookup being done?
Comment: @ma.tome I have posted them. Interested in your input
Comment: @Kkinsey That's something I put in in the answer in place of the actual server ip.
Comment: I know it's a placeholder ... the question, what network is it on?  Latency, loopbacks, firewalls, nginx configured to look at rdns ... trying to rule out network issues as part of your problem....
Answer: 500 concurrent requests are way too much for such a little PHP process pool. Try raising your min and max php processes and test again until you reach the maximum CPU usage.
Most surely, if you perform your tests with lower client concurrency (maybe 100 due to your low CPU usage per request) you will get a better global performance and no request errors. The same way, if you perform your test for longer periods of time you should observe worse and worse statistics and higher error ratios.
Anyway, once you reach your 100% CPU usage test scenario, keep in mind thatwhen you deploy your production code these pool values won't be of any use. A typical PHP e-commerce application is CPU intensive enough to starve your 2 vCPUs with barely 4-5 concurrent checkouts.
Typically, CPU or memory intensive applications will better work with small PHP process pools, while fast low CPU applications will make better use of large pools.
Comment: Thanks. Can you be more specific when you say raise my min and max processes? Which of these should I increase: max_children, start_servers, min_spare_servers, min_spare_servers, max_requests?


How to connect database in UnitTestCase subclass?

Question: I know there are mockups, data providers, bla bla bla.
I don't care now, I just want to connect to my dev site db and use nodes, terms for unit tests.
How can I do it? In D7 it was very simple in plain PHPUnit, what about D8?
I've tried bootstrap D8, but failed.
Comment: Have you reviewed https://api.drupal.org/api/drupal/core!core.api.php/group/testing/8.2.x ?
Comment: @Kevin so I should use WebTestBase to access/create nodes in tests?
Comment: anyone? So I MUST use this slow like lava hell simpletest again?
Comment: This totally defeats the purpose of a unit tests. You should be creating an integration test or higher level test. Drupal 8 supports thats.
Answer: See https://www.drupal.org/phpunit for better documentation.
There are 4 test base classes:

UnitTestBase, pure unit tests where everything but your code has to be mocked and only supports classes
KernelTestBase, which provide a basic in-memory drupal environment. Much faster than browser tests but more tedious to set up, you have to explicitly install tables you need and depend on all modules you need explicitly
BrowserTestBase, the replacement for WebTestBase, better apis (uses mink and so on) but just as slow.
JavaScriptTestBase, phantomjs based JS tests, even slower but can actually execute JS.
Comment: Yes, you can implement external testing with Behat. Using it will not create an isolated install of Drupal, which means tests will execute faster. Be sure to grab the Drupal Behat Extension. Here is a small writeup demonstrating it. https://www.velir.com/blog/2016/08/25/behavior-driven-testing-drupal-8
Comment: Just as extra note... I have been able to setup Behat/Drupal Behat/DrupalVM and the SeleniumHQ Docker stack. It is worth it.
Comment: Thank you, I suppose that I can replace BrowserTestBase & JavaScriptTestBase with Behat testing, right?
Comment: @Kevin thanks, could you point me to more details about Behat + SelecniumHQ Docker integration?
Answer: What you are probably looking for is Kernel Test base. You can already create nodes and terms there if you want to, and it still can be fast (3-6 seconds).
In Unit test you only test your class and mock the rest, you can't really make real entity instances.
Comment: I agree on this. You will need to make a decision, if you would like to use the faster kernel tests, with much more setup at the beginning, or using the much slower webcase test, where you already got almost everything you need! In most cases I still go for Kernel tests, but this is my taste.
Comment: yea, but If I need to test something related to custom fields I need to create them also in code and if there is a lot of dependencies it becomes tedious task. I mean perspective from working with a lot of legacy code.


C# How to calculate time until someone is 18 based on their DOB

Question: Let's say I need to have a license suspended until the driver is 18 years old.  All I have is their DOB.  I cannot add the time to their specific DOB because this will go for many drivers with different DOB.  Here is the line of code that is already created but this is adding 18 years to their DOB which is not what I want.
        data.EndDate = data.Driver.DateOfBirth.GetValueOrDefault().AddYears(18);

Comment: `this is adding 18 years to their DOB which is not what I want` - why not? To me that sounds exactly like what you're looking for.
Comment: @MirekE: No, that would be "what was the date 18 years before they were born" which isn't terribly useful.
Comment: @MirekE You turn 18 years old 18 years before you are born?
Comment: I believe you want to subtract, not add 18 years. Just replace the 18 with -18.
Comment: No. I would calculate a limiting date (DateTime.Now().AddYears(-18)) and then compare with actual birth date. Please note that the OP is saying he can't add the dates to specific DOB...
Comment: @MirekE That tells you when they would need to be born in order to be 18, not when they turn 18 or how long it will be until they turn 18.
Comment: @AdamV I think I was assuming this was adding 18 years to the current DateTime but it's not.  It is in fact adding 18 years to the DOB which is exactly what I want.  Sorry for the confusion.
Comment: @Servy Looks like we have different understanding of the original question. Mine was that he needs to determine eligibility at the current time. Perhaps I was wrong. Got misguided by the statement that the data.EndDate = data.Driver.DateOfBirth.GetValueOrDefault().AddYears(18); is not what he wants...
Answer: If you want to get the amount of time remaining in a TimeSpan, you can just subtract two DateTimes.
TimeSpan timeLeft = data.Driver.DateOfBirth.Value.AddYears(18)
    - DateTime.Now;

Also, I am using Value instead of GetValueOrDefault(), since you probably never want to use a default value for date of birth.


jade cli environment variable in --obj

Question: I want to be able to use an environment variable in the --obj of the jade cli so I can do this:
$ jade some.jade -O '{"version": "${VERSION}"}'

Where VERSION is an environment variable. But right now "${VERSION}" is what I see in the output. Is there a way to accomplish this? I've tried all kinds of variations on escaping.
Comment: Did you try `$ VERSION=text jade some.jade`  and then read with `process.env.VERSION`?
Comment: Boom! That totally worked! Thanks!
Comment: Any way I can include that environment variable in my `--out` option? Something like: `jade other/index.jade --out dist/$VERSION/`
Comment: If you mean `$ VERSION=v1 jade some.jade --out dist/$VERSION/` yep, you can use it with your command.
Answer: The shell does not expand variables inside single quotes ('). You need to be inside double quotes ("). However, then the double quotes inside would need to be escaped. It looks messy but works:
jade some.jade -O "{\"version\": \"${VERSION}\"}"

Alternatively, you can juxtapose strings like this which also works:
jade some.jade -O '{"version": "'"${VERSION}"'"}'

Here there are 3 strings '...', "${VERSION}" and '"}'. Because there is no space between them, they count as one.

jade cli environment variable in --obj


Why do i keep forgeting the sections while improvising?

Question: I can do variations of my first section but when i go about developing: or i play the new section, but then i don't remember most of the first one; or keep repeting mentaling the first one while trying to make the new section, but my rhythm goes very slow and choppy.
I play the hand whistle, know how to play the diatonic scale but most of the time i go atonalic.
Answer: One common problem
The most common reason I've encountered for this kind of problem is that the music being created is too complex to remember.
When improvising, there are so many details to keep track of that our memory easily gets overwhelmed when we want to return to an earlier part of the music or create a new one.
A good exercise
The remedy is to practice very simple phrases that are remembered with little to no effort. This might mean only one or two notes, if that's what it takes. And the simplicity applies both to the notes and the rhythms. But by using these easily remembered musical materials, one can practice the act of memory while improvising.

Improvise an easily remembered musical gesture.
Improvise a second easily remembered musical gesture.
Replay the first gesture.
Add a third.
Replay the first and second.
Etc.

Another good exercise
Another improvisation/memory exercise I like is to:

Create a brief melody.
Replay the melody, then extend it with something new.
Replay only the new part, then extend that with something new.
Replay only the most recent new part, then extend it with something new.
Etc.


C# method give me an extra Console.WriteLine

Question: I have a little problem, in my source code I don't see why is my ToUpload method give me an extra console.writeLine in the Console window. (write out the beer object)
When I call the ToUpload method, and the beer is in the beers dictionary, it give me an extra Console.WriteLine, where write out the beer object at the Console. And I don't know why.
This is my output:

Borsodi sör 160 4.6 1000
Pilsner Urquell 250 4.4 800
Soproni Ászok 150, 4.5 900
Dreher Classic 200, 5.2 600
125
Borsodi sör 160 4.6 475
Pilsner Urquell 250 4.4 800
Soproni Ászok 150, 4.5 1350
Dreher Classic 200, 5.2 600
Bratista sör, 230, 4.5 300
Soproni Ászok 150, 4.5 450 // this is extra
Borsodi sör 160 4.6 100 // and this is

and i want this:

Borsodi sör 160 4.6 1000
Pilsner Urquell 250 4.4 800
Soproni Ászok 150, 4.5 900
Dreher Classic 200, 5.2 600
125
Borsodi sör 160 4.6 475
Pilsner Urquell 250 4.4 800
Soproni Ászok 150, 4.5 1350
Dreher Classic 200, 5.2 600
Bratista sör, 230, 4.5 300
public void ToUpload(Beer beer, int dl)
{
    int d = 0;
    Beer s = null;
    // search for beer in beers dictionary
    foreach (var item in beers)
    {
        if (item.Key.Equals(beer))
        {
            d = item.Value;
            s = item.Key;
        }
    }
    // if this beer in the beers, update the value
    if (s != null)
    {
        beers[s] = d + dl;
    }
    // if a new beer, just add to beers
    beers.Add(beer, dl); // IDictionary beers = new Dictionary
}

public Pub()
{
    ToUpload(new Beer("Borsodi beer", 160, 4.6), 1000);
    ToUpload(new Beer("Pilsner Urquell", 250, 4.4), 800);
    ToUpload(new Beer("Soproni Ászok", 150, 4.5), 900);
    ToUpload(new Beer("Dreher Classic", 200, 5.2), 600);
}

static void Main(String[] args)
{
    Beer b = new Beer("Borsodi beer", 160, 4.6);
    Beer c = new Beer("Bratista beer", 230, 4.5);
    Beer d = new Beer("Soproni Ászok", 150, 4.5);
    Pub pub = new Pub();
    foreach (var item in pub.beers)
    {
        Console.WriteLine("{0} {1}", item.Key, item.Value);

    }

    Console.WriteLine(pub.Elad("Borsodi beer", 125));

    //pub.ToUpload(b, 2000);
    pub.ToUpload(c, 300); // Don't Write out this beer object
    pub.ToUpload(d, 450); // Write out this beer object the console
    pub.ToUpload(b, 100); // Write out this beer object the console

    foreach (var item in pub.beers)
    {
        Console.WriteLine("{0} {1}", item.Key, item.Value);

    }

    Console.ReadLine();

Here is the Beer class:
public class Beer
{
    string name;
    int price;
double alcohol;

public string Name { get { return name; } }

public int Price{ get; set; }

public double AlkoholTartalom { get { return alcohol; } }

public Beer(string name, int price, double alcohol)
{
    // ide írja a kódot
    this.name = name;
    this.price = price;
    this.alcohol = alcohol;
}

public override bool Equals(object obj)
{
    if (obj is Beer)
    {
        Beer other = (Beer)obj;
        return this.name == other.name;
    }
    return false;
}

public override string ToString()
{
    return this.Name + " " + this.Price+ " " + this.AlkoholTartalom;
}
}

Answer: You are missing "Else" at the ToUpload method.
// if this beer in the beers, update the value
if (s != null)
{
    beers[s] = d + dl;
}
else  // Add this
    beers.Add(beer, dl); // IDictionary beers = new Dictionary

From what i see, this should fix it.
You are adding the beer to dictionary, even thou you should just update it.
Answer: Depending on what type beers is you can just do this:
public void ToUpload(Beer beer, int dl)
{
    int d = 0;
    if(beers[beer] != null)
        d = beers[beer];

    beers[beer] = d + dl;
}

I know that HashTables will automatically either update or add to the dictionary based on whether or not the key was found when they are accessed this way.


Multiple treatment nonparametric testing

Question: I am a SAS programmer and am trying to help out a mate doing a project for work.
He has tested 7 different treatments (growth cultures) across 31 days, I have a value from each treatment for each of the 31 days. The days go from Day 0 to Day 31, and the nature of the testing is that the values at day one are 0 and increase at day 31 to +1000.
I have tried fitting distributions to the data but none are statistcally fitting (Minitab p values all <0.05). So we can't assume normality and use a simple ANOVA with Tukey's Studentized Range (HSD) Test.
I am going to test these using non-parametric testing, using the Wilcoxon rank test on the differences between each treatment, so using day as variable to pair the data, use the differences and then test for a difference in median. The outcome of these tests is that all treatment medians are significantly different but also most of the distributions are significantly different using Kolmogorov-Smirnov Two-Sample Test (Asymptotic) testing.
Does this mean that we can only use the significant values for median differences when the distributions are equal or does it impact the analysis at all?
Can anyone suggest any other testing methods I could use here?
Answer: First, ANOVA does not require normally distributed variables, it assumes normally distributed residuals from the model. (Technically, normally distributed error, but that is measured by the residuals).
Second, with multiple time points, you ought not do simple ANOVA anyway: You will probably want some form of mixed model. These are pretty complex, statistically. They are one way of accounting for the fact that your data are not independent. Since you mention that you use SAS, the PROCs to look into are MIXED and possibly GLIMMIX.


Converting between spherical coordinate systems

Question: Say I have the spherical coordinates of some locations, specifically their longitude ($0$ to 360) and latitude (latitude = $0$ at equator, $90$ at north pole, $-90$ at south pole) on a sphere with a radius of $1$. If I wanted to convert to a different coordinate system, treating the point on the original equator at the original longitude of $X$ (looking for generalization here) as the north pole of a new longitude/latitude, any idea what formulae I would need to apply to convert the original coordinates?
(If you're interested, this problem arises as I try to graph the output of a statistical model's predictions for a spherical phenomenon. My graphics app  can easily create a top-down 2D projection given latitude/longitude data, but I'd also like to create projections centered on arbitrary longitude points along the equator, so I thought the easiest route would be to treat the side-view as a new latitude/longitude coordinate system.)
Answer: Well, I ended up solving this myself after a little more thought. The solution is to convert from the (r, phi, theta) of spherical coordinates to the (x, y, z) of Cartesian coordinates, then swap the z-axis with one of the others before finally converting back to spherical coordinates again.
Comment: I wish there was a method to directly convert/transform the system without going through Cartesian. Perhaps this related question might have a clue: http://math.stackexchange.com/questions/92301/transforming-from-one-spherical-coordinate-system-to-another