How the Net RunRate for each team is calculated in IPL?

Question:
A team's net run rate is calculated by deducting from the average runs
  per over scored by that team throughout the season, the average runs
  per over scored against that team throughout the season. -Cricinfo

I can't understand the above concept clearly.
Please, provide the exact formulas(ie, explain clearly) for calculating the net runrate in IPL with authentic references(with examples).
Answer: The net run rate is calculated with the below formula:
<code>NRR = ((Total runs scored by team)/(Total overs played by team))
        -
      ((Total runs scored against team)/(Total overs played against team))
</code>
Total runs -> This is straight forward. It is the score that a team scores (batting) and is scored against (bowling) in the whole tournament.
Total overs -> This is the total overs played (batting) and delivered (bowling) by a team. This one has a catch though.

If a team is all out within the stipulated 20 overs, then the overs considered for NRR calculation is 20 itself and not the actual overs played.
If a team chases down a target before 20 overs, then the actual overs is considered for NRR calculation.

Find below the current RCB Net Run Rate (0.47) and the break-up of how the figure has been arrived at considering all the games that they have played till now.

RCB

Opponents

Game #
Runs
Overs
Runs
Overs

1
156
20
154
20

2
130
20
130
20

3
162
17.4
161
20

4
158
17.3
154
20

5
165
20
166
19.5

6
152
20
152
20

7
123
17.5
117
20

Totals
1046
133
1034
139.5

A
B
C
D

RCB RR
A/B
7.86
E

Opponent's RR
C/D
7.39
F

NRR
E-F
0.47
Answer: NRR for a team in cricket is calculated by the following formula
NRR = (Average runs scored per over by the team throughout the tournament) - (Average runs scored per over by the opposing teams against it).
Also Cricinfo , says the following rules are applied in case a match is abandoned/ concluded a duckworth lewis method.

Where a match is abandoned, but a result is achieved under
  Duckworth/Lewis, for net run rate purposes Team 1 will be accredited
  with Team 2's Par Score on abandonment off the same number of overs
  faced by Team 2. Where a match is concluded but with Duckworth/Lewis
  having been applied at an earlier point in the match, Team 1 will be
  accredited with 1 run less than the final Target Score for Team 2 off
  the total number of overs allocated to Team 2 to reach the target.

Also only matches that never take place(abandoned without a ball being bowled) are not considered for the same i believe.
For example in current IPL , RCB has for and against values as (1046/133.0) and (1034/139.5) . So it would be (1046/133.0) - (1034/139.5) = 7.8644 - 7.4 = (approx) +0.470
Comment: Hi @kartshan

Can you explain D/L method with an example? Say, RR's score in current IPL is

Match 1: RR-125/9(20), OPP: 127/1(15.5)

Match 2: RR- 153/5(17.5), OPP: 60/4(6), RR won by 10 runs using D/L method.
Match 3:RR- 217/4(20), OPP: 198/5(20).
IPL point table is showing -0.247 run rate, but i am not sure , how it is calculated?
Answer: Across the three games, TEAM1 scored 678 runs in a total of 147 overs and 2 balls (actually 147.333 overs), a rate of 678/147.333 or 4.602 rpo.
The run-rate scored against TEAM1 across the three games is calculated on the basis of 466 runs in a total of 50 + 50 + 50 = 150 overs, a rate of 466/150 or 3.107 rpo.
The net run-rate is, therefore,
4.602 - 3.107 = + 1.495
NET RUN RATE OF TEAM1 is + 1.495
Answer: The basic equation is as follows:
<code>`Net run rate = (number of runs scored/number of overs faced) - (number of runs conceded/number of overs bowled)`
</code>
A positive net run rate means a team is scoring faster than its opposition overall, while a negative net run rate means a team is scoring slower than the teams it has come up against. A positive NRR is therefore desirable.
NRR is usually employed to rank teams that have finished a series or tournament on the same number of points.
Examples:
In the 2012 Indian Premier League (IPL), Pune Warriors scored 2321 runs off 319.2 overs and conceded 2424 runs off 310 overs. Pune Warriors' NRR is therefore:
<code>(2321/319.333) - (2424/310) = 7.268 - 7.819 = -0.551
</code>
If a team is bowled out before completing their full quota of 20 or 50 overs (depending on whether it is a Twenty20 or one day match), that full quota is used in the net run rate calculation. For example, if the team batting first is bowled out for 140 after 35 overs of a 50-over game and the opposition reaches 141 in 32 overs, the NRR calculation for that match goes like this:
<code>(140/50) - (141/32) = 4 - 4.406 = -0.406
</code>
Other Example:
New Zealand scores 1066 runs off 223 overs and conceded 974 runs off 238.2 overs. New Zealand's net run rate (NRR) is therefore calculated as follows:
<code>(1066/223) - (974/238.333) = 4.780 - 4.086 = 0.694
</code>
Note: 238.2 overs, meaning 238 completed overs and two further balls, was converted to 238.333 for the purposes of calculation.
Hope this helps.


Marking a field invalid

Question: I use a custom AJAX vtype, which works and all.
However I notice the extjs docs note that
"Note: this method does not cause the Field's validate or isValid methods to return false if the value does pass validation. So simply marking a Field as invalid will not prevent submission of forms submitted with the Ext.form.action.Submit.clientValidation option set."
How does one mark a field as invalid so that form.isValid() returns false?
My vtype:
Ext.apply(Ext.form.VTypes, {
username: function(value, field){
    var conn = new Ext.data.Connection();
    conn.request({
        url: 'test.php',
        params:{email:value},
        method: 'POST',

        success: function(responseObject){
            var resp = responseObject.responseText;
            if (resp == 0) {
                field.markInvalid('This email is invalid or already registered!');
            } else if (resp == 1) {
                field.clearInvalid();
            }
        },
        failure: function(){
           Ext.Msg.show({title: 'Error', msg: 'Connection error!',});
        }
    });
    return true;
}
});

Answer: Well, if you look at the definition of clientValidation:

Determines whether a Form's fields are validated in a final call to
  isValid prior to submission. Pass false in the Form's submit options
  to prevent this. If not defined, pre-submission field validation is
  performed.

This is basically saying, if its set to false then the form will be automatically validated prior to submission... at which point it will fail if you have marked any fields as invalid. If you set it to true then you need to manually check if the form is valid before submitting.
It's worth pointing out that your AJAX vtype is never going to work. When the form calls the vtype to check whether the field is valid, all it gets in response is true... so the form submits no matter what. Even if you tell it to return after the ajax request has completed, the form would submit before the vtype ajax request completes.
A better solution would be to include the call to the vtype manually in your submit button handler...then in your success of the ajax request just do
if(form.isValid()) {
   form.getForm().submit();
}

This will force the submit button's click event to first validate the username field and then, and only then, will it submit the form.
Comment: Submitting the form like that would break the asynchrony. :( I would prefer to avoid manual validation for the form, would theoritically be much easier to have a function that over rides the vtype checking, that sets isValid= false; somehow.
Comment: You can't, without tying into the ajax success call, because it is asynchronous by nature... the form validation returns true and the form is submitted before the ajax request ever completes. You will either have to override the `submit()` method, maybe force it to check all types and fire ajax requests manually, and also force it to take a callback function as an argument...

Marking a field invalid


Your Ruby version is 2.3.1 but your Gemfile specified 2.5.1

Question: Whenever I run a Rails command, it states that my Ruby version is 2.3.1 but my Gemfile specified 2.5.1. However, "ruby -v" returns "ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux]", my path has no references to ruby 2.3.1, and running "rvm list" shows a properly green highlighted 2.5.1. Bundler is installed, and when I try to run bundle install inside a created Rails folder, a get another "Your Ruby version is 2.3.1 but your Gemfile specified 2.5.1" message. Please advise.
$PATH:
-bash: /home/alowverus/.rvm/gems/ruby-2.5.1/bin:/home/alowverus/.rvm/gems/ruby-2.5.1@global/bin:/usr/share/rvm/rubies/ruby-2.5.1/bin:/usr/share/rvm/bin:/home/alowverus/.rvm/gems/ruby-2.5.1/bin:/home/alowverus/.rvm/gems/ruby-2.5.1@global/bin:/home/alowverus/.rvm/gems/ruby-2.5.1/bin:/home/alowverus/.rvm/gems/ruby-2.5.1@global/bin:/home/alowverus/.rvm/gems/ruby-2.5.1/bin:/home/alowverus/.rvm/gems/ruby-2.5.1@global/bin:/home/alowverus/.rvm/gems/ruby-2.5.1/bin:/home/alowverus/.rvm/gems/ruby-2.5.1@global/bin:/home/alowverus/bin:/home/alowverus/.local/bin:/home/alowverus/.rvm/gems/ruby-2.5.1/bin:/home/alowverus/.rvm/gems/ruby-2.5.1@global/bin:/home/alowverus/bin:/home/alowverus/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin: No such file or directory

Further information in response to answers:
"which rails" returns "/home/alowverus/.rvm/gems/ruby-2.5.1/bin/rails", as expected
Comment: You're need to upgrade ruby up to 2.5.1, and reproduce all steps again.
Answer: Create two files in the root one .ruby-version mention ruby-2.3.1 and .ruby-gemset mention @gemset-name and cd back to the same directory which will create the rvm wrapper for that application then run
rvm current

which outputs like something
ruby-2.3.1@gemset-name

then run
gem install bundler
bundle

may be helpful for you
Answer: I would try (in no particular order):

which rails, is it the correct one?
bundle exec rails c (or whatever your command is)
rvm reload
To start clean, rvm implode and try reinstalling rvm and your Ruby version.
Answer: Your Ruby version is 2.3.8, but your Gemfile specified 2.3.1
check ruby version with ruby -v [version like 2.3.8] make sure ruby version should be same on ruby versions as well as in your GemFile if you have not the same version then your put command on your bash_profile (terminal) rbenv global 2.3.8 & rbenv shell 2.3.8 (the version you can specified accordingly ) then delete your Gemfile.lock then install bundle and install bundler . these steps working form me.
rbenv global 2.3.8
rbenv shell 2.3.8
delete your Gemfile.lock
install bundle
install bundler


Understanding CPP pointers

Question: if
int number[];
int *tommy;

then whats the difference in the following statements? will both the statements not copy the address of number to tommy?
tommy = &number;

OR
tommy = number;

EDIT: sorry guys I meant int array rather than just int.
Comment: To learn basics like this, you should probably pick up a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list).
Comment: The second one won't compile.
Comment: @Firdous There are several online compilers available, e.g. [ideone](http://ideone.com/).
Comment: Everyone answering this question seems to have missed that `number` is an array. The second compiles, the first is a type error.
Comment: @john: That's because it wasn't an array until a minute ago. Now it's an array of unknown size, so it still won't compile.
Comment: Oh well, fundamental edits to the question without explanation. I very rarely do this but -1 from me.
Comment: @Firdous, I would ask this again, but this time ask what you really mean, and try to compile the code before you ask the question.
Comment: @john one might not have the dev environment anytime, the purpose of question is to grasp the concept, if you think question is below standards you are welcome to down vote!
Comment: @Firdous, it's not really about the standard of the question, its just that because of the edit to the question, the answers will be extremely confusing to anyone subsequently reading this. Now you've acknowledged the edit I'm removed my down vote. Still think you might ask again though.
Answer: The first one assigns the address of number into tommy. The second one tries to assign the number number into the pointer tommy, and it should fail to compile.
EDIT
With the edit, it's the other way round: the first one should not compile. An address of an int array is of type int (*)[size], which cannot be converted to int*.
Answer: int number; defines an integer number. int *tommy; defines tommy to be a pointer pointing to an integer.
tommy = &number; Assigns the address of number to tommy. *tommy will give the actual number.
tommy = number stores the value of number in tommy. One, there should be a compilation error and on top of it, if you succeed to store number into tommy, then *tommy will try to deference from an invalid location whose address is same as the content of number and leads to segmentation fault.
Postscript
I am tempted to think if you saw an example as this
int a[10];
int *tommy;

tommy = a; // This will work

In this example, a is the name of the array and is equivalent to the address of array or the first element of the array i.e. &a[0]. Hence, storing a into tommy is valid.
Comment: thanks for interpreting rightly, so would tommy = a and tommy = &a be similar?
Comment: Yes. `a`, the name of the array would be same as the address of the array `&a` and is also the address of the first element of the array `&a[0]`
Answer: For your example to compile, the array will need a size:
int number[1];

since you can't create a variable of unknown size.
tommy = &number;

error: cannot convert 'int (*)[1]' to 'int*' in assignment

This should not compile. &number is a pointer to an array, which is not convertible to a pointer to int, so cannot be assigned to a variable of that type.
tommy = number;

This is fine. When used in an expression, an array can be converted to a pointer to its first element. That pointer type is int*, the same as tommy, so the assignment is allowed.
Answer: The first assignment is correct - it assigns the address of number to the pointer tommy.
The second assignment will assign the value of number to the pointer tommy.
Answer: No, they won't, & is the reference operator or address of it will take the address of the variable you prea-append it with, so this does what you want:
tommy = &number

when you just use plain number it just return the integer value stored in number, which won't compile. This reference on pointers goes into a lot more details.
Update:
So after the edit to the question, this will not compile without a size:
int number[];

this is valid:
int number[10];

So now it is reversed, this is valid and will compile:
tommy = number ;

The second line attempts to treat an array of integers as a single integer and the compiler will not allow this and so it is not valid:
tommey = &number ;

Answer: No, the two are fundamentally different. The expression &number evaluates to the address at which the value of number is stored, whereas the expression number evaluates directly to the value itself.
Suppose that the value of number is 42, and that it is stored att adress 1024 in memory. Memory is linear*, so it will look something like this:
+--------+ Address 0
| ...... |
+--------+
|   42   | Address 1024 (value is stored here)
+--------+
| ...... |
+--------+ Address xxxx

Now, the statement tommy = &number; will assign the value 1024 to tommy, since &number == 1024, the address of number.
The other statement, provided it compiles at all, will assign the (nonsensical) value 42 (the value of number) to tommy. Any attempts to dereference (access the data pointed to by) tommy are likely to generate a segmentation fault, because 42 is (probably) not a valid address.
*At least, the operating system will give you the illusion that your address space is linear and contiguous.

Understanding CPP pointers


Both Z-test and chi-squared apply in testing if a pill makes any difference in avoiding the flu?

Question: I want to test if a certain pill would make any difference in avoiding the flu.
I give the pill to group A and a placebo to group B. Then I count how many individuals got the flu in each group, and how many didn't.
I imagine two ways of testing if the pill made any difference in avoiding the flu:
Z test for proportion: I conduct a z test with the following hypoteshis: Null hypothesis: The proportion of people that got the flu in group A is equal to the proportion of people that got the flu in group B. Alternative Hypothesis: the proportions are different.
Chi-squared test: I create a contingency table with the sample and I conduct a chi-squared test for homogeneity.
What's the most adequate test in this case, and why?
Comment: related to [this question](https://stats.stackexchange.com/questions/403912/chi-square-2x2-contingency-vs-z-test-for-two-proportions-parametric-or-non-para)
Answer: There are various versions of both tests.
If the error variance in the test of proportions is
estimated from the two groups separately, and no
continuity correction is used for either test,
then the two tests may be equivalent.
Suppose there were 403 successes out of 500 subjects in the drug group
and 366 out of 500 in the placebo group, then
here are the two tests as computed in R. Notice that
the methods of formatting the data and the methods of
formatting the output differ between the two tests
as implemented in R.
Test of binomial proportions. Data are numbers of successes
and sample sizes. The continuity correction is declined
(parameter cor=F).
prop.test(c(403,366), c(500,500), cor=F)

    2-sample test for equality of proportions
    without continuity correction

data:  c(403, 366) out of c(500, 500)
X-squared = 7.7066, df = 1, p-value = 0.005502
alternative hypothesis: two.sided
95 percent confidence interval:
 0.0219564 0.1260436
sample estimates:
prop 1 prop 2
 0.806  0.732

Chi-squared test. Data are provided in a contingency table.
The Yates correction is declined.
TBL
     [,1] [,2]
[1,]  403  366
[2,]   97  134

chisq.test(TBL, cor=F)

        Pearson's Chi-squared test

data:  TBL
X-squared = 7.7066, df = 1, p-value = 0.005502

Notes: (1) Proportions test: If a pooled error variance is used in the test of
binomial proportions, then the confidence intervals
do not exactly match the significance test. That is, 95% confidence
intervals excluding $0$ do not exactly match rejection at the
5% level. Also, the X-squared statistic shown in the R output for this test is the square of the z-statistic, shown by some other
statistical software. Relevant Minitab output below:
Test and CI for Two Proportions

Sample    X    N  Sample p
1       403  500  0.806000
2       366  500  0.732000

Difference = p (1) - p (2)
Estimate for difference:  0.074
95% CI for difference:  (0.0219564, 0.126044)
Test for difference = 0 (vs ≠ 0):  Z = 2.79  P-Value = 0.005

Fisher's exact test: P-Value = 0.007

(2) Chi-squared test: If counts are sufficiently small for the
(somewhat overly conservative) Yates correction to make a difference whether to reject, then
perhaps it is best to use a Fisher exact test instead.
The P-value of Fisher's test for my fake data is shown below.
fisher.test(TBL)$p.val
[1] 0.006834361


Calling events for n buttons on the form

Question: In my previus post I asked how to create a set of n draggable buttons, which worked fine, but I'm now working on the following:
I placed an image on the form, and loaded a coordinate matrix, so that when I also drag the image, the buttons "follow the image", I'm trying to acomplish it by calling an event when the button is finished being dragged, calling an event and transforming "image coordinates" to "form coordinates". It works fine for just one, but  the problem arises when I place n buttons, since I don't know how to "recognize" which button called the event, I'll show you how I did my stuff:
 int x, y;

 //Creates a set of four buttons with an icon
 for (int i = 0; i < 4; i++)
 {
     x = rnd.Next(1, this.Width - 30);
     y = rnd.Next(1, this.Height - 30);
     botonCustom newboton = new botonCustom(32, 32, new Point(x, y), imageList1);

     //New event for each button (Is it ok to do?)
     //I tried to call the same function newboton_Move, since i do not know how to create an event for each button
     newboton.Move += new EventHandler(newboton_Move);

     //Name the button and writes it on a lablel
     newboton.Description = EtiDiamond[i];
     DiamondButton.Add(newboton);
     this.Controls.Add(newboton);
  }

Here is the function being called:
private void newboton_Move(object sender, EventArgs e)
{
   // Here i use the coordinates transform method, i won't place the code because
   // its too big and it goes against the rules :P, i think if i could somehow know which button called this...
}

Thanks for reading this
Comment: You have to cast sender to Button. Then you will know which one is call the event.
Answer: sender is the button that raised the event
var myButton = sender as Button;

Comment: So let's say, the sender is the 3rd button, and i want to change its location, could i do  myButton.Location=new point(x,y); and will this  modify the location of the sender?


VSTS NuGet Publisher - 403 (Forbidden) Error

Question: I have created a build definition in Team Services which needs to run on a private agent (i.e. on-premise build server). This agent is running under a domain account. I then created a NuGet feed in Team Services to which I am trying to publish a package created by the NuGet Packager task.
I am getting an authentication error (403 Forbidden) when trying to push a package to the internal feed using the NuGet Publisher Task (NuGet v22.214.171.1243) :
2017-05-04T21:05:06.3076014Z CredentialProvider.TeamBuild: Failed to authenticate to https://mycompany.pkgs.visualstudio.com/_packaging/MyProject/nuget/v3/index.json from your project collection, prefix = https://mycompany.pkgs.visualstudio.com/
2017-05-04T21:05:07.8546075Z System.AggregateException: One or more errors occurred. ---> NuGet.Protocol.Core.Types.FatalProtocolException: Unable to load the service index for source https://mycompany.pkgs.visualstudio.com/_packaging/MyProject/nuget/v3/index.json. ---> System.Net.Http.HttpRequestException: Response status code does not indicate success: 403 (Forbidden).

Please note that I am able to publish the same package manually on the build server using my credentials as decribed here : https://www.visualstudio.com/en-us/docs/package/nuget/nuget-exe
Now, the build definition is project scoped (not Project Collection scoped). Therefore, the default permissions which add the Project Collection Build Service account to the contributors of the feed is probably incorrect.
I believe the Project Build Service account associated with this specific team project needs to be added to the contributors (or owners).
Since there are 15+ projects in this Team Services account and the Project Build Service accounts all have the same name, finding the correct account requires some work. I managed to find the specific Project Build Service account guid by addding the following PowerShell inline script to the build (which I got from here : https://github.com/Microsoft/vsts-tasks/issues/3287):
$headers = @{Authorization="Bearer ${env:SYSTEM_ACCESSTOKEN}"}
$response = Invoke-RestMethod "${env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI}/_apis/connectionData" -Headers $headers
$response.authenticatedUser | Format-List id, customDisplayName | Out-Host

Now, I cannot seem to add the Project Build Service account to the contributors of the feed, either by typing its guid or by typing "Project Build Service" to find the one with the correct guid from the list of accounts.
Is this a bug or did I forget to configure something ?
Comment: What's the build result if you add your account as owners for in feed permissions?
Comment: My (user) account is already an owner of the feed. That is probably why I am able to publish to the feed manually using the VSTS Credentials Provider. The agent service is running under a different (service) account though.

Do I need to create a user for this service account in VSTS ? I didn't see a requirement to do this in the MSDN documentation...
Answer: I managed to find a solution. For the benefit of others who might have the same problem, here what was done to solve the issue.
I started looking at the REST API for feed permissions to try adding the project specific build service account (using the id gathered from the PowerShell script described above) to the feed's contributors.
Looking at the API documentation , I realized that you need to specify the full identity descriptor which has the following format :
Microsoft.TeamFoundation.ServiceIdentity;00000000-0000-0000-0000-000000000000:Build:10000000-0000-0000-0000-00000000000

I then modified the inline PowerShell script to display all the information about the Project Build Service identity :
$headers = @{Authorization="Bearer ${env:SYSTEM_ACCESSTOKEN}"}
$response = Invoke-RestMethod "${env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI}/_apis/connectionData" -Headers $headers
$response.authenticatedUser | Format-List | Out-Host

I then realized that the descriptor returned contains a second guid that appears after the "Build:" part which is different than the identity id. This guid also appears in the providerDisplayName property of the authenticatedUser object returned.
Using the feed permissions interface, I tried to do a search using the providerDisplayName guid and finally got one result ! After adding this Project Build service account to the contributors and running a new build, I was able to publish the feed.
To facilitate the configuration of permissions of the feed, I believe the documentation specific to build identities could be improved as it only mentions project collection scoped build definitions and not project scoped definitions.
Ultimately, the problem stems from the fact that if a Team Services account countains multiple projects, giving the correct permissions to the project's build service account is not easy since they all have the same name, i.e. Project Build Service (account).
Comment: Thanks to your information, I've able to address this same problem. I've found that looking at the Event Viewer at TFS server, you can also get the information about account used by build agent. For example:

ExceptionMessage: Build\308bbda0-dd0a-4358-8e5f-768f58d2c3d5 does not have permission to complete this action. It needs 'ReadPackages'. (type FeedNeedsPermissionsException)


C++: Divisão de vector

Question: Estou fazendo uma classe numérica dinâmica, armazenando o valor do número em um vetor de bytes. Fiz as funções de soma, subtração e multiplicação do mesmo jeito que se aprende na escola, porém isso não pode ser aplicado na divisão. Qual a maneira certa de fazer?
typedef unsigned char uchar;
typedef unsigned short ushort;
typedef unsigned int uint;
typedef unsigned long ulong;

class Num
{
private:
    vector<uchar> x;
    ...
public:
    ...
    Num(vector<uchar> other)
    {
        if(other.size() > 8) other.resize(8);

        while(!other.empty() && other[other.size() - 1] == 0)
            other.pop_back();

        x = other;
    }

    size_t size() const
    {
        return x.size();
    }
    ...
    friend Num operator+(Num l, const Num& rhs)
    {
        Num r = rhs;
        vector<uchar> res (l.x);
        vector<uchar> mod (1, 0);

        while(r.size() < res.size()) r.x.push_back(0);
        while(r.size() > res.size()) res.push_back(0);

        for(uchar i = 0; i < res.size(); i++)
        {
            mod.push_back((ushort)res[i] + (ushort)r.x[i] > 0xff);
            res[i] += r.x[i];
        }

        Num nmod = mod;
        if(nmod.size() > 0) return (Num(res) + nmod);
        return Num(res);
    }
    friend Num operator-(Num l, const Num& rhs)
    {
        Num r = rhs;
        vector<uchar> res (l.x);
        vector<uchar> mod (1, 0);

        while(r.size() < res.size()) r.x.push_back(0);
        while(r.size() > res.size()) res.push_back(0);

        for(uchar i = 0; i < res.size(); i++)
        {
            mod.push_back(res[i] < r.x[i]);
            res[i] -= r.x[i];
        }

        Num nmod = mod;
        if(nmod.size() > 0) return (Num(res) - nmod);
        return Num(res);
    }

    Num& operator+=(const Num& r)
    {
        Num res = *this + r;
        *this = res;
        return *this;
    }
    Num& operator-=(const Num& r)
    {
        Num res = *this - r;
        *this = res;
        return *this;
    }

    friend Num operator*(Num l, const Num& rhs)
    {
        Num r = rhs;
        Num res;

        for(uchar i = 0; i < r.size(); i++)
        {
            vector<uchar> temp(i, 0);
            vector<uchar> mod(i + 1, 0);

            for(uchar j = 0; j < l.size(); j++)
            {
                ushort v = l.x[j] * r.x[i];
                temp.push_back(v % 256);
                mod.push_back(v / 256);
            }

            res += Num(temp) + Num(mod);
        }
        return res;
    }
    ...
};

As operações que fiz são iguais as que se aprende na escola considerando cada uchar do vetor como se fosse um algarismo com base 256.
Answer: Pode sim implementar algoritmos aprendidos na escola. Mas no seu caso você quer fazer uma adaptação onde se trabalha com cada uchar do vetor sendo um algarismo de base 256, correto? Além disso, deve-se definir o tipo de divisão que será feita. Vamos assumir que é divisão euclidiana de números positivos.
A imagem a seguir servirá de guia. Ela apresenta como exemplo a divisão de dois números, um dividendo com seis algarismos (recomenda-se que o de maior magnitude não seja zero) dividido por um divisor de quatro (o de maior magnitude simplesmente não pode ser zero). A imagem apenas apresenta as posições dos algarismos operados para ficar mais claro como se realizam as operações em termos de etapas.
A imagem não apresenta algarismos de exemplo porque isso depende da base em que se trabalha e a explicação será dada independentemente da base. A questão é que a lógica independe da base numérica, portanto vale para sistema binário, octal, decimal, hexadecimal, base 256, etc, assim se atentando apenas às casas de cada dígito e às restrições (por exemplo, em base octal os dígitos vão de 0 a 7 e o que exceder desses limites gera carry).

O algoritmo consiste em repetidamente encontrar um dígito correto do quociente, dos dígitos de maior magnitude aos de menor, e atualizar um número temporário até que o quociente esteja completo, quando então o número temporário final é o resto. Cada repetição é realizada considerando o emparelhamento de algarismos.
No início, o número temporário é igual ao dividendo. A cada repetição, trabalha-se com os dígitos de maior magnitude do temporário. A quantidade de dígitos do temporário trabalhados no primeiro ciclo é o mesmo número de dígitos do divisor (no exemplo, apenas os quatro algarismos mais avançados são trabalhados) e nos seguintes libera-se mais um algarismo do temporário para trabalhar neles. Essas repetições ocorrem até não sobrar mais algarismos no número temporário para incluir ao final do ciclo, sendo este portanto o último.
Esse trabalho consiste em:
(1) investigar qual é o maior algarismo (na base utilizada) cujo produto dele com o divisor é menor ou igual ao trecho trabalhado do número temporário;
(2) setar o algarismo do quociente com esse número;
(3) setar aqueles algarismos temporários com a subtração deles com o produto que foi calculado em (1).
Portanto é necessário um procedimento que compara se um número é menor ou igual a outro (para o passo (1)), outro que calcula multiplicação (para o passo (1)) e outro ainda que calcula subtração (para o passo (3)). É lógico que utilizar o comparador e o produto no procedimento (1), este programado a parte ao invés de calculá-lo inline, na busca do algarismo correto é uma medida adequada. Há várias formas de encontrar esse máximo, fica a sua escolha. No seu lugar eu trabalharia em binário mas refletido em base 256, assim.
Chamando o temporário de "Tmp1", usaria outro temporário "Tmp2" (para valores de potência de 2) e mais um "Tmp3" (para produto "Tmp2*Divisor").
(a) Atribuir, por hora, "DígitoDoQuociente=0";
(b) Repetidamente trabalhar com "Tmp2=128", depois "Tmp2=64", "Tmp=32", daí em diante até o último "Tmp2=1" (repare que dá para calcular deslocando bits para ganhar desempenho):
(b.1) Calcular "Tmp3=Tmp2*Divisor" (dá para calcular deslocando bits;
(b.2) Se "Tmp3<=Tmp1", calcular "DígitoDoQuociente=DígitoDoeQuociente+Tmp2";
(b.3) Se "Tmp3<=Tmp1", calcular "Tmp1 = Tmp1-Tmp3".
Comment: Como o resto pode ser negativo?
Comment: De qualquer forma, a divisão será inteira euclidiana, pois essa classe não possui assinatura e nem algarismos decimais (ponto flutuante)
Comment: A divisão inteira na computação é diferente da divisão inteira na matemática. Se, por exemplo, você escreve em C++ a expressão constante ((-99)%(15)), o valor da expressão será -9 quando na verdade o resto da divisão euclidiana retorna 6 (15-9). É porque ((99)%(15)) é 9, aí se o dividendo (no caso 99) trocar de sinal, na computação o resto (no caso 9) troca de sinal também.
Comment: Qual método você recomenda para o passo (1)? Sou novo nisso, só consigo pensar em usar um `for` ou um `while`, mas eu vou ter com isso 256^8-1 repetições no pior caso (0xFFFFFFFFFFFFFFFF / 1)
Comment: Vou complementar no final da minha resposta.

C++: Divisão de vector


Get the list of all content types

Question: How do I get a list of all the content types defined in a Drupal 8 site?
In Drupal 7 it used to be node_type_get_types(), but it has been deprecated.
I tried Entity::loadMultiple() but it doesn't seem to work. I was thinking about making a custom query, but I don't know how it's stored in the database.
Answer: loadMultiple() should be fine for this:
$types = \Drupal::entityTypeManager()
  ->getStorage('node_type')
  ->loadMultiple();

Comment: This still works fine in Drupal 8.9 @augusto. The other post you've linked to is not the same question - this is for loading the node type config entities, not nodes.
Comment: Not working on  Drupal 8.9.x. Use https://stackoverflow.com/a/38252706/195812 instead
Answer: You can load all of the NodeType entities (config entities) using the NodeType class:
$node_types = \Drupal\node\Entity\NodeType::loadMultiple();
// If you need to display them in a drop down:
$options = [];
foreach ($node_types as $node_type) {
  $options[$node_type->id()] = $node_type->label();
}

Comment: The trick with the static `loadMultiple()`, `load()`, and `create()` methods is to call them on the entity type class that you want to use, then it figures out the type and uses does the above dynamically. This is a bit shorter and easier to use, but it's recommended to use injected services when possible, so in a service/controller/plugin, you'd inject the entity type manager and then use that. Allows for easier (unit) testing but the result is more or less the same.
Answer: There is another Drupal helper function that is not deprecated as of 8.7. node_type_get_names() returns:

string[] An array of node type labels, keyed by the node type name.

API docs
Comment: This is the easiest solution if you need to fill form select (or checkboxes) options.
Answer: Provided in case node_type_get_names() gets deprecated in the future (also a nice example of array_map usage):
function node_type_get_names() {
  return array_map(function ($bundle_info) {
    return $bundle_info['label'];
  }, \Drupal::service('entity_type.bundle.info')
    ->getBundleInfo('node'));
}

Answer: There's a service for that called "entity_type.bundle.info":
>>> $bi = \Drupal::service('entity_type.bundle.info');
=> Drupal\Core\Entity\EntityTypeBundleInfo {#1433
     +"_serviceId": "entity_type.bundle.info",
   }
>>> $bi->getBundleInfo('node');
=> [
     "article" => [
       "label" => "Article",
       "translatable" => false,
     ],
.

Get the list of all content types


Android: How to detect when a scroll has ended

Question: I am using the onScroll method of GestureDetector.SimpleOnGestureListener to scroll a large bitmap on a canvas. When the scroll has ended I want to redraw the bitmap in case the user wants to scroll further ... off the edge of the bitmap, but I can't see how to detect when the scroll has ended (the user has lifted his finger from the screen).
e2.getAction() always seems to return the value 2 so that is no help.
e2.getPressure seems to return fairly constant values (around 0.25) until the final onScroll call when the pressure seems to fall to about 0.13. I suppose I could detect this reduction in pressure, but this will be far from foolproof.
There must be a better way: can anyone help, please?
Comment: I've now abandoned the getPressure approach. It's too unreliable. Instead I'm checking the cumulative distance scrolled and redrawing the bitmap when this exceeds a defined limit. This is more predictable, but still far from ideal. If anyone has any suggestions for a better approach I should be very pleased to hear them!
Comment: I've added `if (e2.getPressure() < 0.15)` to the onScroll() method. As expected this sometimes detects the end of the scroll, but not always. Surely there must be a better way!
Comment: Of the many answers to this thread thosed that have proved most useful to me have been those from Akos Cz, Aron Cederholm and Mike.
Comment: Try this link : http://stackoverflow.com/questions/8181828/android-detect-when-scrollview-stops-scrolling
Answer: Here is how I solved the problem.  Hope this helps.
// declare class member variables
private GestureDetector mGestureDetector;
private OnTouchListener mGestureListener;
private boolean mIsScrolling = false;

public void initGestureDetection() {
        // Gesture detection
    mGestureDetector = new GestureDetector(new SimpleOnGestureListener() {
        @Override
        public boolean onDoubleTap(MotionEvent e) {
            handleDoubleTap(e);
            return true;
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            handleSingleTap(e);
            return true;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            // i'm only scrolling along the X axis
            mIsScrolling = true;
            handleScroll(Math.round((e2.getX() - e1.getX())));
            return true;
        }

        @Override
        /**
         * Don't know why but we need to intercept this guy and return true so that the other gestures are handled.
         * https://code.google.com/p/android/issues/detail?id=8233
         */
        public boolean onDown(MotionEvent e) {
            Log.d("GestureDetector --> onDown");
            return true;
        }
    });

    mGestureListener = new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {

            if (mGestureDetector.onTouchEvent(event)) {
                return true;
            }

            if(event.getAction() == MotionEvent.ACTION_UP) {
                if(mIsScrolling ) {
                    Log.d("OnTouchListener --> onTouch ACTION_UP");
                    mIsScrolling  = false;
                    handleScrollFinished();
                };
            }

            return false;
        }
    };

    // attach the OnTouchListener to the image view
    mImageView.setOnTouchListener(mGestureListener);
}

Comment: Interesting... and very helpful. But in a quick test I seem to be getting a touch-up event before a fling. I want to do different things if a fling is occurring or scrolling has simply stopped. When I detect a touch-up, how do I know if I'm about to get a fling event so that I won't perform my normal scroll-end functionality?
Comment: Thank you very much indeed for this code. It seems to be the answer to my problem. I thought at first the crucial line in your code was "return true" in the onDown method, but in fact this seems to make no difference in my code. The key point seems to be that, so far as I can see, the GestureDetector is never notified of an ACTION_UP event, so as (you correctly identified) I have to include code in my onTouchListener.onTouch() method to look out for this event at the end of the scroll. Thanks again!
Comment: @GarretWilson You can use a VelocityTracker to detect the velocity of your motion event, which then you can use to determine if a fling is about to happen.  See http://developer.android.com/reference/android/view/VelocityTracker.html  and/or the following post http://stackoverflow.com/questions/10155907/speed-or-acceleration-of-motion-event-android
Comment: Thanks for your help. Judging by the thread on Google Code Android, which your link refers to, there seems to be some confusion about the consequences of returning "true" or "false". I'll try "return true" in the onDown method and shall report back.
Comment: to capture `ACTION_UP` in `onTouchEvent`, make sure `onFling()` return false.
Answer: You should take a look at http://developer.android.com/reference/android/widget/Scroller.html.
Especially this could be of help (sorted by relevance):
isFinished();
computeScrollOffset();
getFinalY(); getFinalX(); and getCurrY() getCurrX()
getDuration()

This implies that you have to create a Scroller.
If you want to use touching you could also use GestureDetector and define your own canvas scrolling. The following sample is creating a ScrollableImageView and in order to use it, you have to define the measurements of your image. You can define your own scrolling range and after finishing your scrolling the image gets redrawn.
http://www.anddev.org/viewtopic.php?p=31487#31487
Depending on your code you should consider invalidating (int l, int t, int r, int b); for the invalidation.
Comment: Thanks for your suggestions. The Scroller looks as if it is designed to start a scroll in response to a Fling gesture and to continue scrolling for a distance determined by the programmer (somewhat like the Home screen on HTC phones). However, I want the screen image to move with the user's touch. I have followed ideas in the anddev thread in my app. However, so far as I can see this example only draws the buffer image once. My app has an image of potentially unlimited size which needs to be redrawn when the app is idle (after one scroll has finished and before another starts.)
Answer: SimpleOnGestureListener.onFling()

It seems to take place when a scroll ends (i.e. the user lets the finger go), that's what I am using and it works great for me.
Comment: Sadly, onFling only seems to be called at the end of a quick gesture. I need to redraw, not only after a fling, but at the end of a slow precise scroll as well.
Comment: Thanks for this suggestion. I'm afraid I won't have time to try it out for a few days, but I look forward to seeing if it works for me. It will be very neat if it does!
Comment: It seems onFling really gets called even after a short scroll, but not every time, e.g. if you release it slowly it doesn't. Inside the onFling you need to detect the velocity of the scroll and other stuff.
Answer: Coming back to this after a few months I've now followed a different tack: using a Handler (as in the Android Snake sample) to send a message to the app every 125 milliseconds which prompts it to check whether a Scroll has been started and whether more than 100 milliseconds has elapsed since the last scroll event.
This seems to work pretty well, but if anyone can see any drawbacks or possible improvements I should be grateful to hear of them.
The relevant the code is in the MyView class:
public class MyView extends android.view.View {

...

private long timeCheckInterval = 125; // milliseconds
private long scrollEndInterval = 100;
public long latestScrollEventTime;
public boolean scrollInProgress = false;

public MyView(Context context) {
    super(context);
}

private timeCheckHandler mTimeCheckHandler = new timeCheckHandler();

class timeCheckHandler extends Handler{

        @Override
        public void handleMessage(Message msg) {
        long now = System.currentTimeMillis();
        if (scrollInProgress && (now>latestScrollEventTime+scrollEndInterval)) {
                    scrollInProgress = false;

//              Scroll has ended, so insert code here
//              which calls doDrawing() method
//              to redraw bitmap re-centred where scroll ended
                    [ layout or view ].invalidate();
        }
        this.sleep(timeCheckInterval);
        }

        public void sleep(long delayMillis) {
            this.removeMessages(0);
            sendMessageDelayed(obtainMessage(0), delayMillis);
            }
    }
}

@Override protected void onDraw(Canvas canvas){
        super.onDraw(canvas);

//      code to draw large buffer bitmap onto the view's canvas
//      positioned to take account of any scroll that is in progress
}

public void doDrawing() {

//      code to do detailed (and time-consuming) drawing
//      onto large buffer bitmap
//      the following instruction resets the Time Check clock
//      the clock is first started when
//      the main activity calls this method when the app starts
        mTimeCheckHandler.sleep(timeCheckInterval);
}

//  rest of MyView class
}
and in the MyGestureDetector class
public class MyGestureDetector extends SimpleOnGestureListener {

@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
        float distanceY) {

    [MyView].scrollInProgress = true;
        long now = System.currentTimeMillis();
    [MyView].latestScrollEventTime =now;

    [MyView].scrollX += (int) distanceX;
    [MyView].scrollY += (int) distanceY;

//      the next instruction causes the View's onDraw method to be called
//      which plots the buffer bitmap onto the screen
//      shifted to take account of the scroll
    [MyView].invalidate();

}

// rest of MyGestureDetector class
}
Comment: Although this worked OK the answer provided by Akos Cz on 29-09-2010 (see above) is much neater. Not only is the code much simpler, but it also avoids any unnecessary delay waiting for a time check. With Akos's code the end of the scroll is detected immediately.
Answer: I was looking into this same issue. I saw Akos Cz's answer to your question. I created something similar, but with my version, I noticed that it only worked for a regular scroll - meaning one that doesn't generate a fling. But if a fling did get generated - regardless if I processed a fling or not, then it did NOT detect the "ACTION_UP" in "onTouchEvent". Now maybe this was just something with my implementation, but if it was I couldn't figure out why.
After further investigation, I noticed that during a fling, the "ACTION_UP" was passed into "onFling" in "e2" every time. So I figured that must be why it wasn't being handled in "onTouchEvent" in those instances.
To make it work for me I only had to call a method to handle the "ACTION_UP" in "onFling" and then it worked for both types of scrolling. Below are the exact steps I took to implement my app:
-initialized a "gestureScrolling" boolean to "false" in a constructor.
-I set it to "true" in "onScroll"
-created a method to handle the "ACTION_UP" event. Inside that event, I reset "gestureSCrolling" to false and then did the rest of the processing I needed to do.
-in "onTouchEvent", if an "ACTION_UP" was detected and "gestureScrolling" = true, then I called my method to handle "ACTION_UP"
-And the part that I did that was different was: I also called my method to handle "ACTION_UP" inside of "onFling".
Comment: Thanks for this very clear summary. The code I have ended up with is very similar to yours except that I have not bothered to test for ACTION_UP inside onFling ... I simply treat every onFling call (regardless of its ACTION type) as the end of a scroll (assuming that the scrolling flag is true when onFling is called) in the same way as I treat an ACTION_UP event detected in the onTouch call of the onTouchListener.
Comment: I believe every fling happens as a result of a quick scroll and an ACTION_UP, so I think you are right that there is no need to test for ACTION_UP, but just always assume every fling is the end of a scroll. Using that same logic, do you really need to test to see if the scrolling flag is true in onFling, because if I am not mistaken, you can't have a Fling without a scroll proceeding it, so I don't think you would need to check if your scroll flag is set.
Comment: Yes, I think you're right! However, I think I still need the scroll flag in order to detect (in onTouch) the end of a scroll that is too slow to be treated as a fling, so will need to keep the statement in onFling (as well as in onTouch) which sets the flag to false.
Answer: I am sure it is too late for you, however, it seems I have found the right solution to your original question and not necessarily the intention.
If you are using Scroller/OverScroller Object for scrolling you should check the return value from the following function.
public boolean computeScrollOffset()

Comment: Thanks for your suggestion. As I mentioned above, the Scroller looks as if it is designed to start a scroll in response to a Fling gesture and to continue scrolling for a distance determined by the programmer (somewhat like the Home screen on HTC phones). However, I want the screen image to move with the user's touch.
Answer: I think this will work as you need
protected class SnappingGestureDetectorListener extends SimpleOnGestureListener{

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY){
        boolean result = super.onScroll(e1, e2, distanceX, distanceY);

        if(!result){
            //Do what you need to do when the scrolling stop here
        }

        return result;
    }

}

Comment: In theory maybe, but in practice that doesn't work as expected: you receive false even during scrolling.
Comment: SimpleOnGestureListener does always return false
Answer: This is what worked for me.
I've enriched the existing GestureDetector.OnGestureListener with onFingerUp() method. This listener does everything as the built-in GestureDetector and it can also listen to the finger up event (it's not onFling() as this is called only when the finger is lifted up along with a quick swipe action).
import android.content.Context;
import android.os.Handler;
import android.view.GestureDetector;
import android.view.MotionEvent;

public class FingerUpGestureDetector extends GestureDetector {
    FingerUpGestureDetector.OnGestureListener fListener;
    public FingerUpGestureDetector(Context context, OnGestureListener listener) {
        super(context, listener);
        fListener = listener;
    }

    public FingerUpGestureDetector(Context context, GestureDetector.OnGestureListener listener, OnGestureListener fListener) {
        super(context, listener);
        this.fListener = fListener;
    }

    public FingerUpGestureDetector(Context context, GestureDetector.OnGestureListener listener, Handler handler, OnGestureListener fListener) {
        super(context, listener, handler);
        this.fListener = fListener;
    }

    public FingerUpGestureDetector(Context context, GestureDetector.OnGestureListener listener, Handler handler, boolean unused, OnGestureListener fListener) {
        super(context, listener, handler, unused);
        this.fListener = fListener;
    }

    public interface OnGestureListener extends GestureDetector.OnGestureListener {
        boolean onFingerUp(MotionEvent e);
    }

    public static class SimpleOnGestureListener extends GestureDetector.SimpleOnGestureListener implements FingerUpGestureDetector.OnGestureListener {
        @Override
        public boolean onFingerUp(MotionEvent e) {
            return false;
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (super.onTouchEvent(ev)) return true;
        if (ev.getAction() == MotionEvent.ACTION_UP) {
            return fListener.onFingerUp(ev);
        }
        return false;
    }
}

Answer: I haven't done this myself but looking at onTouch() you always get a sequence 0<2>1, so the end has to be a 1 for finger lift.
Comment: Similar question for a ListView:

http://stackoverflow.com/questions/1768391/how-to-detect-android-listview-scrolling-stopped
Comment: Thanks for the suggestion. I've added "implements OnTouchListener" to the definition of the View class, so the whole line reads 'public class MyView extends android.view.View  implements OnTouchListener {'. However, the onTouch() method never seems to be called when I tap or scroll. Does the fact that I have a separate GestureDetector class which 'extends SimpleOnGestureListener' mean that the OnTouchListener gets by-passed?
Comment: Rob Kent, I've only just seen your comment. So far as I can see the OnScrollListener is only available for a ListView. I'm working with a drawing Canvas on a View that 'extends android.view.View'. Do you know if there's a way I can use an OnScroll method with this (other than the GestureListener I'm already using)?
Answer: i have not tried / used this but an idea for an approach:
stop / interrupt redrawing canvas on EVERY scroll event wait 1s and then start redrawing canvas on EVERY scroll.
this will lead to performing the redraw only at scroll end as only the last scroll will actually be uninterrupted for the redraw to complete.
hope this idea helps you :)
Comment: Thanks for the suggestion. However, I don't think it will help me. I don't want to interrupt the redrawing because I want to scroll smoothly. My approach to this is to do the detailed drawing to a buffer bitmap then in the onDraw() method to plot this bitmap onto the View's canvas. During the course of the Scroll I replot the bitmap shifted slightly to reflect the scroll. What I want to do is detect when the Scroll has ended so that I can redraw the buffer bitmap (which is time-consuming) ready for the next scroll.
Answer: I don't know Android, but looking at the documentation it seems Rob is right: Android ACTION_UP constant Try checking for ACTION_UP from getAction()?
Edit: What does e1.getAction() show? Does it ever return ACTION_UP? The documentation says it holds the initial down event, so maybe it'll also notify when the pointer is up
Edit: Only two more things I can think of. Are you returning false at any point? That may prevent ACTION_UP
The only other thing I'd try is to have a seperate event, maybe onDown, and set a flag within onScroll such as isScrolling. When ACTION_UP is given to onDown and isScrolling is set then you could do whatever you want and reset isScrolling to false. That is, assuming onDown gets called along with onScroll, and getAction will return ACTION_UP during onDown
Comment: Yes, I've tried checking getAction() but it always returns 2 when onScroll is called. The only "up" event that is recognised by onGestureListener is onSingleTapUp; this is not returned at the end of a Scroll.
Comment: But in this code they listen for ACTION_UP within onScroll of a SimpleOnGestureListener: http://code.google.com/p/connectbot/source/browse/trunk/connectbot/src/org/connectbot/Console.java?r=54
Comment: Thanks, Bob. This is a mystery. I've inserted `Log.i("onScroll", Integer.toString(e2.getAction()));` as the first statement in onScroll and LogCat just shows a string of "2"'s when I scroll. If I put the Log statement after `if(e2.getAction() == MotionEvent.ACTION_UP)` nothing is logged in LogCat even when I end the scroll.
Comment: Sorry, just trying to eliminate possibilities here. See my edit above
Comment: Thanks again for your suggestions. Unfortunately, e1.getAction() returns only 0.
Comment: Alright, with those last two suggestions I'm out of ideas. Sorry I can't be more helpful
Comment: My onScroll code returns 'false'. I've tried changing this to 'true' but e2.getAction() still always returns 2 and e1.getAction() still returns 0. How might returning 'true' help? The Android reference says that 'true' should be returned if the event is consumed, so doesn't 'true' prevent any further action in response to the touch/scroll? I'll have a look at your onDown suggestion ...
Comment: I've added code for onDown(), but all I see in LogCat is a single 0 from onDown followed by 2's from onScroll, so I can't see how this could help, I'm afraid. Thanks very much for all your suggestions.
Answer: Extract from the onScroll event from GestureListener API: link text

public abstract boolean onScroll
  (MotionEvent e1, MotionEvent e2, float
  distanceX, float distanceY) Since: API
  Level 1
Returns
      * true if the event is consumed, else false

Perhaps once the event has been consumed, the action is finished and the user has taken their finger off the screen or at the least finished this onScroll action
You can then use this in an IF statement to scan for  == true and then commence with the next action.
Comment: Thanks for this. Are you suggesting that my code should call the onScroll method and check what it returns. If so, I'm not sure how to do this. I thought that it was a method called by the system to run code inserted by me. I was puzzled by the word "returns" in the documentation, but assumed that they meant to say "return" ... in other words my code should return true at the end of the method if the event had been consumed and false otherwise. Can you clarify for me, please?
Comment: Use the return from the touch event as a cue for when the finger has been lifted! When the function returns true the event has finished. So using it in an: If(onScroll == True) { DoThis(); } Else { EffectErrorHandler();} and viola!
Comment: Thanks for your further comment, Blue. I'm afraid I still don't understand what you mean. The onScroll() method is an over-ridden method of OnSimpleGestureListener (it is a method of a class which "extends" SimpleOnGestureListener) and is called by the Android system when a finger is dragged across the screen. How do I call it? Where in my code should I put the call? What arguments should I provide?
Comment: The Android Reference for SimpleOnGestureListener is confusing: the section for OnScroll says that the method "returns
true if the event is consumed, else false" but the Class Overview says the class "does nothing and return false for all applicable methods".
Answer: My attempt at adding additional functionality to the gesture detector. Hope it helps someone put his time to better use... gist
Answer: If you're using SimpleGestureDetector to handle your scroll events, you can do this
fun handleTouchEvents(event: MotionEvent): Boolean {
    if(event.action == ACTION_UP) yourListener.onScrollEnd()
    return gestureDetector.onTouchEvent(event)
}


How to classify an empirical distribution into a group

Question: How can I check that an empirical distribution function belongs to a group of empirical distribution functions?
Imagine I have some customers who have been classified into some groups. Each person has an empirical distribution for price of his previous purchases. Each group therefore has a collection of empirical distributions. If I have a new customer with a new empirical distribution of price of his purchases, how could I say how likely it is that this distribution is similar to each group?
Comment: I can't tell what really counts as "similar" for your purposes. There are infinities of possible measures. What might be good for one purpose may be less good for another.
Comment: you'll need a measure of similarity to compare which things are more similar; and if you want to say something about relative probability of being from various groups you'd need a model and some priors.
Comment: @Glen_b thanks for your response, and which measure of similarity you propose?
Answer: I made a new distribution for each group instead of collection of distribution for each group. Then I normalized distribution in the way integral of distribution be 1. so at the end I just calculate similarity of two distribution.
Answer: "similar" distributions means the type of distribution is the same , for example two normal distributions with different parameters are similar, but in these two normal distributions if parameters have exactly same values we call them " identical " , if you want to check on whether your empirical distribution belongs to a collection of known distributions you should use statistical tests such as shapiro-wilk , Anderson-Darling for testing whether the distribution is normal or not , and kolmogorov-smirnov in non-parametric situation for testing goodness- of - fit between the empirical distribution function to the true cumulative distribution function .
i hope that would be helpful for you !
Rozhan :)
Comment: Could you explain why this notion of "similar" would be relevant for the problem expressed in the question?  For instance, if two customers appear to have gamma distributions of purchase price with exactly the same shape parameter but one has twice the scale of the other--so they are "similar" but not identical according to your definition--I think that the business owner would be *very* interested in that factor of two difference and far less interested in the similarity of distributional shapes.


xmlpull can not load any factory class

Question:
I am trying to use apktool to decompile apk files using the command shown below but it is not able to decode the Android manifest and throws an exception. I have tested it with different apps and get the same exception always. I have the jar of xmlpull-126.96.36.199, xmlpull_1_0_5, and kxml2 in my jre lib path (i.e., /usr/lib/jvm/java-7-openjdk-amd64/jre/lib/ext/) and I have included these paths in the CLASSPATH. How do I resolve this please?

<code>apktool d uk.co.houseoffraser.apk
</code>

I: Using Apktool 2.3.0 on uk.co.houseoffraser.apk
  I: Loading resource table...
  I: Decoding AndroidManifest.xml with resources...
  Exception in thread "main" brut.androlib.AndrolibException: Could not decode XML
      at brut.androlib.res.decoder.XmlPullStreamDecoder.decode(XmlPullStreamDecoder.java:145)
      at brut.androlib.res.decoder.XmlPullStreamDecoder.decodeManifest(XmlPullStreamDecoder.java:153)
      at brut.androlib.res.decoder.ResFileDecoder.decodeManifest(ResFileDecoder.java:140)
      at brut.androlib.res.AndrolibResources.decodeManifestWithResources(AndrolibResources.java:209)
      at brut.androlib.Androlib.decodeManifestWithResources(Androlib.java:137)
      at brut.androlib.ApkDecoder.decode(ApkDecoder.java:113)
      at brut.apktool.Main.cmdDecode(Main.java:160)
      at brut.apktool.Main.main(Main.java:72)
  Caused by: org.xmlpull.v1.XmlPullParserException: could not load any factory class (even small or full default implementation); nested exception is:
      org.kxml2.io.XmlReader
      at org.xmlpull.v1.XmlPullParserFactory.newInstance(XmlPullParserFactory.java:225)
      at org.xmlpull.v1.XmlPullParserFactory.newInstance(XmlPullParserFactory.java:76)
      at org.xmlpull.v1.wrapper.XmlPullWrapperFactory.(XmlPullWrapperFactory.java:52)
      at org.xmlpull.v1.wrapper.XmlPullWrapperFactory.newInstance(XmlPullWrapperFactory.java:29)
      at brut.androlib.res.decoder.XmlPullStreamDecoder.decode(XmlPullStreamDecoder.java:49)
      ... 7 more
Answer: I finally discovered that the xmlpull jar e.g., xmlpull-184.108.40.206.jar, xmlpull_1_0_5.jar is the default xml parser that is always used even if you only have the KXML2 parser in your CLASSPATH. Removing the xmlpull parser from the jre extended library (e.g., /usr/lib/jvm/java-7-openjdk-amd64/jre/lib/ext/) fixes the problem. Even if the CLASSPATH have other xml parsers, as long as only the KXML2 jar is in the jre library, it works.

xmlpull can not load any factory class


Quadratic approximation of $\frac{sin(x)}x$ at $x=0$

Question:
Write down the quadratic $f(0)+f'(0)\Delta x+\frac12f''(0)(\Delta x)^2$ for $f(x)=\frac{sin(x)}x$.

$f(0)$, $f'(0)$ and $f''(0)$ are not defined. How could we produce a quadratic approximation at $x=0$?
Comment: You can use limits
Comment: Since $\sin$ is $C^\infty$ :  $\sin(x) = \sin(0)+ \sin'(0)x +\frac{\sin''(0)}{2!} x^2+ \frac{\sin'''(0)}{3!} x^3+\mathcal{O}(x^4)= x- \frac{x^3}{6}+ \mathcal{O}(x^4)$ so that $\frac{\sin(x)}{x} = 1- \frac{x^2}{6}+\mathcal{O}(x^3)$.
Comment: @user1952009 Just because $\sin$ is $\mathcal C^\infty$ doesn't imply that it equals its own Taylor series. Consider e.g. $1-e^{-x^2}$; other than that the idea is of course correct.
Comment: @Hyperplane Read again I didn't write any series.
Answer: If you call
$$
f(x) = \frac{\sin x}{x}
$$
Use the limit
\begin{eqnarray}
\lim_{x \to 0} f(x) &=& 1 \\
\lim_{x \to 0} f'(x) &=& 0 \\
\lim_{x \to 0} f''(x) &=& -1/3 \\
\end{eqnarray}
So that you have
$$
f(x) = 1 - x^2/6 + O(x^3)
$$
Answer: You could recall that
$$\sin(x)=\sum_{n=0}^\infty\frac{(-1)^nx^{2n+1}}{(2n+1)!}$$
which is the famous expansion for $\sin(x)$.  Then simply divide both sides by $x$.
Answer: I think you are asking about the correctness of the question, rather than the expected answer.
You are absolutely right to wonder about this. $f(x)$ is not defined at $x=0$, so what can $f(0), f'(0), f''(0)$ mean? The question is badly posed.
But in truth it is obvious what the question intends: it is about the function $f$ defined by
$$  f(x) =
\begin{cases}
1,  & \text{if $x = 0$} \\
\dfrac{\sin x}{x}, & \text{if $x \ne 0$}
\end{cases}
$$
And this function is infinitely differentiable at $x=0$.
Comment: Well, when $\frac{g(x)}{h(x)} $ is analytic it is implicit its value at $a, g(a) = 0$ is $\lim_{x \to a}\frac{g(x)}{h(x)}$
Comment: What do you mean by "infinitely differentiable"? Are you trying to say "definitely differentiable"?
Comment: @W.Zhu: $f$ is infinitely differentiable if it is $n$ times differentiable for all positive integers $n$. See for example [this link](http://calculus.subwiki.org/wiki/Infinitely_differentiable_function).


Mapping tomcat apache worker

Question: I am running an Apache2 server connected with Tomcat5.5
Workers.properties
workers.tomcat_home=/usr/share/tomcat5.5
workers.java_home=/usr/lib/jvm/java-6-sun
ps=/
worker.list=worker1
worker.worker1.port=8009
worker.worker1.host=127.0.0.1
worker.worker1.type=ajp13
worker.worker1.lbfactor=1

The JkMount is defined as follows
LoadModule jk_module /usr/lib/apache2/modules/mod_jk.so
JkWorkersFile /etc/apache2/workers.properties
JkLogFile /var/log/apache2/mod_jk.log
JkLogLevel debug
JkLogStampFormat "[%a %b %d %H:%M:%S %Y] "
JkMount /jsp-examples worker1
JkMount /jsp-examples/* worker1
JkMount /servlets-examples worker1
JkMount /servlets-examples/* worker1
JkMount /tcontainer worker1
JkMount /tcontainer/* worker1

If i call 127.0.0.1/servlets-examples, i get the examples displayed and executed correctly.
If i call [same server as above]/tcontainer, i get the following error:
The requested resource (/tcontainer) is not available. (this is an error provided by tomcat5.5)

How can i define where to get the sources?
i have a configuration file in /usr/share/tomcat-5.5-webapps/tcontainer.xml:
<Context path="/tcontainer" docBase="/var/www/web96/html/tcontainer"
   debug="0" privileged="true" allowLinking="true">
</Context>

What did i forget to configure or what is wrong with my definitions?
Thanks
Answer: docBase is the pathname to the web application archive file . So, change:
<Context path="/tcontainer" docBase="/var/www/web96/html/tcontainer"
   debug="0" privileged="true" allowLinking="true">
</Context>

to:
<Context path="/tcontainer" docBase="tcontainer"
   debug="0" privileged="true" allowLinking="true">
</Context>

and try again.

Mapping tomcat apache worker


duplicate categorical variables with different values for multiple linear regression

Question: I am building a regression model and have run into an issue. I'm trying to build a model that predicts the weight of a baby when it is born. One of the explanatory variables is the race of the parents.
In some cases, the baby's parents will have one race and in some, it will have multiple. There is no distinction between the mother or father's race, so essentially I have Parent 1 and Parent 2 as variables. However, the order does not matter, meaning Parent 1 and Parent 2 could have their values swapped with no change to the predictor variable.
I know I have to encode the values categorically but I'm not sure how to handle the Parent 1 and Parent 2 variables such that order doesn't matter. I'm not sure if my issue is coming off as clear so please ask follow-up questions if you're not sure what I'm talking about.
Answer: It seems to me that the mother and the father don't contribute equally to the baby's weight at birth.  Certainly, both contribute nuclear DNA, which would have some influence, but the mother's nutritional status potentially matters more.  Thus, I would analyze the data using two categorical variables (viz., mothers_race, and fathers_race).  If you are really committed to only caring about what the combination of the races is, then make just one categorical variable, with all possible combinations (irrespective of order) as the levels (i.e., both_white, both_black, both_asian, ..., white_black, etc.).
Comment: thanks for the response! I have a different question. What about the case where I'm doing something like top 4 actors in a movie to predict box office success? This strategy wouldn't work because there are too many combinations and not enough data points. What would you suggest for that?
Comment: @BaileyKumar, you should probably ask a new question for that. I would have a variable for each actor under consideration. It isn't sensible that all the actors in the universe matter--it's probably just the top 20 or so stars.


Growth of Limits of $n$-th Terms in Series

Question: I have two divergent series when summed up to infinite $n$: $\frac{1}{n}$ and $\frac{2^n - 2}{2^n}$.  However, in the limit of increasingly large $n$, the $n$-th term of $\frac{1}{n}$ is $0$ and the $n$-th term of the second series goes to $1$ in the limit.
Basically, my question is although both are divergent as infinite series, what is the speed with which the $n$-th term approaches $0$ in the first case and what is the speed with which the $n$-th term approaches $1$ in the second case?  My guess is that in the first case the speed of decay is slower than exponential whereas the speed of the growth of the second case is slower than logarithmic, but what is the formal analysis way to express this?  Can it be shown that one decays slower than the other grows?
Answer: Note that the second one can be expressed as $1-\frac{1}{2^{n-1}}$. This means that the second approaches $1$ faster than the first approaches $0$, because $2^{n-1}$ grows faster than $n$.
Comment: What is the formal way to encapsulate this usually?  Does one just use the big O notation or something like that?
Comment: Yeah, for asymptotic analysis one will usually use big-O to formalize faster or slower growth rates


What is vector for specific word in CBOW word2vec?

Question: Classical CBOW word2vec looks like:

What is vector for specific word in this scheme? How it obtains from WI and WO matrixes? Or useful word-vectors obtains only from Skip-gram word2vec?
Answer: With regard to the diagram you've shown, each row in the WI matrix is a word-vector. (After training, when you ask the model for a word like 'cat', it will find out which slot from 0 to V stores 'cat', then return that row of the WI matrix.)
WI is initialized with random, low-magnitude vectors. WO is left as zeros at the beginning of training. During training, various rows of WO and WI are repeatedly improved, via back-propagation corrective nudges, to make the network's output layer more predictive of each (context)->(word) training example.
For skip-gram, you can think of the input-layer in this diagram as a one-hot encoding of the single context input-word. For CBOW, you can think of the input layer in this diagram as having the count of each word in the multi-word context as the xi values – most zero (sparse). In practice in CBOW, each word is looked up in WI and their word-vectors are averaged to create the hidden-layer activation.
Both skip-gram and CBOW work OK to create useful word-vectors inside WI.


When the average will change?

Question: I have a random number (eg 455,835). Starting from 615 downwards I would like to calculate when the two integers average changing.
For example. I know that 603 and 755's average is 679. How can I calculate it with an equation that the next change will happen at 598?
I can only work with natural numbers. Rational numbers are not allowed.
Edit:
Clarification from eyeballfrog:

So the idea is you have some arbitrary number N choose various x<N.
You calculate another number y=⌊N/x⌋, then take the truncated average
⌊(x+y)/2⌋, and want to know when that average changes.

Sample
Comment: So the idea is you have some arbitrary number $N$ choose various $x < N$. You calculate another number $y = \lfloor N/ x\rfloor$, then take the truncated average $\lfloor (x + y)/2\rfloor$, and want to know when that average changes. Do I have this correct?
Comment: I am not sure I understand how your list is generated. For in the beginning you take the pair $(615, 741)$ then $(614, 742)$ so the first number ticks down and the second ticks up. The two numbers naturally average to the same constant each time because at the $n$:th iteration you are calculating $\frac{(615-n) + (741+n)}{2}=\frac{615+741}{2}$. But, then you skip $761$ which should be at row $22$?
Comment: Hi. In B:4 you can see the equation how the B column is calculated. Integer division. Column A is just -1 each time.
Comment: @eyeballfrog Yes, it is correct.
Answer: The properties of flooring allow us to simplify the expression to
$$
\left\lfloor \frac{ x + N/x}{2}\right\rfloor
$$
We can also tell that the value will change between $x$ and $x + 1$ if there is a real number $y$, $x < y < x+1$ such that $(y + N/y)/2$ is an integer. Calling this integer $k$, we can set $k = (y + N/y) /2$ and solve for $y$ to get
$$
x = \lfloor y \rfloor = \lfloor k \pm \sqrt{k^2 - N}\rfloor
$$
Applying this formula to the values $[678, 683]$ gives $615, 606, 598, 591, 585, 579$, which lines up perfectly with the spreadsheet.
Comment: Thank you. It works flawlessly.

When the average will change?


How to write Pandas dataframe to sqlite with Index

Question: I have a list of stockmarket data pulled from Yahoo in a pandas DataFrame (see format below). The date is serving as the index in the DataFrame. I want to write the data (including the index) out to a SQLite database.
             AAPL     GE
Date
2009-01-02  89.95  14.76
2009-01-05  93.75  14.38
2009-01-06  92.20  14.58
2009-01-07  90.21  13.93
2009-01-08  91.88  13.95

Based on my reading of the write_frame code for Pandas, it does not currently support writing the index. I've attempted to use to_records instead, but ran into the issue with Numpy 1.6.2 and datetimes. Now I'm trying to write tuples using .itertuples, but SQLite throws an error that the data type isn't supported (see code and result below). I'm relatively new to Python, Pandas and Numpy, so it is entirely possible I'm missing something obvious. I think I'm running into a problem trying to write a datetime to SQLite, but I think I might be overcomplicating this.
I think I may be able to fix the issue by upgrading to Numpy 1.7 or the development version of Pandas, which has a fix posted on GitHub. I'd prefer to develop using release versions of software - I'm new to this and I don't want stability issues confusing matters further.
Is there a way to accomplish this using Python 2.7.2, Pandas 0.10.0, and Numpy 1.6.2? Perhaps cleaning the datetimes somehow? I'm in a bit over my head, any help would be appreciated.
Code:
import numpy as np
import pandas as pd
from pandas import DataFrame, Series
import sqlite3 as db

# download data from yahoo
all_data = {}

for ticker in ['AAPL', 'GE']:
    all_data[ticker] = pd.io.data.get_data_yahoo(ticker, '1/1/2009','12/31/2012')

# create a data frame
price = DataFrame({tic: data['Adj Close'] for tic, data in all_data.iteritems()})

# get output ready for database export
output = price.itertuples()
data = tuple(output)

# connect to a test DB with one three-column table titled "Demo"
con = db.connect('c:/Python27/test.db')
wildcards = ','.join(['?'] * 3)
insert_sql = 'INSERT INTO Demo VALUES (%s)' % wildcards
con.executemany(insert_sql, data)

Result:
---------------------------------------------------------------------------
InterfaceError                            Traceback (most recent call last)
<ipython-input-15-680cc9889c56> in <module>()
----> 1 con.executemany(insert_sql, data)

InterfaceError: Error binding parameter 0 - probably unsupported type.

Comment: If you just want the index as a column in the table, can't you just give your DataFrame a column that duplicates the index?
Answer: In recent pandas the index will be saved in the database (you used to have to reset_index first).
Following the docs (setting a SQLite connection in memory):
import sqlite3
# Create your connection.
cnx = sqlite3.connect(':memory:')

Note: You can also pass a SQLAlchemy engine here (see end of answer).
We can save price2 to cnx:
price2.to_sql(name='price2', con=cnx)

We can retrieve via read_sql:
p2 = pd.read_sql('select * from price2', cnx)

However, when stored (and retrieved) dates are unicode rather than Timestamp. To convert back to what we started with we can use pd.to_datetime:
p2.Date = pd.to_datetime(p2.Date)
p = p2.set_index('Date')

We get back the same DataFrame as prices:
In [11]: p2
Out[11]:
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 1006 entries, 2009-01-02 00:00:00 to 2012-12-31 00:00:00
Data columns:
AAPL    1006  non-null values
GE      1006  non-null values
dtypes: float64(2)

You can also use a SQLAlchemy engine:
from sqlalchemy import create_engine
e = create_engine('sqlite://')  # pass your db url

price2.to_sql(name='price2', con=cnx)

This allows you to use read_sql_table (which can only be used with SQLAlchemy):
pd.read_sql_table(table_name='price2', con=e)
#         Date   AAPL     GE
# 0 2009-01-02  89.95  14.76
# 1 2009-01-05  93.75  14.38
# 2 2009-01-06  92.20  14.58
# 3 2009-01-07  90.21  13.93
# 4 2009-01-08  91.88  13.95

Comment: It looks to me that `price2.to_sql(name='price2', con=cnx)` should instead read `price2.to_sql(name='price2', con=e)`. Since otherwise how would the `price2` data get on the on-disk SQLite db corresponding to "pass your db url" in the first place, in order to be retrieved by `read_sql_table`? At any rate, that works for me. Though I find it puzzling that nobody has visibly commented on this since 2013.
Answer: Unfortunately, pandas.io.write_frame no longer exists in more recent versions of Pandas in regards to the current accepted answer. For example I'm using pandas 0.19.2. You can do something like
from sqlalchemy import create_engine

disk_engine = create_engine('sqlite:///my_lite_store.db')
price.to_sql('stock_price', disk_engine, if_exists='append')

And then in turn preview your table with the following:
df = pd.read_sql_query('SELECT * FROM stock_price LIMIT 3',disk_engine)
df.head()

Comment: ```if_exists='append'``` helps prevent ```ValueError: Table 'abc' already exists``` very useful thanks.
Answer: Below is the code which worked for me. I was able to write it to SQLite DB.
import pandas as pd
import sqlite3 as sq
data = <This is going to be your pandas dataframe>
sql_data = 'D:\\SA.sqlite' #- Creates DB names SQLite
conn = sq.connect(sql_data)
cur = conn.cursor()
cur.execute('''DROP TABLE IF EXISTS SA''')
data.to_sql('SA', conn, if_exists='replace', index=False) # - writes the pd.df to SQLIte DB
pd.read_sql('select * from SentimentAnalysis', conn)
conn.commit()
conn.close()

Answer: Minimal example with sqlite3
Based on Keertesh Kumar's answer.
Writing df to sqlite
import pandas as pd
import sqlite3 as sq

df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
table_name = "test" # table and file name

conn = sq.connect('{}.sqlite'.format(table_name)) # creates file
df.to_sql(table_name, conn, if_exists='replace', index=False) # writes to file
conn.close() # good practice: close connection

Reading sqlite to df
conn = sq.connect('{}.sqlite'.format(table_name))
df = pd.read_sql('select * from {}'.format(table_name), conn)
conn.close()

Answer: Pandas read_sql can set the index for you.
Taking the example from Andy Hayden's answer above, instead of:
p2 = pd.read_sql('select * from price2', cnx)
# When stored (and retrieved) dates are unicode rather than Timestamp.
# Convert back to what we started with we can use pd.to_datetime:
p2.Date = pd.to_datetime(p2.Date)
p2 = p2.set_index('Date')

You can simply do this:
p2 = pd.read_sql('select * from price2', cnx, index_col='Date', parse_dates=['Date'])

This will automatically set the Date column as the index and simultaneously convert it to Timestamps.


Looking for an alternative way to obtain the marginal CDF of a function.

Question: I have the following pdf
$f_{XY}(x,y) = \left \{ \begin{matrix} 6\cdot y & \mbox{ if } 0 \leq y \leq x \leq 1
\\ 0 & \mbox{ otherwise }
\end{matrix}\right.$
I want to obtain $F_X(x)$
I have done it as
$F_X(x):\int_0^x\int_0^t6sdsdt=\int_0^x3t^2dt=x^3$,  $F_{X}(x) = \left \{ \begin{matrix} 0 & \mbox{ if } 0 \geq x
\\ x^3 & \mbox{ if } 0 \leq x \leq 1
\\ 1 & \mbox{ otherwise }
\end{matrix}\right.$
I was wondering if this result could be obtained by first calculating $F_{XY}(x,y)$ and then taking the limit $\lim_{y \to \infty}$. However, the limits of integration of $F_{XY}(x,y)$ confuse me. Can someone help me?
I have tried to integrate as follows: $\int_0^x\int_0^y6sdsdt=3y^2x$, which would be $3x^3$ if $y \geq x$, so I don't know what to do with that 3.
Answer: I think the best way to resolve such confusions is to write density explicitly under the integral.
We are indeed interested in $\int_0^x\, ds \int_0^y\, dt\, f(s, t)$. Assuming $0 \leq x, y \leq 1$, this is equal to $\int_0^x\, ds \int_0^{\min(s, y)}\, dt \, 6t$.
If $y > x$, the later is equal to $\int_0^x\, ds\, 3s^2 = x^3$. This is $F_X$.
If $y < x$, this splits into two parts: $\int_0^y\, ds\int_0^s\, dt\, 6t$ and $\int_y^x\, ds \int_0^y\, dt 6t$. The former is $y^3$, the later is $3y^2(x - y)$. Sanity check: $x = y$ gives the same $x^3$ as above.
To fully specify CDF, we need to include cases $y > 1 \geq x$ (the same as just $1 > y > x$) and $x > 1$ (again splits into two: $y < 1$ or $y \geq 1$), but it's similar to the previous work.


c# Microsoft Access convertendo data

Question: Estou tendo problemas com INSERT e UPDATE pois na minha máquina as datas estão sendo convertidas automaticamente, mas nas máquinas dos usuários não.
Ex:
OleDbCommand cmd = new OleDbCommand("UPDATE tblPendencia " +
                                      " SET CarenciaInicio = " + (String.IsNullOrEmpty(pendencia.CarenciaInicioData.Trim()) ? "null" : "#" + pendencia.CarenciaInicioData + "#") + "," +
                                          " CarenciaFim = " + (String.IsNullOrEmpty(pendencia.CarenciaFimData.Trim()) ? "null" : "#" + pendencia.CarenciaFimData + "#") + "," +
                                          " AberturaData = " + (pendencia.AberturaData == null ? "null" : "#" + pendencia.AberturaData + "#") + "," +
                                          " VencimentoData = " + (pendencia.VencimentoData == null ? "null" : "#" + pendencia.VencimentoData + "#") + "," +
                                          " LiquidacaoData = " + (pendencia.LiquidacaoData == null ? "null" : "#" + pendencia.LiquidacaoData + "#") + "," +
                                          " CentroCusto = '" + pendencia.CentroCusto + "'," +
                                          " DiasDecorridos = " + pendencia.DiasDecorridos + "," +
                                          " Lastro = '" + pendencia.Lastro + "'," +
                                          " Corretora = '" + pendencia.Corretora + "'," +
                                          " AdAm = '" + pendencia.AdAm + "'," +
                                          " Observacao = '" + pendencia.Observacao + "'," +
                                          " Officer = '" + pendencia.Officer + "'," +
                                          " Segmento = '" + pendencia.Segmento + "'," +
                                          " Rating = '" + pendencia.Rating + "'," +
                                          " AlcadaTipo = '" + pendencia.AlcadaTipo + "'," +
                                          " Tipo = '" + pendencia.Tipo + "'" +
                                    " WHERE pendenciaNassauId = " + pendencia.PendenciaId, conn);

cmd.ExecuteNonQuery();

Executando essas queries na minha máquina irá salvar no access a data 11/07/2011, mas se um usuário executar na máquina dele irá salvar correto: 07/11/2011.
No desespero alterei o idioma do windows do office  e até do VS2013 na minha maquina, mas não funcionou.
Parameters: (Erro datatype mismatch)
using (OleDbConnection conn = new OleDbConnection(Conexao.getConexao()))
{
    conn.Open();

    using(OleDbCommand cmd = conn.CreateCommand())
    {
        cmd.CommandText = "INSERT INTO tblLog "+
                          "([operadorId], [logTipoId], [logData], [pendenciaId], [valorFatorAnterior], [valorFatorNovo], [statusIdAnterior], [statusIdNovo], [porContratoIdAnterior], [porContratoIdNovo], [isAtivo]) " +
                          "VALUES ( @operadorId, @logTipoId, @logData, @optionalPendenciaId, @optionalValorFatorAnterior, @optionalValorFatorNovo, @optionalStatusIdAnterior, @optionalStatusIdNovo, @optionalPorContratoIdAnterior, @optionalPorContratoIdNovo, @optionalIsAtivo);";

        cmd.Parameters.AddRange(new OleDbParameter[]
        {
            new OleDbParameter("@operadorId", operadorId),
            new OleDbParameter("@logTipoId", logTipoId),
            new OleDbParameter("@logData", logData ),
            new OleDbParameter("@optionalPendenciaId", optionalPendenciaId),
            new OleDbParameter("@optionalValorFatorAnterior", "'" + optionalValorFatorAnterior + "'"),
            new OleDbParameter("@optionalValorFatorNovo", "'" + optionalValorFatorNovo + "'"),
            new OleDbParameter("@optionalStatusIdAnterior", optionalStatusIdAnterior),
            new OleDbParameter("@optionalStatusIdNovo", optionalStatusIdNovo),
            new OleDbParameter("@optionalPorContratoIdAnterior", optionalPorContratoIdAnterior),
            new OleDbParameter("@optionalPorContratoIdNovo", optionalPorContratoIdNovo),
            new OleDbParameter("@optionalIsAtivo", optionalIsAtivo.ToString())
        });

        cmd.ExecuteNonQuery();
    }
}

Testei da forma abaixo mas está dando datatype mismatch.
cmd1 = new OleDbCommand();
cmd1.CommandType = CommandType.Text;

cmd1.CommandText = "INSERT INTO tblLog " +
                           "([operadorId], [logTipoId], [logData], [pendenciaId], [valorFatorAnterior], [valorFatorNovo], [statusIdAnterior], [statusIdNovo], [porContratoIdAnterior], [porContratoIdNovo], [isAtivo]) " +
                   "VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";

cmd1.Parameters.AddWithValue("@operadorId", operadorId);
cmd1.Parameters.AddWithValue("@logTipoId", logTipoId);
cmd1.Parameters.AddWithValue("@logData", logData );
cmd1.Parameters.AddWithValue("@optionalPendenciaId", optionalPendenciaId);
cmd1.Parameters.AddWithValue("@optionalValorFatorAnterior", optionalValorFatorAnterior);
cmd1.Parameters.AddWithValue("@optionalValorFatorNovo", optionalValorFatorNovo);
cmd1.Parameters.AddWithValue("@optionalStatusIdAnterior", optionalStatusIdAnterior);
cmd1.Parameters.AddWithValue("@optionalStatusIdNovo", optionalStatusIdNovo);
cmd1.Parameters.AddWithValue("@optionalPorContratoIdAnterior", optionalPorContratoIdAnterior);
cmd1.Parameters.AddWithValue("@optionalPorContratoIdNovo", optionalPorContratoIdNovo);
cmd1.Parameters.AddWithValue("@optionalIsAtivo", optionalIsAtivo);

cmd1.Connection = conn1;
cmd1.ExecuteNonQuery();

conn1.Close();

Comment: Coloque todo o código
Comment: Coloquei o update
Comment: porque não utiliza o [parameters](http://stackoverflow.com/questions/5893837/using-parameters-inserting-data-into-access-database)? isso já resolve a conversão de data!
Comment: [Exemplo1](http://stackoverflow.com/questions/15345830/update-command-parameters-in-c-sharp-for-access-2003-not-update) e [Exemplo 2](http://stackoverflow.com/questions/5893837/using-parameters-inserting-data-into-access-database) não faça SQL pura, tem diversos problemas relacionados, então, deixo o framework trabalhar por você
Comment: @VirgilioNovic fiz com o parameters mas estou recebendo o erro de datatype mismatch, eu tenho que enviar os dados formatados?

Ex: new OleDbParameter("@logData", logData ) ou new OleDbParameter("@logData",  "#" + logData + "#" ) ?
Comment: Eu fiz sem as aspas simples e sem o cercadilho, porém me retornou datatype mismatch tbm
Comment: `logData` é qual tipo?
Comment: No BD está como datetime.

Não sei se adiciona algo mas eu abri os parameters no cmd através do watch e lá estava como string.
Comment: @VirgilioNovic Inseri as duas formas utilizando parameters, ambas estão dando datatype mismatch.
Comment: Eu reproduzi um exemplo com tipos de campos que geralmente são usados em uma tabela `ACCESS` e fiz uma respostas, verifique o que isso pode ajudar, porque, o seu erro está sendo de tipos diferentes. Observação: verifica a correlação entre os campos ...
Answer: Sempre quando for utilizar gravações de campos específicos (datetime, decimal, double, bit, etc), existe o Parameters do OleDbCommand para converte de maneira correta os dados enviados para sua tabela em banco de dados ACCESS (essa recomendação serve pra todos os bancos de dados).
Exemplo minimo:
Classe modelo:
public class TableData
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime Created { get; set; }
    public decimal Value { get; set; }
    public bool Status { get; set; }
}

Tabela Layout:

Execução do INSERT nessa tabela TableData
TableData tableData = new TableData();
tableData.Name = "Name 1";
tableData.Created = DateTime.Now;
tableData.Value = 550.90m;
tableData.Status = false;

string ConnStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Temp\db2000.mdb";

using (OleDbConnection connection = new OleDbConnection(ConnStr))
using (OleDbCommand command = connection.CreateCommand())
{

    connection.Open();

    string strIns = "INSERT INTO TableData([Name], [Created], [Value], [Status]) ";
    strIns += " VALUES(@Name, @Created, @Value, @Status);";

    command.CommandType = CommandType.Text;
    command.CommandText = strIns;
    command.Parameters.Add("@Name", OleDbType.VarChar, 50).Value = tableData.Name;
    command.Parameters.Add("@Created", OleDbType.Date).Value = tableData.Created;
    command.Parameters.Add("@Value", OleDbType.Single).Value = tableData.Value;
    command.Parameters.Add("@Status", OleDbType.Boolean).Value = tableData.Status;
    command.ExecuteNonQuery();

}

Para UPDATE segue a mesma idéia do INSERT só alterar a SQL.
Observação: Sempre faça uma classe para representar seus dados, isso ajuda na manutenção, padroniza seu código e organiza cada informação.
Referencias:

Classe OleDbCommand
Propriedade OleDbCommand.Parameters
Estrutura Single
Comment: Dessa forma funcionou perfeitamente! Acredito que ele estava de perdendo com os tipo! Obrigado Virgilio!!

c# Microsoft Access convertendo data


Prove that $\left|\frac{z-w}{1-\bar w z}\right|=1$ if $|z|=1$ and $|w| \neq 1$

Question:
Prove: $\left|\frac{z-w}{1-\bar w z}\right|=1$ if $|z|=1$ and $|w| \neq 1$

My attempt:
I reasoned that either $(z-w)$=$(1-\bar w z)$ or $(z-w)$=$-(1-\bar w z)$ must be true for the whole thing to be true. Going with the first option:
$$(z-w)=(1-\bar w z)$$
$$z-w +\bar wz = 1 $$
$$z(1+\bar w)-w=1$$
$$z=\frac{1+w}{1+ \bar w}$$
At this point, I feel like there is some property of conjugates that I should use, but I'm not sure...
Comment: Note: for complex numbers $a,b$, if you have $|a|=|b|$, this does not mean $a=\pm b$.  For example, $|i|=|1|$, this does not mean $i=\pm1$.
Answer: Hint: $$z-w=z\left(1-wz^{-1}\right)=z\left(1-w\overline{z}\right)$$
Comment: Wait, what? The inverse of a complex number is its conjugate? The inverse of $1+i$ is $\frac{1}{1+i}$. Moving the $i$ to the numerator yields $\frac{1-i}{2}$. The conjugate of $1+i$ is $1-i$. How did you arrive at your last step?
Comment: @whatwhatwhat Is $|1+i|=1$? If $|z|=1$ then $z\overline{z}=1$.
Comment: No, it's $\sqrt{2}$. $|1+i|$ = $\sqrt{1^2+1^2}=\sqrt{2}$...
Comment: Ah, I think I see what you're saying. If $|x+iy|=\sqrt{x^2+y^2}=1$, then $x^2+y^2=1$ and because $(x+iy)(x-iy) =x^2+y^2$, then by that method we also get $1$, which proves that $z\bar z =1$ (because $1*1=1$).
Answer: $$\left|\frac{z-w}{1-\bar w z}\right|^2=\frac{(z-w)(\bar z-\bar w)}{(1-\bar w z)(1- w \bar z)}=\frac{1-z\bar w-w\bar z+|w|^2}{1-\bar w z- w \bar z+|w|^2}=1$$
Comment: How did you get the 2nd part?
Comment: $z\bar z=1$. --


Jquery .after()

Question: O erro no código é que, quando clico no botão "Adicionar" novo input file, a intenção é adicionar apenas um campo após o último, mas o botão triplica.
Meu código HTML está assim:

    <input type="file" name="imagem_file[]" class="form-control">

    <input type="file" name="imagem_file[]" class="form-control">

    <input type="file" name="imagem_file[]" class="form-control">

E o botão para a ação:
<button onClick="addInput();" class="btn btn-sm btn-info">[+]</button>

O javascript está assim:

Se deixar apenas um campo input file, ele gera outro, mas a partir daí ele vai multiplicando pela quantidade que está sendo gerada.
O exemplo no Codepen.io.
Answer: O seletor ".input-files" acerta em 3
 do seu html original, por esse motivo acrescenta um novo elemento a seguir a cada um. Ao invés disso pode apanhar apenas o ultimo acrescentando ao seletor :last

function addInput(){
    $(".input-files:last").after('
<input type="file" name="imagem_file[]" class="form-control">
');
    //----------------^ aqui
}

    <input type="file" name="imagem_file[]" class="form-control">

    <input type="file" name="imagem_file[]" class="form-control">

    <input type="file" name="imagem_file[]" class="form-control">

<button onClick="addInput();" class="btn btn-sm btn-info">[+]</button>

Confirme este seletor na referência de seletores do JQuery.
Alternativamente podia ter utilizado o selector :last-child de CSS, que iria funcionar na mesma.
Comment: @EliseuB. Sim, caso queira remover o ultimo `.input-files` que existe
Comment: Obrigado, é isso mesmo, deu certo! em 9min aceito a resposta por padrão aqui, e para remover faço o mesmo? Uso o :last com o .remove(); né?
Comment: Fiz o remover e deu certo

Jquery .after()