Get node view count for each day

Question: I have site with thousands of user and logins each day. I need to track each page views of each user to generate a report.
If a user 'A' visits a page 'P' today, a new entry daycount is added
to the DB. If the same user 'A' visits the same page 'P' on same day,
the daycount will increment by one. If a user 'A' visits page 'P'
tomorrow, a new entry daycount is added to the DB.
I am using drupal 7. The insert and update works properly if there is no date comparison. Once i added  if($TimeNow > $UpdateTime), the page load never ends. Can anyone help me to fix this.
if(db_query('SELECT daycount FROM {report_page_view} WHERE id = 9999999990 AND uid = :uid )', array(':uid' => $GLOBALS['user']->uid))->rowCount() == 0) {

    $ChQry = "(SELECT timestamp FROM {report_page_view} WHERE id = 9999999990 AND uid = :uid )', array(':uid' => $GLOBALS['user']->uid)"; // Get the previous timestamp
    $ChResult = db_query($ChQry);

    while ( $ChGetResult = $ChResult->fetchAssoc() ) {
       $TimeStm = $ChGetResult['timestamp'];
    }
        $UpdateTime = $TimeStm + 86400; //Get the next day
        $TimeNow = time();
        if($TimeNow > $UpdateTime) { // Compare current time and tomorrows date
        // insert if condition works
        $insert_page = db_insert('report_page_view')->fields(array('title', 'memberorg', 'id', 'type', 'timestamp', 'daycount', 'uid', 'fname', 'lname'));
            $insert_page->values(array(
            'title' => $Title,
            'memberorg' => $MemberOrg,
            'id' => 9999999990,
            'type' => 'views',
            'timestamp' => REQUEST_TIME,
            'daycount' => 1,
            'uid' => $UserId,
            'fname' => $FName,
            'lname' => $LName,

          ));
        $insert_page->execute();
    }
    } // else update
    db_update('report_page_view')
    ->fields(array(
            'title' => $Title,
            'memberorg' => $MemberOrg,
            'id' => 9999999990,
            'type' => 'views',
            'timestamp' => REQUEST_TIME,
            'daycount' => 1,
            'uid' => $UserId,
            'fname' => $FName,
            'lname' => $LName,
    ))
    ->expression('daycount', 'daycount + 1')`

Answer: Consider using the Node view count module for this. Here is a quote about it (from its project page, bold markup added here):

... allows to count node views. Unlike statistics module, this module records each view of node with user uid and timestamp. So now you can know how many times a user viewed node by day, week, month and etc.
This module is integrated with Views module. You can use it to create different statistics pages, output new not viewed nodes for user and many more.

By using this module, and to the extend it should be needed, you can then further refine / extend what you get (out-of-the-box) from this module via a custom module(s) and/or view(s).

Get node view count for each day


How to parse an encoded url that is a query parameter in route Angular 1?

Question: In my routes, I have this. However, I can't find a way to properly decode the url. The page just redirects to the base url (not the redirect url). The url is encoded so / are %2F and what not but I don't know how to make it so I can accept it as a query parameter.

.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
   $stateProvider
   .state('example', {
     url: '/{test}/{queryParameterUrl}',
     controller: 'exampleCtrl as example',
     template: require('./partials/test.html')
   });
Comment: Do you have control over the code triggering the redirect?
Comment: I think curly brackets are for regular expressions. You might need `url: '/:test/:urlredirect'`. Also add `controllerAs: 'example'`
Comment: @Protozoid I have this angular app within a laravel app. So currently the url structure for this page would be /exampleroute/fun/{test}/{urlredirect} but since it's not liking urlredirect it just goes to /exampleroute/fun
Comment: @AlekseySolovey No luck same issue.
Comment: Are you redirecting via the state reference? e.g. `$state.go('example', {test: 'value', urlredirect: 'othervalue'})`
Comment: @Protozoid I am using $stateProvider (added above)
Comment: @savvvycode1 I'm not asking about the definition of the state, I'm asking about the code triggering the redirect e.g. a click on an `` tag
Comment: @Protozoid once I try and go to the url as defined in my state, it automatically redirects me to the base url.
Comment: Can you provide the code were the redirect happens?
Comment: I'm not sure if the confusion is because one of the parameters name is urlredirect. Let me just change it to queryParameterUrl
Comment: The issue is the queryParameterUrl is not being properly recognized.
Comment: Do you want to use the value of `queryParameterUrl` to redirect to that URL at some point?
Comment: @Protozoid yes but I want to store it first then on button click I was going to redirect. But that I know, it's just I've never ran into trying to accept an encoded url as a query string parameter.
Answer: In your exampleController you can access the state parameter, parse it and use it to redirect later on, as such:
app.controller('exampleCtrl', ['$state', function ($state) {
    var exampleCtrl = this;

    exampleCtrl.parsedRedirectUrl = $state.params.urlredirect.replace(/%2F/g, '/')
}]);

And in HTML, for example, redirect using a link
Redirect

P.S. In your state definition, use controllerAs
.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
    $stateProvider
        .state('example', {
         url: '/{test}/{urlredirect}',
         controller: 'exampleCtrl',
         controllerAs: 'example',
         template: require('./partials/test.html')
    });

Comment: Hey Protozoid, thanks for the feedback. I actually was able to solve the issue with https://www.coditty.com/code/angular-ui-router-replacing-slash-with-2f-quick-fix . For some reason angular ui router was not liking the encoded /


Calling externally-located csv data in javascript

Question: I'm trying to get externally-situated csv data to load up in a script, but this fails I think due to browser same origin policy.  I've spotted some relevant looking discussion on working around this using cross-document messaging, but to be honest I don't have a clue how to implement this.  Grateful for advice on this or another workaround.  The script below should print each data line to the browser console but fails.
<code><html>
<head>
    <meta charset='utf-8'>
    <script type="text/javascript" src="scripts/d3.v2.js"></script>
    <title>CSV reader</title>
</head>
<body>
    <script type="text/javascript">
        d3.csv("http://www.quake.utah.edu/EQCENTER/LISTINGS/OTHER/Yell_Q32012TT.csv",
        function(parseCoords) {
          parseCoords.forEach(function(d) {
            console.log(d);
          });
        });
    </script>
</body>
</html>
</code>
Comment: The link to the page is a 404.
Comment: The Lars Kotthoff of mayamap.org fame and MRP?  Link works fine for me, also with http instead of https. http://d3.geotheory.co.uk/csv2.html links to another existing csv example but also fails.
Comment: Hmm, the first link is still not working for me, but the second is. Anyway, one way of getting around the same-origin requirements is [JSONP](http://en.wikipedia.org/wiki/JSONP), although that would require you to convert the data to JSON and is a bit hacky in general. The best solution is to put the data on the same server as the script.
Comment: Yes I'll probably have to do this in some cases, but sadly not a solution for csv-API resources.
Answer: If you are doing something like writing HTML and Javascript in a code editor on your personal computer, and testing the output in your browser, you will probably get error messages about Cross Origin Requests. Your browser will render HTML and run Javascript, jQuery, angularJs in your browser without needing a server set up. But many web browsers are programed to watch for cross site attacks, and will block requests. You don't want just anyone being able to read your hard drive from your web browser. You can create a fully functioning web page using Notepad++ that will run Javascript, and frameworks like jQuery and angularJs; and test everything just by using the Notepad++ menu item, RUN, LAUNCH IN FIREFOX. That's a nice, easy way to start creating a web page, but when you start creating anything more than layout, css and simple page navigation, you need a local server set up on your machine.
Answer: I have seen similar problems linking to a file in the drop box public folders area. (specifically https://dl.dropbox.com/u/101577503/D3-Tips-and-Tricks-Latest.pdf). The first time you click on the link from a web page, the downloading of the pdf fails, then refresh and it works. I don't know why it occurs, but I get the same result when I test your 'http://dl.dropbox.com/u/46043231/data/xy.csv' in Chrome. Is it also possible that even if it works first time that you will be stymied by cross domain limitations?
Comment: I've never had that - it may be something with your browser settings. Nice paper though!
Comment: Cheers. I've seen it in my browser and had reports from others that have seen the same. I have a feeling you're right and it is probably browser based, so I'll transition hosting the files to GitHub. Is the cross domain issue going to affect you?
Comment: I think it is a cross-domain issue as you say. I'm wondering if there is a general javascript workaround to it as I can't believe its not possible to import a simple csv from the web!
Comment: I agree, and while I haven't investigated how to do it, I know that Chris Viau has posted some detail on doing it here; http://groups.google.com/group/d3-js/t/3e581f077d160f14 (About the 7th entry down) I had a quick play with this myself and it didn't work for me, so I'm starting to wonder about the browser I'm using... Hmm....
Comment: Hmm... Perhaps not, I just installed Firefox and have the same result. (I use Chrome normally). Check with Chris on the link above. If you can find a work around, drop me a line and I'll include it in the D3 Tips and Tricks :-)
Comment: Cheers d3noob I'll check it out
Answer: Question abandoned because it seems unanswerable. Will update if I find a solution at a later date.


AR model with vector valued variables (in R)

Question: I want to estimate a vector-valued model
$$\mathbf{y}_t = a\mathbf{y}_{t-1}+b\mathbf{y}_{t-2}+\cdots$$
Here, each $\mathbf{y}_t\in\mathbb{R}^n$ and the coefficients $a,b,\dotsc$ are real numbers (unlike in VAR, where they are matrices). I wonder what the best way to do this in R is. Applying the function ar doesn't seem to work for me ([i] is this only for series that lie in $\mathbb{R}^1$?), and when I apply standard linear regression, I'm not sure how I should test for the order of the model, etc. [ii] Should I go for the $R^2$ value and significance of the coefficients?
Also, I have my data in a matrix $Y$ where each column corresponds to one time point. Currently, I regress as follows
Y = c(Y[,10], Y[,9],..., Y[,2])
Y.l1 = c(Y[,9],..., Y[,1])
fit = lm(Y ~ 0 + Y.l1)

[iii] Is there a more elegant way?
Comment: You have at least three different questions in the post (How to technically implement the model? Does `ar` work with univariate data only? How to select model order?), but they seem to get lost in the flow of the text. You may consider highlighting them by restructuring your post.
Answer: First of all let us state that you are trying to fit the model which is not that common. Since $y_t\in \mathbb{R}^n$ you can always estimate $n$ independent AR models. So your model implies that all these $n$ AR models must have the same coefficients. That is a powerful restriction and you need to be sure, that the process you are trying to model satisfies this restriction.
Having said that, if you are sure that the restriction is feasible, the model is a linear model, so you can use OLS to fit it. Naturally R function ar is not suitable for this model, because as I said such model is not that common, so nobody thought that it is worth implementing.
The model order can be chosen in the same way VAR model order is chosen, i.e. using information criteria. If you fit the model via OLS, you can use AIC and BIC with no problems. Just remember that you need to compare AIC and BIC for models which are fitted on the same sample. For VAR models this means dropping the first $k$ observations, where $k$ is the number of highest lag number you are trying to estimate.
For elegant way of fitting (for my understanding of elegant), I recommend using dplyr and tidyr packages to manipulate your data and then fit using lm.
Suppose your data is a matrix, where data for time periods are in columns:
set.seed(100)
Y<-matrix(rnorm(1000),nrow = 10)
colnames(Y) <- 1:100

> Y[1:5, 1:2]

               1           2
[1,] -0.50219235  0.08988614
[2,]  0.13153117  0.09627446
[3,] -0.07891709 -0.20163395
[4,]  0.88678481  0.73984050
[5,]  0.11697127  0.12337950

Your data is in a wide format and I suggest it to convert to long format:
library(dplyr)
library(tidyr)

dY <- Y %>%
data.frame(check.names = FALSE) %>%
mutate(id = 1:10)  %>%
gather("time",Y,-id, convert = TRUE)

> dY[1:10,]
   id time       Y
1   1    1 -0.50219235
2   2    1  0.13153117
3   3    1 -0.07891709
4   4    1  0.88678481
5   5    1  0.11697127
6   6    1  0.31863009
7   7    1 -0.58179068
8   8    1  0.71453271
9   9    1 -0.82525943
10 10    1 -0.35986213

In this format you have two additional columns which record the time period and to which element of the vector the value corresponds to.
Having such format it is easy to add lagged values of $y$:
dY <- dY %>% group_by(id) %>% mutate(Y.l1 = lag(Y,1), Y.l2 = lag(Y, 2), Y.l3 = lag(Y,3))

To fit the model use lm:
lm(Y~Y.l1,data= dY)

Call:
lm(formula = Y ~ Y.l1, data = dY)

Coefficients:
(Intercept)         Y.l1
    0.01749     -0.01624

To choose the order, you need to fit the model for all orders:
ar1 <- lm(Y~Y.l1, data = dY %>% filter(time > 3))
ar2 <- lm(Y~Y.l1+Y.l2, data = dY %>% filter(time > 3))
ar3 <- lm(Y~Y.l1+Y.l2+Y.l3, data = dY %>% filter(time > 3))

Put them all in the list for easier manipulation:
mods <- list(ar1, ar2, ar3)

Check that the sample size is the same for all models, before calculating AIC/BIC:
> mods %>% sapply(function(x)nrow(x$model))
[1] 970 970 970

Calculate AIC:
> mods %>% sapply(AIC)
[1] 2832.232 2832.308 2832.659

Calculate BIC:
> mods %>% sapply(BIC)
[1] 2846.864 2851.817 2857.045

Comment: Thanks a lot mpiktas. I have to digest this now but I think your answer is very helpful (writing from a newly generated account)
Comment: If you have created two accounts you can ask to merge them: http://stats.stackexchange.com/help/merging-accounts
Comment: Hi @mpiktas, I messaged them. But they seem to ignore it, although they should easily have seen my IP. So, I'm sorry that I can't accept your answer.
Comment: No worries. Maybe moderators are busy at the moment.


Can't get user location in iOS 8

Question: I am trying to get the users location in iOS 8 but I get the following error code: Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.
I have called those methods in my code and I have also created the necessary entries in my Info.plist file. What could be the problem?
Here is my code:
ViewController.h
<code>#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>

@interface ViewController : UIViewController <MKMapViewDelegate,CLLocationManagerDelegate>

@property (nonatomic, strong) IBOutlet MKMapView *mapView;
@property (nonatomic,strong) CLLocationManager *locationManager;

@end
</code>
And my ViewController.m
<code>#import "ViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

@interface ViewController ()

@end

@implementation ViewController
@synthesize mapView;
#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)

- (void)viewDidLoad {
    [super viewDidLoad];
    self.mapView.delegate = self;

    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    if(IS_OS_8_OR_LATER) {
        [self.locationManager requestWhenInUseAuthorization];
        [self.locationManager requestAlwaysAuthorization];
    }
    [self.locationManager startUpdatingLocation];

    self.mapView.showsUserLocation = YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
</code>
What could be wrong?
Comment: have you added NSLocationAlwaysUsageDescription key to you property list ?
Comment: You should either request "when in use" or "always" authorization - not both.  Also I would suggest you use `respondsToSelector` to determine if the authorisation methods are available rather than examining the iOS version.  Have you set a breakpoint to confirm the authorisation request methods are being invoked?
Answer: now you need to add more items in your info.plist file:
NSLocationWhenInUseUsageDescription = "your text" (it may be " ")
NSLocationAlwaysUsageDescription = "your text" (it may be " ")
Answer: Add this to your plist
<code><key>NSLocationAlwaysUsageDescription</key>
<string></string>
<key>NSLocationWhenInUseUsageDescription</key>
<string></string>
</code>
And this lines of code
<code>#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)

    if(IS_OS_8_OR_LATER) {
            [locationManager requestAlwaysAuthorization];
        }
</code>
This worked for me. Hope will work for you too :)

Can't get user location in iOS 8


Control my network

Question: I work on a small company where 4 computers are connected to the Internet through a router. (router is linked to a hub 'switcher I think' and gives all computers internet access).
I want to control the internet connection, here's how

See the data flow of computers, this mean track all data computers send and receive through the internet
Check who is connected and control his bandwidth

may be other things, but that's the most important, I'm looking essentially for a third party software that just DO THAT, I don't want a huge software full of 'crap'.
Any idea how can I do that?
Comment: I believe this could be my motto: I don't want a huge software full of 'crap'.
Answer: You should look into getting untangle (http://www.untangle.com/) and get a dedicated box to run that on.  It's FREE, open source, and allows you to do a lot of things to both monitor traffic, and make the internet safer for your company's network.
If you just want to monitor traffic, I'd suggest you use Wireshark, although it won't let you control that traffic, it will allow you (if you configure the network properly) to see all data in and out of the network.
Comment: +1 for recommending an appliance-like solution
Comment: +1 for Untangle.  We use it, and it's great.
Answer: You can use the hardware/software combinations as the above/below stated. I have another recommendation.
There is Broadcom-based router replacement firmware called Tomato. It can do QoS and track connection information and even has some beautiful bandwidth graphs with totals, monthly usage, etc. It basically turns a $50 router into a fully managed switch that can cost $1000s.
It is installable on a number of routers, I have been using it on a WRT54G router for a while and it works great. It would work great with a small office of 4 PCs.
There is a wiki with lots of information.
Answer: The "easiest" way to control and monitor all of this would be to eliminate the hardware router and put in a PC with multiple NICs. Use it to act as a router, and you can perform filtering, Quality of Service, bandwidth throttling, etc.
Since you're not a large company, this is much more doable. Enterprise solutions would be very expensive for you.
This will give you a start with Linux:  http://newbiedoc.sourceforge.net/networking/homegateway.html
And in case you're running Windows server:
https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5844624.html
Comment: I probably wouldn't call moving from a Netgear style router to a Linux firewall/router "easy" for most people.
Comment: That's why I put easy in quotes. It's probably easier than finding a managed switch, configuring the switch to redirect all traffic to a specific host, and then configuring that host to automagically configure the router to throttle a specific connection (which may not even be possible). See? A linux router becomes "easy". ;-)
Answer: If you want to get into content filtering, you could use something like DansGuardian.  It's a free, open-source content filtering system that doesn't just block by a big list, but actually analyzes the pages as they are being served into the system.  If it doesn't hit any flags, the page is served through to the user, completely transparently, but if it sees something that makes it look bad, it blocks the page.
Answer: Netgear (and many other manufacturers) have/has some managed switches (hardware that you may already have?) that can prioritize bandwidth (through a web interface) and you can use Wireshark (free) to examine traffic.
Answer: The easiest thing would be if the router has NetFlow support. Then you can run a netflow program on your PC. This is just for monitoring use.
Since you ask I don't think it does though.
Answer: You didn't mention cost but there are a number of options on the hardware level.  Barracuda and Sonicwall make higher end devices, but you may want to look at the Watchguard Firebox products.  They start at about $600 and can provide a wide range of features like the ones you are looking for.  Just add the Web Blocker to the X10e unit.
Comment: We have an old Firebox here, which I don't have much experience using, with us moving to Untangle and Sonicwall before starting.  As far as I know, they're decent devices, but since this is a very small office that the OP is asking about, I'm tempted to recommend open-source over commercial hardware appliances, for the sole reason of cost alone.  $600 could be much better spent in their organization on a server, another desktop computer, or any other type of IT expense.  Why spend money when you don't have to, right?
Comment: Cost savings is great, but depending on the experience level of the IT administrator, an open source solution may cost far more in the long run if they have to spend hours configuring, troubleshooting, or maintaining it vs a set and forget hardware appliance.
Answer: OK here's the obligatory mention of SQUID.
SQUID is a web proxy so it can handle all web (including ftp://) access. You can restrict content in lots of ways and you can restrict by username and even by time of day, and you can analyse the logs to see exactly what your chaps have been downloading. Best of all SQUID is completely free, and courtesy of http://www.ratsauce.co.uk/notablog/squid27setup.asp easy to get working.
But SQUID isn't a general network monitor, so for example you couldn't intercept or control e-mail. It also can't control bandwidth. If what you really want to control is web access then I can strongly recommend SQUID as I use it at many of our branch offices.
JR

Control my network


How to solve $x^y = ax-b$

Question: I have encountered this equation:
$$x^y = ax-b$$
I know to find $y$ as a function of $x$ then:
$$y\ln(x) = \ln(ax-b)$$
$$y = \frac{\ln(ax-b)}{\ln(x)}$$
or
$$y = \log_x(ax-b)$$
But the problem I need to find $x$ as a function of $y$ and don't know how .
Comment: @Devansh Bhardwaj , the equation is composited by me to solve a problem , y is the number of terms at a geometric sequence , x is the factor , this equation meant to find x using y at any given geometric sequence sum , Ex if the geometric sequence sum is 1000 , the equation will be x^y = 1000x-999 , at sequence sum 10 x^y = 10x-9 , my practical example was that I have programmed a DCA Martingale bot simulator at excel , y is the number of safety orders , x is the volume scaling , the seq. Sum is the number of shares , I thought there is a simple solution but I was so wrong :D
Comment: To be specific this equation is not a part of the simulation itself , but This equation was meant to help me fast limiting the number of assumptions before running the monte Carlo simulation .
Comment: Source of the problem?
Comment: Also, x should be greater than 0 so that $x^y$ is well defined right?
Comment: There is no elementary solution, but it can be solved via the Lambert W function and can also be expressed as a series via the Lagrange inversion theorem. See [here](https://en.wikipedia.org/wiki/Lagrange_inversion_theorem#Example).
Comment: @KStarGamer: Lambert $W$ will not help because there is no $x$ in the exponent.  Similar to why $W$ is useless when solving quintic equations in the case $y=5$.
Comment: @emacsdrivesmenuts ah indeed my mistake. The series solution I mentioned is valid however.
Comment: @KStarGamer: That series only works for integral $y$, or is it generic and also wors for, say $y=\pi$?
Answer: If $y\in \Bbb N$, then the problem is finding roots of a polynomial of degree $y$. This problem has general closed-form representations of roots only for $y\in\{1,2,3,4\}$, for example solutions for linear, quadratic, cubic and quartic equations for the cases 1, 2, 3 and 4, respectively.
Apart from that, there are only few cases that can be reduced to the solutions above:

$y\in\{-1,-2,-3\}$: Multiply the equation with $x^{-y}$ will result in solving a polynomial equation of degree $y+1$.  Notice that $x=0$ needs special treatment.

$y\in\{\frac12,\frac13,\frac14\}$: Substituting $x=z^{1/y}$ will yield a polynomial of degree $1/y$ in $z$.

$y\in\{-\frac12,-\frac13\}$: Substituting $x=z^{-1/y}$ will get us to a polynomial of degree $1-1/y\in{3,4}$.

Approximating Solutions
Apart from that, there are numerical methods like Newton-Raphson iteration that converge very quickly (quadratically) in the general case:
Approximating zeros of $f(x) = x^y-ax+b=0$ by picking some initial value and then iterating
$$x\mapsto x-\frac{f(x)}{f'(x)}
= x-\frac{x^y-ax+b}{yx^{y-1}-a}
= \frac{(y-1)x^y-b}{yx^{y-1}-a}
$$

How solutions change with (small) changes in $y$
The closest you can get to finding $x$ as a function of $y$, is using the implicit function theorem around a solution of the equation.  So let $g(x,y) = x^y-ax+b = 0$ then the total differential is
$$(yx^{y-1}-a)dx + x^y\ln x \,dy = 0$$
so that
$$\frac{dx}{dy} = \frac{x^y\ln x}{a-yx^{y-1}}=:h(x,y)$$
This means that if you found a solution $g(x_0,y_0) = 0$, and you change $y$ a little bit to $y_0+\Delta y$, then the adjusted solution for $x_0$ is around
$$x_0+\Delta x \approx x_0 + \Delta y\frac{x_0^{y_0}\ln x_0}{a-y_0x_0^{y_0-1}}
=\Delta y\cdot h(x_0,y_0)
$$
This is only a hint for $x>0$ (so that we can take $\ln x$) and where the denominator of $h$ is not zero.

Example
Say we have $a=2$ and $b=-4$, then $(x,y) = (2,3)$ is a solution to $g(x,y)=0$.  We want to estimate $x$ when we change $y$ slighly to $y+\Delta y=3.01$. The estimate above tells us we have to expect $x+\Delta x\approx 1.9944548$ whereas the actual solution is around $1.9944853$.
Comment: Thank you so so much for your effort and time , its so helpful and informative , I didn't think that solving this equation is so hard like that , as this equation is composited by me not from a textbook ,I was trying to solve a problem while making a simulation that I need at excel , I thought solving this equation without solver will help me alot , I didn't know its so complicated and indirect like that , thank you again .
Answer: Here are $2$ solutions using Wolfram Alpha with a similar derivation to this solution. The function used is Inverse Beta Regularized $\text I^{-1}_s(a,b)$ which is usually a quantile function. To use it, one must have $0\le s\le 1;a,b>0$:
$$x^y-ax+b=0\implies x=\frac{by\,\text I^{-1}_{-\frac{b^{y-1}(1-y)^{1-y}y^y}{(-a)^y}}(-y,2)}{a(y-1)},y<0,0\le -\frac{b^{y-1}(1-y)^{1-y}y^y}{(-a)^y} \le 1$$
Test the left formula here
and
$$x^y-ax+b=0\implies x=\frac{by}{a(y-1)\text I^{-1}_\frac{b^{y-1}(y-1)}{(-a)^y\left(\frac1y-1\right)^y}(y-1,2)},y>1,0< \frac{b^{y-1}(y-1)}{(-a)^y\left(\frac1y-1\right)^y} <1$$
Test this formula here. For $0<y<1$, try the substitution of $x\to x^{\frac1y}$ and cancel powers.
The question's creator also mentioned excel in a comment, so try using the BETA.INV function instead of InverseBetaRegularized
Answer: We have
$$y=-\frac{\ln(ax-b)+2k\pi i}{\ln(x)}.$$
The function $x\mapsto -\frac{\ln(ax-b)+2k\pi i}{\ln(x)}$ doesn't have a partial inverse that is an elementary function.
It's an open question if the equation has solutions that are elementary numbers.
$\ $
$$x^y=ax-b$$
$$x^y-ax+b=0$$
$$e^{\ln(x)y}-ax+b=0$$
LambertW cannot be applied either.
$\ $
$$x^y=ax-b$$
For rational $y$, this equation is related to an algebraic equation and we can use the known solution formulas and methods for algebraic equations.
For rational $y\neq 0,1$, the equation is related to a trinomial equation.
For real or complex $y\neq 0,1$, the equation is in a form similar to a trinomial equation. A closed-form solution can be obtained using confluent Fox-Wright Function $\ _1\Psi_1$ therefore.
$\ $
Szabó, P. G.: On the roots of the trinomial equation. Centr. Eur. J. Operat. Res. 18 (2010) (1) 97-104
Belkić, D.: All the trinomial roots, their powers and logarithms from the Lambert series, Bell polynomials and Fox–Wright function: illustration for genome multiplicity in survival of irradiated cells. J. Math. Chem. 57 (2019) 59-106

How to solve $x^y = ax-b$


Robust regression or ANOVA for non-normal dependent variable

Question: I have a data set with a dependent variable on a scale from 0 to 100 (n=198). The problem is that many subjects (25) scored exactly 100 but below 100 every score is achieved only once.
This distorts the histogram as you can see on the following link:

I'm trying to run an ANOVA (regression with two contrast coded predictors) and an interaction.
The interaction comes out non-significant, but I was wondering that maybe it is caused by the non-normality of the dependent variable.
Are there any robust methods to avoid this problem?
Answer: First a comment: "robust" usually refers to approaches guarding against outliers and violations of distributional assumptions. In your case, the problem is obviously a violation of distributional assumption, but it seems to depend on your DV (sorry for the pun).
What method to use depends on whether 100 is "truely" the highest possible value of your DV or if your DV measures an unobserved variable that has a latent distribution with possibly infinite values.
For illustration of the "latent variable" concept: On a cognitive test, you want to measure "intelligence", but you only observe if someone solves a question. So if some people solve all the questions, you do not know if these people all have the same intelligence or if there is still some variance in their intelligence scores.
If your DV is of the second kind, you could use tobit regression.
It's more difficult if your DV is really of the first kind, that is, if 100 is truely the highest score that could ever be measured.
And BTW, even with the "right" kind of approach you might still end up with a non-significant interaction.
Comment: @daniel: I don't really know of a good way for that (I would have for the other problem :)) But my guess is that rank-based methods are probably the way to go. OTOH: not knowing the specifics, could it be that participants would have chosen even more if they were able to?
Comment: Thanks for the quick reply! The dependent variable is basically an amount that participants could choose ranging between 0 and 100. So 100 is truly the highest score. Is there any method that maybe gives less weight to the 100s or might some rank-based methods help?
Answer: Rank based tests work by transforming the data to a uniform distribution then relying on the central limit theorem to justify approximate normality (the clt kicks in for the uniform around n=5 or 6), this helps counter the effects of skewness or outliers.  Your data has the opposite problem and the rank transform is unlikely to help (the 100's will still all be ties in the ranks).  For your sample size and the restrictions on the data, the normal theory tests are probably fine due to the clt.  I would be more concerned about unequal variances if some combinations have only 100's or mostly 100's.
If you really want to you could do a permutation test, but I doubt that it will tell you much more than what you have already done, possibly using some statistic based on medians rather than the F-stat may help.
Comment: Not clear on uniform distribution/CLT/normality and rank tests in this context.  But I recommend the proportional odds model for this problem.  It generalizes the Wilcoxon-Mann-Whitney-Kruskal-Wallis test.
Answer: Without knowing that the data are really about it's hard to say.  One potential very general solution is to consider that 100 isn't really 100 (sometimes).  What to do with that is what you need to work out.  You need to come up with a model about what other values 100 is.  Would some people have wanted to pick 1000? 110? 99.9? or was it just a garbage answer?  If you can work that out then you can either throw data away or jitter it in log or linear space.  You could add random noise to the 100s and do it repeatedly and see if outcomes are still relatively consistent across your conditions.
But without much more information it's hard to help.  I hope that I've given you some things to think about.
Comment: the data is basically the amount of money participants were willing to invest ranging from 0 to 100, so yes it is possible that they might have wanted to pick higher values, but in the experiment they were only allowed to pick between 0 and 100, so its not really possible to find out what those values might mean.
Comment: If you've got 200 subjects and don't want to waste your data you might want to look at what happens with a variety of hypotheses about what would happen with a larger scale... or open ended.  You can do that by distributing a proportion of your 100 scores.  I tend to pick those that don't fit the distribution... not all of them.  Explore, and see what happens.
Comment: what exactly do you mean by distributing a proportion of the 100 scores? I've checked separate histograms for each condition and both have similar histograms with the 100s hanging out in the end. I also tried removing all the 100s and seeing whether it becomes significant, but it doesn't.
Comment: For redistributing you've got to come up with a hypothesis about what the scores could be so I can't help you there.  Also, when I say some, you've got to look at the current distribution.  The rest of your data suggest that maybe 10 100s is still lots (assuming they should be something else).  One way to look at it would be to run about 10,000 analysis in a loop keeping a random 10 of your 100s and tossing the rest.  What's the average outcome then?


python etree.ElementTree parse with difficult namespaces

Question: I actually have to parse a online resource but tried to simplify it by coping a .xml file to the directory where I have my currency.py file. Then started with the manual here which is quite short, for a that complex thing in my eyes.
in this sample I cut down the file to 3 items and 2 currencies and parse it as string for simplicity.
import xml.etree.ElementTree as ET
#tree = ET.ElementTree(file='currency.xml')
data = '''
<rdf:RDF xmlns:cb="http://www.cbwiki.net/wiki/index.php/Specification_1.2/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://purl.org/rss/1.0/">
  <channel rdf:about="https://www.snb.ch/de/ifor/media/id/media_rss">
    <title>SNB Devisenkurse</title>
    <link>https://www.snb.ch/de/ifor/media/id/media_rss</link>
    <description>Schweizerische Nationalbank (SNB): Devisenkurse (Ankauf Zürich 11 Uhr)</description>
    <items>
      <rdf:Seq>
        <rdf:li rdf:resource="https://www.snb.ch#GBP_4782176f7871403c002581de004629c7"/>
        <rdf:li rdf:resource="https://www.snb.ch#JPY_4782176f7871403c002581de004629c7"/>
        <rdf:li rdf:resource="https://www.snb.ch#EUR_4782176f7871403c002581de004629c7"/>

      </rdf:Seq>
    </items>
    <dc:publisher>SNB</dc:publisher>
    <dc:rights>Copyright © Schweizerische Nationalbank, Zürich (Schweiz) 2017</dc:rights>
    <dcterms:license>https://www.snb.ch/de/srv/id/disclaimer</dcterms:license>
    <dcterms:created>2017-11-20T19:30:01+01:00</dcterms:created>
  </channel>
  <item rdf:about="https://www.snb.ch#GBP_4782176f7871403c002581de004629c7">
    <title>CH: 1.3116 CHF = 1 GBP 2017-11-20 Tägliche Kurse (11:00)</title>
    <link>https://www.snb.ch</link>
    <description>1 GBP = 1.3116 CHF (Tägliche Kurse (11:00); 2017-11-20T13:46:22.357+01:00)</description>
    <dc:date>2017-11-20T13:46:22.357+01:00</dc:date>
    <dc:language>de</dc:language>
    <cb:statistics rdf:parseType="Resource">
      <rdf:type rdf:resource="http://www.cbwiki.net/wiki/index.php/RSS-CB_1.2_RDF_Schema#Statistics"/>
      <cb:country>CH</cb:country>
      <cb:institutionAbbrev>SNB</cb:institutionAbbrev>
      <cb:exchangeRate rdf:parseType="Resource">
        <rdf:type rdf:resource="http://www.cbwiki.net/wiki/index.php/RSS-CB_1.2_RDF_Schema#ExchangeRate"/>
        <cb:observation rdf:parseType="Resource">
          <rdf:type rdf:resource="http://www.cbwiki.net/wiki/index.php/RSS-CB_1.2_RDF_Schema#Observation"/>
          <cb:value>1.3116</cb:value>
          <cb:unit>CHF</cb:unit>
          <cb:decimals>4</cb:decimals>
        </cb:observation>
        <cb:baseCurrency>CHF</cb:baseCurrency>
        <cb:targetCurrency>GBP</cb:targetCurrency>
        <cb:rateType>Tägliche Kurse (11:00)</cb:rateType>
        <cb:observationPeriod rdf:parseType="Resource">
          <rdf:type rdf:resource="http://www.cbwiki.net/wiki/index.php/RSS-CB_1.2_RDF_Schema#ObservationPeriod"/>
          <cb:frequency>daily</cb:frequency>
          <cb:period>2017-11-20</cb:period>
        </cb:observationPeriod>
      </cb:exchangeRate>
    </cb:statistics>
  </item>
  <item rdf:about="https://www.snb.ch#JPY_4782176f7871403c002581de004629c7">
    <title>CH: 0.8819 CHF = 100 JPY 2017-11-20 Tägliche Kurse (11:00)</title>
    <link>https://www.snb.ch</link>
    <description>100 JPY = 0.8819 CHF (Tägliche Kurse (11:00); 2017-11-20T13:46:22.350+01:00)</description>
    <dc:date>2017-11-20T13:46:22.350+01:00</dc:date>
    <dc:language>de</dc:language>
    <cb:statistics rdf:parseType="Resource">
      <rdf:type rdf:resource="http://www.cbwiki.net/wiki/index.php/RSS-CB_1.2_RDF_Schema#Statistics"/>
      <cb:country>CH</cb:country>
      <cb:institutionAbbrev>SNB</cb:institutionAbbrev>
      <cb:exchangeRate rdf:parseType="Resource">
        <rdf:type rdf:resource="http://www.cbwiki.net/wiki/index.php/RSS-CB_1.2_RDF_Schema#ExchangeRate"/>
        <cb:observation rdf:parseType="Resource">
          <rdf:type rdf:resource="http://www.cbwiki.net/wiki/index.php/RSS-CB_1.2_RDF_Schema#Observation"/>
          <cb:value>0.8819</cb:value>
          <cb:unit>CHF</cb:unit>
          <cb:unit_mult>-2</cb:unit_mult>
          <cb:decimals>4</cb:decimals>
        </cb:observation>
        <cb:baseCurrency>CHF</cb:baseCurrency>
        <cb:targetCurrency>JPY</cb:targetCurrency>
        <cb:rateType>Tägliche Kurse (11:00)</cb:rateType>
        <cb:observationPeriod rdf:parseType="Resource">
          <rdf:type rdf:resource="http://www.cbwiki.net/wiki/index.php/RSS-CB_1.2_RDF_Schema#ObservationPeriod"/>
          <cb:frequency>daily</cb:frequency>
          <cb:period>2017-11-20</cb:period>
        </cb:observationPeriod>
      </cb:exchangeRate>
    </cb:statistics>
  </item>
  <item rdf:about="https://www.snb.ch#EUR_4782176f7871403c002581de004629c7">
    <title>CH: 1.1665 CHF = 1 EUR 2017-11-20 Tägliche Kurse (11:00)</title>
    <link>https://www.snb.ch</link>
    <description>1 EUR = 1.1665 CHF (Tägliche Kurse (11:00); 2017-11-20T13:46:22.343+01:00)</description>
    <dc:date>2017-11-20T13:46:22.343+01:00</dc:date>
    <dc:language>de</dc:language>
    <cb:statistics rdf:parseType="Resource">
      <rdf:type rdf:resource="http://www.cbwiki.net/wiki/index.php/RSS-CB_1.2_RDF_Schema#Statistics"/>
      <cb:country>CH</cb:country>
      <cb:institutionAbbrev>SNB</cb:institutionAbbrev>
      <cb:exchangeRate rdf:parseType="Resource">
        <rdf:type rdf:resource="http://www.cbwiki.net/wiki/index.php/RSS-CB_1.2_RDF_Schema#ExchangeRate"/>
        <cb:observation rdf:parseType="Resource">
          <rdf:type rdf:resource="http://www.cbwiki.net/wiki/index.php/RSS-CB_1.2_RDF_Schema#Observation"/>
          <cb:value>1.1665</cb:value>
          <cb:unit>CHF</cb:unit>
          <cb:decimals>4</cb:decimals>
        </cb:observation>
        <cb:baseCurrency>CHF</cb:baseCurrency>
        <cb:targetCurrency>EUR</cb:targetCurrency>
        <cb:rateType>Tägliche Kurse (11:00)</cb:rateType>
        <cb:observationPeriod rdf:parseType="Resource">
          <rdf:type rdf:resource="http://www.cbwiki.net/wiki/index.php/RSS-CB_1.2_RDF_Schema#ObservationPeriod"/>
          <cb:frequency>daily</cb:frequency>
          <cb:period>2017-11-20</cb:period>
        </cb:observationPeriod>
      </cb:exchangeRate>
    </cb:statistics>
  </item>

</rdf:RDF>'''
tree = ET.fromstring(data)
ns = {'rdf':'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
    'cb': 'http://www.cbwiki.net/wiki/index.php/Specification_1.2/'}
for item in tree.findall('item'):
    for stat in item.findall('cb:statistics', ns):
        for exrate in stat.findall('cb:exchangeRate', ns):
            currency = exrate.find('cb:targetCurrency', ns).text
            print(currency)

So, that's just a MWE. What I actually do is in the end and just a few lines:
tree = ET.fromstring(data)
ns = {'rdf':'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
    'cb': 'http://www.cbwiki.net/wiki/index.php/Specification_1.2/'}
for item in tree.findall('item'):
    for stat in item.findall('cb:statistics', ns):
        for exrate in stat.findall('cb:exchangeRate', ns):
            currency = exrate.find('cb:targetCurrency', ns).text
            print(currency)

now going to terminal and executing:
python3 currency.py
nothing happens...
I would like to get the Currency of JPY (cb:targetCurrency) and multiply it with the 10 x (cb:unit_mult) field. But by now I can't get any .text of a node...
How can I get hold of the currency?
Solution:
import xml.etree.ElementTree as ET
# terminal: cd to this .py file and then do
# $wget https://www.snb.ch/selector/de/mmr/exfeed/rss
# rename the file to rss.xml
tree = ET.ElementTree(file='rss.xml')
root = tree.getroot()
ns = {'rdf':'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
    'none':'http://purl.org/rss/1.0/',
    'dc':'http://purl.org/dc/elements/1.1/',
    'dcterms':'http://purl.org/dc/terms/',
    'cb': 'http://www.cbwiki.net/wiki/index.php/Specification_1.2/'}

for item in root.findall('none:item',ns):
    for statistics in item.findall('cb:statistics',ns):
        for exchangerate in statistics.findall('cb:exchangeRate',ns):
            for  targetcurrency in exchangerate.findall('cb:targetCurrency',ns):
                print(targetcurrency.text)

Comment: Really appreciate the effort to provide a [MCVE](https://stackoverflow.com/help/mcve)! +1
Answer: You didn't account for the default namespace. Descendant elements without prefix implicitly inherits this namespace i.e including the item elements which you try to iterate through :
ns = {'d': 'http://purl.org/rss/1.0/',
     ....}
for item in tree.findall('d:item', ns):
    .....


Posicionar botão em baixo da table não está funcionando

Question: Com esse HTML não consigo posicionar os botões em baixo da tabela. Já tentei várias formas, a atual foi outra tentativa.

            <form style="width:400px; margin: 0 auto;">

                            Código
                            Nome

                            {{ operator.operatorId }}
                            {{ operator.name }}

            </form>

      <button type="submit" class="btn btn-primary" >Atualizar</button>
      <button type="submit" class="btn btn-primary" >Deletar</button>

Veja como aparece os botões Atualizar e Deletar
Answer: O ideal seria "encapsular" os BTNs dentro de uma .row como diz a documentação. Além disso, não vejo porque vc colocar a sua
 dentro de um <form>
Testa com esse código para ver se resolve. Repare que troquei a tag form por uma div e separei os btns em outra row
OBS: Esse código funciona tando no BS3 quanto no 4
Dica: Confira inspecionando os elementos ou no seu CSS se a primeira .row com a tabela não está com position:absolute setado.

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

                            Código
                            Nome

                            {{ operator.operatorId }}
                            {{ operator.name }}

        <button type="submit" class="btn btn-primary" >Deletar</button>
        <button type="submit" class="btn btn-primary" >Atualizar</button>

Comment: Está dentro porque fui fazendo testes e essa foi a última posição. Mas não existe form nessa table, foi apenas para testar
Comment: @pnet já deu um inspect na table para verificar os estilos? Outra coisa, vc "printa" essa tabela na página depois que ela é renderizada? Tente pegar o código do jeito que aparece dando um Ctrl+U na página no Browser, e não o código que vc tem no arquivo.html etc entende. Ai coloca o código na pergunta
Comment: Cara, valeu. Era o css da página: `table {
    width: 60%;
    position: absolute;
    left: 20%;
    top: 15%;
  }

    mat-row:nth-child(even){
    background-color:red;
  }

    mat-row:nth-child(odd){
    background-color:yellow;
  }`
Comment: @pnet sabia que poderia ser isso rss. Tanto que tinha deixado a "Dica:" ai na resposta. Mas que bom que resolveu, acompanhei seu drama ai esses dias com essas perguntas da table e sempre desconfiei que era isso, por isso te mandei inspecionar o elemento!


find the equation of a tangent surface which is parallel to a plane surface

Question: How to get the equation of the tangent surface of $F=x^2 + 2y^2 +3 z^2=21$, which is also parallel to the plane surface $ x+ 4y + 6z=0 $?
Here is what I've tried:
$n = \{1, 4, 6\}$ from $ x+ 4y + 6z=0 $ could be considered as the normal vector for the surface $F$.
$$ F_x = 2x, F_y=4y, F_z = 6z, $$
let $2x = 1, 4y = 4, 6z = 6$, then the tangent point is $(\frac12, 1, 1)$.
the equation representing the tangent surface is $ (x- \frac12) + 4(y-1) + 6(z-1) = 0$.
But I know the result is wrong. Can anyone help on this?
Answer: It is true that the surface you've found is parallel to the plane $x + 4y + 6z = 0$, and it is tangent to a level curve of $F$, but the trouble is that it isn't tangent to the particular level curve $F = 21$.
We need a point on $F = 21$ with gradient parallel to the one you've calculated, which amounts to solving
\begin{eqnarray*}
2x = \lambda \\ 4y = 4\lambda \\ 6z = 6\lambda \\ x^2 + 2y^2 + 3z^2 = 21
\end{eqnarray*}
where $\lambda \neq 0$.  Substituting the first three equations into the last, you should be able to find $\lambda$.  This gets you your $(x,y,z)$ coordinate, and you know what to do from there.


Where to stop a taylor expansion of a function of more than one variable?

Question: I tried to taylor expand a function of three variables $f(x,y,z)$ around $y=0,z=0$ but I don't find a way to decide where to stop the expansion.
Usually when one expands a function of one variable $g(x)$ around $x=0$
$
g(0)+\partial_x g(0) \cdot x + \frac 1 2 \partial^2_x g(0) \cdot x^2 + \mathcal O (x^3)
$
one can immediately say that contributions of (say) $x^3$ or higher can be neglected if $x^3$ is already smaller than the desired precision.
But in the case of three variables I get an expansion like
$
f(x,0,0) + \partial_yf(x,0,0)\cdot y + \partial_zf(x,0,0)\cdot z+\frac 1 2 \big(\partial_y^2f(x,0,0)\cdot y^2  + 2\partial_y\partial_z f(x,0,0)\cdot yz + \partial^2_z f(x,0,0)\cdot z^2\big) + ...
$
but I don't have any clue where to stop. I think the reason is that there are still functions on $x$ to which I can't say anything about their order in opposite to the one dimensional case where just constants appear.
So for example when I say that both $y$ and $z$ are very small but $z$ is way smaller than $y$ and I keep a term like $\partial^2_z f(x,0,0)\cdot z^2$ then there is no reason to neglect the term (say) $\partial_y^7\partial_zf(x,0,0)\cdot y^7z$ since the latter can be bigger than the former for some $x$.
Can someone help me out?
Answer: The Taylor expansion of degree $k$ will involve all terms $x^ay^bz^c$ with $0\le a+b+c\le k$, and then the error will be $O\big((x^2+y^2+z^2)^{(k+1)/2}\big)$. You need to work simultaneously with all three variables.
Comment: thanks for your answer. hm, but then it is pointless for my situation. because in my case $y$ and $z$ are very small (almost 0) and $x$ shall be general. so is there no way to handle that?
Comment: Well, you can handle it by fixing $x=x_0$ for any value of $x_0$ and looking near the point $(x_0,0,0)$. What I said then applies to the polynomial whose terms are of the form $(x-x_0)^ay^bz^c$ ...
Comment: Hm, no this is no option for me. The dependence on $x$ is so important that I can not expand it (I would at least need terms with $x^6$)... but what I did is the following: I just ignored the x dependency and pretended that I have a funcion just of $y$ and $z$. I then just guessed the important orders and the result agrees perfectly with the exact version of the function. I think there must be a way to understand that mathematically...
Comment: Sure. You can do that. Mathematically, we think of a family of functions $f_x(y,z)$, where we view $x$ as a parameter.
Comment: Ok, thanks. But I now have a problem with the error term $\mathcal O\big((y^2+z^2)^{(k+1)/2}\big)$, because my variables have physical units. $y$ is an angle in radiant and $z$ is a length in meter, so adding up $y^2+z^2$ makes no sense. I already saw at some stage before that it is problematic to expand a function in variables with units... but what should I do? I tried to expand in unitless variables but it is a bit artificial then... of course at the end the forced parameter (which I introduced to make a variable unitless) cancels out...
Comment: It seems to me that problem occurs term by term. The units are not going to match up as you go from the zeroth term to the first to the second ...
Comment: no there is no problem since a derivative say $\partial^n_y f$ multiplied with $y^n$ cancels out the unit.
Comment: Oh, well, the error term can be thought of as a polynomial of degree $k+1$, whose coefficients, although not constant, will likewise make each term unitless.
Comment: no, there is still the problem with ADDING up quantities with different units. that does not make sense...
Comment: You are then contradicting yourself. I'm telling you that whatever rationale you have for the terms of degrees $0$, $1$, $\dots$, $k$, applies as well to the remainder term(s).


How to find the Summation of series of Factorials?

Question: $$1\cdot1!+2\cdot2!+\cdots+x\cdot x! = (x+1)!−1$$
I don't understand what's happening here. The given sum of factorials is generalized into a single term. Could somebody please help me finding the logic behind this series.
Thanks in advance!!
Comment: hint: $$n\cdot n!=(n+1)!-n!$$
Comment: To emphasize the hint, the phrase [telescoping series](https://en.wikipedia.org/wiki/Telescoping_series) should come to mind.
Answer: $$
n!\cdot n \quad = \quad n!\Big((n+1) - 1\Big) \quad = \quad  \big(n!(n+1) \big) - \big( n!\cdot1 \big) \quad = \quad (n+1)! - n!.
$$
Therefore
\begin{align}
& 1!1+2!2 + 3!3 + 4!4 + 5!5 \\[10pt]
= {} & \Big(2!-1!\Big) + \big( 3!-2!\Big) + \Big(4!-3!\Big) + \Big(5!-4!\Big) + \big(6!-5!\Big)
\end{align}
Now notice that all terms cancel except the biggest one and the smallest one.
Answer: Michael Hardy's computational proof is the simplest, but there is also a reasonably straightforward combinatorial argument.
There are $(n+1)!-1$ permutations of the set $[n+1]=\{1,2,\ldots,n+1\}$ other than the increasing permutation $\langle 1,2,\ldots,n+1\rangle$. Let $P$ be the set of all such permutations; we'll now calculate $|P|$ in another way.
For $k=1,\ldots,n$ let $P_k$ be the set of permutations $\langle p_1,p_2,\ldots,p_{n+1}\rangle\in P$  such that $p_k\ne k$, and $p_\ell=\ell$ for $1\le\ell<k$. If $\langle p_1,\ldots,p_{n+1}\rangle\in P_k$, $p_k$ cannot be any of the positive integers less than or equal to $k$, so there are $(n+1)-k$ possible choices for $p_k$. Once $p_k$ has been set, $\langle p_{k+1},\ldots,p_{n+1}\rangle$ can be any permutation of the remaining $(n+1)-k$ members of $[n+1]$, so
$$|P_k|=(n+1-k)(n+1-k)!\;.$$
Thus,
$$(n+1)!-1=\sum_{k=1}^n|P_k|=\sum_{k=1}^n(n+1-k)(n+1-k)!=\sum_{\ell=1}^n\ell\cdot\ell!\;,$$
where in the last step I just set $\ell=n+1-k$.


Java spring annotation attribute

Question: I have a post method receiving an object as parameter, in this object I have an attribute with annotations @ValidDate and @NotEmpty.
in another method I want to use the same object but I just want annotation @ValidDate on the attribute.
It's possible ?
the attribute :
@NotEmpty
@ValidDate
private String installDate;

the function :
public String findLinksByCriteria(@Valid @ModelAttribute LinkForm link, BindingResult bindingResult, Model uiModel) {
    if (bindingResult.hasErrors()) {
        return ViewConstants.LINK_SEARCH_VIEW;
    }

Comment: So in situation 1 you want `installDate` to be `@NotEmpty` while in situation 2 it may be empty? I this isn't possible with annotations. I suggest you remove the `@NotEmpty` annotation and check if `installDate` is empty or not by hand when the situation asks for it.
Comment: @Tom yes it's exactly that I want. Ok I will check it by hand. thank you for reply
Answer: Probably one of these thing with multiple solutions. You can remove the optional constraint and do it manually however if you want to keep it strictly within the context of the Bean Validation API then you can do it using validation groups.
https://docs.oracle.com/cd/E19798-01/821-1841/gkahp/index.html

Constraints may be added to one or more groups. Constraint groups are
  used to create subsets of constraints, so only certain constraints
  will be validated for a particular object. By default, all constraints
  are included in the Default constraint group.

By using Spring's @Validated annotation rather than @Valid you can specify one or more groups of constraints to be applied for any given case.
There is a detailed example here:
http://blog.codeleak.pl/2014/08/validation-groups-in-spring-mvc.html

Java spring annotation attribute


How Come My X-CSRF Token And Session One Are Not Generated In The Live Server?

Question: I am trying to upload an application that uses laravel to a live apache server that uses https but I
noticed my post requests stopped working in the process and I noticed that my cookies in the request and response lacked the x-csrf token and session one as well to proceed with the request. For my language switch post (supposed to switch languages) this happens and I get a page expired error
//web.php

Route::post('/language/switch', [LanguageController::class,'switchLanguage'])->name('language.switch');

//languageController.php

public function switchLanguage(Request $request) {
            $language = $request->language;
            app()->setLocale($language);
            $previousUrl = url()->previous();
            $route = Route::getRoutes()->match(Request::create($previousUrl));
            $routeName = $route->getName();
            $newRouteName = preg_replace('/^(en|fr)\.(.*)$/', $language . '.\2', $routeName);
            return redirect()->route($newRouteName);
        }

//navbar.blade.php

                     {{app()->getLocale() == 'en' ? 'English' : 'Français'}}

                     <form action="{{route('language.switch')}}" method="POST">
                       @csrf
                       <input type="hidden" name="language" value="{{app()->getLocale() == 'en' ? 'fr' : 'en'}}">
                       <button class="dropdown-item" type="submit">{{app()->getLocale() == 'en' ? 'Français' : 'English'}}</button>
                     </form>

It is not just the post that gets a page expired error the others do too and I have @csrf on all of them. I tried using a hidden input as well to no avail how can I fix the page expired error?
Comment: Did you try running the optimize:clear command or the view:clear command?
Comment: I don't have a terminal on my live apache unfortunately.
Answer: I used another web host and that seems to have fixed the problem I had.


color yaxis in parallelplot in R-highcharter

Question: This question is an followup on to Parallelcoordinates in R-highcharter R.
Assume we have a parallelplot created by
library(highcharter)
library(purrr)
library(dplyr)

series_lst <-
  iris %>%
  as_tibble() %>%
  asplit(1) %>%
  imap(~list(
    name = paste("observation", .y),
    data = as.numeric(.x[1:4]),
    color = "steelblue"
  ))

hc <-
  highchart() %>%
  hc_chart(parallelCoordinates = TRUE, type = "spline") %>%
  hc_xAxis(categories = names(iris)[1:4]) %>%
  hc_add_series_list(series_lst)

which results in

I now want to customize the y-Axis. Since I am using a dark theme in my app, I need to make the labels white. But in our example, lets say we want to make the y-axis labels red. In highcharter, there are two functions for modifiing the y-axis - hc_yAxis and hc_yAxis_multiples.
I tried
hc %>% hc_yAxis(labels = list(style = list(color = "red")))

which results in making only the labels on the first axis red. I also tried
hc %>% hc_yAxis(labels = rep(list(style = list(color = "red")),4))

but nothing changes. Same for the other function where I tried
hc %>% hc_yAxis_multiples(labels = list(style = list(color = "red")))
hc %>% hc_yAxis_multiples(labels = rep(list(style = list(color = "red")),4))

In the example of highhcarts https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/parallel-coordinates there are also more options for setting up the different y-axes, for example one can change the type or give cutom labels. How to achieve this with the R highcharter-package?
Answer: yAxis_lst <- rep(
  list(
    list(
      labels = list(style = list(color = "red"))
    )
  ),
  4
)

hc <-
  highchart(hc_opts = list(yAxis = yAxis_lst)) %>%
  hc_plotOptions(series = list(label = list(enabled = FALSE))) %>%
  hc_chart(parallelCoordinates = TRUE, type = "spline", reflow = TRUE) %>%
  hc_xAxis(categories = names(iris)[1:4]) %>%
  hc_add_series_list(series_lst)

Yes, these lists look quite complicated :)
One advice I could give here is to use export_hc function. This allows you to save your chart as a javascript code. This way you'll see exactly what each highcharter function does under the hood and it'll be easier to to wrap your head around. Generally it is clear how js output should look to make it work (when you compare to working jsfiddle examples).
The workflow I use is following:

Export your hc to a js file.
Make small edits to R code
Export again
See what's changed
Comment: I tried doing this with `hc_yAxis_multiples` and it in fact was adding one extra (unwanted) layer of list. So I ended up just defining yAxis as a general option.
Comment: Thank you very much again! So I basically forgot to add one layer of `list`


Display price in add to cart form BEFORE add to cart button

Question: the logical flow of choosing attributes is seeing price adjustments based on the attributes chosen before the buy button ... how can i display the price in the form itself so it appears BEFORE the add to cart button?
here is an example of what i am talking about ... you have attributes, then you have price calculations based on attributes selected and very last thing is the buy button ... this is logical and i can't figure it out.
i did try using jquery to append the price to a div inside the form .. but that is a mess. all sorts of problems with ajax etc and not the correct approach anyway.
Comment: When I view an "add to cart" widget and change a product variation, it automatically updates the price via AJAX before I press the buy button.  So I'm pretty sure Commerce 2 works as you want it to, but maybe you don't have something configured correctly.  Please try posting detailed steps about how you set up your variations + add to cart form.
Comment: @Patrick Kenny - thanks for reply. yes, it does the same for me. my issue is that i want the price to appear before the BUY button ... it does not as it is part of the product page and therefore outside of the add to cart form element which means there is no easy way to move the price display BEFORE the buy button. having price appear before add to cart form with attributes or after buy button is not very intuitive.
Comment: Please edit your question with new information, don't just add a bunch of comments.  It's a lot easier to read if people see a question that is cleanly laid out with the relevant information in order. If people see a bunch of messy comments, they are less likely to read them and try to answer the question.
Answer: I also believe the default UX (price above variations, or below add to cart), is a mess.
There's an issue about Moving price before/above add-to-cart button, where I posted a workaround :
<code>/**
 * Implements hook_form_FORM_ID_alter.
 */
function my_theme_form_commerce_order_item_add_to_cart_form_alter(
  array &$form,
  FormStateInterface $form_state
) {
  $form_data = $form_state->getStorage();

  if (!empty($form_data['selected_variation'])) {
    $selectedVariation = ProductVariation::load(
      $form_data['selected_variation']
    );
    $footer_price = $selectedVariation->price->view();
  }
  else {
    $parameter = \Drupal::routeMatch()->getParameter('commerce_product');
    $product = \Drupal\commerce_product\Entity\Product::load(
      (int) $parameter->id()
    );

    $entity_manager = \Drupal::entityTypeManager();

    $product_variation = $entity_manager->getStorage(
      'commerce_product_variation'
    )->load((int) $product->getVariationIds()[0]);

    $footer_price = $product_variation->get('price')->view();
  }

  $form['footer']['price'] = $footer_price;
}
</code>
So far it works, even if I think there might be a slimmer solution. Credits to Alen Simonyan.
Answer: I spent weeks on trying to find a clean solution using the commerce-product.html.twig template but to no avail. The problem is the fact that the variation fields and add-to-cart button are packed together into one component (product.variations) in a way that is difficult to decompose. I cannot think of a way to insert the price in there somewhere. Someone should create an issue about this.
Here is a hacky CSS-workaround.
First, create some space above the add-to-cart button:
<code>.commerce-order-item-add-to-cart-form .form-actions {
   margin-top: 4em;
}
</code>
Now place the price div into the created space:
<code>article .field--type-commerce-price {
   position: absolute;
   bottom: 2.5em;
}
</code>
This also works when the price is updated.
Still looking for a cleaner solution.
Answer: @kojo thanks for your answer. I just had to change it so it would also read my custom PriceResolver. I added 'default' as displayOption for the view so it's now using my calculated formatter.
<code> /**
 * Implements hook_form_FORM_ID_alter.
 * Show price in add to cart form
 */
function template_form_commerce_order_item_add_to_cart_form_alter(array &$form, FormStateInterface $form_state) {
  $form_data = $form_state->getStorage();
  if (!empty($form_data['selected_variation'])) {
    $selectedVariation = ProductVariation::load($form_data['selected_variation']);
  }
  else {
    /** @var \Drupal\commerce_product\Entity\Product $product */
    $product = \Drupal::routeMatch()->getParameter('commerce_product');
    $selectedVariation = $product->getDefaultVariation();
  }
  $form['footer']['price'] = $selectedVariation->price->view('default');
}
</code>
Comment: This looks more like a comment than an answer. You could rephrase the answer so that it's clear that this builds on the answer of someone else and highlight only the additional changes you had to make.


Always returns 'None' when trying to get an element from web page

Question: I'm trying to get the wins from the 'Overall match stats' on this page: https://www.fctables.com/teams/sunderland-194998/?template_id=11. Everything I try it just returns 'None'. This isn't the only page I have tried to use but every one seems to return 'None'. I'm not very advanced in this so any help would be appreciated.
from bs4 import BeautifulSoup
import requests

URL = "https://www.fctables.com/teams/sunderland-194998/"
response = requests.get(URL)

soup = BeautifulSoup(response.text, "html.parser")

wins = soup.find('div', class_='text-success ')
print(wins)

I need it to output the '6' which is the number of wins. Preferably as an integer.
Comment: Try removing the space at the end of `class_='text-success '`.  I see that the space is actually there in the raw html, but I'm guessing the soup parser is trying to be "helpful" by removing it...
Comment: With the space removed, I get `11` as the output.
Answer: You can change how you select the tags:
import requests
from bs4 import BeautifulSoup

URL = "https://www.fctables.com/teams/sunderland-194998/?template_id=11"
response = requests.get(URL)

soup = BeautifulSoup(response.text, "html.parser")

stats = {}
for li in soup.select("h3:-soup-contains('Overall matches stats') + div li"):
    stats[li.p.text] = li.div.text

print(stats["Wins"])

Prints:
6

The stats is a dictionary that contains:
{
    "Matches": "11",
    "Goals": "20",
    "per game": "1.82",
    "Wins": "6",
    "Draws": "1",
    "Losses": "4",
    "Over 2.5": "72.7%",
    "Over 1.5": "81.8%",
    "CS": "36.36%",
    "BTTS": "45.45%",
}

Answer: BeautifulSoup famously is the package that lets
you parse other people's HTML garbage as if it were grammatically correct.
The HTML grammar is, alas, a bit complicated.
You got hung up on the trailing SPACE in the class name.
Just strip it.
>>> from pprint import pp
>>>
>>> pp(soup.find_all('div', class_='text-success '))
[]
>>> pp(soup.find_all('div', class_='text-success'))
[
11
,

1.83
,

4
,

4/6
,

5/6
,

2/6
,

2/6
,

41
,

2.16
,

11
,

78.9%
,

89.5%
,

21.05%
,

68.42%
]

Steve Harvey wants to know, "Could SPACE ever be
part of a valid class name?"
Survey says
"nope!", the SPACE character is specifically prohibited.


How to order regular expression alternatives to get longest match?

Question: I have a number of regular expressions regex1, regex2, ..., regexN combined into a single regex as regex1|regex2|...|regexN. I would like to reorder the component expressions so that the combined expression gives the longest possible match at the beginning of a given string.
I believe this means reordering the regular expressions such that "if regexK matches a prefix of regexL, then L < K". If this is correct, is it possible to find out, in general, whether regexK can match a prefix of regexL?
Comment: If these are all literal strings, you might want to sort the item array alphabetically and by the string length (descending), then join the items with `|`.
Comment: @WiktorStribiżew: Thanks - unfortunately the `regexI` are not all literal strings.
Comment: Hi @PaulBaker , Can you show us an example, or create a http://regex101.com Where we can try out a few things.  It sounds like you are looking for something I also needed a while ago, using REGEX IF/THEN/ELSE.

Also what language would you eventually use this in?  since your question might require comparisions executed outside REGEX et al.
Answer: Use the right regex flavor!
In some regex flavors, the alternation providing the longest match is the one that is used ("greedy alternation"). Note that most of these regex flavors are old (yet still used today), and thus lack some modern constructs such as back references.
Perl6 is modern (and has many features), yet defaults to the POSIX-style longest alternation. (You can even switch styles, as || creates an alternator that short-circuits to first match.) Note that the :Perl5/:P5 modifier is needed in order to use the "traditional" regex style.
Also, PCRE and the newer PCRE2 have functions that do the same. In PCRE2, it's pcre2_dfa_match. (See my section Relevant info about regex engine design section for more information about DFAs.)
This means, you can have ANY order of statements in a pipe and the result will always be the longest.
(This is different from the "absolute longest" match, as no amount of rearranging the terms in an alternation will change the fact that all regex engines traverse the string left-to-right. With the exception of .NET, apparently, which can go right-to-left. But traversing the string backwards wouldn't guarantee the "absolute longest" match either.) If you really want to find matches at (only) the beginning of a string, you should anchor the expression: ^(regex1|regex2|...).
According to this page*:

The POSIX standard, however, mandates that the longest match be returned. When applying Set|SetValue to SetValue, a POSIX-compliant regex engine will match SetValue entirely.

* Note: I do not have the ability to test every POSIX flavor. Also, some regex flavors (Perl6) have this behavior without being POSIX compliant overall.
Let me give you one specific example that I have verified on my own computer:
echo "ab c a" | sed -E 's/(a|ab)/replacement/'
The regex is (a|ab). When it runs on the string ab c a you get : replacement c a, meaning that you do, in fact, get the longest match that the alternator can provide.
This regex, for a more complex example, (a|ab.*c|.{0,2}c*d) applied to abcccd, will return abcccd.
Try it here!
More clarification: the regex engine will not go forward (in the search string) to see if there is an even longer match once it can match something. It will only look through the current list of alterations to see if another one will match a longer string (from the position where the initial match starts).
In other words, no matter the order of choices in an alteration, POSIX compliant regexes use the one that matches the most characters.

Other examples of flavors with this behavior:

Tcl ARE
POSIX ERE
GNU BRE
GNU ERE

Relevant information about regex engine design
This question asks about designing an engine, but the answers may be helpful to understand how these engines work. Essentially, DFA-based algorithms determine the common overlap of different expressions, especially those within an alternation. It might be worth checking out this page. It explains how alternatives can be combined into a single path:

Note: at some point, you might just want to consider using an actual programming language. Regexes aren't everything.
Comment: You might be confused about longest match. The primary function of all regex engines is to get the _leftmost_ match, be it longest or not. It is true POSIX dictates longest match, but that doesn't override leftmost priority. Longest match is a holdover to the time when there was no concept of greedy/non-greedy, it was all greedy. To that extent, alternation construct followed this paradigm. To make the longest match work, it can't have a backtracking mechanism, however it is very slow trying all the permutations.
Comment: @sin `If you apply Set|SetValue to Set or SetValue once, it will match Set` is **wrong** (in the languages I'm talking about). Your other point, about `(a|b.*)` not matching things does not apply to the question at hand here: `knowing if regexK can match a prefix of regexL`.
Comment: @sln I updated my post with a more complex example. AND I updated things for clarity. I understand fully that regexes work leftward through the string to find matches, but my point is that OP asked for **matches at the beginning of the string**, which may mean that they have a regex like this: `^(regex1|regex2|...)`
Comment: PCRE has a DFA mode which essentially always finds the longest match (it's input-driven, not pattern-driven). Same for RE2 etc. You give up sone regex features for this to be possible though.
Comment: As an example of leftmost priority, `(a|b.*)` will not match "a`b_____`" but instead matches "`a`b_____", which is the shortest match but the _leftmost_ match.
Comment: `A POSIX-compliant engine will still find the leftmost match. If you apply Set|SetValue to Set or SetValue once, it will match Set. The first position in the string is the leftmost position where our regex can find a valid match. The fact that a longer match can be found further in the string is irrelevant.` If this weren't true of _all_ regex engines, the language would be useless.
Comment: @Lurel - The question at hand is not if a prefix of two regexes matches here since he states it's not all literals, but is all alternations. Unless its all wildcard matching `.+` or all optional where anything can match anything, it means there will be incongruent distinction. I.e. at some point the alternation items becomes divergent. So the notion of prefixes becomes a simple common factored out issue, but divergent after that. Either way, the examples you show are irrelavent in that he has a mix of literal and wild types. Besides, POSIX doesn't present any rich constructs, simple only.
Comment: And it's always the _leftmost_ match that has highest precedence. Means the shortest match could occur first or not, but it won't be governed by an alternation construct in POSIX unless there is a true prefix within the alternation _AND_ the most important thing, if it is matches at the _current_ (leftmost) character position. The dog wagging the tail is the notion of _leftmost_ not longest.
Comment: I don't think the op means to use the  BOS anchor. But if used, it greatly restricts the alternations. Also, your more complex example is just as I described, filled with wild cards and common characters. In the real world, this just won't happen. The combination of distinction in alternation construct parts and the actual layout of the text will almost certainly guarantee that getting the longest match length will be by accident and have no meaning whatsoever. In that regard, POSIX is irrelevant, and oh so slow and crippled. But, still the OP hasn't shown any regex sample's.
Comment: @Laurel: You mention *these regex flavors are old* - Perl6 is not old, and has a support for an alternation with longest match preference (see [*Longest Alternation*](https://doc.perl6.org/language/regexes#Longest_Alternation)).
Comment: @WiktorStribiżew Fixed it, I was thinking that Perl probably had support for this, but I don't know Perl. I might add more info later from your link.
Comment: @Laurel: Not Perl, Perl6. These are supposed to be different "flavors".
Comment: @WiktorStribiżew I don't know any Perl, so I use `Perl` to mean any/all of the Perl versions. I checked, I have `perl 5, version 12, subversion 3 (v5.12.3)` installed. So close, yet not Perl6. I assume there's a PCRE that has the same setting available, right?
Comment: @Laurel: Perl 6 is a ground-up rewrite of Perl 5, and the regex flavor is very different.  PCRE is based on Perl 5, as are all other "Perl-compatible" or "Perl-derivative" flavors.  If any of them have incorporated longest-token matching, I haven't heard about it.
Comment: @Laurel - I updated to show how this can be done in Perl 5 (>.10) series. Perl is a different animal than PCRE in its integration of regex code constructs `(?{})` and `(?{{}})`.
Comment: @LucasTrzesniewski I searched, and I think you're talking about:`pcre_dfa_exec(), pcre16_dfa_exec() and pcre32_dfa_exec()`, right?
Comment: @Laurel right. Nowadays that would be `pcre2_dfa_match` though, (use PCRE2, it's the newer version). See [here](http://www.pcre.org/current/doc/html/pcre2matching.html).
Comment: I looked at that pcre2 page. The `pcre2_dfa_match()` explanation is convoluted. Says it finds all paths from the beginning of the target string to the end, even though it returns the leftmost longest match. A supreme waste of time and prohibitively slow on open ended repetition. Typical dfa. Have to design a regex with extreme caution. The richness of pcre is dumbed out, no captures, no backreferences, no real useable conditionals. Assertions are there, but who knows what they produce. This is not a model of a modern day regex engine.
Answer: Longest Match
Unfortunately, there is no distinct logic to tell a regular expression
engine to get the longest match possible.
Doing so would/could create a cascading backtracking episode gone wild.
It is, by definition a complexity too great to deal with.
All regular expressions are processed from left to right.
Anything the engine can match first it will, then bail out.
This is especially true of alternations, where  this|this is|this is here
will always match 'this is here' first and
will NEVER ever match this is nor this is here
Once you realize that, you can reorder the alternation into
this is here|this is|this which gives the longest match every time.
Of course this can be reduced to this(?:(?: is)? here)?
which is the clever way of getting the longest match.
Haven't seen any examples of the regex's you want to combine,
so this is just some general information.
If you show the regexes you're trying to combine, better solution could be
provided.
Alternation contents do affect each other, as well as whatever precedes or
follows the cluster can have an affect on which alternation gets matched.
If you have more questions just ask.

Addendum:
For @Laurel. This could always be done with a Perl 5 regex (>5.10)
because Perl can run code from within regex sub-expressions.
Since it can run code, it can count and get the longest match.
The rule of leftmost first, however, will never change.
If regex were thermodynamics, this would be the first law.
Perl is a strange entity as it tries to create a synergy between regex
and code execution.
As a result, it is possible to overload it's operators, to inject
customization into the language itself.
Their regex engine is no different, and can be customized the same way.
So, in theory, the regex below can be made into a regex construct,
a new Alternation construct.
I won't go into detail's here, but suffice it to say, it's not for the faint at heart.
If you're interested in this type of thing, see the perlre manpage under
section 'Creating Custom RE Engines'
Perl:
Note - The regex alternation form is based on @Laurel complex example
(a|ab.*c|.{0,2}c*d) applied to abcccd.
Visually, if made into a custom regex construct, would look similar to
an alternation (?:rx1||rx2||rx3) and I'm guessing this is how a lot of
Perl6 is done in terms of integrating regex engine directly into the language.
Also, if used as is, it's possible to construct this regex dynamically as needed.
And note that all the richness of Perl regex constructs are available.
Output
Longest Match Found:  abcccd

Code
use strict;
use warnings;

my ($p1,$p2,$p3) = (0,0,0);
my $targ = 'abcccd';

# Formatted using RegexFormat7 (www.regexformat.com)

if ( $targ =~
/
   # The Alternation Construct
     (?=
          ( a )                         # (1)
          (?{ $p1 = length($^N) })
     )?
     (?=
          ( ab .* c )                   # (2)
          (?{ $p2 = length($^N) })
     )?
     (?=
          ( .{0,2} c*d )                # (3)
          (?{ $p3 = length($^N) })
     )?
   # Check At Least 1 Match
     (?(1)
          (?(2)
               (?(3)
                 |  (?!)
               )
          )
     )
   # Consume Longest Alternation Match
     (                                  # (4 start)
          (?(?{
               $p1>=$p2 && $p1>=$p3
            })
               \1
            |  (?(?{
                    $p2>=$p1 && $p2>=$p3
                 })
                    \2
                 |  (?(?{
                         $p3>=$p1 && $p3>=$p2
                      })
                         \3
                    )
               )
          )
     )                                  # (4 end)
/x ) {

    print "Longest Match Found:  $4\n";
} else {
    print "Did not find a match!\n";
}

Answer: For sure a human might be able judging whther two given regexp are matching prefixes for some cases. In general this is an n-p-complete problem. So don't try.
In the best case combining the different regexp into a single one will give a suitable result cheap. However, I'm not aware of any algorithm that can take two arbitrary regexp and combine them in a way that the resulting regexp is still matching what any of the two would match. It would be n-p-complete also.
You must also not rely on ordering of alternatives. This depends on the internal execution logic of the regexp engine. It could easily be that this is reordering the alternatives internally beyond your control. So, a valid ordering with current engine mmight give wrong results with a different engine. (So, it could help as long as you stay with a single regexp engine implementation)
Best approach seems to me to simply execute all regexp, keep track of the matched length and then take the longest match.


Compact Subset in $C[0,1]$

Question: Let $S=\{f\in C[0,1]:\max\limits_{x\in[0,1]}(|f|+|f'|)\leq M\}$. Show that $S$ is compact in $C[0,1]$.
I have proved that any sequence in $S$ contains a convergent subsequence by Arzela Ascoli theorem,
but my question is: How can I check that the subsequence converges to the point in $S$ and thus prove that $S$ is compact(sequentially compact)?
Comment: Should not it be $C^1[0,1]$?
Comment: Oh! That's typo. The function in $S$ should be differentiable but it is in the space of continuous function.
Answer: Another way of approach this problem is the following. First prove that
$$||f||:=\max_{x\in [0,1]}(|f(x)|+|f'(x)|)$$
is a norm on $C^1[0,1]$ that is equivalent to the usual supremum norm $||f||_{\infty}=\max_{x\in[0,1]}|f(x)|$. This implies that the topologies induced by these norms are the same.
Now $S$ is precisely the closed ball $B(0,M)$ in the topology induced by $||\cdot||$, which is compact as it is closed and bounded (this is an equivalent to the sequential definition for compactness in metric spaces as you probably know).
Comment: How can I use this norm since the whole space is $C^0[0,1]$ that some of the functions are not differentiable?
Comment: This has to be a typo, the whole space must be $C^1[0,1]$. Mostafa Ayaz already commented about that and you said it was indeed a typo.

Compact Subset in $C[0,1]$


Prove that $\log_n(n+1)\geq\log_{n+1}(n+2)$ for $n>1$

Question:
Prove that $\log_n(n+1)\geq\log_{n+1}(n+2)$ for $n>1$.

So far I only know that $\log_n(n+1)>\frac{\log_n(n+2)}{\log_n(n+1)}$
Since $n>1$, LHS must be greater than RHS.
Is there any other ways to prove this inequality. A proof for this inequality can be found here:
https://brilliant.org/wiki/logarithmic-inequalities/
The proof is incorrect since the author confuses $(\log(n+1))^2$ for $\log(n+1)^2=\log(n^2+2n+1)$. They are different.
Comment: Can I use induction?
Answer: HINT:
Consider the function $$f(x)=\log_x(x+1)=\frac{\log(x+1)}{\log x}.$$ Then $$f'(x)=\frac{\frac{\log x}{x+1}-\frac{\log(x+1)}x}{\log^2x}=\frac{x\log x-(x+1)\log(x+1)}{x(x+1)\log^2x}$$ and since $x$ is positive and $\log$ is monotonically increasing, what is the sign of $f'(x)$?
Comment: If we can show that $f$ is monotonically decreasing then we can prove your inequality. Now the denominator of $f'$  is positive as $x>1$ and because of the square term. What happens to the numerator?
Comment: I don't understand your answer very well. Could you elaborate more on this?
Answer:
The proof is incorrect since the author confuses $(\log(n+1))^2$ for $\log(n+1)^2=\log(n^2+2n+1)$. They are different.

No, the proof is correct. It does not directly substitute one for another, but it uses estimates. The main inequality to be proved is: $(\log(n+1))^2>\log n\log(n+2)$.
It uses the AM-GM (arithmetic mean-geometric mean) to show:
$$(\log(n+1))^2=\left(\frac{\log(n+1)^2}{2}\right)^2>\left(\frac{\log (n(n+2))}{2}\right)^2=\\
\left(\frac{\log n +\log (n+2))}{2}\right)^2\stackrel{AM-GM}{>}\log n\log(n+2).$$
Do not miss the brilliant solution!
Answer: You are correct $( \ln(n+1))^2 \neq \ln((n+1)^2)$. But the latter expression is crucial in showing the ineqaulity.
\begin{eqnarray*}
\ln(n+2)-\ln(n+1) \leq  \ln(n+1)-\ln(n)
\end{eqnarray*}
now multiply by $\ln(n) \leq \ln(n+1)$ to obtain the required inequality.
Answer: By AM-GM
$$\ln_n(n+1)-\ln_{n+1}(n+2)=\frac{1}{\ln_{n+1}n}-\ln_{n+1}(n+2)=$$
$$=\frac{1-\ln_{n+1}n\ln_{n+1}(n+2)}{\ln_{n+1}n}\geq\frac{1-\left(\frac{\ln_{n+1}n+\ln_{n+1}(n+2)}{2}\right)^2}{\ln_{n+1}n}=$$
$$=\frac{1-\frac{1}{4}\ln^2_{n+1}(n^2+2n)}{\ln_{n+1}n}>\frac{1-\frac{1}{4}\ln^2_{n+1}(n^2+2n+1)}{\ln_{n+1}n}=0.$$
Answer: By the change of base formula
\begin{align}
\log_b x = \frac{\log_a x}{\log_a b}
\end{align}
we see that
\begin{align}
\log_{n+1}(n+2) = \frac{\log_n (n+2)}{\log_n(n+1)}.
\end{align}


Fresh grad hiring test quesiton

Question: It's a multiple choice question based question and the options donot contain -2147483642. the options are 10 ,11 etc
func min_jumps(arr[], start, end)
{
    if(start == end)
        return 0;

    int min = INT_MAX;  // Max value of int

    for(idx = 1; arr[start] >= idx AND end >= start + idx; idx++)
    {
        int jumps = min_jumps(arr, start + idx, end) + 1;
        if(min > jumps)
            min = jumps;
    }
    return min;
}

main()
{
    arr[] = [3, 2, 2, 1, 1, 1, 1, 2, 1, 1],
    ans = min_jumps(arr, 0, lenOfArr);
    print ans;
}

I tried to run the code and it only prints the
-2147483642

Comment: What language is this? It won't compile in either C nor C++. And what is "mcq"?
Comment: what is your question? If some multiple choice test is broken you best contact the authors of the test
Comment: Are you even supposed to run the code ? I don't get the point of a question if you could just run the code and get the answer.
Comment: @463035818_is_not_an_ai yes it's a multiple choice test .
Answer: The code has a bug.
When min_jumps doesn't find an answer, it returns INT_MAX.
When the caller adds 1 to the return value, it wraps around to INT_MIN, or   -2147483642.
You should point this out to whoever maintains the test (IF this is exactly the code on the test).
You should also point out that AND is not an operator in C or C++.

Fresh grad hiring test quesiton


Inverting a function given by an integral

Question: I'm not sure if it's even possible to do this in general, but I'd like to find a function $f^{-1}$ which is the inverse of $$f(t) = \int^t_0\frac{ds}{\sqrt{4s(1-s^2)}}$$
Comment: I've taken the liberty of editing the expression so that the function and integration variables are not the same letter, but you should check it in any case.
Comment: @Fimpellizieri Thanks for that, you've edited it correctly.
Answer: Hint
We have
$$f'(t)=\frac{ 1  }{  \sqrt{ 4t(1-t^2) }}$$
$$(f^{-1})'(t)=\frac{1}{  f'(f^{-1}(t))}$$
$$=\sqrt{4f^{-1}(t)(1-(f^{-1}(t))^2)}$$
Answer: For $s\in (0,1)$, the integrand is well-defined and always positive, so $f$ is strictly increasing and hence injective. Moreover, the limit $L= \lim_{t\to 1}f(t)$ does exist, so we may set $f(0)=0$ and $f(1)=L$ to obtain that $f:[0,1]\longrightarrow [0,L]$ is a continuous bijection that is also differentiable on $(0,1)$, with derivative given by the integrand.
This guarantees the existence of $f^{-1}:[0,L]\longrightarrow[0,1]$, but in general it needs not have a 'nice' expression, if that's what you're looking for.
Using Abdallah's idea, one can describe $g=f^{-1}$ by the initial value problem:
\begin{equation}
\left\{\begin{array}{}
g(0)=0\\
g'(t)=2\sqrt{g(t)\left(1-{g(t)}^2\right)}
\end{array}\right.
\end{equation}


Add System application(Through App source code/working AS project) in AOSP source code

Question: I am trying to add an application in AOSP source through app source code, not by apk . My application is simple hello world application which I have developed in Android Studio. I have wrote its Android.mk, placed it in packages/app/myapplication/Android.mk. Registered application package name in aosp_source_code/build/target/product/handheld_system.mk
Did I make any mistakes in Android.mk file? or am I missing any steps.
Here is code of my Android.mk
include $(CLEAR_VARS)

LOCAL_PACKAGE_NAME := Myapplication
LOCAL_MODULE_TAGS := optional
LOCAL_PRIVILEGED_MODULE := true
LOCAL_CERTIFICATE := platform

LOCAL_PRIVATE_PLATFORM_APIS := true

LOCAL_SRC_FILES := $(call all-java-files-under, src/main/java)
LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/src/main/res
LOCAL_MANIFEST_FILE := src/main/AndroidManifest.xml

LOCAL_DEX_PREOPT := false
LOCAL_PROGUARD_ENABLED := disabled

LOCAL_USE_AAPT2 := true

LOCAL_STATIC_ANDROID_LIBRARIES := \
    android-arch-lifecycle-extensions \
    android-support-v7-recyclerview \
    android-support-v7-appcompat \
    android-support-constraint-layout
include $(BUILD_PACKAGE)

Errors
packages/apps/Myapplication/src/main/res/layout/content_main.xml:8: error: attribute defaultNavHost (aka com.myapplication:defaultNavHost) not found.
packages/apps/Myapplication/src/main/res/layout/content_main.xml:8: error: attribute navGraph (aka com.myapplication:navGraph) not found.
packages/apps/Myapplication/src/main/res/navigation/nav_graph.xml:2: error: attribute startDestination (aka com.myapplication:startDestination) not found.
packages/apps/Myapplication/src/main/res/navigation/nav_graph.xml:14: error: attribute destination (aka com.myapplication:destination) not found.
packages/apps/Myapplication/src/main/res/navigation/nav_graph.xml:24: error: attribute destination (aka com.myapplication:destination) not found.
error: failed linking file resources.
11:57:34 ninja failed with: exit status 1

#### failed to build some targets (4 seconds)

Comment: Could you show the dependencies in build.gradle of your app ?
Comment: @TuanPM, ```dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.2.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
    implementation 'androidx.navigation:navigation-fragment:2.3.0'
    implementation 'androidx.navigation:navigation-ui:2.3.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
} ```
Comment: The error is self-explanatory. The build system couldn't find `app:defaultNavHost` and others in your app source code and the dependencies you've listed in `Android.mk`. It seems those attributes are defined in `androidx.navigation` library, but you've not added it in the `Android.mk` file.
Comment: @frogatto
How can i add them in AOSP ? Previously I have added some libraries to AOSP using PRODUCT_COPY_FILES. Do I need to follow similar process or something different
Answer: As i saw on your build.gradle file, you probably need to link androidx.appcompat:appcompat, androidx.constraintlayout:constraintlayout, androidx.navigation:navigation-ui and androidx.navigation:navigation-fragment in your Android.mk
Example
LOCAL_STATIC_ANDROID_LIBRARIES := \
    androidx.appcompat_appcompat \
    androidx-constraintlayout_constraintlayout \
    androidx-navigation_navigation-ui \
    androidx-navigation_navigation-fragment \
    ...

But androidx-navigation_navigation-ui and androidx-navigation_navigation-fragment may available or not available depend on your AOSP build system. You should check by yourself to ensure these libraries available (usually located in prebuilts directory). In case these libraries not available, you need to download them manually then add them to AOSP build system manually.
Comment: @semw I think you should try to add your package to PRODUCT_PACKAGES in file //build/target/product/core.mk
Comment: Thanks, It worked, If my app dependencies are not included in aosp , how can i add them manually to aosp ?


Angular ignora a quebra de linha no String

Question: Estou montando uma mensagem com varias mensagem em JAVA. Apos montada envio para o front/view porém o angular esta comendo todas as quebras de linhas:
public String salvarPorXLS(){

while (rowIterator.hasNext()) {
    pErrors += "\n"+"Atividade do processo: " + numeroProcesso + " cadastrada com sucesso"+"\n";
}

return pErrors;
}

Mensagem:

Atividade do processo: 00003362920178178224 cadastrada com sucesso
  Atividade do processo: 00003362920178178224 cadastrada com sucesso
  Atividade do processo: 00032906420158172001 cadastrada com sucesso
  Atividade do processo: 00032906420158172001 cadastrada com sucesso
  Atividade do processo: 00032906420158172001

Não esta quebrando a linha apos a palavra sucesso!
o angular esta atrapalhando o saida:
Comment: Então edita a pergunta, porque sua duvida não tem a ver com java.
Comment: Nem dá pra testar esse código, então não tem como nem analisar nada. Mas testando no ideone, modificando algumas variaveis, funcionou perfeitamente: https://ideone.com/wVMQBD
Comment: Vê se isso te ajuda: https://pt.stackoverflow.com/questions/7448/usando-quebra-de-linha-n-no-java
Comment: O angular esta atrapalhando na saida da mensagem
Comment: vou acrescentar o codigo em html
Comment: O angular esta comendo a quebra de linha. O java esta certo!
Comment: @jsbueno eu removi a tag java pq a duvida não tinha a ver com java, como o autor mesmo explicou nos comentários.
Comment: mas se você achava que seu problema estava no Java, o trechinho de código que está aí é do código em Java, ach que faz sentido.
Por que se for por aí, também não tem nada a ver com "angular" - a dúvida é só da saída de texto  - terminal (ou arquivo texto) x html.

E na verdade, tem 0 de especificidades do Ângular na pergunta e na resposta, mas alem do código Java na pergunta, eu endereço Java na resposta aceita (mas o que comentei também vale para C, C#, CPP, avascript, Python e Ruby, pelo menos: linguagens que usam a sintaxe de escape de carácteres do C)
Comment: @jsbueno concordo com você, o autor é que não soube expressar direito sua duvida na pergunta. A duvida, no fim, não é nem de java e nem de angular.
Answer: Se a saída é em html, então o \n não é uma quebra de linha - em html, um  caracter \n é umcracter de espaço em branco (whitespace) como o espaço (\x20) e tab (\t) .
Se  a sua saída é em HTML, você deveria estar colocando cada mensagem em um elemento semântico apropriado - usando as regras do seu framework para isso. Se a sua string vai ser usada como HTML direto, em vez de ser processada pelo Framework em um template, você poderia por exemplo, colocar os erros dentro de elementos
...
, e tudo dentro de um
...
.
Ou, a forma "rápida e barata", use um
 onde está colocando \n.
Outra forma, é manter a saída como está, e mudar o estilo (CSS)  de apresentação da página - use CSS para que o elemento HTML que for apresentar o bloco das suas mensagens de erro trate \n como uma quebra de linha - isso pode ser feito colocando a propriedade white-space: pre-line; no elemento apropriado, por exemplo. (dica do @fernandosavio)
A propósito, \n não é nada "mágico" - é apenas o carácter de linefeed, de código decimal 16 (0x10) - e o escape \n para representa-lo é herdado da linguagem C - entre outras coisas, a única coisa que você ganha escrevendo algo como "\n" + "minha frase" em vez de simplesmente "\nminha frase" é digitar uma porção de coisas a mais - não há a menor necessidade disso.
Comment: Vale acrescentar outra forma "rápida e barata": usando a propriedade CSS [white-space](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space).
Comment: A solução foi inserir o a tag  dentro da string


Dúvida sobre o Git - branch master

Question: Reparem na imagem abaixo, não estou mais dentro do diretório onde se encontra o meu repositório do Git, porém o branch master continua aparecendo. Por que?
Comment: Não sei se tem a ver com o git em si, pode ser um bug do shell
Comment: Hmm, tentei reinstalar o Git bash, mas não funcionou. Sabes como posso tentar consertar? @DenisRudneideSouza
Comment: Dê mais detalhes de qual sistema operacional está usando (Windows, Linux, etc), e qual shell está usando (bash, zsh, etc). Nos informe também como a variável `PS1` está definida, já que é nela que fica definida string do prompt. Dê uma checada também se, por engano, não foi criado um diretório `.git` no home do seu usuário...
Comment: @EduardoBaitello, você acertou, era um diretório .git criado por engano. Obrigado.
Comment: Se alguém puder sinalizar como respondida, agradeço. Sou novo aqui e ainda não conheço as boas práticas etc, vou me informar. Obrigado.
Comment: Olá João. Adicionei como comentário pois pedi informações adicionais do problema. Porém, idealmente soluções devem ser postadas como resposta (escrevi uma resposta agora com o que te faria achar a solução da mesma forma). Dê uma olhada aqui para entender melhor [Como e porque aceitar uma resposta](https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta) e sobre os "votos a favor".
Comment: Obrigado @EduardoBaitello, Eduardo, onde posso encontrar as boas práticas do Stack? Quero me adequar a comunidade.
Comment: Recomendo que comece pelo [Tour](https://pt.stackoverflow.com/tour) para entender os conceitos principais (você inclusive irá ganha uma medalha por completá-lo). Na [Central de Ajuda](https://pt.stackoverflow.com/help) você pode encontrar questões frequentes, incluindo as de boas práticas referente as perguntas, respostas, comportamento e etc. Se ainda sim tiver alguma dúvida sobre como usar o site, você pode usar o https://pt.meta.stackoverflow.com/ para procurar por sua resposta ou até mesmo fazer uma nova pergunta.
Answer: A configuração responsável pelo string do prompt é feita pela variável PS1. Supondo Linux + bash, essa variável deve estar definida no .bashrc do seu usuário.
Se estiver tudo certo com a configuração da PS1 o problema geralmente é um diretório .git criado no lugar indevido. Verifique o home do seu usuário se você possui um .git que não deveria estar ali. Apague/mova-o se necessário.
Comment: Obrigado @EduardoBaitello. Era um arquivo `.git` criado indevidamente no meu diretório home.

Dúvida sobre o Git - branch master