Per channel normalization of RGB images

Question: I would like to know how I can manually normalize an RGB image.
I tried:
img_name = 'example/abc/myfile.png'
img = np.asarray(Image.open(img_name))
img = np.transpose(img, (2,0,1))
(img/255.0 - mean)/std

mean and std has shape (3,)
When I run the code above I get this error:
ValueError: operands could not be broadcast together with shapes (3,512,512) (3,)

How can we normalize each channel individually?
Comment: to standardize the transposed image you can simply do `standardized = (img - img.mean((1, 2))) / img.std((1, 2))`  (why do you divide by 255?)
Comment: @Stef With your suggested formula, I still get the same error
Answer: Normalization means to transform to zero mean and unit variance. This is done by subtracting the mean and dividing the result by the standard deviation.
You can do it per channel by specifying the axes as x.mean((1,2)) instead of just x.mean(). In order to be able to broadcast you need to transpose the image first and then transpose back.
import numpy as np

np.random.seed(0)
c = 3  # number of channels
h = 2  # height
w = 4  # width
img = np.random.randint(0, 255, (c, h, w))

img_n = ((img.T - img.mean((1,2))) / img.std((1,2))).T

Original image:
array([[[172,  47, 117, 192],
        [ 67, 251, 195, 103]],

       [[  9, 211,  21, 242],
        [ 36,  87,  70, 216]],

       [[ 88, 140,  58, 193],
        [230,  39,  87, 174]]])

Normalized image:
array([[[ 0.43920493, -1.45391976, -0.39376994,  0.74210488],
        [-1.15101981,  1.63565973,  0.78753987, -0.6057999 ]],

       [[-1.14091546,  1.10752281, -1.00734487,  1.45258017],
        [-0.84038163, -0.27270662, -0.46193163,  1.16317723]],

       [[-0.59393963,  0.21615508, -1.06130196,  1.04182853],
        [ 1.61824207, -1.35729811, -0.60951837,  0.74583239]]])

Verify zero mean and unit standard deviation per channel print(img_n.mean((1,2)), img_n.std((1,2))):
[-1.38777878e-17  0.00000000e+00  0.00000000e+00]
[1. 1. 1.]

Per channel normalization of RGB images


redux form dynamic categories

Question: i am using redux form and what i do here is when user selects category the next select field should have all subcategories depending of category selected.
what i did was i created api for fetching all categories, i trigger action via componentWillMount and load all categories in first categories select field, then i use formValueSelector of redux-form to get selected category to the state/this.props, then i use componentWillReceiveProps() to trigger fetching subcategories with that e.g. "this.props.categoryId" that i put to state with formValueSelector and that works.
and my question is, is this the right aporoach, is there a better way?
and the second question, is how do i reset categoryChildId field to, lets say blank when the categoryId field is changed?
import React from 'react';
import moment from 'moment';
import { Field, reduxForm, formValueSelector } from 'redux-form';
import { connect } from 'react-redux';
import { Link, NavLink } from 'react-router-dom';
import {CopyToClipboard} from 'react-copy-to-clipboard';
import * as actions from '../../actions/category';

const renderField = ({ input, label, type, meta: { touched, error } }) => (

    <input {...input} placeholder={label} type={type} />
    {touched &&
     error &&

{error}
}

)

const renderTextArea = ({ input, label, type, meta: { touched, error } }) => (

    <textarea {...input} placeholder={label} type={type} />
    {touched &&
     error &&

{error}
}

)

class AddProduct extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: `${process.env.SITE_URL}/user/${props.user.username}`,
      copied: false,
      isLoading: false
    };
  }

  componentWillMount() {
     this.props.startSetCategories()
  }

  componentWillReceiveProps(nextProps) {
      this.props.startSetCategoryChildren(nextProps.categoryId)
      console.log(nextProps)
  }

  renderCategorySelector = ({ input, meta: { touched, error } }) => {
    return (

        <select {...input}>
          <option value="">select category</option>
          {!this.props.categories ? (
            <option value="">loading...</option>
          ) : (
            this.props.categories.map(category => <option value={category._id} key={category._id}>{category.name}</option>)
          )
        }
        </select>
        {touched && error && {error}}

    )
  }

  renderCategoryChildSelector = ({ input, meta: { touched, error } }) => {
    return (

        <select {...input}>
          <option value="">select sub category</option>
          {!this.props.categoryChildren ? (
            <option value="">loading...</option>
          ) : (
            this.props.categoryChildren.categoryChildren.map(categoryChild => <option value={categoryChild._id} key={categoryChild._id}>{categoryChild.name}</option>)
          )
          }
        </select>
        {touched && error && {error}}

    )
  }

  submitForm = values => {
    console.log(values)

  }

  render() {
    const username = localStorage.getItem('username');
    const { user } = this.props;
    const { handleSubmit, pristine, submitting, categoryId } = this.props;

    return (

          <form className="profile-addproduct-left" onSubmit={handleSubmit(this.submitForm.bind(this))}>

New Product

Fill out the form.

Title

                <Field
                  name="title"
                  type="text"
                  label="title of a product"
                  component={renderField}
                />

Category

                <Field
                  name="categoryId"
                  type="text"
                  component={this.renderCategorySelector}
                  label="category"
                />
                {this.props.categoryId ?
                  <Field
                    name="categoryChildId"
                    type="text"
                    component={this.renderCategoryChildSelector}
                    label="categoryChild"
                  /> :
                  ''
                }

Description

                <Field
                  name="description"
                  type="text"
                  label="Write some interesting..."
                  component={renderTextArea}
                />

              <button className="button button--register" type="submit" disabled={this.state.isLoading || pristine}>Submit New Product</button>

          </form>

    )
  }
};

AddProduct =  reduxForm({
  form: 'addproduct-form'
})(AddProduct)

const selector = formValueSelector('addproduct-form')

AddProduct = connect(state => {
  const categoryId = selector(state, 'categoryId')
  return {
    categoryId,
    categories: state.category.categories,
    categoryChildren: state.category.categoryChildren
  }
}, actions)(AddProduct)

export default AddProduct

Comment: I think it's a reasonable approach. If you want to delete the field, you can just do `this.props.change('categoryId', null)`
Comment: thank you for your feedback and help, i've managed the reset field problem:)
Answer: You should not call the startSetCategoryChildren (or any other api) in componentWillReceiveProps... because it would call every time whenever componentWillReceiveProps called
componentWillReceiveProps(nextProps) {
  this.props.startSetCategoryChildren(nextProps.categoryId)
  console.log(nextProps)
}

Instead of this you can to do this on handleChange of the Field
            <Field
              name="categoryId"
              type="text"
              component={this.renderCategorySelector}
              label="category"
              onChange={(e) => this.props.startSetCategoryChildren(e.target.value)}
            />

Comment: If this solution is correct, mark as correct for future references.
Comment: Wow thanks, idk how i didnt think of this.:D definitely a better solution

redux form dynamic categories


Wicket on Jetty: Cannot save page with id

Question: I deployed my Apache Wicket App on a Jetty Server and everytime i open a Wicket-Page, i can see the following error on my jetty log:
WARN  - DiskDataStore              - Cannot save page with id '2' because the data file    cannot be opened.
ERROR - DiskDataStore              - /tmp/jetty-0.0.0.0-80-tourney.war-_tourney-any- /wicket.Tourneys-filestore/2gs9iqj4zdjtkerejipyu0co/data (No such file or directory)
java.io.FileNotFoundException: /tmp/jetty-0.0.0.0-80-tourney.war-_tourney-any-/wicket.Tourneys-filestore/2gs9iqj4zdjtkerejipyu0co/data (No such file or directory)
at java.io.RandomAccessFile.open(Native Method)
at java.io.RandomAccessFile.<init>(RandomAccessFile.java:233)
at org.apache.wicket.pageStore.DiskDataStore$SessionEntry.getFileChannel(DiskDataStore.java:410)
at org.apache.wicket.pageStore.DiskDataStore$SessionEntry.savePage(DiskDataStore.java:328)
at org.apache.wicket.pageStore.DiskDataStore.storeData(DiskDataStore.java:176)
at org.apache.wicket.pageStore.AsynchronousDataStore$PageSavingRunnable.run(AsynchronousDataStore.java:348)
at java.lang.Thread.run(Thread.java:636)

Any idea what went wrong? Unix rights are set correctly. I even tried with 777 but no success :(
Comment: Don't know but you could try to change the DiskDataStore temp directory. This is achieved changing the "javax.servlet.context.tempdir" attribute in the servlet context (before wicket starts, for example in a ServletContextListener).
Comment: Do you have an example for changing the DiskDataStore? I have no idea, what to do.
Comment: Try to export give the jvm the property -Djavax.servlet.context.tempdir=/your/dir". Does your webapp name contains special characters ?
Answer: This also happens when you delete the datastore directory while Jetty is running. It still complains even if Jetty is allowed to create a new one.
For me the fix to that problem was to restart Jetty.
Answer: To change the DiskDataStore directory you can use a ServletContextListener:
public class InitListener implements ServletContextListener {
  @Override
  public void contextInitialized(ServletContextEvent sce) {
    final String workDir = sce.getServletContext().getInitParameter("workDirectory"); // Context param with the temp dir path
    sce.getServletContext().setAttribute("javax.servlet.context.tempdir", file); // sets the temp dir (Wicket will read it from here)
  }

  @Override
  public void contextDestroyed(ServletContextEvent sce) {}
}

And this is the neccesary web.xml entries:
<context-param>
  <param-name>workDirectory</param-name>
  <param-value>E:\wicket</param-value>
</context-param>
<listener>
  <listener-class>es.cyum.cruekti.wicket.InitListener</listener-class>
</listener>

Answer: Here is the Wicket API way: org.apache.wicket.settings.IStoreSettings#setFileStoreFolder()
Answer: I figured I would elaborate on Martin's answer since it wasn't immediately obvious to me how to access IStoreSettings.  You can update the data store directory using Wicket's API like this:
public class MyApplication extends WebApplication {
    protected void init() {
        super.init();

        getStoreSettings().setFileStoreFolder(new File("/path/to/directory/"));
    }
}

Although, I wouldn't consider that to be a very good idea.  Since it sounds like Wicket defaults to the value of javax.servlet.context.tempdir, it would be far better to set that property than to hardcode a value in Java.  That way Windows developers can set their own value like C:\Users\lazydaemon\temp, Linux developers can set a value like /home/lazydaemon/tmp/ and server admins can pick something like /var/cache/tomcat-VERSION/Catalina/whatever without any need for code changes or fragile if(configuration==RuntimeConfigurationType.DEVELOPMENT) logic.
So you could either set the property as an argument for when your server starts:
-Djavax.servlet.context.tempdir=/path/to/directory/

Or, if you are starting a Jetty server in code that doesn't get packaged and deployed in your war file, you could set the property in the code that configures and starts Jetty:
System.setProperty("javax.servlet.context.tempdir", "/path/to/directory/");


Array de objetos vazio

Question: Estou com um problema na criação de um array de objetos. Tenho uma função que faz uma requisição ajax e insere objetos dentro de um array num looping.
Acontece que dentro do success da requisição, o array é mostrado no console e através de um alerta da forma certa, mas fora da requisição o alert aparece como um array vazio, [].
        var arrayEvent = [];

        $.ajax({
            type        :   "POST",
            url         :   http_base + "/agendamento/buscaProfessor",
            data        :   {day:day, month:month, year:year},
            cache       :   false,
            dataType    :   "json",
            success :   function(data)
            {
                for (var i = 0; i < data.length; i++){
                    data[i].data = data[i].data.replace(" ", "T");
                    var obj = {title: String(data[i].professor), start: String(data[i].data)};
                    arrayEvent.push(obj);
                }

                /*1*/alert(JSON.stringify(arrayEvent));
                /*1*/console.log(arrayEvent);
            },
            error   :   function(jqXHR, textStatus, errorThrown)
            {
                console.log(textStatus);
            }
        });

        /*2*/alert(JSON.stringify(arrayEvent));
        /*2*/console.log(arrayEvent);

Resultado do alert do stringify do array
Dentro do success da requisição:
/*1*/[{"title":"Professor2","start":"2018-04-26T17:00:00"},{"title":"Professor
1","start":"2018-04-27T17:00:00"}]

Fora:
/*2*/[]

Console.log
/*2*/[]

0:{title: "Professor2", start: "2018-04-26T17:00:00"}
1:{title: "Professor 1", start: "2018-04-27T17:00:00"}
length : 2

/*1*/(2) [{…}, {…}]
0:{title: "Professor2", start: "2018-04-26T17:00:00"}
1:{title: "Professor 1", start: "2018-04-27T17:00:00"}
length:2

Como poderia proceder pra resolver esse problema?
Comment: Se vc quer usar o retorno do Ajax em alguma parte do código fora do success, você deverá fazer uma requisição ao Ajax e esperar a resposta. Usando `.then` você consegue. Algo parecido com esta resposta: https://pt.stackoverflow.com/a/281902/8063
Comment: O Ajax é assíncrono. Quando o script é executado, ao chegar na linha do console.log de fora, o Ajax ainda não respondeu.
Comment: Não entendi. Pelo que pude notar é que o console.log dentro do success retorna normal, 2 objetos na array, e fora dele não retorna nada `[]`
Comment: Obrigado pela resposta. No retorno do console, os valores que retorna dos dois arrays são igual, exceto por um contar como array de um elemento só. Não seria só o caso na declaração do array que algo está incorreto?
Comment: No console.log fora do success ele retorna como se fosse um array vazio (no alert JSON.stringify aparece []), ou de um elemento, com os objetos dentro. Dentro do success, o console.log mostra um array de 2 elementos, e o alert JSON.stringify mostra os objetos dentro do array.
Comment: Então, é o que estou falando, isso não dá certo porque o Ajax é assíncrono. Quando chega na linha do console.log fora do success, o Ajax ainda não foi processado.
Comment: Mas porque já é mostrado o resultado da requisição?
Comment: Esse resultado deve ser o que está dentro do success.
Comment: Onde eu coloco 'Console.log' na pergunta, onde tem /*2*/ corresponde ao resultado do console.log fora do success e onde tem /*1*/ corresponde ao resultado dentro do success. Como tá mostrado lá, ai ta imprimindo no console o resultado da requisição, só que o array ta com um formato diferente.
Comment: O primeiro está em formato de string, me parece, porque usou `JSON.stringify(arrayEvent)`
Comment: Os dois resultados do alert estão com Stringify. E o ultimo código, é o resultado do console.log nos dois casos.
Comment: Isso é coisa do navegador que vai puxar a array atualizada para mostrar no console, mas no JS ela está vazia naquele momento
Comment: Mas veja que mesmo assim ele informa que estava vazia no momento da execução com `[]`
Answer: Basicamente o problema é que uma requisição http é assíncrona, por isso o browser vai passar por todo o bloco da sua função javascript, para depois ir ao servidor.
Por causa disso que o bloco abaixo não funciona.
    /*2*/alert(JSON.stringify(arrayEvent));
    /*2*/console.log(arrayEvent);

Está imprimindo array vazio, pois ainda não houve o retorno do servidor.
Para que aconteça o que você quer, deve ser utilizado o método done, que será executado quando a sua requisição ajax for executada com sucesso.
Segue alteração no seu código com a solução:
    var arrayEvent = [];

    $.ajax({
        type        :   "POST",
        url         :   http_base + "/agendamento/buscaProfessor",
        data        :   {day:day, month:month, year:year},
        cache       :   false,
        dataType    :   "json",
        success :   function(data)
        {
            for (var i = 0; i < data.length; i++){
                data[i].data = data[i].data.replace(" ", "T");
                var obj = {title: String(data[i].professor), start: String(data[i].data)};
                arrayEvent.push(obj);
            }

            /*1*/alert(JSON.stringify(arrayEvent));
            /*1*/console.log(arrayEvent);
        },
        error   :   function(jqXHR, textStatus, errorThrown)
        {
            console.log(textStatus);
        }
    }).done(function(){
        /*2*/alert(JSON.stringify(arrayEvent));
        /*2*/console.log(arrayEvent);
    });

Array de objetos vazio


Serious slow performance when inserting a column in Excel 2016

Question: In Excel 2007 there was no issue but when I hit the below line in Excel 2016, it now takes over a minute each time. There are only 300 rows in the column. All I want to do is cut a column and paste it next to another column.
Selection.Insert Shift:=xlToRight

Sample code is as follows, but I have 30 odd of these so it is taking half an hour.
Columns("E:E").Select
Selection.Cut
Columns("C:C").Select
Selection.Insert Shift:=xlToRight

Any ideas why?
Comment: [How to avoid using Select in Excel VBA](https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba) should speed it up. Test if it takes the same/similar amount of time if you do it manually with ctrl+x/ctrl+v. If yes then it is no programming issue, but an issue with your worksheet and the data it contains.
Comment: Are you sure that you only have 300 rows? This is executed in no time if the sheet is small, but takes forever if a cell  far down/right is filled (maybe accidently).
Comment: Hi, I have tried this and still an issue on line
Selection.Insert Shift:=xlToRight, I even tried using a named range to only select the 300 rows in the column with data and still takes ages
Comment: Have you tried any other methods, like insert the column, then cut and paste it, but just the data.  Also, maybe worth as @FunThomas says, checking what data you have.  Maybe try calculation off for this operation to?
Comment: I ask again: How long does it take if you do it manually with ctrl+x/ctrl+v?
Comment: Could you post the whole code. If it is taking forever, you might have the code in an Event and it should be written differently.
Comment: Yes it takes the same amount of time copying and pasting manually.
Comment: Press Control-Shift - End  - this will take you to the bottom right of the occupied area of the spread sheet. Is that actually row 300?
Comment: Yes it takes the same amount of time copying and pasting manually. Actually I tried just copying one call and pasting and it still took a while. The data in the cell is just 'ID" ! I'm not able to paste full code due to security where I work.
Comment: Nope definitely only 300 rows of data after pressing CTRL+SHIFT+END
Comment: • Do you have any events in VBA if so please show their code. • Did you try to copy paste the data into a completely new workbook and test it their if you got the same issues?
Comment: Yes I copied all the sheets and macros to a new workbook and still the same performance issues. The file itself is only 10MB so not a massive workbook by any means. No events in VBA either. I think it is to do with the fact there is fair bit of data in multiple sheets?
Comment: Well it can can happen if there are many formulas in your sheet especially if they are volatile they can cause a heavy load on re-calculation. Is it slow too if you set calculation to manual before you cut/paste?
Answer: Do you have formulas and maybe even external references? Then please try this:
ActiveWorkbook.UpdateLinks = xlUpdateLinksNever
ActiveWorkbook.UpdateRemoteReferences = False
Application.Calculation = xlManual

ActiveSheet.Columns("E:E").Cut
ActiveSheet.Columns("C:C").Insert Shift:=xlToRight

ActiveWorkbook.UpdateLinks = xlUpdateLinksAlways
ActiveWorkbook.UpdateRemoteReferences = True
Application.Calculation = xlCalculationAutomatic

' If it's faster, then uncomment following line additionally
' Application.CalculateFull

Comment: Thanks very much but unfortunately this did not work. I don;t have any formulas or external references. If I ever find a solution I will update this post
Answer: I had to deal with an Excel xlsx file generated by a Payroll system. Not sure what is causing the slowness on column insert. Inserting a column into a 88,000 row file takes about 25 seconds.
I discovered that if I copy the entire worksheet to a new sheet as values and number formats, the insert column step will run almost instantly. The copy entire worksheet portion takes just 3 seconds! There are no formulas in the file nor conditional formatting.
This is the logic I used:
' Copy source worksheet
Dim rng As Range
Set rng = Worksheets("Sheet1").Cells
rng.Copy ' note that wks.Cells.Copy is very slow

' add new worksheet
Dim newWks As Worksheet
Set newWks = Sheets.Add(After:=ActiveSheet)
newWks.Name = "Values Only"

' paste values and number format into new worksheet
newWks.Range("A1").Select
' xlPasteValues is fast too
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
' if I also include a xlPasteFormats then the insert column will become very slow once again
'  Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

' now the column insert is blazingly fast!
newWks.Columns(14).Insert
newWks.Cells(1, 14).Interior.ColorIndex = 35
' etc.


White space between parent and child div on some devices/browsers

Question: I can't seem to remove the white space between the parent and child div.

It seems that this white line is not visible on all devices/browsers. The bug appears mostly on mobile
All sizes are specified in pixels so it doesn't seem to be half a pixel that is causing the bug.

.parent {
  border: 2px solid;
  border-color: rgb(0, 0, 0);
  height: 80px;
}

.child {
  height: 80px;
  background-color: rgb(0, 0, 0);
}

Comment: can you give an example on which devices/browsers this is happening? Would make it easier to reproduce it
Comment: @MaxHimes - No worries - all is forgiven! ;-) Thank you for adding the code to your question.
Comment: In the code you submitted, the top white space you mention is not visible.
Comment: As I said this white space is not visible on all devices Snorlax
Comment: @Rounin-StandingwithUkraine I'm sorry, it was a mistake on my part, I thought I had to accept your edit for it to be effective, but obviously I did the opposite. I am a new user of SO...
Comment: try using position absolute and set top: 0; right: 0
Comment: I'm also not seeing the issue but I can make some suggestions about the code because in some cases you get unexpected things happen when the code is not written well: don't put div tag inside a tag, always clear floating elements, the math on the .rating div doesn't add up (30px line-height + 7px padding bottom + 5px padding-top = 42 but the height is set to 40px)
Comment: Thank you @Raul, I still got the issue if I set height to a correct value. If I remove the a tag the problem is still here...
Comment: did you try with `box-sizing: border-box` for both div and `margin: -2px` for child div?
Comment: I can see the problem in microsoft edge. test ok: with no border or with border >= 4px. with 2px there is a space on top and left side, with 3px there is space on all side. It seems a bug. On mobile test with android chrome and it work. Is this the behavior you see?
Answer:
This white space is not visible on all devices, I don't know if it's related to the resolution or the browser [...] The problem seems to occur more often on mobile than on PC

It's a rounding discrepancy. Probably related to this line:
font-size: 1.75vw;

The browser on each device is calculating a number of pixels - on some devices the browser ends up with a result which is 1px less than on other devices.
The fix (and I appreciate this will require some design thinking) is to use a more explicit value which is less likely to end up with a possible fraction of a pixel (which then needs to be rounded up or down).
I'd be tempted to start by giving .rating:

an explicit height; and
an explicit line-height
Comment: It doesn't seem to work if I set the font size to 26 pixels, the problem is still there...
Comment: I've added a suggestion to the bottom of my answer above - it might help if you declare an explicit `height` and `line-height` for `.rating`.
Comment: I tried to set the heights of the children and the parents, to set the line-height but nothing solved the problem
Answer: this could be a half pixel, which is being behaved differently with each browser,
it could be seen when zooming in, sometimes it couldn't
https://www.simonbattersby.com/blog/browsers-and-fractional-pixels/
Comment: Thanks for the share ! I simplify the problem it look like an half pixel is not causing the problem..
Comment: Yes by zoom-in into browser I can see the gap. But using outline or box-shadow instead of border, issue can be resolve.
Answer: if you cannot remove it, hide it:

.parent {
  border: 2px solid;
  border-color: rgb(0, 0, 0);
  height: 80px;
}

.child {
  height: 80px;
  background-color: rgb(0, 0, 0);
  box-shadow: 0 0 0 1px rgb(0, 0, 0); /* a tiny box-shadow to cover the gap */
}

Answer: You can to use outline instead of border

.parent {
  outline: 2px solid;
  outline-color: rgb(0, 0, 0);
  height: 80px;
}

.child {
  height: 80px;
  background-color: rgb(0, 0, 0);
}

Answer: Your code is not enough to show your confuse.
It should contain global CSS settings, like resized font-size, line-height, div's display attribute (like inline-block) ...
And in odd number DPR mobile screen, with the global font settings, this appearance will be more common.
Check and resize global or root settings.
Answer:

.parent {
   height: 80px;
}

.child {
   height: 80px;
   background: black;
}

That's more then enough
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


remover listas de um dicionário

Question: tenho um código que testa varias combinações que são geradas, mas estou com um problema de erro de memória. acho que a causa disso que que o dicionário fica muito grande para ser processado, então pensei que a solução poderia ser testar a lista atual e ao mesmo tempo remover a antiga mas não sei algum comando que se encaixe com essa situação. sou novato em Python
<code>#gera a lista/dicionário
for subset in genComb:
    permsList.append(subset)

#testa se o item da lista é igual a uma variavel que é definida no inicio
while desco != senha:
    desco = str(permsList[num]).replace("'", '')
    desco = desco.replace(",", '')
    desco = desco.replace(" ", '')
    desco = desco.replace("(", '')
    desco = desco.replace(")", '')
    num += 1
</code>
Comment: qual o erro de memória está dando?
Comment: line 20, in senhas
    permsList.append(subset)
MemoryError
Answer: Provavelmente é pelo tamanho mesmo, se você ta testando todas as combinações possiveis por exemplo de 13 caracteres diferentes ja daria 6.227.020.800 elementos na sua lista e o python tem como limite 536.870.912.
Comment: sabe de algum comando que possa apagar os elementos que ja foram usados?
Comment: para lista temos o .pop() que remove o ultimo elemento e mostra ele, o .remove() que remove o elemento que vc especificar o .clear() que remove todos.

remover listas de um dicionário


Evaluate the integral $\int_{r\leq R}\frac{\mathrm dr}{r^2-k^2}$

Question: I try to evaluate:
$$\int_{0\leq r\leq R}\frac{\mathrm dr}{r^2-k^2}$$
Where $k$ is a complex number with positive imaginary part and non zero real part. $R$ is a positive number.
By Cauchy's theorem I could say that the integral on a contour away from $k^2$ is $0$, but this doesn't really help in  the explicit computation.
I could also try to find a primitive directly, but that would be the $\arctan$ complex function which I'm not sure how to handle.
Any help welcome.
Comment: $arctan$ isn't what you need. Try partial fractions.
Comment: Is the domain of the integral $0 \le r \le R$ or $-\infty < r \le R$?
Comment: $0\leq r\leq R$ is the right domain
Answer: Use the identity $\displaystyle \frac{1}{2k} \left[ \frac{1}{r-k} - \frac{1}{r+k} \right] = \frac{1}{r^2 - k^2}.$
Comment: When $R$ goes to $\infty$, the integral equals some constant times $\log(-1)$. This is confusing: $\log(-1)$ could be $i\pi$ as well as $-3i\pi$, does it mean that the integral is not well defined?


jQuery Deconstruction | Calling mechanism for $.ajax()

Question: Where is ajax defined in the source and how it is bound to the jQuery object?
I ran a search for it and found it on 5993 inside this thing called:
jQuery.extend({

where fn is an alias for prototype.
How does Jquery know were to find ajax() when you call it.  More generally how does extend work?
http://api.jquery.com/jQuery.ajax/
http://code.jquery.com/jquery-latest.js
Comment: Open the uncompressed jQuery source and search for `"ajax:"`. It's the first match.Notice that this method is added via `jQuery.extend()`, not `jQuery.fn.extend()`. This is because it's a static method, defined on the `jQuery` object itself, rather than a jQuery method.
Comment: A great place to view jQuery internals is at this website: http://james.padolsey.com/jquery/#v=1.7.2&fn=jQuery.ajax. You just search for the function you want, and it displays it. It can even pull the latest version of jQuery from github.
Comment: So `$.` the dot specifies a method is to be used....and ajax() has been copied to the prototype at some point...it is a prototyped method on the jQuery object.
Comment: `jQuery.extend = jQuery.fn.extend`
Answer: The extend method copies properties from one object to another.  With just one argument, it copies properties to this, so in this case it's copying the properties to the fn object itself.
edit in my copy of the 1.7.1 code, the "ajax" method actually is copied in by jQuery.extend(), not jQuery.fn.extend().  It's the same function; extend is bound to both the jQuery object and to the "fn" object (the internal constructor function).  When it's called as jQuery.extend({ ... }) therefore, the properties are copied to the jQuery object (function) itself.
Comment: this relates to the previous question I asked but I'm not so sure about it...I think `this` might actually point to the containing object of the function...and not the function object ( or JQuery object have you) itself...that probably does not make sense...I'm going to perform an experiment and figure this out once and for all.
Comment: `return new jQuery.fn.init( selector, context, rootjQuery );`...I think returns something that points to `jQuery` instantiated.
Comment: they are basically calling new on a prototype...I don't think this sort of thing is covered in textbooks.


constexpr and function body = delete: what's the purpose?

Question: According to the [dcl.constexpr/3]:

The definition of a constexpr function shall satisfy the following requirements:
  [...]
  - its function-body shall be = delete, = default, or [...]

This means that the following class snippet is valid:
struct S {
    constexpr void f() = delete;
};

What's the purpose of having a deleted constexpr function?
What are the benefit of defining it constexpr if any?
I can't figure out any reason, but the fact that maybe it's easier to allow it than to forbid it in the standard.
Comment: `delete`ing any function is a simple way to disable a particular overload. I guess it should be applied for a `constexpr` family of functions as well.
Comment: `constexpr` for functions returning `void` is also *fun*.
Comment: @Jarod42 Touché. Used to create a mvce and that's fine for it, but it makes sense indeed.
Answer: This was based on CWG 1199. Daniel Krügler wrote:

it could be useful to allow this form in a case where a single piece of code is used in multiple configurations, in some of which the function is constexpr and others deleted; having to update all declarations of the function to remove the constexpr specifier is unnecessarily onerous.
Comment: Possible [example](http://coliru.stacked-crooked.com/a/e29e6fb25d185488) ?
Comment: Sooner or later you must teach me how to search through the issues. I've never managed to find out what I was looking for!! That said, I cannot figure out such a case. Can you provide a minimal example?
Comment: @skypjack Not sure, tbh.
Answer: I guess the purpose is the same as with any =delete:
If you inherit from a class, but don't want the function to be available in subclasses.
E.g.:
class P{
    public:
    constexpr int foo(){return 42;}

};

class C : public P{
    public:
    constexpr int foo() = delete; //(*)
};

int main() {
    P p;
    cout << p.foo(); //ok

    C c;
    cout << c.foo(); //Compiler error only if line (*) is present.
    return 0;
}

Even though i can't tell you right now where it is usefull - but i also can't see any reason right now why it should be forbidden.
Comment: The result is the same even though you remove `constexpr` from `C`.


Left join and case clause LINQ in Entity Framework

Question: I am needing to make a left join and also use the select operator case.
My LINQ basic is this and works:
resultado.Dados =
    (
        from a in db.AgendaHorario
        join b in db.Agenda on a.AgendaID equals b.AgendaID
        join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
        from e in d.DefaultIfEmpty()
        select new
        {
            id = a.AgendaHorarioID,
            Medico = e.Identificacao
        });

But I must add a new field and it should be formatted, then my LINQ looked like this:
resultado.Dados =
  (
    from a in db.AgendaHorario
    join b in db.Agenda on a.AgendaID equals b.AgendaID
    join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
    from e in d.DefaultIfEmpty()
    select new
    {
        id = a.AgendaHorarioID,
        Medico = e.Identificacao,
        start = a.Horario.ToString("yyyy-MM-dd HH:mm:ss")
    }
  );

This error happens:
LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated into a store expression.

If you add the ToList() or AsEnumerable() in db.AgendaHorario.ToList() and db.Agenda.ToList() and db.Profissional.ToList() error that appears is:
Object reference not set to an instance of an object.

What should I do to have a left join with case and fields and formatted fields
Answer: try to set the string in a variable then assign it to your query like this:

var myValue = Horario.ToString("yyyy-MM-dd HH:mm:ss");

resultado.Dados =   (
from a in db.AgendaHorario
join b in db.Agenda on a.AgendaID equals b.AgendaID
join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
from e in d.DefaultIfEmpty()
select new
{
    id = a.AgendaHorarioID,
    Medico = e.Identificacao,
    start = myValue
}   );

Comment: Sorry I did not understand. The code you passed does not work.
Comment: the first line of the code above needs to be supplied by your db.AgendaHorario so you need to modify that line to get your value
Answer: Try this:
resultado.Dados =
(
    from a in db.AgendaHorario
    join b in db.Agenda on a.AgendaID equals b.AgendaID
    join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
    from e in d.DefaultIfEmpty()
    select new
    {
        id = a.AgendaHorarioID,
        Medico = e.Identificacao,
        start = a.Horario
    }).AsEnumerable().Select(x => new
    {
        id = x.id,
        Medico = x.Medico,
        start = x.start.ToString("yyyy-MM-dd HH:mm:ss")
    }
);


What does +obj.length mean in Underscore.js's each method?

Question: I am trying to read underscore.js. I'm going through the var each = _.each = _.forEach method.
I understand strict equals (===), but I do not understand what +obj.length means.
else if (obj.length === +obj.length)

Here is a link to the code, and here is the full method:
var each = _.each = _.forEach = function(obj, iterator, context) {
    if (obj == null) return;
    if (nativeForEach && obj.forEach === nativeForEach) {
      obj.forEach(iterator, context);
    } else if (obj.length === +obj.length) {
      for (var i = 0, l = obj.length; i < l; i++) {
        if (iterator.call(context, obj[i], i, obj) === breaker) return;
      }
    } else {
      for (var key in obj) {
        if (_.has(obj, key)) {
          if (iterator.call(context, obj[key], key, obj) === breaker) return;
        }
      }
    }
  };

Comment: I think it ensures that `obj.length` is a number.
Comment: possible duplicate of [Whats the significant use of Unary Plus and Minus operators?](http://stackoverflow.com/questions/5450076/whats-the-significant-use-of-unary-plus-and-minus-operators)
Answer: This is a unary + operator. It converts its argument to a number. Basically that line checks if obj.length is a number.

What does +obj.length mean in Underscore.js’s each method?


Ajax/progress bar not working

Question: I'm trying to have a progress bar until ajax request has ended (this is text field + a canvas image captured from laptop webcam). But there is no progress on my bar... It appears then, when it finished, it disappear, but no visual progression on...
<code> $("#FormSubmitPhotoCapture").click(function (e) {

        e.preventDefault();

        if($("#form_titre_photo_capture").val()==="")
        {
            alert("Veuillez saisir un titre");
            return false;
        }
        var canvas = document.getElementById('canvascapt');
        var context = canvas.getContext('2d');
                var dataURL = canvas.toDataURL();
                document.getElementById('imagecaptimg').src = dataURL;
        var myData = {titre : $("#form_titre_photo_capture").val(), image_capture : "" + dataURL + ""}
        jQuery.ajax({
                beforeSend:function(x){
                    $('#progression').html("<progress id='bar' value='0' max='100'></progress>").show();
                        },
            type: "POST",
            url: "captureimg",
            dataType:"text",
            data:myData,
            success:function(response){
            $('#bar').val(100);
            $("#responds").before(response);
            $("#form_titre_photo_capture").val('');
                        $("#webcam_photo_capture").empty();
                        $('#FormSubmitPhotoCapture').hide();
            },
            complete: function() {
                        $('#bar').hide();
                    }
        });
    });
</code>
Any idea please?
Answer: You're not listening for progress events. This should work:
<code>$.ajax({
  xhr: function()
  {
    var xhr = new window.XMLHttpRequest();
    //Upload progress
    xhr.upload.addEventListener("progress", function(evt){
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        //Do something with upload progress
        console.log(percentComplete);
      }
    }, false);
    //Download progress
    xhr.addEventListener("progress", function(evt){
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        //Do something with download progress
        console.log(percentComplete);
      }
    }, false);
    return xhr;
  },
  type: 'POST',
  url: "/",
  data: {},
  success: function(data){
    //Do something success-ish
  }
});
</code>

Ajax/progress bar not working


Data binding from a partial view in AngularJS

Question: I want to bind a data from partial view to index it is binding in same view but not other view.I tried like this

    $scope.GetDelete = function (cy_name) {
        $scope.items = cy_name;
        //$scope.newItem = { title: '' };
        alert($scope.items);

    }
<button type="button" class="btn btn-xs btn-danger margin-inline" data-toggle="modal" data-target="#dvDelete" ng-click="GetDelete('@item.cy_name')"></button>

                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    ×
                                </button>

Are you sure?

{{items}}

                                <button type="button" class="btn" data-dismiss="modal">Cancel</button>
                                <button type="button" class="btn btn-danger"ng-click="GetDelete('Test')">Delete</button>

Modal is showing but nothing data
Comment: Does the modal come within the scope of the controller?
Answer: For the scope variable to be available within your modal, the modal code needs to fall within the scope of the controller. If it is defined outside the scope, the modal template wouldn't be aware of the existence of the scope.

 angular.module('myapp', [])
   .controller('myctrl', function($scope) {

     $scope.GetDelete = function(cy_name) {
       $scope.items = cy_name;
       //$scope.newItem = { title: '' };
       alert($scope.items);
     }
   });

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

Are you sure?

{{items}}

        <button type="button" class="btn" data-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-danger" ng-click="GetDelete('Test')">Delete</button>

<button type="button" class="btn btn-xs btn-danger margin-inline" data-toggle="modal" data-target="#dvDelete" ng-click="GetDelete('@item.cy_name')">
</button>

Here is a working snippet
Comment: But the button click is not the same view
Comment: Then you should create a directive out of the modal and pass on the scope to it
Comment: tankyou let me try


Find the maximum likelihood estimator

Question: Suppose that $X$ follows a distribution with p.d.f. given by
\begin{equation}
f(x;\theta)=\dfrac{2xe^{-(x/\theta)^2}}{\theta^2}
\end{equation}
for $x>0$ Assume that $X_1,X_2,...,X_n$ is a random sample of size $n$ from the distribution. Find the maximum likelihood estimator, $\tilde{\theta}_{ML}$, of $\theta$
I'm having issues with how this simplifies. Can someone check my work?
\begin{equation}
L(\theta)=\prod^n_{i=1}f(x;\theta)=\frac{2^n}{\theta^{2n}}\prod^n_{i=1}x_ie^{-\left(\dfrac{\sum^n_{i=z}x_i^2}{\theta^2}\right)}
\end{equation}
\begin{equation}
log(L(\theta))=nlog(2)-2nlog(\theta)+\sum^n_{i=1}log(x_i)-\frac{\sum^n_{i=1}x_i^2}{\theta^2}
\end{equation}
\begin{equation}
L'(\theta)=-\frac{2n}{\theta}+\frac{2\sum^n_{i=1}x_i^2}{\theta^3}
\end{equation}
I think I have done this incorrectly because I don't know how I would isolate $\theta$. Any help would be appreciated.
Comment: (1) Should be $\frac{1}{\theta^2} \sum_i x_i^2$ not $\frac{1}{\theta^2} \sum_i x_i$ and (2) What do you mean by isolate $\theta$?
Comment: In your final equation it is legitimate to multiply both sides by $\theta^3$ to clear the denominators.  The resulting equation is trivial to solve.  Incidentally, in the penultimate formula for $\log(L(\theta))$ the terms in the first summation should be $\log(x_i)$: no squares are involved.  (This will not affect the likelihood equations, though.)
Comment: When $\theta^2$ moves outside the product doesn't it become $\theta^{2n}$? When I use the log rules should I keep $\theta^2$? As far as isolating $\theta$ is concerned, when I set the last equation equal to $0$ I need to solve for $\theta$ to find the likelihood estimator right?
Answer: You can do an easy check of your answer by writing the density as an exponential family.  It has sufficient statistic $x^2$, which means that the maximum likelihood estimate must be $\sqrt{\frac{\sum_i x_i^2}{n}}$ as you found.

Find the maximum likelihood estimator


Silverlight Multi-state toggle button

Question: Is there such a thing as a multi-state togglebutton in silverlight? I've tried retemplating radio buttons in a group, but I'd like to make a storyboard that works across the toggle states and because radio buttons are separate objects I'm stuck(I'm trying to make it look like the iphone toggle button, except multi-state)
Answer: You probably know of OOTB checkbox control:
http://samples.msdn.microsoft.com/Silverlight/SampleBrowser/#/?sref=System.Windows.Controls.CheckBoxEx
That was probably useful, but for one of my projects, it had to be similar functionality but using an input box instead so I used custom UserControl approach. I'd highly recommend it.
In the constructor of usercontrol, after InitializeComponent(); you can specify the values that affect the UI. Time permitting I'll annotate some xaml+cs.
Here's some code:
XAML:
<UserControl x:Class="SilverlightApplication1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.Resources>

        </Grid.Resources>
        <TextBox x:Name="BackgroundTextBox" IsEnabled="True" BorderBrush="White" Foreground="{x:Null}" Visibility="Visible" Style="{StaticResource TernaryTB}"/>
        <TextBox x:Name="TernaryTextBox" Style="{StaticResource TernaryTB}" GotFocus="TernaryTextBox_GotFocus"/>
    </Grid>

</UserControl>

CS:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;

namespace SilverlightApplication1
{
    public partial class MainPage : UserControl
    {
        private int current;
        public int Current
        {
            get
            {
                return current;
            }
            set
            {
                current = value;
            }
        }

        public struct DataStructure
        {
            private string label;
            private Color color;
            private Color forecolor;

            public DataStructure(string label, Color c, Color c2)
            {
                this.label = label;
                this.color = c;
                this.forecolor = c2;
            }

            public string Label
            {
                get { return label; }
                set { label = value; }
            }
            public Color Color
            {
                get { return color; }
                set { color = value; }
            }
            public Color Forecolor
            {
                get { return forecolor; }
                set { forecolor = value; }
            }

        }
        IList<DataStructure> DataStructureArray;

        public MainPage()
        {
            InitializeComponent();
            current = 0;
            int i = 0;

            DataStructureArray = new Collection<DataStructure>
            (new[] {
                 new DataStructure ("A", Colors.Red,Colors.Green),
                 new DataStructure ("B", Colors.Green,Colors.Blue),
                 new DataStructure ("C", Colors.Blue,Colors.Red)
            });

            foreach (DataStructure listItem in DataStructureArray)
            {
                if (i == current)
                {
                    TernaryTextBox.Text = listItem.Label;
                    TernaryTextBox.Background = new SolidColorBrush(listItem.Color);
                    break;
                }
                i++;
            }
        }
        public MainPage(IList<DataStructure> NewDataStructureArray)
        {
            int i = 0;
            DataStructureArray = new Collection<DataStructure>();
            foreach (DataStructure ds in NewDataStructureArray)
            {
                DataStructureArray.Add(new DataStructure(ds.Label, ds.Color, ds.Forecolor));
                i++;
            }
        }

        private void TernaryTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            int i = 0;
            current = (current + 1) % 3;

            foreach (DataStructure listItem in DataStructureArray)
            {
                if (i == current)
                {
                    TernaryTextBox.Text = listItem.Label;
                    TernaryTextBox.Background = new SolidColorBrush(listItem.Color);
                    TernaryTextBox.Foreground = new SolidColorBrush(listItem.Forecolor);

                    BackgroundTextBox.Focus();
                    break;
                }
                i++;
            }
            BackgroundTextBox.Focus();
        }
    }
}

To test, simply add a brand spanking usercontrol to your project, copy paste my code; to test my code in isolation, open App.xaml.cs and simply replace:
this.RootVisual = new MainPage();

with:
this.RootVisual = new <Whatevernameyouchosefortheusercontrol>();

to see it in action
Comment: Thanks. I'll think about this
Answer: The standard Silverlight CheckBox as an IsThreeState property. The default visual for the third state is "-", so you might have to customise the visuals.
A CheckBox is a specialisation of a ToggleButton.

Silverlight Multi-state toggle button


the Default 'List' constructor isn't available when null safety enabled

Question: i have an error when i write the code
heres the code i wrote

class ProgressHUD extends StatelessWidget {

  final Widget child;
  final bool inAsyncCall;
  final double opacity;
  final Color color;
  final Animation<Color> valueColor;

  ProgressHUD({
    required Key key,
    required this.child,
    required this.inAsyncCall,
    this.opacity = 0.3,
    this.color = Colors.grey,
    required this.valueColor,
  })  : super(key: key);

  @override
  Widget build(BuildContext context) {
    List<Widget> widgetList = new List<Widget>();
    widgetList.add(child);
    if (inAsyncCall) {
      final model = new Stack(
        children: [
          new Opacity(
            opacity: opacity,
            child: ModalBarrier(dismissible: false, color: color),
            ),
            new Center(
              child: new CircularProgressIndicator()
            ),
        ],
      );
      return Stack(children: widgetList,);
    }
  }
}

The error message that appear is on Build says The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type.
Then the Second error is in List says 'list' is deprecated and shouldnt be used

can someone help me to fix it thanks before
Answer: List<Widget> widgetList = new List<Widget>();
widgetList.add(child);

needs to be
final widgetList = [child];


I'm using Webform. How can I use JavaScript in it?

Question: I am using webform. I'm going to create to fields. First one should be taxonomy term name, and second one should be taxonomy term values. In this case I'm trying to use javascript. When you choose a category in first field, it should be seen categories acording first one. For example: when you choose "animals" category in first field, it should be seen "bear", "lion", "sparrow" and other categories in second. When you choose "fruits" category in first field it should be seen "apple", "bananas", "ananas" and other categories in second. How to solve this problem?
Answer: You should try Webform conditional module.

This modules enhances the existing Conditional Rules of the Webform
  Module. It adds the ability to make components dependent on select
  components(i.e. listboxes, radio buttons, and checkboxes) that appear
  on the same page.

Screencast Demo
View a demonstration form


How can i calculate the height of number in this triangular?

Question: Given this triangular:
$$1$$
$$2,3$$
$$4,5,6$$
$$7,8,9,10$$
$$.............$$
Now, how can i calculate the height of number of some number in this triangular? (Namely, how can i find formula for the height of $n$?)
Comment: This is related to the Cantor pairing function, which is related to how to add up $1 + 2 + 3 + \dots m$.
Answer: For a given value $n$ there exist $h$ such that
\begin{eqnarray*}
\frac{h(h-1)}{2} < n \leq \frac{h(h+1)}{2}.
\end{eqnarray*}
Now treat the the right hand in equality as a quadratic in $h$ and solve to get
\begin{eqnarray*}
h = \left\lceil \frac{-1 + \sqrt{1+8n}}{2} \right\rceil.
\end{eqnarray*}
Comment: How it's give the line of n?
Comment: The answer is good, but I think it may be confusing to OP because it uses the symbol $n$ differently than in the question. In the question, $n$ is a known value and the unknown value to be found is its unnamed "height". This answer uses $m$ as the name of the known value and $n$ as the unknown value to be found. It might help if the notation were consistent with the question and were carefully defined (i.e., say which variable is the "number" and which is the "height").
Comment: @DavidK Thanks for the comment; I have changed the variable names. & thanks for getting the lciel & rciel to look right $ \ddot \smile$
Answer: The first entry in the $n$-th row is $\frac{n(n-1)}{2}+1$ and the last is $\frac{n(n+1)}{2}$ so in order to find the row of the number $x$ you have to find $n$ such that
$$\frac{n(n-1)}{2}+1 \leq x \leq \frac{n(n+1)}{2}$$
Answer: Pointers:

There are $n$ numbers in row $n$.
The last number of the $n^{\text{th}}$ row is $\dfrac {n(n+1)}{2}$.
The first number in the $n^{\text{th}}$ row is $\dfrac{n(n-1)}{2}+1$.

To calculate the row in which any number $x$ lies, just check the triangular number nearest to it and bigger than it, and it lies in the row number $n$ corresponding to that triangular number.
Comment: It's not clear how you get the line from this, can you explain me it?
Comment: @MasterQuestion See the last number in every row. You can see that it is the nth triangular number. Now, the first number in the row is the (n-1)th triangular number +1. So, a Number has to lie between this range only.
Comment: @MasterQuestion Now, the upper bound for a number to be in the nth row is the nth triangular number. So, we check using this criteria itself.
Comment: @MasterQuestion Hence, given a number $x$ we check the closest triangular number to x and bigger than it. It will correspond to some row n because the nth triangular number is n(n+1)/2. Then, we can conclude that $x$ will also be in row $n$.
Comment: @MasterQuestion You can accept my answer if it helped you.
Answer: To find the row that $n$ is on, double $n$, take the square root, and find the nearest integer.
Comment: How you got it?
Comment: and, what I will get if the square is "something.5" ?
Comment: Hint: $(n+\dfrac{1}{2})^2=n^2+n+\dfrac{1}{4}$
Answer: Define a function $h(m)$ recursively:
$h(1) = 1$
Let $h(m)$ be defined.
If $m + 1 \le \dfrac {h(m)(h(m)+1)}{2}$ then $h(m+1) = h(m)$
else
$\qquad \qquad \qquad \qquad \qquad \qquad \qquad \,   h(m+1) = h(m) + 1$

This doesn't provide an explicit formula, but I'm pretty sure that a few lines of code in a (suitable) programming language will do the trick. So that is reassuring.
OK, here is some code. I got some help from python experts; see this stackoverflow Q/A link. Note that this code also gives the row position of each number:
def daHB(m):
    if m == 1:
        return {'rowNum':1, 'posNum':1, 'TriNum':1}
    else:
        r = daHB(m-1)
        if m <= r['TriNum']:
            return {'rowNum':r['rowNum'], 'posNum':r['posNum'] + 1, 'TriNum':r['TriNum']}
        else:
            TriangularNum = (r['rowNum']+1)*(r['rowNum']+2)  // 2
            return {'rowNum':r['rowNum'] + 1,'posNum':1, 'TriNum':TriangularNum}

for n in range(1, 33):
    print (n, daHB(n))

OUTPUT
1 {'rowNum': 1, 'posNum': 1, 'TriNum': 1}
2 {'rowNum': 2, 'posNum': 1, 'TriNum': 3}
3 {'rowNum': 2, 'posNum': 2, 'TriNum': 3}
4 {'rowNum': 3, 'posNum': 1, 'TriNum': 6}
5 {'rowNum': 3, 'posNum': 2, 'TriNum': 6}
6 {'rowNum': 3, 'posNum': 3, 'TriNum': 6}
7 {'rowNum': 4, 'posNum': 1, 'TriNum': 10}
8 {'rowNum': 4, 'posNum': 2, 'TriNum': 10}
9 {'rowNum': 4, 'posNum': 3, 'TriNum': 10}
10 {'rowNum': 4, 'posNum': 4, 'TriNum': 10}
11 {'rowNum': 5, 'posNum': 1, 'TriNum': 15}
12 {'rowNum': 5, 'posNum': 2, 'TriNum': 15}
13 {'rowNum': 5, 'posNum': 3, 'TriNum': 15}
14 {'rowNum': 5, 'posNum': 4, 'TriNum': 15}
15 {'rowNum': 5, 'posNum': 5, 'TriNum': 15}
16 {'rowNum': 6, 'posNum': 1, 'TriNum': 21}
17 {'rowNum': 6, 'posNum': 2, 'TriNum': 21}
18 {'rowNum': 6, 'posNum': 3, 'TriNum': 21}
19 {'rowNum': 6, 'posNum': 4, 'TriNum': 21}
20 {'rowNum': 6, 'posNum': 5, 'TriNum': 21}
21 {'rowNum': 6, 'posNum': 6, 'TriNum': 21}
22 {'rowNum': 7, 'posNum': 1, 'TriNum': 28}
23 {'rowNum': 7, 'posNum': 2, 'TriNum': 28}
24 {'rowNum': 7, 'posNum': 3, 'TriNum': 28}
25 {'rowNum': 7, 'posNum': 4, 'TriNum': 28}
26 {'rowNum': 7, 'posNum': 5, 'TriNum': 28}
27 {'rowNum': 7, 'posNum': 6, 'TriNum': 28}
28 {'rowNum': 7, 'posNum': 7, 'TriNum': 28}
29 {'rowNum': 8, 'posNum': 1, 'TriNum': 36}
30 {'rowNum': 8, 'posNum': 2, 'TriNum': 36}
31 {'rowNum': 8, 'posNum': 3, 'TriNum': 36}
32 {'rowNum': 8, 'posNum': 4, 'TriNum': 36}

Comment: It looks interesting, you know perhaps a C language function (in the MATH library) that does it?
Comment: @mast No - just trying to get up to speed with python...


Find the gradient of $f^*(x)=\langle (\nabla f)^{-1}(x),x)\rangle-f( (\nabla f)^{-1}(x))$ for $x \in \mathbb{R^n}$

Question: I am stuck at the following exercise which serves as a preparation for the upcoming exam:

Let $U \subset \mathbb{R}^n$ be open and $f \in C^2(U, \mathbb{R})$ such that $\det Hf(x) \neq 0, \forall x \in U$ and $\nabla f: U \to \nabla f(U) =:V$ bijective.

Under the above assumptions the function $f^*: V \subset \mathbb{R}^n \to \mathbb{R}$ given by $$f^*(u):=\langle (\nabla f)^{-1}(u),u)\rangle-f( (\nabla f)^{-1}(u)) \tag{*}$$
is clearly well defined and $f^* \in C^1(V, \mathbb{R})$ thanks to the Hessian Matrix of $f$ being invertible and thus $\nabla f$ is a local diffeomorphism. The bijective nature of $\nabla f$ makes $(\nabla f)^{-1}$ a class $C^1$ function.

My problem: I am supposed to find the gradient of $f^*$, in fact I am supposed to verify the identity: $$(\nabla f^*)(u)=(\nabla f)^{-1} (u) \tag{$\alpha$} $$
My approach: Let $u=(u_1, \dots , u_n) \in \mathbb{R}^n$ then it makes sense to only see if the statement in ($\alpha)$ holds for an arbitrary $i \in \lbrace 1, \dots , n \rbrace$.
My problem is that I know nothing about how $(\nabla f)^{-1}$ looks like, so I thought the best attempt would be to just let it be in an abstract form.
Let $h(u):=\langle (\nabla f)^{-1}(u),u)\rangle$ then I assume $h(u)$ looks like $$ h(u)=(\nabla f)_1^{-1}(u)*u_1 + \dots + (\nabla f)_i^{-1}(u)*u_i + \dots + (\nabla f)_n^{-1}(u)* u_n \\ \implies \frac{\partial h(u)}{u_i}=\frac{\partial(\nabla f)_1^{-1}(u)}{\partial u_i}u_1+ \dots + \frac{\partial(\nabla f)_i^{-1}(u)}{\partial u_i}u_i + (\nabla f)_i^{-1}(u)+ \dots + \frac{\partial (\nabla f)_n^{-1}(u)}{\partial u_i}u_n$$
If I have made no mistakes, all there is left to do is to check the second expression in (*) and hope that it annihilates the partially differentiated terms in my expression above. But all I get is: $$\frac{\partial f(( \nabla f^{-1})(u))}{\partial u_i}= \frac{\partial f}{\partial u_i}( \nabla f)^{-1}(u) \cdot \frac{\partial(\nabla f)_i^{-1}}{\partial u_i}(u)$$
So it would be nice if the first term would simplify to $u_i$ but I really don't see it.
Any help or simplification would be appreciated.
Comment: Ok. Then I have a solution for you.
Comment: I do not understand what is $f^{-1}$ since $f$ can not be bijective ?
Comment: @Nicolas $f$, is not bijective, but $\nabla f$ is, thus we introduce $(\nabla f)^{-1}$ the inverse of $\nabla f$, I did correct the parentheses in some cases to avoid confusion
Comment: @Nicolas I would enjoy to see your solution, I couldn't advance any further on this problem.
Comment: Yes, I am writing it, but it is long, sorry! I think to post it in five minutes.
Answer: I propose a solution which is coordinates free (the proof will hold in infinite dimension).
By definition of the differential, if $f:\mathcal{U}\longrightarrow\mathbb{R}$ is differentiable at the point $u\in\mathcal{U}$, then for all $h\in\mathbb{R}^n$ such that $u+h\in\mathcal{U}$, we have
$$f\left(u+h\right)
=f\left(u\right)+\underbrace{\mathrm{d}f\left(u\right)}_{\in\mathcal{L}\left(\mathcal{U};\mathbb{R}\right)}\left[h\right]+o\left(h\right)$$
where $o\left(h\right)=\|h\|\varepsilon\left(h\right)$ with $\varepsilon\left(h\right)\rightarrow 0$ when $h\rightarrow0$.
Now we can define the gradient $\nabla f\left(u\right)\in\mathbb{R}^n$ of $f$ at the point $u\in\mathcal{U}$ as
$$\left\langle\nabla f\left(u\right),h\right\rangle
=\mathrm{d}f\left(u\right)\left[h\right]\in\mathbb{R}.$$
This definition holds for any Hilbert space.
Now we differentiate $f^*$ assuming that $\left(\nabla f\right)^{-1}$ is differentiable on $\mathcal{U}$ :
$$f^*\left(u+h\right)
=\left\langle\left(\nabla f\right)^{-1}\left(u+h\right),u+h\right\rangle-f\left(\left(\nabla f\right)^{-1}\left(u+h\right)\right)$$
$$=\left\langle\left(\nabla f\right)^{-1}\left(u\right)+\mathrm{d}\left(\left(\nabla f\right)^{-1}\right)\left(u\right)\left[h\right]+o\left(h\right),u+h\right\rangle-f\left(\left(\nabla f\right)^{-1}\left(u\right)+\mathrm{d}\left(\left(\nabla f\right)^{-1}\right)\left(u\right)\left[h\right]+o\left(h\right)\right)$$
$$=\left\langle\left(\nabla f\right)^{-1}\left(u\right),u\right\rangle
+\left\langle\left(\nabla f\right)^{-1}\left(u\right),h\right\rangle
+\left\langle\mathrm{d}\left(\left(\nabla f\right)^{-1}\right)\left(u\right)\left[h\right],u\right\rangle
-f\left(\left(\nabla f\right)^{-1}\left(u\right)\right)
-\mathrm{d}f\left(\left(\nabla f\right)^{-1}\left(u\right)\right)\left[\mathrm{d}\left(\left(\nabla f\right)^{-1}\right)\left(u\right)\left[h\right]\right]
+o\left(h\right)$$
$$=f^*\left(u\right)
+\left\langle\left(\nabla f\right)^{-1}\left(u\right),h\right\rangle
+\left\langle\mathrm{d}\left(\left(\nabla f\right)^{-1}\right)\left(u\right)\left[h\right],u\right\rangle
-\mathrm{d}f\left(\left(\nabla f\right)^{-1}\left(u\right)\right)\left[\mathrm{d}\left(\left(\nabla f\right)^{-1}\right)\left(u\right)\left[h\right]\right]
+o\left(h\right).$$
Hence, we have :
$$\mathrm{d}\left(f^*\right)\left(u\right)\left[h\right]
=\left\langle\underbrace{\left(\nabla f\right)^{-1}\left(u\right)}_{\in\mathbb{R}^n},h\right\rangle
+\left\langle\underbrace{\mathrm{d}\left(\left(\nabla f\right)^{-1}\right)\left(u\right)\left[h\right]}_{\in\mathbb{R}^n},u\right\rangle
-\mathrm{d}f\underbrace{\left(\left(\nabla f\right)^{-1}\left(u\right)\right)}_{\in\mathbb{R}^n}\underbrace{\left[\mathrm{d}\left(\left(\nabla f\right)^{-1}\right)\left(u\right)\left[h\right]\right]}_{\in\mathbb{R}^n}\in\mathbb{R}.$$
By definition of the gradient in $\mathbb{R}^n$, we can write the last term above as
$$\mathrm{d}f\left(\left(\nabla f\right)^{-1}\left(u\right)\right)\left[\mathrm{d}\left(\left(\nabla f\right)^{-1}\right)\left(u\right)\left[h\right]\right]
=\left\langle \nabla f\left(\left(\nabla f\right)^{-1}\left(u\right)\right),\mathrm{d}\left(\left(\nabla f\right)^{-1}\right)\left(u\right)\left[h\right]\right\rangle$$
$$=\left\langle u,\mathrm{d}\left(\left(\nabla f\right)^{-1}\right)\left(u\right)\left[h\right]\right\rangle
=\left\langle \mathrm{d}\left(\left(\nabla f\right)^{-1}\right)\left(u\right)\left[h\right],u\right\rangle$$
therefore, we finally find
$$\left\langle\nabla \left(f^*\right)\left(u\right),h\right\rangle
=\mathrm{d}\left(f^*\right)\left(u\right)\left[h\right]
=\left\langle\left(\nabla f\right)^{-1}\left(u\right),h\right\rangle$$
and this is true for all $h\in\mathbb{R}^n$ such that $u+h\in\mathcal{U}$, for all $u\in\mathcal{U}$. Hence, we proved that
$$\nabla \left(f^*\right)=\left(\nabla f\right)^{-1}$$
as wanted.
Comment: Nice ! Good luck for your exam !
Comment: impressive proof, thanks a lot for your effort :-)
Comment: You're welcome !
Comment: I thought I'd understand that proof, but when I tried to comment on it for my own notes I noticed that in the third = sign (when differentiating $f^*$) there appears a $f((\nabla f)^{-1}(u))$ and another expression I don't understand. I thought you achieved that by substituting it into the statement that $f$ is differentiable but I can't make the patterns match.
Comment: It is because I've differentiated $f$ at the point $\left(\nabla f\right)^{-1}\left(u\right)\in\mathbb{R}^n$ in the direction $\mathrm{d}\left(\left(\nabla f\right)^{-1}\right)\left(u\right)\left[h\right]\in\mathbb{R}^n$. It is the most difficult part of the proof. I can detail more if you need to.


Como estilizar o ícone "limpar" do input type search?

Question: Preciso de um meio de estilizar o ícone × que fica ao final do input[type="search"].
O input type search ao focar no elemento, o mesmo apresenta um × caso o mesmo tenha um valor preenchido.
Exemplo:

Eu percebi que ao estiliar o input search, muitas vezes esse "xizinho" some.
Como eu posso fazer para estilizá-lo e ainda preservá-lo no input[type="search"]?
Answer: Talvez uma solução seja justamente o contrario, desabilitar o ícone e usar um background personalizado, veja:

(function() {
  document.querySelector(".fundo").onclick = function() {
    document.querySelector(".fundo").value = "";
  };
}());
input[type="search"]::-webkit-search-decoration,
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-results-button,
input[type="search"]::-webkit-search-results-decoration {
  display: none;
}

.fundo {
  background: url(http://www.nepneuro.com.br/site/img/fechar.svg) no-repeat scroll 98%;
  z-index: 0;
}

<input name="teste" type="search" class="fundo">
Comment: Aí vou ter que colocar uma imagem e um javascript para uma coisa que já faz nativamente :\
Comment: Duas sugestões se me permite, troque o display:none por visibility:hidden; e faça o evento aplicar uma classe que adiciona o x, então ficará perfeito :) ... (ps: eu ainda não testei se visibility funciona)
Answer: Neste caso o que você deseja é o ::-webkit-search-cancel-button.
Ele é o pseudo elemento CSS que representa o "botão de cancelar".
Para estilizar o mesmo você pode fazer algo parecido com isso:

#Search {
  width: 480px;
  height: 49px;
  border: 3px solid black;
  padding-left: 48px;
  padding-top: 1px;
  font-size: 22px;
  color: blue;
  background-image: url('images/search.jpg');
  background-repeat: no-repeat;
  background-position: center;
  outline: 0;
}

#Search::-webkit-search-cancel-button {
  position: relative;
  right: 20px;
  -webkit-appearance: none;
  height: 20px;
  width: 20px;
  border-radius: 10px;
  background: red;
}
<input id="Search" name="Search" type="search" placeholder="Search" />

Vale lembrar que você pode ter problemas de compatibilidades com ele, como apresentado pelo site de Desenvolvedores da Mozilla (MDN).

Caso queira mais detalhes, pode ver esta resposta do SOen.
Comment: Opa, gostei da sua resposta, muito bom. Pena que ainda só o  Webkit tem essa estilização. Implementações de CSS sempre decepcionando :\. +1
Answer: Sim, o tal x (botão de cancelar) some se o mouse não estiver por cima do elemento e não tem como preserva-lo visível, eu até cheguei a encontrar um artigo sobre customizar o botão de cancelar, mas se ler com atenção notará que fala de iOS, testando no Chrome/Opera notará que não funciona e também note que ele mesmo afirma que isto não chega a ser uma boa solução e que é preferível usar algum javascript que auxilie.
A única maneira seria simular este botão usando javascript, ou algum framework javascript
Exemplo cross-platform

var fields = document.querySelectorAll(".field");

for (var i = 0, j = fields.length; i < j; i++) {
    cancelButtonEvents(fields[i]);
}

function updateVisibility(field, btn, timer) {
    timer && clearTimeout(timer);
    timer = setTimeout(function () {
        if (field.value != "") {
            btn.classList.add("visible");
        } else {
            btn.classList.remove("visible");
        }
    }, 10);
}

function cancelButtonEvents(field) {
    var realField = field.querySelector(".main-field");
    var btn = field.querySelector(".cancel");
    var timer;

    btn.onclick = function () {
        realField.value = "";
        updateVisibility(realField, btn, timer);
    };

    realField.onkeydown = function () {
         updateVisibility(realField, btn, timer);
    };
}
.field {
    display: inline-block;
    border: 1px solid #ccc;
}

.field input {
    border: none;
    background: transparent;
    vertical-align: middle;
}

.field a.cancel {
    visibility: hidden;
    text-decoration: none;
    padding: 5px;
}

.field a.visible {
    visibility: visible;
}

    <input class="main-field" type="text" value="">
    x

Exemplo com [type=search] real (somente Webkit/Blink)
Me baseando na resposta do Marcelo criei um exemplo que oculta o botão x com opacity e aplica uma imagem de fundo para trocar simular o x, claro que depende um pouco de JavaScript como citei anteriormente:

note que usei o :not([disabled]):not([readonly]) para evitar que elementos com atributo/propriedade disabled ou readonly exibam o "botão simulado"

var searchFields = document.querySelectorAll("input[type=search]");

for (var i = 0, j = searchFields.length; i < j; i++) {
    cancelButtonEvents(searchFields[i]);
}

function updateVisibility(field, btn, timer) {
    timer && clearTimeout(timer);
    timer = setTimeout(function () {
        if (field.value != "") {
            field.classList.add("no-empty-search");
        } else {
            field.classList.remove("no-empty-search");
        }
    }, 10);
}

function cancelButtonEvents(field) {
    updateVisibility(field);

    field.onkeydown = function () {
        updateVisibility(field);
    };
    field.onchange = function () {
        updateVisibility(field);
    };
    field.oninput = function () {
        updateVisibility(field);
    };
}
::-webkit-search-cancel-button {
    opacity: 0;
    cursor: pointer;
}

.no-empty-search:not([disabled]):not([readonly]) {
    background: url(http://www.nepneuro.com.br/site/img/fechar.svg) no-repeat scroll 98%;
}
Vazio:
<input name="teste1" type="search" value="">

Pré-preenchido:
<input name="teste2" type="search" value="Olá mundo!">

Desabilitado:
<input name="teste3" type="search" value="desabilitado enquanto consulta via Ajax por exemplo" disabled>

Somente leitura:
<input name="teste4" type="search" value="leitura" readonly>


SAS Scoring on new data

Question: I have a training dataset with (x1,x2,x3,y) and these contain some missing observations. I ran proc logistic on this training data and got the parameter estimates (bo, b1, b2, b3).
I tried to apply these estimates(bo, b1, b2, b3) on the test dataset which does not contain any missing observation using proc logistic inmodel the results show lot of missing data and this is the message from the log
" Work.Test data set are not scored because they have class
      levels that are missing or are not present in the analysis data set"
Any suggestion how to score on test dataset without producing missing data even when training dataset contains missing data ? Thanks in advance.
Comment: See also:   https://stats.stackexchange.com/questions/298137/dealing-with-new-factor-levels-in-a-regression-in-r/384749#384749
Answer: Check your scoring input data for character variables which have different classes than in training data. I think that for numeric variables it is no problem but for char variables which are factored using certain codes this can be problem. SAS treats missing data differently if variable is char or num.

SAS Scoring on new data


Whenever Plugin Help

Question: I am trying to use the Whenever plugin for rails to perform a model process at certain times. My schedule.rb is as follows:
 every 1.day, :at => '5:30 am' do
    runner "User.mail_out"
  end

My model is as follows:
class User < ActiveRecord::Base

  acts_as_authentic

  def mail_out

    weekday = Date.today.strftime('%A').downcase

    @users = find(:conditions => "#{weekday}sub = t")

    @users.each { |u| UserMailer.deliver_mail_out(u)}

  end

end

When I try to run the script/runner -e development "User.mail_out" command, I get the following error:
/var/lib/gems/1.8/gems/rails-2.3.5/lib/commands/runner.rb:48: undefined method `mail_out' for #<Class:0xb708bd50> (NoMethodError)
    from (eval):1
    from /usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `eval'
    from /var/lib/gems/1.8/gems/rails-2.3.5/lib/commands/runner.rb:48
    from /usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
    from /usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `require'
    from script/runner:3

Can anyone point out what is going wrong? Also how can I manually invoke the mail_out process (from command line) to test the functionality of my mailing system.
Thank you!
Answer: You're getting that error because you've defined the mail_out method as an instance method instead of a class method. To fix it, change the method definition line to (add self.):
def self.mail_out

To test it from the command line, do something like this:
script/runner "User.mail_out"

You might want to puts or print something so you get some feedback on what happened.
Comment: Thank you for the help. Now I get a new error, I updated my post above. Also I included my mail script. Any ideas of what is not working?
Comment: Good question, but please try to refrain from changing your question significantly after an answer is posted. The goal of this site is to build a collection of web pages with useful responses to specific questions, not just for the question askers, but for the whole development community, including anyone reading this page in the future. Your new question is not related to the original (not totally your fault--it may seem related), so it would be clearer to post it as a new question. (Also, this is the second useful answer I've given you--see your previous questions--how about a vote?)
Comment: Sorry, I am still getting the hang of this site. I will post a new question. And I marked your answers :) Thanks for the help.
Comment: Trevor, no worries--thanks for the votes! I would have answered your new question but I was out for a couple of hours. See you around on the site, and good luck with your projects.
Answer: I was getting the same error as the OP, except I did have the Class method defined correctly (or so I thought).
It turned out that I'd put the method in the Controller (which looked like the right place) instead of the Model (which looked like the wrong place). Anyhow, putting the method in the Model fixed this problem for me.

Whenever Plugin Help


Does my operator $C([0,1]) → C([0,1])$ have an inverse?

Question: Consider the Banach space $X := C_\mathbb{C}([0,1])$ with the supremum norm. Consider the bounded linear operator $T : X → X$ given by
$$ (Tf)(t) = \int_0^t 2sf(s)ds + f(1).$$
I want to know whether $4I - T$ (with $I$ the identity operator) has an inverse in $B(X)$. I know this is the case whenever $\lVert(4I-T) - I\rVert = \lVert3I-T\rVert < 1$. Indeed, the Neumann series $\sum_{n=0}^∞ (T - 3I)^n$ would then be a candidate, and by uniqueness, the inverse of $4I-T$. Now if I perform the calculation, I end up with, if I have interpreted all the norms in the right ways,
$$\lVert 3I - T\rVert = \sup_{\lVert f \rVert ≤ 1} \sup_{t ∈ [0,1]} \left\{\left|3f(t) -2\int_0^t 2sf(s)ds + f(1) \right|\right\} ≤ \left|3 - \int_0^1 2sds + 1\right|≤ 5.
$$
Now, although this is not less than $1$, why could I not simply multiply by, say, ⅙, obtain an operator with norm ⅚ $< 1$, and later scale up by $6$ again, which should not matter much in the vector space setting we are in.
Perhaps I'm approaching this the complete wrong way, though.
EDIT: For a further question (whether $T$ is compact), I know that, since $[0, 1]$ is compact, $\overline{\mathcal{B}_{00}(C_{\mathbb{C}}([0,1]))} = \mathcal{B}_0(C_{\mathbb{C}}([0,1]))$. That is, if $T$ is compact, we can approximate $T$ by a sequence of finite-rank operators. One easy way to define a sequence that converges to $T$ is to define, for every $n ∈ ℕ$, the operators $T_n$ given by
$$ (T_nf)(t) = \int_0^{t(1-\frac{1}{n})}2sf(s)ds + f(1),$$
but I don't know whether these are of finite rank, and I generally have trouble with such arguments in infinite-dimensional vector spaces..
Comment: If $\|T\|<1$ then $\|I-T\|$ is invertible. Also, if $S$ is invertible, then $a S$ is invertible, for every $a \ne 0$. But from these two statements you cannot say $\|I-T\|$ is invertible, since "I can ensure that $\|T\|<1$, by multiplying by some constant"
Answer: Notice that
$$|Tf(t)|\leq\int^t_0|f(s)|2s\,ds+|f(1)|\leq 2\|f\|_\infty$$
and taking $f(t)\equiv1$, we conclude that $\|T\|=2$. Then for all $\lambda\in\mathbb{C}$ with $|\lambda|>2$ is $\lambda I-T=\lambda\big(I-\tfrac1\lambda T\big)$ invertible. This answers the OP completely.

One can further question for which other values of $\lambda\in\mathbb{C}$ is $(\lambda I -T)$ invertible. Notice that
$T$ is a compact operator as $f\mapsto \int^t_02s f(s)\,ds$ and $f\mapsto f(1)$ are compact operator on $C([0,1])$. Thus, $0I-T=-T$ is not invertible (it can be seen that $T$ is injective, however).
Suppose $\lambda\neq0$. Fix any polynomial $p(t)=a_0+\ldots +a_nt^n$. If $f$ solves equation
$$\begin{align}
\lambda f(t)-Tf(t)=\lambda f(t)-\int^t_02sf(s)\,ds- f(1)=p(t)\tag{0}\label{zero}
\end{align}$$
then $f$ is differentiable, and
$$\begin{align}
\lambda f(0)-f(1)=a_0\tag{1}\label{one}
\end{align}$$ Consequently, $f$ solves
$$\begin{align}
\lambda f'(t)-2tf(t)= p'(t)\tag{2}\label{two}
\end{align}$$
Solving equation \eqref{two} we obtain that
$$\begin{align}
\frac{d}{dt}e^{-t^2/\lambda}f(t)=\frac1\lambda e^{-t^2/\lambda}p'(t)\\
\end{align}$$
$$\begin{align}
f(1)e^{-1/\lambda}&-e^{-t^2/\lambda}f(t)=\frac1\lambda\int^1_te^{-s^2/\lambda}p'(s)\,ds
\end{align}$$
and so, after integration by parts we obtain
$$\begin{align}
f(t)&=e^{t^2/\lambda}\Big(f(1)e^{-1/\lambda}-\frac1\lambda\Big(e^{-\tfrac1\lambda}p(1)-e^{-\tfrac{t^2}{\lambda}}p(t)+\\
&\qquad\qquad\frac1\lambda\int^1_t2se^{-\tfrac{s^2}{\lambda}}p(s)\,ds\Big)\Big)\tag{3}\label{three}
\end{align}$$
and
$$\begin{align}
f(1)e^{-1/\lambda}- f(0)&=\frac1\lambda\int^1_0e^{-\tfrac{s^2}{\lambda}}p'(s)\,ds\tag{1'}\label{onep}
\end{align}
$$
As long as $\lambda\neq0$ and
$$\begin{align}
\operatorname{det}\begin{pmatrix}\lambda & -1\\-1 & e^{-1/\lambda}\end{pmatrix}=\lambda e^{-\tfrac1\lambda}-1\neq0\tag{4}\label{four}
\end{align}
$$
conditions \eqref{one} and \eqref{onep} are compatible.
Putting things together, we have that
\begin{align}
\lambda f(t)-\lambda f(0)-\int^t_02s f(s)\,ds=p(t)-a_0
\end{align}
and so,
$$(\lambda I-T)f(t) + f(1)-\lambda f(0)=p(t)-a_0$$
i.e.,  $(\lambda I-T)f=p$.
When $p\equiv0$, once can see that $f(1)=0=f(0)$ and so $f(t)\equiv0$. This means that $\lambda I-T$ is injective.
We have shown that if $\lambda\neq0$ satisfies \eqref{four}, then $(\lambda I-T)$ is injective and has dense range. As $T$ is compact, range of $(\lambda I-T)$ is closed; hence, by the Open Mapping Theorem, $\lambda I-T$ has a bounded inverse. Using \eqref{three} and solving the linear system \eqref{one} and \eqref{onep}, we can in fact derive an explicit expression form $(\lambda I-T)^{-1}$.
Comment: Wow, I was way off. Thanks so much!
Answer: First off, the question in the title -if any operator has an inverse - of course not every operator has inverse. For example, consider operators which have finite dimensional image (or, more general compact operators).
Now, regarding $T$. One easily checks that $||T|| \leq 2$. Hence, $||\frac{1}{4}T|| \leq \frac{1}{2}$. It is a general fact that if $||A|| < 1$ then $I-A$ has inverse.
One just writes formula for it (which is analogous to number like formula) that is
$$(I-A)^{-1} = \sum A^{k}$$. The series one the right side converges because of assumption on $||A||$.
Comment: THe OP has a particular operator in mind, not ANY operator.
Comment: Correct. As I remarked, for his operator we have $||T|| <= 2$. Hence $4I-T= 4(I-\frac{1}{4}T)$. And since $I-\frac{1}{4}T$ has inverse so does $4I-T$.
Comment: @Salcio you should post your argument as an answer.
Comment: I guess my actual question was: if this is all true, then why require $\lVert T - I\rVert < 1$ instead of it just being finite...? I don't see much of a difference here. And maybe that's ok, and the lemma (involving the Neumann series) could have been formulated differently.
Comment: @Jos, I think we want $||T|| < 1$ not $||T-I|| < 1$. If $||T-I|| < 1$ then such $T$ has inverse as can be seen by the same argument as above.
Comment: @OliverDiaz If you're right, this old exam question "Prove that $4I-T$ has an inverse", is wrong. :p
Comment: @Oliver Diaz  The only such function if $f=0$. This can be easily seen by taking derivative on both sides (right hand side is smooth) to get $4f^'(t) = 2tf(t)$, hence $f(t) = Ce^{\frac{1}{2}}t^2$ but also $(Tf)(0) = f(1)$ which should be $4f(0)$ in words $C=4Ce^{\frac{1}{2}}$ so $C=0$
Comment: @Salcio the solution to $y'=\frac{xy}{2}$ is $y=Ce^{x^2/4}$ but your argument is nevertheless valid.
Comment: @Mathew, thanks for pointing it out.


CW complex that deformation retracts to annulus and Möbius band

Question: I am trying to construct a 2-dimensional CW complex that contains both an annulus, thought of as $S_{1}\times I$ and a Möbius band as deformation retracts.
The first part of the problem asked to show that the mapping cylinder of every map $f:S^{1}\rightarrow S^{1}$ is a CW complex so I thought of doing the construction using mapping cylinders, perhaps gluing the mapping cylinder of one map to the mapping cylinder of another map along the base circle. One map would be the identity map on $S^{1}$ since its mapping cylinder will be $S^{1}\times I$, but I can't figure out what the other map should be in order to get a Möbius band.
Answer: Here is a cell complex $X$ containing subcomplexes $A\cong M$ (the Möbius  strip) and $B\cong \mathbb{S}^1\times I$ such that $X$ deformation retracts to both $A$ and $B$ (note that several vertices and edges are identified):

The subcomplex $A$ is

which, when the appropriate points and edges are identified, looks like

which deformation retracts onto $C=(p_2\cup e_5)\cong\mathbb{S}^1$. The subcomplex $B$ is

which, when the appropriate points and edges are identified, looks like

which deformation retracts onto $C=(p_2\cup e_5)\cong\mathbb{S}^1$.
Note that $A\cap B=C$. We can extend the deformation retraction of $A$ onto $C$ to all of $X$ by the identity on $B$, so that $X$ deformation retracts onto $B$, and similarly with the deformation retraction of $B$ onto $C$, so that $X$ deformation retracts onto $A$.
Comment: Oh great Zev, thank you.
Comment: Your pictures illustrate the statements very well. That's my weakness.
Answer: In general, if $W = X \bigsqcup_{A} Y$ is the pushout of two CW complexes along a common subcomplex $A$, $X$ deformation retracts onto $A$, and $Y$ deformation retracts onto $A$, then $W$ deformation retracts onto both $X$ and $Y$, where the retracts from $Y$ and $X$ to $A$ are used to retract $W$ to $X$ and $Y$, respectively. (Hatcher, Prop 0.19 and Cor 0.20.)
To use this to give intuition for the construction without trying to visualize it with pictures (although pictures are great!!), take $X$ to be the annulus and $Y$ to be the Möbius band. Place CW structures on each of these so there is a canonical $S^1$ that is a deformation retract of each, and then just identify the two CW complexes by this $S^1$, where the orientation and vertices match. This will yield the CW complex that has both $X$ and $Y$ as deformation retracts.
(IMO, Hatcher's part (a) is just a red herring for solving this problem.)
Answer: We have a map, $M\to S^1$ that contracts $M$ to it's central circle. When we take the mapping cylinder, one end is a circle. Then attach a cylinder to that circle.


Knockout Foreach Javascript function

Question: Is it possible to declare a javascript function in your knockout foreach binding?  I want to generate a list from a javascript function outside of my view model.
 <select class="form-control" data-bind="foreach: { data: function() { // return list values } }">
 <option data-bind="text: Value, attr: { value: Value }"></option>
            </select>

Comment: You should call that global list from your VM, its there for that reason
Comment: why do u want to do this? what are you trying to achieve?
Comment: I'm trying to pull from a globally defined javascript list.
Answer: No quite sure what you are trying to achieve with <option data-bind="text: Value, attr: { value: Value }"></option>.
Have a look  at my fiddle for a few different setups. It contains usages of both options and foreach bindings on a select element.
To answer the question, you provide a function in your viewModel to provide the desired data. As long as your viewModel can "access" the data, the function will provide it to the binding. If the data were to be a simple list of literals, then all that is required :
Javascript:
var listOfLiterals = function() { return  ["One", "Two", "Three"] };

  var viewModel = {
     selectedLiteral: ko.observable(),
     getLiterals: function() {
       return listOfLiterals();
  }
}

HTML:
<select data-bind="options: getLiterals(), value: selectedLiteral"></select>

Knockout Foreach Javascript function


Why does the best model in the training set have the worst test result?

Question: I have trained eight models using 10-fold cross-validation, and evaluated the models by using resampling technique as described here. The result shows that SVM with sigmoid kernel (SVM-s) and random forest (RF) are the best models, while penalised regressions had the lowest performance:

However, when I predicted the target variable by using the test set, the ROC curves showed very different ranking of model performance. The SVM model turned out to have the lowest AUC, and the penalised regressions had outperformed naive Bayes, neural network and CART.
AUC:
Lasso, RF, Elastic net, Ridge: 0.75;
Naive Bayes, neural network: 0.70;
Classification tree, SVM: 0.65.
Are there any good explanations for almost opposite model performance?
Answer: Yes, this is a classic example of "overfitting." At a high level, this means that your model is "learning" the training set so well that it's "memorized" features that don't work as well in the testing set. In fact, powerful classifiers like deep neural networks will often get 100% accuracy on the training set, and nowhere near that figure on the validation set.
Ideally, when selecting a model, we want our model to 1) learn during training and 2) generalize to unseen data (validation set). We'd like to see a model that has good training performance, and a small gap between train and validation performance. For your metric (AUC-ROC), I'd calculate the area between curves as discussed here to quantify how much your models are overfitting so you can make a better decision.
I've left some intuitive (hopefully) explanations for this effect below as well for your reference.
Some Intuition
Intuition with model accuracy. I'm going to talk about this in the context of accuracy. I think the below image from Wikipedia demonstrates the general idea quite well: suppose you're doing a binary classification task (separate blue and red data points). We see the training set here. The green classifier has 100% accuracy: it draws a (very twisty) boundary between the two classes.
Green classifier overfits. However, we might intuit instead that the separation between red and blue data points is better explained by the black boundary. Based on this intuition, it seems like the green classifier "overcomplicated" the problem: there's going to be some regions, which may appear in our test set, where the simpler explanation (black boundary) works better! The green classifier is very sensitive to small changes in the data.

Bias-Variance Tradeoff
That "almost-opposite" effect that you notice here is the bias-variance tradeoff, which can be derived by decomposing the mean squared error of a model. The bias is the error resulting from inherent limitations/assumptions in the model; variance is the sensitivity of the model to small data changes.
Intuition: why is there a tradeoff? A "simple" model may not be able to capture the underlying differences between data classes well (high bias), but isn't as sensitive to small changes in the data (low variance), while a complex model might be able to separate data classes well (low bias) but runs the risk of memorizing noise in training data, which is quite brittle (high variance).
Some of the models you've posted are overfitting, demonstrating low bias and high variance. Regularized regression methods like ridge or LASSO are specifically designed to combat overfitting, so I'm not too surprised by your results.
Comment: Thank you very much for the reply, amazing answer and very helpful indeed. :)
Comment: Probably a quite newbie question: what should one do with overfitting that happened to certain models (e.g. the SVM sigmoid)? A quick search online suggests (1) increase sample size for the test set, (2) k-fold cross validation or (3) resampling. I've tried all three approaches but they did not seem to solve the problem. Any suggestions? :)
Comment: No, these are fine questions. Think of it this way: overfitting is a thing that can happen given some model and some training set. So doing stuff to the test set is a little orthogonal: 1) and 2) will only help you catch overfitting more reliably. To combat it, you need to either 1) do something to your model or 2) do something to the training set.
Comment: I don't quite understand what 3) is -- "resampling" could mean a lot of things, so if you have a link to the specific method (or even the code) I might be able to help more.
Comment: But back to changing the model: as a heuristic, you can think of more "complicated" models as ones that have more parameters (this doesn't hold true always!) -- for example, I'd expect neural networks to overfit pretty badly here. Alternately, "simpler" models are ones that make some assumptions about your data or constrain the model somehow -- i.e. small parameter norm (as in ridge) or sparsity (as in LASSO). For random forest, a simpler model might be shallower, or has less trees. SVMs I haven't played with much recently and I'd have to review the math.
Comment: And lastly, for changing the training set -- you can make it larger, either by manually collecting more data, or, if viable, generating synthetic data using SMOTE, data augmentation, or related techniques (depending on your task).
Comment: At a glance, [this answer](https://stats.stackexchange.com/questions/35276/svm-overfitting-curse-of-dimensionality) seems to discuss SVMs and overfitting at a much deeper level than I can.
Comment: Wow, thank you so much for the great answers! And the link :). Yes I have oversampled the training set with SMOTE, and resampling is basically the same as k-fold cv (should have been only two points there). It's also a good idea to test simpler models! I'll try it. Seems like a paradox here: we tune the hyperparameters to improve the models' accuracy and to get better better fit; on the other hand it leads to overfitting...