Store session in operation hook - Loopback

Question: I want to store some data other than userId or accessToken to store in a session, in after save or before save operation hook in Loopback application using express-session.
I have this in my server/server.js :
....
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
....

app.use(session({
    name:'session-name',
    secret: 'keyboard cat',
    store: new MongoStore({url: 'mongodb://localhost/test', ttl:1}),
    resave: false,
    saveUninitialized: true
}));

And as I'm defining the remote-method with some parameters it actually passing the parameter and not the req object, so I can't do it the express way.
How can I use the session to store and get value?
EDIT :
I have found a way to set the session in remote method, by adding this to my model.json's remote-method :
"accepts": [
    {
        "arg": "req",
        "type": "object",
        "http": {
            "source": "req"
        }
    }
]

And, adding the req parameter to the remote-method function,
Model.remoteMethod = function (req, callback) {
    req.session.data = { 'foo': 'bar' }
    callback(null)
};

Now, the issue is I want to get this session value in operation hook
Model.observe('before save', function (ctx, next) {
    //How to get the session here?
})

Comment: what you have getting error and response. please explain
Comment: I don't know how to store data in session (other than access token or user id)
Comment: It's a bit of a hack, but I would attach the whole context object (https://loopback.io/doc/en/lb3/Remote-methods.html#http-mapping-of-input-arguments) to the instance in question with the remote hook and remove it in the `before save` hook afterwards. The problem is that the model hooks aren't necessarily associated with individual requests. This is something that they either have or are trying to solve in LoopBack 4.
Answer: try this now :
you can set ctx value :
var LoopBackContext = require('loopback-context');

    MyModel.myMethod = function(cb) {
      var ctx = LoopBackContext.getCurrentContext();
      // Get the current access token
      var accessToken = ctx && ctx.get('accessToken');
      ctx.set('xx', { x: 'xxxx' } );

    }

it's get ctx value :
 module.exports = function(MyModel) {
      MyModel.observe('access', function(ctx, next) {
        const token = ctx.options && ctx.options.accessToken;
        const userId = token && token.userId;
        const modelName = ctx.Model.modelName;
        const scope = ctx.where ? JSON.stringify(ctx.where) : '<all records>';
        console.log('%s: %s accessed %s:%s', new Date(), user, modelName, scope);
        next();
      });
    };

loopback context store userId and accesTokan. in whole web you can access using ctx  it's work like session in loopback.
Comment: hey, I tried this, but getting the stored object in ctx object undefined.
Comment: can you install loopback-context model..?
Comment: Yes, I installed it along with cls-hooked
Comment: can you add server/middleware.json    this code

{
  "initial": {
    "loopback-context#per-request": {
      "params": {
        "enableHttpContext": true
      }
    }
  }
}
Comment: what's your loopback version..?
Comment: I am using  loopback version 3
Comment: I don't need accessToken or userId, I just want what I stored in ctx.
Comment: hey @imranali, Updated the question if you can help with this one.
Comment: I think that using loopback-context is dangerous... It's been a while since I triaged LB3 issues but I know that there were a lot of race conditions (sorry I can't give a better answer, but I don't want anyone to shoot themselves in the foot).


How does X% Chance of Finding gold work for a party?

Question:
Possible Duplicate:
How does X% Chance of Finding Magical Items work for a party?

I was reading this question. Works the same way for gold or is it different? Could someone provide a explanation for this?
Comment: The accepted answer specifically says it applies to gold find as well.
Comment: Looks like it does o.O" I read that and didn't saw it. I was going to delete the question, but it's good milestone ...
Comment: @MichelAyres don't delete it, still good for SEO
Comment: @NickT I'll not =) I was going to but them I though that like I was lost with this, someone may have this kind of problem too. as I said, it's a good milestone =)
Answer: Perhaps it could be more prominent in the accepted answer on your linked question, but as bwarner points out: "magic find in a party is averaged between party members...The same thing applies to gold find bonuses and bonuses to XP."


RPi - Python Curses program running at boot does not have keyboard focus

Question: I am trying to write a program that will run when my raspberry pi starts up and will allow me to immediately begin typing things with my keyboard and have it be picked up by the program. I don't want to have to manually start the program when the pi starts. I need to use curses (or a similar unbuffered keyboard input library) because I display what I am typing on a 2x16 I2C LCD, but I also need everything that I am typing to be recorded to a text file.
Right now, I am auto-starting the program at boot by putting a line in rc.local. This works, and the I2C display is correctly showing program output, but it does not respond to keyboard input, and the keyboard input is instead displayed (when I connect the pie to a screen, the goal is to run headless) on an odd console layout that exits when I press enter and says -bash: 'whatever I just typed' command not found.
I have already tried:

Setting a timer at the beginning of the program to wait until the pi has fully booted before initializing the curses window and keyboard capture
Creating a seperate python program to wait until the pi has fully booted and then running the main script by importing it

Neither of these methods works though, I get the same problem with slight differences.
To be clear, the program works flawlessly if I run it manually from the command line. But there is no keyboard input to the program (or at least not where it is supposed to be inputted) when I autostart the script with rc.local.
My code:
 #!/usr/bin/python
import I2C_LCD_driver, datetime, sys
from time import *
from subprocess import call

mylcd = I2C_LCD_driver.lcd()

for x in range(30): #waits for raspberry pi to boot up
    mylcd.lcd_display_string("Booting Up: "+str(x), 1)
    sleep(1)

import curses
key = curses.initscr()
curses.cbreak()
curses.noecho()
key.keypad(1)
key.nodelay(1)

escape=0
while escape==0:
    #variable initialization

    while 1:
        k=key.getch()
        if k>-1: #runs when you hit any key. getch() returns -1 until a key is pressed
            if k==27: #exits the program when you hit Esc
                break
            elif k==269:
                # a couple other special Function key cases are here
            else:
                inpt=chr(k)
                mylcd.lcd_display_string(inpt,2,step) #writes the last character to the display
                #some more code that handles writing the text to the LCD, which works flawlessly when run manually.

    file.write("%s\r\n" % entry)
    file.close()
    mylcd.lcd_display_string("Saved           ",2)
    mylcd.lcd_display_string("F1 New F2 PwrOff",1)
    while 1:
        k=key.getch()
        if k>-1:
            if k==265: #do it again! with F1
                mylcd.lcd_clear()
                break
            elif k==266: #shut down with F2
                escape=1
                break
curses.nocbreak()
key.keypad(0)
curses.echo()
curses.endwin()
call("sudo shutdown -h now", shell=True)

The line that I have in /etc/rc.local is as follows if that is important:
sudo python3 journal.py &

and it is followed by the 'exit 0' line.
Thanks for any help you can provide. I know this is a very specific problem and will be tedious to reproduce, but if anyone knows anything about autostarting functions I would be very appreciative of any tips.
Answer: Ok, literally all I had to do (which I did find after some more research on stackexchange, this is the thread that contained the answer I was looking for) was run my program from ~/.bashrc instead of /etc/rc.local. This method works perfectly, exactly what I wanted.
Answer: This should be because of how you called the program:
python3 journal.py &

You may want to check out JOB CONTROL of bash (or your shell) man page:

Only foreground
         processes are allowed to read from ... the terminal.  Background processes which
         attempt to read from ... the
         terminal are sent a SIGTTIN ... signal by the kernel's terminal
         driver, which, unless caught, suspends the process.

In short, once curses (or anything for that matter) try to read from stdin your process is likely stopped (after it may have already written to your display). Keep it in the foreground to be able to have it use stdin (and by extension keyboard).
Side note: Not sure about distro and details of implementation of rc.local in your case, but aren't init scripts normally run with uid/gid 0 already (without wrapping individual calls through sudo?)
Comment: I'll work on researching Job Control and trying to find a workaround. Do you have any tips on how to keep my python program in the foreground without actually typing out and running the script manually? On the topic of your side note, I don't know if I need to put sudo in the init command, I just did it becuase I thought it might need that to work, although I don't know enough about linux to know if I need it or not. It is likely that I don't.
Comment: The quickest way that comes to mind: Drop `&` if it is OK for you to have just stay in `rc.local` local until your script finishes. You actually really woldn't want background processes (not in the foreground of current console) to keep getting input from your keyboard, that open a host of (also security) problems.
Comment: I have tried dropping &, but when I do that my pi never boots fully on the main display output (I have to SSH into it and change the code of rc.local to get the pi to boot fully again). It gets stuck just after the 'Starting Hostname Service' line.
Comment: "Never fully boot" I suppose means the `getty` (or similar) does not start? Do you expect the system to start `getty` / present login prompt and the keyboard to be available to both your app and login prompt? Or run your application instead of the login prompt? Unfortunately all that is somewhat distro specific. I could see updating `rc.local` (or even `rc.S` or `rc.M`) being an option (on my system). Otherwise `/etc/inittab` could also be of interest. systemd based system would be configured differently again (and is not familiar to me).
Comment: Thanks for your help, I'll look into these things.


Return Largest Numbers in Arrays in javascript

Question: Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.
I am getting output [27,27,39,1001] but the output should be [27,5,39,1001].
function largestOfFour(arr) {
  // You can do this!
  var largest=[];
  var gr=0;
  for(var i=0;i<arr.length;i++){
    for(var j=0;j<=arr[i].length;j++){
      if(arr[i][j]>gr){
        gr=arr[i][j];

      }
    }
    largest.push(gr);
   }
 return largest;

}

largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

Comment: What is the question?
Comment: Divide the problem into smaller problems and solve each problem on its own: 1) find the max value of a single array (put this logic in a function) 2) iterate over elements of array and find max of each (call function from step 1) 3) build a new array from the results of step 2 4) return the resulting array from step 3 5) profit
Answer: Your logic is quite not right. To point out the error, see below.
Iteration 1
       ->gr = 0
       ->27 > 0?
       ->gr = 27
       ->push gr(27)
Iteration 2
       ->gr = 27
       -> 5 > 27?
       ->push gr(27)
Iteration 3
     ->gr = 27
     ->39 > 27?
     ->gr = 39
     -push gr(39)
Iteration 4
      ->gr = 1001
      ->1001 > 39?
      ->gr = 1001
      ->push gr(1001)

Try Creating a function with an array parameter that gets the largest number in that parameter instead of declaring a new for loop.
Array.max = function( array ){
    return Math.max.apply( Math, array );
};

Comment: *gr* should be initialised to [*Number.MIN_VALUE*](http://www.ecma-international.org/ecma-262/6.0/#sec-number.min_value) or maybe *NaN* as the arrays might contain negative numbers.
Answer: You can try something like this:

var data = [[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]];
var maxArr = data.map(function(item){
  return Math.max.apply(null,item)
});

document.write(maxArr);

Explanation of your code:

function largestOfFour(arr) {
  // You can do this!
  var largest=[];
  var gr=0;
  for(var i=0;i<arr.length;i++){
    for(var j=0;j<=arr[i].length;j++){
      if(arr[i][j]>gr){
        gr=arr[i][j];
      }
    }
    largest.push(gr);
   }
 return largest;

}

var r = largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
document.write(r)

You code works file, but the issue is with var gr=0;. This is initialized outside the for loop, so its comparing largest number of first array with second and since 27>5 is false, it is assigning 27 only.

function largestOfFour(arr) {
  // You can do this!
  var largest = [];

  for (var i = 0; i < arr.length; i++) {
    var gr = 0;
    for (var j = 0; j <= arr[i].length; j++) {
      if (arr[i][j] > gr) {
        gr = arr[i][j];
      }
    }
    largest.push(gr);
  }
  return largest;

}

var r = largestOfFour([
  [13, 27, 18, 26],
  [4, 5, 1, 3],
  [32, 35, 37, 39],
  [1000, 1001, 857, 1]
]);
document.write(r)

You need to reset this value of gr for every iteration, hence, it should be initialized inside loop.
Comment: Simply posting code doesn't really help. The OP has issues with their logic, so you need to explain why they're having their issue and how to fix it.
Comment: @RobG Thanks for pointing it. Have explained the issue and another resolution.
Answer: Your function is right but you need put var gr=0; inside first for loop:
 function largestOfFour(arr) {
  // You can do this!
  var largest=[];
   for(var i=0;i<arr.length;i++){
    var gr=0;
    for(var j=0;j<=arr[i].length;j++){
      if(arr[i][j]>gr){
        gr=arr[i][j];

      }
    }
    largest.push(gr);
   }
 return largest;
}

largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

Answer: function largestOfFour(arr) {
  var results = [];
  for (var n in arr) {
      var largestNumber = 0;
      for (var num in arr[n]) {
          if (arr[n][num] > largestNumber) {
              largestNumber = arr[n][num];
         }
     }
    results[n] = largestNumber;
    }
  return results;
    }

largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]);

Answer: Even-though, it looks like a test question and not having a clear question. I am going to go ahead and help you out.
var arr = [[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]];
var res = [];
arr.forEach(function(val, ix){
var sub = val;
var large = 0;
for(var i=0;i large){
  large = sub[i];
 }
}
 res.push(large);
});

Fiddle: https://jsfiddle.net/jeremyrajan/hted9eg5/
if you look at the code, I am using forEach(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) to loop through array and collect the subarray. And then running a for-loop through the elements to find the max number.
The only difference being that, I used forEach in my case to make things a bit prettier.
Hope that helps!
Comment: Using forEach doesn't make it look any prettier, but uglier.
Comment: What happens when a sub array contains all negative numbers, Jeremy? Also, using [`.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) is far more elegant. `let largest = (...arrays) => arrays.map(array => Math.max.apply(Math, array));`
Answer: Here is a cleaner way to do it, but it's relatively slow if you care about fast.
function get_array_of_largest(rank2Array){
  var newArray = [];
  for (var i = 0; i < rank2Array.length; i ++){
    newArray.push(rank2Array[i].slice().sort(function(a, b){return a < b;})[0]);
  }
  return newArray;
}

.slice() copies a portion of an array. Since no arguments were given, it copies the whole thing.
.sort() sorts an array according to a function. Given the function I've sorted using, it sorts the array in descending order (element 0 is thus the greatest).
The reason yours is not working is that you're not resetting gr to 0 after you push the element.
Comment: Not my down vote (it's really annoying to get down votes without an explanation), but sorting modifies the original arrays and is inefficient here.
Answer: function largestOfFour(arr) {
  var newArr=[];
  for(i=0;i<arr.length;i++){
     var num=Math.max.apply(null,arr[i]);
     newArr.push(num);
  }
  return newArr;
}

The following function uses Function.prototype.apply() to find the maximum element in a numeric array. getMaxOfArray([1, 2, 3]) is equivalent to Math.max(1, 2, 3), but you can use getMaxOfArray() on programmatically constructed arrays of any size.
function getMaxOfArray(numArray) {
  return Math.max.apply(null, numArray);
}

Answer: function largestOfFour(arr) {
    return arr.map(x => x.sort((a, b) => b - a)[0]);
}

Answer: Here is an answer that junior level like me might find easier to understand.
function largestOfFour(arr) {

// We need a way new array that would store the largest number as required.

  let newArr = []

  // We need a way to traverse through the subArrays
  for (let i=0;i<arr.length; i++)
  {
    // We need to find max in each sub array and add to newArr
    newArr.push(Math.max(...arr[i]))
  }
  console.log(newArr) // Check if its the answer we expect
  return newArr;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

Answer: This of your input purely as a matrix.
Now, you can spread the rows of the matrix into a function that takes varargs. These functions capture the arguments into an array and send them into a reducer.

const
  avg = (...arr) => arr.reduce((a, b) => a + b) / arr.length,
  avgPerRow = (...matrix) => matrix.map(row => avg(...row)),
  minPerRow = (...matrix) => matrix.map(row => Math.min(...row)),
  maxPerRow = (...matrix) => matrix.map(row => Math.max(...row));

let matrix = [
    [13, 27, 18, 26],
    [4, 5, 1, 3],
    [32, 35, 37, 39],
    [1000, 1001, 857, 1]
  ],
  averageOfFour = avgPerRow(...matrix),
  smallestOfFour = minPerRow(...matrix),
  largestOfFour = maxPerRow(...matrix);

console.log(...smallestOfFour); // [ 13 , 1    , 32    ,    1    ]
console.log(...averageOfFour);  // [ 21 , 3.25 , 35.75 ,  714.75 ]
console.log(...largestOfFour);  // [ 27 , 5    , 39    , 1001    ]
Answer: In this case, map and reduce together as a solution can be used.

The array is mapped

Found the largest numbers in the mapped array lists with reduce function
 function lgArry (arr) {
    return arr.map(function(sub){
        return sub.reduce(function(a,b){
            return a > b ? a : b;

        })
    })
}


the number $x$ was drawn x from with uniform distribution of the integers {1,2,...,n} (n is unknown), what is n most likely to be?

Question: the number $x$ was drawn from with uniform distribution of the integers ${1,2,...,n}$  ($n$ is unknown), what is n most likely to be?
intuition tells me its $x$, if that's true the probability of it being chosen would be $\frac1n = \frac1x$, any other possible value would be higher then $x$ would result in a smaller probability that $x$ was be chosen.
is that a valid argument?
Comment: The question is not well-posed.  It doesn't make sense to say "what is the most likely value of $n$? (given some observation)" unless you have prior knowledge or assumptions about the distribution of $n$.  Note especially that there is no uniform distribution on $\mathbb N$ so you can't just say "they're all equally likely" which is what your argument presumes.
Comment: Your intuition is correct. The maximum likelihood estimate of $n$ is $x$: http://en.wikipedia.org/wiki/Maximum_likelihood#Discrete_uniform_distribution
Comment: Let me put it this way, since as the above comments are pointing out, it's not so cut and dried.  If you want to calculate the maximum likelihood estimator amongst the distributions you can select from, then yes that is a valid argument to calculate it.
Comment: i know that there is no uniform distributions on the natural numbers, but if i you drew the number 5, or 8293, without knowing the maximum number that can be drawn, isn't there anything constructive we can deduce from what we know about n? (except the it must be at least x...)
Comment: I think to nail down your question you need to define a notion of what statistic your estimator should optimize.  e.g. If $\hat{N}$ is your choice of $n$ given the one outcome, perhaps you would like to minimize the variance of $\hat{N} - N$ where $N$ is the true length of the distribution.
Answer: This is called the German Tank Problem. In the case when the sample size is $1$ and the datum is $n$, the best estimate is $2n-1.$
Answer: It seems to me in order to put this question on the most solid ground you need a prior distribution on $n$ to make this work, and ideally a proper prior distribution (i.e. a real-valued distribution over the integers whose sum is 1). Just doing maximum likelihood to determine $n$ is equivalent to using an improper prior, specifically uniform over the set of positive integers (so the probability of each integer is identical and basically zero but somehow the probabilities all add up to 1, which is impossible but we pretend it's true). A proper prior distribution is much more satisfying than this. For example, with a proper prior you can come up with a confidence interval for $n$, but this is impossible with the improper "uniform" prior I described. If your prior distribution probability values are decreasing in $n$, then you will still get the result that the most likely value of $n$ is the value that you sampled. The difference is that now the result will be much more well-founded.


Understanding the encryption type


Why is my Angular template throwing this Typescript error?

Question: I'm building an Angular 4 project in Typescript 2.3.4. I can't figure out what's wrong with the code below.
IDialog interface
export interface IDialog{
    cancellable?: boolean,

    inputs?: Array<{label: string, value?: any, description?: string}|string>
    message: string
    title?: string,
    type?: DialogInputTypes // <- an Enum
}

SampleComponent.ts
  public dialog:IDialog = {
    cancellable:false,
    title:'Dialog Title',
    message:'This is a modal dialog',
    type:DialogInputTypes.button,
    inputs:[
      {label:'OK', value:'OK'},
      {label:'Cancel', value:'Cancel'}
    ]
  };

SampleComponent.html
<input *ngFor="let input of dialog.inputs" [value]="input.value">
                                                    ^^^^^^^^^^^^

This error is thrown by the compiler:

Angular: Identifier 'value' is not defined. <anonymous> does not contain such a member

I just upgraded from Angular 2 with Typescript 2.0 and this error was not present before.
Why is this error thrown? Perhaps it has to do with the fact that IDialog.inputs is defined as either an array or a string, and at compile time there is no way for the compiler to know which shape inputs has. If I remove |string from the interface, the error goes away.
More importantly, I don't know how to fix my code.
Comment: I wonder if `[value]="input.value"` should be `[value]="input?value"` since that is how it is declared in the interface.
Comment: Thanks. Using `input?.value` makes no difference. I think the error has to do with the fact that `IDialog.inputs` is defined as either an array or a string, and at compile time there is no way for the compiler to know which shape `inputs` has. I'm just speculating though
Comment: I agree with @BeetleJuice, I suspect it has to do with the "|string" as part of the IDialog interface. You'll need to cast it to the right type.
Comment: I don't think that's the problem. It's easy to test though, just remove that `|string` and see if the error is still there.
Comment: @HarryNinh If I remove `|string` the error goes away, but that's not a solution because sometimes that member is a string. So making this change will throw errors elsewhere.
Comment: If that is the case, you would want to change your template anyway, what if the inputs contains a string and everything will screw up.
Comment: @HarryNinh my mistake. It's never a string. Sometimes it's an array of strings, as the OP interface shows. However in the context of this component, I know it will always be an `Array<{label:string, value:string}` because this is hard-coded (see the `SampleComponent`  code section in the OP)
Comment: Please reproduce it
Answer: Its definitely your project configuration
Your code works perfectly fine if its like this

@Component({
   template: `
       <input *ngFor="let input of dialog.inputs" [value]="input.value">
   `
})
export class WhateverComponent{
    public dialog:IDialog = {
        inputs:[
            {label:'OK', value:'OK'},
            {label:'Cancel', value:'Cancel'}
        ]
    };
}
export interface IDialog{
    inputs: Array<iSomeControl | string >;
}
export interface iSomeControl{
    label: string;
    value: string;

}

I am using Angular 4.0.2 Typescript 2.2.2
I modified in order to be more specific
Comment: Changing the interface is not the solution I want. The interface as it's written in the OP shows the correct shape of `IDialog.inputs`. Sometimes it's an array, sometimes it's a string. If I just change it to `Array`, errors will be thrown elsewhere where `inputs` is used as a string
Comment: I am not an expert but the label , value , description are an anonymous Array or are they a specific type ? My guess is if they are anonymous the compiler doesnt know how to pick between an anonymous Array or a string
Comment: This is happening for me with simple strings: `{value:string, message: string, description:string}[]`
Answer: Disable angular extension pack and angular language service plugins from VS code.
I had a similar problem and this solved it.
Comment: I would not want to do that because I find the angular language service very valuable: it allows autocomplete and type checking of component properties while I write my template. It was just this specific situation that I found annoying. I think I downgraded from `typescript 2.3.4` to `typescript 2.3.3` to address this, but I don't remember clearly.


Trouble with simple notation in proving linearity of an operator.

Question: Consider the operator $T\colon \mathcal C[0,1]\to \mathcal C[0,1]$ defined by
$$ Tf(x) = \int_0^x f(t) \, dt, \quad \forall f \in \mathcal C[0,1].$$
To prove its linearity, consider two scalars $\alpha,\beta \in \mathbb K$ and two functions $f,g \in \mathcal C[0,1]$, as arbitrary as possible. Then,
\begin{equation*}
    T(\alpha f+\beta g)\color{red}{(x)} = \int_0^x (\alpha f + \beta g)(t)\, dt = \int_0^x \alpha f(t) + \beta g(t) \, dt = \alpha \int_0^x f(t) \, dt + \beta \int_0^x g(t) \, dt = \alpha Tf\color{red}{(x)} + \beta Tg\color{red}{(x)}.
\end{equation*}
My question. Does my notation in $\color{red}{red}$ makes sense? Somehow, in my head it would make more sense if I just wrote $T(\alpha f + \beta g)$ but, at the same time, according to the definition it doesn't make that much sense. I get even more confused when it comes to the final conclusion: We just proved that
$$ T(\alpha f + \beta g) = \alpha Tf + \beta Tg, \quad \forall \alpha,\beta \in \mathbb K, \, \forall f,g \in \mathcal C[0,1].$$
Here, I didn't use the notation in $\color{red}{red}$ since it makes zero sense to me.
Thanks for any help in advance.
Comment: That makes sense to me. It's totally clear what you mean. I wouldn't pay too much attention to these minor notational issues if I were you
Answer: It would be better to put brackets around $Tf$. So, it should look like $$(Tf)(x)=\int_{0}^x f(t)dt$$ This is because the function $T$ takes a function $f\in C([0, 1])$ to the function $Tf : [0, 1]\to K$ defined by $$(Tf)(x)=\int_{0}^x f(t)dt$$
When proving the linearity of $T$, the usage of $x$ is vague. The $x$ should be placed like $$(T(\alpha f+\beta g))(x)$$ Because the $x$ corresponds to the function $T(\alpha f + \beta g)$ and not $(\alpha f+\beta g)$. After the usage of $x$ is cleared up, you should include the $x$ as we have to prove that the function $T(\alpha f + \beta g)$ is equal to the function $\alpha(Tf)+\beta(Tg)$. And when proving that two functions $h$ and $j$ are equal, one often proves that $h(x)=j(x)$ for all $x$. Then using the linearity of the integral we conclude that $$(T(\alpha f+\beta g))(x)=\alpha(T f)(x)+\beta(T g)(x)\text{ for all }x\in [0, 1]$$
Also, it is vague to write $\alpha Tf(x)$ as the usage of $x$ is vague. So it is better to write $\alpha(Tf)(x)$. The same goes for $\beta Tg(x)$. It should be written as $\beta (Tg)(x)$.
The above expression is a bit convoluted. Breaking up the above expression in terms of additivity and homogeneity, we have shown that $$(T(f+g))(x)=(Tf)(x)+(Tg)(x)\text{ for all }x\in [0, 1]$$ and $$(T(\alpha f))(x)=\alpha (Tf)(x)\text{ for all }x\in [0, 1] \text{ and for all }\alpha \in K$$ It doesn't matter whether we include the $\alpha $ inside the brackets $(Tf)$ as the usual definition of scalar multiplication of a function is defined by $$(cf)(x)=cf(x)$$
Hope this clears things up!
Comment: Well, I would say it "more or less" does clear things up: I understand your thoughts in the parenthesis issue/confusion. Altought, the notation $Tf(x)$ instead of $(Tf)(x)$ follows from the exercise I am solving and (thus) what I do afterwards must be based off this inital notation. Besides this, the rest of your answer looks pretty usefull and seems what I am looking for!


Can I download firebase database json

Question: Can we download firebase database json through android application if yes how can we do that. I can do it manually from Firebase console. I want to know how can I do it programmatically through android application
Comment: Hey @UmairIqb , this is the same problem currently I'm facing. Did you got proper solution. I'm new to android and can't understand Frank's answer. Could you please share the solution.
Comment: you have to download firebase data in hashmap type as it is store in the database and then you can convert it into json
Answer: If you want to read the entire contents of the Firebase Database without using the Firebase SDK, you can do so with its REST API.
To do so, use the URL that you can see in your Firebase console and then by adding .json to the end. So for example, https://yourproject.firebaseio.com/.json.
Comment: Iam creating an application usin firebase realtime database in which user store and retrieve information.Now I want on a button click user can able to download its information from firebase database in json format.Is it possible?
Comment: Yes. If you want a direct export, you'd use the REST API as mentioned. See https://firebase.google.com/docs/database/rest/retrieve-data. You'll have to authenticate their requests yourself in that case though, which the SDK would usually do for you behind the scenes. So definitely consider if it isn't easier for you to just reconstruct the download data on the client from the `DataSnapshot`s you already have.

Can I download firebase database json


Triple integral volume by equations

Question: I have trouble setting up a triple integral to find volume bound by equations, such as:
$$z = x^2 + 3;\quad y = 3 - x^2;\quad x + y = 2;\quad z = 0.$$
I'm not sure how to figure how to find the boundaries for the $z$-axis. How would I go about setting up the triple integral?
Comment: Let's pretend your floor is the $xy$ plane. Then $z=0$ is on the floor, and $z=x^2 +3$ is how high your upper surface lies. The remaining equations will dictate the "shadow" of your surface on the floor. Try sketching out the curves involving $x$ and $y$, plotting relevant intersections, to get a better idea.
Answer: You have $y=3-x^2$ and $x+y=2$. Set them equal to each other and find the intersection points. Namely, $3-x^2=2-x$ gives $x=\frac{1\pm\sqrt{5}}2$. Our lower $x$-limit is $\frac{1-\sqrt{5}}2$ and our upper $x$-limit is $\frac{1+\sqrt{5}}2$.
Furthermore, $3-x^2 \ge 2-x$ on the interval $[\frac{1-\sqrt{5}}2,\frac{1+\sqrt{5}}2]$. Our lower $y$-limit is $2-x$ and our upper $y$-limit is $3-x^2$.
We also see that our lower $z$-limit is $0$ and our upper $z$-limit is $x^2+3$.
Our volume $V$ is therefore represented by the triple integral $$V=\int_\frac{1-\sqrt{5}}2^\frac{1+\sqrt{5}}2 \int_{2-x}^{3-x^2} \int_0^{x^2+3} dz \, dy \, dx.$$
Comment: Thanks, this really cleared things up for me! I took @zahbaz advice and sketched out the xy plane and I figured it out!

Triple integral volume by equations


How to escape characters like colon : and comma , in for loop?

Question: I have a file named "blocked.txt" which contains name of 4000 files like below:
1502146676.VdeI4b5c5cbM804631.vps47619.domain.local:2,
1502146676.VdeI4b5c5cdM808282.vps47619.domain.local:2,
1502146677.VdeI4b5c5d3M192892.vps47619.domain.local:2,
1502146677.VdeI4b5c5d7M213070.vps47619.domain.local:2,
1502146677.VdeI4b5c5e5M796312.vps47619.domain.local:2,
1502146678.VdeI4b5c5efM412992.vps47619.domain.local:2,
1502146678.VdeI4b5c5f1M613275.vps47619.domain.local:2,
1502146679.VdeI4b5c5f8M11301.vps47619.domain.local:2,
1502146682.VdeI4b5c66dM115848.vps47619.domain.local:2,S
1502146682.VdeI4b5c676M608733.vps47619.domain.local:2,
1502146685.VdeI4b5c69aM1652.vps47619.domain.local:2,
....
 ....

i ran below command on shell to copy the files to /tmp/backup directory
for i in `cat blocked.txt`; do cp -f  "${i}" /tmp/backup/ ; done

but this gives me error "do you want to overwrite ? y/n" even though i have used  -f with cp
Any idea whats wrong in the command ?
Comment: I have used your code and I can not reproduce (using linux and bash). Files are correctly copied and no error message when we try this several times
Answer: You likely have an alias,
alias cp="cp -i"

or function
cp () {
    command cp -i "$@"
}

that interferes.
To solve this, simply use command cp instead of just cp:
while read -r name; do
    command cp "$name" /tmp/backup
done <blocked.txt

Or specify the full path to cp:
while read -r name; do
    /bin/cp "$name" /tmp/backup
done <blocked.txt


jquery not calling php using $.post

Question: I have a jquery that gets called when a checkbox is clicked. The jquery executes, however the PHP file isn't being called (at least I don't think it's being called).
I can't put "echo" statements in the PHP function since nothing is returned from PHP (it just updates a table when called by jquery) + I don't know where it would echo too!

Can someone tell me why the PHP function isn't being called?
How do I "debug" a PHP function being called this way through jquery assuming I can't just echo out variables?

The jquery:
$('#notify_checkbox').click(function(){

if($('#notify_checkbox').is(':checked'))
    {
        $.post("/upic/update_notify", { checked: "y", email: "<?php echo $this->session->userdata('email');?>" });
        $( "#notifyresult" ).html( "
Awesome, we'll send you an email!
" );
}
else
{
        $.post("/upic/update_notify", { checked: "n", email: "<?php echo $this->session->userdata('email');?>" });
        $( "#notifyresult" ).html( "
Okay, we won't email you.
" );
}
});

And the PHP (I'm using the CodeIgniter framework):
function update_notify()
{
    // Passed through AJAX
    $notify = $_POST['checked'];
    $email = $_POST['email'];

    $this->load->model('musers');
    $query = $this->musers->update_user_notify($email, $notify);
}

EDIT: Using the full URL (http://.../upic/update_notify) in the $.post works. But calling just the controller and the function does not.
Comment: Install firebug and see what actually has happened
Comment: Damn jQuery, it never calls anymore... :P
Comment: wrap your click function in a document ready call otherwise it'll never be attached... that is `$(function(){   ...your javascript here... });`
Answer: I find using log_message useful when doing debugging with CodeIgniter, take a look here: http://codeigniter.com/user_guide/general/errors.html
Apart from that, why do you think that the action is not being called?
Comment: Hey Freeat... good point, but this is more of a comment than an answer.
Answer: You better to use:
$.post('<?=site_url('controller/function');?>',{data here})

jquery not calling php using $.post


How should I mix validated and unvalidated properties for a Vue component?

Question: I have a VueJS component that has a validated property called "name"; however, the remaining properties will not be validated.
How should I reference my unvalidated properties? Should I simply insert an empty string or object (as I have done so below) as the property's value?
The properties in my Vue component
props: {
   name: { required: true },
   generatecontrchart: {}
}

Comment: You can indicate the property's type when there is no validation needed (ex: https://vuejs.org/v2/guide/components.html#Prop-Validation)
Answer: I also posted this question on the official VueJS forum and based off the answer there, you should do the following when you want to mix validated and unvalidated properties for a Vue component:
You should set the unvalidated property to type:null, which means that it can be anything.
props:{
  name:{type:String, required:true},
  generatecontrchart:{type:null}
}

Comment: You don't need to write `{type: null}` but you could simply define your property as `generatecontrchart: null`.


Is it possible to create a texturepack for non-existing items/blocks?

Question:
What I exactly wanted to ask: every item in minecraft has it's own ID and SubID
For example:
1:2 (where 1 is ID and 2 is subid)
wool:3 (where wool is ID and 3 is subid)
and etc.
Can I create a resourcepack that will contain textures for non-existing subids?
For example 1:102, 101:500 ?
Answer: No, you can't add new blocks using just a resource pack, since the game doesn't get the block IDs from there. You'd still need to tell minecraft what block your resources are about.

You have other options:

Use Forge or similar and make a small mod to include your block(s). This requires at least some basic Java knowledge. (Here is an example tutorial)
Customize existing blocks using a resource pack.
Make use of a block designer (which requires a special resource pack).
Comment: Yep, block designer is what I actually needed. Thanks.
Answer: Not necessarily, but you can change the texture of the 'texture not found' texture, which is the black and purple checkered texture you get on an item that has an unknown block id. But you cannot create new block ids with a texture pack, you need mods for that. You can look up a minecraft modding tutorial or if you just need to make a "new block" that you can't place then you can just use the 'texture not found' texture (although keep in mind that the texture is larger than other blocks, so you may be better off just looking up a modding tutorial).
Comment: Nice idea, but it will not work for my situation.


Error: Invalid "keyPath" option supplied in AWS IoT Node-red

Question: I am getting this message when trying to use aws iot with node red on Raspberry Pi, using node-red-contrib-aws-iot.
I've tried putting the certs in various directories, ~/, ~/.node-red/, ~/.node-red/certs/ etc but always get the same error
Does anyone know where is the correct place for the certs, and what is the correct corresponding key path for the aws-iot-broker node Security tab settings?
Thank you in advance
Answer: Here, We need to add client id along with the name of the certificate names, then only we can able to connect it.
Answer: If you get this error, be aware that there has been a change in the recent versions
File specification for the certificates changed! So you might have to change the filenames of your certificates.
See https://github.com/cuongquay/node-red-contrib-aws-iot/commit/bba0df4b0fa8e13a60f98c0ba05e57f423ad9bf8
Until February it was:
clientId + '-private.pem.key'
clientId + '-certificate.pem.crt'

Now it must be:
clientId + '.private.key'
clientId + '.cert.pem'


Removing useless tag in XML from XSLT

Question: I have following output in XML and i have problem on removing useless tags from the content. I have following XML values:
<Site EntityType="2" Identifier="CL">
  <Name Last="Rai"/>
  <Address/>
    <Contacts>
      <Contact>
        <Number/>
          </Contact>
      </Contacts>
</Site>

My question is how to remove useless tag from above XML using XSLT?
Desire output is like this:
<Site EntityType="2" Identifier="CL">
  <Name Last="Rai"/>
</Site>

In above input <Address/>, <Contacts>...</Contacts> makes no sense so we are deleting those contents.
Comment: Can you me more precise as to what "useless" means, as even "empty" elements may have a use? For example, what if the element had attributes, like ``, or if the element only had "useless" children, like ``. Would these need to be removed too? Thank you!
Comment: I mean if it has useless children like  OR if it has no any contain, means if it has just a tag like .
Comment: please post your desired XML output also.
Comment: Edited the question.
Comment: What is XSLD?  Do you mean XSLT?
Answer: In situations like this you should start off with the identity template which will copy across all existing nodes and attributes
<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>

This means you only need to write templates for the nodes you wish to remove. Taking you definition of "useless" as "elements with no descendant text nodes (or processing instructions), and with no attributes and no descendant elements with attributes", then the template match would you like this
 <xsl:template match="*[not(descendant-or-self::*/@*|descendant::text()[normalize-space()]|descendant::processing-instruction())]" />

Try this XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" />
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="*[not(descendant-or-self::*/@*|descendant::text()[normalize-space()]|descendant::processing-instruction())]" />
</xsl:stylesheet>

Alternatively, if you use xsl:strip-space, you could adjust it slightly to this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" />
  <xsl:strip-space elements="*" />
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="*[not(descendant-or-self::*/@*|descendant::text()|descendant::processing-instruction())]" />
</xsl:stylesheet>

Comment: I am not able to delete whole  block from above XSLD.
Comment: This should delete the whole Contact element. Are you definitely using the XML you have shown in your question? Thank you.

Removing useless tag in XML from XSLT


JavaScript regular expression ignore case exception (Invalid group)

Question: I have the following Regular expression :
(?i:(?:(?:(?:fbx|fo))\d+)|(?:(09|0[1-5])\s?(?:\d{2}\s?){4})(?:(@freeadsl)?))

I tested the expression in https://regex101.com/ and it works.

But in javascript, it dosen't work.

After doing a search, it turned out that the problem is that javascript doesn't accept regex ignore case ?i.
What's the best solution to remedy this problem.
Any help, i'll appreciate it, thanks !
Answer: JavaScript regex engine does not support inline modifier groups. You may  use a i modifier in the JS regex and remove unnecessary non-capturing groups to reduce your regex to
var rx = /(?:fbx|fo)\d+|(?:09|0[1-5])\s?(?:\d{2}\s?){4}(?:@freeadsl)?/i;
                                                                      ^

See the regex demo. The /i at the end makes the letters in the pattern match both lower- and uppercase letters.
Details:

(?:fbx|fo)\d+ -  fbx or fo substring followed with 1+ digits
| - or
(?:09|0[1-5]) - 09 substring or 0 followed with 1 to 5 digit.
\s? - an optional (1 or 0) whitespaces
(?:\d{2}\s?){4} - 4 occurrences of:

\d{2} - 2 digits
\s? - an optional (1 or 0) whitespaces

(?:@freeadsl)? - an optional @freeadsl substring.
Comment: Thank you for your response @Wiktor. Just for information, i get the regex from Backend, i can't change it but i see that your regex is better, i'm gonna talk about it to backend developper. thank you for your help


how to implement payment methods in iphone?

Question: I have implemented product management system.I want to add one new features in which user can buy product from the iphone so user can do payment for particular products.
But i dont know how it possible.If you have any idea about that then please help me for this query.
Edit:
I have seen amazon.com and eBay application in apple store.I want to implement similar amazon.com and eBay application.For particular product buying or purchase.I have no idea how to implement.
If you have any reference documents then please provide me so it will be help full to me.
Answer: You are not allowed to sell stuff via an iPhone app. The only exception is Store Kit with its in app purchases, but you aren't allowed to sell real world stuff there. Only virtual stuff that users can consume on their phone/ipod/ipad.
Comment: You can of course sell a service. For example, as with the Spotify application.
Comment: Read what I wrote, its allowed as long as its consumable on the phone.
Source: https://developer.apple.com/appstore/resources/approval/guidelines.html
(11)
Comment: Interesting, Apple states clearly that they don't want this ("Apps utilizing a system other than the In App Purchase API (IAP) to purchase content, functionality, or services in an app will be rejected")
I must admit that I never used spotify as it isn't available here in germany. I just looked at the website and saw that you can buy offline music listening. Would you mind telling me how they sell their stuff?
Comment: You pay something like £10 a month and without an account, the App does nothing but show a login screen.
Comment: It may just be that big companies can do what small time developers can't because of things like PR with Apple. It's obviously not a written rule but just what I've heard from experience of other developers at conferences.
Comment: So this isn't done in the app at all? This would be allowed from what I read, but I guess that isn't the solution JohnWhite is looking for.
But interesting anyway, thanks for clarifying this
Comment: Frankly, I think you are misreading their guideline. You are, of course, allowed to sell things via an iphone app. You are not allowed to sell "real" things using IAP, nor are you allowed to sell functionality circumventing the app store. But you can sell stuff all you want. Look at Amazon.


Postgresql - Constraints on Ranges - Two tables

Question: With constraints on ranges, we prevent adding any overlapping values in an existing table. For example, in the following room_reservation table, we make sure that no room is reserved in a conflicting time.
CREATE EXTENSION btree_gist;
CREATE TABLE room_reservation (
    room text,
    during tsrange,
    EXCLUDE USING GIST (room WITH =, during WITH &&)
);

What we need here is to also consider another table (rooms) also having room and during fields and consider the records within that table while making a reservation?
Our specific scenario is exam management. We have an invigilation table (room reservation) and also a time table of classes. Once we are adding an invigilation record, we need to make sure that it does not coincide with any other invigilation record and make sure that there is no lecture at that time in that room.
Answer: You cannot do that with a single exclusion constraint. Instead, you should use the exclusion constraint on one table, say invigilation, and then use a BEFORE INSERT trigger on that same table that checks if there is a conflict in the second table, say rooms. The trigger function on the first table would do a simple range check on the second table:
CREATE FUNCTION check_no_class() RETURNS trigger AS $$
BEGIN
  PERFORM * FROM rooms
  WHERE room = NEW.room
    AND during && NEW.during;
  IF FOUND THEN
    RETURN NULL;
  ELSE
    RETURN NEW;
  END IF;
END; $$ LANGUAGE plpgsql;

CREATE TRIGGER check_rooms
BEFORE INSERT ON invigilation
FOR EACH ROW EXECUTE PROCEDURE check_no_class();

If a class is scheduled in a room then the insert on invigilation will fail.
Comment: Thanks @Patrick! I was trying to add one more trigger based on updates on the invigilation table (i.e. a current invigilation record is updated to a new one). To do this, I created another trigger (check_rooms_2) by only changing the second line to "BEFORE UPDATE ON invigilation". However it seems that this did not work out?!
Comment: Having tested again, the updates are accepted (i.e. the record is not highlighted in blue). However if it is a conflicting update, once the invigilation table is refreshed, the table reverts back to the initial content.


Showing unique values/levels for each character/factor variable at once?

Question: How to show unique values/levels for each character/factor variable at once?
Data
library(tidyverse)

d = tibble(age = rnorm(10, 50, 3),
           sex = rep(c("male", "female"), 5),
           name = letters[1:10]) %>%
  mutate(sex = as.factor(sex))

d

Checking variables one-by-one is time consuming as I work with large datasets
levels(d$sex)

1 "female" "male"
Expected result should be something like this
Answer: library(tidyverse)
d %>%
  select(!where(is.numeric)) %>%
  split.default(names(.)) %>%
  lapply(unique)

$name
name
1:    a
2:    b
3:    c
4:    d
5:    e
6:    f
7:    g
8:    h
9:    i
10:    j

$sex
sex
1:   male
2: female

Answer: is this what you're looking for?
d %>% mutate_all(funs(replace(., duplicated(.), NA)))

# A tibble: 10 x 3
     age sex    name
   <dbl> <fct>  <chr>
 1  54.0 male   a
 2  50.3 female b
 3  49.1 NA     c
 4  47.0 NA     d
 5  49.6 NA     e
 6  51.0 NA     f
 7  54.4 NA     g
 8  56.9 NA     h
 9  47.3 NA     i
10  52.4 NA     j

To sort the values and push NA to the last rows
d %>%
  mutate_all(list(~replace(., duplicated(.), NA))) %>%
  mutate_all(list(~sort(., na.last = TRUE))) %>%
  filter(if_any(everything(), ~ !is.na(.))) # To remove rows with all NA's

Comment: Would it be possible to do show that it will omit the original row structure, meaning that all unique values are shown on the first top rows?
Answer: You can tweak the argument maxsum in the function summary to display as many levels as you like for each factor.
d = data.frame(age = rnorm(10, 50, 3),
           sex = rep(c("male", "female"), 5),
           name = letters[1:10])
d$sex <- as.factor(d$sex)
d$name <- as.factor(d$name)

summary(d, maxsum = 10000000)


.php how to display an image that I can change and stock on my directory

Question:
Hello,
I'm trying to achieve something quite simple in php.
I want to get a page that display an image that I can change by sending a new one and that is stocked in the same folder than my php. So when I open my page I'll have the last image uploaded.
Idealy I would be able to crop it like the way croppie does (https://foliotek.github.io/Croppie/), but I want to understand the steps so let stay simple, the crop will be for later.
The code I have so far that allow me to upload images is
upload.php:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

and index.html
<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>

So not only I want to have a preview of the image displayed but I also want to stock only one image with a particular ID (If you want to know why, it's because then it goes straight to indesign, anyway...)
Thanks for your help guys !!!
Answer: SOLUTION I'VE FOUND
inspired from that page
How to upload & Save Files with Desired name
<form action='' method='POST' enctype='multipart/form-data'>
<input type='file' name='userFile'>

<input type='submit' name='upload_btn' value='upload'>
</form>

<?php
$info = pathinfo($_FILES['userFile']['name']);
$ext = $info['extension']; // get the extension of the file
$newname = "newname.".$ext;

$target = 'images/'.$newname;
move_uploaded_file( $_FILES['userFile']['tmp_name'], $target);
?>

clean and efficient ! works well !
Answer: First create in index.html following code
<?php

$path = 'i/';
$tmp_path = 'tmp/';
$types = array('image/gif', 'image/png', 'image/jpeg');
$size = 1024000;

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
 if (!in_array($_FILES['picture']['type'], $types))
  die('wrong type. maybe another file?');

 // Check size
 if ($_FILES['picture']['size'] > $size)
  die('BIG. maybe another file?');

 // Upload
 if (!@copy($_FILES['picture']['tmp_name'], $path . $_FILES['picture']['name']))
  echo 'wrong';
 else
 echo 'good see ' ;
}

?>
<!DOCTYPE html>

  <title></title>

  <form method="post" enctype="multipart/form-data">
 <input type="file" name="picture">
 <input type="submit" value="Upload">
  </form>

It's a shit code. Try to share the php code from html
http://php.net/manual/en/features.file-upload.post-method.php
Comment: I get the "wrong" echo when I try this code...


Find record where subject code is not zero for that class

Question: This is student table.
StudentId ClassId SubjectCode
101       201     0
101       201     1
101       301     1
101       401     0

Suppose I making final marksheet for his/her course.Student can attend different class.I want to find out the row where
student does not have subjectcode 0 for that class.Like this
   101       301     1

How to do that?
If I do like this
select Studentid,classId,subjectcode from Student
where operator <> 0

That give this record also
101 201 1    .I don't want that.because it has 0 for that class 201.

Answer: You can use GROUP BY and HAVING:
SELECT
    StudentId, ClassId
FROM Student
GROUP BY
    StudentId, ClassId
HAVING
    SUM(CASE WHEN SubjectCode = 0 THEN 1 ELSE 0 END) = 0

ONLINE DEMO


Displaying report based on data table selection

Question: First, hello to everyone since this is my first post in ux.stackexchange.com.
Now to my question:
Right now I have really simplistic view containing a search input + button and a jQuery datatable which is displayed only on find results after the search. Here is how it looks:

So as I said really simplistic. The data represents entities with similar properties. Now, the idea is that when you click on a certain entity (row in the datatable) a simple report should be displayed for this particular entity. And since the table contains entities of the same type, even if you select another row/entity, the values will be different but the structure of the report will remain the same. Basically the report will be several charts (3 to 5) and some text.
However my question is regarding how to display this report.

Modal - since there is a potential (but not 100% sure) that a user may want to see reports for several entities a thought that maybe a modal will make sense since it creates the feeling of logical separation but yet it's easy to get back and load another report. However, after a discussion with a colleague I get the argument the in the future the report may grow in size, maybe it won't fit in one screen and (this is just my and my colleagues understanding) the modals are not meant to show a large amounts of data.
Dedicated page When we were presented with the task, the PO mentioned that it won't be a problem even if we display the report in dedicated page. Since I was still thinking how to logically separate the search functionality from the display functionality this idea also appealed to me, for the reasons I've just mentioned, it gives the user clean separation of the different parts of the application - here is where you search, and this is where you see the data. However, thinking more about it, one big cons that come to mind is that each time that you want to see another report you will need to go through the navigation to open again the search page and since I'm still not very sure what is the expected use-case - is it most likely that a user will be searching for a particular entity and wanting to see report only for it, or opens several reports, I think this approach actually is no very user friendly.
Display the report below the data table - So first I was strongly against this. For me searching and reporting have enough difference to keep them logically and visually separated. However, thinking more and more about the different options I'm getting to think that this might actually be the best way to serve the data. Yes, you will have a search input, a data table below it, and then a report with, which is a little bit messy for my test, but it gives an easy way for the user to apply new search criteria or generate reports for different entities.

For now I think there is no need to show the report itself (even though if you think it's important I can include some mock up) but what I would like to hear is what you think would be the best user experience? If my initial reaction wasn't so strongly against displaying the report on the same page as the search functionality maybe I would go for this option, but now I wonder. I would also be glad to read some alternative ideas.
Answer: We build a lot of software that contains reporting features like this. We've tried different alternatives and have found that it's best to show the report on the same page as the search/filtering if the user is likely to view multiple reports. This makes it fast for the user which is often important if they have to view a lot of them.
The downside of this approach is that it can be a bit messy and having it all on one page can be distracting to the user. To combat this, it helps to visually separate the search section from the report section. Further, we find it useful to hide the search section one a report has been selected, with an easy way to bring it back. E.g. search fields and results are kept in a collapsible panel that is collapsed automatically when a selection is made.
If they're likely to only view one or two reports, then putting in on a new page can work as well. If you choose to do this, I would ensure that there is enough information in the search results table for them to pick the right report (avoid them going back and forth if they make a mistake), and provide an easy way to return to the search.
Comment: Thanks, good info and tips. I was also thinking about new page with very explicit way to easily go back to the search page. Now that you are also mentioning it I'm starting to think that maybe this could be a very good option.


Is there any move that cures the enemy pokemon's status problems?

Question: I am currently engaged in a desperate struggle to capture the roaming legendary beasts. I have my sights set on Entei at the moment, having brought it down to 1 HP and paralyzed it. Sadly, it is still infuriatingly difficult to catch.
This was all done before I realized that applying the "sleep" condition is preferable than applying the "paralysis" condition for the purpose of capturing pokemon.
Seeing how you cannot afflict a pokemon with two status ailments, I would like to cure the Entei's paralysis so that I could make it sleep instead. Is there any move that will allow me to do this?
Answer: There are at least three ways. Unfortunately, none will work on your scenario.
Fling, when used with a corresponding status healing berry, should recover the status condition. However, it counts as a 10 Power attack prior to causing the effect, so you would not even be able to throw a Sitrus berry for healing before you would kill something at 1 HP.
Trick and all of its derivatives can be used to swap a status healing berry onto the target. None of the Legendary Beasts have held items to my knowledge, though, so this won't work.
Finally, the moves Wake-Up Slap and Smelling Salts will cure Sleep and Paralysis respectively. But not only do they do damage, they do double damage to such an afflicted Pokémon. So like Fling, not viable.
Comment: The Fling/Smelling Salts causing damage problem can be worked around if you heal the enemy first. You can use Pain Split, or get lucky with Present(20% chance). Since Present has an 80% chance to KO the enemy if it has 1HP, I'd go with Pain Split.
Comment: Most? That looks like all, to me.
Comment: @Aubergine It's a leftover from when I wasn't sure about Fling. I'll fix that.
Answer: Kill it. No, really. After you defeat the Elite Four again, any roaming legendaries you knocked out will return to the the Brass Tower, at full health and status effects.
As for capturing Entei, beware that roaming legendaries can flee even when asleep. You need to use Mean Look or Block, or a Pokemon with the ability Shadow Tag or Arena Trap. This will give you more than one round to throw Pokeballs, and greatly increase your chance of capturing Entei.
Entei can still escape using Roar, but blocking this while keeping a no-fleeing effect in play involves a lot of specialist breeding work. The easiest is to level an Eevee to L36 to learn Baton Pass, evolve it to an Umbreon and level it to L57 to learn Mean Look. Use this to trap Entei and Baton Pass out to something with the ability Soundproof or Suction Cups or the move Ingrain, any of which will block Roar. Many such Pokemon can learn a sleep or paralysis move by breeding or level.
Both Entei and Raikou are fast enough to benefit from Fast Ball, which gives a 4x catch rate, better than an Ultra Ball. There is no better Pokeball for Entei or Raikou.
Comment: "Can flee even when asleep" http://www.awkwardzombie.com/index.php?page=0&comic=053110 http://stephi-jk.deviantart.com/art/Fast-Asleep-Entei-162032873
Answer: Use Manaphy to Skill Swap its Hydration ability to the target pokemon. Since you only have one turn, you may have to do this on route 33 where it rains naturally.
Unfortunately, no pokemon with Leaf Guard or Shed Skin (my first idea) will learn Skill Swap.
Comment: My apologies, I must have mixed that ability with something else that simply heals a pokemon (thus allowing me to remove the paralysis using one of the other methods mentioned above). I'll go ahead and kill my previous comment. I won't argue with your, however, that a Manaphy is a pretty problematic prerequisite.
Answer: Having the paralyze condition instead of sleep is not a problem at all, especially when its HP is down to 1. Furthermore, pokemon wake up from sleep, whereas they do not get cured of paralysis (unless they have the move Refresh).
Paralyze is 1.5x instead of 2x for sleep, but using a Dusk Ball (3.5x) or Quick Ball (4x) or Timer Ball (4x) is more effective than both if used at the right time. You'll catch it eventually!
Side note: Haze used to cure the opponent's status ailment in the first two generations, but this has since been removed for some reason.
Comment: While true, seeing how the Entei constantly tries to flee, sleep could give me several turns to catch it, instead of just one. Also, you'd be surprised how many quick balls I have wasted in my attempts already, so I'm really trying to up my chances.
Comment: @Aubergine: Aren't you using Mean Look or similar move that prevents fleeing? If not then half the time your sleep move won't work and the pokemon will flee anyway. So there is barely any difference.
Comment: They still flee while asleep...
Answer: Kill it. After you beat the Elite Four again, they will reappear at full health and everything. Or! Hunt for him at night or set your DS clock to night and then throw dusk balls at it. Use mean look or something. Paralysis reduces the speed and dusk have a 4x catch multiplier when thrown at night. I caught all legendaries using a Dusk Ball. Try it! you get it at the pokemart.
Answer: Use Present. It might affect it but there is a 10% chance it will cure Entei. You can turn off without saving and try it again, though.
Comment: Does [present](http://bulbapedia.bulbagarden.net/wiki/Present_(move)) actually cure status effects? Bulbapedia doesn't say so
Comment: A good question... Present was actually mentioned in one of the higher rated comments for the accepted answer as something to bolster my chances of not killing Entei with other moves, moves that could solve my predicament if they did not cause damage. I don't see how present is a direct solution to the problem.


Concerning averages.

Question: Here is a simple test question:

The average of 5 different integers is 33. The smallest of the 5 integers is 30. The largest of the five integers is N. How many possible values of N are there?
A. 3
B. 6
C. 5
D. 4
E. 7

It seems pretty simple question, but I cannot get the right answer. Here is a solution.
Let the integers be $a_1, a_2, a_3, a_4, a_5$ and let $a_1=30$ be the smallest of 5. So, $a_2 + a_3 + a_4 + a_5 = 33*5-30=135$. If we brute-force the solution, we will have:
$31 + 32 + 33 + 39 = 135$
$32 + 33 + 34 + 36 = 135$
Which gives only $2$ possible solutions, but there is no choice of 2. What am I missing?
Answer: You are missing $31+32+34+38=135$ and $31+32+35+37=135$  You identified the end cases correctly, but all the ones in between work, too.
Comment: Ah, can't believe how I missed them. Thanks.

Concerning averages.


Maclaurin series and general term for $e^{(x-2)^2}$

Question: I need to write the first four nonzero terms and the general term for the Taylor series for $g(x)=e^{(x-2)^2}$ about $x=2$. I tried foiling out $(x-2)^2$ and using that whole term to replace $x$ in the general term and in the series, but it gets very messy and I do not believe I am correct. Thanks in advance!
Comment: If you are looking for the Maclaurin series, then why are you looking for the general term for the Taylor series of $g(x)=e^{(x-2)^2}$ about $x=2$? The Maclaurin series is about $x=0$.
Comment: What is your question? Do you want the **Maclaurin series** (as stated in the heading) or the **Taylor series about $x-2$** (as stated in the body)? Which is it?
Answer: It does get ugly, true...
$\begin{align*}
   \exp((x - 2)^2)
       &= \sum_{n \ge 0} \frac{(x - 2)^{2 n}}{n!} \\
       &= \sum_{n \ge 0}
                \frac{1}{n!}
                   \sum_{0 \le k \le 2 n}
                       \binom{2 n}{k}
                            \cdot (-2)^{2 n - k}  x^k \\
       &= \sum_{n \ge 0} \sum_k
                \frac{1}{n!} \binom{2 n}{k}
                     \cdot (-2)^{2 n - k}  x^k \\
       &= \sum_k x^k
                \sum_{n \ge 0}
                    \frac{1}{n!} \binom{2 n}{k}
                     \cdot (-2)^{2 n - k}
\end{align*}$
We can drop the range of the inner sum as outside the range the binomial coefficient is zero, and switching summation orders around is permissible as long as the mess converges absolutely, which it does for the exponential sum and the internal sum is finite.
A "nice" form for the coefficient (inner sum) is rather unlikely.


Robovm bindings import issue

Question: I am trying to import the RoboVM bindings to implement mopub in my project, but I ran into a problem when I tried to "build model". I tried to import it as a gradle project, but when I build it I get the error:
<code>"Error in runnable 'Creating Gradle Model'"
</code>
And it says:
<code>"could not find com.github.jtakakura:gradle-robovm-plugin:0.0.9-SNAPSHOT.
Required by:
:robovm-ios-bindings-master:unspecified
See error log for details"
</code>
in the error log it said

"FAILURE: Build failed with an exception.
What went wrong:
  A problem occurred configuring root project 'robovm-ios-bindings-master'.
  Could not resolve all dependencies for configuration ':classpath'.
  Could not find com.github.jtakakura:gradle-robovm-plugin:0.0.9-SNAPSHOT.
       Required by:
           :robovm-ios-bindings-master:unspecified
Try:
  Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output."

I am not even sure how to run with the stacktrace option, does anyone have any insight on how to solve this problem?
Comment: Okay so it seems like I shouldn't be importing the binding project as a gradle project, because I had it working in a different workspace, and it looks like I had it imported as a normal project. The only problem is that I redownloaded the bindings to see if they would work. Now if I try to reopen the project in the workspace which had it working, it says I am missing the .project file. Any ideas what the problem might be?
Answer: Found it out! I went into the ios bindings folder, opened the build.gradle, and found the line of code that had the 0.0.9-SNAPSHOT. Then I went to the github for robovm, and opened the build.gradle there. I saw that it had 0.0.10 as the snapshot, so I changed it to that. It now works, and I feel pretty brilliant for that.

Robovm bindings import issue


Minecraft won't download sound file calm3.ogg!

Question: right now I'm on vacation on my brother's computer and when I download Minecraft it works but when i press play it wont download calm3.ogg this is the error message
<code>Name: calm3.ogg
URL: http://resources.download.minecraft.net/14/14ae57a6bce3d4254daa8be2b098c2d99743cc3f
Error details: Request error -101: ERR_CONNECTION_RESET
Filename on disk: e90c-b0f6-a01f-0e8c
Path: C:\Users\WEARE4~1\AppData\Local\Temp\e90c-b0f6-a01f-0e8c
Exists: file
</code>
I'm using version 1.7.10 but same happens on every other version
Comment: OMG I TRIED AGAIN AND IT WORKED THX!
Answer: This issue is most frequently caused by antivirus, firewall or other type of software which scans downloads.
Try temporarily disabling your antivirus software.
Comment: I have windows defender and I disabled it but it still doesn't work it downloads every other file but not that one!


Pigeonhole principle for n queens

Question: Suppose we have a board $100 \times 100$ and place $100$ queens such that none attack another. Prove that each of the four $50 \times 50$ sub-boards (gotten by dividing the board in $4$) contains at least one queen.  Additionally, prove that if one of the boards contains exactly one queen, replacing queens by knights would lead to knights attacking each other.
My approach has been to use that each of the row and column must contain only one queen, then utilize pigeonhole principle somehow. Still, I'm not sure how is it possible to place only one queen on $50 \times 50$ board.
Comment: The question is asking you to show "each subboard has at least one queen," not "at least one subboard only has one queen."
Answer: Each row must contain exactly one queen; each column must contain exactly one queen.
Suppose for sake of contradiction the upper-left subboard contains no queens.

This implies that the 50 queens in the upper half of the board must be in the upper-right subboard.
This also implies that the 50 queens in the left half of the board must be in the bottom-left subboard.

Since these two sets of queens are disjoint, this accounts for all $100$ queens: all are either in the upper-right or bottom-left subboards.
However, these two subboards contain only $2 \cdot 50 - 1 = 99$ diagonals, so there must be two queens on the same diagonal somewhere. This is a contradiction.

Pigeonhole principle for n queens


Can I skip levels to get the "no damage" achievements?

Question: Several items in the Binding of Isaac allow you to skip a level without facing the boss (We Need to Go Deeper and the Teleport! item, though teleporting is a less reliable form of level skipping).
I've managed to get all "no damage" achievements except the one for The Depths, mainly due to the abundance of Leapers on those levels. Whenever I unlocked one of said achievements, it was always the instant I defeated the boss on the second floor for that level, making it seem like the two are tied together.
So I was wondering, suppose I simply skip through the second level without having incurred damage on the first (possibly skipping some or most of it as well), will I still get the achievement?
Answer: No, you cannot. Sadly, the achievement only registers on the boss kills, and not by going further down the dungeon.
Comment: Actually, you can skip the first level boss, but you need to face the second.
Comment: Well, I guess that is to be expected of such a fiendish game.


How can i fix this part

Question: Using Python, write a program that will check the employees years in service and office. The user will input number for years and in service and the following offices (it, acct, hr) Check the following conditions. Office IT ACCT HR Years More than or equal 10 years 10000 12000 15000 Below 10 years 5000 6000 7500
i already have my code but im having a hard time to.. make it more specific
# take the input from user
year = int(input('Please enter the years: '))
office = input('Please enter the office name: ')
# if-else condition
if (office.upper() == "IT" or office.lower() == "it") or (office.upper() == "ACCT" or office.lower() == "acct") or (office.upper() == "HR" or office.lower() == "hr"):
    {
        print("Employee office is: "+ office)
    }
else:
    {
        print("The wrong office name entered")
    }
# if-else condition
if year >=10:
    {
        print("10000 12000 15000")
    }
else:
    {
        print("5000 6000 7500")
    }

but the expected result should be like this:
enter years in service: 15
enter office : IT
salary based on year/exp: 10000
Comment: what are those double checks? `office.upper() == "IT" or office.lower() == "it"`, `lower` lowers the entire string and also you can check against multiple by using a tuple and `in`, so just have `if office.lower() in ('it', 'acct', 'hr'):` and also don't use the curly braces, completely unnecessary
Comment: Why do you have curly braces around the `if` condition body?  This isn't C.
Comment: There are 3 options for the salary in case of years<10 and same for years>=10. How is it deciding salary as 10000 in your expected result?
Comment: ohh nvm i already realized it
Comment: You need more code to get it to print only one amount
Comment: To add to @Matiiss said, are the three values: "10000", "12000", "15000" corresponding to these three offices? If so, I would not merge them together as a single if. It would be better to separate them and do nested ifs. if(office = "hr): if (years > 10): print("15000") . Just as an example
Answer: All you need is to repeat the year if-statements in the individual office name if-statements:
year = int(input('Please enter the years: '))
office = input('Please enter the office name: ')

print("\nsalary based on year/exp: ",end='')
if office.upper() == "IT" or office.lower() == "it":
    if year >=10: print(10000)
    else: print(5000)
elif office.upper() == "ACCT" or office.lower() == "acct":
    if year >=10: print(12000)
    else: print(6000)
elif office.upper() == "HR" or office.lower() == "hr":
    if year >=10: print(15000)
    else: print(7500)
else:
    print("The wrong office name entered")

Comment: you can easily remove either `.lower() == 'string'` or `.upper() == 'string'` because using either of those achieves the same thing.
Answer: You can use a dictionary to store key and value pairs, where you can access the value by using the key. So let the key be the office name and value a tuple containing salary for less than 10 years and for more or 10 years. Then ask for the office name and immediately lower the returned value to make things easier. Then ask for years in service and convert the returned value to an integer to be able to make comparisons. Then get the value from the dictionary and if the key doesn't exist (incorrect office name), return a tuple of two values so that later usage of indexes doesn't raise an exception. Then based on the years print either the first value or second value in the tuple:
office_salary = {
    'it': (5000, 10_000),
    'acct': (6000, 12_000),
    'hr': (7500, 15_000)
}

office = input('Enter office name: ').lower()
years = int(input('Enter years in service: '))

salaries = office_salary.get(office, (None, None))
if years < 10:
    print(salaries[0])
elif years >= 10:
    print(salaries[1]

Answer: If I understood you correctly:
# take the input from user
year = int(input('Please enter the years: '))
office = input('Please enter the office name: ')
# if-else condition
if (office.upper() == "IT"):
    if (year >= 10):
        print("10000")
    else:
        print("5000")
elif (office.upper() == "HR"):
    if (year >= 10):
        print("12000")
    else:
        print("6000")
elif (office.upper() == "ACCT"):
    if (year >= 10):
        print("15000")
    else:
        print("7500")
else:
    print("The wrong office name entered")

If not, you need to clarify further.

How can i fix this part


Java Console Application Locked

Question: Java is not my main programming language so my expertise are generally limited in this area.
Scenario
This app is supposed to execute for indefinitely like a service or daemon. Its main purpose is to process some rows in DB as they are inserted by some other process.
The app at times Spits out log messages through System.out.println. It also uses some other log files. I was earlier using log4j but that is disabled for the moment.
Also I am running this in Windows Server environment, if that helps. I cant use linux for now.
Problem
The problem is that, on rare occasions, I find the application in staging/prod env becomes locked or does not seem to process any DB rows further. After I press enter  a few times on screen it moves ahead and start processing as usual. This is strange because I am not expecting any input from the user. Any input the app has is either from command line or from DB.
Also I know for sure that its not a DB issue. The app is not waiting for any table lock. It may have to do with some file locking or System.out stream being locked. The later I did not think of possibility until I see that some keystroke on screen 'wakes' the application.
So I am wondering if someone may point me in a direction where I can debug this further.
Answer: Microsoft in all its infinite wisdom has made the console window in such a way that it allows you to select a rectangular area of characters with the mouse. So far so good.
And supposedly in order to make it easier for the user to select text while text may be scrolling, they (in their infinite wisdom) freeze the process hosted by the terminal window if it attempts to emit text while you are selecting text. (*)
And it just so happens that if you do as little as click a console window with the mouse, they (in their infinite wisdom) put the window in text selection mode, as witnessed by the presence of a little white square.
Which is very unfortunate, because clicking on a window is what we also do in order to simply bring the window to the foreground.  But there is a huge gotcha here: if the console window was not already on the foreground, then clicking it brings it to the foreground.  But if the console window was already on the foreground, then clicking it enters selection mode.  (And of course most people rarely know, or care, or want to be bothered, with whether the window is already on the foreground or not.)
So, to conclude: try not clicking your window.  Click only the caption if you have to.  If you do accidentally click on the window, then press [Enter] or click again to make the little white selection rectangle go away.
Because for as long as the little white selection rectangle is there, your program is frozen.

(*) Now, they could have easily frozen the display of the window while selecting without freezing the process; they could have made it so that the output of the process keeps being buffered, and then dumped on the screen once selection is done, but I guess they were too busy with their plans for world domination to get around to fixing this.  I cannot even begin to think how much time (= money) must have been wasted all over the world so far due to microsoft console windows sitting idle in selection mode while people are under the impression that they are crunching data.
Comment: Thanks I think that was the cause. I never notice that at times I am in selection mode.
Answer: this is the way to do it
go tp properties and un-check : "quick edit mode"

Java Console Application Locked


Reading Docker container status inside application

Question: I have a C++ application containerised as docker container. I have come across a scenario where the docker daemon on a host where the docker containers are running ,goes down. Thereby the container run time also goes down. How do i read this status inside the application which is residing in the container itself?
Thanks in advance
Comment: If the application is in the container, and the container is exited, then the application is exited, and there's not really anything you can check.  Or am I misunderstanding the setup?
Answer: Use --network="host" in your docker run command, then 127.0.0.1 in your docker container will point to your docker host. You can then ping 127.0.0.1 from your container to get the status of your host. But I don't see a point of doing it because if your host is going down, anyways containers would be the first to loose network connectivity and you won't be able to read the status inside the application ever.
Recommended way is to perform container orchestration using swarm, k8s, openshift etc to avoid this issue.