What sort of setup do I need to record reasonable quality singing and guitar playing?

Question: I would like to start recording myself singing on audacity and I know I need a better hardware setup to get reasonable quality recordings, how ever I have no idea where to begin to do this. I am humbly completely aware of my own lack of knowledge on this topic and I would like to get the most basic advice.
I have already tried recording myself singing and playing the guitar with audacity using my computer's (lenovo g500s) built in microphone and both sound really bad. The sound is very tinny, and lacking in body, this is not just down to my level of talent in singing, as I can compare how my guitar sounds to my ear to how it sounds on the recording and there is a world of difference there.
I'm sure that one of the things I need is an external microphone, but is that all that I need? Is there some other hardware interface that I need to connect my mic to audacity, or can I just plug a mic in and it will immediately sound good?
Concretely, my question has three parts:
1) Will a better setup produce better quality recordings?
2) as stated above, what is the setup that I need to make reasonably decent recordings? E.g. a mic plus something else? I would like to continue using Audacity as I am a little accustomed to it, and it seems relatively easy to use. Plus I run Ubuntu on my laptop so Audacity is nice and compatible.
Thank you in advance for answering my very basic question!
Comment: Would it be OK to edit or some things from the second last paragraph? The part about "recommend[ing] **specific** mics to purchase" is clearly of topic.
Comment: Did you mean that you want me to change it?
Comment: If you like any or all of the answers, you can indicate that by clicking on the little up arrow in the upper left corner of the answer. If one answer is the best answer that has helped you solve your problem, you can mark it as the best answer by clicking on the check mark under the up and down arrows.
Answer:
1) Will a better setup produce better quality recordings?

A better setup will make it possible to produce better quality recordings, just like a better guitar helps a good guitarist sound better, but doesn't do as much for someone who has no idea how to play. Learning to record is like learning an instrument. It requires years of study of theory and technique, and years of practice.

2) as stated above, what is the setup that I need to make reasonably
  decent recordings? E.g. a mic plus something else?

You do need a mic. I suggest getting a mic that has an XLR interface, not USB or 1/4" or anything else. Along with the mic, you will want an audio interface to connect the mic to the computer. The interface should have a built-in mic preamp that has an XLR input. Then you'll want an XLR cable to connect the mic to the interface and a mic stand to put the mic on. At that point it should be possible to set up the mic and the interface to record audio into Audacity.
You will probably find that you have many little troubles along the way. I suggest reading instructions, doing web searches, and asking questions here. Don't expect to get your new toys and have a professional sounding recording that afternoon.
One more note on microphones: they are like the musical instruments of recordists. You can start small but with a quality mic that will last you for decades. I suggest looking at dynamic microphones in the range of prices around $100/€100. A good starting interface will run about the same, but you might consider saving for something that has at least two mic preamps for when you get your second microphone.
I strongly suggest not compromising on budget, and instead saving every penny and prioritizing your spending on what you care about most. If that's music, you will quickly find that cutting back on everything else makes it possible to afford great gear that will last a lifetime.

3) Can anyone recommend specific mics to purchase?

We don't do specific recommendations here. I suggest finding a store or an online retailer where you can go in or call and ask questions.
Comment: Great thanks for the answer! But regarding question 1. Assuming the person has years of experience in singing and thus is pretty good at it, wouldn't there be an immediate improvement to be heard in the recording quality if the person was to switch from the computer's buit-in mic, to a dynamic mic as you suggest?
Comment: On what basis do you suggest a dynamic mic for vocals instead of a condenser mic? Google seems to suggest the opposite is better...
Comment: @stevezissou Remember how we don't do recommendations here? Well I was kinda trying to steer you in a certain direction without actually recommending something. Regarding what is "better": *Thriller* by Michael Jackson is by far the best selling album of all time. All of MJ's vocals on *Thriller* were recorded using the Shure SM7 **dynamic** microphone. It just worked for his voice. So there is no "better". The SM7 is a great mic and there is a more affordable mic that uses the same capsule called the SM-57, which is a very popular and useful microphone. So... just throwing that out there.
Answer: As usual, there are many useful resources and tutorials on the internet. Feel free to research the topics i mention, but beware of taking advice from HiFi cultists, y'know, those "700 buck solid gold cable" people.
Here are the basic components of a digital recording rig:

Sound source (in this case your voice and guitar)
Microphone(s)
Sound card (your laptop mic jack will often not do)
Computer/ digital recorder

So let's quickly go through them one by one in your case, with a professional result in mind.

A reasonable acoustic guitar that is intonated and doesn't have ancient strings. A vocalist who knows basic mic technique.
One or more microphones. If you are going to record guitar and vocals at the same time, get at least two, since they are usually directional. You will likely be looking at dynamic mics for your budget. Look up what the intended use for the mic is, they do have different sounds. Condenser mics are nice for guitar and some vocals, but no must.
A sound card (interface) that has at least one mic input for every microphone you intend to record. 44kHz 16bit is the minimum definition you want to use, good thing that such definition is abundant in sound cards. Focus more on getting good mic preamps and more inputs. Anything above 16 bit is also only necessary if you are only able to get whisper-level signals into the card and somehow manage to avoid all the other noise. Any samplerate above 48 kHz is only good if you need to capture ultrasonics.

For your particular use (Ubuntu), some cards are not compatible, but most manufacturers simply don't tell you whether a card is compatible. I recommend buying from a local store, and to make sure you can return it for a refund if it turns out to require any source building or reverse engineering (because those will fail if you don't know what you're doing). The ALSA project also has a list of some cards which are supported.

A computer. It needs to be powerful enough to run recording software. A faster computer will manage a lower buffer size, and minimize latency (that delay between the signal that comes in and the one that gets recorded, that makes playing in time to already recorded material a pain). If you plan to record many tracks, go for much RAM and a fast hard drive.
Some good "reference" or "flat response" monitors are also good if you plan to do any mixing beyond the simplest two-track deal.
etc. etc. (There is lots more gear you can buy that's not really necessary for your current ambitions)

That's pretty much it. Let me also clarify:
<code>1) Will a better setup produce better quality recordings?
</code>
Yes, but recording is a skill, an expensive rig doesn't guarantee anything. Get the best you can comfortably afford and start practicing. As i said, lots of helpful resources elsewhere on the net to get you started.
Comment: @stevezissou "Sound card" and "audio interface" are two different terms for the same thing. A USB mic will be less flexible in the future and only handles the input to the computer for that one mic. A sound card/interface gives you more flexible input options, more room to grow, and it also gives you better quality output options than the built in output of your computer.
Comment: Thank you for your response! I now have two answers which make sense, however they make different recommendations, so i don't know which direction to take. You have recommended investing in a new sound card, whilst @ToddWilcox has recommended getting an audio interface along with the mic. Do I need both of these, or will one substitute for the other, for example, a good sound card means i won't need an audio interface and vice versa? Furthermore, LaurencePayne recommends just starting with a simple USB mic...
Answer: For a one-microphone solution, get a USB microphone like the Samson CO1U.   Link
Caveat:  Check the compatibility with Audacity and Ubuntu.  Some reports say it works, some say it doesn't.  But as a Linuz user, you're used to sorting this sort of thing out I expect!   (Is there ONLY Linux available on your laptop?)
Comment: Regarding the last sentence, I bet Linux is the only thing OP is **comfortable** with using on their personal computer.
Comment: Yeah, whatever.  It's sensible to be 'comfortable' with the software that does the job you need.
Comment: thanks for the quick solution, Linux is the only thing available for now as a matter of principle ;)
Answer: I would recommend buying a Zoom H2n Handy Recorder, with the optional accessory kit, and a upright (telescoping) microphone stand.
For little over two hundred dollars you will end up with a recording capability that is unbelievably versatile and high-quality, and for a fraction of the investment you might have expected to make.
The Zoom records to SD card, so you can export your songs to your computer (and therefore the internet) in a matter of minutes.
Answer: Adding something which has not been addressed in previous answers: try multi-tracking software (Audacity is capable of this). First you record the guitar via an interface or via microphone, as many times as necessary until you are satisfied. Then record the vocals via microphone, again as many times as possible.
The reason for separating the recordings is that one can apply different effects to different tracks. The guitar may be ok on its own, but it probably wouldn't hurt to add a little chorus in order to thicken the sound. Similarly, the vocal will probably need to be compressed then adjusted with eq as well as adding other effects such as chorus and/or reverb.
My favourite vocal recording technique is to record in stereo, then add about 5-6 microseconds of silence in front of one track only. This creates an effect similar to 'automatic double tracking', which thickens the vocal in a pleasing way.
I've also been playing with autotune programs - not so much as to tune my vocals, but rather to create harmony parts without having to sing them myself.


Select from table A which does not exist in table B

Question: I am trying to compose a SELECT statement for MySQL which select from table A what does not exist in table B.  For example:
Table A:
+------+
| BAND |
+------+
| 1    |
| 2    |
| 3    |
| 4    |
| 5    |
+------+

Table B:
+------+
| HATE |
+------+
| 1    |
| 5    |
+------+

So if table A is all bands, and table B is the bands I hate, then I only want bands I do NOT hate.  So the result of a select should be:
+------+
| BAND |
+------+
| 2    |
| 3    |
| 4    |
+------+

How would I write a single select for this? Here was my last attempt:
SELECT * FROM A LEFT JOIN B ON A.BAND = B.HATE WHERE B.HATE IS NULL;

EDIT: The line above has been fixed!  See comments below..."= NULL" versus "IS NULL".
Comment: @Michelle your query seems to be ok. why do you say it doesn't work?
Comment: See my comment below.  For anyone else with the same problem "IS NULL" is not the same as "= NULL" in MySQL.  I tried one way and the query works, the other way it returns an empty set.  Strange!!!
Comment: Not only in MySQL, but on any SQL dialect. The `NULL` value in SQL has the property of being different to any other value, including another `NULL`. Because of that, you can't expect `= NULL` to work on a SQL query... you need to use `IS NULL`.
Answer: I would use a join
select A.*
from A left join B on A.BAND = B.HATE
where B.HATE IS NULL;

Remember: Create the appropriate indexes for your table
Comment: That's almost identical to what I tried (see response above).  You ask for only A.* in return from select statement...perhaps that's the issue.
Comment: and it should give you the right answer! (by the way, I posted this before your edit). This should return what you need. Or why do you say it is not returning what you need?
Comment: OK - I found the problem!  I was testing for "B.HATE = NULL", not "B.HATE IS NULL".  My text above was what I used to create my SQL command, but when I actually typed the code (into a PHP string) I changed it to = NULL.  Strange that they are different!?
Comment: @Michelle As far as I know, in SQL `NULL` is different to any other value, including other `NULL`. It is usual to find things like `a == Null` in programming languages, but (at least) in MySQL, if you want to filter null values, you need to use `IS NULL` to test a null value, or the `ISNULL()` function, which returns `TRUE` if the argument is null
Answer: You can use IN, but it's super inefficient:
SELECT * FROM tableA WHERE id NOT IN (SELECT id FROM tableB)

Comment: I never said it was better, I actually say the opposite. `IN` sucks, because it runs the inner query for every row checked (so, for each row in `tableA`).
Comment: Why is this better than using a join?
Comment: I would think this is slow if tables A or B are big (for small tables, the performance difference is practically nothing)
Answer: SELECT * FROM tableA WHERE id NOT EXISTS (SELECT DISTINCT id FROM tableB)

or
SELECT * FROM tableA WHERE id NOT EXISTS (SELECT id FROM tableB GROUP BY id)

Answer: SELECT BAND FROM A WHERE BAND NOT EXISTS(SELECT DISTINCT HATE FROM B)

OR
SELECT BAND FROM A WHERE NOT EXISTS ( SELECT HATE FROM B WHERE A.BAND = B.HATE);


Organic Groups strict membership access

Question: I have set up multiple organic groups on my site that can only be joined with admin approval.
My issue now is that members can post content in groups of which they are not members. I really don't want this.
Does anyone know of a module or technique to stop unauthorized members from posting content in a group but only in groups they are members of and hence authorized to do so?
Answer: You need to enable Organic groups access control module. This will let you set your groups to public/private.
There is a tutorial series on Organic Groups which explains everything you need to know about the configuration at http://modulesunraveled.com/organic-groups

Organic Groups strict membership access


Remove redundant timestamps from csv

Question: I have created a CSV file from the recording of different sensors using pandas DataFrame. The CSV file basically looks like this:

I would like to get rid of the redundant timestamps and instead have all sensor entries that share a timestamp appear in the same row (for example x2 and x3 in the image).
Also, the labels that share a timestamp are always identical, but would need to be reduced as well.
So far, I've come across the drop_duplicate() function which only drops entire rows.
Edit: here's a text version of the example above:
timestamp,sensor_a,sensor_b,sensor_c,label
1,x1,,,0
2,,x2,,0
2,,,x3,0
3,x4,,,1
4,,,,1
5,,x6,,1
5,,,x7,1

Comment: what is the content of the empty spaces is it `` or None or what else? I think its better to give the dataframe in text as you have.
Comment: I added the example as a text. I double checked with the real dataframe I am working on - the empty spaces are just empty as in the text example.
Answer: I will assume that you store the data in a text file sensors.txt, so we con consolidate the data based on timestamp according to the following code
import pandas as pd

df = pd.read_csv('sensors.txt', delimiter=',', header=0)

df2 = df.groupby('timestamp').ffill()
df2['timestamp'] = df['timestamp']
df2 = df2.groupby('timestamp').bfill()
df2['timestamp'] = df['timestamp']
df2 = df2.drop_duplicates()

df = df2[['timestamp', 'sensor_a', 'sensor_b', 'sensor_c', 'label']]
print(df)

output
   timestamp sensor_a sensor_b sensor_c  label
0          1       x1      NaN      NaN      0
1          2      NaN       x2       x3      0
3          3       x4      NaN      NaN      1
4          4      NaN      NaN      NaN      1
5          5      NaN       x6       x7      1

further editing will be based on your questions in the comments below
Good Luck

Remove redundant timestamps from csv


Simulated DHARMa residuals, how are they created?

Question: I am currently working with the DHARMa package and I was looking at the explanations of how the residuals are simulated (https://cran.r-project.org/web/packages/DHARMa/vignettes/DHARMa.html):

Simulate new response data from the fitted model for each observation.

For each observation, calculate the empirical cumulative density function for the simulated observations, which describes the possible values (and their probability) at the predictor combination of the observed value, assuming the fitted model is correct.

The residual is then defined as the value of the empirical density function at the value of the observed data, so a residual of 0 means that all simulated values are larger than the observed value, and a residual of 0.5 means half of the simulated values are larger than the observed value.

However, I do not fully understand this. For example, how can one simulate new response data from a fitted model? Does it assume the errors are distributed according to the family specified in the glm and create new response data from this? Does it also use the data the model was fitted on? Then in point 2, what do they mean with each observation? Do they mean for each observation in the dataset each new response variable and their explanatory variables? Is the cdf created using the error distribution?
Hopefully someone can explain a bit more elaborately to me how these residuals are created!
Answer: One way to try to understand this is to try to make a simple example. But first, let us clear up your doubt in

For example, how can one simulate new response data from a fitted model? Does it assume the errors are distributed according to the family specified in the glm and create new response data from this?

One does exactly as is done in parametric bootstrapping, assuming that the fitted model is the true one, replacing the unknown parameters with the fitted values. So, with a normal (Gaussian) family, we assume normal errors, with a Poisson family we simulate response values from a Poisson distribution, and so on.
A simple example, with code in R. Let us first simulate some data:
set.seed(7*11*13) ### My public seed

x <- rep(1:10, 2)
y <- 1  +  0.5 * x  +  rnorm(x, 0, 2)
mod <- lm(y  ~ x)
intercept <- coef(mod)[1]; slope <- coef(mod)[2]
sigma <- summary(mod)$sigma
### Then we can simulate responses,  as in
#### parametric bootstrapping:
ystar <- intercept  +  slope*x  +  rnorm(x, 0, sigma)
### Then this would have to be repeated many times!

To repeat, this is really parametric bootstrapping!
Then we can program the tree steps of the algorithm you reference as a simple R function, which will work for linear models (lm) and glm (generalized linear models) objects. The DHARMa package must be more complicated, as it works for many other model types. Making a minimal code can be a good way to understand an algorithm, as usual working code as that in the DHARMa package might be difficult to read, as such code is often dominated by error checks, guards and strange border cases. No such distractions below:
sim_res <- function( model,  B, seed) {
    ystars <- simulate(model, nsim=B, seed=seed)
    # step 1
    y <-  model.response(model.frame(model))
    N <- NROW(ystars)
     my_ecdf <- function(data) {
        function(y) sum( data <= y)/length(data)
     } ### using systen ecdf gives error I do not understand
    simres <- rep(as.numeric(NA), N)
    for (i in seq_along(simres)) {
        efun <- my_ecdf( ystars[i, ] ) # step 2
        simres[i] <- efun( y[i] )      # step 3
    }
    return( simres )
}

Hopefully, this code should clarify your doubts:

Then in point 2, what do they mean with each observation?

The loop in the code goes through the dataset, for each observation $y_i, i=1, 2, \dotsc, N$ it takes the $B$ simulated (bootstrapped) responses, stored in row $i$ in object ystars, calculates its ecdf (empirical cumulative distribution function), and then applies this function to the actual observation $y_i$.

Is the cdf created using the error distribution?

The cdf is created using the simulated responses.
Comment: As DHARMa maintainer, I can confirm that this is entirely correct, with two additions: 1) most R regression classes implement already a simulate function. For lm / glm, you can simply type simulate(model, 5), which will simulate from the fitted MLE (as done here in the code). The DHARMa S3 function DHARMa::getSimulations standardizes this functionality for various packages, so you could use it to create simulations from arbitrary models. (1/2)
Comment: About 2): for discrete pdfs, there is the additional problem that the ecdf is not smooth, that's why the need for adding some noise (aka randomized quantile residuals). You can see how this is done in the code of DHARMa::getQuantile. (2/2)
Comment: Hey, absolutely, I didn't mean to say that there's something wrong with your explanation, I think it's answering what the OP wants to know. Just wanted to clarify how it works technically in DHARMa.
Comment: Thank you for this very clear answer!
Comment: @FlorianHartig: Thanks for this, looking into it now, but I think a very simple basic implementation is helpful for understanding the basic logic. I will add some comments on further problems!


Find the sum of $\sum_{k=2}^\infty x^k (1-x)$

Question: I was working on this and thought that it didn't matter what my function was. However I noticed in order to solve it like I usually do. It has to look like
$$\sum a_k x^k$$
However mine does not look like that. It does not have an $x^k$.  $$\sum_{k=2}^\infty x^k (1-x)$$
I am positive the sum exists but don't know how I should find it.
Comment: Try splitting it up into two sums, using $x^k(1-x)=x^k-x^{k+1}$.
Comment: I believe I have to show that they are both convergent in order to do that? So if I show they are both convergent when $|x| < 1$ then is it okay to use it?
Comment: Yes, this is valid if $|x|<1$.
Answer: Note that
$$\sum_{k=2}^{\infty}x^k(1-x)=x^2(1-x)\sum_{i=0}^{\infty}x^i =x^2,$$
if $|x|<1$.

If $|y|<1$ then $$\frac{1}{1-y} = 1+y+y^2+\cdots = \sum_{i=0}^{\infty} y^i.$$
Answer: Suppose $|x|<1$; then
\begin{align*}
\sum_{k=2}^{+\infty}x^k(1-x)
&=(1-x)\sum_{k=2}^{+\infty}x^k\\
&=(1-x)\sum_{k=0}^{+\infty}x^k-(1-x^2)\\
&=\frac{1-x}{1-x}-1+x^2\\
&=x^2
\end{align*}


How to get index value for a cell in order to reference a sheet

Question: I am making a UI to easily access data from other sheets. The sheet names are the years from 2009-2019, and I have a drop down list in one of the cells that I want to use as a reference to the particular sheet I want to use.
I've seen people using the =indirect() function but I was not able to get it to work
What works:
=INDEX('2009'!C1:C100,C26)

What doesn't work:
=INDEX(indirect("C11")!C1:C100,C26)

where C11 is the value of the drop-down menu
Any help would be appreciated as I do not have very much experience with google sheets.

source sheet: here
Answer: it's because indirect("C11")!C1:C100 is not a valid range. try:
=INDEX(INDIRECT(C11&"!C1:C100"), C26)


Can a OCS 2007 R2 mediation server be installed on a front end server?

Question: Is it possible to install the mediation server component of Office Communication Server 2007 R2 on to the same hardware as the front end server component, or do I need additional hardware?
If it is possible, what would be the user limit before the roles needed splitting onto separate hardware? (assume I'm using fairly good hardware, i.e. Fast Xeon CPUs, lots of memory, 64 bit Windows 2008).
Answer: Found the answer after much digging, and the answer is no. The mediation server can not co-exist with other components of OCS.
Reference: http://technet.microsoft.com/en-us/library/dd425201(office.13).aspx


Load content without refreshing page in views

Question: i am trying to create a view with pagination. In this view i have images and fivestar rating for it. When user clicks on next i want next image and fivestar to load with out refreshing page.
Thanks.
Answer: What you need is the views load more module

This module has some very key differences then the other load more
  module.

Provide ajax/no-ajax views load more
Works with views default ajax implementation, no hacks (check/uncheck ajax)
Supports the Waypoints module for loading on various points, Such as when the scroller is visable on the page.
Supports the Fade effect when loading new content


Getting an URL from Chrome using AutomationElement

Question: I have an application that monitors the URL of a browser. Currently I'm using chrome. I followed the solution from this answer:
public static string GetChromeUrl(Process process) {
    if (process == null)
        throw new ArgumentNullException("process");
    if (process.MainWindowHandle == IntPtr.Zero)
        return null;
    AutomationElement element = AutomationElement.FromHandle(process.MainWindowHandle);
    if (element == null)
        return null;
    AutomationElement edit = element.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));
    return ((ValuePattern)edit.GetCurrentPattern(ValuePattern.Pattern)).Current.Value as string;
}

Then I have this method to log the URL in a text file (using log4net):
while (true) {
    foreach (Process process in Process.GetProcessesByName("chrome")) {
        string url = GetChromeUrl(process);
        if (url == null)
            continue;
        Console.WriteLine(url); //for viewing purpose, it actually logs in orig code
    }
    Thread.Sleep(1000);
}

It works pretty well. But somehow there's an inconsistency with the GetChromeUrl method. Sometimes it returns null, and this is my big problem. Does anyone has a better solution?
Comment: What line returns null? the MainWindowHandle check? the FromHandle check, or the Current.Value?
Comment: Hi Simon, This lines Returns the null
AutomationElement edit = element.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));

I also noticed that when you right click on the page in chrome then do nothing, it will also returns a null value.

Thanks
Comment: And i found another way to throw a null.
if you mouseover on a link or tittle bar,
title bar with long text(if it popups the whole text or as tooltip pops) it will throws a null.
looks like this will cause a problem in my work.
Comment: Hmmm.. I don't have a magic bullet here. When you want to "program" a distant application that was not designed for this specifically, you only have building bricks (ui-automation) and you need to managed your way out with with tricks like in Patrick's answer.
Comment: Thanks for the reponse,
i already created a solution, to store the previous link in a variable, and incase the user force it to throw nulls(by way of right clicking on the page, mouse over on a link or title bar and etc) since the code will throw an exception I've just catch it and retrieve the value of the previous link.
Answer: Which bit returns null? Windows will often overlook programs whose ShowInTaskbar property is changed. This could be the reason for a null in the first check (and second). Concerning the second fault I cannot provide any help but I had the same problem a few weeks ago. I decided to use the position element of Chrome's URL bar, change the cursor position to it, and then get the AutomationElement under the cursor:
    Form1_Load()
    {
        Cursor.Position = element's position;
        Timer.Start();
    }

    Timer_Tick()
    {
        AutomationElement element = AutomationElement.FromPoint(new System.Windows.Point(mouse.X, mouse.Y));
            string current = element.Current.Name;
        Console.WriteLine(current); //log in text file...
    }

Does this provide an answer to your query?
Comment: Im trying your code, but i couldn't get the mouse.x and y? is this a value of mouse or the url bar?
Comment: The mouse and the URL bar as we set the cursor to be at its position. Once you have the automationElement you can probably get an id and keep getting its name instead of having to have the mouse hovering there. I'd write it but I'm on my phone. Not worth an upvote at least?
Comment: @Fadz You might be able to do new Point (Cursor.Position) but I'm not sure.
Comment: @Fadz here are some links to getting the id of the URL bar: [AutomationID](http://msdn.microsoft.com/en-us/library/aa349646.aspx) and [MSDN:AutomationID](http://msdn.microsoft.com/en-us/library/system.windows.automation.automationelement.runtimeidproperty.aspx). Have a crack at that method!


For the creation of a prepopulate link, how can i strip out slashes if they occur in the title?

Question: if(isset($node->field_eventform['und'][0]['nid'])) {
          echo '

';
          echo 'field_eventform['und'][0]['nid'].'/'.$node->title.'/'.$node->nid.'">'.$node->field_eventform['und'][0]['node']->title.'';
        echo '

';
   }

?>

With this snippet we prepopulate a webform for events. But when a site editor uses a "/" in the title the link doesn't work anymore. How can I strip out slashes if they occur in the title?
Comment: have you tried pathauto module.
Answer: echo 'field_eventform['und'][0]['nid'].'/'.str_replace('/','',$node->title).'/'.$node->nid.'">'.str_replace('/','',$node->field_eventform['und'][0]['node']->title).'';

You have to check, if the link works, when you strip the '/', if not, replace the '' in str_replace with the correct replacement, that your path alias use.


ReferenceError: documentId is not defined

Question: Olá, estou tentando criar uma Firebase function para meu app em flutter enviar notificação para o token que esta em uma subcoleção sem especificar o document. Em dart eu consigo usar "documentId", porém na função em javascript me retornou "ReferenceError: documentId is not defined". Como faço para acessar essa subcoleção sem especificar o documento? Desde já agradeço.
const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

var msgData;

exports.chatTrigger = functions.firestore.document(
     'chat/{chatId}/users/{usersId}/messages/{messagesId}'
).onCreate((snapshot, context) => {
   msgData = snapshot.data();

return

  admin.firestore().collection('chat').document(documentId)
  .collection('users').document(documentId)
  .collection('messages').get().then((snapshots) => {
     var tokens = [];
     if (snapshots.empty) {
        console.log('No Devices');
        return false;

     } else {
      for (var token of snapshots.docs) {
          tokens.push(token.data().token);
      }

      var payload = {
         "notification": {
             "title": msgData.name,
             "body": msgData.title,
             "sound": "default"
          },
          "data": {
             "sendername": msgData.name,
             "message": msgData.title,
         }
       }

       return admin.messaging().sendToDevice(tokens, payload).then((response) => {
          console.log('Pushed them all');
       }).catch((err) => {
           console.log(err);
       })
     }

   })
})

Answer: A variável documentId não parece ter sido declarada em lugar algum do teu script, logo você não criou tal variável, então vai dar ReferenceError mesmo
O que você quer é provavelmente isto:
admin.firestore.FieldPath.documentId()

Conforme é documentado: https://firebase.google.com/docs/reference/admin/node/admin.firestore.FieldPath#.documentId
Você poderia setar no começo do script:
var msgData;
var documentId = admin.firestore.FieldPath.documentId();

...

Comment: Valeu Guilherme, realmente não sabia, dai preciso referenciar o caminho para o documento?


Is $f(x) = (x,x)$ not continuous in this topology?

Question: Let $S$ be the unit circle with the usual topology and let $\mathbb{R}$ be equipped with the discrete topology, then consider $S \times \mathbb{R}$ with the product topology, and consider the map $f(x) = (x,x)$ from $S$ to $S \times \mathbb{R}$, where here we are identifying $S$ with, say, $[0,1)$.
Is this map $f$ continuous?
The preimage of any $U \times R$ under $f$ for $U$ open in $S$ and $R$ open in $\mathbb{R}$ (any subset) is just $U$ or $\emptyset$, which is open in $S$, so it seems that $f$ should be continuous.
On the other hand...
Consider a non-closed subset $B$ of $S$. We have that $B = f^{-1}(f(B))$, but $f(B)$ is closed since any converging sequence in $S \times \mathbb{R}$ must be eventually constant. So, if $f$ were continuous we would have $B$ is closed since it is the inverse image of a closed set under a continuous map, a contradiction.
Clearly there is a mistake somewhere, but where have I gone wrong? Is the map $f$ continuous or not?
Comment: The preimage of $U \times R$ is actually $U \cap R$.
Comment: Alternately, $f$ is continuous if and only if $\pi_1 \circ f$ and $\pi_2 \circ f$ are continuous where $\pi_1 : S \times \mathbb{R} \to S$ and $\pi_2 : S \times \mathbb{R} \to \mathbb{R}$ are the projections.  $pi_1 \circ f$ is the identity function $S \to S$ so there's no problem there.  The issue is: is $\pi_2 \circ f : S \to \mathbb{R}$ continuous?
Comment: Also, converging sequences in $S \times \mathbb{R}$ don't necessarily have to be eventually constant.  It's sufficient (and also necessary) for the first component to be a convergent sequence in $S$, and the second component to be a convergent sequence in $\mathbb{R}$ and therefore eventually constant.
Comment: $S\times \{0\}$ is open in $S\times \mathbb R$, but $f^{-1}(S\times\{0\})$ is a single point.
Answer: To see that $f$ is not continuous, observe that $f[S]$ is a discrete subset of $S\times\Bbb R$. To see this, let $x\in S$, where I identify $S$ with $[0,1)$; then $f(x)=\langle x,x\rangle$, so $S\times\{x\}$ is an open nbhd of $f(x)$ that contains no other point of $f[S]$. (In fact the discrete subsets of $S\times\Bbb R$ are precisely those $A\subseteq S\times\Bbb R$ with the property that $A\cap(S\times\{x\})$ is finite for each $x\in\Bbb R$.) Since $S$ is not a discrete space, $f$ cannot be continuous.


Musical Shape on music stand

Question:
I've seen this shape a few times, but what exactly does it represents?
Comment: the lyra is the symbol for music: banners, uniforms, concert programs, flyers etc:
https://www.google.com/search?safe=active&rlz=1C1CHBH_deCH697CH697&biw=1230&bih=562&tbm=isch&sa=1&ei=AkzQXJCMAuPjgwfdxoqoCw&q=lyra+symbol+for+music&oq=lyra+symbol+for+music&gs_l=img.3...6352.12492..12755...2.0..0.98.1611.19......1....1..gws-wiz-img.......35i39j0i67j0j0i30j0i5i30j0i8i30j0i24.Hl_zQH0MVs0
Answer: It's a lyre of some kind:

A lot of ancient civilizations used variations of this instrument, especially the ancient Greeks. It's similar to a small harp .

Musical Shape on music stand


Solutions of AX=B

Question: I want to determinate if this system has one solution and infinite solutions.$AX=B$, with $A_{m\times n}$, $X_{n\times p}$ and $B_{m\times p}$
So i don't know if I can use the rank of A to determinate this, however i don't know if A is a square matrix. So if A is column row rank then:
$AX=0 $ implies  $X=A^{-1}AX=A^{-1}0=0$
so it has one solution, but what happens if the system has infinite solutions?
Answer: The solution set to $Ax=b$, when $x \in \mathbb{K}^n,b \in \mathbb{K}^m$, is always either empty (if no solution exists) or an affine space of dimension equal to the nullity of $A$ (if some solution exists). The nullity of $A$ is $n-r$ where $r$ is the rank (this is the "rank-nullity theorem").
For $AX=B$ where $X$ and $B$ are now matrices, you just apply the previous statement to each column of $B$ separately (since $AX=B$ is really just $p$ systems $Ax_k=b_k$).

Solutions of AX=B


Does Java have an exponential operator?

Question: Is there an exponential operator in Java?
For example, if a user is prompted to enter two numbers and they enter 3 and 2, the correct answer would be 9.
import java.util.Scanner;
public class Exponentiation {

    public static double powerOf (double p) {
        double pCubed;

        pCubed = p*p;
        return (pCubed);
    }

    public static void main (String [] args) {
        Scanner in = new Scanner (System.in);

        double num = 2.0;
        double cube;

        System.out.print ("Please put two numbers: ");
        num = in.nextInt();

        cube = powerOf(num);

        System.out.println (cube);
    }
}

Comment: `p*p` is `pSquared`, not `pCubed`.
Answer: There is no operator, but there is a method.
Math.pow(2, 3) // 8.0

Math.pow(3, 2) // 9.0

FYI, a common mistake is to assume 2 ^ 3 is 2 to the 3rd power. It is not. The caret is a valid operator in Java (and similar languages), but it is binary xor.
Comment: I wonder why `^` is the de factor standard for the bitwise XOR operator (e.g. Java & Python) - must have confused many a beginners or MATLAB users...
Comment: Why single out java and python? `^` as bitwise xor in a general purpose procedural programming languages was introduced by C, and virtually any language based on C (or that took inspiration from C or C++) has followed that convention. The fact that it means something else in a special-purpose maths programming language shouldn't really confuse anyone?
Answer: To do this with user input:
public static void getPow(){
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter first integer: ");    // 3
    int first = sc.nextInt();
    System.out.println("Enter second integer: ");    // 2
    int second = sc.nextInt();
    System.out.println(first + " to the power of " + second + " is " +
        (int) Math.pow(first, second));    // outputs 9

Answer: The easiest way is to use Math library.
Use Math.pow(a, b) and the result will be a^b
If you want to do it yourself, you have to use for-loop
// Works only for b >= 1
public static double myPow(double a, int b){
    double res =1;
    for (int i = 0; i < b; i++) {
        res *= a;
    }
    return res;
}

Using:
double base = 2;
int exp = 3;
double whatIWantToKnow = myPow(2, 3);

Comment: @libik What if b is negative ?
Comment: The myPow(double, double) method signature implies it calculates with floating point powers while in fact it doesn't. The method signature should read myPow(double, int). Math.pow(double, double) does take floating point powers into account, e.g., Math.pow(4, 0.5) returns the square of 4, so 2, whereas myPow(4, 0.5) would return 4.
Comment: how do i prompt users to put two numbers? i.e 2 3 = 8
Comment: in your example base will be 3 and exponent 2. I guess you should be multiplying by a inside loop and iterate b times instead.
Comment: @HummelingEngineeringBV - ok, lets fix it after more than 4 years :)
Answer: There is the Math.pow(double a, double b) method. Note that it returns a double, you will have to cast it to an int like (int)Math.pow(double a, double b).
Answer: you can use the pow method from the Math class. The following code will output 2 raised to 3 (8)
System.out.println(Math.pow(2, 3));

Answer: In case if anyone wants to create there own exponential function using recursion, below is for your reference.
public static double power(double value, double p) {
        if (p <= 0)
            return 1;

        return value * power(value, p - 1);
    }

Comment: please don't suggest such algorithms, it will only work for a negligible subset of p's domain
Comment: Save yourself and others the time and use `Math.pow()`. Don't do this.

Does Java have an exponential operator?


Cubic residue problem

Question: Let $x,y,z$ integers and $p$ is a prime satisfying
$x^3 + y^3 + z^3 \equiv 0 \pmod p \Rightarrow xyz \equiv 0 \pmod p$
this proposition. Is there infinity $p$ primes or $p$ is only $2,7,13$ ?
Answer is easy when
$x^2 + y^2 + z^2 \equiv 0 \pmod p \Rightarrow xyz \equiv 0 \pmod p$
Only $2$ and $5$ satisfies this proposition. We can use Legendre symbol or other elementary methods.
For $x^3$, there is a tool like a legendre symbol. But i don't know how to use it.
Answer: For $p\ge5$, $X^3+Y^3+Z^3=0$ is the homogeneous equation of an elliptic curve in the projective plane. It has $p+1-a$ points over $\Bbb F_p$ where $|a|<2\sqrt p$
(Hasse's theorem). But it has most $9$ points with $XYZ=0$. As long
as $p+1-2\sqrt p=(\sqrt p-1)^2>9$, it has points with $XYZ\ne0$.
This is the case for $p\ge17$.
Comment: That's a curve of genus $g=\frac12(n-1)(n-2)$ in general. Again there is a lower bound on the number of points in terms  of $g$ (Riemann hypothesis for curves) and for each $n$ there is $c_n$ such that the curve has points with $XYZ\ne0$ for $p>c_n$ by a similar argument. @Dogukan.N
Comment: what about $x^n+y^n+z^n \equiv 0 (mod p) , n>3$ ?

Cubic residue problem


Como converter o número de horas em formato de data em r

Question:
Tenho uma coluna neste formato e não consigo converte-la em formato de
  data. Neste momento encontra-se em horas. Exemplo: 8,5 é na verdade
  08:30:00 e por ai adiante... Alguma ideia de como o fazer? (ver
  imagem)

start_date <- as.POSIXct(data$START, format = "%Y-%m-%d %H")
data <- mutate(data, START=start_date)

end_date <- as.POSIXct(data$END, format = "%Y-%m-%d %H")
data <- mutate(data, END=end_date)

Ao escrever o código nesse formato o que acontece é que ele "ignora"
  as meias horas, ou seja, por exemplo, na primeira linha em vez de
  colocar 08:30:00 coloca 08:00:00.
Comment: Poste uma amostra dos seus dados como texto (por exemplo, usando `dput` - consulte o tópico sobre exemplos mínimos reproduzíveis na ajuda do site).
Answer: Se tem apenas horas inteiras ou meias horas, pode usar gsub para substir .5 para :30 antes de converter para POSIX. Escreva como uma função para evitar repetição de código quando for aplicar ao data.frame.
exemplo <- c('2013-09-02 8.5', '2013-09-02 9', '2013-09-02 10.5')

ajustaData <- function(x) {
  y <- paste0(x, ':00')
  y <- gsub('.5:00$', ':30', y)
  as.POSIXct(y, format = '%Y-%m-%d %H:%M')
}

> ajustaData(exemplo)
[1] "2013-09-02 08:30:00 -03" "2013-09-02 09:00:00 -03" "2013-09-02 10:30:00 -03"

Answer: A seguinte função converte as datas com horas em números com decimais em datas com horas no formato HH:MM:SS.
dec2hour <- function(x){
  d <- sub("(^.*) .*$", "\\1", x)
  h <- sub("^.* ", "", x)
  h <- as.numeric(h)
  m <- h - floor(h)
  h <- floor(h)
  m <- m*60
  s <- m - floor(m)
  m <- floor(m)
  s <- s*60
  y <- paste(h, m, s, sep = ":")
  y <- as.POSIXct(paste(d, y))
  y
}

x <- c("2013-09-02 8.5", "2013-09-02 10", "2013-09-02 11.5", "2013-09-02 3.508333")
dec2hour(x)
#[1] "2013-09-02 08:30:00 WEST" "2013-09-02 10:00:00 WEST"
#[3] "2013-09-02 11:30:00 WEST" "2013-09-02 03:30:29 WEST"

Nota: "WEST" deve-se ao meu fuso horário.
Sys.getlocale("LC_TIME")
#[1] "pt_PT.UTF-8"

Answer: Para transformar hora decimal em hora, basta manter a quantidade de hora e multiplicar os minutos por 60.
Exemplo: 1.50
Mantenho o 1 e pego os minutos como 0,50 e depois multiplico por 60... sendo assim ele se torna 30, agora é só concatenar 1||':'||30 e dar um parse para date.


Advice for Visual Studio NewB. Reusing existing class libraries?

Question: I am getting started on my first project experience with Visual Studio. My task is to use an existing Solution's source and expand its capabilities by adding new projects to said Solution.
My issue is that much of the existing source would be getting duplicated except for small changes.  I am unfamiliar with with Visual Studio, so I don't know what time saving techniques are available to me.
In my mind it would be ideal if I could duplicate some of the existing classes and simply have renamed copies of them added to the project that I could edit without fudging up the parts of the project that are working.
I should add, the only reason I would need to go this far to duplicate mostly identical code, is because the naming conventions used on the earlier projects would be extremely misleading if I used them as dependancies in my own project.
Will Visual Studio maintain itself if I start changing namespaces of existing classes to something more generic so I can use them without making my code confusing for others to follow?
Is there an easy way in Visual Studio to duplicate an OLD class if my NEW class is going to have half the code be the same anyway?
Any advice on approach or convention is more than welcome. Incidentally, I am working in Visual Studio 2012 Pro. and the project is mostly coded in C# if that helps anyone.
Comment: Lets assume the original project was an application for a government organization, the `Department of Motor Vehicles (DMV)`. My project would be to produce and link a new application that handles for a different yet similar government organization, the `Motor Vehicle Association (MVA)`.
Comment: I want to use many of the same class libraries but they are all named `DMVLibrary1, DMVLibrary2... etc.` How can I use these class libraries but not have the code be hella confusing?
Answer: Your question is vague, to get better answers you should put a concrete example of the problem you are facing.
Here are my ideas so far, they might give you a hint on what to do :

You could use the Facade pattern, by hiding the awful implementation and presenting a handsome one : http://en.wikipedia.org/wiki/Facade_pattern
You can extend classes using extension methods : http://msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx
You can make an alias of a particular namespace

Example of the some of the hints described above :
<code>using System;
using MyFamiliarNamespace = MyScaryNamespace;
using MyFamiliarClass = MyScaryNamespace.MyScaryClass;

namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var @class = new MyFamiliarClass();
            @class.HelloWorld();
        }
    }

    public static class MyScaryClassExtensions
    {
        public static void HelloWorld(this MyFamiliarClass myScaryClass)
        {
            Console.WriteLine("Hello world !");
        }
    }
}

// Consider this part being in another assembly
namespace MyScaryNamespace
{
    public class MyScaryClass
    {
    }
}
</code>

In my opinion you should not copy classes, while it seems the easiest thing to do it would sooner or later make things even more confusing, remember to Don't repeat yourself in programming.
Renaming namespaces : unless you have a tool like Resharper, doing it manually can be a real pain and prone to errors
Duplicating objects (or sort of) : if you absolutely have to duplicate objects then using something like Automapper can be a real-time saver in some situations.

Provide more details in your question so we can suggest better answers.
And giving a better title to it might be wise, too.
Comment: I added an analogy, but I think the extension example helps me a great deal. Thanks.


Programmatically add a footer to a view

Question: I need add a footer to a view based on certain conditions. I followed this article and as per my understanding this should work. But this is not giving me any result.
Here is my code:

function utility_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  $item = array(
    'id' => 'area_text_custom',
    'table' => 'views',
    'field' => 'area_text_custom',
    'relationship' => 'none',
    'group_type' => 'none',
    'admin_label' => '',
    'empty' => NULL,
    'tokenize' => NULL,
    'content' => array(
      'value' => "Footer content is great.",
      'format' => "basic_html",
    ),
    'plugin_id' => 'text',
  );
  $view->setHandler($display_id, 'footer', 'area_text_custom', $item);
}

Update: Using the above hook the footer is getting called but renders as Array
Comment: `based certain conditions` like what?
Comment: The conditions isn't important. That can be handled. But the problem is even the footer isn't showing up anyway. (Without any condition)
Answer: I was able to add a Views footer with some code in a custom module.
use Drupal\views\ViewExecutable;
function YOURMODULENAME_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if ($view->id() == 'view_machine_name' && $display_id === 'view_display') {
    $options = array(
      'id' => 'area_text_custom',
      'table' => 'views',
      'field' => 'area_text_custom',
      'relationship' => 'none',
      'group_type' => 'none',
      'admin_label' => '',
      'empty' => TRUE,
      'tokenize' => FALSE,
      'content' => 'Footer content is great.',
      'plugin_id' => 'text_custom',
    );
    $view->setHandler('view_display', 'footer', 'area_text_custom', $options);
  }
}

Reference: Drupal 8: Programmatically Adding a Views Footer
Comment: Thanks Sanjay, I was missing out the content and making it as an array for which the render was messed up.
Comment: If it really helps you. Mark vote up for this answer... Thanks :)
Answer: User area instead of area_text_custom, below solutions is working for me
$item = array(
  'id' => 'area',
  'table' => 'views',
  'field' => 'area',
  'relationship' => 'none',
  'group_type' => 'none',
  'admin_label' => '',
  'empty' => NULL,
  'tokenize' => NULL,
  'content' => array(
    'value' => 'Footer Text goes here',
    'format' => "full_html",
  ),
  'plugin_id' => 'text',
);

$view->setHandler('display_name', 'footer', 'area', $item);

Answer: You can attach a few other types of content also. Here is an example for a paragraph entity, but any entity type will be similiar.
/**
 * Implements hook_views_pre_view().
 */
function mytheme_views_pre_view(ViewExecutable $view, $display_id, array &$args)
{
  if ($view->id() == 'my-view-id') {

    // Load your entity however you want.
    $paragraph_entity = '[my-entity]';

    $item = [
      'id' => 'area',
      'table' => 'views',
      'field' => 'entity_paragraph',
      'empty' => TRUE,
      'target' => $paragraph_entity->uuid(),
    ];

    // This can be header, footer, etc. See ViewExecutable::getHandlerTypes();
    $type = 'header';

    // Handler ID.
    $id = 'paragraph_entity';

    // Finally, attach the handler to the view.
    $view->setHandler($display_id, $type, $id, $item);

  }
}

To understand better how to interface with handlers, see
core/modules/views/src/ViewExecutable.php
view->getHandler() and view->removeHandler() are also useful.

Programmatically add a footer to a view


Can I improve speed in Hyper-V?

Question: I use Windows Server 2008 R2 (it is host) with Hyper-V and a guest running Ubuntu 12.04 LTC. It is my settings:

RAM 32768
Cores (virtual processes) 4. (I need 12)

I also use virtual hard drive with 2 TB
Please, tell me:
1) Do I increase speed, if I use real hard drive?
It is important to know that I use Ubuntu. It is installed on the virtual hard drive. I know that in virtual box I always mount disk to Ubuntu via NAT. So there are not difference between virtual hard drive and real hard drive.
2) How can I set 12 processors?
Answer:
Do I increase speed, if I use real hard drive?

Yes, but it should not be relevant - 1-3%. Your main problem likely is that the hard disc is a hard disc which is just slow. It likeiy is not a larger RAID 10 of fast discs or an SSD.

How can I set 12 processors?

Use a modern version of Hyper-V. Not an outdated one with this low limit. 2012 is current, 2012 R2 coming out in two weeks.
Comment: I think you are wrong. http://windowsnotes.ru/virtualization/snimaem-ogranichenie-na-4-logicheskix-processora-v-windows-server-2008-r2-hyper-v/
Comment: Just because you can manually hack away at the actual xml file doesn't mean you should. This would place you in an unsupported configuration - in ANY sort of production environment, you would not want to be running in this configuration.
Comment: Esactly. There are - besides the fact you are in territory without support - known and published reasons the loimnit was put that low. And then raised in later releases.

Can I improve speed in Hyper-V?


Ajax requests and racing conditions (client and server side)

Question: Let's imagine the situation that we've sent two similar (almost similar) async ajax requests to server one by one. Because of lag in network, the second request was executed before first request.
Ajax request #1: /change/?object_id=1&position=5
Ajax request #2: /change/?object_id=1&position=6

In result, we have object_id=1 position set to position=5, but we want position=6 because Ajax request #2 was executed after Ajax request #1 by us.
What is the best practice to avoid this on server side and client side?
Answer: Are you worried about racing conditions from the same client or from multiple clients?
If from the same client, I would think the safest bet would be to include a unix timestamp in the ajax request and log this value on the server.  If a request comes with a timestamp that is older than the last logged value, ignore the request (or send a warning back to the browser).
I'm not sure how you would handle multiple clients with unsynchronized clocks...
Answer: For situations like this, I usually put a check in my success handler to make sure that the value being returned is still the one that I want. This will require sending up the parameter you're searching across in the results object.
For example:
var query = $('input').val();

$.get('/search', { query: query }, function(res) {
  if(res.query == $('input').val()) {
    //show search results
  }
});

I don't know the particulars of your use case, but this general pattern should help.
Answer: On the server :

Build a request table to map request id to timestamp
Log any request to the server, expect all requests come with timestamp
If any request comes out of order (e.g. position 6 comes before 5)

Check the request table, if it is an earlier request (timestamp) then do not process the request and send an ignore flag

If it comes in order

This is fine, proceed as usual and no need to send any ignore order

On the client:

When request comes back in, check the ignore flag. If it is there. Don't do anything to the client
Otherwise proceed as usual by processing the data

Note that this implementation that I suggested requires you to send back and forth data (such as JSON) and not the presentation code (such as HTML fragment) as you would need to check for the ignore flag on the client side.
This answer is similar to what @Farray suggestion of using timestamp.


Como repetir o código no final no python?

Question: então, eu estou iniciando programação (apenas por apender mesmo ) e queria saber como fazer para o código reiniciar no final.
Sei que pode parecer algo simples mas eu não faço nenhum curso, estou aprendendo sozinho
lanchonete = ("500$")

açaiteria = ("900$")

uber = ("200$")

pationorte = ("1200$")

pergunta = input ("Diga o nome do estabelecimento desejado ")

if pergunta ==("lanchonete"):
   print (lanchonete)

elif pergunta ==("açaiteria"):
   print (açaiteria)

elif pergunta ==("uber"):
   print (uber)

elif pergunta ==("pationorte"):
   print (pationorte)

else:
   print ("Este estabelecimento não esta cadastrado no nosso banco de
   dados")

Answer: Já que está aprendendo, vale a pena comentar. O que você fez no seu código basicamente foi relacionar quatro variáveis aos seus respectivos valores e, a princípio, não variarão durante a execução. Algo assim geralmente é chamado de mapa: você define uma relação direta entre uma chave e um valor. Neste caso, a chave seria o nome do estabelecimento e o valor a quantidade monetária relacionada. No Python, a maneira mais simples de se implementar isso é com dicionário:
estabelecimentos = {
    'lanchonete': '500$',
    'açaiteria': '900$',
    'uber': '200$',
    'pationorte': '1200$'
}

Para obter o valor a partir de uma chave, basta utilizar o método get, que, inclusive, permite definir um valor padrão para caso a chave não exista:
padrão = 'Este estabelecimento não esta cadastrado no nosso banco de dados'
pergunta = input("Diga o nome do estabelecimento desejado ")
print(estabelecimentos.get(pergunta, padrão))

Colocando isso dentro de um laço de repetição, ficaria:
estabelecimentos = {
    'lanchonete': '500$',
    'açaiteria': '900$',
    'uber': '200$',
    'pationorte': '1200$'
}

padrão = 'Este estabelecimento não esta cadastrado no nosso banco de dados'

while True:
    pergunta = input("Diga o nome do estabelecimento desejado ")
    print(estabelecimentos.get(pergunta, padrão))

Veja funcionando no Repl.it
Answer: Basta envolver seu código num loop while True.
O while verifica uma condição, e se ela for verdadeira, executa novamente tudo o que está dentro do seu bloco de indentação. Como passamos True, ele sempre executará tudo de novo.
Como outra dica: os parênteses são desnecessários nos casos de atribuição (=) e comparação (==), e só são necessários aqui pras funções. Seu código fica um pouco mais claro sem eles!
while True:
    lanchonete = "500$"

    açaiteria = "900$"

    uber = "200$"

    pationorte = "1200$"

    pergunta = input ("Diga o nome do estabelecimento desejado ")

    if pergunta == "lanchonete":
       print (lanchonete)

    elif pergunta == "açaiteria":
       print (açaiteria)

    elif pergunta == "uber":
       print (uber)

    elif pergunta == "pationorte":
       print pationorte

    else:
       print ("Este estabelecimento não esta cadastrado no nosso banco de dados")


Asking a question with a known answer

Question: Earlier today, I was about to submit a new question regarding layout XML. Before submitting, I had a simple thought that I figured I'd try, and it ended up working.
I was hesitant to then ask the question followed by including an answer immediately. I know others could benefit, so I do believe it's a worthwhile question, but I'm not sure if this type of "quick tips" type of posting would be a good candidate for a new question.
Answer: I believe that Robert's comment only applies during this very early phase of the site, for the reasons that he mentions.  If you're asking whether this is allowed in general, I think the answer is yes, it is not only allowed, it's encouraged:
http://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/
In my opinion, any non-trivial question and answer add value to a stackexchange site.
Note that not everyone is aware of this, and you will many times be downvoted for answering your own question - particularly if you do it quickly - by people who aren't aware of this.
Comment: Good to know. +1
Answer: Please be careful about staging questions you already know the answer to… especially so early in a site's development. I try and convey this to every new site we launch, but your home page says a lot about your site. If there's a sense that that the users don't really need the help they are asking for, the whole exercise would likely be perceived as a waste of time.
Please, at least read
Your New Site: Asking the First Questions
I understand that you actually had the question you asked about. But let's not present this as some type of solution — to start adding "quick tips" as a way of growing this site. Ask about problems you actually have, and please don't "seed" questions as a way of upping your numbers.
It will not work. Trust me.
Comment: Would it be more appropriate to just ask the question and leave it to be answered for X amount of time before providing a solution? Not to "game" the system in any way, but it's something I've been curious about in the past with SO.
Comment: @pspahn In my opinion, that's a pretty risky proposition. The folks here are **real people** taking their valuable time out to help you. If they learn you never needed the help in the first place, you are betraying an essential motivation for folks who take the time out to share their hard-earned knowledge through this site.
Comment: Very good point. I didn't like the idea myself, but hadn't thought of that.
Answer: I don't think it's a good idea to ask a question and answer it right away.
If you think your finding can be useful to others, consider writing a blog post. In case you don't have your own blog you can contribute to any existing Magento related blog. I'm sure they will be glad to publish it.
Answer: Well there is a "Answer your own question – share your knowledge, Q&A-style" checkbox (on the bottom of the page where you write/ask your question) for a reason.
It's appreciated if you share knowledge Q&A style as long as it's not a silly mistake. If it's actually something that could help many others then please do share!
Comment: I agree. If you already were about to click the submit button for your question, in my opinion it would be a pity to just throw everything away. By marking your answer as a community wiki answer, it wouldn't look like you just want to gather reputation because you don't get reputation for the answer (right?) but you still can help other people having the same question.

Asking a question with a known answer


Configuring WSUS server to use NIC#1 (LAN#1) to push, NIC#2 (LAN#2) to sync

Question: Oh boy... This should be easy, but my head is swimming. I work in two domain environments. My primary domain (LAN1) is completely offline, but has regular domain services (DC, DHCP, router (legacy, used for DMZ)...). My lab domain (LAN2) is online, and also has regular domain services.
LAN1 (production)
add: 10.0.1.0/24
LAN2 (lab):
add: 10.10.10.0/24
router: 10.10.10.1
I'm working on deploying a WSUS server to service the devices LAN1. The server is a Hyper-V VM configured with Server 2012 Core with RRAS and WSUS, and two virtual adapters (one connected to each LAN). It is hosted in Hyper-V Server 2012. The host server has four NICs (2 teams) for LAN1, one NIC reserved for host, and one NIC connected to LAN2. Both LAN1 teams and the LAN2 NIC are connected to external virtual switches for use in Hyper-V.
My goal is to have the WSUS server joined to LAN1's domain, to manage updates to the devices in the 10.0.1.0/24 subnet, and to use LAN2's connection to sync and download updates.
What is the best way to accomplish this without encountering DNS issues or crosstalk? Would a static routes work if configured correctly?
Answer: I believe this thread will have all the information you need to get this working.
In a nutshell, your LAN2 NIC must be assigned a default gateway (10.10.10.1) and a DNS server IP address capable of resolving internet DNS names.  The LAN1 NIC must not be assigned a gateway and the internal DNS server IP address.
You need to change the binding order by going to Network & Sharing Center > Change Adapter Settings > Advanced (hold down alt if you don't see it) > Advanced Settings and to make LAN1 is first on the list so it tries this firs for network services.
Hope this helps!
Comment: Thanks for the response Chris. I implemented this solution and it's working great. The only additional configuration I had to do was to add a "mydomain.com" forward lookup zone on my lab DNS server and create host records to point to my production DC's. But yea, WSUS is currently doing a post-installation sync, and everything looks good.
Comment: Cool. Glad I could help! :)


Pandas concatenate function problem

Question: I have a dataframe of shape (1388, 14) where two of the columns represent the  years of education of each parent. Both these columns have missing values, which are denoted as '.' in the original dataset. What I need to do is clear the dataframe from these entries and then concatenate the variables of interest into a new dataframe so I can run a regression. So far I have this:
df_bwght = pd.read_excel('bwght.xls')
df_bwght.drop(df_bwght[df_bwght.motheduc=='.'].index, inplace=True)
df_bwght.drop(df_bwght[df_bwght.fatheduc=='.'].index, inplace=True)

bwght = df_bwght['bwght']
cigs = df_bwght['cigs']
parity = df_bwght['parity']
faminc = df_bwght['faminc']
motheduc = df_bwght['motheduc']
fatheduc = df_bwght['fatheduc']

When I run df_bwght.shape it tells me that the necessary rows have been removed and the shape is now equal to (1191,14). The shape for each individual column is also equal to (1191,)
Next I try to concatenate the variables of interest:
X = pd.Series(np.repeat(1,len(df_bwght)))
X = pd.concat([X,bwght],axis=1)

Both the variables being concatenated have the shapes (1191,), but the resulting dataframe has the shape (1357,2).
Can someone please help and explain to me why this happens?
Comment: This would be more suitable to ask on stackoverflow. https://stats.stackexchange.com/help/on-topic
Answer: When you drop the rows from df_bwght, the indices were not dropped. They were probably like
> list(df_bwght.index)
[0,1,3,5,9,10,11,12,...]

When you join with the 1 vector (which has sequential indices), it skipped through the null indices.
You can do this to reset the indices
df_bwght.reset_index(drop=True, inplace=True)

reference to https://stackoverflow.com/questions/32801806/pandas-concat-ignore-index-doesnt-work

Pandas concatenate function problem


Using Python version 2.7 *virtually* when I only have version 3.10 installed

Question: I have version 3.10.2 of Python installed on my Windows machine via the Anaconda distribution.  There is an API that I'd like to use that supports only Python version 2.7.
In order to use this API, do I need to also install version 2.7 (which I would rather not do!)?
Or, can I use version 2.7 of Python virtually through some means?  And, if, "yes", what is the best way to do so virtually?
Thanks!
Comment: Python 2 was officially sunset in January 2020. As a consequence, it hasn't received any patches or security updates since then. It's generally *not* a good idea to write new code that depends on Python 2. All else equal, I would recommend seeking alternatives for the libraries you're seeking to leverage, while also acknowledging there are *some* scenarios where this type of dependency is unavoidable.
Comment: APIs generally don't care what you call them with. Do you mean you have a Python library for this API but the _library_ is for Python 2? Try translating it with `2to3` but don't necessarily expect it to work right out of the box. In particular, Python 3 distinguishes between Unicode strings and `bytes` sequences where Python 2 obliviously let you mix the two; perhaps see also http://nedbatchelder.com/text/unipain.html
Comment: You can, but not in the same *process*. If you have code that only runs under Python 2.7, you'll need to install Python 2.7 in order to run it. A virtual environment is just a name for a specific installation and some shell configuration to ease its use.
Comment: https://stackoverflow.com/questions/27863832/calling-python-2-script-from-python-3
Comment: @esqew For reference: [Sunsetting Python 2](https://www.python.org/doc/sunset-python-2/)
Answer: Create a new virtual env with python 2.7, with conda create --name new_env, and run your code with the python.exe inside this env
conda
Comment: Shouldn't that be `conda create --name new_env python=2.7`?
Comment: yes i mean you can install whatever you want in a virtualenv
Comment: Oh wait, maybe I'm misunderstanding. How does this use Python 2.7 virtually, like OP's asking? If you don't specify the Python version, Conda uses the **system** version, no? So that'd be 3.10 for OP. Or if you are in fact suggesting that OP install Python 2.7 in the virtual env, how does that help? OP's asking how to **avoid installing it**. (Personally, I think I understand how Conda works, I'm just not very experienced with it.)
Comment: with an env with python=2.7, just do `conda activate name_of_env` and then localize where is python with `echo $CONDA_PREFIX`, after in console execute your python script with this python.exe, it will run in a different process


Get call without form possible?

Question: Hi I need to know if it is possible to have an ajax GET call without having a form.
I tried:
$(".edit_event").live("click", function() {
    var currentID = $(this).data("event-id");
    var currentTable = $(this).data("table");

    if (currentTable == 'Coffee_talk') {
        alert('Erzaehlcafe mit ID' + currentID);

        $.ajax({
            url: 'index.php?section=event_select&id=' + currentID + '&table=' + currentTable,
            type: 'GET',
            dataType: 'json',
            success: function (select) {
                alert(select);
            }
        });
        return false;
    } else if (currentTable == 'Presentation') {
        alert('Vortrag mit ID' + currentID);
    } else if (currentTable == 'Exhibition') {
        alert('Ausstellung mit ID' + currentID);
    }
});

Debugging with Firebug says, that there is a GET call with ID and Table but I don't get any value back (no json nor php echo).
This is my php:
if ('GET' == $_SERVER['REQUEST_METHOD']) {
    if ($_GET['table'] == 'Coffee_talk') {
        echo ('test');

        $response['code'] = '1';
        echo json_encode($response);
    }
    if ($_GET['table'] == 'Presentation') {

    }
    if ($_GET['table'] == 'Exhibition') {

    }
}

Just used some test values.
Comment: [Stack Overflow is not in need of your SEO skills](http://meta.stackexchange.com/a/130208/143302)
Answer: Get rid of echo ('test');, it isn't json.
$.get() does not require a form.
Comment: thx deleted echo statement. Used following code:`$.get("index.php?section=event_select&id=" + currentID + "&table=" + currentTable,
    function(data){
     alert(data);
    }, "json");
   return false;`But I dont get JSON back.
Comment: do you get `[object Object]`?
Comment: Ok sry found the bug. I wanted to use event_edit section but while coding I preffered to use event_select and didn't define new section.. Its working now thx ;)

Get call without form possible?


Exercise 2.51 H. Abels. Pseudo differential and singular integral operator an introduction with applications

Question: Exercise 2.51 Let $\langle \xi\rangle =\sqrt{1+|\xi|^2}$. Prove that for any $s\in\mathbb{R}, \alpha\in\mathbb{N}_{0}^{n}$ there is some $C_{s,\alpha}>0$ such that
$$|\partial_{\xi}^{\alpha} \langle \xi\rangle^s|\leq C_{s,\alpha}(1+|\xi|)^{s-|\alpha|}\quad \text{ for all } \xi\in\mathbb{R}^n$$
Hint. Consider the function $f(a,x):=(a^2+|x|^2)^{m/2}$, where $a\in\mathbb{R}, x\in\mathbb{R}^n$. Use that $f$ is homogeneus of degree $m$, i.e., $f(ra,rx)=r^mf(a,x)$ for all $r>0, a\in\mathbb{R}, x\in\mathbb{R}^n$.
Hello. I am trying to use the hint but I don't know how to use it. I tried not to use it and directly applied induction on the multi index large but the problem gets complicated. How does the homogeneous function f help solve the problem?
Answer: Now, I have solved!
If $f(ra,r\xi)=r^sf(a,\xi)$ then
$r^{|\alpha|}(\partial_{\xi}^{\alpha}f)(ra,r\xi)=r^s\partial_{\xi}^{\alpha}f(a,\xi)$
\begin{eqnarray}
\partial_{\xi}^{\alpha}f(a,\xi)&\leq& r^{|\alpha|-s} C_{\alpha,s} \\
&=&C_{\alpha,s} (1+|\xi|)^{s-|\alpha|}
\end{eqnarray}
where $r=(1+|\xi|)^{-1}$ and $C_{\alpha,s}=\sup_{(a,\xi)}(\partial_{\xi}^{\alpha}f)(ra,r\xi)$


Can I do a ctrl-z without the process locking up?

Question: So lets say I'm executing a command on the CLI and it spawns a GUI and I forget the & at the end.  Now I want my shell back,  so I hit a ctrl-z but the GUI locks up!   Is there any way to do a ctrl-z without locking up the GUI?  I am using Linux with a bash shell,  xorg and gnome. This is an Ubuntu system.
Answer: Use bg to put the command that you have stopped in the background.
Comment: It says "no such job"
Comment: When you stop the job you will get something like `[n]+ command stopped` enter `bg n` to backgrounds the job
Comment: Type 'jobs' to see currently running jobs. You should be able to pick the one you need from here. It'll probably be marked 'stopped'.
Comment: and @wzzrd  yeah but its not a job,  its just a command like `firefox`.
Answer: Check out GNU Screen. It is very useful for this type of thing as well as offering a bunch of other terminal multiplexing functionality that can be very nice.
Comment: I would call screen a lot of things, but a place to start GUI apps from and them (and it) leave them running until eternity wouldn't be one of them. Standard job control fits this job a lot better.
Comment: And why is that? X11 forwarding works perfectly fine through `screen`. The OP wasn't asking how to suspend and resume his application, he really just wanted his shell back, which `screen` will give him.


How to rename a "using Directive" C#

Question: How would you rename a "Using Directive" Using C#?
Because some times You copy a class from somewhere (Example below)
//Other Code
        Excel.ApplicationClass excel;
        Excel.Workbooks workbooks;
        Excel.Workbook workbook;
        Excel.Worksheet worksheet;
        Excel.Sheets worksheets;
//Other Code

and instead of renaming everything to
//Other Code
        Microsoft.Office.Interop.Excel.ApplicationClass excel;
        Microsoft.Office.Interop.Excel.Workbooks workbooks;
        Microsoft.Office.Interop.Excel.Workbook workbook;
        Microsoft.Office.Interop.Excel.Worksheet worksheet;
        Microsoft.Office.Interop.Excel.Sheets worksheets;
//Other Code

So having something like
Using  Microsoft.Office.Interop.Excel.ApplicationClass as 'Excel'

Comment: How about if you use 'using i = Microsoft.Office.Interop' and the variables can be changed 'i.Excel.ApplicationClass excel;'
Comment: That "how to change namespace of entire project?" isn't even close to what I asked for.
Answer: You can create an alias like this:
// for whole namespace
using Excel = Microsoft.Office.Interop.Excel;
// use like this
Excel.ApplicationClass excel = /* ... */;

// or for single type
using ExcelApp = Microsoft.Office.Interop.Excel.ApplicationClass;
// use like this
ExcelApp excel = /* ... */;

Answer: I think you're just looking for:
using Excel = Microsoft.Office.Interop.Excel;

(I don't think you wanted ApplicationClass here. That would be an alias for the type rather than the Microsoft.Office.Interop.Excel namespace. It's not really clear from your question though.)
This is called a using-alias-directive. From section 9.4.1 of the C# 4 spec:

A using-alias-directive introduces an identifier that serves as an alias for a namespace or type within the immediately enclosing compilation unit or namespace body.

So after that using directive, it would be valid to have:
Excel.ApplicationClass excel = new Excel.ApplicationClass();

... which is what I think you wanted?
Answer: What about:
using Excel = Microsoft.Office.Interop.Excel;

Answer: As the msdn documentation says http://msdn.microsoft.com/en-us/library/sf0df423%28v=vs.71%29.aspx
using [alias = ]class_or_namespace;

So in your case:
using Excel = Microsoft.Office.Interop.Excel;

How to rename a "using Directive" C#


How to create a drag & drop sorting interface programmatically?

Question: If you have seen the Views module, there is "sorting criteria", where we add fields and then rearrange fields to set the priority. In order to rearrange, we click on "rearrange" link and all fields get a draggable UI so that we can move it up or down to set sorting priority.
How can I do this thing exactly programmatically?
Comment: So, you don't want to use Draggable Views? https://www.drupal.org/project/draggableviews
Comment: Planing to implement it in a **view** or in **form**...??
Comment: Implementing it in a ctool modal. Form actually, that opens up in popup.
Answer: Here is a drupal_add_tabledrag function using which you can add draggable functionality programmatically.

Assists in adding the tableDrag JavaScript behavior to a themed table.
Draggable tables should be used wherever an outline or list of
  sortable items needs to be arranged by an end-user. Draggable tables
  are very flexible and can manipulate the value of form elements placed
  within individual columns.

See this blog for example. You may need to imprement theme function.
$element = $vars['element'];
drupal_add_tabledrag('sample_table', 'order', 'sibling', 'item-row-weight');

$header = array(
  'label' => t('Attribute'),
  'checkbox' => t('Enabled/disabled'),
  'weight' => t('Weight'),
);

Answer: Here are the 3 simple steps to create a form with drag and drop ordering:

Implement hook_menu, to register the URL of the form

function module_name_menu() {
$items = array();
$items['admin/config/content/module_name/manage'] = array(
    'title' => 'Recent News: List Links',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('module_name_manage'),
    'access arguments' => array('access administration pages'),
);
}

We will use the following function to render the form:

function module_name_manage() {
$db_result = db_query( "select id,title position from recent_news order by position");
// create array and add one element called data
$rows= array();
$form['#tree'] = TRUE;
$max = 60;
foreach($db_result as $row){
    $title = $row->title;
    if(strlen($title)>$max)
        $title = substr($title,0,$max).' ...';
    $form['slides'][$row->id]['id'] = array(
        '#type' => 'hidden',
        '#default_value' => $row->id,
    );
    // Textfield to hold content id.
    $form['slides'][$row->id]['title'] = array(
        '#type' => 'item',
        '#title' => $title
    );
    // This field is invisible, but contains sort info (weights).
    $form['slides'][$row->id]['weight'] = array(
        '#type' => 'weight',
        '#title' => t('Weight'),
        '#title_display' => 'invisible',
        '#default_value' => $row->position,
    );
}

$form['submit'] = array('#type' => 'submit', '#value' => t('Save changes'));
return $form;
}

implement hook_theme, to register theme implementation of form with drag and drop support

function module_name_theme($existing, $type, $theme, $path) {
return array(
    'module_name_manage' => array(
        'render element' => 'form',
    ),
);
}

And here is the callback function which will render the form with drag
  and drop capabilities

function theme_module_name_manage($variables) {
$form = $variables['form'];

$rows = array();
foreach (element_children($form['slides']) as $nid) {
    $form['slides'][$nid]['weight']['#attributes']['class'] = array('slides-order-weight');
    $rows[] = array(
        'data' => array(
            array('class' => array('slide-cross')),
                drupal_render($form['slides'][$nid]['title']),
                drupal_render($form['slides'][$nid]['weight']),
            ),
        'class' => array('draggable'),
    );
}

$header = array('',t('title'),t('position'));
$output = drupal_render($form['note']);
$output .= theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'slides-order')));
$output .= drupal_render_children($form);

drupal_add_tabledrag('slides-order', 'order', 'sibling', 'slides-order-weight');

return $output;
}

Implement hook_submit, to handle form submit and save the ordering

function module_name_manage_submit($form, &$form_state) {
$slides = array();
foreach ($form_state['values']['slides'] as $slide) {
    $slides[] = array(
        'id' => $slide['id'],
        'weight' => $slide['weight'],
    );
}
if (!empty($slides)) {
    usort($slides, '_module_name_arraysort');
}
$position = 1;
foreach($slides as $slide){
    $id = $slide['id'];
    $sql = "UPDATE recent_news SET position={$position} WHERE id = {$id}";
    db_query($sql);
    $position++;
}

drupal_set_message(t('Ordering have been saved.'));
}

// Custom array sort function by weight.
function _module_name_arraysort($a, $b) {
if (isset($a['weight']) && isset($b['weight'])) {
    return $a['weight'] < $b['weight'] ? -1 : 1;
}
return 0;
}

The code is quite long but you can just copy and paste then modify it if necessary. This tutorial is based on Ki Kim's post on http://www.urbaninsight.com/2012/09/11/creating-table-with-draggable-weights-in-drupal-7


Calling an Array from a ForLoop

Question: I'm learning java a bit and I need help calling an array while its in a For Loop, Here's my array code.
Entire Code was Requested, Sorry If its sloppy or bad coding
    import java.util.Scanner ;
       public class jakeGrim {

        public static void  main(String[] args) {
                // Local variable

                int option;
                String squareFootage="";
                int noBed = 0;
                double totalSum =0;
                String propertyCode="";
                String propertyType="";

                Scanner input = new Scanner( System.in );
                Scanner user_input = new Scanner( System.in );

  do{
                  // Display menu graphics
                System.out.println(" ");
            System.out.println("|  *****Rental Menu*******   |");
            System.out.println("|        1. Enter rental property Details     ");
            System.out.println("|        2. Enter monthly rent ( 12 Months )       ");
            System.out.println("|        3. Display Annual Rent");
            System.out.println("|        4. Display rental report       ");
            System.out.println("|        5. Display Monthly rents falling below a certain threshold       ");
            System.out.println(" ");
            System.out.println(" Please Select an option: ");
            option = input.nextInt();

  {

    switch (option) {

   case 1:

            System.out.println("Enter Rental Details: ");
            System.out.println("Property Code:            ");
            propertyCode = user_input.next();
            System.out.println("Property Type:            ");
            propertyType = user_input.next();
            System.out.println("Square Footage:           ");
            squareFootage = user_input.next();
            System.out.println("Number Of bedrooms        ");
            noBed = input.nextInt();
            break;

      case 2:

     {
                Scanner keyboardScanner = new Scanner(System.in);
         double[] array = new double[12];
         for (int i = 0; i < 12; i++) {
         System.out.println("Enter Rental for month[" +( i +1)+ "]");
         array[i] = keyboardScanner.nextDouble();
       }

       //So now, we need to do something with that array and sum up all the values in that array.
       for (int i = 0; i < array.length; i++){
         System.out.println(array[i]);

        totalSum += array[i];
      }
       }

        break;

            case 3:
            System.out.println("The annual rent for propery code "+propertyCode+" is:  " +    (totalSum));

       break;

    case 4:
           System.out.println(" Property Code:      "+propertyCode);
           System.out.println(" Property Type:      "+propertyType);
           System.out.println(" Square Footage:     "+squareFootage);
           System.out.println(" Number of Bedrooms: "+noBed);
           System.out.println("");
           System.out.println("");
       for(int i = 0; i<12; i++)
           System.out.println("Rental for month " + (i+1) + " : " + array[i]);

           break;
           default:
             System.out.println("Invalid selection");
             break;
            }
         }
       }while (option!=0);
       }
       }

Now I need to display the 12 different User entered numbers in a Different Case, Due to this all being part of a switch method. Is there a way to do this, I have tried the very simple code Like
          System.out.println("Rental for month 1: "+i(1));

But it says "cannot find symbol- method i(int)"
I just want to declare them, Is there any way?
Comment: It seems like you're trying to index into your loop variable, an integer, with a constant, when you should be indexing into your array (which remains the same) with your loop counter.
Comment: @CosmicComputer Can you write that in answer form with instructions on how to do so? I'm pretty useless at code at this point :3
Answer: Try this-->
This will print rent for each month..
for(int i = 0; i < 12; i++)
    System.out.println("Rental for month " + (i+1) + " : " + array[i]);

One more edit in your code should be made..
     double[] array = new double[12];

     for (int i = 0; i < 12; i++)
     {
         System.out.println( "Enter Rental for month[" + (i+1) + "]" );
         array[i] = keyboardScanner.nextDouble();
     }

Comment: It says cannot find variable array, I already have an array All i need to do is to print the already made array that the user will basically "fill out"
Comment: I dont want it to print as soon as they type it.. it is being called in a seperate menu option, A different case in a switch statement.
Comment: @JakeGrim: Ohh.. so what do you want in your switch case? Will the user explicitly enter the month for which he needs the rent for?
Comment: No they will literally enter what rent they payed 12 different months, that is already sorted, I wish to call the 12 numbers they entered and put it in a different statement. Basically giving an overview of what they typed.
Comment: @JakeGrim: ok.. I am getting confused.. Isn't the code that I wrote doing that? My code will print the rent they entered/payed for 12 different months..
Comment: Im not sure, I'm doing the edits now on my main code. Post back in a moment to check.
Comment: It still cannot find the variable Array
Comment: Entire code is Posted, Can you do anything with it?
Answer: System.out.println("Rental for month 1: "+i(1));

What is i here ? Looks like a method which you dont have. You have to do following in a loop
System.out.println("Rental for month " + (i+1) + " : " + array[i]);

Comment: It doesnt seem to find the variable array, The i would be the name of the array.

Calling an Array from a ForLoop


Computing probability density function at a point, given the covariance matrix and mean

Question: (Edited for clarity.)
Say I have the variance-covariance matrix $\mathbf{V}$ and mean $\mathbf{\mu}$ of a multivariate normal distribution. Given a sample, $\mathbf{s}$, can I compute/estimate the value of the probability density function at that sample?
I'm trying to determine how well a given sample "fits" the various distributions determined by some $\mathbf{V}_i$ and $\mathbf{\mu}_i$ in order to label the sample with $\underset{i \in 0, 1, ...}{\arg\max\,}{f(\mathbf{s}; \mathbf{V}_i, \mathbf{\mu}_i)}$.
Comment: For anyone else who comes with the same question: yes, there is an analytic form for the PDF of the multivariate normal, and it's fairly convenient; see, for example, the `scipy` docs [here](https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.multivariate_normal.html)
Answer: The mean vector and covariance are not sufficient to give the entire probability distribution, so this is a case where you have not prescribed enough information to yield a probability density/mass function, or a likelihood function.  If you were to prescribe a class of distributions parameterised by the mean and covariance matrix (e.g., the normal distribution) then that would be sufficient to give you a likelihood function.  For example, if you use the normal distribution, the log-likelihood function is:
$$\ell_\mathbf{s}(\mathbf{V}) = - \frac{1}{2} \text{det}(\mathbf{V}) -\frac{1}{2} \mathbf{s}^\text{T} \mathbf{V}^{-1} \mathbf{s}
\quad \quad \quad
\text{for all } \mathbf{V} \in \mathcal{V},$$
where $\mathcal{V}$ is the set of real square positive-definite matrices of the required dimension.
Comment: You can't be using any kind of "maximum-likelihood" estimator unless you have a likelihood function -- what would you be maximising?  Thus, if you are using a procedure like this, there *must* be some specification (possibly implicit) of what the likelihood function actually is.  Most likely the procedure you are using is (implicitly) assuming a Gaussian distribution, but you should check this.
Comment: @Linuxios: Unfortunately, what you've written now does not quite make sense.  Taking $\text{arg max}$ over the variable $i$ would mean that you are looking for the single data point with the highest sampling probability.  I presume that is not what you're trying to do.  Perhaps read about [maximum likelihood estimation](https://en.wikipedia.org/wiki/Maximum_likelihood_estimation) and then see if this is what you want to do.
Comment: $i$ is an index over various distributions; $\mathbf{s}$ remains fixed.
Comment: Okay, so what you have is a maximum likelihood problem then.
Comment: Where the candidate distributions are given, yes
Comment: In practice, I'm using the maximum-likelihood empirical covariance estimator to get $\mathrm{V}$ in the first place, so making that same assumption (multivariate Gaussian) here is no worse than making it in the first place, right?
Comment: Maybe I'm not saying what I think I'm saying. I have some set of observations from which I'm computing the covariance matrix (from [`sklearn`](https://scikit-learn.org/stable/modules/generated/sklearn.covariance.EmpiricalCovariance.html)). This computes the covariance assuming a multivariate normal distribution, I think.
Comment: Further, I think I'm looking for a $\ell_\mathbf{V}(\mathbf{s})$, for lack of a better way to put it. Does that have the same form? The likelihood of the sample $\mathbf{s}$ given the mean, covariance matrix, and the assumption of multivariate normal distribution.
Comment: Okay, well in that case you can use the formula above.  (Note that I have omitted the constant term $-\tfrac{n}{2} \cdot \ln (2 \pi)$ from the function, where $k$ is the length of the vector $\mathbf{s}$.  The computer program you are using would probably include this term.)
Comment: Great. How does one interpret a likelihood value? (I know you said that the above is log-likelihood, but I don't see any logs -- is it implied that I should be considering the log of this quantity?)
Comment: Hi @Ben: thanks for taking the time to try and answer my question before. Now that I've clarified it, does this answer still hold?


Altering LAN Settings from a batch file and/or C#?

Question: I'm not sure how to describe this without an image, so attached is a quick snip from what I want to do in a batch file (Windows 7 Enterprise 32 bit)

In Internet Options, under the Connections tab, there's a LAN settings button (marked in red), that opens the displayed dialog from the image. I already have the address and port I want, all I want is a way to check or uncheck the marked checkbox from a batch file. I would also accept an answer for how to do it in C#.
EDIT:
For other people who stumble across this question, this question is just for me being a power user. If you have a product that needs to change Proxy server settings, don't assume the settings are correct, use PostMan's second registry entry to properly set the proxy first.
Answer: Yes you can do this using the command reg.
it's stored in HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\
so you can use the following command in a batch file:
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\\" /v "ProxyEnable" /T REG_DWORD /d 1

This will set the ProxyEnable to 1 (Enabled)
and
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\\" /v "ProxyServer" /T REG_SZ /d "192.168.1.1:8080

To set the proxy to 18.104.22.168:8080
Take note of the extra slash at the end of Internet Settings, without it the slash cancels the "
Also, You can add /f to force the over writing of the old value, currently it will ask to confirm overriding.
Comment: Thank you @PostMan. Do you know how to set or unset 'Automatically Detect Settings' checkbox, too?
Comment: @GokcenG create a String field named 'AutoConfigURL' with your automatic config url, and this will tick the checkbox and populate the text box with the contents of this registry entry. Create the field in the same location as above (HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\)
Comment: Hi @PostMan. I think I've stated my question wrong. I wonder the check box next to the 'Automatically Detect Settings' not 'Use automatic configuration script'.
Comment: @GokcenG I believe (based on very small testing) that the checkbox is driven from the AutoConfigURL field, so if you remove it then the checkbox won't be checked.
Comment: I am really interested in unchecking that checkbox too, since if it is checked it does not go online (it does not prompt me the password for the proxy connection). Any help?
Comment: solid! thanks! but, there's any doc files where i can know how did u get that url? and those field names?
Answer: You could use Powershell for playing with proxy settings from a batch file or command line, one example in this blog entry http://devpinoy.org/blogs/velocity/archive/2007/06/23/setting-proxy-settings-in-ie-using-powershell.aspx


correlation of predictions and actuals

Question: I should say that this question has nothing to do with regression. I am familar with the Sums of Squares Decomposition when there is an intercept in a regression but I'm not referring to that in this question. The setting is the following:
Suppose I have a series of actuals, $Z_t$, and two sets of forecasts, $X_t$ and $Y_t$ where $t = 1, \ldots n$.
I can calculate the sample pearson correlation coefficient, $\rho$ as described here:
https://en.wikipedia.org/wiki/Pearson_correlation_coefficient.
So, if I want to calculate the sample correlations,  $cor(X_t,Z_t) = \rho_{xz}$ or $cor(Y_t, Z_t) = \rho_{yz}$, this is straightforward.
Also, besides the sample correlation, suppose I also want to calculate $SSE_{xz}$ and $SSE_{yz}$
where $SSE_{xz} = \sum_{t=1}^{n} (X_{t} - Z_{t})^2$ and $SSE_{yz} = \sum_{t=1}^{n} (Y_{t} - Z_{t})^2$.
My question is: Suppose one has $Z_{t}, X_{t}$ and $Y_{t}$,
Can it ever be the case $SSE_{xz} < SSE_{yz}$ and $cor(X,Z) < cor(Y,Z)$.
We know that in the case of a regression with intercept, the above cannot
happen. But I'm not talking about the regression framework when I'm posing my question. In fact, it may be the case that I should be using the term cross-correlation rather than correlation but, as far as formulae, that's just semantics. Thanks.
Answer: Toy example:
<code>Z   X     Y
1   3   100
2   2   200
3   1   300
</code>
$cor(X,Z) = -1, cor(Y,Z) = 1$ while $SSE_{xz}<SSE_{yz}$
I'd say it's a matter of scale. Correlation accounts for it, while $SSE$ do not.
Another, not relying on scales example:
Take arbitrary $\varepsilon>0$ and
$X_1=Z_1, X_i=Z_i+\varepsilon$ for $i=2,3,\ldots$
$Y_i = Z_i+2\varepsilon$ for $i=1,2,3,\ldots$
$cor(X,Z)$ is slightly below 1 and $cor(Y,Z) = 1$ while $SSE_{xz}<SSE_{yz}$.
Comment: Derylo: I like your answer but the X and Y are predictions which means they are trying to be close to Z so the artificial scale difference that you constructed ( very cleverly I might add ) isn't going to happen. I'm wondering if what I described can happen in "non-difference in scale" cases.  If there a formula relating cor and SSE, outside of the regression framework, that would probably prove or disprove my conjecture ( that it can happen ). Thanks.
Comment: I added a few lines to my answer :)
Comment: Hi Derylo: Very nice example. Y is perfectly correlated Z but with a large bias. X is almost perfectly correlated with Z with a smaller bias.  I'm not sure if that's what happening in my example but atleast now I know that it can happen.  I'm checking your answer. Thanks a lot.

correlation of predictions and actuals


ASP.NET Web Api 2 Documentation splitting?

Question: In a big system, where there are an api for lots of resources, I want split documentation in some configured manner.
Like if they were different apis.
So in main page of web api I have a list of configured 'resources'.
Let's say:
Managing contacts [Here i want to expose the 'contact' resource, the 'address' resource, etc.
Managing orders [product resource, order resource, delivery resource, balance resource, etc]
Managing products [product resource, category resource, etc]
So it's easier for api consumers to understand based on the task to accomplish which methods should been taken care of.
Also, as you can see, different sections use same resources, that means if I change something on the Product resource, both documentations should (ideally) be automatically updated, including versioning info, etc.
EDIT:
    public ActionResult Index()
    {
        ViewBag.DocumentationProvider = Configuration.Services.GetDocumentationProvider();
        return View(Configuration.Services.GetApiExplorer().ApiDescriptions);
    }

this is my index action on helpcontroller, not sure what you mean.
Answer: Have you looked at HelpController under Areas\HelpPage\Controllers? If you notice the Index action of this controller displays information about all controllers.
If each of your resource is represented by a controller, you should be able to filter the ApiDescription to only show only the resources that you like to.
Comment: not sure what you mean, i edited the question with my index action.
Comment: As you can notice this index action returns all `ApiDescription` of all controllers or resources in your case. You can filter these descriptions to only show controllers which you would like to show.


Time complexity of a combination function

Question: I have this function that creates pairs from a list of numbers.  We know that there will be a total of n choose 2 iterations every time.  So does that make the time complexity O(nC2)?
or is it O(n^2)?
If it is O(n^2) why is it O(n^2)?  The function does not iterate that many times and it never will.
def find_pairs(nums):
    pairs = []
    for i in range(len(nums)):
        current = nums[i]

        for n in nums[i+1:]:
            pairs.append((current, n))

    return pairs

Comment: as `O` is worst case scenario in your case it will be `O(n**2)` reason.. your inner loop will  iterates `(n-1)` for each element `(n)` hence approximately it runs O(n**2) times..!
Answer: Time complexity isn't about exactly how many times an algorithm is run, it's how the algorithm scales.
In your case n choose 2 is equal to:
n! / (2 * (n - 2)!)

This can be simplified to
n * (n-1) / 2 = (n^2 - n) / 2

As you can see we have a 2nd degree polynomial function (quadratic). Therefore we consider the time complexity to be O(n^2) since it will scale quadratically.
Answer: The time complexity for above code is O(n^2)
It will iterate 2 times always, both the time on nums,
just after it completes current = nums[i] it will iterate again if your secn loop was out of 1st loop i.e something like this
def find_pairs(nums):
    pairs = []
    for i in range(len(nums)):
        current = nums[i]

    for n in nums[i+1:]:
        pairs.append((current, n))

    return pairs

then time complexity would have been O(n)