Test APK Dependency Conflicts

Question: Em uma aplicação antiga que fui atualizar a versão das dependências do gradle, ao executar recebi a seguinte mensagem a respeito de um conflito entre a versão da dependência com.google.code.findbugs:jsr305 para app e para test:

Error:FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:preMyAppDebugAndroidTestBuild'. >
  Conflict with dependency 'com.google.code.findbugs:jsr305' in project
  ':app'. Resolved versions for app (1.3.9) and test app (2.0.1) differ.
  See https://d.android.com/r/tools/test-apk-dependency-conflicts.html
  for details. * Try: Run with --stacktrace option to get the stack
  trace. Run with --info or --debug option to get more log output. Run
  with --scan to get full insights. * Get more help at
  https://help.gradle.org BUILD FAILED in 0s

Alguém já passou por algo similar? Como devo proceder? Segue abaixo minha lista de dependências:
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:27.1.0'
    annotationProcessor 'com.jakewharton:butterknife:7.0.1'
    compile 'com.jakewharton:butterknife:7.0.1'
    compile 'com.google.code.gson:gson:2.8.2'
    compile 'com.google.guava:guava:23.3-android'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.squareup.okhttp:okhttp:'
    compile 'com.squareup.okhttp:okhttp-urlconnection:2.7.5'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.google.code.gson:gson:2.8.2'
    compile 'com.squareup.dagger:dagger:1.2.5'
    compile 'com.android.support:design:27.1.0'
    compile 'com.google.zxing:core:3.2.0'
    compile 'com.google.zxing:android-core:3.2.0'
    compile 'com.google.zxing:android-integration:3.2.0'
    compile 'commons-codec:commons-codec:1.5'
    annotationProcessor 'com.squareup.dagger:dagger-compiler:1.2.5'
    provided 'com.squareup.dagger:dagger-compiler:1.2.5'
    androidTestCompile 'org.mockito:mockito-core:'
    androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.2'
    androidTestCompile 'com.android.support:support-annotations:27.1.0'
    androidTestCompile 'com.android.support.test:runner:1.0.1'
    androidTestCompile 'com.android.support.test:rules:1.0.1'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:3.0.1'
    androidTestCompile ('com.android.support.test.espresso:espresso-contrib:2.2'){
        exclude module: 'support-annotations'
        exclude module: 'support-v4'
        exclude module: 'support-v13'
        exclude module: 'recyclerview-v7'
    }
    androidTestCompile 'com.android.support.test.espresso:espresso-intents:3.0.1'
}

Answer: O que está acontecendo é que duas ou mais dependências estão dependendo dessa biblioteca com.google.code.findbugs:jsr305, mas em versões diferentes. Com isso, está ocorrendo esse conflito.
Forçar uma única versão
A primeira solução é forçar que o gradle compile apenas o número da versão que você declara para todas as dependências, não importando qual número de versão as dependências em si tenham declarado. Isso pode ser feito direto no arquivo build.gradle:
android {
    configurations.all {
        resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
    }
}

Nesse exemplo, estamos forçando a versão 1.3.9.
Descobrir em quais dependências está o conflito
Outra solução é avaliar toda sua árvore de dependencias e identificar quais dependências estão dependendo essa mesma biblioteca findbugs e realizar excludenas incompatíveis.
Para isso, podemos usar o comando para listar toda nossas árvores de dependências:
./gradlew app:dependencies

Ou mesmo podemos pesquisar por um dependência em específico como compile, testCompile ou androidTestCompile:
./gradlew :app:dependencyInsight --configuration compile --dependency <name>
./gradlew :app:dependencyInsight --configuration testCompile --dependency <name>
./gradlew :app:dependencyInsight --configuration androidTestCompile --dependency <name>

No caso:
./gradlew :app:dependencyInsight --configuration compile --dependency com.google.code.findbugs:jsr305
./gradlew :app:dependencyInsight --configuration testCompile --dependency com.google.code.findbugs:jsr305
./gradlew :app:dependencyInsight --configuration androidTestCompile --dependency com.google.code.findbugs:jsr305

Mediante a lista de dependências especificadas, o problema está na biblioteca com.google.guava:guava:23.3-android, sendo assim, concluimos com o seguinte exclude:
compile ('com.google.guava:guava:23.3-android') {
   exclude group: 'com.google.code.findbugs'
}

Test APK Dependency Conflicts


Relatively open subsets of the unit interval can be expressed uniquely as unions of disjoint open intervals

Question: From "An Introduction to Lebesgue Integration and Fourier Series" by Howard J. Wilcox and David L. Myers:
7.2 Theorem: Every non-empty open set $G \subset \mathbb{R}$ can be expressed uniquely as a finite or countably infinite union of pairwise disjoint open intervals.
The meaning of 'uniquely' is defined in Exercise 9.11: Prove uniqueness in Theorem 7.2; if $G = \cup_{n} I_{n} = \cup_{k} J_{k}$, where $I_{n}$, $J_{k}$ are open intervals and $I_{n} \cap I_{m} = \varnothing$, $J_{k} \cap J_{l} = \varnothing$ for all $n$, $m$, $k$, $l$, then show that for every $n$ there is a $k$ such that $I_{n} = J_{k}$, and for every $k$ there is an $n$ such that $J_{k} = I_{n}$.
The author then states:
Whenever we use open sets in the unit interval $E$, we shall use "open" to mean open in the relative topology of $E$ as a subspace of $\mathbb{R}$. That is, $G$ is open in $E$ if and only if $G = E$ intersected with some open subset of $\mathbb{R}$. Then it is clear that the theorem holds in the relative topology of $E$, in the sense that if $G$ is open in $E$, there is a unique representation $G = \cup_{i} I_{i}$, where the $I_{i}$ are disjoint intervals of the form $(a_{i}, b_{i}) \cap E$.
I am attempting to prove that this holds. I believe I have been able to demonstrate that every non-empty subset $G$ of $[0,1]$ that is open in the relative topology of $[0,1]$ can be expressed as a finite or countably infinite union of pairwise disjoint intervals of the form $(a_{i}, b_{i}) \cap [0,1]$:
Let $G$ be an arbitrary non-empty subset of $[0,1]$ that is open in the relative topology of $[0,1]$. Then there exists a non-empty set $U$, open in $\mathbb{R}$, such that $G = U \cap [0,1]$. By Theorem 7.2, $U$ can be expressed as a finite or countably infinite union of pairwise disjoint open intervals. That is, $U = \cup_{i} (a_{i}, b_{i})$. Then $G = U \cap [0,1] = [\cup_{i} (a_{i}, b_{i})] \cap [0,1] = \cup_{i} [(a_{i}, b_{i}) \cap [0,1]]$.
I am struggling to prove uniqueness. The problem seems to be that if $G = U \cap [0,1]$, then although $U$ can be expressed uniquely as a finite or countably infinite union of pairwise disjoint open intervals, it does not appear that this implies that $U \cap [0,1]$ can.
EDIT
Based on Paul Frost's answer:
Let $G$ be an arbitrary non-empty subset of $[0,1]$ that is open in the relative topology of $[0,1]$. Let $I$ and $J$ be finite or countably infinite sets of pairwise disjoint intervals open in the relative topology of $[0,1]$ such that $G = \cup I$ and $G = \cup J$.
Suppose $0 \in G$ and $1 \notin G$. Then $0 \in \cup I$ and $0 \in \cup J$. Since the intervals in $I$ are disjoint, then there is a single interval $I_{0} \in I$ that contains $0$. Since the intervals in $J$ are disjoint, then there is a single interval $J_{0} \in J$ that contains $0$.
$I_{0} = [0, e)$ for some $e \in (0,1)$. $J_{0} = [0, f)$ for some $f \in (0,1)$.
Let $a < 0$. Let $I_{0}' = (a, 0] \cup [0, e)$. Then $I_{0}'$ is an open interval. Let $J_{0}' = (a, 0] \cup [0, f)$. Then $J_{0}'$ is an open interval.
Let $I'$ be the set formed by replacing $I_{0}$ by $I_{0}'$ in $I$. Let $J'$ be the set formed by replacing $J_{0}$ by $J_{0}'$ in $J$.
Then $\cup I' = \cup J'$. Then since $I'$ and $J'$ are finite or countably infinite sets of pairwise disjoint open intervals, $I' = J'$ by Theorem 7.2. Then since $I_{0}'$ and $J_{0}'$ are the only sets in $I'$ and $J'$ that contain $0$, $I_{0}' = J_{0}'$. Then $I_{0} = J_{0}$. Then $I = J$.
Comment: The statement of Theorem 7.2 is valid only if we include $\Bbb R, \emptyset,$ and all $(r,\infty)$ and $(-\infty,r)$ among the "open intervals", i.e. it would be clearer if it said "convex sets" instead of "intervals"
Comment: Check out [this question and its answers](https://math.stackexchange.com/q/318299/4280).
Answer: Both in $\mathbb{R}$ and in $[0,1]$ the decomposition is just the unique decomposition of an open set into its connected components, which are in both cases relatively open due to local connectedness.
Comment: I apologize, it has been a while since I studied connectedness, so I don't quite understand this yet.
Comment: @Patrick Look up connected components. Also, local connectedness.
Answer: Let us consider $G \subset [0,1]$ which is open in the relative topology of $[0,1]$. What does $G$ prevent from being open in $\mathbb{R}$? If $G \subset (0,1)$, then $G$ is open in $\mathbb{R}$, but if one of the boundary points $0,1$ is contained in $G$, then $G$ is not open in $\mathbb{R}$. We consider the case that $0 \in G$ and $1 \notin G$, the other cases are treated similarly. We know that there exists $\varepsilon \in (0,1)$ such that $[0, \varepsilon) = (-\varepsilon, \varepsilon) \cap [0,1] \subset G$. Then $G' = G \cup (-\varepsilon,0]$ is open in $\mathbb{R}$. Apply to theorem to express $G'$ uniquely as a finite or countably infinite union of pairwise disjoint open intervals $I'_n$. Then the $I_n = I'_n \cap [0,1]$ are the desired subintervals of $[0,1]$.
Now assume you have another family $J_k$ for $G$. Exactly one of the $J_k$, call it $J_0$, contains $0$. All other intervals are contained in $(0,1)$ (recall $1 \notin G$) and are therefore open in $\mathbb{R}$. Define $J'_0 = J_0 \cup (-\varepsilon,0]$ and $J'_k = J_k$ else. Then the theorem applies to show that the families $I'_n$ are $J'_k$ are identical up to a bijection between the indices. W.l.o.g. assume that $0 \in I'_0$. Then necessarily $I'_0 = J'_0$, hence  $I_0 = J_0$, and we are done.
Comment: I wasn't entirely certain that I understood the second part of your answer, so I tried to expand it as an edit to mine. Is my interpretation correct?
Comment: Yes, it is correct.
Comment: Thank you. Was the original existence part of my proof correct?
Comment: Yes, that was also correct. Note that Henno Brandsma's proof is much more elegant then reducing the $[0,1]$-case to $\mathbb{R}$.
Comment: It has been a while since I studied connectedness, so I don't quite understand his answer yet.
Comment: Do we deal with the case where $G$ contains both $0$ and $1$ by splitting it into the case where $G = [0,1]$ and the case where $G$ has separate open intervals containing $0$ and $1$?
Comment: No, treat it like the case with $0 \in G$ and $1 \notin G$. You have $I_0, I_1$ with $0 \in I_0, 1 \in I_1$ etc.
Comment: If both $0 \in G$ and $1 \in G$, couldn't we have $0 \in I_{0}$ and $1 \in I_{0}$?
Comment: Yes, but only when $G = I_0 = [0,1]$ which is trivial.
Comment: I think I see what you mean.


Compare two distributions with bias

Question: I have been programming in R and have a dataset containing the results (succes or not) of two Machine Learning algorithms which have been tried out using different amounts of parameters. An example is provided below:
<code>type success paramater_amount
a1     0       15639
a1     0       18623
a1     1       19875
a2     1       12513
a2     1       10256
a2     0       12548
</code>
I now want to compare both algorithms to see which one has the best overall performance. But there is a catch. It is known that the higher the parameter_amount, the higher the chances for success. When checking out the parameter amounts both algorithms were tested on, one can also notice that a1 has been tested with higher parameter amounts than a2 was. This would make simply counting the amount of successes of both algorithms unfair.
What would be a good approach to handle this scenario?
Answer: EDIT: I changed the answer from a simple decision rule to a more statistical answer.
You would be well advised to use a weights-based approach to handle the problem. One simple way to do so is to multiply the success count of type $a1$ by $\frac{t_2}{t_1}$, where $t_1$ and $t_2$ are the associated totals of the parameter_amount variable: $t_1=54137$ and $t_2=35317$.
So, if the original contingency table was
$$\begin{array}{c|c|c|c}
 & \text{Successes} & \text{Failures} & \\ \hline
\text{Type a1} & a & b & a+b\\ \hline
\text{Type a2} & c & d & c+d\\ \hline
\text{} & a+c & b+d & a+b+c+d\\ \hline
\end{array},$$
it should be replaced by
$$\begin{array}{c|c|c|c}
 & \text{Successes} & \text{Failures} & \\ \hline
\text{Type a1} & \frac{t_2}{t_1} a & b & \frac{t_2}{t_1}a+b\\ \hline
\text{Type a2} & c & d & c+d\\ \hline
\text{} & \frac{t_2}{t_1}a+c & b+d & \frac{t_2}{t_1}a+b+c+d\\ \hline
\end{array}$$
This way, one penalises type $a1$ for its unfair advantage by changing only one of the four non-marginal entries in the contingency table.
Now, it is appropriate to use a one-tailed Fisher's exact test because the individual observations are independent.
Let $p_1,p_2$ be the success rates (the underlying theoretical ones for which we are conducting inference).
Let $\alpha$ be our chosen confidence level. A $(1-\alpha)\times100\%$ confidence interval for $p_1-p_2$ is given by
$$ \hat{p_1}-\hat{p_2} \pm z_{1-\frac{\alpha}{2}} \sqrt{\frac{\hat{p_1}(1-\hat{p_1})}{n_1}+\frac{\hat{p_2}(1-\hat{p_2})}{n_2}},$$
where the $\hat{p_i}'s$ and the $n_i's$ are the weight-corrected proportions (success rates) and sample sizes, and $z_{1-\frac{\alpha}{2}}$ denotes the corresponding percentile point of the standard normal distribution.
I hope this helps. Let me know if anything is unclear.
Comment: This method intuitively makes a lot of sense, thanks! I did the calculations for my real dataset and I got two numbers 64 and 46 but I'm wondering what conclusions I can now derrive from it. Shouldn't I still run some kind of statistical test which can lead me to some conclusion with a certain confidence interval? I'm thinking of maybe making a  2 x 2 matrix with the weighted successes/failures and using using a Fisher's test as I only have 100 sample size to compare them?
Comment: Thanks for your ellaboration. To me, only having to correct one of the four entities sounds a bit counter-intuitive, won't it ruin the original ratio between successes/failures? I've tried translating your answer to R code to be sure I'm interpreting it correctly (look my original question), is this the correct way to do it?
Comment: Whilst the approach alters the ratio, it is sound if your primary purpose is to compare the two algorithms fairly. Indeed, you would like to be able to say that $p_1=0.4$ is worse than $p_2=0.4$, for example, taking into account *parameter_amount*.
Comment: Are you familiar with the difference between one-tailed and two-tailed Fisher's test ? Given your question, you want to perform a one-sided Fisher's test with H1: $p_1>p_2$ or H1:$p_1<p_2$. Don't forget to add **alternative = "one.sided"** in the fisher.test function. Feel free to let me know if anything is unclear. Do you know domain-knowledge that guarantees $p_1 \geq p_2 $ or $p_1 \leq p_2 $?
Comment: Yes, I remember those concepts from an earlier statistics course I had. I currently use `alternative="greater"` which returns a p-value of 0.8547. I'm interpreting that as that there is not enough evidence to reject the null hypothesis in which alogorithm 1 performs equally to algorithm 2. On the oppositive however, we also can't definitively conclude that algorithm 1 does perform better than algorithm 2. Is this the correct interpretation?
Comment: What you can conclude from this test is that there is not enough evidence to reject the null hypothesis that algorithm $1$ and algorithm $2$ perform equally (if we take into account the penalty we defined).
Comment: One final question, would we draw a different conclusion if we used a two-sided fisher test?
Comment: If you conduct a two-sided Fisher's test, it means H0: $p_1=p_2$ and H1:$p1 \neq p2$. Then, if the p-value is smaller than $\alpha$, you must reject the null hypothesis, otherwise there is not enough evidence to reject the null hypothesis.

Compare two distributions with bias


Blacklisted client: why did Postfix not reject this email?

Question: Answer
The best answer was on the postfix-users mailing list and it is summarized here for the benefit of serverfault's users.

I had forgotten soft_bounce = yes.  Always switch it back to no after validating the configuration
When asking for help about Postfix configuration, always include the complete output of postconf -n
Stop accepting mail AT ALL from IPs that have no PTR records.  Add reject_unknown_reverse_client_hostname to smtpd_recipient_restrictions AFTER permit_mynetworks and permit_sasl_authenticated

If the reply code is 4xx, it invites the other mail server to retry.  The IP address seems to be used by a "snowshoe" spammer, making detection harder.  Those IP addresses flicker in and out of the blacklist as blacklist operators (Spamhaus in this case) are working to counter the snowshoers' tactics.  It is an ongoing, global arms race.  Rejecting mail from IPs that have no PTR records reduces significantly the size of the local battlefield.
Original Question
This is logged on a low usage, personal Postfix server.  I believe there should be two reasons to reject emails based on the headers below, but the outcome is a delivery to INBOX.  Excerpts of the relevant Postfix configuration follows and my questions are at the end.
Log Exercerpt
Jun  5 09:58:37 x2 postfix/smtpd[8440]: connect from unknown[18.104.22.168]
Jun  5 09:58:37 x2 postfix/smtpd[8440]: NOQUEUE: reject: RCPT from unknown[18.104.22.168]: 454 4.7.1 Service unavailable; Client host [184.108.40.206] blocked using zen.spamhaus.org; from=<email@example.com> to=<XXX@XXX> proto=ESMTP helo=<mr99.dgnmkt.com>
Jun  5 09:58:37 x2 postfix/smtpd[8440]: disconnect from unknown[188.8.131.52]
Jun  5 10:01:57 x2 postfix/anvil[8394]: statistics: max connection rate 1/60s for (smtp:184.108.40.206) at Jun  5 09:51:57
Jun  5 10:01:57 x2 postfix/anvil[8394]: statistics: max connection count 1 for (smtp:188.8.131.52) at Jun  5 09:51:57
Jun  5 10:01:57 x2 postfix/anvil[8394]: statistics: max cache size 2 at Jun  5 09:55:18
Jun  5 10:06:39 x2 postfix/smtpd[8507]: connect from unknown[188.8.131.52]
Jun  5 10:06:40 x2 policyd-spf[8513]: None; identity=helo; client-ip=188.8.131.52; helo=mr99.dgnmkt.com; firstname.lastname@example.com; receiver=XXX@XXX
Jun  5 10:06:40 x2 policyd-spf[8513]: Pass; identity=mailfrom; client-ip=22.214.171.124; helo=mr99.dgnmkt.com; firstname.lastname@example.com; receiver=XXX@XXX
Jun  5 10:06:40 x2 postfix/smtpd[8507]: 49D01C1EDE: client=unknown[126.96.36.199]
Jun  5 10:06:40 x2 postfix/cleanup[8514]: 49D01C1EDE: message-id=messageid-3-M3w1NDIzfDU4fDM3ODk3OTR8eWxlYmF5Y2EwNEBzZmluYS5jb218U2F0LCAwNCBKdW4gMjAxNiAwNToxNDowNyAtMDcwMA==
Jun  5 10:06:40 x2 opendkim[1220]: 49D01C1EDE: [18.104.22.168] [220.127.116.11] not internal
Jun  5 10:06:40 x2 opendkim[1220]: 49D01C1EDE: not authenticated
Jun  5 10:06:43 x2 opendkim[1220]: 49D01C1EDE: no signature data
Jun  5 10:06:43 x2 postfix/qmgr[1337]: 49D01C1EDE: from=<firstname.lastname@example.com>, size=91945, nrcpt=1 (queue active)
Jun  5 10:06:43 x2 postfix/smtpd[8507]: disconnect from unknown[184.108.40.206]
Jun  5 10:06:43 x2 dovecot: lmtp(8516): Connect from local
Jun  5 10:06:43 x2 dovecot: lmtp(8516, YYY@XXX): nhVjEfMxVFdEIQAAzX/GXw: msgid=messageid-3-M3w1NDIzfDU4fDM3ODk3OTR8eWxlYmF5Y2EwNEBzZmluYS5jb218U2F0LCAwNCBKdW4gMjAxNiAwNToxNDowNyAtMDcwMA==: saved mail to INBOX
Jun  5 10:06:43 x2 postfix/lmtp[8515]: 49D01C1EDE: to=<YYY@XXX>, orig_to=<XXX@XXX>, relay=XXX[private/dovecot-lmtp], delay=3.6, delays=3.5/0.01/0.02/0.05, dsn=2.0.0, status=sent (250 2.0.0 <YYY@XXX> nhVjEfMxVFdEIQAAzX/GXw Saved)
Jun  5 10:06:43 x2 dovecot: lmtp(8516): Disconnect from local: Successful quit
Jun  5 10:06:43 x2 postfix/qmgr[1337]: 49D01C1EDE: removed

Notes About the Log

@XXX is my domain
XXX@XXX is an alias
YYY@XXX is a mailbox

My understanding is that the bad sender [22.214.171.124] has been
blocked at 9:58:37 based on zen.spamhaus.org, but 8 minutes later it
reconnected and delivered successfully what should have not passed
through.

Headers of the Mail That Should Have Been Rejected
Return-Path: <firstname.lastname@example.com>
Delivered-To: <YYY@XXX>
Received: from XXX
by XXX (Dovecot) with LMTP id nhVjEfMxVFdEIQAAzX/GXw
for <YYY@XXX>; Sun, 05 Jun 2016 10:06:43 -0400
Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=220.127.116.11; helo=mr99.dgnmkt.com; email@example.com; receiver=XXX@XXX
Received: from mr99.dgnmkt.com (unknown [126.96.36.199])
by XXX (Postfix) with ESMTP id 49D01C1EDE
for <XXX@XXX>; Sun,  5 Jun 2016 10:06:39 -0400 (EDT)
Received: from stormmta (unknown [18.104.22.168])
by mr99.dgnmkt.com (Postfix) with ESMTP id DD84AE61F8A
for <XXX@XXX>; Sun,  5 Jun 2016 08:16:33 -0700 (PDT)
From:=?UTF-8?B?VG1hcnQuY29t?=<firstname.lastname@example.com>
To:XXX@XXX

Postfix Configuration
Relevant main.cf Options
smtpd_recipient_restrictions =
  permit_mynetworks
  permit_sasl_authenticated
  reject_unauth_destination
  reject_invalid_hostname
  reject_non_fqdn_hostname
  reject_non_fqdn_sender
  reject_non_fqdn_recipient
  reject_unknown_sender_domain
  reject_unknown_recipient_domain

  check_recipient_access hash:/etc/postfix/recipients
  # used to have Postgrey here
  # check_policy_service inet:127.0.0.1:10023
  reject_rbl_client zen.spamhaus.org
  check_policy_service unix:private/policy-spf
  permit

smtpd_restriction_classes =
  ebay

ebay =
  check_reverse_client_hostname_mx_access pcre:/etc/postfix/ebay.pcre

/etc/postfix/recipients
XXX@XXX ebay

ebay.pcre
/.ebay.com$/ DUNNO
/(.*)/  REJECT Not allowed to relay from $1.  Please use eBay's contact form if you have legit communication for this email address.

My Comments and Questions
I assign aliases to isolate sources of mail.  One such alias is assigned
to eBay.  eBay leaks buyer's email address to merchants.  Not all
merchants respect buyers' communication preferences.  My solution is to
restrict the emails accepted on the eBay alias to emails from eBay and
reject all noise.
First, I thought that this email should have been rejected by:
  check_recipient_access hash:/etc/postfix/recipients

because following /etc/postfix/recipients the ebay restriction apply and
ebay.pcre would have caught it on the second line.
Second, I thought that this email should have been rejected by:
  reject_rbl_client zen.spamhaus.org

like the attempt a few minutes earlier.
Obviously what I expected did not happen.  Why?  And how can I fix it?
Answer: If you like to block the IP of the sending client, than you will have to set up the RBLs in ...
smtpd_client_restrictions = permit_mynetworks,
        permit_sasl_authenticated,
        reject_unauth_destination,
        reject_rbl_client zen.spamhaus.org,
        reject_rbl_client bl.spamcop.net,
        reject_rbl_client cbl.abuseat.org,
        permit
The sequence in Postfix' restrictions is always

smtpd_helo_restrictions
smtpd_client_restrictions
smtpd_sender_restrictions
smtpd_recipient_restrictions
Comment: Answer does not address my question.  I asked why the message went through, not how to block the IP of the sending client.  There are many ways to configure Postfix to block incoming messages, and many good reason not to put restrictions in `smptd_client_restrictions`.
Answer: From what I see it looks like Spamhouse has answered differently second time. I.e. first answer was "there is a spammer", but 8 minutes later answer was "there is nothing special". Why it was answered it is hard do say.
If you have access do DNS server query logs which is set to resolve your mail server's dns queries, you might find some clues there. For example, Spamhouse provides service according to their policies, which state some limits for how many queries per hour, per month and so on you can make. They even could evaluate to whom they provide service this time and opt to not give meaningful answers to those who they consider as spammers.
Probably, you'd send this log directly to Spamhouse and they could speak for themselves.
But!
It is hard to say exactly without seeing detailed debug level 2 where Postfix logs query information for each statement in each XXX_restriction option. The exact rbl reply would have been also logged there.
Also, the way you presended the Postfix config is wrong. You should always give complete output from the "postconf" command. This is what Postfix developers require in their mailing list and there are reasons to do so.
Comment: Selected as best answer because it addressed the incomplete question (my fault for not providing `postconf -n` output) and advanced additional debugging steps that could be taken to complete the picture.


Can I combine multiple "no results behavior" to avoid repetition?

Question: I have a Search API view that has 3 attachments. This is so I can display different content type results with unique layouts.
If the user searches something too specific, they'll see the No Results Behavior up to 4 times in a row. This looks bad.
How can I only display the No Results Behavior (custom textarea) when there are no results in the view AND its 3 attachments?
Comment: In edit View, under "Advanced" there is an option to customize the no results behaviour. Do this for each of your views. As each view should be treated separately evethough they are attached.
Comment: This isn't the issue. I'm already using the "No Results Behavior" feature. But since I have 4 attachments, the user will see up to 4 "NO RESULTS FOUND" messages. I only want them to see AT MOST one no results - even if all 4 views fail to return anything.
Comment: Oh right sorry. You'll need to use [hook_views_pre_render](https://api.drupal.org/api/drupal/core%21modules%21views%21views.api.php/function/hook_views_pre_render/8.7.x) and perform a check if they all say no results and if yes then you override the output of the attached views and set them to null/nothing/empty.
Comment: Thanks for the tip. Can you give me a rough outline of what to do with that hook? I'm not sure how I can check it a view is empty with PHP. I also don't know how to take content from the hook and have it change the output of the view.
Comment: There doesn't appear to be way, ran into dead ends. Not sure if it's a Views bug or just how it's suppose to be. I guess another way would be to hide the duplicates via custom JS/jQuery.
Comment: Thanks for trying. Your second reply got me moving towards the solution. I resolved the issue so THANK YOU!! I've added my answer below.
Answer: I solved it myself (that's a first and probably a last)!
I'm sure this isn't the best code but it works and I don't know enough PHP to clean it up.
I disabled all "No Results Behaviors" in the view settings. I'm using the hook_preprocess_views_view hook to count the number of results for each of my attachments. Only if all 4 === 0 will it print the correct empty message.
<code>function MYTHEMENAME_preprocess_views_view(&$variables) {
  $view = $variables['view'];
  if ($view->name == 'search_results') {
    $view1 = $view2 = $view3 = $view4 = $view;

    if (is_object($view1) && is_object($view2) && is_object($view3) && is_object($view4)) {
      $view1->setDisplay('page_1');
      $view2->setDisplay('attachment_1');
      $view3->setDisplay('attachment_2');
      $view4->setDisplay('attachment_3');

      $view1->execute();
      $view2->execute();
      $view3->execute();
      $view4->execute();

      if (count($view1->result) === 0 && count($view2->result) === 0 && count($view3->result === 0 && count($view4->result) === 0)) {
        $variables['empty'] = "Sorry, but we couldn't find any results for your query. Try broadening your search terms.";
      }
    }
  }
}
</code>
Comment: Improved your answer. Added a conditional, as you don't want this code to run on every single view that your site has.
Comment: Hmmm this doesn't seem to be working. $view->name doens't appear to return anything.


How to decode celery result from the Mongo DB?

Question: When I execute the task using celery where backend is Mongo DB, It is storing the result in the form of BinData(0,"gAJLEy4=") in the database.
How can we read this 'result' data from the Mongo DB and decode it to string?
I want to write a new python script where it reads all the results from the Mongo db.
Is there any direct API available in the celery result module or in pymongo to process this result?
In my case the result will be the HTML source of web pages (i.e crawled data)
Answer: Got an answer. By default, Celery is storing the result as a pickle object in the data store.
We can retrive this value by calling a function pickle.loads
import pickle
# Connect db
# Fetch record from the collection
str_result = pickle.loads(c['result'])


Evaluate $\int_{{\frac {\pi}{8}}}^{{\frac {7\,\pi}{8}}}\!{\frac {\ln \left( 1- \cos \left( t \right) \right) }{\sin \left( t \right) }}\,{\rm d}t$

Question: I'm interested in this integral: $\int_{{\frac {\pi}{8}}}^{{\frac {7\,\pi}{8}}}\!{\frac {\ln  \left( 1- \cos \left( t \right)  \right) }{\sin \left( t \right) }}\,{\rm d}t$
I found this particular closed form with Maple and finally : $-{\frac { \left( \ln  \left( 2-\sqrt {2+\sqrt {2}} \right)  \right) ^{
2}}{2}}-{\frac {{\pi}^{2}}{12}}+{\frac {11\, \left( \ln  \left( 2
 \right)  \right) ^{2}}{8}}-{\frac { \left( \ln  \left( 1+\sqrt {2}
 \right)  \right) ^{2}}{2}}+{\frac {3\, \left( \ln  \left( 2+\sqrt {2}
 \right)  \right) ^{2}}{4}}+{\it {Li_2}} \left( -{\frac {\sqrt {2+
\sqrt {2}}}{4}}+{\frac{1}{2}} \right)
$, where \Li_2 is the dilogarithm function.
Please, can someone prove it ?
Comment: Start with the property of definite integrals that $\int_{a}^{b}f(x)dx=\int_{a}^{b}f(a+b-x)dx$
Answer: $$I=\int{\frac {\log \left( 1- \cos \left( t \right) \right) }{\sin \left( t \right) }}\,dt=\int \sin(t){\frac {\log \left( 1- \cos \left( t \right) \right) }{1-\cos^2\left( t \right) }}\,dt$$
Let
$$x=\cos(t)\implies I=\int \frac{\log(1-x)}{x^2-1} \,dx=-\frac12\int\frac{\log(1-x)}{ 1-x}\,dx-\frac12\int\frac{\log(1-x)}{ x+1}\,dx$$
$$\int\frac{\log(1-x)}{ 1-x}\,dx=-\frac{1}{2} \log ^2(1-x)$$
For the second integral, integration by parts gives
$$\int\frac{\log(1-x)}{x+1}\,dx=\text{Li}_2\left(\frac{1-x}{2}\right)+\log (1-x) \log \left(\frac{x+1}{2}\right)$$ Combining the results
$$I=\int \frac{\log(1-x)}{x^2-1} \,dx=\frac{1}{4} \left(\log (1-x) (\log (4(1-x))-2 \log (x+1))-2
   \text{Li}_2\left(\frac{1-x}{2}\right)\right)$$ Go back to $t$ if you wish and use bounds.
Comment: So great and thanks !
Comment: @Dens. Glad to help ! In fact the problem is simple if you think about the first trick $$\frac 1 {\sin(x)}=\frac {\sin(x)}{\sin^2(x)}=\frac {\sin(x)}{1-\cos^2(x)}$$
Comment: Merci bien pour le conseil !
Comment: If I may ask, where are you located ? I am in Pau. Cheers :-)
Comment: Je suis francais et je me trouve en Saône et Loire.D'ailleurs, je vous avais écris au sujet d'une publication sur Vixra << values of barnes function >>. C'est moi !
Comment: @Dens. NIce to see you again ! Sorry for not remembering (age problem !!!). Cheers :-)


Does the same key have both major and minor pentatonic notes?

Question: When guitarists (or musicians for that matter) talk about keys.
For example they say that they are in the key of A. Does it mean it could be either A major or A minor or both?
Another example: Some guitarist teaches the E minor pentatonic scale to some beginner. It's a continuation of learning the 12 bar blues in the key of E. So he's going to learn the scale that he can use to start improvising guitar solos in that same key.
Here he uses the words: "same key". He learned E major first, then he's going to learn E minor, but the teacher say that its the same key.
Would this mean that the key of E can contain notes from both E and Em? But its a bit confusing because I heard that with the Circle of fifths the same notes in E major are D-Flat minor, A Major has same notes as F#-minor and so on. How does these things relate to eachother when talking about keys? I think I need some extra push to understand what musicians mean when they talk about keys. Thank you.
Answer: In naming keys, "major" is often omitted, so "in A" normally means "in A major."  I could imagine someone saying "in A" to mean "A minor" in informal usage, but only if the context makes it clear that the key is A minor rather than A major.
The key (apologies) to understanding E major and E minor as the same key is the blue note.  If the third scale degree is sliding around a bit, it could be a major third or a minor third, or even both at the same time.  It's ambiguous.  The same is true of the seventh degree (which is also, of course, the third of the dominant chord).
This ambiguity is often realized by playing the tonic major chord but using the minor third in the melody, or indeed in the guitar solo.  As the Wikipedia article notes, the blue note is usually thought of as slightly lower.  Pianos can't do "slightly lower," so pianists often just play the minor third, or even the major and minor third simultaneously.  With the guitar, on the other hand, you can bend the pitch up rather easily, so if you want a pitch between the minor third and the major third, you play the minor third and possibly bend it sharp.

Would this mean that the key of E can contain notes from both E and Em?

Well yes, any piece in any key can contain all 12 tones.  Key is a subtle concept.  The most important thing with a key is the tonal center: A, E, or whatever.  The second most important thing is the third degree of the scale: major or minor.  But saying that a piece is in E major doesn't mean that G natural is forbidden, nor must a piece in E minor avoid G sharp.  Using the note that is nominally "out of the key" provides color (hence the term "chromatic").  Blues-scale guitar solos are a well known example of that.
Comment: That's not the blue note. In E, it's sharp from G and flat from G#. Plus there's B♭ and another between C# and D that's less common. That's a distraction; there's not much about the difference between the major and minor scales that needs to consider the blue third. Otherwise, pretty good.
Comment: In key E minor, G# is *normally* avoided, as it just doesn't fit well. The 'blue' notes are b3, b5 and b7.
Comment: @DaveJacoby are you seriously suggesting that, for example, the G flats in [Piano Red's rendition of Shake, Rattle, and Roll](https://youtu.be/y81Tl4M5vzE) are not blue notes?  What are they then?  And I am not bringing up the blue note to explain the difference between the major and minor scales, but rather to explain why one would use the E minor pentatonic scale for a solo in E major.
Comment: @Tim the _first_ piece in E minor I found from a very casual search has a G sharp in its _second_ measure: [Bach's suite BWV 966](https://youtu.be/jtdZSYXR-00).
Comment: @Tim, within delta. You can hear the blue third as the "Spoon" in "Spoonful" by Howling Wolf.
Comment: @phoog. I'm hearing a guitar, a piano, a bass and a singer, and while you can play hella bluesy on piano, you don't get the blue third on a reasonably-tuned piano. Everyone else? Sure.
Comment: A challenge, diving deeper into the blue third discussion I should really make a specific question for: play the fourth fret harmonic on the low E string. It _should_ be a G#. Find that note on the high E. It's flatter than the fourth fret G#, but much sharper than the G one fret down. The "in-tune" pre-12TET note is the blue note.
Comment: @DaveJacoby you are confusing tuning with function.  You also can't get a proper major third on a piano, but people still use the term "major third" to refer to the interval on the piano.  Also consider ["It has recently been found empirically to center at 6/5...\[and\] is commonly slurred with a perfect third at 5/4.... This bending or glide between the two tones is an essential characteristic of the blues,"](https://en.wikipedia.org/wiki/Blue_note) and then note how you can see his finger grabbing the G flat and then slipping to the G when he plays an E-flat major arpeggio.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/131363/discussion-between-phoog-and-dave-jacoby).
Comment: That G# is part of a chromatic passage, and occurs on an unstressed part of the bar! I keep saying that *any* note can fit anywhere in any key. That's almost it. However, since it's purely non-harmonised anyway, who's to say the piece didn't morph momentarily into the parallel major key? What I'm saying, from 60 yrs playing experience of Blues (the subject matter) is that G# is an avoid note  in Em - except maybe where the harmony moves to Am, played to get there. And - Bach didn't play Blues - did he..?
Comment: @Tim the statement "nor must a piece in E minor avoid G sharp" is general.  It's not intended to apply to the blues!  It's a statement in service of the notion that any note can be used in any key, to illustrate the common confusion we see here between the concepts of _key_ and _scale._  It's certainly not intended to exclude the possibility that using some specific note might be unstylistic in a specific style.
Answer: For starters, D♭ minor does not have the same notes as E major - C♯ minor does. E major and C♯minor both have 4 sharps - D♭ minor has only flats.
On to the question.
When improvising in E major - (not Em), then notes from both E pent. major and E pent. minor are often used - good players will incorporate both sets of notes (and any of the other notes which don't belong as well !)
So, when saying 'E', it will usually mean both pent. sets of notes - from a good teacher.
Comment: I wonder whether it more common in the blues than in other genres to omit the "major" or "minor" designation specifically because of the ambiguity between major and minor that is created by the blue notes, or in other words because of the fact that you can use both the major and minor pentatonic scales.
Comment: I'm sure it is. The underlying harony will be major or minor, but the notes used (except that one!) will be from both parallel keys. It's what Blues players do.
Comment: The typical blues is more on the major side than the minor, and typically this would be expressed by chordal accompaniment sticking more to major flavour, with the ambiguous/minor tonalities superimposed in melodic or lead parts. Specifying a minor key is useful to indicate a *strictly* minor tonality, where major notes would be avoided - this is found less in Delta blues and more in the jazz side, e.g. tunes like "St James Infirmary", or later electric blues like BB King "The Thrill Is Gone".


Como ler arquivo CSV do sdcard?

Question: Atualmente eu leio um arquivo csv da pasta assets com o código a seguir:
    String arquivoCSV = "clientes.csv";
    AssetManager manager = context.getAssets();
    InputStream inputStream = null;

    try{
        inputStream = manager.open(arquivoCSV);
    }catch (IOException e){
        e.printStackTrace();
    }

    BufferedReader buffer = new BufferedReader(new InputStreamReader(inputStream));

Porém eu preciso atualizar esse arquivo constantemente, e pela pasta assets não é possível, preciso ler o arquivoCSV do sdcard, alguém tem alguma idéia de como fazer?
Utilizei o código, porém agora ele não identifica nenhuma linha, segue o código:
    File path = Environment.getExternalStorageDirectory();
    File file = new File(path, "/produtos.csv");
    FileInputStream fileInputStream = new FileInputStream(file);

    BufferedReader buffer = new BufferedReader(new InputStreamReader(fileInputStream));
    String line = "";
    conn.beginTransaction();
    conn.delete("PRODUTOS", "1", null);
        try{

            while ((line = buffer.readLine())!= null){
                String[] colunas = line.split(",");
                    if (colunas.length != 6){
                        Log.d("CSVParder","Ignorando linhas ruins");
                        continue;
                    }
                ContentValues cv = new ContentValues();
                cv.put("COD_PRODUTO",colunas[0].trim());
                cv.put("NOME",colunas[1].trim());
                cv.put("DESCR",colunas[2].trim());
                cv.put("GRUPO",colunas[3].trim());
                cv.put("SUBGRUPO",colunas[4].trim());
                cv.put("MEDIDA",colunas[5].trim());

                conn.insert("PRODUTOS",null,cv);

            }

        }catch (IOException e){
            e.printStackTrace();
        }
    conn.setTransactionSuccessful();
    conn.endTransaction();
    Toast.makeText(context,"Produtos atualizados com sucesso!",Toast.LENGTH_LONG).show();

Comment: Tenta Alterar o seu while para este     while ((line = buffer.readLine())!= -1) {
// intrução }     Creio que funcione
Comment: Não tem como, String comparar com int, na verdade acho q não está conseguindo ler nenhuma linha pois no log está dando muitas CSVParder","Ignorando linhas ruins" e o bd está vazio!
Answer: Olá,
Basta voce criar um tipo File e depois passa-lo ao FileInputStream
Desta forma:
File path = Environment.getExternalStorageDirectory();
File file = new File(path, "path/clientes.cvs");
FileInputStream fileInputStream = new FileInputStream(file);

Comment: Utilizei o código, porém agora ele não identifica nenhuma linha, segue o código:
Answer: Funcionou perfeitamente, meu csv que estava corrompido. Obrigado!
File path = Environment.getExternalStorageDirectory();
File file = new File(path, "/produtos.csv");
FileInputStream fileInputStream = new FileInputStream(file);

BufferedReader buffer = new BufferedReader(new InputStreamReader(fileInputStream));
String line = "";
conn.beginTransaction();
conn.delete("PRODUTOS", "1", null);
    try{

        while ((line = buffer.readLine())!= null){
            String[] colunas = line.split(",");
                if (colunas.length != 6){
                    Log.d("CSVParder","Ignorando linhas ruins");
                    continue;
                }
            ContentValues cv = new ContentValues();
            cv.put("COD_PRODUTO",colunas[0].trim());
            cv.put("NOME",colunas[1].trim());
            cv.put("DESCR",colunas[2].trim());
            cv.put("GRUPO",colunas[3].trim());
            cv.put("SUBGRUPO",colunas[4].trim());
            cv.put("MEDIDA",colunas[5].trim());

            conn.insert("PRODUTOS",null,cv);

        }

    }catch (IOException e){
        e.printStackTrace();
    }
conn.setTransactionSuccessful();
conn.endTransaction();
Toast.makeText(context,"Produtos atualizados com sucesso!",Toast.LENGTH_LONG).show();

Comment: Se possível marque como respondido para fechar o tópico, e dar uma ajuda ;)

Como ler arquivo CSV do sdcard?


Infinite product of sinc function

Question: Is there a closed form for this infinite product? :
$$\prod_{n=1}^{\infty}\operatorname{sinc}\left(\frac{\alpha}{n}\right)$$
where $\operatorname{sinc}(x)=\sin(x)/x$ is the familiar "sinc" function and $\alpha$ is some real parameter.
I would be rather surprised there is, but nevertheless ...
SIDE NOTE : I perform a numerical analysis and my guess for its taylor series in terms of $\alpha$ upto second power may be : $1-\alpha^2\zeta(2)/6$
Comment: See the proof of theorem $1$ here http://www.thebigquestions.com/borweinintegrals.pdf
Answer: Since
$$\frac{\sin x}{x}=\prod_{n\geq 1}\left(1-\frac{x^2}{\pi^2 n^2}\right) $$
we have:
$$ \log\text{sinc}(x) = -\sum_{n\geq 1}\sum_{m\geq 1}\frac{x^{2m}}{m\pi^{2m} n^{2m}}=-\sum_{m\geq 1}\frac{\zeta(2m)}{m\pi^{2m}}x^{2m}$$
and

$$ \sum_{n\geq 1}\log\text{sinc}\left(\frac{\alpha}{n}\right) = -\sum_{m\geq 1}\frac{\color{red}{\zeta(2m)^2}}{m\pi^{2m}}\alpha^{2m}.$$
Answer: If you are familiar with Fourier transforms, you can interpret this product as the iterated convolution of the fourier transform of the sinc function, which is a constant function on an interval, and 0 outside of that interval. Furthermore if we interpret this function as a probability density function of a random variable (uniform probability distribution), and that convolution of density functions correspond to the density function of the sum of the random variables and also remember https://en.wikipedia.org/wiki/Law_of_large_numbers this will approach a normal distribution for any function that is "nice enough", and certainly a uniform distribution is nice enough for that.
Comment: Actually yes, exactly you have said, that should had been my attempt (long ago) to "prove" Basel problem, which has turned up to be a complete "fiasco", since I cannot "invert" the characteristic function - this way the resulting product to be inverted. Although, it can be partially "resolved" using probabilistic approach like this one using another distribution, namely Laplace will do the work - I wrote an answer few days ago (link bellow) so you can check If you and I ment the same :

link : http://math.stackexchange.com/a/1833829/240067
Comment: It's not a fiasco - it's just the phenomenon that the ones that are fast to accomplish anything tend to get more attention than the ones who do the thorough work.

Infinite product of sinc function


Hiding language names in "Language switcher" block and displaying only country flags

Question: I would like to hide language names (like "English", "Español", "Magyar", etc.) in the "Language switcher" block, and display only country flags, because I have Language icons module installed, and the flags are unambiguous enough for navigating between different languages.
I already set language elements to be displayed in an "inline" style and hide language switcher block's title in my stylesheet file (in a Zen sub-theme) like this:
#block-locale-0 li{
    display:inline;
    list-style-image: none;
}
#block-locale-0 .title{
    display:none;
}

Answer: OK, in the meantime I found the perfect solution which I earlier just simply overlooked: there's a really simple configuration option in Language icons module's settings in http://<yoursite>/admin/settings/language/icons (D7: http://<yoursite>/admin/config/regional/language/icons) .
You have to set "Icon placement" option from "Before link" or "After link" to "Replace link", which results in displaying only the country flags.
Here are some screenshots (on the admin site I'm currently using RootCandy Dark):
BEFORE:

AFTER (on the admin site):

AFTER (on the main site's right sidebar [design is strongly under development :P]):


What is good software to do basic network administration with windows computers

Question: I manage IT for a small business with a couple locations (about 10-15 computers each). Mostly users just use online services but there are a couple desktop applications they need and at each site there is a common network share of files that they access. Up till now I have not setup a server (except for the common shared folder on one regular win7 computer at each site). I create an Admin and GeneralUser account on each computer since we don't have any need to give each user an account. So far this has worked alright. They login have a network share, go online and that's most of what they need.
We will be opening more sites and more computers. Therefore the basic setup/configuration stuff is getting too much to do on each computer (Setting up user accounts on each computer, installing software such as chrome on each computer, setting the default home page in the browsers, mapping a network drive, etc.)
My question: What is a good approach to managing this? The Windows server website is confusing and they have too many services to easily decide what will work. Will Small Business Server do these things? Is there better sotware to accomplish the same thing? Online servies would be even nicer since I have multiple physical sites, but am not familiar with any?
Comment: possible duplicate of [Active Directory explained](http://serverfault.com/questions/18339/active-directory-explained)
Answer: Oh, dear God in heaven.
First off, you're not talking about network administration, (which deals with network gear - switches, routers, firewalls, APs, etc.) although that's probably something you need as well.
What you're talking about is server administration/Windows administration, and I can sense you're pretty far out of your depth, no offense.  What you really need to set up is a domain of some sort, most likely a Windows domain, using Active Directory.
This is not a trivial task, though installing the services/"roles" and creating a domain controller are pretty easy, it requires at least some planning and design to make sure it's not a train wreck from the get-go.  Might want to consider contracting a consultant to get that off the ground for you, ideally one who's got his MCITP certification for Active Directory. (MCITP: Enterprise Administrator level, or whatever the hell test number that is.)
Comment: I actually read your "Oh, dear God in heaven" before the question... and from there on I already knew where the question was going. Sadly, I was *not* wrong.
Answer: What you need is called an Active Directory domain. The most basic description that can be given of it is along the lines of "a distributed database which manages user accounts and policies across multiple computers, letting you administer them globally without the need to manually perform the same tasks on each single one, and with much better security". Of course, there is much more to it than this, but it's something good enough to start with.
While setting up a basic domain is not difficult at all, setting it up properly can get tricky, especially in a multi-site environment like yours. It can also (and should) involve multiple servers performing the role of domain controller, i.e. managing the domain operations and the user database; the bare minimum needed is a single server, but you'll want at least two of them for redundancy, and probably many more, because a standard setup for a multi-site environment involves at least one server per site.
There are literally tons of documentation around about Active Directory, as each and every aspect of Windows administration revolves around it; I strongly suggest you buy a book or two about Windows administration, and go on from there; I also strongly suggest you hire a consultant, because he'll be able to help you setting all up properly, giving you advices on design issues that you may not even know exist at all.
This is where everything starts:
http://technet.microsoft.com/en-us/library/cc731053(v=ws.10).aspx
Answer: If you want to set up basic directory and group policy services, Windows Server Standard Edition would probably fit your bill. You could also look at Small Business Server 2011 Essentials. But I stress that these servers must be configured and deployed properly. I don't mean this disrespectfully, but it sounds like you have little or no Windows server experience. You should strongly consider learning about Windows server before deploying it to your clients. A poorly configured server is a management, security, and performance headache.
Answer: I'm going to venture outside the "standard" reply and guess that what you need may be less a "centralized infrastructure" (single domain) and more of a centralized management tool.
You might have a look at something like Italc.  http://italc.sourceforge.net/  It provides you a central command/control console, a singular view of your PC fleet.  You'll still have to treat each PC individually, but you can do it all from one place both in the geographical and logical sense.
And it's free...


i need to given state and district details in same select box with ngFor angular 5

Question: This is my json value,
{
"location": [{
        "state": "state1",
        "cities": [{
                "city1": "city1"
            },
            {
                "city2": "city2"
            }
        ]
    },
    {
        "state": "state2",
        "cities": [{
                "city1": "city1"
            },
            {
                "city2": "city2"
            },
            {
                "city3": "city"
            }
        ]
    }
]

}
sample output in select box:
state1 - state name - parent
city1  - city name - child
city2

state2 - state name - parent
city1 - city name - child
city2
city3
    <select>
      <option *ngFor="let locations of location">
        {{locations.state}}{{locations.cities.citiname}}
      </option>
   <select>

it is not multiselect. it is like grouping by state under cities.
Thanks in advance.
Answer: You can use optgroup attribute for select element.
<select>
  <optgroup *ngFor="let location of locations" [label]="location.state">
    <option *ngFor="let city of location.cities">{{Utils.keys(city)[0]}}</option>
  </optgroup>
</select>

Typescript
Utils = {
     keys : Object.keys
}

You cannot use directly Object.keys because Object is a part of window/global and angular cannot evaluate that expression.
Comment: Thanks for your answer. i will check
Comment: i got it.  i got error "key is not defined"  but i populated my cities value directly.it is solved. again Thanks.


Dell PowerEdge 2900: raid/Linux conversion logistics

Question: I've got a Dell PowerEdge 2900 (currently running windows) that I want to convert into a Linux server.  But, it's got a hardware RAID controller and I want to be sure I don't destroy the configuration utility.  When it boots, I can currently (when prompted) hit CTRL-R and it launches a raid config utility:
<code>PERC 5/i Integrated BIOS Configuration Utility 1.02-0007
</code>
Where is this utility located (Disk vs BIOS)?  If it's on disk, what's the best way to keep that functionality available post-linux install?
Comment: Does this RAID card have battery backup?  If not, you're better using software RAID...
Answer: The pre-boot RAID BIOS is embedded into the RAID card. It's completely OS-independent.
Comment: @Gus the RAID-controller needs to map into BIOS so you can boot from a raid-device. Apart from that the configuration is stored in NVRAM of the controller AND in every disk.
Comment: Great; thanks for the swift response.  It sounds almost silly to ask that question since it says "BIOS" in the name, but I seem to remember being bitten once by a raid config utility living on the disk once, and once it's gone, it'd be painful to get back.


tvOS System UIButton parallax effect

Question: I have a UIButton and a UIImageView with an image on the first view of a tvOS app.   It's a system UIButton with no image associated with it, and the app is Objective-C.
I've looked all over the place, but can not figure out why it's not getting a parallax effect on the UIButton.   The button itself works fine, and animates a press when I press the controller, and segues as expected.
Am I incorrect in assuming it's supposed to have a parallax effect by default?  Am I supposed to add this myself?
Any pointers would be greatly appreciated.
Comment: Custom `UIButton`'s do not get the *free* effects that a system button gets. You have to create these effects yourself.
Comment: Here's an example of how to implement the effects yourself: http://stackoverflow.com/a/35206995/2108547
Comment: We created controls and extensions that can be used to easly add parallax effect to any UIView https://github.com/PGSSoft/ParallaxView
Comment: just for anyone coming to this very old question!  what Daniel said above @DanielStorm is no longer true, it's now built in.  simply set `.imageView?.adjustsImageWhenAncestorFocused = true`
Answer: For 2022. Fortunately it's now trivial.
1, In storyboard have a normal UIButton. In the attributes inspector of the button, just select the image as normal from the drop-down. That's it.

Use one of your own images (i.e., a photo of a cat, etc)
or just use one of the SFSymbols if you want.
It makes no difference if the button is set to system, custom, etc. Use any settings you wish.

2, Then you must do this in code:
<code>thatButton.imageView?.adjustsImageWhenAncestorFocused = true
</code>
It's annoying but you cannot do (2) on storyboard. You have to add a line of code. It's just how it is.
(Of course, often you would just do it in your button subclass, either way.)
However ...
Be aware that you will still suffer the weird scaling problem with images in tvOS. When using adjustsImageWhenAncestorFocused, they really won't scale properly for you.  contentMode is ignored.
Multilayer image ...
If you want to have an actual parallaxing image. It's easy. Make an image stack. You have to put in at two layers minimum. Note that you don't have to have three unless you want to. For a simple test just have the rear one as "a black rectangle" and the middle one as your normal PNG image of your logo or whatever.
In step "1" above just select that image stack ("image stacks" are just images, they are listed the same).
Note that you absolutely do not have to have an image stack. It's completely normal to just have "a plain image". Note that for example, many of Apple's own buttons are, simply, a PNG and not an image stack.  For example the "controls" one (with the gears) is an image stack. But many are just plain flat PNGs, no parallax.

tvOS System UIButton parallax effect


How do I get a user's private message channel in Discord.py?

Question: I need to get a user's PM channel to see the messages my bot has previously sent to that user. I already have their User object from a command message in a standard channel.
This is what I've tried so far:
@client.event
async def in_msg(msg):
    user = msg.author
    privateChannel = client.get_channel(user.id) # not working
    if privateChannel is not None:
        await doSomethingWithChannel(privateChannel, user)
    else:
        privateChannel = await client.start_private_message(user)
        await firstMessageToUser(privateChannel, user)

However, it seems like a user's DM channel is not related to their user id. What should I do now?
Answer: There isn't any simple way to do this currently. There might be plans for a user.dm_channel in a newer version, but for now we have to make do with looping through client.private_channels and looking for the user:
@client.event
async def in_msg(msg):
    user = msg.author
    for ch in client.private_channels:
        if user in recipients and len(recipients) == 2:
            await doSomethingWithChannel(ch, user)
            return
    # user doesn't have a PM channel yet if we got here
    ch = await client.start_private_message(user)
    await firstMessageToUser(ch, user)

Answer: your user object itself becomes the destination for pm.
So,  privateChannel = user
Comment: you cannot get channel history from a user object


imprimir a mesma variavel em dois lugares diferentes

Question: Estou com um problema que é o seguinte.
Estou querendo fazem uma ficha na qual você escreve nome, telefone, problema, etc
e ai então as informações preenchidas são imprimidas em uma mascara padrão.
Porem eu preciso que aparece a mesma informação em duas mascaras diferentes, no caso colocar a mesma variável em dois lugares distintos. ai esta o código inteiro caso possam me ajudar.

    <title>Teste</title>

    Nome <input id='nome' type='text' value='' onkeyup="insere()" />
    Cont 1 <input id='fixo' type='text' value='' onkeyup="insere()" />
    Cont 2 <input id='contato' type='text' value='' onkeyup="insere()" />
    Problema <input id='problema' type='text' value='' onkeyup="insere()" />

problema continua

Cliente:

       Contatos: \

       descrição do problema:

problema resolvido

Cliente:

       Contatos: \

       descrição do problema:

Comment: Você tem mais de um elemento com o mesmo id, o que é uma péssima prática. Desse jeito, quando você faz a seleção pelo id é retornado apenas o elemento da primeira ocorrência.
Answer: Como já foi dito você está repetindo ids é isto é uma má prática, você pode colocar ao invés de id uma class para os elementos e pegar o valor pelo índice do mesmo:

var cliente = document.getElementById('nome');
var fone = document.getElementById('fixo');
var contato = document.getElementById('contato');
var problema = document.getElementById('problema');

var cliente1 = document.getElementsByClassName('cliente')[0];
var cliente2 = document.getElementsByClassName('cliente')[1];

var tel1 = document.getElementsByClassName('tel')[0];
var tel2 = document.getElementsByClassName('tel')[1];

var cont1 = document.getElementsByClassName('cont')[0];
var cont2 = document.getElementsByClassName('cont')[1];

var pro1 = document.getElementsByClassName('pro')[0];
var pro2 = document.getElementsByClassName('pro')[1];

function insere() {

  if (cliente.value !== '') {
    cliente1.innerHTML = cliente.value;
    cliente2.innerHTML = cliente.value;
  }

  if (fone.value !== '') {
    tel1.innerHTML = fone.value;
    tel2.innerHTML = fone.value;
  }

  if (contato.value !== '') {
    cont1.innerHTML = contato.value;
    cont2.innerHTML = contato.value;
  }

  if (problema.value !== '') {
    pro1.innerHTML = problema.value;
    pro2.innerHTML = problema.value;
  }

}
Nome <input id='nome' type='text' value='' onkeyup="insere()" /> Cont 1 <input id='fixo' type='text' value='' onkeyup="insere()" /> Cont 2 <input id='contato' type='text' value='' onkeyup="insere()" /> Problema <input id='problema' type='text' value=''
  onkeyup="insere()" />

 problema continua

  Cliente:

  Contatos: \
  descrição do problema:

 problema resolvido

  Cliente:

  Contatos: \
 descrição do problema:

Comment: cara muito obrigado bela ajuda, sou iniciante nisso então estou vivendo e aprendendo kkk...


Is there any default java class for a Popup JDialog?

Question: I have been using this code to implement a Popup JDialog of sorts, like what you see when your anti-virus is scanning your system or updates itself:
import java.awt.*;
import javax.swing.JDialog;
import javax.swing.JLabel;

public class PopupDialog extends JDialog {

    public PopupDialog() throws HeadlessException {
        createUI();
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                PopupDialog popupDialog = new PopupDialog();
                popupDialog.setVisible(true);
            }
        });
    }

    private void createUI() {
        setTitle("Popup Dialog");
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

        addComponentsToFrame();

        //This call will give screens viable area, which takes into account the taskbar, which could be at the bottom, top,left or right of the screen.
        Rectangle maxBounds = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();

        //get screen size
        int sWidth = maxBounds.width, sHeight = maxBounds.height;

        setSize(275, 225);//set frame size
        Dimension appDim = getSize();
        //get app size
        int aWidth = appDim.width, aHeight = appDim.height;

        //set location like a tooltip would be except its a custom dialog like an AV
        setLocation(sWidth - aWidth, (sHeight - aHeight));
    }

    private void addComponentsToFrame() {
        JLabel label = new JLabel("Popup Dialog");
        getContentPane().add(label, BorderLayout.CENTER);
    }
}

But my question is: is there any class or package in java that will do this for me?  and if not how would I go about allowing the JDialog to slide up from the taskbar (or offscreen)? or somehow become visible in a slow manner like a ToolTip Popup would from the system tray. Thanks.
EDIT The reason i want to use a JDialog or Frame is because i want to be able to fully skin the Popup window, using setUndecorated(true); and adding custom exit icons, backgrounds etc
Answer: You mean like the examples here: http://docs.oracle.com/javase/tutorial/uiswing/misc/systemtray.html ?
Comment: No problem, if you're really keen on it, you might consider sharing your result by results via an open source library. I think others will be really happy to get their hands on something like that.
Comment: Sorry, none that I know of till now. However the guy here managed a nice translucent effect, and if you scroll down you might see some others suggested 2-3 libraries: http://stackoverflow.com/questions/3240415/how-to-create-a-notification-in-swing
Comment: I know how to do a system tray, however i want to be able to customize it as if it was a frame, i.e add a button and labels etc., however, i do want the ability of the slow 'Popup' of the tooltips provided by the system tray. Basically i want a frame because i will be able to skin it comletely. i.e undecorated and add labels with images for the exit icons etc
Comment: ThanksThat really helped, I guess I'll have to do it manually :( lol
Comment: Hehe yeh maybe I will do that. Thank you for your help!
Answer: First, you can make your frame be always on top, this will ensure it is always visible.  Next, you could position the frame off the bottom of the screen and slide it up programmatically. This should be fairly smooth even on an older XP machine.  There is no standard Java API to do this but you can do it yourself pretty easily.  Another option instead of sliding is to make the window fully transparent and fade it in.  This API was added in recent (last 2 years) Java 6 updates, so it should be available everywhere.


Submit ao digitar no input tipo texto para o codigo php na mesma pagina

Question: Teria alguma forma de ao digitar o formulário vai enviando os dados para o código PHP sem ter de apertar o submit, simplesmente digitando na entrada de texto?
<form method="POST" action="">
  nome:
  <input type="text" name="Pesq" placeholder="Digite o nome">

  <input name="EnviarPesq" type="submit" value="Pesquisar">
</form>

<?php

    $EnviarPesq = filter_input(INPUT_POST, 'EnviarPesq', FILTER_SANITIZE_STRING);
    if($EnviarPesq){
        $Pesq = filter_input(INPUT_POST, 'Pesq', FILTER_SANITIZE_STRING);
        $itens_coletados = "SELECT * FROM tabela WHERE nome LIKE '%$Pesq%'";
        $resultado_de_itens = mysqli_query($conexao, $itens_coletados);
        while($exibir_itens = mysqli_fetch_assoc($resultado_de_itens)){
            echo "id:" . $exibir_itens['id'] . "
";
            echo "nome" . $exibir_itens['nome'] . "
";
            echo "
";
        }
    }

?>

Comment: Tem, mas não da maneira que provavelmente você pretende. Leia sobre AJAX (inclusive aqui no site tem bastante conteúdo)
Comment: De uma olhada [aqui](https://pt.stackoverflow.com/questions/180156/como-buscar-valores-em-um-arquivo-php-com-jquery-ajax), tem esse tutorial [aqui](https://www.gigasystems.com.br/artigo/35/pesquisa-dinamica-com-ajax-banco-de-dados-e-php) que pode ajudar também.
Comment: pode usar o evento `onchange` do input onde é digitado o nome e ir executando o código no `php` através de uma chamada `Ajax`
Comment: no caso seria algo parecido com isso então:      $.ajax({
        url: $(this).attr('action'),
        type: $(this).attr('method'),
        data: $(this).serialize(),
        success: function(l) {
        }
    });
Answer: Pode usar um evento oninput no campo e ir chamando o Ajax à medida que vai digitando no campo. Porém, eu sugeria incluir o Ajax numa função setTimeout com um pequeno intervalo (no meu exemplo eu coloquei 1000 milissegundos = 1 segundo), para que dê tempo do Ajax "respirar" antes de enviar uma nova requisição.
Incluí também duas linhas para abortar a última requisição do Ajax e apagar o setTimeout enquanto se está digitando de forma rápida:
if(AJAX) AJAX.abort();
clearTimeout(delay);

Isso é interessante porque cancela as requisições anteriores enquanto se digita no campo. Isso poupa o servidor de requisições excessivas, pois ao meu ver, o que importa é o resultado quando o usuário para de digitar por um breve intervalo.
Crie uma div após o formulário para receber os dados vindos do Ajax:
<form method="POST" action="">
    ...
</form>

O script completo fica assim (veja no código as explicações):
var delay, AJAX; // declaro a variável do temporizador e do Ajax
$("[name='Pesq']").on("input", function(){ // captura digitação no campo

   if(AJAX) AJAX.abort(); // cancela o último Ajax, se existir;
   clearTimeout(delay); // apago o temporizador, para não criar um em cima do outro

   if($(this).val()){ // só chama o Ajax se o campo não estiver vazio
      delay = setTimeout(function(){ // redefino o temporizador
         console.log("enviando ajax...");
         AJAX = $.ajax({
            url: $("form").attr('action'),
            type: $("form").attr('method'),
            data: $("form").serialize(),
            success: function(data){
               $("#pesquisa").html(data); // altero o conteúdo da div com o resultado
            }
         });
      }, 1000);
   }else{
       $("#pesquisa").empty(); // esvazia a div caso o campo esteja em branco
   }
});

E o PHP?
Sugiro criar um PHP próprio para isso (digamos, pesquisa.php) e colocar apenas o código que faz a pesquisa e o retorno nesse arquivo (claro, incluindo também o código que faz a conexão com o banco de dados através da variável $conexao):
<?php

    // inclua aqui a conexão com o BD

        $Pesq = filter_input(INPUT_POST, 'Pesq', FILTER_SANITIZE_STRING);
        $itens_coletados = "SELECT * FROM tabela WHERE nome LIKE '%$Pesq%'";
        $resultado_de_itens = mysqli_query($conexao, $itens_coletados);
        while($exibir_itens = mysqli_fetch_assoc($resultado_de_itens)){
            echo "id:" . $exibir_itens['id'] . "
";
            echo "nome" . $exibir_itens['nome'] . "
";
            echo "
";
        }
?>

Não esqueça de incluir a página no action dor formulário. Ex.: action="pesquisa.php".
Comment: Cara, ficou muito top esse código
Comment: Vlw! Mas fiz uma pequena alteração. Acho que não precisa daquela parte `var form = $("form");`
Comment: Tem mais uma coisa que faltou na parte do PHP, tem que tirar a variável `$EnviarPesq` e sua referencia e a condição no `if` que pega ela, porque não existe mais o botão, do contrario não funcionará.
Comment: Bem observado. Mas era só pra ter uma ideia mesmo. :D
Comment: Mas e se no caso eu depois que eu escrevesse e resolvesse pagar tudo no input, como faria para zerar o'que foi escrito na `div`?
Comment: pode fazer um `else` nesse `if($(this).val()){`, tipo: `}else{ $("#pesquisa").empty(); }`
Comment: Deu certo, eu já estava pensando em mexer na parte do `php` kkk, obrigado pela explicação!


Multiple Bind and base DNs in ldap.conf

Question: I have multiple LDAP servers and different user groups in each. I want to authenticate using both LDAP servers which have different base DNs.
Is it possible to put in multiple bind and base DN values in ldap.conf?
Answer: No. At best, you could split off authentication to one server and your NSS lookups for users and groups to another server.
The only way to have a "meta database" that consolidates the information of both is to actually maintain one. You must sync data from one server to the other, or set up a third server that replicates the necessary trees from the two other servers.
Comment: Hi @andrew-b. How do you split off authentication and the NSS lookups. I do not quite get the picture.
Comment: @Carlo That's a different question than the one you were asking and the answer is not simple. Please submit a new question.
Comment: Hi @Andrew. I've already created a question and here is the link: http://serverfault.com/questions/521800/split-authentication-and-nss-lookups-for-users-and-groups-to-different-servers

Thank you very much for the response.

Multiple Bind and base DNs in ldap.conf


How can I create a DTAQ in one of two different libs, controlled by the jobs liblist?

Question: On our as/400 we have a test environment and a productive environment. Once we tested our programs are working, we can put them in the productive environment. Both environments contain a similiar set of libraries.
The basic mechanism to tell our programs, in which environment they work, are liblists used for the jobs they run in. That works great, for some things, but for others it doesn't. Therefore we often have a parameter passed to the programs on job submission, that tells the program to work in either test or productive environment. That annoys the hell out of me, since my programs always have to carry this parameter throughout their whole execution time, and often even pass it on to other programs. Sometimes the initial program does not even need the information itself, but still has to take it as a parameter, because it calls a program that does need it.
To present the specific problem I am faced with:
Communication between individual parts of a bigger process is often done via dataqueues throughout our sytem. Reading a specific DTAQ according to the liblist works like a charm, simply call RCVDTAQ on the DTAQ's name, the liblist takes care of choosing the right lib. Same goes for writing into DTAQs.
But sometimes the program has to create a new DTAQ before listening or writing to it. Now that does not work with our layout and the liblists. Think of it like this:
PROD-liblist:
PPGMLIB1
PPGMLIB2
PDFILELIB1
PDTAQLIB1
P...
...

TEST-liblist
TPGMLIB1
TPGMLIB2
TDFILELIB1
TDTAQLIB1
T...
...

Now my program should create the DTAQ in ?DTAQLIB1, where ? should be either P or T.
My first idea would be to go through the liblist and look for the entries PDTAQLIB or TDTAQLIB, and take whichever comes first -- but than I couldn't figure out how to to that (hence my connected question: How can I read the liblist from within an ILE-Program? (preferably RPG or CL)).
I know I could possibly achieve my goal by checking, which user owns the current job, but that would break our logic of selecting the libs by liblists (like our current workaround does).
Is there anything I'm missing? Some special way to to call CRTDTAQ maybe, or some special api to do this liblist comparison, that I'm trying to write?
Comment: Is the program called out of either PPGMLIBn or TPGMLIBn? And does that always correlate with either PDTAQLIBn or TDTAQLIBn? If so, then the program simply uses the correlated DTAQ library based on where it was called from. Pull the program library from the Program Status DS in RPG.
Comment: @user2338816 I guess that would work in most cases, but not if you wanted to use a program from PPGMLIBn to access a DTAQ from TDTAQLIBn (why ever someone wanted that). The problem I see there, is that it would give you different mechanisms for creating a DTAQ and reading it. You could end up creating a DTAQ outside of your LIBLIST and dumping when trying to read from it with 'object not found'.
Comment: Agreed for potential odd cases. That's why I asked for the clarification on the program library and the correlation, and it could make a difference for such cases. Are you looking for "DTAQ" as a substring in any library in *LIBL?
Answer: Warren's configuration file idea is a good one, but sounds like it would be a lot more than you need.  How about just using a data area?
For example, ensure there is always a data area called MODE in your ?DFILELIB1 library.  It would have just a single character, "P" or "T", for the mode.
Or even simpler (though perhaps less clear): you could test for the presence or absence of a TESTMODE data area, and proceed accordingly.
Comment: Yes, the general configuration data store is probably more than is needed for this particular project.  We have this as general infrastructure for use by all our applications.  Squeezing it in as Maybe its a good candidate for an open source project ;-)  The data queue service information table was put into a recent project, because we recognized that this was a design Pattern that we use repeatedly.  These services have some common configuration needs, so a table with a row for each service was deemed more appropriate, at least for us.
Comment: I really like the idea of the `MODE` dataarea. Sure, there is something new created, but in a way that does not anything existant to be changed. It integrates well with the concept of liblist control, and it is cleaner and more flexible than parsing the liblist for special libs. Also, there is no loop included, but only one clean call to `rtvdtaara` without any lib. You could even extend it to adding a dtaara `DTAQLIB` for direct control over where libs are created.
Comment: Sure a data area is a fine way to store small amounts of configuration data.  But keep it simple. Store the entire library name in the data area.  Retrieve it.  One line of CL. Simple.  Yes, you could have a "neat trick" that works here, in the current scenario, by adding just a little bit more unnecessary code.  But really, why? But everytime you hardcore things, or build in arbitrary limitations, you help lock in the status quo, making it harder to change environments down the line.
Answer: To read the library list in CL, use RTVJOBA.
To read it in ILE RPG, I'd suggest the QUSRJOBI API, format JOBI0700.  http://publib.boulder.ibm.com/infocenter/iseries/v5r4/index.jsp?topic=%2Fapis%2Fqusrjobi.htm
I think your idea of scanning the library list is probably the best one for your environment.
Comment: I still think, this is the only one, where I don't have to introduce something new. But I still think, I will head for @martin's answer (see there for reasons).
Answer: I generally try to avoid hard-coding library names anywhere in my programs.  If you are scanning for specific names or name patterns, this may work fine for now, but what happens down the line when new environments are created, perhaps with a new naming scheme.  Therefore I would store environmental setup as configuration data.
I have two approaches for this.
You can set up a general configuration values table, which can be used by all sorts of programs to look up all sorts of configuration values.  In our shop, we call this our Generic Values file.  It has to main key fields, the first is often used for a program name, and the second for the name of the value being configured.  We also frequently put a table name as the first key, and a column name as the second, each record defining a valid value for the column and a description of it.
Where I am implementing SOA services with Data Queues, I have a table specifically to define information about the service.  This includes information such as library and data queue names, as well as other information used by the client interface, by the job performing the service, or by the job managing my servicing jobs.
In either case, configuration files are in the environment-specific data libraries, with values appropriate for that particular environment.  I have commented SQL script members that contain the INSERTS for all the configuration records, so that a source scan can easily find library or object name references.   I recommend segregating environment specific configuration from other application configuration data that will be tested and moved over to production.
Comment: This is a good approach in general, espacially if you create something new. In my scenario, it does not really fit, since I had to restructure everything, and I don't like forcing collegues to change everything, if not necessarry.


Find all homomorphisms from $A_4, D_{2n}$ to $\mathbb C^\times$

Question: I have a question that how to find all homomorphisms from

dihedral group $D_{2n}=\langle s,r :  s^2=r^n=1 ,  srs=r^{-1} \rangle$ to the multiplicative group $\mathbb C^\times$?
alternating group $A_4$ to the multiplicative group $\mathbb C^\times$?

I came up with a single approach to deal with the problems.

Note that $D_{2n}$ which is generated by $r, s$ so in order to specify a homomorphism from $D_{2n}$ to $\mathbb{C}^*$, we only need to say what happens to each of these elements. Assume that $\phi:D_{2n}\rightarrow\mathbb{C}^*$ is a homomorphism, then $\phi(r)^n=1$, so $\phi(r)= \exp(2k\pi i/n)$, $k=0,\ldots,n-1$, and similarly $\phi(s)=\pm 1$. Thus we have $2n$ options for homomorphism $\phi$.
We know that $A_4=\langle (123), (234) \rangle$ and each of generator has order $3$. Using the similar arguments above we deduce that there are $9$ possible homomorphisms.

Do the above solutions look fine? Please light up my mind by your comments.
Answer: As you figured out, the first part is not quite so simple. Neither is the second part.
Let $\sigma$ and $\tau$ be the two generators of $A_4$ that you mentioned. In particular, note that $\sigma\tau$ has order $2,$ and so if $f:A_4\to\Bbb C^\times$ is a homomorphism, then $f(\sigma)f(\tau)=f(\sigma\tau)\in\{1,-1\}.$ Given the possibilities for $f(\sigma)$ and $f(\tau),$ we conclude that $f(\sigma\tau)\ne-1,$ and so $f(\sigma)$ and $f(\tau)$ must be multiplicative inverses. This leaves $3$ possible homomorphisms $A_4\to\Bbb C^\times$. Checking the two nontrivial possibilities is straightforward.


How long do I have to wait to say with 95% confidence my Poisson-distributed software failure is fixed?

Question: I have attempted to workaround a software issue which has caused intermittent failures twice in a one week period.

Assume the failures are Poisson-distributed.  i.e. $P(X=x)=\frac{e^{-\lambda}\lambda^x}{x!}$ for unknown $\lambda$
Assume an unsuccessful workaround will have no effect on the frequency with which the problem is occurring.
The problem will never re-occur if the workaround is successful.

How long do I have to wait (should no further failures occur) in order to be able to declare with 95% confidence that my workaround is a success?

I think the assumptions I've made are reasonable, and I've got as far graphing possible values of $\lambda$ against their likelihood given the two failures in a week, i.e. $P(X=2)=\frac{e^{-\lambda}\lambda^2}{2}$.  I think the relevant equation for introducing time t is $p(X=0)=e^{-\lambda t}$, but I'm a Software Developer without much of a stats background at all, and now I'm stuck.
Comment: Without some assumption about the value of $\lambda$, it would be impossible to calculate. If you assume $ \lambda =2$, are you looking for the value of $t$ such that $e^{-2t}<0.05$? In which case$t>1.497$
Comment: @DavidQuinn The estimate of $\lambda=2$ is too high.  This should ring alarm bells too, but I'm tempted to pick $0.25$ a lower-bound for $\lambda$ because at that point the probability of it generating my original observation drops below $0.025$.  Then we need t such that $e^{-0.25t} < 0.025$ in which case $t>14.7$ and when I combine my two $0.975$ confidences it comes in just above $0.95$
Comment: Spunds like you need more time to get a sensible estimate for $\lambda$, in which time hopefully you will have solved your software problem once and for all. :)
Comment: @DavidQuinn however much data I collect, there will always remain some uncertainty in the estimate of $\lambda$.  But I've possibly found a way to address this in the answer that I've posted utilizing Bayes theorem?
Answer: I realise that running a simulation is a horrible way of doing mathematics, but I think the answer is 1.7 weeks (standard deviation 0.037).  Programming language is R.
<code>set.seed(1)

getPoissionTime <- function(smallLambda)
{
    count <- 0
    while(rpois(1, smallLambda) == 0)
    {
        count <- count + 1
    }
    count
}

answers <- c()

while(length(answers) < 100)
{
    values <- c()

    while(length(values) < 10000)
    {
        # I guess this is an additional assumption - that prior to observations, all
        # values of lambda were equally likely.
        lambda <- runif(1) * 20

        if (rpois(1, lambda) == 2)
        {
            t <- getPoissionTime(lambda/100)/100
            values <- c(values, t)
        }
    }

    q <- quantile(values, probs=0.95)
    answers <- c(answers, q)
}

print(paste("mean", mean(answers), "sd", sd(answers)))
</code>
I've checked this against @DavidQuinn's example i.e. if I force $\lambda$ to be 2 then the program agrees with him that $t$ is 1.497
Comment: Technically I rounded this the wrong way and should wait 1.8 weeks to be on the safe side.  The real problem with this methodology is that it tries to simulate the observed data, and thus would quickly become unfeasable to run once further observations have been made.
Answer: The Poisson distribution tells us that $P(X=2|\lambda)=\frac{e^{-\lambda}\lambda^2}{2}$.  According to Bayes theorem
$$P(\lambda_i|X=2)=\frac{P(X=2|\lambda_i)P(\lambda_i)}{P(X=2|\lambda_1)P(\lambda_1)+P(X=2|\lambda_2)P(\lambda_2)+...+P(X=2|\lambda_N)P(\lambda_N)}$$
This is the discrete form of Bayes theorem - I'm not going to attempt the integral in the continuous form.  I have used some R code to assist my calculations.
Choose a sample of possible $\lambda$ (note in my sample N=200)
{0.1, 0.2, 0.3... 20.0}
Choose priors for these
{1/N, 1/N, 1/N... 1/N}
Calculate the Poisson probabilities P(X=2|$\lambda$), which will be the likelihoods in the Bayes equation.
{0.0045, 0.016, 0.033... 0.00000041}
Calculating the weighted-sum of the last two sets gives us our denominator
0.050
And complete the Bayesian part of the calculation by dividing each likelihood - again weighted by the priors - by the denominator.  These are our posterior probabilities.
{0.00045, 0.0016, 0.0033... 0.000000041}
Now we can make a series of guesses about the value of t, and use an algorithm such as binary chop to get arbitrarily close to its true value (actually we can't get arbitrarily close with binary chop alone.  Due to errors introduced by sampling, we'd have to make the sample progressively finer too).
Let us suppose t=1.72
The half-life formula tells us that $$p(X=0)=e^{−\lambda t}$$ is the probability of no failure occurring in this length of time.  Calculate it for each $\lambda$ in our sample:
{0.842, 0.709, 0.597... 0.0000000000000011}
Now we can weight these probabilities against the (posterior) probability of each value of $\lambda$ occurring.  This weighted sum is 0.04969, so 1.72 weeks is the answer, because the chance of a failure occurring within that time comes in nicely at just under 5% as required.
It is nagging me slightly that I can't quantify the errors I have created in using a discrete sample, but as I see it, the main problem with this calculation is my choice of priors, and the only way to reduce their influence is by observing more data.  I would welcome your feedback too.
Edit 2016-06-13, added graphs:
Graphs


Modulus and Bound Problem

Question: If $z_0$, $z_1$ $\in B(0,\epsilon)$ where $B(0,\epsilon)$ is a subset of $\mathbf{C}$. Under what condition on $\alpha$ and $\beta$, $\frac{\alpha+z_0}{\beta z_1+z_0}$ would be in $B(0,\epsilon)$?
That is, if $|z_0|<\epsilon$ and $|z_1|<\epsilon$, under what condition on $\alpha$ and $\beta$, $|\frac{\alpha+z_0}{\beta z_1+z_0}|<\epsilon$ ?
Note that, $\alpha$ and $\beta$ and $z_0$ and $z_{1}$ are all complex numbers.
Answer: If I understand your question correctly, it is the following:

Let $\epsilon > 0$ be given.
  For what $\alpha, \beta \in \mathbb C$ does the following hold:
  $$
 \left|\frac{\alpha+z_0}{\beta z_1+z_0}\right|<\epsilon \quad \text{ for all }
 z_0, z_1 \in \mathbb C \text{ with }
 |z_0|<\epsilon \text{ and } |z_1|<\epsilon \, .
$$

First let us assume that $\beta \ne 0$. Then we can choose
$$
  z_0 = \frac \beta n \, , \quad z_1 = -\frac 1n
$$
where $n$ is so large that $|z_0|<\epsilon$ and $|z_1|<\epsilon$.
Then $\beta z_1+z_0 = 0$ so that the fraction becomes infinite.
So $\beta$ must be zero and the fraction reduces to
$$
\frac{\alpha+z_0}{z_0}
$$
which is infinite if $z_0 = 0$ and $\alpha \ne 0$.
Therefore $\alpha = \beta = 0$, which is a (trivial) solution
only if $\epsilon > 1$. For $\epsilon \le 1$ there is no solution at all.

Modulus and Bound Problem


Set the color of the text in the top level mx MenuBar differently than menu Pop Up color?

Question: Is there a way to set the text of the top level MenuBar differently than the color in the popup menu items? In the attached image the color of the text is light gray. This works because the top level menu items, "Menu1" and "Menu2" are over a dark background. In the popup you can hardly read the text so it needs to be set to a darker color. MenuBar has one style called color.

Code:
<mx:MenuBar id="mainMenuBar"
                dataProvider="{new XMLListCollection(menubarXML)}"
                labelField="@label"
                color="red"
                >
</mx:MenuBar>

<fx:Declarations>
    <fx:XMLList id="menubarXML">
        <menuitem label="Menu1" data="top">
            <menuitem label="MenuItem 1-A" data="1A"/>
            <menuitem label="MenuItem 1-B" data="1B"/>
        </menuitem>
        <menuitem label="Menu2" data="top">
            <menuitem label="MenuItem 2-A" type="check" data="2A"/>
            <menuitem type="separator"/>
            <menuitem label="MenuItem 2-B" >
                <menuitem label="SubMenuItem 3-A" type="radio"
                    groupName="one" data="3A"/>
                <menuitem label="SubMenuItem 3-B" type="radio"
                    groupName="one" data="3B"/>
            </menuitem>
        </menuitem>
    </fx:XMLList>
</fx:Declarations>

Answer: Try this,
<fx:Style>
       @namespace s "library://ns.adobe.com/flex/spark";
       @namespace mx "library://ns.adobe.com/flex/mx";
       mx|MenuBar{
                  color:#ff0000;
             }
       mx|MenuItemRenderer{
              color:#00ff00;
            }
</fx:Style>

Reomove color attribute from your <mx:MenuBar>
Hope it helps.


Not able to parse data in codable. I am able to fetch data but some how once I use decode function I get error

Question: I am not able to parse the data using decodable. I am able to fetch the data but not able to parse it using decodable function. It says

unresolved identifier 'data' in that function.

I Have tried various ways but still not getting it.
import UIKit
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

var str = "Hello, playground"

struct category : Codable {
    let success: Bool
    let list: [List]
    let slide: [String]
}

// MARK: - List
struct List: Codable {
    let id, categoryName: String
    let subcategory: [Subcategory]
}

// MARK: - Subcategory
struct Subcategory: Codable {
    let subCategoryID: SubCategoryID
    let subCategoryName, categoryID: String
    let banner: String

    enum CodingKeys: String, CodingKey {
        case subCategoryID = "sub_category_id"
        case subCategoryName = "sub_category_name"
        case categoryID = "category_id"
        case banner
    }
}

enum SubCategoryID: Codable {
case integer(Int)
case string(String)

init(from decoder: Decoder) throws {
    let container = try decoder.singleValueContainer()
    if let x = try? container.decode(Int.self) {
        self = .integer(x)
        return
    }
    if let x = try? container.decode(String.self) {
        self = .string(x)
        return
    }
    throw DecodingError.typeMismatch(SubCategoryID.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for SubCategoryID"))
}

func encode(to encoder: Encoder) throws {
    var container = encoder.singleValueContainer()
    switch self {
    case .integer(let x):
        try container.encode(x)
    case .string(let x):
        try container.encode(x)
    }

    let session = URLSession(configuration: .default)
    var datatask : URLSessionDataTask?
    let url = "http://comus.in/co/webservice/getCategoryList.php"
    var items = [URLQueryItem]()
    var myURL = URLComponents(string: url)
    let param = ["vendorId":"32"]
    for (key,value) in param {
        items.append(URLQueryItem(name: key, value: value))
    }
    myURL?.queryItems = items
    let request =  URLRequest(url: (myURL?.url)!)

    datatask = session.dataTask(with: request, completionHandler: {data, response, error in
        if error == nil {
            let receivedData = try? JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
            print(receivedData!)
            let listings = try? JSONDecoder().decode(List.self , from: data)
            if let listings = listings{

            }
        }

    })
    datatask?.resume()
}

}
Comment: Don't use `try?`, specially not when your code doesn't behave the way you want, Change to `try` and catch and print any error, `do { let listings = try JSONDecoder().decode(List.self , from: data) } catch { print(error) }`. And please clean up the posted code a little by removing all the multiple empty lines
Comment: Can you post the schema of the data you're trying to parse please?
Comment: I have shared the schema of the data in the form of struct which I want to parse and create model. Do you mean something else ?
Comment: No one can help if you don't post the complete error and show the actual JSON you are trying to decode. Change your code as @JoakimDanielson stated and update your question with the complete error and the JSON.
Answer: This is a simple syntax error. Because you missed an ! after data in decode function. Also as @Joakim Danielson suggested in comments, don't try? when you don't know what is happening. So change this:
let listings = try? JSONDecoder().decode(List.self , from: data)
if let listings = listings{

}

to this:
do {
    let listings = try JSONDecoder().decode(List.self , from: data!)
    print(listings)
} catch {
    print(error)
}