Grouping/Aggregating by 2 Columns in R

Question: I'm having a lot of trouble trying to figure out how to use the aggregate function in R and I'd appreciate some guidance.  About the only way I could get aggregate to work was by following the syntax given here.
Given the data
data <- data.frame(alpha = c(1,1,1,1,2,2,2,2),
               beta = c(1,1,2,2,3,3,4,4),
               gamma = c(.1,.2,.3,.2,.4,.1,.3,.5))

I would like to aggregate by the columns 'alpha' and 'beta'.  If I was just aggregating by 'alpha', for example, I could just do:
aggregate(x = data[ , colnames(data) != "alpha"],
          by = list(data$alpha),
          FUN = sum)

Trying
aggregate(x = data[ , colnames(data) != "alpha" | colnames(data) != "beta"],
          by = list(data$alpha, data$beta),
          FUN = sum)

didn't work.  Could someone help me find the correct syntax?
Thanks!
Comment: What is your expected result? I.e. do you want to get the sum of gamma by all possible combinations of alpha and beta pr do you want to get the sum of gamma by aggregating alpha and then also get the sum of gamma when aggregating beta?
Answer: Using the formula interface might be easier here:
aggregate(gamma ~ alpha + beta, data = data, FUN = sum)

Answer: how about:
library(dplyr)
data.frame(alpha = c(1,1,1,1,2,2,2,2),
           beta = c(1,1,2,2,3,3,4,4),
           gamma = c(.1,.2,.3,.2,.4,.1,.3,.5)) %>%
  group_by(alpha) %>%
  summarise(across(.fns = sum))

# A tibble: 2 x 3
  alpha  beta gamma
  <dbl> <dbl> <dbl>
1     1     6   0.8
2     2    14   1.3

?

Grouping/Aggregating by 2 Columns in R


hover menu jquery slide up and down too fast

Question: i made this hover menu but is buggy
this my jquery code
  $("#right_side li").mouseenter(function(e) {

        $(this).children('ul').stop(true,true).slideDown();

    });
    $(this).stop();
    $("#right_side li").mouseleave(function(e) {
        $(this).children('ul').stop(true,true).slideUp();

    });

and this my php code
function menu($li)
{
   echo "
";
        $result = mysqli_query($li, "SELECT * FROM `categories` WHERE 1") or die(mysqli_error($li));

    while ($Row = mysqli_fetch_array($result)) {
        echo "

"  . $Row['catname'] . "

";
                                $result2 = mysqli_query($li, "SELECT * FROM `brand` WHERE catid=".$Row['catid']."") or die(mysqli_error($li));
                    while ($Row2 = mysqli_fetch_array($result2)) {
                    echo "
"  . $Row2['name'] . "
";
                                        }
                echo"

";
                }

echo "
";
}

my problem is
when my mouseleave
and i mousein too fast
my menu sliding up and down too fast
please help meeeee!!!
Comment: Add the `slideUp` and `slideDown` time, like so, `.slideUp(500)`, `.slideDown(500)`.
Comment: my problem is not about timing my problem is when i leave and hover again too fast when my slidedown doesnt done yet my my sub ul gooes too fast up and down
Comment: @Davion By default slideUp and SlideDown execute at 400 miliseconds, so adding it to 500 makes no difference. alirezavalipour Can you recreate the problem in a fiddle? Is your problem that when you pass with the mouse multiple times over the menu, the menu executes multiple times up and down?
Comment: no fixed multiple time with stop()
Comment: @alirezavalipour Can you show us the html? Not the php code
Comment: its simple just think that my mouse on first ul and i leave ul to body and comeback before my animate of slideUp is working so problem start from here my sub ul hide and show too fast is about 60HZ :))
Comment: http://jsfiddle.net/97raxhxa/8/
Answer: Add the speed to your slideUp call e.g. "slow"
slideUp("slow")

You can also use a value in milliseconds.
Comment: i know about timing but my problem is something else
Comment: Your code doesn't include it.Adding slow will slow down your slide speed - which is what you asked for, right?
Comment: no ,when i leave and hover again too fast when my slidedown doesnt done yet my my sub ul gooes too fast up and down
Comment: Create a jsfiddle or codepen demonstrating the problem -  it's hard to tell exactly what's happening when we can't see it.
Comment: its simple just think that my mouse on first ul and i leave ul to body and comeback before my animate of slideUp is working so problem start from here my sub ul hide and show too fast is about 60HZ :))
Comment: I understand the problem now, but can't help without seeing a working reduced test case.
Answer: you may simply add a time in milliseconds like slideUp(1000) or slideDown(300) or slideDown("fast") or slideUp("slow")
Hope this helps.
Answer: Can you change your script to this one and let me know if the issue is fixed
$("#right_side li").on({
    mouseenter: function(){
        $(this).children('ul').stop().slideDown();
    },
    mouseleave: function(){
        $(this).children('ul').stop().slideUp();
    }
});

Comment: Well make a fiddle with your issue :)
Comment: Your fiddle has no #right_side and it is not working :)
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/62934/discussion-between-alireza-valipour-and-bojan-petkovski).
Answer: There is a known issue with the jQuery slideUp/slideDown functions when the element being slid up/down has no set height. Ensure the element to be hidden has a specified height.
ALSO, the min-height css property will mess things up. Remove min-height from the element.
Reference:
https://forum.jquery.com/topic/slideup-slow-and-slidedown-slow-happening-instantly
Comment: This fixed my problem after I spent an hour trying to figure it out. Don't know why someone down voted this...


Bind classes to Global Scope in ES6

Question: i'm trying to recreate jQuery validator in ES6 without using any jQuery, and i've kinda hit a roadblock in trying to recreate it's functionality for adding validation methods by using the Global scope, that is if you call Validator.addMethod anywhere, it'll run the associated function in the Validator and add a method to the Validator.
I can't seem to do this in ES6 since i'm not allowed to export my class to the Global scope, my class is never accessible from the window object, like for instance jQuery is, without this anyone who wants to add a new validation function would have to import a new function to add it class, and i cannot simply call
Validator.addMethod('required', function(element, value){
  return value.length > 0;
})

On any file i want after loading the validator class, so my question is, is this really impossible in ES6 or am i missing something? I already know it's not the best of practices and would be open to suggestions but the idea is ease of use even for people not well versed in ES6.
Comment: So this validator runs on the front-end? where are you writing it? is it isomorphic?
Comment: @duxfox-- It only runs on the front-end, i have a separate PHP validator running on the server
Answer: ES6 and above has been designed to avoid polluting the global scope. Your concerns are just the solution to a lot of evil bad coding practices in JavaScript.
BTW, you can always access window object and add a property called the same way as your class:
class Validator {}

window.Validator = Validator;

...because a class is still a constructor function and prototypal inheritance wrapped by a class-based syntax.
If you're going to distribute your library both in browsers and NodeJS, you might want to do this:
class Validator {}

var global = window || global;
global.Validator = Validator;

BTW, if you want to do things in the right way, you can distribute your library using the universal module definition. Learn more at the official GitHub repository of Universal Module Definition (UMD).
Comment: Or use `globalThis`

Bind classes to Global Scope in ES6


Might basic finance questions be on-topic?

Question: Could stuff taught in introductory finance at university level which may involve topics such as WACC, risk-adjusted return, dividends (involving stuff like DDM or gordon growth; I get that Modigliani-Miller is on-topic), derivatives (not pricing, just basic stuff like definitions, payoffs, etc), arbitrage strategies, etc?
All the topics I listed were discussed in finance classes I took, but they were mentioned, though not really but sometimes discussed, in economics classes I took or of which I have heard.
Finally, I believe this question differs from this other one because I am asking specifically about basic finance.
Answer: Finance is on topic on this site. There's even a tag for it (finance). The only caveat is that the answer that you will get will be coming from an economics perspective. There is plenty of common ground covered between this site and https://quant.stackexchange.com/. The site that you choose to use will probably determine the kind of answer that you receive---an economics perspective versus a "quant" perspective. Between the two sites, you should be able to find a place for your question.
Possible cases of when the question might not belong are if it's an accounting-type question or if it is a question that might belong on https://money.stackexchange.com/. In any case, feel free to ask and let us figure it out later. It's very easy to transfer a question from one site to another if needed.
Also, we are always looking for more questions!


Equality of push-forward measure and borel measure

Question: I am trying my hands at a problem in Donald Cohn book on measure theory.

Let $\mu$ be a nonzero finite Borel measure on $\mathbb{R}$, and
  define the function $F(x) := \mu((−\infty, x])$, and $g$ defined on $(0, \,
 \mu(\mathbb{R}))$ by $g(x) = \inf \, \{t \in \mathbb{R}: F (t) \geq
 x\}$.
Prove that $\mu(B)=\lambda(g^{-1}(B))$, where $B=(-\infty, b]$, $b\in\mathbb{R}$.

$\lambda(g^{-1}(B))$, $g$ being measurable, is by definition the push-forward measure of $\lambda$ so we can use the change of variable formula
$$\lambda(g^{-1}(B))=\int_\mathbb{R}1_B \; d(\lambda g^{-1}) = \int_\mathbb{R}1_B\circ g \;d\lambda =
$$
At this point if I can prove that $g=d\mu/d\lambda$ I think I could conclude but I am not sure it is a viable approach since I know nearly nothing about $\mu$...
The question is then: can this approach succeed or a different more low level one is necessary.
(Note: I recognize that we could normalize the measure $\mu$ to recover the probabilistic interpretation in which $F$ is then the CDF of the random variable $X(\omega)=\omega$ on $(\mathbb{R}, \mathcal{B}(\mathbb{R}), \mu/\mu(\mathbb{R}))$ but to procede further I would need that $g$ be the density of $X$ which seems to be equivalent to proving that $g=d\mu/d\lambda$)
Comment: If $g = d\mu / d\lambda$ was true, then we would have $\int_{\mathbb{R}} 1_B \cdot g \; d\lambda = \mu(B)$, where the dot denotes the __product__ of functions. This is different from the equation you wrote, in which you __compose__ the functions. So the Radon-Nykodym derivative won't help you here (it might not even exist!). The idea here is really to consider $B$ of the form $(-\infty, b]$ and unwind the definitions of $F$ and $g$ to guess what $g^{-1}(B)$ looks like.
Comment: Since my question was on the feasibility of my approach, your answer is the most on-point, however I can't close the question on a comment. I will accept the response thereafter posted by chilango.
Thanks
Answer: $F$ is non-decreasing, positive and vanishes at $-\infty$. This, together with the definition of $g$, implies first, that $g$ is strictly increasing, hence injective, and then that $g^{-1}(B)=(0,g^{-1}(b)]$.
We have $\tag1\lambda (g^{-1}(B))=\lambda((0,g^{-1}(b)])=g^{-1}(b)$.
Now, $a=g^{-1}(b)\Leftrightarrow g(a)=b,$ so $b=\inf \, \{t \in \mathbb{R}: F (t) \geq
 a\}$ which means that $F(b)=a$ because $F$ is right-continuous.
Thus,
$\tag2g^{-1}(b)=a=F(b)=\mu (B)$.
Combining 1) and 2) gives the result.


Can't get Azure to work with Ionic2/Angular2/Cordova app

Question: I am using the base Ionic2 Blank app.  When I instantiate Azure with the following line in home.ts
import azureMobileClient from 'azure-mobile-apps-client';

, it deploys without an error.  The failure is just a blank screen on Ripple or a blank screen on the device.  I do not see any errors on build.
Current setup:
Win10 x64
Visual Studio 2015 Community
Cordova CLI: 6.3.1
Ionic Framework version: 2.0.0-rc.1
Ionic CLI Version: 2.1.1
Ionic App Lib Version: 2.1.1
Node Version: v4.6.0
Here are the steps I took

Create new project from Ionic 2 (Beta 10)
Blank Restore dependencies
ran "npm install azure-mobile-apps-client" (received npm WARN enoent
ENOENT)
Edit package.json, added "azure-mobile-apps-client": "^2.0.0-rc1"
In app folder, create new file declarations.d.ts.
Added
    declare module 'azure-mobile-apps-client';
to declarations.d.ts (Deploy still shows home page)
Edited home.ts, added
import azureMobileClient from 'azure-mobile-apps-client';
under import {NavController} from 'ionic-angular'; (Project deploys but shows
blank screen)

Package.json
{
  "name": "io.cordova.myapp3e6a78",
  "private": true,
  "version": "0.0.1",
  "description": "ionic2-ts-blank: An Ionic project",
  "dependencies": {
    "@angular/common": "2.0.0-rc.3",
    "@angular/compiler": "2.0.0-rc.3",
    "@angular/core": "2.0.0-rc.3",
    "@angular/platform-browser": "2.0.0-rc.3",
    "@angular/platform-browser-dynamic": "2.0.0-rc.3",
    "@angular/http": "2.0.0-rc.3",
    "es6-shim": "^0.35.0",
    "ionic-angular": "2.0.0-beta.10",
    "ionic-native": "1.2.4",
    "ionicons": "3.0.0",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.6",
    "zone.js": "^0.6.12",
    "azure-mobile-apps-client": "^2.0.0-rc1"
  },
  "devDependencies": {
    "del": "2.2.0",
    "gulp": "3.9.1",
    "gulp-watch": "4.3.5",
    "ionic-gulp-browserify-typescript": "2.0.0",
    "ionic-gulp-fonts-copy": "^1.0.0",
    "ionic-gulp-html-copy": "^1.0.0",
    "ionic-gulp-sass-build": "^1.0.0",
    "ionic-gulp-scripts-copy": "^2.0.0",
    "run-sequence": "1.1.5",
    "typings": "^1.3.1"
  },
  "cordovaPlugins": [
    "cordova-plugin-whitelist",
    "cordova-plugin-console",
    "cordova-plugin-statusbar",
    "cordova-plugin-device",
    "cordova-plugin-splashscreen",
    "ionic-plugin-keyboard"
  ],
  "cordovaPlatforms": [ ],
  "scripts": {
    "build": "node_modules/.bin/gulp build",
    "typings": "node_modules/.bin/typings install",
    "postinstall": "npm run typings && npm run build"
  }
}

declarations.d.ts
declare module 'azure-mobile-apps-client';
home.ts
import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import azureMobileClient from 'azure-mobile-apps-client';

@Component({
  templateUrl: 'build/pages/home/home.html'
})
export class HomePage {
  constructor(private navController: NavController) {
    }
  onLink(url: string) {
      window.open(url);
  }
}

Comment: did you had any luck with this issue?
Comment: @RandikaRatnayake I got further, but still couldn't get Azure to connect.  I manually added all the packages because there was some kind of loading issue.

I also had to manually add an Azure typings and then the page would load, but once I actually called any Azure method I would get an instantiation error.  I tried using both app level and page level Azure object declarations, to no avail.  Very frustrating.  I was able to do normal web calls, but not Azure.  I haven't played with it in two months..

If you have any insights, I'd appreciate them.
Comment: I am still working on, will keep you posted.
Answer: You aren't actually using azureMobileClient in your code, aside from bringing it in.  The ENOENT means it didn't get downloaded.  You need a successful npm install before you can use it.  You then actually need to use it.


Binary relationship between powers and sum of powers.

Question: I want to optimize a function that determines whether a given number $n$ is EITHER (a power of 2) OR (the sum of powers of 2). Using, this answer, it appears that a sum of power of 2s contain at most two 1s in binary representation. If my observation is incorrect, it defeats the purpose of this question so please state the same otherwise read on.
Let $f(n)$ be $true$ if the binary representation of $n$ contains at most two 1s.
I am working with a 2D grid of such numbers and currently calculate the following as unrelated operations:

$a=f(x)$
$b=f(y)$
$c=f(x+y)$
$d=f(x-y)$

Is it possible to reduce these four distinct computations by inferring one from the other?
Comment: I don't understand. Any power of 2 is already a power of 2, so why does it need to be represented as a sum of 2 powers of 2?
Comment: The functions test arbitrary coordinates that do not have to be a power of 2. I will try to clarify the question as best I can.
Answer: For your first question I assume you're considering only positive integers. If that's so then in binary we'll have
$$
2^n = \mathtt{1}\underbrace{\mathtt{0\dots 0}}_n
$$
so the sum $2^n+2^m$, expressed as a binary number, will indeed have exactly two $\mathtt{1}$s, in places $n$ and $m$ (counting from the rightmost position, which we'll take as position zero), as long as $n\ne m$. If you have $n=m$, then $2^n+2^m=2\cdot2^n=2^{n+1}$, which will have a single $\mathtt{1}$ when expressed in binary.
Summing up (no pun intended), the sum of two distinct powers of 2 will indeed have exactly two $\mathtt{1}$s in its binary representation. In fact, this generalizes naturally: a positive integer is the sum of $k$ distinct powers of $2$ if and only if its binary representation has exactly $k$ $\mathtt{1}$s.
Thus your $f(n)$ will be true if and only if $n$ is either a power of two or the sum of two distinct powers of two. In particular, knowing $f(x)$ and $f(y)$ will not be sufficient to determine $f(x+y)$. Sorry.


Update WinForm From Non-Member Thread Process

Question: I know how to update a winform when the thread method is a member of the WinForm class using delegates. But how does this work if the thread function is not a member of the WinForm? How do you do it in this case?
Comment: Can you elaborate? maybe give code example of what you're trying to do? do you want to pass delegate which is not a memeber function? do you want to sync into the form from another class which has reference to the form?
Answer: In this case you need form reference in the thread function. Using this reference, you can call any public form method, and update the form by the same way as from class member.
It's up to you to decide, how to pass form reference to the thread function. Obvious way is to do this using function parameter.
Comment: Yes, I'm just being stupid. My apologies for asking such an obvious question. Thanks.


jQuery Ajax File Upload to ASP.NET web service with JSON response

Question: I am trying to upload a file using jQuery Ajax to a c# Web Service (.asmx). The file is then processed by the Web Service and the result of the operation is returned asynchronously to the calling JavaScript.
The file upload works. However, it requires that I omit the option contentType: 'application/json; charset=utf-8' when calling the $.ajax() function. And this causes the result not to be serialized as XML rather than the expected JSON. And this, in turn, causes jQuery to call the error handler instead of the success handler.
This is my client-side code:
$.ajax({
    url: global.ajaxServiceUrl + '/StartStructureSynchronisation',
    type: 'POST',
    dataType: 'json',
    //Ajax events
    success: function (msg) {
      // this handler is never called
    error: function () {
      // this handler is called even when the call returns HTTP 200 OK
    },
    data: data, // this is a valid FormData() object
    //Options to tell jQuery not to process data or worry about content-type.
    cache: false,
    contentType: false,
    processData: false
});

And this is my server-side code:
[WebMethod(EnableSession = true)]
public string StartStructureSynchronisation()
{
    return this.Execute(delegate
    {
        if (HttpContext.Current.Request.Files.Count == 0)
        {
            Global.StructureSyncResult = new SyncResult() { Result = false, Log = new List<string>() { "No file uploaded." } };
        }
        else if (!new List<string>() { ".xls", ".xlsx" }.Contains(Path.GetExtension(HttpContext.Current.Request.Files[0].FileName).ToLower()))
        {
            Global.StructureSyncResult = new SyncResult() { Result = false, Log = new List<string>() { String.Format("({0}) is not a valid Excel file.", HttpContext.Current.Request.Files[0].FileName) } };
        }
        else
        {
            Global.StructureSyncResult = new Synchronization().SyncStructure(HttpContext.Current.Request.Files[0].InputStream, ref Global.DocSyncCurrent, ref Global.DocSyncMax);
        }

        return Global.Serializer.Serialize(Global.StructureSyncResult);
    });
}

So, basically, what I am looking for is one of two things:

Either upload the file using contentType: 'application/json; charset=utf-8'. That way, the response will be serialized as JSON. I could even access the file as a parameter of my WebMethod instead of using HttpContext.Current.Request.Files.
Or find a way to force the WebService to always serialize the returned value as JSON, regardless of what the client says.

Any ideas?
Thanks a lot in advance and kind regards,
Chris.
Answer: You can use Ajax Library query.ajax_upload.0.6.js, this is simple to use.
My code is Just for hint !
Button1 is basically the button to select the file from File Selector dialog .
$(document).ready(function () {
    function  uploadFile(parameters) {
        /* example 1 */
        var button = $('#button1'), interval;
        $.ajax_upload(button, {
            action: "FileHandler.ashx?test=" + $("#paramter").val(),
            name: Selectedval,
            onSubmit: function (file, ext) {
                StartLoading();
            },
            onComplete: function (file, response) {
                StopLoading();
            }
        });
        uploadButton();//Register Event
    });
});

    Select File

On Server Side, You can write httpFile handler;
public class FileHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        //For multiple files
        foreach (string f in context.Request.Files.AllKeys)
        {
            HttpPostedFile file = context.Request.Files[f];
            if (!String.IsNullOrEmpty(file.FileName)) {
                string test = file.FileName;
            }
        }
    }
}

Comment: Thank you for your answer. While your solution may allow to return a JSON serialized result, it totally bypasses the web service. Can you think of a solution that does still involve the web service?


pages always 100% height and 100%width

Question: How is it possible to build a one page website with different pages with each page that has a 100% width and 100% height?
My first solution would be a fixed value but I want it to scale to the size of the screen. So that each page has the size of the screen.
Note that it has to be a "one page" so the pages will be underneath each other.
Thanks for your help!
Comment: It's not clear what you're asking. Are you asking if it's possible? Yes, it is. But what do you *really* want to know?
Comment: How can `one page` be 100% of browser window height?
Comment: You want a one page multi-page site? And your concern is with the height and width?
Comment: I find it hard to explain. But I want a one page design website. But which has 4 pages underneath eachother. Like a list or something. But I want each page to fit the screen perfectly. I dont want to see all the 4 pages when I am on a 27" screen for instance. No, I still want to 1 full page and I have to scroll down to see the other one. So it needs to be responsive-ish. So it shoudnt matter on which screensize I look at it. Sorry for the vague question and answer
Answer: Depends how you want to build it and resize it. Is it responsive? If so, make sure you use then a framework that supports it.
Also, start off as following in your CSS
body, html              {height: 100%;width: 100%;}

This will always fill your screen for 100% with the body. Now for your secondairy question. You want to fill each page? Cause you lost me there. Content is varriable, thus cant always fit on a 100% height and width (think of smartphones, you have to scroll sometimes, due to the limited width and height in pixels from a smartphone)
I suggest your pages should be sections, and place them in my body tag. Each section is then a different element and you can call them off your menu (i asume you want to scroll then down in your menu) so simply giving them an ID and the page will jump to it with the help of JQuery or JavaScript.
Do a codecheck on this page to see what I mean: http://www.jellyfishwebdesign.nl/Joost/index.php
Answer: Give height:100% to html,body & your page container.
Answer: I think this CSS solution is enough..

And the CSS:
html,body {
   height:100%;
   margin:0;
   padding:0;
}

#one {
   min-height:100%;
   position:relative;
}

#two {
   min-height:100%;
   position:relative;
}

#three {
   min-height:100%;
   position:relative;
}

Answer: This is the code you need:
<!DOCTYPE html>

The divs inside the #parent all have a height of 100%. Even if you resize the screen.
Tested it on Chrome, IE and Firefox.
Comment: This is exacly what I was looking for! Thank you very much sir!
Comment: No problem :) could you mark it as accepted answer by clicking the "check" sign? Would help out others with the same problem. Thanks

pages always 100% height and 100%width


Proving limit on angle of a hyperbolic right triangle

Question: I'm trying to prove that for a right triangle $\Delta ABC$ with right angle $B$, the angle $BAC \le \sin^{-1}(sech AB)$
I'm not really able to find a way to bring this proof together. I've tried converting $\sin^{-1}(sech AB)$ to $\int_{0}^{sec(AB)} \frac 1 {\sqrt{1-z^2}}dz$ and trying to relate that integral to the area of a hyperbolic triangle, but I'm having no luck.
Answer: By the angle of parrallelism  https://en.wikipedia.org/wiki/Angle_of_parallelism
When C is an ideal point $ AC = BC = \infty , \angle C = 0 $
Then by the angle of parallelism  https://en.wikipedia.org/wiki/Angle_of_parallelism you get
$\sin \Pi(AB) = \sin \angle BAC = \frac {1}{\cosh (AB) } = sech(AB)$.
When $ \angle BAC$ is larger than $ \Pi(AB)$ there is no triangle (the "sides" won't meet)
and when $ \angle BAC$ is smaller than $ \Pi(AB)$ C is not an ideal point and you have a normal triangle.
To prove all of this you are in a difficult point , it all depends on the curvature (in the formula's above it is supposed to be $-1$)
If the curvature is not suppoost to be $-1$ the curvature first need to be calculated and then AB must be replaced by $ \frac{AB}{-K} $
so i guess you will need to find any proof of the angle of parallelism and tweak it a bit.
hopes this helps.


VBA - Copiar e colar coluna para a nova aba com o código dado

Question: Olá! Eu tenho um código VBA no formato abaixo. Ele pega todas as informações da coluna B e manda para outra aba, sempre que o valor de B1 for alterado (só não cria outra, se já tiver uma igual), renomeando essa nova aba criada com o valor que estiver descrito em B1. No entanto, eu quero colocar nas abas novas que forem criadas, também a coluna A do modo como elas estiverem descritas na planilha original (que chamei de Plan3) (pode ser a coluna toda ou de A1:A11). Como poderia prosseguir?
<code>   Dim i: i = 1
   Dim B1_val As String
   B1_val = ThisWorkbook.Worksheets("Plan3").Range("B1").Value
   myValue = ThisWorkbook.Worksheets("Plan3").Range("B" & i).Value
   Dim ws As Worksheet
   If Not (doesSheetExist(B1_val)) Then
      Set ws = ThisWorkbook.Worksheets.Add(Type:=xlWorksheet)
      With ws
        .Name = B1_val
      End With
        While myValue <> ""
          Set cellv = ThisWorkbook.Worksheets(B1_val).Range("B" & i)
          cellv.Value = myValue
          i = i + 1
          myValue = ThisWorkbook.Worksheets("Plan3").Range("B" & i).Value
        Wend

   End If

End Sub
Public Function doesSheetExist(strSName As String) As Boolean
    Set wb = ActiveWorkbook
    Dim obj As Object
    On Error GoTo ErrorHandler
    Set obj = wb.Sheets(strSName)
    doesSheetExist = True
    Exit Function
ErrorHandler:
    doesSheetExist = False
End Function
</code>
Answer: Segue aqui a minha sugestão de como fazer isso. Já adianto que não é a maneira mais prática, porém como sua questão envolve apenas duas colunas, dá para fazer assim.
Entretanto, eu fiz de maneira que funcione mesmo se as colunas tiverem um número diferente de linhas preenchidas entre elas (ou seja, se a coluna A estiver preenchida até a linha 11, mas a coluna B até a linha 23 - e vice-versa - funciona mesmo assim).
Se em algum momento você precisar inserir mais colunas na Aba nova criada, sugiro você reestruturar o código e incluir as colunas adicionais usando Offset.
Por fim, segue aqui a minha sugestão:
<code>Private Sub btAba_Click()

 Dim i: i = 1
   Dim A1_val As String
   Dim B1_val As String
   A1_val = ThisWorkbook.Worksheets("Plan3").Range("A1").Value
   B1_val = ThisWorkbook.Worksheets("Plan3").Range("B1").Value
   myValueA = ThisWorkbook.Worksheets("Plan3").Range("A" & i).Value
   myValue = ThisWorkbook.Worksheets("Plan3").Range("B" & i).Value
   Dim ws As Worksheet
   If Not (doesSheetExist(B1_val)) Then
      Set ws = ThisWorkbook.Worksheets.Add(Type:=xlWorksheet)
      With ws
        .Name = B1_val
      End With
       Do While myValue <> "" Or myValueA <> ""
          Set cellvA = ThisWorkbook.Worksheets(B1_val).Range("A" & i)
          Set cellv = ThisWorkbook.Worksheets(B1_val).Range("B" & i)
          cellvA.Value = myValueA
          cellv.Value = myValue
          i = i + 1
          myValueA = ThisWorkbook.Worksheets("Plan3").Range("A" & i).Value
          myValue = ThisWorkbook.Worksheets("Plan3").Range("B" & i).Value
      Loop

   End If

End Sub
Public Function doesSheetExist(strSName As String) As Boolean
    Set wb = ActiveWorkbook
    Dim obj As Object
    On Error GoTo ErrorHandler
    Set obj = wb.Sheets(strSName)
    doesSheetExist = True
    Exit Function
ErrorHandler:
    doesSheetExist = False
End Function
</code>
Qualquer problema, me avise.


Como criar divs dentro do javaScript e utilizar Json

Question: Estou tentado criar e preencher vários cards html de acordo com o retorno Json que tenho de um arquivo PHP, tenho o Javascript que pega o array Json, minha duvida é como faço para criar vários cards dentro desse javascript ?
Javascript
 $(function(){
    carregar(0,12,'Chamadas/testeCarregarAnuncios.php');
    $("#carregarMais").click(function(evento){
        evento.preventDefault();
        var init = $().length;
        carregar(init, 12, 'Chamadas/testeCarregarAnuncios.php');
    });
    function carregar(init, max, url){
        var dados = {init: init, max : max};
        $.post(url, dados, function(data){
          for(i = 0; i < data.dados.length; i++){

         }
         var anunciosExibidos = $("").length;
         if(anunciosExibidos== data.totalAnuncios)
         {
             $("#carregarMais").hide();
         }
        },"json");
    }
});

Card HTML que preciso criar para cara retorno json

                                        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

                                    Informática

devo criar linha a linha do card dentro do Javascript ? tem alguma outra forma de fazer isso ?
Comment: Eu to aprendendo a usar o vue.js e acho que seria muito util pra você. Para o que você quer fazer acho que seria uma otima solução, pq vc pode fazer um modelo de card onde vai receber os dados e o vue.js duplica os cards de acordo com os registros em JSON.  o site do https://vuejs.org/ pra vc conhecer melhor
Answer: Olha como eu respondi no comentário da pergunta, acho que o vue.js seria bem melhor para você.
Aqui eu dou um exemplo bem fácil de como usar.

new Vue({
  el: '#v-for-cards',
  data: {
     itens: [{"titulo":"Titulo do card 1", "descricao":"Descrição de teste"},{"titulo": "Titulo do Card 2", "descricao":"mais um teste"}]
  }
});

 Titulo: {{ item.titulo }}

 {{ item.descricao }}


Passing arguments with variables in PowerShell to native application

Question: Here is a part from my deployment automation script:
$SVNEXE = "$env:ProgramFiles\TortoiseSVN\bin\svn.exe"
foreach ($element in $commandstoken) {
#$exportfile = [System.Web.HttpUtility]::UrlPathDecode($StreamServe5RepoURI + $commandstoken[$a])
$exportfile = ($StreamServe5RepoURI + $commandstoken[$a])
$SVNRevision = $commandstoken[$a+1]
[string]$SVNCommand = "export -r $SVNRevision --force"
Write-Host -ForegroundColor Red $SVNCommand
Write-Host -ForegroundColor Red $SVNCommand $exportfile
&"$SVNEXE" $SVNCommand $exportfile "C:\Temp\__foo\export"
$a = $a+2
}

I want to pass the svn.exe the $SVNCommand variable but the svn.exe throws an error: svn.exe : Unknown subcommand: 'export -r 2384 --force'
As far as I can see the variable expansion is working so I can not understand why the svn.exe throws this error.
Answer: The error Unknown subcommand: 'export -r 2384 --force' suggests that call operator treats  'export -r 2384 --force''export -r 2384 --force' this like a single argument (from technet on the & call operator):

Things can get tricky when an external command has a lot of parameters
  or there are spaces in the arguments or paths! With spaces you have to
  nest Quotation marks and the result it is not always clear!

In your case, you could do something like like suggested on that page:
 $SVNcommand = @('export', '-r', $SVNRevieion, "--force", $exportfile, "C:\Temp\__foo\export")

And invoke with all arguments like this:
&"$SVNEXE" $SVNCommand

Comment: Yes, that has to do with the way write-host prints out arrays. To the call operator & what you pass in your powershell script maps to command arguments, so the issue you face relates to how the svn.exe interprets the arguments. What error do you get after trying the solution I suggested?
Comment: Try building your command like this `& "$SVNexe" @("export", "-r")` and see where the errors no longer makes sense for what your're trying to do!
Comment: Thank you for your help. I just tried as suggest but the command still fails. If print out the $SVNCommand with Write-Host everything looks good. I can even copy and paste the command line to the CMD where everything works as expected.
Comment: Thx for the fast reply.

Here is the error:

export -r 2384 --force https://example.com/svn/repository/Dir1/SubDir/SubDir/SubDir/file.txt C:\Temp\__foo\export
svn.exe : Unknown subcommand: 'export -r 2384 --force https://example.com/svn/repository/Dir1/SubDir/SubDir/SubDir/file.txt
C:\Temp\__foo\export'
In C:\Temp\__foo\SVN Export.ps1:16 Zeichen:1
+ &"$SVNEXE" $SVNCommand
+ ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Unknown subcomm...p\__foo\export':String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

Type 'svn help' for usage.
Comment: Is quoting a variable name necessary?  wouldn't the invoke use the value from the variable exactly the same as if it was not quoted?
Answer: The only way I got it to work is to hold every parameter in a separate variable:
$arg1 = 'export', '-r'
$arg2 = $SVNRevision
$arg3 = '--force'
$arg4 = $exportfile
$arg5 = 'C:\Temp\__foo\export\'
&"$SVNEXE" $arg1 $arg2 $arg3 $arg4 $arg5

This seems actually bug Executing commands which require quotes and variables is practically impossible
Comment: Thanks for this, it took way too long to figure out how to do such a simple thing, batch scripts are much easier for something like this.
Comment: Wow, SVN wants the first argument to be an array?   That's nuts.


What if one experimental treatment affects whether another treatment is seen?

Question: Suppose I run an experiment which tests which version of an email is most likely to cause people to click on a survey link inside the email.
There are two experimental manipulations: the email subject and the text within the email. For each experimental manipulation there are two levels (treatment and control). Both experimental manipulations are randomized independently of each other.
Normally (assuming no interaction effects), one would simply estimate treatment effects by running the following regression:
$ClickedLink_i = \beta_0 + \beta_1 EmailSubject_i + \beta_2 EmailText$
Where ClickedLink is a binary variable equal to 1 if user i clicked on the survey link, 0 otherwise. EmailSubject and EmailText are also binary variables, equal to 1 if the user received the Treatment email subject and email text respectively. (It may actually be more appropriate to use logit/probit models, and feel free to use those when answering, but this isn't the main point of the question)
I notice that email subject actually affects whether users actually see the email text. That is, if users don't click on the email after reading the subject line, the text of the email won't matter. How can I reformulate my regression to take this into account?
Comment: Do you know whether a user saw the email text or not?
Comment: Not totally sure, but this thread might be relevant: https://stats.stackexchange.com/q/372257/121522
Comment: @mkt Good question. Let's assume we can't (the analysis seems pretty straightforward if we can)
Answer: This is really quite straight-forward --- you just include the interaction term in your regression model.  By having a control and experimental group for two separate parts of the message, you effectively have four possible messages, and your experiment is seeking to find the effect of each of these four messages.  So just treat this as an RCT with four experimental groups, and make an inference for all those groups (by including an interaction term in your model).  If it is indeed the case that the subject message affects whether the user reads the text, then that should show up in your data.


Change language code in URL using Javascript

Question: I am developing a website that works in two languages. I need to change URL to include the selected language.
What I exactly need is:

Pick the current URL
Check if the URL contains any language code
Append the code if not exist or change the code to the selected one if exists

For example, there is an URL for English (default):
http://localhost:11767/Home/resultMain?model=1&&type=1

When a user selects Spanish (es) it should be:
http://localhost:11767/es/Home/resultMain?model=1&&type=1

Comment: In which language is your backend written? Are you using node js?
Comment: @Daniel ASP.NET MVC
Comment: Change window.location?
Answer: You can parse the URL with the help of an a element then replace the part you want and re-build the URL :

function addReplaceLangCode(url, langCode) {
  var a = document.createElement('a');
  a.href = document.getElementById('url').value; // or document.location.href;

  var paths = a.pathname.split('/');
  paths.shift();

  if(paths[0].length == 2) {
    paths[0] = langCode;
  }else{
    paths.unshift(langCode);
  }
  return a.protocol + '//' +
    a.host + '/' + paths.join('/') +
    (a.search != '' ?  a.search : '') +
    (a.hash != '' ?  a.hash : '');
}

function onClickReplace() {
    document.getElementById('result').innerHTML = addReplaceLangCode( document.location.href, 'es');
}
URL : <input type="text" id="url" style="width:400px" value="http://localhost:11767/Home/resultMain?model=1&&type=1"><input type="button" value="Replace" onclick="onClickReplace()">

Result:
Comment: Indeed. Please check now. We don't have to add extra '/' before the query string and the hash.
Comment: this method will eliminate the part of query string parameters if the url is
http://localhost:11767/es/Home/resultMain?model=1&&type=1
and user click on english the link will be
http://localhost:11767/en/Home/resultMain
Comment: Thanks very much it is now working fine and you really save my day :)
Comment: Littile bug in this code when the url is
http://localhost:11767/en/Home/resultMain?model=2&type=2
and i click on en agin it will result
http://localhost:11767/en/Home/resultMain/?model=2&type=2
click again on en
http://localhost:11767/en/Home/resultMain//?model=2&type=2

Note the slash that is appended before question mark
Comment: Thanks for the example. Still helpful today. I have replaced `'/'` with `(langCode == '' ? '' : '/')` to make it work the other way round.
Answer: I don't know if it is exactly this, what you want. But JavaScript can obtain URL using object "location". Especially location.pathname is useful for you. You can apply reg-exp on location.pathname to check if URL contain /es/ and if yes, then translate website by proper Ajax requests to your backend.
But generally I recommending to use routing of your backend. The best solution in my opinion - use http headers to inform server about preferred language.

https://www.w3.org/International/questions/qa-accept-lang-locales
Answer: Based on @Bulnet Vural's answer above, I wrote the following code because I needed to toggle the language path in and out of the url.
var getOtherLanguageLocation = function (currentUrl, languagePath) {
    // based on https://stackoverflow.com/a/42176588/1378980
    var anchorTag = document.createElement('a');
    anchorTag.href = currentUrl;
    var paths = anchorTag.pathname.split("/");

    // remove all the empty items so we don't get double slash when joining later.
    var paths = paths.filter(function (e) { return e !== '' })

    // the language will be at index 1 of the paths
    if (paths.length > 0 && paths[0].toLowerCase() == languagePath) {
        // remove the language prefix
        paths.splice(0, 1);
    } else {
        // add the language prefix
        paths.unshift(languagePath);
    }

    return anchorTag.protocol + '//' +
      anchorTag.host + '/' + paths.join('/') +
      anchorTag.search + anchorTag.hash;
};


Hide records from datatables based on database value 0/1

Question: I'm trying to hide the records fetched from my database based on their value if its 0 or 1, its displaying all records i just want to display the ones with value 1, I'm using Laravel 5.2 with Yajra/Datatables.
this is my controller:
public function get() {
    if(!access()->allow('customers.read')) {
        return redirect()->route('admin.dashboard')->withFlashDanger(trans('customers.general.messages.denied'));
    } else {
        $customers = Customer::select(array(
            'id', 'code', 'name', 'rnc', 'ced', 'phone', 'email', 'active'
        ));

        return Datatables::of($customers->get('status'), $customers->get('trashed'))
            ->addColumn('actions', function($customers) {
                return $customers->action_buttons;

            })->addColumn('check', '<input type="checkbox" name="selected_users[]" value="{{ $id }}">')
            ->make(true);
    }
}

This is my view:
@extends('backend.layouts.master')

@section('title', app_name() . ' | ' . trans('customers.general.customers_title'))

@section('after-styles-end')
{{ Html::style("css/backend/plugin/datatables/dataTables.bootstrap.min.css") }}
@stop

@section('page-header')

        {{ trans('customers.general.customers_title') }} - {{ trans('customers.general.general') }}

@endsection

@section('content')

{{ trans('customers.general.customers_list') }}

            {{ trans('customers.general.buttons.new_customer') }}

                    <input type="checkbox" name="select_all" value="1" id="example-select-all">
                    {{ trans('customers.general.table.code') }}
                    {{ trans('customers.general.table.business_name') }}
                    {{ trans('customers.general.table.document') }}
                    {{ trans('customers.general.table.phone') }}
                    {{ trans('customers.general.buttons.email') }}
                    {{ trans('labels.general.actions') }}

@endsection

@section('after-scripts-end')
{{ Html::script("js/backend/plugin/datatables/jquery.dataTables.min.js") }}
{{ Html::script("js/backend/plugin/datatables/dataTables.bootstrap.min.js") }}

@stop

in my view im retreiving all the results but its also showing the ones that i have disabled with value 1, i just want to show the ones with value 0 in the list, any help would be really appreciated.
thanks all
Answer: You can use scopes or global scopes in your model, so those records are not retrieved at all.
In your model:
public function apply(Builder $builder, Model $model)
    {
        return $builder->where('parameter', 1);
    }

This will return only the records where the parameter = 1.


Not getting correct value from click method

Question: I am trying to get the value from a data controlled by v-model within a component.
The data changes in the app and in Vue dev tools but if I console log that data I always get the previous value.
Vue App
Here is the data I'm passing to the components
new Vue({
  el: "#app",
  data: {
    "children": {
        "haveAnyOtherDependents": 'yes',
        "havePets": 'no',
    },
  },
})

Vue Component
Here I pass the data I need from the app
// button-group component
Vue.component('button-group', {
    props: {
        title: {
            type: String
        },
        name: {
            type: String
        },
        content: {
            type: String
        },
        dataSource: {
            type: String
        }
    },
    data: function () {
        return {
            myTitle: this.title,
            myName: this.name,
            myContent: ''
        }
    },
    created(){
        this.myContent = this.setMyContent
    },
    methods: {
        sendData: function(){
            console.log('data: ', this.myContent, 'source', this.dataSource);
        }
    },
    computed: {
        setMyContent: function(){
            return this.content
        }
    },
    template: `

                        <input type="radio" :name="myName" value="no" v-model="myContent" @click="sendData()">

                            No

                        <input type="radio" :name="myName" value="yes" v-model="myContent" @click="sendData()">

                            Yes

                        <input class="d-none" type="radio" :name="myName" value="unknown" v-model="myContent" @click="sendData()" checked>

                            Unknown

    `
});
// end button-group

HTML

  <button-group title="Other Dependants" name="other_dependents"
:content="children.haveAnyOtherDependents" data-source="children.haveAnyOtherDependents"></button-group>
        <button-group title="Pets" name="pets" :content="children.havePets" data-source="children.havePets"></button-group>

Here is a fiddle, https://jsfiddle.net/yktoL8oz/
Comment: The click event fires before the model is updated. Use a different event like change.
Comment: Genius as usual @Bert That's the solution
Answer: As answered in the comments by @Bert

The click event fires before the model is updated. Use a different event like change"

I changed the @click="sendData()" to @change="sendData()" and that solved the issue.


Show that in the sequence space $l^1$, the unit ball with respect to $d_1$ is closed in the topology induced by the sup metric $d_\infty$

Question: Let
$l^1 = \left\{ (x_i)_{i\in\mathbb{N}} \mid \sum_{i =1}^{\infty} | x_i |<\infty \right\}$,
the space of all sequences whose associated series converge absolutely.
Let $A= \{\sum_{i = 0}^{\infty} | x_i |\leq1\}$
(Note: $A$ is the unit ball with respect to $d_1$ where $d_1((x_i)_{i\in\mathbb{N}},(y_i)_{i\in\mathbb{N}}) = \sum_{n = 0}^{\infty} | x_i - y_i |$.)
Let $d_\infty((x_i)_{i\in\mathbb{N}},(y_i)_{i\in\mathbb{N}}) = sup_{i\in\mathbb{N}}| x_i - y_i |$.
I want to show $A$ is closed with respect to the topology induced by $d_\infty$. (I see how to show it's closed with respect to $d_1$)
Suppose we have a sequence $(x^n)_{n\in\mathbb{N}}$ of members of $A$  converging to $y\in l^1$. (Each $x^n \in A$, so this is a sequence of sequences). I will try to show $lim_{n\rightarrow \infty} \sum_{i=1}^\infty|x_i^n|=\sum_{i=1}^\infty|x_i|$. Here's my attempt.
For each $n$, we have:
$$|(\sum_{i=1}^\infty|x_i^n|-\sum_{i=1}^\infty|x_i|)|=\sum_{i=1}^\infty(|x_i^n|-|x_i|)|\leq\sum_{i=1}^\infty||x_i^n|-|x_i||\leq \sum_{i=1}^\infty|x^n_i -x_i|$$
$$=\sum_{i=1}^{k}|x^n_i-x_i| + \sum_{i=k +1}^\infty|x^n_i-x_i|$$ for any $k$. (We may want k to depend on n). We can make $\sum_{i=1}^{k}|x^n_i-x_i|$ small by the convergence of $(x^n)$ to $y$ with respect to $d_\infty$. And given a particular $n$, we can make $\sum_{i=k_n +1}^\infty|x^n_i-x_i|$ small by taking $k_n$ large. However, the latter is not good enough. Given $\epsilon>0$, it seems we need to find $k$ such that For All sufficiently large $n$, $\sum_{i=k_n +1}^\infty|x^n_i-x_i|<\epsilon/2$. I don't see how to do this.
Comment: Note that $$\sup_{i\in\mathbb N}|x_i-y_i|\leqslant\sum_{i\in\mathbb N}|x_i-y_i|, $$ so if a sequence converges in $\ell^1$ it also converges in $\ell^\infty$.
Comment: @Math1000 I'm not seeing how that helps since the hypothesis is convergence in $l^\infty$ not convergence in $l^1$, and the former does not imply the latter.
Answer: The problem with your proof is that it does not use the structure of the set. It's as if you try to prove that every $\ell^1$-closed set is $\ell^\infty$-closed, which is false. (In fact, the converse is true: a smaller norm, such as $\ell^\infty$, induces weaker topology on the same space.)
Let's work with the complement and show it's open.  Suppose $\|x\|_1>1$. Then there exists $n$ such that $|x_1|+\dots+|x_n| >1$. Let $\epsilon = (|x_1|+\dots+|x_n| -1)/n$. Then for any $y$ with $\|y-x\|_\infty<\epsilon$ we have
$$
\|y\|_1 \ge |y_1|+\dots+|y_n| > |x_1|+\dots+|x_n| - n\epsilon = 1
$$
which proves that the complement of unit ball is open in $\ell^\infty$ norm.


Removing items from a Dictionary using foreach

Question: I am trying to test values of a SortedDictionary and removing some accordingly but I think the foreach doesn't accept the change in the Dictionary. Is there a better way of doing? Am I right about the kind of issue?
<code>try{
    foreach (var elmt in buffer)
    {
        if (condition(elmt)
        {
             buffer.Remove(elmt.Key);
        }
    }
}
catch(Exception e)
{
    Logger.LogInformation("marker: " + e.Message)
}
</code>
The exception thrown is: "marker: Collection was modified after the enumerator was instantiated."
Answer: A documentação diz: "Os enumeradores podem ser usados para ler os dados na coleção, mas não podem ser usados para modificar a coleção subjacente." No próprio site.
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Discrepancy between Kaplan-Meier curves and Cox Model

Question: I have plotted Kaplan-Meier curves of survival times for cancer patients with above and below average levels of Copy Number Variation (CNV), and performed a log-rank test for each cancer type.
I have also fit a univariate Cox Model for each cancer type, with CNV levels as the variable.
There are several cancers which reach statistical significance in the Cox Model and not for the Kaplan-Meier curves. There is one cancer where the situation is vice-versa.
What could be causing this effect and which test should I trust?
Answer: Differences in "significance" between non-parametric tests (no assumptions about underlying distributions of variables, typically just based on relative ranks) and parametric tests (with assumptions about distributions, for example that they follow a normal distribution) are frequently found in other types of statistical analyses, with non-parametric tests typically having less power (if the assumptions of the parametric test hold). Here, K-M/log-rank tests are non-parametric (just looking at which events occur first), while the Cox model is semi-parametric (unspecified baseline hazard, but hazard ratios among groups assumed to be strictly proportional). My guess is that you are on the borderline of having enough events in your data sets to document a relation of survival to CNV.
Look at the shapes of the K-M curves to see what's going on, and do appropriate tests that the Cox proportional-hazards assumption is being met.
Which to "trust" depends on the use you intend to make of your analyses. If you are simply doing these analyses to determine whether to follow-up with an independent study, use your scientific judgment along with the hints these results provide. If you are intending to publish these results, you should probably trust neither on its own without further analyses. Studies such as this are notorious for finding "significant" results that are very dependent on the peculiarities of a particular data set. This site has many pages on how to overcome these limitations with techniques like cross-validation and bootstrapping; this page and its "Related" pages are good places to start.


Print elementos de um regex em sequência no python

Question: Boa tarde pessoal, sou novo no python e estou aprendendo ao poucos com isso gostaria de pedir ajuda de vocês, eu tenho o seguinte código fonte retirado de um site:

1 - 1

Extreme Aggressor Sep. 22, 2005

1 - 2

Compulsion Sep. 28, 2005

Com isso fiz esse pequeno código com o seguinte regex:
site = "https://www.assistirseriesflix.com/series/mente-criminosa-dublado-hd/"
response = requests.get(site)
data = response.content
data.decode('utf-8')

match = re.findall(b'
(.*?)

(.*?)', data)

Já tentei de várias formas imprimir da seguinte forma o código:
Episódio 1 - 1 Extreme Aggressor | Link : https://www.assistirseriesflix.com/episodios/assistir-mentes-criminosas-1x1-dublado-e-legendado-online-hd/
Episódio 1 - 2 Compulsion | Link : https://www.assistirseriesflix.com/episodios/assistir-mentes-criminosas-1x2-dublado-e-legendado-online-hd/
onde 1 - 1 vem de
1 - 1

E nome do episódio e link vem de
Extreme Aggressor

Dando um print(match) ele mostra corretamente todos os dados que eu quero pegar, porém eu não consigo filtra-los da forma que citei acima
Tentei com vários códigos que encontrei em tutoriais na internet e alguns tópicos aqui do próprio stack, mas não consegui com nenhum, tentei também entender o beautifulsoup mas não tive muito sucesso, na verdade eu não sei qual é a melhor forma de se fazer isso no python, agradeço desde já a ajuda de vocês!
Comment: Não use regex para trabalhar com HTML: https://pt.stackoverflow.com/a/440262/112052 <-- esse link mostra como a regex pode se tornar cada vez mais complicada, enquanto se usar a ferramenta certa, como por exemplo o beautiful soup, é bem melhor
Answer: Certamente a BeautifulSoup é a biblioteca mais adequada para o seu caso, veja só:
import sys
import requests
from bs4 import BeautifulSoup

url = 'https://www.assistirseriesflix.com/series/mente-criminosa-dublado-hd/'

response = requests.get(url)

if response.status_code != 200:
    print(f'Erro HTTP: {response.status_code}')
    sys.exit(1)

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

episodios = soup.find('ul', {'class': 'episodios'})

for episodio in episodios.findAll('li'):
    div = episodio.find('div',{'class': 'numerando'})
    numeracao = div.text

    div = episodio.find('div',{'class': 'episodiotitle'})
    a = div.find('a', href=True)
    titulo, link = a.text, a['href']

    print(f'Episodio: {numeracao} {titulo} | Link: {link}')

Saída:
Episodio: 1 - 1 Extreme Aggressor | Link: https://www.assistirseriesflix.com/episodios/assistir-mentes-criminosas-1x1-dublado-e-legendado-online-hd/
Episodio: 1 - 2 Compulsion | Link: https://www.assistirseriesflix.com/episodios/assistir-mentes-criminosas-1x2-dublado-e-legendado-online-hd/
Episodio: 1 - 3 Won't Get Fooled Again | Link: https://www.assistirseriesflix.com/episodios/assistir-mentes-criminosas-1x3-dublado-e-legendado-online-hd/
Episodio: 1 - 4 Plain Sight | Link: https://www.assistirseriesflix.com/episodios/assistir-mentes-criminosas-1x4-dublado-e-legendado-online-hd/
Episodio: 1 - 5 Broken Mirror | Link: https://www.assistirseriesflix.com/episodios/assistir-mentes-criminosas-1x5-dublado-e-legendado-online-hd/
Episodio: 1 - 6 L.S.D.K. | Link: https://www.assistirseriesflix.com/episodios/assistir-mentes-criminosas-1x6-dublado-e-legendado-online-hd/
Episodio: 1 - 7 The Fox | Link: https://www.assistirseriesflix.com/episodios/assistir-mentes-criminosas-1x7-dublado-e-legendado-online-hd/
Episodio: 1 - 8 Natural Born Killer | Link: https://www.assistirseriesflix.com/episodios/mentes-criminosas-1x8/
Episodio: 1 - 9 Derailed | Link: https://www.assistirseriesflix.com/episodios/mentes-criminosas-1x9/
Episodio: 1 - 10 The Popular Kids | Link: https://www.assistirseriesflix.com/episodios/assistir-mentes-criminosas-1x10-dublado-e-legendado-online-hd/
Episodio: 1 - 11 Bloody Hungry | Link: https://www.assistirseriesflix.com/episodios/assistir-mentes-criminosas-1x11-dublado-e-legendado-online-hd/
Episodio: 1 - 12 What Fresh Hell? | Link: https://www.assistirseriesflix.com/episodios/mentes-criminosas-1x12/
Episodio: 1 - 13 Poison | Link: https://www.assistirseriesflix.com/episodios/assistir-mentes-criminosas-1x13-dublado-e-legendado-online-hd/
Episodio: 1 - 14 Riding the Lightning | Link: https://www.assistirseriesflix.com/episodios/assistir-mentes-criminosas-1x14-dublado-e-legendado-online-hd/
Episodio: 1 - 15 Unfinished Business | Link: https://www.assistirseriesflix.com/episodios/mentes-criminosas-1x15/
Episodio: 1 - 16 The Tribe | Link: https://www.assistirseriesflix.com/episodios/mentes-criminosas-1x16/
Episodio: 1 - 17 A Real Rain | Link: https://www.assistirseriesflix.com/episodios/assistir-mentes-criminosas-1x17-dublado-e-legendado-online-hd/
Episodio: 1 - 18 Somebody's Watching | Link: https://www.assistirseriesflix.com/episodios/assistir-mentes-criminosas-1x18-dublado-e-legendado-online-hd/
Episodio: 1 - 19 Machismo | Link: https://www.assistirseriesflix.com/episodios/assistir-mentes-criminosas-1x19-dublado-e-legendado-online-hd/
Episodio: 1 - 20 Charmed And Harm | Link: https://www.assistirseriesflix.com/episodios/mentes-criminosas-1x20/
Episodio: 1 - 21 Secrets And Lies | Link: https://www.assistirseriesflix.com/episodios/assistir-mentes-criminosas-1x21-dublado-e-legendado-online-hd/
Episodio: 1 - 22 The Fisher King (1) | Link: https://www.assistirseriesflix.com/episodios/mentes-criminosas-1x22/

Comment: obrigado pela ajuda, estou entendendo pelo seu código o uso do Beautifulsoup nesse caso, não querendo pedir demais você conseguiria dar um exemplo usando o regex também por favor? Se não tiver problema claro, Obrigado


Divide PHP errors and Application Errors

Question: I'm working on an Application and a question occurred. I was thinking of letting PHP errors a side (they would be log in the database or in a file) and manage other errors (such as "Your username is not valid" or "Your typed the wrong password" or "The image could not be loaded") with the so famous try-catch method. Is it good to completely manage this kind of errors only with try-catch?
Answer: The main advantage of exceptions is it's behavior of "petite mort", a local die() inside try{} block, preventing further code from execution.
While it's quite handy in handling application errors, it become not so good when dealing with validating user input. If a user made 3 mistakes filling a form, it would be merciful to show them all at once, not one after another.
You rather need POST/Redirect/GET pattern to handle user errors:
<?
if ($_SERVER['REQUEST_METHOD']=='POST') {

  $err = array();
  //performing all validations and raising corresponding errors
  if (empty($_POST['name']) $err[] = "Username field is required";
  if (empty($_POST['text']) $err[] = "Comments field is required";

  if (!$err) {
    //if no errors - saving data and redirect
    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
  }  else {
    // all field values should be escaped according to HTML standard
    foreach ($_POST as $key => $val) {
      $form[$key] = htmlspecialchars($val);
    }
} else {
  $form['name'] = $form['comments'] = '';
}
include 'form.tpl.php';
?>

Answer: I think: It is not, because this are not errors, or exception, but simply invalid input. They are also quite common and in this context not an exception in the meaning of the word.
On the other hand, because every exception breaks the current execution, it may lead to unexpected behaviour, when some code is not executed, just because someone entered an unknown username or something. In case of errors, or exceptions, you usually want to stop the execution, because you assume that the execution is not (reasonable) possible (until you catch the exception and go on).
Comment: Catching an exception will not break the execution. I tried to catch and exception and after that echo 'Something' and the string is shown.
Comment: I mean, at least the code beetween `throw` and the matching `catch` is skipped. Of course, if there is no code, nothing is skipped ;) But if you always catch exceptions right after they are thrown, why do you throw them at all? And depending on how/where you react on exceptions, the paths an application can take can get very confusing.
Answer: For enduser errors you should introduce a separate application level handling system.
Exceptions are useful for handling error conditions (errors that arise on production), while custom E_USER_ errors are the best fit for signaling data/debug/security issues (anything that should be handled at development stage).
Comment: @Charlie just validate user data in order and collect errors into array. Then finally check if this array is empty and then branch your code to save data or show the form back along with found errors
Comment: Are there any tutorial on how to better manage enduser errors?
Comment: @Charlie: I'm not aware of any. And there is certainly no standardized/best practice way to do it. Every application seems to require a custom mechanism. (Most frameworks provide some limited method to handle form validation at least.)
Answer: I use a custom Log class I wrote, and set it up as the default error handler and exception handler, as well as providing "debug", "info", "warning", "success" and "deprecated" methods for manually logging (and optionally displaying) messages.
The bonus is, it shows a dump of the variables in the current scope when an actual error occurs, rather than just telling you where it occurred.
Answer: Errors and exceptions are a technical matter while validation it's business mater.
IFs handle Business, TRY/CATCH handles technical stuff they do not mix and you should not mix them. There are times when you must use an if which throws an exception (PHP stuff) but that is the necessity at framework/architecture level for example
if(database_error_handle_raises_error()) {
     throw new MyDatabaseException(driver_raised_error);
}

this way you can better control the errors. But the rule stays:
Try/Catch/Throw = technical
If/Else Switch =  business


Using Dominance Convergence Theorem in derivation of Leibniz's rule

Question: I really need help understanding how Dominance Convergence Theorem applies to the following limit:
$$
\underset{\Delta t\rightarrow 0}{lim}\int_{a(t)}^{b(t)}\frac{f(x, t+\Delta t)-f(x,t)}{\Delta t}dx
$$
So that we can change the limit to the following integral:
$$
\int_{a(t)}^{b(t)}\underset{\Delta t\rightarrow 0}{lim}\left ( \frac{f(x, t+\Delta t)-f(x,t)}{\Delta t} \right )dx
$$
For clarification as to where I got this limit from, I was watching a video on the derivation of Leibniz's rule (link) and this was the only portion that I was unable to understand. The person doing the derivation just said we can switch the integral and limit, but I would like to understand why. Looking into it on my own, I understand that Dominance Convergence Theorem is used to switch a limit and integral, I just don't understand why this theorem can be applied in this specific case.
Answer: Fix $t$. Let $g_h(x) = \frac{f(x, t+h) - f(x,t)}{h}$. If there exists a function $g^*$ that

is integrable on the interval $[a(t), b(t)]$, and
is such that $|g_h(x)| \le g^*(x)$ for all $x \in [a(t), b(t)]$,

Then $\lim_{h \to 0} \int_{a(t)}^{b(t)} g_h(x) \, dx = \int_{a(t)}^{b(t)} \lim_{h \to 0} g_h(x) \, dx$ (i.e. you can switch the order of limit and integration.)
I didn't watch the video, but I assume there are some assumptions on $f$ such that the above conditions hold.


put string to length 20 (input and put function) sas

Question: I am trying to run the next code, because I need to put a string as char of length 20:
<code>data input;
input str: $16.;
format str $16.;
datalines;
9224000007993931
9224000008225795
9033000008162048
9111000001835936
9999000000350632
;
run;

data transf;
set input;
n1=substr('00000000000000'||str,length('00000000000000'||str)-19,20);
n2 = put(input(str,20.), z20.);
run;
</code>
And then output is the next:

Why the last digit in n2 variable change for the first and second record?
n1 is the true result.
Answer: It's a numeric precision issue. The maximum integer SAS can store exactly varies by OS; I'm guessing you've exceeded the limit. On windows, the maximum integer represented exactly is 2**53 = 9,007,199,254,740,992. You're probably best off leaving this as a character value.  When you use input() to convert it to a numeric value, you can lose precision.


Compare Two Select Lists, and Require User to Select Different Values

Question: Use case:  I'm presenting the User with two Select Lists populated with the same People names.
The first select list is Primary Person, the second select list is Backup Person.
The User must select a different value from each list. The same Person can't be a primary and backup. If the User attempts to save the page using the same value, Drupal will throw an error.
What's the best approach?
Answer: For the Drupal form API, this would be handled with your validation handler. Have it check your 2 form values for equality, and throw an error if so.
<code>function MYFORMBUILDER_validate($form, $form_state) {
  if($form_state['values']['person_primary'] == $form_state['values']['person_backup']) {
    form_set_error('person_primary', t('The primary and backup person must be different'));
    form_set_error('person_backup', t('The primary and backup person must be different'));
    array_pop($_SESSION['messages']['error']); //Remove duplicate message
  }
}
</code>
Comment: He may also need hook_form_alter() to add his custom validate handler to the existing node form first in the right order.
Comment: Yeah, this answer assumes a custom form. If it's created by another module you'll need `hook_form_alter()`.
Comment: Ok, thanks for the feedback. Should I put this in a Block with PHP filter, or in a custom module?
Comment: Custom module. A validation handler would not work embedded in a PHP filter block.
Comment: Ok. So If I understand all of comments - I will be creating a custom module, using hook_form_alter, and the above function ?
Comment: Correct, if this is a pre-existing form (not a custom one that already exists in your own module), then you'll need a `hook_form_alter()` invocation.


Same variable importance scores for SVM, KNN, and NB classifiers (R CARET )

Question: I am comparing some ML classifiers (RF, KNN, SVM, NB, and XGBOOST). After training these classifiers, I extracted variable importance scores from each of these models using varImp function in CARET.
I noticed that the variable importance scores for SVM, KNN, and NB are exactly the same. I am wondering, how is this possible.
Any help on this will be highly appreciated.
Thanks in adavance.
Answer: It is probably due to the fact that these are methods where no built-in importance score is implemented and the default behaviour to estimate importance is to compute the area under the ROC curve for each predictor. It is better explained at ch. 15 of the documentation  "The caret package" at https://topepo.github.io/caret/.
Comment: Thanks a lot autu_mn. This was very helpful.


VAR lag selection tests: Which one do I choose?

Question: When running varselect in R, I usually get a few different models to choose from based on different statistics. I know of:

Akaike information criterion (AIC)
Bayesian information criterion (BIC) or Schwarz criterion (SC)
Final Prediction Error (FPE) criterion
Hannan–Quinn information criterion (HQC)

What is the practical difference between these tests and under what circumstances should I prefer one over the other?
Comment: See Lütkepohl ["New Introduction to Multiple Time Series Analysis"](http://www.springer.com/gp/book/9783540401728) (2005), Section 4.3 "Criteria for VAR Order Selection", it gives a thorough discussion. Trying to summarize it here would be quite some work, though, but I hope you can access the original – it is pretty readable and clear. See also ["AIC,BIC,CIC,DIC,EIC,FIC,GIC,HIC,IIC — Can I use them interchangeably?"](https://stats.stackexchange.com/questions/86767/aic-bic-cic-dic-eic-fic-gic-hic-iic-can-i-use-them-interchangeably?rq=1) for AIC, BIC, and HQC; FPE is not covered there, though.
Comment: Just a curiosity: for a paradox involving AIC vs. BIC, see ["Paradox in model selection (AIC, BIC, to explain or to predict?)"](https://stats.stackexchange.com/questions/177391/paradox-in-model-selection-aic-bic-to-explain-or-to-predict?rq=1).
Comment: I think Lütkepohl's books is great, and the paper by Galit Shmueli too (each in its own way)!
Comment: @RichardHardy awesome.
Answer: Monte Carlo evidence suggests that the BIC penalty function works well in designs calibrated to macroeconomic data (Stock and Watson, 2011). It is common to run them all for comparison purposes.
Comment: Welcome to CV. Please add full reference in case your link dies in the future. Thanks


Help w/ Multivariable Chain rule?

Question: I'm having issues cranking through this problem. I think I'm not understanding the question at a more fundamental level, so any help is appreciated:

Find $dy/dx=y'(x)$ if $x$, $y$ are related by $\sin(x)+\cos(y)=\sin(x)\cos(y)$.

Here are my thoughts: I can divide by a $\sin(x)$ to get $1+\cot(y/x)=\cos(y)$, thus giving me $\cos(y)-\cot(y/x)=1$, and then go from there?
This is a confusing problem for me. Any help is great. Thanks!
Comment: (a) How did you get $\cot(y/x)$??? I'm afraid you have a very fundamental misunderstanding of trigonometric functions. (b) This type of problem belongs to the topic of "implicit differentiation". Have you studied it?
Answer: The first thing to realize is that this is not a "multivariable" calculus problem. While there are clearly two variables, you want to think of $y$ as a function of $x$, which is a standard single-variable situation.
The technique used to solve problems like these, where x and y are related with an equation, but not in the form of $y = f(x)$, is called implicit differentiation. The trick is to realize that, as you stated at first, $y$ is really a function of $x$ (you called it $y(x)$), not an independent variable.
So you want to differentiate both sides of the equation with respect to $x$, and when you see $y$, think of it as a function of $x$. This means that the (single-variable) chain rule must be used. For example, $\dfrac{d}{dx}(\cos y) = \dfrac{d}{dx}(\cos (y(x)) = -\sin y \cdot y'(x)$.
In this problem we have:
$\frac{d}{dx}(\sin x + \cos y) = \frac{d}{dx}(\sin x \cos y)$
$\cos x -\sin y \cdot y'(x) = \cos x \cos y - \sin x \sin y \cdot y'(x)$.
This gives you an equation that you can solve for $y'(x)$. Note that the other side will involve both $x$ and $y$, which is pretty common. You usually don't need to solve for $y$ in terms of $x$ or anything.

Help w/ Multivariable Chain rule?


Sphinx LaTeX Table of Contents - avoid toctree nesting of included rst files

Question: I have a Sphinx documentation with the following structure:
My chapter title
=====================

Chapter intro part 1
--------------------------
Brief introduction that I would like to have in the start of this chapter...

Chapter intro part 2
--------------------------
Another short section ...

.. toctree::
   :hidden:
   :maxdepth: 2

   folder/subchapter1
   folder/subchapter2

When I render the HTML based on this, things work as intended - I have a starting page for this chapter and my sub chapters are available from the side menu.
However, when I build my LaTeX/PDF output, the hierarchy is structured as follows in the Table of Contents and numbering:
0.2 My chapter title
- 0.2.1 Chapter intro part 1
- 0.2.2 Chapter intro part 2
  - 0.2.2.1 subchapter1
  - 0.2.2.2 subchapter2

What I wanted to have was below:
0.2 My chapter title
- 0.2.1 Chapter intro part 1
- 0.2.2 Chapter intro part 2
- 0.2.3 subchapter1 title
- 0.2.3 subchapter2 title

Or alternatively:
0.2 My chapter title
0.2.1 subchapter1 title
0.2.2 subchapter2 title

I realize this is probably an attempt to "hack" the toctree concept a bit, but I'm trying to both satisfy my hierarchy requirements for HTML and LaTeX with the same code.
I'm using Sphinx 1.8.5 and default LaTeX build settings.
Comment: Your `toctree` is under the heading `Chapter intro part 2` and will inherit its numbering. IMO a more correct structure would be to move the intros into their own chapter index files—`chapter1/index` and  `chapter2/index`—each with their own sub `toctree`, and the subchapter files into the correct `chapterN` folder. Thus your root `index` file is exactly what it should be used for, an index. Alternatively you can create a separate `latexindex.rst` and use that for latex builds, like in [Pyramid's docs](https://github.com/Pylons/pyramid/tree/master/docs).
Answer: I ended up using a structure as below:
Hardware
=============================

.. only:: html

  .. include:: hardware/intro.rst

.. toctree::
   :hidden:
   :maxdepth: 2

   hardware/intro
   hardware/installation
   hardware/connector

In the conf.py I added:
if tags.has("output_html"):
    exclude_patterns.append("*/intro.rst")

And in my build process I add the tag output_html as the standard html tag is not accessible in the conf.py. With this I got what I wanted.


Can't find files downloaded inside gitlab runner

Question: I'm setting up GitLab CI for a gradle project. After downloading gradle, the unzip command reports that no zip file is found even though the download was successful. I added a an ls just to see the contents of the directory and my zip file was not present. Below is my .gitlab-ci.yml file
image: docker:latest

stages:
  - build

before_script:
  - cd /usr/lib
  - curl https://services.gradle.org/distributions/gradle-2.10-bin.zip -o gradle-2.10-bin.zip
  - unzip "gradle-2.10-bin.zip"
  - ln -s "/usr/gradle-2.10/bin/gradle" /usr/bin/gradle
  - rm "gradle-2.10-bin.zip"
  - export GRADLE_HOME=usr/lib/gradle-2.10
  - export PATH=$PATH:$GRADLE_HOME/bin

build_job:
  image: java:8
  stage: build
  script:
    - gradle -v

This the error output of the job

$ unzip "gradle-2.10-bin.zip" unzip:  cannot find or open
  gradle-2.10-bin.zip, gradle-2.10-bin.zip.zip or
  gradle-2.10-bin.zip.ZIP. ERROR: Job failed: exit code 1
Answer: That is not the full error output of that command, this is:
$ unzip "gradle-2.10-bin.zip"
Archive:  gradle-2.10-bin.zip
  End-of-central-directory signature not found.  Either this file is not
  a zipfile, or it constitutes one disk of a multi-part archive.  In the
  latter case the central directory and zipfile comment will be found on
  the last disk(s) of this archive.
unzip:  cannot find zipfile directory in one of gradle-2.10-bin.zip or
        gradle-2.10-bin.zip.zip, and cannot find gradle-2.10-bin.zip.ZIP, period.

And if we check it that file is empty. If we do a curl -I on that url we get a 301 so you need to add the -L to that curl command to follow the redirection:
curl -L https://services.gradle.org/distributions/gradle-2.10-bin.zip

Comment: here's the screenshot to the whole screen http://pasteall.org/pic/show.php?id=25b447e8dd714a23e2b856cd82d2f0d4
Comment: Thanks. This was the solution. But now I'm getting gradle command not found. Is there a problem with the way I added it to the path?
Comment: Never mind, I found the problem. I missed a foward slach in export GRADLE_HOME=usr/lib/gradle-2.10


Why do batsmen usually ask a fielder to tie their shoelaces?

Question: When a batsman's shoelaces come undone, he usually asks a fielder (or umpire) to tie them. Why do they do that instead of doing it by themselves?
I would imagine it doesn't save any time. In fact, it would likely take more time unless the fielder is standing in a close-in position.
Answer: It's just a matter of convenience.
If a batsman has to tie his own shoelaces, he has to remove his gloves, and also look around his pads. Try wearing pads, kneeling down, and tying your shoelaces. You'll see the pads do seem to get in the way. Also, it's not like the batsman walks very far to ask a fielder/umpire to do this. He only asks the nearest person to him (who can tie his laces without much bother) to help him out, be it a fielder or an umpire.
But its not that a batsman cannot tie his own laces. I have seen plenty of cases where the batsman does it himself (like you mentioned, usually when there is nobody nearby to help). He just asks a fielder/umpire because it is less of a hassle and usually, fielders/umpires are glad to help out. Cricket is said to be the "gentleman's game" after all.
Comment: Perfect explanation. And this is exactly why the wicket keeper doesn't tie batsmen's shoelaces!  He has his own pads to handle :D
Comment: @Dawny33 No the wicket-keeper doesn't. Hence the bracketed **who can tie his laces without much bother**.


If $f(z)$ is an entire function, prove that it has a zero at $z_0$ of order $k\ge 1$ iff $z_0$ is a simple pole of $\frac{f'(z)}{f(z)}$

Question: Let $f(z)$ be an entire function. Prove that $f(z)$ has a zero at $z_0$ of order $k\ge 1$ iff  $z_0$ is a simple pole of $\frac{f'(z)}{f(z)}$ and the residue of $\frac{f'(z)}{f(z)}$ at $z_0$ is $k$.
Ok, so I know that every entire function $f(z)$ can be represented as a power series $f(z)=\sum_{n=0}^\infty a_nz^n$ where $n\gt1$ that converges everywhere in the complex plane. So I can say that $f(z)$ is differentiable everywhere. So, would I just be able to take the polynomial function maybe and work with that, $f(x) = a_nx^n + a_{n−1}x^{n−1} + . . . + a_2x^2 + a_1x + a_0$?
Continuing from @Raclette's answer below,
$\frac{f'(z)}{f(z)}=\frac{k}{(z-z_0)g(z)} + \frac{g'(z)}{g(z)}$or $=\frac{k+g'(z)(z-z_0)}{(z-z_0)g(z)}$
Comment: how is "zero of order k" defined in your lecture?
Comment: It should probably be "of order $k > 0$" (or $k\geqslant 1$). Write $f(z) = (z-z_0)^m\cdot g(z)$ with $g$ holomorphic and $g(z_0) \neq 0$.
Comment: @DanielFischer, corrections were made. Thanks
Answer: Write $f(z) = (z-z_0)^k g(z)$ where $k$ is the order of the zero of $f$ at $z_0$ (i.e., if $k=0$ then $f$ has no zero at $z_0$ and if $k < 0$ then $f$ has a pole at $z_0$) and $g(z)$ is analytic in a neighborhood of $z_0$.
Then $f'(z) = k(z-z_0)^{k-1}g(z) + (z-z_0)^kg'(z)$.
Now, what is $\frac{f'(z)}{f(z)}$?
Comment: give me a minute,I'm not as fast. Will put up my proposed solution shortly.
Comment: does the above seem correct to you?
Comment: yes! Here, the first term has a pole of order 1 unless $k=0$. The second term is analytic in a neighborhood of $z_0$, as $g(z)$ is.


Android -- AudioManager.onAudioFocusChange() fires randomly

Question: I'm building a media player and implementing onAudioFocusChange() in a way similar to the docs:
OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
    if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT
        // Pause playback
    } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
        // Resume playback
    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
        am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
        am.abandonAudioFocus(afChangeListener);
        // Stop playback
    }
  }
};

The only weird issue: when leaving my phone sitting with the app in the background and the mediaplayer paused, the service will randomly start playing.  When I remove the above code, it doesn't happen. So, onAudioFocusChange() is being called with AUDIO_FOCUS_GAIN as the argument seemingly randomly. Has anyone else dealt with this issue?
Answer: onAudioFocusChange() will be called everytime an app request or release the audio focus. This can come from any app, not just yours.
In fact, every notification that plays a sound (eq. Text/mail/...) will gain the focus and then release it. Once another app release the audio focus, your app will gain the focus again thus your resume playback will be called.
To avoid playing when you dont want to, you can keep a boolean that indicates if your app should play:
boolean wantsMusic = true;
OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
    if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT
        // Pause playback
    } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN && wantsMusic) {
        // Resume playback
    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
        am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
        am.abandonAudioFocus(afChangeListener);
        // Stop playback
    }
  }
};


How to validate links before moving to different location

Question: This would be most simple functional question in Drupal 7.
Now below mentioned things are mandatory to do and cant change the functionality.
1) I have created a custom block in module.
2) I have included form like below:-
function usercontent_block_view($delta='')
{

   $block = array();
   switch($delta)
   {
     case 'user_front_page' :
       $block['content'] = drupal_get_form('genre_all_login');
     break;
   }
   return $block;
}

3) Now I have some other content in block but which put me in trouble is shown below:-
function genre_all_login($form) {
  $form['new_user'] = array(
  '#type' => 'item',
  '#markup' => l('Add New User','http://www.google.com'),
    );
    return $form;
  }

4) So it includes a link which will move me to Google once clicked.
5) Now I want to validate certain content inside the block before user navigates to Google.So if the condition doesn't match then I will stop the user by showing an error message and hence user cannot traverse to Google.
Please tell me if it is possible or should I use different technique to handle this scenario.
Answer: You can achieve this using a client side validation. Like below,

Add an ID attribute to the external link
$form['new_user'] = array(
  '#type' => 'item',
  '#markup' => l('Add New User','http://www.google.com', array('attributes' => array('id' => 'external-link'))),
);

Add a JavaScript code to validate and preventi the click.
jQuery(document).ready(function() {
  jQuery('#external-link').click(function(event) {
    // Perform your validation. If the validation fails prevent events default behavior.
    validated = false;
    if (!validated) {
      event.preventDefault(); // You can also use return false instead of prevent default.
    }
  });
});

Hope this helps :)
Comment: Thanks. In my scenario I want to do PHP validation. Does Drupal provides anything out of box for PHP validation for links?
Comment: I will try to achieve functionality using this. Thanks for response


JS – Reload script when resizing viewport

Question: I have a dynamic HTML element which has a height set in percent and a width equal to the height. – The height changes, depending on the viewport size and I always have to obtain a 1:1 aspect ratio, which is why I use a scrip, on page load, to look at the height and make that the width too.
So when I open the site, everything looks like it should, but as soon, as I resize it, the height value of course changes and the width stays the same.
Is there a way so that I can make it, that my scrip reloads, when the viewport changes size?
Comment: Javascript works in an infinite loop of events. Take interest in events and find the right one. Maybe onresize? https://www.w3schools.com/jsref/dom_obj_event.asp
Comment: @SlawomirDziuba Thank you, I will look into this. – Still very new to JS. Regards- Simon
Answer:

…solves the Problem. – I just made my script into a function an added onresize to the body.
Credit to: w3schools – onresize Event and @SlawomirDziuba for pointing this out to me.
Edit:
As @SlawomirDziuba pointed out, you can also use:
window.addEventListener ('resize', myFunction);

Doing it like that allows you to have all your JS at one place.
Comment: It will make more sense to use js only in the js file and use: window.addEventListener ('resize', myFunction); Note the lack of parentheses () after myFunction. You don't call it, you assign it.
Comment: @SlawomirDziuba Thank you! – This feels like a more elegant solution. :)


Tuning adaboost

Question: The boosting algorithm Adaboost (when using a tree) has three core parameters:

number of weak learners to train
learning rate
max nb of splits (depth of tree)

What are good practices, perhaps proven empirically, for finding the appropriate value for these parameters?
One option I can think of is to do a grid search via cross validation and get out the validation accuracy (1-generalization error).
Answer:
Number of weak learners

Train many, many weak learners.  Then look at a test-error vs. number of estimators curve to find the optimal number.

Learning rate

Smaller is better, but you will have to fit more weak learners the smaller the learning rate.  During initial modeling and EDA, set the learning rate rather large (0.01 for example).  Then when fitting your final model, set it very small (0.0001 for example), fit many, many weak learners, and run the model over night.

Maximum number of splits

There is no a-priori best answer.  You need to grid search this one.
Comment: Thanks. Sounds a lot like grid search. Any literature/references you can think of that discuss this topic?

Tuning adaboost


How to set schema in datasource for DB2 connection in Spring boot

Question: I have different database connections but same tables in them. So for reusing those entity classes I have to fetch schema name dynamically. Tried to set schema in properties file and in datasource and is not working.
application.properties file :
spring.datasource1.url=jdbc:db2://localhost:5054/AB01
spring.datasource1.username=abc
spring.datasource1.password=abc
spring.datasource1.driver-class-name=com.ibm.db2.jcc.DB2Driver
spring.datasource1.testWhileIdle=true
spring.datasource1.validationQuery=SELECT 1

Have tried to set schema in properties file as below and got error "The DDM parameter value is not supported.  DDM parameter code point having unsupported value : 0x2110." error.
spring.datasource.url=jdbc:db2://localhost:5054/AB01?currentSchema=schema
spring.datasource.url=jdbc:db2://localhost:5054/AB01?search_path=schema
spring.datasource.url=jdbc:db2://localhost:5054/AB01?searchpath=schema

Tried like below in configuration class also but not working.
public DataSource dataSource() {
    DriverManagerDataSource ds = new DriverManagerDataSource(databaseURL, username, pwd);
    ds.setDriverClassName(driverClassName);
    Properties connectionProperties = new Properties();
    connectionProperties.setProperty("spring.datasource.schema", "schema");
    ds.setConnectionProperties(connectionProperties);
    return ds;
}

Comment: did you see this answer : https://stackoverflow.com/questions/24278659/change-database-schema-used-by-spring-boot
Comment: if you are using jdbc try this: spring.datasource.jdbc-url=jdbc:db2://localhost:5054/AB01:currentSchema=YOURSCHEMA;
Comment: Tried like this and got  Invalid database URL syntax error
Answer: Schema can be referred in application.properties as below
spring.datasource1.serverName=160.60.660.6
spring.datasource1.database=ABC
spring.datasource1.port=5083
spring.datasource1.schema=fdsf
spring.datasource1.username=usr
spring.datasource1.password=pwd

use DB2SimpleDataSource to create database
public DataSource dataSource() {
                    DB2SimpleDataSource  datasource = new DB2SimpleDataSource ();
                    datasource.setUser(username);
                    datasource.setPassword(password);
                    datasource.setServerName(server);
                    datasource.setDatabaseName(databse);
                    datasource.setPortNumber(port);
                    datasource.setDriverType(4);
                    datasource.setCurrentSchema(schema);
                    return datasource;
}


USSD service not working

Question: I'm trying to develop an application which silently dismiss the USSD responses.
I've used the code from http://commandus.com/blog/?p=58 with minor changes. I've created the IExtendedNetworkService.aidl in the package com.android.internal.telephony and USSDDumbExtendedNetworkService inside the package com.commandus.ussd. The problem is, nothing happens after running the application (even after restarting the phone).
Can someone point out what am I doing wrong? Should I write any additional code for making it work?
IExtendedNetworkService.aidl
package com.android.internal.telephony;

/**
*  Interface used to interact with extended MMI/USSD network service.
*/
interface IExtendedNetworkService {
 /**
 * Set a MMI/USSD command to ExtendedNetworkService for further process.
 * This should be called when a MMI command is placed from panel.
 * @param number the dialed MMI/USSD number.
 */
void setMmiString(String number);

/**
 * return the specific string which is used to prompt MMI/USSD is running
 */
CharSequence getMmiRunningText();

/**
 * Get specific message which should be displayed on pop-up dialog.
 * @param text original MMI/USSD message response from framework
 * @return specific user message correspond to text. null stands for no pop-up dialog need to show.
 */
CharSequence getUserMessage(CharSequence text);

/**
 * Clear timeout message and pre-set MMI/USSD command
 * This should be called when user cancel a pre-dialed MMI command.
 */
void clearMmiString();
}

USSDDumbExtendedNetworkService
    package com.commandus.ussd;
    import android.app.Service;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.net.Uri;
    import android.os.IBinder;
    import android.os.PatternMatcher;
    import android.os.RemoteException;
    import android.util.Log;

    import com.android.internal.telephony.IExtendedNetworkService;

    /**
    * Service implements IExtendedNetworkService interface.
    * USSDDumbExtendedNetworkService Service must have name
    * "com.android.ussd.IExtendedNetworkService" of the intent declared in the
    * Android manifest file so com.android.phone.PhoneUtils class bind to this
    * service after system rebooted. Please note service is loaded after system
    * reboot! Your application must check is system rebooted.
    *
    * @see Util#syslogHasLine(String, String, String, boolean)
    */
    public class USSDDumbExtendedNetworkService extends Service {
    public static final String TAG = "MobileServices";
    public static final String LOG_STAMP = "*USSDTestExtendedNetworkService bind successfully*";
    public static final String URI_SCHEME = "ussd";
    public static final String URI_AUTHORITY = "g_el.net";
    public static final String URI_PATH = "/";
    public static final String URI_PAR = "return";
    public static final String URI_PARON = "on";
    public static final String URI_PAROFF = "off";
    public static final String MAGIC_ON = ":ON;)";
    public static final String MAGIC_OFF = ":OFF;(";
    public static final String MAGIC_RETVAL = ":RETVAL;(";

    private static boolean mActive = false;
    private static CharSequence mRetVal = null;
    private Context mContext = null;
    private String msgUssdRunning = "G Testing...";

final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_INSERT.equals(intent.getAction())) {
            mContext = context;
            if (mContext != null) {
                msgUssdRunning = "ussd blocker Running";
                mActive = true;
                Log.d(TAG, "activate");
            }
        } else if (Intent.ACTION_DELETE.equals(intent.getAction())) {
            mContext = null;
            mActive = false;
            Log.d(TAG, "deactivate");
        }
    }
};

private final IExtendedNetworkService.Stub mBinder = new IExtendedNetworkService.Stub() {

    @Override
    public void setMmiString(String number) throws RemoteException {
        Log.d(TAG, "setMmiString: " + number);
    }

    @Override
    public CharSequence getMmiRunningText() throws RemoteException {
        Log.d(TAG, "getMmiRunningText: " + msgUssdRunning);
        return msgUssdRunning;
    }

    @Override
    public CharSequence getUserMessage(CharSequence text)
            throws RemoteException {
        if (MAGIC_ON.contentEquals(text)) {
            mActive = true;
            Log.d(TAG, "control: ON");
            return text;
        } else {
            if (MAGIC_OFF.contentEquals(text)) {
                mActive = false;
                Log.d(TAG, "control: OFF");
                return text;
            } else {
                if (MAGIC_RETVAL.contentEquals(text)) {
                    mActive = false;
                    Log.d(TAG, "control: return");
                    return mRetVal;
                }
            }
        }

        if (!mActive) {
            Log.d(TAG, "getUserMessage deactivated: " + text);
            //return null;//Use this in order to cancel the output on the screen.
            return text;
        }
        String s = text.toString();
        // store s to the !
        Uri uri = new Uri.Builder().scheme(URI_SCHEME).authority(URI_AUTHORITY).path(URI_PATH).appendQueryParameter(URI_PAR,text.toString()).build();
        sendBroadcast(new Intent(Intent.ACTION_GET_CONTENT, uri));
        mActive = false;
        mRetVal = text;
        Log.d(TAG, "getUserMessage: " + text + "=" + s);
        return null;
    }

    @Override
    public void clearMmiString() throws RemoteException {
        Log.d(TAG, "clearMmiString");
    }
};

/**
 * Put stamp to the system log when PhoneUtils bind to the service after
 * Android has rebooted. Application must call
 * {@link Util#syslogHasLine(String, String, String, boolean)} to check is
 * phone rebooted or no. Without reboot phone application does not bind tom
 * this service!
 */
@Override
public IBinder onBind(Intent intent) {
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_INSERT);
    filter.addAction(Intent.ACTION_DELETE);
    filter.addDataScheme(URI_SCHEME);
    filter.addDataAuthority(URI_AUTHORITY, null);
    filter.addDataPath(URI_PATH, PatternMatcher.PATTERN_LITERAL);
    registerReceiver(mReceiver, filter);
    // Do not localize!
    Log.i(TAG, LOG_STAMP);

    return mBinder;
}

public IBinder asBinder() {
    Log.d(TAG, "asBinder");
    return mBinder;
}

@Override
public boolean onUnbind(Intent intent) {
    unregisterReceiver(mReceiver);
    return super.onUnbind(intent);
}

   }

Manifest file
<service android:name="com.commandus.ussd.USSDDumbExtendedNetworkService">
        <intent-filter >
            <action android:name="com.android.ussd.IExtendedNetworkService" />
                <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
 </service>

Answer: Have you declared your broadcast receiver in your manifest file?
add inside your manifest:
<receiver android:name="com.xxx.receivers.BootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

<service android:name="your.package.ExtendedNetworkService" />

in BootReceiver.java :
    public void onReceive(Context context, Intent intent) {

        context.startService(new Intent(context,ExtendedNetworkService.class));
}

in ExtendedNetworkService.java :
public class ExtendedNetworkService extends Service {

    IExtendedNetworkService.Stub binder = new IExtendedNetworkService.Stub() {

        public void setMmiString(String number) throws RemoteException {}
        public CharSequence getMmiRunningText() throws RemoteException {

            return null;
        }
        public CharSequence getUserMessage(CharSequence text)
                throws RemoteException {

            Log.d(Constants.TAG, "Message : " + text);
            Log.d(Constants.TAG, "getMmiRunningTest() : " + getMmiRunningText());
                return null;
        }
        public void clearMmiString() throws RemoteException {
        }

    };

        return false;
    }

    public void onCreate() {

        Log.d(Constants.TAG, "ExtendedNetworkService Started..");

        super.onCreate();
    }

public IBinder onBind(Intent arg0) {

        Log.d(Constants.TAG, "ExtendedNetworkService got binded...");

        return binder;

    }

}

Comment: No.Its dynamically registered inside the service so, there is no need for implementing it through manifest.

http://developer.android.com/reference/android/content/BroadcastReceiver.html
Comment: Actually , i meant the receiver for Boot Complete. Have you declared it .?
Comment: No... What should i do with it? Start the service again from the receiver?
Comment: Yes. The ExtendedNetworkService or in your case the USSDDumbExtendedNetworkService will only get binded after you boot your phone. So , you must implement a Boot Completed Broadcast Receiver in your application. And inside onReceive() of that, start the USSDDumbExtendedNetworkService. Hope it solves your problem.
Answer: Complete working code sample https://github.com/alaasalman/ussdinterceptor
Enjoy!
Comment: the above code doesnot work with 4.2.2 aka sdk 17. Even its working with 4.2.1... the onBind() is not invoked at startup for 4.2.2
any idea?
Comment: Since 4.2.2 IExtendedNetworkService was removed due to security improvement. https://code.google.com/p/android/issues/detail?id=57120#c14
Answer: Please note that, this interface IExtendedNetworkService was removed starting from Android 4.2.2
No alternative provided by Google yet, and no plans to provide such alternative
For reference you can see
http://code.google.com/p/android/issues/detail?id=57120.
Answer: If your using android 3.1 (API 12), when an app installs it's in a stopped state by default until the user starts your app explicitly as stated in the commonsblog:
http://commonsware.com/blog/2011/07/13/boot-completed-regression-confirmed.html
and in the android documentation:
http://developer.android.com/about/versions/android-3.1.html#launchcontrols
I believe the bottom line is that an app containing only an IntentService or BroadcastReceiver cannot be started by it's own.

USSD service not working