org.im4java.core.CommandException: magick: no images found for operation

Question: I am trying to compare two images located under my OS machine.
I have ImageMagick running on my os machine.
and I am using this method:
public boolean compareImages (String expectedScreenShot, String capturedScreenShot, String pdiffCompare) {
  ProcessStarter.setGlobalSearchPath("/usr/local/bin/");
  CompareCmd compare = new CompareCmd();
  // For metric-output
  IMOperation cmpOp = new IMOperation();
  // Set the compare metric
  cmpOp.metric("AE");
  // Add the expected image
  cmpOp.addImage(expectedScreenShot);
  // Add the current image
  cmpOp.addImage(capturedScreenShot);
  // This stores the difference
  cmpOp.addImage(pdiffCompare);
  try {
     // Do the compare
     compare.run(cmpOp);
     compare.getErrorText();
     return true;
  }
  catch (Exception ex) {
     return false;
  }
   }

I'm using im4java:1.4.0, but when I run compare.run(cmpOp); I am receiving this exception:

org.im4java.core.CommandException: org.im4java.core.CommandException:
  magick: no images found for operation `-metric' at CLI arg 1 @
  error/operation.c/CLIOption/5225.

Any help would be appreciated.
Comment: What are the values of `expectedScreenShot` and `capturedScreenShot`? What is an OS machine?
Comment: @Mark Setchell expectedScreenShot and capturedScreenShot are the absolute path of the images that i want to compare between them and Yes it's an OS machine expectedScreenShot = /Users/username/src/automation/test2/test.png
capturedScreenShot = /Users/username/src/automation/test3/test.png
Comment: If you want the `AE` you need to set up a consumer for `stderr` with `compare.setErrorConsumer(StandardStream.STDERR);` I think.
Comment: @Mark Setchell when i used compare.setErrorConsumer(StandardStream.STDERR); i received org.im4java.core.CommandException: java.lang.NullPointerException
Comment: Mmmm, not too sure about that one - sorry. Can you try temporarily creating two JPEG files to compare rather than two PNG files and see if that helps. (Your installation may be incomplete and JPEG is more likely to work than PNG as the latter requires 2 additional libraries.)
Comment: @MarkSetchell same issue even when i use jpeg org.im4java.core.CommandException: java.lang.NullPointerException still apears
Answer: Actually this is a comment and not an answer, but I'm not allowed to comment here. I'm the author of im4java, but I don't have currently IM 7 installed on my machine. I'll try to upgrade if possible and gain some insights.
In the meantime, could you please try to dump the generated commandline (see the im4java-docs) and try that commandline directly? Please post the result.
Another workaround would be to use the convert-command, something like
convert -verbose file1.jpg file2.jpg -metric ae -compare diff.jpg
This creates the diff file, but my installation does not write the metrics to stderr. This might be the problem you have with the ErrorConsumer. In this case, ImageMagick has to fix their tools (magick is just a new name for convert).
Another option would be to switch to GraphicsMagick.
Comment: Thanks for the hint. My working solution is to add "convert": op.addRawArgs("convert"); Is this you intended solution?
Comment: Thanks Matthias! I was experiencing a similar issue with `Info` class / `identify` command and my solution was to write a similar class as `Info` but with `op.addRawArgs("identify");`. I guess this makes im4java run `magick identify args...` thus working around the issue.
Answer: I was also seeing this on linux, but not windows, with IMJava version 1.4 and ImageMagick 7.
After digging and debugging I was able to workaround this by deleting the compare file (a symlink to magick) and then copy magick back over compare (to get rid of the symlink).
Some more details for the curious - when im4java is getting ready to run the imagemagick command it does a File.getCanonicalName on the command (in this case 'compare') and that call comes back with 'magick'. So then im4java runs and calls magick with the command line parameters that compare expects and you get the exception youssef reported. The workaround above tricks getCanonicalName into not resolving to 'magick'.
Edit to answer Bernhard's question because i too can't comment: if you run the command line it generates you get no errors because the command line uses the 'compare' command. What's happening in the API is that it's using 'magick' instead. For example "compare -metric AE foo.png bar.png diff.png" works but "magick -metric AE foo.png bar.png diff.png" will not.
Comment: Reply above really helped us a lot. As a side note - you can also create hardlinks to `magick` instead of symlinks that it is by default: `ln magick compare` -- make sure to do so for all of them (`identify`, `convert`, etc)
Answer: I met the same question today with ImageMagick7 and im4java.
And that is my answer:Use custom command instead of these prepared commands,like ImageCommand imageCommand = new ImageCommand("magick","compare"); instead of CompareCmd compare = new CompareCmd();,
because IM7 add a prefix 'magick' before IM6's commands.


filterFunction with custom filter

Question: The filterFunction method is not called with custom filter component.
I tried assigning a filterFunction to this.column in the custom component. I tried setting filterFunction in the configuration of filter object.
createdOn: {
        title: 'Created On',
        valuePrepareFunction: (createdOn) => {
          return this.datePipe.transform(createdOn.toDate(),'dd.MM.yy,
                   HH:mm');
        },
        filterFunction: (value, query) => {
          value = this.datePipe.transform(value.toDate(), 'dd.MM.yy');
          return value.indexOf(query) >= 0;
        },
        filter: {
          type: 'custom',
          component: DateFilterComponent
        }
    }

Comment: Your mean filter by date, isn't right?
Answer: This is my solution about filter by date:
settings = {
    columns: {
        createDatetime: {
            title: 'Date Submitted',
            filter: {
                type: 'custom',
                component: DateFilterComponent,
            },
            valuePrepareFunction: (created) => {
                return this.datePipe.transform(new Date(created), 'MM/dd/yyyy');
            },
        }
    }
};

<ng2-smart-table [settings]="settings" [source]="..."></ng2-smart-table>

Don't forget: type: 'custom' in filter
And DateFilterComponent component:
import { Component, OnInit, OnChanges, SimpleChanges } from '@angular/core';
import { FormControl } from '@angular/forms';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/skip';
import { DefaultFilter } from 'ng2-smart-table';
import { debounceTime, distinctUntilChanged, skip } from 'rxjs/operators';

@Component({
    selector: 'date-filter',
    template: `<input [formControl]="inputControl" class="form-control" type="date" />`
})
export class DateFilterComponent extends DefaultFilter implements OnInit, OnChanges {
    inputControl = new FormControl('');

    constructor() {
        super();
    }

    ngOnInit() {
        this.inputControl.valueChanges
            .pipe(
                distinctUntilChanged(),
                debounceTime(this.delay),
            )
            .subscribe((value: number) => {
                this.query = value !== null ? this.inputControl.value.toString() : '';
                this.setFilter();
            });
    }

    ngOnChanges(changes: SimpleChanges) {
        if (changes.query) {
            this.query = changes.query.currentValue;
            this.inputControl.setValue(this.query);
        }
    }
}

filterFunction with custom filter


Cannot resolve symbol Digits.Builder()

Question: I want to  change the theme of the Digits screen , and also the text on the button that is provided by default.
Comment: If it can't resolve a symbol, then you're missing a library
Answer: change the background of the digit whatever color you want set it,same as settextColor like,
button.setTextColor(0xff0000);

or
button.setTextColor(Color.parseColor("#ff0000"));

or
button.setTextColor(getApplication().getResources().getColor(R.color.red));

set color to the layout as:
v.setBackgroundColor(0xFF00FF00);

Comment: i dont want to change the button named use my phone no..I want to change the theme of the screen where user enter there mobile no. and otp
Comment: yes,I have successfully integrate the library,and my app is working well.i am not able to theme the screen that is provided by api

Cannot resolve symbol Digits.Builder()


Javascript - Animation loop and frame rate

Question: I followed an article about getting the best out of delta time in animation loops.
It's the most advanced way to handle loop renders and updates I've ever read.
https://isaacsukin.com/news/2015/01/detailed-explanation-javascript-game-loops-and-timing
I implemented it within a class and it works.
However:
I would like to understand why I have sudden FPS drops when adjusting values:

I am on an iMac Pro which has a refresh rate of 60hz. But, when I set "maxFPS" to 60 (or any value below 70), my frame rate drops in 5 seconds from 60 FPS to 32fps. So, I need to increase "maxFPS" and I only get a steady 60fps when I set it above 70, to any value.

Whatever "maxFPS" I put, if I change the "if (timestamp > this.lastFpsUpdate + 1000)" statement to something slightly lower than 1000 (even 950), once, again, my frame rate drops dramatically around 32fps. So, if I want to refresh the update counter every half second, I just...can't.

Messing with those 2 values lead to the EXACT same behavior.
FYI:
my canvas is 3840 x 2160 but, the 2 issues I mentioned here above are exactly the same at that resolution or at 960x540. The resolution doesn't seem to affect the issues at all (I get the same frame rates and (lack) of performance no matter the resolution).
The fps drops seem so sudden for very specific parameter values that it feels like it's a code issue rather than a performance issue. Indeed, I don't see why a change from 1000ms to 950ms in the FPS display refresh rate would drop the FPS so dramatically all of a sudden. And I don't see why setting the maxFPS to 60 is a problem on a 60hz screen while setting it to 70 or even 1500 is just fine. And these drops will consistently happen no matter if I actually render something or if my draw/update functions are completely empty.
Here is my loop class file:
class Loop{

    //--------------------------------------------------------------------

    constructor(maxFPS,displayFPS){

        this.fps              = 60;
        this.maxFPS           = maxFPS; //if lower than 70, the fps is dropping fast
        this.displayFPS       = displayFPS;
        this.timestep         = 1000/this.fps;
        this.delta            = 0;
        this.lastFrameTimeMs  = 0;
        this.framesThisSecond = 0;
        this.lastFpsUpdate    = 0;

    }

    //--------------------------------------------------------------------

    mainLoop(timestamp) {

        if (timestamp < this.lastFrameTimeMs + (1000 / this.maxFPS)) {

            requestAnimationFrame(this.mainLoop.bind(this));
            return;

        }

        this.delta          += timestamp - this.lastFrameTimeMs;
        this.lastFrameTimeMs = timestamp;

        //any value lower than 1000ms is dropping the FPS here...
        if (timestamp > this.lastFpsUpdate + 1000) {

            this.fps              = 0.25 * this.framesThisSecond + 0.75 * this.fps;
            // same issue if I just put:
            //this.fps            = this.framesThisSecond;
            this.lastFpsUpdate    = timestamp;
            this.framesThisSecond = 0;

        }

        this.framesThisSecond++;

        var numUpdateSteps = 0;

        while (this.delta >= this.timestep) {

            // the update function of my working file
            update(this.timestep);

            this.delta -= this.timestep;

            if (++numUpdateSteps >= 240) {

                this.delta = 0;
                break;

            }

        }

        if(this.displayFPS == true){

            document.getElementById('frameRate').textContent = (Math.round(this.fps * 100) / 100).toFixed(2);

        }

        context.clearRect(0, 0, canvas.width, canvas.height);

        // the draw function of my working file
        draw(this.delta/this.timestep);

        requestAnimationFrame(this.mainLoop.bind(this));

    }

    //--------------------------------------------------------------------

    start(){

        // the setup function of my working file
        setup();

       requestAnimationFrame(this.mainLoop.bind(this));

    }

    //--------------------------------------------------------------------

}

Here is my working file:
//--------------------------------------------------------------------
// Initialize
//--------------------------------------------------------------------

const canvas = document.querySelector('canvas')
      canvas.width  = 3840; // tested: no impact on my issues
      canvas.height = 2160; // tested: no impact on my issues
const context       = canvas.getContext('2d');

const loop = new Loop(maxFPS=70, display=true);
      loop.start();

//--------------------------------------------------------------------
// Variables
//--------------------------------------------------------------------

var boxSize;
var boxPos;
var lastBoxPos;
var boxVelocity;
var limit;

//--------------------------------------------------------------------
// Animation Test
//--------------------------------------------------------------------

function setup(){

    boxSize     = 200;
    boxPosX     = 10;
    boxPosY     = 10;
    lastBoxPosX = 10;
    boxVelocity = 1;
    limit       = canvas.width - boxSize;

}

//--------------------------------------------------------------------

function update(delta){

    boxLastPosX  = boxPosX;
    boxPosX     += boxVelocity * delta;
    if (boxPosX >= limit || boxPosX <= 0) {boxVelocity = -boxVelocity;}

}
//--------------------------------------------------------------------

function draw(interpolation){

    context.beginPath();
    context.fillStyle = "#3e4856";
    context.fillRect((boxLastPosX + (boxPosX - boxLastPosX) * interpolation), boxPosY, boxSize, boxSize);

}

//--------------------------------------------------------------------

Thanks for your input.
Comment: You should reduce this to a single unambiguously answerable question focusing on a single issue.
Comment: I edited my question so that it is more focused. Thank you.
Answer: This is a function I once used in some prototyping task. It stores delays of several most recent frames in a buffer, and uses simple statistics to decide if the current frame should be rendered or dropped. It also detects "laggy frames" (like those slowdowns when you switch to another tab, or short inconsistent hangs while CPU is heavily loaded) and excludes them from calculations. This helps to avoid overcompensation which otherwise results in bursts of increased framerates.
In most cases, the function achieves nearly stable arbitrary FPS. However, it doesn't guarantee accurate regular patterns of allowed and dropped frames. Sometimes it even produces weird artifacts; like allowing 2 frames in a row, then dropping 2, then again allowing 2 (which should've been uniformly alternated instead). It is not a production quality of course, and should be possible to create better algorithm. The question is, whether the result is sufficiently good for a given task, or not.
Also notice that FPS here is top-bounded (and sometimes is slightly exceeded) rather than averaged.
The output of the following code doesn't fit into the console wrapper, so better look into the actual browser console. There're 5 sample loops, 3 seconds each.
PS1: bufferAll is needed not for the algorithm, but for calculating the actual FPS generated by the function. It keeps delays of all allowed frames over the last second (BUFFER_ALL_MIN_DURATION).
PS2: Values of all constants are there for fine-tuning. Current values might not be optimal, but they were fine for me the time I used this.

function startRenderLoop (fps, renderCallback) {

    // buffer of all frames; used to calculate actual average FPS
    const bufferAll = [0];
    // buffer of fast (non-laggy) frames; used to determine frame drops
    const bufferFast = [0];
    // bufferAll: minimum total duration, in seconds
    const BUFFER_ALL_MIN_DURATION = 1;
    // bufferAll: minimum number of frames
    const BUFFER_ALL_MIN_ENTRIES = 1;
    // bufferFast: minimum total duration, in seconds
    const BUFFER_FAST_MIN_DURATION = 1;
    // bufferFast: minimum number of frames
    const BUFFER_FAST_MIN_ENTRIES = 20;
    // callback delay will be considered laggy if exceeds 110 % AND at least 5 ms longer than expected delay;
    // laggy frames are always rendered, but don't contribute to stabilization of subsequent fast frames;
    // laggy delay unit is 10 microseconds
    const LAGGY_DELAY = Math.max(
        Math.floor(1.1 * 100000 / fps),
        Math.floor(100000 / fps) + 500
    );

    var bufferAllDuration = 0;
    var bufferFastDuration = 0;
    var loopStartTime;
    var lastCallbackTime;
    var lastFrameTime;
    var lastFrameDrops = 0;
    var frameId = -1;
    var requestId = requestAnimationFrame(rafCallback);
    var proceed = true;

    function rafCallback (time) {

        // use 10 microsecond time resolution; force to integers to avoid rounding errors
        time = Math.floor(time * 100);

        // first frame
        if (frameId == -1) {
            frameId = 0;
            loopStartTime = lastCallbackTime = lastFrameTime = time;
            renderCallback(0, 0, 0, 0, false, 0);
        }

        // subsequent frames
        else {
            let frameDelay = time - lastFrameTime;
            let callbackDelay = time - lastCallbackTime;

            // bufferAll: update buffer and its delay accumulator
            bufferAllDuration -= bufferAll[bufferAll.length - 1];
            bufferAllDuration += frameDelay;
            bufferAll[bufferAll.length - 1] = frameDelay;

            // bufferAll: remove old entries
            while (bufferAll.length > BUFFER_ALL_MIN_ENTRIES && ((bufferAllDuration - bufferAll[0]) / 100000) >= BUFFER_ALL_MIN_DURATION) {
                bufferAllDuration -= bufferAll.shift();
            }

            // this is a fast frame
            if (callbackDelay < LAGGY_DELAY) {
                // bufferFast: update buffer and its delay accumulator
                bufferFastDuration -= bufferFast[bufferFast.length - 1];
                bufferFastDuration += frameDelay;
                bufferFast[bufferFast.length - 1] = frameDelay;

                // bufferFast: remove old entries
                while (bufferFast.length > BUFFER_FAST_MIN_ENTRIES && ((bufferFastDuration - bufferFast[0]) / 100000) >= BUFFER_FAST_MIN_DURATION) {
                    bufferFastDuration -= bufferFast.shift();
                }

                // decrease statistical influence of the oldest frames (slightly improves stabilization)
                let weightedDuration = 0;
                let weightedDurationFactor = 0;
                for (let i = 0; i < bufferFast.length; i++) {
                    let factor = (i < 16)? ((i + 1) / 16): 1;
                    weightedDuration += bufferFast[i] * factor;
                    weightedDurationFactor += factor;
                }

                let fastFPS = 100000 * weightedDurationFactor / weightedDuration;
                // render if current frame fits into a desired FPS
                var render = (fastFPS <= fps);
            }

            // this is a laggy frame
            else {
                // bufferFast: discard the most recent frame
                bufferFastDuration -= bufferFast.pop();
                // render regardless
                var render = true;
            }

            if (render) {
                let averageFPS = 100000 * bufferAll.length / bufferAllDuration;
                frameId++;
                renderCallback(
                    // convert to milliseconds
                    (time - loopStartTime) / 100,
                    (time - lastFrameTime) / 100,
                    frameId,
                    lastFrameDrops,
                    callbackDelay >= LAGGY_DELAY,
                    averageFPS
                );
                lastFrameTime = time;
                lastFrameDrops = 0;
                bufferAll.push(0);
                bufferFast.push(0);
            }
            else {
                lastFrameDrops++;
            }

            lastCallbackTime = time;
        }

        if (proceed) {
            requestId = requestAnimationFrame(rafCallback);
        }
    }

    return function stopRenderLoop () {
        cancelAnimationFrame(requestId);
        proceed = false;
    };
}

function renderCallback (loopDuration, frameDelay, frameId, frameDrops, laggy, averageFPS) {
    console.log(
        `Loop: ${(loopDuration / 1000).toFixed(3)} sec ` +
        `/ ${averageFPS.toFixed(3)} FPS ` +
        `/ frame: ${frameId} ` +
        `/ delay: ${(frameDelay).toFixed(2)} ms ` +
        `/ dropped: ${frameDrops} ` +
        (laggy? '/ LAGGY': '')
    );
    if (loopDuration >= 3000) {
        stopRenderLoop();
        console.log('-'.repeat(80));
        if (fpsTestArray.length) {
            stopRenderLoop = startRenderLoop(fpsTestArray.shift(), renderCallback);
        }
    }
}
var fpsTestArray = [7.777, 33, 45, 59, 9000];
var stopRenderLoop = startRenderLoop(fpsTestArray.shift(), renderCallback);
Answer: I'll explain why, when you try to achieve 59 fps and your display is refreshing at 60 fps, that your technique actually achieves only 30 fps.
Allow me to make an analogy to sending packages with a delivery service:
Imagine you want to send a package once every 25 hours (yes, one more than 24 - that's slightly less frequently than once per day).  But the delivery person shows up each day on their schedule at exactly 9:00 am to collect any packages you want to send. (This is akin to your display's frame rate).
On Monday, you send your first package and feel like you're off to a good start.  Then, on Tuesday, the delivery person shows up at 9:00 am and you realize that only 24 of the desired 25 hours have elapsed, so you don't give the delivery person any packages, and instead say "I have nothing for you right now, see you later!"  The delivery person leaves, and then diligently shows up on their schedule on Wednesday at 9:00 am.  At this point you feel slightly annoyed but hand them your (now 23-hours late) package anyway and it gets delivered.  You sure would have liked to send it at 10:00 am on Tuesday, but that's not the delivery person's schedule.  They show up at 9:00 every day no matter what.
Then on Thursday the delivery person shows up again. And once more, you notice that it has been a mere 24 hours since you handed them your Wednesday delivery so you decline to give them a package to deliver on Thursday.  And on Friday at 9:00 am they show up and you again hand them a (again very late) package.
The cycle repeats and on average, with this technique, you are sending a package once every other day.  That's one package every 48 hours instead of one every 25 hours as you intended.
By your record keeping, you are achieving a goal of not delivering two packages fewer than 25 hours apart.  But you are not achieving a goal of delivering a package on average once every 25 hours over a longer period of time.  To do so, you would need to keep track of your average rate (number of packages delivered divided by total time elapsed over some reasonably long period of time), not the instantaneous rate (absolute interval between two deliveries).
(end of analogy)
If you want to achieve a rate slightly less than 60 fps, then hopefully you can see the analogy between rendering (delivering a package) and the rate at which the delivery person shows up to request renders (the requestAnimationFrame request and the refresh rate of your display).  And how, if the opportunities to render are happening once every 60th of a second, but you are declining to render on every second opportunity (because not enough time has elapsed - because you are using the instantanous accounting method described in the analogy), then you will achieve a rate of only 30 fps.
To correct the problem, the instantaneous accounting technique of if (timestamp < this.lastFrameTimeMs + (1000 / this.maxFPS)) { is inadequate and you must instead keep track of total frames rendered over some total time period using a moving average technique.
Comment: @BachirMessaouri, the expression you asked about is the author's attempt at adding [Hysteresis](https://en.wikipedia.org/wiki/Hysteresis) as a damping effect so that the reported fps is influenced by history in a way that smooths out large changes from frame to frame.  Note that `fps` is not used in the calculation that decides whether to drop a frame (which is `timestamp < this.lastFrameTimeMs + (1000 / this.maxFPS)`)
Comment: Thanks very much for this. I will read and re-read this as well as your link as many times as necessary so that I get the subtleties. And your dumbed down analogy will certainly help. One question though: is it because of that, that the author used "this.fps = 0.25 * this.framesThisSecond + 0.75 * this.fps;" instead of simply use "this.fps = this.framesThisSecond;" to display the frame rate? Isn't it his way of mimicking a moving average?


ODE: $y''y+ax+by+c=0,y=k\pm\sqrt2\int\sqrt{a\int\ln(y)dx-(ax+c)\,\ln(y)-by+K}dx,\int\frac{dy}{\sqrt{K-(ax+c)\,\ln(y)+a\int\ln(y)dx-by}}=k\pm\sqrt2x$

Question: Imagine we had a differential equation like:
$$y''-\frac xy=0$$
Now let's standardize the signs. Note we do not need a constant for the first term because of the zero product property. We can generalize any way we want, but this way of adding constants will generalize linearly and intuitively:
$$y''+\frac {ax+c}{y}+b=0\implies y''y+ax+by+c=0\implies y=y(a,b,c;x)\ne 0$$
where a,b,c are  any constants
Notice that we can then do:
$$y''+a\frac {x+\frac ca}{y}+b=0\implies y''y+a\left(x+\frac ca\right)+by=0$$
It can be shown that an implicit solution for $y=y(0,b,c;x)$ is the function $y(x)$ which satisfies the following functional integral equation. Be careful with the squared terms when solving here:
$$y''y+by+c=0\implies\left(\int_1^{y(x)}\frac{dt}{\sqrt{c_1-2(bt+c\ln(t)))}}\right)^2=(x+c_2)^2$$
This might remind you of an inverse gamma-type function which I did not see coming. Another nice thing is a closed form for $y(0,0,c;x)$ which uses the Inverse Error function:
$$y''y+c=0\implies y(x)=e^{\frac{c_1-2c\left(\operatorname{erf}^{-1}\left(\pm \sqrt{\frac 2\pi}\sqrt{ce^{-\frac{c_1}{c}}(x+c_2)^2}\right)\right)^2}{2c}} \implies \left(\int_1^{y(x)}\frac{dt}{\sqrt{c_1-2c\ln(t))}}\right)^2=(x+c_2)^2$$
Here is what the sample solution family for $y''y+x+y+1=0\ $looks like:

Here is what the sample solution family for $y''y-x-y-1=0\ $ looks like:

Related problems:

Approach Zero Search Results

This almost looks like the Airy Differential Equation, but it is not related:
$$y''-xy=0\implies y=\operatorname{Ai}(x)+i\operatorname {Bi}(x)$$
Unfortunately, we cannot use the Principle of Superposition to find a more general solution as the equation is nonlinear. @Eli showed that the following is a particular solution:
$$y=-\frac{ax+c}b\ne 0\implies -\frac{ax+c}b \frac{d^2}{dx^2} \frac{-ax-c}b +ax-b\frac{ax+b}b +c=0+ax-ax-c+c=0$$
The problem is that this is not the general solution. One attempt at finding such a general solution will use our aforementioned a=0 using a Generalized Puisex Series, with machine help, at t=0, but the convergence may be a problem. I have listed out a few of many known terms:
$$y''y+by+c=0\implies\left(\int_1^{y(x)}\frac{dt}{\sqrt{k-2(bt+c\ln(t)))}}\right)^2=(x+c_2)^2\implies \int_1^{y(x)}\frac{dt}{\sqrt{k-2(bt+c\ln(t))}}=\int_1^{y(x)}\left(\frac 1{\sqrt{k - 2 c \ln(t)}}+ \frac{b t}{(k - 2 c \ln(t))^\frac32} + \frac{3 b^2 t^2}{(2 (k - 2 c \ln(t))^\frac52)} +O\left(t^3\right)\right) $$
Then one may use an inversion theorem to find the inverse and find $y(x)$ with correct convergence.
My question is how to either find a closed form for $y(x)=y(a,b,c;x)$ or a general series representation for the general case without any initial values. Please do not give any implicit solutions as the goal is to find $y(x)$. You can even use an inversion theorem like the Lagrange Inversion Theorem. Please correct me and give me feedback!
Here is a general integral solution for which the main integral we need to put in terms of x. Here is a reference problem for the technique used by @Ron Gordon to solve the general solution and somehow integrate a general $y'y''$:

Solution to Differential Equation: $y'' = \frac{c_1}{y} - \frac{c_2}{y^2} $.

$$y''y+ax+by+c=0\mathop \implies^{y\ne0} y''+a\frac x{y'}+b+ \frac cy=0\implies -y''y'= a\frac {x y'}{y}+by'+ c\frac {y'}y$$
Now we integrate and use the referenced integration technique along with Logarithmic Differentiation. One also uses Integration by Parts of x and $\frac {y'}{y}$:
$$ \int -y''y'dx= a\int \frac {x y'}{y}dx+b\int y'dx+ c\int \frac {y'}y dx\implies c_1-\frac{y'^{\,2}}2=ax\,\ln(y)-\int \ln(y) dx+c_2+by+c_3+c\,\ln(y)+c_4\implies y'^{\,2}=-2ax\,\ln(y)+2a\int \ln(y)dx-2by-2c\,\ln(y)+c_1\implies y'=\pm\sqrt{c_1 -2ax\,\ln(y)+2a\int \ln(y)dx-2by-2c\,\ln(y)} \implies y=c_2\pm \sqrt 2\int\sqrt{a\int \ln(y)dx -ax\,\ln(y)-by-c\,\ln(y)+c_1} dx$$
Here is another way to solve:
$$\frac{y'}{\sqrt{c_1 -2ax\,\ln(y)+2a\int \ln(y)dx-2by-2c\,\ln(y)} }=\pm1\implies \int \frac{\frac{dy}{dx}}{\sqrt{c_1 -2ax\,\ln(y)+2\int \ln(y)dx-2by-2c\,\ln(y)}}dx=\pm\int dx  \implies \int \frac{dy}{\sqrt{c_1 -2ax\,\ln(y)+2a\int \ln(y)dx-2by-2c\,\ln(y)}}=c_2\pm x\implies \int \frac{dy}{\sqrt{c_1 -ax\,\ln(y)+a\int \ln(y)dx-by-c\,\ln(y)}}=c_2\pm \sqrt2 x$$
This is where I got stuck. If we could integrate, by substitution in terms of x maybe, with a series expansion and use a series reversion, then it should output $y(x)$ explicitly.
Comment: Particular solution of $y=-(ax+c)/b$.
Comment: Note that $\operatorname{Ai}(x)+i\operatorname{Bi}(x)$ is just a particular solution to Airy's equation.
Comment: @Gary That example was just used for context. The actual differential equation in the question has nothing to do with Airy's equation. It was just an explanation for how I came up with the general differential equation. Do you know any ideas to solve it as a series or in closed form?
Comment: Doesn't the substitution $y \to 1/y$ lead to terms involving $y'$?
Comment: @Aruralreadern Notice how I did not literally write: $$\frac 1{y''}-\frac xy=0$$, but instead: $$y''-\frac xy=0$$ this brings up a new family of functions when generalized. Please see the new edit.
Comment: @Eli What do you mean? Could you please write it out? This is because I am an amateur when it comes to differential equations. Also, part of the differential equation has (ax+c)/y
Comment: @TymaGaidash It means that $y=-(ax+c)/b$ solves the equation (plug it in and check for yourself!) but does not contain all possible solutions, evidenced by the fact that it has no arbitrary constants.
Comment: @Eli Yes, setting some a,b,c=0 works. You have solved part of the question. Thanks! How about the rest of the problem in a series or closed form?
Answer: I present to you 2 solutions. The first solves your ODE for the $b=0$ case by quadrature. The second is a solution via the power series method, which it seems like you'd be more interested in.
$\rule{170pt}{1pt}$
For $b=0$, the equation reduces to an Emden-Fowler equation, which can be transformed to an Abel equation of the second kind. Letting $y=-(ax+c)^{3/2}u/2$, and $ax+c=e^t$ brings the equation to an autonomous one,
\begin{align}
\ddot u=\dot u+\frac{3}{16}u+\frac{1}{a^2}\frac{1}{u}=0.
\end{align}
Now taking $\dot u=p(u)$, $\ddot u=pp'$ brings the equation to
\begin{align}
pp'=p+\frac{3}{16}u+\frac{1}{a^2}\frac{1}{u}.
\end{align}
This unfortunately does not fall under the Abel equations with simple solutions category. I'll copy the solution from "Exact analytic solutions of the Abel, Emden–Fowler and generalized Emden–Fowler nonlinear ODE" by Dimitrios E. Panayotounakosa and Dimitrios Kravvaritis without copying the method (it requires you to pay to view it).
\begin{align}
&p(u)=\frac{1}{2}(u+2\lambda)\left(\bar N(u)+\frac{1}{3}\right),\\
&G(\bar \xi)=\frac{e^{-\bar \xi}}{16}\frac{[(\bar \xi\sin(\bar \xi)\mathrm{ci}(\bar \xi)+\cos(\bar\xi)^2][4\bar \xi\mathrm{ci}(\bar\xi)+\cos(\bar \xi)]}{(\bar \xi \mathrm{ci}(\bar \xi))^3},\\
&\mathrm{ci}(\bar\xi)=-\int_{\bar\xi}^\infty\frac{\cos(s)}{s}\mathrm ds,\quad \bar\xi=\ln|u+2\lambda|,\\
&\left(\bar N(u)+\frac{4}{3}\right)^2-1=8\int\left[\frac{G(u)}{(u+2\lambda)^2}+\frac{1}{(u+2\lambda)^2}\left(\frac{3}{16}u+\frac{1}{a^2}\frac{1}{u}\right)\right]\mathrm du,
\end{align}
where $\lambda$ is an integration constant. Here is a paper I'd consider a 'proof by graphing' for the solution. $u(t)$ is then given by
\begin{align}
2\int \frac{\mathrm du}{(u+2\lambda)(\bar N(u)+1/3)}=t+\lambda_2,
\end{align}
and then $y(x)$ is implicitely given by
\begin{align}
\ln|ax+c|+\lambda_2=2\int \frac{\mathrm du}{(u+2\lambda)(\bar N(u)+1/3)},\quad u=\frac{-2y}{(ax+c)^{3/2}}.
\end{align}
An implicit solution? Yes. A useful solution for your needs? I doubt it. Just maybe if you go through the dirty work of finding $\bar N(u)$ the integral turns out possible.
$\rule{170pt}{1pt}$
With $b\neq0$, it is similar to an Emden-Fowler equation, but does not succumb to the same trick to make it autonomous.
First, we can eliminate all three constants from your equation. Taking $y=a^2u/b$ and $ax+c=a^2\xi/b^2$,
\begin{align}
uu''+u+\xi=0.
\end{align}
I can't find an analytical solution or come up with one myself, so I'll use a power series solution. Assuming a power series solution of the form
\begin{align}
u(\xi)=\sum_{n\geq 0}c_n\xi^n,\quad
u(\xi)''=\sum_{n\geq 0}(n+2)(n+1)c_{n+2}\xi^{n}.
\end{align}
The product $uu''$ can be found using the Cauchy product
\begin{align}
\left(\sum_{i\geq0}a_ix^i\right)\left(\sum_{j\geq0}b_ix^i\right)=\sum_{k\geq0}c_kx^k,\quad \text{where}\quad c_k=\sum_{l=0}^{k}a_lb_{k-l}.
\end{align}
So
\begin{align}
uu''=\sum_{n\geq0}b_n\xi^n,\quad \text{where}\quad b_n=\sum_{m=0}^n(m+1)(m+2)c_{2+m}c_{n-m}.
\end{align}
Substituting into the ODE gives that
\begin{align}
\sum_{n\geq0}(b_n+c_n)\xi^n+\xi=0.
\end{align}
For $n=0$:
\begin{align}
c_0(2c_2+1)=0.
\end{align}
The case of $c_0=0$ corresponds to the particular solution $u(\xi)=-\xi$. You can check that the rest of the coefficients turn out to be zero for this case.
Edit:
The coefficients are not that difficult to solve for, if you don't make mistakes! I've edited in the correct solution, and I've checked it in Desmos in the same manner that you have.
So for the other case we take
\begin{align}
c_2=-1/2.
\end{align}
Then the equation of recurrence becomes
\begin{align}
\xi+\sum_{n\geq0}\left(\sum_{m=1}^n (m+2)(m+1)c_{2+m}c_{n-m}\right)\xi^n=0.
\end{align}
Now correctly calculating the coefficients gives
\begin{align}
&n=1: 6c_3c_0=-1\\
&n=2: 6c_3c_1+12c_4c_0=0\\
&n=3: 6c_3c_2+12c_4c_1+20c_5c_0=0\\
&n=4: 6c_3^2+12c_4c_2+20c_5c_1+30c_6c_0=0\\
&n=5: 6c_3c_4+12c_4c_3+20c_5c_2+30c_6c_1+42c_7c_0=0.
\end{align}
Which has $c_0$ and $c_1$ as unknown quantities, corresponding to $c_0=u(0)$ and $c_1=u'(0)$, which makes much more sense than what I was touting before. Solving for some coefficients
\begin{align}
c_0&=u_0\\
c_1&=u'_0\\
c_2&=-1/2\\
c_3&=\frac{-1}{6c_0}\\
c_4&=\frac{-1}{2c_0}c_3c_1\\
c_5&=\frac{-1}{10c_0}(3c_3c_2+6c_4c_1)
\end{align}
Finding an equation for $c_n$ is a matter of spotting patterns and guessing a few times,
\begin{align}
c_n=\frac{-1}{n(n+1)c_0}\sum_{m=4}^n(m-2)(m-1)c_{m-1}c_{n-m+1},\quad n\geq4
\end{align}
So the solution is given by
\begin{align}
u(\xi)=\sum_{n\geq0}c_n\xi^n,
\end{align}
where the coefficients are given by
\begin{align}
c_0&=u_0,\quad c_1=u'_0,\quad c_2=-1/2, \quad c_3=-1/(6c_0), \\c_n&=\frac{-1}{n(n+1)c_0}\sum_{m=4}^n(m-2)(m-1)c_{m-1}c_{n-m+1},\quad n\geq4.
\end{align}
And in terms of $y(x)$:
\begin{align}
y(x)=\sum_{n\geq0}c_n\frac{b^{2n-1}}{a^{2n-2}}(ax+c)^n.
\end{align}
Here I've input up to the 7th coefficient to check in Desmos.
Comment: You have given me some fun reading to do. I will read over your answer and accept it once I finish. Do you know if it is possible to simplify the power series?
Comment: I wasn't able to find any sources online referencing similar recurrence relations. Perhaps somewhere in a non-linear analysis book? It should be possible to automate finding the coefficients to an arbitrary power, but I wasn't able to get it working in SymPy in the hour or two that I gave it a try.
Comment: That is fine, as long as we have an explicit general working solution, that is the goal. Are there any possible applications of the differential equation? Thanks again.
Comment: I'm not aware. From the Desmos graph you posted, it looks like I made an error or the series converges very slowly?
Comment: @TymaGaidash I've corrected my solution. The power series for sure works now!
Comment: I used the special case coefficients you gave and not the generalized coefficients, plus I could have easily made a typo. From the graph, the series seems to work where u"u+u+a≈0. This means for larger $c_1$ more terms may be needed.  _Could you please add in the rest of the parameters (a,b,c,$c_0,c_1$) into desmos because you have the special case of u"u+u+x=0? If not, then please at least add in the general, and simplified equation, of u"u+u+ξ,$c_0,c_1$?_ This will help visualize the entire solution set. Thanks!
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/129316/discussion-between-tyma-gaidash-and-eli).


What are the 3 note Freddie Green jazz chords?

Question: Freddie Green, the guitar player in the Count Basie Orchestra, had amazing chordal technique. I use his chords all the time but I think I'm missing some of the voicings. Where can I find a complete listing of Freddie Green chords?
Answer: If you're playing this style, I would suggest that instead of looking for a list of Freddie Green chords, you should procedurally construct all drop 2 chords using string set 643. Freddie Green chords are merely drop2 chords on strings 6543, but with the note on string 5 always omitted to leave a little bit of space for the rest of the ensemble.
(Straw man coming up...) Some may say, "but wait, sometimes you play a major 6th chord in substitution of a major seventh, and that merits its own place on a list of "major 7th freddie green chords." Hogwash, I say. The decision to make small harmonic substitutions is not really directly related. You can make many substitutions especially in this use of thin shell chords.
Comment: I've been experimenting with drop 2 voicings on ukulele, though the reentrant tuning makes some of them near-impossible. Funnily enough, the guitar's drop 2 chords on the top set are the ukulele's close-position chords!
Answer: Here are the complete Freddie Green chord forms in a compact format that demonstrates both the economy of the form together with the chord structure.

Each vertical line is a guitar string for guitars tuned EADGBE.
Each grid is moveable up and down the neck.
"X" signifies the root of the chord.
The numbers below each grid show the scale degrees (notes) of the chord.  In this case X = 1 :-)
"-" signifies a flatted note
As I first learned from other players when I was learning jazz, if you know all the scale degrees of a chord and you know the exact location of the root note (1) of the chord then you can easily create all the other chords you need from a dominant seventh or diminished chord.

This grid is not for using on the bandstand, it's for practicing chord progressions at any arbitrary place on the neck.
As an example let's do a compact and efficient ii-V7 move in the key of C.

So we're looking at Dm to G7 or some variant of the same.
Dm: D F A
G7: G B D F
Use the first X7 form on the 10th fret for a Dm7 by flatting the b7 to get a 6, easy.
D is the 5 of the G7 chord so use the third grid on the 10th fret, a simple shift of just one note.
Astute readers will see that if you used a Dm6 instead of a Dm7, you don't even have to change the chord form for the ii-V7 progression.


Exclude users from users list in issue tracking

Question: I'm trying to implement an issue tracking application with Drupal.
I have 4 clients and I want that each one of them will be able to access the site and add an issue.
I filter the project ID so any client see only his project issues.
The only thing I don't get how to do is to assign an issue.
In the "Issue" content type I created a "user Reference" filed called "Assign To" (which cause to Rules to send an email to the assigned user).
I want to be able to assign an issue to any client, but I want a client to be able to assign an issue only to me.
How can I do that?
If I can't exclude some users from the list (say-by role) - do you have any idea about different way to achieve the "Assign To" functionality?
Answer: Since your needs are so specific, I think the easiest (and maybe most logical) way to do this is not to restrict the users on the list. Instead, hide the field for all users of a certain role and have the value default to you. And for you, just don't hide it.
You can achieve this in a few ways. It would be very simple to write a custom module to do this. Use hook_form_alter() to access your issue form. In that function, use the global $user object to check the role of the current user, and  if it's your clients' role, set the '#access' property to FALSE and the '#value' to your user id. That's all.
You can probably do this without custom code also. Every field already has a default value in Drupal core. Set the default value for that field to you. Then use a module like Field Permissions to hide the field from your clients.
This achieves what you want without actually messing with the user reference list. That is also an option, but seems like a worse option to me. To do that, you would need a custom hook_form_alter() that, depending on the current user's role, would loop through the #options for that field and remove any users that aren't you.
Comment: That is a good idea. thank you. I wanted the client to understand that he/she are rolling the issue to my side and that it is my responsibility now, but it seems like I can't do that.
Comment: Well, you could. Like I mention in the last part of the answer, it is totally possible to do what you're thinking. Note though that even If you go with my first suggestion (hiding the field), it would only be hidden on the edit form. As soon as your client would create the issue, It would be listed as assigned to you, and they would see that on the node view page, just not the create or edit page.
Comment: you are right. that is the solution I'm going to implement. BTW - I created a view that will show issues for a specific project. example: /issues/11. how can I prevent the client to guess that there are other projects and load issues from other project? (in other words: how can I define that a specific role  is allowed to see content with a specific field value?)
Comment: well - seems like this would do what I want: http://drupal.org/node/31601


Event logger won't start: error 2 The system cannot find the file specified, Windows server 2008R2

Question: NOTE: this is a "spawn" of a previous post which dealt with 2 different issues and became too lengthy, so I decided to clean the original question and post this issue in a separate question
When I try to start Windows Event Log via net start eventlog or via Services panel, I get an error:
C:\Users\Administrator>net start eventlog
The Windows Event Log service is starting.
The Windows Event Log service could not be started.

A system error has occurred.

System error 2 has occurred.

The system cannot find the file specified.

I tried the following advice I from here:

restarted the OS (virtual on the host's VMWare).
re-checked the settings in services menu -they are like in the link.
checked the identity in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\eventlog - the identity is NT AUTHORITY\LocalService
gave all Authenticated Users full access to C:\Windows\System32\winevt\Logs
ran fc /scannow - Windows Resource Protection did not find any integrity violations.
went to the file %windir%\logs\cbs\cbs.log  - all clean, [SR] Repairing 0 components

EDIT: Uninstalled the recent system updates and rebooted - didn't help
EDIT: Sysinternals Process Monitor results when running start service from services panel (procmon in elevated mode):

filters:
process name is svchost.exe : include
operation contains TCP : exclude

the  events captured are:
21:50:33.8105780    svchost.exe 772 Thread Create       SUCCESS Thread ID: 6088
21:50:33.8108848    svchost.exe 772 RegOpenKey  HKLM    SUCCESS Desired Access: Maximum Allowed, Granted Access: Read
21:50:33.8109134    svchost.exe 772 RegQueryKey HKLM    SUCCESS Query: HandleTags, HandleTags: 0x0
21:50:33.8109302    svchost.exe 772 RegOpenKey  HKLM\System\CurrentControlSet\Services  REPARSE Desired Access: Read
21:50:33.8109497    svchost.exe 772 RegOpenKey  HKLM\System\CurrentControlSet\Services  SUCCESS Desired Access: Read
21:50:33.8110051    svchost.exe 772 RegCloseKey HKLM    SUCCESS
21:50:33.8110423    svchost.exe 772 RegQueryKey HKLM\System\CurrentControlSet\services  SUCCESS Query: HandleTags, HandleTags: 0x0
21:50:33.8110705    svchost.exe 772 RegOpenKey  HKLM\System\CurrentControlSet\services\eventlog SUCCESS Desired Access: Read
21:50:33.8110923    svchost.exe 772 RegQueryKey HKLM\System\CurrentControlSet\services\eventlog SUCCESS Query: HandleTags, HandleTags: 0x0
21:50:33.8111257    svchost.exe 772 RegOpenKey  HKLM\System\CurrentControlSet\services\eventlog\Parameters  SUCCESS Desired Access: Read
21:50:33.8111547    svchost.exe 772 RegCloseKey HKLM\System\CurrentControlSet\services  SUCCESS
21:50:33.8111752    svchost.exe 772 RegCloseKey HKLM\System\CurrentControlSet\services\eventlog SUCCESS
21:50:33.8111901    svchost.exe 772 RegQueryValue   HKLM\System\CurrentControlSet\services\eventlog\Parameters\ServiceDll   SUCCESS Type: REG_SZ, Length: 68, Data: %SystemRoot%\System32\wevtsvc.dll
21:50:33.8112148    svchost.exe 772 RegCloseKey HKLM\System\CurrentControlSet\services\eventlog\Parameters  SUCCESS
21:50:33.8116552    svchost.exe 772 Thread Exit     SUCCESS Thread ID: 6088, User Time: 0.0000000, Kernel Time: 0.0000000

NOTE: previoulsy,  for
21:46:31.6130476    svchost.exe 772 RegQueryValue   HKLM\System\CurrentControlSet\services\eventlog\Parameters\ServiceDll   SUCCESS Type: REG_SZ, Length: 68, Data: %SystemRoot%\System32\wevtsvc.dll

I also got NAME NOT FOUND error ,so I created the new string value for the Parameters with the name ServiceDll and data %SystemRoot%\System32\wevtsvc.dll (copied from the upper HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog key) and this event now is
21:46:31.6130476    svchost.exe 772 RegQueryValue   HKLM\System\CurrentControlSet\services\eventlog\Parameters\ServiceDll   SUCCESS Type: REG_SZ, Length: 68, Data: %SystemRoot%\System32\wevtsvc.dll

I also checked for the presence of wevtsvc.dll in the place and it's there.
Also, I tried to capture all events with path containing 'event' and got following events firing every several seconds:
21:38:38.9185226    services.exe    492 RegQueryValue   HKLM\System\CurrentControlSet\services\EventSystem\Tag  NAME NOT FOUND  Length: 16
21:38:38.9185513    services.exe    492 RegQueryValue   HKLM\System\CurrentControlSet\services\EventSystem\DependOnGroup    NAME NOT FOUND  Length: 268
21:38:38.9185938    services.exe    492 RegQueryValue   HKLM\System\CurrentControlSet\services\EventSystem\Group    NAME NOT FOUND  Length: 268

Also, I tried to capture all the events containing 'file', excluding w3wp.exe, chrome.exe, wmiprvse.exe, wmtoolsd.exe, System and it shows NO attempts to access any file ih the time I try to start the event logger  (if run from cmd - there are several hits by net executable, not present if run from the panel).

EDIT: the event logging stopped working on 04/May/2014 at 03:15.
The only change that day was security update 2964444 - Security Update for Internet Explorer 11 for Windows Server 2008 R2for x64-based Systems, that was installed exactly 04/May/2014 at 03:00. Apparently, that's what broke my machine...
What can be done?
Answer: What solved the problem was to delete the
HKLM\System\CurrentControlSet\services\eventlog\Parameters\

key.
As I stated earlier, I've seen this error with Process Monitor, but chose to put there some key - and that was my mistake. I should've delete this key instead.
Comment: This also fixes the same problem on Windows server 2012 R2.


$f(2x)-f(x)<f(3x)-f(2x)$ using Lagrange theorem

Question: Let $f$ be a continuous function, with the initial condition: $f''>0$.
I need to prove that $f(2x)-f(x) < f(3x)-f(2x)$.
By $f''>0$ I can learn that $f'$ is monotonous increasing, and so I tried to use Lagrange or Taylor.
Thank you.
Comment: By some theorem (I'm not sure which one) and under some conditions (I'm not sure which conditions) $f(2x) = f(x) + x f'(y)$ for some $0\leq y \leq x$ and similarly $f(3x) = f(2x) + x f'(y)$ for some $2x \leq y \leq 3x$.
Comment: By the way, It's kind of odd to refer to the mean value theorem as Lagranges theorem, I had to use wikipedia to know what you mean. (Where I've seen it, it is used for Lagranges theorem in group theory, or Lagranges four-square theorem.)
Comment: @Myself: What is meant is probably the Lagrange form of the remainder in the Taylor expansion, which indeed is (a generalization of) the mean value theorem.
Comment: @Myself: it's a common name for the mean value theorem outside the US.
Comment: @Andy: I don't even live in the US, perhaps you mean "outside Frenchspeaking countries"? Maybe Italy counts too, I remember Lagrange was actually Italian. :-) Thanks for the clarification though.
Comment: @Myself: sorry for the misunderstanding ;) I checked your profile and since there was nothing on it I made an assumption, no harm intended :D. Maybe it's for "romance language"-speaking countries, I don't know. ;)
Answer: You are given that $f''(x)>0$ everywhere. If this condition holds, then $f(x)$ is convex on its domain.
Any convex function will satisfy Jensen's Inequality. Using Jensen's inequality with two terms, you have
\begin{equation}
f(2x)<\frac{f(x)+f(3x)}{2}
\end{equation}
i.e.,
\begin{equation}
f(2x) - f(x) < f(3x) -f(2x)
\end{equation}
Comment: It's nice to recognise the special case of Jensens inequality (I totally hadn't noticed) but doesn't it feel a bit like 'cheating', considering the "calculus I" environment?
Comment: If you are willing to use that $f'' > 0 \implies$ convexity, then isn't the desired inequality the "other", known to be equivalent for smooth functions, characterisation of convexity? (In other words, Jensen's inequality with two terms applied to convex functions is trivially true.)
Comment: @Myself - I didn't think I was cheating here because the OP didn't say anything about using only "Calculus I" methods.
Answer: Let $g(y) = f(2x+y)$. Then
$$g(y) = g(0) + y g'(0) + \frac{y^2}{2} g''(\xi)$$
$$g(-y) = g(0) - y g'(0) + \frac{y^2}{2} g''(\eta)$$
Note that $g'' > 0$. Hence, adding the above two we get $$g(y)+g(-y) = 2g(0) + \frac{y^2}{2} g''(\xi) + \frac{y^2}{2} g''(\eta) > 2g(0)$$
Hence, we get $$f(2x+y) + f(2x-y) > 2f(2x)$$ Plug in $y=x$ and rearrange to get
$$f(2x)-f(x) < f(3x)-f(2x)$$
(PS: This is nothing but the derivation of Jensen's in the case when $\lambda = \frac{1}{2}$)
Answer: I'll try to expand my comment a bit:
First assume $x>0$.
Since $f$ is continuous everywhere, it is continuous on $[x,2x]$. By the mean value theorem, there is some $y_1\in [x,2x]$ such that $f(2x)-f(x) = xf'(y_1)$.
Similarly, there is some $y_2\in [2x,3x]$ suc that $f(3x)-f(2x) = xf'(y_2)$.
Therefore it is sufficient to show that $xf'(y_2) > xf'(y_1)$, or (because $x>0)$ that $f'(y_2) > f'(y_1)$. We know that $y_2 \geq y_1$ and that $f'$ is strictly increasing so we'll just have to exclude the possibility that $y_1 = y_2$. But in that case $y_2 = y_1 = 2x$ which leads to a contradiction. ( $f(2x) = f(x) + \int_x^{2x} f'(t)dt < f(x) + \int_x^{2x} f'(2x) dt = f(x) + xf'(2x) = f(2x)$. Although there are probably neater ways to find a contradiction.)
Now assume $x<0$. Construct $g(x) = f(-x)$ and reason with $g(x)$; I haven't done it but it shouldn't be too hard.


Python gives a "Syntax Error" on "else:"

Question: My Error
Python throws a syntax error pointed at the last "e" of "else:", preceded by an if statement and inside a while loop.
My Objective
Test if certain parameters are true, if true then go to the beginning of the loop and if not true then perform certain statements and increment a value.
My Source Code
from random import randint

def returnDigRoot(num):
    digs = []
    while len(str(num)) != 1:
        num = str(num)
        for each in num:
            digs.append(each)
        num = int(num)
        digs = [int(i) for i in digs]
        num = sum(digs)
    return(num)
def rnum():
    return(randint(1,99999))
ran_nums = []
sols = []
it = 1

The problem area is here
while it <= 3:
    print("Generating numbers")
    current = randint(1,99999)
    print("randomly intializing the 'current' int value")
    print("testing if the digital root is greater than 6")
    if returnDigRoot(current) > 6:
        print("going back to start of loop")
        continue
    print("testing if it isnt")
    else:
        ran_nums.append(current)
        print("append 'current' to ran_nums")
        sols.append(returnDigRoot(current))
        print("appending its digital root to sols")
        it += 1
        print("incrementing the iterator variable")

My Research
I looked at many questions on StackOverflow and other sites and could not find a solution to my problem; most problems people had with else statements were related to tabbing errors, preceding errors (which I checked for), no preceding if statement, or multiple else statements.
Thanks in advance for any help.
Comment: Please cut/paste the traceback you see and the command you use to execute the program.
Comment: code seems to have issues. use prints to find your error
Comment: I ran the code from IDLE, so it doesn't have a traceback, it just shows a popup box that says "syntax error", and the print statements i had in before removing them from the question don't come up, it's just the popup box
Comment: The code works, but it works forever
Comment: Confusing syntax errors are often due to missing closing parentheses. The syntax error is triggered by code that is fine, it's just the first thing that would not be valid inside the previous parenthesized expression. I don't see any such issue in the code you've posted, but perhaps you've fixed the error in copying your code to Stack Overflow.
Comment: I'll edit the source code in the question to include everything
Comment: The line `print("testing if it isn't")` isn't indented correctly
Answer: print("testing if it isnt") needs to be indented. As it stands, your code doesn't really relate the if with the else because of the indentation. It's like writing something like this in C:
if(<condition>)
{
  <action>
}
prinf(...)
else
{
 <action>
}

Just align the print line with the rest of the code under the if statement.
Answer: The line:
print("testing if it isnt")

isn't indented correctly.  You can't have anything in between an if block and the else block.
Answer: Your statement:
print("testing if it isnt")

is indented to the wrong level; that makes the else: that follows an independent statement, which is syntactically wrong.  Probably you meant that print statement to follow the else and be indented one level.
Answer: This is most likely a indentation/space/tabbing issue since I copy pasted the code and I don't get any errors. Though I am on Python 2.7.10. (Repasting it here to ensure you can copy paste the same and try):
from random import randint

def returnDigRoot(num):
    digs = []
    while len(str(num)) != 1:
        num = str(num)
        for each in num:
            digs.append(each)
        num = int(num)
        digs = [int(i) for i in digs]
        num = sum(digs)

    return(num)
def rnum():
    return(randint(1,99999))
ran_nums = []
sols = []
it = 1

while it <= 3:
    current = randint(1,99999)
    if returnDigRoot(current) > 6:
        continue
    else: # this is where the error is pointed
        ran_nums.append(current)
        sols.append(returnDigRoot(current))
        it += 1

On an unrelated note, that while loop will take a long time to exit since the exit criteria is very small (two current <=36 only will cause exit).


Proof Combinatorics problem

Question: Proof that :
$P^n_r + P^{n+1}_r + P^{n+2}_r +...+ P^{n+m}_r =
 \frac1{r+1}(P^{n+m+1}_{r+1} - P^{n}_{r+1})$
Attempt:
LHS :
$r!C^{n}_r + r!C^{n+1}_r + r!C^{n+2}_r + ..... r!C^{n+m}_r$
$=r!(C^{n}_r + C^{n+1}_r + C^{n+2}_r + ..... C^{n+m}_r)$
$=r!C^{n+m+1}_{r+1}$
$=r!\frac{(n+m+1)!}{(r+1)!(n+m-r)!}$
$=\frac1{r+1}\frac{(n+m+1)!}{(n+m-r)!}$
$=\frac1{r+1}\frac{(n+m+1)!}{(n+m-r)!} \frac{(r+1)!}{(r+1)!}$
$=\frac1{r+1}\frac{(n+m+1)!}{(n+m-r)!(r+1)!} (r+1)!$
$=\frac1{r+1}C^{n+m+1}_{r+1}(r+1)!$
$=\frac1{r+1}P^{n+m+1}_{r+1}$
Need help stuck.
Answer: You had the right idea, but you made a mistake going from the second line of your calculation to the third: it's not true in general that
$$\sum_{k=n}^{n+m}\binom{k}r=\binom{n+m+1}{r+1}\;.$$
What is true is that
$$\sum_{k=\color{red}r}^{m+n}\binom{k}r=\binom{n+m+1}{r+1}\;.$$
Thus,
$$\sum_{k=n}^{n+m}\binom{k}r=\sum_{k=r}^{m+n}\binom{k}r-\sum_{k=r}^{n-1}\binom{k}r=\binom{n+m+1}{r+1}-\binom{n}{r+1}\;.$$
Comment: Hi could you explain the last line on how you split the summation. Is that Vandermonde's Identity. I have it in my notes but it looks  different there
Comment: @RStyle: No, it's just grouping terms. Maybe it's easier to see if you rewrite it as $$\sum_{k=r}^{m+n}\binom{k}r=\sum_{k=r}^{n-1}\binom{k}r+\sum_{k=n}^{m+n}\binom{k}r\;.$$ Does that help? (And yes, you need $r<n$ in order to make this split.) The first summation on the right contains the term with $k<n$, and the second contains the terms with $k\ge n$.
Comment: Additional: The question did state that r<n  if that helps in explaining to me
Comment: No lol i dun get the n-1 part. Is there an explanation through words :D
Comment: @RStyle: For simplicity let $a_k=\binom{k}r$. On the left we have $$a_r+a_{r+1}+\ldots+a_{m+n}\;.$$ On the right we simply split this as $$(a_r+\ldots+a_{n-1})+(a_n+\ldots+a_{m+n})\;.$$ We know the lefthand sum and the first sum on the right; they're $\binom{n+m+1}{r+1}$ and $\binom{n}{r+1}$. Subtracting one from the other gives us the second sum on the left, which is the one that we really want.
Comment: @RStyle: You're welcome!

Proof Combinatorics problem


Why linear regression has assumption on residual but generalized linear model has assumptions on response?

Question: Why linear regression and Generalized Model have inconsistent assumptions?

In linear regression, we assume residual comes form Gaussian
In other regression (logistic regression, poison regression), we assume response comes form some distribution (binomial, poission etc.).

Why sometimes assume residual and other time assume on response? Is is because we want to derive different properties?

EDIT: I think mark999's shows two forms are equal. However, I do have one additional doubts on i.i.d:
My other quesiton,
Is there i.i.d. assumption on logistic regression? shows generalized linear model does not have i.i.d assumption (independent but not identical)
Is that true that for linear regression, if we pose assumption on residual, we will have i.i.d, but if we pose assumption on response, we will have independent but not identical samples (different Gaussian with different $\mu$)?
Comment: See also https://stats.stackexchange.com/questions/295340/what-to-do-with-glm-gamma-when-residuals-are-not-normally-distributed/302413#302413
Answer: The assumptions are not inconsistent. If, for $i = 1, \ldots, n$, you assume
$$
Y_i = \beta_0 + \beta_1 X_{i1} + \ldots + \beta_k X_{ik} + \epsilon_i,
$$
with the errors $\epsilon_i$ being normally distributed with mean 0 and variance $\sigma^2$, that's the same as assuming that conditional on $X_{i1}, \ldots, X_{ik}$, the response $Y_i$ is normally distributed with mean
$\beta_0 + \beta_1 X_{i1} + \ldots + \beta_k X_{ik}$
and variance $\sigma^2$.
This is because having conditioned on $X_{i1}, \ldots, X_{ik}$, we treat $\beta_0 + \beta_1 X_{i1} + \ldots + \beta_k X_{ik}$ as being constant.
The usual multiple linear regression model with normal errors is a generalised linear model with normal response and identity link.
Answer: Simple linear regression having Gaussian errors is a very nice attribute that does not generalize to generalized linear models.
In generalized linear models, the response follows some given distribution given the mean. Linear regression follows this pattern; if we have
$y_i = \beta_0 + \beta_1 x_i + \epsilon_i$
with $\epsilon_i \sim N(0, \sigma)$
then we also have
$y_i \sim N(\beta_0 + \beta_1 x_i, \sigma)$
Okay, so the response follows the given distribution for generalized linear models, but for linear regression we also have that the residuals follow a Gaussian distribution. Why is it emphasized that the residuals are normal when that's not the generalized rule? Well, because it's the much more useful rule. The nice thing about thinking about normality of the residuals is this is much easier to examine. If we subtract out the estimated means, all the residuals should have roughly the same variance and roughly the same mean (0) and will be roughly normally distributed (note: I say "roughly" because if we don't have perfect estimates of the regression parameters, which of course we do not, the variance of the estimates of $\epsilon_i$ will have different variances based on the ranges of $x$. But hopefully there's enough precision in the estimates that this is ignorable!).
On the other hand, looking at the unadjusted $y_i$'s, we can't really tell if they are normal if they all have different means. For example, consider the following model:
$y_i = 0 + 2 \times x_i + \epsilon_i$
with $\epsilon_i \sim N(0, 0.2)$ and $x_i \sim \text{Bernoulli}(p = 0.5)$
Then the $y_i$ will be highly bimodal, but does not violate the assumptions of linear regression! On the other hand, the residuals will follow a roughly normal distribution.
Here's some R code to illustrate.
x <- rbinom(1000, size = 1, prob = 0.5)
y <- 2 * x + rnorm(1000, sd = 0.2)
fit <- lm(y ~ x)
resids <- residuals(fit)
par(mfrow = c(1,2))
hist(y, main = 'Distribution of Responses')
hist(resids, main = 'Distribution of Residuals')

Comment: @hxd1011: yes, this is the difference between the marginal distribution (clearly not normal) and conditional distribution given x (we know it's normal since we simulated it!). Not thinking about the difference between conditional and marginal distributions is an extremely common mistake.
Comment: the example $y_i = 1 + 2 \times x_i + \epsilon_i$, really opened my mind. never think in this way where still use identity link, and residual assumption not violated !
Comment: "Simple linear regression having Gaussian errors is a very nice attribute that does not generalize to generalized linear models." What about a Gaussian GLM with the log link? Its errors will be normally distributed. The fact that the errors follow a Gaussian distribution for the simple linear regression is because the response does (conditioned on a given value of the predictor(s)).  Adding or subtracting a value from a normally distributed variable will not change its distribution (the variable is still going to be normal), so the errors will be normal.
Comment: @slava-kohut: my point is that this does not *generalize* to GLMs: it's a nice attribute that occurs as a result of Gaussian errors, but since GLMs relax that assumption (along with the linear link) you can't always use it.


Permutation in product of its transpositions

Question: Is there is any specific rule of writing any permutation into product of its transpositions? I know that permutation $$(123...n)= (1, n)(1, n-1)(1, n-2) \cdots(12)$$ but how can we reach to this result. Please give me some idea about.
Comment: @pjs36 I think the question was not so much to prove the result but to explain how we thought of it. Probably the answer is by trial and error.
Comment: On the right, just show that $i \mapsto i + 1$ for $i = 1, \ldots, n - 1$ (and deal with $n$ too). What's the first transposition that touches $i$? Where does it send $i$? Does that number get sent anywhere else by transpositions to the left of it, and so on?
Answer: Yes there is.Take any permutation.
every permutation can be written as product of disjoint cycles
Say one such cycle is ($a_1,a_2,...a_n$) then u can write this cycle as ($a_1,a_n$)($a_1,a_{n-1}$)....($a_1,a_2$)
Repeat for each cycle and you have product of transpositions.
P.S. This representation may not be unique.But surely this is one way to achieve.
Answer: An approach might be the following. (I am writing composition of functions right-to-left, as you do, although particularly with permutations I prefer it the other way around.)
$\alpha = (1 2 \dots n)$ maps $1$ to $2$, so we might start writing
$$
\alpha = \cdots (1 2),
$$
where the dots has yet to be filled with transpositions.
Now the left-hand side, as written so far, correctly maps $1$ to $2$, but maps $2$ to $1$, whereas $\alpha$ maps $2$ to $3$. So we fix this by adding $(1 3)$:
$$
\alpha = \cdots (1 3) (1 2),
$$
and now the left-hand side, as written so far, correctly maps $1$ to $2$, and $2$ to $3$, etc.
But then, as noted in another answer, this is by far not the only way of writing $\alpha$ as a product transpositions. One might for instance start with
$$
\alpha = \cdots (2 3),
$$
etc.


How to merge two arrays into a map using Java streams?

Question: Lets suppose we were given the following two arrays
String[] keys   = new String[] {"a", "b", "c", "aa", "d", "b"}
int[]    values = new int[]    { 1 ,  2 ,  3 ,  4  ,  5 ,  6 }

And by merging these 2 arrays into HashTable we get the following
// pseudo-code
Map<String, Integer> dictionary = new HashTable<>(
  ("a"  => 1)
  ("b"  => 8) // because "b" appeared in index 1 and 5
  ("c"  => 3)
  ("aa" => 4)
  ("d"  => 5)
);

How can we do this using java Lambda style?
So far I have the following:
// this loops through the range given (used for index start and end)
// and sums the values of duplicated keys
tree.listMap = IntStream.range(range[0], range[1]).boxed().collect(
  Collectors.toMap(i - > dictionary[i], i - > i + 1, Integer::sum, TreeMap::new)
);

However, I'd like to take 2 arrays, merge them by key and value, where value is the sum of all values for duplicated keys. How can we do this?
Answer: There you go:
Map<String,Integer> themap =
       IntStream.range (0, keys.length).boxed()
                .collect (Collectors.toMap(i->keys[i],
                                           i->values[i],
                                           Integer::sum,
                                           TreeMap::new));

Output:
{a=1, aa=4, b=8, c=3, d=5}

This is quite similar to the snippet you posted, though, for some reason, the snippet you posted contains no reference to the keys and values arrays.
Comment: @nullpointer `Map` makes no guarantees about iteration order so the output is for all intents and purposes the same.
Comment: @nullpointer My answer returns a `TreeMap` (as in the OPs code), so the keys are sorted. You can also modify the `groupingBy` solution to return a `TreeMap` (by default, the current implementation returns a `HashMap`).
Comment: There is a slight difference in the output of [this](https://stackoverflow.com/a/46948467/1746118) and [this](https://stackoverflow.com/a/46948406/1746118). Just curious to know, does the `groupingBy` sorts the data as well?
Comment: Thanks Eran for your answer. I was kind of stuck on how we merge 2 separate arrays. Hence why you don't see any reference of keys and values. I have only obtained a single array prior to your solution.
Answer: I don't like using streams when referring to indexes, but you can use groupingBy and summingInt to accomplish this:
Map<String, Integer> result = IntStream.range(0, keys.length)
   .boxed()
   .collect(
       Collectors.groupingBy(
           i -> keys[i],
           Collectors.summingInt(i -> values[i])
       )
   );

Note that this works on the assumption that keys and values are both of equal length, so you may want to do some additional validation.
Comment: @Jamie Nope, your question was perfectly clear. Happy to help.
Comment: I didnt give too much focus towards sorted map. The requirement was simply to merge two arrays with given values as sum for duplicated keys. Have I been too vague in my question? Let me know and I'll edit. Regardless Michael, I appreciate your answer. It was very warming to learn something new :)


Reducing noise between guitar amplifier and mixer

Question: I am trying to add electric guitar amplifier to my setup, and I am experiencing a lot of noise between the amplifier and a mixer.
My setup is wired as following:

Computer running Ableton
Zoom H4n running in audio interface mode connected through USB to the computer
1010 Music Bluebox audio mixer plugged into Zoom H4n
Fender Mustang LT50 Line out plugged into one of the bluebox inputs

I have other equipment (Moog Studio 3, Waldorf Blofeld and 1010 Music Blackbox sampler) plugged into the mixer and it makes no noticeable noise. I have the amplifier and mixer plugged to separate outlets, I tried replacing power cables to both devices and used few different cables between the amp and a mixer but the noise is there as soon as amplifier is powered up. If I plug the amplifier straight into the ZOOM H4n noise is down to usable levels.
From the research I made I think there are two likely causes: dirty power or the amplifiers unbalanced line out. I think that the unbalance line out is more likely of the two, I'd expect dirty power to affect other equipment too if it was the problem.
I hope to avoid buying equipment that I ultimately don't need, hence the question: is direct input box what I need to remedy the noise. Should it be active, or can I get away with a passive one? Are there any other solutions? I've been thinking about getting a proper audio interface too. Could I get away with plugging the amplifier straight to the interface?
Comment: It looks like the [LT50 Line Out](https://www.fender.com/en-AU/guitar-amplifiers/mustang-lt50/2311203000.html) is labelled 'TRS Balanced'.  However, the Bluebox doesn't seem to handle balanced inputs, so using a TRS cable is not the answer.  See [1010music forum](https://forum.1010music.com/forum/products/bluebox-compact-digital-mixer-recorder/support-bluebox/29894-unbalanced-inputs)
Answer: You have a balanced TRS output on the amp and a stereo unbalanced output on the mixer/recorder. If you want to test whether a DI would help, just use a TRS cable, record a stereo track, then subtract left and right tracks in postprocessing in order to get a mono signal.
If this difference track is reasonably good, a DI box (which does the "subtraction" in an analog manner) should work well.
Comment: DI box sometimes has ground lift, and if the source of the noise is a ground loop, this may help more than just the subtraction you describe.


How can I skip field validation if the field is hidden?

Question: I get a node form with node_form and then I render it with some modifications.
One of the modifications is that I duplicate the fields so I have the same fields twice. One field is disabled and the other same field is enabled, I also have a checkbox to show or hide the disabled/enabled field with #states. So I have only one field visible at time, for example, I have a disabled field visible, if I check the checkbox then disabled field is hidden and enabled field is shown.
The problem comes with the #requried = TRUE fields. When I submit the form it validates the two fields (enabled and disabled) but I only want to validate the visibile field. So, if it's visible the disabled field, I don't want to validate the enabled field.
What is a good way to achieve this?
Comment: @madhurjya Some people (me incuded) prefer to code their own solution
Comment: Could you please tell me why you not using field-conditional-state module?
Comment: yes clive i know but, in this question i look that it can be perform by the simplest way of field-conditional-state module, thats why i am putting this comment...:)
Comment: can you remove all #required=>TRUE elements and specify you own validation?
Comment: I had [similar problem](http://drupal.stackexchange.com/q/95320/16495) and the answer is - recreate your hiding logic in your validator.
Comment: @madhurjya like Clieve I prefer to code my own solution, but in this case is a client request
Comment: @xurshid29 yes I can, but I'm asking if there is a better solution.
Answer: I've tacked a variation on this before and this was the only solution I found that didn't have problems of some sort.
The key is not to skip all validation as you may add security holes so you have to specifically skip required validation. - Specifically what I'm getting at here is don't use #limit_validation_errors.
You cannot stop drupal core from validating that required fields are not empty, so you have to make the fields not required when they get validated.
Note that this example will make all fields not required, so you'll have to add some logic to only do that for the fields you are interested in.
I couldn't add this because I don't have enough info about your setup.
In your form add this:
  // Add an after build callback so we can modify the form before validation.
  $form['#after_build'][] = 'MYMODULE_form_after_build';

Then add that after build function and a helper function:
/**
 * Form after build callback.
 *
 * We are using this to modify the form after it has been submitted,
 * but before it has been validated.
 * This means we can remove required flags for certain fields.
 *
 * @param array $element
 *   An associative array containing the structure of a form element.
 *   In this case the form.
 * @param array $form_state
 *   The form state array.
 *
 * @return array
 *   An associative array containing the structure of a form element.
 */
function MYMODULE_form_after_build($element, &$form_state) {
  // Check that the form has been submitted.
  if ($form_state['process_input']) {
    // Deal with required fields.
    _MYMODULE_remove_required($element);
  }
  return $element;
}

/**
 * Make elements of a form not required.
 *
 * This example function will make all required fields not
 * required.
 * In your case you want to only do certain fields so you will have
 * to add logic in here to only affect some fields.
 * You could do this based on field name or some other flag you have
 * set, or whatever.
 *
 * @param array $elements
 *   An associative array containing the structure of a form.
 */
function _MYMODULE_remove_required(&$elements) {
  // Recurse through all children.
  foreach (element_children($elements) as $key) {
    if (isset($elements[$key]) && $elements[$key]) {
      _MYMODULE_remove_required($elements[$key]);
    }
  }
  if (!empty($elements['#required'])) {
    $elements['#required'] = FALSE;
  }
}

Comment: Ok, so with this approach I set `#required = FALSE` for enabled fields (hidden for default) and then I have to implement a `hook_validate` to validate if a enabled field is shown, right?
Comment: Instead of just setting required = FALSE for all fields as per my example, I would try to set it to FALSE only for fields that are hidden, then you don't need any validation function. At the time of the after build you should have access to the values of the form, so you can check the status of the fields you were using for your states to determine what's hidden and needs to have required = FALSE. You can always pass $form_state into _MYMODULE_remove_required if you need to.
Comment: But I show/hide fields with [`#states`](https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#states) (with JavaScript). `after_build function` is called before you click submit, right? So I think I have to set `#required = FALSE` for every field and then validate what fields I want, right?
Comment: After build function is called when the form is built, which happens both before and after submission. There is a check in the after build callback that makes sure you are dealing with the form after the submit button is pressed. #states work based on values of other fields, so in you after build you can check the values of those fields to work out what the state was and which fields would have been hidden. You don't need any custom validation code.
Comment: If course you could also make all fields not required and then do custom validation if you wanted. That would still work.
Comment: Finally, I understand what you want to say to me and it works :).
Comment: I am using after_build with client side validation 7.x-1.40,but if i check $form_state['process_input'] then id does not work.
Comment: What do you mean by "id does not work"?


Expectation with $-1$

Question: I am trying to study probability theory by myself. I asked myself a question about expectation, and I have no idea how to solve it. Please help me with solution and my understanding.
The question I asked is following:
Let $a, b, c, d$ be non-negative natural numbers, say from the set $\{0, 1, ..., n\}.$
Calculate the expectation
$$
E\left( (-1)^{a+b+c+d}\right).
$$
Thank you for your help.
Comment: You should say something about the probability distribution of your four random variables $a,b,c,d$.
Answer: $(-1)^{a+b+c+d} = (-1)^a (-1)^b (-1)^c (-1)^d$.  Assuming $a,b,c,d$ are independent (which you didn't say but is probably what is meant), the expected value of the product is the product of the expected values.  $(-1)^a$ is $-1$ if $a$ is odd and $1$ if $a$ is even. So if the values $0,1,\ldots,n$ are all equally likely (which again you didn't say but you probably meant), it all comes down to counting how many odd and even numbers there are in $0,1,\ldots,n$.
Comment: ...and that depends on whether $n$ is odd or even.  If $n$ is odd, then there are equally many odd and even numbers, so $E((-1)^a)$ would be $0$.  If $n$ is even, it's a bit more complicated.

Expectation with $-1$


Switch from minor melodies to major

Question: As a composer (and electronic music producer), I'm currently facing what I think is a big issue : each and every melody I compose is in minor mode, so it makes them gloomy. But now I would like to compose melodies that rhyme with summer and happiness.
So my question is : Is there a trick to switch my minor melodies to sunny major melodies ? (e.g. : adding a sharp note, or a halftone ?)
Answer: If your melodies are based on the notes of a minor scale, change them to fit a major one!    Two basic techniques would be:

Shift into the tonic major - if your tune used the notes in C minor scale, change it to use those of C major.  That means the Eb, Ab and (maybe) Bb will become E, A and B naturals.  Your basic chords will be C, Dm (or D major - that's a very common extension), F, G, Am...   (But you can use plenty more and still be 'in C major'.)

Shift into the relative major.  Keep your Eb, Ab and Bb but make Eb the 'home' note.  Your basic chords might br Eb, Ab, bb7, Cm...
Comment: Cold turkey could involve *only* using the three major chords for a while - avoid ii, iii and vi altogether, otherwise the OP could modulate back to vi...
Answer: l like Laurence's answer very much, but I'm going to ask a question and then offer some additional alternatives-- not instead of his but in addition to them.
You didn't say which of the three types of minor scales you were using:  natural, harmonic, or melodic.  I'm going to offer three strategies, and you should pick the one that matches the type of minor you tend toward:
Natural:  Try sharping ONLY the third note of the scale (counting from the bottom),  Leave the rest of the scale unchanged.  See how that affects the feel of the melody.  If it's comfortable, go with it through the whole tune and pick chords that match.  It won't quite be major but it might still sound 'happier' than what you've been doing, and it might eventually pull you into actual major.
Harmonic:  First, get rid of the augmented second, either by sharping the sixth note of the scale or flatting the seventh one.  See which of those feels more kin to your style.  If you pick sharping the sixth tone, then you have shifted into Melodic minor, so skip to that paragraph below.  If you pick flatting the seventh, you are now in Natural, so skip to that paragraph above.
Melodic:  Try using the same scale going up as you are using going down (Melodic Minor scales are different whether the tune is ascending or descending.)  See how that feels. if you like it, start sharping the third tone of the scale.  Voila!  You're now in the enharmonic major and have solved your problem.  If you don't care for the effect, no harm done and you can try one of Laurence's suggestions.
Hope that helps.
Comment: It's also possible he's got stuck into a minor-ish mode, maybe Dorian.  A good way to get un-stuck from your safe, stock chords and licks is to NOT play an instrument while composing.  Particularly if it's guitar!  Compose on paper.If you're not fluent with notation, get fluent!  Don't think 'melody and chords', try writing two melodies that fit together.  Get out of your comfort zone!
Comment: Melodic minor jazzwise tends to be the ascending notes only. But with jazz - anything goes!
Comment: Thanks @L3B , your answer is a good completion for Laurence's one and I'll try all these tricks (but I actually don't know if my melodies are in Natural, Harmonic or Melodic minor scales, and I think they're all different)
Comment: @paulolo, it sounds like you might benefit from some ear training to the point where it's easier for you to know what your natural tendencies are.  Self knowledge is the key to a lot of areas in music.

Switch from minor melodies to major


Using input variable in two controllers

Question: I'm having a problem using one "input variable" but in to different controllers (and models), I'm using code igniter.
I have a form in view1, once submit we call controller1, the controller1 verifies if $this->input->post(name) exists or not:
if exist {echo exist }
else {
// redirect to another controller2 when you should click "add" to add
// "$this->input->post(name)" to a table
}

now I don't know how to use the same variable $this->input->post(name) in the second model2.
I'd be thankful if you help me.
Comment: While redirecting send value through URL and get it in controller2
Comment: or you can save in session and can use anywhere.
Answer: You can do something like this in controller 1:
redirect('/Controller2/function2/value');

In your controller 2 something like this:
public function function2($value){
    // send value to the model
}

Also you can do it with sessions but the choice is yours
Answer: you can save it into a variable and pass it
for example
    //get the variable and save it
    $myVariable = $this->input->post('name');
    //load the model
    $this->load->model('model2');
    //now send the variable to the model
    $this->model2->doSomethingElse($myVariable);

Using input variable in two controllers


Por que usar um retorno genérico?

Question: Estava olhando a assinatura dos métodos da classe Optional e não entendi o que significa esse <T> na frente do retorno do método empty():
public static <T> Optional<T> empty()

Ele retorna um Optional<T>, certo!?
Mas por que usar um <T> na frente do retorno do método?
Comment: Relacionado: [Diferenças entre  e ](http://pt.stackoverflow.com/q/68554/3117)
Answer: Entendendo a sintaxe
Considerando a parte importante:
<T> Optional<T> empty()

T é uma variável de tipo. Isso funciona mais ou menos como uma variável em um template, onde você pode substituir T por um tipo qualquer, lembrando que tipo em Java é sinônimo de classe (não confundir com *tipos primitivos).
O primeiro <T> diz: este método vai usar um tipo genérico T em algum lugar. É como uma dica para o compilador (e para o programador desatento).
O tipo de retorno do método Optional<T> então diz que o tipo genérico de Optional deve ser do mesmo tipo genérico do método.
Confuso, né? Quando o Java vai saber o tipo T? Isso ocorre no momento em que você vai usar o método. Como o @Maniero já disse, quando você chama o método atribuindo o resultado a um certo tipo, o Java consegue inferir o tipo usado naquela chamada.
Por exemplo, se você está atribuindo o retorno do método a uma variável do tipo Optional<String>, então T = String e você pode ler o método como:
Optional<String> empty()

De fato, as IDEs mais avançadas como Eclipse e IntelliJ irão mostrar a assinatura com a substituição adequada de T durante o autocompletar sempre que for possível inferir tipo pelo contexto atual.
É bom lembrar que a inferência de tipos genéricos é uma garantia em tempo de compilação de que não haverá incompatibilidade entre tipos durante atribuições e acessos. Portanto, isso nada influencia durante a execução do programa.
Outro exemplo
Esta não é a única maneira do compilador subentender o tipo genérico. Um exemplo clássico é um método que retorna um mesmo tipo passado por parâmetro:
static <T> T instanciar(Class<T> classe) throws IllegalAccessException, InstantiationException {
    return classe.newInstance();
}

Da mesma forma que no primeiro exemplo, <T> diz que o método é genérico, o retorno será do tipo T e o método recebe uma classe do tipo Class<T>. Exemplo de uso:
Cliente c = instanciar(Cliente.class);
Produto p = instanciar(Produto.class);

Como o Java infere o tipo T aqui? O compilador olha o tipo de classe passado no parâmetro e assim garante que o valor retornado seja do mesmo tipo.
Diferente do caso da pergunta, onde o tipo é inferido pela variável que recebe o retorno do método, aqui o tipo é inferido por um dos parâmetros informados.
Por exemplo, Cliente.class é um atributo que retorna um objeto do tipo Class<Cliente>, portanto o retorno da primeira chamada será to tipo Cliente, onde T = Cliente.
Porque <T> é necessário antes do tipo do método
Há classes/interfaces genéricas e métodos genéricos. Se a classe/interface for genérico, os métodos dela podem usar o tipo genérico.
Exemplo:
interface Generico<T> {
    T empty();
}

Ou:
class Generico<T> {
    T empty() { ... }
}

Entretanto, se apenas o método é genérico, a declaração precisa vir antes do método. Isso vale para métodos estáticos e de instância.
Note que você pode misturar classes e métodos genéricos e usar diferentes nomes para as variáveis de tipos:
class Generico<T> {
    T empty() { ... }
    static <X> Optional<X> empty() { ... }
    <Y> Optional<Y> of(Y instance) { ... }
}

Entretanto, considere que existe uma convenção para nomes de variáveis de tipos.
Creio que a decisão de exigir a declaração do tipo genérico foi tomada por questões de legibilidade do código, além de evitar sintaxes obscuras para não confundir um tipo genérico T com um class T {}.
O tipo genérico é estritamente necessário?
Não. Os genéricos em Java são apenas uma questão de segurança para o programador.
Você bem pode fazer isso:
public static Optional empty() {
    return Optional.empty();
}

E voltamos à era do Java 1.4, onde não havia genéricos, mas em compensação casts e erros de ClassCastException apareciam em todo lugar.
Comment: "Entretanto, se apenas o método é genérico, a declaração precisa vir antes do método, como no exemplo.", apenas métodos estáticos ou instâncias de classes também?
Comment: @Patrick Se a variável genérica não pertence à classe ela deve ser declarada em todos os casos.
Answer: Este é um placeholder para o tipo que será usado. É como se fosse uma super variável. O "valor" dela é o tipo que foi escolhido do uso do método ou classe. Até aí provavelmente você sabe.
A questão é que um método estático não tem como saber que tipo foi selecionado para a classe. Afinal o método pertence à classe e não à instância e a classe não é instanciada. Então o método precisa ser chamado indicando qual é o tipo que deve ser usado nele. Este primeiro <T> é a sintaxe usada para receber este tipo.
Portanto você pode usar:
Optional<Integer> x = Optional.empty();

neste caso ele vai chamar o equivalente a:
public static <Integer> Optional<Integer> empty() ...

Alternativa de chamada dentro de uma expressão:
Optional.<Integer>empty();

Coloquei no GitHub para referência futura.
Se o método tivesse um parâmetro igual ao retorno ele poderia inferir por ele mas neste caso o único jeito é ser explícito.
Se me perguntar se dava para ter uma sintaxe sem isto eu acho que sim mas os criadores da linguagem quiseram diferenciar explicitamente o caso, ou sabem de algum problema que eu não sei.
Lembre-se sempre que os métodos da classe são completamente distintos dos métodos da instância e portanto o tipo de uma pode ser diferente do tipo da outra
Comment: Ainda que esse fosse um método de instância, uma construção dessa poderia ser útil caso ele operasse em outros tipos arbitrários que não um dos tipos genéricos da classe. A propósito, muito interessante essa forma de usar, não conhecia, +1.
Comment: Eu não entendi o  `` antes. Ele poderia ser omitido? O retorno é um `Optional`, se a assinatura fosse `public static Optional empty()` seria a mesma coisa?
Comment: Não seria. O Java não aceita esta sintaxe.

Por que usar um retorno genérico?


Como fazer exibição dinâmica em HTML+PHP?

Question: Estou estudando HTML e PHP, mas tem coisas que não estou conseguindo descobrir como faz. Afinal como obtenho dados de entrada para processá-los? Como no teclado com aqueles campos de texto <input type="text">. E, depois disso, como adapto a interface da página ou a atualizo com a nova interface em função dos dados coletados?
Para facilitar, coloquei um exemplo onde se fornece um tamanho de matriz quadrada e de acordo com o valor fornecido a interface da página disponibiliza células para serem preenchidas. O gif abaixo ilustra de forma bem simples essa ideia, mostrando as mudanças da página a cada modificação da string no campo "ordem".

Já agradeço antecipadamente a quem me esclarecer.
Comment: Esse tipo de modificação é feito por JavaScript, não PHP. O que sabe de JavaScript?
Comment: para passar as variáveis pro PHP é usado geralmente `$_POST['exemplo']` ou `$_GET['exemplo']`, que pega o valor do ``, quanto à matriz, apesar de ser MUITO mais fácil com JS, também é possível via PHP, através de `forech` e uma ``
Comment: Obrigado. Descobri aqui como se faz mais ou menos.
Comment: somente php dinamicamente sem att página nao é possível... apenas usando ajax ou javascript, pois nao atualiza a página
Answer: Descobri como faz, sem a necessidade de ajax, javascript, table e outros. Vou explicar com o exemplo. Fiz a interface dinâmica de matriz quadrada toda no arquivo "index.php".
Primeiramente, coloco o campo que deve atualizar a interface. Usando <form action="index.php" method="post">, a entrada pelo campo <input name="numeroDeEquações" type="text" /> vai reabrir a página "index.php" com a variável $_POST['numeroDeEquações'] atualizada com o valor que foi passada no campo.
O segundo e último passo é determinar a interface de acordo com o valor do campo. Para isso, primeiramente verifico se $_POST['numeroDeEquações'] foi definido. Depois verifico se o valor é válido. De acordo com as condições, se constrói a interface.
Simples assim. Segue o código e agradeço a todos que tentaram ajudar.

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Matriz Quadrada</title>

        <form action="index.php" method="post">
            Ordem: &nbsp&nbsp <input name="numeroDeEquações" type="text" />

        </form>

        <?php
            $inválido = true ;
            if( isset($_POST['numeroDeEquações']) ){
                $numeroDeEquações = $_POST['numeroDeEquações'] ;
                if( $numeroDeEquações>1 && $numeroDeEquações<10 ){
                    $inválido = false ;
                    for( $índice1=0 ; $índice1<$numeroDeEquações ; $índice1++ ){
                        for( $índice2=0 ; $índice2<$numeroDeEquações ; $índice2++ ){
                            echo( "<input size=1 type='text' />" ) ;
                        }
                        echo( "
" ) ;
                    }
                }
            }
            if( $inválido ) echo( "
Forneça um número de 2 a 9." ) ;
        ?>

Comment: Esse código funciona, mesmo com acentos nos nomes das variáveis?
Comment: Sim, se escolher arquivo de texto com caracteres utf-8 sem bom...