How to create spring controller for auto convert response jaxbelement to xml

Question: I have spring contoller:
<code>@Controller
@RequestMapping(value="/fake_cp")
public class FakeContentProvider {
    @RequestMapping(value="/request")
    public @ResponseBody JAXBElement<MetaRequest> request(
            @Valid @ModelAttribute FaceContentProviderCommand command
            )
            throws Exception {
        ru.icb.cpaclick.controller.jaxb.MetaRequest request = new ru.icb.cpaclick.controller.jaxb.MetaRequest();
        request.setAccessUrl("http://accessUrl.ru");
        request.setErrorUrl("http://errorUrl.ru");
        request.setShortdesc("This is short desc");
        request.setLoadUrl("http://loadru.ru");
        request.setTariffclass(20501);
        return new ObjectFactory().createRequest(request);

}
</code>
server return answer:
<code>org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.writeWithMessageConverters(AnnotationMethodHandlerAdapter.java:993)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.handleHttpEntityResponse(AnnotationMethodHandlerAdapter.java:952)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.getModelAndView(AnnotationMethodHandlerAdapter.java:878)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:428)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:662)
Could not find acceptable representation
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
[application/octet-stream, */*, text/plain;charset=ISO-8859-1, */*, */*, application/xml, text/xml, application/*+xml, application/x-www-form-urlencoded, multipart/form-data, application/xml, text/xml, application/*+xml]
05.08.2011 10:57:08 org.apache.catalina.core.StandardContext reload
</code>
How to create response converter for jaxbelement, or how to config spring?
Answer: This is maybe not the best way to handle REST or SOAP services in Spring.
A spring mvc controller is best used for rendering web pages. If you want to handle REST or SOAP services, you're better off adding an Apache XCF servlet integrated with Spring.
Using xjc (REST) and wsimport (SOAP) you can use a contract first approach to generated the classes and interfaces related to the service you want to expose.
Based on that you create an endpoint in the xcf configuration and your're done.


How to check if view result is empty Twig

Question: To check the field I use the following code:
{% if content.field_name|render is empty %}

How to check on node.twig if {{ my_cool_view }} result is empty? Is this generally possible in Drupal 8? Thank you for help.
Answer: You can use twig_tweak Module, and use drupal_view_result extension like:
{% if drupal_view_result('who_s_new', 'block_1') is empty %}

For more info look at this module Cheat sheet
Comment: Extra tip: you can add argument too, like drupal_view_result('who_s_new', 'block_1', 'all'), this is useful if you render with argument elsewhere the check is wrong


$A\subset B\subset K$, $K$ field of fractions of $A$, $B$ flat over $A$ $\implies B=S^{-1}A\ ?$

Question: Let $A\subset B\subset K$ be domains such that $K$ is the field of fractions of $A$, and $B$ is flat over $A$.
Is there a multiplicative subset $S$ of $A$ such that $B=S^{-1}A\ ?$
Comment: An integral domain is Prufer iff every overring is flat. In particular, every overring of a Dedekind domain is flat. A noetherian domain has the QR-property (each overring is a quotient ring, or a fraction ring if you prefer) iff it is a Dedekind domain with torsion class group. This shows that a Dedekind domain whose class group is not torsion provides a counterexample.
Comment: @user26857 - Thanks for your awesome comment! Would you mind giving some references?
Comment: 1) https://en.wikipedia.org/wiki/Pr%C3%BCfer_domain; 2) https://link.springer.com/article/10.1007%2FBF01361178
Comment: @user26857 just wanna note that you can get a class of non-Noetherian examples by the same token, since Goldman's theorem extends to generalized Dedekind domains (i.e. Prüfer domains $D$ in which $minSpec(D/I)$ is finite for each ideal $I$ and each prime is idempotent).
Answer: No, flat overrings are not necessarily localizations (although the converse of course holds).  But there are important similarities, enough to motivate their being called "generalized quotient rings."
You need to generalize the notion of a localization to properly characterize flat overrings as quotient-like structures.  The appropriate generalization is to take a multiplicatively closed collection of ideals, $\mathfrak{I}$, and to define the generalized transform of $R$ with respect to $\mathfrak{I}$ as $R_{\mathfrak{I}}=\bigcup_{A\in \mathfrak{I}}A^{-1}$.  Here, by $A^{-1}$, I mean the quotient ideal $(R :_K A)$.  There's no need to limit our discussion to integral domains.

Theorem: Given $A \subset B \subset K$, $B$ is flat over $A$ iff there exists a multiplicatively closed collection of ideals $\mathfrak{I}$ in $A$ such that $B = A_{\mathfrak{I}}$ and each $I \in \mathfrak{I}$ generates $B$ as a $B$-module.

This is Theorem 1.3 in this paper of Arnold and Brewer.
Akiba gives an example (see beginning of section 2) showing that a flat overring need not be a localization.

Let C be a non-singular plane cubic curve defined over a field $k_0$
  and let $P$ be a generic point of C over $k_0$, and let $k$ be a field containing
  $k_0(P)$. Then the homogeneous coordinate ring $R_0=k[x, y, z]$
  of $C$ over $k$ is normal.
Let $A=k[x, y, z]_{(x,y,z)}$, and set $\mathfrak{I} = \{\mathfrak{p}^n \mid n \in \mathbb{N} \}$ where $\mathfrak{p}$ is the homogeneous prime ideal of $A$ corresponding to $P$. Let $B= A_\mathfrak{I}$.

Then $A$ is a local domain and $B$ is a flat overring of $A$ such that no non-unit of $A$ becomes a unit in $B$.  For our purposes, this shows that $B$ is not a localization of $A$.  For Akiba's purposes, it showed the stronger statement that $B$ is not a generalized transform of $A$ with respect to any collection of invertible ideals.


What are the reserve days for play off matches of IPL7?

Question: In this post, it was reported that the reserve day for first playoff match is May 28.
What are the reserve days for the second and third playoff matches of IPL7?
Answer: Generally reserved days are scheduled on the next day of the actual match day in every tournaments.
From IPL's match playing conditions:

50. IPL 2014 PLAYOFF MATCHES
5.  A reserve day is available for three of the four playoff matches, as follows:
a. Qualifier 1 – reserve day: Wednesday 28 May at Eden Gardens, Kolkata starting at 4pm
  b.  Eliminator – reserve day: Thursday 29 May at CCI, Mumbai starting at 8pm
  c.  Qualifier 2 – no reserve day
  d.  Final – reserve day: Monday 2 June at M. Chinnaswamy stadium, Bengaluru starting at 8pm

Since there is no reserve day for Qualifier 2 the winner will be decided as per below conditions: (emphasis mine)

    For the Qualifier 2 playoff match (no reserve day), in the event that it is not possible to schedule a 5 over match to complete by the end of the extra time that evening/night, the teams will, if conditions permit, play a Super Over to determine the winner of the Qualifier 2. The pitch and ground must be ready for play so that the Super Over can start at the latest by 1.10am on Saturday 31 May.
    If it is not possible to start the Super Over as described in the above paragraph or to then complete the Super Over without interruption, the team that finished highest in the league table after the 56 matches of the regular season shall be declared the winner of the relevant playoff match.


If I do not close the file in C

Question: Let's say we have a c program as follow:
int fun(char *path) {
    FILE *f = fopen(path, "r");
    int result;
    // Do something here without closing the file
    return result;
}

int main(int argc, char *argv[])
{
    int i = fun(argv[1]);
    printf("%d\n", i);
    return 0;
}

I know that it is not a good habit to not close a file. But I wonder when will be file be closed by the OS. When fun returns or when main returns? How about when the program is killed?
Comment: According to the Standard (C11 §18.104.22.168.3 1), "a return from the initial call to the **main** function is equivalent to calling the **exit** function....", which closes all open streams. As for "how about when the program is killed?", that sounds like it would depend on the OS.
Answer: It's main. File handles are allocated to the process, not any given function. Think of what would happen if you declared f as a global variable. Any process termination will close files and free any other system resources associated to the process.
Comment: It would not crash the OS.
Answer: Yes, OS will reclaim the file descriptor which is open after program completes execution. However, if your program is a daemon then it will keep opening files causing OS to reach the limit of FS_OPEN_MAX. You can see this with the command ulimit -a along with other limits.
This is specific to Unix or GNU/Linux for Windows I do not know.
$ ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 63179
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 63179
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

Comment: You can exceed the number of open files on any process, not just a daemon.
Comment: Yes I know that. There are two ways. One through ulimit and another through sysfs or sysctl configuration files. But that was not asked for.

If I do not close the file in C


Complete atomic boolean subalgebras of power set boolean algebra

Question: Let $I$ be a set and $P(I)$ its power set. I want to prove:
Set $E(I)$ of all equivalence relations on set $I$ and set $A(I)$ of all complete atomic subalgebras (i.e. subalgebras that are atomic and complete) of boolean power set algebra $P(I)$ have same cardinality.
Note that every equivalence relation on $I$ defines unique complete atomic subalgebra of $P(I)$ boolean algebra (with equivalence classes as atoms). So we have that $\left\lvert E(I) \right\rvert$ $\le$ $\left\lvert A(I) \right\rvert$
I tried to prove the other inequality (find injection) but I failed to prove that in complete atomic boolean subalgebra of $P(I)$ boolean algebra $\inf B$ equals to intersection of all elements of $B$ where $B$ is set of elements of this subalgebra. (equivalently: every (nonzero) element of complete atomic boolean subalgebra of $P(I)$ algebra can be written as union of atoms). If the above statement is true then such complete atomic subalgebra defines a partition of set $I$. Also, I was unable to find a counterexample.
Any sugestions?
Comment: There is some subtlety in the terminology here: is a "complete subalgebra" a subalgebra that happens to be complete, or is it a "sub-complete algebra", i.e. a subalgebra which is also closed under infinite joins and meets in $P(I)$?  (Note that actually _every_ complete subalgebra in the second sense is atomic.)  You seem to be assuming the first interpretation, but I would assume the second unless context suggested otherwise...
Comment: A complete atomic subalgebra is a subalgebra that happens to be complete and atomic. I will edit it, thanks.
Answer: This isn't true if $I$ is infinite.  It is easy to see that $|E(I)|=2^{|I|}$; I claim that $|A(I)|=2^{2^{|I|}}$.
To show this, let $\beta I$ be the Stone space of $P(I)$, i.e. the space of ultrafilters on $I$.  Note that $\beta I$ is the free compact Hausdorff space on the set $I$ (with elements of $I$ corresponding to the principal ultrafilters).  So any map $I\to \beta I$ extends uniquely to a continuous map $\beta I\to \beta I$.  It follows that any map $I\to \beta I$ with dense image extends to a continuous surjection $\beta I\to \beta I$, which is then dual to an injective homomorphism $P(I)\to P(I)$.  Since the principal ultrafilters are dense in $\beta I$, we can construct maps $I\to \beta I$ with dense image by splitting $I$ into two subsets of cardinality $|I|$, mapping one of them onto all the principal ultrafilters, and then mapping the rest wherever we want.  Thus there are $|\beta I|^{|I|}$ different maps $I\to\beta I$ with dense image.  Since $|\beta I|=2^{2^{|I|}}$ (by a well-known theorem of Hausdorff; see this answer, for instance), this means there are $2^{2^{|I|}}$ such maps.
We have thus shown that there are $2^{2^{|I|}}$ different injective homomorphisms $P(I)\to P(I)$.  However, we aren't done, because different homomorphisms might correspond to the same subalgebra.  If two injective homomorphisms $f,g:P(I)\to P(I)$ have the same image, then $f^{-1}\circ g$ defines an automorphism $h:P(I)\to P(I)$ such that $g=f\circ h$.  There are only $2^{|I|}$ such automorphisms (since each one comes from a bijection $I\to I$), and so each subalgebra can only come from $2^{|I|}$ different injective homomorphisms $P(I)\to P(I)$.  Thus there must actually be $2^{2^{|I|}}$ different subalgebras of $P(I)$ that are isomorphic to $P(I)$ (and hence complete and atomic).
(If you want to express this all directly in terms of $P(I)$ without using topological properties of $\beta I$, you can do so as follows.  Let $S$ be any set of ultrafilters on $P(I)$ containing all the principal ultrafilters.  Define a homomorphism $f:P(I)\to P(S)$ by $f(A)=\{U\in S: A\in U\}$.  Since $S$ contains all the principal ultrafilters, it is easy to see this $f$ is injective.  If $|S|=|I|$, we can can then compose $f$ with an isomorphism $P(S)\to P(I)$ to get an injective homomorphism $f':P(I)\to P(I)$.  Moreover, we can recover the set $S$ from $f'$ as the set of inverse images of the principal ultrafilters under $f'$.  Since there are $2^{2^{|I|}}$ different such sets $S$ with $|S|=|I|$, this gives $2^{2^{|I|}}$ different injective homomorphisms $P(I)\to P(I)$.)
In conclusion, I expect that you were actually intended to use the other definition of "complete subalgebra"; i.e. a complete subalgebra is a subalgebra which is complete and such that the inclusion map preserves infinite joins and meets.  With that definition, your argument works fine to give a canonical bijection between $E(I)$ and $A(I)$.
Comment: Thank you very much. How did you manage to prove it in 20 minutes? :) amazing!
Comment: Well, every complete atomic Boolean algebra is isomorphic to $P(S)$ for some set $S$.  An injective homomorphism $P(S)\to P(I)$ corresponds to a continuous surjection $\beta S\to \beta I$, which corresponds to a map $S\to \beta I$ with dense image.  So if you want to count how many complete atomic Boolean subalgebras of $P(I)$ there are, you are interested in maps to $\beta I$ with dense image.  Taking $S=I$ then allows you to control the fact that multiple homomorphisms might have the same image (since there are only $2^{|I|}$ automorphisms of $P(I)$).


Kubernetes Rook-Ceph: different pools for different use-cases?

Question: I'm experimenting with rook-ceph on kubernetes for storage again. I have 3 nodes, which each have

a local ssd-partition mounted at /dev/sda2, and
a NAS-volume at /dev/sdb.

In my rook-config, I use all devices, which automatically finds and uses both as OSDs. So far so good.
What I'd like to do is treat them as two separate storage classes in kubernetes - the ssd-pool is fast but small, while the NAS-pool is slow but huge. That way, I could attach IO-intensive pods like databases onto the ssd-storageclass, while size-heavy pods like fileservers would attach to the NAS-storageclass.
Since rook-ceph currently attaches all OSDs to the same pool, I can not target specific ones via a kubernetes storageclass:
bash-4.4$ ceph osd tree
ID  CLASS  WEIGHT   TYPE NAME               STATUS  REWEIGHT  PRI-AFF
-1         0.82942  root default
-7         0.27647      host k8s-storage-1
 1    ssd  0.17879          osd.1               up   1.00000  1.00000
 5    ssd  0.09769          osd.5               up   1.00000  1.00000
-3         0.27647      host k8s-storage-2
 2    ssd  0.17879          osd.2               up   1.00000  1.00000
 3    ssd  0.09769          osd.3               up   1.00000  1.00000
-5         0.27647      host k8s-storage-3
 0    ssd  0.17879          osd.0               up   1.00000  1.00000
 4    ssd  0.09769          osd.4               up   1.00000  1.00000

bash-4.4$ ceph osd status
ID  HOST            USED  AVAIL  WR OPS  WR DATA  RD OPS  RD DATA  STATE
 0  k8s-storage-3   196M   182G      0        0       1       16   exists,up¹
 1  k8s-storage-1   374M   182G      0        0       0        0   exists,up¹
 2  k8s-storage-2   261M   182G      0        0       1       90   exists,up¹
 3  k8s-storage-2   121M  99.8G      0        0       0        0   exists,up²
 4  k8s-storage-3   187M  99.8G      0        0       0        0   exists,up²
 5  k8s-storage-1  85.3M  99.9G      0        0       0        0   exists,up²

¹local SSD storage
²remote NAS storage (it's just a 100gb for testing purposes)

I did find a possible solution, where I run two separate rook-ceph instances with a deviceFilter, so that one rook-ceph-cluster only uses the SSDs, while the other only uses the NAS-volumes. I dislike this solution due to the disadvantage of having to run two rook-ceph-cluster-instances in one kubernetes-cluster.
Is there a way to get rook-ceph to separate the SSD- and NAS-storages, so that they can be independently targeted by kubernetes storage classes?

Update 1: I found that I can update the storage classes for devices manually: ceph osd crush set-device-class osd.XXX - only thing I'm missing now is how to target them from a kubernetes storageclass via a ceph pool, in which (I guess?) the OSDs have to be put?
Best,
Lars
Answer: @LarsKumbier You can create cephcluster to specify deviceClasses for set of OSD'S https://github.com/rook/rook/blob/f70b687a6077877e29ab02b06a881ed2d65c3c78/Documentation/CRDs/Cluster/ceph-cluster-crd.md#osd-configuration-settings https://github.com/rook/rook/blob/f70b687a6077877e29ab02b06a881ed2d65c3c78/Documentation/CRDs/Cluster/ceph-cluster-crd.md#storage-class-device-sets  and use that deviceclasses for cephfs and rbd pools and create a storageclass to point to the rbd pool and cephfs data pools? this takes out the creation of multiple ceph clusters?


Compare wildcard string inside bash awk command

Question: Is there a way to compare a substring with wildcard in bash inside "awk" command like this
awk '{for(i=1;i<=NF;i++) if ($i=="redis-*") print $(i+1)}' /etc/redis/sentinel.conf | head -1

I want the command to look for any string  that starts with "redis-" e.g., redis-pers, redis-test, redis-session etc from the sentinel.conf file.
I do not want to grep the string (e.g., redis-test), but the string that following the wildcard.
So if the sentinel.conf file has a line like tis
sentinel known-slave redis-test 192.168.1.100 6379
, i want to return  192.168.1.100
Comment: Your question has nothing to do with bash or shell.
Comment: Awk is not a bash command, it's a programming language. `if ($i~/^redis-/)` [This](https://www.gnu.org/software/gawk/manual/html_node/Comparison-Operators.html) is a start.
Comment: This is a bash command, and i just want help on how this can be accomplished
Comment: I see. Now that that is cleared, how can i achieve what i have presented?
Comment: You can see all bash commands by typing `help`.
Comment: [edit] your question to contain the missing parts of the [mcve] with concise, testable sample input and expected output if you'd like help. See [ask] if that's not clear.
Answer: Awk doesn't have the glob (wildcard) syntax you're looking for, but you can convert your pattern to a regular expression and match that using the ~ operator:
if ($i ~ /^redis-/)

Regular expressions are more capable than shell globs - any glob pattern can be expressed as a regexp (but not vice versa).
Comment: If you are using Awk anyway, you might as well get rid of the `head`.  `awk '{for(i=1;i<=NF;i++) if ($i ~ /^redis-/) print $(i+1); exit}' /etc/redis/sentinel.conf`
Comment: `Awk doesn't have wildcards` is a bit misleading. Regexps have `.` which is a wildcard as it matches any character, and then of course you can add `?`, `*`, or `+` to match repetitions of any character.
Comment: Thanks @Ed; it's more accurate to say that regular expressions have a different syntax to shell globs.  I've updated accordingly.


Vandermonde determinant from 3-by-3

Question: I am a novice at math and need help calculating the determinant of the Vandermonde matrix, which is:
$V=\begin{bmatrix}
1&a_1&a_1^2&\dots&a_1^{n-1}\\
1&a_2&a_2^2&\dots&a_2^{n-1}\\
\vdots&\vdots&\vdots&\vdots&\vdots\\
1&a_n&a_n^2&\dots&a_n^{n-1}
\end{bmatrix}$
$det(V)={\displaystyle \prod_{1\le i\lt j\le n} (a_j-a_i)}$
I want to start with the following 3-by-3 and generalize to the n-by-n.
$A=\begin{bmatrix}
1&a_1&a_1^2\\
1&a_2&a_2^2\\
1&a_3&a_3^2
\end{bmatrix}$
So far I have:
$det(A) = a_2a_3(a_3-a_2)-a_1a_3(a_3-a_1)+a_1a_2(a_2-a_1)$
But I cannot figure out how to simplify this into a form like the determinant for $V$ above. What do I need to do?
Comment: Hint: if $a_i = a_j$ then there are two identical rows in the matrix, so the determinant is 0.  By the polynomial factor theorem, $a_j - a_i$ is a factor of the determinant.
Comment: One way to get started is to do row operations on $A$. In particular, try subtracting the first row from the others, and consider what factors would be common to the new rows.
Comment: It is not clear to me what you are asking. You already know the complete factorization of the determinant into linear factors. What do you want to do now? Prove that the factorization is equal to the determinant? It is easy enough to completely expand the product and also the determinant and verify that they are equal.
Comment: Wikipedia has an article on this: [Vandermonde matrix](https://en.wikipedia.org/wiki/Vandermonde_matrix)
Answer: I am a novice as well. I tried figuring this out.
$$\begin{bmatrix}1 & a& a^2 \\1&b&b^2 \\1 &c& c^2 \end{bmatrix}$$
$R_2 \rightarrow R_2 -R_1 \\
R_3 \rightarrow R_3 -R_1$
$$\begin{bmatrix}1 & a& a^2 \\0&b-a&b^2-a^2 \\0 &c-a& c^2-a^2 \end{bmatrix} $$
Taking out $(b-a)(c-a)$ from rows $R_2,~ R_3$
$$(b-a)(c-a) \cdot \begin{bmatrix}1 & a& a^2 \\0&1&b+a \\0 &1& c+a \end{bmatrix}$$
Taking Determinant gets us.
$$|A| = (b-a)(c-a)(c-b)$$
Comment: When taking out $(b-a)(c-a)$ you dont take it out of the matrix but out of the determinante, apart from that your answer seems good.

Vandermonde determinant from 3-by-3


How to save graylog logs to mongodb

Question: I'm trying to output all the logs from a Graylog server stream to a mongodb server. There is a jdbc output plugin that stream to RDBMS using jdbc but how to save the logs to Mongodb. Graylog is saving configuration data and stream configuration to mongodb and logs at elastic search but I want to also save the logs to mongodb server for audit trail purpose.
Does somebody have an idea on how I could do it ?
Answer: That is going to blow up the size of your MongoDB. Be sure to send it to an instance other than your Graylog instance to avoid trouble. Or cap the collection you store it in at a fairly aggressive number.
Comment: Thanks
but is there any option to move the logs to mongodb?
Comment: I don't know. You could send them to Graylog via filebeat though.

How to save graylog logs to mongodb


Tokens for Webform Component

Question: Is there a way to set up a Webform such that I can turn component field submissions into tokens for use in the submission email?
For example, I want to include "Message from [email address]" in the email subject line. The default options only allow for including only the component field in the email (subject: [email]), or only custom text.
Is there a way I can turn the component field submission into a token for use in the email? Looks like there's a module for turning webform items into tokens, but it's not for use within webform.
Answer: I figured it out. Use <code>%value[key]</code>.

Tokens for Webform Component


how to ignore the validation of hidden form fields in the user registration form?

Question: I am having a problem regarding the validation of the hidden fields.
I have some some fields that are hidden and only visible if a specific field is selected.
And I marked those those hidden fields as required. So I want to validate those fields only if they are visible and not validate if they are hidden.
I tried the client side validation module but the problem is if I enter the visible required field values then upon submission it also validate those hidden fields.
Any idea?
Comment: Only way is to make custom form validate for that form and avoiding the required value.
Comment: can you give an example of it please?
Answer: You need to use #ajax attribute on your specific field to alter the form ( to remove #required for your hidden element ). It lets Drupal re-build the form before submission and core validation. You will need to implement hook_form_alter and an ajax callback function.
Here is a workaround.
function yourmodule_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'user_register_form'){

        $form['toggle_me'] = array(
            '#type' => 'checkbox',
            '#title' => t('Tick this box to type'),
            '#ajax' => array(
              // #ajax has two required keys: callback and wrapper.
              // 'callback' is a function that will be called when this element changes.
              'callback' => 'ajax_form_alter',
              // 'wrapper' is the HTML id of the page element that will be replaced.
              'wrapper' => 'replace_field_div',
              // Don't show any throbber...
              'progress' => array('type' => 'none'),
             ),
        );

        # This field will be shown or hidden when "toggle_me" is checked or unchecked
        $form['dependency'] = array(
          '#type'       => 'hidden', # initially hidden
          '#title'      => 'Dependency',
          '#required'   => TRUE,
          '#prefix'     => '
',
          '#suffix'     => '
',
        );
        // An AJAX request calls the form builder function for every change.
        // We can change how we build the form based on $form_state.
        if(isset($form_state['values']['toggle_me']) && $form_state['values']['toggle_me'] == 1){
            # when "toggle_me" is checked, show this field and set required.
            $form['dependency']['#type'] = 'textfield';
            $form['dependency']['#required'] = TRUE;
        }else{
            # when "toggle_me" is unchecked, hide this field and remove required.
            $form['dependency']['#type'] = 'hidden';
            $form['dependency']['#required'] = FALSE;
        }
    }
}
/**
 * Callback for toggle_me
 *
 * On an ajax submit, the form builder function is called again, then the $form
 * and $form_state are passed to this callback function so it can select which
 * portion of the form to send on to the client.
 *
 * @return renderable array (the textfield element)
 */
function ajax_form_alter($form, $form_state){
    return $form['dependency'];
}

The example shows only two new elements ( toggle_me and dependency ) which are added to user registration form using hook_form_alter. When "toggle_me" is checked, show "dependency" and set required. When "toggle_me" is unchecked, hide "dependency" and remove required.
If you don't know about ajax form alter, download examples module and check ajax example.
Answer: Specify the conditions under which the field is required using drupal_process_states(). There's a UI for it, called Conditional Fields, but it does not have a recommended release yet.


Multiple xmlns attributes affect page performance?

Question: We are working on adding some Facebook Connect functionality to our site. Part of their requirements for FB Connect require adding several additional xmlns attributes to the html element. We are likely going to have 5 or 6 of their custom attributes by the time we're done, and I want to know if this will negatively affect our page performance. I.e. will these be additional resources that the browser has to download?
I have checked in Firebug and I don't see additional requests, but I don't know if that is because requests are not made by the browser, or if Firebug simply doesn't track them.
Answer: No. Namespace declarations are for identification only; take no more resources than storing any other attribute/value pair.
Although it is customary to use resolvable URIs for namespace identifiers, no XML processing tool will actually attempt to fetch that URI.


Create views with UI Pattern Views

Question: I have views like this:

I want use module UI Pattern Views. I defined UI Pattern. File card.ui_patterns.yml with content
card:
  label: Three column fluid
  description: Three column fluid
  fields:
    image:
      type: render
      label: Image
      description: Media image.
      preview:
        theme: image
        uri: http://lorempixel.com/900/500/sports/1
        width: 150
        attributes: {}
    title:
      type: link
      label: Title
      description: Media title.
      preview:
        type: processed_text
        text: Etiam iaculis nunc ac metus
        format: basic_html

and file pattern-card.html.twig have content:

    {% if image is not empty %}

            {{ image }}

    {% endif %}

{{ title }}

I don't know how can use multil image style for this case. Any suggetion?
Comment: Well this is suppose to be solved easily by adding a row counter and your image again and then doing an if statement, but sadly there is a Drupal Bug  [Global: View Result Counter does not evaluate properly in IF statements](https://www.drupal.org/node/2764651)
Comment: @NoSssweat Sorry. Do you try use module UI Pattern Views?  I don't understand with your suggestion.
Answer: Here's a step-by-step:

Install the UI Patterns Views module
Insert the fields and map them to the UI Pattern fields

Note: You are mapping fields for the rows.

At this point, each piece of content should be rendered as a UI Pattern
Now, if you want to arrange the cards in a specific way (say, using Masonry), then you can do it in one of the following ways:

Add a class to the entire view, say, js-view-masonry – you can then use this class in JavaScript to detect this view and apply the JS plugin that organizes the cards like you want.
The other way will be to create a superpattern of the card pattern. Say, a card_collection pattern, with a field named items. Next, override the view's template, especially the part where the rows are rendered. Here, instead of displaying the rows, into the "card_collection" pattern.

Here's a working example of the second method using "card_collection". The blog list consists of 2 patterns. The "card" pattern and a pattern called "card collection" which wraps the cards.

Create views with UI Pattern Views


update table where there is duplicate records using sql

Question: i am trying to update a table but my problem is the target table has duplicate records so my update is failing for that reason. This is the error: attempt to update a target row with values from multiple join rows.   I know when updating a table, we have to join unique keys but i cannot delete the duplicates from the table so i am looking for a work around for my situation.  The CUSTOMERTABLE is the one that has the duplicates.  Here is my query:
UPDATE CUSTOMERTABLE
SET SERVICE = 'BILLING'
FROM
(SELECT distinct(CUSTOMER_ID)AS ACCT_ID
       ,ED.CUSTOMER_NAME
       , ED.CUSTOMER_ADDRESS
  FROM CUSTOMER_RELATION ED, STG_CUSTOMER_REV TXN
  WHERE ED.CUSTOMER_ID = TXN.CUS_ID
 )AS X

WHERE X.ACCT_ID = CUSTOMERTABLE.ACCOUNT_NUMBER;

Answer: Try writing it with an IN clause:
UPDATE CUSTOMERTABLE
SET SERVICE = 'BILLING'
WHERE CUSTOMERTABLE.ACCOUNT_NUMBER IN
    (SELECT CUSTOMER_ID
     FROM CUSTOMER_RELATION ED
     JOIN STG_CUSTOMER_REV TXN ON ED.CUSTOMER_ID = TXN.CUS_ID)

Answer: Here is another option, which probably has a better performance compared to an IN solution if CUSTOMER_RELATION or STG_CUSTOMER_REV are large tables.
UPDATE C
   SET SERVICE = 'BILLING'
FROM CUSTOMERTABLE C
WHERE EXISTS (SELECT 1
              FROM CUSTOMER_RELATION ED, STG_CUSTOMER_REV TXN
              WHERE ED.CUSTOMER_ID = TXN.CUS_ID AND CUSTOMER_ID = C.ACCOUNT_NUMBER);

Comment: That's interesting. Why do you say that has better performance?
Comment: I agree there are other things to consider (indexes, stats, optimizer, etc). It's not a given it will be faster.
Comment: Check the following link for a discussion on this subject. http://stackoverflow.com/questions/2065329/sql-server-in-vs-exists-performance
Comment: Fair point but don't forget the query optimizer might generate the same plan for both if it can determine they are logically equivalent based on the table definitions.
Answer: Try grouping on the CustomerId
UPDATE CUSTOMERTABLE
SET SERVICE = 'BILLING'
FROM
(SELECT distinct(CUSTOMER_ID)AS ACCT_ID
       ,ED.CUSTOMER_NAME
       , ED.CUSTOMER_ADDRESS
  FROM CUSTOMER_RELATION ED, STG_CUSTOMER_REV TXN
  WHERE ED.CUSTOMER_ID = TXN.CUS_ID
  GROUP BY ED.CUSTOMER_ID
 )AS X

WHERE X.ACCT_ID = CUSTOMERTABLE.ACCOUNT_NUMBER;

You need to make sure that your select return non duplicates. Try using that select without the update statement and check if the select cotains the duplicates you want to get rid off.
Comment: thanks Key, the subquery runs fine but the problem is this:CUSTOMERTABLE.ACCOUNT_NUMBER, the account_number in the customer table has duplicates
Comment: @moe, if the account_number has duplicates then the update will update them all unles you add a anothere where clause distinguish them. Did you try acfrancis answer?


db_query question

Question: I'm writing a custom module and trying to use the db_query functions instead of just doing straight MySQL calls.
Here's my query.
$nid = $node->nid;
$result = db_query('SELECT * FROM {field_data_field_room_rates} WHERE field_room_rates_target_id = :nid', array(':nid' => $nid));
drupal_set_message('
'. print_r($result, TRUE) .'
');

...and here's what I get back.
DatabaseStatementBase Object
(
    [dbh] => DatabaseConnection_mysql Object
        (
            [needsCleanup:protected] =>
            [target:protected] => default
            [key:protected] => default
            [logger:protected] =>
            [transactionLayers:protected] => Array
                (
                    [drupal_transaction] => drupal_transaction
                )

            [driverClasses:protected] => Array
                (
                    [SelectQuery] => SelectQuery
                    [DatabaseTransaction] => DatabaseTransaction
                    [InsertQuery] => InsertQuery_mysql
                    [UpdateQuery] => UpdateQuery
                )

            [statementClass:protected] => DatabaseStatementBase
            [transactionSupport:protected] => 1
            [transactionalDDLSupport:protected] =>
            [temporaryNameIndex:protected] => 0
            [connectionOptions:protected] => Array
                (
                    [database] => my_db
                    [username] => user
                    [password] => pw
                    [host] => localhost
                    [port] =>
                    [driver] => mysql
                    [prefix] => Array
                        (
                            [default] =>
                        )

                )

            [schema:protected] =>
            [prefixes:protected] => Array
                (
                    [default] =>
                )

            [prefixSearch:protected] => Array
                (
                    [0] => {
                    [1] => }
                )

            [prefixReplace:protected] => Array
                (
                    [0] =>
                    [1] =>
                )

        )

    [queryString] => SELECT * FROM field_data_field_room_rates WHERE field_room_rates_target_id = :nid
)

if I were querying the SQL manually the query would be:
SELECT * FROM field_data_field_room_rates WHERE field_room_rates_target_id =2164
and it would yield back the proper row of items...which this doesn't seem to be giving.  All it seems to be giving back is Drupal database info.
What am I doing wrong?  :)
Answer: You need to fecth the results from the $result object. See https://www.drupal.org/node/1251174 for reference.
For instance, you might do something like:
$row = $result->fetch();

Hope it helps,

db_query question


How to get the number of pages in a view template?

Question: I'm trying to get the number of total "pager" pages with a view by using the views-mini-pager.html.twig. Here is my code so far...
{% if items.previous or items.next %}

            {% if items.previous %}
                {% if items.current %}
                    {% trans %}
                    Page {{ items.current }}
                    {% endtrans %}
                {% endif %}
                    ←{{ items.previous.text|default('‹‹'|t) }}
            {% endif %}
            {% if items.next %}
                {% if items.current %}
                    {% if items.previous %}
                    {% else %}
                        {% trans %}
                        Page {{ items.current }}
                        {% endtrans %}
                    {% endif %}
                {% endif %}
                {{ items.next.text|default('››'|t) }}→
            {% endif %}

{% endif %}

I want to have something like this

And currently, I can only get the current number page which ends up like this ...

I have searched for the variables inside of views-mini-pager.html.twig and I have not found the number of pages.
My question is...

How can I get the number of pages total? So I can display it at views-mini-pager.html.twig

For instance, if I view is divided into three pages I want to display "Page 1 of 3"
Answer: Mini Pager doesn't give you that information. It's designed to not execute a count query. It just knows that there's at least one additional result (because it actually queries 21 if you show 21).
Comment: Not directly I fear. The normal Full pager works with that information, that's basically the page ID in the "Last" link. It doesn't seem to be available directly in the template. See template_preprocess_pager(), $pager_max is what you're looking for, mor or less. Which in turn is in the $pager_total global (yeah, there are still some of those left in dark corners of D8 and pager is a very dark corner). So, implement your own preprocess, and then put it in $variables so you can use it in your template.
Comment: Just out curiosity, Do you know if there is another setting that provides this information ?
Comment: I think in d9 has no more this global variable "$pager_total"
Answer: This is also an option:
/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME_preprocess_pager(array &$vars) {
    $element = $vars['pager']['#element'];
    $pager_manager = \Drupal::service('pager.manager');
    $pager = $pager_manager->getPager($element);
    $vars['pager_max'] = $pager->getTotalPages();
}

Found this option here: https://api.drupal.org/api/drupal/core%21includes%21theme.inc/function/template_preprocess_pager/9.0.x
Answer: Berdir is right: the full pager needs to be used. Three steps are involved to get the output you wanted:

Switch the Views pager type to the full pager
Implement a hook_preprocess_pager() function

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME_preprocess_pager(array &$variables) {
  // @see globals.api.php
  global $pager_total;
  $element = $variables['pager']['#element'];
  // Get the max page number for the current pager.
  $variables['pager_max'] = $pager_total[$element];
}

Override the default pager template

Put something like this in pager.html.twig:
{#
/**
 * @file
 * Theme override to display a pager.
 *
 * @see template_preprocess_pager()
 */
#}
{% if items %}

{{ 'Pagination'|t }}

      {# Print previous item if we are not on the first page. #}
      {% if items.previous %}

            {{ 'Previous page'|t }}
            {{ items.previous.text|default('‹ Previous'|t) }}

      {% endif %}
      {# Now generate the actual pager piece. #}
      {% for key, item in items.pages %}
        {% if current == key %}

            {% trans %}
              Page {{ current }} of {{ pager_max }}
            {% endtrans %}

        {% endif %}
      {% endfor %}
      {# Print next item if we are not on the last page. #}
      {% if items.next %}

            {{ 'Next page'|t }}
            {{ items.next.text|default('Next ›'|t) }}

      {% endif %}

{% endif %}

The template is based on the template provided by Classy theme. It's inside the {% trans %} block where the magic happens.
Comment: i think in d9 has no more this global variable "$pager_total"
Answer: Drupal 9 has a service that provides the pager data. Use the following in a preprocess to get the total number of pages:
$total_pages = \Drupal::service('pager.manager')->getPager()->getTotalPages();

Answer: In Drupal 9, you can put this line in pager.html.twig:
Page {{ current }} of {{ items.pages|length }}

Twig lets you output the length of the Twig array as a number of items in the array. This equals the total number of pages.
The $pager_total global variable mentioned earlier is no longer available in Drupal 9.
Make sure you  change your view settings to use a full pager. You can further modify pager.html.twig so that it looks like a mini pager by removing stuff you don't need.
No preprocess functions needed.
Comment: Drupal 9 has a service that provides the pager data. Use the following in a preprocess to get the total number of pages:

``` lang-php
    $total_pages = \Drupal::service('pager.manager')->getPager()->getTotalPages();
```


Unused Argument Error in function during a do.call loop in R

Question: funMergeA <- function(x,y = NULL) {
    if (is.null(y)) {
        return(x)
    } else {
        return(funMerge(x,y,"a"))
    }
}

funMerge <- function(x,y,myby="a") {
    return(merge.data.frame(x,y,by=myby,all=TRUE))
}

b <- list(data.frame(a=1:10,b=rnorm(10)),
          data.frame(a=1:10,b=rnorm(10)),
          data.frame(a=1:10,b=rnorm(10)))

this works :
funMergeA(funMergeA(funMergeA(b[[1]],NULL),b[[2]]),b[[3]])

this doesn't :
do.call(funMergeA,b)

I am confused as to why the second one doesn't work. My understanding is that the 2 expressions are strictly equivalent. Is my understanding flawed ?
All help welcome !
Comment: You need `Reduce(funMergeA,b)` - do.call works through b one at a time but is not recursive in the way that you need it to be.
Comment: Thank you @Andrew Gustar for the helpful tip. If you want to post an answer i'll validate it.
Comment: `do.call(funMergeA,b)` is the same as `funMergeA(b[[1]], b[[2]], b[[3]])`, so your understand is flawed.
Answer: do.call iterates through b one element at a time but is not recursive in the way that you need it to be.  You need Reduce(funMergeA, b).


O que é SimpleChanges no Angular? Seria uma API do Angular?

Question: Tenho o seguinte código:
@Input() listas: IniciarFuncaoModel;

 ngOnChanges(changes: SimpleChanges): void {
    if (changes.listas) {
      this.iniciarFuncao();
    }
  }

O SimpleChanges é uma API do Angular?
Eu entendi que, no exemplo, o SimpleChanges está tipando o parâmetro changes. (É isso?)
Mas não entendi porque se usa o 'changes.lista' como parâmetro do if.
Minha dúvida é: Ao tipar o parâmetro changes com o SimpleChanges, este faz com que a variável listas se torne um atributo do parâmetro changes?!
Answer:
O SimpleChanges é uma API do Angular?

É a interface que representa o objeto de alterações para todas as propriedades de entrada

Eu entendi que, no exemplo, o SimpleChanges está tipando o parâmetro changes. (É isso?)

Sim, esta tipando a variável changes

Mas não entendi porque se usa o changes.lista como parâmetro do if.

if é uma estrutura de decisão, é feito uma decisão pelo visto se existe essa lista é como disse na primeira resposta: lista é um elemento de entrada de dados, quando ele contiver dados, executa a this.iniciarFuncao();

Minha dúvida é: Ao tipar o parâmetro changes com o SimpleChanges, este faz com que a variável listas se torne um atributo do parâmetro changes?

Sim, ele faz com que os input de entrada seja analisados e permitidos a verificação de sua alteração conforme já demonstrado por você mesmo if(changes.lista).

Interface
interface SimpleChanges {
    __index(propName: string): SimpleChange
}

Referencias

SimpleChange Class and SimpleChanges Interface
SimpleChanges


What are the difference between Cherry-pick and patch apply?

Question: I am aware about git cherry-pick and git apply terminalogies. But today i came across with some issue. I was applying one patch by using the diff of two revisions. I used the below command:

git diff HEAD  > diff.patch
git apply diff.patch

I got patch apply failed for one file.
Then i simply tried to cherry-pick the commit-id2. It is cherry-picked successfully.
What may be the reason? Anyone wants to throw some light on the same.
Answer: Two possibilities:

The changes in diff.patch are probably different from the changes in commit-id2, which is why the two behaved differently.
git diff HEAD shows the diff between HEAD and the current working directory.  git cherry-pick commit-id2 applies the diff between commit-id2 and its parent (and commits the result using the metadata from commit-id2).  The diff between commit-id2 and its parent is not (usually) the same as the diff between HEAD and the current working directory.
You did not tell git apply to fall back to a 3-way merge like cherry-pick does.  Try adding the --3way (or -3) option to git apply.

Try the following:
git diff commit-id2^! >diff.patch
git apply -3 diff.patch

The above should behave like git cherry-pick -n commit-id2.  (See git help revisions for an explanation of the ^! syntax.)


Query and list admin levels - join two tables

Question: I want to creat a admin group which can access data by this level table,
the low level can't see the higher level's data.
 0  =>   3
high => low
User Table:
<code>---------------------
uid  gid  uname
---------------------
110   4   Jacky       =>means {gname: art_admin  ,level: 2}
111   1   Niky        =>means {gname: site_admin ,level: 0}
112   4   Cupe        =>means {gname: art_admin  ,level: 2}
113   2   Nancy       =>means {gname: gen_admin  ,level: 1}
113   5   Joe         =>means {gname: admin      ,level: 3}
</code>
Group Table:
<code>---------------------
gid     gname       level
---------------------
1    site_admin    0
2    gen_admin     1
3    sys_admin     1
4    art_admin     2
5    admin         3
</code>
It means Jacky is belong to 'art_admin', and he's level is '2'.
so when he view the all user table, it just show the level under 2.

Jacky can see:< Jacky , Cupe, Joe> ,
Niky is the higher, so he can see all users:< Jacky,Niky,Cupe,Nancy,Joe >,
Joe is the lower, so she just can see herself: < Joe >

And then, how can I query it? Thanks.
Pseudo code
<code>$uid = 110 ;// Assume I'm Jacky
$result = mysql_query("
    SELECT
        user.uname from user
    WHERE
        [ group.level >= Jacky's level ]
";);

while($row = mysql_fetch_array($result)){
   echo $row['uname']." , ";
}
</code>
It should return
<code> Jacky , Cupe , Joe
</code>
Comment: mysql_* is deprecated, use mysqli_* or PDO
Comment: Thanks, I am try to use PDO rightnow
Answer: Is this the query you are looking for?
<code>select u.uname
from user u join
     groups g
     on u.gid = g.gid
where g.level >= (select g2.level
                  from user u2 join
                       groups g2
                       on u2.gid = g2.gid
                  where u2.uname = 'Jacky'
                 );
</code>


Responsive background image in Twig template

Question: I would like to render an image as background image in my Twig template. To optimize my resources I'd like to use a responsive image but I cannot find a way to use it for background images.
For a standard image I would use something like
<code>img src="{{ file_url(node.field_with_image.entity.uri.value) }}" alt="my_alt" class="my_class">
</code>
How can I achieve that with a background image?
Answer: You should definitely have a look at Background Images Formatter.

It contains a submodule to handle responsive images as well.

Either use that or check how they are doing it.
Comment: Is there any way to access the image within the twig with something like {{ content.my_field }} ?
Comment: Something like {{ node.my_field.entity.uri.value | image_style('thumbnail') }} but for responsive images ?
Comment: Has anybody tried Background Images Formatter. Id like to do the same thing but this doesnt work-  | responsive_image('')


C# Duplicati Interface restore single file

Question: I'm trying to use the Duplicati API to restore a single file.
About the Scenario: The whole thing runs on linux so it is compiled with mono. My backup contains two source Folders, so if I run Interface.ListSourceFolders() I get an Array of two.
Desired result: I want to restore one single file (or Folder) from my backup
Current result: If I run the code below it restores all the backed up files (so Folder 1 and Folder 2) into the path in //Comment1.
List<string> files = new List<string>();
files.Add("path");    //Comment1

Dictionary<string,string> options = new Dictionary<string,string>();
options["passphrase"] = MySettings.Password;
options["restore-time"] = date;
//Comment2

Interface i = new Interface("file:///path/to/archives", options);
string result = i.Restore(files.ToArray());

What I tried: I tried to set the path at //Comment1 to the absolute path (/desired/file/to/restore) or using the index of the source Folder (0/file/to/restore) and I also played around at //Comment2. e.g. I added something like options["restore-path"] = "/path/to/restore". I always get the same result.
Does anyone see what I'm doing wrong? Because I don't know what else I could try. There is almost no documentation so I don't know where to search. If someone knows a link for a good documentation I would be happy too!
Answer: In case if someone is interested. After trying around for hours I finally found out how to restore just a single file or folder. Here is what I'm doing now:
List<string> files = new List<string>();
files.Add("/restore/path");    //Comment1

Dictionary<string,string> options = new Dictionary<string,string>();
options["passphrase"] = MySettings.Password;
options["restore-time"] = date;
options["file-to-restore"] = "files";    //Comment2

Interface i = new Interface("file:///path/to/archives", options);
string result = i.Restore(files.ToArray());

At //Comment1 you need to set the desired restore path. In this folder all backup-set-folders are created (The folders from Interface.ListSourceFolders())
At //Comment2 you can specify the files to be restored in this form: 0/file/to/restore where 0 is the index of the source folder (Interface.ListSourceFolders()). If you need to restore multiple files you can do it by combining them into one string: e.g. Windows: 0/file1;1/file2 or Linux 0/file1:1/file2 (The difference is semicolon or colon)
Now there is just one more thing: You can not restore a folder with its files. You need to combine all files and sub-files in the string mentioned above.
I hope I could help somebody.


How to find possible duplicates using something like reduce and filter?

Question: I have an array of arrays like this
let a = [
  //    Line #    Vendor      Proj       Amount      Description
  [      '1',     '213e',    '2300',    '456.09',   'for gutter cleaning'],
  [      '2',     '3334',    '3321',    '321.10',   'for upkeep'],
  [      '3',     '213e',    '2300',    '456.09',   'for mowing']
]

I'd like to filter the array to only show the arrays that have the same vendor, project and amount. How can I do that in an elegant way, without using a nested loop?
I'm wondering if I can find dupes with a combination of reduce and filter? I know this isn't in the standard, but are there any homebrewed solutions?
Something like
let dupes = a.reduceFilter((curArr, nextArr) => curArr[1] === nextArr[1] && curArr[2] === nextArr[2] && curArray[3] === nextArr[3])

And then I'd end up with this:
dupes: [
  ['1','213e','2300','456.09','for gutter cleaning'],
  ['1','213e','2300','456.09','for mowing']
]

Answer: I would use reduce and flatMap to get the dupes.

let a = [
  //    Line #    Vendor      Proj       Amount      Description
  ['1', '213e', '2300', '456.09', 'for gutter cleaning'],
  ['2', '3334', '3321', '321.10', 'for upkeep'],
  ['3', '213e', '2300', '456.09', 'for mowing']
]

const findDupes = (array, keys) => {
  const mapped = array.reduce((acc, line) => {
    const genKey = keys.map(i => line[i]).join('-');
    acc[genKey] = acc[genKey] || [];
    acc[genKey].push(line);
    return acc;
  }, {});

  return Object.values(mapped).flatMap(items => items.length > 1 ? items : []);
}

console.log(findDupes(a, [1, 2, 3]));
Answer: Consider grouping the items and then filter groups bigger than one

const cache = {}

let a = [
  //    Line #    Vendor      Proj       Amount      Description
  [      '1',     '213e',    '2300',    '456.09',   'for gutter cleaning'],
  [      '2',     '3334',    '3321',    '321.10',   'for upkeep'],
  [      '3',     '213e',    '2300',    '456.09',   'for mowing']
]

const result = a.forEach((obj) => {
  const [, vendor, proj, amount] = obj
  const key = `${vendor}\x00${proj}\x00${amount}`
  if (!(key in cache)) {
    cache[key] = []
  }
  cache[key].push(obj)
})

const dupes = Object.values(cache).filter(array => array.length > 1).flat()
console.log(dupes)
Comment: Please add a delimiter to the cache key, one that you don't expect to exist in the source data (e.g. `\x00`). Otherwise you have a bug where `foo/fo/fo` and `foof/o/fo` (and so on) are considered duplicates.
Comment: @TravisHeeter I removed `_`. Yes, you have to add `.flat()`. `flatMap` is a combination of `map` and `flat`
Comment: What is happening in `const [_, vendor, proj, amount] = obj`? I'm guessing you're creating variables with names based on `obj`? What does the underscore `_` do in that line?
Comment: Also, this is giving me an array of arrays. I'm going to add a `.flatmap` to make the result flat.
Answer: I do not ever recommend using this in production but here is my solution in a single line. Basically, use a filter to check if the rest of the items concatenated into a single string contain the vendor, project, and amount as a single string. If so, it is a dupe

let a = [
  //    Line #    Vendor      Proj       Amount      Description
  [      '1',     '213e',    '2300',    '456.09',   'for gutter cleaning'],
  [      '2',     '3334',    '3321',    '321.10',   'for upkeep'],
  [      '3',     '213e',    '2300',    '456.09',   'for mowing']
]

let dupes = a.filter(row => a.filter(x => x[0] !== row[0]).map(x => x.join("")).join("").includes(row.slice(1, 4).join("")))

console.log(dupes)
Answer: The code below is self-documenting.
I broke each step of the logic out into individual functions.

Reduce each row into a map (keyed-on vendor, project, and ammount)
Take the values of the map and filter them by length greater than 1
Flatten the resulting list

const csvData = [
  // Line #  Vendor   Proj     Amount     Description
  [  '1',    '213e',  '2300',  '456.09',  'for gutter cleaning' ],
  [  '2',    '3334',  '3321',  '321.10',  'for upkeep'          ],
  [  '3',    '213e',  '2300',  '456.09',  'for mowing'          ]
];

const getOrDefault = (map, key, defaultValue) => {
  if (map.has(key)) return map.get(key);
  map.set(key, defaultValue);
  return defaultValue;
};

const updateMap = (map, keyFn, row) => {
  modification(getOrDefault(map, keyFn(row), []), row);
  return map;
};

const modification = (target, value) => target.push(value);

const hashFn = (...data) => data.join('\x1e'); // Record Separator

const findDuplicates = (data, keyFn) =>
  [...data.reduce((map, row) => updateMap(map, keyFn, row), new Map).values()]
    .filter((rows) => rows.length > 1)
    .flat();

const keyFn = ([_, vendor, proj, amount]) => hashFn(vendor, proj, amount);

const duplicates = findDuplicates(csvData, keyFn);

console.log(duplicates);
.as-console-wrapper { top: 0; max-height: 100% !important; }


$f$ function with $\nabla f=\bar{0}$

Question: Let $f:D\subset\mathbb{R}^2\rightarrow\mathbb{R}$ be a function with $D$ open and connected set such that $\nabla f=\bar{0}$ for all $x\in D$ Proof that $f$ is a constant function.
Hi! I have some problems with this exercise. I think that I have the proof, but, in this, I never use the fact that $D$ is a  connected  set. Can anyone help me? Please.
My proof:
First, since $\nabla f=\left(\displaystyle\frac{\partial f}{\partial x},\displaystyle\frac{\partial f}{\partial y} \right)=(0,0)$, then, $\displaystyle\frac{\partial f}{\partial x}=0$ and $\displaystyle\frac{\partial f}{\partial y} =0$. Hence, the partial derivatives are bounded, i.e., there exist a $K,M\in\mathbb{R}^{+}$ such that $\left|\displaystyle\frac{\partial f}{\partial y}  \right|\leq K$ and $\left|\displaystyle\frac{\partial f}{\partial x}  \right|\leq M$ (I think that anything $K$ and $M$ it works, because the partial derivatives are $0$).
Now let $a = (a_1,a_2)$ and $b = (b_1,b_2) \in D$. Then we have:
\begin{align*}
f(a) - f(b) &= f(a_1,a_2) - f(b_1,b_2)
\\
f(a)-f(b) &= f(a_1,a_2) - f(a_1,b_2) + f(a_1,b_2) - f(b_1,b_2)
\end{align*}
Then, by the triangle inequality:
$$|f(a)-f(b)| \leq |f(a_1,a_2) - (a_1,b_2)| + |f(a_1,b_2) - f(b_1,b_2)|$$
And since the partial derivatives exist, we can use the one-dimensional Mean Value Theorem to show that there exists some $c$ such that:
$$\frac{f(a_1,a_2)-f(a_1,b_2)}{a_2-b_2} = \displaystyle\frac{\partial f}{\partial y}(a_1,c)$$
And noting how we defined $K$, it follows that
$$|f(a_1,a_2) - f(a_1,b_2)| \leq K|a_2 - b_2|$$
And similarly
$$|f(a_1,b_2) - f(b_1,b_2)| \leq M |a_1-b_1|$$
And using the statement we got from the triangle inequality, we have that
$$|f(a)-f(b)| \leq M|a_1-b_1| + K|a_2 - b_2|$$
And by the Cauchy-Schwarz inequality, we have that
$$M|a_1-b_1| + K|a_2 - b_2|
\leq
\sqrt{M^2 + K^2}\cdot
\sqrt{(a_1-b_1)^2+(a_2-b_2)^2}
=
\sqrt{M^2 + K^2} \cdot
||a-b||$$
Whereby
$$|f(a)-f(b)| \leq \sqrt{M^2 + K^2} \cdot ||a-b||$$
So $f$ is Lipschitz with $L = \sqrt{K^2 + M^2}$.
Hence, the function is continuous. But, $M=K=0$ works, we can consider $L=0$ and the nex equality $$0\leq|f(a)-f(b)| \leq 0$$Then $|f(b)-f(a)|=0$ and we can conclude that $f(b)=f(a)$ for all $a,b\in D$. Then, the function is constant. But, in the proof, I never used the connected of $D$. Where is the wrong? Can anyone help me? Thanks.
Comment: You use connectedness of $D$ in the application of the Mean Value Theorem.
Comment: Here is a counter-example if $D$ is not connected: let $D = \mathbb{R}^2$ with the $y$-axis removed then $f = -1$ on $\mathbb{R}_{> 0}$ and $f = 1$ on $\mathbb{R}_{< 0}$ has $\nabla f = 0$ on $D$ and $D$ is open (but not connected). The thing that fails in your proof for this case is the application of the mean value theorem. If $D$ is not connected then there is not a continuous curve in $D$ connecting point $a$ to point $b$ for which you can apply the mean-value theorem to.
Comment: No, your proof is incorrect.
Comment: I'm pretty sure this was asked yesterday.
Comment: @Mattos, sure, the post of yesterday is the reason for this question. I think in the solution and I posted here.

Oh, then, the connectedness is so important for this result. Thus, my proof is complete.
Answer: Suppose $\nabla f=\left(\displaystyle\frac{\partial f}{\partial x},\displaystyle\frac{\partial f}{\partial y} \right)=(0,0)$.
$$
\frac{\partial f}{\partial x} = 0 \quad \Rightarrow \quad f(x,y)=A+g(y),
$$
where $A\in \mathbb{R}$ and $g:\mathbb{R}\rightarrow \mathbb{R}$. Note that this only holds if $D$ is connected; e.g., if you consider
$$f:]0,1[\cup ]1,2[\times \mathbb{R}\rightarrow  \mathbb{R} \\(x,y)\mapsto\lfloor x \rfloor$$ it satisfies $\frac{\partial f}{\partial x} = 0$ but is not constant.
Then, we have $\frac{\partial f}{\partial y} =0= g'(y)$, therefore
$
g(y)=B \in \mathbb{R}
$.
In summary
$$
f(x,y)=A+B\in \mathbb{R}
$$
Comment: But, where you using the connectedness of the domain?
Comment: I believe it is here : $$
\frac{\partial f}{\partial x} = 0 \quad \color{red}{ \Rightarrow} \quad f(x,y)=A+g(y)
$$
Comment: Your claim $$\frac{\partial f}{\partial x} = 0 \quad \Rightarrow \quad f(x,y)=A+g(y)$$ needs some proof.
Answer: Your application of the mean value theorem is not always valid as there is no reason why all the points on the line between $(a_1,a_2)$ and $(a_1,b_2)$ has to be in $D$. To close this loophole you need to use the missing ingredient. If $a,b\in D$ then since $D$ is connected we know there exists a smooth curve (see e.g. this answer) $\gamma(t):[0,1]\to D$ such that $\gamma(0) = a$ and $\gamma(1) = b$. You can now apply the mean value theorem to the function $g:[0,1]\to\mathbb{R}$ given by $g(t) = f(\gamma(t))$ to get the desired result:
$$f(b) - f(a) = g(1) - g(0) = g'(c) = \nabla f(\gamma(c))\cdot \gamma'(c) = 0$$
Also it's not stated that $f$ is differentiable, but since all partial derivatives $\nabla_i f = 0$ is continuous and $D$ is open this is guaranteed for all points in $D$ (see e.g. this question).
Comment: @CarlosJiménez See the answer I link to in the post for a discussion on how these different definitions are related. See also: http://math.stackexchange.com/questions/56741/connected-implies-path-polygonally-connected?noredirect=1&lq=1 ; http://math.stackexchange.com/questions/766422/when-does-open-and-connected-imply-path-connected?rq=1 Also note that you can modify this procedure to work with "connected by paths" definition (i.e. without assuming that $\gamma$ is smooth): just apply the MVT to each of the straights lines in the polygonal chains.
Comment: Now, I have a great confussion. In my class, we define three kinds of connected sets:
Arc-connected: A set $X$ is path connectedness (I don't know if this is the correct translate from the spanish. In spanish we have like "Conjunto arco-conexo") if for all $a,b\in X$ there exist a continuous function $\gamma:[0,1]\rightarrow\mathbb{R}$ such that joins $a$ with $b$
Connected by paths: $X$ is connected by paths if there exist a polygonal chain https://en.wikipedia.org/wiki/Polygonal_chain that joins $a$ with $b$ (in spanish is Poligonalmente conexo) and the usual definition for connected.
Comment: I readed the answers, but, the definitions are so confusing for me now. Maybe for the languaje.
Comment: You are using the chain rule, which works if $f$ is differentiable everywhere, but we don't have that do we?
Comment: @zhw. $f(x)$ is differentiable in $D$ and $\gamma(t) \in D$ so I don't see the problem here?
Comment: Why is $f$ differentiable in $D?$ The everywhere existence of partial derivatives does not imply differentiability.
Comment: @zhw. Ok, now I see what you mean. I thought that was given in the question, but now I see that it's not.
Comment: @zhw. I think it's still fine since $D$ is open and $\nabla f$ is continuous it should imply differentiabillity for all points in $D$. Here is a reference:  http://math.stackexchange.com/questions/1007709/proof-that-continuous-partial-derivatives-implies-differentiability
Comment: Oh yes, you're right. Good point. The partials are $0$ therefore continuous, hence $f$ is $C^1$ which implies differentiability. That's worthwhile pointing out I think

$f$ function with $\nabla f=\bar{0}$


Which is the physical device behind the logical /dev/___ device

Question: From time to time I get myself dealing with this same problem: from a linux logical block device (something below /dev/), I need to find the actual hardware behind it (something probably being listed on lspci).
The solution is always some side check for the specific hardware I am dealing with, using some contextual or historical data, or just by elimination, but when you are dealing with large heterogenous installations, that can be really hard to achieve. I would like to find a proper and more generic way to query the kernel about this. My guess is that must be some kind of link (and a way to query it) between the major:minor device numbers to the actual hardware.
Comment: Can you give a better example of what you're talking about? Disks? Storage?
Comment: I am pretty sure this is the function of `sysfs`, typically mounted at `/sys` although I am not sure where the path to every piece of hardware is kept for every device node.
Comment: Sure, in this case I have 3 possible block devices that can be on the machine: a HDD, a SSD or a fusion IO card. I can try writing specific checks for each one of them, but I would like to go in a more generic way (at least for block devices)
Comment: With a RAID controller or no?
Comment: Dont know exactly to be honest, but I am assuming that its not RAID
Comment: I'm still not clear on what you're trying to do.
Comment: Henriks answer is just what I needed. In the end is a generic way to map a (block) logical device to the actual underlying hardware
Answer: If you have udev configured in a good way you can look at places like /dev/disk/by-id/ and /dev/disk/by-path/ to see exactly what hardware matches /dev/sd?.
Comment: Thats exactly what I needed. You are awesome :)


Reconstruct dictionary in python

Question: I have two dictionaries created from a config file:
    dict1 = {'x':'A', 'y':'B', 'z':'C'} # decoding ABCs
    dict2 = {'ID1': ('x','n1'), 'ID2': ('y','n2'), 'ID3':('z', 'n3') }

I want to create a new dictionary in the following format:
    final = {'A':{'ID1':'n1', 'ID2':'n2'}, 'C':{'ID3':'n3'}, ...}

I did not come up with a clever way to do this. Does anyone have any ideas?
Comment: Should that second `'A'` be a `'B'`?
Comment: You can't. You cannot create a dictionary with duplicate keys. I see how `'x'` maps to `'A'` via `dict1`, but you need to work out how to resolve the conflicts.
Comment: @jamylak: I rolled back your edit. You can't just assume something is a typo and change the meaning of the question like that.
Comment: @interjay would make a lot of sense though
Comment: Gosh you guys are fast:) Actually it was intended, but of course it does not make sense.  A, B, and Cs can occur multiple times.
Comment: Apart from the great answers and your fast responses, there is still an issue I am struggling with understanding here, perhaps it is nothing. But why do you have the inner dicts keys in the form 'ID#' as a string, and they are spread out to all the outer keys. It seems that if I want the value for ID2 I need to look in all the outer keys before I find the inner key to ID2, also, it means an outer key, lets say 'F' would have seemingly arbitrary inner keys like ID32, ID35 ... etc.. there seems to be no order to this, perhaps you should rethink this structure.
Answer: Assuming x, y, z in dict2 and A, B, C in final:
final = {dict1[k]: {id: v} for id, (k, v) in dict2.items()}

In [6]: dict1 = {'x':'A', 'y':'B', 'z':'C'}

In [7]: dict2 = {'ID1': ('x','n1'), 'ID2': ('y','n2'), 'ID3':('z', 'n3') }

In [8]: {dict1[k]: {id: v} for id, (k, v) in dict2.items()}
Out[8]: {'A': {'ID1': 'n1'}, 'B': {'ID2': 'n2'}, 'C': {'ID3': 'n3'}}

If you really did mean there should be two As, then it cannot be expressed as a dict. Will a list of pairs do? You'll have to decide on an ordering then.
In [10]: [(dict1[k], {id: v}) for id, (k, v) in dict2.items()]
Out[10]: [('A', {'ID2': 'n2'}), ('C', {'ID3': 'n3'}), ('A', {'ID1': 'n1'})]

Comment: I assumed the second A and the second x are typos — it just doesn't make any sense otherwise.
Comment: Oh wait, he *could* have meant that there should be two `A`s.
Comment: It seems quite a stretch to assume that there were two independent typos which have the same meaning. More likely, OP doesn't know dicts can't have multiple keys.
Comment: which leads to *one* `'A'` key replacing the other. It'll be arbitrary which one wins.
Comment: @MartijnPieters: That may be a copy/paste mistake in the original question.
Comment: Sorry for the confusion. Hopefully corrected in a meaningful way now. I am aware that one cannot have multiple identical keys.
Answer: Consider:
final = {}
for id, (x, n) in dict2.items():
    final.setdefault(dict1[x], {})[id] = n

which creates
{'A': {'ID2': 'n2', 'ID1': 'n1'}, 'C': {'ID3': 'n3'}}

Don't know if this meets your needs, but at least it's a valid structure.

Reconstruct dictionary in python


How to set nginx root path based on host

Question: How i can set for a visitor host to use a specific root path in nginx?
Visitor with IP 220.127.116.11  will use
root /srv/web1

all other Visitors will use
root /srv/web2

Comment: So what have you tried so far?
Comment: @Drifter104 I have try with if ($remote_addr = 1.1,1,1) { root ... } ... this wont work.
Answer: While this question is easily answered by simply doing a bit of research and reading the documentation (preferably starting from the Beginner's Guide and then How nginx processes a request), I will answer it anyway.
I assume you have a server with more than one network interface and IP address, where the 126.96.36.199 address is assigned to one interface and other addresses to their respective interfaces.
Nginx is very flexible in this regard, in fact, there always is a server block that is used as default when nginx can't match any other server block by server_name: that is either the first server block of the file or the one which specifies default_server in its listen directive. And remember that you can specify an IP in the listen directive.
That means, in your case:
server {
    listen 80 default_server;
    root /srv/web2;
    [...]
}
server {
    listen 126.96.36.199:80;
    root /srv/web1;
    [...]
}
As you can see in the example above, the first server block listens on all interfaces on port 80, while the second block listens only on the 22.214.171.124 interface, on port 80. Therefore, anyone visiting your site through the 22.214.171.124 network interface will receive files from /srv/web1, independently from the Host field in the HTTP request (that is, the domain name written in the URL bar).
Another similar behavior can be obtained by putting the IP address in the server_name directive, like so:
server {
    listen 80;
    server_name 22.214.171.124;
    [...]
}
* Note that this last server block only catches requests to the literal IP address and not to domain names.
I hope this answers your question, but next time please put additional information about your current setup and please do some research.
Update
To obtain the described behavior you can use the geo module as explained in this question:
geo $client {
    default web2;
    184.108.40.206 web1;
}
server {
    [...]
    root /srv/$client;
    [...]
}
This config uses the geo module to set a variable ($client) based on the client's IP address. That variable gets set to either the default web2 or the specific web1 and then is substituted in the root directive.
Note that the geo directive must be inside the http block and not server blocks; the snippet above should work as-is, but I don't guarantee anything since I did not test it.
Comment: sorry my questions was not well written, I need a solution that specific visitors are server by a different root path, means visitor with IP 184.108.40.206 will be server by /srv/web1 and all other by /srv/web2
Comment: @nenad007 I updated my answer (down below, 'Update' section). If it works for you, feel free to accept the answer.

And regarding your other comment about `if($remote_addr...)`, it doesn't work because you cannot put a `root` directive inside an `if` block. Read [If Is Evil](https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/).


12 bar blues, spread rhythm: alternative to 6th chord to avoid finger stretch

Question: I'm learning blues guitar from a book, and after going through chord progressions (I-IV-V, etc.) and making me play the rhythm with the whole chord, the book introduces what it calls "spread rhythm" whereby only two of the strings of the chords are played.
As well as only using two of the chords, this also introduces a variation: each bar uses two different chords, a 5th and a 6th chord. The first bar looks like this:

-------------------
-------------------
-------------------
-------------------
-7-7-9-7--7-7-9-7--
-5-5-5-5--5-5-5-5--

The notes with the "7-5" are A5 and the notes with "9-5" are A6.
I hurt my little finger at some point in the past, and while it's mostly recovered I'm finding that "9-5", the A6, to be more than it can currently take - it feels painful.
I know that with time and practice I will get there eventually, but as I want to give more time for my little finger to rest I was looking for an alternative to that 6th chord.
I have seen people doing similar rhythms with open chords, but I'm interested in a moveable version. Also I realise I could stick to the 5th chord, but it doesn't nearly as interesting.
So: Are there any other similar, moveable patterns that don't require the finger stretch?
Answer: Funnily enough, as a guitarist for over 50 yrs, this is one riff pattern that's always eluded me. Short fingers don't help. It's a very common sort of pattern, which can get even more stretchy when the b7 gets added into the pattern. I keep it in E, A and occasionally D, with open strings - that's what works for me. Or I'll get someone else to play the riff!
The only simple solution I could come up with was to capo it wherever the key required. Not perfect, but it often sounds better, as it emulates the open string sound.
Answer: Yeah, play it with the open A string as below:
('X' is muting the big E string)

Trickier, but worth a try is the following, but has the downside that you have to make sure to mute the A string between the fretted strings:
Comment: If you do your second example, it'll work all the way up the neck, and be easier the further up you go.
Comment: I like your second one as it's moveable. I tend to finger pick, so strumming two separate strings is ok. I'm trying to find which chords match these notes in those exact position. I found Am9 for the 2x5, but I can't find any chord that includes the exact notes (in that position) 4x5 - do you know where they come from?
Comment: Ah, I think I get it. The positions I got from the book (75 and 95) also don't match the normal way of doing an A5 or A6. They are just two notes of those chords. The ones you gave here are also alternate ways of doing A5 and A6 with two strings, just using a different fingering. That makes sense, thanks!


Forbid the word administrator as username

Question: I was make a function for a signup account page so someone will not can be signup with username admin or administrator. The code is below:
function forbidden($word){
$forbidden = array('Admin', 'admin', 'Administrator', 'administrator', 'admin1', 'Admin1', 'admin123', 'Admin123', 'admin123456', 'Admin123456', 'Administrator1', 'Administrator2',
'Administrator3', 'admin3', 'admin4', 'Administrator123', 'administrator123', 'administrator1', 'administrator2', 'administrator123', 'administrator3', 'aDmin', 'adMin', 'ADMIN',
'ADMINISTRATOR', 'admIn', 'admiN', 'ADmin', 'AdMiN', 'ADmin', 'ADMin', 'ADMIn', 'aDMin', 'ADministrator', 'aDministrator', 'adMinistrator','ADMinistrator', 'ADMInistrator', 'ADMINistrator',
'ADMINistrator', 'ADMINIstrator', 'ADMINIStrator', 'ADMINISTrator','ADMINISTRator','ADMINISTRAtor','ADMINISTRATor','ADMINISTRATOr','ADMINISTRATOR_a','ADMINISTRATOR_b');

for($i=0; $i<=count($forbidden); $i++) {
        if(isset($forbidden[$i])){
            if( $word == $forbidden[$i] ){
            $check_forbitten = "true";
            return $check_forbitten;
            break;
            }
        }

}

}

My question is there a more accurate and quick way to do this?
Comment: I'd probably use a case-insensitive regular expression check to see if the username begins with "admin". **Edit** Or actually just check if a lowercase substring of the first 5 characters matches "admin".
Comment: Sounds like a good opportunity to learn about the benefits of using regular expressions for pattern matching...
Comment: I really don't understand why i get downvoted again....
Answer: function forbidden($word) {
  return !preg_match('/admin/i', $word);
}

Includes all your defined words and some more I suppose you want filtered out.
Maybe some fine-tuning since it look like you only want to forbid admin as the start:
function forbidden($word) {
  return !preg_match('/^admin/i', $word);
}

Beware, that this is returning the boolean true/false. If you really want a string as in your example this would work:
function forbidden($word) {
  return (preg_match('/^admin/i', $word) ? 'false' : 'true');
}

Comment: I was about to comment on `/^admin/i`
Comment: thank's best solution so far ! I will accepted as correct answer!
Answer: the function in_array() would be the best to use here if you want to keep your array of forbidden words. Beside that, I would suggest something like @rickdenhaan answer and use a regex. You could use (\d)?(admin)(istrator)?(\d)?
function forbidden($word){
    $forbidden = array('Admin', 'admin', 'Administrator', 'administrator',
        'admin1', 'Admin1', 'admin123', 'Admin123', 'admin123456', 'Admin123456',
        'Administrator1', 'Administrator2',
        'Administrator3', 'admin3', 'admin4', 'Administrator123',
        'administrator123', 'administrator1', 'administrator2', 'administrator123',
        'administrator3', 'aDmin', 'adMin', 'ADMIN',
        'ADMINISTRATOR', 'admIn', 'admiN', 'ADmin', 'AdMiN', 'ADmin', 'ADMin',
        'ADMIn', 'aDMin', 'ADministrator', 'aDministrator',
        'adMinistrator','ADMinistrator', 'ADMInistrator', 'ADMINistrator',
        'ADMINistrator', 'ADMINIstrator', 'ADMINIStrator',
        'ADMINISTrator','ADMINISTRator','ADMINISTRAtor',
        'ADMINISTRATor','ADMINISTRATOr',
        'ADMINISTRATOR_a','ADMINISTRATOR_b');
    // word is forbidden
    return in_array($word, $forbidden));
}


Downloading from private directory corrupting some file types

Question: We have set up a private file system on a website based on drupal's guidelines. We are using Drupal 8.
We have setup the private file directory outsite of /var/www at /var/privatefiles. When downloading certain types of files - specifically docx - files are being corrupted. pdfs and other common types seem to be working fine.
File upload is working correctly as I am able to scp the files directly from the server and they are intact.
Additionally, on a test server made from a copy of the server we set up the private files inside the siteroot and that works without problem. This solution is not ideal however as we do not want the files to be accessible directly from the web.
I cannot find anything that discusses this issue, surely I am not the first person to set up a private directory this way and have docx files break?
UPDATE:
Further testing indicates that what is occurring is that drupal or php are adding 3 newline 0a characters to the start of every file served from the private file system. It has np effect on some formats but all MS files - docx,xlsx etc - are broken.
How do I fix this?
Comment: How big are your files and how much memory does your PHP has on the server? Did you get any errors logged to PHP's error log when downloading the files? Private files are served using PHP. So the culprit may be your PHP configuration (memory_limit, base path, ...). Make sure it doesn't report any errors and/or report back what you find investigating it.
Comment: my test file is 139 KB on disk (All the other broken files are of similar size). Download is still the same size but all garbage and not retrievable by word. No php errors are being logged. php config is set to allow 8MB max file size with 24M post_max and a memory limit of 128MB
Comment: Ok after looking more closely at a binary diff of a good and bad file I can see Drupal or php is inserting 3 chars at the start of the file....
Comment: I assume this is related to this issue https://drupal.stackexchange.com/questions/240016/how-to-remove-utf-8-bom-from-docx-files however I do not know how to force php NOT to do this...
Answer: We have finally solved the issue and in case it is of use will put the answer here.
Based on this php issue we realised the issue could be a closing php tag somewhere else on the site.
In the end we found three small modules - one animated a set of banner images on the site; one made some api calls for a search feature; and another created some custom blocks from an external api call.
Each of these had ?> at the end of their .module files. Removing them fixed the problem.
Why this problem went on to affect all files served I do not know.


Best suggested textbooks on Bootstrap resampling?

Question: I just wanted to ask which are in your opinion the best available books on bootstrap out there. By this I don't necessarily only mean the one written by its developers.
Could you please indicate which textbook is according to you the best for bootstrap that covers the following criteria?

The philosophical/epistemological basis for the technique that
lists domain of applicability, strengths and weaknesses, importance
for model-selection?
A good set of simple examples that show implementation,
philosophical underpinnings, preferably with Matlab?
Answer: There are two "classic" ones:
Efron, B. & Tibshirani, R. J. (1993). An introduction to the bootstrap. London: Chapman & Hall/CRC.
Davison, A. C. & Hinkley, D. V. (2009). Bootstrap methods and their application. New York, NY: Cambridge University Press.
The first one is very readable and gives you good idea what bootstrap is and what is the general reasoning behind this method. It also provides many examples and practical hints about using bootstrap in real life. The second is a really extensive review of different usages of bootstrap, with lots of examples and also examples of code written in R. I would say that those two alone give you pretty complete overview of the method and could lead you starting from the basics, up to pretty advanced topics.
If you don't know much on bootstrap yet I'll suggest starting with Efron & Tibshirani since it is written in a much simpler language and walks you through the topic step by step from the basics. Davison & Hinkley is a little bit tougher to read but provides you with many practical information and details.
Comment: I like both, and I thought they complemented one another well. It is probably a bit much to start learning bootstrap by reading both books at the same time. But if you choose one to learn the method, it is probably worth while to keep the other book in mind  for reading "at some point in the future".
Answer: It might be worth going back to the origins of Bootstrapping and learning a bit about jackknifing from sources such as Quenouille and Tukey. Personally, the book "Data analysis and regression : a second course in statistics" by Mosteller and Tukey really helped me when I was first learning about bootstrapping.
Comment: Mosteller and Tukey is a great book, but it predates bootstrapping. Jackknifing is covered there, certainly.
Comment: For sure. I find that running through the history of these kinda things helps. :)
Comment: Thanks, that's fantatstic addition to the discussion. Will certainly check these books. BTW, I just came across this review paper that adds to the history of resampling: http://www.stat.cmu.edu/~fienberg/Statistics36-756/jackknife.pdf


Wedding seating chart combinations

Question: Given the example problem described here at page 2:
Example Problem

Take a small wedding consisting only of the immediate family. There are 17 guests total
  (assume the bride and groom sit at their own sweetheart table) and since each table can seat 10 guests, only
  two tables are necessary. Let us also say that each guest must know at least one other people at their table.
  So m = 17, n = 2, a = 10, and b = 1.

where a the maximum number of guests a table can seat
    & b the minimum number of people each guest knows at their table

There are $2^{17}$= 131,702 possible combinations for seating these guests.

How is the $2^{17}$ number of combinations derived?
Comment: Bounty added,lets see.
Answer: This is a bit misleading I think. It seems to me that they have just done the following.
Every guest can choose between table $a$ or table $b$. i.e. have two choices. So this will give the total number of possibilities as $2^{17}$. But this number does not respect all the conditions in the problem. e.g. there can only be $10$ guests at every table.
In the next example there is also an error where they write
"The number of possible combinations is $4^{17} = 7.63 × 10^{11}$"
The $4$ here is supposed to be a $5$.
Comment: Thanks for taking the time to answer, you re right, this is what perplexed me. The 15th guest, for example, would only ever have one choice, not 2 etc. Just trying to see if there is something I'm missing in regards to this or some type of formula(im unaware) can be simplified to get this result.

Wedding seating chart combinations


How can I allow Domain Users to update printer drivers without any prompts?

Question: Each time Xerox release a new printer driver and we update our network printers on our servers we have to go around each domain computer and enter the Administrator details in to the update printer driver prompt. Until this is done the users cannot print.
We now have 300+ domain computers so this is becoming unrealistic. Is there a Group Policy option that allows users to just click Yes to these prompts, so when we update the printer driver on the server they can go ahead and just click Yes to these prompts?
Comment: N00b, why bother?  You can just update on the server and let the drivers trickle down to the users.  I don't see why it's 'gross' to allow clients to obtain print drivers from the print server (with appropriate point-and-print GPO in place).
Comment: This sounds like an [xy problem question](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem).  Why are you making users update their own drivers?  That's gross. Why not update the drivers for them?
Comment: They have to accept the driver update that's pushed out via the server. That's the point in the question. They aren't doing manual driver updates as you suggest.
Comment: I think you're kind of missing what I'm saying.  Why don't you update the drivers on the clients (via script, or whatever configuration management or patch management system you have) when you do the update on the server? (Rather than waiting for the client to connect to the print server and get prompted to update to the newer drivers.)
Answer: You can change the Point and Print Restrictions policies.  Reference this article from Microsoft.  The settings are located at:

Computer Configuration\Policies\Administrative
  Templates\Printers\Point and Print Restrictions

From the article:

You can use the Point and Print Restrictions Group Policy setting to
  control how users can install printer drivers from print servers. You
  can use this setting to permit users to connect to only specific print
  servers that you trust. Because this setting prevents users from
  connecting to other print servers that could potentially host
  malicious or untested printer drivers, you can disable printer driver
  installation warning messages without adversely compromising security.


Kernel of a homomorphism is a subobject?

Question: Background
I'm currently reading an abstract algebra textbook, written in a category-theoretical way. The contents are similar to any other algebra textbook. It covers groups, rings, $R$-modules, $R$-algebras, fields, etc. One special thing (in my opinion) about this textbook is that the author states definitions, theorems and exercises using "$\square\square$", which is an interface for algebraic structures mentioned above. For example,

Definition. Let $X$, $X'$ be a $\square\square$. For each binary operation $\ast$ equipped in $X$, if there exists a bijection $\varphi: X\rightarrow X'$ that satisfies $$\varphi(x\ast y) = \varphi(x)\ast\varphi(y)$$ then we say that "$X$ and $X'$ are isomorphic as $\square\square$". Moreover, $\varphi$ is called an $\square\square$-isomorphism.

I have no problem understanding this - I can plug in groups, rings in $\square\square$ - and I really like the way the author introduces isomorphism in this way, since it gives the general idea of an isomorphism and isomorphic structures.
I was doing fine, until I started a chapter on subobjects...
The author chose not to define the (category theoretical) term object, and introduced subobjects as the following.

Definition. Let $X$ be a $\square\square$, and let $Y\subseteq X$. Using the binary operations of $X$, if $Y$ itself forms a $\square\square$, then $Y$ is a sub-$\square\square$ of $X$, and we write $Y\leq X$.

I also had no problem understanding the definition, (I don't know if this is actually correct, I have no reason not to believe the definition in the book) since I have already studied subgroups and (vector) subspaces. But as I read on, I felt that there must be something I don't know yet.

The Problem

Let $\varphi:X\rightarrow Y$ be a $\square\square$-homomorphism. Show that $\ker \varphi \leq X$.

The statement itself looks really simple. But I got stuck when I tried to prove this. If $\square\square$ were some concrete algebraic structure such as groups or rings, I could prove this, using the subgroup/subring criterion.
One thing I realized was that such criterion is different for different algebraic structures.

My Question (TL;DR)

What is a subobject?
Is the statement in the problem true for general algebraic structure $\square\square$?
If the statement is true, how would I prove this general statement? (Other than proving for each algebraic structure)

The question became too long, but thanks for reading and any references, hints are always welcome. Thanks in advance.
Note. I keep referring to category theory, but I have not studied category theory. It's just that I got curious and did some googling online for objects and subobjects (since the author won't be defining it) and found many results being related to category theory.
Answer: Before we start, I just want to note one thing. While most algebraic structures have at least one binary operation, they can also have nullary operations that need to be preserved by homomorphisms. Nullary operations take no inputs and given an output. In other words, they're just constants. For example, groups have their identities and unital rings have both $0$ and $1$ that need to be preserved.
You might even make things more general by having any finite arity, or even infinite arity operations.

What is a subobject?

In this specific context, I would say it's a subset that is closed under all the operations of the algebraic object, be that binary operations (like the $*$ mentioned) or nullary operations.
Perhaps more generally than you need, a subobject in a category can be defined to be an equivalence class of monomorphisms into that object, where two such monomorphisms are equivalent if they factor through each other. If none of that made sense, don't worry. You'll learn all the necessary details in time.

Is the statement in the problem true for general algebraic structure $\square\square$?
If the statement is true, how would I prove this general statement? (Other than proving for each algebraic structure)

To even define $\ker \varphi$, we need some notion of a zero in $Y$. This is why I mentioned nullary operations above: $0$ is a nullary operation. Granted this, $\ker \varphi$ can be defined as the subset of elements of $X$ that $\varphi$ maps to $0$.
To check if this is a subobject, we need to check that it's closed under any binary operations and any nullary operations. If $x$ and $x'$ are in the kernel, then $x *_X y$ is in the kernel precisely if $\varphi(x *_X y) = 0 \leftrightarrow \varphi(x) *_Y \varphi(y) = 0 \leftrightarrow 0 *_Y 0 = 0$. For any nullary operation $e$ (i.e., a constant), $e_X$ is in the kernel iff $\varphi(e_X) = 0 \leftrightarrow e_Y = 0$.
So for this to be true in general, this zero element has to be closed under all the binary and nullary operations of the algebraic structure (in particular, the only nullary operation can be $0$ itself).
This should make some amount of sense. For groups, all this works perfectly. For rings there's a bit of a wrinkle with unital vs. non-unital rings. For unital-rings, kernels aren't really subobjects. The objects you get are (in general) non-unital, so they aren't algebraic objects of the same type. This happens precisely because $1 \neq 0$ in general, so $1$ is rarely in the kernel (remember that unital ring homomorphisms have to take $1$ to $1$).
For non-unital rings, things work out better. Non-unital ring homomorphisms don't need to worry about $1$ at all, so the only thing to check is that $0$ is closed under $*$ and $+$. Since $0 * 0 = 0 + 0 = 0$, kernels are subobjects.

Just an addendum. An example of an algebraic structure that most people don't really thing of as algebraic is pointed sets. For pointed sets, there aren't any binary operations: just a single nullary operations giving a specified point in the set. Homomorphisms of pointed sets have to preserve this specified point and the criterion above shows that we can use the specified point to define kernels and show that they're subobjects.
Comment: Thank you very much for your detailed answer. I have another question related to your answer. Is it sufficient to show that $\ker\varphi$ is closed under the operations? As far as I know, algebraic structures have axioms (group axioms, ring axioms) that hold. Does closed-ness imply the axioms? Or is proving the axioms actually unnecessary?
Comment: @zxcvber Since the operations are the same in the subobject, any equational axioms should still hold. Existential axioms like inverses in groups should really be thought of as as operations (e.g. a unary operation $x \mapsto x^{-1}$). So you'd have to check that your "zero" is closed under those operations as well (and indeed $e^{-1} = e$).
Comment: Right. That was rather simple than I expected. Thank you, I learned a lot.