Sets / Bijection / Countablity

Question: Can you please help me with this question?

Is the set finite, countably infinite, or uncountable?
a. The set of all real-valued random variables on a finite sample space.
b. The set of all integer-valued random variables defined on the sample space $W$ of positive integers, with $\operatorname{Pr}[w] = 1/(2^w)$
c. The set of all integer-valued random variables on a finite sample space.
d. The set of all possible functions from $\mathbb{Z}_{97}$ to $\mathbb{Z}_{97}$ (modulo 97).
e. $\mathbb{Z}^3 = \{(a,b,c): a,b,c \in \mathbb{Z}\}$ (the set of triples of integers)
Comment: What do you know? What did you try? Why did this fail?
Comment: A random variable is just a function. Already if the sample space has $1$ point, there are as many random variables on the sample space as there are real numbers, since the point can be mapped to any real.
Answer: An $S$-valued random variable on a sample space $X$ is simply a function from $X$ to $S$. Thus, a real-valued random variable on a set $X$ is simply a function from $X$ to $\mathbb{R}$, and an integer-valued random variable on $X$ is a function from $X$ to $\mathbb{Z}$. Your questions (a) and (c) are therefore the same as the questions that I answered here. That answer should also help you with (d) and (e), but (d) shouldn't cause any trouble anyway: $\mathbb{Z}_{97}$ has $97$ elements, and in $\mathbb{Z}_{97}\times\mathbb{Z}_{97}$ each of them appears in an ordered pair with each of them, so you have a total of $97^2$ elements, a finite number.
That leaves only (b). The information that $\text{Pr}[w]=1/2^w$ is superfluous: you're just looking at functions from $W$ to $\mathbb{Z}$. There are at least as many of those as there are functions from $W$ to $\{0,1\}$, so ... ?
This should at least get you started.
Comment: Thanks a lot! I understand the questions much better. I have one question though on e... I am still a little unsure how to prove it. Can i just say that we can create a mapping for each triplet in the sense that (0,0,0) -> 0, (1,0,0) -> 1, (1,0,1) -> 2 etc... every triplet will be accounted for and only once (bijection). Therefore, it is countable?
Comment: In addition, building off on this...can you explain to me how to do this one: T = {p(x) : p(x) = a_n*x^n + ... + a_1*x + a_0; where n \in N and a0, a1, ..., an \in Z} (the set
of all polynomials with integer coecients, of any degree)

I believe you use induction on just a polynomial of degree 2 (which is identical to the comment above)...but am not exactly getting it.

Sets / Bijection / Countablity


A relationship between the Laguerre and the Hermite equations

Question: The Hermite and the Laguerre differential equations are respectivly given by
$$(1)\quad y'' -2x y' + n y = 0$$
$$(2)\quad xy'' + (1 - x)y' + ny = 0$$
I look for a transformation that enables to go from $(1)$ and $(2)$ or the contrary?
Comment: Are you kidding me? Posing a question like that with the experience you have on this site is an absolute impudence (-1)
Comment: Ok, I edited the question
Answer: The general solution of the Hermite equation is :
$$ (1)\quad y'' -2xy' + ny = 0 \quad\to\quad y=c_1\: {_1F_1}\left(-\frac{n}{4}\:,\: \frac{1}{2}\:;\:x^2\right)+c_2 H_{n/2}(x)$$
${_1F_1}$ is a confluent hypergeometric function of the first kind.
The general solution of the Laguerre equation is :
$$(2)\quad xy''+(1-x)y'+ny=0  \quad\to\quad y=C_1 U(-n,1,x)+C_2 L_n(x)$$
$U$ is a confluent hypergeometric function of the second kind.
The Hermite functions and the Laguerre functions are not independent. The relationships are known : http://functions.wolfram.com/Polynomials/HermiteH/27/01/
On the other hand, the first and second confluent hypergeometric functions are independent.
As a consequence, one cannot expect a general relationship between the Hermite and Laguerre equations. One can only expect to transform one to another similar equation. By similar, I mean an equation on the same kind, but not exactly the same. To be more explicit :
Consider the Hermite equation (1). Change of variable :$\quad X=\frac{x^2}{4}$
$\frac{dy}{dx}=\frac{x}{2}\frac{dy}{dX} \quad\to\quad \frac{d^2y}{dx^2}=X\frac{d^2y}{dX^2}+\frac{1}{2}\frac{dy}{dX}$
$\left(X\frac{d^2y}{dX^2}+\frac{1}{2}\frac{dy}{dX}\right) -2x\left(\frac{1}{2}x\frac{dy}{dX}\right) + ny = 0$
$$X\frac{d^2y}{dX^2}+\left(\frac{1}{2}-4X\right)\frac{dy}{dX} + ny = 0$$
This equation is similar, but different from the Laguerre equation :
$$x\frac{d^2y}{dx^2}+(1-x)\frac{dy}{dx}+ny=0$$


$s=t$ iff the (co)equalizer of $s$ and $t$ exists and is an isomorphism

Question:
Let $s,t:X\to Y$ be maps in some category. Prove that $s=t$ iff the equalizer of $s$ and $t$ exists and is an isomorphism, iff the coequalizer of $s$ and $t$ exists and is an isomorphism.

Is the following proof correct?
Suppose $(E,f)$ is the equalizer of $s$ and $t$, and suppose that $f$ is an iso with inverse $F$. Then we have $sf=tf$, and composing with $F$ gives $sfF=tfF$, i.e., $s=t$. Conversely, suppose $s=t$. Let $E=X,f=id_X$. Then $sf=tf$, so $(E,f)$ is a fork. If $(E',g)$ is another fork, then define $\bar g:E'\to E$ by $\bar g=g$. Then $f\bar g=g$, and this $\bar g$ is the unique map with such property (because the property reads $id_X \bar g=g$ or $\bar g=g$). Thus $(E=X,f=id_X)$ is the coequalizer of $s$ and $t$.
For the second part, let's change the notation a bit: let $s,t:Y\to X$. Suppose $(C,f)$ is the coequalizer of $s$ and $t$ and that $f$ is an iso with inverse $F$. Since $fs=ft$, we have $Ffs=Fft$ or equivalently $s=t$. Conversely, if $s=t$, then define $C=X,f=id_X$. Claim: $(C,f)$ is the coequalizer of $s,t$. Indeed, $fs=ft$ (so $(C,f)$ is a cofork, if this is the right term), and if $(C',g:X\to C')$ is another cofork, then define $\bar g:C\to C'$ by $\bar g=g$. As in the previous case, $\bar g$ is the unique arrow that satisfies $g=\bar g f$.
Comment: Related : https://math.stackexchange.com/questions/1991334/equaliser-of-equal-arrows
Answer: Yes, your proof is correct (except for a typo at the end of the first paragraph: $(E = X, f = \mathit{id}_X)$ is an equalizer, not a coequalizer).
For the second part, I suggest that you exploit the so-called duality principle: if a statement is true in a category $\mathcal C$, its dual is true in the opposite category $\mathcal C^{\mathrm{op}}$. In this way you don't need to repeat the same argument as in the first part.


How to choose which Excel version to open using VB.NET?

Question: I have several excel sheets which I'd like to work with different Excel versions using VB.NET
Basically, I want to choose which Excel version I will open certain worksheet using VB.NET. Is there any way to know which Excel version is installed in the machine and how many versions with VB.NET? And how do I choose which Excel version I will open it?
I'd like to know it through programming, I know that this can be done if you take a look at the registry keys in the machine. Although, what I need is to create a software that asks the user for the Excel version he want to open
Comment: [Detecting Installed Excel Version (and Service Packs)](http://stackoverflow.com/questions/858966/detecting-installed-excel-version-and-service-packs/859462#859462)
Comment: i thought that would answer "Is there any way to know which Excel version is installed in the machine?".
Comment: Could you clarify please, when talking about "opening Excel" .. are you literally just after launching a specific Excel executable with a parameter, or do you want to use the Office Automation APIs in order to interact with that instance of Excel from VB?
Comment: _Although, what I need is to create a software that asks the user for the Excel version he want to open_.  Are you really saying that someone may have multiple versions of Excel installed and you need  your application to prompt the user to select a version of the Excel .exe to open?
Comment: Yep.. it happens where I work. Some computers may have more than 1 Excel installed, and I wish I could open certain worksheet with the version the user chose
Answer: The following code snippet gets a list of all the installed copies of Excel on the computer (this has been tried and tested on a Windows XP machine, running both Excel 2003 and 2007).
Dim reg As RegistryKey
Dim subKey As RegistryKey
Dim rtn As New Dictionary(Of String, String)

reg = Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Office")
If reg IsNot Nothing Then
    For Each subKeyName As String In reg.GetSubKeyNames
        subKey = reg.OpenSubKey(subKeyName)
        If subKey IsNot Nothing Then
            If subKey.GetSubKeyNames().Contains("Excel") Then
                subKey = subKey.OpenSubKey("Excel\InstallRoot")
                rtn.Add(subKeyName, subKey.GetValue("Path").ToString)
            End If
        End If
    Next
End If
For Each kvp In rtn
    MessageBox.Show(String.Format("Version: {0} at '{1}Excel.exe'", kvp.Key, kvp.Value))
Next

In the variable rtn you have a dictionary of the versions (the key) and the directory that Excel is installed in (the value). As you can see in the MessageBox bit at the end of my code, you'll need to add "Excel.exe" to the end of it.
Now you have the location of the installed copies of Excel and their versions, you can create a form which lists them, to allow for the user to select which version they wish to use.
Whilst I'm sure you can find the command line for opening an Excel spreadsheet with Excel, I thought I would include it here for completeness;
excel.exe "c:\My Folder\book1.xlsx"

(http://office.microsoft.com/en-us/excel-help/command-line-switches-for-excel-HA010158030.aspx)
A slightly more full explanation of how to identify installed Excel versions and their location.
Comment: Excelent! Just another question, what if I needed to control the Workbook by VB.NET. I mean, besides open it, I need to run macros, exclude rows, etc via VB.NET
Comment: My suggestion would be to open a new question for that as its probably going to require a bit more information and the response would be longer than a single comment would allow (I would guess, I don't know how to do that off the top of my head).


Retornar somente um item relacionado a tabela principal

Question: Tenho duas tabelas, respostas e respostas_log, onde eu guardo informações das respostas em respostas e algumas outras que tem que ir logando em respostas_log.
Eu estou precisando no meu SELECT trazer apenas o último log de cada resposta.
Exemplo das tabelas e conteúdo:
CREATE TABLE IF NOT EXISTS `respostas` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `responsavel_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `respostas_log` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `respostas_id` int(11) NOT NULL,
  `opt_aplicavel` tinyint(1) DEFAULT NULL,
  `txt_resposta` text,
  `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`id`),
  KEY `respostas_id` (`respostas_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

INSERT INTO `respostas` (`id`, `responsavel_id`) VALUES
(1, 1),
(2, 3);

INSERT INTO `respostas_log` (`id`, `respostas_id`, `opt_aplicavel`, `txt_resposta`, `created_at`) VALUES
(1, 1, 1, 'Resposta 1 de 1', '2014-05-13 00:00:00'),
(2, 1, 1, 'Resposta 2 de 1', '2014-05-13 00:00:00'),
(3, 1, 0, 'Resposta 3 de 1', '2014-05-13 00:00:00');

E a query que eu tentei
SELECT  r.id,
    r.responsavel_id,
    l.opt_aplicavel,
    l.txt_resposta,
    max(l.id)

FROM respostas r

LEFT JOIN respostas_log l ON l.respostas_id = r.id

GROUP BY  r.id,
    r.responsavel_id,
    l.opt_aplicavel,
    l.txt_resposta

Exemplo no SQLFiddle
Desse exemplo, seria para trazer somente a primeira e ultima linha
Comment: Dúvidas: (1) quais são a primeira e a última linha, as respostas com id 3 e 2? A query não tem ORDER BY. (2) Não entendi o pedido de "o último log de cada resposta"; as duas linhas que você quer no exemplo não são ambas da mesma resposta?
Comment: Boa @bfavaretto . Se olhar o texto da resposta é a  com 'Resposta 3 de 1' e com valor '(null)'. E esse último log de cada resposta é assim: para todas respostas alguns itens vão para o log de respostas e tenho que exibir somente a última resposta.
Answer: Dá para pegar o id do último log com uma subquery:
SELECT  r.id,
        r.responsavel_id,
        l.opt_aplicavel,
        l.txt_resposta,
        l.id idLog
FROM respostas r

LEFT JOIN respostas_log l
  ON l.id = (select max(id) from respostas_log l2 where l2.respostas_id = r.id)

Acho que não é possível, em um único select, pegar o id o último log e os detalhes deste log.
Para descobrir o valor do último log, você precisará de uma função agregadora (que é o caso do MAX). Ao agregar por id, os outros campos retornados (opt_aplicavel e txt_resposta) precisam ser agrupados por cada valor existente. Como agrupar por estes campos faria com que MAX retornasse valores diferentes para cada registro, o valor agregado precisa ser obtido em uma consulta separada, e depois usado na consulta que retornará os outros campos.
Este artigo da documentação do MySQL 5.0 demonstra uma maneira de fazer com que a subquery não seja "correlata" à query principal, o que pode melhorar o desempenho:
SELECT  r.id,
        r.responsavel_id,
        l.opt_aplicavel,
        l.txt_resposta,
        l.id idLog
FROM respostas r

LEFT JOIN (select respostas_id, max(id) id from respostas_log group by respostas_id) l2
  ON l2.respostas_id = r.id

LEFT JOIN respostas_log l
  ON l.id = l2.id;

Ambos os exemplos no SQL Fiddle
Se o desempenho de ambos os casos estiver abaixo do esperado, talvez seja o caso de criar um índice que facilite a consulta.
Comment: Isso funcionou para o que eu preciso, só tenho uma dúvida, isso por acaso não pode deixar a minha query muito lenta ou não preciso me preocupar com isso?
Comment: Editei a resposta para incluir uma alternativa com melhor desempenho.
Comment: Valew mesmo @Dang , estou analisando aqui, mas da primeira forma como passou da para ver que retorna os dados da linha da segunda tabela, no caso, respostas_log.


How to remove newline from the end of a file using Perl

Question: I have a file that reads like this:
dog   cat   mouse
apple    orange    pear
red    yellow    green

There is a tab \t separating the words on each row, and a newline \n separating each of the rows. Below the last line, red   yellow   green there is a blank line due to a newline \n after green.
I would like to use Perl to remove the newline.
I have seen a few articles like this How can I delete a newline if it is the last character in a file? that give solutions for Perl, but I would like to do this in hard code so that I can incorporate it into my Perl script.
I don't know if this might be possible using chomp, or if chomp works on each line separately (I would like to keep the newline between lines).
Also I have seen previously comments that suggest maintaining a newline at the end of a file because Unix commands work better when a file ends with a newline. However, I have created a script which relies on input files not ending with a newline, therefore I really feel removing the newlines is necessary for my work.
Comment: Why does your script rely on a file not ending with newline? That sounds like a poor script to me.
Comment: Note that the above comment is highly opinionated.  A text file does not need to end with a newline, but IMO they ought to.  If you have a utility that treats `one\ntwo\n` as a three line file, that utility is broken.
Comment: Something like this will work, the chmp removes new lines, the split is on one of more white save. The -lane processes the file a line at a time, inline.
perl -lane 'chomp; if ($_) {@list=split(/\s+/); print join("|",@list);}' file1
Comment: does `od -c yourfile | tail` end with `g r e e n \n` or `g r e e n \n \n` ?
Comment: @TLP I created the script before I knew files were supposed to end with a newline, and much of the script involves count the number of lines. Why is it bad form to not end with a newline?
Comment: @EssexBoy `-l` already does chomp and `-a` does autosplit: `perl -lanE '$_ && say join "|",@F'`
Comment: @jhnc The end of the file looks like this:
0017360  \n
0017361
So just a single \n I believe
Comment: If there's a blank line, that would imply that there are 2 `\n` after green.  If there is only one `\n`, there is no blank line.
Comment: @WilliamPursell There does appear to be a blank link though.
Comment: If there's a blank line, then there are two newlines after `green`.  You almost certainly want to keep one of them.  The file with content `one\ntwo\n` has two lines.  The file with content `one\ntwo\n\n` has 3 lines, and one of them is blank.  The file with content `one\ntwo` is barely even describable as a text file, and is more accurately described as ill formed garbage.
Comment: Fix your program to handle a newline at the end of any line. You are eventually going to run into problems where editors re-add the newline. Instead of duct-taping over the problem, don't make it a problem. Consider the pain people experience in this issue: https://github.com/gohugoio/hugo/issues/1753
Answer: You can try this:
perl -pe 'chomp if eof' file.txt

Here is another simple way, if you need it in a script:
open $fh, "file.txt";
@lines=<$fh>;          # read all lines and store in array
close $fh;
chomp $lines[-1];      # remove newline from last line
print @lines;

Or something like this (in script), as suggested by jnhc for the command line:
open $fh, "file.txt";
while (<$fh>) {
  chomp if eof $fh;
  print;
}
close $fh;

Comment: Could you give any guidance as to how to do this - or if not, explain what the aspects of your code do?
Comment: `perl -pe 'chomp if eof' file.txt` is a bit shorter
Comment: I used `open $fh, "file.txt";
while (<$fh>) {
  chomp if eof $fh;
  print;
}
close $fh;` and that did the trick


admin/config page taking around 30 seconds to load; the rest of the website loads fast

Question: I have a new Drupal install and it works allright, everything loads fast, except for the Configuration page at admin/config. What I have done so far to try to tackle the problem:
- Disabled all contrib modules, with no success.
- Disabled the Update Manager module, no success either.
- Enabled Devel and extended query logs, besides page execution time: ordinary pages take some 300 ms to load. The admin/config page is taking around 30000 ms to load. There is no evidence in the logs that it has to do with the database queries. On the Config page, none of them is above the threshold limit.
It then occurred to me trying something else: I am inside a corporate network and there are two different ways to enter this Drupal site: by checking the internal IP false address and by checking the external IP address the IT team has set for this server (open to the world).
I found that by navigating to the Configuration page from the internal IP address, there is no delay at all, the page loads fast! By navigating into it from the external IP address, the page gets these 30 seconds delays to load.
Any ideas on how I should try to fix this issue with the IT team? I have access to the server and I can run commands on the command line and maybe check server logs. I am not a Linux specialist, but I can follow instructions and run commands.
Comment: In the net panel of your browser it should break down what is taking the longest, DNS, time to first byte, ect. Knowing that will help diagnose the issue.
Comment: Thank you, I could narrow down the issue to one specific wi-fi network where this issue is happening (my office wi-fi network, but one that is used by guests). I will try to monitor with the browser tools. Anyway, not a Drupal issue. I am just curious about what could be causing all this delay specifically in admin/config page. If I find out, I will post it here.
Comment: When connecting to the network again on another day, I didn`t experience any more problems with the slow admin/config page: it is coming fast now, the same way as the other pages. So I guess I won't have an answer to this question. The issue is solved.
Answer: The admin/config page can trigger a check of the site 'status report' which depending on the modules & services your site uses may check for the ability to connect to certain services. 30 seconds sounds like it is trying to use some service but throws a timeout after 30 seconds. Try checking the status report under working / not-working conditions to see if some services are being blocked.
Answer: This will happen if your watchdog table is very large. Going into the mysql backend and doing
truncate watchdog;
solved this problem for me.
The watchdog table contains logs, so truncating it is safe in that it will not affect the working of the system.
Comment: Thank you for sharing this solution, Naomi. This is an old post and I don't even remember the project which was experiencing the issue described in this post. I think it was a project running in a local environment. Anyway, I will 'store' this solution in my mind as a possible solution in case I ever come accross such problems again. Thank you for sharing!


Even though have installed "cucumber-tag-expressions 3.0.0" the behave command with "and" and "or" operator are not working

Question: Resources:
Repository:
https://github.com/anton-lin/tag-expressions-python
Behave Documentation for tags:
https://behave.readthedocs.io/en/latest/tag_expressions.html
package name: :
https://pypi.org/project/cucumber-tag-expressions/
My Feature File
@regression
Feature: showing off behave

  @slow
  Scenario: run a slow test
    Given we have behave installed
    When we implement a test
    Then behave will test it for us!

  @wip
  Scenario: run a wip test
    Given we have behave installed
    When we implement a test
    Then behave will test it for us!

  @wip @slow
  Scenario: run a wip and slow test
    Given we have behave installed
    When we implement a test
    Then behave will test it for us!

Tried commands none of them working: getting results zero scenarios are run
behave --tags="not @slow" .\features\tutorial.feature
behave --tags="@slow and @wip" .\features\tutorial.feature
behave --tags="@slow or @wip" .\features\tutorial.feature

While command with single tag is working fine and executing only scenarios of that specific tag
Getting Below outcome with all three commands:
@regression
Feature: showing off behave # features/tutorial.feature:2

  @slow
  Scenario: run a slow test          # features/tutorial.feature:5
    Given we have behave installed   # None
    When we implement a test         # None
    Then behave will test it for us! # None

  @wip
  Scenario: run a wip test           # features/tutorial.feature:11
    Given we have behave installed   # None
    When we implement a test         # None
    Then behave will test it for us! # None

  @wip @slow
  Scenario: run a wip and slow test  # features/tutorial.feature:17
    Given we have behave installed   # None
    When we implement a test         # None
    Then behave will test it for us! # None

0 features passed, 0 failed, 1 skipped
0 scenarios passed, 0 failed, 3 skipped
0 steps passed, 0 failed, 9 skipped, 0 undefined
Took 0m0.000s

Comment: Which version of `behave` do you have installed on your system?
Comment: i have got behave 1.2.6 installed.
Answer: 'and'/'or' usage as you have attempted is not available in python-behave 1.2.6.
For 1.2.6 try instead:
OR example:
behave --tags @slow,@wip

AND example:
behave --tags @slow, --tags @wip

Negative tag example:
behave --tags ~@slow

See further docs with
behave --tags-help

The reason for the confusion is that when you install behave, by default you pull the most recent stable version from places like pypi.org (so 1.2.6), while the behave docs refer to the "latest" version (1.2.7, which has been in development for quite some time now).
The same issue was raised and closed a while ago in github and closed.
Comment: Thank you Obuz for the explination. I found the same instruction in behave 1.2.6  library code and it worked.


Variable passed from Method.invoke doesn't show up in anything but System.out.println

Question: What I'm trying to do is create in input box for a game I'm making that displays on-screen with a message such as

"Name: (input would appear here)"

What I did was pass in the message, which object I want my input to go to, and what function will use the variable(such as a function that sets the input to the player's name). Now, I could just access the input variable from the InputBox object, but, in the long run, this will be more efficient. I'm using Method.invoke to pass the function into the object I want with the input string as an argument. Here is my code:
public class InputBox extends Textbox {

    public String input = "";
    private String out;
    private Object obj;

    private int lastLastKey = 0;

    /**
     *
     * @param message
     * @param cl The object/class where the output variable is.
     * @param out The method to run. Only takes the input variable, so use this format: void toRun(String input)
     */
    public InputBox(String message, Object obj, String out) {
        super(message);
        this.out = out;
        this.obj = obj;
    }

    public void tick(Game game){
        if (game.input.lastKey != 0 && !game.input.keys[KeyEvent.VK_ENTER]
                && !game.input.keys[KeyEvent.VK_SPACE] && !game.input.keys[KeyEvent.VK_SHIFT] && !game.input.keys[KeyEvent.VK_BACK_SLASH]){
            if(game.input.lastKey != lastLastKey) input+=Character.toUpperCase((char) game.input.lastKey);
        }else if(game.input.keys[KeyEvent.VK_ENTER] && !input.isEmpty() && !cleared){
            Method method = null;
            try {
                method = obj.getClass().getMethod(out, new Class[]{ String.class, Object.class });
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            }

            try {
                method.invoke(obj, new Object[]{ input, obj });
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            cleared = true;
        }

        lastLastKey = game.input.lastKey;
    }

    public void render(Graphics g){
        if(!cleared){
            g.setColor(Color.white);
            g.fillRect(10, Display.height-110, Display.width-20, 100);

            g.setColor(Color.black);
            g.drawRect(10, Display.height-110, Display.width-20, 100);

            g.setFont(Game.smallFont);
            FontMetrics fm = g.getFontMetrics();
            g.drawString(message+" "+input, Display.width/2-fm.stringWidth(message+" "+input)/2, Display.height-50);
        }
    }

}

Comment: What is your question?
Comment: My question is that whenever I run this code, the variable is passed to the other class like I want, but the only thing I can do to it is use System.out.print on it. Other variables work, but this doesnt
Comment: I don't understand what that means. Can you please rephrase, ideally adding a [mcve] showing the issue with `System.out.print`?
Comment: When I pass the variable input to another class using Method.invoke, the variable is received correctly. I did a System.out.println(input) and it came up with RYAN, which was what I typed in. But when I try to display it on the actual screen, it doesn't come up, but if I use another variable, it does. I also tried writing it to a file; that didn't work either.
Answer: Your description for the constructor says that the expected method has a signature of
void toRun(String input) {}

But your reflection code looks for a method with the signature
void toRun(String input, Object o) {}

If you are using Java 8 you can make use of a Consumer and remove all the reflection code:
public class InputBox extends Textbox {

    private Consumer<String> out;

    public InputBox(String message, Consumer<String> out) {
        this.out = out;
        ...
    }

    public void tick(Game game){
        ...
        out.apply(input);
        ...
    }
}

Assuming that your Player class has a method setName(String) like this:
public class Player {
    public void setName(String name) {
    }
}

you can create an InputBox with a method reference
public InputBox createNameInputBox(Player p) {
    return new InputBox("Name: ", p::setName);
}

or with a lambda expression
public InputBox createAlternateNameInputBox(Player p) {
    return new InputBox("Name: ", name -> p.setName(name));
}

To read more about lambda expressions and method references see the Java Tutorial series (https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html). For a discussion of whether you should use method references or lambda expressions see https://stackoverflow.com/a/24493905/5646962
Comment: How do I initialize a consumer object?
Comment: @bloobchube added example code and links for reference
Comment: Thanks, this worked! Now I can finally continue developing my game.


Android WebView and Word Online

Question: I am working on an Android project where I have to open a Word Online document that has to be opened without exposing the URL.   I have the following code which opens a document, but some kind of error is happening.  I'm pretty sure it has something to do with permissions, but I am unsure of what exactly I am missing.
FrameLayout.LayoutParams rl = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
                android.webkit.WebView wView = new android.webkit.WebView(this.getContext());
                wView.setId(0x100);
                //wView.setWebChromeClient(new WebChromeClient());
                wView.setWebViewClient(new WebViewClient());
                wView.getSettings().setJavaScriptEnabled(true);
                wView.getSettings().setAllowFileAccess(true);
                wView.getSettings().setAllowUniversalAccessFromFileURLs(true);
                wView.getSettings().setAllowContentAccess(true);
                wView.getSettings().setAppCacheEnabled(true);
                wView.getSettings().setAppCachePath(getContext().getCacheDir().getPath());

                wView.setScrollContainer(false);
                wView.setLayoutParams(rl);
                wView.loadUrl(docURL);

And here is the log when the view is displayed
I/WebViewFactory: Loading com.android.chrome version 72.0.3626.121 (code 362612102)
I/cr_LibraryLoader: Time to load native libraries: 17 ms (timestamps 4146-4163)
I/chromium: [INFO:library_loader_hooks.cc(42)] Chromium logging enabled: level = 0, default verbosity = 0
I/cr_LibraryLoader: Expected native library version number "72.0.3626.121", actual native library version number "72.0.3626.121"
W/cr_ChildProcLH: Create a new ChildConnectionAllocator with package name = com.android.chrome, sandboxed = true
I/cr_BrowserStartup: Initializing chromium process, singleProcess=false
W/ResourceType: Failure getting entry for 0x7f120538 (t=17 e=1336) (error -2147483647)
W/nicle.chronicle: type=1400 audit(0.0:15466): avc: denied { read } for name="vmstat" dev="proc" ino=4026532345 scontext=u:r:untrusted_app:s0:c512,c768 tcontext=u:object_r:proc:s0 tclass=file permissive=0
W/Adreno-EGL: <qeglDrvAPI_eglGetConfigAttrib:612>: EGL_BAD_ATTRIBUTE
W/Chrome_InProcGp: type=1400 audit(0.0:15467): avc: denied { search } for name="kgsl-3d0" dev="sysfs" ino=19452 scontext=u:r:untrusted_app:s0:c512,c768 tcontext=u:object_r:sysfs_kgsl:s0 tclass=dir permissive=0
W/Adreno-ES20: <get_gpu_clk:229>: open failed: errno 13
W/Adreno-EGL: <qeglDrvAPI_eglGetConfigAttrib:612>: EGL_BAD_ATTRIBUTE
I/Choreographer: Skipped 46 frames!  The application may be doing too much work on its main thread.
W/cr_CrashFileManager: /data/user/0/com.gochronicle.chronicle/cache/WebView/Crash Reports does not exist or is not a directory
W/VideoCapabilities: Unrecognized profile 2130706433 for video/avc
Unrecognized profile 2130706434 for video/avc
W/VideoCapabilities: Unsupported mime video/divx
W/VideoCapabilities: Unsupported mime video/divx4
W/VideoCapabilities: Unrecognized profile 2130706433 for video/avc
Unrecognized profile 2130706434 for video/avc
I/VideoCapabilities: Unsupported profile 4 for video/mp4v-es
W/Adreno-ES20: <get_gpu_clk:229>: open failed: errno 13
W/Chrome_InProcGp: type=1400 audit(0.0:15468): avc: denied { search } for name="kgsl-3d0" dev="sysfs" ino=19452 scontext=u:r:untrusted_app:s0:c512,c768 tcontext=u:object_r:sysfs_kgsl:s0 tclass=dir permissive=0
 I/zygote: Do partial code cache collection, code=1006KB, data=690KB
I/zygote: After code cache collection, code=1006KB, data=690KB
Increasing code cache capacity to 3MB
I/chromium: [INFO:CONSOLE(1)] "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.", source: https://c1-word-view-15.cdn.office.net/wv/s/161151337776_App_Scripts/WordViewer.js (1)
I/chromium: [INFO:CONSOLE(0)] "The resource https://c1-word-edit-15.cdn.office.net/we/s/161151337776_App_Scripts/jSanity.js was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it has an appropriate `as` value and it is preloaded intentionally.", source:  (0)
I/chromium: [INFO:CONSOLE(0)] "The resource https://c1-word-edit-15.cdn.office.net/we/s/161151337776_App_Scripts/Compat.js was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it has an appropriate `as` value and it is preloaded intentionally.", source:  (0)
I/chromium: [INFO:CONSOLE(0)] "The resource https://c1-officeapps-15.cdn.office.net/we/s/161151337776_App_Scripts/MicrosoftAjax.js was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it has an appropriate `as` value and it is preloaded intentionally.", source:  (0)
[INFO:CONSOLE(0)] "The resource https://c1-word-edit-15.cdn.office.net/we/s/161151337776_App_Scripts/WordEditor.js was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it has an appropriate `as` value and it is preloaded intentionally.", source:  (0)
[INFO:CONSOLE(0)] "The resource https://c1-word-edit-15.cdn.office.net/we/s/161151337776_App_Scripts/wacbootwe.js was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it has an appropriate `as` value and it is preloaded intentionally.", source:  (0)

Here is what appears to be the error, though I have gone through all of the webview settings and given a very broad range of permissions
D/libc-netbsd: getaddrinfo: word-edit.officeapps.live.com get result from proxy gai_error = 0
D/OpenSSLLib: OpensslErr:Module:12(116:176); file:external/boringssl/src/crypto/asn1/asn1_lib.c ;Line:186;Function:ASN1_get_object
D/OpenSSLLib: OpensslErr:Module:12(116:176); file:external/boringssl/src/crypto/asn1/asn1_lib.c ;Line:186;Function:ASN1_get_object
D/OpenSSLLib: OpensslErr:Module:12(116:176); file:external/boringssl/src/crypto/asn1/asn1_lib.c ;Line:186;Function:ASN1_get_object
OpensslErr:Module:12(116:176); file:external/boringssl/src/crypto/asn1/asn1_lib.c ;Line:186;Function:ASN1_get_object
D/libc-netbsd: [getaddrinfo]: hostname=word-view.officeapps.live.com; servname=(null); netid=0; mark=0
[getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=1024; ai_family=0
D/libc-netbsd: getaddrinfo: word-view.officeapps.live.com get result from proxy gai_error = 0
D/libc-netbsd: [getaddrinfo]: hostname=c1-officeapps-15.cdn.office.net; servname=(null); netid=0; mark=0
[getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=1024; ai_family=0
D/libc-netbsd: [getaddrinfo]: hostname=c1-word-view-15.cdn.office.net; servname=(null); netid=0; mark=0
[getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=1024; ai_family=0
D/libc-netbsd: getaddrinfo: c1-word-view-15.cdn.office.net get result from proxy gai_error = 0
D/libc-netbsd: getaddrinfo: c1-officeapps-15.cdn.office.net get result from proxy gai_error = 0
D/OpenSSLLib: OpensslErr:Module:12(116:176); file:external/boringssl/src/crypto/asn1/asn1_lib.c ;Line:186;Function:ASN1_get_object
OpensslErr:Module:12(116:176); file:external/boringssl/src/crypto/asn1/asn1_lib.c ;Line:186;Function:ASN1_get_object

Comment: You have no errors. Those are info and warning log messages.
Comment: Do you mind to post `docURL` so that someone could reproduce the issue?
Comment: @Onik I have added additional logging from testing today.   The interesting thing is that when I run this in the simulator, using Android 9, it works.  But when I use 8 or 6, the two physical devices I have (both tablets), I get the errors above.
Comment: On the real devices, do you get the WebView working? If not, what exactly happens on the screen?
Comment: @Onik I added a screenshot of the error message after the site tries to load
Answer: You can achieve this by an alternative way using WebView and Google Docs like below.
String url = "http://docs.google.com/gview?embedded=true&url="+YOUR_DOC_URL;

private void loadWebViewAndDocUrl()
{
    String googleDocViewer = "";
    progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
    final WebView wvExternalLink = (WebView) view.findViewById(R.id.wvExternalLink);
    wvExternalLink.getSettings().setJavaScriptEnabled(true);

    wvExternalLink.loadData(googleDocViewer, "text/html", "utf-8");

    wvExternalLink.setWebViewClient(new WebViewClient(){
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            wvExternalLink.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            // Show progress till url loads completely using progressbar
        }
    });

}

Answer: You could try
WebView urlWebView = (WebView)findViewById(R.id.containWebView);
urlWebView.setWebViewClient(new AppWebViewClients());
urlWebView.getSettings().setJavaScriptEnabled(true);
urlWebView.getSettings().setUseWideViewPort(true);
urlWebView.loadUrl("http://docs.google.com/gview?embedded=true&url="
                + "YOUR_DOC_URL_HERE");

public class AppWebViewClients extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);

    }
}

Answer: In your log file I can see two main reason that caused the crashes.
W/cr_CrashFileManager:
/data/user/0/com.gochronicle.chronicle/cache/WebView/Crash Reports does not
exist or is not a directory

I/Choreographer: Skipped 46 frames!  The application may be doing too much
work on its main thread.

The former error could be due to the appCachePath which took time to process due to wrong path.
The later error is due to the fact that your code/webview is  taking long to process and frames are being skipped because of it, It maybe because of some heavy processing that you are doing at the heart of your application  which causes the thread to stop for a while.
The solution would be to use thread separate from main UI thread for which you can use AsyncTask in android.
In your case Async task might not be required if the error was due to directory not found for appCachePath.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
FrameLayout.LayoutParams rl = new
FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT);
            android.webkit.WebView wView = new
android.webkit.WebView(this.getContext());
            wView.setId(0x100);
            //wView.setWebChromeClient(new WebChromeClient());
            wView.setWebViewClient(new WebViewClient());
            wView.getSettings().setJavaScriptEnabled(true);
            wView.getSettings().setAllowFileAccess(true);
            wView.getSettings().setAllowUniversalAccessFromFileURLs(true);
            wView.getSettings().setAllowContentAccess(true);
            wView.getSettings().setAppCacheEnabled(true);
            //also check this line of code for appCachePath
            String appCachePath = this.getCacheDir().getAbsolutePath();
             webSettings.setAppCachePath(appCachePath);

            wView.setScrollContainer(false);
            wView.setLayoutParams(rl);

            //execute asynctTask
          new LoadWebViewAsync.execute();

}
   class LoadWebViewAsync extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {

          wView.loadUrl(linktourl);
            return null;
        }
    };

Answer: You should try to open your docURL on your Tablet's browser, preferably Chrome.
Your code worked for me for this document, on a Samsung Galaxy J7 Pro, Android 8.1, and a Moto G4, Android 7.0. Both physical devices. And it did not show the URL.
It also worked on Simulated Android Nexus 5 API 23, which is Android 6.0.
The only permission you need is this:
<uses-permission android:name="android.permission.INTERNET" />
Make sure to have the Android WebView up to date on your tablets.
This could be also an issue with your DNS setup, your document's content or the domain for your document. I created the link for my test going to File -> Share -> Insert Into Blog or or Site, and took the content for the src attribute for the generated iframe.

Android WebView and Word Online


Does minus operator and not exist result in same result in oracle

Question: Can anyone help to confirm that in oracle minus operator and not exists are returning same result set?
Regards,
Mayuran
Answer: Here's proof that the minus and the not exist queries do not return the same results:
Minus Query
with t1 as (select 1 id, 'a' val from dual union all
            select 1 id, 'a' val from dual union all
            select 2 id, 'b' val from dual),
     t2 as (select 2 id, 'b' val from dual union all
            select 3 id, 'c' val from dual)
select id, val
from   t1
minus
select id, val
from   t2;

Minus Results
        ID VAL
---------- ---
         1 a

Not Exists Query
with t1 as (select 1 id, 'a' val from dual union all
            select 1 id, 'a' val from dual union all
            select 2 id, 'b' val from dual),
     t2 as (select 2 id, 'b' val from dual union all
            select 3 id, 'c' val from dual)
select id, val
from   t1
where  not exists (select null
                   from   t2
                   where  t1.id = t2.id
                   and    t1.val = t2.val);

Not Exists Results
        ID VAL
---------- ---
         1 a
         1 a

Comment: Thanks for the answer


getDefaultProcessEngine() return null

Question: ProcessEngines.getDefaultProcessEngine()
return me null when I try init a new process in activiti engine.
Do you know what could be the reason ?
Answer: Taken from the Activi forums user frederikheremans:

As stated in the Javadoc for ProcessEngines, this class is used by a
  ServletContextListener, which calls the ProcessEngines.init().  The
  init() will scan the classpath for activiti.properties an tries to
  build a ProcessEngine for each file found.
The getDefaultProcessEngine() only works [if] the ProcessEngines.init()
  has been called (by
  org.activiti.impl.servlet.listener.ProcessEnginesServletContextListener
  or by calling it yourself once) and if a process-engine with name
  'default' is available.

The OP of the thread I got that from stated that he too received null from getDefaultProcessEngine. Hope that helps.

getDefaultProcessEngine() return null


How do I convert from a cli::array to a String?

Question: I have a array<unsigned char>^ which contains a load of ascii characters which I'd like to convert into a String^. What's the most efficient way to do this?
Answer: Found a solution here:
BufferedStream file = gcnew BufferedStream(gcnew FileStream(fileName,FileMode::Open));
array<unsigned char>^ arr = gcnew array<unsigned char>(10);
file->Read(arr,0,10);

String^ s;
Text::Encoding^ enc = Text::Encoding::UTF8;
s = enc->GetString(arr);

Comment: You said they were ASCII characters in the array. Wouldn't Text::Encoding::ASCII be more appropriate?
Comment: Both appear to work for the data sets I'm using but ASCII probably _is_ more appropriate. My code actually uses ASCII but the example I was quoting says UTF8...


J: Handy method to enter a matrix?

Question: I have a n-by-m matrix written at paper and I want to make calculations on it in J.
I can enter matrices like that (n = 3, m = 3):
   A =: 3 4 $ 1 3 2 4 7 8 1 2 2 0 0 1

The question is how to enter a matrix like that:
   A =: (something here)
1 3 2 4
7 8 1 2
2 0 0 1
)

The reason why I'm asking such a weird question is that I have seen in some book a similar method of typing matrices using verb 0 : 0 or something alike, but I cannot remember where. :{
Comment: It's much easier to remember `noun define` than `0 : 0`, and I find code clearer and more maintainable with `verb define` than `3 : 0` or `adverb def 'blah blah blah'` than `1 : 'blah blah blah'` etc.
Comment: yes, good remark, although I like `0 :0` more :). I've read once `0 :0` and `3 :0`, remembered and since that time I forgot about `verb define` and others. that's a matter of taste :)
Answer: I use (something here) as (".;._2) 0 : 0. That way I can also mix expressions.
] A =: (".;._2) 0 : 0
5 $ 0
? 5 $ 5
5 $ 1
1 2 3 2 1
)
0 0 0 0 0
2 1 0 0 3
1 1 1 1 1
1 2 3 2 1

Comment: Thank you. @Tikkanz 's answer is more detailed, but yours looks laconic - in J style, so to say. :) And ability to mix expressions is really awesome!
Answer: The use of dyadic (rather than monadic) ". will attempt to resolve each line as a string of numbers rather than evaluate it as a J sentence. Where a string cannot be resolved to a number, the left argument (_99 in the example below) is used instead. This approach will correctly interpret a larger set of numbers represented as strings.
The choice of noun define rather than 0 : 0 simply saves a set of brackets that is otherwise needed to separate the _2 from the 0.
   ]A =: _99&".;._2 noun define
1 -3 2 4
7 8 1 2
2 0 0 1
)
1 _3 2 4
7  8 1 2
2  0 0 1

Comment: Thank you. I agree about `noun define`, although I believe that every J programmer firstly learns what conjunction `:` is together with `0 :0`, so he knows what is `0 :0`. And what I like in this form is that it looks like egg `0` falling at someone's screaming face `:0`. ahah :D

J: Handy method to enter a matrix?


PHP pass additional data to a callback

Question: class A {

    protected function b($string, $data) {
        return preg_replace_callback('/pattern/', [$this, 'c'], $string);
    }

    protected function c($match) {
        return $data[$match[1]];
    }

}

I want to be able to access $data from function c.
Things I DO NOT want to do:

define an anonymous function inside b, because b will get called fairly frequently and I don't want to define a new function every time.
bind $data to the instance of A, because then it will remain in memory until the instance is destroyed. I want to just pass the data and let it be collected after the replace has finished.

Do I have any other options?
Comment: Maybe instead of an anonymous function just call `$this->c($data);` in `b`? Maybe I misunderstood your intention.
Comment: @Kapparina `c` is getting called by `preg_replace_callback`, not me
Comment: You should go for an anonymous function. PHP is smart enough to cache the bytecode and not redefine the function on each call. If you think it could cause a performance issue, you should consider benchmarking the function and you'll find that your optimization probably doesn't change anything.
Comment: @this.lau_ that's very interesting, so php caches every single anonymous function ever defined (in the script) and if I try to define the absolutely same function, somewhere else entirely independent of the first declaration, php will already have it cached?
Comment: Scenario seems a bit convoluted. But couldn't assign $data to an instance variable of `A`, and set it before calling the function and unset it immediately afterwards, if you want that memory marked as available for the GC?
Comment: @yivi why would you say that is convoluted? If I did that I would need to assign the output of `preg_replace` to a variable, that's an operation I'd like to avoid doing if possible.
Comment: You shouldn't try to force something, that (according to your description) looks like meant for functional programming, inside the oop paradigm. Either there is no point in wrapping this in a class **OR** your question has left out the context.
Comment: With your restrictions you've set what you're asking for is impossible. You can't share a variable that's in the scope of one function in the scope of another function without having to bind it at a place which is commonly accessible.
Comment: for what u need access to $data ??
Answer: i highly recommend using an anonymous function for this. I know you dont want to, but it is the lest dirty way to do what you want.
I did sonse tests. A callback as in your Question and a version with an anonymous functoin.
Test I made: http://phpfiddle.org/main/code/01t6-rqjh
Results (values are seconds)

| cycles  | callable         | anonymous function |
|---------|------------------|--------------------|
| 1000    | 0.00196886062622 | 0.00189614295959   |
| 100000  | 0.187341928482   | 0.205796957016     |
| 1000000 | 1.88189315796    | 1.87302780151      |

As you can see, there is not much of a difference.
Anyway, here is my solution for you:
class A {
    protected function b($string, $data) {
        return preg_replace_callback('/pattern/', function($match) use ($data) {return $data[$match[1]];}, $string);
    }
}

Answer: I know that you don't want

...to define an anonymous function inside b, because b will get called
  fairly frequently and I don't want to define a new function every
  time.

But I still provide you a code version which does exactly what you... don't want. Or it... doesn't? ;-)
Beside this one, I think that there could also be another solution: recursively calling your b method as the callback. I didn't try to implement it yet. But I'll certainly do it.
I felt, of course, free to change your absolutely minimal namings as I wished. Don't take it personal! :-)
I'm kidding. Good luck.
<?php

class Replacement {

    /**
     * Handler for the preg-replace matches.
     *
     * @var Closure
     */
    private $handler;

    /**
     *
     * @param mixed $subject The string or an array with strings to search and replace.
     * @param mixed $pattern The pattern to search for.
     * @param array $replacements Replacements list.
     * @param integer $matchPosition [optional] Match-position for which a replacement takes place.
     * @param integer $recreate [optional] If TRUE, recreate handler.
     * @return mixed
     */
    public function start($subject, $pattern, $replacements, $matchPosition = 1, $recreate = FALSE) {
        $this->createHandler($replacements, $matchPosition, $recreate);
        return preg_replace_callback($pattern, $this->handle(), $subject);
    }

    /**
     * Create a handler for the preg-replace matches.
     * A replacements list is passed.
     *
     * Creation takes place only once in the lifecycle
     * of the instance of this class.
     *
     * @param array $replacements Replacements list.
     * @param integer $matchPosition [optional] Match-position for which a replacement takes place.
     * @param integer $recreate [optional] If TRUE, recreate handler.
     * @return $this
     */
    public function createHandler($replacements, $matchPosition = 1, $recreate = FALSE) {
        if (!isset($this->handler) || $recreate) {
            $this->handler = function($matches) use ($replacements, $matchPosition) {
                return $replacements[$matches[$matchPosition]];
            };
        }
        return $this;
    }

    /**
     * Handle preg-replace matches.
     *
     * @return Closure
     */
    public function handle() {
        return $this->handler;
    }

}

// Subject string.
$subject = 'Next april fools day is 04/01/2018 and the last Christmas was 12/24/2017.';

// Pattern to search for: mm/dd or yyyy.
$pattern = "|(\d{2}/\d{2}/)(\d{4})|";

// Create test object
$replacement = new Replacement();

// Display results.
echo '
BEFORE: "' . print_r($subject, true) . '"
' . PHP_EOL;

//*******************************************
// TEST 1: Closure creation
//*******************************************

// Replacement data.
$replacements = [
    '04/01/' => 'the same as each year',
    '12/24/' => 'in december',
];

// Start replacement process.
$output = $replacement->start($subject, $pattern, $replacements);

// Display results.
echo '
AFTER (test 1): "' . print_r($output, true) . '"
' . PHP_EOL;

//*******************************************
// TEST 2: Closure RE-creation
//*******************************************

$replacements2 = [
    '04/01/' => 'test1',
    '12/24/' => 'test2',
];

// Start replacement process.
$output2 = $replacement->start($subject, $pattern, $replacements2, 1, TRUE);

// Display results.
echo '
AFTER (test 2): "' . print_r($output2, true) . '"
' . PHP_EOL;

EDIT 1:
Oh, just forgot: The subject string and the pattern in my example are taken from the PHP docs. I changed the subject string a little bit, in order to give it a better sense. Anyway, the PHP guys can explain the patterns better then me (I'm not an expert in regex's):

Example #2 preg_replace_callback() example.

And for the recursive solution see

Example #3 preg_replace_callback() using recursive structure to
handle encapsulated BB code.

EDIT 2 (20.06.'17):
I changed the code: closure recreated on-demand by reading the $recreate bool value now. You can decide if the recreation takes place before starting replacement, by checking if the array values have changed since their initial form.
Comment: Very interesting, but how are `$replacements` in `createHandler` not remaining as the initial value passed? I'm going to look into that!
Comment: Replacements are kept and you can not use this function twice, [see here](http://sandbox.onlinephpfunctions.com/code/6025cf6281fb4c2f4f1b13d2bdf2d60f8ff76986).
Comment: @php_nub_qq Hi, so... what do you mean?
Comment: @php_nub_qq You mean replacements & mposition are read on creation and can't be changed through object lifecycle?
Comment: @php_nub_qq I changed the code correspondingly to fit the new requirements.
Comment: @php_nub_qq You'll have the impression, that the new form is not flexible. Well, it is. Because how you handle the replacement, e.g how/when you create your object, or change the replacements array, or etc, is up to you. Also read the notes in EDIT 2.
Answer: You could use a static field on the class to avoid memory usage or use a non-static field and just clear it before returning. Something like this:
class A {

    protected static $_data;

    protected function b($string, $data) {
        self::$_data = $data;
        $return = preg_replace_callback('/pattern/', [self, 'c'], $string);
        unset(self::$_data);
        return $return;
    }

    protected function c($match) {
        return array_shift(self::$_data);
    }

}

Comment: How is that any different (or better) than binding `$data` to the instance?
Comment: Well it is binding $data to the instance but if you have a static property it doesn't affect server memory as much since only one instance of $data is used, if you unset it afterwards it will only be populated while the function is running
Answer: I would create a separate class with $data property, so you can set it on an object:
interface IReplacer
{
    public function handler(array $matches);
}

class DataReplacer implements IReplacer
{
    private $data;

    public function __construct(array $data = null)
    {
        if (!is_null($data)) {
            $this->data = $data;
        }
    }

    public function setData(array $data)
    {
        $this->data = $data;

        return $this;
    }

    public function clearData()
    {
        $this->data = null;

        return $this;
    }

    public function handler(array $matches)
    {
        if (!isset($this->data[$matches[0]])) {
            // Do what ever is more plausable here.
            // Throw an exception or provide default value.
            return 'default value';
        }

        return $this->data[$matches[0]];
    }
}

Then you will inject an object of this class as a dependency into your A class:
class A
{
    private $replacer;

    public function __construct(IReplacer $replacer)
    {
        $this->replacer = $replacer;
    }

    public function b($string, array $data)
    {
        $result = preg_replace_callback(
            '/pattern/',
            [$this->replacer->setData($data), 'handler'],
            $string
        );

        // Clear data so it is not hanging around in the memory.
        $this->replacer->clearData();

        return $result;
    }
}

Having this you can use it like (I have made method b public for the sake of testing simplicity):
$a = new A(new DataReplacer);

$string = 'This is example with pattern';

var_dump($a->b($string, ['pattern' => 'foo']));
var_dump($a->b($string, ['pattern' => 'bar']));
var_dump($a->b($string, []));

Here is working demo.
Answer: There are 2 strategies you can consider to access the data variable:

Hide its contents in your regex. Example:
$string = "Goodbye cruel world!";
$replacements = [ "Goodbye" => "Hello", "cruel" => "nice" ];
//Build your regex with named capturing groups e.g.
$result = preg_replace_callback("/(?P<Hello>Goodbye)|(?P<nice>cruel)/" , function ($match) {
        $filtered = array_filter($match,function ($v,$k) { return $v != null && !is_numeric($k); }, ARRAY_FILTER_USE_BOTH);
        return array_keys($filtered)[0];
}, $string);

If all else fails there's always the backtrace:
protected function b($string, $data) {
    return preg_replace_callback('/pattern/', [$this, 'c'], $string);
}

protected function c($match) {
    //Second argument of the function that is 3rd on the call stack
    // 0 is this function 1 is the preg_replace_callback function so 2 is b
    $data = debug_backtrace()[2]["args"][2];
return $data[$match[1]];
}

Notes: There's very strict limitations in what names the capturing groups can have so it's probably not a viable choice many times. However I don't think the backtrace will offer any sort of improvement over binding the function though.
I'd suggest you do the simple:
protected function b($string, $data) {
    return preg_replace_callback('/pattern/', function ($match) use ($data) {
       return $data[$match[1]];
    }, $string);
}

which is just embedding the function. PHP optimizations will prevent the $data array from being copied unless it's actually modified.
Answer: try this
class A {

    private $data;

    protected function b($string, $data) {
        $this->data = $data;
        return preg_replace_callback('/pattern/', [$this, 'c'], $string);
    }

    protected function c($match) {
        return $this->data[$match[1]];
    }

}

PHP pass additional data to a callback


Finding rational solutions to a function with integer inputs

Question: I'm trying to find rational solutions to the equation $$f(x) = \frac{1-x+\sqrt{5x^2-2x+1}}{2x};\{ x \in \mathbb{N} \}$$
The only operation that could produce an irrational answer is the square root, so I figure all I need to do is find rational solutions to
$$y = \sqrt{5x^2-2x+1}$$
which I think can be further adjusted to say:
$$y^2= 5x^2-2x+1; \left \{x \in \mathbb{N} \ \text{and} \ y \in \mathbb{Q} \right \}$$
(excuse my notation if it's wrong) Without the $-2x$, it looks like another similar problem I've done where I've used Pell's equation to solve it, but this is a little different. How do I find the integer solutions? Can it be solved with pells equation?
Comment: You have $5x^2-2x+1=4x^2+x^2-2x+1=(2x)^2+(x-1)^2$, now apply Pythagoras if possible...
Comment: @abiessu when you say apply Pythagoras, do you mean use a generating function to find Pythagorean triples?
Comment: I mean that you have $y^2=a^2+b^2$, and you know the form that $a$ and $b$ take on.  I would use the $p,q$ form to find a way to match up with $2x$ and $x-1$...
Comment: @abiessu P,q... are you are referring to euclids formula, letting $a = (2x)^2 = p^2 - q^2$ and $ b= (x-1)^2 = 2pq$ then solving for x using a system of equations? It would only leave me with another expression that introduces two new variables under a square root... Im sorry I don't understand where you're going with that
Answer: $5x^2 - 2x + 1 -y^2 = 0 \implies \triangle' = (-1)^2 - 5(1-y^2) = 5y^2 -4 = m^2\implies 5y^2 - m^2 = 4$. This Pell equation has initial solution $(m,y) = (\pm 1, \pm 1)$. You can google the full solution set on the internet. Check out Lenstra's Pell equation notes.
Comment: How can you do that if Pell's equation takes the form $x^2 - ny^2 = 1$ and the equation has the additional $-2x$ term?
Answer: If you let $y=\dfrac{p}{q}$, $p,\,q\in\mathbb{Z}$, and complete the square on the polynomial under the radical you get
$$ \sqrt{\frac{(5x-1)^2+4}{5}}=\frac{p}{q} $$
then you have
$$ \frac{(5x-1)^2+4}{5}=\frac{p^2}{q^2} $$
Letting $r=5x-1$ this transforms into the question solving for  $p,\,q,\in\mathbb{Z}$, $r\in\mathbb{Q}$ satisfying
$$ (r^2+4)q^2=5p^2 $$


Two sample K-S test as an alternative to maximum likelihood

Question: I have a model with 3 parameters that I would like to fit to my (unidimensional iid) data. The model is a Hidden Markov Model and therefore it is intrinsically probabilistic. It is fairly straightforward to simulate samples from it. However, given the functional form of the transition and emission probabilities, it is very troublesome to obtain the likelihood function.
So I was thinking, what if I simulate $n$ iid samples $\mathbf{y}={y_1,y_2,...,y_n}$ from the model and then compare it with my sequence of $m$ iid observations $\mathbf{x}={x_1,x_2,...,x_m}$ with a two sample K-S test to check if they are drawn from the same distribution? Then I could find the set of parameters that minimize the $D_{nm}$ statistic coming from the K-S test.
How does this compare to maximum likelihood? Would this method have any clear disadvantages? Is there a preferred size $n$ of the simulated samples that would optimize the method according to $m$?
Comment: I am curious how you would go about finding those parameters, since your objective function isn't differentiable and can be computed only approximately.  I suspect the solution would (in general) be a large set of parameters even if you could compute the objective function exactly.
Comment: Assuming $D$ would be concave, I would create a grid for the parameters and iterate over it until I find the minimum, or use something more sophisticated like fminsearch in matlab.
Comment: Your computational requirements will be enormous, because simulation will only approximate the distribution poorly unless $n$ is huge.
Comment: Do you think that a particle filter (sequential MC) approach is generally more adequate? (In line with what @Alf suggested)
Answer: To a certain extent, and more informally, your proposal is related to the Approximate Bayesian Computation (ABC) approach in which you simulate from your model and check whether or not it is similar to your original data. In your case, you are comparing the two samples using the KS test, and the performance of this approach depends on the tunning parameters (significance level, sample size, and etcetera). The following reference discusses different approaches to estimate the parameters in hidden Markov models, which are related to ABC:

Dean, Thomas A., et al. "Parameter estimation for hidden Markov models with intractable likelihoods." Scandinavian Journal of Statistics 41.4 (2014): 970-987.


Configuring react-bootstrap with Rails 4.2

Question: I would like to integrate React-bootstrap with my current Rails project. I am new to ReactJS, so I thought using the react-bootstrap lib would make things a bit easier. However, I find the configuration very hard. There is supposedly a gem for this, but it throws an error of 'Permission denied' once the instructions on the README are followed. I tried a snipped from the react-bootstrap web site, which works without the react-bootstrap syntax. However, all the solutions I have tried involing Bower, npm, rails-assets gem, etc., don't make the react-bootstrap syntax render. This is my Button.js.jsx file which won't render to my home page:
var button = ReactBootstrap.Button({
  bsStyle: "success",
  bsSize: "large",
  children: "Register"
});

React.render(button, document.getElementById("content"));

Tips and suggestions are very welcome!
Comment: How are you bringing ReactBootstrap into scope? Are you using CommonJS? Or are you using the asset pipeline and requiring react-bootstrap via sprockets?
Answer: I had a similar issue today of integrating the react-bootstrap package into my RoR application, so I found this gem: https://github.com/mariopeixoto/react-bootstrap-rails which basically puts all react bootstrap components at your disposal by just accessing a global variable ReactBootstrap.
Hope this helps!
Answer: I'm assuming that you have bootstrap.min.css included in your HTML file.
Something else to keep in mind is that facebook admits to this being in development.
The project is under active development, and APIs will change. Check out the 1.0.0 Roadmap and Contributing Guidelines to see where you can help out. Prior to the 1.0.0 release, breaking changes should result in a Minor version bump.
Make sure that you follow these steps (http://react-bootstrap.github.io/getting-started.html) for however you are including the files
I personally chose this way and it created the elements fine for me.

Answer: Using the aforementioned gem, and including
//= require react_bootstrap

in application.js, I was able to get the following code to render without errors.
var button = ReactBootstrap.Button;

ReactDOM.render(<button
    bsStyle="success"
    bsSize="large"
    children="Register"/>,
  document.getElementById("content"));

Comment: I don't think, this gem is being maintained


prove this inequality $\sum\frac{a}{b}\ge \sum a^2$

Question: Let $a,b,c>0$ such $a+b+c=3$, show that
$$\dfrac{a}{b}+\dfrac{b}{c}+\dfrac{c}{a}\ge a^2+b^2+c^2$$
I have show this not stronger inequality
$$\sum\dfrac{a}{b}\ge \sum a$$
Comment: What is the range of your sums? What have you done so far? Can you explain more?
Comment: Use the $uvw$ technique.
Answer: Let $\sum $ denote cyclic sum, then observe:
$$\sum a(a-b)^2(b-2c)^2 \geqslant 0$$
$$\implies \sum ab^4 + \sum a^3b^2 + 2\sum a^2b^3+4abc\sum ab -8abc\sum a^2 \geqslant 0 $$
$$\implies 2\left( \sum a \right)^2\sum ab^2 + abc\left(\sum a\right)^2 \geqslant 21abc\sum a^2$$
$$\implies 6 \sum \frac{a}b + 3 \geqslant 7\sum a^2$$
Add the obvious $\sum a^2 \geqslant 3$ to the above to conclude. Equality is when $a=b=c=1$.
Comment: Yes, it's a very known solution, but I think it's impossible to find this solution  during a competition. By the way, the $uvw$'s technique gets a smooth proof.


Android Accelerometer - Dynamic Time Warping

Question: For a class project I need to recognise gestures using the accelerometer.
I currently use an explicit method of if statements on the x, y and z values.
I've read that Dynamic Time Wrapping is a more efficient way as it checks for a match between a gesture and a previously stored gesture.
How would I go about coding this in Android as I can't seem to find anything online.
public void onSensorChanged(SensorEvent event) {

    final float alpha = (float) 0.8;

    // Isolate the force of gravity with the low-pass filter.
    gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0];
    gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1];
    gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2];

    // Remove the gravity contribution with the high-pass filter.
    linear_acceleration[0] = event.values[0] - gravity[0];
    linear_acceleration[1] = event.values[1] - gravity[1];
    linear_acceleration[2] = event.values[2] - gravity[2];

    float x1 =  linear_acceleration[0];
    float y1 =  linear_acceleration[1];
    float z1 =  linear_acceleration[2];

    x.setText("X: "+ x1);
    y.setText("Y: "+ y1);
    z.setText("Z: " + z1);

    if(y1 < -2 && z1 > 2)
    {
        action.setText("Phone Moved Forward!!");
        image.setVisibility(View.VISIBLE);
        image.setImageResource(R.drawable.forwardarrow);
    }
    else if(y1 < -2 && z1 < -2)
    {
        action.setText("Phone Moved Toward Face!!");
        image.setVisibility(View.VISIBLE);
        image.setImageResource(R.drawable.backarrow);
    }
    else if(y1 < -2 && x1 > 2)//y down, x up = left tilt
    {
        action.setText("Phone Titled Left!");
        image.setVisibility(View.VISIBLE);
        image.setImageResource(R.drawable.leftarrow);
    }
    else if(y1 < -2 && x1 < -2)//y down, x down = right tilt
    {
        action.setText("Phone Titled Right!");
        image.setVisibility(View.VISIBLE);
        image.setImageResource(R.drawable.rightarrow);
    }
    else
    {
        image.setVisibility(View.GONE);
        action.setText("Stable");
    }

}

Answer: I've uploaded a repository to GitHub which demonstrates an example of Dynamic Time Warping for acceleromter data; you might find it useful!
Answer: The dynamic time warping computes the distance between two time-series. You store a template for the comparison and use the actual move as candidate. If you use all channels, you will have three different time-series and distances. If the accumulated distance is under a specific threshold, the movement will be marked as recognized. The difficult part is that you have continuous time-series. It's hard to spot gestures. Nevertheless the algorithm finds the best alignment between two time-series.
The method onSensorChanged gives you a single point of the time-series. So you have to build a First-In-First-Out (FIFO) data structure (e.g. a queue) which stores all changes of the last second.
Maybe the FastDTW library is helpful: https://code.google.com/archive/p/fastdtw/


Não consigo redirecionar para uma nova uma aba dentro da mesma url

Question: Sou iniciante em PHP e estou com dificuldades pra conseguir achar uma solução pro meu problema.
Tenho um array principal com 7 arrays, com 2 campos cada, que são abas numa das urls do site.
Preciso que ao clicar no botão 'próxima etapa' seja redirecionado para a segunda aba, mas não consegui fazer nem por json nem por javascript. Alguém pode me ajudar?
Segue abaixo parte do código.
$topicos = array(
    array(
        "id"    => 1,
        "label" => "Formação"
    ),
    array(
        "id"    => 2,
        "label" => "Cursos Extra Curriculares"
    ),
    array(
        "id"    => 3,
        "label" => "Experiências Profissionais"
    ),
    array(
        "id"    => 4,
        "label" => "Experiências Internacionais"
    ),
    array(
        "id"    => 5,
        "label" => "Idiomas"
    ),
    array(
        "id"    => 6,
        "label" => "Conhecimentos Técnicos Específicos"
    ),
    array(
        "id"    => 7,
        "label" => "Outras Informações"
    )
);

<form action="<?= $path ?>banco_de_talentos_add_2" id="segundo_formulario" method="post" enctype="multipart/form-data">
<input type="hidden" id="proxima" name="proxima" value="0"/>

                <?php
                foreach ($topicos as $t):
                    if($t["id"] == 1):
                        echo "
" . $t["label"] . "
";
                    else:
                        echo "
" . $t["label"] . "
";
                    endif;
                endforeach;
                ?>

            <?php foreach($topicos as $t):
                if($t["id"] == 1):
                    echo '
';
                else:
                    echo '
';
                endif;

                include "banco_de_talentos_formulario_" . $t["id"] . ".php";

                echo '
';
            endforeach; ?>

    <input type="submit" value="Salvar" class="btn"/>
    <input type="button" id="btn_anterior" value="Etapa Anterior" class="btn" onClick="document.getElementById('proxima').value = 2; document.getElementById('segundo_formulario').submit()"/>
    <input type="button" id="btn_proxima" value="Próxima Etapa" class="btn" onClick="document.getElementById('proxima').value = 1; document.getElementById('segundo_formulario').submit()"/>

Answer: Dê uma olhada nesse JSFiddle.
https://jsfiddle.net/o47v8La9/
Fiz um sistema de abas que dá para você entender.
HTML

     PHP
     HTML
     JS

 Teste Aba PHP

 Teste Aba HTML

 Teste Aba JS

Note que no código acima criei 3 abas. Cada uma delas tem um ID.
E depois embaixo criei 3 divs com o mesmo ID da aba, mas sem a #.
Depois no JS com jQuery...
$('.tab').click(function(){
    $('.main').hide();

    var tabSelecionada = $(this).prop('id');

    $(tabSelecionada).show();
});

A primeira linha é a função do click no elemento da aba, nos Links por assim dizer.
Quando clico em um deles, a função esconde todas as abas (na segunda linha) e depois mostra apenas que foi selecionada (na quinta linha).
Agora é só implementar no seu código, caso sirva.
Comment: Obrigado, mas eu preciso colocar essa mudança de abas para o evento onclick, no botão próxima etapa. Toda vez que eu clicar no botão próxima etapa, ele redireciona para a próxima aba. Você poderia me ajudar?
Comment: Então, é a mesma ideia...
Comment: Usei a mesma idéia, só alterando para os nomes das classes que eu tenho, mas ainda assim não consegui. Em outra página do site, foi feitoa mesma coisa, só que com duas abas, clico no botão e redireciono para outra aba...


I need to do rollback or somenthing when I don't need to do anything more?

Question: I have this method that return a bool:
using(Entities dbContext = new Entities())
{
    using (DbContextTransaction myTransaction = dbContext.Database.BeginTransaction())
    {
        //Get data from database

        //check data from database

        //if my data is the expected: return true;
            //???: rollback or something to do or is it enough with the return?

        //if not is expected:
            //update data;
            //dbContext.Savechages();
            //myTransaction.Commit();
            //return true;
    }
}

My doubt is, if I don't have to do more with the data, is it enough returning true or It would be recommended to do a rollback, or commit with no SaveChanges?
Thanks.
Comment: If you are reading the data and doing nothing to it, then you do not need to rollback since there is nothing to rollback.
Answer: You should check your data before begin transaction, you dont need begin trasnaction while you are reading data from DB, because first part in your logic there is no any update,insert... and you dont need any commit or rollback
Actually your code should be like this
using(Entities dbContext = new Entities())
{
        //Get data from database

        //check data from database

        //if my data is the expected: return true;

using (DbContextTransaction myTransaction = dbContext.Database.BeginTransaction())
    {
         //if not is expected:
            try
             {
               //update data;
               //dbContext.Savechages();
               //myTransaction.Commit();
               //return true;
             }
           catch(Exception ex)
           {
            transaction.Rollback();
            ......
            return false;
        }
    }
}

Comment: Thanks. But if I open the transaction after check the data, another user could modify the data and when I open the transaction I can't be sure that the data has the expected values. If i use the transaction it is to ensure that.
Comment: begin transaction cant lock your table or table row, if you are in begin trasaction block that time  another user can change data in your database, there is no any lock, Try to lock row , or check your row status was it changed or no... you can use "RowVersion"  like this http://stackoverflow.com/questions/14718929/best-practice-to-lock-a-record-for-editing-while-using-entity-framework
Comment: Yes, in my example for simplify, I dind't explain that in my case I want to use pesimistic concurrency. But with EF, if I don't block the rows with hits like UPDLOCK, there is no reason to use a transaction, from my point of view, because dbContext is a transaction.


Thread local variable accessed through non-thread local object

Question: Let's start with a piece of code (Coliru):
#include <iostream>
#include <thread>

using namespace std;

struct A
{
    thread_local static A* p_a;
    thread_local static int i;
};

thread_local int A::i;
thread_local A* A::p_a;

int main( )
{
    A::p_a = new A;

    auto lambda = [](A* a)
        {
          a->i = 1; // Prints 1 (below, of course)
          std::cout <i << std::endl;
        };

    std::thread t(std::bind(lambda, A::p_a));
    t.join();

    // Prints 0 (it hasn't been modified)
    std::cout <i << std::endl;

    return 0;
}

As all of you can see, the second thread modifies its thread local copy of A::i, even though I accessed it from another thread local object of another thread. Is it the expected behaviour? Because it makes impossible to get info from another thread using a "referer" unless I pass a pointer or reference to the foreign's thread_local object which I want to read.
With "referer" I refer something which manages or can give you access to its own thread_local variable from its thread. But that's impossible!! Any expression yielding a thread_local variable, no matter from whom (I have done different test, even with accessor functions), ends by using the thread_local instance of the reading thread.
Comment: I am not sure using a `thread_local` to communicate between threads is a in keeping with the spirit of `thread_local` storage. Why not just use a normal `static`?
Comment: Ah well its a *syntax* issue. Just because you are using syntax that looks like you are dereferencing an `A` pointer, you're not. The compiler sees it is a `static` and ignores the pointer and goes straight for the single (per thread in this case) static instance. The whole `thread_local` business is actually irrelevant to that.
Comment: I'm just.... "understanding the behaviour" (or trying to).
Comment: Make i a regular non static and non thread_local member. Then your lambda will be referring to the i from the instance of A created in main.
Answer: This is a syntax issue: In this case a->i; is identical to A::i; because A::i is a static member and its address is not dependant on any one instance of A.
So just because you are using syntax that looks like you are dereferencing an A pointer, you're not. The compiler sees it is a static member and ignores the pointer and goes straight for the single (per thread in this case) static instance. The whole thread_local business is actually irrelevant to that.
So when you are accessing a static member of A through A* a in your lambda, the compiler is ignoring the address you gave it and doing A::i regardless (getting its own thread_local version).
struct A
{
    static int i;
};

A* a = new A;
a->i; // identical to A::i (because i is static)

This is standard syntax as mentioned here in the C++14 Standard:

5.2.5 Class member access [ expr.ref ]
1. A postfix expression followed by a dot . or an arrow ->, optionally followed by the keyword template (14.2),
  and then followed by an id-expression, is a postfix expression. The postfix expression before the dot or arrow
  is evaluated; 65 the result of that evaluation, together with the id-expression, determines the result of the
  entire postfix expression.
...
65) If the class member access expression is evaluated, the subexpression evaluation happens even if the result is unnecessary
  to determine the value of the entire postfix expression, for example if the id-expression denotes a static member.

(emphasis mine)
Comment: @Peregring-lk I just included an excerpt from the `C++14 Standard` confirming this syntax is legal when accessing *static members*. Regarding overloading `operator->` well that just yields another pointer to which the `->` is finally applied. I would imagine (though not confirmed) the type of the yielded pointer determines which class' static member is accessed in that case.
Comment: But that's a "compiler" thing? Or is it present on the standard?
Comment: @Peregring-lk Its part of the syntax. If you think about it there is only **one** version of static members per class. So how can the compiler care about which address you access that **single** instance? With `thread_local` it simply means there is only one *per thread* but the problem remains. Accessing *static* members through `->` doesn't use the pointer, it just uses the *class type* to find the static (or thread_local static) instance.
Comment: Yes.  my comment deleted as obsolete.  This one will follow shortly.
Comment: Yes its clearer. I was just wondering if you replied because of your "own deductions" or that's the "designed" behaviour. Thinks that the dereference operator is being ignored; it is just seen to track which object the expression refers to; it's like searching "by name". Thinks that "p_a" could be a custom made pointer wrapper with an overloaded `operator*` and so on; the "syntax sugar" explanation will be harder to defend (what if there's an `if` involved before returning the reference?). But anyway, in any case, I'm convinced the used var will be the thread local one and no the external one.
Answer: you passed one 'A' porinter, but we should know that 'i' variable and 'p_a' variable are not belong 'A' actually, then are static, so although you started a thread passed by a 'A' pointer,then modified 'i' variable, it is different ,because this 'i' is not outside 'i',they are different.


drush cron fails: Drush command terminated abnormally due to an unrecoverable error

Question: $ drush -v -d cron
Bootstrap to phase 0. [0 sec, 1.65 MB]                               [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0 sec, 1.77 MB]    [bootstrap]
Cache HIT cid: 5.4-commandfiles-0-33f01882e55343a61f1cb10880b0da0f [0.01 sec, 1.78 MB]                                          [debug]
Bootstrap to phase 0. [0.02 sec, 4.16 MB]                                                                                [bootstrap]
Bootstrap to phase 6. [0.02 sec, 4.16 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_root() [0.02 sec, 4.17 MB]                                                  [bootstrap]
Initialized Drupal 7.28 root directory at ...htdocs [0.03 sec, 5.78 MB]                                [notice]
Drush bootstrap phase : _drush_bootstrap_drupal_site() [0.03 sec, 5.78 MB]                                                  [bootstrap]
Initialized Drupal site default at sites/default [0.03 sec, 5.79 MB]                                                           [notice]
Cache HIT cid: 5.4-commandfiles-2-c32acd775c18a90c5b41d0fc9accf5ab [0.03 sec, 5.79 MB]                                          [debug]
Drush bootstrap phase : _drush_bootstrap_drupal_configuration() [0.03 sec, 5.79 MB]                                         [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_database() [0.03 sec, 5.8 MB]                                               [bootstrap]
Successfully connected to the Drupal database. [0.03 sec, 5.8 MB]                                                           [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_full() [0.04 sec, 6.3 MB]                                                   [bootstrap]
Cache HIT cid: 5.4-commandfiles-5-21916586faf556c236c401ff89ea50f6 [0.18 sec, 33.52 MB]                                         [debug]
Drush bootstrap phase : _drush_bootstrap_drupal_login() [0.18 sec, 34.19 MB]                                                [bootstrap]
Successfully logged into Drupal as Anonymous (uid=0) [0.18 sec, 34.2 MB]                                                    [bootstrap]
Found command: core-cron (commandfile=core) [0.18 sec, 34.2 MB]                                                             [bootstrap]
Drush command terminated abnormally due to an unrecoverable error. [0.2 sec, 34.87 MB]                                      [error]

There's nothing showing up in admin/reports/dblog.
Note that heading to /cron.php?cron_key=... works fine from the web interface. But it fails when curling it from console.
(I also reported an issue at https://github.com/drush-ops/drush/issues/664 but was directed here.)
How can I find out what's wrong?
P.S. related: https://stackoverflow.com/questions/10014142/cron-fails-when-running-through-drush-and-calling-node-load
Comment: Instead, `drush elysia-cron` worked fine!
Comment: Right, if you have Elysia Cron installed, you have to run `drush elysia-cron` instead of `drush cron` (which is an alias for `drush core-cron`).
Comment: Can you try: drush elysia-cron Does that work?
Answer: Apparently Elysia Cron was installed and in that case you have to
drush elysia-cron

And drush cron is an alias of drush core-cron.


Using setTimeout and setInterval

Question: I need to call a function with in 30 seconds when I initially load the page. Thereafter it should be called in 60 seconds automatically.
What i did is,

But The function is called in irregular times, i think. Am I doing correct? If any mistake kindly share....
Comment: By the way, your closing `` tag is in the wrong place, should be before ``.
Comment: The seconds were called using php code. I didnt shared for simplifying the code.
Comment: How irregular? Currently, it'll call it at 30, 60, 120, 180... Make it smaller numbers so you can confirm? Also, it's better to write `30 * 1000`, 30k is not bad but especially with bigger numbers it's just unreadable. It sounds like you may have checked but are you sure PHP code is right?
Answer: Don't pass a string .. pass the function name/declaration itself:
setTimeout(function () {
   ajaxload();
   setInterval(ajaxload, 60000);
}, 30000);

Comment: This is absolutely the correct response.  Proper use of setTimeout and setInterval as well as use of anonymous function instead of a string.

Only thing I would do is assign the setInterval to a variable so it can be cancelled at a later time, if required.
Answer: You are using it a bit incorrectly. If the first one is at 30 secs and thereafter at 60 secs you should do it in sequence.
setTimeout(startAjaxLoad,30000);

function ajaxload()
{
     //code
}

function startAjaxLoad()
{
    ajaxload();
    setInterval(ajaxload,60000);
}

Answer: change to
setTimeout(function(){ajaxload()},30000);
setInterval(function(){ajaxload()},60000);
function ajaxload()
        {
         //code
        }

Comment: There's no need for the anonymous functions.  You can just pass ajaxload directly as a reference here and this doesn't solve any problems.
Answer: I would consider something a little tidier if you're going to continuously call an AJAX method, by waiting for it to finish first and then simply using setTimeout() again.
function ajaxload()
{
    $.ajax({

        // AJAX Settings.
        // ...

        complete: function()
        {
            // Call .ajaxload() 60 seconds from the completion of this request.
            setTimeout(ajaxload, 60000);
        }

    });
}

// Initial call.
setTimeout(ajaxload, 30000);

Using setTimeout and setInterval


Como fazer o keyframe parar no 100%/ficar estático após a animação?

Question: Tenho o seguinte keyframe:
@keyframes bolha
    0%   {width: 0px;
         height: 0px;}
    50%  {width: 600px;
         height: 600px;}
    100% {width: 400px;
         height: 400px;}
}

chamo ele dessa forma:
-webkit-animation: bolha 1s;

O resultado: Execute 1 vez a animação e pare no 100% ficando estática.
Sou iniciante, desculpem pela ignorância...
Comment: Essa repetição só ocorre se você colocar `animation: bolha 1s infinite`
Answer: Adiciona o seguinte atributo no CSS: animation-fill-mode: forwards.
Pra funcionar em todos os navegadores:
-webkit-animation-fill-mode: forwards;
-moz-animation-fill-mode: forwards;
animation-fill-mode: forwards;

Documentação aqui


Create a csv file with file name and path specified

Question: I know this should be simple but I am naive in c#. I have the following object to generate as csv. and I am successfully able to generate a csv string using the method here
[Serializable]
public class UserSession
{
    public string UserName { get; set; }
    public string UserGuid { get; set; }
    public string MachineGuid { get; set; }
    public Guid SessionGuid { get; set; }
    public DateTime LoginTime { get; set; }
    public DateTime? LogOffTime { get; set; }
    public TimeSpan? DesktopReady { get; set; }
    public bool IsReadable { get; set; }
    public int SessionId { get; set; }
}

Now I want to save this file in a specified path (for eg :

c://csvfolder/{myFilename}.csv

Can anyone suggest a method to write this csv file to 'myFilename.csv' and save it in c://csvfolder in c#??
Comment: System.IO.File.WriteAllText(@"c:\csvfolder\myFilename.csv", text); where text is the csv string you created
Comment: Btw. if any of the fields (string representation) contains the separator, you're gonna have a bad time...
Comment: Well, if *one* field contains a separator, how do you distinguish it from being *two* fields? Usually by either escaping the separator or enclosing the field in double quotes. Now what if the field contains the escape character or double quotes? What about line breaks? You get down a rabbit hole quite fast. CSV sounds easy, but corner cases can make it troublesome. See [CSV trouble](http://www.secretgeek.net/csv_trouble) for example.
Comment: Thanks @Corak... I think i will find some other method for creating csv...
Answer: That should be pretty simple. It looks like you have a generic class that can serialize your object into a string buffer.
All there's left is to take the string containing the CSV data and write it to a file. Fortunately that's quite trivial in C#:
string path = @"c:\csvfolder\myFilename.csv";

// assuming there's a UserSession object called userSessionObject..
string csvData = ToCsv<UserSession>(",", new [] {userSessionObject});
File.WriteAllText(path, csvData);

Answer: Try the following code, for saving the CSV File (Includes the creation of CSV)
    string path = "c://csvfolder";
    string fileName = "FileName.csv";

    StreamWriter SW = new StreamWriter(path, false);

     SW.Write( /*Can create the comma sperated items*/);
    /*Create y our CSV file data here*/

    fs = File.Open(path, FileMode.Open);
    int BUFFER_SIZE = Convert.ToInt32(fs.Length);
    int nBytesRead = 0;
    Byte[] Buffer = new Byte[BUFFER_SIZE];
    nBytesRead = fs.Read(Buffer, 0, BUFFER_SIZE);
    fs.Close();
    Response.AddHeader("Content-disposition", "attachment; filename=" + fileName);
    Response.ContentType = "application/octet-stream";
    Response.BinaryWrite(Buffer);
    Response.Flush();
    Response.End();


Importação de Modulos python

Question: eu estou com um problema com o python.
Eu tenho um arquivo com códigos python trabalhando com selenium, e eu tenho outro arquivo python trabalhando em JSON. Esses dois códigos estão dentro da mesma pasta, para eu importar um arquivo JSON.py para o arquivo Selenium.py
Este é o arquivo JSON.py
import json
def json():
    dados = '{'dados_enviar': 'google.com'}'
    data = json.loads(dados['dados_enviar'])
    print(data)
json()

Este é o aquivo Selenium.py
from JSON import * # meu arquivo JSON.py que está na mesma pasta que o Selenium.py
import json           # biblioteca nativa do python
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get('https://www.google.com')
elem = driver.find_element_by_name('q')
elem.send_keys('{}'.data['dados_enviar'])

quando eu executo o código ele me retorna o seguinte erro.
NameError: global name 'data' is not defined

Alguém pode me ajudar por favor???
Answer: Bom, cara rodei o seu código em minha IDE, e inicialmente o primeiro erro foi referente ao nome da função que você atribuiu no "JSON.py", o nome json() não pode ser utilizado quando se importa a biblioteca json, ao tentar criar uma função com esse nome ele dará erro, visto que essa função já esta deifinida na biblioteca json. Estranho foi seu editor não ter apontado tal problema.
Segunda coisa, você não precisaria necessariamente importar o json nos dois programas, pois se um está importando o outro, não há necessidade.
E perceba que a declaração da variável "dados" possui um erro de sintaxe, se querer que a mesma seja um dicionário, deveria ser da seguinte forma:
dados = {'dados_enviar': 'google.com'}

EDIT: Quanto ao erro que dá, o mesmo indica que a variavel data não está definida, e isso acontece pois os nomes definidos numa função fazem referência ao módulo em que eles entã odefinidos, e não nos módulos em que eles estão sendo importados, tenho uma sugestão para corrigir isso, que seria:
JSON.py:
import json
def worker():
    dados = {'dados_enviar': 'google.com'}
    data = json.loads(dados['dados_enviar'])
    return data

Selenium.py:
from JSON import *
import json
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

data = worker()   #Fazendo isso, você estancia a variavel no módulo local, recebendo o valor retornado pelo import

driver = webdriver.Firefox()
driver.get('https://www.google.com')
elem = driver.find_element_by_name('q')
elem.send_keys('{}'.data['dados_enviar'])

Comment: Eu tinha colocado (dados =  '{"processo": "google.com"}'  ), editei o código como você disse mas ele retorna um erro para mim (  TypeError: expected string or buffer  )
Comment: eu editei o nome da função, coloquei (  def worker():   ), continua dando o mesmo erro.
Comment: editei a pergunta a fim de tentar resolver o que queres, veja se foi coerente, e se funcionou!
Comment: OOOWW obrigado cara ajudou muito!!!!!!
Answer: Quando você define uma variável em uma função, ela só é acessível nessa função. Portanto, o data definido em def json() não está disponível em no contexto do seu Selenium.py.
Para disponibilizar informações para outras funções, você as tem que passar através de uma instrução de retorno dentro da função, possivelmente atribuindo-a a uma variável. Assim você poderá chamar essa variável retornada que está "carregada" com os dados que vieram do seu json.
import json
def json():
    dados = '{'dados_enviar': 'google.com'}'
    data = json.loads(dados['dados_enviar'])
    print(data)
    return data
json()

Comment: então, eu fiz isso que você me sugeriu, ele me retornou error ( NameError: name 'data' is not defined )
Comment: Sim, você tem que declarar ela como variável global. Dá uma lida nisso. É bem fácil de entender e aplicar. Ali coloquei só um direcionamento

Importação de Modulos python


What are the consequences when large-sample asymptotics does not hold?

Question: Lots of (frequentist) statistical inference is based on large-sample asymptotics.
What are the specific consequences when a sample size is not big enough for the sampling distribution of an estimator to be approximated using the asymptotic sampling distribution?
The confidence interval will not have proper coverage, but will it be too wide or too narrow?
Comment: Can be too wide, too narrow, or a mixture of both, sometimes a complicated mixture of both. For one example pertaining to asymptotics on Bernouli see the simulation presented in  Agresti, A. and Coull, B. A. (1998). [Approximate is better than "exact" for interval estimation of binomial proportions](http://www.math.unm.edu/~james/Agresti1998.pdf). *The American Statistician*, 52(2):119–126.
Comment: @Alexis I think that's basically an answer, maybe with a bit more detail. Do you want to write it?
Comment: @PeterFlom-ReinstateMonica Thank you for the encouragement. I also welcome any guidance on my answer, now posted.
Answer: Asymptotic confidence intervals on 'small' samples can have wider than nominal coverage, narrower than nominal coverage, or a mixture of both… sometimes a complicated mixture of both wider and narrower coverage.
(This is a broad question, so this answer is similarly broad.)
The particulars of wider vs narrower vs a mixture of both will depend on the specific distribution and the sample size in question, as well as by the specific form of CI. As one example, Figure 4 from Agresti & Coull (1998) below illustrates the empirical coverage probabilities based on simulations using two asymptotic CIs (left and center), and the exact CI (right) for a proportion (the $p$ of a Bernoulli distribution) at sample sizes 5 and 10.

As you can see, the Wald CI produces narrower than nominal coverage for virtually all values of $p$, the adjusted Wald CI appears to have less bias than the Wald CI when averaged across all values of $p$, but has a mixture, and the exact ('non-asymptotic') has strictly wider coverage. Also of note is the heterogeneous patterning of the biases across values of $p$.
So the answer is in effect it depends.


How to store subList operation on an ArrayList in another ArrayList in Kotlin?

Question: I am using Kotlin REPL in IntelliJ Idea

I have an ArrayList.
val myArrayList: ArrayList<String?> = arrayListOf("pig", null, "cow", "chicken", "chicken", "duck", "turkey", "pig", null, null, "turkey", "pig")

the operation
myArrayList.subList(2, 3)

gives me the output:
res5: kotlin.collections.MutableList<kotlin.String?> = [cow]

But the operation
val myArraySubList: ArrayList<String?> = myArrayList.subList(2, 3)

gives me the error:
error: type mismatch: inferred type is MutableList<String?> but kotlin.collections.ArrayList<String?> /* = java.util.ArrayList<String?> */ was expected
val myArraySubList: ArrayList<String?> = myArrayList.subList(2, 3)
                                         ^

So, here how can I store the result of a subList operation on an ArrayList in another ArrayList?
Answer: ArrayList(myArrayList.subList(2, 3))

using this constructor:

<init>(elements: Collection<E>)

Creates an ArrayList filled from the elements collection.

But consider whether you actually need it: using ArrayList explicitly instead of MutableList is very rarely useful.
Comment: I am extremely sorry for my typing mistake, I have edited my question
Comment: Ah, ok. Happily this doesn't affect the main part of the answer :) Also, the list is not nullable either (that would be `ArrayList?`), it's a list of nullable strings.
Comment: I mean able to store `null` as value in the `ArrayList`
Comment: Thank you for clearing my confusion, I have further modified the question to make it more meaningful :-)