Computing the shape operator

Question: I am trying to compute the shape operator and Gaussian curvature for some smooth zero sets of polynomials $f$ in $\mathbb{R}^n$, oriented by $N = \nabla f / || \nabla f||$
The approach I thinking about is this (which I didn't learn from a text, so maybe there is a problem with it):

Compute the normal at a point $p$, and pick some vectors $v, w \ldots $ that are a local frame for the tangent space.
Compute $\langle \nabla_{v} N, w \rangle = \frac{1}{||\nabla f||}\Sigma_{i,j=1}^{n+1} \frac{\partial^2 f}{\partial x_i \partial x_j} v_i w_j$. (The justification for this formula: $\nabla_v \frac{ \nabla f}{|| \nabla f ||} = (\nabla_v (\nabla f)) (1/ ||\nabla f||) + NormalComponent$)
Deduce from this the matrix for $L_p(v) = - \nabla_v N$.

However, something seems to be wrong with this approach. For example, in my computation below for the sphere, I get a Gaussian curvature that is not constant.

We pick some point where $y \not = 0$ and $x \not = 0$, then $((x,y,z),-y,x,0)$ and $((x,y,z),0,-z,y)$ describes a local frame. (The first triple is the point, the next three coordinates describe the vector in the tangent space of $\mathbb{R}^3$).
Computing the matrix $L_p$ in this basis gives $1/r^2 \begin{pmatrix} x^2 + y^2 &  -xz \\ -xz & z^2 + y^2 \end{pmatrix}$, which has determinant $-y^2 / r^2$...

I am really confused. I would appreciate someone pointing out my mistake.
Comment: What is the function $f$ that you want to find the shape operator for?
Answer: Okay - I figured out my mistake. Pretty silly - I was jumping from 2 to 3 as if my choice was of an orthonormal basis, but of course it was not.

Computing the shape operator


Including the current method name when printing in Python

Question: Often times in C programs (and using GCC) I will create a debug print macro that includes the name of the current function. That is, something like:
#define DPRINTF(fmt, ...) printf("[%s] " fmt, __FUNCTION__, ##__VA_ARGS__)

When used, the current function will be prepended to each print, providing more useful debug information at runtime. For example, the following code
#include <stdio.h>

#define DPRINT(fmt, ...) printf("[%s] " fmt, __FUNCTION__, ##__VA_ARGS__)

void testfunction1(){
    DPRINT("Running %d\n",1);
}

void testfunction2(){
    DPRINT("Running %d\n",2);
}

int main(void) {
    DPRINT("Running: %d\n",0);
    testfunction1();
    testfunction2();
    return 0;
}

Would output:
[main] Running: 0
[testfunction1] Running 1
[testfunction2] Running 2

Can something like this be done in Python?
I searched around a bit and found this StackOverflow question explaining how inspect can be used to read names from the stack. However, from what I've found Python does not support macros, so the same form as my C program cannot be used.
Is there some mechanism by which this type of debug printing can be supported? I tried lambdas, but the "function name" in this case prints as "< lambda >".
Comment: its still unclear about what you are expecting
Comment: @AmeyYadav, Updated the question.
Comment: can you put the sample code of what you tried?, it is often easy to start from there. To quickly answer, yes you could , check the use of decorators in python. you could wrap a function to debug its name.
Answer: You can inspect the last frame to retrieve the caller name and the rest is simple formatting, something like
import sys

def dprint(fmt=None, *args, **kwargs):
    try:
        name = sys._getframe(1).f_code.co_name
    except (IndexError, TypeError, AttributeError):  # something went wrong
        name = "<unknown>"
    print("[{}] {}".format(name, (fmt or "{}").format(*args, **kwargs)))

def testfunction1():
    dprint("Running {}", 1)

def testfunction2():
    dprint("Running {}", 2)

def main():
    dprint("Running {}", 0)
    testfunction1()
    testfunction2()
    return 0

if __name__ == "__main__":
    main()

# prints:
# [main] Running 0
# [testfunction1] Running 1
# [testfunction2] Running 2

Answer: I would suggest not using print at all, and instead setup a logger. The logging module has a funcName attribute available for all LogRecords.
You'll then have (code taken from zwer's answer):
import logging

def create_logger(app_name=None):
    logger = logging.getLogger(app_name or __name__)
    logger.setLevel(logging.DEBUG)
    log_format = '[%(asctime)-15s] [%(levelname)08s] (%(funcName)s %(message)s'
    logging.basicConfig(format=log_format)
    return logger

LOGGER = create_logger()

def testfunction1():
    LOGGER.info("Running %d", 1)

def testfunction2():
    LOGGER.error("Running %s", 2)

def main():
    LOGGER.debug("Running %03d", 0)
    testfunction1()
    testfunction2()

if __name__ == "__main__":
    main()

which will generate something similar to:
[2017-06-13 19:41:45,677] [   DEBUG] (main) Running 000
[2017-06-13 19:41:45,677] [    INFO] (testfunction1) Running 1
[2017-06-13 19:41:45,677] [   ERROR] (testfunction2) Running 2

Comment: a much more robust answer
Answer: import inspect
import sys
def DPRINT(fmt, *args):
    print "{} {} {}".format(sys._getframe(1).f_code.co_name, fmt, args)

    # below line is another way to get the name of a calling function
    # print "{} {} {}".format(inspect.stack()[1][3], fmt, args)

def testfunction1():
    DPRINT("Running: 1")

def testfunction2():
    DPRINT("Running: 2")

def main():
    DPRINT("Running: 0")
    testfunction1()
    testfunction2()

main()

I don't know if this could be helpful
Comment: @AmeyYadav - reading the whole stack just to grab the last frame is awfully wasteful, tho.
Comment: Oh .. man. As I was reading your solution it was so obvious. If you can read the current function's name from the stack then you could also just read the caller's name from the stack ..
Comment: True indeed @sherrellbc
Comment: @zwer for obvious reasons I wasn't thinking of an optimized answer, I just new one way to do it, there could be a million more.


Reduce stacks of duplicates in an array into only one of them in c#

Question: I'll take it directly:
For example I have an array
int[] integers = {1, 2, 2, 2, 4, 5, 2, 2, 2};

And all I like is to reduce all the stacks of 2 into only one 2. I need to get this at the end:
{1, 2, 4, 5, 2};

I read about the .Distinct() method and every kind of comparers, but that method deletes all the same elements and I don't want this. I still think there shold be some certain method to do it via Linq or somethig. Thanks!
Comment: Check this out http://stackoverflow.com/questions/3350641/array-remove-duplicate-elements
Comment: If I understand you, what you want is something that does the same thing as [the Unix ``uniq`` utility](http://linux.die.net/man/1/uniq), except that it acts on the entries of an array rather than on the lines of a file.
Comment: What language are you using? There seem to be "unique" functions in many languages, but they eliminate _all_ duplicates, not just consecutive ones. Here is what someone had to do to work around this in Ruby, for example: http://stackoverflow.com/questions/4576652/how-do-you-merge-consecutive-repeating-elements-in-an-array
Comment: @David K thanks, I'm gonna check that Ruby out, I think I'm gonna be ok with that. Gonna post a refference as soon as I'm done.
Answer: Use the LINQ, Luke!
var result = integers.Where((n, i) =>
    i == 0 ? true : n != integers[i - 1]);

More concise:
var result = integers.Where((n, i) =>
    i == 0 || n != integers[i - 1]);

Comment: Exactly what I needed. Thanks!
Answer: I think .net doesn't have function for this.
So you should use simple foreach.
var result = List<int>();
foreach(var item in integers)
{
    if(!result.Any())
    {
        result.Add(item);
    }
    else if(result[result.Count() - 1] != item)
    {
        result.Add(item);
    }
}


Bash: most concise way to read a string of space into two variables

Question: I have a string variable line="foo bar". I want to read it into two variables, $foo and $bar.
My code doesn't work:
read foo bar < <($line)

This results in:
-bash: foo: command not found

Answer: read -r foo bar <<< "$line"

<(list): this is called a process substitution. The list is executed and the output is then referred to using a filename. $line expands to foo bar, bash then tries to execute foo with one argument, bar. Thus the error foo: command not found
<<< word: this is called a here string. word gets expanded and the result is supplied as a single string with a newline appended. $line expands to "foo bar" and is correctly supplied to the read command
-r: used so that read doesn't mangle any backslashes

You could also change your code like this (here string is better):
read -r foo bar < <(echo "$line")


Clearing Boost cache with drush

Question: I am testing the boost module out, it is a great performance enhancement for the site I am working on.
However I would like to be able to get boost to clear it's cache using drush. Drush cc all doesn't seem to do this. And looking in the boost module code, there doesn't seem to be a cron command for it. Am I missing something or is this currently not implemented?
Answer: Answering my own question. I was missing something.
Boost is a bit more fussy about the URL than the rest of drush when clearing the cache
drush --uri=http://my.site.name cc all

will work.
Answer: If you just want to clear Boost's cache and not any other caches:
drush --uri=http://example.com boost-cache-clear-all
See also the notes at the Drush integration patch for Boost.
Comment: Ah, I had assumed that since my patch got committed to the dev branch, that it had made its way into an official release. That only works if there's an official release after the commit. You could probably use the Drush include file, renaming it to remove the underscore, from the "patch" but still use the official release of Boost, since there are no changes to Boost necessary for the Drush functionality to work.
Comment: Thanks for this, looks like this is only in the dev release of boost for the moment, but still good to know.
Answer: If you have drush aliases configured, just do this:
    drush @name_of_alias cc all
I'm using Drush 8 and Drupal 7, but this also worked on my earlier versions.

Clearing Boost cache with drush


Can Principal Component Analysis be used on stock prices / non-stationary data?

Question: I am reading an example given in the book, Machine Learning for Hackers.
I will first elaborate on the example and then talk about my question.
Example:
Takes a dataset for 10 years of 25 share prices.
Runs PCA on the 25 share prices.
Compares the principal component with the Dow Jones Index.
Observes very strong similarity between PC and DJI!
From what I understand, the example is more like a toy to help newbies like me understand how effective a tool PCA is!
However, reading from another source, I see that share prices are non-stationary and running PCA on share prices is absurd. The sources from where I read totally ridicule the idea of calculating covariance and PCA for share prices.
Questions:

How did the example work so well? The PCA of share prices and DJI were very close to one another. And the data is real data from 2002-2011 share prices.
Can someone point me to some nice resource for reading up on stationary / non-stationary data? I am a programmer. I have a good math background. But I haven't done serious math for 3 years. I have started reading again about stuff like random walks, etc.
Answer: This piece serves to partly answer the original question and some of the questions raised in comments to @JonEgil's answer.
Financial (logarithmic) returns* are approximately $i.i.d.$ (although there is often some conditional heteroskedasticity) -- while prices are approximately random walks. Under the assumption of $i.i.d.$ observations, principal component analysis would directly generalize from sample to population (i.e. the sample principal components would be estimating the population principal components), but this might not hold under non-$i.i.d.$ observations -- see this thread. This is why it makes sense to run PCA on (logarithmic) returns rather than prices.
Ruey S. Tsay has argued for running PCA on residuals from econometric models of financial time series, since residuals are normally assumed to be $i.i.d.$ I think that this idea might be included some place in his "Multivariate Time Series Analysis with R and Financial Applications" textbook (he explained the idea to me in person, so I am not sure where it is written).
* Logarithmic return on price $P_t$ is defined as $r:=\text{log}(P_t)-\text{log}(P_{t-1})=\text{log}\frac{P_t}{P_{t-1}}$. Logarithmic returns are used for convenience in place of percentage returns $r':=\frac{P_t-P_{t-1}}{P_{t-1}}$. The convenient feature of logarithmic returns  is that you may sum up $h$ individual logarithmic returns to get the total logarithmic return over $h$ periods, while this does not hold for percentage returns. For relatively small percentage returns (which is common in finance), logarithmic returns approximately equal percentage returns as the logarithm has approximately unit slope around one.
Comment: +1, this is interesting. Can you expand a bit on what actually is a "return"? My knowledge of economics is zero; I googled and found that if price is given by $f(t_i)$ time series, then returns are defined as $\log\frac{f(t_{i+1})}{f(t_i)}$. Is that correct? If so, then why the logarithm? I would understand your argument about the relation between iid returns and random walk prices if returns were defined as differences. Apart from that, DJ is the average price, so I still don't understand why PC1 of returns should be a better match than PC1 of prices, even given your considerations about iid.
Comment: @amoeba, I added a quick explanation and have to leave now. I hope I did not make too many mistakes there. I will be back tomorrow if there are any further issues.
Comment: Thanks. I see now that returns (logarithmic returns) are essentially a derivative (first difference) of the logarithm of prices. So if the claim is that returns are iid and log prices are random walks, then it makes sense. However, I am still surprised by the Dow Jones example and would appreciate any further clarifications.
Answer: I run these types of analysis professionally and can confirm that they indeed are useful. But please make sure you analyse returns not prices. This is also highlighted by the critique in Slender Means:
<code>To perform PCA, your data have to have a meaningful covariance matrix
(or correlation matrix, but the conditions are equivalent). They analyze
stock prices, which are non-stationary time series variables.
</code>
A typical usecase in our analysis is to quantify systemic risk in the market place. The more co-movement in the market, the less of a diversification you really have in your portfolio. This can, for example, be quantified by the amount of variance described by the first principal component. Which is identical to the value of the first eigenvalue.
For financial data, one typically examines a moving window over time. Some form of decay factor that downweights older observations is useful. For daily data, anything from 20-60 days, for weekly data maybe 1-2 years, all depending on your needs.
Note that for global financial markets, with tens- or hundreds of thousands of asset prices changing continuously, one typicall can't run a 100K vs 100K  covariance matrix. Instead, typical usecase is to run the analysis per country, per sector or other more meaningful groups. Alternatively break down the return by a set of underlying factors (value, size, quality, credit ....) and do the PCA / Covariance analysis on these.
Some nice articles include Attilio Meucci's discussion on effective number of bets:
http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1358533
, and also Ledoit and Wolf's Honey I shrunk the sample covariance matrix
http://www.math.umn.edu/~bemis/MFM/2014/spring/References/lw_shrinkage.pdf
For a financially oriented introduction to stationarity, why not start with Investopedia. It's not rigorous, but conveys the main ideas.
Good luck!
EDIT: Here is a 3-stock example showing Apple, Google and Dow Jones with daily returns through 2015. The upper triangle shows correlation of return, the lower triangle show correlation of prices.

As can be seen, Apple has a higher price-correlation with Dow (bottom left 0.76) than return correlation (top right 0.66). What can we learn from that? Not much. Google has a negative price correlation with both Apple (-0.28) and Dow (-0.27). Again, not much to learn from that. However, the return correlations tell us that Apple and Google both have a fairly high correlation with the Dow (0.66 and 0.53 respectively). That tell us something about the co-movement (price-change) of assets in a portfolio. That is useful information.
The main point is that although price correlation can be just as easily computed, it is not interesting. Why? Because the price of a stock is not interesting in itself. The price change, however, is very interesting.
Comment: @claudius: The fact that PCA on prices gives something similar to Dow Jones which is the average price is not surprising at all. I'm rather wondering why PCA on returns produces a better fit. Perhaps Jon will be able to clarify.
Comment: I have not looked at the actual code run in ML for Hackers, but whenever someone say they analyse prices, 99 times of of a 100 what they actually analyse is log-returns.

For example, today the Dow is down 162 points, while Apple is down 0.88 dollars. Not only are the numbers vastly different, they even are on a different scale, index points vs money. But in pct terms 0.91% and 0.75% are comparable and the numbers you want to work with.

For some analysis, one can de-trend the data by subtracting the mean. In short term financial timeseries this is often ignored, assuming no trend.
Comment: @amoeba, To (partly) answer the questions raised in comments, returns are approximately i.i.d. while prices are approximately random walks. Principal components have their nice properties under the assumption of i.i.d. observations. This is why it makes sense to run PCA on returns rather than prices. Ruey S. Tsay has argued for running PCA on residuals from econometric models of financial time series, since residuals are normally assumed to be i.i.d. I think that might be included some place in his "Multivariate Time Series Analysis with R and Financial Applications" textbook.
Comment: Can you please expand more on the main part of the question which is about the difference between using prices vs. returns? I understand that when using prices, correlation matrix will be influenced by the non-stationarities; e.g. if all prices linearly grow, then all correlations will be strongly positive. First, why is it bad? In particular given that Dow Jones is essentially an average price and it will grow too (as PC1 will). Second, how is using returns supposed to help? AFAIK "returns" are logged ratios of neighbouring points; why is it meaningful and how is it related to Dow Jones?
Comment: thanks for your informative reply. But it doesn't answer my question. I want to understand why analysis on price is working very well for the data set in the book? And amoeba has raised a lot of valid questions.
Comment: This is an example where returns is a better fit with DJI. This is based on dataset from ML for Hackers. http://nbviewer.ipython.org/github/carljv/Will_it_Python/blob/master/MLFH/ch8/ch8.ipynb. @amoeba Even I would like to know why returns produce a better fit with DJI, considering that DJI itself is influenced by non-singularities.
Comment: @Richard and Jon. Thanks a lot for your explanations. Is there an intuitive explanation as to why PCA needs i.i.d observations??
Comment: Hey. I have been reading further about PCA and i.i.d. If all observations are independent then the observations are not correlated, right? If observations are not correlated running PCA is futile, right? PCA reduces dimensions only when some of the observations are correlated, right?
Comment: No. $i.i.d.$ is a property of a univariate series. That does not exclude cases where one series is correlated to another. Thus you *can* run PCA and obtain some dimension reduction.


Django 2.7 Rest API Validation Request

Question: I use Django 2.7 to build Rest API application, and having problem to validate/clean the request data from client for get detail transaction (Not Save/update). for example the request data trx_no cannot less than 5 char length. where's the validation class i should create? should I validate on Model.py or using forms, or in serializer?
Here's my models.py:
class mst_trx(models.Model):
    trx_no = models.CharField(max_length=20,primary_key=True)

Here's my views.py:
class views_index(APIView):

def post(self,request):
    action = request.POST['action']

    if action == 'detail' :
        resp = detail.as_view()(request)

class detail(APIView):
    def dispatch(self,request):

    ##I want to validate first before get data
    try:
        detail = mst_trx.objects.select_related().get(pk=request.POST['trx_no'])
    except mst_trx.DoesNotExist:
        raise Http404("Transaction does not exist")
    else:
        serializer = TrxDetailSerializer(detail)
        return serializer.data

And Here's my serializer.py :
class TrxDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = mst_trx
        fields = ('trx_no')

Answer: Validation logic should be in forms.py file
for e.g.
def clean_columnname(self):
    columnname = self.cleaned_data['columnname']
    if len(columnname) < 1:
        raise ValidationError('Please add some content  ...')
    elif len(columnname) > 500000:
        raise ValidationError('Too many characters ...')
    return columnname

Comment: @dennysaputra You just need to call isValid() for your form and `clean_fieldname` will be called.

`form = YourForm(request.POST)
 form.is_valid()`
For more details you can refer [official doc](https://docs.djangoproject.com/en/1.10/ref/forms/validation/)

Django 2.7 Rest API Validation Request


Unix services on Windows Server 2008

Question: Looking to remove a domain controller that is currently the NIS master for our identity management for unix service.  Need to know how to migrate the master to a different Windows server.
When you add a subordinate it always gets recognized as a unix server even if it is a Windows machine. How does one migrate the NIS master to a different Windows server?
Answer: NIS data automatically replicates to all your domain controllers through AD replication.  To migrate to a new master, you should be able to simply install the unix services for windows NIS service on the new server (a DC), and then add it and promote it to master.

Unix services on Windows Server 2008


How can I change the specific word from the text file using loops and if statements?

Question: I am doing a simple project for my first python course and I am stuck in one part which I have no idea how to continue.
So in this part user should input a vehicle id that he/she wants to rent. After putting the vehicle ID, my code starts to search for that vehicle ID in the  Vehicle.txt text file. If the code finds the VehicleID variable and also finds that it is "A" (which means available), it starts printing details for that specific car.
My Vehicle.txt text file looks like this;
XJY-604,Hyundai Getz,O,0,45.00,A
AJB-123,BMW mini,P,200,65.00,A
WYN-482,Ford Fiesta,O,0,40,A
BKV-943,Ford Ikon,P,150,60,A
JMB-535,Ford Flex,O,0,50,A
FKI-232,Fiat Egea,O,0,30,A
KLE-154,Toyota Corolla,O,0,40,A
ITO-444,Renault Clio,O,0,55,A
MAA-321,Honda Civic,O,0,70,A
IRK-948,Hyundai i20,O,0,30,A
TRY-475,Peugeot 2008,O,0,50,A
IBM-984,Skoda Superb,O,0,60,A
KRI-365,Opel Corsa,O,0,50,A
PMA-760,Citreon C3,O,0,55,A
NGT-407,KIA Sportage,O,0,60,A

So until this far, everything is fine; if the code finds the Vehicle ID (and the condition "A") then the code starts to print details as I want (if the condition is different or vehicle ID is not found it also prints appropriate error massages which are also perfectly working as I want).
My problem starts after this part:
After printing the details from the car, my code should change that specific car's condition from "A" (available) to "R" (rented) in the Vehicle.txt text file.
For example, let's say the user entered the Vehicle ID TRY-475 --> After this input, my excepted change in the Vehicle.txt text file is;
excepted change
But the actual change in the text file is;
actual change
My code looks like this;
from datetime import datetime
now = datetime.now()
dateandtime = now.strftime("%d/%m/%Y %H:%M:%S")

def rentVehicle():
    VehicleID = input("Please enter the vehicle ID you want to rent: ")
    with open("Vehicle.txt","r+") as f1:
        for line in f1:
            l = line.split(",")
            if l[0] == VehicleID and l[5] == "A\n" or l[5] == "A":
                renterID = input("Please enter your ID: ")
                startingodometer = input("Please enter the current odometer reading: ")
                print("\nCar",l[0],"is rented to", renterID,"\n")
                print("\t\t******************** Vehicle Details ********************\n")
                print("Vehicle ID =",l[0],"\t\tDescription =",l[1],"\t\tDaily Rate =",l[4],"\tStatus =",l[5],"\n")
                print("Renter ID =",renterID,"\tDate/time of rent =",dateandtime,"\tRent Starting Odometer =",startingodometer)
                f1.write(l[5].replace(l[5],"R\n"))
                print("\nRenting vehicle is successful!")
                break
             elif l[0] == VehicleID and l[5] == "R\n" or l[5] == "R":
                print("\nThe vehicle you entered is rented. Please display available cars from the main menu.")
                break
        else:
            print("\nThe vehicle ID you entered does not exist. Please enter a valid vehicle ID.")
            break
rentVehicle()

I think the problem is in line 17 ( f1.write(l[5].replace(l[5],"R\n"))). I searched for the other options but they also didn't give my excepted output in the Vehicle.txt text file. Additionally, I am not allowed to change my file name or add these lines to another file (manually or in the code) as it is restricted in my project work. I should only update the current Vehicle.txt via code. I would be very glad if someone solve this. For a beginner, these problems are really challenging sometimes. Thanks in advance.
Answer: the problem in your code is here:
with open("Vehicle.txt","r+") as f1:
    for line in f1:
        l = line.split(",")
        if l[0] == VehicleID and l[5] == "A\n" or l[5] == "A":
            renterID = input("Please enter your ID: ")
            startingodometer = input("Please enter the current odometer reading: ")
    ~~~~~~~~~~~~~~~~~~~
            f1.write(l[5].replace(l[5],"R\n"))
    ~~~~~~~~~~~~~~~~~~~
            break
        elif l[0] == VehicleID and l[5] == "R\n" or l[5] == "R":
            print("\nThe vehicle you entered is rented. Please display available cars from the main menu.")
            break
    else:
        print("nothing found")
        break

I supposed that you are not very familiar with how does the file reading work on the background ... To put it simply, there is a buffer of a specific length (for example 1028B) whihc means it is going to read 1028B of text. The reason why it is this way is that you are unable to efficiently know, how long the line will be, and also reading from a file is slow, therefore reading as much as possible in the shortest time possible is what everyone is aiming for.
Now to your code, what happend there is that your whole file got loaded into the mentioned buffer and a file pointer ended up at the end of the file.
What you should do and is recommended to do is not to rewrite the file you are currently reading (you can check out some articles about how files actually work, sorry I am not 100% sure right now whether it even lets you to write to a file that you are reading ...).
Therefore, what you need to do, is this (this is pseudocode, in order for you to do it yourself, to gain more experience :)):
with open("Vehicle.txt","r+") as read_file:
    with open("Vehicle2.txt","w+") as write_file:
        for line in read_file:
            if (your checks):
                ... (setting up)
                write_file.write(f"{l[0]},{l[1]},{l[2]},{l[3]},{l[4]},{edited_thing}")
            else:
                write_file.write(line)

// after this, you can eighter rename these files or delete the original one and then rename the other one ther:
// vehicle.txt -> temp.txt ; Vehicle2.txt => Vehicle.txt ; delete temp.txt ?

I hope this answer helps and I wish you a nice programming journey ;)
EDIT:
I just noticed that you have multiple checks there. if you do not really need to break it, I recommend you using continue which will immediatelly start the next iteration.
Comment: Hey @StyleZ and thank you for answering me! I tried to change my code as you showed me, but I got a syntax error when I did the part write_file.write(f"{l[0]},{l[1]},{l[2]},{l[3]},{l[4]},{edited_thing}"). The syntax error is --> f-string expression part cannot include a backslash (which is a totally new syntax error to me :0). And also, my code should only update the current Vehicle.txt and not write details into another one ( I am not allowed to change file names manually or add a new file as it is restricted in my project work :/ ). I should only update the current Vehicle.txt.
Comment: if you got any questions, feel free to ask :) I will gladly try to answer them (if I know the answer :D)
Comment: Hi, could you please provide the full error message (with the code as well). from what I understand is that you are trying to add there manually into the f-string `"\"` which is unfortunatelly not possible. what you can do, is create a variable `back_slash = "\"` and add it into the f-string `f"{x} {back_slash} {y}"`. I hope it makes sense. Also unfortunately, it is not possible to write into the file while reading and it is a bad practice to read the whole file into a varaible and rewrite it (I hope you can see why). Check out these 2 links for more information about the files:
Comment: https://stackoverflow.com/questions/125703/how-to-modify-a-text-file

https://stackoverflow.com/questions/14271216/beginner-python-reading-and-writing-to-the-same-file/14271376

and a small advice. if you get stuck to a similar error as you have mentioned, try googling it before asking. It will make you realise, how to google efficiently :)
Comment: Hey again @StyleZ , after trying your steps, I corrected my errors in the previous try. It is now working as you showed, but now I can't show any appropriate messages if my conditions are different, or there is no such a VehicleID (because of that else: write_file.write(line) condition is not allowing to me add new if condition before it). Also, the code creates a new file which I manually need to rename. This will not be okay with my project work because it is restricted. I need to update the current text file via code only. And from your view, I understand that it is not possible to do :/
Comment: Firstly, you can add multiple condition, since in your code, you are using break in each statement. If you do not want to stop, just continue the next iteration, you keyword 'continue'. Also this should be done using a database, since you are using ID's, where inserting is possible. Lastly, i hate to say this, but if you want to risk it ... you can create a list of lines ans edit those. But it will crash on a large files / memory errors


How to make the subscriptions module produce notifications on a screen?

Question: Really struggling with subscriptions on my site or users.
I'm currently trying the subscriptions module, but I am unable to have the user notified on the site iself. I can see it can send emails to the users which is good, but I also would like to have a little notification at the top like stackexchange has.
Anybody point me in the right direction?
Comment: Maybe subscriptions isn't the right tool? Notification module looks like it is struggling to find maintainers.
Comment: Have a look at http://drupal.stackexchange.com/questions/179158 for a potential alternative ...
Answer: Same thing I wanted to do for some kind of notification.
Finally, this was the implementation:

Added one function which returns the count and notification with HTML.
Then added Ajax request to fetch the result and place it on the notification element which is already placed in page.tpl.php
Added JS code to custom.js which works on every page of site.
See below:

But remember don't make it heavy ajax request, it may slow down your site. And remember to add JS code at bottom of page.
Also you can do one thing, put ajax request on click of the element, look what StackExchage do:

on click of notification they send request and fetch the data...


How to column bind every n rows of a vector?

Question: I have a vector that is a 1100 elements long in sets of 11, 11x1000, I would like to split the data every 11th value and add this as a column to a data frame.
An example would be as follows:
vector <- c(1,2,3,4,5,6,7,8,9,10,11,12)

such that the output would look as follows:

Race 1
Race 2
Race 3
Race 4

1
4
7
10

2
5
8
11

3
6
9
12

I think this would work with a loop but have seen some tidy verse bits that might help however am unsure how to apply them.
Please let me know if this isn't clear!
Thanks in advance
Comment: `data.frame(matrix(vector, nrow = 3))` for this data, perhaps `data.frame(matrix(vector, nrow = 11))` for your larger data. You'll likely want to change the column names using `names` or `colnames`.
Comment: concise brilliance should likely be both an answer and explained as answered questions are the coin of the realm...for others, later.
Comment: @Chris: You are right. That is why It is [accepted at SO that you answer on behalf of others taking their (hidden) answer from a comment](https://meta.stackoverflow.com/questions/251597/question-with-no-answers-but-issue-solved-in-the-comments-or-extended-in-chat). So, if you feel like answering it yourself, read the post and go ahead.
Answer: matrix accepts nrow= as an argument, so the dimensions of the data can be controlled, then data.frame(.) wrapped around that converts it into a frame.
vector <- c(1,2,3,4,5,6,7,8,9,10,11,12)
data.frame(matrix(vector, nrow = 3))
#   X1 X2 X3 X4
# 1  1  4  7 10
# 2  2  5  8 11
# 3  3  6  9 12
vector <- 1:33 # multiple of 11
data.frame(matrix(vector, nrow = 11))
#    X1 X2 X3
# 1   1 12 23
# 2   2 13 24
# 3   3 14 25
# 4   4 15 26
# 5   5 16 27
# 6   6 17 28
# 7   7 18 29
# 8   8 19 30
# 9   9 20 31
# 10 10 21 32
# 11 11 22 33


Changes in compression rate

Question: Every month I usually compress all my database dumps into a rar file.
I was very happy with the compression rate, as each compressed file was usually about 30MB, with a compression rate of 99%.
Since a few weeks ago, without having touched anything (neither in the compressor parameters nor in the dump system), the compression rate has dropped to 70% and now the compressed file occupies about 1.50GB.
Any idea why this is happening?
Thanks!
Comment: you may try with xz if it gets better ratio imho
Answer: This is probably happening due to the database containing less compressible stuff.
Generally the level of compression depends on the context. Pure text (e.g. a natural language) compresses really well, while already compressed formats such as JPEG or PNG doesn't compress at all.
You should look into what content you have in your database, and how the various content types are affected.

Changes in compression rate


Fazer com que o SonarQube com o OpenCover ignorarem algumas classes C#

Question: É possível configurar o SonarQube com o OpenCover para ignorar algumas classes do meu projeto .NET?
Answer: Adiciona a flag -filter ao comando de execucao do OpenCover para excluir tipos que pertencem a um namespace MyNamespace:
-filter:"+[*]* -[NomeDaAssembly]MyNamespace.*"

Nao tenho a certeza, mas acho que tambem se pode excluir ficheiros especificos de uma forma semelhante:
-filter:"+[*]* -[NomeDaAssembly]MyNamespace.MySpecificClass.cs"

Comment: Eu não chamo diretamente o OpenCover, tudo é feito pelo Sonar, de acordo com o arquivo sonar-project.properties. Tem como colocar esses comando "filter" no sonar-project.properties? Pela documentação do sonar, aparentemente, só dá pra excluir a nível de projeto...


Atualização de quantidade com update (Carrinho de compras)

Question: Estou criando um carrinho de compras. Este carrinho é sem usuário e senha, ou seja, ele usa apenas a sessão do próprio carrinho que é criado quando o usuário escolhe o produto. Após o cliente escolher o produto e clicar em "IR PARA CHECKOUT", o sistema faz um inserção no banco de dados dos produtos que ele escolheu (nome_produto; descrição e valor) e o código do pedido se torna a sessão do cliente. Logo, eu consigo fazer uma busca no banco de dados da sessão criada. O Código da sessão também é inerido no banco de dados, para que eu consiga fazer a busca.
Código da inserção no banco de dados:
                @$produto = $_POST['produto'];
                  if(isset($produto)) {
                      foreach ($produto as $reck) {
                        $consultaProduto = $conexao->query("SELECT * FROM produtos WHERE id = '$reck'");
                        while($exibeProdutos = $consultaProduto->fetch_assoc()){
                            $nome_produto = $exibeProdutos['nome_produto'];
                            $valor_produto = $exibeProdutos['valor'];
                            $descricao = $exibeProdutos['descricao_produto'];
                            $imagem = $exibeProdutos['imagem_produto'];
                            $pedidoReck = "200";
                            $horarioReck = date("h:i:s");
                            $pedidoLokos = "{$pedidoReck}{$horarioReck}";
                            $insereProduto = $conexao->query("INSERT INTO carrinho (numeroPedido, produto, descricao, valor) values ('$pedidoLokos','$nome_produto','$descricao','$valor_produto')");
                            $_SESSION['numero_pedido'] = $pedidoLokos;
                           /* if($insereProduto){
                              echo "Produto inserido";
                            }else{
                              echo "Produto não inserido". mysqli_error($conexao);
                            }*/

                          }
                        }

                        header("Location: carrinho.php");

                      } /*Fecha produto*/

Após isso, o cliente/usuário é redirecionado para o carrinho.php. Nele, eu faço a consulta se a sessão está criada e se estiver e ela for igual ao do inserido no banco de dados, ela ira trazer os produtos lá cadastrado.
Código completo do carrinho:
    <form action="" method="POST">

                      <?php
                         session_start();
                          header('Content-Type: text/html; charset=utf-8');
                          date_default_timezone_set('America/Sao_Paulo');
                          $conexao = new mysqli("xxxxxxxxxx","cardapio_cheirinbao","d#m14e4E","cardapio_cheirinbao");

                          if(!$conexao){

                            echo "Impossível se conectar ao banco de dados";
                            exit;
                          }
                           $pedidoLokos = $_SESSION['numero_pedido'];
                            $consultaProduto = $conexao->query("SELECT * FROM carrinho WHERE numeroPedido = '$pedidoLokos'");
                            $valorTotal = 0;
                            while($exibeProdutos = $consultaProduto->fetch_assoc()){
                                $nome_produto = $exibeProdutos['produto'];
                                $valor_produto = $exibeProdutos['valor'];
                                $valorVirgula = str_replace('.', ',', $valor_produto);
                                $valorTotal += $valor_produto;
                                $descricao = $exibeProdutos['descricao_produto'];
                                $imagem = $exibeProdutos['imagem_produto'];
                                $id = $exibeProdutos['id'];
                                $quan = $exibeProdutos['quantidade'];
?>

                       <a href="excluirproduto.php?a=<?=$id?>" class="mad-close-item2">

                            <?php

                            if($imagem){

                              echo "";

                            }else{

                            echo "";
                            }
                            ?>

                          <input type="text" value="1" readonly="" name="quantidade_produto">
                          <button type="button" class="qty-plus"></button>
                          <button type="button" class="qty-minus"></button>

                            <input type="hidden" value="<?=$id?>" name="id_produto"><?=$nome_produto;?>  (<?=$quan;?>x)

                            R$ <?=$valorVirgula;?>

<?php

                            }

                      ?>

Total do pedido: R$  <?php echo number_format($valorTotal, 2, ',', ' '); ?>   Limpar Carrinho

                        <button class="btn w-100">Finalizar Pedido   </button>

</form>

Observem que em cada produto (no carrrinho.php ), existe um campo de quantidade para que o cliente/usuário possa aumentar a quantidade:

                      <input type="text" value="1" readonly="" name="quantidade_produto">
                      <button type="button" class="qty-plus"></button>
                      <button type="button" class="qty-minus"></button>

Foi criado um SCRIPT para quando o cliente/usuário adicionar aumentar a quantidade o sistema faça um UPDATE lá na tabela dos valores e também da quantidade e apresente na tela após fazer essa atualização. Veja:
<?php

@$id_produto = $_POST['id_produto'];
@$quantidade = $_POST['quantidade_produto'];

if(isset($id_produto)):

$consultaProduto = $conexao->query("SELECT * FROM carrinho WHERE id = '$id_produto' AND numeroPedido = '$pedidoLokos'");
$atualizaValor = $consultaProduto->fetch_assoc();
$valorBanco = $atualizaValor['valor'];

$valorReal = $valorBanco * $quantidade;

$atualizaProduto = $conexao->query("UPDATE carrinho SET valor = '{$valorReal}', quantidade = '{$quantidade}' WHERE id = '{$id_produto}' AND numeroPedido = '{$pedidoLokos}'");

if($atualizaProduto){
  echo "Feito";
}else{
  echo "Desfeito";
}

endif;

?>

Contudo, quando o sistema só está fazendo a atualização do último produto.  Por exemplo: Quando eu seleciono 2 produtos, ele trás corretamente no carrinho.php. Quando eu clico na quantidade no ULTIMO produto (aumento a quantidade) e clico em "FINALIZAR PEDIDO" ele faz a alteração normalmente. Porém, quando eu tento fazer a alteração em outros produtos tirando o último ele dá a mensagem que foi feito com sucesso, mas não atualiza. Veja a foto:

Desta forma, eu não estou conseguindo achar uma solução para que o programa consiga fazer a atualização também em outros produtos além do último. Como eu posso fazer? Obrigado.
Answer: Você não está identificando os produtos que devem ter as quantidades alteradas quando o botão é pressionado.
Uma sugestão de solução seria alterar os componentes para os botões plus e minus usando um link como fez para a remoção. Por exemplo, substituir os dois buttons pelas linhas a seguir
<a href="alterarquantidade.php?a=<?=$id?>&o=plus" class="qty-plus">

<a href="alterarquantidade.php?a=<?=$id?>&o=minus" class="qty-plus">

Note

que nelas suponho a criação do script alteraquantidade.php, específico para tratar o aumento ou redução da quantidade de produtos no carrinho, mesma estratégia que você utilizou para remover. E também simulo a passagem do parâmetro o (pensei em operação) passando se a ação é de adição ou subtração (plu ou minus).
que estou usando a abordagem de a cada clique o script ser chamado e nele você deverá redirecionar para o carregamento do carrinho novamente, como já acontece com sua estratégia atual, para não realizar o refresh de página seria necessário utilizar AJAX.
Comment: Apenas uma dúvida, como eu poderia fazer para o PLUS virar um número para se multiplicar?
Comment: Uma ideia seria alterar o campo de quantidade para que permita ao usuário digitar nele (input text) e ao invés de minus e plus, colocar somente um botão alterar qtde


cannot call method 'then' on undefined sequelize error

Question: I am returning a promise inside a function and and the handling the promise outside the function but I am getting cannot call method 'then' on undefined error. Can somebody point out what am I doing wrong or how can this be fixed.
function getMeterReadingByMeterIdandDate(sequelize, Dials, Meter, Server, meter_id, date){
   getNameByMeterId(sequelize, Meter, meter_id)
  .then(function(meter){
    getServerIdByMeterId(sequelize, Server, meter_id)
    .then(function(server){
      var name = meter[0].meter_id;
      var channel = "Ch"+name.substr(-1);
      var serialNumber = parseInt(name.substr(0,12));
      console.log({name:name,channel:channel,serialNumber:serialNumber});
      var server_id = server[0].server_id;
      return sequelize.query("select SUM(?) as total from dial?s where RealReadDate <= ? and SN = ?",
      {
        model:Dials[server_id],
        replacements:[channel, server_id, date.toISOString(), serialNumber],
        type: sequelize.QueryTypes.SELECT
      });
    });
  });
}

function getStartMeterReadingByMeterIdAndBillingId(sequelize, Dials, Billings, Meter, Server, meter_id, billing_id){
   getStartDateByBillingId(sequelize,Billings,billing_id)
  .then(function(date){
    return getMeterReadingByMeterIdandDate(sequelize, Dials, Meter, Server, meter_id, date[0].start_date);
  });
}

 getStartMeterReadingByMeterIdAndBillingId(sequelize, Dials, Billings, Meter, Servers, meter.id, billing_id)
            .then(function(current_date_result){
              meter_obj.current = current_date_result[0].total;
});

I am getting cannot call method 'then' error when I function callgetStartMeterReadingByMeterIdAndBillingId  . Are we allowed to return Sequelize promises like than and then handle then else where by using the function.
Answer: The getStartMeterReadingByMeterIdAndBillingIdfunction does not return a promise based on your code example.
Assuming that getStartDateByBillingId returns a promise, you should change the code to:
function getStartMeterReadingByMeterIdAndBillingId(sequelize, Dials, Billings, Meter, Server, meter_id, billing_id){
   return getStartDateByBillingId(sequelize,Billings,billing_id)
  .then(function(date){
    return getMeterReadingByMeterIdandDate(sequelize, Dials, Meter, Server, meter_id, date[0].start_date);
  });
}

Comment: and this still may not get the result you want, because getMeterReadingByMeterIdandDate also does not return anything.


Randomization scheme for rating images and assessing inter-rater reliability

Question: Apologies for the basic question, but I'm new to the area and I'm working on a research project on rating images, and assessing the reliability of these ratings, with the following structure:
There are 973 images, each of which has to be rated 3 times. These 2919 total ratings are to be allocated as evenly as possible between 5 raters (e.g., so that a rater is unlikely to rate the same image 3 times). Each rater will rate the "goodness" of their images on a 3-point scale ("Pass", "Maybe", "Fail"). Finally, we also want to assess the inter-rater reliability of the ratings.
If anyone knows of (and how to implement) a good (or, better yet, optimal) randomization scheme to allocate the images to the raters in a way that would facilitate the assessment of the reliability of the ratings, any advice would be greatly appreciated.
Answer: If you want to calculate inter-rater reliability, you should prevent each individual rater from assigning multiple ratings to the same image.  That is, each image should be rated by three different raters. Aside from that, any randomization scheme would be fine. Maybe try to ensure that all five raters end up rating similar numbers of images (e.g., $2919/5=583.8$).
Also, be sure to use a formulation of agreement that allows for multiple, different raters. A generalized formula for agreement, Fleiss' kappa coefficient, or Bennett et al.'s S score with ordinal weights would work well.


WP7: Questions regarding Touch Gestures

Question: I am using the Silverlight Toolkit for Windows Phone 7 (http://silverlight.codeplex.com/). What I would like to do is check for a flick on a text block. On a flick up I want to increment a value and on a flick down I want to decrement the same value.
Answer:
<TextBlock Text="0">
    <toolkit:GestureService.GestureListener>
        <toolkit:GestureListener Flick="GestureListener_Flick" />
    </toolkit:GestureService.GestureListener>
</TextBlock>

private void GestureListener_Flick(object sender, FlickGestureEventArgs e)
{
    //use e.Direction to determine which way
}

WP7: Questions regarding Touch Gestures


Statistics for posts from unregistered versus registered accounts

Question: This request stems from a related discussion, Banning Unregistered Users. According to a similar question on Meta.SO, the registered/unregistered status is not available in the SE data explorer, so I'm requesting summary statistics similar to the ones provided in Meta.SE and Meta.ServerFault. Ideally, the statistics would be for at least the past year as opposed to the past 60 days.
To be specific, I'll copy verbatim the request at Meta.SE, since mine is essentially the same:

I would like to have statistics for the quality of posts coming from
unregistered versus registered accounts on my site.
It is my suspicion that people who are willing to put out the effort
to register an account will also put more effort into writing good
questions; I'd like to see some evidence for or against this.
I also suspect that on my site the vast majority of good questions and
answers come from registered users, but again I'd like to see some
data.
Is this already possible through the Data Explorer? If so, how? If not
consider this a feature request.
Comment: I am adding status review tag to this question. The previous questions you linked were answered by CM not moderators. To my best knowledge we moderators do not have access to breakdown by registered/unregistered users, and as moderators we also have to agree to privacy policy and I am not sure if sharing this would still be allowed (since the posts are old and from pre-GDPR era so I would assume that back then privacy policy was less strict - although I have no law background so it is just my guess). The status-review tag should bring this to the attention of CMs
Comment: Acknowledging this is on the CM backlog — we'll get back to you once this is assigned to one of us :)
Comment: Apologies if this is a very basic question, but how is it possible to have an account but be unregistered? It's many years since I opened my own account so I don't recall the procedure.  In the Help Centre there is information on accounts but I couldn't find anything about registration.
Comment: @AdamBailey: On an unregistered user's page, you can see a mark that indicates that status (registered users won't have that mark). Here is an example: https://economics.stackexchange.com/users/30948/user30948.  See also https://meta.stackexchange.com/q/68524/243394.
Comment: It looks like our local troll is registering accounts now...
Comment: @BrianRomanchuk: Yeah I noticed. Maybe they saw my meta post.
Answer: Please let me share stats on registered and unregistered users' posts for the last 60 days. Below one can see almost the same data as by links in the question. I defined a "bad" post as one that has been closed, deleted, or with a negative score.
Questions
Registered Unregistered Registered Badness Unreg Badness PctRegBad PctUnregBad
---------- ------------ ------------------ ------------- --------- -----------
448        47           182                27            40.63     57.45

Answers
Registered Unregistered Registered Badness Unreg Badness PctRegBad PctUnregBad
---------- ------------ ------------------ ------------- --------- -----------
536        13           136                7             25.37     53.84

Comment: by the way just out of curiosity does this account for the accounts that were later discovered to be socks and merged with main account or it does not distinguish between those? I mean are those socks counted separately or after they are merged with main account only the one counts?
Comment: @1muflon1 Good question. Those that were merged are counted as one, those that were deleted do not represented in the data above at all.


Is this quotient topology possible?

Question: Consider the set $\mathbb Z\times[0,1]$ and enumerate the rationals $\mathbb Q=\{q_n:n\in \mathbb Z\}$.  For every $n$ identify the point $(n,0)$ with $(q_n,0)$.   Is there a natural topology (separable metric) on this set so that at height $1$ there is just a discrete point set, and at the height 0 there is the rationals, and  each 'vertical' interval is in the standard topology as a subspace?
This is hard to draw so also is there a better way of describing this space?
Comment: Do you mean $q_n$ instead of $(q_n, 0)$? I assume you constructing a quotient of $\mathbb Z \times [0, 1] \sqcup \mathbb Q$.
Answer: The space is homeomorphic to
Q×{0} $\cup$ Z×{0}.
a subspace of the real plane.
Answer: Let $X = \mathbb Z \times [0,1] \cup \mathbb Q \subset \mathbb R^2$ as a set, and define a metric on $X$ by
$$ d((x,y), (x',y')) = \begin{cases} |y-y'| &: x=x' \\ |x-x'| + y + y' &:\text{otherwise} \end{cases} \,. $$
I believe this gives your space. It should be easy to check that $X \cap \mathbb Q^2$ is a countable dense subset.

Is this quotient topology possible?


Logistics regression decision categorical variable makes huge difference in Kaggle-Titanic problem in R

Question: I have this linear model:
fit = glm(Survived ~ Pclass + Sex + Age + SibSp + Parch + Fare,
          data=passengers, family=binomial)
summary(fit)

Coefficients:
         Estimate Std. Error z value Pr(>|z|)
(Intercept)  5.318162   0.571693   9.302  < 2e-16 ***
Pclass      -1.175648   0.145979  -8.054 8.04e-16 ***
Sexmale     -2.760823   0.199952 -13.807  < 2e-16 ***
Age         -0.043866   0.008220  -5.336 9.49e-08 ***
SibSp       -0.428252   0.106963  -4.004 6.24e-05 ***
Parch       -0.099051   0.118328  -0.837    0.403
Fare         0.002587   0.002362   1.095    0.274

So according to the Z score I can say that the decision variables Pclass, Sexmale, Age, SibSp deal a huge part in deciding whether the depending variable will be 0 or 1.
Now I change the fit to the following (added Title):
fit = glm(Survived ~ Pclass + Sex + Age + SibSp + Parch + Fare + Title,
          data=passengers, family=binomial)
summary(fit)

Coefficients:
          Estimate Std. Error z value Pr(>|z|)
(Intercept)  3.458e+01  1.906e+03   0.018  0.98552
Pclass      -1.108e+00  1.556e-01  -7.123 1.06e-12 ***
Sexmale     -3.180e+01  1.906e+03  -0.017  0.98669
Age         -3.110e-02  9.574e-03  -3.249  0.00116 **
SibSp       -6.079e-01  1.250e-01  -4.862 1.16e-06 ***
Parch       -3.614e-01  1.346e-01  -2.685  0.00726 **
Fare         4.168e-03  2.573e-03   1.620  0.10531
TitleDr     -6.257e-01  1.691e+00  -0.370  0.71142
TitleLady   -1.605e+01  1.452e+03  -0.011  0.99118
TitleMaster  2.541e+00  1.552e+00   1.637  0.10163
TitleMiss   -2.982e+01  1.906e+03  -0.016  0.98752
TitleMlle   -1.642e+01  2.356e+03  -0.007  0.99444
TitleMr     -9.856e-01  1.439e+00  -0.685  0.49339
TitleMrs    -2.904e+01  1.906e+03  -0.015  0.98784
TitleMs     -1.498e+01  3.064e+03  -0.005  0.99610
TitleRev    -1.576e+01  9.616e+02  -0.016  0.98692
TitleSir    -4.003e-01  1.705e+00  -0.235  0.81438

So now my model is much "weaker" in a sense that I have more weak decision variables and the Sexmale is also "overshadowed" with the categorical Title variable.
Could someone tell me the reason? Also, please help me deciding if the new model is really weaker than the previous one or am I missing some fundamental thing here?
Comment: As you stated yourself, variables are not really independent and some of them "shadow" others. Sex itself is a strong predictor, but in presence of more fine-grained Title* variables it loses some of its importance. However, many "weaker" variables may give better results than few "stronger". That's why I proposed to evaluate models first. In general, if variables are highly correlated, coefficients may not really reflect importance of features.
Comment: Why don't you run cross validation and see what model gives better prediction?
Comment: I will but testing the model comes after fitting it and I want to understand why are the scores so different? Or maybe they don't really matter after all?
Comment: above is a good point. but the use of "weaker" is also incorrect, or rather I don't understand the logic behind its use here. You've provided no measures of model performance, how are you comparing models?
Comment: Ok, so based on the above 2 models *without* measuring, what exactly can we infer?
Comment: (1) I'd look at how coefficients change. The Greenland (10% to) 20% rule of thumb isn't unreasonable for confounding. (2) It does look like Title and MaleSex are correlated. Interesting to see how the SE inflates with the addition of Title (essentially you're doing a VIF? - there might be a function for this in R). (3) But whether the addition of Title improves or weakens model you can't tell. (4) I'm not sure how big the sample size is, you're adding a few degrees of freedom
Comment: "The Greenland (10% to) 20% rule of thumb isn't unreasonable for confounding." -> I'm sorry but I didn't get this at all, what did you wanted to say here? You mean the SE of SexMale, right? Sample size consists of 891 rows so I'd say it's enough
Answer: This is a version of a frequently asked question.  The answer is that Title is correlated with the other variables that are already in the model.  As a result, the estimates for the variables in the model can change when Title is added.  The basic story is discussed in many places on CV, but if you want a generic introduction, it may help you to read my answer here: Is there a difference between 'controlling for' and 'ignoring' other variables in multiple regression?
Comment: Thank you, the answer you linked was very helpful. The indicator for correlation is the fact that adding Title in the model greatly affected other variable's z score rigth? Still I'm confused about the z score then. Should I care about it? What should indicate in my case that I _might_ get a better fit by using the second fit?
Comment: If you want to know if the fit is better, take a look at measures of fit for both models. A common measure is the area under the ROC curve (AUC). If you are wondering about the models' out of sample performance, you can cross-validate to get estimates of out of sample AUCs. I wouldn't worry too much about the z-scores in either case.


bash command - using for i in `ls` with an if statement

Question: I'm trying to clean up some directories that are all named in sequence 1001, 1002, 1003 and I can't seem to get this script to work to delete directories with a value less than a number
Contents of the DIR
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014

My command
for i in `ls`; do if (( $i < 1011 )) then echo rm $i -rf; done

but I get the error
-su: syntax error near unexpected token `then'

Can anyone point me in the right direction?
Comment: for starters, syntax of for needs 'do'. i.e `for i in *; do`
Comment: Additionally, there's no need to run `ls`; just use a glob: `for i in *; do ...; done`.
Comment: I've tried with an without do but I've edited the question so everyone doesn't just jump to that conclusion
Comment: @sputn1ck well, `if` needs `then`and `fi` too. Have you looked at even one other bash script ever? I'm not trying to be rude, but there's probably like a hundred bash scripts on your machine. Source: `/etc/`.
Answer: for i in *; do [ $i -lt 1011 ] && rm -fr $i; done

does the job.
Note: this really removes the files and does not just print the remove commands.
Comment: I would have preferred arithmetic context instead of [ x -lt n ], and I think you are missing a semicolon, but this solution is on the right track. `for i in *; do (( i < 1011 )) && rm -rf "$i"; done`
Comment: Thank you for the hint with the semicolon - was obviously a copy&paste error.
Answer: Looping over ls is bad, as explained here. Instead, use find, like so:
find . -regex '\./10[01][0-9]' -exec echo rm '{}' -rf \;

Answer: try
for i in `ls`; do if [ $i -lt 1011 ]; then echo rm $i -rf; fi; done

edited
Comment: true, it had other problems like missing 'fi', missing semicolon
Comment: that returns -su: [: -it: binary operator expected
Comment: that could be because you misspelled it, try with -lt not -it :)
Answer: do

that's the reason.
for i in `ls` ; do whatever ; done


Tipo numérico, não consigo fazer um range

Question: Boa tarde. Estou fazendo um simples range, e me retorna NA. Alguma dica?
is.numeric(df_1$VLR_FTRMTO)
#[1] TRUE
range(df_1$VLR_FTRMTO)
#[1] NA NA
head(df_1$VLR_FTRMTO)
#[1] 36627192 13165967 63455580 10001774 16173720 75503974
typeof(df_1$VLR_FTRMTO)
#[1] "double"

Comment: Tente `range(df_1$VLR_FTRMTO, na.rm = TRUE, finite = TRUE)`.
Answer: Basta ter um NA no vetor para que range retorne c(NA, NA).
O exemplo mínimo é esse.
vetor <- c(1, NA, 3)
range(vetor)
# [1] NA NA

Para corrigir isso, use o argumento na.rm. Assim
range(vetor, na.rm = TRUE)
# [1] 1 3


Why is running split tests until statistically significant a "bad thing"? (Or is it?)

Question: I read this article on "how not to run an A/B test".
And I still don't understand what exactly the author's reasoning is. Can someone dumb it down for me?
I think what it might be saying is that reading the results of my split tests over time misleads me. I want to be able to understand this well enough that I can explain it to others, though.
Any help?
Answer: It's the "best two out of three" phenomenon.  You know the joke:

"Let's flip for it."
"OK, go!"
"Oops, I lost.  How about flipping two more times, with the winner being the best of the three total times?"

Significance testing is exactly like coin flipping (but with biased coins, usually).  If you run a short test and it's not significant, maybe you can achieve significance (partly through luck) by prolonging the testing.
The converse of this (I'm tempted to say the "flip side" of this :-)) is that if you plan to conduct a certain number of tests and happen to see a "significant" result early, that's also not dispositive.  It's analogous to the reverse of our first contest:

"Let's flip for it.  Best two out of three?"
"OK, go!"
"Ha, I won the first flip, so I win!"

Having said that, note that there are versions of testing which allow you to monitor the (nominal) significance as you go along.  These work like ending a contest early when it gets too one-sided, so-called mercy rules.  If, in the early going, it becomes extremely obvious that a difference is real, you can save time and effort by ending the testing.  These are called sequential hypothesis testing procedures.  A good case could be made that these should be your standard way of conducting A-B tests, because in the long run you will spend less time and effort overall.


Passar model genérico para controller

Question: Meu projeto segue o seguinte modelo:

Em meu Controller possuo o seguinte:

Notei que poderia estar usando esse ActionResult de forma dinâmica. Minha view é tipada.
Gostaria de saber se há como passar o tipo da minha view pro model ou então algum meio de receber dinamicamente o model em meu controller. Sendo no exemplo, meu model "GrupoHomogeneo".
Em resumo, minha intenção é passar o nome do model e de alguma forma, criar algo que retorna o model filtrado pelo nome em minha ActionResult, como no caso de um System.Object
"Exemplo" do que eu quero:
        var Nome = "GrupoHomogeneoEF";
        var bdModel = new (Nome)(contexto);

Comment: Qual o objetivo disso?
Comment: @CiganoMorrisonMendez Reutilizar a mesma ActionResult para mais de um model
Comment: Tipado não dá. Os *Models* possuem um ancestral comum?
Comment: Sim sim. Apenas para constar, posso alterar a minha arquitetura para se adaptar a algum meio de conseguir fazer o que quero
Answer: Ainda não entendi o que você quer fazer, mas a View aceita por padrão o seguinte:
@model dynamic

Ou seja, você pode sempre passar qualquer coisa.
Claro que isso tem consequências. Você precisa ficar conferindo se a propriedade de Model existe:
@if (Model.GetType().GetProperty("propriedade") != null) { ... }

Eu faria também um Controller genérico:
public abstract class Controller<T> : System.Web.Mvc.Controller
    where T: class, new() { ... }

E a Action GrupoHomogeneo:
public virtual ActionResult GrupoHomogeneo(T objeto, FormCollection collection) { ... }

Ou ainda, você pode definir um ancestral comum:
public abstract class ModelAncestralComum { ... }

E restringir o Controller genérico:
public abstract class Controller<T> : System.Web.Mvc.Controller
    where T: ModelAncestralComum, new() { ... }

Comment: Acredito que o Controller genérico me ajudaria. Tentei aqui mas obtenho erros, você poderia colocar a minha estrutura no seu exemplo?
Aplicando     `public abstract class WebController : Controller
    where T: class, new() { Aplicacao.Core.RepositorioEF.Base.Repositorio}` recebo mensagem "Invalid token '}' in class, struct, or interface member declaration"
Comment: Sim, edite sua pergunta colocando o código como texto que eu altero pra você.
Answer: Bem, pelo que entendi você quer tornar seu controller generico e ter uma action generica, mas a view continuará a ser especializada.
Abaixo é uma sugestão bem direta ao seu ponto, mas teria N outras melhorias que poderiam ser feitas, você poderia ler este artigo para ter mais informações.
public class GenericController<TObjeto, TRepositorio> : Controller
    where TObjeto : ObjetoBase, new()
    where TRepositorio : RepositorioEFBase, new()
{
    [HttpPost]
    public virtual ActionResult AcaoGenerica(TObjeto objeto, FormCollection collection)
    {
        var repositorio = new RepositorioEFBase(contexto);
        ...
        return RedirectToAction(collection["ReturnView"], objeto);
    }
}

public class GrupoHomogeneoController : GenericController<GrupoHomogeneo, GrupoHomogeneoRepositorioEF>
{
}

public abstract class ObjetoBase
{
    public int ID {get; set;}
}

public class GrupoHomogeneo : ObjetoBase
{
    public string Campo1 {get; set;}
}

public abstract class RepositorioEFBase<TObjeto>
    where TObjeto : ObjetoBase, new()
{
    private DbContext _contexto;
    public RepositorioEFBase(DbContext contexto)
    {
            _contexto = contexto;
    }

    //utilize esse DbSet para os seus metodos genericos
    internal IDbSet<TObjeto> DbSet { get { return _contexto.Set<TObjeto>(); } }

    //metodos genericos do repositorio
}

public class GrupoHomogeneoRepositorioEF : RepositorioEFBase<GrupoHomogeneo>
{

}

Passar model genérico para controller


Scatterplots multiple columns in rstudio

Question: i have the following data:
ID  VALUEA  VALUEB  TIMEA  TIMEB
0   4.3      2.1.   6.1    7.2
1   4.6      6.4.   4.1    2.2
2   4.4      3.1.   2.1    5.2
3   6.3      2.5.   4.1    7.2
4   9.3      9.1.   6.1    1.2

And i need to represent the data like this in Rstudio:
https://www.subeimagenes.com/img/imagen-2183442.html
The axis x is the identifier and the y is the time a and time b
I need to represent the data ordered by the time
Anyone know how to do that, i followed many tutorial but any of these helped me.
Thanks in advance
Answer: I'm not quite sure if this is what you are looking for but if you want to plot 20 points with 4 distinct categories then the following will work:
Data
df <- data.frame(ID = c(0:4),
           VALUEA = c(4.3,4.6,4.4,6.3,9.3),
           VALUEB = c(2.1,6.4,3.1,2.5,9.1),
           TIMEA = c(6.1,4.1,2.1,4.1,6.1),
           TIMEB = c(7.2,2.2,5.2,7.2,1.2))

Convert to long format using tidyr::pivot_longer and merge the categorical variables of 'VALUE' and 'TIME' together using tidyr::unite
library(tidyr)
library(dplyr)

df_long <- df %>%
  pivot_longer(c(VALUEA,VALUEB),
               names_to = "VALUE_TYPE",
               values_to = "VALUE",
               names_prefix = "VALUE") %>%
  pivot_longer(c(TIMEA,TIMEB),
               names_to = "TIME_TYPE",
               values_to = "TIME",
               names_prefix = "TIME") %>%
  unite(VALUE_TIME, c(VALUE_TYPE, TIME_TYPE), remove = FALSE) %>%
  select(ID, VALUE_TIME,VALUE,TIME)

Plot using ggplot2
library(ggplot2)

df_long %>%
  ggplot(mapping = aes(VALUE, TIME, shape = VALUE_TIME)) +
  geom_point()

Result
Comment: perfect answer!! if i need to sort the times how can i do it?
Comment: How would you like to sort the times out?


Activeadmin Resource Names

Question: this is a bit of a beginner's question, but I've searched everywhere and can't seem to solve it.
I'm using Rails and ActiveAdmin, and I've set up internationalization to use my es.yml locale.
So far so good.  The admin interface shows up nicely in Spanish, as do error messages, dates, etc.   Even the forms pick up the names of the models and the attributes (so formtastic is getting the translations OK).  I have only one locale - Spanish:
config/initializers/i18n.rb
#encoding: utf-8
I18n.default_locale = :es

LANGUAGES = [
  [ 'Español', 'es' ]
]

I have a problem with getting the resource names translated in the ActiveAdmin interface, though.  At the top of the page, for example, it says "Users", "Estimates", etc. instead of "Usuarios", "Cotizaciones".
I can solve this by registering the classes like this:
ActiveAdmin.register User, :as => "usuario" do
...
end
but then I get admin_usuarios_path, admin_usuarios_url, /admin/usuarios etc. which I find very very ugly.  I would rather use English internally.  The ActiveAdmin source for active_admin/resource/naming says it should be picking up the model's human_name, which is correctly being read from the localization file:
(in the console)
User.model_name.human.titleize
=> "Usuario"

So why does "Usuario" not show up on the menu bar, but "User"?  I'm a bit mystified here. I must be missing something really simple.
Thanks in advance!
Kyle
Answer: As mentioned in this issue : https://github.com/gregbell/active_admin/issues/434
Your initializer should look like this:
config/initializers/i18n.rb
I18n.load_path += Dir[Rails.root.join('config', 'locales', '*.{rb,yml}').to_s]
I18n.locale = :es
I18n.default_locale = :es
I18n.reload!

Active Admin's support for i18n is not very complete nor stable at present (v0.3.4) but it should get better in the next few releases.
Comment: Thanks Jean-Do, that worked! I still have some awkward pluralizations, but that's probably my fault, haven't really looked into the inflectors yet.
Answer: There must be something in the controller overriding the default locale. If a locale parameter is set then it becomes the default for the session. You could try clearing your cookies, however somehow the locale was set to another value you can try forcing it to Spanish by adding a GET prarmeter to your URL however other post parameters may override it.
You can set the locale parameter by adding a parameter to the URL. Try something like www.myapp.com/controller/action?locale=es or www.myapp.com/controller/action?parameters_from_active_admin=foo&locale=es
If that dosnt work for you take a look at the Rails console and look at the parameters provided to the application? Is there a locale parameter set to something other than es?
For more information see the Rails i18n guide.
Comment: Thanks @Devin. It doesn't seem to be an issue of another locale being present.  When I load the site in development mode, it fails to load the translations until I modify one of the ActiveAdmin files (under `app/admin`) - afterwards it works!  (ruby 1.9.2, rails 3.1.3, ActiveAdmin 0.3.3) Simply touching the files does not have the same effect.  More likely a caching issue?  The deployed site behaves the same (using passenger/apache) which is unfortunate.
Comment: Hmm, yeah whats the caching layer look like? I would figure that the i18n locale would be taken into account when caching content...

Activeadmin Resource Names


Adding matrices based on row and column designation

Question: I am sure the answer to this is up somewhere, but I don't think I've been using the right search terms.
Here is my issue.  I have multiple matrices (I will simplify to just two here), where each row is a uniquely labeled individual (some of which are shared between matrices, and some of which are not), and common column headings that are shared.
For example:
first<-matrix(rbinom(20,1,.5),4,5)
first[,1]=c(122,145,186,199)
colnames(first)<-c("ID",901,902,903,904)
first
      ID 901 902 903 904
[1,] 122   1   0   0   0
[2,] 145   0   0   0   1
[3,] 186   0   0   1   1
[4,] 199   1   0   0   0

second<-matrix(rbinom(30,1,.5),6,5)
second[,1]=c(122,133,142,151,186,199)
colnames(second)<-c("ID",901,902,903,904)
second
      ID 901 902 903 904
[1,] 122   0   1   1   1
[2,] 133   0   0   0   1
[3,] 142   1   1   0   1
[4,] 151   0   1   0   0
[5,] 186   1   0   1   1
[6,] 199   1   0   0   0

I would like to add 'first' and 'second' together based upon the 'ID' and column names.  This should result in a matrix with 7 rows (since there are 4 IDs in the 'first' matrix, and 3 new and 3 old IDs in the 'second' matrix: "122,133,142,145,151,186,199"), and the same number of columns.
In this example, the result I would want would be:
      ID 901 902 903 904
[1,] 122   1   1   1   1
[2,] 133   0   0   0   1
[3,] 142   1   1   0   1
[4,] 145   0   0   0   1
[5,] 151   0   1   0   0
[6,] 186   1   0   2   2
[7,] 199   2   0   0   0

Answer: Original answer
Building on the approach from @RYogi where you use rownames and colnames to describe your matrix, I propose the following:
res <- rbind(first,second)
res <- tapply(res, expand.grid(dimnames(res)), sum)

All rows which have equal rownames will be summed.
When using data frames
If your input is a data.frame, the above will not work, as a data.frame must not have any duplicate row names. Another approach wich works there as well this:
rowsum(rbind(first, second), c(rownames(first), rownames(second)))

This approach will work on matrices as well. As it only takes one line, you might consider it simpler. I guess it might be more efficient as well, as it is less general than tapply. You could adjust this solution to the data format from your question, where the identifiers are in a separate column:
rowsum(rbind(first, second)[,-1], c(first[,1], second[,1]))

Note that the result would still have named rows, not a column containing those names.
Funny thing is, I accidentially read about rowsum while looking for rowSums in a rather complicated approach for the data.frame version of this problem here. Lucky me.
Additional hints
If you find the resulting names Var1 and Var2 for the dimensions confusing, you can remove them using
names(dimnames(res)) <- NULL

If your data really is in the format you describe, with the row names in the first data column, you can change them to proper row names using these commands:
rownames(first) <- first[,1]
first <- first[,-1]

Comment: @user1399311, could it be your original data is stored in data frames instead of matrices? It appears that they exhibit the behaviour you describe, as duplicate row names aren't allowed for a data.frame. You could convert them matrices, but I'll edit my answer to provide a better solution.
Comment: I'm not sure why, but when I used rbind on my real data set (where I used ID as the rownames), the duplicate rownames had a number appended at the end of them.  For example, if ID# 165320128 showed up 3 times, one row would be '165320128', the next '1653201281', and the last '1653201282'
Answer: I set up your problem slightly differently:
first <- matrix(rbinom(16,1,.5),4,4)
rownames(first) <- c(122,145,186,199)
colnames(first) <- c(901,902,903,904)

second <- matrix(rbinom(24,1,.5),6,4)
rownames(second) <- c(122,133,142,151,186,199)
colnames(second) <- c(901,902,903,904)

The matrices now have named rownames
> first
    901 902 903 904
122   1   0   0   1
145   1   0   0   0
186   0   0   1   1
199   1   0   1   1
> second
    901 902 903 904
122   1   1   0   0
133   0   0   1   1
142   1   0   1   0
151   1   0   1   1
186   0   1   0   1
199   0   0   0   0

Now it is easy to do set operations on the row names:
SumOnID <- function(A, B){
  rnA <- rownames(A)
  rnB <- rownames(B)

  ls.id <- list(ids = intersect(rnA, rnB), #shared indices
                idA = setdiff(rnA, rnB),   #only in A
                idB = setdiff(rnB, rnA))   #only in B

  do.call(rbind,
    lapply(names(ls.id), function(x){
      if (x == "ids") return(A[x,, drop = F] + B[x,, drop = F])
      if (x == "idA") return(A[x,, drop = F])
      if (x == "idB") return(B[x,, drop = F])
    }))
}

Lets try it:
> SumOnID(first, second)
    901 902 903 904
122   2   1   1   1
186   1   1   0   1
199   2   1   1   0
145   1   1   0   1
133   1   0   1   1
142   1   0   1   0
151   1   1   1   1

Answer: I was looking for a solution without a "for" loop using builtin functions without  success.
So here is my approach
set.seed(1) # make it reproducible
first <- matrix(rbinom(20,1,.5),4,5)
first[ ,1] <- c(122, 145, 186, 199)
colnames(first) <- c("ID", 901, 902, 903, 904)

second <- matrix(rbinom(30, 1, .5), 6, 5)
second[ ,1] <- c(122, 133, 142, 151, 186, 199)
colnames(second) <- c("ID", 901, 902, 903, 904)

first

      ID 901 902 903 904
[1,] 122   0   1   1   1
[2,] 145   1   0   0   1
[3,] 186   1   0   1   0
[4,] 199   1   0   0   1

second
      ID 901 902 903 904
[1,] 122   0   0   1   1
[2,] 133   0   0   0   1
[3,] 142   1   1   1   0
[4,] 151   0   1   1   0
[5,] 186   0   1   1   1
[6,] 199   1   0   1   1

## stack them rowise
mat <- rbind(first, second)

ind <- unique(mat[,"ID"])

result <- matrix(nrow = length(ind), ncol = 5)
result[,1] <- ind

for (i in seq_along(ind)) {
    result[i,-1] <- colSums(mat[mat[ ,"ID"] == ind[i], -1, drop = FALSE])
}
colnames(result) <- colnames(mat)

result
      ID 901 902 903 904
[1,] 122   0   1   2   2
[2,] 145   1   0   0   1
[3,] 186   1   1   2   1
[4,] 199   2   0   1   2
[5,] 133   0   0   0   1
[6,] 142   1   1   1   0
[7,] 151   0   1   1   0


How can I stop my app from being lucky patched?

Question: Is there a way to stop my app from being lucky patched or hacked? What people are doing because the app is becoming a little more popular is using lucky patcher to remove adverts?
I have read this. What I want to know, is this code still applicable? Because this post was from 2012. Is it really as simple as if packagename changes kill the app? Can the app still be hacked using the lucky patcher? And if it is no applicable, what can I do to protect my app from these sort of hacks?
How lucky patcher works? I was looking for a copy to trail it, but I had trouble locating a real version.
Edit
So I managed to find a copy of the allusive lucky patcher, and the fact of the matter is the app is an absolute joke. It removes signing removes adverts can manipulate code, remove permissions. How can I defend against that?
I have seen while researching, that one of the best ways to protect against attacks of this kind is to use a Key/Value pair and give the user a token, as the app is installed or first run. Then send the key to my server, and every time the user opens the app, my server then asks for that key. If the key is diff or not present then close the app.
The answer here would be great, but how do I make sure this number is different for every install, except for clones or copies?
Edit
Just found this.
Comment: OK so far I've figured that they try loads of really sneaky tactics to get past the package name code. Also that they do things like break the  receiver or hide the advert with a black box.
Answer: It seems that all these hacking tools modify the java machine signature verify so all the verify results are successful.
To prevent my app from running on hacked devices, I verify the signature of a random byte array with a fake signature, that always must fail on signature verify but if the result is ok then system has been modified and I close the app.
Also as Google recommends it's better to verify purchases signature in a external server :
https://stackoverflow.com/a/48531877/7690376


How can i declare a boolean variable in class in c++

Question: i want to know how can i declare a variable that contain boolean in it in the class section like as
  class account {
  char           itemName[50];
  double         actualPrice;
  bool empty= false;
  public:
  void           create_account();
 void           displayRecord() const;
 void           drawLine3(int n, char symbol);
  };
 void
  account::create_account()
  {
 do{
   cout << "Type the name of Item " << endl;
   cin.getline(itemName, 50);
 }while(itemName!=empty);
  cout << "Actual price :" << endl;
  cin >> actualPrice;
cout << endl;
cout << "Item Name :-> " << itemName << endl;
 cout << "Actual Price :->" << actualPrice << endl;
 }

Comment: What is your question here? are you stating that your attempt doesn't work? if so, what errors are there? by the way you can't initialise class members like you've done they should be done in the member initialiser in the ctor
Answer: You should have a constructor to initialize class members:
class account {
    char itemName[50];
    double actualPrice;
    bool empty;
public:
    account() : empty(false) {} // this initializes the 'empty' variable to 'false'.
    void create_account();
    void displayRecord() const;
    void drawLine3(int n, char symbol);
};

Answer: You cannot, except if your compiler is C++-11 compliant (in that case the syntax you wrote is correct), otherwise you should add a constructor that sets inital values for the variables that need an initialization:
class account {
  public:
    account() : itemName(""), actualPrice(0.0), empty(true) {}
    [...]
};

PS: if your compiler is GCC or CLANG you can enable C++-11 compatibility through the command line switch -std=c++11


SPSS ANOVA or MANOVA or huh?

Question: Me again asking the silly questions - this might belong here as I've been told it may belong in a software section somewhere..? Which I have still been unable to find.
Here is a screenshot of my data:

Thanks to an awesome answer to my last question I was able to calculate the variable I wanted - which is labeled YrmthASpsec (in screenshot). This is the percentage of time spent in each feeding event on a monthly basis (year>month) by age-sex category.
No what I would like to do is compare this via ANOVA - however I am having much troubles.
I would like to compare the mean percentage on a monthly basis for each age-sex category by plant part. So... compare mean % of time of fruit consumption (number 1) between age-sex classes for April 2002 for example.
I have fiddled with this for a while but with no success.
Need more info? Just ask :)
EDIT1
I am seeking to determine whether there is a significant difference in dietary composition between age-sex categories.
Furthermore I am also looking at nutritional composition (macro) so protein, lip and sugar across age-sex classes.
So looking for the best way to do that using the data presented above. Most sources I have consulted use time as a proportion as it indicates importance/investment in a food item.
Comment: If you can frame your question clearly as a statistical one (rather than simply 'what commands do I need to do X'?) then it definitely belongs here. If it's effectively a 'what commands' question, suitable places for help on using stats packages are listed [here](http://meta.stats.stackexchange.com/questions/793/internet-support-for-statistics-software); the specifc-to-SPSS answer is then [here](http://meta.stats.stackexchange.com/a/807/805)
Comment: As a general comment on your problem, with compositional data, including "percentage of time spent in activity" type DVs, it's very common to have skewness (since those percentages may often be small) and heteroskedasticity (since the expected percentage tends to change in different conditions, and the spread in a bounded variable will generally be related to the mean). There are more appropriate models for that kind of data (beta regression is a common choice, for example). ...(ctd)
Comment: (ctd) ... If it makes sense for your application, a transformation may be useful (e.g. sometimes log of proprotion, or log of odds of being engaged in the activity may be reasonable to consider and may be less skew and less heteroskedastic), but I wouldn't necessarily go that way. If the percentages are not typically all that small you may be okay with ANOVA, though it might be necessary to consider a Welch-type adjustment for heteroskedasticity.
Comment: please see edit.
I have been told so many different things I am lost.
I understand stats is a huge field and there is still much debate but I have one person (not on here, just in general) telling me I can't do it because of skew and another saying because it is all skewed in a certain way that it should be fine. :( I find it all so confusing.
Comment: Wait ... so someone said to you that if it's all similarly skewed ANOVA should be fine? That's not generally the case. Did they provide any kind of support for the claim?
Comment: All he said was that some are happy to use ANOVA as long as the data is all skewed in the same direction, and that this would be fine for me.
Comment: This is a good discussion to read on whether is might be appropriate to use a percentage as a dependent variable in your analysis:  http://stats.stackexchange.com/questions/11296/using-anova-on-percentages
Answer: Beta regression is available in SPSS Statistics via the STATS PROPOR REGR extension command.  That can be installed from the Utilities menu with V22 or later or downloaded from the SPSS Community website (www.ibm.com/developerworks/spssdevcentral) in the Extension Commands Collection.  See that item for details.

SPSS ANOVA or MANOVA or huh?


Deducing material implication from inference rule

Question: Say I have a rule of inference
$$
\vdash P\Rightarrow\;\vdash Q,
$$
where $\Rightarrow$ denotes logical inference (as opposed to material implication) and $P$ and $Q$ are some forms. For example, $P$ may be of form $\varphi$ and $Q$ may be of form $\forall x\varphi$.
Then I propose an (arbitrary) instance of
$$
\vdash P\rightarrow Q,
$$
with $\rightarrow$ denoting material implication.
This seems to follow from a metalogical argument by cases. For a given instance of $P$ and corresponding instance of $Q$, if you have $P$, then you can deduce $Q$, and thus, both being true, $P\rightarrow Q$. If you have rather $\neg P$, $P\rightarrow Q$ is immediately vacuously true.
However, I've not been able to construct an argument to this effect in the system. This leads me to two questions:

Is the above argument sound, or have I missed some subtlety?
If it is sound, can it be shown in the system for a given rule and instantiation, or if not, what modification to the system must be made to assert such a conclusion?

"The system" being typical classical logic, say modus ponens and a typical axiomatization:
$$
\vdash\varphi\;\&\vdash\varphi\rightarrow\psi\Rightarrow\enspace\vdash\psi\\\vdash\varphi\rightarrow(\psi\rightarrow\varphi)\\\vdash(\varphi\rightarrow(\psi\rightarrow\chi))\rightarrow((\varphi\rightarrow\psi)\rightarrow(\varphi\rightarrow\chi))\\\vdash(\neg\varphi\rightarrow\neg\psi)\rightarrow(\psi\rightarrow\varphi)
$$
Answer: As far as I understand, your deductive system is the Hilbert calculus for classical propositional logic.
The property that you want to prove is the deduction theorem: roughly, it says that if we deduce a proposition $B$ on the assumption of a proposition $A$, then we conclude that the implication "If $A$ then $B$" holds (i.e. $A \to B$ is derivable). Deduction theorem explains why proofs of conditional sentences in mathematics are logically correct.
The proof of this property is by induction on the length of the derivation of $B$ from the assumption $A$.
For details, see here (and here for a discussion).
Answer: For completeness, the answer to the second question:
The deduction theorem depends on the existence of a theorem to deduce the following form:
$$
\vdash H \rightarrow P\\
\vdash H \rightarrow Q\\
...\\
\vdash H \rightarrow R
$$
where
$$
\vdash P\;\&\vdash Q\;\&\;... \Rightarrow\;\vdash R\\
$$
for all inference rules in the system.
For example, for modus ponens:
$$
\vdash H \rightarrow \varphi\\
\vdash H \rightarrow (\varphi \rightarrow \psi)\\
\vdash(H \rightarrow (\varphi \rightarrow \psi))\rightarrow ((H\rightarrow \varphi) \rightarrow (H \rightarrow \psi))
$$
and then by modus ponens twice, $\vdash H\rightarrow \psi$.
For the example I used of $\vdash\varphi\Rightarrow\;\vdash\forall x\varphi$, the axiom typically providing for this prerequisite theorem is $\vdash\varphi\rightarrow\forall x\varphi,\ x\ \text{not free in}\ \varphi$. Obviously this is the desired implication, but from this axiom follows $\vdash(H\rightarrow\varphi)\rightarrow(H\rightarrow\forall x\varphi),\ x\ \text{not free in}\ \varphi$, which would be sufficient for the deduction theorem to hold.
(NB: The restriction on $x$ being not free in $\varphi$ is not a weakening as compared to the inference rule, as it too requires that $x$ not be free in $\varphi$. The non-freeness of $x$ is however implied by $\vdash\varphi$, as no variable is free in a theorem)


PROCV entre duas planilhas

Question: O resultado que devo mostrar na coluna autores da planilha produção é o nome de todos os autores que escreveram aquela disciplina.
Estou utilizando a seguinte função =PROCV(C8;'Remanejamento'!C3:D55;2) mas a mesma não retorna todos os registros encontrados na planilha Remanejamento, mostrando apenas o último registro que achou.
O maior problema é que a mesma matéria pode ser dada em outros anos/séries e com isso, quando arrastar a fórmula para a próxima célula (caso a disciplina ainda não tenha sido pesquisada) pode sair novamente.
Abaixo mostro as colunas da planilha:
Planilha produção

Planilha Remanejamento
Comment: `PROCV` obtêm um registro apenas e não todos, é a forma como funciona. Outra  forma de perceber isto é que é uma formula colocada numa célula, logo só vai gerar o valor para uma célula, dai apenas um resultado.
Comment: Você utiliza o Excel 2016? Que então você poderia utilizar o `UNIRTEXTO`
Comment: @danieltakeshi - Utilizo o Excel 2010
Comment: @Isac - Entendi. Por exemplo, quero mostrar o nome dos professores da planilha Remanejamento (pessoa 1, pessoa 2 e pessoa 3) no campo autores da planilha produção utilizando este comando =CONCATENAR(PROCV(C7;'Remanejamento'!C3:D55;2);", ";PROCV(C7;'Remanejamento'!C3:D55;2);). Só que o registro que retorna na célula é "Pessoa 3, Pessoa 3". Conhece algum outro método que poderia fazer sem repetir os nomes?
Comment: Não tenho muito contexto para aferir o que está a tentar fazer, mas se é o que eu penso então uma tabela dinâmica será uma possibilidade.
Comment: `UNIRTEXTO` realizaria a concatenação de múltiplos resultados. Porém, como sua versão não suporta esta função... Sugiro uma UDF (User Defined Function) em VBA para a sua necessidade. Ou instalar o Excel 2016... Ou cria uma coluna auxiliar e gera uma concatenação de todos os valores...
Comment: Obrigado a todos pela ajuda. Verei o que consigo fazer.
Answer: Tente o seguinte:
Crie uma planilha chamada Auxiliar
Na planilha Auxiliar Célula A1 use a seguinte fórmula:
=SEERRO(ÍNDICE(Remanejamento!A$2:D$18;MENOR(SE((Remanejamento!B$2:B$18=Produção!A$2)*(Remanejamento!C$2:C$18=Produção!B$2);LIN(Remanejamento!B$2:B$18)-1);LIN(L1));4);"")
Na planilha Auxiliar Célula B1: =SEERRO(ÍNDICE(Remanejamento!A$2:D$18;MENOR(SE((Remanejamento!B$2:B$18=Produção!A$3)*(Remanejamento!C$2:C$18=Produção!B$3);LIN(Remanejamento!B$2:B$18)-1);LIN(L1));4);"")
Na planilha Auxiliar Célula C1: =SEERRO(ÍNDICE(Remanejamento!A$2:D$18;MENOR(SE((Remanejamento!B$2:B$18=Produção!A$4)*(Remanejamento!C$2:C$18=Produção!B$4);LIN(Remanejamento!B$2:B$18)-1);LIN(L1));4);"")
Na planilha Auxiliar Célula D1:
=SEERRO(ÍNDICE(Remanejamento!A$2:D$18;MENOR(SE((Remanejamento!B$2:B$18=Produção!A$5)*(Remanejamento!C$2:C$18=Produção!B$5);LIN(Remanejamento!B$2:B$18)-1);LIN(L1));4);"")
Na planilha Auxiliar Célula E1:
=SEERRO(ÍNDICE(Remanejamento!A$2:D$18;MENOR(SE((Remanejamento!B$2:B$18=Produção!A$6)*(Remanejamento!C$2:C$18=Produção!B$6);LIN(Remanejamento!B$2:B$18)-1);LIN(L1));4);"")
E copie a fórmula para baixo arrastando. (Lembrando que a função é matricial, toda vez que mexer na caixa de fórmula usar o CTRL + SHIFT + ENTER)
Na planilha Produção célula F2:=CONCATENAR(Auxiliar!A1;" ";Auxiliar!A2;" ";Auxiliar!A3;" ";Auxiliar!A4;" "; Auxiliar!A5;" ";Auxiliar!A6)
Na planilha Produção célula F3:=CONCATENAR(Auxiliar!B1;" ";Auxiliar!B2;" ";Auxiliar!B3;" ";Auxiliar!B4;" "; Auxiliar!B5;" ";Auxiliar!B6)
Na planilha Produção célula F4:=CONCATENAR(Auxiliar!C1;" ";Auxiliar!C2;" ";Auxiliar!C3;" ";Auxiliar!C4;" "; Auxiliar!C5;" ";Auxiliar!C6)
Na planilha Produção célula F5:=CONCATENAR(Auxiliar!D1;" ";Auxiliar!D2;" ";Auxiliar!D3;" ";Auxiliar!D4;" "; Auxiliar!D5;" ";Auxiliar!D6)
Na planilha Produção célula F6:=CONCATENAR(Auxiliar!E1;" ";Auxiliar!E2;" ";Auxiliar!E3;" ";Auxiliar!E4;" "; Auxiliar!E5;" ";Auxiliar!E6)
Comment: Obrigado por responder. Fiz os testes com  que enviou e só o comando que coloquei na célula E1 funcionou, onde que mostrava (Pessoa 1, pessoa 2, pessoa 3) mas não mostrava o resto. Realizei mais algumas pesquisas e ajuda de um colega, conseguimos resolver o problema seguindo esta instrução em VBA ->  https://stackoverflow.com/questions/47837452/vba-code-to-vlookup-multiple-criteria-remove-duplicates
Comment: Fiz uma alteração e adicionei uma imagem da planilha auxiliar. Conferi as fórmulas e não encontrei erro.
@Danilo
Comment: Descobri aonde estava errando. Obrigado.

PROCV entre duas planilhas