How to calculate the long run proportion of time spent at a certain state, given that the Markov chain starts at a different state?

Question: I have a Markov chain with an n * n matrix starting with all elements equal to 0. At each step, one of the elements is chosen uniformly at random and flipped, (that is, 0 is changed to 1, or 1 is changed to 0).
Now I am trying to find the long run proportion of times the matrix is the identity matrix. Here, we have a total number of 2^(n^2) states.
I tried the following:
The long run proportion of times the matrix is the identity matrix
= The stationary distribution value at the identity state
= no. of moves possible from the identity state / total number of moves possible from all states
= 1/ (2^(n^2)).
Is this argument reasonable ? But what makes me doubtful is that here, we are not starting from the identity matrix. Instead, the Markov chain starts at the matrix where all entries are 0. Does the starting state make a difference in finding the long run proportion of time spent at a given state?
I also think this chain is periodic.  And I read that the chain converges to its stationary distribution only if the chain is aperiodic.  Thanks a lot for any help.
I wonder if it relates to the concept of limiting probabilities... If so, how can I use limiting probability to find the long run proportion of time spent at a certain state, given that the chain starts from a different state?
Answer: You are right, there is a slight problem caused by periodicity. However, it turns out you still get the same answer in the end. Basically, periodicity is not a problem, because we are looking at the long-term average, so the effect of constantly bouncing between the two parts gets averaged out and does not matter.
If a Markov chain is ergodic (meaning every state can reach every other) and aperiodic, then every initial distribution will converge to the unique stationary distribution. This means that it does not matter what state you start at, or even what probability distribution you initially have for the first state; the distribution of the states at a given time will always converge. For a periodic chain, you do not quite get convergence. Instead, you will get a separate stationary distribution for each of the periodic parts of the chain, and the whole state will alternate between these distributions.
Instead of proving all that in general, I will just discuss how this applies to your case. Let $G=(V,E)$ be a simple connected bipartite graph. Let $A$ and $B$ be the parts of this graph, so $V=A\sqcup B$, and every edge in $E$ connects a vertex in $A$ to a vertex in $B$. We will have a random walk on this graph, where if you are currently at vertex $v\in V$, then the next vertex is uniformly chosen from the neighbors of $v$. Your problem is an example of this; $V$ is the set of all matrices, while $A$ is the set of matrices with an even number of ones, and $B$ is the set of matrices with an even number of ones.
Suppose that, initially, you start at a vertex in the $A$ part. This vertex is state number zero. This means that, certainly, state $1$ will be in the $B$ part, state $2$ in the $A$ part, and so on. In general, even numbered states are in $A$, and odd numbered states are in $B$. I claim that the following is true:

Whenever $t$ is even, the probability of being at a vertex $v\in A$  at time $t$ converges to $(\deg v)/|E|$ as $t\to\infty$.
Whenever $t$ is odd, the probability of being at a vertex $v\in B$ at time $t$ converges to $(\deg v)/|E|$ as $t\to\infty$.

So, for your matrix question, you start from the all-zeroes matrix. If $n$ is even, then the identity matrix is in the same part as the starting matrix. Therefore, at even numbered turns, the probability is $1/2^{n^2-1}$ of being in the identity matrix, and zero for odd turns. If $n$ is odd, then you switch those two answers.
Now, let us compute the long-run probability of being in the identity matrix state. In the general setting of random walks on a bipartite graph, let $v\in V$, and
let $X_0,X_1,X_2,\dots$ be the random state at each time. I will first assume that $v$ is in the $A$ part, but the proof for the $B$ part is similar. Then
$$
\begin{align}
\text{long run prob. of being at $v$}
&=\lim_{n\to\infty} \frac1n \sum_{t=0}^n {P(X_t=v)}
\\
&=\lim_{n\to\infty} \frac1n \left(\sum_{t=0}^{\lceil n/2\rceil} {P(X_{2t}=v)}+\sum_{t=0}^{\lfloor n/2\rfloor}P(X_{2t-1}=v)\right)
\end{align}
$$
Since $v$ is in the $A$ part, we have $P(X_{2t-1}=v)=0$. On the other hand, $P(X_{2t}=v)$ converges to $(\deg v)/|E|$. Therefore, the above converges to
$$
\frac1n\cdot \left(\lceil n/2\rceil \frac{\deg v}{|E|}\right)\to \frac{\deg v}{2|E|}
$$
This is exactly the same as the answer for the aperiodic case. Therefore, for your matrix problem, the answer is still $1/2^{n^2}$.
Comment: This explanation is very helpful to understand the underlying concept.  Thank you so much for your time and insights...


How does IMAP/POP Server fetch emails from my SMTP server?

Question: I have a domain abc.com with MX record/SMTP server mx1.example.com. My IMAP/POP server (incoming server) is imap.example.com and pop3.example.com.
How does my IMAP and POP server fetch emails from mx1.example.com ? Do IMAP/POP Server use any protocols to fetch emails from mx1.example.com. How does my IMAP server knows that emails should be fetched from mx1.example.com. I am using postfix and dovecot for email service.
Please clear my these confusions.
Answer: It's quite simple: Postfix just hands the mail over to Dovecot automatically as soon as it arrives instead of storing the mail itself.
Comment: Thanks for reply. :-) So, how does my SMTP Server finds that IMAP or POP server ? Where is the configuration portion ? Should we configure something like on SMTP that my imap/pop server is imap.abc.com or pop3.abc.com ? Or, are there any packages installed on IMAP server for fetching it from SMTP like fetchmail, get mail ??
Answer: In main.cf you can describe how exactly postfix will communicate to dovecot. If postfix and dovecot are sharing the same host, you can setup communication using LMTP protocol via unix socket. This approach will have less overhead than TCP based communication.
In main.cf you should specify your domain and unix socket details
virtual_mailbox_domains = yourdomain.com
virtual_transport = lmtp:unix:private/dovecot-lmtp

In dovecot's 10-master.conf also provide socket details
service lmtp {
 unix_listener /var/spool/postfix/private/dovecot-lmtp {
  group = postfix
  mode = 0600
  user = postfix
  }
}

Permissions on socket file
srw-------  1 postfix  postfix     0B Aug 17 00:35 /var/spool/postfix/private/dovecot-lmtp

I'm using FreeBSD, in Linux paths may be different.
Comment: Hi, thanks for reply.

I have dovecot on different server. How do I point on my SMTP server that this is my dovecot server. Like should I use, transport_maps option on main.cf ?

transport_maps = hash:/etc/postfix/smtproutes

and on smtproutes file:

abc.com.np smtp:184.108.40.206
Comment: Is mail delivering to real (system) users or to virtual users?
Comment: For virtual users.
Example my smtp server is 18.104.22.168 and my dovecot server is 188.8.131.52.
Comment: Can you please tell me, how can we establish that link between Postfix and Dovecot ?


React-Axios => Cannot read properties of undefined (reading 'length')

Question: I am trying to retrieve some data from an API. When I console the data it works fine:
import axios from 'axios';

export default function Model() {

    const url = "api.blabla.com/blabla"
    const [model, setModel] = useState()
    useEffect(() => {
      const axiosPosts = async () => {
        const response = await axios(url)
        setModel(response.data)
      };
      axiosPosts();
    }, []);

   console.log(model.slug) //prints the slug!!

    return (

       {model.slug} : {model.name} // TypeError slug undefined

    )

What can be the problem with this code?
Comment: And where does length come into it? Note that the _initial_ state of model is indeed undefined.
Comment: Thank you for the edit and you are right problem solved.
Answer: It takes time for the api to respond, so at the start model is assigned the value of the parameter you passed to the useState() hook.
You passed nothing so during the first react render model is undefined.
One solution could be to change your template to:
{model?.slug} : {model?.name}

Or make it conditional
{model && (
  <>
    {model.slug} : {model.name}
  </>
)}

Comment: A better practice could be to create another component with only one role: render the data. You could only display this component when the data is available, just like I showed you in the second example.
Comment: Thanks a lot, it works fine right now. Is it always necessary to use data like this when fetching from API or is there any other way (possibly better practice)?
Answer: adding more to @ploppy's answer above, a common pattern here would be
import axios from 'axios';

export default function Model() {

const url = "api.blabla.com/blabla"
const [status, setStatus] = useState("idle");
const [model, setModel] = useState({
  slug: "",
  name: ""
})
useEffect(() => {
  setStatus("pending");
  const axiosPosts = async () => {
    try{
    const response = await axios(url)
    setModel(response.data)
    setStatus("resolved")
   }catch(error){
    console.log(error);
    setStatus("rejected");
   }
  };
  axiosPosts();
}, []);

console.log(model.slug) //prints the slug!!

if(status === "pending"){
    return (
Loading...
)
}
if(status === "rejected"){
    return (
Something went wrong!
)
}
return (

   {model.slug} : {model.name} // TypeError slug undefined

)

This gives you a good advantage to handle API calls and their responses better.


Como setar um estado que está em uma constante com React com uma função

Question: Tenho o seguinte trecho de código:
const [aulas, setAulas] = React.useState([{
 id:1,
 title: 'Aula 1',
 descricao: 'Matemática',
}, {
 id:2,
 title: 'Aula 2',
 descricao: 'Portugues',
}])
 function addAula(aula) {
  // aqui eu precisaria atualizar o estado de 'aulas' com uma nova aula.
 }
 return null
}

Porém eu não sei como eu poderia utilizar uma função para setar o state e atualizá-lo, apenas utilizando está função.
Se puderem em ajudar agradeço, estou iniciando em React e aprendendo os princípais ocnceitos de estado ainda.
Comment: Podes explicar melhor o que queres mostrar nessa página/app? o que faz `addAula`? como deve mostrar no html?
Answer: A função setAulas deve ser a única forma de atualizar o state aulas.
Por exemplo, com setAulas(novoObjetoAulas).
Eis aqui um exemplo completo, com demonstração no Codepen:
function Component() {
  const defaultObject = [
    {
      id:1,
      title: 'Aula 1',
      descricao: 'Matemática',
    },
    {
      id:2,
      title: 'Aula 2',
      descricao: 'Portugues',
    }
  ]

  const [aulas, setAulas] = React.useState(defaultObject)
  const [id, setId] = React.useState(3)

  function addAula(aula) {
    const atualizacao = [...aulas, aula]
    setAulas(atualizacao)
  }

  function handleClick(event) {
    const aula = {
      id: id,
      title: 'Título qualquer que vc pode controlar',
      descricao: 'Descrição qualquer que vc pode controlar',
    }

    setId(id + 1)
    addAula(aula)
  }

  return (

      <button onClick={handleClick}>
        Adicionar aula
      </button>

      {
        aulas.map(item => {
          const {id, title, descricao} = item

          return (

              id = {id}

              title = {title}

              descricao = {descricao}

          )
        })
      }

  )
}


Compare less than today date & Autofill Issue

Question: Need help with my code. I have two issues.

1st issue is I try to make my code to loop if fulfill empty cell and date at column 1 less than today dateAnd .Cells(rw, 1) < Format(dt, "dd-mmm")but this < today date not able to work. The macro still continue even date is greater than today date
2nd issue is where i would like to autofill from column 5 to 9 from previous row. I keep encounter range errorSet rng = .Range(.Cells(rw - 1, 5), .Cells(rw, 9))
Selection.AutoFill Destination:=rng, Type:=xlFillDefault
andSelection.AutoFill Destination:=Range(.Cells(rw - 1, 5), .Cells(rw 1, 5)), Type:=xlFillDefault

Sub DataGrab()
Dim rw As Long, x As Range, rng As Range
Dim extwbk As Workbook, twb As Workbook

Set twb = ThisWorkbook
Set extwbk = Workbooks.Open("D:\Users\Desktop\Report " & Format(Now, "DD-MMM-YYYY") & ".xls")
Set x = extwbk.Worksheets("Summary").Range("A4:AF100")

dt = Date

With twb.Sheets("Sheet1")
    For rw = 3 To .Cells(Rows.Count, 1).End(xlUp).Row
        If .Cells(rw, 2) = "" And .Cells(rw, 1) < Format(dt, "dd-mmm") Then
            .Cells(rw, 2) = Application.VLookup(.Cells(rw, 1).Value2, x, 23, False)
            .Cells(rw, 3) = Application.VLookup(.Cells(rw, 1).Value2, x, 29, False)
            .Cells(rw, 4) = Application.VLookup(.Cells(rw, 1).Value2, x, 31, False)
            Set rng = .Range(.Cells(rw - 1, 5), .Cells(rw, 9))
            Selection.AutoFill Destination:=rng, Type:=xlFillDefault
            'Selection.AutoFill Destination:=Range(.Cells(rw - 1, 5), .Cells(rw 1, 5)), Type:=xlFillDefault
        End If
    Next rw
End With
extwbk.Close savechanges:=False
End Sub

Comment: Try changing of `.Cells(rw, 1) < Format(dt, "dd-mmm") ` with `.Cells(rw, 1) < CLng(dt) `. Excel doesn't care about the date format. It keeps the date as `Long`...
Comment: @DirkReichel stil encounter `Autofill method of Range class failed`
Comment: @FaneDuru `.Cells(rw, 1) < CLng(dt)` yes, this help. Thanks so much.
Comment: @LeoEY: Glad to help! I will transfer my comment to an answer... If you will tick the check box to the left side of the code, this will set it like accepted answer...
Comment: @FaneDuru thanks so much. Yup mark ticks on the comment. Left 2nd issue to troubleshoot
Comment: I must confess that I do not understand what "autofill from column 5 to 9 from previous row" means... Can you better clarify the issue?
Comment: @FaneDuru this excel is intended to copy cell value for column 2 to 4 based on the date. Then column 5 to 9 is formula calculate base on value in column 2 to 4. Example when row 4, column 1 to 4 data fill up, then I would like column 5 to 9 from row 3 autofill to  current row 4
Comment: @FaneDuru i found out the problem. The autofill occur at my external workbook instead of my active workbook. So I have to transfer `Range("E4").AutoFill Destination:=Range("E4:E" & Cells(Rows.Count, "D").End(xlUp).Row), Type:=xlFillDefault` to after `extwbk.Close savechanges:=False` external workbook close
Comment: @LeoEY: Good for you! In order to avoid such a situation, it is good to fully define your variables. Firstly, use `Option Explicit` on top of your module! This will oblige you to declare all variables. Then, never use `Range("A2")`! Use 'sh.Range("A2")`, where `sh` has previously being declared `As Workseet` and it has been set as a specific sheet: `Set sh = wb.Sheets("MySheet")`, where `wb` is the workbook (declared `As Worbook`) which has been set like: 'Set wb = Workbooks("MyWorkbook")`...
Comment: @FaneDuru Thanks for the tips. Gonna do some cleanup to my code. Thanks and appreciate for the helps!!!
Answer: (since I cannot comment, i'll do it through an answer)
first of all you should add Option Explicit at the beginning of your module. (this forces you to create variables before you give them a value)
next up, you have .Cells(rw, 2) = " " I assume you are trying to get the value of that cell?
if you add a MsgBox .Cells(rw, 2), in your code, you see that it will not return the value of that cell. thats why you need to use .Cells(rw, 2).Value
Also, we don't check an empty cell with " " but with if IsEmpty(.Cells(rw, 2).Value)
this should push you in the right direction :)
Comment: .Value can be empty. I just checked it in a sheet :)
Comment: @Nemoko i try with `.Cells(rw, 2) = " "' ` it doesn't work but if `.Cells(rw, 2) = "" ` without space in between `""`, then it works. As for date i change my code from `Format(dt, "dd-mmm")` to `CLng(dt)` and it works perfectly now.
Answer: Try changing of .Cells(rw, 1) < Format(dt, "dd-mmm") with .Cells(rw, 1) < CLng(dt) . Excel doesn't care about the date format. It keeps and operates date as Long.


Controle de Permissão em c# e Windows Form

Question: Eu gostaria de criar em C# com Windows Forms ( basicamente igual de permissão de pasta do Windows), níveis de acesso para os usuários, mas não como nível 1, 2 e 3, mas sim por exemplo:

Usuário A só pode visualizar um cadastro de cliente;
Usuário B pode excluir e deletar;
Usuário C pode visualizar só alguns campos do cadastro do cliente.

Qual seria a melhor forma de fazer isso?
Obrigado pela atenção
Comment: oi Amigo, boa noite, recomendo as leituras
https://www.codeproject.com/kb/miscctrl/application_login.aspx
https://www.codeproject.com/kb/cs/securebaseform.aspx
Comment: Muito complexo o que você quer para uma simples pergunta...
Answer: 1 - Uma tabela no banco com campos bool para guardar a permissão (um campo para cada item que você deseja alterar a permissão)
2 - Um objeto no seu sistema para receber os dados de permissão do banco;
3- Na inicialização do sistema ao logar você deve varrer os componentes setando o no componente.enable ou comente.visible o valor da permissão correspondente.
Answer: Você deve construir sua aplicação no formato "Baseada em Regras" (role-based em inglês).
Para isso, você pode fazer com que seus forms herdem alguns comportamentos específicos de controle acesso.
Aqui você encontra um tutorial detalhado de como fazer isso (em inglês).
Com tudo, esse tutorial não chega ao nível de campo (somente de formulários). Essa parte você precisará implementar "na mão" através da propriedade Visible dos componentes.

Uma outra forma de implementar é fazer o controle de acesso antes de abrir o form em si.
Normalmente utiliza-se um menu baseado em dados no banco de dados e esses dados podem definir se a opção do menu será exibida ou não.
Mas ainda assim, as permissões em nível de campo deverão ser implementadas manualmente.

Setar a propriedade Visibile para false pode acarretar em problemas de layout caso você não esteja utilizando classes específicas de layout (containers) no seu form.
Se ainda não utiliza, aconselho a leitura de FlowLayoutPanel e TableLayoutPanel


what is the unit of this rate of change?

Question: I'm given a table that shows the percent of Canadian households that used e-mail from year A to year B. Then what is the unit of the average rate of change of the percent of households using e-mails from year A to year B? Is it percent per year? I'm fine with dollars per year, miles per hour and so forth, but percent per year seems weird to me.
Comment: Yes, it would be percent per year.
Comment: Percent terminology can be a bit tricky. Suppose the values were $10\%$ in $2000$, and $20\%$ in $2001$. In a strict "unit-per-unit" sense, they rose "$10\%$ per year"; and yet, usage *doubled*, so it's also correct to say that it rose by "$100\%$ per year". To avoid confusion, we can use "percentage points" to describe changes in calculated percents;  hence, "$100$ percent/year" vs "$10$ *percentage-points*/year". ... Note: People are often casually careless —and sometimes intentionally deceptive— about this distinction. For the particular question, the distinction might be unimportant.
Answer: The unit of the average rate of change of the percent of households using e-mail from year A to year B would indeed be percent per year.
Here's why:
When we talk about the rate of change, we're essentially talking about how much something changes over time. In this case, the percentage of households using e-mail is changing over a period of time from year A to year B.
Percent is a unit of measurement that represents a portion of 100. So, when we say "percent per year," we're expressing the change in percentage over the course of one year.
For example, if the percentage of households using e-mail increased from $30%$ in year A to $40%$ in year B over a span of 5 years, the average rate of change would be $(40% - 30%) / 5 years = 2%$ per year. This means that, on average, the percentage of households using e-mail increased by $2%$ each year during that time period.


Form loaded with ajax call not having autocomplete enabled

Question: I have a form (loaded by obiumap function) that have a section loaded ( by function obiumap_addobj() ) with a $.ajax call from jQuery script (addobj.js) by clicking a button (addobj_btn). This new section is loaded in an
existing div (addobj-container) but without autocomplete functionality and also without default_value.
This is main form:
function obiumap($form, &$form_state) {
drupal_add_js(drupal_get_path('module', $this->modName) . '/addobj.js');
global $user;

$form=array();
$form['uid'] = array(
'#type' => 'hidden',
'#title' => 'uid',
'#default_value' => '3',
'#id' => 'uid',
);
$form=array();
$form['name'] = array(
'#type' => 'textfield',
'#title' => 'name',
'#id' => 'name',
);
$form['addobj_btn'] = array(
     '#type' => 'button',
     '#value' => t('Add new objects'),
     '#id' => 'addobj_btn'
);
$form['addobj-container'] = array(
        '#markup' =>  '

'
);
die(drupal_render_children($form));
}

This is section definition loaded via ajax:
function obiumap_addobj($form, &$form_state){
global $user;
$form=array();
$form['uid'] = array(
'#type' => 'textfield',
'#title' => 'uid',
'#default_value' => '10',
'#id' => 'uid',
);
$form['fldset_addobj'] = array(
'#type' => 'fieldset',
'#title' => t('Add new object'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
$form['fldset_addobj']['objname'] = array(
'#type' => 'textfield',
'#id' => 'objname',
'#title' => t('Object name'),
'#autocomplete_path' => 'obimap/obiumap_addobj',
'#required' => TRUE,
);
 $form['fldset_addobj']['submit'] = array(
'#type' => 'submit',
'#value' => 'Add object',
'#id' => 'addobj_btn'
);
die(drupal_render_children($form));
}

and this is addobj.js
function addItems(arg1, arg2) {
jQuery(document).ready(function() {
jQuery('#addobj_btn').click(function() {
var formURL = 'obiumap_addobj';
jQuery("#obiumap").submit(function(){
 return false;
 });
    jQuery.ajax(
    {
        url : formURL,
        type: "GET",
        data : { uid: jQuery('input[name=uid]').val() },
        success:function(data, textStatus, jqXHR)
        {
            jQuery('#addobj-container').html(data);
            console.log("###### Drupal.attach #####");
            Drupal.attachBehaviors("#addobj-container");
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
        }
    });

});

});
}

I really need autocomplete for that field but I don't now how to activate it.
Answer: If you want Drupal's autocomplete, you need to modify form using Form API '#ajax'. If you are doing it with your custom scripts, Form API will not know that field really belongs to your form, and will not handle field's calls.1
The way you should do it is:

In your form building function, create element with '#ajax' property, that will be responsible for loading your form part, or add it to existing element.
Also in your form building function, add an if that will check triggering element ($form_state['triggering_element']), and if that was your button, add entry in $form_state that new section should be visible.
If there is an entry mentioned in 2., output form part you want to be loaded with AJAX.
Use AJAX callback function only to select and return proper part of the form.

1 Simplified explanation, of course.


How enable PHPMailer to write complete persistent log?

Question: I am using the PHPMailer module to send emails to a user group (role) by a poormanscron-job.
I can see errors in my "recent log entry" view in the backend but I cannot get a persistant log with all log entries (I set the phpmailer settings to INFO or DEBUG level in the backend) somewhere.
I would like to check afterwards, who got the email and if there were dropped mails without errors (if that is possible).
Answer: It's not clear from your question what Drupal version you are on. But the Maillog / Mail Developer module might be handy here. Some more details about it (from its project page):

... provides an easy possibility to log all Mails for debugging purposes. It's possible to prevent the mails to being sent, so there is no need for an extra mail server to test the mail functionality of other modules or the drupal core. Additionally you can immediately display the mail through the Devel dpm() facility.

But you might get integration problems, since it's not easy and highly Drupal version dependent to get more than one email module at a time working.
Comment: I use the maillog module, and it seems to work well. I use with the SMTP  module though, not phpmailer.
Answer: Make sure that you are using the correct phpmailer version(library) php5 or 4.
Do not use SMTP and phpmailer MODULES together.
Try to connect to localhost (port 25) first.


Apigility Duvida nos Metódos

Question: Eu estou a usar o Apigility para criar Web Services Rest só que tenho uma duvida , eu posso acrescentar métodos na class   Resource  , se sim como é que consigo fazer uma chamar o método através do php.
Obrigado
Answer: Olá, a classe "Resource" no Apigility, tanto Rest como RPC é criada com os métodos que serão chamado pelo controller.
Você normalmente criar métodos dentro da classe e usá-los na própria classe com "$this". Se você pretende chamar estes métodos de outras classes, provavelmente existe algum erro de arquitetura pois a classe resource deve ser usada exclusivamente para responder a um request.
Se quiser detalhar mais seu problema, que tipo de método quer criar, posso ajudar mais.

Apigility Duvida nos Metódos


SVM mathematical background

Question: I try to get the basic understanding behing SVM algorithm, however I have a problem with basic mathematics.
I follow the lecture Support Vector Machine.

Suppose the two classes can be separated by a hyperplane:$(w \cdot x) + b = 0$

Acoording to wikipedia, hyperplane is defined as $n(r-r_0)=0$, does it mean that $b=-w \cdot r_0$?
I tried to consider 2-dimensional case, when $w \cdot x +b =0$ is a line, but it's completely doesn't make sense, $b=-w \cdot x$, where $b$ should be a constant, how can I generalize it to a 2 dimensional case.
In addition, why $w$ is actually orthogonal to the plus and minus plane?
Answer: suppose a plane (you can simplify it as a line too) w'*x + b = 0. If you take two vectors on the plane (it will be two points on the line) x1, and x2, since
w'*x1 + b = 0
w'*x2 + b = 0

we get,
w'*(x1 - x2) = 0

which is the same form as wiki definition you provided. This vector production is actually the dot product, and equivalent to the projection of vector x1 - x2 on w. The projection is zero, indicating w is orthogonal to the plane.
Comment: Thank you very much for your answer, you say I can simplify it as a line too, $w'*x+b=0$ but it's a "strange" line, as a line I expect to see something like y = k*x+b, but here $y=0$, so it is just X-axis?
Comment: Yes it is y=w'x+b, or f(x,b)=w'x+b. We just define f(x,b)=0 as the plane that will have the largest margin. f(x,b)=1 means the plane/line moves down by a unit distance but the slope keeps the same as w'. You can easily catch this by drawing a line y=x+1 and y=x. Here if we define x+1=0 as the control plane, x+1=1 refers to y=x, but it doesn't mean x is zero (that is not an equation)
Answer: take your hand as the plane, and a finger as the normal direction, then it should be clear that the plane is defined by two quantities, the direction of the normal and distance - how far your finger is planted in the plane. that distance is what b is representing.
so yes
b=-n.r_0
b is the distance of the hyperplane to the origin (assuming n is unit length). So all points on the plane have the same "perpendicular distance" to the origin, and that's why you have a constant b , on the one side, and a seemingly varying quantity w.x on the other side.
draw a plane, and a line joining the origin to any arbitrary point in the plane, together with the shortest line joining the origin to the plane (which is precisely the one that enters the plane at right angles). Then you can decompose all points on the plane as a vector from the origin to closest point on plane together with an orthogonal vector within the plane. So that distance from origin to closest point doesnt change and that is what is giving you b.

SVM mathematical background


I need help in this integral

Question: $$\int_{-\infty}^\infty e^{-\alpha x^2}\sec{h^2}(x)\sum_{n=0}^\infty \frac{H_n(x\sqrt\alpha)}{\sqrt{2^n n!}}\sum_{m=0}^\infty \frac{H_m(x\sqrt\alpha)}{\sqrt{2^m m!}}dx \vert$$
$H$ is the Hermite polynomial.
$\alpha$ is a positive quantity.
As you know, because of the following relation:
$$H_n(-x)=(-1)^nH_n(x)$$
this integral is nonzero if both $m$ and $n$ be positive or negative. Please consider the positive case.
Comment: Can we see your attempt? Or at least how you thought this might be resolved?
Answer: By starting with the integral
\begin{align}
I_{n}^{m} = \int_{- \infty}^{\infty} e^{- \alpha t^{2}} \ sech^{2}(t) \ H_{n}(\sqrt{\alpha} t) H_{m}(\sqrt{\alpha} t) \ dt
\end{align}
and the generating function it is seen that
\begin{align}
\sum_{n=0}^{\infty} \sum_{m=0}^{\infty} I_{n}^{m} \frac{ x^{n} y^{m} }{n! m!} &= \int_{- \infty}^{\infty} e^{- (\alpha + 2) t^{2}} \ e^{2 \sqrt{\alpha} (x+y) t} sech^{2}(t) \ dt \\
&= e^{\alpha (x+y)^{2}/(\alpha +2)} \ \int_{- \infty}^{\infty} e^{-(\sqrt{\alpha+2}t - p)^{2}} sech^{2}(t) \ dt,
\end{align}
where
\begin{align}
p = \sqrt{\frac{\alpha}{\alpha+2}} (x+y).
\end{align}
Complete the integral and then evaluate the result to obtain $I_{n}^{m}$.

I need help in this integral


Campo com formato DateTime não altera o formato para Date - Asp.net MVC

Question: Preciso fazer com que seja mostrado apenas o formato de data em um campo do tipo DateTime, mas estão aparecendo apenas letras no campo (mesmo que a propriedade value contendo uma data).

VIEWMODEL:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
[DataType(DataType.Date, ErrorMessage = "Data em formato inválido")]
[DisplayName("Data de Emissão")]
public DateTime DataEmissao { get; set; }

RAZOR:
<input type="date" asp-for="DataEmissao" id="financeiro-parcela-data-emissao" class="form-control" />

HTML:
<input type="date" id="financeiro-parcela-data-emissao" class="form-control" data-val="true" data-val-required="The Data de Emissão field is required." name="DataEmissao" value="03/11/2020 00:00:00">

Alguém sabe como resolver?
Obrigado :)
Comment: é do próprio navegador isso ai
Comment: O Interessante @ novic é que se eu alterar type="date" para type="datetime", no razor, ele funciona corretamente, mas exibindo data + hora... eu queria apenas que fosse a data...
Comment: o `datetime` inclusive parece que está depreciado kkk se não me engano. besteira essa mudança
Answer: Descobri, sem querer, o problema.
Estava chamando uma janela Modal a partir de outra Modal. Por algum motivo, a Controller não estava criando o prefixo da Modal que deveria ser "FinanceiroParcelaViewModel". Isso, por algum motivo, atrapalhava a exibição das datas, pois fazia como que os campos entendessem que estava null, quando na verdade, estavam "setados" com suas respectivas datas.
Solução:
[HttpGet]
[Route("financeiro-parcela-gerenciar/editar-financeiro-parcela")]
public IActionResult EditFinanceiroParcela(FinanceiroParcelaViewModel financeiroParcelaViewModel)
{
    ViewData.TemplateInfo.HtmlFieldPrefix = "FinanceiroParcelaViewModel"; //Acrescentei esta linha.
    return View(_financeiroParcelaAppService.UpdateAttributes(financeiroParcelaViewModel));
}


Conditional probability, balls, urns and a coin

Question: We are given $2010$ numbered balls and $2$ urns.
Firstly, we throw a symmetric coin $2010$ times.
If at the $i-$th throw we get heads, we place the $i$-th ball in the first urn.
If we get tails, we place it in the second urn.
Then we randomly pick a number $1 - 2010$ (in such a way that choosing each of the numbers is equally probable) and we place the ball with this number in the other urn. That is, if at the first stage the $i$-th ball was in the first urn and we have now picked number $i$, we take the out and place it in the second urn.
For what $k \in \{0, ..., 2010\}$ is the probability that before the transfer there are $k$ balls in the first urn bigger than after the transfer?
Could you explain to me, more or less step-by-step, how to deal with such problems?
Thank you!
Answer: Well, since the placement process is precisely equivalent to that of choosing a uniform number $i$ from 1 to 2010, then placing all balls other than $i$ into urn A on heads and urn B on tails, but placing ball $i$ into urn A on tails and urn B on heads.  Since the probabilities of heads and tails are equal, we could notice that the before and after probabilities are equal for any $k$.  So the answer is, no values of $k$ give you higher after probability.
But let's say you didn't notice this semi-clever way of looking at it, and wanted to tackle the problem head-on.
For this sort of problem I always start by looking at an extreme case, to see if it gives me some insight.  Take $k = 0$ -- is the probability of $0$ balls in urn A before the transfer bigger or smaller than after the transfer?  Well, we know how to get $0$ balls before the transfer ( $P = 2^{-N} \binom{N}{0} = 2^{-2010})$; and to get $0$ balls after the transfer there needed to be $1$ ball before the transfer and we needed to get lucky, moving that ball out instead of one of the 2009 balls in ($P = 2^{-N} \binom{N}{1} \frac{1}{N} = 2^{-N} \frac{N}{N}$.
So we see that for $k=0$ the probabilities are equal, but more importantly, we see how to express the "after" probability.  the next step is to generalize that:
$$
\begin{array}{c}
P_{\mbox{before}}(k) = 2^{-N} \binom{N}{k} \\
P_{\mbox{after}}(k) = P_{\mbox{before}}(k-1)\frac{N-(k-1)}{N} + P_{\mbox{before}}(k+1)\frac{k+1}{N} \\
P_{\mbox{after}}(k) = 2^{-N} \left[ \binom{N}{k-1} \frac{N-k+1}{N}
+ \binom{N}{k+1} \frac{k+1}{N}
\right]
\end{array}
$$
The third step is to do the math for the comparison.  Taking out the common factor $2^{-n}$ we see that the after probability is greater if
$$
\binom{N}{k-1} \frac{N-k+1)}{N} + \binom{N}{k+1} \frac{k+1)}{N} > \binom{N}{k}
$$
And we can factor out $\binom{N}{k}$ because it is easy to write the neighboring binomial coefficients in terms of $\binom{N}{k}$ (for example, $\binom{N}{k-1} = \frac{k}{N-k+1} \binom{N}{k}$ and $\binom{N}{k+1} = \frac{N-k}{k+1} \binom{N}{k}$ ). The condition becomes
$$
\frac{k}{N-k+1} \frac{N-k+1}{N} + \frac{N-k}{k+1} \frac{k+1}{N} >1
$$
which simplifies to $ 1 > 1$.  So the probability after is always, for any $k$, equal to the probability before.
Comment: Yes, from your words, you understand this correctly.
Comment: Thank you a lot. I have one question about calculating the after probability. If we want $k$ balls to be in A after the transfer, we needed to have $k-1$ balls to be in A before the transfer and take the right ball from B and place it in A (we cannot choose the numbers that are already in A, hence $\frac{N-(k-1)}{N}$) or have $k+1$ balls in A and transfer one of them to B - we need to choose one of the $k+1$ numbers that are in B. Do I understand the formula correctly?


Tkinter How to cut widgets and labels that go beyond frame width?

Question: In my Code the user can add text and widgets to a Frame. Sometimes the row ends with a combobox, sometimes with a label.
Sometimes these widgets go beyond the Frame.
Is there any way to place widgets like Combobox in second row and to cut labels at the end of the frame and place the rest of it also in the second row.
Thanks for help!

Working minimal code:
from tkinter import *
from tkinter import ttk
import re
import tkinter

root = Tk()
root.resizable(False, True)
bframe = Frame(root, width=300, height=50)
bframe.grid(row=0, column=0, sticky = W)
bframe.grid_propagate(False)

linelist1 = ['some long text 1 as a label', '@combo@Aa Bb Cc Dd', 'some long text 2 as a label', 'some long text 3 as a label', '@combo@Ee Ff Gg Hh', 'some long text 4 as a label']
lines_with_combobox = [e for e, s in enumerate(linelist1) if '@combo@' in s]

for line in range(0, len(linelist1)):
    if line in lines_with_combobox:
        delete_combo_marker = re.split("@combo@", linelist1[line])
        words = delete_combo_marker.pop(0)
        word_as_values = re.split('\s+', delete_combo_marker[0])
        combobox = ttk.Combobox(bframe,width=10, values=word_as_values)
        combobox.grid(row=0, column=line, sticky= W)
    else:
        text = linelist1[line]
        Labeltext = ttk.Label(bframe, justify=LEFT ,text=text, wraplength=730)
        Labeltext.grid(row=0, column=line, sticky = W)

root.mainloop()

Comment: #root.resizable(False, True)
bframe = Frame(root, width=80, height=100)
Comment: combobox.grid(row=line1, column=1, sticky= W) and Labeltext.grid(row=line, column=0, sticky = W). I got 4 labels and 2 combox
Comment: Do you require actual columns? For example, if a combobox wraps to the second row and it's widget than the label, so the column grow? In other words, do you require a literal grid, or is your requirement just a list of rows with content that varies in size?
Comment: @Bryan Oakley. I just found in line 12. Something is missing keyword.
Comment: @Bryan Oakley there are long rows of widgets. What i need is a way to detect the end of the frame and then wrap the widgets that get out of the frame into another row.
Comment: So, to be clear, you _don't_ need columns, you just want widgets to wrap?
Comment: No, i dont need columnd i need the widgets to wrap. But i need som kind of way to mark the position of the widget. And until now i used columns to find out the location of the widget in the row
Answer: A simple solution for putting widgets in a row and having them wrap when they do not fit is to use a text widget to manage the other widgets. A text widget has wrapping features built in.
Here's an example that creates a couple of rows of widgets that need to wrap. Once the UI opens, you can resize it to see the widgets dynamically adjust to the width of the window.
import tkinter as tk

data = """
The cow is of bovine ilk;
One end is moo, the other is milk.
"""

root = tk.Tk()
text = tk.Text(root, wrap="char", background=root.cget("background"))
text.pack(fill="both", expand=True)

for line in data.strip().split("\n"):
    for word in line.split(" "):
        label = tk.Button(text, text=word)
        text.window_create("end", window=label)
    text.insert("end", "\n")
text.configure(state="disabled")

root.mainloop()

Comment: This is almost the perfect solution. The only problem ist that I rely heavily on grid column information with .grid_info(), to later get the postion of the widget. But ill just use textvariable=line and the solution you gave. Thanks alot.
Comment: do you know any way to connect additional information like the line to a widget. like v = label['information_variable']
Comment: @Kazkuris Each widget can be a class based on a frame, with as much other information and other widgets as you want.
Comment: @Kazkuris This solution doesn't put the widgets in a grid. Your question was unclear on whether you needed a grid or just a row that wraps. This gives you the ability to create a row that wraps.


MacOS + apache + mod_wsgi + django: what's a correct folder layout and permissions for web apps?

Question: I'm testing django right now on Max OS X Snow Leopard Server. I have compiled mog_wsgi for build-in apache/python and enabled it in apache via LoadModule wsgi_module. I have also installed django via standard python setup.py install command. After that, i have created a test django application by named webtest in ~/Documents and enabled it in Apache via WSGIScriptAlias / /Users/me/Documents/webtest/django.wsgi (django.wsgi is a file i have created manually).
As expected, nothing works with cryptic "access to /error/HTTP_FORBIDDEN.html.var denied" apache error. As google says, that is most probably reads like 'apache was not able to read script file'. Ok, i have changed sudo chmod -R 777 /Users (calm, it's a virtual PC :) - and all works just fine.
So, the question: what is a recommended folder structure for my django apps in described configuration and what permissions i need? 777 is not for production :)
Answer: 0755 (directories) and 0644 (files) should be plenty, but under a user's home directory is not the normal place for a web app regardless. /srv is the new place to put them, but this isn't found in a standard OS X installation.


Using mongoDB how can i prevent someone from using the same username as someone else?

Question: I have a form where a user is supposed to put in there nickname, the issue is I need the nickname to be unique, in that no one else should be able to make there nickname the same as someone elses. Is there a fix for this using only mongoDB and not mongoose?
var bodyParser = require("body-parser");
var express = require("express");
var app = express();

var PORT = 3332;

app.use("/", express.static(__dirname));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

mongoose.connect("mongodb://localhost/gtra", {
  useNewUrlParser: true
});

var db = mongoose.connection;
db.once("open", function(cb) {
  console.log("connection established");
});

app.post("/addname", (req, res) => {
  var name = req.body.pickname;
  var data = {
    nickname: name
  };
  db.collection("dat").insertOne(data, function(err, coll) {
    if (err) throw err;
    console.log("rec estab");
    res.redirect("/");
  });
});

app.listen(PORT, function() {
  console.log("server is up and running using port " + PORT);
});

Comment: Did you check my  answer?
Comment: just did, and it worked thank you :)
Answer: You can check if there is already a username in the collection, if exists you can throw exception.
app.post("/addname", (req, res) => {
  var data = {
    nickname: req.body.pickname
  };

  db.collection("dat").findOne({ nickname: data.nickname }, function(err, doc) {
    if (err) throw err;

    if (doc) {
      return res.status(400).send("Nickname already taken"); //or throw whatever you want
    } else {
      db.collection("dat").insertOne(data, function(err, coll) {
        if (err) throw err;
        console.log("rec estab");
        res.redirect("/");
      });
    }
  });
});

Another option is creating a unique index on the nickname field.
db.users.createIndex( { "nickname": 1 }, { unique: true } )

Change users to your collection name.


how to replace abusive words php

Question: hello all i have a page where i need to replace all the occurrence of some particular words which may be abusive  with a image (same image for all the words)  and i have following function which does the work but it is case sensitive . like it replaces f*k  but not f*k  f*k f*k  f**k  etc.. and i think there is a better way to do this please help .
my function is
function filter($text) {
    $icons = array(
            'f**k '    =>  '',
            'something else'    =>  '',
            ' something else'   =>  ''
    );
    return strtr($text, $icons);
}

Comment: Just be careful with what you do, or I might find you and buttbuttinate you! :p
Answer: You'd need a bigger filter based on RegEx for this
Like this:
function filterAbusiveWords( $string ) {

    static $abusiveWords = array(
        '/f[u]+c?k/i' => 'some icon',
        '/f[\*]+c?k/i' => 'some icon',
        '/f[a]+c?k/i' => 'some icon',
        '/some normal word/i' => 'some icon'
    );

    return preg_replace( array_keys( $abusiveWords ), array_values( $abusiveWords ), $string );
}

This would (in theory) replace all occurences of fak, fuck, f**ck, f*k, faaak, fuk etc.
Comment: but there are hundreds of other word that i need to filter i can not do this way to filter them this is quite long process..
Comment: man your answer is acceptable can you just explain me a little how do i do this with other words . say rahul,sandeep etc.. can you just explain me a little ablut the /[]+?i etc please please...
Comment: Explaining Regular Expressions could take days and a lot more space than this comment field. In short: Everything in [] means "characters of this set", + means "one or more times", * means "0 or more times", ? means "optional" at the end of a statement, i means Case-Insensitive, / are just separators you have to set. For more just read something about Perl Regular Expressions, these are used here

how to replace abusive words php


Find sets of points, where function from one topological space to another is continuous.

Question: We have got two functions :
$f(x,y) = (2x,y)$
$g(x,y) = (x+1,y) $
They are transormations from one topological space to another ( from $ (\mathbb{R^2}, \tau')$ to $ (\mathbb{R^2}, \tau'')$ ), where $ \tau'$ is topology induced by rail metric and ,$\tau''$ ais topology  induced by river metric. We need to find sets of points, where the function is continuous.
So, there'll be 4 possibilites  for every function :
river into river
river into rail
rail into river
rail into rail
RAIL METRIC - $$d(x,y) =\begin{cases} \lVert x-y\rVert & \text{if }x,y\text{ and }0\text{ lie on the same line,}\\ \lVert x\rVert + \lVert y\rVert & \text{otherwise,} \end{cases}$$ where $\lVert\cdot\rVert$ is the standard Euclidean norm on $\Bbb R^2.$
RIVER METRIC - $$d(x,y) =\begin{cases} \lvert x_2-y_2\rvert & \text{if }x_1 = y_1,\\ \lvert x_2\rvert + \lvert x_1 - y_1\rvert + \lvert y_2\rvert & \text{otherwise.}\end{cases}$$
Could anyone help me to understand idea of problem like this?
Comment: I'm not familiar with "rail metric" or "river metric." Can you include those definitions in your question? (Also, it seems that you should have $\Bbb R^2$ in both cases, rather than $\Bbb R$.)
Comment: What's the definition of "rail" and "river" metrics?
Comment: http://wwwf.imperial.ac.uk/~svanstri/Files/ma222.pdf They are called "French railway metric" and "Jungle river metric"
Comment: My compliments on an interesting question! I have to head out the door shortly, but if it remains unanswered when I return this evening, I will take a crack at it. I *will* say, though, that it would be to your benefit to know what the open balls in the two metrics look like. Note that they will differ in shape, depending on where they are "centered" and what the "radius" is.
Comment: I do know how they look like. At first we have to ascertain if transformations are continuous ( check whether or not preimage of some set in an image belongs to topology in domain )
Comment: $f$ from rail into rail is cont. all over $\mathbb{R^2}$. From river into river as well. from river into rail and from rail into river $f$ is continuous all over X axis and Y axis. $g$ rail into rail is cont. in $\mathbb{R}|{(0,0)}$, river into river in $\mathbb{R^2}$, rail into river in X axis and Y axis, river into rail all over line $x=-1$. It's only my intuition I don't know formal proof
Answer: Some HINTS:

Assume that $a\ne 0$, and let $p=\langle a,b\rangle$. For $n\in\Bbb N$ let $p_n=\langle a,b+2^{-n}\rangle$; then $\langle p_n:n\in\Bbb N\rangle\to p$ in the river metric. Does $\langle g(p_n):n\in\Bbb N\rangle$ converge to $g(p)$ in the rail metric? Does $\langle f(p_n):n\in\Bbb N\rangle$ converge to $f(p)$ in the rail metric?
Assume further that $b\ne 0$, let $m=\frac{b}a$, and for $n\in\Bbb N$ let $q_n=\langle a+2^{-n},m(a+2^{-n})\rangle$; then $\langle q_n:n\in\Bbb N\rangle\to p$ in the rail metric. Does $\langle g(q_n):n\in\Bbb N\rangle$ converge to $g(p)$ in the river metric? Does $\langle f(q_n):n\in\Bbb N\rangle$ converge to $f(p)$ in the river metric? What if $b=0$?

It may be useful to note that all four image sequences converge to $p$ in the usual metric on the plane.


Must have a body because it is not marked abstract, extern, or partial

Question: Not entirely sure why I'm getting this error. Looked up and down the code for a few hours but I assuming it's a simple fix. Some of the code is copied over from a video and his works perfectly fine, so I don't know why it'd cause me any issues:
using UnityEngine;
using System.Collections;

public class GoldPerSec : MonoBehaviour {

    public UnityEngine.UI.Text gpsDisplay();
    public Click click;
    public ItemManager[] items;

    void Start() {
        StartCoroutine(AutoTick());
    }

    void Update() {
        gpsDisplay.text = GetGoldPerSec() + " gold/sec";
    }

    public int GetGoldPerSec(){
        int tick = 0;
        foreach (ItemManager item in items) {
            tick += item.count * item.tickValue;

        }
        return tick;
    }

    public void AutoGoldPerSec() {
        click.gold += GetGoldPerSec();
    }

    IEnumerator AutoTick() {
        while (true) {
            AutoGoldPerSec();
            yield return new WaitForSeconds(1);
        }
    }
}

Answer: The problem is in
public UnityEngine.UI.Text gpsDisplay();

That is a method declaration, but there's no code inside the method.
It's unclear from the context what that should actually be. If it's a method, you can either implement it in this class, like
public UnityEngine.UI.Text gpsDisplay()
{
     return <something useful>;
}

Maybe it shall be a method and you want to implement it in a subclass, then mark the class as abstract:
public abstract class GoldPerSec : MonoBehaviour

Perhaps it should have been a field, then use
public UnityEngine.UI.Text gpsDisplay;

without the parentheses.
Comment: Either remove the () to make it a member variable or add a code block { } to actually make it a method.
Comment: @Grisgram: I was in the middle of adding that. Thanks.
Comment: I didn't mean to set gpsDisplay as a function, so that is what caused the issue. Thank you so much!
Answer: I got this error when I mistakenly added ; before method body. Removing ; stops compiler error.
==My Code. Look ; on very first line ===
      public string ReadPopMessage(String identifierOfElement, String elementKey);
        {

        //string elementID;
        elementID = ConfigurationManager.AppSettings.Get(elementKey);
        Console.WriteLine("The value of" + elementKey + "is " + elementID);
        //MessageBox.Show(elementID);

        string strPopupText = oWD.FindElement(By.CssSelector(elementID)).Text;
        return elementID;

        }

Comment: While your answer does provide help for someone who might run into this issue with a similar situation, it does not apply to the original question given the code sample posted.


How to bring the application to the front?

Question: Currently copied and modifying a portion of a coding within the same program to create a button that when clicked will bring the Vision application to the front of the GUI.

Created a button called "btVisionCam_Click()"
Declared "Private lVideo As Long"
CEIVidCap is the Vision application that is running behind of the GUI when the GUI is opened

Private Sub btVisionCam_Click()

    If btVisionCam.Value = 1 Then
        lVideo = FindWindow(vbNullString, "CEIVidCap")
            If lVideo = 0 Then
                lVideo = Shell("C:\machine\appls\CEIVidCap.exe", vbNormalFocus)
            End If
    End If

End Sub

When the button is clicked, it does not bring the Vision application to the front of the GUI. Please help, thanks!
Answer: Create a module and copy the following declarations:
Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Declare Function ShowWindow Lib "user32" (ByVal hwnd As Long, ByVal nCmdShow As Long) As Long

Then in your button, as you are already doing, use FindWindow to get the window handle and use ShowWindow to bring it up:
Dim lnghWnd As Long

lnghWnd = FindWindow(vbNullString, "CEIVidCap")
ShowWindow lnghWnd, 1

Supported values for nCmdShow parameter of ShowWindow:
SW_HIDE = 0
Hide the window.
SW_MAXIMIZE = 3
Maximize the window.
SW_MINIMIZE = 6
Minimize the window.
SW_RESTORE = 9
Restore the window (not maximized nor minimized).
SW_SHOW = 5
Show the window.
SW_SHOWMAXIMIZED = 3
Show the window maximized.
SW_SHOWMINIMIZED = 2
Show the window minimized.
SW_SHOWMINNOACTIVE = 7
Show the window minimized but do not activate it.
SW_SHOWNA = 8
Show the window in its current state but do not activate it.
SW_SHOWNOACTIVATE = 4
Show the window in its most recent size and position but do not activate it.
SW_SHOWNORMAL = 1
Show the window and activate it (as usual).

Comment: Please update your question with your current code so we can help troubleshoot
Comment: Hi Étienne Laneville, the codes still doesn't work.. When i clicked on the btVisionCam button the CEIVidCap window doesn't show up in front of the GUI. Another thing to point out is when the GUI is opened, the CEIVidCap window is already maximized and running behind of the GUI. Hope someone can help me to make it show up in the front of the GUI when the button is pressed..
Answer: Try setting it as the foreground window.
Add this to your other API calls:
Declare Function Win32_SetForegroundWindow Lib "user32" _
    Alias "SetForegroundWindow" ( _
    ByVal hWnd As Long) _
As Long

Then add:
Dim Ret As Long
Ret = Win32_SetForegroundWindow(lnghWnd)
If Ret Then
    ' Your window should be foreground
End If


Inconsistent results when using selenium and when manually clicking

Question: I am trying to automate logging into my salesforce account. When I use my code:
<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser= webdriver.Firefox()
browser.get("https://xxxxx.my.salesforce.com/?
SAMLRequest=&startURL=%2Fidp%2Flogin%3Fapp%
3D0sp0g000000Gmhj&un=xxxxx.xxxxx%40xxxxx.com")

elem=browser.find_element_by_id("username")
elem.send_keys("firstname.lastname@example.com")
elem_pass=browser.find_element_by_id("password")
elem_pass.send_keys("xxxxxxx")
rem_me=browser.find_element_by_id("rememberUn")
rem_me.click()
elem.send_keys(Keys.ENTER)
</code>
As you can see, I pass the link to the url, pass the usname, password and remember me.
When I run this with Selenium, it goes to a email 2FA authentication page.
But when I do it manually:
Copy the url mentioned above.
Paste it into the address bar of firefox browser.
The uname and pass show already populated.
When I hit enter, it logs me in. (No 2FA).
Is Salesforce somehow detecting that request is from selenium?
And is there a way to get around it?
Could this be related to this?
Different results when using Selenium + Python
Comment: Yup, I got it resolved. I had to import cookies from Firefox, and use them with Selenium.

    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    import os
    os.chdir("C:\\Users\\tsingh\\Desktop\\Cookies")
    ffprofile = webdriver.FirefoxProfile('C:\\Users\\tsingh\\Desktop\\Cookies')
    browser = webdriver.Firefox(firefox_profile=ffprofile)
Comment: Are you doing the same manually in incognito mode? Because selenium runs by default in incognito mode. Probably it is the reason for difference
Comment: @SunnySingh Add the resolution you mentioned as a comment as the answer for the benefit of the future readers.
Answer: Yup, I got it resolved. I had to import cookies from Firefox, and use them with Selenium. from selenium import webdriver from selenium.webdriver.common.keys import Keys import os os.chdir("C:\Users\tsingh\Desktop\Cookies") ffprofile = webdriver.FirefoxProfile('C:\Users\tsingh\Desktop\Cookies') browser = webdriver.Firefox(firefox_profile=ffprofile)


same cross-validation set for parameter tuning and RMSE calculations

Question: I miss some very basic distinction between cross-validations used for parameter tuning and cross-validation used for calculating the performance of my algorithms (RMSE).
I have two functions: one performs grid search and the other calculates cross-validated RMSE.
def grid_search(clf, param_grid, x_train, y_train, kf):
    grid_model = GridSearchCV(estimator = clf,
                              param_grid = param_grid,
                              cv = kf, verbose = 2)
    grid_model.fit(x_train, y_train)

def rmse_cv(clf, x_train, y_train, kf):
     rmses_cross = np.sqrt(-cross_val_score(clf, x_train, y_train, scoring="neg_mean_squared_error", cv = kf))
     return rmses_cross

The functions are called this way:
X_train, X_test, y_train, y_test =  train_test_split(dataset, Y, test_size=0.2, random_state=26)
kf = KFold(10, shuffle = True, random_state = 26)

grid_search(clf, param_grid, X_train, y_train, kf)
# adjust parameters of a regressor
rmses_cross = rmse_cv(clf, splits, X_train, y_train, kf)

As you see I use the same KFold for my parameter tuning and exactly the same KFold set for my calculation of cross-validation RMSE.
And on basis of the calculated cross RMSEs I chose which algorithms performs better. BUT RMSEs are calculated exactly on the same folds on which hyper parameter tuning was performed.
Is it incorrect to do so? I feel that while tuning my model learns on the hold-out folds and it would be incorrect to use them when calculating the RMSEs. Should I choose different KFold for calculation of RMSE?
EDIT:
Why do those two codes produce two different results? I though the cross_val_score refits a given model to each fold. And therefore applying cross_val_score on grid_model or parameterised model should be the same.
kf = KFold(10, shuffle = True, random_state = 26)

First:
grid_model = grid_search(clf, param_grid, X_train, y_train, kf)
grid_model.fit(x_train, y_train)
clf = SVM(kernel='rbf',C=grid_model.best_params_['C'])
rmses_cross = np.sqrt(-cross_val_score(clf, x_train, y_train,
                      scoring="neg_mean_squared_error",cv = kf))

Second:
grid_model = grid_search(clf, param_grid, X_train, y_train, kf)
grid_model.fit(x_train, y_train)
rmses_cross = np.sqrt(-cross_val_score(grid_model, x_train, y_train,
                      scoring="neg_mean_squared_error", cv = kf))

Comment: Just a reminder that **R**oot**MSE** is [**subadditive**](https://math.stackexchange.com/questions/1588776/subadditivity-of-square-root-function) and should only be calculated at the very end -- and based on *"all"* **S**quared **E**rrors.
Answer:
RMSEs are calculated exactly on the same folds on which hyper parameter tuning was performed.
  Is it incorrect to do so?

yes.

I feel that while tuning my model learns on the hold-out folds and it would be incorrect to use them when calculating the RMSEs. Should I choose different KFold for calculation of RMSE?

yes.

What you need to do is called nested cross validation.
I recommend treating the hyperparater tuning as part of model training (that's a particular point of view on what nested cross validation or a train/optimize/valdation (aka train/validate/test depending on your field) split does.
Briefly, you have 3 functions:

a bare bone (low level) training function (clf (training_data, hyperparameters)) w
a tuned model (high level) training function that internally does the hyperparameter fitting (grid_search (training_data))
a testing funcion (rmse_cv)

Now, as you want to measure the performance of the ready-to-use tuned model, you call rmse_cv on the tuned model training function: rmse_cv (grid_search, dataset)
(regardless of whether or not grid_search makes internal use of rmse_cv for tuning purposes as well).
See also here.
Comment: I followed the example [here](http://scikit-learn.org/stable/auto_examples/model_selection/plot_nested_cross_validation_iris.html). And they use the same KFold for inner and outer loop but exactly how you mentioned, they insert grid_search classifier into rmse_cv function. What is the difference between rmse_cv(grid_search, dataset) and taking the best_parameters from grid_search, updating the classifier and doing rmse_cv(clf,dataset)? (I updated my question)


Fixed point and fractional iteration: if $F(k)=k$ then $F^{1\over n}(k)$ is another fixed point of $F$

Question: My knowledge of the fixed points and iteration equals zero, same for the notation and terminology but I really need to know if this deduction has trivial errors or is really as nice as it seems.

I would like to prove the following:
Notation 1 - Given a function $f:A\rightarrow A$ define the set $Fix(f)\subseteq A$ as the set of $f$'s fixed points
$Fix(f):=\{\phi:f(\phi)=\phi\}$
Notation 2 - Given a function $f:A\rightarrow A$ and the definition of function composition $\circ$ define the function $f^n$ by recursion
$i)$ $f^0:=\operatorname{id}_A$
$i)$ $f^{n+1}:=f\circ f^n$
Definition 1 - Given a function $F:X\rightarrow X$, the " $1\over n$-iterate" of $F$ is a function $\Psi:X\rightarrow X$ with this property
$\forall x(x\in X) (\Psi^n(x)=F(x))$
I guess that we can write $\Psi=F^{1\over n}$

To Prove - If $k\in X$ is a fixed point of $F$ and exists a fucntion $\Psi$ such that $\Psi^n=F$ then $F^{1\over n}(k)$ is a fixed point of $F$
$$k\in Fix(F)\implies \forall n(n\ge1)(F^{1\over n}(k)\in  Fix(F))$$

Proof 1 - For a fixed $n\gt 1$ define $\lambda:=\Psi(k)=F^{1\over n}(k)$
$\lambda:=\Psi (k)=\Psi(\Psi^n(k))$ because $k=\Psi^n(k)$
$\lambda=\Psi^n(\Psi(k))$ because iterates commute
$\lambda=\Psi^n(\lambda)$ because $\Psi(k)=\lambda$ by definition
Since $\Psi^n=F$ by definiton we conclude that $\lambda=F(\lambda)$ and thus
$$\lambda\in Fix(F)$$
Anyways this proof seems weird to me... I feel like there is something missing: I want to prove that for every natural number (greater than zero), if $F^{1\over n}$ exists,  $F^{1\over n}(k)$ is a fixed point so maybe I need to use induction but I really don't know how I could do it

Questions

$1)$ - Is this proof correct? If yes and it is a known result, can you
   add some info about it?
$2)$ - Is it possible to use induction for the proof? Or it is useless?
$3)$ - If the proof is correct, is this a result that can be
   strengthened? In fact it seems to me that the real generalized result
   would be something like $$k\in Fix(F)\implies \forall q(q\in\Bbb
 Q\land 0\lt q \lt 1)(F^{q}(k)\in Fix(F))$$
Comment: I don't know whether this is relevant, but I've one time stumbled on the problem of ***self-intersecting*** flows in the iteration of the exponentiation, which means in some mysterious way, that ***the same*** complex point could be arrived by different iteration-heights (and so should be a fixed point) but also been left on different pathes. I do not yet understand that phenomen (if it were one at all, I still scratch my head). It was for instance discussed on this post in the tetration-forum http://math.eretrandre.org/tetrationforum/showthread.php?tid=499&pid=5133#pid5133 and other places.
Comment: MphLee, sorry, it's just over my head at this days; I just wanted to give that reminder of an older discussion (which also had let me headscratching until today... ;-)) I hope someone else shall help out here.
Comment: One more reminder. Of course, if we have $F$ has a fixpoint, say $F(t_0)=t_0$ and $\Psi$ as some $1/n$ iterate of $F$ with the property that $t_1 = \Psi(t_0) \ne t_0$ but $\Psi^{on}(t_0)=t_0$ then what you say should be obvious, and a set of points $t_0,t_1,...,t_n=t_0$ occurs. But even more should be expected for the generalization of $\Psi$ for continuous iterations: then instead of a set of points $t_0,t_1,...,t_n=t_0$ we should have a continuous curve (if in the complex plane). I considered one time a bizarre effect when then curve became fractal (and possibly some of (....)
Comment: (...) your mentioned/assumed properties possibly do no more hold. I'd marked that discussion with the term "equator" and made some pictures for the tetration-forum, where also Sheldon made some nice comments. Perhaps this is interesting as well. See http://math.eretrandre.org/tetrationforum/showthread.php?tid=120&pid=6026#pid6026 for instance, but all posts around it are related. Closing remark: sorry that the discussion of *tetration* comes so dominant here, I found it surely interesting for the more general case of iterated functions as properly adressed by your question.
Comment: Definition (1) does not hold $\forall x$ if the half iterate is not entire...  I will post exactly an example for which this is the case.  Then, we can have the case where $h^{o2}(x)=F(x)$ within some radius of convergence. But call one of the other fixed points $L_1$, $h(L_1)=z \land $h(z)=L \land F(z)<>z$
Comment: @GottfriedHelms you mean that exist $h\lt i$ such that $\exp_b^h(x_0)=\exp_b^i(x_0)$? In that case, if $\delta=i-h$ then $\exp_b^{\delta}$ should go **ideally** from $\exp_b^{h}(x_0)=x_h$ to $x_h$ itself so

1- $\exp_b^{h}(x_0)=x_h\in Fix(\exp_b^\delta)$

2- $x_0\in Fix(\exp_b^{\delta})$

Anyways this is only **ideally** because the fact itself that the flow do intersect Imo implies the non-injectivity of the function, and we also know that complex exponentiation is not injective and not invertible...
Comment: "The $\frac{1}{n}$-iterate" implies only one. Is there a reason you think there is only one?
Comment: @ThomasAndrews, no I just mean "a $1\over n$-iterate", I assume that there is at least one.
Comment: Yeah, was just quibbling with the word "the..."
Comment: @GottfriedHelms about the application of the result to tetration, tell me if I'm right, we could write it as ${}^{1}k={}^{n}k\implies {}^{1+{1\over m}}k={}^{1+{1\over m}+n}k$. About your last comment I'll write more when I have time, I need time to think too.
Comment: As at the notation for tetration: yes, that's a correct notation I think. With the "fractal" and "equator" curve the aspect which triggered me, was, that seemingly *between two integer* iterates of the $\Psi$-function (a fractional iteration of the tetration) the curve might get some break out to a singularity which in turn would force us to make sure, that no anormality like this (or possibly others) would destroy our nice formula. Of course, such an "equator"-curve might only occur with such special bases $b$ in tetration on the border of the Shell-Thron-region. But I think I should (...)
Comment: (...) possibly stop now from such repeated "caveat caveat" warnings. Because I even don't know whether there is real substance in it... :-/
Comment: If F, and $F^{1/n}$ are entire, than I think the Op's result is correct.  But often times, fractional iterates of entire functions are not entire.   So, one can generate counter examples, but they involve non-entire fractional iterates.
Comment: @SheldonL If my should be true for the class of functions that admit at least one frac. iterate, but you say that the subclass of non-entire functions (that admits a frac. iter.) gives a counter example....then it means that my deduction has a wrong assumption...associativity of composition, substitution and fixed point definition...
wich one of my assumption does not holds for the not entire functions?
Answer: I do not believe there is a short answer that will adress all your questions.
However consider the analytic solutions and the complex numbers.
Then we might have $f(z_0)=z_0$ where $z_0$ is a complex number and $f$ is an analytic function.
Now consider the function $F(z+1) = f(F(z))$.
Now your question is equivalent to $if$ $F(q)=z_0 $ where $q$ is finite ,
is it Always true that $F(q + {1\over m} + n) = F(q+{1\over m})$ for positive integers $n,m$ ?
And the answer is NO !
( In fact this has been mentioned and investigated by tommy1729 , Gottfried and probably all frequent posters at the tetration forum )
Here is the proof :
$F(q + {1\over m} + n) = F(q+{1\over m})$ implies that $F(q + {a\over m} + an) = F(q+{a\over m})$ for positive integer $a$.
( Notice the subtle $an$ term , not just $n$ ; the $a$ th iterate of $F({1\over m} + n)$ => $F({a\over m} + an)$. You might want to think about this. )
As a consequence since $q$ is finite and $an$ is an integer ... and $f$ is analytic then by analytic continuation $F$ ... and the fact that the rationals are dense in the reals ... $F$ is periodic with period $an$.
But superfunctions tend not to be periodic.
( superfunction means inverse abel function for those unfamiliar with the term )
Notice that $F(z+\theta(z))$ where $\theta$ is a one-periodic function satisfies the same functional equation but the same problem/solution (proof steps above) holds ... unless of course ( the "new" ) $q$ is no longer finite.
I can find you some related threads on the tetration forum if you like.
You know , periodicity is an important concept the re-occurs often.
This is not Always clear from (basic) traditional education apart from trigonometry.
Guess that gives you some insight why your idea is a bit too optimistic.

(ordinary reader may stop reading , this is a specialized comment )
As for tetration The kneser solution has the primary fixpoints of exp at +/- oo $i$. And there at oo $i$ the function is indeed flat and periodic. Hence there it is true what you assume ... by " design of the superfunction " ,  however I assume the fixpoints have no finite $q$ for the kneser function.
Formalizing that might be difficult.
I considered thinking about univalent zones , but since exp is a chaotic map that seems difficult.
Maybe that would make a good question at the tetration forum.
Comment: Tommy considered tetration for other numbers then the complex ones. But they suffered the same problem.
Im not sure about non-complex numbers and iterations of other functions ( not exp ).
Comment: mhh,$x_0$ is the fixed point of $f$, consider the $x_0$-based superfunction of $f$, yeah, it is the function that satiefies $F(0):=x_0$ and $F(z+1)=f(F(x))$ (we have that $F(z)=f^{\circ z}(x_0)$). Since $x_0$ fixed point implies that $F(n)=F(n+1)$ for all the naturals, my question is equivalent to aks if $F(n)=F(n+1)$ implies $F({1\over m})=F({1\over m}+1)$... while the third question asks if it is possible to conclude that $F(z+1)=F(z)$ always.Said that, thank you for the answer, I really should study alot more about periodicity and fixed points since now I'm very confused ;D.
Comment: anyways I don't get the proof, can you rephrase it in a simpler way? I don't get some steps: I don't know nothing about analycity and the fact that the rationals are dense in the reals so I can't get the implication.
Comment: I've edited your question, tell me if the edit is correct.
Comment: Btw I don't get how you introduce the term $a$
Comment: Your edit is correct.
As for the " a" ; HINT if f(1/3 + 1) = f(1/3) then f(1/3 + 1 + 1 + 1/3) = f(1/3 + 1/3).
Comment: Hehe I noticed your badges at this moment 1 7 29.
1729 !
The taxicab number that tommy loves :)
Answer: I think the main thing missing from the proof is a description of functions admitting an $n^{\rm th}$ root.  There is nothing strange (that I can see) in the steps of your proof but it begs the question - for what $F$ is the set $\{ \Psi : \Psi^n = F \}$ nonempty?
Starting with $X = \mathbb{R}^k$, I believe any linear transformation admits a ${1\over n}$-iterate $\Psi$, but that still leaves the field very open.
Comment: Ye, I didn't write it clear. The existence of $\Psi$ is given before. So the theorem I want to prove is of the form: If $\Psi$ exists and if a fixed point $k$ exists then...
Anyways the question about the set $\{ \Psi : \Psi^n = F \}$ is interesting and I'd like to open a new question about it, if you are not interested in it.
Comment: Assuming you have a $\Psi$, then the proof is very clear.  You use the assumption on $k$, associativity of function composition (I'm sure in some esoteric setting this could fail, but by our everyday definition function evaluation is associative), then the definition of $\lambda$.  This seems airtight.
Comment: As to your other questions: 2) you don't need induction for the proof since you are assuming a $\Psi$ exists for each integer $n$.  3) I'm not familiar with your notation $\wedge$, but if $\Psi$ is an $n^{\rm th}$ `root' of $F$, then any function in $\{ \Phi : \Phi^n = F^k ~~ \forall ~~ x \in X \}$ will also fix $k \in Fix(F)$, so $k$ is also a fixed point of $F^{k/n}$.
Comment: $\land$ means "and"... it means that q is ration AND the disequality holds.
I don't get the answer to the 3rd question. Anyways can you glue all the comments and add it inside your answer, adding a proof to your last statement?
Answer: I think the Op's proof is correct assuming both functions are entire.  However, even if $F(x)$ is entire, the fractional iterate is in general not entire.  The Op's result does not hold if the fractional iterate is not entire
$$F^{o\frac{1}{n}}(x)\;\;\;\;h(x)=F^{o \frac{1}{2}}(x)\;\;\;\;h(h(x))=F(x)$$
If the half iterate is not entire then there are points for which $F(x)=h(h(x))$ is only by analytic continuation, and not by direct computation.  So definition (1), $\forall x\;\;h(h(x))=F(x)$ does not hold $\forall x$, since the half iterate has multiple values depending on the path, unless the half iterate is also entire, which pretty much rules out all non-trivial half iterates!
I wanted to generate a counter example that was as simple as possible.  Lets start with a function that has three fixed points, $(0,\pm 1)$, and we will develop the half iterate at the fixed point at the origin.  I also wanted to avoid the parabolic case see Will Jagy's half iterate of sin(x) post which occurs when the first derivative of the fixed point=1, so I chose a positive 1st derivative at the fixed point at the origin of 4.  Avoiding the parabolic case gives guaranteed convergence so then the formal half iterate would have guaranteed convergence near the origin, and would have a first derivative of 2.
So here is my counter example, for $F(x)=4x-3x^3$, for which the half iterate is $h(x)$, and $F(x)$ has fixed points of $(0,\pm 1)$. For all points within some radius of convergence, $h(h(x))=F(x)$, but eventually we get to the singularity of $h(x)$ which gives it a defined radius of convergence.  But weird stuff happens when the radius of convergence of $h(x)$ is larger than $h(1)$ where 1 is one of the other fixed points.  So, below, I post the formal half iterate of $F(x)$, which has a radius of convergence of  $\frac{16}{9}\approx 1.78$.  Here, is my counter example, where all three fixed points for $F(x)$ has $h(x)$ within its analytic radius of convergence, and even $h(1), h(-1)$ are within the radius of convergence so the half iterate seems to be completely unambiguous at these points.  And yet this leads to a clear counter example.
$$F(1)=1$$
$$h(1)=1.66125776701924932137$$
$$h(1.66125776701924932137)=1$$
$$F(h(1))=F(1.66125776701924932137)=-7.10907369782592055937<>h(1)$$
However, even though the radius of convergence of the Taylor series of $h(x)>h(1)$, when you look at a number 1.2399067, $h(1.2399067)=16/9$, so $h(h(x))$ has a smaller radius of convergence is 1.2399067.  Of course, this smaller radius of convergence has a singularity that cancels by analytic continuation since $F(x)$ is entire.  And this is what allows weird stuff to happen... where in the complex plane, $h(x)$ at the fixed point of $F(x)$ has multiple values depending on the path, even though $F(x)$ is entire and is always well defined independent of the path.  So $h(x)$ can only by fully defined by path dependent analytic continuation in the complex plane.
<code>{h(x)=
+x   *2
-x^ 3*3/10
-x^ 5*27/850
-x^ 7*243/44200
-x^ 9*4391901/3862196000
-x^11*4097709/15835003600
-x^13*263696194479501/4216940633698000000
-x^15*4352793841907459397/276378289132566920000000
-x^17*0.00000408866926284292783744
-x^19*0.00000108632410179569368855
-x^21*0.000000293954426198467149790
-x^23*0.0000000807297320769806555906
-x^25*0.0000000224441951265113300999
-x^27*0.00000000630439537551479828510
-x^29*0.00000000178645419922952969101
-x^31*0.000000000510065370119009481553
-x^33*1.46596264762260914617 E-10
-x^35*4.23776939074721938452 E-11
-x^37*1.23135265881044955235 E-11
-x^39*3.59433071863758569107 E-12  ....
}
</code>
Besides the formal Taylor series, one may generate the half iterate by using the identity::
 $$h(x) = F \circ h \circ F^{-1} = \lim_{n \to \infty} F^{n} \circ h \circ F^{-n} = \lim_{n \to \infty} F^{n}(2\cdot F^{-n}(x))  $$
The $h = F \circ h \circ F^{-1}$ equation also shows that the half iterate radius of convergence is tied to the radius of convergence of $F^{-1}(x)$, which is $\frac{16}{9}$.  This may be calculated from where $\frac{d}{dx}F(x)=0$ which is at $x=\pm \frac{2}{3}$ where $F(\pm \frac{2}{3})=\pm\frac{16}{9}$.  Here is a graph of h(x), at the real axis, from -16/9 to +16/9, which is out to the radius of convergence, where the derivative of h(x) goes to infinity.  The singularity is cancelled out when iterating $h(h(x))$ since the derivative of $h(x)=0$ where $h(x)=16/9$.

One more image showing $h(x), h^{o2}(x)=F(x), h^{o3}(x), h^{o4}(x)$ from 0 to 1.  Odd iterations are in purple, and even iterations are in red.  Notice that $h^{o3}(1)$=-7.10907 as expected, as opposed to $h(1)$=1.6612577.  We see that $h(1)$ has multiple values, depending on how many times we have iterated $h(x)$. But F(x) is entire, so no matter how many times we iterate F(1)=1.  Also notice that this still contradicts the Op's proof, since for analytic functions, the half iterate is multiple valued, apparently infinitely valued in this case, depending on the path in the complex plane.
Comment: Damn, I see it but I can't believe it (hah just kidding...) actually I see it but I can't understand why O.O. I need time to even understand what I don't understand. Thank you for the answer. I will comment soon.
Comment: @mick, MphLee; I really like your question, btw, it just took me awhile to realize that MphLee's proof was correct iff the fractional iterate was entire ... and then I got really interested.  I wanted to post as simple and counterexample as I could.  I probably should've skipped the Taylor series, and stuck with the limit definition of $h(x)$, but I generated the formal Taylor series solution of $h(x)$ first ...
Comment: Do this actually implies that the existence of a function with $\Psi^n=F$ is equivalent to/implies having $\Psi$ and $F$ entire?
Because the existence of a function with $\Psi^n=F$ already implies that $\Psi^n(x)=F(x)$ for all the $x$ in $dom(F)=dom(\Psi)=X$(domain of F).. and the fact that $\Psi^n$ exists means automatically that $cod(F)=\Psi^n[X]\subseteq \Psi^{n-1}[X]\subseteq...\Psi^2[X]\subseteq\Psi[X]\subseteq X$. (continue)
Comment: (continue) Could this mean that this assumption is enough strong to imply entireness? But Entireness uses alot of structures such as $X=\Bbb C$ and holomorphy... while my deduction should run on a really wider class of maps over a generic set $X$...So at this point I wonder what are the real implication of such general assumption...
Comment: **Note 2** In the costruction using the limit you do use the abel function and the super function... anyways how do we know that is legit to do that?What if the superfunction or the abel function are not invertible? the formula will only hold on a subset of the complex where it gets invertible... is this related with the failure of the definition (1) adn thus with the failure of the theorem?
Comment: I'm not qualified to address generic X domain, but I do enjoy working with half iterates and analytic functions, and entire functions...  But for non-entire $F$, how would you know what to set the domain to???   For the limit equation, all that is required is the fixed point at the origin, and the absolute value of the first derivative is at the origin is >1.  I wanted to avoid Abel functions and Superfunctions, which is why I started with the Formal Taylor series solution for the half iterate.  But then I needed to know the closest singularity for h, so I also had to use the limit equations.
Comment: I fixed up the counter example, by showing that it is the fractional iterate, $h(x)$ that takes on multiple values at the fixed point, depending on how many times we have iterated the function.  And that leads to the contradiction.
Comment: I give the bounty for the effort, there was not alot of time anymore.
You ask me *"But for non-entire F, how would you know what to set the domain to???"* If with $F$ you mean the function that we want to half iterate iis by definition a map $F:X\rightarrow X$ then its domain is $X$, functions are defined to be total. Since $dom(f\circ g)=dom(g)$ we have that $dom(F)=dom(\Psi)=dom(\Psi^i)$ for every $i$ if a $\Psi$ such that $\Psi^n=F$ exists.We also have that $cod(\Psi^{m+1})\subseteq cod(\Psi^m)\subseteq X$...
Comment: Since multivaluedness seems the root of the failure, could I safely assume that my proof is correct since it assumes the existence of a "proper" function? (thus total on the domain, not multivalued)?
Comment: Thanks for the bounty.  I think if you restrict yourself to starting with $$F^{[1/n]}=\Psi(x)$$ and $\Psi(x)$ is single valued, then the resulting $F(x)$ is single valued.  But this seems to me like working with $f(x)$ and $f^{[n]}(x)$ ... when one speaks of a fractional iterate, normally I would think of a general analytic function.  So that's why I say your definition of a fractional iterate is flawed.  It sounds like you are really interested in integer iterates ...
Comment: @SheldonL quote : " btw, it just took me awhile to realize that MphLee's proof was correct iff the fractional iterate was entire ... "
I was amazed to read this !
I considered that trivial and assumed everone knew it.
Especially someone from the tetration forum.
I assumed Sheldon knew this already as a baby :)
Guess you can consider my high expectations as a compliment , or the fact that I see this as trivial as not a compliment.
Just saying :)
Comment: @SheldonL $$h(x) = F \circ h \circ F^{-1} = \lim_{n \to \infty} F^{n} \circ h \circ F^{-n} = \lim_{n \to \infty} F^{n}(2\cdot F^{-n}(x))  $$ How do you justify approximating h(x) by 2x here ?
Sure I can see $F^{-n}(x)$ gets closer to 0 and therefore $2x$ becomes an increasing better approximation , but Im not convinced by that alone.
I need to be convinced of both convergeance and correctness.
I will ask a related question on main.
Comment: See : http://math.stackexchange.com/questions/1104745/how-to-prove-that-fx-lim-n-to-infty-fn-f-0-cdot-f-nx
@SheldonL


OpenGL Frambuffers, Rendering to Depth Texture

Question: The problem:
The code is supposed to render the scene and write the results into a depth texture. When I check the contents of the texture after the render, it contains all 0 values.
What I have tried:
I have tried outputting to the screen instead of the texture and it draws the scene as expected, so the vertex and matrix values are being read correctly. I have tried multiple tutorials an they all basically say to bind a framebuffer to a texture, which is exactly what I do. I believe the trouble is probably some sort of versioning issue or something I overlooked like a parameter or something. I've been at it for a few hours and I can't quite spot it. Hopefully someone can.
Details:

OpenGL 3.1
GLSL 140

Note: The purpose of this is to allow shadow mapping to work. So there are 2 sets of shaders and draw functions. One to draw to the depth buffer and the other to draw the objects.
Code:
Shader initialization code:
void Engine::loadMObject()
{
    glGenFramebuffers(1, &MObject::fbo);
    glGenTextures(1, &MObject::shadowMap);

    glBindFramebuffer(GL_FRAMEBUFFER, MObject::fbo);
    glBindTexture(GL_TEXTURE_2D, MObject::shadowMap);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, windowWidth, windowHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, MObject::shadowMap, 0);

    glDrawBuffer(GL_NONE);
    glReadBuffer(GL_NONE);

    GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
    assi(status == GL_FRAMEBUFFER_COMPLETE, "FBO error!");

    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    MObject::shadowProgram = Shader::compile((char*)MObject::shadowVertexShaderFile, (char*)MObject::shadowFramentShaderFile);

    MObject::shadowPositionLoc = glGetAttribLocation(MObject::shadowProgram, "position");

    MObject::shadowModelProjectionMatrixLoc = glGetUniformLocation(MObject::shadowProgram, "modelProjectionMatrix");

    MObject::objectProgram = Shader::compile((char*)MObject::objectVertexShaderFile, (char*)MObject::objectFragmentShaderFile);

    MObject::objectPositionLoc = glGetAttribLocation(MObject::objectProgram, "position");
    MObject::objectTexCoordLoc = glGetAttribLocation(MObject::objectProgram, "texCoord");
    MObject::objectNormalLoc = glGetAttribLocation(MObject::objectProgram, "normal");

    MObject::objectWorldMatrixLoc = glGetUniformLocation(MObject::objectProgram, "worldMatrix");
    MObject::objectViewMatrixLoc = glGetUniformLocation(MObject::objectProgram, "viewMatrix");
    MObject::objectProjectionMatrixLoc = glGetUniformLocation(MObject::objectProgram, "projectionMatrix");
    MObject::objectTextureLoc = glGetUniformLocation(MObject::objectProgram, "texture");
    MObject::objectDepthModelProjectionMatrixLoc = glGetUniformLocation(MObject::objectProgram, "depthModelProjectionMatrix");

}

Object initialization code
void Engine::load(MObject* object)
{
    unload(object);

    // |Physics|
    object->mesh = memoryManager.alloc<btTriangleIndexVertexArray>(
                                        object->elements.length()/3,
                                        (int*)&object->elements[0],
                                        3*sizeof(GLuint),
                                        object->attributes.length(),
                                        (btScalar*)&object->attributes[0],
                                        sizeof(MObject::Attribute));

    btCollisionShape* shape;
    btScalar mass = 0;
    btVector3 inertia(0, 0, 0);
    if(object->dynamic)
    {
        shape = memoryManager.alloc<btGImpactMeshShape>(object->mesh);
        ((btGImpactMeshShape*)shape)->updateBound();
        mass = 1;
        shape->calculateLocalInertia(mass, inertia);
    }else{
        shape = memoryManager.alloc<btBvhTriangleMeshShape>(object->mesh, true);
    }

    object->rigidBody = (btRigidBody*)memoryManager.galloc(sizeof(btRigidBody), memoryManager.alignment<btRigidBody>());
    new (object->rigidBody) btRigidBody(mass, object, shape, inertia); // 16-byte aligned param work around...
    physicsWorld->addRigidBody(object->rigidBody);

    // |Graphics|

    // Vertex array object

    glGenVertexArrays(1, &object->objectvao);
    glBindVertexArray(object->objectvao);

    // Vertex buffer object

    glGenBuffers(1, &object->vbo);
    glBindBuffer(GL_ARRAY_BUFFER, object->vbo);
    glBufferData(GL_ARRAY_BUFFER, object->attributes.length()*sizeof(MObject::Attribute), object->attributes.data, GL_STATIC_DRAW);

    // Vertex attributes

    glEnableVertexAttribArray(object->objectPositionLoc);
    glVertexAttribPointer(object->objectPositionLoc, 3, GL_FLOAT, GL_FALSE, sizeof(MObject::Attribute), (void*)0);
    glEnableVertexAttribArray(object->objectTexCoordLoc);
    glVertexAttribPointer(object->objectTexCoordLoc, 2, GL_FLOAT, GL_FALSE, sizeof(MObject::Attribute), (void*)offsetof(class MObject::Attribute, texCoord));
    glEnableVertexAttribArray(object->objectNormalLoc);
    glVertexAttribPointer(object->objectNormalLoc, 3, GL_SHORT, GL_TRUE, sizeof(MObject::Attribute), (void*)offsetof(class MObject::Attribute, normal));

    // Element buffer object

    object->eboNumElements = object->elements.length();
    glGenBuffers(1, &object->ebo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, object->ebo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, object->elements.length()*sizeof(GLuint), object->elements.data, GL_STATIC_DRAW);

    glBindVertexArray(0);

    // Shadow vao

    glGenVertexArrays(1, &object->shadowvao);
    glBindVertexArray(object->shadowvao);

    glBindBuffer(GL_ARRAY_BUFFER, object->vbo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, object->ebo);

    glEnableVertexAttribArray(object->shadowPositionLoc);
    glVertexAttribPointer(object->shadowPositionLoc, 3, GL_FLOAT, GL_FALSE, sizeof(MObject::Attribute), (void*)0);

    glBindVertexArray(0);

    mObjectList.pushBack(object);
}

Draw code:
/* START - SECTION OF MAIN UPDATE LOOP */
    // |Draw update|
// Shadow Pass

// testing...
if(isKeyDown(SDL_SCANCODE_0)){
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glUseProgram(MObject::shadowProgram);
    glBindFramebuffer(GL_FRAMEBUFFER, MObject::fbo);
    glBindTexture(GL_TEXTURE_2D, MObject::shadowMap);
    for(U32 i=0;i<mObjectList.length();++i)
    {
        drawShadow(mObjectList[i]);
    }
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glBindTexture(GL_TEXTURE_2D, MObject::shadowMap);
    GLfloat* pixels = new GLfloat[windowWidth*windowHeight];
    glGetTexImage(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, GL_FLOAT, pixels);
    for(U32 i=0;i<windowHeight*windowHeight;++i)
    {
        if(pixels[i] != 0.0f)
            printd("I GOT IT!");
    }
    delete[] pixels;
}else{

    // Object Pass
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glUseProgram(MObject::objectProgram);
    for(U32 i=0;i<mObjectList.length();++i)
    {
        drawObject(mObjectList[i]);
    }
}

// Swapping buffers
SDL_GL_SwapWindow(mainWindow);

/* END - SECTION OF MAIN UPDATE LOOP*/
void Engine::drawObject(MObject* object)
{
    TransformMatrix matrix;
    getOrthographicMatrix(matrix, -10, 10, 10, -10, -10, 20);
    glBindVertexArray(object->objectvao);
    glUniformMatrix4fv(MObject::objectWorldMatrixLoc, 1, GL_FALSE, (GLfloat*)&object->worldMatrix);
    glUniformMatrix4fv(MObject::objectViewMatrixLoc, 1, GL_FALSE, (GLfloat*)&getViewMatrix());
    glUniformMatrix4fv(MObject::objectProjectionMatrixLoc, 1, GL_FALSE, (GLfloat*)&getProjectionMatrix());

    glUniformMatrix4fv(MObject::objectDepthModelProjectionMatrixLoc, 1, GL_FALSE, (GLfloat*)&getProjectionMatrix());
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, object->tbo);
    glUniform1i(MObject::objectTextureLoc, 0);
    glDrawElements(GL_TRIANGLES, object->eboNumElements, GL_UNSIGNED_INT, 0);
}

void Engine::drawShadow(MObject* object)
{
    TransformMatrix matrix;
    //getOrthographicMatrix(matrix, -10, 10, 10, -10, -10, 20);
    matrix = getProjectionMatrix() * getViewMatrix() * object->worldMatrix;
    glBindVertexArray(object->shadowvao);
    glUniformMatrix4fv(MObject::shadowModelProjectionMatrixLoc, 1, GL_FALSE, (GLfloat*)&matrix);
    glDrawElements(GL_TRIANGLES, object->eboNumElements, GL_UNSIGNED_INT, 0);

}

Vertex Shader:
#version 140

in vec3 position;

uniform mat4 modelProjectionMatrix;

void main(){
    gl_Position =  modelProjectionMatrix * vec4(position, 1.0f);
}

Fragment Shader:
#version 140

out float fragmentdepth;

void main(){
    fragmentdepth = gl_FragCoord.z;
}
/*
out vec4 color;

void main(){
    color = vec4(clamp(gl_FragCoord.z, 0.0f, 1.0f), 0.0f, 0.0f, 1.0f);
}*/

Comment: did you try adding `glEnable(GL_DEPTH_TEST);`
Answer: I figured it out. Apparently if you rearrange the opengl calls a little bit it works. I believe what I did was put glBindFramebuffer before glUseProgram and it worked.


On proving that $\sup_{x \in ] -1, 1[} \{ x^{n+1}+ x^{n+2}+ \dots + x^{n+p} \} = p $ .

Question: As a step to complete an exercise I would like to prove that the $$\sup_{x \in ] -1, 1[} \{ x^{n+1}+ x^{n+2}+ \dots + x^{n+p} \} = p $$
I am a bit stuck on how to do this, anybody mind showing me how?
Comment: The $\sup$ isn't $p-1$ , is $p$.
Comment: thank you both I will edit.
Answer: Hint: you can ignore the $x$ with $x<0$ (why?) and $x\mapsto x^{n+1}+ x^{n+2}+ \cdots + x^{n+p}$ is increasing for $x\ge 0$.
Comment: Thanks yes I think I see where you are pointing me (taking the limit as $x \rightarrow 1$ correct?). So is there an analogue to the monotone convergence theorem for functions? I still can't seem to formalize it well.
Comment: @Monolite, the $\le p$ is obvious. Suppose the inequality is strict...
Comment: Oh so it's increasing and strictly bounded by $p$, so if I take the limit as $x \rightarrow 1$ I obtain $p$ and it's impossible that I could obtain something more because otherwise there would be a positive distance between $p$ and the limit and for an $\epsilon$ smaller than that positive quantity I can't find any response.
Comment: So what is this theorem called (the supremum on an increasing interval of a function is equal to the limit of the function taken as x goes to the endpoint of the set) ? By the way thank you very much.
Comment: @Monolite, I don't know any "official" name.


Validation on textfield

Question: I have gotten my validation module to kind of work, I have this:
function product_id_form_validate($form, &$form_state) {
if($form_state['node']->field_product_id['und']['0']['value'] == '123'){
    form_set_error('field_product_id', 'Product ID: is taken');
}

}
But when I change the value in field_product_id the value doesn't change upon save, it stays the same as when I first entered the form. Is there a function I need to call to say, when I click save look at this field again?
Thanks
Answer: Submitted values are stored in the $form_state['values'] array so you need to test that instead:
if ($form_state['values']['field_product_id'][LANGUAGE_NONE][0]['value'] == '123') {
  ...
}

Validation on textfield


Browsing an object's fields

Question: In Objective C, I have an object e.g. Person with a lot of fields firstName, lastName, phoneNumber, address, city... and so on. These fields types are NSString and any of these could be nil.
Now I want to concatenate my field values in another NSString :
Person *p = ...
NSMutableString *s = [[NSMutableString alloc] init];
for (NSString *field in @[p.firstName, p.lastName, p.phoneNumber,
                          p.adress, p.city, ....more fields...]) {
    if ([field length] > 0) {
        [s appendFormat:@"%@\n", field];
    }
}

Issue is that this code crash whenever one of the field is nil. I have the exception :
[__NSPlaceholderArray initWithObjects:count:]: attempt to insert nil object
from objects[0]'

How could I handle simply the case of nil values within my for loop ?
Comment: Not me, voted you up and kept it :-)
Comment: Edited my question for clarity : there will be a lot of fields in the object (around 15)
Comment: Okay, that means I have to change my answer :)
Comment: @Tom Yep, sorry, my example was too specific.
Comment: I saw my vote count go up and then down.  Someone voted me down, and I lost 2 rep points.. Anyway I updated my answer to make it more complete.
Answer: I agree with @TomPace's post, for this small number I would do a simple if/else.
However, there may be times you do need to loop through a list of fields.
It's a bad idea to blindly pull the values into an array as you could be trying inserting nil values into the array. In this case, it would be better to place the field names into a key array as strings and loop through the list using valueForKey: to access the values. I would possibly store the keys list somewhere else where it can be used again.
Person *p = ...
NSMutableString *s = [[NSMutableString alloc] init];

NSArray *keys = @[@"firstName", @"lastName", @"phoneNumber", @"adress", @"city"];

for (NSString *key in keys)
{
    NSString *value = [p valueForKey:key];
    if ([value length] > 0) {
        [s appendFormat:@"%@\n", value];
    }
}

Answer: For a selection of fields this small, don't use a for loop.
You may be saving a bit of code by attempting the for-loop structure, but it's really not the way to go if you're building the NSArray with only a few fields, and especially because you can't put nil items in it.
A better way to go is:
Person *p = ...
NSMutableString *s = [[NSMutableString alloc] init];
if ([p.firstName length] > 0)   [s appendFormat:@"%@\n", p.firstName];
if ([p.lastName length] > 0)    [s appendFormat:@"%@\n", p.lastName];
if ([p.phoneNumber length] > 0) [s appendFormat:@"%@\n", p.phoneNumber];
if ([p.adress length] > 0)      [s appendFormat:@"%@\n", p.adress];
if ([p.city length] > 0)        [s appendFormat:@"%@\n", p.city];

Edit, after original Question was updated with large amount of fields.
Like @BergQuester said, an approach to support a larger, arbitrary set of fields is using KVO-style inspection.
NSArray *fieldNames = @[@"firstName", @"lastName", @"phoneNumber", ....more fields...];
NSString *field;
for (NSString *fieldName in fieldNames) {
    field = [p valueForKey:fieldName];
    if ([field length] > 0 ) {
        [s appendFormat: @"%@\n", field];
    }
}

Comment: The `> 0` is redundant (not wrong, just pointing out another stylistic option.)
Comment: @AaronBrager thanks, yes you're right. I guess I was just following the style of the original question. I prefer the omission myself.
Answer: Person *person = [[Person alloc] init];
person.firstName = nil;
person.lastName = @"lastName";

NSMutableString *s = [[NSMutableString alloc] init];
[s appendFormat:@"%@\n", person.firstName == nil?@"":person.firstName];
[s appendFormat:@"%@\n",  person.lastName == nil?@"":person.lastName];

Answer: You can override the getters of the class Person.
    @implementation Person

    - (NSString *)firstName{
        if (_firseName == nil)
             _firstName = @"";
        return _firstName;
    }
///....Other setters

    @end

Like this you can define all your setters here.
Comment: Those are getters, not setters.
Comment: Also, this solution wastes memory and could have negative side effects.
Answer: Try to create NSMutableString category
#import "NSMutableString+checkForNilObject.h"

@implementation NSMutableString (checkForNilObject)

-(void) appendNotNillObject:(NSString *) string
{
    if(string)
    {
       [self appendString:string];
    }
}
@end

Browsing an object's fields