Which fields satisfy the Freshman's Dream?

Question: It is well-known that the Freshman's Dream, $(a+b)^p = a^p + b^p$, holds in fields of characteristic $p$. For $p = 2$, in fact those are the only fields; for, $(a+b)^2 = a^2 + b^2 \Rightarrow 2ab = 0$ for each $a, b$, so in specific the field has characteristic $2$. But $(a+b)^3 = a^3 + b^3$ is satisfied by every element of $\mathbb{F}_2$, as well as in fields of characteristic $3$. In fact this is the only field of characteristic $\ne 3$ in which this identity holds; the identity is equivalent to $3ab(a+b) = 0$, which in characteristic $\ne 3$ means $ab(a+b) = 0$ or, letting $b = 1$, $a = 0,-1$.

In which fields does the identity $(a+b)^p = a^p + b^p$ hold for every $a, b$ (with $p$ fixed)?
Comment: ...answering my question seconds before I post it... are you a wizard, @MartinBrandenburg?
Comment: A finite prime field $\mathbb{F}_\ell$ has this property iff $\ell-1|p-1$. But I assume that you are interested in arbitrary fields?
Comment: It may be good to first consider the restriction of this question to finite fields.
Comment: @MartinBrandenburg Yes, I am, though the motivation came from the case of finite (not necessarily prime) fields.
Answer: Claim: Let $n \geq 2$ be a natural number and $F$ be a field. Then $F \to F, a \mapsto a^n$ is additive iff $F$ has positive characteristic $p$ and

either $F$ is finite, say $|F|=p^e$, and $p^k \equiv n \bmod p^e-1$ for some $k$,
or $F$ is infinite and $n$ is a power of $p$.

Proof. First we note that if $a \mapsto a^n$ is additive, it is actually a field homomorphism (since it is multiplicative anyway). It follows that if $F=\mathbb{F}_p$ for a prime $p$ the map is additive iff it is the identity iff $a^{n-1} = 1$ for all $a \in \mathbb{F}_p^*$ iff $p-1\mid n-1$, using that $\mathbb{F}_p^*$ is cyclic.
If more generally $F=\mathbb{F}_{p^e}$ is a finite field, the map is additive iff it equals one of the elements of $\mathrm{Gal}(\mathbb{F}_{p^e}/ \mathbb{F}_p)$. This group is cyclic, generated by the Frobenius. Hence, the condition becomes $\forall a \in F : a^n = a^{p^k}$ for some $k$. We may assume $a \in F^*$ here. Using that $F^*$ is cyclic, this reduces to $p^k \equiv n \bmod p^e -1$.
Now let $F$ be an infinite field, and consider the equation $(a+b)^n=a^n + b^n$ in $F$. It is trivial for $b=0$. If $b \neq 0$, we may as well assume $b=1$ by dividing $b^n$ on both sides. Thus, we reduce to $(a+1)^n = a^n+1$, which becomes $P|_F=0$ for $P(x)=\sum_{k=1}^{n-1} \binom{n}{k} x^k$. Since $F$ is infinite, this implies $P=0$, i.e. $\binom{n}{k}=0$ for all $0 < k < n$. In particular, $n=\binom{n}{1}=0$ in $F$, and we see that $F$ has positive characteristic $p$. But then these equations already hold in $\mathbb{F}_p$, and we get $\binom{n}{k} \equiv 0 \bmod p$ for $0<k<n$. Now it is well-known that $n$ is a power of $p$: Write $n = p^v m$ with $p \nmid m$. Since $a \mapsto a^{p^v}$ is injective and additive, it follows that $(a+b)^m=a^m+b^m$. By the same reasoning as above, it follows $\binom{m}{k} \equiv 0 \bmod p$ for all $0<k<m$. But since $\binom{m}{1}=m \not\equiv 0 \bmod p$, it follows that $m=1$. $\square$
The condition is in both cases that $n \bmod \exp(F^*)$ is a power of $p$. Here, we define the exponent $\exp(G)$ of a group to be the nonnegative generator of the ideal $\{z \in \mathbb{Z} : \forall g \in G : g^z=1\}$. If $F$ is a finite field, $\exp(F^*)=|F|-1$, and if $F$ is an infinite field, then $\exp(F^*)=0$.
Comment: This argument is not quite complete; from $P = 0$ it does not follow that the coefficients of $P$ are zero unless $F$ has characteristic zero, or at least sufficiently large characteristic.


Iframe always showing vertical scroll in edge browser

Question: I'm using iframe in my application, iframe style with no scroll. And it is working fine in the Chrome browser. Whereas in the Edge browser always one vertical scroll bar is showing. Unable to remove it in the Edge browser.
Answer: [DUPLICATE] How do I make an HTML iFrame fit the whole page without needing to scroll?
To get an iframe that takes the whole page without scrollbars You can try this :
Best regards.
Nicolas.

html,body{
            width:100%;
            height:100vh;
            overflow:hidden;
            margin:0px;
            padding:0px;
            border:none;
        }
        iframe{
            width:100%;
            height:100vh;
            overflow:hidden;
            margin:0px;
            padding:0px;
            border:none;
        }

Comment: @karthikraja kandasamy If this is the answer you're looking for please mark it as solved.


Is there a simpler way to calculate this?

Question:
A number of five different digits is written down at random. Find the probability that the number has the largest digit in the middle.

My Solution:
If $9$ is in the middle then the first place from left can be filled in $8$ ways. Remaining $3$ places can be filled in $^8P_3$ ways.
If $8$ is in the middle then the number of ways are $7\times (^7P_3)$
This would go till $3(^3P_3)$
Thus, probability$=\frac{\sum_{n=3}^8n(^nP_3)}{9(^9P_3)}$
I calculated using calculator and got $\frac7{36}$
Is there an easier way to calculate this (in a time bound exam)?
I tried writing $n(^nP_3)$ as $(n+1-1)(^nP_3)=(n+1)(^nP_3)-(^nP_3)=(n+1)(n)(n-1)(n-2)-(n)(n-1)(n-2)$
I was hoping to get telescopic series, but not getting that.
Another try:
$n(^nP_3)=\frac{n\times n!}{(n-3)!}\times\frac{3!}{3!}=6n(^nC_3)=6(n+1-1)(^nC_3)=6(4(^{n+1}C_4)-(^nC_3))$
Not able to conclude from this.
Comment: To be clear... are you or are you not allowing leading zeroes?  If you are allowing leading zeroes, then the probability should be very simply $\frac{1}{5}$... hardly any thought required.  One of those five positions will be the largest and it is equally likely to be any of the positions.  The problem becomes harder if you don't allow leading zeroes.
Comment: @JMoravitz leading zeros are not allowed.
Answer: If you allow a leading zero then there are $\frac{10!}{5!}=30240$ possible numbers with distinct digits, of which a fifth, i.e. $6048$, have the largest in the third place
Of these, a tenth have a leading zero, i.e $3024$, of which a quarter, i.e. $756$, have the largest in the third place
So prohibiting a leading zero, that leaves $27216$ possible numbers with distinct digits, of which $5292$ have the largest in the third place.  $\frac{5292}{27216}=\frac{7}{36} \approx 0.194$
You can do this with smaller fractions rather than counts: $$\dfrac{\frac15  - \frac14 \times \frac1{10}}{1-\frac1{10}} = \dfrac{8-1}{40-4}=\dfrac{7}{36}$$
Comment: The whole fun lies in the fractional part ! $\;\;$ :)
Comment: Hey, thanks. Just to be clear, are we saying we'll get the same result whether we use distinct digits or repetition is allowed?
Comment: No - you would get a different answer with repetition allowed, and would need to define the meaning of *"the largest digit in the middle"* more carefully if there can be ties for *largest*
Comment: Oh, yes, thanks.
Answer: If you allow leading zeroes, then this is simply $\frac{1}{5}$ as every digit is equally likely to appear at each position.
If you do not allow leading zeroes, then the probability gets a bit worse as if a zero digit appears then it is more likely to be the center digit than other digits due to the restriction of zero not being allowed as the leading digit.
If you do not allow leading zeroes, then I'd break into cases based on if a zero was or was not used.  For those where zero is not used, again the simple answer of $\frac{1}{5}$ applies.  Using your notation, no zero appears with probability $\frac{~^9P_5}{9\cdot ~^9P_4}$
For those where zero is used, first check that the zero doesn't go in the middle which occurs $\frac{3}{4}$ of the time, and then given that happened check that of those nonzero terms the largest goes into middle which occurs $\frac{1}{4}$ of the time, for a combined probability of $\frac{3}{16}$.  The probability of a zero appearing is $\frac{4\cdot ~^9P_4}{9\cdot ~^9P_5}$
This gives a final answer of:
$$\frac{~^9P_5}{9\cdot ~^9P_4}\cdot \frac{1}{5} + \frac{4\cdot ~^9P_4}{9\cdot ~^9P_4}\cdot \frac{3}{16} = \frac{7}{36}$$
Comment: Thankyou, I understood your approach.


What iterate mean in activemq source code

Question: I mean the iterate() func in org.apache.activemq.thread.Task, which have implements in Queue,Topic, etc.
I really can't understand what it mean and what's used for.
Can somebody explain it in an easily understood way?
Answer: This is an internal interface in ActiveMQ, you shouldn't worry about it ;-)
This is just an abstraction about splitting a long job into smaller tasks: instead of using a thread for a long time, this interface allows to split a task between several iteration, each iteration using a thread for a short time.
Some "repeatable" task use this interface too: As this is an internal interface of the current implementation of ActiveMQ, there is not really strict rules about it.


Does octave not matter when tuning?

Question: Why does it not matter what octave you're tuning to? If you wind a string to two different octaves of the same note, surely it's going to have a big effect on the sound, no?
Comment: For the extreme bass and treble of a piano, it does matter -- the octave are stretched.
Answer:
Why does it not matter what octave you're tuning to?

If you want to set a string to a certain pitch, of course it does matter what octave you adjust the string to.
Setting a string to A3 (220Hz) is not the same as setting it to A4 (440 Hz). Not only will the sound be different, but you might make the string very hard to play if it is too slack, or break your string (or your instrument!) if it is too tight.
However, "tuning to" can refer to the reference you are listening to while you tune. And because of the phenomenon of octave equivalence, it is possible to listen to A3 as a reference while adjusting an instrument to play A4, as long as you have some way of not getting confused about which octave you are actually adjusting the string to.
This is normally quite easy, because usually an instrument is approximately in tune - the strings might be a semitone out-of-tune at the most. So if you need to tune the A string on your guitar, you can play any A on the piano*, and tune your guitar to the correct A, because you know that you only need to adjust the guitar slightly.
*Notes near the extremes of the piano might not be good choices, because the strings behave in a somewhat 'less-ideal' way.
Comment: I agree, except octave equivalence has little to do with it - especially because the answer to the linked question shows that there is essentially nothing special about the octave other than the high overlap of overtones, which higher pitches from the overtone row have too. A trained musician could use a reference pitch at, say, a fifth from the pitch they're tuning (like string players). An octave is just the easiest interval (apart from a prime) from the reference pitch. A tenth (or rather a seventeenth) should be possible as well, if you practice a bit (but any higher would be tricky).
Comment: @11684 I guess it's *possible* to tune using any reference, if you have sufficient training, or for some people maybe even no reference. The octave is often easier in 12-TET though not just because of overtone similarity, but also because octaves are perfect, while fifths are a little flat. I used to assume that octave equivalence was only due to overtone coincidence but I've also read that there is some physiologically octave-related structure in the "Medial Geniculate"... whatever that is.
Comment: Yes, in 12-TET the octave is easiest (even more so than in other temperaments). That has nothing to do with octave equivalence either - and as I said I agree with your answer except the octave equivalence bit. In 12-TET octaves are the only pure interval so it's the only interval with which you can use the overtones to tune. If you have to tune a pure interval, you can use higher overtones as well, but the higher the harder to hear. Octaves are easiest because the first overtone is the octave, not because of "octave equivalence" (this in line with the Physics.SE answer you linked to).
Comment: @11684 to my mind, octave equivalence encompasses everything that makes notes an octave apart seem 'easy to equate' - whether that's the high overlap of overtones, or any deeper physiological reason - and my line of thinking is that in a general sense, those are the same things that make it easy to tune a string to A4 while listening to A3. I didn't want to get too much into the detail of using overtones to tune as I wasn't sure the idea the OP was referring to that technique in particular.
Comment: then I suggest removing the link to Physics.SE since it specifically asks for something deeper than overlapping overtones, my comments being proof of the resulting confusion.
Comment: @11684 as per my previous comment, AFAIAA there may well be something deeper to octave equivalence than overlapping overtones - and if so, whatever that is would be highly likely to make it easier to tune with a note an octave away from you target pitch than with a note some other interval away. It seems to be something of a developing area of human knowledge.
Comment: Then link to a source that says that, because the top answer from the Physics.SE question denies the possibility of a deeper reason. It may well be wrong so if you want please make the case in favour of octave equivalence, but as it stands the only reference you provide actually contradicts your assertion.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/87596/discussion-between-topo-morto-and-11684).
Comment: Even better, theoretically one can listen to ANY NOTE in order to tune to anything, as long as your relative pitch is just inhumanly good.
Comment: @user45266 or even no reference (as per my second comment above)...
Comment: @topomorto Of course, for certain people.
Answer: True enough, sonically. You'll also probably end up with two different guitar parts too. 'Why does it not matter?' - it does.
I think you may be referring to tuning an A string (for example) to an A note - but maybe an A note in a different octave. If so, the frequencies of each note are double or haqlf to arrive at another A. It will be an 'octave copy' of what you need, but for a lot of folk, it's a good reference point. Not as good as the actual note you need to match, but good enough. We do it all the time when singing. If a man and a woman were singing the same melody, they'd be an octave or two apart, without thinking about it. Neither would be trying to reach the other's actual notes, only octave copies thereof.
That apart, it's impossible to 'wind a string to two different octaves'. There's only one string, therefore only one note available. The strings on any instrument are the correct gauge for the notes they're going to be tuned to. Go down an octave and they're too floppy; go up and they're way too tight. Neither move is sensible.
Answer: @topomorto provided a very nice answer so I won't repeat what he already wrote.
But... FWIW, it does matter to me in which octave the reference pitch is.

1 (E)   329.63 Hz   E4
2 (B)   246.94 Hz   B3
3 (G)   196.00 Hz   G3
4 (D)   146.83 Hz   D3
5 (A)   110.00 Hz   A2
6 (E)   82.41 Hz    E2

When I tune the low E2 string, I have trouble tuning it to the high E4 string as a reference pitch.
I usually fret string 4 at the 2nd fret for an E3 reference pitch, and also fret the 6 string at the 5th fret for the unison with the open string 5 (A2.)
In this sense the octave does matter to me for tuning. If the reference pitch is 2 octaves away, I can't hear the "beating" between the two pitches as clearly.
Comment: The 'beats' would hardly be discernible at two octaves apart. I can't even hear them! +1 for beats.
Answer: Just to add the boring mathematical basis for the other excellent answers: the reason we have the "octave equivalence effect" is because tones an octave apart, a 2/1 ratio in frequency, are the closest to being the same tone mathematically, a 1/1 ratio, and we hear this similarity.
Comment: @CarlWitthoft That's because a minor second is close to it numerically, but not multiplicatively. What we hear as "close" is how well the waveforms sync up. A note one octave up would synchronize every other period. See [this explanation](https://music.stackexchange.com/a/3850/56120)
Comment: That's not accurate --- take a look at the ratio of, say, a minor second. That's much closer to 1:1 but hardly "feels" the same.

Does octave not matter when tuning?


Where is the module registry stored outside the database?

Question: As a long time Drupal dev, I should probably know the answer to this question, but I'm stumped by the behavior I'm seeing.
Let's say I have a local and a remote site.  On the remote site a module is uninstalled properly and the module code is removed from the file system (git tracks the deletion, etc).
Then to get my local installation up to date, I completely drop all tables in my database (it's completely empty) and I do a git pull, so the local module files are deleted. I then get the remote database and load it into my local.
In that situation there are no database remnants from my old local install and the file system is updated with the deleted modules.  It should reflect the remote site completely.
However, when I load up the local site I get all the 'XXXX module is missing" and everything breaks.  I run the registry rebuild via drush rr, and it fixes everything.  But then, going forward into the future, I continue to see this broken registry each time I reload the site from the remote database (meaning I have to rr each time).
This strikes me as so odd...because where are those old registry records stored outside the database? Why, if I have a fully clean database, does it recognize old modules as missing?
And of course...how can I 'clean them up' permenantly?
Comment: You're not copying the cache table data down are you? If so, script something to stop that happening, it stands to reason there could be invalid path references in there from one environment to another. If you're not, check any non-DB cache you have enabled (redis/memcache/etc) has been cleared properly on your local machine
Comment: I want copying any cache files when moving the database...as you mention, and as mentioned below, it must be an external cache retaining the 'bad' module data.
Comment: How aggressive is your op code caching?
Answer: Common causes:

External cache (Memcache, etc) that is not purged on rebuild
Your SQL import contains cache from prod (I tend to make sure backups make cache tables structure-only).
Your SQL is imported into a DB which contains tables, but does not drop some of them (such as cache). (I personally drop and create the DB before each import).
The module is still enabled/present in the system table (confirm in your SQL that the row in the system table is gone/disabled & uninstalled).
Something else on your site depends on it and is re-enabling it (eg master module, feature dependencies, etc (although dependencies usually block things from being disabled)).
Sometimes worth doing a drush cc drush after importing the SQL. When in doubt, clear caches ;)
Comment: Nice, thanks...I think in my case it was an external cache that wasn't fully cleared (because nothing else really makes sense).  I kinda suspected that must be where it was, but wanted confirmation.  Thanks!


RedirectIfAuthenticated redirect if attempt to open other login form

Question: I have two login forms with two different tables.One is default with /login route and the other has route /myportal. I have extra logincontroller
    protected $redirectTo = '/student-home';
    public function showLoginForm()
    {
        return view('my_portal');
    }

    public function logout(Request $request)
    {
        $this->guard()->logout();
        $request->session()->flush();
        $request->session()->regenerate();
        return redirect('/my_portal');
    }

    protected function guard()
    {
        return Auth::guard('web_student');
    }

    public function username ()
    {
        return 'username';
    }

This login is working fine. But, I am having problem with RedirectIfAuthenticated
public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {
            return redirect('/home');
        }

        else if(Auth::guard('web_student')->check())
        {
            return redirect('student-home');
        }
        return $next($request);
    }

Now, if the user is already logged in, it is redirected to /student-home only if the route is /login and not /my-portal. i.e only if i click on regular form not this extra form I created. How can I redirect to student-home if user clicked on /my-portal?
Answer: You can connect a controller to the my-portal route with :
Route::get('test', 'exampleController@example') ;

Then in the controller function, you can check if the user is already logged in by
public function example() {
    if(Auth::check()) {
        //This condition will run if the user is logged in !
        return redirect('student-home');
    }
    //Do whatever you want if user is not logged in!
}

Hopefully, this answers your question!
Answer: Please change your RedirectIfAuthenticated middleware like this
public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {

           if(guard == 'web_student') {
                return redirect('student-home');
             }else return redirect('/home');
        }
    return $next($request);
}

The problem with your code is that the following segment will always true if a user is logged in. You have to check for whether or not a specific guard is set, inside this if statement if you want to redirect them accordingly.
if (Auth::guard($guard)->check()) {
            return redirect('/home');
        }


How to make custom PSR-7 ResponseInterface to reduce boilerplate?

Question: I'm implementing a service using Slim 4 framework which will pretty much always be returning JSON responses. I'm trying to keep all of the responses uniform with a structure similar to this:
{
    "status": "success",
    "data": {"foo": "bar"} // the actual data relevant to the request
    "messages": []
}

In the most basic format, this is the code that I would need to do to make responses like this:

public function __invoke(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface {

    // Do something

    $response
        ->getBody()
        ->write(json_encode([
            'status' => 'success',
            'data' => [
                'foo' => 'bar'
            ],
            'messages' => [],
        ]));
    return $response
        ->withHeader('Content-Type', 'application/json')
        ->withStatus(200);
}

Right now, I've been using a basic helper class that essentially wraps most of that boilerplate into a few static functions, so I can write a response like this:
public function __invoke(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface {

    // Do something

    $data = ['foo' => 'bar'];

    return APIResponse::success($response, $data)->into();
}

However, now I'm encountering an issue where I'd like to make the responses slightly more complex which would require additional dependencies, such as custom serializer classes. The naive option would be to continue to pass additional dependencies to APIResponse::success($response, $serializer, ..., $data), but that's obviously bad and not a good long-term option.
Another option I thought of would be to make an APIResponseFactory, which would take in any dependencies in the constructor and be filled via PHP-DI. That would be a little cleaner, but every route handler would need to have the factory injected and I'd still need to manually pass $response every time.
return $responseFactory->success($response, $data);

So, what I'm considering now is trying to build a custom class that would implement ResponseInterface, thus allowing me to build in the boilerplate helpers into every request handler automatically. I was looking over the current PSR7 ResponseInterface implementation that's being used in my project, and the code comments mentioned that the class should never be extended, and suggested using a Decorator Pattern. So, this is a basic pseudocode implementation I made for my current idea.
class MyCustomResponse implements ResponseInterface {

    private $serializer;

    private $actualResponse;

    // any other dependencies

    public function __construct(ResponseInterface $actualResponse, Serializer $serializer /*, other dependencies */) {
        $this->actualResponse = $actualResponse;
        $this->serializer = $serializer;
    }

    // Use this class as a decorator and pass all ResponseInterface calls to the external implementation
    // EDIT: It looks like I can't use `__call` to fulfill the interface, so I'd need to manually define to functions, but you get the gist.
    public function __call($name, $args) {
        return $this->actualResponse->$name(...$args);
    }

    public function success($data) {
        $this->actualResponse
            ->getBody()
            ->write($this->serializer->serialize([
                'status' => 'success',
                'data' => $data,
                'messages' => [],
            ]));
        $this->actualResponse
            ->withHeader('Content-Type', 'application/json')
            ->withStatus(200);
        return $this;
    }
}

Thus, I would (hopefully) be able to return responses like this:
public function __invoke(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface {
    $data = ['foo' => 'bar'];
    return $response->success($data);
}

My actual questions: Is this the proper way to implement custom helper methods for PSR-7 Response handlers? Is there a better way? Is writing helper functions like this bad practice? PSR-7 interfaces seem to be, for lack of a better description, low-levelish and verbose, which makes me worry that writing a wrapper like this somehow goes against the intent of the standard. Are there any other ways to follow the standard but reduce boilerplate and keep responses uniform?
Comment: This was a good question until the end. Your "actual questions" are all asking for opinions. I'd suggest editing to include actual problems you've faced trying to implement this code.
Comment: To be clear, most of this was simplified for the sake of the post. I am currently using middleware to set the content type. I would prefer to not inject the serializer into every controller, since the pattern I'm using has one class for each route; that would work fine, but it's a lot of redundant typing. An abstract base class might work, but I think I'd still need to add the serializer to the controller constructor, right?
Comment: Here's [the `APIResponse` class I have been using](https://github.com/marcusball/virtual-phone-server/blob/f30294941e2d8de43f14ae74e730cdc120b6b131/src/API/APIResponse.php) and referenced at the beginning of the question.
Comment: No, it'd be the opposite case in which the child _would_ define it's own constructor to receive other injected dependencies. Like, if the Base class just required the serializer, but a child class required `DependencyA` and `DependencyB` classes, I'd still need to make the child class constructor take all three including the serializer, so I could call `parent::__constructor($serializer)`.
Answer: A 'nice' controller actions return $response->success($data); can be done via

https://php-di.org/doc/definition-overriding.html#decorators
https://php-di.org/doc/best-practices.html#using-libraries - interface with a implementation assotiation

This a bad practice

The {"status":"", "data":[], "messages": []} format may change
Appearing file, stream, etc responses

Forgot about the ResponseInterface $response argument, how was it done with the array $args argument.
Inject the response factory to each controller, so your actions would look like
public function __invoke(ServerRequestInterface $request): ResponseInterface
{
    // Do something

    return $this->responseFactory->createJson($data);
    // OR
    //return $this->responseFactory->createSomethingElse();
}

Comment: A few opinions for my use case: I'm not sure I see how the "bad practices" are applicable.  I specifically want to define a *standard* output format; yes, it might change in the future, but if it did, I'd want that format change reflected in **all** responses. I'm not considering file/stream responses, but if I did, I would add different response methods; this is just a stripped down example for the question. This might actually be the best answer, but I still don't like that I would have to manually inject the `responseFactory` into *every* route controller, which is what I'm trying to avoid.
Answer: You've written multiple times that you'd like to avoid injecting the dependency for every controller, I don't think you should avoid using dependency injection since it's not that much work load and it comes with a lot of advantages such as:

testability You can mock all the dependencies at truly test everything
modularity Thus way your class is isolated from others and does not depend on global and not clear dependencies
maintainability You have a clear definition of what that class needs to work, and I assure you that's going to be essential a few years from now

A dependency injection container really helps with the amount of code written to apply di.
My controllers usually end up looking something like this:
    class MyController implements RequestHandlerInterface
    {
        private Presenter $presenter;

        public function __construct(
            Presenter $presenter
        ) {
            $this->presenter = $presenter;
        }

        public function handle(ServerRequestInterface $request): ResponseInterface
        {
            return $this->presenter->present(
                200,
                [
                    'status' => 'success',
                    'data' => $data,
                    'messages' => [],
                ],
                //other presenter arguments here such as a class instance that defines a standard Metadata object to be included in all Responses
            );
        }

Your presenter can have it's dependencies too and it's all kept clean and tidy.
The Slim 4 routing setup will be something like:
$app->get('/route_name', MyController::class);

This way it's DI Container manner to inject everything and routing page is clean and tidy too!
Comment: Yeah, I am using PHP-DI, so I may have to go this route. Basically, the main thing that *feels* wrong to me is that if **every** route will need that dependency injected, it feels like there should be a way to abstract that away so it wouldn't need to be explicitly added to every controller class. I'd still need to manually pass the `$response` to the serializer/`Presenter` for every response too. Conceptually it feels like it's unnecessary duplication, but it's looking like that may be the only option.


How to set additional node type options programmatically?

Question: When creating a node type programatically, some node type options can be set in hook_node_info, including name, base, description, has_title, title_label, has_body, and help. As far as these node options go, using hook_node_info is cleary the canonical way of doing it.
However, some additional node type options cannot be set using this hook, and I have not yet found any canonical documentation that explains how do do this.
The options I look for a method of setting programatically include:

whether commenting by default are open or closed;
whether the node should be published, promoted, sticky and/or have revisions enabled upon creation;
whether it should display author and date information.

The solution I currently use is to set the appropriate database variables in hook_install for the module that creates my_nodetype to the defaults I want, e.g.:
variable_set('comment_my_nodetype', COMMENT_NODE_CLOSED);
variable_set('node_options_my_nodetype', array('status','promote'));
variable_set('node_submitted_my_nodetype', FALSE);

I figured out this solution by reading the source code to discover that these database variables determine behavior at runtime.  I've not found documented anywhere how one should go about setting these additional node type options.
Is there a better way of doing this than the improvised soluton I currently use?
Answer:
Is there a better way of doing this than the improvised soluton I
  currently use?

I don't think so. Also I don't find it improvised.

Here's a D7 module I once made that creates a new content type: https://github.com/leymannx/drupal-personality-test/blob/master/personality_test.install
/**
 * Implements hook_install().
 */
function MYMODULE_install() {
  node_types_rebuild();
  $types = node_type_get_types();

  // Add a body field
  node_add_body_field($types['MY_CONTENTTYPE']);

  // Add custom fields
  add_custom_fields();

  // Default to not to be promoted
  variable_set('node_options_MY_CONTENTTYPE', array('status'));

  // Disable comments
  variable_set('comment_MY_CONTENTTYPE', COMMENT_NODE_CLOSED);

  // Hide date and author information
  variable_set('node_submitted_MY_CONTENTTYPE', FALSE);

  // Disable node preview
  variable_set('node_preview_MY_CONTENTTYPE', 0);

  // Disable menu entry
  variable_set('menu_options_MY_CONTENTTYPE', array(0));
}

I experienced just the same and solved it exactly like you via hook_install. If I remember it right, I probably found the code in core when looking how the article and page node types get created.

Related: How to set node type options programmatically (where another tiny module gets recommended you'd need to have everything together in hook_node_info).


Rotas em arquivos separados

Question: Como coloco rotas em arquivos separados?
var express = require('express');
var App = express.Router();
var Notas = require('../api/notas');

App.route('/notas')
    .get(Notas.read)
    .post(Notas.create);

App.route('/notas/:id')
    .get(Notas.profile)
    .put(Notas.update)
    .delete(Notas.delete);

É bom separar as rotas?
Answer: Você pode separar as rotas por arquivo. Para isso crie um novo Router no novo arquivo e referencie no seu arquivo principal de rotas:
app.js
const express = require('express');
const app = express.Router();
const notas = require('../api/notas');

app.use('/notas', notas);

notas.js
const express = require('express');
const router = express.Router();

const get = async (req, res) => {
  res.jsonp({ mensagem: 'OK' });
}

router.get('/', get);

module.exports = router;

Router
A router object is an isolated instance of middleware and routes. You can think of it as a "mini-application", capable only of performing middleware and routing functions. Every Express application has a built-in app router.

Em tradução livre:

Um objeto router é uma instância isolada de middleware e rotas. Você pode pensar nisso como uma "mini aplicação", capaz apenas de realizar função de middleware e roteamento. Toda aplicação Express tem um roteador de aplicativos integrado.

Rotas em arquivos separados


Demonstrating equality of Extended Cauchy-Schwarz Inequality

Question: I have a bit of a problem with the Extended Cauchy Schwarz Inequality, specifically at the line
"with equality if and only if b = cB^(-1)d for some constant c."

As such, I'm having problems understanding the following lemma, at a similarly worded line:
"with the maximum attained when x = cB^(-1)d for any constant c != 0."

How do I demonstrate that the equality holds/maximum is attained if b = cB^(-1)d ? Most resources I found cater to general linear algebra courses, so it is very hard for me to relate to this text (Johnson & Wichern, Applied Multivariate Statistical Analysis).
Answer: Presumably you remember $x'y=x\cdot y = \|x\|\|y\|\cos\theta$ from your multivariable calculus classes. So the dot product is maximized when $\cos\theta=1$, which means $x$ is a positive scalar multiple of $y$.
Following the proof and applying this, equality holds here if and only if $B^{1/2}b$ is a (positive) scalar multiple of $B^{-1/2}d$. But $B^{1/2}b=cB^{-1/2}d$ means $b=cB^{-1}d$.


Notation for element-wise function application

Question: Is there some kind of specific notation I could use to specify that function $f$ is applied to each element of matrix $W$ and not to a matrix as a whole. Specifically, I am writing about applying activation function for a layer of neural network. Or just writing this is clear enough: $f(W)$?
Comment: If the shape of $W$ is rectangular, then there is no ambiguity in your notation since the only way to evaluate the function is element-wise. When $W$ is square, then matrix-wise evaluation can be attempted. For Neural Networks, rectangular matrices and element-wise function evaluation are the norm.
Answer: If $W_{ij}$ represents the elements of the matrix, then $f(W_{ij})$
Answer: An elegant choice of notation would be $f \circ W$ where $\circ$ denotes function composition, because
\begin{align*}
(f \circ W)_{i,j}
&= (f \circ W)(i,j) \\
&= f(W(i,j)) \\
&= f(W_{i,j})
\end{align*}
Answer: I think there are no common notation to describe elementwise function application, but for some binary operators like $+, \cdot$ it is common to use $\oplus, \odot$ in neural networks. Some programming languages like Julia adopt dot operator f.(W), X .* Y to denote elementwise application. $f \circ W$ is not appropriate because
$$
\exists W, \exists i, j, \exp(\text{get}_{ij}(W)) = \exp (W_{ij}) \ne (\exp (W))_{ij} = \text{get}_{ij}(\exp(W)),
$$
this means $\exp \circ \text{get}_{ij} \ne \text{get}_{ij} \circ \exp$.
I personally like to use adding a symbol $\circ$ or others to the bottom or top of the function like $\overset{\circ}{f}(\{ a_i \}_{i \in I}) := \{ f(a_i) \}_{i \in I}, \overset{\circ}{f}(W) = ( f(W_{ij}) )_{ij}$ to mean an elementwise function.


Send Envelope Using a Template Replacing Signer Name and Email

Question: We use DocuSign to request signatures from business partners.
For each campaing, we create a template in DocuSign with the required documents and SignHere tabs (Places to sign) placed in those documents. and these SignHere tabs are associated to a Signer that is defined in the template.
When we are ready to send the documents to the users to sign (an envelope), we want to use the above template. but the name and email of the signer should change for each envelope.
We have tried (Assume that the template we provide here has a signer with the role Partner)

Providing the TemplateRoles
<code>    var envelope = new EnvelopeDefinition
    {
        TemplateId = "...",
        TemplateRoles = new List<TemplateRole>
        {
            new TemplateRole
            {
                RoleName = "Partner",
                Name = "John Doe",
                Email = "firstname.lastname@example.com",

            }
        },
        EmailSubject = "...",
        Status = "created"
    };

    var result = await envelopeApi.CreateEnvelopeAsync(accountId, envelope);
</code>
Using CompositeTemplate
<code>    var envelope = new EnvelopeDefinition
    {
        CompositeTemplates = new List<CompositeTemplate>
        {
            new CompositeTemplate
            {
                ServerTemplates = new List<ServerTemplate>
                {
                    new ServerTemplate
                    {
                        TemplateId = templateId,
                        Sequence = "1",
                    }
                },
                InlineTemplates = new List<InlineTemplate>
                {
                    new InlineTemplate
                    {
                        Sequence = "2",
                        Recipients = new Recipients
                        {
                            Signers = new List<Signer>
                            {
                                new Signer
                                {
                                    RoleName = "Partner",
                                    Name = "John Doe",
                                    Email = "email@example.com",
                                    RecipientId = "1"

                                }
                            }
                        }
                    }
                }
            }
        },
        EmailSubject = "...",
        Status = "created"
    };

    var result = await envelopeApi.CreateEnvelopeAsync(accountId, envelope);
</code>

But in both cases, it doesn't update the name and email but it adds a new signer to the envelope along with the signer existing in the template. (This is not what we want).
How can we do that using the .Net SDK ?
Thank you.
Comment: @FeRaaC Check the updated question.
Comment: Please read the [how to ask](https://stackoverflow.com/help/how-to-ask) and edit your question accordingly. Right now it is highly unlikely that anyone really understands what your problem is.
Answer: When you create a template in DocuSign, you have 2 types of recipients:
1. Fixed recipients, which are defined with user/email.
2. Placeholders. these only have a "RoleName" but they are not filled with email and name. They must be updated before sending the envelope or you'll get an error.
I suspect (not sure) your envelope is using the #1 type of recipients. Your use-case suggest you need the #2.
With the #2 you must ensure that the RoleName is exactly the same (case sensitive) as in the template.
Then all you have to do is create the envelope from the templates and provide the recipients in the API call (PUT) to update the recipients.
And yes, you can do this from the C# code. The EnvelopeDefinition class also has a TemplateId which you can use to just pass which template to use to create the envelope from as well as TemplateRoles which will go to the recipients.
(there's no need to use composite templates for this simple case)
Comment: After removing the name and email of the recipients from the template, we could set it when creating the envelope. so first code example in my question works if the name and email of the recipients of the template are not set. thanks for the explanation.
Answer: Here's a C# example of setting a template's role to someone:
<code>EnvelopeDefinition env = new EnvelopeDefinition();
env.TemplateId = templateId;

TemplateRole signer1 = new TemplateRole();
signer1.Email = signerEmail;
signer1.Name =  signerName;
signer1.RoleName = "signer";

TemplateRole cc1 = new TemplateRole();
cc1.Email = ccEmail;
cc1.Name = ccName;
cc1.RoleName = "cc";

env.TemplateRoles = new List<TemplateRole> { signer1, cc1 };
env.Status = "sent";
</code>
Comment: Thanks for the comment but this is exactly what I did  (see the code in the question) but didn't work. the problem is in the template. check the accepted answer.


Confused about Owl carousel with Paragraph

Question: I'm very new to Drupal and not (yet) familiar with the terms and namings.
I came across a web site in Drupal 8 that uses Paragraph. I'm trying to reproduce the slideshow that apparently uses Owl carousel. But I'm confused about how they made that slider:

(These images slide from right to left)
In the Inspector, the code shows that Owl carousel used in the div wrapper and each item. But there is no owl included in the template twig file.
Inspector screenshot:

Template twig file:

{{content.field_title.0}}

{{content.field_description.0}}

       {% for item in paragraph.field_client_image %}

        {% endfor %}

              {{ content.field_button.0['#title'] }}

I assume the below code generates the classes owl-item, owl-item cloned:
{% for item in paragraph.field_client_image %}

{% endfor %}

Anyone can enlighten my candle?
PS: I have access to all templates files and even have access to the site: no Owl carousel module installed but the libraries is present.
Thanks for your time.
Comment: How do you know Owl isn't included in global JS? It won't always be in a twig file.
Comment: Oh, really? I have no Idea, should look. But I have a doubt
Comment: But my question is how it is included in that particular line: `{% for item in paragraph.field_client_image %}` ?
Comment: It isn't @esQmo_, that line is looping through an array. It's included elsewhere. Probably in a field widget class or template
Comment: Thanks, that's what I'm trying to figure out. haven't found so far
Answer: You have to separate between two components:
A) Markup generated on server-side by Drupal, which is used as base structure for Owl carousel.
B) Markup modified by Owl in the client's browser.
Drupal render's something like

  {% for item in paragraph.field_client_image %}

  {% endfor %}

The code above is not really depending or specific for Owl carousel.
The thing transforms it to a carousel is a JS call similar to
$(document).ready(function(){
  $(".partners").owlCarousel();
});

somewhere else in a JS file of your theme or a module. This is the "magic" that transforms the server-rendered HTML to something like your screenshot is showing (adding additional
s, classes and styles)
Comment: Thanks for your answer. I tried to reproduce what they made but no luck, I have even copied their files, modified `info.yml` and `libraries.yml` file to point to the files,  still can't reproduce it :(
Comment: Is there a way to know which JS file is being used? Like we do with twig files in debug mode?
Comment: [Learn how to use a JavaScript debugger](https://developers.google.com/web/tools/chrome-devtools/javascript/), but this topic is way to broad for this Q&A site
Comment: You might try your luck with a code search for `.owlCarousel()` in your theme directory... but this is just a wild guess, it could be in a module too
Comment: Hey, found this line in theme.js : `o(".partners").length&&o(".partners").owlCarousel({loop:!0,items:5,margin:110,autoplay:!0,response:!0,responsive:{300:{items:1,margin:0},500:{items:3},700:{items:3},800:{items:4,margin:40},1e3:{items:5}}})`


Derivative of a piecewise defined function

Question: I want to ask something about the definition of derivative. If we have a function like this $ f(x) =
  \begin{cases}
    x^2+1       & \quad \text{if } x<0 \\
    \cos x  & \quad \text{if } x\ge 0\\
  \end{cases}
  $
 and we want to compute the derivetive in $x_0=0$ why is necessary to compute this with the definition of derivative? It will be wrong to find the the derivative of $ x^2+1$ and of $\cos x$ with types and to compute in $x_0=0$? Could you give me an example which is compute only with the limit and it is not compute with formulas? Thanks in advance
Comment: Your function is not continuous in $0$
Comment: You are right stity. i fix it
Answer: For your example formulas work (with some caution).  Define $g(x)=\cos x$ and $h(x)=x^2 + 1$.  Then $f(x)=g(x)$ for all $x\geq 0$ and $f(x)=h(x)$ for all $x\leq 0$.  There is no trouble finding the derivative for $x\not=0$,
but what to do at $x=0$?
Well the (right-hand) derivative of $g(x)$ at this point is $g'(0)=g_+'(0)=0$ and so the right-hand derivative of $f$ must be the same, i.e., $f_+'(0)=0$.
And the (left-hand) derivative of $h(x)$ at this point is $h'(0)=h_-'(0)=0$ and so the left-hand derivative of $f$ must be the same, i.e., $f_-'(0)=0$.
Since both sides agree then $f'(0)$ must be this common value.
We didn't need to use the definition of the derivative--we used properties of the derivative and computed merrily the way any calculus student would want to.
Doesn't always work.  Try $$ F(x) = x^{ 2} \sin x^{-2}$$ with $F(0)=0$.  None of your calculus skills help.  Sure you can compute $F'(x)$ for any $x\not=0$ by your formulas, but that doesn't lead to an answer for $F'(0)$.  You simply return to the definition of the derivative and compute that limit as best you can.  (Or examine the graph closely for ideas.)


Estrutura de arquivos e deployment de aplicações JSF com JBoss EAP no Debian 8

Question: Gostaria de saber se há como configurar o JBoss EAP para fazer deploy de aplicações Java (JSF, Hibernate, PrimeFaces, Maven) na pasta /var/www/.
A estrutura da pasta /var/www é a seguinte:
/var/www
    /php
    /java
        /appjsf1.war
        /appjsf2.war
    /python

O JBoss está instalado em /opt/jboss-eap-6/ e as aplicações Java rodam em /opt/jboss-eap-6/server/default/deploy só que eu não quero que as aplicações fiquem dentro da pasta do servidor de aplicação.
Minha dúvida vem da insatisfação com a atual estrutura dos arquivos que roda dentro da pasta do servidor de aplicação e também por curiosidade. Já que existem muitos sistemas distribuídos para dar escalabilidade aos grandes projetos de software e o JBoss é usado em muitos deles, eu pense que eu pudesse separar o repositório de códigos das minhas aplicações do servidor JBoss.
Aproveitando, e se eu quiser rodar o JBoss num servidor e deixar meus códigos em outro servidor distinto, é possível?
Answer: Depois de pesquisar bastante encontrei a forma certa de perguntar e é esta:
Como alterar a pasta de deployment default do JBoss?
As respostas surgiram naturalmente:

How to change JBoss eap 6.1 deployment
folder
Deploying a war outside of a deploy directory in
jboss

A principal fonte é a da própria RedHat ("dona" do JBoss EAP):

Chapter 7. Deploying
Applications


load balancer - web app AZURE

Question: I've deployed my php app on azure (web app MS + SQL).
I'd like to do a load balancer for education purpose and I have no idea how to do it, cause every tutorial is for VM's or app sevice enviroment.
how could i do load balancer with app service or should I deploy my project on virtual machine?
Answer: Azure App Service has a built in load balancer. You can add more nodes by scaling out.

Reference Article here
Comment: Web apps have load balancing built in. All you do is set the number of instances you want to run. If you are on the lower tiered app plans you will not have that capability.
Comment: I'm using free plan and there isn't any autoscale option. And I'd like to do it on my own for education purpose like doing it with VMs, when you have to configure 'few things'

load balancer - web app AZURE


Speed in mph of vehicle spun in crash

Question: I witnessed a multi-vehicle crash last night, and was just reviewing my dash cam video. (You can see it [mp4 video, you'll have to download to view] at https://app.box.com/s/9f21n705od726fxjj1zbi8djiyvu92yo if you'd like).
The "middle" vehicle, a small pickup, was spun after being pushed by a vehicle passing him on the right. He hit a third vehicle 90 degrees through that spin. It took 25 frames (5/6 of a second) to spin another 270 degrees after the second impact. (Side note: the video above only shows about 10 frames a second, I'm counting off the original video at 30 fps)
For the sake of coming up with a best-guess value, I'm going to offer these assumptions:

his speed at initial impact was 40 miles an hour
at the point of second impact, he was moving at 5 miles per hour at a 90-degree axis to his original travel. The original spin had stopped and he was moving in a straight line.
distance from the point of impact to the center of his mass was 10 feet
(if it makes any difference, the truck he hit was moving 40 miles an hour at 90 degrees to the small truck's motion)

I have two questions:

what was the linear speed of the driver, in mph, during the 5/6 of a second he spun 270 degrees?
what force (pounds, units of gravity, whatever) did he undergo at impact (I'm thinking this is an instantaneous acceleration question)?

I understand the basics of the first calculation involve the radius (10 feet) and the radians he moved around the center point. But that's the limit of my understanding of this particular geometry problem. I have no clue how to calculate that instantaneous force.
The small truck driver was pretty dazed and was taken to the hospital. What I'm basically wondering is how badly his brain was shaken in his skull (coup-contracoup injury). I realize that's beyond the scope of this group, but with the two numbers calculated above, I can do some research on the head injury piece. It's all for interest sake, anyway...I don't know the guy.
Comment: This question might be better suited for [Physics.SE]. PS why are you riding on the left lane forcing vehicles to pass you on the right? Also the truck on your right never pressed the brake, so he wasn't paying attention either (like the van that caused everyting).
Comment: I was driving at the speed limit, so generally that would mean a person would need to speed to pass me on the right. I had slowed below the speed limit for the left-turning truck seen at the start of the sequence. Hanging out in the left lane is a habit I got into when I worked EMS (avoids confusion when you light up while driving, keeping you from getting boxed in by people trying to get out of your way).   It hasn't gone away in the years since. If I don't see any answers here in the next day or so I'll close this and post on Physics. Thank you!
Comment: We were also a couple blocks past a commercial area where left turns are protected by islands and turning traffic in the right lane is frequent, so the lane I was in is the smoothest-flowing lane. My answer above is the primary reason, though...
Comment: Thanks for the video. I am going to show it to my kids so they understand the severity of a crash at 40mph and all the factors that played a role.
Comment: Was the turn signals on for truck turning left in front of the van? It seems the van was veering & the truck didn't use a turn signal to alert the van he was slowing down.
Comment: I'm not sure. Based on the behavior of the van driver after the accident, I'm not completely certain the pickup was turning -- she was saying "I'm sorry, I'm so sorry" -- just beside herself.
Answer: This question really needs to be posted to [Physics.SE]
There are two components of acceleration (and forces) at play. One is the deceleration of the center of mass and the second is the spin and the centrifugal forces.
My estimation is that the front of the red truck came to a stop really fast (the truck center of mass remains near the impact location along the road). You can see the bed cover flying out at about the speed the truck had before impact. I also estimate about 40mph before impact and 0mph after impact. I think happened over 0.2 seconds, so the decelleration is
$$ a = \frac{40 {\rm mph}}{0.2 {\rm sec}} = 89.6 {\rm m/s^2} = 9.1 {\rm gee}$$
Now as far as the centrifugal acceleration you noted 270 degress in 5/6 of a second, which means
$$ \omega = \frac{270°}{0.833 {\rm sec}} = 5.65 {\rm rad/s} $$
We have to estimate the distance of the person from the center of rotation. To me it looks like the center of rotation is in the middle of the dash of the car. The driver got flung to the window which is like 2ft away ($r=0.61{\rm m}$). The acceleration due to the rotation is
$$ a = r \omega^2 = 19.5 {\rm m/s^2} = 2.0 {\rm gee}$$
So there you have it, 9 gee of acceleration due to stopping and 2 gee due to rotation.
Comment: I would have thought more, but I was estimating the center of rotation at the bumper, not the dash. You are correct about the axis being more to the center of the vehicle. Thank you for working through it! The little bit of research I've done indicates 50-95G is the estimated force needed to cause concussion...so hopefully he just had a headache, not something worse.
Comment: It depends if he was restrained or not, and if his head hit something hard.
Comment: He was restrained. Was having difficulty getting himself out of the belt when I got his door forced open to check on him. I can't say for sure, but I'd imagine he hit the B post or the driver's window, though the window was not starred from an impact.
Comment: I hope everyone walked away with no long term injuries.

Speed in mph of vehicle spun in crash


What is interfering with my form?

Question: I created a form in codepen and once I was satisfied with it, I entered in my html and css for my banner and nav, but something is now interfering with my form. Can someone point out to me what I can do get my form to return to it's previous state.
Here is the code for my form without the banner and nav information.
HTML:

<form action="/my-handling-form-page" method="post">

        Name:
        <input type="text" id="name" name="user_name" placeholder="Your Name"/>

        E-mail:
        <input type="email" id="mail" name="user_mail" placeholder="firstname.lastname@example.com"/>

        Message:
        <textarea id="msg" name="user_message" placeholder="Tell us about your story!"></textarea>

        <button type="submit">Send your message</button>

</form>

CSS:
.form-share {
  margin-top: 50px;
  margin-bottom: 50px;
}

form {
    /* Just to center the form on the page */
    margin: 0 auto;
    width: 400px;
    /* To see the outline of the form */
    padding: 1em;
    border: 1px solid #CCC;
    border-radius: 1em;
}

form div + div {
    margin-top: 1em;
}

label {
    /* To make sure that all labels have the same size and are properly aligned */
    display: inline-block;
    width:  77px;
    text-align: right;
}

input, textarea {
    /* To make sure that all text fields have the same font settings
       By default, textareas have a monospace font */
    font: 1em sans-serif;

    /* To give the same size to all text field */
    width: 300px;
    -moz-box-sizing: border-box;
    box-sizing: border-box;

    /* To harmonize the look & feel of text field border */
    border: 1px solid #999;
}

input:focus, textarea:focus {
    /* To give a little highlight on active elements */
    border-color: #000;
}

textarea {
    /* To properly align multiline text fields with their labels */
    vertical-align: top;

    /* To give enough room to type some text */
    height: 5em;

    /* To allow users to resize any textarea vertically
       It does not work on all browsers */
    resize: vertical;
}

.button {
 /*margin: 0 auto;*/
  padding-left: 77px;
  padding-right: 16px;
}

button[type=submit] {
 -webkit-appearance: none;
 -moz-appearance: none;
 display: block;
 margin: 1.5em 0;
 font-size: 1em;
 line-height: 2.5em;
 color: #333;
 font-weight: bold;
 height: 2.5em;
 width: 100%;
 background: -moz-linear-gradient(top, rgb(204,233,250) 0%, rgb(214,119,126) 100%);
 background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgb(204,233,250)), color-stop(100%,rgb(214,119,126)));

 -webkit-border-radius: 10px;
  -moz-border-radius: 10px; border-radius: 10px;
}

button:hover {
  cursor: pointer;
}

and Here is the Code for my page with the form, the banner and the nav.
Html:

      Information

     Resources

     Media

      Share

Understanding Gender identities and Sexual Orientation.  Find out more about terms and misconceptions.

Access information providing links and other sources for those looking to reach out to others or simply learn more about gender Identitiy and orientation.

 Examples of books,  television, movie and other media that bring light to the topic of gender idenitity and sexual orientation.

Share any stories you may have, whether it be about your own experience with your gender or sexuality, or from the perspective of an allie, questions you may have, or other resources that could be useful for other!

<form action="/my-handling-form-page" method="post">

        Name:
        <input type="text" id="name" name="user_name" placeholder="Your Name"/>

        E-mail:
        <input type="email" id="mail" name="user_mail" placeholder="firstname.lastname@example.com"/>

        Message:
        <textarea id="msg" name="user_message" placeholder="Tell us about your story!"></textarea>

        <button type="submit">Send your message</button>

</form>

   Home |
   Terms  | Media | Resources  | Share

  | 2016 | Web Design

CSS:
@font-face { font-family: "aqua";
  src: url('aqua.ttf'); }
@font-face { font-family: "axis";
  src: url('Axis Extrabold.otf'); }
@font-face { font-family: "atami";
  src: url('Atami-Regular.otf'); }

.container {
  width: 100%;
  margin: 0 auto;
}

.banner{
  display: block;
margin: 0 auto;
  width: 100%;
  min-width: 400px;
  /*margin-bottom: 40px;*/
}

#content {
  position: absolute;
  z-index: 1;
  width: 100%;
}

.gender {
  padding-top: 20px;
  padding-bottom: 20px;
 /* background-color: black; */
  margin-bottom: 20px;
}
.gender h3{
text-align: center;
 color: rgb(0,0,0); /* white*/
  animation: rgb infinite alternate;
  animation-duration: 15s;
  font-size: 2em;
}

@keyframes rgb {
  /* 0% will fallback to the default background-color of #rgb*/
 50% {color: rgb(29,185,226); /*blue*/ }
  75% {color: rgb(105,45,138); /*purple*/ }
  100% {color: rgb(237,49,147); /*pink*/}
}

h3{
font-family: "axis", sans-serif;
}

h1{
font-family: 'Poppins', sans-serif;
font-size: 2.5rem;
}

.content-info {
  margin-top: 20px;
  text-align: center;
  display: block;
}

* { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box;  margin: 0; padding: 0; }

#wrap { width: 100%; margin: 0 auto; min-width: 300px; max-width: 2000px;
}

#tabwrap {
    /*background: #fff;*/
    overflow: hidden;
    width: 100%;
  max-height:  10rem;
    /*min-height: 300px;*/
    margin: 0 auto;
  background-color: black /*rgb(255,204,254)*/;
    /*box-shadow: 0 0 20px #ddd;*/
    /*border: 1px solid #ddd;*/
}
#tabs { overflow: hidden;  }
#tabs li { list-style: none;
           font-family: "axis", sans-serif; }

#tabs li a {
    float: left;
    display: block;
    padding: 10px;
    color: white;
    width: 25%;
    text-decoration: none;
    text-align: center;

    border-left: 1px solid #888;
    font-size: 15px;
  font-family: 'Montserrat', sans-serif;
}

#tabs li a:hover { background: #666; }
#tabs li:first-child a { border-left: 0; }
#tabs li:last-child a { border-right: 0; }

#tabs li.current a {
    background: #fff;
    color: #666;

}

#tabs li.current a.cyan{
    background: rgb(245,166,200); /*pink*/
    color: white;
}

#tabs li.current a.green{
background-color: rgb(164,206,249); /*blue*/
    color: white;
}

#tabs li.current a.lav{
 background-color: rgb(200,200,255);
    color: white;
}

#tabs li.current a.teal{
 background-color: rgb(163,109,174);
    color: white;
}

#content > div {
    clear: both;
    padding: 20px;
    line-height: 19px;
    color: white;
    display: none;
font-family: "aqua", sans-serif;
  text-align: center;

}
.animated {
    -webkit-animation-duration: 1s;
       -moz-animation-duration: 1s;
         -o-animation-duration: 1s;
            animation-duration: 2s;
}

#content .current { display: block }
#content p { /*margin: 0 0 20px 0;*/
  z-index: 1;
}

@-webkit-keyframes fadeInLeft {
  0% {
    opacity: 0;
    -webkit-transform: translateX(-10px);
    transform: translateX(-10px);
  }

  100% {
    opacity: 1;
    -webkit-transform: translateX(0);
    transform: translateX(0);
  }
}

@keyframes fadeInLeft {
  0% {
    opacity: 0;
    -webkit-transform: translateX(-10px);
    -ms-transform: translateX(-10px);
    transform: translateX(-10px);
  }

  100% {
    opacity: 1;
    -webkit-transform: translateX(0);
    -ms-transform: translateX(0);
    transform: translateX(0);
  }
}

.fadeInLeft {
  -webkit-animation-name: fadeInLeft;
  animation-name: fadeInLeft;
}

#terms {
  background-color: rgb(245,166,200); /*pink*/
}

#resources {
  background-color: rgb(164,206,249); /*blue*/
}

#culture{
    background-color: rgb(200,200,255);
}

#share {
    background-color: rgb(163,109,174);
    z-index: 1;
}

.main-caro img{
  display:block;
  margin: 0 auto;
  padding-bottom: 10px;
}

/* Delete this
------------------------------------------------ */
body {
  background: white;
  padding: 0;
  }
footer.info { text-align: center; color: #888; margin: 30px 0; }
footer.info p { color: black; }

.last-home {
padding-top: 10px;
}

JS:
$('#tabs li a').hover(function(e) {
    $('#tabs li, #content .current').removeClass('current').removeClass('fadeInLeft');
    $(this).parent().addClass('current');
    var currentTab = $(this).attr('href');
    $(currentTab).addClass('current fadeInLeft');
    e.preventDefault();

}, function(){
   $('#tabs li, #content .current').removeClass('current').removeClass('fadeInLeft');
});

Comment: What problem are you having specifically? I put it into jsfiddle and didn't see any issues submitting the form: https://jsfiddle.net/duxprgua/
Comment: The form does not look the same as when it is by itself. The name and the label are misaligned and to the left when inserted with the banner and I don't understand why.
Comment: If this helped you can you please accept the answer?
Answer: To align the name and label you might want to try adding a display type of inline-block to your label and also specify a width. E.g:
.form-share label {
    display: inline-block;
    width: 75px;
    text-align: right;
}

https://jsfiddle.net/duxprgua/1/
But I would probably recommend using something like bootstrap and it will make your life a lot easier:
https://jsfiddle.net/0k7nd6oh/2/

What is interfering with my form?


How to remove any spacing from bootstrap toast message?

Question: I'm trying to show a bootstrap alert message as an overlay toast (so it auto hides, and is shown above other elements).
Problem: I have a spacing at the bottom of the toast, and cannot get rid of it:
https://jsfiddle.net/dertqczw/

Success

//show toast with:
$("#myToast").toast('show');

/* get rid of toast styles */
.toast-body {
    padding: 0;
    font-size: 1rem;
}
.toast {
    border: none;
    background-color: inherit;
}

Answer: Reset the margin on the .alert-primary
.alert-primary {
    margin: 0;
}

Fiddle

If you wish to remove the margin for all the alerts, target the .alert class;
.alert {
    margin: 0;
}

Fiddle

To only target .alert inside an toast; target all the child elements;
.toast-body .alert {
    margin: 0;
}

Fiddle
Comment: use the `.alert` class if you wish to target ALL alerts
Comment: Please check the edit. However, this should be included in the OP since it's a different question.
Comment: How could I remove the margin for just any alert type?
Comment: Great, and if I'd only want to target alerts *inside* just any toasts?
Answer: Add this to your css:
#myToast .alert {
    margin-bottom: 0;
}

Or a more general solution:
.alert {
    margin-bottom: 0;
}

EDIT:
For only toast alerts:
.toast-body .alert {
    margin-bottom:0;
}

Compared to the other answer, this one is just slightly better due to the specificity of setting 'margin-bottom', which is what the OP wanted, instead of 'margin'.
Comment: That's nice. Can I restrict the css on alerts only **inside** toasts (independent of a `#myToast` id?


Transactional update policy for multiple tables with the same source table

Question: Let's say I have two tables on which I define two different update policies but with the same source table. Both the update policies are transactional. So basically the two update policies look like this:-
<code>.alter table Target1 policy update @'[{"IsEnabled": true, "Source": "MySource", "Query": "UpdatePolicy1_MySource()", "IsTransactional": true, "PropagateIngestionProperties": false}]'

.alter table Target2 policy update @'[{"IsEnabled": true, "Source": "MySource", "Query": "UpdatePolicy2_MySource()", "IsTransactional": true, "PropagateIngestionProperties": false}]'
</code>
Now since both of the update policies are transactional, as per the documentation

If transactional and the update policy fails, the source table is not
updated

So what will happen in my case where only one of the update policy fails? Source table for both the update policies is the same in my case , does it mean that all the update policies for a given source table have to succeed before source table is updated ?
Answer: Yes, if the update policies are transactional, all have to succeed for commit to take place. If any update policy fails, there will be no ingestion to any of the tables.


Problema no checkin no VisualStudio 2012

Question: Ao tentar fazer o checkin a seguinte mensagem é exibida:
Check-in validation failed. A policy warning override reason and/or a check-in note is required.

Achei que era problema porque faltava comentário mas mesmo adicionando no checkin o erro permanece.
Answer: Desce até o final da janela de "Pending Changes", tem um campo chamado "Notes", insira o comentário do checkin lá também. :D


How to show messages starting with "Debug : " to an administrator only?

Question: I'm developing a lot of complex rules in D7 and for debugging reasons it is very handy to have different messages (the standard Drupal message) within the website. For this I use "showing a message on the site".
If a message of this starts with "Debug : " then I want it to only be displayed for the role of administrator. I do not want to add a condition to every message. That's is just to much.
How to achieve this?
Note: I wrote my first "Hello world" module last month, so I have a custom module in the site. I have to find the correct hook for this, so I looked into https://api.drupal.org/api/drupal/includes%21module.inc/group/hooks/7. But I cannot find a good hook for this.
Comment: You need to write your own module for this perhaps. Drupal does not offer such feature/filter out of the box.
Comment: I wrote myfirst Hello world module last month :-), so I have a custom module in the site. I have to find the correct hook for this so I looked into https://api.drupal.org/api/drupal/includes%21module.inc/group/hooks/7. But i cannot find a good hook for this? Any suggestion?
Comment: Dankjewel for your (late) accept! PS: did you get my re-forwarded eMail reply?
Comment: Welcome ☺ nop did not got a reply. Retry?
Answer: Option 1: Use the Disable Messages module
Use the Disable Messages module for this. Here is a quote from its project page:

Gives a site owner options to disable specific messages shown to end users. The core drupal message system as offered by drupal_set_message is an excellent way for modules to send out messages to the end users. However not all drupal site owners are keen to show all the messages sent out by drupal core and all modules to their users. This module gives site administrators a reasonably powerful way to filter out messages shown to the end users.

Some of its features are:

Filter out messages that match a full text string exactly.
Filter out messages that match a regular expression.
Permissions to specifically hide all messages of a given type from any role.
Disable all filtering for specific users.
Disable all filtering for specific paths.
Apply filtering only for specific paths.
Debug system to get messages in the HTML without showing it to the end users.

Available for either Drupal 6 or Drupal 7 (and a DEV version for Drupal 8).
Option 2: Write your custom code
Use a variation of the approach as explained on Hook into and Preprocess Drupal Messages? Here is a quote from it:

The following example hides all error/warning messages from anonymous users and user's who don't have the 'administer nodes' permission. You can easily add your own conditions to filter out which message types should be displayed to who.

<code>function mytheme_status_messages ($display = NULL) {

  $output = '';
  foreach (drupal_get_messages($display) as $type => $messages) {

    // skip all error/warning messages for anonymous users
    if (!user_is_logged_in() && ($type == "error" || $type == "warning")) { continue; }

    // skip error/warning messages for users who don't have the 'administer nodes' permission
    else if (!user_access('administer nodes') && ($type == "error" || $type == "warning")) { continue; }

    ...
</code>


Relationship with webform submission

Question: I have a view displaying a list of nodes. Each node has a webform submission related, and the sid is stored in one field "field_sid".
I'd like to be able to access the submission data in the node view, using a relationship thanks to the sid field.
Is there a good and efficient way to do this?
Answer: You have to use hook_views_data_alter().
function mymodule_views_data_alter(&$data) {
  if (isset($data['webform_submitted_data']['data_numeric'])) {
    if (!isset($data['webform_submitted_data']['data_numeric']['relationship'])) {
      $data['webform_submitted_data']['data_numeric']['relationship'] = array (
        'handler' => 'views_handler_relationship',
        'base' => 'node',
        'base field' => 'nid',
        'label' => t('Referred node'),
      );
    }
  }
}

Comment: Hello, and thank you. I tried it but unfortunately I wasn't able to link the "field_sid" from the node to the good submission ID. Can you help me again?

Relationship with webform submission


Comparing The Correct Responses of Different Sections of a Test

Question: I have the results of an exam for 21 students. The exam has 144 correct/incorrect questions with three equal Sections (48). I want to confirm if the difference in the correct/incorrect answers for each Section is different than the overall correct/incorrect.
For example, Student A had an overall mark of 70% (101/144): Section A 98% (47/48), Section B 73% (35/48), and Section C 40% (19/48).
I was thinking that I could do a Chi-Square test comparing the observed results against the expected, based upon the overall score. Using the example of Student A, based upon the overall mark (70%) I would expect the distribution to be 31 Correct and 17 Incorrect in all three Sections.
Assuming the same percentages applied to all answers to the tests, that would give me:

Observed
Section A
Section B
Section C

Correct
987
735
399

Incorrect
21
273
609

TOTAL
1008
1008
1008

Expected
Section A
Section B
Section C

Correct
706
706
706

Incorrect
302
302
302

TOTAL
1008
1008
1008

However, I feel like I'm doing this wrong.
It's been awhile since I did something like this, and this analysis is only a side part of a larger project, so I'm worried I've pulled the wrong concept from memory.
Can anyone tell me if I've simply overthought this and there is a simpler test, and/or if this is the wrong way to be doing this type of Chi-Square?
In particular, something in the back of my mind makes me think that I'm doing it wrong by including each student's total numbers rather than comparing the percentages somehow, but at this point I have read so much in a short time that I've ended up less confident that I even understand basic addition.
Thank you in advance.
Answer: That looks fine to me. You would now compute (observed - expected)^2 / expected for each of the 6 cells in your table (e.g., (987-706)^2/706=111.84 for the top-left cell), take the sum, and compare it to the critical values of the Chi-square distribution.


how to count a measure with dotted and triplet rhythms

Question: This is the Hungarian Sonata by Richard Clayderman. I don't know how to count this measure.
Comment: You could make it much easier by turning the note in the first quarter into a triplet. Nobody's going to notice the difference, particularly since it's probably going to be rubato anyway.
Comment: @PiedPiper - I once transcribed a 180 bpm piece that uses an 8th rest-dotted 8th-dotted 8th rhythm (the equivalent of a 16th rest-dotted 16th-dotted 16th rhythm at a faster-than-the-OP 90 bpm), and yes, I could tell that using a triplet there instead was wrong.
Comment: @Dekkadeci You obviously have an excellent sense of rhythm. Most amateur pianists don't.
Comment: Consider as another example  Chick Corea's "Spain" where - depending on who did the transcription - the initial theme starts with  dotted-quarter, dotted-quarter, quarter measures, but then switches to a  4-beat triplet.  Definitely a different 'feel'  .  (Many fakebooks don't do this switch but I think they're wrong)
Answer: First, recognize that each set of notes is barred together into whole beats.

Beat 1 = sixtheenth rest + 2 notes following
Beat 2 = triplet of three eighth notes
Beat 3 and 4 = dotted-eighth / sixteenth pairs.

To understand the first beat, think of dividing the beat into eight equal parts. The rest/notes align this way:
X: 1
T: Hungarian Sonata
T: Counting example 1
C: Richard Clayderman
K: none clef=perc stafflines=1
M: 4/4
L: 1/32
%%score (V1 | V2)
[V:V1 stem=up] z2 c3c3
[V:V2 stem=down] AAAAAAAA
w: 1 2 3 4 5 6 7 8

However, eighths of a beat don't lend themselves to easy counting, so I would suggest thinking of it, initially, in terms of sixteenth notes.
X: 1
T: Hungarian Sonata
T: Counting example 2
C: Richard Clayderman
K: none clef=perc stafflines=1
M: 4/4
L: 1/16
%%score (V1 | V2)
[V:V1 stem=up] z c3/2c3/2
[V:V2 stem=down] AAAA
w: 1 e & a

Once a feel is developed for that, then the entire measure can be counted in eighth notes. This means the left hand, which is written entirely in eighths, can serve as your metronome whenever playing hands together.
X: 1
T: Hungarian Sonata
T: Counting example 3
C: Richard Clayderman
K: none clef=perc stafflines=1
M: 4/4
L: 1/8
%%score (V1 | V2)
[V:V1 stem=up] z/2 c3/4c3/4 (3ccc c3/2c/2 c3/2c/2
[V:V2 stem=down] AA AA AA AA
w: 1 & 2 & 3 & 4 &

Comment: Especially since there is indeed eight-note pattern in the left hand.
Comment: I linked a video where I found it.
Comment: @user1079505 Do you have an image? If yes, please feel welcome to add it to the post. That's really helpful to know.


Tie-breakers in the group

Question: The ranking of each team in each group shall be determined as follows:
a) greatest number of points obtained in all group matches;
b) goal difference in all group matches;
c) greatest number of goals scored in all group matches.
If two or more teams are equal on the basis of the above three criteria, their rankings shall be determined as follows:
d) greatest number of points obtained in the group matches between the teams concerned;
e) goal difference resulting from the group matches between the teams concerned;
f) greater number of goals scored in all group matches between the teams concerned;
g) drawing of lots by the FIFA Organising Committee.
I want to ask about the following case, based on above rules:
A vs B: 1-2
B vs C: 0-1
A vs D: 6-0
A vs C: 2-0
C vs D: 6-0
B vs D: 5-0
The table looks like this:
A: 6 point, 9 scored, 2 against
B: 6 point, 7 scored, 2 against
C: 6 point, 7 scored, 2 against
D: 0 point, 0 scored, 17 against
How to determine the first, second, and third positioned team in the group. I need to know it because two top teams will qualify to semifinal.
Comment: How to determine the qualified teams? You follow the procedure you've detailed - which bit of it don't you understand?
Answer: Obviously, rule-a tells us who's the 4-th placed team in the group:

a) greatest number of points obtained in all group matches;

It's team D with the least points (0 points).
Now rule-a doesn't help us to determine first 3 positions in the table as all three teams (A, B, C) have 6 points. That's why we move to rule-b, which states:

b) goal difference in all group matches;

Out of 3 teams in question, team A has the best goal difference (9 - 2 = 7), so team A is ranked first.
As Team B and Team C have equal goal differences (7 - 2 = 5), rule-b doesn't help us in breaking the tie between these teams, hence we move to rule-c:

c) greatest number of goals scored in all group matches.

But rule-c doesn't help us either, as both teams have scored 7 goals each. We move to rule-d. Remember, the teams in question are Team B and Team C. rule-d states:

d) greatest number of points obtained in the group matches between the
  teams concerned;

Only 1 match has been played between teams concerned and Team C has won it. So, it's Team C which will be ranked second and Team B which will be ranked 3rd.
Hence, the final rankings are as follows:

Team A
Team C
Team B
Team D

So, Team A and Team C will qualify.

Tie-breakers in the group


Proof verification of non vanishing of $ ~L(1, \chi) \neq 0~$ for real valued character

Question: I am self studying analytic number theory from Tom M Apostol introduction to analytic number theory and I am asking for solution verification for a part of Theorem 6.20 of Apostol.
I am adding it's image -

I have only doubt in proving that $L(1, \chi) \neq 0$ .

My attempt - Assuming Part (b) , if I put $x\to\infty$ in part (b) , then if $ L(1, \chi ) =0 $ for some $n$, then $B(x) \to \infty = O(1)$ , which is a contradiction.
Is my proof right? Can someone please verify.
Edit 1 -> This is the proof given in Apostol Introduction to analytic number theory. Please note that he doesn't proves  how L(1 , $\chi ) \neq $ 0 .
That's why I am asking for verification of my argument.
Comment: Its better for you to type the mathematics in the images
Comment: @Calvin khor actually 1 user reuns is misunderstanding the problem. So, I added image .
Comment: Tim:  You've been around awhile, so I think you should replace the images with $\LaTeX$ markup, at least in quoting the original exercise, and perhaps leaving Apostol's proof of (a),(b) as merely a link to the image.  The very length of those images distracts from your intended approach, to assume (a),(b) and ask only about the non-vanishing of $L(1, \chi)$.  Use the space allowed in the body of the Question instead to focus on your interest in that aspect of the exercise.
Answer: Why is $B(x)=O(1)$ a contradiction. What can you say about $A(n)$ (hint : look at $A(p^k)$ or at the Euler product of $\sum_n A(n)n^{-s}$, you'll find that $A(n)\ge 0$ and for $p> q$, $A(p^2)\ge 1$, since $\sum_p \frac1p \approx \lim_{s\to 1} \log \zeta(s)=\infty$ we get $\sum_n \frac{A(n)}{n^{1/2}}\ge \sum_{p> q} \frac{A(p^2)}{p}=\infty$ )
Also it is worth noticing that for complex Dirichlet characters $\bmod q$, if $L(1,\chi)=0$ then so does $L(1,\overline{\chi})=0$ thus $\prod_{\chi\bmod q} L(s,\chi)$ has at least a simple zero at $s=1$ which is a contradiction because its $\log $ is $\sum_{p^k} \frac{p^{-sk}}{k} \sum_{\chi\bmod q} \chi(p^k)=\varphi(q)\sum_{p^k\equiv 1\bmod q} \frac{p^{-sk}}{k} $ which is non-negative at $s=1+\epsilon$.
Comment: You don't have any argument. Once you know that $B(x)$ is unbounded then $L(1,\chi)=0\implies B(x)=O(1)$ is a contradiction, if you are not confortable with that then you have a problem..
Comment: can you please tell what mistake is in using unboundedness of B(x) and then using (a) ?
Comment: 1. if x->$\infty$ , then B(x) -> $\infty $ but if B(x) =O(1) then B(x) becomes bounded, by Definition of Big O as B(x) -> $\infty$  . Can you please tell if my argument is right?  2.  For Complex valued characters Apostol has already given a nice explanation in chapter-7 which is clear to me.
Comment: Why do you think $B(x)\to \infty$...
Comment: if I put x->$\infty$ then B(x) ->$\infty$
Comment: ???? How do you know that $\lim_{x\to \infty} B(x)=\infty$
Comment: it's given in the statement of theorem  in the image in the question( part (a) to be precise ) . I am using that. Is my argument right?
Comment: I was just asking if it was right to think about non vanishing in this way or not!!
Comment: Ok, then no you are not thinking right.
Comment: my question is what mistake I am making , whatever you have written in 1st paragraph proves  that B(x) ->$\infty$ as x->$\infty$ .
Comment: I've upvoted because reuns tackles the hard part of the Apostol exercise, and I think this content has lasting value.  The inference that $L(1, \chi) \neq 0$ from (a),(b) is comparatively easy.
Answer: Yes, assuming (b), if L(1,X)=0 then B(x) = O(1), and this is in contradiction with (a).  So given these results (a) and (b) it follows that L(1,X) is not zero.
[Edit: Originally I mistyped this as "B(x) = O(x)"]
Comment: Did you mean to say "then $B(x) = O(x)$?  That would not contradict (a), since $B(x) \in O(x)$ could very well tend to infinity as $x \to \infty$.
Comment: @Tim: I said your argument is correct, that $B(x)$ is bounded (or $O(1)$, same thing) is inconsistent with the property (a) that your Question **takes as given**.  So hopefully we are on the same page.  My Comment on this answer was similar to yours, that perhaps not $O(x)$ but $O(1)$ should be written there, so we get "contradiction with (a).".
Comment: @hardmath If User Answering question meant that B(x) =O(1) , then was answer correct?
Comment: @hardmath  So, You means that my argument is wrong .Why so ? Can you please tell in detail as I wasn't able to understand reuns answer and he didn't elaborated. So, I thought I am right as no - one was answering. Luckily for me there is a guy whohas now posyted an answer. So, If you answer / explain in detail then it will really help me , man. It's my humble requets if you can spare some time for this.
Comment: @hardmath Thanks a lot !
Comment: @StuartPresnell  Did you meant B(x)=O(1) in line 1 of your answer?
Comment: Sorry, yes, I meant B(x) = O(1)


How to find a string in an array in PHP?

Question: I have an array:
$array = array("apple", "banana", "cap", "dog", etc..) up to 80 values.

and a string variable:
$str = "abc";

If I want to check whether this string ($str) exists in the array or not, I use the preg_match function, which is like this:
$isExists = preg_match("/$str/", $array);

if ($isExists) {
    echo "It exists";
} else {
    echo "It does not exist";
}

Is it the correct way? If the array grows bigger, will it be very slow? Is there any other method? I am trying to scaling down my database traffic.
And if I have two or more strings to compare, how can I do that?
Comment: can use two function in_array() and array_search()
Plaese see the tutorial prepared by me
http://braincybersolutions.com/php-tutorial/php-search-in-array/
Answer:  bool in_array  ( mixed $needle  , array $haystack  [, bool $strict  ] )

http://php.net/manual/en/function.in-array.php
Answer: If you just need an exact match, use in_array($str, $array) - it will be faster.
Another approach would be to use an associative array with your strings as the key, which should be logarithmically faster. Doubt you'll see a huge difference between that and the linear search approach with just 80 elements though.
If you do need a pattern match, then you'll need to loop over the array elements to use preg_match.

You edited the question to ask "what if you want to check for several strings?" - you'll need to loop over those strings, but you can stop as soon as you don't get a match...
$find=array("foo", "bar");
$found=count($find)>0; //ensure found is initialised as false when no terms
foreach($find as $term)
{
   if(!in_array($term, $array))
   {
        $found=false;
        break;
   }
}

Answer: preg_match expects a string input not an array. If you use the method you described you will receive:

Warning: preg_match() expects parameter 2 to be string, array given in LOCATION on line X

You want in_array:
if ( in_array ( $str , $array ) ) {
    echo 'It exists';
} else {
    echo 'Does not exist';
}

Comment: the string like this $var "id1;id2";
Answer: Why not use the built-in function in_array? (http://www.php.net/in_array)
preg_match will only work when looking for a substring in another string. (source)
Answer: If you have more than one value you could either test every value separatly:
if (in_array($str1, $array) && in_array($str2, $array) && in_array($str3, $array) /* … */) {
    // every string is element of the array
    // replace AND operator (`&&`) by OR operator (`||`) to check
    // if at least one of the strings is element of the array
}

Or you could do an intersection of both the strings and the array:
$strings = array($str1, $str2, $str3, /* … */);
if (count(array_intersect($strings, $array)) == count($strings)) {
    // every string is element of the array
    // remove "== count($strings)" to check if at least one of the strings is element
    // of the array
}

Answer: The function in_array() only detects complete entries if an array element. If you wish to detect a partial string within an array, each element must be inspected.
foreach ($array AS $this_string) {
  if (preg_match("/(!)/", $this_string)) {
    echo "It exists";
  }
}


X-Sendfile works for all folder and not just XSendFilePath

Question: I have xsendfile module working and files are being served using X-Sendfile header. But somehow files from any folder gets served.
How do I rectrict it so that I can use X-sendfile headers only for specific folders?
I have tried setting XSendFilePath, even then files outside that folder also get sent if I use X-Sendfile header.
This is what I have in my virtualhost section

      XSendFile on
      XSendFilePath /home/domain/public_html/files

If I use php to send files from /home/domain/public_html/abc using X-Sendfile. It gets sent without any problem. I do not want this. I only want X-Sendfile to work for files within /home/domain/public_html/files.
Answer: Try with the XSendFilePath directive

XSendFilePath allow you to add additional paths to some kind of white list. All files within these paths are allowed to get served through mod_xsendfile.
Comment: In my case all folders seem to be white listed. I am able to serve files from any location using the X_Sendfile header.
I do not want this. I want to use this header only for folders i specify.
Answer: It is imporant the the XSendFilePath directive is in a apache config file context that is relevant to the url you are using, e.g. not within a virtual host section which is not interpreted due your actual virtual host (in your url).
probably and in most configurations, XSendFilePath is used in the main section of apache config file, not in a specific context like virtual host, dolmain, etc.
does this help?

XSendFilePath /tmp
<VirtualHost *>
 ServerName www.someserver.com
 XSendFilePath /home/userxyz
</VirtualHost>

(first occurance of XSendFilePath -> works globally, second occurance does only work if your php script producting the XSendFile header is called from within domain www.someserver.com)


Templatize functionpointer with default argument

Question: I want to templatize that code below:
void attachHelpfunctionPointer(void (* functionPointer)(int),  int test=0);
void (* helpFunctionPointer)(int);

void attachHelpfunctionPointer(void (* functionPointer)(int), int test) {
    helpFunctionPointer = functionPointer;   //pass the address
}

and then somewhere later in the code call it:
attachHelpfunctionPointer(testFunctionXY, testValue);  //attach new function with argument
helpFunctionPointer (test);   //pass the argument

how can I replace the type "int" by a template of type "T"?
Answer: Something like this should work..
template <typename T>
class Foo {
  std::function<void(T)> f_;
  void setFunc(std::function<void(T)> f, T def = {}) {
    // save
    f_ = [=](T p) {
      // pseudo code follows:
      // if not p
        f(def);
      // else
        f(p);
    };
  }

  void callFunc(T param) {
    f_(param);
  }
}

If you can't modify the approach (i.e. need to use a free function like you are doing to set it to some arbitrary object) then you will need to use some type such as boost::any (or std::any if you have C++17) for the parameter and in your function test it.. so the signature becomes std::function<void(std::any)>
EDIT: missed the default parameter criteria, so modified the save function a little bit.
Comment: Uff, that looks complicated, I don't even know what: "[=]" means. But Im gonna try that tomorrow, thanks
Comment: It's a lambda and whatever is in the square brackets `[]` is captured, two ways to capture, by value (copy) `=`, or by reference, the latter is a headache as you have to guarantee lifetime, and given this is just a default value, copy is easiest.
Answer: You can write a code similar to your example, but templatized, using template variables.
Unfortunately they are available only starting from C++14.
By example
template <typename T>
void (* helpFunctionPointer)(T) = nullptr;

template <typename T>
void attachHelpfunctionPointer (void (*fP)(T), T test)
 { helpFunctionPointer<T> = fP; }

The following is a full working example
#include <iostream>

template <typename T>
void (* helpFunctionPointer)(T) = nullptr;

template <typename T>
void attachHelpfunctionPointer (void (*fP)(T), T test)
 { helpFunctionPointer<T> = fP; }

void foo (int)
 { std::cout << "foo (int function)" << std::endl; }

void bar (long)
 { std::cout << "bar (long function)" << std::endl; }

int main()
 {
   attachHelpfunctionPointer(foo, 0);
   attachHelpfunctionPointer(bar, 0L);

   helpFunctionPointer<int>(1);
   helpFunctionPointer<long>(1L);
 }

For C++11 the best I can imagine is wrap the function pointer in a template struct or class or something similar (see the Nim's answer, by example).
An iper-simplified example can be based on
template <typename T>
struct funcPtr
 { void (*fp)(T) = nullptr; };

The following is a full working (C++11) example
#include <iostream>

template <typename T>
struct funcPtr
 { void (*fp)(T) = nullptr; };

void foo (int)
 { std::cout << "foo (int function)" << std::endl; }

void bar (long)
 { std::cout << "bar (long function)" << std::endl; }

int main()
 {
   funcPtr<int>  fpi { foo };
   funcPtr<long> fpl { bar };

   fpi.fp(1);
   fpl.fp(1L);
 }

Comment: Unluckily I have C++11 (Arduino), but thanks anyway.
Comment: @Hydra - added a iper-simplified C++11 solution (but the Nim's one, based on `std::function` maybe is better)


Missing bottom level item when a node is linked to two menu objects

Question: I have been trying to create a custom menu block which shows a number of menu items with images on the current level.
I am having an issue where the active trail array doesn't return an menu item for the active node on level 4 of my menu. Here is an example of how I get the active trail:
<code>$menu_tree = \Drupal::menuTree();
$menu_parent_tree = \Drupal::menuTree();
$menu_name = 'main';

// Build the typical default set of menu tree parameters.
$parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);

foreach($parameters->activeTrail as $active_menu_link) {
  if($active_menu_link !== '') {
    $active_menu_id = explode(':', $active_menu_link);
    $entity = \Drupal::entityManager()->loadEntityByUuid($active_menu_id[0], $active_menu_id[1]);

    kint($entity->getTitle());
  }
}
</code>
It seems that the issue is mostly related to the fact that the same node is linked to both a child menu item and a parent menu item. If I remove this then the function works as expected. This is the my menu structure.

The two menu items highlighted in red are both linked to the same node since I want it to act as an overview page for the category. It could be that theres something else I can do to structure the menu differently. I am open to any alternatives on how I can get around this.
Answer: I resolved this by manipulating the tree object manually further down my module. I checked if the url of the parent object matched any of the child objects via a loop.
<code>$menu_tree = \Drupal::menuTree();
$menu_parent_tree = \Drupal::menuTree();
$menu_name = 'main';

// Build the typical default set of menu tree parameters.
$parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);

// Setup current link
$currentLinkId = reset($parameters->activeTrail);
$parameters->setRoot($currentLinkId);

// Load the tree based on this set of parameters.
$tree = $menu_tree->load($menu_name, $parameters);

// Get the parent of current menu so we can use its
// children as the links
$parameters->setRoot(reset($tree)->link->getParent());
$tree = $menu_parent_tree->load($menu_name, $parameters);

// Transform the tree using the manipulators you want.
$manipulators = array(
  // Only show links that are accessible for the current user.
  array('callable' => 'menu.default_tree_manipulators:checkAccess'),
  // Use the default sorting of menu links.
  array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
);
$tree = $menu_parent_tree->transform($tree, $manipulators);

foreach($tree as $key => $menu_item) {
  // Check if the link is the current page?
  $current_internal_path = $menu_item->link->getUrlObject()->toString();
  foreach($menu_item->subtree as $sub_key => $sub_link) {
    $sub_internal_path = $sub_link->link->getUrlObject()->toString();

    if($current_internal_path == $sub_internal_path) {
      unset($tree[$key]->subtree[$sub_key]);
    }

    // Check if we have another sub tree (we are not the parent). This can happen when a parent
    // link is attached to the same node as a child one.
    if($sub_link->subtree && count($sub_link->subtree)) {
      $lower_level_links = $sub_link->subtree;

      foreach($lower_level_links as $lower_link_key => $lower_level_link) {
        $lower_level_url = $lower_level_link->link->getUrlObject()->toString();
        if($sub_internal_path == $lower_level_url) {
          // Set the active menu level as this.
          $tree = array($sub_link);
        }
      }
    }
  }
}

// Build up our menu
$menu = $menu_tree->build($tree);
</code>
This is perhaps not the cleanest solution with a lot of extra processing required but seems to work in this instance.


React Native Bridge Library for existing Objective C Framework which depends on other iOS Frameworks

Question:
I have an Objective-C Framework, which depends on other third party Frameworks through CocoaPods.
i.e A-->B,C,D

I created a react-native-create-library bridge which wraps the code around Objective-C Framework A.
i.e React_Native_A-->A-->B,C,D

I tried creating an example app Example_React_Native_A which links the React_Native_A using the react_native link command. Hoping that it links to the other frameworks added using the CocoaPods.

Unfortunately, this doesn't work in this way. It won't even consider React_Native_A-->A link.

Is there any other way to generate the example app, so that it can link all the required frameworks i.e A-->B,C,D.
Comment: Did you find an answer to this problem?
Answer: If anyone looking for the solution, the way is mentioned in the RNNearBee.podspec here. The wrapper podspec depends on the version of the react as per the local machine installed version and then it depends on the original native podspec.