What Continuous Integration System is most geared?

Question: I am looking for a Continuous Integration System to use with Drupal 7. Preferably it should be widely used and easy to support.
Do you have any thought?
Comment: I have no direct experience with it but I've heard very good things about [Jenkins](http://groups.drupal.org/taxonomy/term/4471). You might find some more info at the [Drupal CI group](http://groups.drupal.org/taxonomy/term/4471)
Comment: Is there any benefit in using Team City or would Jenkins be the preferred option? Most resources I can find talk about Jenkins.
Comment: I haven't used either so I can't really comment, except to say that Jenkins is the one that always (literally, always) comes up when talking CI with Drupal people
Comment: There was a session on this at Drupalcon Munich- [Achieving Continuous Integration with Drupal](http://munich2012.drupal.org/program/sessions/achieving-continuous-integration-drupal). You can watch the video for free online at the linked site.
Answer: Among open-source PHP projects, the two most widely-used CI implementations are easily Jenkins (jenkins-ci.org) and Travis (travis-ci.org). Both have significant communities, and you can find examples of using them with Drupal (eg wiki.jenkins-ci.org/display/JENKINS/Drupal+Development and www.vmdoh.com/blog/how-we-test-drupal-7-modules-travis-ci).
Between the two:

Jenkins' positioning is more like Drupal's -- it's an open-source product with a lot of add-ons/options/features, but you have to think a lot about deployment and picking options. It's useful for testing and many other things (e.g. deployment, nightly tarballs, cron-jobs).
Travis is a proprietary SaaS offered on a freemium basis -- free for public/FOSS code; paid otherwise. It's generally easier to setup because Travis provides servers and bundles more features in the default. It has a more focused/limited range of use-cases.

For some specific features that differentiate them (at time of writing):

Jenkins provides reports -- e.g. when a test fails, it lists out specific failures on a nice web-page. You can see an example of a full report at https://test.civicrm.org/job/CiviCRM-Core-Matrix/CIVIVER=4.5,label=test-debian6-1/lastCompletedBuild/testReport/ . In Travis, this is a long-standing feature-request: https://github.com/travis-ci/travis-ci/issues/239
Travis makes it relatively easy to test with different combinations of key dependencies (e.g. PHP 5.2+5.3+5.4+5.5 and MySQL 5.1+5.5+5.6). In Jenkins, this is possible but requires much more sysadmin skill.

As a rule of thumb:

If you have a large project (with lots of code, lots of tests, peculiar integrations, some budget), then Jenkins' deeper feature-set and configurability make it the better choice.
If you have a small project published on Github (e.g. an individual Drupal module or PHP library with no budget), then Travis's simplicity and bundling make it the better choice.
If your project is in between, then there is no clear rule of thumb; it's a judgment call.

Aside: You may find buildkit.civicrm.org interesting. The summaries and explanations are written for an audience that works with Drupal/Joomla/WordPress, although a lot of technical details would need tuning for a Drupal-only audience (e.g. replace "civibuild" with "drush"; replace "Build Types" with "makefiles").
(NOTE: I left several links as plain-text because stackexchange limits the #links from new users.)
Answer: I don't think there's a better-than-anything-else reason why you should use some tool over other CI tools, they all do pretty much the same thing (get source, do stuff).
I'm using Jenkins at the moment and it works quite well.
At the moment we're using Jenkins to:

Fetch the latest code from the code repository
Update the database
Clear the cache
Run tests
Generate documentation using Doxygen

You could also add steps for syncing databases, code review, deployment, ... A lot of Drupal specific work (update the database, clear cache, run test) is done using Drush. If you are planning to use a CI system Drush is pretty much a must-have.
Hint: run-tests.sh or drush test-run can generate JUnit compatible XML reports, so Drupal tests are supported by default in Jenkins.
Hint: if you're on a multisite installation and you're moving stuff between /sites/all and the site specific directory, use Registry Rebuild to fix the registry.
There are lots of plugins available, ranging from deployment to agile dashboards, but we've got a pretty standard setup.
At first it requires some experimenting but once you have the right setup for your team, it's pure profit. The way I see it you'll need to do more thinking on how you're going to organize your configuration (using Features or other exportables) in Drupal.
Answer: There are so many now but there isn't so much a clear cut winner.
It is a very hard decision because there are so many and they all do a lot of the same things.
Basically I guess you have to decide what your specific requirements are, see which options provide what you need.
Then there will probably still be multiple that meet your needs you have to try as hard as possible to find any pros and cons of each (maybe some are better supported, fit your existing technical skillset better, have more community, etc.) and in the end just choose the one you like the best and go with that.
If you wanted and had the time and resources you could also try out a couple of your top preferences and see which you prefer.
Here are some continuous integration related options. Some hosted, some self managed, some with both options. Some aren't focused solely on CI.
Good luck choosing :)

Ansible
Atlassian Bamboo
Buildbot
Buildbox
CircleCI
CloudBees
Codeship
CruiseControl
deploydo
drone.io
Hudson
Jenkins
PHPCI
Semaphore
Ship.io
Shippable
Solano Labs
Strider
TeamCity
Thoughtworks (Go, Snap)
Travis CI
wercker


How to create DropShadow effect in QML with Qt6?

Question: In Qt5 this was easy with using DropShadow.
But in Qt6 the module QtGraphicalEffects is removed.
Is there any trick, workaround or maybe new way in Qt6 to create drop shadow around some component?
Comment: Well, it's definitely not easy, but you can still write your own [ShaderEffects](https://doc.qt.io/qt-6/qml-qtquick-shadereffect.html) in Qt6. I'm pretty sure QtGraphicalEffects will come back in later releases, but for now you have to do it yourself.
Comment: Or you could do it with translucent images.
Comment: yea it looks like that is the way. I will try your suggestion and add it as answer if it works. Thank you
Comment: @user123445151156 can you please post example usage of ShaderEffects if you succeed creating Shadow?
Answer: As you noticed yourself, Qt Graphical Effects is removed (definitely):

The following modules are removed and not planned to be developed
further.

Qt Graphical Effects
[...]

However, the Qt Graphical Effects is made compatible with the new QRhi (Qt Rendering Hardware Interface) used by Qt6. [1]
Note that this doesn't mean it will be included in Qt 6 at a later stage. [2]
Nevertheless, I expect it would be relatively easy to use DropShadow from the dev or Qt 5.15 branch of git.
Note that it is included as a Qt5 Compatibility API in Qt6.1: DropShadow.
Comment: Now there is a new module [QtQuick.Effects](https://doc.qt.io/qt-6/qtquick-effects-qmlmodule.html) since [Qt 6.5](https://www.qt.io/blog/a-short-guide-to-qt-quick-effects)
Comment: @danieltakeshi, you may consider adding an answer yourself explaining how it could be done in Qt 6.5 (and newer).
Answer: Qt6 DropShadow
import Qt5Compat.GraphicalEffects
DropShadow {}

Comment: any suggestions for `innershadow`?
Answer: You can add QtGraphicalEffects module to Qt6 manually and then use DropShadow in your code.
Generally, to unofficially employ QtGraphicalEffects in Qt 6, do the following:
$ git clone git://code.qt.io/qt/qtgraphicaleffects.git
$ cd qtgraphicaleffects/
$ git checkout 59ab3e11433a5157aac0f3af7c0d7fe70a373373 & cd ..
$ ~/Qt/<VERSION>/gcc_64/bin/qmake qtgraphicaleffects
$ make
$ find qtgraphicaleffects/src/effects/ -maxdepth 1 -name \*.qml -exec cp {} qml/QtGraphicalEffects \;
$ cp -r qtgraphicaleffects/src/effects/private/ qml/QtGraphicalEffects
$ cp -r qml/QtGraphicalEffects ~/Qt/<VERSION>/gcc_64/qml/

This will obtain the module source code to the point where it wasn't yet completely removed from the repository. Then it is built and copied with the required files to the Qt installed directory.
So to use DropShadow component, add
import QtGraphicalEffects 1.0

You can also use the following components in your QML code:

BrightnessContrast
Colorize
ColorOverlay
ConicalGradient
Desaturate
Displace
DropShadow
FastBlur
FastGlow
GammaAdjust
Glow
HueSaturation
LevelAdjust
LinearGradient
OpacityMask
RadialGradient
RectangularGlow
ThresholdMask
Comment: If anyone can do that why did they removed it?
Answer: When it comes to 2D effects, get familiar with MultiEffect. For the most common effects, such as blur or drop shadow, this should be the primary choice.
Avoid pulling in the legacy Qt Graphical Effects types from the Qt5Compat module.
Source: https://www.qt.io/blog/post-processing-effects-for-3d-in-qt-6.5
import QtQuick
import QtQuick.Effects

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello Shadow")

    Rectangle {
        id: sourceItem
        width: 100
        height: 100
        radius: 10
        y: 40
        x: 40
        color: "red"
    }

    MultiEffect {
        source: sourceItem
        anchors.fill: sourceItem
        shadowBlur: 1.0
        shadowEnabled: true
        shadowColor: "black"
        shadowVerticalOffset: 15
        shadowHorizontalOffset: 11
    }


Find the number of nodes of n-element heap of given height

Question: We have came across a question in Thomas H. Cormen  which are asking for showing

Here I am confused by this question that how there will be at most nodes
For instance, consider this problem:

In the above problem at height 2 there are 2 nodes. But if we calculate by formula:
Greatest Integer of  (10/2^2+1) = 4

it does not satisfy Thomas H. Cormen questions.
Please correct me if I am wrong here.
Thanks in Advance
Comment: Not that it matters for the question, but the tree in your question is not a heap.
Comment: sepp2k, yaa you are correct after appliying subroutine Heapify it will become Binary Heap, But here my question is different i am asking regarding How many nodes at height h.
Answer: Reading all the answers, I realized that the confusion comes from the precise definition of height. In page 153 of CLRS book, the height is defined as follows:

Viewing a heap as a tree, we define the height of a node in a heap to be the number of edges on the longest simple downward path from the node to a leaf...

Now let's look at the original heap provided by Nishant. The nodes 8, 9, 10, 6, and 7 are at height 0 (i.e., leaves). The nodes 4, 5 and 3 are at height 1. For example, there is one edge between node 5 and its leaf, node 10. Also there is one edge between node 3 and its leaf node 6. Node 6 looks like it is at height 1 but it is at height 0 and hence a leaf. The node 2 is the only node at height 2. You may wonder node 1 (the root) is two edges away from node 6 and 7 (leaves), and say node 1 is also at height 2. But if we look back at the definition, the bold-face word "longest" suggests that the longest simple downward path from the root to a leaf has 3 edges (passing node 2). Finally, the node 1 is at height 3.
In summary, there are 5, 3, 1, 1 nodes at height 0, 1, 2, 3, respectively.
Let's apply the formula to the observation we made in the above paragraph. I would like to point out that the formula given by Nishant is not correct.
It should be
ceiling(n/2^(h+1)) not ceiling(n/(2^h+1). Sorry about the terrible formatting. I am not able to post an image yet.
Anyways, using the correct formula,
h = 0, ceiling(10/2) = 5 (nodes 8, 9, 10, 6, and 7)
h = 1, ceiling(10/4) = 3 (nodes 4, 5 and 3)
h = 2, ceiling(10/8) = 2 (node 2, but this is okay because the formula is predicting that there are at most 2 nodes at height 2.)
h = 3, ceiling(10/16) = 1 (node 1)
With the correct definition of height, the formula works.
Answer: In Tmh Corman   I observed that he is doing height numbering from 1 not from 0 so the formula is correct, I was doing wrong Interpration. So leaf as height 1 and root has height 4 for above question
Answer: It looks like your formula says there are at most [n/2^h+1] nodes of height h. In your example there are two nodes of height 2, which is less than your computed possible maximum of 4(ish).
Answer: While calculating the tight bound for Build-Max-Heap author has used this property in the equation.
In this case we call the helper Max-Heapify which takes O(h) where h is the height of the sub-tree rooted at the current node (not the height of node itself with respect to the full tree).
Therefore if we consider the sub tree rooted at leaf node, it will have height 0 and number of nodes in the tree at that level would be at most n / 20+1 = n/2 (i.e h=0 for the sub tree formed from node at leaves).
Similarly for sub-tree rooted at actual root the height of the tree would be log(n) and in that case the number of nodes at that level would be 1 i.e floor of n / 2logn+1 = [n/n+1].
Answer: Formula for
no. of nodes = n/(2^(h+1))

so when h is 2, and n = 10
no. of nodes = 10/(2^(2+1)) = 10/(2^3) = 10/8 = 1.25

But
ceil of 10/8 = 2

Hence there are 2 nodes which you can see from the figure.
Answer: Though it is mentioned in Cormen that height of a node is the greatest distance traveled from node to leaf(the number of edges), if you take height to be the distance of a node from the leaf, i.e. at leaf the height is zero and at root the height is log(n). The formula stands correct.
As for the leaves you have h=0; hence by the formula n/(2^(h+1))
h=0; max number of leaves in the heap will be n/2.
Answer: what about height 1. Cormen's theory gives 10/(2^(1+1))=3(ceil) while there is 4 nodes at height 1. This is a contradiction.
Answer: It is not true that Thomas H. Cormen is counting the height of the tree starting from one, height is h = 0, 1, ..., log n and it increases as you go upwards:

and in the following formula, he added 1 plus the height:

All the confusion is coming from the fact that this will work nicely with Perfect Binary Trees, not with the one you are showing in your question, this is why he is saying ON MOST
when you consider Big-O it wouldn't really matter
Answer: This formula is wrong, it gives wrong answers in many cases like in this question for h=1 (ie second last level) it gives maximum number of nodes is 3 but there are 4 nodes. Also let us consider a tree with 4 nodes :
             a
            / \
           b   c
          /
         d

node d has height 0, let us consider for height =1 using the formula n/2^(h+1) we get
4/2^(1+1) = 1
which means this level can have at most 1 node which is false !
so this formula is not right.
Answer: The formula is quite correct. Nothing is wrong with the formula!!
Lets take the tree(although its not heap yet its complete) in the question posed by Nishant on the top.
For h=0 means all leaves so ceil(10/2^(0+1)=5) so there are 5 leaves
For h=1 means all nodes which have one arc to reach the leaves, so ceil(10/2^(1+1))=3 there are 3 such nodes in your tree.
For h=2 means all nodes which have two consecutive arcs to reach leaves, so ceil(10/2^(2+1))=1 so you have only one such node(left successor of the root)
For h=3 means all nodes which have three arcs to leaves, so ceil(10/2^(3+1))=1 which is the root.
Moral of the story is that you are confused between height and level. Level starts from up to down. Which means you have 4 nodes on level 2. i.e you can reach 4 nodes if you start at root and moves two arcs down.
Whereas height is completely different. Like in above case at height 0 there are 5 nodes (3 on level 3, and 2 on level 2). Hence height h of a node n means how many arcs you can travel to reach a leaf.
regards,
Hope it clarifies the point.
Safdar from Pakistan


Large test virus file for ClamAV

Question: I need a test file larger than 10K that will trigger ClamAV
As per Large Virus File with EICAR-Test-Signature not identified by the clamav library , ClamAV will not detect the EICAR test virus when it is embedded inside a larger file (even though many other AVs will).
Does anyone know what my options are here?
Answer: I found that a zip file containing the EICAR test virus plus other files does get flagged by ClamAV and can be made as large or small as necessary.

Large test virus file for ClamAV


Which audio processing techniques lead to soft, warm, velvety, ASMR-like kind of sound?

Question: The goal is to create as soft music as possible.
It might be EQ, tube preamps, saturation, compression, recording on tape, tape delay, certain mic positioning, or something else. I just don't know from where to start this beautiful quest of making the softest music I can.
Might you please suggest some essential tricks that work for you or some fundamental reading?
Also, might there be any research on which frequencies are perceived as being the softest ones?
Thanks a lot!
Comment: This question is a little bit like "how do I write a hit song?" or "how do I play guitar?" There isn't some kind of short answer or formula or list of frequencies. Find music that sounds the way you want your music to sound and start working on making music that sounds the same or similar. Study and practice and study and practice. In 10 to 20 years you should be doing very well indeed with your production and engineering skills.
Comment: Please update your question to include links to recorded examples of what you're after.  Incidentally, ASMR is not a type of sound.  It is a [purported] physiological response to various stimuli and has been reported in response a wide variety of things ranging from tapping noises to watching someone execute a mundane task.
Comment: For the last point about which frequencies are softest, you ought to play around with EQ settings in your DAW of choice. That's probably the best way for you to figure out what feels "soft" in the frequency spectrum.
Comment: Mix on NS10M's, for that instant 80's "hole in the middle" soft EQ ;)) Frankly, I think this is too broad a question to be able to answer in a few paragraphs. There are no 'magic' EQ settings to make things 'soft'.
Answer: I suspect that may aspects of sound that might subjectively be thought of as warm will (as so much in life) lie not in the extremes, but somewhere in the middle of the spectrum of various possible sonic characteristics. For example....

People often associate having strong low-end frequencies with warmth, but some very strong bass might seem unnatural or uncomfortable
a little pitch instability/vibrato is often seen as 'warm', but again, very extreme vibrato might seem mechanical and might also disrupt the harmony of the piece.

A lot will also be in the realm of the subjective. If you love old analogue synths you may be very used to a resonant filter sweep being associated with warmth, but if you are more used to orchestral sounds, that kind of sound might seem cold or artificial. And the kind of harmonies that you consider 'warm' will depend a lot on your exposure to different genres.
So I think Todd's comment is spot on - you will need to seek music that sounds the way you want your music to sound, and try to work out what its characteristics are.
Even if you can pin down your formula for 'warmth', you'll still need to consider how to make those warm sounds work in a mix - perhaps your warm strings will seem muddy unless they're in a mix with some other crystal clear sound to provide a contrast.
In fact if you want to be a bit focused with your of research, I'd suggest reading some books / doing some courses on mixing, which will teach you a lot about EQ ranges, how sounds are perceived, and how to get them to work together.
Answer: The most obvious thing is consistent levels.  You don't want jumps in volume, and you don't want plosives.
Start with the recording.  You need a good pop filter, and you want someone with the right kind of voice who knows how not to pop their plosives too much.
Then a large-diaphragm microphone is your friend, ideally a dynamic mic like an SM7 (the classic radio mic).  There's no reason you can't make do with any other kind of mic, but a larger diaphragm mic tends to roll off the higher frequencies in a smooth, natural way, and a dynamic mic does that even more.  With a cardioid mic you also get proximity effect which lifts the bass and low-mids, which can help the "depth" of the voice.  Too much makes it boomy though.  If you want to stop them doing this, put the pop filter where you want their mouth to be.
Then look at EQ.  Most people don't have anything going on below 100Hz vocally, so a high-pass there is good to get rid of ambient noise in the recording from aircon, footfall, and so on.  If the low-mids are sounding muddy, you might want to roll out a bit (although ideally just get the talent to move away from the mic a bit).  You might want to roll out a bit gently around 3-5kHz (the "baby crying" resonant frequency of our ears) to make it less harsh, although if you take out anything significant then you're probably losing clarity on the voice so be cautious.  And a gentle roll-off above 10kHz will smooth out the edges and reduce recording hiss.  Beware with all of this that things still need to be clear and audible though.
Then look at compression.  This will even out jumps in volume.  A two-stage process is good here: one stage to react quickly to transients above some level, maybe even  a limiter; and a slower stage to even out the general volume.  On speech, if the talent knows what they're doing then you'll likely only be looking at about 3dB on each compressor.
And then decide where you want this spatially.  Do you want it ultra-dry, like they're whispering into your ear?  Do you want a touch of short, well-damped reverb for a bedroom?  Or do you want to add some low wind and nature sounds, with a subtle well-damped echo to suggest trees around you?
Mainly though you need to start with the voice.  With a good voice, all you need to do is add some sparkle and try not to kill it.  If you haven't got that, you can polish the turd as much as you like, but all you've got at the end is a sparkly turd. :)
Answer: I'll add a tip, with the disclaimer that I'm a performer not a recording engineer: Pay attention to envelopes. In particular, if the goal is to avoid anything too jarring—crash, bang, click, pop—then you want to avoid "plosives," and probably want to soften the attacks of impulses.
At the same time, my (limited) understanding of ASMR is that it's not just about a wash of new-agey pads that slowly fade in and out, but about impulses—gentle sounds like the tap of fingers, mouth sounds, paper sounds, etc. So you probably want to use some impulse sounds, but smooth out their envelope. Again, I'm not 100% sure, but I imagine this is more about recording very soft sounds with very close mic.
Comment: I'd argue that ASMR uses a lot of plosives. But they're made more gentle by making them with the mouth alone, and not powered by the lungs.
Comment: @trlkly If they're like plosives, but made without the lungs, linguists would call them "[ejectives](https://en.wikipedia.org/wiki/Ejective_consonant)".
Comment: @trlkly  (You might instead mean that they should be unaspirated plosives.)
Comment: @Theodore Well, I was using it in a very scary-quotey way — there's no indication that the OP is even talking about using human voice (and now has edited into something hopelessly vague). I'm using "plosive" in a broad sense to also include instrumental sforzandos, etc.
Answer: One thing that tends to make almost anything sound "soft" is compression, possibly with just a touch of reverb.
So, try applying a compression to the different instruments in the mix, testing different levels and settings, and you will probably get something useful.
Of course, there's a lot more to it, and various other answers contain important advice that you should study and apply as well.


Can the distribution of a pivot depend on known parameters?

Question: I have a question about the distribution of a pivot. Different sources give slightly different definitions of a pivot. Some of them define it as a random variable $Q(\mathbf{X}, \theta)$ whose distribution is the same for all $\theta$, where $\theta$ is a vector of parameters of $X$'s distribution (see definitions from wikipedia and Casella-Berger below; here $X$ is a r.v. which generate observations). But some other sources define pivot as a random variable whose distribution doesn't depend on unknown parameters of $X$'s distribution (see definition from "probability course" below), this means that theoretically pivot's distribution can depend on known parameters of $X$'s distribution. All examples of pivots for different population distributions, that I have seen in textbooks, didn't depend on all (known and unknown) parameters of $X$'s distribution.
So, my question is – can the distribution of a pivot depend on known parameters of $X$'s distributiion?
I mean cases when $X \sim P_\theta; ~\theta = (\theta_1, \ldots, \theta_k),$ and some of the components of vector $\theta$ are known (known parameters) and other components are unknown (unknown parameters); and we need to build confidence interval for some unknown parameter $\theta_j$ using sample from $P_\theta$ (typically we construct a pivot for this purpose).
Below definitions of a pivot from three different sources are given.
First one is the definition of a pivot from wikipedia:

In statistics, a pivotal quantity or pivot is a function of observations and unobservable parameters such that the function's probability distribution does not depend on the unknown parameters (including nuisance parameters). A pivot quantity need not be a statistic — the function and its value can depend on the parameters of the model, but its distribution must not. If it is a statistic, then it is known as an ancillary statistic.
More formally, let $\mathbf{X} = (X_1,X_2,\ldots,X_n)$ be a random sample from a distribution that depends on a parameter (or vector of parameters) $\theta$. Let $g(\mathbf{X},\theta)$ be a random variable whose distribution is the same for all $\theta$. Then $g$ is called a pivotal quantity (or simply a pivot).

And here is the definition of a pivot from Casella-Berger's book "Statistical inference":

Finally, here is the definition of a pivot from the website probabilitycourse.com:
Answer: The usefulness of a pivot is that you know its distribution, so you can actually do calculation with it, such as in finding a confidence interval. If its distribution depends on known parameters, you still know its distribution, and still can do the calculations ... so it really behaves like a pivot, yes?
So, yes, the distribution of a pivot can depend on known parameters.


Does the continued fractions $3+\frac{1}{5+\frac{1}{7+\cdots}}$ equal $\pi$?

Question: $3+\frac{1}{5+\frac{1}{7+\cdots}}=\pi$ Is it true? If yes, how to show it?
Please help. Thank you.
Comment: Why do you expect it to? Is this an exercise from some book, and in that case, what sort of level is it?
Comment: I found it on the internet. I think it is not true. Is it?
Comment: In that case, could you provide a link?
Comment: [See this](http://math.stackexchange.com/questions/502233/relation-between-e-and-pi) See the comment to the question.
Comment: Sorry, The new answer tells that I was expecting wrong.
Comment: http://oeis.org/A001203 says it's not $3, 5, 7$ but rather $3, 7, 15$ which starts off the continued fraction.
Answer: If the continued fraction converged to $\pi$, the value of the  odd convergent
$$
3 +\cfrac1{
5 +\cfrac1{
7}} = \frac{115}{36} = 3.19444\ldots
$$
would be strictly smaller than $\pi$.  But the convergent is already too big.  The actual value of the continued fraction must exceed $\frac{115}{36}$;  it lies somewhere between
 $\frac{115}{36} \approx 3.1944$ and $\frac{1051}{329} \approx 3.1945$.

Another way to see this is:

Simple continued fraction representations of irrational numbers are unique
The continued fraction representation of $\pi$ begins $3+\frac1{7+\cdots}$, not $3+\frac1{5+\cdots}$.
Therefore, this is not the continued fraction representation of $\pi$.


Is it true: $||A||_2 = \min\{ ||A||_1 ,||A||_3,||A||_4,\ldots \ldots, ||A||_{\infty},\|A\|_F\} $?

Question: While running one algorithm , I observed the following peculiar relationship (at-least to me). I am not quite sure whether it is true in general, but I could not succeeded either in producing any counter example to nullify it.
Let $A$ be a square matrix;
$$\|A\|_2 \leq \|A\|_1\quad,$$
$$||A||_2 \leq ||A||_{\infty}\quad,$$
$$||A||_2 \leq ||A||_F\quad.$$
Where $||A||_1,||A||_2,||A||_{\infty}$ and $||A||_F$ are 1-norm, 2-norm, infinity norm and frobenius norm respectively.
Are above relationships indeed true? and if so, then is it correct to say that (2-norm) always lower bounds all the other norms. i-e $||A||_2 \leq ||A||_1 ,||A||_3,||A||_4,\ldots \ldots, ||A||_{\infty},||A||_F $ ?
Would be thankful for any suggestion.
Comment: This question is asking about matrix norms, i.e. $||A||_p = \max_{||x||_p=1} ||Ax||_p$, which isn't the same as the vector norm of the components of $A$.
Comment: Can't find a source at the moment, but I believe there is a theorem that states for $1 \leq p \leq q \leq \infty$, if $p < q$ then $||x||_q \leq ||x||_q$ for all $x \in \mathbb{R}^n$
Answer: All norms on a finite dimensional vector space are equivalent (that is, for any two norms A and B, there exist universal constants $C_1, C_2,C_3, C_4$ such that $C_1 || \cdot ||_A \leq || \cdot ||_B \leq C_2 || \cdot ||_A$ and  $C_3 || \cdot ||_B \leq || \cdot ||_A \leq C_4 || \cdot ||_B$).
But this by no means tells you one norm is always the smallest in a family of norms (without knowing the constants, anyway). A cute result from these notes related to Fritz John's ellipsoid theorem tells you on a n-dim real normed vector space with norm A, you can always find an inner product norm $B$ with $C_1 = 1$ and $C_2 = \sqrt{n}$ where these constants are indeed tight.
I just used Octave to generate some random matrices using the code:
octave:6> A=randn(2); norm(A)-norm(A,1)
ans =  0.023753
octave:7> A
A =
1.4542  -1.0416
-1.7263   2.0556
to get a counter example.
As for the other way around,
octave:15> A=randn(2); norm(A)-norm(A,1)
ans = -0.70221
octave:16> A
A =
0.30553  -1.79793
0.41323   0.93044
Comment: thanks for producing counter examples. My matrices were actually order > 50, and in that case it was very difficult to get norm(A)-norm(A,1)<0. :)


Inner product matrix

Question: Let A $\epsilon$ $\mathcal M_n$. Define in $\mathbb {R^n}$x$\mathbb {R^n}$:
$\langle$x,y$\rangle_A$=$\langle$Ax,Ay$\rangle$
Prove that $\langle \rangle_A$ is an inner product in $\mathbb R^n$, if and only if, A is invertible. (In the right side on the equation, we have the canonical inner product in $\mathbb R^n$)
Comment: Does this answer your question? [Prove $\left\langle v | u \right\rangle = v\cdot (A^tAu) $ is an inner product](https://math.stackexchange.com/questions/1826429/prove-left-langle-v-u-right-rangle-v-cdot-atau-is-an-inner-product)
Answer: If $A$ is not invertible the null space of $A$ is not just $\{\vec{0}\}$. Therefore $<x, x>_A$ will be 0 for every element in the nullspace of $A$, which is not prohibited by definition of an inner product.

Inner product matrix


How to customize iPhone UISlider control at runtime - where do I place the color update code?

Question: I have added a UISlider control to an iPhone View-based application and have wired up a text field that gets the values from the slider. To fit with the user interface colors in the application I need to change the color of the slider.
With a little googling I was able to find 2 samples which do this (http://blog.hill-it.be/post/2009/03/23/Pimp-My-UISlider and http://developer.apple.com/iphone/library/samplecode/UICatalog/index.html) but I'm stuck because I'm not sure where I should be calling the code from.
I have a method which should return a custom UISlider object, but how do I override the one that I created through interface builder that lives in my sliderViewController.m and sliderViewController.h?
- (UISlider *)createCustomSlider
{
  CGRect frame = CGRectMake(174, 12.0, 120.0, 7.0);
  UISlider customSlider = [[UISlider alloc] initWithFrame:frame];
  [customSlider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
  // in case the parent view draws with a custom color or gradient, use a transparent color
  customSlider.backgroundColor = [UIColor clearColor];
  UIImage *stetchLeftTrack = [[UIImage imageNamed:@"orangeslide.png"]
                            stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0];
  UIImage *stetchRightTrack = [[UIImage imageNamed:@"yellowslide.png"]
                             stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0];
  [customSlider setThumbImage: [UIImage imageNamed:@"slider_ball.png"]     forState:UIControlStateNormal];
  [customSlider setMinimumTrackImage:stetchLeftTrack forState:UIControlStateNormal];
  [customSlider setMaximumTrackImage:stetchRightTrack forState:UIControlStateNormal];
  customSlider.minimumValue = 0.0;
  customSlider.maximumValue = 100.0;
  customSlider.continuous = YES;
  customSlider.value = 50.0;

  return customSlider;
}

With .NET I'd normally have some code generated by the WinForms editor which I would then be able to override by creating a new object and assigning to the existing reference.
Answer: You shouldn't do it this way. You have three options:

Instead of having your method return a new UISlider object, have it modify the existing UISlider instance you created in IB.
Write a custom UISlider subclass and put your customization code in its awakeFromNib method. Make this class the class of the slider instance in IB.
Remove the slider from the NIB completely and create it programmatically as you are doing in your method. Then add it as a subview to your mainView.


How to calculate the variance of $(X_1-X_2)^2$?

Question: $X_1$ and $X_2$ are both a random sample from $\mathrm{N}(\mu,\sigma^{2})$.
How to calculate variance of $(X_1-X_2)^2$?
Comment: Well, what is the distribution of  $X_1-X_2$?  Then what is the distribution of  $(X_1-X_2)^2$?  Then what is the variance of  $(X_1-X_2)^2$?
Comment: @TPArrow Exactly how do you conclude there are two degrees of freedom and why do you introduce $\mu$ when the mean of $X_1-X_2$ obviously is zero?
Comment: @Nicole, just follow the outline in my comment above.
Comment: Do both $X_1$ and $X_2$ come from the same distribution or do they differ in terms of the mean and variance?
Comment: @COOLSerdash Both of them follow normal distribution with mean u and variance sigma square. iid
Comment: Have you heard of [LOTUS](https://en.wikipedia.org/wiki/Law_of_the_unconscious_statistician)?
Comment: If both follow the same normal distribution, the answer is $8\sigma^{4}$.
Comment: @DilipSarwate yes, but it would be complex if calculate in that way
Comment: @TPArrow I know that sum of (x1-u)^2 and  (x1-u)^2 follow chi(2) distribution proved by MGF. But I can't figure out the last item since I have to prove independent between this item with the other two items. How you figure out the distribution form?
Comment: @COOLSerdash Thanks, I am curious how did you get this answer. TPArrow's answer give some hint, the variance of his distribution is your answer. But how to get that distribution? I try to use MGF but didn't work it out. Thanks
Comment: I just followed @MarkL.Stone's outline. Try to follow it too and tell us at what point you are stuck.
Comment: @MarkL.Stone  I get what you mean, thanks. x1-x2 follows N(0,2sigma^2) using law of MGF and then [(x1-x2)/(2*sigma^2)]^2 follows chi square distribution. Then I get the answer. Right?
Answer: Here is the outline provided by @MarkLStone.
First, the distribution of $Z=(X_1-X_2)$ is $\mathrm{N}(0,2\sigma^{2})$.
Next, we know that a squared normal distribution with mean zero and unit variance follows a Chi-square distribution with one degree of freedom. Consequently:
$$
\frac{Z^{2}}{2\sigma^{2}}\sim \chi^{2}(\nu=1)
$$
Hence
$$
Z^{2}\sim 2\sigma^{2}\chi^{2}(\nu=1)
$$
Edit: Thanks to @Glen, there is even a faster way than that outlined below:
The variance of the Chi-squared distribution is $2\nu$. Furthermore, a basic property of the variance is $\mathrm{Var}(kX)=k^{2}\mathrm{Var}(X)$. So with $k=2\sigma^{2}$ we arrive immediately at
$$
\mathrm{Var}(Z^{2})=\mathrm{Var}(2\sigma^{2}\chi^{2}_1))=4\sigma^{4}\mathrm{Var}(\chi^{2}_1))=4\sigma^{4}\cdot2=8\sigma^{4}
$$

Old version
The next step is to know the following relationship between a Chi-squared distribution and the gamma distribution:
$$
\mathrm{If}\: X\sim\chi^{2}(\nu)\;\mathrm{and}\;c>0, \;\mathrm{then}\; cX\sim\mathrm{Gamma}\left(k=\nu/2, \theta=2c\right)
$$
So we have at last:
$$
Z^{2}\sim \mathrm{Gamma}\left(k=1/2, \theta=2\left(2\sigma^{2}\right)\right)
$$
The variance of a gamma distribution is $k\theta^{2}$. So we end up with
$$
\mathrm{Var}(Z^{2})=\frac{1}{2}\cdot \left(4\sigma^{2}\right)^{2}=8\sigma^{4}
$$
Comment: +1 but you can proceed more directly. From your line "$Z^2\sim 2\sigma^2\chi^2(1)$" you can use basic properties of variance ($\text{Var}(kX)=k^2\text{Var}(X)$) and the fact that $\text{Var}$ of a $\chi^2_\nu$ is $2\nu$, immediately obtaining $(2\sigma^2)^2\times 2=8\sigma^4$.
Comment: Yes, I had in mind this solution with the Glen_b variant.  I also had in mind that there would be something left for the OP to do on her homework problem.
Comment: @Glen_b Right, that's much faster. I added your solution. Many thanks for the hint!
Comment: @MarkL.Stone Thanks, the need to leave something for the OP on self-study questions is a good point
Answer: Denote
\begin{eqnarray*}
z &=&\left( X_{1}-X_{2}\right) ^{2} \\
&=&X_{1}^{2}-2X_{1}X_{2}+X_{2}^{2}
\end{eqnarray*}
Therefore,
$$
\mathbb{E}\left( z\right) =2\sigma ^{2}
$$
and
\begin{eqnarray*}
z^{2} &=&\left( X_{1}-X_{2}\right) ^{4} \\
&=&X_{1}^{4}-4X_{1}^{3}X_{2}+6X_{1}^{2}X_{2}^{2}-4X_{1}X_{2}^{3}+X_{2}^{4}
\end{eqnarray*}
now all you need to remember is that if $X_{1}\sim \mathcal{N}\left( \mu
,\sigma ^{2}\right) $ then
$
\mathbb{E}\left( X_{1}^{3}\right) =\mu ^{3}+3\mu \sigma ^{2}
$
and $\mathbb{E}\left( X_{1}^{4}\right) =\mu ^{4}+6\mu ^{2}\sigma ^{2}+3\sigma ^{4}
$
similarly to $X_{2}$ hence
\begin{eqnarray*}
\mathbb{E}\left( z^{2}\right)  &=&2\left( \mu ^{4}+6\mu ^{2}\sigma
^{2}+3\sigma ^{4}\right) -8\mu \left( \mu ^{3}+3\mu \sigma ^{2}\right)
+6\left( \mu ^{2}+\sigma ^{2}\right) ^{2} \\
&=&12\sigma ^{4}
\end{eqnarray*}%
\begin{eqnarray*}
Var\left( z\right)  &=&\mathbb{E}\left( z^{2}\right) -\left( \mathbb{E}%
\left( z\right) \right) ^{2} \\
&=&12\sigma ^{4}-4\sigma ^{4} \\
&=&8\sigma ^{4}
\end{eqnarray*}
Comment: Thank you for your detailed answer. The proof suggested by MarkL.Stone is more direct. By the way, what software or plug you use to insert those formulas. Thank you again.
Comment: Correct a typo in one of my comment. [(x1-x2)/(2*sigma^2)^(1/2)]^2 follows chi square distribution with freedom 1.
Comment: Yeah you are right there is an easier version of the proof. I supposed here you do not know chi squared. I use scientific work place.
Comment: @COOLSerdash Thank you for your time and patience, I also get it proved.


Why are my mails sent from Postfix recognized as Spam?

Question: I have a postfix mail server for our firm.
The mails sent from this server to gmail and yahoo goes in spam.
The postfix is configured on our server and it has never been used for spamming.
Everything is configured as is should. The server works fine, the headers are as they should be.
What should I do in order the messages not to go in spam?
Answer: Take this Email Server Test and it will tell you what you can do to deliver your emails cleanly.

Email Server Test
Welcome to the Email Server test page.
This page does a check of your Outgoing Email Server to see how the
  Email server fares with respect to some of the "best practices".
If you are facing issues where your outgoing Emails are consistently
  rejected by other servers or land up in Junk Email or SPAM folders of
  the recipient mail box, this test can help you in identifying the
  problems.
Some of the technologies/RFC Compliance your Email server is tested
  for are:
HELO Greeting
Reverse DNS
DNSBL (RBL)
SPF
Domain Keys
SPAMAssassin Content Checks
BATV (Bounce Address Tag Validation)
Greylisting
URIBL

Testing Process
1. Send an Email to Test Email Address email@example.com
2. That email will bounce with a URL in the bounce messge.
3. Either click on the URL or Copy/paste the URL in a browser.
4. You will see report on your Email Server.

If you do find the report useful, please feel free to drop a note of
  appreciation. The Email server test report will be available in this
  page.
Comment: all about spam is greylisted.
Answer: Check the headers of the email received by GMail and Yahoo accounts for hints as to why they are being marked as spam.
As Berkay said, it could be SPF-related; the headers should show this, e.g.
Authentication-Results: mx.google.com; spf=pass
(google.com: domain of firstname.lastname@example.com designates
xxx.xxx.xxx.xxx as permitted sender)

It doesn't sound like you're blacklisted, else other domains would have issues with your email, but DNSBL can be used to check your IP if you need to.
The article that itsadok linked to gives a good overview of things to check.
Comment: +1 as you mentioned how to check for SPF related headers.  This has been the most frequent cause mail sent via my mailserver ending up in the spam folder.
Answer: Jeff recently published a blog entry on Coding Horror called So You'd Like To Send Some Email (Through Code). This has quite a number of good tips for what you can do to make your sending email more acceptable to external services.
Answer: Just to be safe, check your mx entries and check if you are blacklisted.
http://www.mxtoolbox.com/
Answer: it can be due to the failing of  SPF checks. read here to get information about SPF( Sender Policy Framework)
Answer: This article has a great list of thing you should check. Its main points:

Don't send spam
Remove Your Server From Spamhaus's Blocklists
Configure Reverse DNS Lookups
Format Messages Properly
Create SPF Records
Send All Messages From the Same Address
Sign Email With DomainKeys or DKIM
Use 'Precedence: bulk' for Bulk Emails?
Answer: You may want to read this blog entry : "Postfix with DKIM, Domainkeys, SPf and Sender-ID" at http://www.tai.ro/2010/04/03/postfix-with-dkim-domainkeys-spf-and-sender-id/


fs.readFileSync ReferenceError: fileContents is not defined

Question: I am trying to read files recursively from directory and trying following code.
readDirFiles.list('/dir/subDir/', 'utf8', function (err, filenames) {
      if (err) return console.dir(err);
      //filenames haslist of all files and dirs in '/dir/subDir/'

      if(filenames){
        filenames.forEach(function(filename) {
          //filename is full path of file and array also contains sub directory paths

          try {
            console.log('Opening file '+  filename);
            fileContents = fs.readFileSync(filename, 'utf8');
            console.log(md5(fileContents));
          } catch (err) {
            console.log(err);
          }

        }, this);
      }
    });

in filenames I have list of all files and directories from which I want to read only files and skip directories. When I am trying to read file using fs.readFileSync(filename, 'utf8') it is giving me two erros
1. { [Error: EISDIR: illegal operation on a directory, read] errno: -21, code: 'EISDIR', syscall: 'read' } this one is ok as it is trying to read directory and not file.
2.[ReferenceError: fileContents is not defined] Dont know why this error is coming as I am passing correct file path wit correct extension.
Comment: `utf8` is not an extension rather its the encoding system.What type of files you have in the directory?
Comment: I have .js files in directory. My issue is solved. problem was I have mentioned 'use strict' at top of my file and did not declare 'fileContents' properly.
Answer: Before reading a file, you should check if the path is directory or filepath.
use fs.statSync(path).isDirectory() to check if it is a directory and ignore it.
Answer: Your script probably has 'use strict' at the top, and since you're not declaring fileContents properly, you're getting a reference error.
To fix, use a proper variable declaration:
let fileContents = fs.readFileSync(filename, 'utf8');

Comment: Thank you so much. It worked for me. I have voted your answer but due to my less reputation it will not appear.
Answer: Since the read of directory failed because it's not a file, your fileContents variable is undefined and md5 fails with [ReferenceError: fileContents is not defined]. You should use the above proposed check using fs.statSync(path).isDirectory()
Comment: Thanks for reply.  fs.statSync(path).isDirectory() worked for me.
Answer:
fs.readFileSync() requires a full path to the file, not just the name. filenames returned by list is just a list of filenames, not full path.
fileContents in your example is not defined as noted by the error.
To check if filename is a file, you need to first use fs.stat().
const fs = require('fs');
const path = require('path');

const dir = '/dir/subDir/';

fs.readdir(dir, function (err, filenames) {
    if (err) {
        return console.dir(err);
    }

    // `filenames` haslist of all file names only.
    Promise.all(filenames.map(filename => new Promise((resolve, reject) => {
        const filePath = path.join(dir, filename);

        console.log('Opening file '+  filePath);

        fs.stat(filePath, (err, stats) => {
            if (err) {
                return reject(err);
            }

            if (stats.isFile()) {
                const fileContents = fs.readFileSync(filePath, 'utf8');

                console.log(md5(fileContents));
            }

            resolve();
        });
    })));
});


Prove that $n(n+1)(n+2)$ where $n\in N$ and $n+1=k^2$ ($k\in N$) is divisible by $60$.

Question: My Attempt
Let $N=n(n+1)(n+2)$
Now $n=k^2-1 \implies N=(k^2-1)k^2(k^2+1)$
Now if $k=2m \implies N=(4m^2-1)4m^2(4m^2+1)$ which is divisible by $3$ and $4 \implies$ It is divisible by $12$.
Now if $k=2m+1 \implies N=(4m^2+4m)(4m^2+4m+1)(4m^2+4m+2)$ which is divisible by $8$.
This is as far as I got. How do I prove its divisible by $60$? Sorry if the formatting isn't the best.
Comment: Do you know Fermat's little theorem?  If $p$ is prime, then $k^p-k$ is divisible by $p$.  In particular, $k^5-k$ is divisible by $5$ and by $3$
Comment: No I don't, does it have something to do with primes? I vaguely remember something like that.
Answer: To conclude you have to show that it is divisible by $5$ so you have to see what the possible remainders of $n+1$ when dividing by $5$ are, and conclude that at least one of $n,n+1$ and $n+2$ is a multiple of $5$.

 If $n+1$ is a square then $n+1\equiv -1,0$ or $1\bmod 5$. It follows at least one among $n,n+1,n+2$ is $0 \bmod 5$ as desired.
Comment: Yeah that's a fine way to go about it. My pleasure.
Comment: Alright I guess I do this by assuming all integers to be of the form $5n,5n\pm1,5n\pm2$ and on squaring they are of the form $5m,5m\pm1$ right? Thanks a lot for the help!


Como remover as horas de uma string DateTime

Question: Estou puxando um registro datetime do meu Banco de Dados e estou formatando ela para o formato tradicional brasileiro, no entanto, não consigo retirar as horas depois do último valor, sempre repete a hora. A minha função é esta;

const formatarData = (data) =>{
    var arrayData = data.split('-');
    var dataCorreta = `${arrayData[2]}/${arrayData[1]}/${arrayData[0]}`;
    return dataCorreta;
}

Entranto, o resultado que sai na formatação é este:
Answer: Observe que você utilizou a função Split especificando o delimitador "-" na String "2020-07-06 15:00:00".
Dessa forma você obteve 3 Strings:
arrayData[0] = "2020"
arrayData[1] = "07"
arrayData[2] = "06 15:00:00"

É interessante, nesse caso que primeiro você utilize a função Split com o delimitador " " (caracter espaço) para já inicialmente separar hora da data. E numa segunda etapa utilize novamente a função split para separar dia, mês e ano.
Exemplo:
var arrayDataHora = date.split(" ");
var arrayData = arrayDataHora[0].split("-");

Answer: Uma possível solução é utilizar a classe Date:
const formatarData = (data) =>{
    let d = new Date(data);
    // Month retorna entre 0 e 11, por isso a adição +1
    return `${d.getDate()}/${d.getMonth()+1}/${d.getFullYear()}`
}

Answer:

function dataFormatada(dataBanco){
    let data = new Date(dataBanco),
        dia  = data.getDate().toString(),
        diaF = (dia.length == 1) ? '0'+dia : dia,
        mes  = (data.getMonth()+1).toString(), //+1 pois no getMonth Janeiro começa com zero.
        mesF = (mes.length == 1) ? '0'+mes : mes,
        anoF = data.getFullYear();

    // return diaF+"/"+mesF+"/"+anoF;

    console.log(diaF+"/"+mesF+"/"+anoF);
}

/* ###### data vindo do banco exemplo com PHP
    dataBanco="<?php echo $dataBanco ?>";
########################################### */

dataBanco="2020-07-06 15:00:00";

//chamada da função
dataFormatada(dataBanco);

A tarefa da instrução new Date( ) é criar um local na memória para todos os dados que uma data precisa armazenar.

console.log(new Date("2020-07-06 15:00:00"));

O método getDate() retorna o dia do mês
O método toString() converte um objeto Date em uma string

let data = new Date("2020-07-06 15:00:00")

console.log(data.getDate().toString());

getMonth() - mês dentro do ano (janeiro = 0)
getFullYear() - retorna o ano da data especificada de acordo com a hora local
De posse desse dados você constrói a sua data da forma que desejar
(diaF+"/"+mesF+"/"+anoF)

(anoF+"/"+mesF+"/"+diaF)


Issue when trying to splice an element from array

Question:

const data = response.data
console.log(data) let tmp = data.groups_with_selected[7];
data.groups_with_selected.splice(7, 2);
data.groups_with_selected.splice(2, 0, tmp);

I am trying to splice an element from an array from 7th position, and then insert into 2nd position. But during that process I am successfully able to change the 7th position to 2nd. but issue is after changing the position 7 or 8th position is reflecting in the array.
Comment: I couldn't catch what is the problem, please share an example of your data and what you got after it; and what it should be
Comment: Would you please elaborate on your problem properly? Even the code snippet is not working & doesn't have any real data.
Comment: "but issue is after changing the position 7 or 8th position is reflecting in the array."  what does this mean?
Comment: @Ebay its 7th position, because after splicing the value and inserting in particular position.
At this line data.groups_with_selected.splice(2, 0, tmp);  i am not sure, weather i placed value correctly or not
Comment: If i keep data.groups_with_selected.splice(1, 0, tmp); all the values are displaying correctly. Only if i replace with data.groups_with_selected.splice(2, 0, tmp); then only one value from array is missing
Answer: you can do it like that:
you should choose the first element of the array which produced by splice by default to become an item and not an array, then insert it to your array at a certain position;
const temp = data.groups_with_selected.splice(7,1)[0]
 data.groups_with_selected.splice(2,0,temp )

so it will insert the 8th element in the third position;
Comment: Thanks its perfectly working fine. I understood that  first element of array to become an item and not an array, then can u please clarify me
Why the zero is required :)
Comment: And if i want to replace multiple array values to certain position then can i do like
const temp = data.groups_with_selected.splice(7,1)(9,1)[0]
data.groups_with_selected.splice(3,0,temp )
Comment: splice by default returns an array so we need to choose the specific element of it, extract it. in your case you need to insert the extracted element by splice, so by putting [0] after it, we extract the item and now it's not array now;
Comment: the second comment, is not obvious to me, sorry, Do you want to do it in one go? if it is the case: you should: data.groups_with_selected.splice(2,0,data.groups_with_selected.splice(7,1)[0])


Converter LocalDate para LocalDateTime

Question: Possuo em minha classe de Filtro os seguintes atributos:
private LocalDate periodoDe;
private LocalDate periodoAte;

Porém, o objeto no qual estão as informações o atributo que será filtrado é um LocalDateTime, logo, em meus testes, não posso fazer isso:
filtro.setPeriodoDe(LocalDate.of(2018, Month.SEPTEMBER, 17));
filtro.setPeriodoAte(LocalDate.of(2018, Month.SEPTEMBER, 21));

Ou seja, preciso estar preparado para receber um LocalDate mas tenho que converter para um LocalDateTime.
Answer: LocalDate só possui a data (dia, mês e ano) e LocalDateTime possui a data e hora. Para fazer a conversão, você precisa definir o horário que será usado. Alguns exemplos:
LocalDate data = LocalDate.of(2018, Month.SEPTEMBER, 17);
// seta o horário para 10:30
LocalDateTime dt = data.atTime(10, 30);

// seta o horário para 10:30:45
LocalDateTime dt = data.atTime(10, 30, 45);

// seta o horário para 10:30:45.123
LocalDateTime dt = data.atTime(10, 30, 45, 123000000);

A API tem precisão de nanossegundos, o que quer dizer que é possível ter até 9 casas decimais na fração de segundos:
// seta o horário para 10:30:45.123456789
LocalDateTime dt = data.atTime(10, 30, 45, 123456789);

No caso de um filtro de busca, é comum que a data inicial tenha o horário setado para meia-noite e a data final para 23:59:59.999 (para ter certeza que vai considerar todo o dia na busca).
Sendo assim, você poderia fazer:
filtro.setPeriodoDe(LocalDate.of(2018, Month.SEPTEMBER, 17).atStartOfDay());
filtro.setPeriodoAte(LocalDate.of(2018, Month.SEPTEMBER, 21).atTime(LocalTime.MAX));

atStartOfDay() seta o horário para meia-noite. E LocalTime.MAX é uma constante que vale 23:59:59.999999999.

Timezones e horário de verão
Só lembrando que LocalDateTime não possui timezone, portanto não leva em consideração os efeitos de horário de verão, por exemplo.
Neste caso, você precisaria de um ZonedDateTime, e para isso precisaria definir um timezone também:
// seta o horário para 10:30 no timezone America/Sao_Paulo
ZonedDateTime zdt = data.atTime(10, 30).atZone(ZoneId.of("America/Sao_Paulo"));

// seta o horário para início do dia no timezone America/Sao_Paulo
ZonedDateTime zdt = data.atStartOfDay(ZoneId.of("America/Sao_Paulo"));

Um exemplo é quando começa o horário de verão no Brasil: à meia-noite o relógio é adiantado para 01:00. Isso quer dizer que neste dia, todos os horários entre 00:00 e 00:59 não existem neste timezone. atStartOfDay(ZoneId) já verifica isso e seta o horário para 01:00, que é o primeiro horário válido neste caso.

Já para obter o final do dia, é um pouco mais complicado. Quando termina o horário de verão no Brasil, por exemplo: à meia-noite o relógio é atrasado em uma hora, de volta para 23:00. Isso significa que todos os horários entre 23:00 e 23:59 existem 2 vezes neste dia (uma no horário de verão e outra no horário "normal").
Por isso setar o horário para LocalTime.MAX em um ZonedDateTime nem sempre vai funcionar. O jeito mais garantido é obter o início do dia seguinte e subtrair 1 nanossegundo. Assim, tem-se o último instante do dia, no timezone, independente das mudanças de horário de verão que porventura possam ter.
// seta o horário para o final do dia no timezone America/Sao_Paulo
ZonedDateTime zdt = data
    // início do dia seguinte no timezone
    .plusDays(1).atStartOfDay(ZoneId.of("America/Sao_Paulo"))
    // menos 1 nanossegundo
    .minusNanos(1);

O nome do timezone (America/Sao_Paulo) faz parte da lista de timezones definidos pela IANA. Você pode obter a lista de todos os disponíveis usando ZoneId.getAvailableZoneIds(). Também é possível usar o timezone default da JVM usando ZoneId.systemDefault().
Claro que aí você teria que mudar sua busca para usar ZonedDateTime, mas aí fica a seu critério se vai considerar os efeitos do horário de verão ou não.
Comment: Ficou excelente!
Comment: Só tenho dúvidas se isso funciona quando o horário de verão inicia ou termina ou quando ocorre mudança de fuso horário (não sei, vou fazer uns testes). Mas de qualquer forma a sua resposta está muito boa.
Comment: @VictorStafusa `LocalDateTime` não levam em conta o horário de verão nem quaisquer regras de timezones. Atualizei a resposta, valeu!

Converter LocalDate para LocalDateTime


Why is that for any trigonometric function $f, f(2\pi + \theta )=f(\theta )$ for any value of $\theta$ [proof reading]

Question: Here was the question asked to me ::  Why is that for any trigonometric function $f, f(2\pi + \theta )=f(\theta )$ for any value of $\theta$
I spontaneously said that it was because of their very definition.
Here is the complete description of answer i provided.
Normally we define trigonometric functions for acute angles using right angled triangle as follows.

$$\sin \theta = \frac {opp}{hyp} \qquad  \cos \theta = \frac {adj}{hyp}  \qquad \tan \theta = \frac {opp}{adj}$$
$$\csc \theta = \frac {hyp}{opp} \qquad \sec \theta = \frac {hyp}{adj} \qquad \cot \theta = \frac {adj}{opp}$$
But we can extend our definitions for even other angles using point $P(a,b)$ on cartesian plane as follows
Definition of trigonometric functions as i remember
Consider a point in cartesian plane in $1^{st}$ quadrant as shown

$$\sin \theta = \frac {b}{r} \qquad \cos \theta = \frac {a}{r} \qquad \tan \theta = \frac {b}{a}$$
$$\csc \theta = \frac {r}{b} \qquad \sec \theta = \frac {r}{a} \qquad \cot \theta = \frac {a}{b}$$
Now consider another point in $2^{nd}$ quadrant

$$\sin \theta = \frac {b}{r} \qquad\cos \theta = \frac {-a}{r} \qquad \tan \theta = \frac {b}{-a}$$
$$\csc \theta = \frac {r}{b} \qquad \sec \theta = \frac {r}{-a} \qquad \cot \theta = \frac {-a}{b}$$
As you can see we consider the signed values of x and y in the definition keeping in mind that r is always greater than zero.
similarly we can extend this definition (in other quadrants) for other angles.
so if we rotate the line passing through origin and $P(a,b)$ through an angle of $360^o$ we again reach the same point and hence $f(2\pi + \theta )=f(\theta )$ where f is any trigonometric function.
Is my arguement for the question given to me correct ???
Comment: I think it boils down to the fact that the rays induced by $\phi+2k\pi$ angles are isomorphic and that trigonometric functions deal with ratios of certain segments on these rays (which is well-defined because of the Intersept theorem). Maybe this shortens the argument a fair bit.
Answer: Yes, this is a common way to define trigonometric functions, and if you take this to be your definition your proof is essentially correct. Strictly speaking one probably ought to define the basic trigonometric functions for a particular radius, as in principle one must check that the ratios are independent of the radius $r$ of the circle.
It's worth noting that if one takes a circle of radius $1$, then $\sin \theta$ and $\cos \theta$ can be regarded as the (signed) lengths of the horizontal and vertical legs of the triangle you construct, rather than as merely ratios. In fact, with a little more work, and can also realize the other four standard trigonometric functions as lengths on a diagram defined by a unit circle and a given angle. Constructing these lengths is an enjoyable exercise.
Comment: (And, you're welcome, I'm glad to help.)
Comment: Thankyou for your reply @Travis. Is that the only definition we can define trigonometric function or we can define it some other way.
Comment: There are many ways to define trigonometric functions, though the one you present here is both the most common and (typically) the first encountered. Another very useful definition, encountered in complex analysis, is that $\sin$ and $\cos$ are respectively the real and imaginary parts of the complex exponential map, $z \mapsto e^z$.
Comment: where can i find such generalized (and even different) definitions of different functions normally used in math @Travis.
Comment: That's a very general question, and there's no single exhaustive answer. Wikipedia is often a productive starting point, but for more details about a particular function you should consult a text that discusses it.
Answer: The key point of your argument is that a $2\pi$ rotation yields a point coterminal with the original point.
If an angle $\theta$ is in standard position, the vertex is at the origin, the initial side of the angle lies on the positive x-axis, and the terminal side of the angle intersects the unit circle at the point $(\cos\theta, \sin\theta)$.  Since coterminal angles intersect the unit circle at the same point, the values of $\cos\theta$ and $\sin\theta$ are the same for coterminal angles.  Since the measures of coterminal angles differ by integer multiples of $2\pi$,
\begin{align*}
\sin(\theta + 2\pi) & = \sin\theta\\
\cos(\theta + 2\pi) & = \cos\theta
\end{align*}
Since the other trigonometric functions are defined in terms of sine and cosine, if $f$ is a trigonometric function, then $f(\theta + 2\pi) = f(\theta)$.


Refinement for Lebesgue Integral

Question:
Let $f$ be measurable on $[a,b]$ and let $P_1$ and $P_2$ be measurable partitions of $[a,b]$. If $P_2$ is a refinement of $P_1$, show that $$L[f,P_1]\leq L[f,P_2]\quad\text{and}\quad U[f,P_2]\leq U[f,P_1]$$

Definition:
(1) Let $P=\{E_j\}_{j=1}^n$ and $P^*=\{F_k\}_{k=1}^m$ be two measurable partitions of $[a,b]$. We say $P^*$ is a refinement of $P$ if for every $k$, there is a $j$ such that $F_k\subseteq E_j$
(2) The upper sum $U[f,P]=\sum_{j=1}^nM_j \underbrace{m(E_j)}_{\text{Lebesgue Measure}}$ where $M_j=\sup_{x\in E_j}f(x)$
(3) The lower sum $L[f,P]=\sum_{j=1}^nm_j \underbrace{m(E_j)}_{\text{Lebesgue Measure}}$ where $m_j=\inf_{x\in E_j}f(x)$

For Riemann Integral, we can split the interval and use the Infimum property.
But for Lebesgue Integral, I couldn't understand how to write things in rigorous way? As, we use Lebesgue Measure for the set. How can we use the fact $F_k\subseteq E_j$ to trace the sum? Because here, $$F_k\subseteq E_j \implies m(F_k)\leq m(E_j)$$And infimum/supremum is not less/greater than before. It will be a great help for me if anyone gives me any hint or answer to demystify this.
Answer: I give an answer which assumes that the properties of Lebesgue integral are already known, at least for simple functions, namely for finite linear combinations of indicator functions. Otherwise, the proof is a bit longer.
According to the definitions above, $L(f,P)$ is the integral of the function $$f_P := \sum_{j=1}^n \big( \inf_{E_j} f \big) \mathbb1_{E_j}$$
with regard to the Lebesgue measure. Hence it suffices to check that when $P^*$ is a refinement of $P$, one has $f_P \le f_{P^*}$ everywhere on $[a,b]$.
To check this, fix $x \in [a,b]$, call $E_j$ (resp $F_k$) the only block of $P$ (resp $P^*$) which contains $x$. Then $F_k \subset E_j$, so $f_P(x) = \inf_{E_j} f \le \inf_{F_k} f = f_{P^*}(x)$.
I now complete the proof for the case where the properties of Lebesgue integral of simple functions are not known yet.
For each $j \in [1,n]$, choose $a_j$ in $E_j$ and let $K_j = \{k : F_k \subset E_j\}$. Since $P^*$ is a refinement of $P$, each $E_j$ is the disjoint union of the $F_k$ over all $k \in K_j$ (proof below). For each index $k$, choose $b_k \in F_k$. Then
\begin{eqnarray*}
L(f,P)
&=& \sum_j f_P(a_j) m(E_j) \\
&=& \sum_j f_P(a_j) \sum_{k \in K_j}m(F_k) \\
&=& \sum_j \sum_{k \in K_j} f_P(b_k) m(F_k) \textrm{ since $f_P$ is constant on each $E_j$} \\
&=& \sum_k f_P(b_k) m(F_k) \\
&\le& \sum_k f_{P^*}(b_k) m(F_k) \textrm{ since } f_P \le f_{P^*} \\
&=& L(f,P^*).
\end{eqnarray*}
Proof that each $E_j$ is the (disjoint) union of the $F_k$ over all $k \in K_j$.
We say $P^*$ is a refinement of $P$ if for every $k$, there is a $j$ such that $F_k \subset E_j$. Such a $j$ is unique because $P$ and $P^*$ are partitions.
Given $x \in E_j$, since $P^*$ is a partition on $[a,b]$, $x$ belongs to some $F_k$. By assumption, $F_k$ is contained in some $E_{j'}$. Since the subsets $E_{j'}$ are pairwise disjoint, $j'=j$, hence $k \in K_j$.
Conversely, if $x \in F_k$ for some $k \in K_j$, then $x \in E_j$ since $F_k \subset E_j$.
Comment: You are using if $f\leq g$ then $\int f\leq \int g$ property. But it seems the property use the refinement property itself (circulation). @ChristopheLeuridan
Comment: I see. Then I should use $f_P := \sum_{j=1}^n \big(\sup_{E_j} f \big) \mathbb1_{E_j}$ for $U[f,P]$ case, right? @ChristopheLeuridan.
Comment: Yes. And the proof is the same.
Comment: Thanks, @ChristopheLeuridan. I have an off-topic question. Like Do $U[f+g, P]\leq U[f, P]+U[g, P]?$, for bounded functions $f,g$ on $[a,b]$ with measurable partition $P$. For me, it's seem true because I feel $\sum_{j=1}^n\sup_{x\in E_j}(f+g)(x)m(E_j)\leq\sum_{j=1}^n\sup_{x\in E_j} f(x) m(E_j)+\sum_{j=1}^n\sup_{x\in E_j}g(x) m(E_j)$, but couldn't conclude something concretely.
Comment: It follows from inequalities $\sup_{E_j} (f+g) \le \sup_{E_j} f+ \sup_{E_j} g$. You get an inequality between simple fonctions, and you integrate as before.
Comment: @emonHR That is why I wrote « I give an answer which assumes that the properties of Lebesgue integral are already known, at least for simple functions, namely for finite linear combinations of indicator functions. Otherwise, the proof is a bit longer. » I will give hints about it.
Comment: It might be great if you justify why **"each $E_j$ is the disjoint union of the $F_k$ over all $k \in K_j$"**. Otherwise, the answer is OK. (+1) for your edited version. Cheers.
Comment: @emonHR I added an explanation for this statement.
Answer: Let me give you some hints:
From your definition for every $k$, there is a $j$ such that $F_k\subseteq E_j$. Could you trace $F_k$'s for fixed $E_i$. Construct a set $A_i$.

 $A_i=\{F_\lambda:F_\lambda\subset E_i\}$

Could you show that $m(E_i)=\sum_{F_\lambda \in A_i}m(F_{\lambda})$?

 To prove $m(E_i)\leq\sum_{F_\lambda \in A_i}m(F_{\lambda})$ and $m(E_i)\geq\sum_{F_\lambda \in A_i}m(F_{\lambda})$ use $E_i=\bigcup F_j\cap E_i$ and $F_k'=F_k\setminus\left(\cup_{i=1}^{k-1} F_{\lambda_j}\right)$ (construct a pairwise disjoint partition) respectively.

Now from $U[f,P_1]=\sum_{i=1}^n\sup_{x\in E_j}f(x)\:m(E_i)$ try to show $U[f,P_1]\geq U[f,P_2]$.

 Use $m(E_i)=\sum_{F_\lambda \in A_i}m(F_{\lambda})$ and $\sup_{x\in E_i} f(x)>\sup_{x\in F_{\lambda}} f(x)$. You might be encounter double summation, but you can carefully handle this and turn them into a single summation.

I might be sloppy with some notation. If you need any further clarification, then ask me on comment. Cheers.
Comment: You might have a typo for $m(E_i)=\sum_{F_\lambda \in A_i}m(F_{\lambda})$. For the rest, I need some time to check. Thanks for your response @emonHR
Comment: You are right @falamiw

Refinement for Lebesgue Integral


Add-in to allow user to save Office document directly to an owned/assigned Project Team Site

Question: I'm newbie for office O365 development. I'm trying to develop outlook OWA mail add-in using Visual studio 2013. I need to show the drop-down that should list all the projects which have been assigned for this particular user/mail-id in Project On-line. Also I need a "Save Document" button in this add-in hence the attachment(s) should upload to the selected project's document library once I clicked on "Save Document" button. How can I do this? Please help me in this regard.
If anyone having the similar kind of samples or links please help. Thank you in advance!!
Answer: Your best bet is to just go with the standard Custom pane approach, with your UI appearing in the message body.  You could use a custom Ribbon button, but Add-in commands are currently only supported in Outlook 2016 and not OWA/Outlook.com yet.
You can use the item.AttachmentDetails object to get the MIME content for each attachment to upload to SharePoint.


Simple Android Method Crashing..why?

Question: I'm a new programmer, and I only know the basics of Java/Android programming. I'm trying to make a basic app to convert Fahrenheit to Celsius. I coded the method to do it, hooked it up to a button, and my app crashes. I could not seem to find the error and/or an alternative way of doing it. I was wondering if anyone knew what caused the crash and if they can tell me how to avoid it in the future. This would benefit me as well as beginner Java programmers.
Here is my Java Code:
    public void appControl (View view){

    EditText giveFarenheit = (EditText) findViewById(R.id.farenheit_int);
    String oldFarenheitString = giveFarenheit.getText().toString();
    int oldFarenheit=Integer.parseInt(oldFarenheitString);
    int step1 = oldFarenheit - 32;
    int newCelcius = step1*5/9;
    EditText giveCelcius = (EditText) findViewById(R.id.celcius_int);
        giveCelcius.setHint(oldFarenheit);

}

Here is the log with the crash:
08-28 22:07:55.384  14825-14825/com.paulrotman.tempconverterfree E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.paulrotman.tempconverterfree, PID: 14825
java.lang.IllegalStateException: Could not execute method of the activity
        at android.view.View$1.onClick(View.java:4247)
        at android.view.View.performClick(View.java:5191)
        at android.view.View$PerformClick.run(View.java:20916)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:145)
        at android.app.ActivityThread.main(ActivityThread.java:5972)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
 Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at android.view.View$1.onClick(View.java:4242)

            at android.view.View.performClick(View.java:5191)
Comment: full stacktrace. this is only the beginning.
Comment: can you also please provide more code? maybe usages of appControl?, also full stacktrace as mentioned before.
Comment: Follow and do [this](http://allandroidexamples.blogspot.com/2012/12/sum-of-two-number-using-edittext-and.html) example. It is somewhat similar to your requirement.
Answer: Your this line is causing error, i guess:
giveCelcius.setHint(oldFarenheit);

Its simply because you are giving integer as an argument instead of CharacterSequence[] (I guess); So just add +"" to make it String, and your code should work.
...
giveCelcius.setHint(oldFarenheit+"");

Answer: Change this.

(EditText) view.findViewById(R.id.farenheit_int);

public void appControl (View view){
   EditText giveFarenheit = (EditText) view.findViewById(R.id.farenheit_int);
   String oldFarenheitString = giveFarenheit.getText().toString();
   int oldFarenheit=Integer.parseInt(oldFarenheitString);
   int step1 = oldFarenheit - 32;
   int newCelcius = step1*5/9;
   EditText giveCelcius = (EditText) view.findViewById(R.id.celcius_int);
   giveCelcius.setHint(String.ValueOf(oldFarenheit));
}

Answer: don't initialize EditText giveFarenheit inside a method.
instead of doing this way
do like this
EditText giveFarenheit; above the method
giveFarenheit = (EditText) findViewById(R.id.farenheit_int);
it may be resolve the problem
see the bellow link
Android java.lang.IllegalStateException: Could not execute method of the activity
Comment: Unfortunately, after I tried that, the app just simply crashed when I ran it instead of the layout showing up and crashing after I pushed the button

Simple Android Method Crashing..why?


Prove that $N \subset Z(G)$

Question:
Assume that $N$ is a normal subgroup of $G$ such that $N \cap G'=\{e\}$.  Prove that $N \subset Z(G)$.

Note 1: $Z(G)$ is the center of the group $G$, and $G'$ is the set of all commutators of $G$.
Note 2: Assume that $n \in N$. We want to show that for all $g \in G,$  $ng=gn$. But, I don't know how to use the fact that $N \cap G'=\{e\}$ to reach this.
Any hints? suggestions? answers?
Answer: Let $n\in N,g\in G$.
Then $$[n,g]=n^{-1}(g^{-1}ng)\in N\cap G'=1$$
So $n$ commutes with $g$.
Since $g$ is arbitrary, $n\in Z(G)$.
Hence $N\leq Z(G)$.
Further explanation if you can't get the hint

 (i) $[n,g]$ is a commutator hence $[n,g]\in G'$
 (ii) Since $N$ is normal in $G$, $g^{-1}ng\in N$, hence $[n,g]=n^{-1}g^{-1}ng\in N$
 From these two points, $[n,g]\in N\cap G'=1$ which means that $n^{-1}g^{-1}ng=1$ and hence $ng=gn$.

Prove that $N \subset Z(G)$


Como filtrar um bloco de array dentro de array em javascript + como imprimir conteúdo de objeto dentro de array

Question: Quero fazer um sistema em que a pessoa cadastre um bloco (array produto) com dois valores (nomeProduto e valorProduto). Posteriormente, quero aplicar um filtro pelo nome do produto ou pelo preço.
Quero que todo o bloco (produto: nome + preço) seja exibido.
Nesse teste abaixo, estou trabalhando com dois campos (nomeProduto e valorProduto), mas depois quero fazer 3 campos: nome do produto, preço e categoria.
Então agora seguem meus dois problemas.
1. Quando eu pesquisar pela categoria ou preço ou produto, quero que sejam exibidos todos os dados daquele produto, mas não consigo fazer isso.
2. Eu exibo na tela os valores adicionados (nome e preço), mas como estou usando ARRAY dentro de ARRAY, não consigo tirar uma vírgula no começo de toda linha exibida no html do usuário. Tentei usar OBJETO dentro da array, pra evitara a vírgula, mas desse jeito não aparecia o conteúdo do objeto, aparecia somente [object Obeject]... Se tiver um jeito de exibir e pesquisar o conteúdo de objeto dentro da array, acho que seria até melhor, não sei..
Segue a imagem do resultado:
[Foto do resultado: web + console][1]
Segue abaixo meu código completo (só estou utilizando um arquivo):
        <!DOCTYPE html>

        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>

        <input id="entradaNomeProduto" placeholder="Nome do Produto">
        <input id="entradaValorProduto" placeholder="Valor do Produto">
        <button onclick="fRegistro(entradaNomeProduto.value, entradaValorProduto.value)">Registrar Produto</button>
        <button onclick="fBusca(entradaNomeProduto.value)">Buscar Produto</button>

PS: No momento, o filtro busca somente o conteúdo que tem no campo nomeProduto.

Se puderem daí me explicar os comando pra resolver, agradeço, pois comecei recentemente e não conheço muito, rs..

Galera, desde já, muito obrigado pela ajuda.

  [1]: https://i.stack.imgur.com/9p7sm.png
___________________

**RESOLUÇÃO:**

Deu certo agora.
Fiz alguma alterações.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <input id="entradaNomeProduto" placeholder="Nome do Produto">
    <input id="entradaCategoriaProduto" placeholder="Categoria do Produto">
    <input id="entradaValorProduto" placeholder="Preço do Produto">
    <input id="entradaDataProduto" placeholder="Data (01/01/2022)">
    <input id="entradaIdInterno" placeholder="Id (Somente para pesquisa!)">

       <button onclick="fRegistro(entradaNomeProduto.value, entradaValorProduto.value, entradaCategoriaProduto.value, entradaDataProduto.value)">Registrar</button>
       <button onclick="fPesquisar(entradaNomeProduto.value, entradaCategoriaProduto.value, entradaValorProduto.value, entradaDataProduto.value, entradaIdInterno.value)">Filtrar</button>

Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Comment: Não cumprimente, não agradeça e não escreva resolvido nos títulos. Também não use o campo de perguntas para apresentar soluções. As soluções devem publicadas nos de respostas.
Comment: Ok... Não sabia disso. Vlw
Comment: Sua pergunta parece ter alguns problemas e sua experiência aqui no Stack Overflow em Português poderá não ser a melhor por causa disso. Queremos que você se dê bem aqui e consiga o que quer, mas para isso precisamos que você faça a sua parte. Veja algumas orientações que vão te ajudar: [Guia de sobrevivência do Stack Overflow em Português](https://pt.meta.stackoverflow.com/q/8045). Ao postar um código completo ou código muito extenso dificulta a localização do problema, a recomendação é que seja feito um [mcve] que é uma simplificação compilável do código onde replique a porção que gera o erro
Comment: Ok, obrigado pelas indicações
Answer: Dá para você usar o método filter e filtrar pela propriedade que você deseja.
Ex:
const produtos = [
 { nome: 'macarrão', preco: 12.3, categoria: 'massas'},
 { nome: 'feijão', preco: 10.0, categoria: 'cereais'},
 { nome: 'arroz', preco: 20.0, categoria: 'cereais'},
]

produtos.filter((p) => p.preco > 10.0) //retorna um array com os objetos de macarrão e feijão

produtos.filter((p) => p.name === "arroz") // troca o arroz pelo input digitado assim vai filtrando conforme for digitando

Para evitar que apareça [object Obeject] basta acessar a propriedade (key) do objeto que você quer
Ex
produtos[0].nome // macarrão

Comment: Muuito obrigado pela disposição!

Eu tentei ajeitar aqui, mas não adiantou muito...

Quanto ao filtro, ele funciona somente com aquilo que adiciono manualmente no array EXTRATO/PRODUTOS, o que é adicionado por PUSH não funciona..
Comment: Fiz um comentário postando o meu código, porque não coube aqui...
Comment: Tem como acessar todas as propriedades (keys) da array?
Porque não sei quantas terão... Cada vez que alguém registrar, ela vai aumentar..


Copy a shell script to android out folder and execute it during boot

Question: I have a shell script which I need to copy to anywhere in out folder during Android build process so that it appears somewhere in Android RootFS.
Now, once it is copied after Android build process and becomes part of Android RootFS, I want to execute the shell script during boot time.
How can I do it?
Answer: Well, I created a root folder in AOSP or anywhere, then created Android.mk and copied the script to be copied to out folder. Added below comments in Android.mk
$(shell cp -rf $(LOCAL_PATH)/myscript.sh `pwd`/$(TARGET_OUT)/path/to/folder/)

Now to make it run during Android boot, I added below code in last of init.goldfish.rc:
service myscript_start /system/bin/busybox ash /system/path/to/folder/myscript.sh
    class main
    oneshot

Also, I added below line under # start essential services section of init.goldfish.rc
start myscript_start

That way my script was copied to desired location of out folder and also got called during android boot time.
I wonder if there is any better way to do that. I would like to know if anyone has suggestions.


Notation of staccato rhythm

Question: I'm notating a line for bass and effectively want the 1st and 4th semiquaver of a beat played staccato. I've thought of four ways of notating this that I think would effectively sound the same if played correctly, however I don't know which is clearest. Here are the options I've come up with:
1. A staccato dotted quaver followed by a staccato dotted semiquaver:

2. A staccato quaver followed by a semiquaver rest followed by a staccato semiquaver:

3. A staccato semiquaver followed by a quaver rest followed by a staccato semiquaver:

4. A staccato semiquaver followed by two semiquaver rests followed by a staccato semiquaver:

I personally think the first and fourth examples are clearest, however I am open to suggestions as to why this might not be the case.
Comment: The four options will *not* effectively sound the same if played correctly - the 3rd and 4th options will have the shortest staccato notes in the 1st semiquaver of Beat 1, and the 1st and 2nd options will have longer staccato notes there. In fact, at NinSheetMusic (a video game music transcription site I contribute to), site staff there consistently have me turn the start of the 1st option into a *non-staccato* 8th note followed by a 16th rest.
Comment: While my comment above applies more strongly to instruments like piano and wind instruments, I expect the bassist to mute shorter staccato notes sooner.
Comment: Do you want the third and fourth notes to be played longer than the first and second?
Answer: I would suggest the first instance, if only because it makes the notation more clear. On the other end of the spectrum, I recommend against using option 3; the eighth rest in the middle of the beat could be needlessly confusing.
While options 2–4 may be more accurate in terms of what you want, you run the risk of confusing the performer with the notation and even potentially adjusting their understanding of the phrasing. Depending on the larger context, for instance, it may not be clear that the C at the end of beat 1 is a continuation from the prior A.
With that said, you may find that notation programs only perform what you want if you notate it like in 2, 3, or 4. In this case, trust your own musical intuitions and not the software's playback.
Also keep in mind that text annotations in the score can often give your performers a clearer idea of what you want. Something like secco ("dry") or molto staccato above option 1 would seem, to me, to be very clear in intent.
Comment: This. Readability is key. The more short pauses and notes there are, the more confusing it is to read.
Comment: I also say #1 because that is readable in 4, whereas the others are very subdivided and a performer might even choose to add the stems and flags of #1 to the sheet music if presented with 2, 3, or 4, for clarity, to ensure a precise rendering.
Answer: Although I agree with Richard that option one is good in terms of simplicity and readability I think putting a staccato over a dotted note can be confusing or misleading. Some might think the first note should be longer than the second one.
For that reason I like option 4 BUT with the first and fourth 16th notes beamed together. That way you are showing beat one as a single unit. You are also showing the note durations in the most accurate way. This also eliminates the need to put staccato markings on the notes although it doesn't hurt to include them.
Option two is not bad with the notes beamed together but having both notes be 16ths is more precise. Option three can also be done this way but seeing an eighth note rest starting on the second 16th may be a little confusing to some so it's best to go with #4 with the notes beamed together.
Answer: You've left out the best one!   Write the note lengths you want, beam to the beat.

But are you sure you don't want this?

Or this?
Comment: I think I prefer the original no. 1 version.
Answer: I also think 1st and 4th are best.
Regarding the question whether the 1/16 note staccato is shorter or not:
I think it is clear that they have the same duration. If they were meant to be different, one would put a portato line on the 1/4 note, or a wedge over the 1/16 notes.
Things would also be different if the 1/16 notes were all on the beat. This would clearly indicate that there seems to be a difference, otherwise the 1/16 notes would have been notated as 1/4 too.

Notation of staccato rhythm


How to monitor REST API latency with Prometheus and Grafana

Question: I would like to monitor request processing latency on my Tomcat server. It would be nice to perform some alerting based on this later. I configured Tomcat valve with %D pattern so it will log time taken to process each request in access log file. What would be correct way to calculate 50, 90, 99 percentiles from these log lines? I already have configured Prometheus and Grafana for basic host metrics(cpu/mem,hdd), but it is not clear to me how to correctly calculate percentiles and graph them with prometheus/grafana? Idea is to detect application hicckups and react before it goes totally unresponsive. Thank you all in advance!
Comment: Using the tomcat_exporter seems to be the way to go. But keep in mind that tomcat nor the exporter knows how long it took for the request to get there. There is at least some duration for DNS resolution and you might have a reverse proxy in front of tomcat which can introduce delay too. For these things you can use the [blackbox_exporter](https://github.com/prometheus/blackbox_exporter). If you want measurements from multiple locations you can also check out [my service](https://latency.at) which runs blackbox_exporters for you in various locations.
Answer: You could use my tomcat_exporter to do this by configuring the filter for the response time metrics. Alternatively you could implement a similar filter by yourself.


Javascript: Cannot display image from array

Question: I'm learning javascript by building a quiz app. I have an array and each item in the array contains a question, image, options, answer. But I don't know how to display images to HTML. Please help me. Thank you.
html file:

            What does HTML stand for?

Quiz.js (array)
let quiz = [
{
    question: "What does HTML stand for?",
    image: "img/5.jpg",
    option: [
        "Hyper Tag Markup Language",
        "Hyper Text Markup Language",
        "Hyperlinks Text Mark Language",
        "Hyperlinking Text Marking Language",
    ],
    answer: 2,
},
{
    question: "What does CSS stand for?",
    image: "../img/6.jpg",
    option: [
        "Computing Style Sheet",
        "Creative Style System",
        "Cascading Style Sheet",
        "Creative Styling Sheet",
    ],
    answer: 3,
},
];

script.js (Function)
let index =0;
let attempt = 0;

let totalQuestion = questions.length;
function printQuestion(i) {
   $(".questionBox").text(questions[i].question);
   $(".optionBox span").eq(0).text(questions[i].option[0]);
   $(".optionBox span").eq(1).text(questions[i].option[1]);
   $(".optionBox span").eq(2).text(questions[i].option[2]);
   $(".optionBox span").eq(3).text(questions[i].option[3]);
   //How to display image property
}

Comment: Then your paths are wrong, add a prefix to the path with the location of your images.
Comment: Thank you so much! It's worked!!
Comment: something like ``?
Comment: Thanks Cid. But it doesnt work :(
Comment: Just set the `src` property of the image: `$('#iqid img').attr('src', questions[i].image);`
Comment: @ElChiniNet It shows error: Failed to load resource: net::ERR_FILE_NOT_FOUND. Here's the error: https://imgur.com/rRkkaoR
Answer: The images you have are paths to the image, as you might already know. So you'll need to tell html where the find these images, in an image tag.
where you use the image, like  you'll need to programmatically loop through your array and create an  tag for each one.
something like this.
let div_contains_images = $('.image_div')
for (let q of quiz){
   let image_element = $(`<img src="img/${q.image}">`)
   div_contains_images.append(image_element)
}

// -------------------------------------
// or for a single image in your use case

let image_number = 2
let image_path = quiz[image_number].img
$('#iqid > img').attr('src', image_path)

Comment: Thanks Kevin. It's still the same: it uses the image in the html to display, not the image in the array. It's neccessary that I remove the image source in html?
Comment: It should replace the `src` when you set in using jquery, however just make sure with your version of jquery, it could be `$().prop('src', src)`, `$().attr('src', src)`, `$().scr(src)` or even `$().src = src`
Comment: Thanks Kevin. I don't use jquery, I use js vanilla. So I should use jquery?
Comment: Oh my bad, there is jQuery in your question. If you want to use vanilla JS you might need to use `document.createElement('img')`and set the source using `element.src=src;`
Comment: `const img = document.createElemtent("img");` here's your advice. `img.src = currentQuestion.image; questionImage.appendChild(img);` after that I add 2 more lines. Am I correct?
Comment: Yes. rather use `let`, and not `const`, because `let` allows you to modify the variable. `const` does not allow any changes
Comment: It's seem not understand what I want to do :(( this time I lost the answers: [link](https://imgur.com/rYx6YU4)
Answer: You just need to loop through the quiz array, and prepare the html structure you want to create.

let quiz = [
{
    question: "What does HTML stand for?",
    image: "img/5.jpg",
    option: [
        "Hyper Tag Markup Language",
        "Hyper Text Markup Language",
        "Hyperlinks Text Mark Language",
        "Hyperlinking Text Marking Language",
    ],
    answer: 2,
},
{
    question: "What does CSS stand for?",
    image: "../img/6.jpg",
    option: [
        "Computing Style Sheet",
        "Creative Style System",
        "Cascading Style Sheet",
        "Creative Styling Sheet",
    ],
    answer: 3,
},
];

function printQuestions(questions){
  let htmlString = '';
  questions.forEach(question => {
    // add question text
    htmlString += `

            ${question.question}

`;

    // add the image
    htmlString += `

`;

    let optionsString = '';
    question.option.forEach(option => {
      optionsString += `<span onclick="checkAnswer(this)" data-opt="1">${option}</span>`;
    });

    // add options to htmlString
    htmlString += `<div class="optionBox">${optionsString}</div>`;
  });

  // append htmlString to wrapping element
  $('#questionScreen').html(htmlString);
}//printQuestions()

// call the function we just defined
printQuestions(quiz);
.questionBox
{
  border-top: 3px solid black;
  margin-top: 30px;
}

.optionBox span
{
  border-left: 3px solid black;
  display: block;
  margin-bottom: 2px;
  padding: 5px;
}

Comment: Thanks Mohit. It shows error when I press Play button.
Comment: @AnhKhoa I see the HTML generated when I click the `Run code snippet` button. It's only when you click one of the options that you get the error, and that occurs because the code doesn't include the `checkAnswer` function.


How to add ad script in top- header in Prestashop - 1.6?

Question: I am using prestashop 1.6 . I want to add google ads in top of the header and bottom in footer. I tried many ways but all are not succeed. Please how can i add script in my prestashop website?
Thanks in advance.
Comment: It may be useful : https://gist.github.com/hereswhatidid/8c8edef106ee95138b03 "PrestaShop Media class override to allow for forcing some inline JavaScripts to remain inline."
Answer: You need to find header.tpl file:
https://github.com/PrestaShop/PrestaShop/blob/develop/themes/default-bootstrap/header.tpl

    {$HOOK_HEADER}
    <link rel="stylesheet" href="http{if Tools::usingSecureMode()}s{/if}://fonts.googleapis.com/css?family=Open+Sans:300,600&subset=latin,latin-ext" type="text/css" media="all" />

Remember to disable CCC options for JS (especially moving JavaScript to the end):

Anything within {literal}{/literal} tags is not interpreted, but displayed as-is
{literal}

{/literal}

{ldelim} and {rdelim} are used for escaping template delimiters, by default { and }:

gives:

If you still have a problem you may try to override Media Class:
https://gist.github.com/hereswhatidid/8c8edef106ee95138b03

Some HTML goes here

Media.php:
<?php
Class Media extends MediaCore
{
    public static function deferScript($matches)
    {
        if (!is_array($matches))
            return false;
        $inline = '';

        if (isset($matches[0]))
            $original = trim($matches[0]);

        if (isset($matches[1]))
            $inline = trim($matches[1]);

        /* This is an inline script, add its content to inline scripts stack then remove it from content */
        if (!empty($inline) && preg_match('/<\s*script(?!.*data-keepinline)[^>]*>/ims', $original) !== 0 && Media::$inline_script[] = $inline)
            return '';

        /* This is an external script, if it already belongs to js_files then remove it from content */

        preg_match('/src\s*=\s*["\']?([^"\']*)[^>]/ims', $original, $results);
        if (isset($results[1]) && (in_array($results[1], Context::getContext()->controller->js_files)
            || in_array($results[1], Media::$inline_script_src)))
            return '';

        /* return original string because no match was found */
        return $original;
    }
}

Answer: The correct way should be using a module. Also check if the function htmlpurifier is blocking your scripts tags.
Answer: A little late, but it is solved by using {literal} //script here {/literal}. It's supposed to be used only if there are curly brackets in your script, but it works.


jQuery autocomplete enter key issue

Question: I have a text box for searching using jQuery autocomplete. When I type something in text box, it is showing the suggestions out of which none is selected.
I found out that selectFirst: true is not supported now. If I select an item in the drop down list and press enter, it is working fine.
The problem is that if user enters  app for apple and presses the enter key, it tries to submit the form with app. The form should only be submitted with one of the values from the drop down list.
I tried to disable the form submit on pressing enter so that I could submit form from JavaScript but couldn't find a solution.
Here is my code:
$("#searchtext").autocomplete({
    source: path + 'autocompletesearch?category=' + $("select[name='category'] option:selected").val(),
    width: '500px',
    matchContains: true,
    select: function(event, ui){
        $(".searchform").attr("action", path + "fullproductinfo/" + ui.item.id);
        $("input[name='searchid']").val(ui.item.value);
        $(".searchform").submit();
    }
});

And my form:
        <form method="post" action="search" class="searchform">

                <input type="text" id="searchtext" name="searchtext"
                    placeholder="Search a product or a brand" autocomplete="off"/>

                <input type="button" name="btnsearchproduct" value="Search" />

        </form>

Note that there is <input type='button' and not 'submit', so default enter pressing should not work for form. It is the autocomplete i guess that is submitting the form on submit.
Comment: Would it be fine if like you expect `selectFirst` option to work, you can have the first option to be focused by default?
Comment: Yes, that would be best, but selectFirst is not working
Answer: If you are using this: http://jqueryui.com/autocomplete/
Then you want first item to autoFocus, you can use that option now:
$( ".selector" ).autocomplete({ autoFocus: true });

Mentioned in documentation: http://api.jqueryui.com/autocomplete/
EDIT
Since you have enter key issue, you can try like this:
$(".selector").keydown(function(event){
    if(event.keyCode == 13) {
      if($(".selector").val().length==0) {
          event.preventDefault();
          return false;
      }
    }
 });

Answer: If you are using jquery ui for auto complete, all you need is specifying the autoFocus: true option.
It will automatically select the first result and when hit enter key it will use the first result.
$( ".selector" ).autocomplete({
  autoFocus: true,
  source: function (request, response) {
    //your code
  },
  select: function(event, ui) {
    //your code
  }
});

Answer: I had a similar issue & this is how I resolved it
if ($(".selector").val().length > 0) {
var options = $(".selector").autocomplete("option");
var fromAutocomplete = false;

jQuery.each(options.source, function(index, device) {
if ($(".selector").val() == options.source[index]) {
    fromAutocomplete = true;
}
});

if (!fromAutocomplete) {
$(".selector").val("");
    $(".selector").attr("disabled", false);
    return false;
}
}

jQuery autocomplete enter key issue