What's the proper right arm position for an electric guitar?

Question: With my classical guitar arm positioning has never been an issue.  I just rest my arm naturally on the body at the crook of the elbow:

My wrist stays pretty flat:

I feel like I could sit like that for hours.  My electric guitar has been a struggle.  The first position I was told to try was to rest my arm a bit past the elbow:

This feels pretty awkward and my wrist doesn't look so good

I have been playing around with resting at the crook of my elbow:

It seems better on the wrist:

But I get pins and needles in my right arm after only about 10 minutes in this position.  It's almost as if the thinner body of my electric guitar is digging into my arm and maybe cutting off circulation?  What's the right way to position my right arm for good ergonomics and comfort?
Comment: The only real answer is whatever is most comfortable to you. Your arm length and sitting/standing/strap position are all factors, but whatever lets you play comfortably. There are some great players out there with some goofy arm positions (check out Marty Friedmans's wrist position sometime).
Comment: You might find it interesting to Google for the story of Les Paul and his broken arm.  Rather than amputation, which would have completely ended his playing career, he opted to have it set in a fixed position which still allowed him to play guitar.
Answer: I don't rest my arm on acoustic or electric guitars, as it would severely impede my playing.
If you are sitting, I would suggest moving the guitar to your other leg - this changes the angles such that your arm won't rest on it any more.
I would suggest standing though - you have a much wider range of positions.
I sometimes rest my little finger on the scratch plate if I am doing some delicate picking, or I may rest the side of my hand on the strings if playing heavily damped, but most commonly I would have my arm relaxed so the hand is next to the strings.
This gives you speed and flexibility, and won't give you pins and needles.
As an example, my bass player is using his fingers and my rhythm guitarist and I are using right hand damping in the picture below.
Answer: I agree with @Dr Mayhem that the way the guitar is sitting on your leg may be a problem.  Also, are you leaning forward (crouching over the guitar)?
You could try playing standing up, and adjusting the strap to try to find a comfortable position.  When you do, you can see if that continues to work when you sit down.  If not, you might try a more stool-like seat, so your legs are not as scrunched up.
Answer: In your classical position, you are resting on the right leg, whereas typically the waist of the guitar rests on the LEFT leg (so that the lower bout is between the player's two legs -- you can find pictures or video of classical playing).    Also, the neck is usually tilted so that the peghead is up higher in the air.  Both these things mean that the right arm would be rested further from the elbow (further toward wrist).
With plectrum 'spanish' guitar -- particularly thin or solid-body electric -- arm positions vary wildly (as does most everything else).   Not all of these positions are used strictly for ease or quality of playing -- many are just used for 'looks' or appearances, or to be able to stand while playing.
Note that (kind of in reference to the rock/metal band photo above), having the guitar hanging low (or peghead tilted low), will not only alter right arm position, but will also greatly affect LEFT hand position (detrimentally for certain scale/arpeggio playing, in my opinion -- although many many blues and rock players do it this way, and it works for what they do).
The 'proper' left hand position should allow the wrist to be straight with the forearm, and allow the left fingers to spread and stretch out along the neck -- and usually without the thumb wraping around the neck.
While many many guitarists, particularly in rock and blues, have the guitar hanging low (and yes many are great musicians), notice that they would not be able to play certain scale or single-note arpeggio forms in that position (as well as missing many advanced chord-forms).
For me, it seems that the right ARM position while using a pick, is usually different from that when using a classical guitar.
Remember, the classical bodies have the necks join the body at the 12th fret -- though often having as long, or longer scale lengths than a lot of folk and electric guitars (particulary Gibson).
Electrics and plectrum acoustic necks join usually at the 14th fret and higher (esp. electrics).  This means that resting the waist on the RIGHT leg allows the neck to be pulled closer in front of the player's body.  This also moves the lower bout toward the right elbow joint.
On a plectrum acoustic guitar, when I play true 'rhythm', my forearm never rests on the body, and only the upper arm rests fairly lightly on the edge of the top of the lower bout (btw, I really like armrests on my guitars; note some guitars have them or have chamfers on the body -- check out Greenfield guitars).
In my opinion, single-note scale and/or arpeggio playing requires some sort of 'reference' for the hand to 'know' where the strings are.  This should NOT be anchoring the right-hand or arm anywhere to the guitar.  It should just be light touching, brushing, and/or palming, usually against  adjacent strings, pickguard, or top.  And it depends upon the musical passages, which of these is appropriate.
True rhythm guitar does not have the right hand or fingers resting on the guitar (and again, certainly not the forearm either).  The right hand flecks up and down, quickly, at the wrist, which is shaken by the forearm (which in turn is why forearm cannot rest on the guitar body).  The analogy given by W.G. Leavitt of Berklee said something like 'imagine you are trying to shake a bug/spider off the back of your hand'.
In classical guitar's apoyando (rest stroke), there's usually a finger and often the thumb also resting on a string.  And in tirando (free stroke), I frequently lightly rest the thumb or edge of it on a string (unless it's plucking already).  With arpeggios there are often finger-plants (in preparation for plucking) or thumb rests as well.
In any event, no body part should be resting on the guitar to the point where it is 'anchored' (this also applies to many other musical instruments I believe).  The other poster is quite correct in saying that -- while it might seem a more secure way at first -- it will ultimately hinder playing ability.
Now on solid-body electrics, because of the plethora of (often ridiculous) shapes, all bets are off!   But a Les Paul or Strat or Tele or related shape should be more like a flat-top or archtop -- in the way that it's held -- than, say maybe, a Flying V.
Ultimately, 'rules' ARE broken all the time.
But just because you see some pro-player (particularly in the popular music genres) using some unorthodox or unique technique or playing position, it doesn't mean THAT is what made them great.
They usually became great in spite of those things, and not because of them -- because they were so naturally talented and/or success driven to begin with.
In the really demanding and disciplined music genres, however, avoiding undue stresses, and maximizing potential, becomes critical.
Answer: To a certain extent it may depend upon what kind of music you are playing, and what the R.H. is doing.
When playing single-line stuff (riffs, melodic lines etc.) a lot of electric players would rest the heel of the hand (near the wrist) on the guitar, either just above string 6 or on the bridge, or if playing on the highest strings actually resting on the lowest strings. This makes it easy to play quickly and accurately as the point at which you are resting your hand is close to the point at which you are playing. (This small distance is crucial to accuracy; when teaching I use the analogy of trying to write holding a pen in the usual way, or trying to write holding a pen at the end opposite the nib, which is less accurate.) Resting on the lowest strings also damps them, which is particularly useful when playing with distortion or at high volume.
When playing chords you can't rest the heel of the hand on the guitar (except maybe for two-string fifths shapes, for instance), but I would still have a resting point closer than when playing acoustic or classical. I would rest my arm on the guitar at about the mid-point of my forearm, when playing electric (kind of halfway between your first and third electric pictures above). And like you I would rest the crook of my elbow on the guitar for acoustic and plectrum classical guitar (though not when playing with orthodox finger-style classical technique).
I'm a Telecaster person, and not a great fan of Strats. But one thing I do like about Strats (especially when my pupils are playing them!) is the way the edge of the body leans back, which suggests a good, comfortable position to rest the arm on the guitar - with the middle of the forearm resting on the body, slightly diagonally down towards the strings.
Answer: This is such an important question to consider. You should feel blessed that have reached this point of indecision of how to hold the electric guitar at this phase, because when first switching to electric guitar from a different instrument is when bad habits are often formed.

you need to decide what your primary manner of articulating with your right hand will be. Are you going to use your fingers and fingerpicking or do you plan to use a pick? There is also a hybrid-style, where you can tuck the pick underneath one finger when not using it. (How to hide a flat pick in the right hand when switching to finger picking, Warren Haynes style). If you decide to use pick-only, there are two styles (this comes from what they teach at Berklee college of music), holding the pick at a downward angle against the string, vs an upward angle. Both are valid, but you would have to CHOOSE which is most comfortable for you. All of these techniques are tried and true, but my personal opinion is that the guitar players who are the best with their right hand always hold the pick at an upward angle against the string, sometimes slightly palm muting. You can observe Django Reinhardt, Allan Holdsworth, Pat Metheney and George Benson all holding the pick in this way. For a finger-style approach, I recommend checking out Lenny Breau.
Once you've decided how you want to pluck the strings, you need to observe other, better players using similar right-hand technique and model your arm position after them. It's as simple as that. With each different picking style, the right arm will have a slightly different position. Strap height is also very important if you choose to stand up, so pay attention to how other players adjust their straps as well.


Apigility+Doctrine: custom response

Question: I have a project running on Apigility + Doctrine. From a scratch (automatically without writing extra code), I can retrieve entities and collections with pagination, filtering, etc.
This is perfect when retrieving DB rows, however, most services need to return much more data. For example: a to-do list where the "tasks" have parents, if you want to retrieve this like a tree, you´ll have to process it first. Very often I need flags to tell the frontend how to process data or keys to display or hide stuff. Sometimes it is useful to retrieve extra information that is not expressed in the database as FK or PK, etc.
So far, with Apigilty+Doctrine, if I want to add ANY information to the output, I have to modify the Entity, set up the correct keys, and it works. However, from the previous examples you can see that the data that I need is NOT coming from the database or I cannot simply express the relation as a DB dependency.
Questions:

What is the correct way of doing this?
Is there are documentation about this problem?
How can I customize my output keeping a correct HAL structure?
Answer: By default, the Entity values will be given as response as is. If you want to modify the value (eg: retrieving parent data, retrieving child data, or modifying the data format) you should create a Hydrator for this Entity, and custom Hydrator Strategy for this Entity value.
Here is Hydrator example from my Apigility and Doctrine project
https://github.com/aqilix/zf3-apigilty-oauth2/blob/1.0.1/module/User/src/V1/Hydrator/UserProfileHydratorFactory.php

Apigility+Doctrine: custom response


postfix multiple IP SMTP banner

Question: I've installed postfix 2.11.3 and we have multiple IP addresses on our server which we want to host two domains, isolated and running on their own IPs.
domain1  unix -       -       n       -       -       smtp
   -o smtp_bind_address=126.96.36.199
   -o smtp_helo_name=mail.abc.com
   -o syslog_name=postfix-mail.abc.com

domain2  unix -       -       n       -       -       smtp
   -o smtp_bind_address=126.96.36.199
   -o smtp_helo_name=mail.xyz.com
   -o syslog_name=postfix-mail.xyz.com

Following transporter /etc/postfix/sender_transport also defined in main.cf:
@abc.com    domain1:
@xyz.com    domain2:

After restarting postfix, it stopped listening on port 25:
[firstname.lastname@example.com]# telnet 184.108.40.206 25
Trying 18.104.22.168...
telnet: connect to address 188.8.131.52: Connection refused

But if I use following line in master.cf it listen on 25 and i can see banner if i telnet:
126.96.36.199:smtp inet  n - n - - smtpd -o myhostname=mail.abc.com
188.8.131.52:smtp inet  n - n - - smtpd -o myhostname=mail.xyz.com

But I want to tell my mail server when you send out email use specific domain just like sender_transport
What i am doing wrong?
Notes:
I have removed following line from master.cf and replaced with above domain1 and domain2:
smtp      inet  n       -       n       -       -       smtpd

Comment: Any error lines in `maillog` after you restart postfix??
Comment: Yes, restarted and nothing in logs, I have very good knowledge of `qmail` mail and mail services so i have checked all basic stuff, I am new with postfix so bit confused, I think we need `220.127.116.11:smtp` line without that it is not going to listen on `25` port, Now i have put both entries `domain1/2` with `ipaddress:smtp` now it is listening on both IPs. but issue is when i am sending email from xyz.com it is default using `126.96.36.199` IP that means it is not looking into `sender_transport` file.
Comment: This is what i am trying to do but it didn't work https://wied.it/blog/sender-dependent-default-transport-maps-with-postfix-the-easy-way.html
Comment: Sorry guys! i have figured out what was the issue, we need both entries. `x.x.x.x:smtp` and `domain1/2` before i was using either domain1 or smtp but i got the point.. sorry for hassle
Answer: Solution - Postfix version 2.7 or above required:
/etc/postfix/master.cf
#smtp      inet  n       -       n       -       -       smtpd
127.0.0.1:smtp inet  n     -       n       -       -       smtpd
      -o syslog_name=postfix-localhost
      -o smtp_helo_name=localhost
      -o smtp_bind_address=127.0.0.1
      -o myhostname=localhost

65.xxx.xxx.100:smtp inet  n     -       n       -       -       smtpd
      -o syslog_name=postfix-mail.abc.com
      -o smtp_helo_name=mail.abc.com
      -o smtp_bind_address=65.xxx.xxx.100
      -o myhostname=mail.abc.com

65.xxx.xxx.200:smtp inet  n     -       n       -       -       smtpd
      -o syslog_name=postfix-mail.xyz.com
      -o smtp_helo_name=mail.zyx.com
      -o smtp_bind_address=65.xxx.xxx.200
      -o myhostname=mail.xyz.com

abc-out  unix -       -       n       -       -       smtp
   -o smtp_bind_address=65.xxx.xxx.100
   -o smtp_helo_name=mail.abc.com
   -o syslog_name=postfix-mail.abc.com

xyz-out  unix -       -       n       -       -       smtp
   -o smtp_bind_address=65.xxx.xxx.200
   -o smtp_helo_name=mail.xyz.com
   -o syslog_name=postfix-mail.xyz.com

/etc/postfix/main.cf
sender_dependent_default_transport_maps = hash:/etc/postfix/sender_transport

/etc/postfix/sender_transport
# Use source IP - 65.xxx.xxx.100
@abc.com                abc-out:
@example.com            abc-out:

# Use source IP - 65.xxx.xxx.200
@xyz.com                xyz-out:

Run command to generate hash db
postmap hash:/etc/postfix/sender_transport

Restart/Reload postfix
service postfix reload

Testing
[root@localhost ~]# telnet 65.xxx.xxx.200 25
Trying 65.xxx.xxx.200...
Connected to 65.xxx.xxx.200.
Escape character is '^]'.
220 mail.xyz.com ESMTP Postfix

Sending email test
[root@localhost ~]# telnet localhost 25
Trying ::1...
telnet: connect to address ::1: Connection refused
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
220 localhost ESMTP Postfix
helo localhost
250 localhost
mail from: email@example.com
250 2.1.0 Ok
rcpt to: firstname.lastname@example.com
250 2.1.5 Ok
data
354 End data with <CR><LF>.<CR><LF>
Hello world!
.
250 2.0.0 Ok: queued as 93E708207BA

Got to gmail Inbox > Show Original
Delivered-To: email@example.com
Received: by 10.xxx.xxx.xxx with SMTP id w64csp782609qgd;
        Tue, 9 Dec 2014 09:35:57 -0800 (PST)
X-Received: by 10.xxx.xxx.xxx with SMTP id o28mr4132552yha.168.1418146557180;
        Tue, 09 Dec 2014 09:35:57 -0800 (PST)
Return-Path: <firstname.lastname@example.com>
Received: from mail.xyz.com ([65.xxx.xxx.200])
        by mx.google.com with ESMTPS id n10si743294ykc.114.2014.12.09.09.35.56
        for <email@example.com>
        (version=TLSv1.2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128);
        Tue, 09 Dec 2014 09:35:56 -0800 (PST)
...
...
Message-Id: <firstname.lastname@example.com>
Date: Tue,  9 Dec 2014 12:37:11 -0500 (EST)
From: firstname.lastname@example.com

Hello world!

Voila!! see it used 65.xxx.xxx.200 IP address to sent out email..
Received: from mail.xyz.com ([65.xxx.xxx.200])

Comment: I'm trying the same but hitting a configuration conflict with the default directives Ubuntu uses in master.cf. There is a conflicting smtp listener for the main IP address. How do you deactivate the default SMTP service? This is also for a system using amavis.
Comment: @soze hash on begin mean comment line #smtp      inet  n
Comment: Is there a way to set options like `smtp_bind_address` directly from `transport_maps` / a MySQL table instead of having them hardcoded at the `master.cf` file?

postfix multiple IP SMTP banner


Substituting $y=1/x$ to apply Eisenstein's Criterion

Question: Apparently, the polynomial $1-3x^3$ can be shown to be irreducible in $\mathbb{Q}[x]$ by using the substitution $y=1/x$ and then applying Eisenstein's Criterion. My question is, how can one apply Eisenstein to the function
$$
1-\frac{3}{x^3}
$$
Obviously multiplying by $x^3$ gives an irreducible polynomial but how does that help me?
Comment: Are you asking about the relations between factorizations of $1-3x^3$ and $y^3-3$?  Those at least are both polynomials.  The rational function $1-\frac{3}{x^3}$ is not in $\mathbb{Q}[x]$, so it doesn't "factor" there.
Answer: Hint: Let $k$ be a field and let $f(x) \in k[x]$ be a non-zero polynomial of degree $n$. Define $\sigma(f)(x) := x^n f(1/x).$ Then $\sigma(f)(x) \in k[x].$ Suppose $f$ has non-zero constant coefficient. Then $f$ is irreducible if and only if $\sigma(f)$ is irreducible.
In this case $f(x) = 1 - 3x^3.$ So $\sigma(f)(x) = x^3 - 3.$ By Eisenstein's Criterion, $\sigma(f)(x)$ is irreducible. Hence $f(x)$ is irreducible.
$\bf{EDIT:}$ (proof of the above mentioned result.)
The following things are easy to verify: (a) $\sigma(fg) = \sigma(f) \sigma (g),$ and (b) $\sigma(\sigma(f)) = f,$ (c) $deg(\sigma(f)) = deg f.$ If $f$ is reducible, then $f = gh$ for some non-constant polynomial $f, g \in k[x].$ Then $\sigma(f) = \sigma(gh) = \sigma (g) \sigma(h)$ and both $\sigma(g), \sigma(h)$ are non-constant polynomials in $k[x].$ On the other hand, assume that $\sigma(f)$ is reducible. Then $\sigma(f) = gh,$ for some non-constant polynomials $g, h \in k[x].$ Then $f = \sigma(\sigma(f)) = \sigma(f) \sigma (g)$ and $\sigma(g), \sigma (f)$ are non-constant polynomials in $k[x].$
Comment: Yes, if I knew this proposition was true then I'd be fine! But I suppose that's my question; how does one go about showing this?
Comment: Suppose $f$ is reducible, i.e. $f = hk$. Then $g = (x^{\text{deg}(h)} \cdot h)(x^{\text{deg}(k)} \cdot k)$ so $g$ is reducible. Can you try the other direction?
Comment: @TomOffer: I've included a proof of the mentioned result.
Comment: Very neat. Thanks!


how to use image for next previous link in pager in drupal 7

Question: I am woking on drupal 7 I want to change link text and replace them with image. How can I achieve following:

Is there any function in template.php to do so?
Is there any way to overridden template to pager in custom theme?
Comment: Just use CSS and hide the text. Much better for accessibility.
Answer: In template.php
<code>function THEMENAME_pager($tags = array(), $limit = 10, $element = 0, $parameters = array()) {

}
</code>
http://api.drupal.org/api/drupal/includes!pager.inc/function/theme_pager/7
For api please check above link you can overridden.   also check below link.
In drupal 7, How to override theme_pager?


Can a player hold the ball under their body or legs in football?

Question: In a junior football match, one of the players had picked up an unusual habit. She would make a sliding tackle but end up on the ground, with the ball between her legs. She would then keep possession, using her legs while still sitting on the floor.
It seemed unorthodox and possibly dangerous, as she was at risk of being fouled by opposition players trying to get the ball.
Rugby union has a rule whereby the ball must be released; the player that is tackled and the tackling player must immediately release the ball to allow for play to continue.
I couldn't find a similar rule in football's laws of the game. Can a player hold the ball under their body or legs in association football?
This is distinct from Walking the ball across the line for a goal, as there is no attempt to move the ball or score a goal.
Comment: Sir we said possible duplicate because  answer in there answer this question. Sir lets wait for other to review if they don't think it is one I will retract my own also.
Answer: Law 12.2 is straightforward, that

An indirect free kick is awarded if a player:

plays in a dangerous manner

whence "playing in a dangerous manner" is defined as

[...] any action that, while trying to play the ball, threatens injury to someone (including the player themself) and includes preventing a nearby opponent from playing the ball for fear of injury.

with my emphasis. Law 12.3 further provides that

A player is cautioned if guilty of:
...
persistent offences (no specific number or pattern of offences constitutes "persistent")

should the referee determine that they continued to commit this offence.
Comment: I think the emphasis would be better at "including the player themself", other than that, this would  also be my reply.


Incomplete Cholesky decomposition conjugate gradient method in Matlab

Question: I have a problem in finding the numerical material that describing in detail for incomplete Cholesky combined with conjugate gradient method by using Matlab. Someone can help me? Many thank in advance.
Answer: I'm not really sure what the "numerical material" means but if you'd like to use the incomplete Cholesky preconditioner with conjugate gradients in MATLAB, you might consider using doc cholinc and doc pcg commands for detailed information.
Working example:
A = gallery('poisson', 32);
b = ones(32^2, 1);
R = cholinc(A, 0.1); % Incomplete Cholesky fact.: A \approx R * R'
x = pcg(A, b, 1e-6, 100, R, R');


save results of a promise to a variable in controller?

Question: I am stuck on promise resolution, can anyone explain to me how to store the promise result in a variable? I am working with mongoDB and I want to get some data from it.
here is my example.
const checkRelated = new Promise((resolve, reject) => {
     return RelatedProducts.find({
        parent_id: { $in: product_id.split(',') },
      })
        .then((res) => reject(res))
        .catch(err => reject(err))

    })

after getting the data I want to do some validation. For example.
if(checkRelated.length > 0) {
do smth....
}

but to my surprise I get "promise {pending}"
Comment: why are you creating a new promise?
Comment: what should I do?
Comment: Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! What you actually want/need is to put that `if` condition inside the `.then(checkRelated => { … })` callback.
Answer: You're overcomplicating Mongoose, if you want to do an async function you can but I've never seen a new Promise being used with Mongoose.
If you want to create an async method with mongoose do the following
exports.getRelatedProducts = async (req, res) => {
  try {
    const checkRelated = await RelatedProducts.find({parent_id: {
  $in: product_id.split(',') }})

    if (checkRelated.length > 0){
      do smth...
    }
  } catch (error) {
      reject(error)
  }
}

but keep in mind you must create the async method first. then you can use await.
Comment: I'm just modifying someone else's code that has already been written..
Thanks, I'll try now
Comment: `catch (error) { reject(error) }` makes no sense
Comment: I just used what they had listed above. They can do whatever they want in the error handler.


Protocol Relative URLs in Drupal 6

Question: I'm trying to avoid serving pages that load css and js resources through URLs that specify either http or https.
Because Drupal is specifying http:// for the href for all the CSS and JS files.
Caching server varnish, caching the JS & CSS files twice (through http & https).
Instead of
<link type="text/css" rel="stylesheet" href="http://www.example.com/sites/default/files/css/css_pbm0lsQQJ7A7WCCIMgxLho6mI_kBNgznNUWmTWcnfoE.css" media="all" />

I'd like to serve
<link type="text/css" rel="stylesheet" href="//www.example.com/sites/default/files/css/css_pbm0lsQQJ7A7WCCIMgxLho6mI_kBNgznNUWmTWcnfoE.css" media="all" />

Trying to achieve this in Drupal 6 sites through a module.
Comment: Unless you force a $base_url configuration in the settings.php file, Drupal will always use relative URLs (base URL for both URLs in the question would be `/`... `/about`, `/contact`, likewise).
Comment: Because of how [url](https://api.drupal.org/api/drupal/includes!common.inc/function/url/6) works, relative urls are the default behaviour, so I still have no idea what your trouble is. Why would you need a module, and what would it do?
Comment: `/about` (Drupal default) is technically the same as `//www.example.com/about` (what you need) protocol wise. Are you trying to serve cookies differently or anything different from the general use case?
Comment: I don't understand what the problem is.
Comment: @Letharion , now the Drupal 6 sites we are maintaining has absolute URLs for Javascript & Stylesheets in headers, and we are using varnish for caching which loads these style sheets and JS files twice, so we are trying to remove the Protocol from the URLs
Comment: @letharion, the op wants to use `//` instead of `http://` or `https://` according to which protocol the user may be browsing. Especially useful in external urls.
Comment: @kekkis Yes exactly which I'm trying to get
Comment: Yes, our content is serving via both https & http, so it is caching twice.Currently both JS and CSS files in header has Full Urls with protocol, so I wanted to remove protocol from Header Style and JS Files.
Comment: But that's exactly the use case for `base_path()`. You don't need the server name at all, just the path relative to your html_root, so to say.
Comment: I edited my question now and I guess it is more clear now and also this issue is resolved and Posted .module implementations in answers and I don't know still why it is in Hold.
Answer: Issue is fixed now. Implemented module_preprocess() (in custom module)
function module_name_preprocess(&$vars) {
    foreach (array('head', 'styles', 'scripts') as $replace) {
    if (!isset($vars[$replace])) {
        continue;
    }

    $vars[$replace] = preg_replace('/(src|href|@import )(url\(|=)(")http(s?):/', '$1$2$3', $vars[$replace]);
}

}

Protocol Relative URLs in Drupal 6


How should I balance Features and Installation Profile in a Code Driven Development workflow?

Question: Drupal Installation Profiles (in Drupal 7) are pretty powerful and can do just about anything a module can do. I'm using an Installation Profile along with Features to develop my site, keeping everything in code so I don't have to version my database.
Given the power of Installation Profiles, many of the things you can do in a Features module can also be done in an Installation Profile. E.g., creating content types, configuring permissions, etc. How should you go about deciding whether something belongs in an Installation Profile or in a Features module when using a Code Driven Development workflow in Drupal?
Comment: Nuvole answered this question and I'm too lazy to post a summary as an answer. http://nuvole.org/blog/2012/feb/07/hard-and-soft-configuration-drupal-distributions
Answer: I've recently started using the Features module as a deployment system, as described in this presentation on features deployment. Assuming your using a similar setup with hook_update_N, features has one clear advantage that I'm aware of: it's aware of any changes that are not in code. This makes it a fair bit easier to track changes to (for example) views and content types, and also allows you to auto-generate the new features code to be committed and deployed.
I'm not overly familiar with installation profiles, but from the link you've provided it doesn't look like they provide this functionality. However it might be a case of use whichever suits you the best.
Edit: rethought response.
Comment: Profiles can have update hooks, they're pretty much modules in Drupal 7
Comment: One of the issues I've run into is that not everything can go in a feature, and even when it can, it doesn't always play nicely when enabling all the features at once. For example, I've had issues putting different taxonomy vocabularies and permissions in different modules. In that case, a SQL exception prevented the modules from enabling correctly.
Answer: I'm using drush quite a bit for this. I have three combined commands (never tried it in one line lol) that I execute after installing Drupal. I got most of the things up and running quite quickly.
So many things you can do with Drush. Downloading and enabling multiple modules is as simple as
<code>drush dl rules views admin_menu && drush en -y rules views admin_menu && drush dis -y toolbar
</code>
multiple views can be imported per module easily https://www.drupal.org/node/1393228.
Just annoying that I can't import multiple rules (without the Features module).


Como exibir valores do gráfico em chartJS sem mouseover?

Question: var chartData = {
    labels: [<?php echo html_entity_decode($nomes) ?>],
    datasets: [{
        label: 'Desempenho global (Todas limpezas efetuadas em <?php echo $anoAvaliado ?>)',
        data: [<?php foreach($limpezasAnuais as $limpeza){ echo $limpeza.",";} ?>],
        backgroundColor: [<?php foreach ($cores as $cor){echo "\"" . $cor . "\",";} ?>],
        borderWidth: 1
    }]
}
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'horizontalBar',
    showTooltips: false,
    data: {
        labels: [<?php echo html_entity_decode($nomes) ?>],
        datasets: [{
            label: 'Desempenho global (Todas limpezas efetuadas em <?php echo $anoAvaliado ?>)',
            data: [<?php foreach($limpezasAnuais as $limpeza){ echo $limpeza.",";} ?>],
            backgroundColor: [<?php foreach ($cores as $cor){echo "\"" . $cor . "\",";} ?>],
            borderWidth: 1
        }]
    },
    options: {
        scales: {

            xAxes: [{
                ticks: {
                    beginAtZero: false
                }

            }]

        }
    }
});

Answer: Você pode user o eventos que o ChartJS disponibiliza. Por exemplo, para que o gráfico responda apenas a eventos de clique, você pode usar:
options: {
        //Este gráfico não responderá ao mousemove, etc
        events: ['click']
}

Para deixar o Tooltip sempre visível na versão ChartJs > 2.1.5 você pode controlar através das propriedade do options. Lembrando que você precisa registrar o plug-in antes de inicializar o gráfico.
Fonte
Chart.pluginService.register({
  beforeRender: function(chart) {
    if (chart.config.options.showAllTooltips) {
      chart.pluginTooltips = [];
      chart.config.data.datasets.forEach(function(dataset, i) {
        chart.getDatasetMeta(i).data.forEach(function(sector, j) {
          chart.pluginTooltips.push(new Chart.Tooltip({
            _chart: chart.chart,
            _chartInstance: chart,
            _data: chart.data,
            _options: chart.options.tooltips,
            _active: [sector]
          }, chart));
        });
      });
      chart.options.tooltips.enabled = false;
    }
  },
  afterDraw: function(chart, easing) {
    if (chart.config.options.showAllTooltips) {
      if (!chart.allTooltipsOnce) {
        if (easing !== 1)
          return;
        chart.allTooltipsOnce = true;
      }

      chart.options.tooltips.enabled = true;
      Chart.helpers.each(chart.pluginTooltips, function(tooltip) {
        tooltip.initialize();
        tooltip.update();
        tooltip.pivot();
        tooltip.transition(easing).draw();
      });
      chart.options.tooltips.enabled = false;
    }
  }
});

Em seguida usar
options: {
    showAllTooltips: true
}

Exemplo

var canvas = document.getElementById('myChart');
Chart.pluginService.register({
  beforeRender: function(chart) {
    if (chart.config.options.showAllTooltips) {
      chart.pluginTooltips = [];
      chart.config.data.datasets.forEach(function(dataset, i) {
        chart.getDatasetMeta(i).data.forEach(function(sector, j) {
          chart.pluginTooltips.push(new Chart.Tooltip({
            _chart: chart.chart,
            _chartInstance: chart,
            _data: chart.data,
            _options: chart.options.tooltips,
            _active: [sector]
          }, chart));
        });
      });
      chart.options.tooltips.enabled = false;
    }
  },
  afterDraw: function(chart, easing) {
    if (chart.config.options.showAllTooltips) {
      if (!chart.allTooltipsOnce) {
        if (easing !== 1)
          return;
        chart.allTooltipsOnce = true;
      }

      chart.options.tooltips.enabled = true;
      Chart.helpers.each(chart.pluginTooltips, function(tooltip) {
        tooltip.initialize();
        tooltip.update();
        tooltip.pivot();
        tooltip.transition(easing).draw();
      });
      chart.options.tooltips.enabled = false;
    }
  }
});

var data = {
  labels: ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho"],
  datasets: [{
    label: "Meu dataset",
    backgroundColor: "rgba(255,99,132,0.2)",
    borderColor: "rgba(255,99,132,1)",
    borderWidth: 2,
    hoverBackgroundColor: "rgba(255,99,132,0.4)",
    hoverBorderColor: "rgba(255,99,132,1)",
    data: [65, 59, 20, 81, 56, 55, 40],
  }]
};

var myBarChart = Chart.Bar(canvas, {
  data: data,
  options: {
    showAllTooltips: true,
    tooltips: {
      callbacks: {
        title: function(tooltipItems, data) {
          return '';
        },
        label: function(tooltipItem, data) {
          var datasetLabel = '';
          var label = data.labels[tooltipItem.index];
          return data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
        }
      }
    }
  }
});

<canvas id="myChart" height="230" width="680"></canvas>
Comment: Muito obrigado pela ajuda @Netinho Santos. Funcionou!!! Deus te abençoe!
Comment: Entendi Netinho, mas não é possível que o valor seja exibido sem eu precisar clicar e sem precisar do mouseover?  Preciso que funcione assim para sair no PDF.
Comment: @ViniciusAvanzi é possível sim. Alterei a resposta. Vê se te atente. Att.
Comment: deu certinho! Só mais uma coisa, tem como exibir somente o valor? Está exibindo os nomes e também a legenda.Queria postar o print aqui mas ainda não sei mexer direito no fórum, rsrsrsr
Comment: @ViniciusAvanzi Alterei novamente a resposta para exibir apenas o valor. Caso tenha mais dúvida, consulte a documentação do plugin: http://www.chartjs.org/docs/latest/
Se a resposta te atender vote nela para ajudar a outra pessoas. Att.
Comment: o que você fez? Alterou o registro do plugin ? Obrigado! Como faço para votar na resposta ?
Comment: @ViniciusAvanzi eu coloquei no option a função callbacks. Para você votar como resposta aceita clica no 'v' dá resposta. Veja o print aqui: https://uploaddeimagens.com.br/imagens/capturar-png-6347e280-f9dd-416e-942f-97b650b40ca1
Comment: @ViniciusAvanzi O stack tem um tour onde você poderá sanar suas dúvida como voto útil, voto de aceite para resposta, condutas e como elaborar perguntas e resposta. Segue o link https://pt.stackoverflow.com/tour

Att.


perl regex of exactly 10 characters

Question: I'm using perl flavored regexes in PHP with the preg_match function. I want to validate a key that is exactly 10 characters, with upper case alpha characters or numbers.
I have
preg_match( '/[^A-Z0-9]/', $key);

which finds invalid characters next to valid ones. In my limited knowledge, I tried
preg_match( '/[^A-Z0-9]{10}$/', $key);

which turns out to match all my test strings, even the invalid ones.
How do I specify this regular expression?
Answer: You've misplaced the ^ character which anchors the beginning of a string. /[^A-Z0-9]{10}$/ would match all files ending on 10 characters that are not uppercase letters and digits.
The correct RE would be:
preg_match( '/^[A-Z0-9]{10}$/', $key);

Explanation of the regexp:

^ - matches from the beginning of the string

[ - begin of a character class, a character should match against these. If a ^ is found straight after this [, it negates the match

A-Z - uppercase letters
0-9 - digits

] - end of a character class
{10} - matches the previous character class 10 times

$ - matches the string till the end
Comment: @user151841: if you want to return on strings that contain invalid characters or do not have a length of 10, use the `!` to negate the return value. I.e. `if (!preg_match('/^[A-Z0-9]{10}$/')) return false;`
Comment: Ah! I see what I did. When I started writing it, I intended to check for any *invalid* character (and return false). Then I wanted to ensure it was 10 characters long. Is there any way to write the regex to check for *invalid* characters **and** make sure the string is 10 characters long?
Comment: `/^[^a-z]{10}$/` will match 10 digit strings that don't have any lowercase characters.
Comment: @Jacob yeah, but I need it to throw out any non-alphanumerics, too.
Comment: This should work for anything that in not a lowercase and not a non-word character `[a-zA-Z0-9_]` and not an _ `/^[^a-z\W_]{10}$/`
Comment: @Lekensteyn Sorry you're mistaken. I've tested `/^[^a-z\W_]{10}$/` successfully [here](http://www.spaweditor.com/scripts/regex/index.php) against strings such as `ASDFAS_FA8` `ASDFAS#FA8` `ASDFASFFA8` `asfdasdf89` and `ASDFASDFASDF`
Comment: @Jacob: oops, my fault. I've misinterpreted the results from my functions.

perl regex of exactly 10 characters


adding css class in content pages

Question: I am working on a page which is using a Master page for some default design,
I need some css class to be added to the conent page, which we add normally in script tag in normal pages,
My question is how to add some css content in a page which is using Master page,
Thanks,
Vishal.
Answer: In your master page you can add a content area within the  block.  We call ours "HeadContent".
Our master page's head block looks like this:

    ...
    <asp:ContentPlaceHolder ID="HeadContent" runat="server" />

From your content pages you can then include custom scripts/css etc:
<asp:Content runat="server" ID="Head" ContentPlaceHolderID="HeadContent">

</asp:Content>

Answer: You could add a ConentPlaceHolder in the head area of your masterpage like this:

 ....
<asp:ContentPlaceHolder id="PlaceHolderAdditionalPageHead" runat="server" />

In your content page you just need a content control:
<asp:Content ID="Content1" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="Server">
   // Put your css stuff here
</asp:Content>

adding css class in content pages


Identificar determinada url e alterar propriedade href com preg_match_all

Question: Opa pessoal,
Estou com uma função que deve identificar uma determinada url. Caso a url seja identificada, ela deve ser envolvida com a tag  e sua propriedade href deve ter o valor igual ao da url passada. No caso, quero que apenas uma url e seus diretórios sejam transformados em links, ao passo que outras url diferentes continuem do mesmo jeito que estão.
Exemplo: A url que quero transformar em link sempre que aparecer no texto é: www.meusite.com.br
O problema que estou tendo é o seguinte: Na minha função, não estou conseguindo identificar a url sem o http. O que eu preciso é identificar a url com ou sem o protocoloco http e fazer com que o link tenha o seu href preenchido corretamente.
Preciso identificar os 3 casos abaixo, porém só consigo identificar o primeiro.
http://www.meusite.com.br
www.meusite.com.br
meusite.com.br

Lembrando que urls diferentes dessa não devem ser identificadas no filtro da função. Ex: meusite2.com.br não deve ser filtrado
Segue minha função com o que tentei:
    function checkUrl($text){
        $pattern = "(https?)?://[a-z0-9./&?:=%-_]*";

        preg_match_all($pattern, $text, $matches);
        if( count($matches[0]) > 0 ){
            foreach($matches[0] as $match){
                $text = str_replace($match, "" . $match . "", $text);
            }
        }
        return $text;
    }

$text = "Em http://www.meusite.com.br você encontra muitas dicas sobre o assunto. Na url www.meusite.com.br você encontra especialistas com seus artigos esclarecdores. E claro, meusite.com.br é o melhor site no assunto";

Acredito que meu problema esteja somente na variável $pattern, em que passo o padrão a ser encontrado.
Pesquisei aqui no fórum, mas não encontrei exatamente o que eu precisava
Identificar URLs e criar links
O link acima não ajudou, e devo fazer isso no php.
Comment: Saquei, `RE` não é meu forte...rsrs
Comment: Com `http` está funcionando corretamente?
Comment: Sim. Meu problema está quando retiro o http da url. Ele para de reconhecer :(
Comment: Só fiquei na dúvida pois no seu código ali esta com `https`...
Comment: aquela parte ali diz que tanto o http como o https podem ser usados. No caso o uso do s seria opcional.
Comment: kkkk nem o meu, por isso to pedindo ajuda kkkkk
Comment: hahaha, acho que minha resposta deve ajudar...
Answer: Você pode tratar antes para sempre ter http na url da seguinte forma:
function checkUrl($text){

    //primeiro garantindo que todos vão estar iguais
    $find = ['http://www.meusite.com.br', 'https://www.meusite.com.br', 'www.meusite.com.br'];
    $replace = "meusite.com.br";
    $text = string_replace($find, $replace, $text);

    //depois será possível colocar o http sem duplicar, caso já tivesse antes
    $find = ['meusite.com.br'];
    $replace = "http://www.meusite.com.br";
    $text = string_replace($find, $replace, $text);

    //e o que já estiver funcionando vai tratar tudo agora...
    $pattern = "(https?)?://[a-z0-9./&?:=%-_]*";

    preg_match_all($pattern, $text, $matches);
    if( count($matches[0]) > 0 ){
        foreach($matches[0] as $match){
            $text = str_replace($match, "" . $match . "", $text);
        }
    }
    return $text;
}


grails spring-security plugin secures all controllers instead of just ones with @Secured annotation

Question: I'm following the tutorials to use springsecurity authentication plugin.  I am using grails version 2.3.8 and spring-security-core:2.0-RC2.  It worked as expected to create the HelloWorld controller with the Secured annotation:
package basicauthdemo
import grails.plugin.springsecurity.annotation.Secured

class HelloController {
    @Secured(['ROLE_USER'])
    def index() {
    render "Hello World"
    }
}

and then be presented with a login screen.
My question is that when I created another controller without the @Secured annotation.  I still get the login screen when navigating to that controller.  Spring security is now in charge of all access to my controllers as I can see from the filter-mapping in the generated web.xml:
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>ERROR</dispatcher>
    <dispatcher>REQUEST</dispatcher>
  </filter-mapping>

How to tell the plugin to allow open access to some controllers and not others?  I thought that this would be determined by presence of @Secured annotation but that only defines the role with permissions for the controller.
Answer: According to the documentation for Spring Security Core plugin the default behavior is pessimistic lockdown

...  then any URL that has no request mappings (an annotation, entry
  in controllerAnnotations.staticRules or interceptUrlMap, or a
  Requestmap instance) will be denied to all users.

I highly recommend reading that particular section of the documentation to see how to configure the plugin for your use. Typically this will be modifying the default value of rejectIfNoRule and configuring the appropriate staticRules.


When is a Fourier series analytic?

Question: By Fourier theory, every continuously differentiable function $f : S^1 \to \mathbf C$ admits a unique, uniformly convergent Fourier expansion
$$f(\theta) = \sum_{n\in \mathbf Z} a_n e^{in\theta}.$$
Does there exist a condition on the sequence $(a_n)$ equivalent to $f$ being analytic in $\theta$ in a neighborhood of $\theta=0$ (meaning that it has a convergent Taylor expansion $\sum_{m\geq 0}\frac{\theta^m}{m!} b_m$ in a neighborhood of $0$)?
Writing $e^{in\theta} = \sum_{m\geq 0} \frac{(in)^m}{m!} \theta^m$, formally switching the two sums yields
$$f(\theta) = \sum_{n\in \mathbf Z} \sum_{m\geq 0} a_n \frac{(in)^m}{m!} \theta^m = \sum_{m\geq 0} \sum_{n\in \mathbf Z}  a_n \frac{(in)^m}{m!} \theta^m =  \sum_{m\geq 0}\frac{\theta^m}{m!} b_m$$
where $$b_m = i^m\sum_{n \in \mathbf Z} a_n n^m.$$
(Remark that there is the formal "double-sided" Dirichlet series
$$L(f, s) = \sum_{n \in \mathbf Z} a_n n^{-s}$$
and formally, we can write $b_m = i^mF(-m)$.)
First question: is it true that $f(\theta)$ is analytic at $0$ if and only if:

the sums defining the $b_m$'s converge absolutely, and
the series $\sum_{m\geq 0}\frac{\theta^m}{m!} b_m$ converges in a
neighborhood of $0$, in which case it coincides with $f$ around $0$?

Second question: Can we determine whether $f$ is analytic around $0$ directly by looking at the sequence $(a_n)$?
Comment: Dear @user147263 : Thanks for pointing that out, I have modified the assumption on $f$. Do you happen to have a reference for the proof of the equivalence between analyticity on all of $S^1$ and rapid decay of $(a_n)$? Also, I'm curious to know why you think it is unlikely that there exists a criterion for analyticity at $0$. (My intuition for these things is rather poor.)
Comment: Dear @user147263: Thanks a lot for the proof sketch and for your intuition. I'll give it some thought. If you have the time to write that into an answer, I will gladly accept it.
Answer: I begin with the second question. By looking at the coefficients $a_n$, you can easily see analyticity on all of $S^1$: it holds iff $|a_n|$ decay exponentially in both directions. This is Exercise I.4.4 from An Introduction to Harmonic Analysis by Y. Katznelson, 3rd edition:

Show that $f$ is analytic on $\mathbb T$ if and only if there exist constants $K>0$ and $a>0$ such that $|\hat f(j)|\le K e^{-a|j|}$.

Indeed, think in terms of complex plane, replacing $\exp(i\theta )$ by $z$. Two-sided exponential decay gives you convergent Laurent series in some annulus containing the circle. Conversely, analytic function on the circle can be extended to analytic function on some annulus; such a function is represented by a convergent Laurent series, which gives exponential decay of coefficients.
At the same time, Fourier coefficients are poorly suited to detect analyticity at a point, since they take into account the whole function. If you have a break in second derivative somewhere on the circle, that is going to dominate the behavior of coefficients; the contribution of analytic piece somewhere will be tiny in comparison.

First question: the conditions 1-2 are sufficient for analyticity in a neighborhood of $0$, but are not necessary. To begin with, the series
$$b_m = i^m\sum_{n \in \mathbf Z} a_n n^m \tag{1}$$
converges for all $m$ iff $|a_n|$  decay faster than any power of $n$. This kind of decay is equivalent to $f$ being in $C^\infty(\mathbb T)$ (see section I.4 in Katznelson's book). So, if you have an analytic function in a neighborhood of $0$ that is not $C^\infty$ on the entire circle, the condition for $b_m$ does not make sense*.
(*) You could try to regularize the divergent series (1), but I think the regularization would amount to summing the Fourier series and then differentiating the sum.
Sufficiency can be established without rearranging the series. As noted above, the convergence of every series in (1) implies $f\in C^\infty(\mathbb T)$. We evaluate the derivatives of $f$ at $0$ just by  plugging in $\theta=0$ into the differentiated Fourier series. This gives Taylor coefficients, in terms of which the analyticity at  $0$ is characterized.
Comment: Thanks a lot, that is exactly what I was looking for.

When is a Fourier series analytic?


SnapRaid scrub shows tons of data errors on parity drive

Question: I am new to SnapRaid and wonder what is wrong when all scrub runs look like this:
<code>...
Data error in parity 'parity' at position '11242042', diff bits 1048371/2097152
Data error in parity 'parity' at position '11242043', diff bits 1048278/2097152
Data error in parity 'parity' at position '11242044', diff bits 1048591/2097152
Data error in parity 'parity' at position '11242045', diff bits 1047674/2097152
Data error in parity 'parity' at position '11242046', diff bits 1049725/2097152
Data error in parity 'parity' at position '11242047', diff bits 1048050/2097152
Data error in parity 'parity' at position '11242048', diff bits 1048318/2097152
Data error in parity 'parity' at position '11242049', diff bits 1049356/2097152
Data error in parity 'parity' at position '11242050', diff bits 1049158/2097152
Data error in parity 'parity' at position '11242051', diff bits 1047212/2097152
Data error in parity 'parity' at position '11242052', diff bits 1049267/2097152
Data error in parity 'parity' at position '11242053', diff bits 1048615/2097152
...

100% completed, 6380380 MB accessed in 3:49

0 file errors
0 io errors
6084943 data errors
</code>
Looks like all data on parity is kinda broken.
But the setup is only 1 month old and scrubbing started just some days ago.
There are no smart errors or similar and the raid is in sync.
I guess it is related to some misconfiguration or snapraid issue.
Would be great to know how to investigate this problem further.
Answer: With help from the guys in the SnapRaid-Forums I could identify the problem:
It looks like SnapRaid runs into major problems when hitting an I/O error while the first sync is done. From that point all blocks on parity have been jammed.
For everyone hitting this issue here I will provide some info how I could solve it:
Check 100 blocks from offset 11242042 to get the kind of error:
<code>$ snapraid -S 11242042 -B 100 check

100% completed, 105 MB accessed in 0:00

100 errors
  0 unrecoverable errors
WARNING! There are errors!
</code>
Ok, seems like everything is recoverable.
Check how much data is affected:
<code>$ snapraid status

[...]
No sync is in progress.
The 100% of the array is not scrubbed.
You have 164 files with zero sub-second timestamp.
Run the 'touch' command to set it to a not zero value.
No rehash is in progress or needed.
DANGER! In the array there are 7926625 errors!

They are from block 7107252 to 15055004, specifically at blocks: 7107252 [...]
</code>
Ok, to me it was quite a lot... so force a resync from before the first affected block of the parity disk:
<code>$ snapraid fix -d parity -S 7000000
</code>
Alternativly fix already detected bad blocks only:
<code>$ snapraid fix -d parity -e
</code>
If you have mostly everything broken I recommend:
<code>$ snapraid --force-full sync
</code>
It took a couple of hours, but now SnapRaid is happy again.
Comment: Thanks for leaving your solution. Needed this info.
Too many questions on here where people don't return when they find out an answer


How can I route all calls starting with string api to their handlers in an express middleware

Question: I have a express app.js with typical
app.get('/path1', (req, res => {})
app.get('/path2', (req, res => {})
app.get('/path3', (req, res => {})

now I want to catch all routes, starting with api such as below and redirect them to their corresponding handler in express but not sure how to achieve that
/api/path1
/api/path2
/api/path3

I' assuming i can have a catch all api as below
app.all('/api/*', function (request, response, next) { //in a server.js file
       //how can i call the corresponding paths here??
       // looking for something to do forward to current-route.replace('api','')
       // or something like that
})

Answer: Maybe a router-level middleware could solve your problem:
const router = express.Router();

router.get('/path1', (req, res => {});
router.get('/path2', (req, res => {});
router.get('/path3', (req, res => {});

app.use('/api', router);

Update:
Use redirect (not that much of a difference to your current solution; not tested):
app.all('/api/*', (request, response) => res.redirect(request.url.replace('/api', '')));

Comment: actually yes,  I can use this in combination with app router! thank you
Comment: sorry maybe i should had been more clear, trying to run both express and react from the same port and wanted to send non api calls to  res.sendFile(path.join(__dirname, 'build', 'index.html'))
Answer: this worked for me, please let me know if there is a better way
app.all('/api/*', function (request, response, next) {
    request.url = request.url.replace('/api','');
    next();
})


Can I apply a Cochran-Armitage test (chi-squared linear trend test) to compare two categories of data?

Question: I have a problem where I am trying to determine whether there is statistical significance from two groups of data.
I have two columns which show the frequency of visits to their personal trainer based on receiving notifications about their fitness.

Score
BEFORE
AFTER

severe
3
28
78

elevated
2
262
346

moderate
1
1344
1523

low requirement
0
2311
2400

There are different notification severity categories labelled as "severe", "elevated", "moderate" and "low requirement". The "before" period is the baseline with "suppressed" notifications, which means that we the investigators are the only ones that know of the notification status during this time. There is an "after" period where now people are receiving these notifications.
I want to see whether the notifications had an impact on the frequency of visits to their personal trainers.
I've come across the Cochran-Armitage test for trend (chi-squared test for linear trend) and am wondering whether this would be appropriate?
Answer: I don't see the need to use a chi-square test (or the one for trend,aka CA test), because you have a categorical variable and a numerical variable as I see (number of visits or number of people, not sure!), and since it's a before and after protocol, I think a paired t-test is more suitable for this (if the normality is not violated of course, otherwise use wilcoxon test)


Select image from grid view and show it in next activity and in this activity there are buttons to capture image and also to save it

Question: I am showing images from my gridview.
When an image is selected it is shown in new activity.
In new activity there is 2 buttons one to capture image and one to save it along with the image chosen from gridview.
My problem is that when I select image from gridview then the buttons in the next activity do not respond.And when they respond then chosen image from gridview is not shown.
Capture image and save buttons logic is in different class.
I am trying to call these by intent.
this is my code where the problem is,when i am using two intent then also only is working.
          public class SingleItemView extends Activity {
           //final static int CAMERA_RESULT = 0;
          ImageView imv;    private int TAKENPHOTO = 0;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    // Get the view from singleitemview.xml
    setContentView(R.layout.singleitemview);

    // Get position from intent passed from MainActivity.java
    Intent i = getIntent();
    //startActivityForResult(i, 1);

    int position = i.getExtras().getInt("id");

    // Open the Image adapter
    ImageAdapter imageAdapter = new ImageAdapter(this);

    // Locate the ImageView in singleitemview.xml
    ImageView imageView = (ImageView) findViewById(R.id.image);

    // Get image and position from ImageAdapter.java and set into ImageView

    imageView.setImageResource(imageAdapter.mThumbIds[position]);
    //i = new Intent(SingleItemView.this, saveandshare.class);
//  startActivityForResult(i, 1);
    //Intent openNewActivity = new Intent(getApplicationContext(), saveandshare.class);
//  startActivity(openNewActivity);

}

    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    if (resultCode == RESULT_OK) {
            Bundle extras = intent.getExtras();
            Bitmap bmp = (Bitmap) extras.get("data");
        imv = (ImageView) findViewById(R.id.imageView);
    imv.setImageBitmap(bmp);

    }

}

Answer: Hi please try below code , hope it will help you
write below code into your item click listener of gridView
Intent intent = new Intent(m_context, SecondActivity.class);
intent.putExtra("ImagePath", "Your Image path(either it is url or uri)");
startActivity(intent);

Write below code in your second activity
if(getIntent().getExtras() != null)
{
    String path;
    path = getIntent().getExtras().getString("ImagePath");
}

Write below code in your button click for pick image from gallery
And use Universalimageloader library for loading image
Intent m_galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(m_galleryIntent, 200);

  @Override
    protected void onActivityResult(int p_requestCode, int p_resultCode, Intent p_data)
    {
        if(p_requestCode == 200 && p_resultCode == RESULT_OK)
        {
            try
            {
                Uri m_selectedImageUri = p_data.getData();
                m_userSelectedImagePath = getPath(m_selectedImageUri);
                if(m_userSelectedImagePath.toString().startsWith("http"))
                {
                    m_loader.displayImage(m_userSelectedImagePath, m_ivScenarioImage);
                }
                else
                {
                    m_loader.displayImage("file://" + m_userSelectedImagePath, m_ivScenarioImage, m_options);
                }

            }
            catch(Exception m_e)
            {

            }
        }
    }

Use below function for store media
private File getOutputMediaFile()
    {

        File m_mediaFile;

            m_builder = new StringBuilder();
            m_builder.append(Constant.m_mediaDirectoryPath).append(Constant.IMAGE_DIRECTORY_NAME);
            File m_imageStorageFile = new File(m_builder.toString());

            // Create the storage directory if it does not exist
            if(! m_imageStorageFile.exists())
            {
                if(! m_imageStorageFile.mkdirs())
                {
                    return null;
                }
            }
            // Create a media file name
            String m_timeStamp = new SimpleDateFormat(Constant.TIME_STAMP_FORMAT, Locale.getDefault()).format(new java.util.Date());
            m_builder = new StringBuilder();
            m_builder.append(m_imageStorageFile.getPath()).append(File.separator).append("IMG_").append(m_timeStamp).append(".jpg");
            m_mediaFile = new File(m_builder.toString());

        return m_mediaFile;
    }

after above function you have to write below code in your save image button click
try
    {
       String saveImagePath;
        saveImagePath = getOutputMediaFile().getPath();
        m_bitmap = CommonUtills.getImageBitmap(m_context, m_userSelectedImagePath, 500, 500);
        ByteArrayOutputStream m_out = new ByteArrayOutputStream();
        if(m_bitmap != null)
        {
                 m_ivScenarioImage.setImageBitmap(m_bitmap);
        }
    }
    catch(Throwable m_e)
    {

    }

     public static Bitmap getImageBitmap(Context p_context,String p_filePath, int p_width, int p_height)
    {
        try
        {
            ExifInterface m_exif = new ExifInterface(p_filePath);
            int m_rotation = m_exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

            Matrix m_localMatrix = new Matrix();

            if(m_rotation == ExifInterface.ORIENTATION_ROTATE_90)
                m_localMatrix.postRotate(90);
            else if(m_rotation == ExifInterface.ORIENTATION_ROTATE_180)
                m_localMatrix.postRotate(180);
            else if(m_rotation == ExifInterface.ORIENTATION_ROTATE_270)
                m_localMatrix.postRotate(270);
            else
                m_localMatrix.postRotate(0);

         //   Bitmap  m_retBmp = decodeFile(p_context, p_filePath,p_width,p_height);
           // Bitmap m_retBmp = ImageHelper.scaleImage(p_filePath, p_width, p_height);
          //  Bitmap m_retBmp =  CommonUtills.decodeFile(p_context, p_filePath, p_width, p_height);
            Bitmap m_retBmp =  CommonUtills.scaleImage(p_context,p_filePath,p_width,p_height);

            return Bitmap.createBitmap(m_retBmp, 0, 0, m_retBmp.getWidth(), m_retBmp.getHeight(), m_localMatrix, true);
        }
        catch(Throwable p_e)
        {

        }
        return null;
    }

     public static Bitmap scaleImage(Context p_context, String p_path, int p_reqHeight, int p_reqWidth)
    {
        Bitmap m_retBmp = null;
        try
        {
            System.gc();
            File m_file = new File(p_path);

            if (m_file.exists())
            {
                BitmapFactory.Options m_o2 = new BitmapFactory.Options();
                m_o2.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(m_file.getPath(), m_o2);

                m_o2.inSampleSize = calculateInSampleSize(m_o2, p_reqHeight, p_reqWidth);

                m_o2.inJustDecodeBounds = false;
                m_retBmp = BitmapFactory.decodeFile(m_file.getPath(), m_o2);
            }
        }
        catch (Exception p_e)
        {

        }

        return m_retBmp;
    }

     private static int calculateInSampleSize(BitmapFactory.Options p_options, int p_reqWidth, int p_reqHeight)
    {
        // Raw height and width of image
        final int m_height = p_options.outHeight;
        final int m_width = p_options.outWidth;
        int m_inSampleSize = 1;

        if (m_height > p_reqHeight || m_width > p_reqWidth)
        {

            final int m_halfHeight = m_height / 2;
            final int m_halfWidth = m_width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((m_halfHeight / m_inSampleSize) > p_reqHeight && (m_halfWidth / m_inSampleSize) > p_reqWidth)
            {
                m_inSampleSize *= 2;
            }
        }
        return m_inSampleSize;
    }

Comment: Still seeing the capture image not the selected image from galley.I want to see both the images.
Comment: i have sent you code for store capture image also . Use getOutputMediaFile function . its working fine


When does the MLE of the Logistic Distribution exist and when is it unique?

Question: I am trying to understand the procedure for finding the MLE of the parameter $\theta$ of a Logistic Distribution. The book I am reading has the following derivation:
I am having trouble understanding how the book's analysis shows that MLE exists and is unique (which is discussed in the last paragraph). The book I am reading has not discussed any theorems on either the existence or the uniqueness of MLEs. Is the last paragraph implicitly based on any theorems? In general, how does one know (and verify) that the MLE of a certain parameter of a certain distribution exists and if is exists, that the MLE is unique? Any help is greatly appreciated!
Comment: The second derivative of the log likelihood is strictly negative, hence the log likelihood is concave and therefore has a unique maximum.
Comment: You can see this by applying his reasoning to 6 1 9 instead. Take the derivative of that. Now you have 1 minus the term in the sum. But this term is bounded above one, hence the second derivative is negative.
Comment: This is a standard analysis based on differential Calculus -- it's not special to MLE.  A good intro Calc text will cover every concept and technique used in this quotation.
Answer: As the Equation 6.1.10 can be likely solved by an iterative numerical method (like Newton-Raphson) using the first derivative and successive point approximations. See this source for operational and convergence details.
The operational question is there a point in the realm of real numbers where the denominator of the first derivative goes to zero. The answer is no.
To demonstrate, if we did set the denominator equal to zero, take the square-root of both sides, and look for solutions indicating a possible singularity:
$ 1 + exp( -(x_i - \theta )) = 0 $
Or:
$ exp( -(x_i - \theta )) = -1 $
Or:
$ -(x_i - \theta ) = log(-1) $
To investigate a solution, I start with some background courtesy of Wikipedia, to quote:

For example, ln(i) = πi/2  or 5πi/2 or -3πi/2, etc.;

So, upon multiplying both sides of the first representation by two, I can successively develop an equivalence:
$2 \log(i) = log(i^2) = log(-1) = πi $
where my log function is more precisely defined as the natural log extended to the realm of complex numbers. Side note, I could have also used in place of πi/2 the value -πi/2, in which case the answer is also -πi.
Now, going back to our denominator set equal to zero, a singularity could theoretically arise when $\theta\ - x_i$ equals πi. However, this would imply either $\theta\ $ or $ x_i$ lie in the complex plane. which they do not.


Configure DNS to forward email to google

Question: I'm trying to reconfigure a bind record on an Ubuntu 9.04 server so that email is redirected out to gmail  My existing records look like this (not the real ip)

; MX Records
@   IN  MX  10  mail

; Address Records
@   IN  A   126.96.36.199
www IN  A   220.127.116.11
ftp IN  A   188.8.131.52
mail    IN  A   18.104.22.168

Am I correct in thinking that the change that is needed is simply

; MX Records
@       IN      MX      10      mail

; Address Records
@   IN  A   188.8.131.52
www IN  A   22.214.171.124
ftp IN  A   18.104.22.168
mail    IN      CNAME   ghs.google.com

I'm making the changes to the db file held in /var/cache/bind and subsequently going to restart bind to apply them.  Is this sufficient?
Answer: You probably want something like this. (see link)
<code>    IN  MX  1   ASPMX.L.GOOGLE.COM.
    IN  MX  5   ALT1.ASPMX.L.GOOGLE.COM.
    IN  MX  5   ALT2.ASPMX.L.GOOGLE.COM.
    IN  MX  10  ASPMX2.GOOGLEMAIL.COM.
    IN  MX  10  ASPMX3.GOOGLEMAIL.COM.
    IN  MX  10  ASPMX4.GOOGLEMAIL.COM.
    IN  MX  10  ASPMX5.GOOGLEMAIL.COM.
</code>
Make sure you add that trailing period.
Comment: I ALWAYS forget the trailing period on FQDN, and the silly DNS server NEVER does what I want until I go back and put the Period in:-)
Answer: From Google: Configuring Your MX Records: Other domain hosts
http://www.google.com/support/a/bin/answer.py?answer=33915
Answer: You cannot reference a CNAME record in your MX record. You will need to obtain the correct MX entry from Google.


prove problem if $m^2 | n^2, \text{then } m|n$

Question:
Prove that if $m^2 | n^2, \text{then } m|n$
if $m^2 | n^3, \text{then } m|n$? prove or disprove.

i really no idea of that, someone could help me?
Comment: For $2$, set $m = 8$ and $n = 4$.
Comment: Do you know the fundamental theorem of arithmetic, that every integer $n>1$ has a unique factorization as a product of primes?
Comment: @ulead86: Indeed it is, and that question has a couple of excellent answers, one using the fundamental theorem and the other avoiding it.
Comment: Or as addition to Andrew $m=a^3$, $n=a^2$ is for every $a>1$ a counterexample
Answer: For 1. there are a lot of proofs. This one is my Favorite
$$m^2|n^2 \implies  k = \frac{m^2}{n^2} = \left(\frac{m}{n}\right)^2 $$
But because only Integers have Integer roots, $\frac{m}{n}$ must be an Integer.
For 2. Let $a$ be an Integer greater than 1. set $m=a^3$ and $n=a^2$. We see
$m^2 = a^6 = n^3$ so $m^3| n^2$ but $a^3$ is not a divisor of $a^2.$


How can i create a point to point connection?

Question: We have a measurement campaign in a field, until now we had the following network structure

The distance was 400m between the two points so the most easy solution was to use a Wifi pont to point bridge connection. The PC with the 192.168.0.10 IP act as a server, and run a software which controls the other PC. In this network structure all PC had the same subnet and it was easy to establish TCP/UDP(Broadcasting, unicasting) connections.
From now on the distance between the two point is 20km, so the wifi solution is not working any more. In this case we have the following network structure:

My question is how can I establish a point to point connection through internet, to get the same structure as in the first image? For example where I still can broadcast and unicast through UDP etc.
Edited
I know only the VPN server IP, so from the PC with the 13x.xxx.xxx.xxx IP can connect to the VPN server, therefore that PC will be in the same subnet(192.168.1.0/24).
For example, there will be eth0 with 13x.xxx.xxx.xxx IP and tun0 with 192.168.1.22, in this case can I run a VPNServer on that PC so the PC with the 192.168.1.21 IP can establish a VPN Bridge connection?
Comment: setup a site to site vpn ?
Comment: Um, what?  You don't have access to the VPN server... so your job would be, what, exactly?
Comment: It looks like what you want is to set your VPN for layer 2 bridging... except that your VPN server is in a different network entirely (192.168.1.x).
Comment: I don't have access to the VPN server, so I can't modify the settings,but I can connect to this VPN server
Comment: Yes, because this is an university network, they are providing only the access to the VPN server.
Comment: I've never dealt with anything like this but you should be able to set up your own pair of VPN servers supporting layer 2 bridging and NAT-Traversal in 192.168.0.x, and having your VPN traffic go over the university's VPN.  You'll have to deal with small MTU (each encapsulation reduces the amount of data that can go in a packet) and the university's VPN may not accept non-TCPIP traffic, but I think it may be possible if you control 192.168.0.10 and 192.168.0.20.
Answer: You should get site 2 a permanent, reliable internet connection and use a permanent site to site VPN. You'll need a router each side capable of doing so, though.


Como criar "layouts responsivos" no Android?

Question: Estou com dúvida de como criar um "Layout" responsivo para que sirva em todos os dispositivos smarts e tablets, para que o tamanho de textos, botões se adapte adequadamente para cada tela, qual a melhor maneira e prática para isto?
Aproveitando sobre o assunto, dando um exemplo referente ao framework javascript METEOR, nele você pode separar as "tags" html's por templates para não ficar o código grande e cada template ou .html você separa por pastas, é possivel fazer algo assim no Android?
Comment: Nada melhor do que ler a documentação: [Compatibilidade com várias telas](https://developer.android.com/guide/practices/screens_support.html), [Suporte para diferentes tamanhos de tela](https://developer.android.com/training/multiscreen/screensizes.html) e [Como projetar para várias telas](https://developer.android.com/training/multiscreen/index.html)
Answer: Não creio que de para trabalhar como o Meteor no esquema no Android, mas o Android tem layouts que podem ser usados por include, por exemplo:
Seu Layout principal:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/app_bg"
    android:gravity="center_horizontal">

    <include android:id="@+id/news_title"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             layout="@layout/title" />

    <TextView android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:text="@string/hello"
              android:padding="10dp" />
</LinearLayout>

Seu layout reusável/reaproveitável:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/titlebar_bg">

    <ImageView android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:src="@drawable/gafricalogo" />
</FrameLayout>

Leia sobre em:

https://developer.android.com/training/improving-layouts/reusing-layouts.html
https://developer.android.com/training/improving-layouts/loading-ondemand.html

Existem também os Fragments, mas eles são um caso bem especifico https://developer.android.com/guide/components/fragments.html
Sobre a "Reponsividade"
Basicamente você terá que criar um Layout para cada tamanho, isto não é necessariamente "responsivo", mas funciona bem, você pode criar um layout para cada tela assim:
res/layout/my_layout.xml              // telas normais (por defeito/por padrão)
res/layout-large/my_layout.xml        // telas largas
res/layout-xlarge/my_layout.xml       // telas muito largas
res/layout-xlarge-land/my_layout.xml  // telas muito largas e em landscape

Mais detalhes em: https://developer.android.com/guide/practices/screens_support.html
Ou você pode tentar a dica desta resposta no SOen, se precisar fazer algo com tamanhos customizados que você deseja, um exemplo se a tela for maior que 600:
Configuration config = getResources().getConfiguration();

if (config.smallestScreenWidthDp >= 600) {
    setContentView(R.layout.main_activity_tablet); //activity para tablets
} else {
    setContentView(R.layout.main_activity); //activity normal
}

WebView como aplicativo
Existe também a possibilidade usar WebView parar criar um WebApp, mas realmente nem sempre compensa (vai depender muito do caso), todavia se desejar usar o Meteor, Bootstrap e afins pode tentar esta resposta:

https://pt.stackoverflow.com/a/50679/3635


How to plot unix timestam

Question: I have a time serie determined by sec.nsec (unix time?) where a signal is either 0 or 1 and I want to plot it to have a square signal. Currently I have the following code:
from matplotlib.pyplot import *

time = ['1633093403.754783918', '1633093403.755350983', '1633093403.760918965', '1633093403.761298577', '1633093403.761340378', '1633093403.761907443']
data = [1, 0, 1, 0, 1, 0]

plot(time, data)
show()

This plots:

Is there any conversion needed for the time before plotting? I cannot have date:time as this points might have ns to ms between them
Thank you.
EDIT: The values of the list for time are strings
Comment: adding `drawstyle='steps-pre'` to plot worked. However, is that the correct way to plot it?
Comment: `date = np.datetime64(time, 's')` should give you numpy datetime64 array and Matplotlib should give you better looking ticks.  If you don't care about dates, then you could also just subtract the start of the day or hour or something.
Comment: The thing is that I am not getting the time from a python script but plotting from a file. However, just to test your suggestion, I tried `date = np.datetime64(time[0], 's')` but that throw the error `Could not convert object to NumPy datetime`. Still, using `drawstyle='steps-pre'` worked
Comment: Sorry, you need to convert to int before passing to datetime64.  So maybe: `date = np.datetime64(int(1e6*time[0]), 'us')`
Comment: I've just edited the question. The list `time` is composed by strings (sec.nsec). What I am thinking is that I should convert the sec and nsec individually to int, then convert the sec to nsec and and those two numbers together....
Answer: To convert unix timestamp strings to datetime64 you need to fist convert to float, and then convert to datetime64 with the correct units:
time = ['1633093403.754783918', '1633093403.755350983', '1633093403.760918965', '1633093403.761298577', '1633093403.761340378', '1633093403.761907443']
time = (np.asarray(time).astype(float)).astype('datetime64[s]')
print(time.dtype)
print(time)

yields:
datetime64[s]
['2021-10-01T13:03:23' '2021-10-01T13:03:23' '2021-10-01T13:03:23'

Note the nanoseconds have been stripped.  If you want to keep those...
time = (np.asarray(time).astype(float)*1e9).astype('datetime64[ns]')

yields:
datetime64[ns]
['2021-10-01T13:03:23.754783744' '2021-10-01T13:03:23.755351040'
 '2021-10-01T13:03:23.760918784' '2021-10-01T13:03:23.761298688'
 '2021-10-01T13:03:23.761340416' '2021-10-01T13:03:23.761907456']

This all works because datetime64 has the same "epoch" or zero as unix timestamps (1970-01-01T00:00:00.000000)
Once you do this conversion, plotting should work fine.

How to plot unix timestam


Legibilidade de códigos javascript

Question: Ao escrever um código você deve fazê-lo de modo que o tempo necessário para sua compreensão seja mínimo. Essa é a métrica mais importante para se ter um código legível e é o fundamento do teorema fundamental da legibilidade.
Quanto maior o tempo gasto, menor é a legibilidade do seu código, e isso é um sinal de que ele precisa de melhorias a nível de legibilidade. Um código ilegível hoje, pode ser a sua perda de produtividade no futuro. O que você faz hoje, com total compreensão, daqui uns 2 anos quando precisar fazer uma manutenção, pode ser ilegível até para você mesmo, e isso fará com que você gaste um tempo precioso tentando entender aquilo que você mesmo escreveu.

Então, quais seriam as formas interessantes de aplicar esse teorema e medir o nível de legibilidade do código?

Não é desejável que as respostas a esta pergunta sejam baseadas em opiniões mas sim em fatos, referências ou experiência específica.
Comment: devo entender que o voto negativo diz que não é necessário se preocupar com legibilidade, qualquer porcaria escrita de qualquer forma está bom, desde que funcione
Comment: Não fui eu que votei negativo, mas suponho que quem quer que seja tenha simplesmente entendido que a pergunta é ampla demais. De fato, "legibilidade" é um conceito nebuloso, e um bom estilo em uma linguagem pode ser um estilo ruim em outra. Aliás, pode variar de projeto para projeto. E a linha que separa "opiniões" de "experiência específica" é tênue...
Comment: A pergunta vale para qualquer linguagem e a resposta vai ser a mesma. Agora, para evitar dar tiros no pé com Javascript, eu recomendo o livro *Javascript: the good parts*.
Comment: Eu escrevi um artigo há algumas semanas para um blog onde descrevo algumas práticas para deixar um código autodocumentado. Segue o link: http://www.sigaonerd.com/2017/06/vba-artigo-034-deixando-o-codigo.html

Espero que o artigo ajude a responder sua questão. O melhor mesmo é ler o livro que coloquei como referência no final do artigo.
Comment: Relacionadas: [O que torna um código fonte um código de fácil manutenção?](https://pt.stackoverflow.com/q/186346/91) e [O que é "expressão idiomática" na programação?](https://pt.stackoverflow.com/q/184238/91)
Answer: Existe um livro que é algo como a Bíblia Sagrada sobre esse assunto. Eu já o tomei por verdade sacrossanta e enxergo qualquer desvio de seus ensinamentos como heresia.
Meu evangelho se chama Código Limpo - Habilidades Práticas Do Agile Software,
e foi escrito por São Roberto Martinho (do original em Inglês, Robert C. Martin). Seguem duas gravuras que são a codificação que recebemos da doutrina.
A métrica canônica para medida de bom código:

E o caminho da verdade e da justiça para a escrita de bom código:

Todo o resto são só diferentes interpretações mais ou menos ortodoxas da verdade.
Answer: Tive um pouco de dificuldade de entender a imagem postada pelo nosso amigo Renan. Depois de um bom tempo digitando cada trecho no Google Tradutor, me ocorreu a ideia de postar aqui a imagem com os trechos em português para facilitar o entendimento da mesma por parte da comunidade que não entende inglês assim como eu.

The whole rest is different alone interpretations more or less orthodox of the truth   :)

Legibilidade de códigos javascript


Decrement cells when records are deleted

Question: So I have a simple MySQL table (block) as such:
SELECT * FROM `block` WHERE 1 ORDER BY `year`, `month`, `day`, `block`;

id      year    month day block te status
20000   2015    12  28  1   100000  1
20001   2015    12  28  2   100000  1
20002   2015    12  28  3   100001  1
20003   2015    12  28  4   100001  1
20004   2015    12  29  1   100001  1
20005   2015    12  29  2   100001  1
20006   2015    12  29  3   100002  1
20066   2015    12  30  1   100003  1
20078   2015    12  30  1   100007  1
20070   2015    12  30  1   100004  1
20067   2015    12  30  2   100003  1
20071   2015    12  30  2   100004  1
20079   2015    12  30  2   100007  1
20072   2015    12  30  3   100004  1
20080   2015    12  30  3   100007  1
20068   2015    12  30  3   100003  1
20069   2015    12  30  4   100003  1
20073   2015    12  30  4   100004  1
20074   2015    12  31  1   100004  1
20075   2015    12  31  1   100000  1
20076   2015    12  31  2   100000  1
20077   2015    12  31  3   100000  1
20007   2016    1   1   1   100017  1
20008   2016    1   1   2   100017  1
20009   2016    1   1   3   100017  1

My question is, how can I shift all the remaining rows up if I delete a contiguous section of rows?
For example, if I delete all blocks for 2015-12-28, I want all the remaining blocks to decrement to occupy the unused blocks on the schedule.
Let me know if this is confusing or unclear. Thanks.
Comment: Any table's primary key is not supposed to change. In your case, you want to change the same.
Comment: you want to update your block value on deleting the records correct ??
Comment: I don't want to change the primary key (id). I want to update `year`, `month`, `day`, and `block` for all remaining rows when a chunk is taken out of the middle.
Comment: I realize this probably can't be done solely with MySQL. Perhaps a PHP routine would be better. Maybe I need to do like a strtotime() and do some date math?
Comment: Just to give us an impression, WHY do you want your ids to be continuous? Do you want to order your data by ids? Then there are better ways to do so.
Answer: I think a bit more background is required. What is your eventual goal?
Two options...
First Option
Check out the link below on numbering rows in MySQL. You can use something like this to make your blocks dynamic.
http://www.xaprb.com/blog/2006/12/02/how-to-number-rows-in-mysql/
Second Option
If you are pulling data by day, just pull the data in order of the id and you can just assume that the blocks are in order in whatever application you use the data in.
Answer:
For example, if I delete all blocks for 2015-12-28, I want all the remaining blocks to decrement to occupy the unused blocks on the schedule.

You do not actually specify what decrementing means. I think you want to shift the dates in all the blocks. But look here:
20000   2015    12  28  1   100000  1
20001   2015    12  28  2   100000  1
20002   2015    12  28  3   100001  1
20003   2015    12  28  4   100001  1

20004   2015    12  29  1   100001  1
20005   2015    12  29  2   100001  1
20006   2015    12  29  3   100002  1
20066   2015    12  30  1   100003  1

We have four blocks for 2015-12-28 and three for 2015-12-29. Say we delete the four 28's. What happens? Do three of the 29's shift to 28's, and the 30 become 29? Or do the three 29's and the 30 shift to fill the four places left by the 28's?
Depending on the strategy you need to choose different strategies. Perhaps you should define what exactly a block is, and what data is outside a "block", and supply a couple examples of a shift (with different numbers of days - e.g., 28 28 29 30 and you delete the two 28. BTW, can you delete only one? If so, what would happen then?).
Say each date can hold a fixed number of records
For example you can first count how many rows you're going to delete
SELECT COUNT(*) FROM ... WHERE day=28 AND month=12 AND year=2015

and then select the next items that have a later date. You then shift them, but you need to do this iteratively (once the 29's are gone, the 30's will shift, and so on). This may become quite expensive to calculate.
But in this case you might separate the date from the data:
TableA
2015 12 28
2015 12 28
2015 12 28

TableB
20000 100000 1
20001 100000 1

Now you need to join the tables in such a way that you can... well, join them. Whatever their cardinality. You might have a longer TableA than TableB, or vice versa.
This would be pretty easy in some RDBMS. In MySQL it's pretty awful (you can't even use CREATE VIEW to simplify the syntax because you'd need either a variable or a subquery in the view), and for small data sets you'd be better off by selecting TableA, then selecting TableB, and using a cycle in PHP:
// Run the query from tableA to get the dates
$TableADataSet = array();
while ($tuple = SQLFetch($rs)) {
    $TableADataSet = $tuple;
}

// Run the query from tableB to get the rest
$TableBDataSet = array();
while ($tuple = SQLFetch($rs)) {
    $TableBDataSet = $tuple;
}

// Now put them together.

for (;;) {
    if (empty($TableADataSet)) {
        if (empty($TableBDataSet)) {
            break;
        }
        $TupleA = $EmptyRowFormattedAsTableA;
        $TupleB = array_pop($TableBDataSet);
    } else {
        $TupleA = array_pop($TableADataSet);
        if (empty($TableBDataSet)) {
            $TupleB = $EmptyRowFormattedAsTableB;
        } else {
            $TupleB = array_pop($TableBDataSet);
        }
    }
    // Now you have a row with dates and data "aligned".
    // Missing data are taken by the sample rows EmptyRowFormattedAs... .
}

The result could be (simplifying)
2015 12   28      RowA
2015 12   28      RowB
2015 12   29      RowC
NULL NULL NULL    RowD

and if you delete RowB, the rightmost part of the rows shifts upwards:
2015 12 28 RowA
2015 12 28 RowC
2015 12 29 RowD

In MySQL you first need to number the rows, and you have no RECNO() or ROW_NUMBER() function, so you do it like
SELECT @a:=@a+1 AS ranka,data1.* FROM ( SELECT * FROM TableA ORDER BY year, month, day ) AS data1, (SELECT @a:=0) AS init1;

and get your dates with a row number.
1   2015 12 28
2   2015 12 28
3   2015 12 29

You do the same for TableB. But now you have to do the "horizontal join" trick. We can be in one of these three cases:
B is longer     A is longer    Same length
A B             A B            A B
A B             A B            A B
- B             A -            A B

The "A B" part we can get with a JOIN. The "A -" part we get with a LEFT JOIN with a WHERE TableB.primarykey IS NULL. The "- B" part we get with a RIGHT JOIN WHERE TableA.primarykey IS NULL. Finally we put it all together with a UNION. And these three queries will need to be made with the awkward syntax above.
The (quite convoluted) query coming out of all this is
SELECT * FROM
    ( SELECT @a:=@a+1 AS rank1a, data1.*
        FROM ( SELECT * FROM TableA ORDER BY year, month, day ) AS data1,
        (SELECT @a:=0) AS init1
    ) AS ta
JOIN
    ( SELECT @b:=@b+1 AS rank1b, data2.*
        FROM ( SELECT * FROM TableB ORDER BY something ) AS data2,
        (SELECT @b:=0) AS init2 )
    ) AS tb
ON (rank1a = rank1b)

UNION

SELECT * FROM
    ( SELECT @c:=@c+1 AS rank2a, data3.*
        FROM ( SELECT * FROM TableA ORDER BY year, month, day ) AS data3,
        (SELECT @c:=0) AS init3
    ) AS tc
LEFT JOIN
    ( SELECT @d:=@d+1 AS rank2b, data4.*
        FROM ( SELECT * FROM TableB ORDER BY something ) AS data4,
        (SELECT @d:=0) AS init4 )
    ) AS td
ON (rank2a = rank2b) WHERE ( rank2b IS NULL )

UNION

SELECT * FROM
    ( SELECT @e:=@e+1 AS rank3a, data5.*
        FROM ( SELECT * FROM TableA ORDER BY year, month, day ) AS data5,
        (SELECT @e:=0) AS init5
    ) AS te
LEFT JOIN
    ( SELECT @f:=@f+1 AS rank3b, data6.*
        FROM ( SELECT * FROM TableB ORDER BY something ) AS data6,
        (SELECT @f:=0) AS init6 )
    ) AS tf
ON (rank3a = rank3b) WHERE ( rank3a IS NULL )

which, from a performance point of view, is probably a hog.


How do I animate tintColor to gray on a custom-drawn control when a sheet/alert is shown in iOS 7?

Question: In iOS 7, when a UIActionSheet is presented, the system controls all animate their tintColor to gray. When the sheet is dismissed, they animate back.
I have some controls with custom background images or drawRect implementations that use the tint color, and I'd like them to animate that change just like the system controls.
Apple added - (void)tintColorDidChange to UIView, but redrawing with the new color in this method doesn't animate the change — it just switches from full color to full gray immediately, which looks bad when other system controls around it are animating.
How can I make my custom-drawn controls animate the tintColor transition like Apple's?
Answer: You can do this with a Core Animation transition applied to the view layer:
//set up transition
CATransition *transition = [CATransition animation];
transition.type = kCATransitionFade;
transition.duration = 0.4;
[self.layer addAnimation:transition forKey:nil];

//now trigger a redraw of the background using the new colour
//and the transition will cover the redraw with a crossfade
self.flagToIndicateColorShouldChange = YES;
[self setNeedsDisplay];

EDIT: there may be a race condition between the animation and the redraw depending on exactly how you do the redraw. If you can post the original redraw code you tried that updated immediately (without animation) I can provide a more specific answer.
Comment: I don't believe there is a constant for it. The default CoreAnimation or UIView animation duration is 0.25 seconds, but often Apple use longer durations like 0.3 or 0.33 so you'll probably just have to experiment to see what looks right.
Comment: This actually works without the bottom two lines if called directly from `tintColorDidChange`. For the sake of correctness, any idea if the duration of a UIActionSheet presentation is a constant defined somewhere officially?
Comment: Looks like 0.25 is it, at least as of iOS 7.0.3. Thanks again.
Answer: Have you tried tintAdjustmentMode?
You should watch WWDC 2013 Session 214 Customizing Your App's Appearance for iOS 7 and read the TicTacToe demo app
Something like this
- (void)onPopupOpened
{
    [UIView animateWithDuration:0.3 animations:^{
        window.tintAdjustmentMode = UIViewTintAdjustmentModeDimmed;
    }];

    popupView.tintAdjustmentMode = UIViewTintAdjustmentModeNormal;
    popupView.tintColor = [UIColor redColor];
}

- (void)onPopupClosed
{
    [UIView animateWithDuration:0.3 animations:^{
        window.tintAdjustmentMode = UIViewTintAdjustmentModeAutomatic;
    }];
}

Answer: Shouldn't drawRect: be called automatically for the animation to update for the new tintColor?
I've made a demo application that has three controls in the main view controller. The first is a button that brings up a standard action sheet. The second is a button that's there for observation (the tapped button is hard to compare to during the animation). The third is a custom UIView subclass that simply draws a rectangle of the view's tintColor. When tintColorDidChange is called, I call setNeedsDisplay, which in turn will call drawRect:.
I created a new application with one view controller:
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [[UIApplication sharedApplication] keyWindow].tintColor = [UIColor blueColor];

    // Button to bring up action sheet
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = (CGRect){10,30,300,44};
    [button setTitle:@"Present Action Sheet" forState:UIControlStateNormal];
    [button addTarget:self
               action:@selector(didTapPresentActionSheetButton:)
     forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];

    // Another button for demonstration
    UIButton *anotherButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    anotherButton.frame = (CGRect){10,90,300,44};
    [anotherButton setTitle:@"Another Button" forState:UIControlStateNormal];
    [self.view addSubview:anotherButton];

    // Custom view with tintColor
    TESTCustomView *customView = [[TESTCustomView alloc] initWithFrame:(CGRect){10,150,300,44}];
    [self.view addSubview:customView];
}

- (void)didTapPresentActionSheetButton:(id)sender
{
    UIActionSheet *as = [[UIActionSheet alloc] initWithTitle:@"Action Sheet"
                                                    delegate:nil
                                           cancelButtonTitle:@"Cancel"
                                      destructiveButtonTitle:@"Delete"
                                           otherButtonTitles:@"Other", nil];
    [as showInView:self.view];
}

where TESTCustomView is a UIView subclass with implementation as follows:
- (void)drawRect:(CGRect)rect
{
    NSLog(@"Drawing with tintColor: %@", self.tintColor);

    // Drawing code
    [super drawRect:rect];

    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(c, self.tintColor.CGColor);
    CGContextFillRect(c, rect);
}

- (void)tintColorDidChange
{
    [self setNeedsDisplay];
}

Running this application in the simulator shows that the custom view's tintColor is automatically animated with the standard UIButton instances in the view controller.


Can't understand integration-through-symmetry argument

Question: In a previous question of mine, I asked how the volume of the region
$$xy>zw \quad\wedge \quad x>-y$$
bounded by the unit $4$-ball (so $x^2+y^2+z^2+w^2<1$) could be calculated.
The answer to my question implied that the answer ($1/4$ the volume of the unit $4$-ball) could easily be seen through symmetry, but I never really understood the arguments, hence this question.
I'd really appreciate either a new perspective on this, or an explanation of the answerers argument, which roughly goes as follows:

The condition $0<x+y$ divides the circle (the area of the projection of the total region on the $x,y$ plane, given the values of $z$ and $w$) in half (on the $x,y$ plane).
Folding the negative $z$ half plane onto the positive one, to get the complementary superposition, divides the volume in half (on the $z,w$ plane).

The total result is to divide the whole ball by $4$.

I believe I understand the first part, but the second part eludes me; I cannot seem to visualize this "folding".
I think the idea is to say that for every pair of values of $(z,w)$ and $(-z,w),$ the sum of the areas of the projections of the region in question onto the $x,y$ plane for these two pairs ($(z,w)$ and $(-z,w)$) is a quarter of the area of the circle, or something like that. The answerer writes "the sum of the two areas, for the same $|z \cdot w|$ value, totals that of the semicircle." But I can't see why this should be true from the symmetries of the region.
Thank you.
Answer: Hint Each point on the $4$-ball is in precisely one of the subsets $$M_+ = \{xy > zw\}, \qquad M_- = \{xy < zw\}, \qquad M_0 = \{xy = zw\}$$
of the $4$-ball, and, being Zariski closed (and not the whole space), $M_0$ does not contribute to the volume of the region. On the other hand, the volume-preserving map $\phi : (x, y, z, w) \mapsto (-x, y, -z, w)$ interchanges $M_+$ and $M_-$.
One can readily modify this argument to treat the condition $x > -y$ simultaneously.
Comment: So the point of the map being volume-preserving is that $\mathrm{vol}(M_+)=\mathrm{vol}(M_+)=\frac{1}{2}V_{\text{ball}},$ right? Also, I'm feeling a bit slow today - would you be so kind as to include the modification? Thank you.
Comment: I meant $\mathrm{vol}(M_+)=\mathrm{vol}(M_-)$, of course.
Comment: Yes, that's right, they have the same volume, therefore both are $\frac{1}{2} V_{\mathrm{ball}}$. In the same vein, we can define $9$ subsets according to which relations ($>, =, <$) hold for each of the inequalities. This time, five of them (precisely those involving $=$) will not contribute to the volume. Now, define the volume-preserving map $\psi : (x, y, z, w) \mapsto (-x, -y, z, w)$, and show that you can map the given region to any of the other three contributing subsets with appropriate compositions of $\phi, \psi$.
Comment: Thanks, that was very clear! But I'm still not sure I understand why the subsets with an $=$ sign have zero volume. I guess it is like if we had a $3$-ball $x^2+y^2+z^2\leq 1$ .. if we now change the $\leq$ to an $=$, the resulting region is the unit $2$-sphere, which is two-dimensional and therefore does not contribute to the volume of the sphere. But if the ball is 4D, the sphere becomes 3D - surely that has a volume? I think my concept of "volume" is too tied to 3D structures, but where exactly am I going awry?
Comment: That's right---we're measuring $4$-dimensional volume, and, roughly speaking, $3$-dimensional objects have zero $4$-dimensional volume, in analogy with your $3$- and $2$-dimensional example.
Comment: That was what I thought (and still think is correct), but the ratio of the volume of the $3$-ball to the volume of the $4$-ball is not zero?
Comment: Yes, it is, since the (again, $4$-dimensional) volume of the $3$-ball is zero.
Comment: Ah, there it was, thank you for your patience!