How to check that any of the channel in spring-integration SI flow is in processing state?

Question: Hi Artem / Gary/ Friends,
There is a requirement where I need to deploy my ear on application server on PROD. The solution flow starts with JMS Message Listener in SI flow and the whole framework is SI based, where we have used delayer aggregator JDBC outbound adapter.
Now before deployment I need to know that there is no live thread active in SI flow ( means processing has been completed by all the channel and there is no live message in between ) so that I can begin the deployment of EAR on my application server.
As I have used control bus to stop the message listener but I also need to know that the message processing has been completed to end and no live SI message exists in the flow.
Can you please help.
Thanks
Ram
Answer: Well, actually I'm not sure why you worry about that. Any re-deploy causes the application stop and resources disposal, therefore, no more any thread activity after that.
Although you can consider to use SmartLifecycleRoleController for the purpose like assign for all critical endpoints the same role and invoke its stopLifecyclesInRole() when you need.
From other side the endpoint stop means that it won't consume any new messages from the channel (or source system like JMS). Right any long-running Thread will be still active and may be even with some process around the message. AFAIK the container tries to finalize all the active threads for the application and eventually just interrupts if otherwise. For this case you definitely should ensure some transactional / anknowlage rejection semantics for critical data. Therefore any unfinished process will just end up with rallback/nack state for the message. And a new instance of your application will be able to start over for that message again.
I don't have any answer for you regarding some hook to check thread activity at run time. But I wonder if you will be able to figure out something like claim-check to wait until sending part is equal to processed after the JMS Inbound Endpoint stop.


mono gtk hello world failing, 'Missing method'

Question: I am trying out mono for the first time.  Here are the steps I took to set it up.
Installed Kubuntu 12.04 LTS in VirtualBox
apt-get install mono-complete gtk-sharp2

Then I tried running the hello world applications in this tutorial.
http://www.mono-project.com/Mono_Basics
The command line application ran fine.
I compiled the GTK application with the following command as per the instructions:
gmcs hello.cs -pkg:gtk-sharp-2.0

When I run the application it fails with the following errors:
Missing method System.Type::op_Inequality(Type,Type) in assembly /usr/lib/mono/2.0/mscorlib.dll, referenced in assembly /usr/lib/mono/gac/gtk-sharp/188.8.131.52__35e10195dab3c99f/gtk-sharp.dll

Unhandled Exception: System.MissingMethodException: Method not found: 'System.Type.op_Inequality'.
  at Gtk.Window..ctor (System.String title) [0x00000] in <filename unknown>:0
  at Hello.Main () [0x00000] in <filename unknown>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.MissingMethodException: Method not found: 'System.Type.op_Inequality'.
  at Gtk.Window..ctor (System.String title) [0x00000] in <filename unknown>:0
  at Hello.Main () [0x00000] in <filename unknown>:0

To me it looks like the mono libraries are incompatible with the gtk-sharp libraries.
Does anyone have any suggestions on how I can get this working?
Comment: This seems to a known [bug](https://bugs.launchpad.net/ubuntu/+source/mono/+bug/882501), as mentioned in the bug report you can try to run it as `mono --runtime=v4.0 hello.exe` or compile with `dmcs` as [suggested by marek.safar](http://stackoverflow.com/a/10474535/925381)
Answer: All 12.04 Ubuntu editions have Mono defaulting to 4.0 profile (similar to .NET 4.0). You are compiling your hello.cs using gmcs compiler which is intended to target 2.0 profile (similar to .NET 2.0).
Use dmcs compiler instead of gmcs and the error will go away.


Number of functions from $ \{1, 2, 3, 4, 5, 6\} \to \{1, 2, 3, 4, 5, 6\} $ s. t. $|f^{-1}[\{a\}] |= 1$, $|f^{-1}[\{b\}] |= 2$, $|f^{-1}[\{c\}] |= 3$

Question: Let $ A = \{1, 2, 3, 4, 5, 6\}. \,$ I need to find the number of functions $ \, f : A \to B \, $ such that there are $ \,  a, b, c \in A \, $ for which $ \, \left|f^{-1}[\{a\}]\right| = 1, \left|f^{-1}[\{b\}]\right| = 2 \, $ and $ \, \left|f^{-1}[\{c\}]\right| = 3$.
Did I do it correctly?
First choose $ 3 $ random elements from $ A $, there are $ {6 \choose 3} $ ways to do so. Arrange the elements in an ordered list: $ a, b, c $ - There are $ 3! $ ways to do that.
For each element, choose its $ f^{-1} $.
$ a: {6 \choose 1} = 6$
$ b: \frac{{5 \choose 2}}{2!} = 5$
$ c: $ automatically chosen.
Therefore, according to the rule of product, there are $ {6 \choose 3}\cdot3!\cdot6\cdot5 $ such functions.
Comment: What are all those absolute value signs in your question? It seems like you don't need them.
Comment: @SuzuHirose it denotes the cardinality of the set
Comment: Thank you for clarifying.
Comment: I think that this should say $f:A\rightarrow A$ not $B$, there is no definition of $B$.
Comment: Also if $a$ is a subset of $A$ then it should say $a\subset A$.
Comment: @Prem but aren't we supposed to decide which one is $ a $, which one is $ b $, and which one is $ c $?
Comment: @Prem what are these ordered pairs?
Comment: Choosing "b" , it is not necessary to "Divide by 2!" , In other words , it is not 5, but 5x2. It then "matches" the Answer given by @Arnau Mas !
Answer: Let $a$, $b$ and $c$ be fixed elements of $A$ and consider a function $f$ that satisfies the desired property.
First note that, by the pigeonhole principle, every element in $A$ can only be mapped to either $a$, $b$ or $c$. In other words, $f^{-1}(\{a\}) \cup f^{-1}(\{b\}) \cup f^{-1}(\{c\}) = A$ and the union is disjoint. So it is now a matter of counting partitions of this form.
The preimage of $a$ must have one element, so there are 6 possible choices. The preimage of $b$ must have two elements, and it is also disjoint from the preimage of $a$, hence we must make two choices out of the 5 remaining elements in $A$, i.e. ${5 \choose 2}$. Finally the preimage of $c$ must contain three elements and also be disjoint from the preimages of both $a$ and $b$, hence there is no choice to be made since there are only three elements left.
So, for any choice of $a$, $b$, $c$ there are $6 \cdot {5 \choose 2}$ functions from $A$ to itself that satisfy the required property. There are $3!{6 \choose 3} = \frac{6!}{3!}$ possible picks of $a$, $b$ and $c$, since order does matter here. Hence a total of $3! \cdot {6 \choose 3} \cdot 6 \cdot {5 \choose 2}$ functions that satisfy the desired property.
Comment: The binomial coefficient ${5 \choose 2}$ counts number of unordered pairs, so I believe the overcounting is already accounted for. If anything OP undercounts by dividing by $2!$
Comment: @Prem This answer is now correct.  The OP's answer is incorrect since there are $\binom{5}{2}$ ways to select the preimage of $b$, not $5$.
Comment: You chose which elements are in the image set.  However, you have not chosen which of those three elements is the image of one element, which is the image of two elements, and which is the image of three elements.
Comment: That's the last step, which gives the factor of ${6 \choose 3}$.
Comment: That is incorrect.  There are $\binom{6}{3}$ ways to select which three elements are in the image.  You have not accounted for which one is which.
Comment: Yeah you're right, order does matrer in the choice of $a,b$ amd $c$.
Comment: Oh yes , your contribution to this calculation has made it Correct , @N.F.Taussig


Runtimeexception on admin console of GlassFish

Question: I downloaded the latest version (4.1.1) of GlassFish, unzipped to a local folder, started the domain with command asadmin start-domain from the bin directory.
I Opened the admin console of the server on web browser and clicked the new button on resources-> jms resources -> connection factories which resulted in a runtimeexception.
I then clicked the new button on resources->JDBC Resources which also resulted in a runtimexception. In short, clicking on any 'new' button results in a runtimexception.
I didn't find any answer to this problem online. If anybody know the reason, please let me know.
Here is the log:
2015-12-10T23:03:25.558-0500] [glassfish 4.1] [INFO] [] [org.glassfish.admingui] [tid: _ThreadID=51 _ThreadName=admin-listener(1)] [timeMillis: 1449806605558] [levelValue: 800] [[
  Redirecting to /index.jsf]]

[2015-12-10T23:03:26.392-0500] [glassfish 4.1] [INFO] [] [org.glassfish.admingui] [tid: _ThreadID=53 _ThreadName=admin-listener(3)] [timeMillis: 1449806606392] [levelValue: 800] [[
  Admin Console: Initializing Session Attributes...]]

[2015-12-10T23:03:36.527-0500] [glassfish 4.1] [INFO] [] [javax.enterprise.resource.webcontainer.jsf.context] [tid: _ThreadID=53 _ThreadName=admin-listener(3)] [timeMillis: 1449806616527] [levelValue: 800] [[
  Exception when handling error trying to reset the response.
java.io.IOException: Connection is closed
    at org.glassfish.grizzly.nio.NIOConnection.assertOpen(NIOConnection.java:432)
    at org.glassfish.grizzly.http.io.OutputBuffer.write(OutputBuffer.java:653)
    at org.apache.catalina.connector.OutputBuffer.writeBytes(OutputBuffer.java:355)
    at org.apache.catalina.connector.OutputBuffer.write(OutputBuffer.java:342)
    at org.apache.catalina.connector.CoyoteOutputStream.write(CoyoteOutputStream.java:161)
    at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
    at sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:282)
    at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:125)
    at java.io.OutputStreamWriter.write(OutputStreamWriter.java:207)
    at com.sun.faces.renderkit.html_basic.HtmlResponseWriter.flushAttributes(HtmlResponseWriter.java:1211)
    at com.sun.faces.renderkit.html_basic.HtmlResponseWriter.endElement(HtmlResponseWriter.java:582)

Comment: Does this happen every time? Even after you restart the domain or even after you download a new version?
Comment: Yes Everytime. I repeatedly downloaded v4.1.1 from https://glassfish.java.net/download.html. and followed the steps mentioned on that page from step 0 till step 4 and clicked on 'new' button on jms connection factories, jdbc resources etc. Everytime, I got the above runtimeexception as pasted. You can try the same as described on the page https://glassfish.java.net/download.html
Answer: Glassfish allowes creation of Resources only through asadmin console for v4.1.1
   Eg :
     asadmin> create-jms-resource --restype javax.jms.ConnectionFactory
     --description "connection factory for durable subscriptions" --property
     ClientId=MyID jms/DurableConnectionFactory

     asadmin> create-jms-resource --restype javax.jms.Queue --property
              Name=MyQueue jms/MyQueue

Though updating and deleting is allowed through admin web console, creation is disabled. Alternatively, these resources can also be created by adding them manually in domain.xml file under glassfish/domain-name/config
<resources><connector-connection-pool max-pool-size="250" resource-adapter-name="jmsra" steady-pool-size="1" name="jms/MyConnectionFactory-Connection-Pool" description="MyConnectionFactory" connection-definition-name="javax.jms.ConnectionFactory" transaction-support=""></connector-connection-pool>
<connector-resource pool-name="jms/MyConnectionFactory-Connection-Pool" jndi-name="jms/MyConnectionFactory"></connector-resource>
<admin-object-resource res-adapter="jmsra" description="myQueue" res-type="javax.jms.Queue" jndi-name="jms/myQueue">
  <property name="Name" value="myQueue"></property>
</admin-object-resource>  </resources>

Comment: GlassFish should still work on JDK 7 with no issue, the recommendation of JDK 8 is due to the fact that Java 7 reached "end of life" in April this year, so is no longer supported by Oracle. Having mentioned this to the Payara guys, this looks like a bug in GF 4.1.1 which is fixed in the latest Payara. I can't find any Github issue to back that up at the moment, though.
Comment: Could you please let me know whether you are getting the same issue or am I the only one with this issue?
Comment: Faced same problem on Mac OS El Capitan with NetBean. Glassfish version 4.1.1.
Had to go with terminal to /Applications/NetBeans/glassfish-4.1.1/bin
and execute ./asadmin


JQuery empty input not working with .val('');

Question: I have a function that works in my JQuery autocomplete.
The function itself seems to work, but when selecting from autocomplete list, the line to empty the input is not working.
I re-created the issue here:
http://jsfiddle.net/bv8nr2gp/1/
Everything works, except the line $('#' + x).val('');
UPDATE
I've updated the fiddle to include the missing elements.
If you enter a value in the input field and click Add it works. The value is added to the textarea and span and then removed from the input.
If you enter "one" or "two" in the input and choose it from the autocomplete list, it works apart from clearing the input
Comment: The elements with partial id like `_display` and `_add` seems to be missing in your jsfiddle. Please include those and explain in detail how we can test that it's not working
Comment: See update, just added it to the fiddle and added a further explanation
Comment: Please include the code in a snippet in the question, not relying on third-party sites.
Comment: Your issue is that you're clearing the input before the autocomplete has completed.  So it goes: auto-complete:select event, your add function:clear input, auto-complete:set input to selected value.   You can confirm this by adding a setTimeout around the .val('') http://jsfiddle.net/dgxk23b6/
Answer: The issue is that you're clearing the input before the autocomplete has completed.
From jquery-ui (with emphasis):

select( event, ui )
Triggered when an item is selected from the menu. The default action is to replace the text field's value with the value of the selected item.
Cancelling this event prevents the value from being updated, but does not prevent the menu from closing.

The process is:

auto-complete select event
which calls your add function which clears the input
auto-complete then sets the input to the selected value as part of the autocomplete process

You can cancel the autocomplete select so that it doesn't update the input:
    select: function(event, ui) {
      addEmailContact(this.id, ui.item.value);
      event.preventDefault();
    }


Why does the assignment of values to keys in identical, but differently created nested dictionaries leads to different results?

Question: Code snippets are worth a thousand words, so here they are:
# Creation of data_dict1
data_types = ('abnormal', 'normal')
data_dict1 = dict.fromkeys(data_types, {0: {}, 1: {}})
# Creation of data_dict2
data_dict2 = data_dict2 = {'abnormal': {0: {}, 1: {}}, 'normal': {0: {}, 1: {}}}

# Check
print(data_dict1)
print(data_dict2)
print(data_dict1 == data_dict2)

>>> {'abnormal': {0: {}, 1: {}}, 'normal': {0: {}, 1: {}}}
>>> {'abnormal': {0: {}, 1: {}}, 'normal': {0: {}, 1: {}}}
>>> True

As you can see, the nested dictionaries data_dict1 and data_dict2 are identical regardless of their methods of creation.
But when I assign values in the same way, I get different results:
data_dict1['abnormal'][0]['result'] = 'abnormal_0'
data_dict1['abnormal'][1]['result'] = 'abnormal_1'
data_dict1['normal'][0]['result'] = 'normal_0'
data_dict1['normal'][1]['result'] = 'normal_1'

data_dict2['abnormal'][0]['result'] = 'abnormal_0'
data_dict2['abnormal'][1]['result'] = 'abnormal_1'
data_dict2['normal'][0]['result'] = 'normal_0'
data_dict2['normal'][1]['result'] = 'normal_1'

# Check
print(data_dict1)
print(data_dict2)
print(data_dict1 == data_dict2)

>>> {'abnormal': {0: {'result': 'normal_0'}, 1: {'result': 'normal_1'}}, 'normal': {0: {'result': 'normal_0'}, 1: {'result': 'normal_1'}}}
>>> {'abnormal': {0: {'result': 'abnormal_0'}, 1: {'result': 'abnormal_1'}}, 'normal': {0: {'result': 'normal_0'}, 1: {'result': 'normal_1'}}}
>>> False

The values for data_dict1['abnormal'][0]['result'] and data_dict1['abnormal'][0]['result'] are 'normal_0' and 'normal_1', respectively, and not 'abnormal_0' and 'abnormal_1' as they should be. Why is this the case?
Answer: This is coming about due to the way you initiate data_dict1.
data_dict1 = dict.fromkeys(data_types, {0: {}, 1: {}})

When you do this, both of the keys in data_dict1 are set to the same nested dictionary. This means that after these lines:
data_dict1['abnormal'][0]['result'] = 'abnormal_0'
data_dict1['abnormal'][1]['result'] = 'abnormal_1'

The value of both keys in the dictionary, abnormal and normal is changed. If we check data_dict1 at this point, we see:
>>> data_dict1
{'abnormal': {0: {'result': 'abnormal_0'}, 1: {'result': 'abnormal_1'}},
 'normal': {0: {'result': 'abnormal_0'}, 1: {'result': 'abnormal_1'}}}

When we continue to then change the value of the normal key, the same thing happens, giving us the result you have found.
We can check that both nested dictionaries are actually the same dictionary in memory by using is:
>>> data_dict1['abnormal'] is data_dict1['normal']
True

You have initiated data_dict2 by actually assigning different nested dictionaries to the keys, and we can see that this is true in the same way as above:
>>> data_dict2['abnormal'] is data_dict2['normal']
False

We can avoid this behaviour, without having to type it out like you did in data_dict2. One way to do this would be to use a dictionary comprehension:
>>> data_types = ('abnormal', 'normal')
>>> data_dict1 = {k: {0: {}, 1: {}} for k in data_types}
>>> data_dict1['abnormal'] is data_dict1['normal']
False

Comment: Thanks, that was very clear. So what is the point of using the function fromkeys() to create a nested dictionary like I did for data_dict1? Is there a way to efficiently initialize nested dictionaries without having to do it like I did for data_dict2?


How to use Webform values in Rules?

Question: I am using the Webform Rules module and I created an event 'After submitting webform', and an action 'Fetch webform submissions'.
When I add an action 'Show a message on the site', I get all the webform data values and I can print them out in status message.
Now I want to Get the user ID who submitted the webform to send that user a private message (about the form data). But when I add an action 'Fetch entity by ID', I get no webform data values there (I'd like to use a data value as entity ID).
Am I missing something, is this the right way to achieve this ? Any other idea on how to do this please?
Answer: Using the Webform Rules module is indeed part of the puzzle to answer your question, as you can read also on its project page:

This module adds rules integration on webforms.
Did you ever want to react on webform submission using rules but couldn't find the proper event?
Webform Rules makes it possible to catch webform submissions by rules and do whatever you'd like to do with it (meaning: do whatever rules let you do with it).

1. Get the user ID who submitted the webform
Have a look at this example rule (in Rules export format):
{ "rules_process_submitted_webform" : {
    "LABEL" : "Process submitted webform",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "DO" : [
      { "mail" : {
          "to" : "[site:mail]",
          "subject" : "A new webform submission has occured",
          "message" : "A new webform submission has occured (with form-id \u0022[form-id:value]\u0022). It was submitted by the user with id = [user:id], name = [user:name] and eMail Id = [user:mail] ...",
          "language" : [ "" ]
        }
      }
    ]
  }
}

I intentionally did not include any Rules Conditions here, just to illustrate that by using the Rules Event you're already using, you do have access to a limited set of tokens related to the user who submitted the webform, such as [user:id], [user:name] and [user:mail]. In other words, you don't need a Rules Action like "fetch entity by ID" for these kinds of tokens to be available.
Of course, because of the nature of your question, you may want to add a Rules Condition to check that the user is not an anonymous user.
2. About the Webform data
The "Webform data"-part of your question seems like an example (variation?) of what's asked for in the feature request "Expose submission data to rules". Here is a summary of it:

Right now, submission data is not exposed to rules except by way of token replacement or custom php actions. This patch exposes submission data in a "first-class" way.

Issue status is "Needs work" ... not an "easy" issue though.
The very same issue contains a comment with a workaround (it's genious I think, because it's so simple), here is a relevant quote from it:

You can initialize a rules string variable with the tokens. If you need integers or booleans you can subsequently convert it to whatever and then use it to load nodes or whatever.

A picture is worth more then 1000 words: checkout the screenprint included in that comment.
So you could use a technique similar to what is described in my answer to "How to do a data comparison to submitted webform data when using the Rules module?". For short:

Add an extra Rules Action to Add a variable, with a value assigned to it equal to your Webform data you want to use (and with an appropriate data type). You'd need 1 such variable for each Webform component for which you want to access its Webform data.
In your subsequent Rules Actions you can refer to the value of these variables you just added (that's the clue!).

PS: I'm assuming this question is about D7.

How to use Webform values in Rules?


Como virar uma imagem com CSS?

Question: Estou com um problema com CSS. Tentei girar uma imagem com CSS para que ela ficasse de lado, funcionou no Firefox porém no Safari não.
Segue o codigo usado para girar a imagem:
.body-element-p1{
    top: 11%;
    left: 41%;
    position: absolute;
    z-index: 10;
    transform: rotate(180deg);
}

Se tiverem alguma dica estou aceitando.
Answer: TL;DR
Adicione o prefixo -webkit-.
.body-element-p1{
    top: 11%;
    left: 41%;
    position: absolute;
    z-index: 10;

    -webkit-transform: rotate(180deg);
    -moz-transform: rotate(180deg);
    -o-transform: rotate(180deg);
    -ms-transform: rotate(180deg);

    transform: rotate(180deg);
}

Complemento
Esses prefixos foram adicionados às propriedades para que os desenvolvedores pudessem experimenta-las, já que — em teoria — não deveria haver mudança visual.
Os desenvolvedores devem esperar para incluir a propriedade não pré-fixada até que o comportamento do navegador seja padronizado.¹
Segundo o site da Mozilla:

Os fabricantes de browsers estão trabalhando para parar de usar prefixos de fornecedores para recursos experimentais. Os desenvolvedores da Web têm vindo a usá-los em sites de produção, apesar de sua natureza experimental. Isso tornou mais difícil para os fornecedores de navegadores garantir a compatibilidade e trabalhar com novos recursos; também foi prejudicial aos navegadores menores que acabam forçados a adicionar prefixos de outros navegadores para carregar sites populares.

Qual ordem usar?
Na pergunta Ordenar estilos com prefixos no CSS (informada pelo @dvd), não há explicações do por quê você deve usar uma determinada ordem, mas isso acontece pois os navegadores leem essas propriedades na ordem que você colocar. Porém isso é relativo (como mostrado abaixo).
Acontece pois os navegadores utilizam esses prefixos para (como foi dito anteriormente) coisas experimentais e por isso eles processam essas informações de modo diferente. Portanto, você deve verificar qual a melhor forma de utilizar. Exemplos:
Modo Correto:
#rightway { background: #ccc; padding: 30px;
  /* Navegador vai tentar aplica-lo */
  -webkit-border-radius: 30px 10px;

  /* Porém não vai conseguir, pois essa propriedade irá substituir a anterior. */
  border-radius: 30px 10px;
}

Modo Correto ²:
#wrongway { background: #ccc; padding: 30px;
  border-radius: 30px 10px;
  -webkit-border-radius: 30px 10px 30px 10px;
}

Nos modos corretos o navegador irá interpretar a última propriedade da seguinte maneira:
border-top-left-radius: 30px;
border-top-right-radius: 10px;
border-bottom-right-radius: 30px;
border-bottom-left-radius: 10px;

Modo Incorreto:
#wrongway { background: #ccc; padding: 30px;
  border-radius: 30px 10px;
  -webkit-border-radius: 30px 10px;
}

Nesse modo, o navegador irá substituir a propriedade "real" border-radius, pela propriedade prefixada, porém, a interpretação do navegador será uma borda elíptica. Ex:
border-top-left-radius: 30px 10px;
border-top-right-radius: 30px 10px;
border-bottom-right-radius: 30px 10px;
border-bottom-left-radius: 30px 10px;

Comment: Prefixos devem vir antes. Veja mais aqui nesta pergunta: https://pt.stackoverflow.com/q/245870/8063
Comment: @dvd Isso é relativo e pode depender da propriedade e dos valores dela. https://codepen.io/valdeir2000/pen/bLRLdP
Comment: Sim, a regra se aplica quando há 2 valores. Mas para não correr riscos, é sempre melhor colocar os prefixados acima e o não-prefixado por último.

Como virar uma imagem com CSS?


How to establish bijective between the set of rooted trees and natural numbers, using Godel numbering?

Question: Consider the structure of a rooted tree independent of its underlying set, (i.e. in the sense of trees as combinatorial species). I know a number of ways which we can encode any such tree in natural numbers, but all of them fail to be a bijective, i.e. Some numbers can not be decoded into any sensible tree structure. I would be very pleased to see such concrete correspondence. Thank you.
Comment: If you can encode each structure as a natural number, and there are infinitely many different structures you can collapse the range of the encoding to have a bijection with $\mathbb N$.
Answer: See Y. Abe, Tree representation of positive integers, Applied Mathematics Letters
Volume 7, Issue 1, January 1994, Page 57:

Abstract. We define a natural one-to-one correspondence between the set of positive integers and the set of equivalence classes of isomorphic rooted trees. By this correspondence, one can translate number-theoric concepts or quantities of a positive integer into graph-theoretic ones of a rooted tree. For example, a positive integer is prime if and only if the corresponding rooted tree is planted, that is, the valency of the root is equal to $1$.
Comment: Note that this result was first discovered by Matula (1968): "A natural rooted tree enumeration by prime factorization".
Answer: See also A new bijection between natural numbers and rooted trees (Cappello).
Comment: Repeating my comment above: this result was first discovered by Matula (1968): "A natural rooted tree enumeration by prime factorization", predating Cappello by 20 years.


Can I use Public-Key-Pins with LetsEncrypt?

Question: Can I setup Public-Key-Pins when I setup a cronjob to renew the LetsEncrypt certificate every 30 days?
If the certificate is renewed then the Public-Key-Pin is also renewed right?
Answer: Some words of caution to begin with:

Know what you're doing, if you're planing to implement HPKP.
If you don't do it right, or "if bad things happen", which aren't under your control, you might render your domain unusable.
Be sure to test your setup with a domain which isn't that important, or with a very short cache time, like ten seconds for example.
Think about which certs you would like to pin: Root, intermediate, leaf...
Think about if it makes sense to pin another (backup) certificate authority, it's intermediate certificates and your leaf certificate.
Better safe than sorry: Think about if it makes sense to pin another backup CA / cert, to have two.
If these points and questions sound "new" to you: Read what HPKP is about and the common traps and caveats, before you implement this.

Can I use Public-Key-Pins with LetsEncrypt?

Yes.

If the certificate is renewed then the Public-Key-Pin is also renewed right?

This depends on which certificate you're referring to and which cert(s) you're pinning.
Answer: Would echo everything that gf_ said.
However, to answer the question, yes you can.
By default Let's Encrypt recreates the key and the cert at renewal. This makes implementing HPKP difficult if you want to pin at the leaf, which you probably should do in case intermediate changes (like it did in March 2016).
So you've several options around this if you still want to do HPKP:

Use your own fixed CSR rather than the standard client which creates the CSR for you each time so the leaf key doesn't change. This blog post explains how to do this specifically because the author uses HPKP.
Use short HPKP expiries and renew within that expiry time and change policy to have both old and new keys before actually changing the cert, with enough time for new policy to be picked up by any visitors.
Pin the Let's Encrypt root instead of the leaf or cert.
Comment: How is it "really easy" for an attacker to get a cert for your domain name using Let's Encrypt? Not aware of any way of doing that. However it *may* be possible with *any* CA if they have bugs in their domain validation procedures. By pinning LE root you've massively reduced your attack surface down to just Let's Encrypt as opposed to every CA in the world. Still not as safe as pinning leaf I agree but that introduces it's own risks so depends on your definition of "safe".
Comment: Good additions, +1.
Comment: Is it safe to pin the root? For a MITM it's really easy to use his own Let's Encrypt certificate.
Comment: I would say that neither of these options is optimal, but option 1 is the "least worst".
Comment: Saying that I do think there are MASSIVE risks to HPKP - mostly from a self suicide perspective - so am not a fan. If you decide to change CA, or cert path changes (e.g. due to SHA-256 depreciation), or urgently have to reissue cert, or backup key gets compromised/lost or the person who set it up leaves and next person doesn't realise they use HPKP and/or doesn't know about it. HPKP also doesn't protect against local roots such as Superfish. So, for **most** sites, HPKP, is too complex and, IMHO, not worth the added protection for the little added security gain. But that's just my opinion.
Comment: Ok, I only asked because I thought, that all the LE certificates have the same root certificate. So if you pin the root somebody else with another LE certificate can just use an MITM and fake in it's own cert. Do you know what I mean?
Comment: Yes but you can only get a cert for a domain you can prove you own. That underpins the whole point of HTTPS. So if you have a LE cert for melbic.com then that's no use to use on a different site. Just because it's a LE cert doesn't mean you override the basic requirements of the cert matching the domain name. Saying that some CAs have had failures in the past hence why HPKP allows you to limit this. If all CAs were 100% secure then there would be no need for HPKP. Understand?
Answer: I just implemented this using the dehydrated client with dns01 validation. The dns01 hook is certzure because our DNS is hosted in Azure.
Edit: when I talk about private keys, obviously I always mean that you only turn the public key parts into pins. The private keys, as the name suggests, should always remain private. See my own hook for implementation details.

You need private key rollover to make this possible. That is, you always have the current private key (call it A) and the future private key (call it B) at hand, so that you can add them both to your pins. So at this point your pins are A and B. When the day of cert renewal comes, private key A becomes obsolete and B becomes live. At the same time you get a new future private key, call it C. You regenerate your pin list so now it contains B and C. So that's how you roll your private keys over. dehydrated supports this now.
Also, you need a hook that is called every time you renew your certs and thus roll over your private keys. I implemented this on my own.
Finally, if I get this right, you gotta make sure that:
<code>HPKP age x 2 < days between cert renewals
</code>
For example, if your HPKP age is 50 days and you renew certs every 30 days, a client who visited your site on day one will be stuck with private keys A and B, and you rolled over to B and C at day 31. Your server has B and C, the client has A and B, there's a match even on day 50 and the client opens the site correctly.
BUT let's see if HPKP age is 70 days. You renew certs every 30 days, and the client visited your site on day one, so again, it only has private keys A and B. You rolled over to B and C at day 31, and rolled over to C and D at day 61. Your server has C and D, the client has A and B, there's no match and the client is given the middle finger from day 61 until day 71, when its HPKP policy expires.

Another, probably safer, and certainly much simpler option is using the same private key every time and generating one or several backup private keys, then hardcoding these into your HPKP config and be done with it.

Yeah, it's tricky and there might be caveats I haven't thought of, but we'll see in the long run. Obviously I deployed it on an uncritical subdomain with short (15 days) HPKP age so that it doesn't cause huge troubles.

Edit: I've written a few scripts to help you setting up HPKP with Let's Encrypt and dehydrated using Nginx:
HPKPinx
Comment: I decided to have the best of both worlds. Automated private key rollover + a static private key. Might write a blogpost about it if anyone's interested.
Comment: Link added. Documentation is scarce yet, but the code is there so that you can try it and hack on it.
Comment: If you do this, please edit your post and insert the link - thanks!
Comment: Thanks, I'll try my best to finish that this or next week


theme style.css is not loading for custom theme

Question: I am trying to learn Drupal 8 theme development. I am trying to create basic theme
My Folder structure
|-themes
  |  |-custom
  |  |  |-contra
  |  |  |  |-css
  |  |  |  |  |-style.css
  |  |  |  |-contra.info.yml
  |  |  |  |-contra.libraries.yml

My contra.info.yml is as follows:
name: contra
description: 'Drupal 8 starter theme'
type: theme
core: 8.x
libraries:
   -'contra/global-styling'

My contra.libraries.yml is as follows:
global-styling:
version: 1.0
css:
    theme:
        css/style.css: {}

I have cleared the cache in Admin->Configuration->Development and also refreshed my browser but I dont see the style.css loaded in view source.
Comment: As shown, your .libraries.yml file has incorrect spacing. Does that reflect your file, or just the copy and paste?
Comment: yes that reflects my file. But I tried changing space. Where should I give space?
Comment: Looks like you may have 3 spaces when adding your library to your .info.yml file as well.
Answer: Try adjusting your spacing. 2 spaces are required.
.info.yml:
name: contra
description: 'Drupal 8 starter theme'
type: theme
core: 8.x
libraries:
  - contra/global-styling

.libraries.yml:
global-styling:
  version: 1.0
  css:
    theme:
      css/style.css: {}

Also, take a look at https://www.drupal.org/docs/8/theming/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme


jquery returns undefined for data()

Question: I tried so many things and still can't make it run
Delete button

    wanna delete?
    <form action="" method="post">
        <input type="button" value="cancel" class="delete_cc">
        <input type="submit" name="comment_delete" value="delete">
    </form>

http://jsfiddle.net/urK5L/10/
Comment: Your `.data` have `[]` while it should be `()`
Comment: A good question provides some context and explains what goes wrong, eg by providing some output of eg firebug. This makes the question more useful to a larger audience.
Answer: Its alert('' + $('.delete_co').data('comment-id'));
not alert('' + $('.delete_co').data['comment-id']);
The problem is the []
Comment: @MitkoGrjkAmaruShakur For future reference the jQuery documentation at http://api.jquery.com/ (and http://api.jquery.com/data/ for this particular method) is always useful if you aren't sure how to use a method.
Comment: wow :D I tried 300 ways to fix it and I couldn't notice this tiny problem :D Thanks, I can accept your answer after 9 minutes :3

jquery returns undefined for data()


How do I go about showing the cardinality of two sets are the same?

Question: How do I go about showing that the cardinality of the set of natural numbers and the cardinality of the cartesian product of integers is the same?:
$$|\Bbb N|=|\Bbb Z \times \Bbb Z|$$
Directly $|\Bbb N| = \aleph_0$ and I can separate the right side like this: $|\Bbb Z||\Bbb Z|$, and because the cardinality of the set of integers is $\aleph_0$, $\aleph_0$ times $\aleph$ is still $\aleph_0$ and thus they are equal. However, I need to show an example how a bijection can be used here? How do I construct a map to let me see a bijection is being used/provide that it is surjective/injective?
Comment: Don't get distracted by that. Your task is to find one. Never mind that there are many, we just need one. A common example, that has a nice intuitive picture attached to it, is Cantor's pairing, see [here](http://en.wikipedia.org/wiki/Pairing_function). One that is easier to verify uses that each positive integer is the product of an odd number and a power of two, $n=2^a(2b+1)$. This gives you a bijection $n\mapsto(a,b)$ between the positive integers and $\mathbb N\times \mathbb N$.
Comment: Do you know any bijections between $\mathbb Z$ and $\mathbb N$? How about between $\mathbb N$ and $\mathbb N\times\mathbb N$?
Comment: I can set up a table such as the top row resembles integers: 0,1,-1,2,-2,3,-3,4,-4... and the bottom row resembles natural numbers: 1,2,3,4,5,6,7,8... There is a bijection
Comment: I know that, but how do I do it?
Comment: I know that they both have bijections but I do not how to prove it/find it
Comment: The first one (a bijection between $\mathbb Z$ and $\mathbb N$) is really easy. Start with that, and show us what you get once you find it.
Comment: OK, so you have that bijection. Do you see how to finish the problem is you also had a bijection between $\mathbb N$ and $\mathbb N\times \mathbb N$?
Comment: So I will just basically have each element in N point to exactly one in NxN? But how will I do it for ZxZ because the sets can go to infinity both directions(negative and positive) while the natural numbers only go positive?
Comment: Why do you think I asked first for a bijection between $\mathbb N$ and $\mathbb Z$?
Comment: Ohhhh okay, I got it now! Thank you very much!!
Comment: Well, OK. Do you then have a bijection between $\mathbb N$ and $\mathbb N\times \mathbb N$? This is the tricky part.
Comment: But how would I set a table up for me to see it? I understand what to do now, I just don't know how to let my teacher know that I know what I am doing
Comment: There is no bijection is there between N and N x N?
Comment: There are many. Why would you suddenly think that there isn't one?
Comment: @AndresCaicedo: Could you sum up your advices in an answer?
Comment: @Berci Sure I could. But no, thanks.
Comment: But how do you know there are many bijections N and N×N?
Comment: Is this not a duplicate of http://math.stackexchange.com/questions/588190/cardinality-of-a-set-of-natural-lattice-points-versus-natural-numbers
Answer: Much like eating a steak, this problem is easier to swallow if you cut it into smaller pieces and chew on them. Specifically here you can do it in three steps:

There is a bijection $f$ between $\Bbb{N\times N}$ and $\Bbb N$.
There is a bijection $g$ between $\Bbb Z$ and $\Bbb N$.
Now define, $h(m,k)=f(g(m),g(k))$, and show it is a bijection.

If indeed you succeeded in the first two steps, then the third is easy.

$h$ is injective, since if $h(m,k)=h(m',k')$, then $f(g(m),g(k))=f(g(m'),g(k'))$. But $f$ is injective, so $g(m)=g(m')$ and $g(k)=g(k')$. But $g$ is also injective. So $m=m'$ and $k=k'$ as wanted.
$h$ is surjective, since if $n$ is any natural number, then since $f$ is surjective, there are some $s,t\in\Bbb N$ such that $f(s,t)=n$. But also $g$ is surjective, so there are some $m,k\in\Bbb Z$ such that $g(m)=s$ and $g(k)=t$. Therefore $h(m,k)=n$ as wanted.


Pros and cons of matched vs. traditional grip for lefties

Question: There's a wonderful thread What are the pros and cons of Traditional Grip vs. Matched Grip for snare and drumset?.  Are any of the points mentioned there different in the case of a leftie?
In particular, my twelve-year-old leftie learned matched, and has never tried traditional.  Oddly enough, his left stroke is not as strong as his right, and this causes some problems with some of his rudiments.  He tends to practice his rudiments starting with the right hand.  When I am able to convince him to start with the left, that seems to help somewhat.

Basically I'm looking for percussionists and drummers only to respond, and I'd like the responders to read the linked thread first.  Thanks.
Comment: Has he tried playing on a 'right-handed' kit? As long as he comes back in on beat at the end of a drum break, it shouldn't make a lot of difference. In fact, holding the sticks in either way won't influence what you describe. Sounds like eventually, he'll be able to lead with either hand - not a bad thing.
Comment: @CarlWitthoft - there was a (rich) guy who did have a left-handed piano made. I mentioned it a couple of years ago, but, sorry, can't remember in what specific connection. Interesting that while violins et al are all played right-handed, if you call it that (!) guitars are handed preferentially.
Comment: Pretty much all musicians have to learn to train both hands to do their "jobs."  While there have been a few lefties who stubbornly insist on playing guitars backwards,  you'll never see a bowed-instrument player to that route.  Similarly,  lefty vs. righty for a pianist has no meaning.
Comment: @Tim - His drumset is standard.  My comment about the rudiments was just in the context of practice pad (ersatz snare drum).
Answer: Many of the referenced thread's pros and cons of a trad grip for a right handed player still hold true for a left handed player, namely a trad grip for a leftie would still look subjectively cool, and would still make it easier to play softly, as much as that is ever true.  It will still be tricky to maintain balance, and will create similar obstacles in moving around a set.
The differences depend on whether he does the trad grip with his right or left hand, and I would suggest trying the trad grip with the left hand for a few reasons:

If he ever wants to march, he will match his bandmates (this may not just be a nice-to-have, it may be required)
I think it would be easier to do the more awkward underhanded grip with his dominant hand.  You may ask, if so why didn't traditional evolve this way?  I would argue that it's less awkward to drum with your left palm up than to march with a drum resting on your dominant leg.
Since he's playing a right-handed set he can look to plenty of successful examples who have done this before, and he'd still be conveniently set up to play the hi-hat with his dominant left with no crossover issues.  LH trad on a RH set could certainly also be made to work, but he would have to figure some things out on his own without as many examples.  This could be a good or bad thing depending on the style he's pursuing.
Comment: Your second point is exactly right - that's why traditional has the odd left hand. Having a drum hang over your right leg is really uncomfortable and makes your first step (leading with left foot) really off.
Answer: I teach ancient style snare on old rope drums, so we only do traditional. I can't comment on the pros and cons of each for lefties, but I have noticed that they pick up the traditional grip more easily than righties. Last night I had a first lesson with a pair of twins, one righty and one lefty. It was obvious the lefty "got" the grip much more quickly than his brother.
It seems that after that initial moment, the challenges are pretty similar - retrograde motion is just as difficult, bouncing seems to depend on the student more than the dominant hand, stick control just takes time.
I would suggest that unless you're playing on a sloped head, the difference in power between the hands probably won't be resolved by changing grip. The best thing is to play your most basic rudiments (start really basic - singles and long roll) with your eyes closed and really listen for evenness at every speed. Then record yourself playing them and listen. Do daily for a couple weeks and it will probably clear up.
/* What follows worked for me, and I'm pretty sure that it's not a good idea. The concept could probably be applied in a safer way. I have not used this method with any of my students, but I believe the concept is sound: balance the hands by building hand strength independently. Below the picture you can see exercises I use with my own students. */
I really struggled getting my left hand to perform well, my wrist was really stiff and tired easily. My instructor installed an old rusty socket on a stick for my left hand, along the lines of one of these. When I switched back to my regular sticks a few weeks later, my stamina (and flamacue) was immensely improved. I've never done this with any of my students, as I'm concerned about repetitive stress injuries (RSIs), but it certainly worked very well in my case. He later also made each of us a "stick" from 1/2 inch steel dowel (smooth, not rebar) for stamina building, 500 on a hand. I still use it periodically for a workout.
.
If you determine that the problem is either strength or stamina, here are some exercises I use:

Use different weight sticks (probably heavier) for a week. The change seems to reset the autopilot and help players focus on sound and feeling.
Play on a pillow. This builds wrist strength since there's no rebound. A bowl of water also works well but it potentially messy.
All on one hand, either bucks (soft LOUD soft LOUD) or just straight beats, at a steady tempo (140-180bpm) for either a time limit (3 minutes) or a number (600), depending on age.
Old style long roll (pre-1850s), where the second stroke on each hand (rebound) is accented.
Roll as fast as possible (cleanly) without bouncing.
In all cases, daily practice is necessary to be most effective.

Then, once the hands are stronger than they "need" to be for general playing, focus on listening to balance the hands. Eventually this will become second nature.

Use two different style sticks and make them sound as even as possible. Perfection won't be possible, but the exercise helps to focus on the problem.
Close eyes and play simple rudiments while focusing only on sound. The teacher can make a sound (click for example) when they can identify the hand that is playing without looking.
Record rudiments and listen to yourself.
Play on something that isn't a drum, like a countertop, and try to even the sticks.
All these should be done slower than normal and on a pad, not a drum.


Trying to understand a proof in an example

Question: I read a proof of Example 3.7 from this article.

Then, I do not understand the sentence that I highlighted.

Why $(a_l,b_l)\subset J\subset X_{i_0}$?

I do not think that it is because $J$ is an open interval so that $(a_l,b_l)\subset J$.
Is it because for some $l\in\mathbb{N}$, the open interval $(a_l,b_l)$ is an element from $\{(a_i,b_i):i\in\mathbb{N}\} $  the family of open subintervals of $I=[0,1]$?
Thanks for any explanation.
Comment: It is precisely because $J$ is a non-empty open set.
Comment: $\{(a_i,b_i)\}$ contains all open intervals with rational end points.
Comment: @geetha290krm then, why $(a_l,b_l)\subset J$?
Answer: The open interval $J\subset[0,1]$ is implicitely assumed to be non-empty, hence (by density of $\Bbb Q$ in $\Bbb R$) it contains some interval $(a,b)$ with $a,b$ rationals and $0\le a<b\le1,$ i.e. some $(a_i,b_i).$


detect duplicate character in string

Question: I am doing the exercises in the Cracking The Coding Interview book and I am trying to determine if there is a duplicate character in a string. I am using the ArrayList data structure. My method is of return type Boolean, which returns true if there is a duplicate and returns false if there is no duplicate character. I added a third return statement so the program would compile but it always returns false.
import java.util.*;

public class QuestionOneCrackingCode {

    public static void main(String[] args) {
        String s = "abcdefga";
        ArrayList<String> c = new ArrayList<String>();
        c.add(s);

        System.out.print(check(c));
    }

    public static boolean check(ArrayList<String> g) {
        for (int i = 0; i < g.size(); i++) {
            for (int j = i + 1; j < g.size(); j++) {
                if (g.get(i) == g.get(j)) {
                    return true;
                } else {
                    return false;
                }
            }
        }
        return false;
    }
}

Comment: Note that `if (...) { return true; } else { return false; }` can be simplified to `return ...;`.
Comment: I would recommend doing something even easier: look inside the `String`, use a `char` variable for the current char and do a search from the current position to the last or from the current position to the first. This saves time and it's easier to code.
Comment: @LuiggiMendoza I don't think that's the correct dupe - even if he switched to `.equals()` it wouldn't work - the real problem is rather that he's expecting `c.add(s)` to split the String into characters when it's actually just going to result in a single-item list of the original String, which won't even get compared to anything. And if he was actually comparing chars, `==` would be correct
Comment: @CupawnTae well yes, there are more problems with this implementation. I'll reopen the question. Please provide an answer making use of this now non-dup as well.
Comment: @CupawnTae OP's comparing `String`s, not `char`s, check the parameter: `ArrayList g` and its usage: `g.get(i)`.
Comment: @LuiggiMendoza I realize that, but fixing the algorithm (as opposed to replacing it with a better one) would result in comparing chars, so the parameter would presumably change too
Comment: @CupawnTae let's talk about your proposed solution, not over a possible solution on the fly trying to reuse this code.
Comment: Actually, I wasn't proposing a solution, just pointing out that it's not really a dupe of comparing strings, but for example `check(CharSequence g)` ...  `if(g.charAt(i) == g.charAt(j))` would preserve the spirit of the algorithm while fixing the specific issue
Comment: What about `"test".matches(".*(.).*\\1.*")`
Comment: @CupawnTae yes, it will. And that's why I'm asking (for a third time) if you please could post an answer :)
Comment: @LuiggiMendoza Well up until about 10 seconds ago I couldn't because it was closed!
Comment: Thank you for your help. I am using the String data structure and it is working. :)
Answer: In Java 8, you could do it like this:
public static boolean check(CharSequence checkString)
{
  return checkString.length() != checkString.chars().distinct().count();
}

I.e. if the number of distinct characters in the string is not the same as the total number of characters, you know there's a duplicate. It's not necessarily the most efficient way, but it's succinct.
Answer: You're not separating your string into characters, you're creating a single-element list containing your string. Without making big changes to your algorithm, you could do it like this:
public static void main(String[] args) {
    String s = "abcdefga";

    System.out.print(check(s));
}

public static boolean check(CharSequence g) {
    for (int i = 0; i < g.length(); i++) {
        for (int j = i + 1; j < g.length(); j++) {
            if (g.charAt(i) == g.charAt(j)) {
                return true;
            }
        }
    }
    return false;
}

Note that the first return false; was also incorrect because it would stop the algorithm from continuing past the first comparison.
As an aside, when you are comparing Strings, you should use .equals() instead of ==.
Answer: Your solution compares string references in a list. The list itself contains only one String.
Try the following:
// check one string for duplicate chars
public static boolean check(String checkString)
{
    // result flag
    boolean foundDuplicate = false;
    // get string length
    int stringLength = checkString.length();
    // create a set for all found characters (max size is number
    // of characters in the string to check
    Set<Character> characters = new HashSet<>(stringLength);
    // loop all characters in string
    for (int i = 0; i < stringLength; i++)
    {
        // construct a object (may be use internal JDK cache)
        Character c = Character.valueOf(checkString.charAt(i));
        // check if character is already found
        if (characters.contains(c))
        {
            // yes, set result to TRUE
            foundDuplicate = true;
            // break the loop
            break;
        }
        else
        {
            // not found, add char to set
            characters.add(c);
        }
    }
    return foundDuplicate;
}

This is limited by the string length and the heap size. But I assume that all UTF-8 characters may fit into heap.
@Maarten Bodewes You are right. The check can be simplified to:
        // add character to set and check result
        if (!characters.add(c))
        {
            // returned false: character already exists
            foundDuplicate = true;
            // break the loop
            break;
        }
        // no else necessary

Comment: You can simply use the return value of `add`.
Answer: Here are the results of my version of your code.
abcdefga true
abcdefgh false
abcdefdh true

I modified the check parameter to take a single String.  There's no need for a List of Strings.
In the check method, you can exit once one pair of characters match.  You have to test the entire string before you can say there are no matching characters.
The first for loop can stop at the second to last character.  The second for loop will get the last character.
Since I'm comparing char values, I use the ==.  If I were comparing String values, I would use the .equals method.

Here's the code.
package com.ggl.testing;

public class QuestionOneCrackingCode {

    public static void main(String[] args) {
        String s = "abcdefga";
        System.out.println(s + " " + check(s));
        s = "abcdefgh";
        System.out.println(s + " " + check(s));
        s = "abcdefdh";
        System.out.println(s + " " + check(s));
    }

    public static boolean check(String s) {
        for (int i = 0; i < (s.length() - 1); i++) {
            for (int j = i + 1; j < s.length(); j++) {
                if (s.charAt(i) == s.charAt(j)) {
                    return true;
                }
            }
        }
        return false;
    }
}

Comment: Thank you for your help. :)
Answer: My participation:
    public static void main(String[] args) {
        System.out.println(check("abcdefga"));                    // true
        System.out.println(check("noduplicate"));                 // false
        System.out.println(check("withduplicate"));               // true
        System.out.println(check("abcdefghijklmnopqrstuvwxyz"));  // false
        System.out.println(check("abcdefghijklmnopqrstuvwxyzz")); // true
    }

    /**@brief Check if a String contains duplicated characters.
     * Strong expectation for the string: The String must only contains
     * lowercase alpha characters (ie. in [a-z])
     * @returns true if a char is present more than once */
    public static boolean check(String str) {
        int presentChars = 0; // will store the table of already found characters
        int l = str.length();
        for (int i = 0; i < l; ++i) {
            char c = str.charAt(i);
            int offset = c - 'a';             // a=0, b=1, ... z=25
            int mask = 1 << offset;
            if ((presentChars& mask) != 0) {  // Oh! Char already tagged as found
                return true;                  // No need to process further, bye!
            }
            presentChars|= mask;              // Tag the current char as present
        }
        return false;                         // No duplicate
    }

}

My goal with this code is to minimize the complexity. This algorithm is in O(N) on the worst case. Also, the memory footprint of the function is very low: only one int is really necessary (presentChars) even if I use more in order to improve readability =)
Downside of this code: there is a big prerequisite on the inputed string. I've detailed this on the comments, but it works only with characters in the [a-z] range.
I hope it's helps!
Answer:
Use a String instead of ArrayList.
Do not return if the comparison fails, you need to keep searching and not return false, this is why it always returns false.
Even then this is not the most optimized solution, try thinking about bucket sort and how it fits this problem. This will make your solution run in O(N) instead of O(N^2).

public static boolean check(String g) {

    for (int i = 0; i < g.length(); i++) {
        for (int j = i + 1; j < g.length(); j++) {
            if (g.charAt(i) == (g.charAt(j))) {
                return true;
            }
        }
    }

    return false;
}

Answer: I used a table to count how many times a character is repeated, if a character appeared more of one time then return true, the code in the worst case is O(n)
public static void main(String[] args) {

    String test ="abdefghijklmnoPQRSTUVWXYZa";
    System.out.println(isThereAnyCharacterRepeated(test));
}

public static boolean isThereAnyCharacterRepeated(String str){

    int repeatedCharacters[] = new int[255];
    for(int i=0;i<str.length();i++){
        int index=(int)str.charAt(i);
        repeatedCharacters[index]++;
        if(repeatedCharacters[index]>1)return true;
    }
    return false;
}

detect duplicate character in string


Does memtest86+ test memory which is used to run itself?

Question: One of the common server failure scenarios is bad DRAM, sometimes even when ECC memory is used.
memtest86+ is one of the most useful tools to diagnose DRAM problems. As it loads itself at the start of the memory, I've been wondering if memtest86+ checks the part of the memory which memtest86+is loaded into.
Is the memory allocated to memtest86+so small that it doesn't matter, or is it possible that memtest86+ could miss a defect in the DRAM because it can't test the memory locations it's residing in?
Comment: While this question is relevant for a server, it's also relevant for an ordinary PC, so I've voted to move this question to [Super User](http://superuser.com/) where it can reach more people.
Answer: Obviously, memtest86+ cannot test the memory region which currently contains the memtest86+ executable code (but if there are memory errors in that region, it is very likely that the test itself will crash). However, memtest86+ is able to relocate its own code to a different address at runtime, and by using this trick it is able to test all memory which it is allowed to use by the firmware (BIOS) — just not all at once.
This code relocation is described in README.background inside the memtest86+ source code archive (the file is slightly out of date — e.g., it states that the addresses used for memtest86+ code are 0x2000 and 0x200000, but the low address as defined in the source is actually 0x10000, and the high address is either 0x2000000 or 0x300000 depending on the amount of memory in the machine).
But even with this relocation trick memtest86+ is not able to test all memory for the following reasons:

Usually the firmware (BIOS) reserves some RAM regions for its own use (e.g., ACPI tables). While these RAM regions can be accessed by CPU, writing anything into them can result in unpredictable behavior.
Some part of RAM is used for the System Management  Mode and is not even accessible from the CPU outside of the privileged SMM code.
The RAM address range between 640K and 1M is inaccessible due to quirks of the legacy PC memory layout (some of this RAM may be used as a shadow for BIOS ROM and for SMM, other parts may be completely inaccessible).
Comment: if you have several ram modules, perform a second test after having swapped them...
Comment: @JanDvorak: In theory, it's possible, of course. In practice, I'd say it's only slightly more likely than banging your head on the keyboard and randomly typing out a Shakespearean sonnet.
Comment: Interesting, I missed its relocation capability. Obviously SMM and the likes are out of range (apart specific BIOS support).
Comment: Those mapped regions generally exclude the DRAM as something else "off module" is being addressed ? ROM and peripheral devices say.
Comment: Is it possible to have memory fail in just the right way to have memtest incorrectly report success due to having its instructions rewritten? Or rather, how many faults does it take?
Answer: No, memtest can't test its own memory. However, it is so small (only some KB) that it hardly matters. EDIT: this statement is wrong since, as stated in the selected answer, memtest can dynamically relocate itself to test all user addressable memory.
--
In theory, modern processor can, at boot time, configure part of their cache as programmable memory, from within very small programs (as memtest) can be run without touching DRAM at all.
However, it is a model-specific feature (which require BIOS support) and I don't think memtest is using it.
Comment: Are you sure about this?  I thought it copied itself somewhere else while testing the memory it normally lives in.  That's why every test has a slow part (most of memory) and a really fast part (the tiny bit where its code/data is stored).
Comment: Besed on [memtest86 documentation](http://www.memtest86.com/technical.htm) it does **not** test the processor cache, at least in a direct manner. Moreover, modern processors have separate instructions and data cache (I$ and D$). Executable code is loaded into the instruction cache and it can't be directly modified / overwritten
Comment: memtest86+ definitely tests the CPUs data cache, but that doesn't matter for this question. Thank you again for your answer.
Comment: @DmitryGrigoryev: Ah okay.. so I've learnt something more :-) Cool thanks!
Comment: Thank you for your answer. `memtest` is testing the CPU cache as well. So if `memtest` would be loaded into this cache, then it this part of the cache couldn't be tested, which is more problematic, because it's much smaller than the memory?
Comment: @Robin any reference on "memtest86+ definitely tests the CPUs data cache"? [Wikipedia](https://en.wikipedia.org/wiki/Memtest86) doesn't seem to agree: "access patterns are designed to keep most cache organizations flushed so that memory accesses are actually seen to the RAM"
Comment: As mentioned in Sergey's answer, memtest86+ relocates itself, so it effectively does test its own memory.  I think this answer is misleading.
Comment: @DmitryGrigoryev: memtest86+ tests L1, L2 and L3 caches of a CPU, which is the data cache, right?
Comment: @NateEldredge true. I edited it to point to the correct answer.
Comment: @Robin by reference I mean a link to some kind of source which confirms what you say. So far, I've only seen Wikipedia which says it doesn't
Comment: @DmitryGrigoryev: http://storage5.static.itmages.com/i/16/0122/h_1453462950_5192344_b15635706a.png
Comment: @Robin I bet info on that screenshot comes from [`cpuid`](http://stackoverflow.com/questions/14283171/how-to-receive-l1-l2-l3-cache-size-using-cpuid-instruction-in-x86). Testing the cache would mean you write a pattern in each cache line and read it back.
Comment: @shodanshok, for what it's worth, [__memtest86__](http://www.memtest86.com/) and [__memtest86+__](http://www.memtest.org/) are different programs.


Contact form with Wordpress wp mail

Question: I want to build a simple contact form, without plugins, on Wordpress using the build in wp_mail function. Standard fields, email subject and message.
The following features are required:

Ajax Submit (nice to have) (I use the jQuery framework)
If Ajax submit, a non javascript
fallback.
I'll validate the form client side,
but would also like to know the best
way to do server side validation, and
pass the message back, within the context of Wordpress.

What is the best practice to achieve this? Any pointers or tutorials. I found this question of note.
If you thinking I'm just reinventing the wheel let me know. I normally use Contact Form 7 (plugin) but am bored of its heavy html markup and the way it loads JS on everypage.
Thanks!
Answer: Contact Form 7 is written very well, and ripping apart the guts of that code is a great place to start for pointers and ideas.
Most of the time you could just strip out the core functionality there, and just create a more lightweight front end to suit your needs.

Contact form with Wordpress wp mail


Format float number

Question: Hi I want to format float numbers such that it will be displayed as follows:
decimal.fraction
where  decimal = max 11 digits and
fraction = max 9 digits
and if no fraction part it should display not fraction and for more than 11 digits in decimal part representation will be in scientific form.
Can anyone help me ?
Answer: I don't think there's an internal format like this. You need to format it yourself (not tested):
<code>void fprintf_float(FILE* f, double value) {
   if (-1e11 < value && value < 1e11) {
     double d = fabs(value);
     const char* sign = d > 0 ? "" : "-";
     double ipart, fpart;
     char fpartstr[16];
     int pos;
     fpart = modf(d, &ipart);
     snprintf(fpartstr, 16, "%.9f", fpart);
     for (pos = 10 /*strlen(fpartstr)-1*/; pos > 0; -- pos)
       if (fpartstr[pos] != '0' && fpartstr[pos] != '.')
         break;
     fpartstr[pos+1] = '\0';
     fprintf(f, "%s%.11g%s", sign, ipart, fpartstr+1);
   } else {
     fprintf(f, "%.10e", value);
   }
}
</code>
Answer: The standard library cannot directly do that for you. I would suggest your own decimal formatter if you need that specialized formatting, but you can also do by measuring the value and then setting proper mode and precision for the standard library.
Answer: Like this?
<code>#include <stdio.h>
#include <string.h>
#include <math.h>

void printnum(double num_in)
{
    char buff[32];
    char buff2[32];

    if (num_in >= 10000000000.0)
    {
        sprintf (buff, "%e", num_in);
    }
    else
    {
        char *pt;
        unsigned long long tmp;
        tmp = floor (num_in);
        sprintf (buff, "%llu", tmp);
        num_in -= tmp;
        if(num_in < 1.0e-11)
        {
            printf("%s\n",buff);
            return;
        }
        sprintf (buff2, "%10.9lf", num_in);
        pt = memchr (buff2, '.', 32);
        strcat (buff, pt);
    }
        printf("%s\n",buff);
    }

    int main(void)
    {
        double t = 100.0;
        int i;
        for(i=0;i<11;i++)
        {
        printf("%lf\t",t);
        printnum(t);
        t *= 12.3456;
    }
    return 0;
}
</code>
Answer: I think streams can do the job.
<code>#include <locale>
#include <sstream>

std::wostringstream out;
out.imbue(std::locale::classic()); // Make sure a '.' is used as decimal point
out.precision(9); // set fraction to 9 digits

out << 1.2;

const std::wstring str = out.str();
</code>

Format float number


Performance Difference SAS vs. SATA?

Question: Can not find that anywhere it seems.
What is the expected performance difference in a storage backend scenario that is heavily parallellized in access (like a SAN, Virtualization host storage etc.) between SAS and SATA, all other things being equal?
I Think it runs down to the impact of NCQ (32 command limit) to the MUCH higher oustanding command limit of SAS discs.
We are considering replacing some discs and have a chance to go for SAS or SATA - all the rest is in place - and I look for an evaluation from a performance point. Please ignore all the other issues (reliability etc.) - I purely wonder about the impact SAS will have on similar specced discs (RPM etc. being equal). The discs we have in mind can be ordered with both connectors and - there is an idea here to use SATA for ap ossibly repurpose later. THe price difference is not really high, but it made me wonder about the performance impact...
Comment: It's not like you to ask "All things being equal" because the differences in SAS and SATA are enough that things... are not equal.
Comment: Are you considering nearline SAS at 7.2k RPM, or real SATA?
Comment: @MarkHenderson Reality is - all other things can be equal. Seagate offers some discs with either SAS or SATA connectivity, so all other parameters (cache memory, rotational speed, speed of moving the moving parts) are equal, it all runs down to the SAS / SATA Protocol issues.
Comment: @Andrew Yeah, like I am the only one who ever did that. I remember (faintly) once being told to expect about 50% more IOPS based on serious queue lengths being possible in SAS (but not SATA) under heavy parallel load (so a long gueue length does actually happen). Just missing any sort of reference.
Comment: @Basil As I said - ALL other things being equal. I really care only about "what impact does SAS vs. SATA have at the performance of a disc under heavy parallel IO (random)". I don't find any benchmark done by anyone for that. The serious difference in handling queueing SHOULD give SAS a significant advantage (the NCQ limit in SATA is very low).
Comment: I think you'd have to benchmark the specific disks under your specific workload to be absolutely sure - maybe you can get a few disks of each, benchmark & post it back here?
Comment: I am considering Seagate Constellation 2. They are available with SAS and SATA interface - otherwise totally identical. I did not want to get exacty here (because I wanted this to be generic) but this is what we talk about - so the deives are totally identical except in this case.
Comment: Oh, by "all other things equal", you are including spindle speed! That totally changes my answer...
Answer: Yes, the extensive command set of the SCSI is a big bonus of using it over SATA. from SAS' Wiki:

SATA uses a command set that is based on the parallel ATA command set and then extended beyond that set to include features like native command queuing, hot-plugging, and TRIM. SAS uses the SCSI command set, which includes a wider range of features like error recovery, reservations and block reclamation. Basic ATA has commands only for direct-access storage. However SCSI commands may be tunneled through ATAPI[2] for devices such as CD/DVD drives.

The error recovery commands and block reclamation commands are pivotal in data integrity, S.M.A.R.T. is really for consumer grade equipment.
Also, SAS uses a higher signaling voltage, which enables longer cables compared to that of SATA. That's important when trying to cable up additional storage to an existing SAN.
You menitoned NCQ, but SCSI uses TCQ instead, which can be used in three different modes, however the bigger bonus imo with regard to parallelized setups is the ability to send up to 2^64 commands before filling the queue. Protocols like iSCSI and Fibre Channel limit this right now but the ability is there for future use.
I can only answer that portion, because I don't know if going with SAS for a couple of new disk will give you the same benefit of a purely SAS setup.
Comment: Some of the error recovery features are spilling over into ATA, with some drives now supporting TLER (though I don't believe there is any standardized command in ATA to configure the error timeout, as there is in SCSI).
Answer: This is a late answer, but I would like to add my opinion.
From a pure speed standpoint, a nearline drive (as the ones OP considered) will performs practically the same both using the SATA interface or SAS interface. Despite the much lower-depth NCQ (31 entries rather than TCQ 64K), this limited hardware queue is sufficient, when augmented with the much deeper software-based IO queue, to extract almost the same IOPS which can be obtained using SAS-based TCQ.
Anyway, this does not means that SAS has no practical advantages:

much better support for expanders
support for double-link interface
full-duplex operation
much faster maximum signaling rate (12 Gb/s vs 6 Gb/s)

However, when considering performance alone, the sad reality is that mechanical disk's random IOPS values are so low that the interface has almost no impact, excluding huge disk arrays where is can sometime limit your sequential IO transfer rate. Due to how it take rotational delay (which is hidden from the OS) into account, the killer performance-enhancing feature is NCQ/TCQ, and the SATA implementation is sufficiently good at that.
Some more significant differences appear when considering higher end SAS disks, which not only offer higher-RPM disks (10K and 15K), but have some interesting write-coalescing technologies (ie: HGST media cache tech) which, by the way, are slowly spilling into enterprise-SATA drives also.
1 https://ata.wiki.kernel.org/index.php/Libata_FAQ:

However, the ATA standard has a design flaw. The NCQ tag is presumed
to be a 32-bit bitmap (32-bit dword). If all 32 tags are asserted,
this produces a value (0xffffffff) that is the same value returned by
reading a hardware register after the hardware has been hot-unplugged,
or suffers a major failure. Thus, to distinguish this condition,
libata artificially limits all NCQ configurations to 31 tags rather
than 32.
Comment: Good answer. We have since moved to SATA SSD (in a SAS backplane) - which actually ARE bandwidth limited ;) But thanks, I expected that much as you said.
Comment: Yeah, SSDs are different beasts ;)
Comment: This is the answer I came here for; more about the practical implications of the protocol rather than design choices that accompany devices with the protocol. In addition, it should be noted that SMART attributes are not the same as they are on SATA disks. The familiar table in `smartctl` looks quite different for SAS drives and it's not even clear to me if they actually log the information SATA drives do.
Answer: Old post, but I wanted to update it since I never see mention of the most important difference in terms of performance which is that SATA is only half duplex. Expect a huge performance difference under heavy loads with a mix of read/write. Definitely not suitable for SAN or virtualization IMO.
Of course as stated above there are other benefits with SAS. Nowadays NL-SAS disks can be had for not much more than SATA.

Performance Difference SAS vs. SATA?


Changing color of React textarea resize corner

Question: Is it possible to adjust the color of the little diagonal lines at the bottom right corner of React textarea? I have switched the border color, but the small diagonal lines are still gray (both in Chrome and Firefox). I have tried every color property that VSCode would suggest, nothing has worked.
Component:
 <textarea id = "comment-box" className="form-control" rows= "3" value={newCommentBody} onChange={(event) => setNewCommentBody(event.target.value)}></textarea>

CSS:
#comment-box {
  border-color: darkred;
  box-shadow: 0 0 0 0.25rem rgba(139, 0, 0, 0.2);
}

Rendered:
Answer: WebKit provides the pseudo-element ::-webkit-resizer for the resize control it automatically adds to the bottom right of textarea elements. The ::-webkit-resizer pseudo-element allow some basic styling.

textarea::-webkit-resizer {
  border-width: 8px;
  border-style: solid;
  border-color: transparent orangered orangered transparent;
}
<textarea>text</textarea>
Answer: i have try to research on that , and this is what i get :
The little diagonal lines at the bottom right corner of a textarea are typically part of the browser's default styling and are not directly customizable using CSS. However, you can try a workaround by using a custom CSS trick called "appearance" to hide or modify the appearance of the textarea's resize handle. Here's an example:
#comment-box {
  border-color: darkred;
  box-shadow: 0 0 0 0.25rem rgba(139, 0, 0, 0.2);
  resize: vertical; /* or horizontal, depending on your needs */
  appearance: none;
}

#comment-box::-webkit-resizer {
  display: none; /* Hide the default diagonal resize handle in WebKit browsers */
}

By setting appearance: none;, you can override the default styling of the resize handle. The ::-webkit-resizer selector specifically targets the resize handle in WebKit browsers (like Chrome and Safari) and hides it using display: none;.
Comment: By "research" I think you mean "ask ChatGPT and then copy-paste the answer directly". This is not acceptable. Please read https://stackoverflow.com/help/ai-policy and consider which of your answers you may need to delete.


Linear objective function in non-convex feasible region: Is the global optima in the frontier?

Question: Considering an optimization problem in which the objective function is linear and the feasible region is a non-convex set: Can we assure that the global optima is still in the frontier of the feasible region? Any proof or counterexample?
I have thought about it, and I would say this holds considering an objective function $f: \mathbb{R}^{2} \rightarrow \mathbb{R}$. However, I do not know if this is true or if it can be generalized.
Maybe this is a very naive question, but I could not find any resource clarifying this.
Thank you in advance for your comments. Best regards.
Comment: No. Any non-convex optimization problem can be put in this form via epigraph formulation.  Change minimize objective subject to constraints; to minimize t subject to objective <= t and original constraints. This now has your "special" form.
Comment: Hello Mark.

You are right, I could estate the problem as you suggest so that the new formulation satifies my conditions. However, in that specific form, the global optima will be in the frontier given that the constraint: objective <= t will be active.
Comment: I have been thinking about this a little bit more and I would say it is true. Intuitively, if the feasible region is compact and the objective function is linear, the gradient of the objective function won't be null in the interior of the feasible region. Therefore, the global optima lays in the frontier necessarily. However, in pretty fresh in this field and I can still be totally wrong.

Anyway, I truly appreciate your comments.

Best regards.
Answer: I assume by "frontier" you mean boundary. Let's assume we are maximizing $f(x)=c^\prime x$ over $X\subseteq \mathbb{R}^n,$ with $c\neq 0.$
Suppose that $X$ has full dimension $n$ and $x$ is a point in the interior of $X.$ Then $x\in B \subseteq X$ for some nontrivial ball $B$, and that ball must contain $x+\lambda c$ for some $\lambda > 0.$ Since $f(x+\lambda c)=c^\prime x + \lambda \left\Vert c \right\Vert^2 > c^\prime x,$ $x$ cannot be a maximum. So the maximum, if one exists, must lie on the boundary of $X.$
Now suppose instead that $X$ has dimension less than $n,$ meaning it is contained in an affine subspace of dimension $d<n.$ Then the interior of $X$ is empty, and technically the boundary of $X$ is $X,$ meaning any maximum is automatically a boundary point. I suspect, though, that you are interested in the relative boundary (the complement in $X$ of the relative interior of $X$).
Project $c$ into the affine subspace containing $X.$ If the projection is 0, $f(x)$ is constant over $X$ and every point of $X,$ whether in the relative interior or the relative boundary, is a maximum. If the projection is not 0, apply the previous argument (using the projection of $c$ and a ball of dimension $d$ in the relative interior of $X$) to rule out the possibility of a relative interior point being a maximum.
Note that, without additional assumptions, there is no guarantee that $X$ has a boundary (or, more precisely, that its boundary belongs to it), nor any guarantee that a maximum exists.
Comment: Your assumptions in regards to what I mean are right. Next time, I will be much more precise in my explanations and assumptions.

You formalized all concepts, arguments, and exceptions I thought about. Therefore, first, I would like to say that I fully agree with you. Secondly, I enormously appreciate your comments and help.

Summing your comment up, if I undertood you correctly, we could then say: "Given an optimization problem in which the objective function is linear. If the global optima exist, it can be found on the boundary of the feasible set".
Comment: Also, I would like to know the best solvers for this kind of problem. I have seen that the SLP (Successive Linear Programming) algorithm is commonly used to solve optimization problems in which the objective function is linear and the feasible set is non-convex. This is a separate discussion though. If you are interested in discussing it, I will create a separate post to address it.

Thank you very much. Best regards.
Comment: I agree with the conclusion that, if the optimum exists, at least one boundary point is optimal. Regarding the new question, I will not be much help (I typically stick to problems with convex feasible regions, at least if you relax integrality), but there are other people here who could provide useful answers ... and I agree that it should be posted as a separate question.


Suppose $f:X\to Y$ is onto and $A\subseteq Y$. Then $f(f^{-1}(A))=A$.

Question: Prove, disprove, or give a counterexample:
Suppose $f:X\to Y$ is onto and $A\subseteq Y$. Then $f(f^{-1}(A))=A$.
Edit: Does this work?
Suppose $f:X \to Y$ is onto and $A \subseteq Y$.
We know that for all $y\in Y$, there exists $x\in X$ such that $f(x)=y$. Let $x\in f(f^{-1}(A))$ and because $f:X\to Y$ is onto then for all $x\in A$ there exists $y\in f^{-1}(A)$ such that $f(y)= x$. Therefore, $x\in f(f^{-1}(A))$ $\to$ $A\subseteq f(f^{-1}(A))$. Thus, $f(f^{-1}(A))=A$ by definition of set equality.
There is likely a problem or two with that proof. If anyone had further input that'd be great!
Comment: See also: [Demonstrate that if $f$ is surjective then $X = f(f^{-1}(X))$](http://math.stackexchange.com/q/557764)
Answer: The inclusion $f(f^{-1}(A))\subset A$ always holds. Conversely, let $y\in A$. Since $f$ is surjective there exists $x\in X$ such that $y=f(x)$. Hence $x\in f^{-1}(A)$ so that $y=f(x)\in f(\underbrace{f^{-1}(A)}_{\ni x})$.


If $x^n+y^n=a^n$, what is dy/dx?

Question: I have done the math and my answer is $-(x/y)^{n-1}$. But I am not sure this is correct.
Comment: Yes, that's right. Next time, it would be good if you included your working in the question. Questions that don't include evidence of your attempts to solve the problem typically end up closed, deleted, and tend to be voted down.
Answer: $$x^n+y^n=a^n$$
$$\frac{d}{dx}\left[x^n+y^n\right]=\frac{d}{dx}\left[a^n\right]$$
$$nx^{n-1}+ny^{n-1}\frac{dy}{dx}=0$$
$$\frac{dy}{dx}=\frac{-nx^{n-1}}{ny^{n-1}}=\frac{-x^{n-1}}{(a^n-x^n)^{\frac{n-1}{n}}}$$
Answer: Let's see.   $x^n+y^n=a^n\implies nx^{n-1}+ny^{n-1}\frac{\operatorname{dy}}{\operatorname {dx}}=0\implies\boxed{\frac{\operatorname{dy}}{\operatorname {dx}}=-(\frac xy)^{n-1}}$

If $x^n+y^n=a^n$, what is dy/dx?


AS3/Flash: XML-PHP or PHP-MySQL advise request

Question: I need to create a Flash based application than must store data (and read also) in a database.
It will be dealing with about 500 records to fill and update a data grid with four columns.
Can it be done with pure AS3/XML/PHP or it's better to use MySQL?
Could you point to me to good tutorials or book?
I did buy an adobepress book (ActionScript 3 for Flash CS5) a couple of years ago but it only covers XML reading.
Many thanks in advance.
UPDATE 1:
I have done the same as desktop app yet. The database is stored in a local XML file (My Documents/storage folder) that I can read/write without any problem.
I need to adapt the project for on-line use.
UPDATE 2:
I did find this files: http://www.kirupa.com/web/xml/examples/newseditor.htm
The tutorials has some errors but is very simple. I will test it's performance with 500 records (I need something like 250 records)
Cheers
Answer: I'll suggest to use MySQL. The idea is to use the PHP as bridge between AS3 and the database. Flash has native support of XML, but if it is possible for you use JSON. Here is a short article about that subject.
Comment: I have done the same as desktop app yet. The database is stored in a local XML file (My Documents/storage folder) that I can read/write without any problem. I need to develop an on-line version. Thanks for your help Krasimir.
Comment: In your article (really nice one) you say: "In line 24 I'm defining a random parameter that we will add to the URL to prevent the caching of the data." How this work?
Comment: Every time when you make a request to some url the browser caches the result. Next time when you try to make the same request the browser checks if there is result for the same url and returns it. Using different url every time prevent this. However, the cache has also expire time.
Comment: Thanks for the explanation. I'll test the PHP/MySQL/Flash formula. I did fallow a tutorial years ago (Lee Brimellow, I think)


Make own INTERNET WIFI web-based authentication page using WAMPSERVER

Question: i wondering, it is possible to redirect ALL WEBSITE to a URL(authentication page) in localhost (wampserver)..
after client login (in the authentication page) with correct ID and PASSWORD, then the client will be able to access to any WEBSITE.
Comment: If you dont mind me asking, why? What are you actually trying to achieve
Comment: im actually trying to build a captive portal by using wampserver
Answer: You could setup basic authentication in apache. Edit httpd.conf by clicking through from the WampServer icon and follow these instructions. However, instead of using <Directory "/var/www/html/protected"> and doing it for each vhost, use <Location />. This is because each site will match that location directive so will all need to run the same authentication before sites will be shown.
If you didn't want to use basic auth in this manner, then I'd suggest you setting up shared authentication on your sites (like stack uses OpenID) or looking at something like CORS, but that seems like a lot of work.
The final thing I'd point out is IP restriction. We have some clients/staff/etc that access our dev servers but it's all locked down to specific IPs and luckily so far everyone who's needed it has had a static IP. This may not be an option.


User Cancels In App Purchase. How to end the transaction

Question: I have a small issue with iAP. I have the code working for the most part. It's just when the user cancels the purchase, the device doesn't think its over and keeps it. Thus if you try to buy it again, you will buy 2 of the product...which is bad, since they only want one. I must be missing some code. I will attach a Console log so you can see whats going on.
2010-12-21 15:47:29.364[204:307] Parental-controls are disabled (I launch the iAP)
2010-12-21 15:47:33.816[204:307] Win (There are products)
2010-12-21 15:47:37.043[204:307] Buying... (I pressed buy)
2010-12-21 15:47:40.661[204:307] FailedTransaction (Essentially I canceled)
2010-12-21 15:47:40.674[204:307] DefaultAction (which is to dismiss the modal view)
2010-12-21 15:47:42.738[204:307] Parental-controls are disabled (reopen the iAP view)
2010-12-21 15:47:44.440[204:307] Win
2010-12-21 15:47:46.939[204:307] Buying...
2010-12-21 15:47:46.945[204:307] Buying...
2010-12-21 15:47:48.414[204:307] FailedTransaction
2010-12-21 15:47:48.427[204:307] DefaultAction
2010-12-21 15:47:48.437[204:307] FailedTransaction
2010-12-21 15:47:48.449[204:307] DefaultAction
2010-12-21 15:47:50.622[204:307] Parental-controls are disabled
2010-12-21 15:47:51.314[204:307] Win
2010-12-21 15:47:51.883[204:307] Buying...(see how it compounds?)
2010-12-21 15:47:51.889[204:307] Buying...
2010-12-21 15:47:51.896[204:307] Buying...
2010-12-21 15:48:10.764[204:307] Posted5
2010-12-21 15:48:10.782[204:307] Yipeee!
2010-12-21 15:48:10.810[204:307] Posted5 (It gave the users 15 credits!)
2010-12-21 15:48:10.869[204:307] Yipeee!
2010-12-21 15:48:10.897 204:307] Posted5
2010-12-21 15:48:10.912[204:307] Yipeee!

Here is the code I am running:
#import "PurchaserViewController.h"

@implementation PurchaserViewController

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"yayadaadul.com/checkcredits.php"]]];

    if ([SKPaymentQueue canMakePayments]) {
        NSLog(@"Parental-controls are disabled");

        SKProductsRequest *productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:@"com.company.name.song"]];
        productsRequest.delegate = self;
        [productsRequest start];
    } else {
        NSLog(@"Parental-controls are enabled");
    }
}

- (IBAction)purchase {

    SKPayment *payment = [SKPayment paymentWithProductIdentifier:@"com.changedwe.worksinxcode.song"];
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}

- (IBAction)stop {
    [player stop];
}

- (IBAction)play {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *file = [NSString stringWithFormat:@"%@/Song.mp3", documentsDirectory];

    player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:file] error:nil];
    [player play];
}

- (void)downloadFromURL:(NSURL *)url {
    NSData *data = [NSData dataWithContentsOfURL:url];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *file = [NSString stringWithFormat:@"%@/Song.mp3", documentsDirectory];

    [data writeToFile:file atomically:YES];
}

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
    SKProduct *validProduct = nil;
    int count = [response.products count];
    if (count > 0) {
        validProduct = [response.products objectAtIndex:0];
        NSLog(@"Win");

    } else if (!validProduct) {
        NSLog(@"No products available");

    }
}
-(IBAction)home {
    [self dismissModalViewControllerAnimated:YES];

}

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
    for (SKPaymentTransaction *transaction in transactions) {
        switch (transaction.transactionState) {
            case SKPaymentTransactionStatePurchasing:
                NSLog(@"Buying...");
                break;
                break;

            case SKPaymentTransactionStatePurchased:
                [self downloadFromURL:[NSURL URLWithString:@""]];

                NSString *post =[NSString stringWithFormat:@"username=lol&cval=5"];

                NSString *hostStr = @"http://mysite.com/subdom/ccredit.php?";
                hostStr = [hostStr stringByAppendingString:post];
                NSLog(@"Posted5");

                NSLog(@"Yipeee!");
                [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://Action to Post.php?"]]];

                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];

                break;

            case SKPaymentTransactionStateRestored:
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                NSLog(@"Restored");

                break;

            case SKPaymentTransactionStateFailed:
                NSLog(@"FailedTransaction");
            //  [self finishTransaction:transaction wasSuccessful:NO];

                if (transaction.error.code != SKErrorPaymentCancelled) {
                    NSLog(@"An error encounterd");
                }

                //You need to clear their purchases here

                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                NSLog(@"DefaultAction");

                [self dismissModalViewControllerAnimated:YES];

                break;
        }
    }
}

Answer: Yes. You need to implement the success and failure delegate methods of SKRequest. Please refer to the documentation. http://developer.apple.com/library/ios/#documentation/StoreKit/Reference/SKRequestDelegate/Reference/Reference.html#//apple_ref/doc/uid/TP40008416
- (void)requestDidFinish:(SKRequest *)request
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error

Answer: It looks like you keep adding yourself as the transaction observer every time the purchase action is performed. Press it once, everything works fine. Press it again and your observer delegate methods get called twice, both for the second transaction.
Comment: Actually most of the tutorials I found indicate to add there the transaction observer, maybe because they are thinking of a simple solution for a one time buy. But where could you add only once the transaction observer? Because I've read that if you add it at an incorrect time you could also have problems. In my code I've added a bool variable to check if the transaction observer has been added to not add it anymore, but I don't think this is the best solution, what is your opinion on this?


Notify Angular a variable has changed

Question: I'm just starting with Angular and have a quick question:
var data = JSON.parse('[{"name": "Joe","account": "12355845454","rent": "500"}]');

angular.module('ngAppRentManager', []).
controller('RentCtrl', ['$scope', function ($scope) {
    $scope.tenants = data;
}]);

setTimeout(function () {
    data = JSON.parse('[{"name": "Sara","account": "54874","rent": "600"}]');
    console.log("Poke Angular!");
}, 2000);

When my variable data has changed. How do I tell Angular to update the model?
Fiddle
Comment: see $timeout service. This makes sure your angular is aware of your async operations .
Comment: or call $scope.apply() to ask angular to check data, and update bindings.
Comment: @Subin $scope is not defined in the current context, how do I reference it? I'm not doing anything async btw, I'm changing `data` when a user loads a csv file in a file input. Should I approach this differently?
Comment: check update up my answer
Comment: http://jsfiddle.net/pjsx1460/3/
Comment: make sure $scope is visible in current context. you can invoke async operation from within controller as shown in fiddle above. Also make sure you are setting modifying `$scope.tenants`, not variable `data`
Comment: Might want to fire `$scope.$apply();` onchange on your slider
Answer: ad .apply() to your code like this
var data = JSON.parse('[{"name": "Joe","account": "12355845454","rent": "500"}]');

angular.module('ngAppRentManager', []).
controller('RentCtrl', ['$scope', function ($scope) {
    $scope.tenants = data;

  setTimeout(function () {
    $scope.tenants = JSON.parse('[{"name": "Sara","account": "54874","rent": "600"}]');
    console.log("Poke Angular!");
     $scope.$apply();
}, 2000);

}]);

http://jsbin.com/tirebavaho/1/
Comment: Your changed your whole answer after I wrote my comment. Before it was `data = JSON.parse(...)` Next time you post please check your code before posting and not after...
Comment: it does - check jsbin  example
Answer: Use the $timeout service to stay within angular context.
var data = JSON.parse('[{"name": "Joe","account": "12355845454","rent": "500"}]');

angular.module('ngAppRentManager', []).
controller('RentCtrl', ['$scope', '$timeout', function ($scope, $timeout) {
    $scope.tenants = data;
}]);

$timeout(function () {
    data = JSON.parse('[{"name": "Sara","account": "54874","rent": "600"}]');
    console.log("Poke Angular!");
}, 2000);

Comment: [Link to comment below](http://stackoverflow.com/questions/26689447/notify-angular-a-variable-has-changed/26689794?#comment41998544_26689794)
Answer: I've found a working solution for my problem
var data = JSON.parse('[{"name": "Joe","account": "12355845454","rent": "500"}]');

angular.module('ngAppRentManager', []).
controller('RentCtrl', ['$scope', '$timeout', function ($scope, $timeout) {
    $scope.tenants = data;
    $scope.getData = function (newData) {
        $scope.tenants = newData;
        $scope.$apply();
    };
}]);

setTimeout(function () {
    data = JSON.parse('[{"name": "Sara","account": "54874","rent": "600"}]');
    console.log("Poke Angular!");
    // Is this the best way to call Angular from outside scope?
    angular.element($('#control')).scope().getData(data);
}, 2000);

If this can be improved by calling the controller directly, please let me know.
Fiddle
Comment: JimmyRare's answer is correct. no need to use #id's while working with angular.... neither DOM manipulation NOR getting handle to elements should be done with angular
Comment: I have no use for `timeout` in reality I want to update my view after a function outside the controller parsed a CSV file.
Comment: Do not use scope.apply inside angular context, that makes your method attached to the controller scope unusable from angular (as it is going to throw phase error). So ideally scope.apply must be invoked at the source not in the function that is effected. I.e you would do it in the setTimeout in your case. Also what does this timeout of 2sec give you? what if your process takes more time or even much less time you make the user wait?
Comment: @PSL the `setTimeout` is there for the sole purpose to simulate a user changing `data` at a certain point and has absolutely nothing to do with the actual code.
Comment: but how will you fetch the data, using $http??
Comment: @Jonathan Alright that is fine.. However i mentioned my point about scope.$apply it still applies in your case :). And also if you convert whatever service you are using to parse a csv file you could wrap it and make an angular service and you will not have to do all these, You may want to read up on services, run phase(if you want to do it during your app initialization and have the service manage the data though promise pattern) of the app etc..
Comment: @PSL I'm rewriting an existing application to learn Angular and get rid of all the code where I'm creating most of the DOM in custom JS. I already have the code that handles the data.
Comment: @harish I get it from a HTML file input where the user can drop a CSV which is then parsed for the relevant fields.
Answer: You can use $scope.$watch:
$scope.$watch("data", function (newVal, oldVal) {
     //your update code
     //newVal is your data's changed value
});

Notify Angular a variable has changed