What regression method should I use?

Question: I have a very high dimensional (p=946, n =123) dataset. For the one's i have checked, the covariates do not really have a relationship with the response so i have ruled out linear regression. Then, i tried to find the distribution of Y as plotted below. I found that Weibull distributuon fits this dataset best followed by Gamma second based off AIC/BIC.
I thought I would go for Gamma as this might be easy to implement using glmnet in R but this package doesn't support the Gamma distribution. So i'm wondering, for high dimensional datasets, what regression method could i use in which an R package may support it? I'm not sure what model i could use with a Weibull distribution. In particular i'd like to use a package where I can. use screening methods for variable selection.
The data can be found by the following commands
<code>install.packages('PRIMsrc')
library(PRIMsrc)
data(Real.2)
</code>
Answer: You say     "Then, i tried to find the distribution of Y as plotted below. I found that Weibull distributuon fits this dataset best followed by Gamma second based off AIC/BIC."
I say nonsense "The distribution of Y is not a concern. All of the assumptions in regression are about the distribution of the error terms which is in effect a conditional distribution of Y."
Paraphrasing "There is nonsense and there is nonsense but the most nonsensical nonsense of them all is statistical nonsense"
EDITED AFTER RECEIPT OF DATA 123 OBSERVATIONS/SAMPLES WITH 140 CANDIDATE PREDICTORS:
Time series analysis allowing for the effect of auto-correlated data i.e. non-independent samples requires certain procedures to be used in identifying a useful model . Here is a discussion that I authored some 20-25 years ago https://autobox.com/pdfs/regvsbox-old.pdf . Your data is cross-sectional thus "shuffling the cards" is not necessary as the 123 observations are free of auto-correlation because they were independently collected.
Cross-sectional regression (your problem) is a particular case of
a SARMAX problem https://autobox.com/pdfs/SARMAX.pdf without the ARMA component or differencing or lagged structure in the X's.
Cross-sectional data and time series data have a number of commonalities viz..
1) the need to identify pulses i.e. an instantaneous adjustment to the expected value.
2) the need to consider when you have more input series(140) than obervations(123) and how to obtain the optimal/parsimonious/sufficient set of predictors
3) what kind of power transformations are necessary to form a useful model
With these common objectives in place , I introduced your data to AUTOBOX ( a generalized regression package that I have helped to develop ) specifying that order in the observations was not of interest or concern by declaring the "seasonality to be 1" and supressed lag structure in the predictors AND lag structure in the memory of Y.
Here is a plot of the original data   suggesting an outlier/pulse at period 10 which might be due to one or more of the 140 causal series . Nonetheless it certainly would thwart any attempt to specify a stabilizing xform . Not treating that one observation can easily lead to a spurious conclusion about the need for some sort of transformation.
AUTOBOX has a feature to do a sub-set elect and concludes that 12 of the 140 are both sufficient and statistically significant predictors while treating the errant 10th observation.
Following is a plot of the residuals from that model suggesting model sufficiency.

The optimal sub-set model is here   AND here in two parts
The model statistics are here
The Actual/Fit graph is here
 and the cleansed graph is here

The histogram of the residual series is here  and in contrast the histogram of the original series is here showing the effect of the anomaly at period 10  and the omission of the selected 12 input series.
There is no evidence of any needed power transformation

In closing "All models are wrong but some are useful" from G.E.P Box . This example should be useful to all those studying how to form a possible model.
Comment: So i need to run each possible regression model first and then diagnose the residuals to see if it fits? For GLM & other models what do i need to look for?
Comment: after developing a model and treating anomalies (albeit insufficient model!) I suggest that you look at  http://stats.stackexchange.com/questions/18844/when-and-why-to-take-the-log-of-a-distribution-of-numbers. I tried to download your data but couldn't read it perhaps you need to save it as a csv file or a text file.
Comment: I have tried some transformations but this doesn't make my data normal. I thought for a GLM that each outcome Y of the dependent variables is assumed to be generated from a particular distribution in an exponential family, therefore i need to check the distribution in this case rather than residuals?
Comment: i've also edited the question so the data should be (easily) downloadable now
Comment: In this case AFTER you have identified the BEST SUBSET of time series less than the # of observations AND any  anomalies  pulses  IN THE ERROR PROCESS ( 1 in this example) and incorporated an appropriate dummy indicator , the solution is MLR with STEPDOWN . AUTOBOX is available in R .

What regression method should I use?


Math&JS: sinusoidal animation

Question: given incremental values form 0 to infinite
I'd like to get back a value that increase, then decrease, then increase, then decrease...like a sine
I'm basically trying to get an animation of a ball that goes up and down, based on input values that are only linearly increasing (this value is given by scrolling the page for example to from 0px to TBD +1)
what the math function should I use?
thanks
Answer: Well, JavaScript has a sine function:
var y = Math.sin( Math.PI );   // returns 0

Math.sin() takes its argument in radians.
If you want to "slow down" the oscillation, what you have to do is stretch out the input parameter: just divide what you're passing into the sine function by some constant.  For example, if x is your input parameter, and you want the animation to go half as fast, do this:
var y = Math.sin( x / 2 );

Also keep in mind that sine goes negative; its range is [-1,1].  So if you want to avoid the negative values, you'll have to add 1 to the output of the function:
var speed = 0.5;  // 2=2x speed, 0.5=half speed, etc.
var y = (Math.sin( x * speed ) + 1)/2;
// y will range from [0,1]

See this jsfiddle for a demonstration: http://jsfiddle.net/r8yRN/
Comment: thank you! I actually tried it var ballY = Math.sin( x ) * 100; where x is the with +1 increments, but for some reason the ball oscillate up and down but too fast...i forgot all about sin and geometry i dont remeber how to extend the frequency...

Math&JS: sinusoidal animation


When would Bach start an ornament- just before the beat, or right on it?

Question: In his table (see below) , all examples seem to start ON the beat, not before it.
https://upload.wikimedia.org/wikipedia/commons/1/1e/Bach-ornamentguide.jpg
Comment: Thanks, I have now included the source above as you suggested.
Comment: Please cite the source of "his table."  There are dozens of scholarly works discussing the implementation of trills, mordents, grace notes, etc. from that period.
Answer: Baroque ornamentation usually has a rule that it starts on the upper-auxiliary note, something which is not the case for other eras of music. whether the ornament is on the beat or not is a matter of what fits, what is most musical and what aids in the message of the music.
Except for a few ornaments that are always on the beat you are going to have to use your 'interpret' muscle to decide on how to exactly play the ornaments. That is why some famous baroque pieces never seem to sound the same when you listen to multiple recordings.
Baroque music is richly ornamented but Bach never gave exact meaning to what he wanted from the ornaments, considering the particulars of the playing of ornaments, the performers prerogative.
Comment: True - but the OP asked about the timing, not the note.  Appogiatura are almost always on the beat, but trills often start (with upper note) just before the beat, and so on.
Comment: Thank you both. This helps me to narrow my question somewhat down to this: in which examples in his Explication (the above document-or any other by Bach) does he actually indicate that one should begin the ornament just before the beat?
Comment: @ChrisFletcher he doesn't.  In general they don't start before the beat.  The first note of an ornament generally carries the accent, so it should be on the beat.


Can I exclude some methods from manual template instantiation?

Question: We have complex template classes that have some methods which will not work with certain policies or types. Therefore, when we detect those types (at compile time, using type-traits) we fire a static assertion with a nice message.
Now we do a lot of manual template instantiation as well. Partly it is so that the methods are forced to compiler to syntax check the methods. It also reduces compile time for the library user. The problem is that the static assertions are always fired and consequently we cannot manually instantiate the template class in question.
Is there a workaround for this?
EDIT: To make it clearer, here is an example (the explicit instantiation in this case will fail on someFunc1():
// header
template <typename T>
class someClass
{
  void someFunc() {}
  void someFunc1() { static_assert(false, assertion_failed); }
};

// source
template someClass<int>; // Explicit instantiation

EDIT2: Here is another example. This time you can compile it to see what I mean. First compile right away. The code should compile. Then Uncomment [2] and the static assertion should fire. Now comment out [2] and Uncomment [1]. The static assertion will fire because you are explicitly instantiating the template. I want to avoid removing explicit instantiation because of the benefits that come with it (see above for benefits).
namespace Loki
{
  template<int> struct CompileTimeError;
  template<> struct CompileTimeError<true> {};
}

#define LOKI_STATIC_CHECK(expr, msg) \
    { Loki::CompileTimeError<((expr) != 0)> ERROR_##msg; (void)ERROR_##msg; }

template <typename T>
class foo
{
public:

  void func() {}
  void func1() { LOKI_STATIC_CHECK(sizeof(T) == 4, Assertion_error); }
};

template foo<int>;
//template foo<double>; // [1]

int main()
{
  foo<int> a;
  a.func1();

  foo<double> b;
  //b.func1(); //[2]

  return 0;
}

Comment: I agree with the others that complain about with the lack of details. But anyway, this ringed a bell to me: "The problem is that the static assertions are always fired".
http://www.boost.org/doc/libs/1_48_0/doc/html/boost_staticassert.html#boost_staticassert.templates, last remark: is that the issue that you're having?
Comment: It is not clear from the description what the problem is, but from the scope of the problem it seems like enable_if is for you (http://www.boost.org/doc/libs/1_48_0/libs/utility/enable_if.html)
Comment: @bobah: That is not a bad idea at all... I will look into it. If you can prepare a simple example that I can verify, I'll mark that as an answer?
Comment: @LorenzoPistone: I am not sure how I would apply that in the example I gave above (in Edit2)?
Answer: Alright, so if you're forcing the instantiation of all methods using explicit instantiation, you can't get away with any compile time tricks to prevent instantiation of the offending methods, such as enable_if. It'd be easy enough to move the error to runtime, but that's undesirable.
I think the best you can do is move the error to link time, which will statically ensure that the program does not contain a code path that could potentially call the prohibited function, but the error messages won't be very helpful to anyone that doesn't know about the restriction you're imposing. Anyway, the solution is to declare a specialization of the prohibited member functions but not define them:
template<typename T>
struct Foo {
    void bar() {
        std::cout << "bar\n";
    }
    void baz() {
        std:: cout << "baz\n";
    }
};

template<> void Foo<int>::baz(); // use of Foo<int>::baz() will resolve to this specialization, and linking will fail

template struct Foo<int>;
template struct Foo<char>;

int main() {
    Foo<int> f;
    f.bar();
    // f.baz(); // uncommenting this line results in an ugly link time error
    Foo<char> b;
    b.bar();
    b.baz();  // works with Foo<char>
}

The static asserts no longer help give nice error messages when a mistake is made in client code, but you might want to leave them in because they'll fire if you forget to provide a specialization.
Comment: That is fine if you are creating an instance. In our case we are using explicit instantiation which causes the problem (see edit above)
Comment: To avoid confusion for any future SOer, my comment above is for the reply _before_ the edits (which was made before I clarified my question with some edits as well)
Comment: +1 **This should be the Answer.** Requires a bit of redundant work but delivers :)
Answer: You can't have both: you can't have a static assertion to prevent instantiation and explicitly instantiate the type! This is an obvious contradiction. What you can have, however, is conditionally included functionality even though it is somewhat a pain in the neck: If a certain member function is not supposed to be supported for certain types, you can move this function into a base class which conditionally has it. This way you wouldn't use a static assertion but just remove the member function. I realize that this introduces interesting other problems, e.g. with respect to the location of member variables, but I think in the context you are describing this is the best you can get.
Here is a quick example of how this could look like:
template <typename T, bool = std::numeric_limits<T>::is_integer> struct foo_base;
template <typename T> struct foo_base<T, false> { /* intentionally left blank */ };
template <typename T> struct foo_base<T, true> { void foo() { /*...*/ } };

template <typename T>
struct Foo: foo_base<T> { /* .... */ };

template struct Foo<int>;    // will have foo()
template struct Foo<double>; // will not have foo()

Answer: enable_if is a flexible mechanism for precise template methods targeting, may be what you are after. Example:
#include <string>
#include <iostream>

#include <boost/utility.hpp>
#include <boost/type_traits.hpp>
#include <boost/static_assert.hpp>

template <class T> class mywrapper
{
  T _value;

  template <class V>
  typename boost::enable_if<boost::is_scalar<V>, void>::type printval_(V const& value)
  {
    BOOST_STATIC_ASSERT(boost::is_scalar<V>::value);
    std::cout << "scalar: " << value << std::endl;
  }

  template <class V>
  typename boost::enable_if<boost::is_compound<V>, void>::type printval_(V const& value)
  {
    BOOST_STATIC_ASSERT(boost::is_compound<V>::value);
    std::cout << "compound: " << value << std::endl;
  }

public:
  mywrapper(T const& value):_value(value) { }
  void printval() { printval_(_value); }
};

template class mywrapper<int>;
template class mywrapper<std::string>;

int main()
{
  mywrapper<int> ival(333);
  mywrapper<std::string> sval("test");

  ival.printval();
  sval.printval();
  return 0;
}

Comment: I don't have `boost` currently, but will that work with explicit instantiation as well? For example, just before `int main()` if you put `template mywrapper; template mywrapper;` and in each of the functions, you have a static assert to make sure you are working with scalar and compound types respectively; will it compile then?
Comment: Thank bobah! I'll test it out as soon as I can get `boost`.
Comment: If this solution meets your needs the standard `static_assert` and `enable_if` will work. You won't need boost unless you need one of the specific `is_*` templates that's not part of the standard.
Answer: I did not get an opportunity to test enable_if as suggested by bobah but I did come up with a solution that does not require boost and that satisfies my original requirement to a good extent (I say good and not full, will explain at the end)
The solution is to put a dummy template on the code that will fail if compiled under some selected types and is fine under others. So:
struct dummyStruct {};

#define DUMMY_TEMP typename dummy
#define DUMMY_PARAM dummyStruct

namespace Loki
{
  template<int> struct CompileTimeError;
  template<> struct CompileTimeError<true> {};
}

#define LOKI_STATIC_CHECK(expr, msg) \
{ Loki::CompileTimeError<((expr) != 0)> ERROR_##msg; (void)ERROR_##msg; }

template <typename T>
class foo
{
public:

  void func() {}
  template <typename T_Dummy>
  void func1() { LOKI_STATIC_CHECK(sizeof(T) == 4, Assertion_error); }
};

template foo<int>;
template foo<double>; // [1]

int main()
{
  foo<int> a;
  a.func1<DUMMY_PARAM>();

  foo<double> b;
  //b.func1<DUMMY_PARAM>(); //[2] - this is a static error

  return 0;
}

In all of my template code, these kind of functions (i.e. the ones that have static asserts OR work on some types and may fail on others by using type traits [in which case there is a selection of several different functions for different types]) are hidden from the client. So in my implementation, adding the extra dummy parameter is an OK compromise.
As a bonus, it lets me know that this function is designed to be used by only certain types. Furthermore, my original problem of explicit instantiation is solved by this simple technique.


Simple combination/probability question based on string-length and possible-characters

Question: Assuming "complete randomness" and given a string with a length of 20 characters where each character may be one of 62 possible characters:

What are the total number of combinations possible? (Guessing 20 to the power of 62.)
Also, if new strings are randomly selected one after another and added to a list of strings selected so far, how many strings must be selected before the chance of selecting a string that has already been selected is below 1-in-100000 ($10^{-5}$)?

Note: 62 comes from: numeric digits (0-9), uppercase letters (A-Z), and lowercase letters (a-z).
Comment: Your second bullet point can be read in (at least) two possible ways. I'm wondering which you're interested in. (**1**) The probability that the $n$th string matches one of the previous strings or (**2**) The probability that by the time the $n$th string is selected there exists *some* duplicate within the collection of strings drawn so far. The answers to these two questions will be ***very*** different. :)
Comment: Perhaps considering a two-character alphabet will make the difference clear. Let the letters be $H$ and $T$. We can ask: (**1**) For what $n$ do we have at least a 99% chance of the $n$th string being a duplicate of a previous string? The $n$ here is 8 since the only way we fail is if our sequence is either $TTT \cdots TH$ or $HHH\cdots HT$, which has total probability $2^{-(n-1)}$. Or, we ask (**2**) For what $n$ do we have at least a 99% chance of seeing some duplicate? In this case $n = 3$ since by the time we've seen three strings either $H$ or $T$ has been repeated at least once.
Comment: Matt's answer handles (**1**), which essentially answers the question about whether "my" string matches somebody else's. But, if you are worried about some other two people's strings *also* potentially matching, then you are interested in (**2**). It comes down to whether you have a particular string of interest that you're comparing all others to or whether you are comparing all strings to each other. I'm not sure if I'm making that any clearer, though. (Your problem boils down to one of two variants of the famous so-called "birthday problem".)
Comment: Cardinal is, as usual, correct. I assumed you had one "target" string, for which you were generating a list of guesses. If instead, you're generating strings at random and want to know the number it's safe to generate before any two strings match, then the answer is very different indeed. I'll amend my answer to address that case, if it's okay with you.
Comment: I didn't make my previous example completely clear. Sorry about that. I was thinking of a two-letter alphabet $\{H,T\}$ and drawing strings of *length one*. Hence, when I wrote $HHH\cdots HT$, that stood for $s_1 = H$, $s_2 = H$, ..., $s_{n-1} = H$, $s_n = T$.
Comment: @blunders (and cardinal). I added a bit about the collision problem and cleaned up the formatting a little bit. The first two sections are the same (but neater).
Comment: @cardinal: Believe the second, though to be honest, not completely sure what the difference in meaning is between the two possibilities you supplied are. Taking a step-back, the goal is to understand the risk a collision/duplication of a string will take place. The odds I selected were based simply on being able to say there's a 99.999% chance your string is not the same as another persons string. Does that help?
Comment: @cardinal: As you might expect, it's still a little unclear what the difference is, but limiting the scope of the character set did help. So, it does not matter is a character in any position is a repeat of another in another string, only that the string itself, meaning the whole sequence of characters in order that makes up the string itself are unique. For example, it would not matter that "CBA" and "ABC" share "B" in character position 2, or that they share (A,B,C) -- though it would matter if string 1 and 2 where "ABC". Does that help? +3 for the questions, since it's important to me.
Comment: +1 @Matt Krause: It's correct that there is not seed string for which then is compared to a growing list of randomly selected strings using the same generation parameters as the seed. The probability in question is how many randomly generated strings must be created using the profile supplied before the odds that the newly generated string will be a duplication of any of the other randomly generated strings reaches 1-in-100000.
Comment: +1 @cardinal: I see, makes sense, guess I reference to a coin-toss would have made the results length more clear, and also the odds, but it's now clear, and understand the use of how a 2-character set string with a length of one is the most simple example. Also, based on Matt Krause, appears you're correct that my question was unclear; in fact, it is now clear H/T stood for heads/tails. Thanks for pointing out the issue!
Answer: Total number of possibilities
1) Close! You've got 62 choices for the first character, 62 for the 2nd, etc, so you end up with $62 \cdot 62 \cdot 62 \cdot  \cdots 62 = 62^{20}$, which is an absurdly huge number.
Collision with a "Target" String
2) As we established above, there are $62^{20}$ potential strings. You want to know how many you'd need to guess to have better than 1 in 100,000 odds of guessing the "target" string. Essentially, you're asking what $$\frac{x}{62^{20}} \ge \frac{1}{10^5}$$To get it spot on, you'd have to round x up (or add one, if they're precisely equal), but as you'll see in a second, it doesn't really matter.
Through basic algebra, we can rearrange that as
$$\begin{aligned}
10^5x &\ge 62^{20}\\
10^5{x} &\ge (6.2 \cdot 10)^{20}\\
10^5x &\ge 6.2^{20} \cdot 10^{20}\\
x &\ge 6.2^{20} \cdot 10^{15}
\end{aligned}$$
Doing the  math, $6.2^{20}$ is about $7 \cdot 10^{15}$, so let's call the whole thing $7 \cdot 10^{30}$ or, more succinctly, a whole heck of a lot.
This is, of course, why long passwords work really well :-) For real passwords, of course, you have to worry about strings of length less than or equal to twenty, which increases the number of possibilities even more.
Duplicates in the list
Now, let's consider the other scenario. Strings are generated at random and we want to determine how many can be generated before there's a 1:100,000 chance of any two strings matching. The classic version of this problem is called the Birthday Problem (or 'Paradox') and asks what the probability that two of n people have the same birthday. The wikipedia article[1] looks decent and has some tables that you might find useful. Nevertheless, I'll try to give you the flavor for the answer here too.
Some things to keep in mind:
-The probability of a match and of not having a match must sum to 1, so $P(\textrm{match}) = 1 - P(\textrm{no match})$ and vice versa.
-For two independent events $A$ and $B$, the probability of $P(A \& B) = P(A) \cdot P(B)$.
To get the answer, we're going to start by calculating the probability of not seeing a match for a fixed number of strings $k$. Once we know how to do that, we can set that equation equal to the threshold (1/100,000) and solve for $k$.
For convenience, let's call $N$ the number of possible strings ($62^{20}$).
We're going to 'walk' down the list and calculate the probability that the $k$^{th} string matches any of the strings "above" it in the list. For the first string, we've got $N$ total strings and nothing in the list, so $P_{k=1}(\textrm{no match}) = \frac{N}{N} = 1$. For the second string, there are still $N$ total possibilities, but one of those has been "used up" by the first string, so the probability of a match for this string is $P_{k=2}(\textrm{no match}) = \frac{N-1}{N}$ For the third string, there are two ways for it a match and therefore $N-2$ ways not to, so $P_{k=3}(\textrm{no match}) = \frac{N-2}{N}$ and so on. In general, the probability of the $k$th string not matching the others is $$P_{k}(\textrm{no match})= \frac{N-k+1}{N}$$
However, we want the probability of no matches between any of the $k$ strings. Since all of the events are independent (per the question), we can just multiply these probabilities together, like this:
$$P(\textrm{No Matches}) = \frac{N}{N} \cdot \frac{N-1}{N} \cdot \frac{N-2}{N} \cdots \frac{N-k+1}{N}$$
That can be simplified a little bit:
$$\begin{aligned}
P(\textrm{No Matches}) &= \frac{N \cdot (N-1) \cdot (N-2) \cdots (N-k+1)}{N^k} \\
P(\textrm{No Matches}) &= \frac{N!}{N^k \cdot (N-k)!} \\
P(\textrm{No Matches}) &= \frac{k! \cdot \binom{N}{k}}{N^k} \\
\end{aligned}
$$
The first step just multiplies the fractions together, the second uses the definition of factorial ($k! = (k) \cdot (k-1) \cdot (k-2) \cdots 1$) to replace the products of $N-k+1 \cdots N$ with something a little more manageable, and the final step swaps in a binomial coefficient. This gives us an equation for the probability of having no matches at all after generating $k$ strings. In theory, you could set that equal to $\frac{1}{100,000}$ and solve for $k$. In practice, it's going to be difficult to an answer since you'll be multiplying/dividing by huge numbers--factorials grow really quickly ($100!$ is more than 150 digits long).
However, there are approximations, both for computing the factorial and for the whole problem. This paper[2] suggests $$ k = 0.5 + \sqrt{0.25 - 2N\ln(p)}$$ where p is the probability of not seeing a match. His tests max out at $N=48,000$, but it's still pretty accurate there. Plugging in your numbers, I get approximately $3.7 \cdot 10^{15}$.
References
[1] http://en.wikipedia.org/wiki/Birthday_problem
[2] Mathis, Frank H. (June 1991). "A Generalized Birthday Problem". SIAM Review (Society for Industrial and Applied Mathematics) 33 (2): 265–270. JSTOR Link
Comment: Glad to help! Let me know if anything's unclear. For kicks, I ran the numbers. You'll need 7044234255469980229683302646164 guesses; like I said--a lot!
Comment: +1 Awesome, given clearly my poor math skills resulted in asking the question, so I'll leave the question unanswered for a day, but looks good to me, and is way more clear of an answer than I expected - thank you!
Comment: +1 @Matt Krause: +1 to your comment below the answer; your answer and commitment to giving the best answer possible is exemplary, worthy of note, and thank you for all of your hard work!
Answer: I wrote a calculator for general cases of this problem. Let's say you have 6 unique characters (A,B,C,D,E,F) and each combination is 3 characters in length (e.g. "DBF", "EAC"...). If you have 12 samples, then the collision probability is 26.7%.
https://codepen.io/Walkipedia/pen/wvzeZeM


How to train for faster picking speed on guitar?

Question: I've been training on speed picking on major scale as my daily routine, following this Justin Guitar's guide on scale picking for one year since last year June, but until now my G major scale picking rooted on 3rd fret of E string still couldn't reach 4 notes per metronome click on 120bpm of speed, never improved since my max of 108bpm and average of 94/100bpm recently. I have one Cort semi-acoustic guitar and one MIM Standard Fender Telecaster, which I find Telecaster is more comfortable to train on since it has thinner strings.
Am I training in the wrong way? I spend 5 minutes per day on scale picking with few stops between the 5 minutes because muscles around my fretting thumb is exhausted/sore. The muscles are not supposed to be sore? And I think my main problem is on my right hand picking because I often picked at the wrong string especially when it's upward direction.
Many people recommending that the pick should be at 45 degree, but I find it not so comfortable while picking the strings(135 degree, which is 45 degree towards west from my view). The picking hand should be the rotating wrist(which is more relaxing and faster but less accurate) or powering upward and downward strum-like pattern using muscles around elbow(exhausts my arm and slower but more accurate)?
Someone please guide me through this. I'm learning guitar by myself and I really want to train well on it after 5 years of strumming and picking basics on guitar.
Comment: You should try to avoid using strength. Use the minimum pressure necessary to hold the pick, and the minimum pressure on your fretting fingers. Your thumb muscles shouldn't get sore. Proper sleep and nutrition are also important.
Comment: I use finger picking because its easier to hit more notes at once, and for me, the fatigue felt using a pick has a lot to do with why this is my preferred method. I am able to attain as much speed as my accomplished pick using friends. I play only acoustic though.
Answer: Do exercises for both left and right hand.
Exercises for pickig hand

16th notes as fast as you can on G string 5th fret. Start with 120bpm and raise by 10
Play triplets on the open strings, moving from low E to high E string. Start at 80bpm
Same triplets, but with string skipping. From string 6(low E) to 4, then 5 to 3, 4 to 2, 3 to 1 and back to low E.
Same exercises but then 16th notes, also start at 80bpm

Excercises for the fretting hand (also use a metronome)

spider excercise (you can find this on justin guitar or on youtube)
going up the ladder: playing each fret for each finger for all string. Just like doing the majer scale but then using no scale at all, pure speed building.
Practicing scales, major, minor pentatonic forms etc

You should keep track of your bpm for each excercise. Start 10bpm below for a minute and then practice on your current bpm where you can play it. After that raise by 10 bpm to push to the next level.
running trough these excercises should take about 30 minutes to an hour a day.
Answer: To add to what Jeroen has answered.
You need to do exercises that train your hands in more than just picking speed. That includes...
Vibrato exercises.
That includes wide and regular vibrato with the fingers and also by pivoting the wrists.
Slides / Glissando's
This is somewhat self explanatory. Also remember the backwards slide.
Hammer on's and Pull off's
To get truly shred level of speed you need to learn to add hammer on's in certain places. On electric guitar you can add a lot of speed to your playing by adding hammer on's in your runs. You need to practice hammering ons with the weak fingers as well. This will also help you with trills.
Scales starting on various fingers.
Don't get pigeon holed by only knowing your scales in the regular caged pattern. Start on your various left fingers and also do one, two and three string patterns in the various position.
We want you to be able to play your scales up and down the neck.
Answer: Assuming we're talking about alternate picking, there are basically two exercise methods for building speed.
The first and the better known one is to start slow. Set your metronome to a comfortable tempo and play the exercise a few times. Then go up 2 bpms or so and repeat. Continue alternating between plus two and minus one. Back down some 10 bpm when you hit your limit and work your way up from there again. You can go up 10 bpm or so from time to time just to see how it feels.
The second one is to practice in bursts. Start with two notes and play as fast as you can. Then add the third and continue from there. This method is not as well known as the first one but is every bit as useful. You can also start from the most difficult spot on the exercise and add notes on both sides.
Practicing scales only is probably not the best way to go. There are specially crafted exercise sets to build speed that isolate common patterns. Troy Stetina's book Speed Mechanics contains one such set.
In terms of technique, on your left hand, only apply enough pressure to avoid buzz. You'll get tired very quickly if you exert more force than necessary. The lighter your left hand touch is, the easier it is to play fast. It's easier said than done but that's the whole idea of practicing.
On your right hand, I wouldn't worry that much about wrist vs. elbow unless you're aiming for Guiness speed record. Wrist movement is probably a bit better but there's nothing wrong with a combination of wrist and elbow. Guitarists argue about it all the time but there are superb guitarists in both camps which proves that both techniques are equally viable. Just avoid finger movement, it doesn't work for fast playing.
Answer: The suggestions above are great. I would only add that once you've reached a 'desirable' speed with notes, you begin changing time signature. For example, once you got 4 notes licked at 4/4, begin practicing the following notes at 5/4, 6/4,7/4 etc. This way you don't get used to playing in a 'regular' tempo. The fingers will get used to phrasing riffs without getting used to most tunes which are in double or triple meter. Hope this helps.
Answer: I have an alternate suggestion, but you may not want to do this at first as it may actually interfere with your progress with more normal exercises (like the other fine answers here).
In addition to working on metered picking, there is also unmetered speed picking which is more like the tremolo technique used for melodies on the Mandolin.
Think Dick Dale's Pulp Fiction theme (I forget the real title) to get the idea, but don't copy his technique. He uses a great deal of force to achieve a distinctive sound. But using force this way is not a good idea for a beginner (or anybody, really).
Instead, for the best start, watch the old Humphrey Bogart movie To Have And Have Not (it's just as good as Casablanca, just less well known). Specifically, there's a scene with a Gypsy guitarist in the Café. The technique she uses is a very fast tremolo strum with the flats of her fingertips. Of course, the notes are not ringing since the vibration is constantly being stopped by another finger. Basically, each string of the chord is going through a very fast cycle of ring -> mute -> ring -> mute -> ring -> mute.
Practicing this finger-strum technique will help you work on the balance between the muscles of the wrist and forearm and higher-up in the shoulder as well. But the musical effect is not strictly about super-speed but fluidity and supporting a singer with a very free rubato, almost no time at all.
Next, grab the pick and try doing a tremolo on one string with heavy palm-muting. We want to stop as much ringing as possible with the muting so the string doesn't move around so much. This makes it easier for the pick to "find" the string in the reverse direction and should help avoid increasing the tension in the muscles. Use a thick string and fret it very high up the neck, too, to reduce the string's vibration further. I'd recommend a thick pick with a dull tip for this, too. It should have less drag than other kinds.
Next, try a mandolin-style tremolo melody, even just running scales will work. Now, we're deliberately not counting notes here. Up-and-down-and-up-and-...-down-and-up-and. Don't count in the middle, but pay attention to the very last stroke of one note and the start of the next. If you're changing frets on the same string, I think it works best to start the new note with a down-stroke. If you're switching strings, however, it's best to sweep into it. So, a down-sweep if you're going up a string (in pitch). And an up-sweep if you're going down a string (in pitch).
Next, try with different pick thicknesses/pointinesses. A thinner pick, a sharper pick. These will all drag differently, losing more or less energy to the string, requiring more or less muscular power/control to compensate.
So I'd recommend following the other, metered suggestions for a few months or even a year. Then, when you hit a plateau with that effort, come back and attack it from a different angle. Do this for a few weeks or months without doing the normal metered exercises. When you go back to them, you should find yourself back on the mountain again. :)


@JsonIgnoreProperties usage for both known and unknown properties

Question: My current annotation for ignoring the known properties for a JPA entity is:
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler","created","updated","createdBy","lastUpdatedBy"})

In addition to ignoring these class properties, I would also like to ignore any unknown properties that the server receives. I know the alone way to ignore the unknown properties by the following annotation:
@JsonIgnoreProperties(ignoreUnknown=true)

But not sure how to add this to my current annotation given above. I tried multiple methods ås below but none seem to work and I could not find an example online for this scenario.
Any example or leads on documentation would also help.
Comment: @CássioMazzochiMolin yes it does. Thank you!
Answer: Set ignoreUnknown to true and define the names of properties to ignore in the value element:
@JsonIgnoreProperties(ignoreUnknown = true,
                      value = {"hibernateLazyInitializer", "handler", "created"})

How does it work?
Have a look at this quote from the documentation (highlight is mine):

In its simplest form, an annotation looks like the following:
@Entity

The at sign character (@) indicates to the compiler that what follows is an annotation. In the following example, the annotation's name is Override:
@Override
void mySuperMethod() { ... }

The annotation can include elements, which can be named or unnamed, and there are values for those elements:
@Author(name = "Benjamin Franklin", date = "3/27/2003")
class MyClass() { ... }

or
@SuppressWarnings(value = "unchecked")
void myMethod() { ... }

If there is just one element named value, then the name can be omitted, as in:
@SuppressWarnings("unchecked")
void myMethod() { ... }

Other way to handle unknown properties
To ignore unknown properties, you also could do:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

Comment: Why isn't `ignoreUnknown=false` working? https://stackoverflow.com/questions/56052262/how-do-i-enable-strict-validation-of-json-jackson-requestbody-in-spring-boot
Comment: @Chloe `false` is the default value https://fasterxml.github.io/jackson-annotations/javadoc/2.6/com/fasterxml/jackson/annotation/JsonIgnoreProperties.html#ignoreUnknown()


Erro de condição do PyCharm

Question: Estou tendo erro de condição no PyCharm. Estava funcionando normalmente minutos atrás. Já fechei o programa, porem não resolveu.
valorProduto = float(input('Qual é o valor do produto de compra? R$ '))
modoPagamento = input('Deseja parcelar ou pagar à vista? ')

if modoPagamento == 'à vista' or 'À vista':
    desconto = valorProduto - (valorProduto * 20 / 100)
    print('Certo! Nesse caso, você recebe-rá 20% de desconto.')
    print('O novo preço do produto é R${:.2f}'.format(desconto))

elif modoPagamento == 'parcelar' or 'parcela':
    print('Certo! Pagamento parcelado. Segue abaixo tabela de parcelamentos:')
    print('=' * 10, 'Tabela', '=' * 10, '\n2 à 3 parcelas, acréscimo de 5%.\n4 à 6 parcelas, acréscimo de 10%.'
                                      '\n7 à 10 parcelas, acréscimo de 15%.\n11 parcelas ou mais, acréscimo de 25%.')
    parcela = int(input('Deseja fazer em quantas parcelas? '))

    if parcela <= 3:
        valorParcela = ((valorProduto / parcela) + ((valorProduto * 5) / 100))
        preçoFinal = valorParcela + valorParcela
        print('Certo! {} vezes. Nesse caso, você receberá um acréscimo de 5% sobre o valor do produto.\nTotalizando'
              ' {} parcelas de R${:.2f} com o preço final do produto de R${:.2f}'.format(parcela, parcela, valorParcela,
                                                                                preçoFinal))

    elif parcela <= 6:
        valorParcela = (valorProduto / parcela) + ((valorProduto * 10) / 100)
        preçoFinal = valorParcela + valorParcela
        print('Certo! {} vezes. Nesse caso, você receberá um acréscimo de 10% sobre o valor do produto.\nTotalizando'
              ' {} parcelas de R${:.2f} com o preço final do produto de R${:.2f}'.format(parcela, parcela, valorParcela,
                                                                                preçoFinal))

else:
    print('Modo de pagamento inválido!')

Comment: Seu problema parece ser o mesmo que esse: https://pt.stackoverflow.com/q/353470/112052
Comment: Segui as dicas do Anderson Carlos Woss, mas não consegui resolver o problema ainda. É como eu comentei. Tempinho atrás estava funcionando normalmente if e elif com outro programa. agora parou de funcionar em qualquer programa no que criar. em qualquer newfile.
Comment: @Jones Se o seu problema foi solucionado, não deixe de marcar a resposta como aceita.
Answer: Dias atrás eu tive dúvida parecida e o Anderson Woss me respondeu brilhantemente neste post aqui: Dificuldades com uso do IF.
Seu problema é basicamente o mesmo que o meu. Copiei o seu código, colei aqui e coloquei pra rodar, de início ele sempre entrava no if do à vista, mesmo que eu escolhesse a opção de parcelamento, conforme imagem a seguir:

Então fiz alterações na seguinte linha de código:
if modoPagamento == 'à vista' or 'À vista':

Mudei para:
if modoPagamento in {'à vista','À vista'}:

E, por consequência, também fiz alteração nesta linha:
elif modoPagamento == 'parcelar' or 'parcela':

Mudei para:
elif modoPagamento in {'parcelar','parcela'}:

Agora o programa já me apresenta as opções de parcelamento caso eu escolha a opção de  pagar parcelado, conforme mostra a imagem abaixo:

Reparei também que seu programa está com um erro quando o usuário escolhe a opção de pagar parcelado. Repare na imagem a seguir:

Repare que eu optei em pagar em 3 vezes um produto que custa 1000 reais e mesmo com o acréscimo de 5% devido ao parcelamento o preço do produto final ficou em 766,67. Isto ocorreu devido a um erro na construção matemática da solução e não exatamente devido a um erro no programa, por isso não vou me preocupar em corrigir, mas repare que poderia ser feito de uma forma mais sucinta, conforme mostro a seguir:
if parcela <= 3:
    valorProduto = valorProduto * 1.05 #Multiplicando por 1,05 você já aumenta o preço final do produto em 5%
    valorParcela = (valorProduto / parcela)
    print('Certo! {} vezes. Nesse caso, você receberá um acréscimo de 5% sobre o valor do produto.\nTotalizando {} parcelas de R${:.2f} com o preço final do produto de R${:.2f}'.format(parcela, parcela, valorParcela, valorProduto))

Seu código final ficou assim:
valorProduto = float(input('Qual é o valor do produto de compra? R$ '))
modoPagamento = input('Deseja parcelar ou pagar à vista? ')

if modoPagamento in {'à vista','À vista'}:
    desconto = valorProduto - (valorProduto * 20 / 100)
    print('Certo! Nesse caso, você receberá 20% de desconto.')
    print('O novo preço do produto é R${:.2f}'.format(desconto))

elif modoPagamento in {'parcelar','parcela'}:
    print('Certo! Pagamento parcelado. Segue abaixo tabela de parcelamentos:')
    print('=' * 10, 'Tabela', '=' * 10, '\n2 à 3 parcelas, acréscimo de 5%.\n4 à 6 parcelas, acréscimo de 10%.'
                                  '\n7 à 10 parcelas, acréscimo de 15%.\n11 parcelas ou mais, acréscimo de 25%.')
    parcela = int(input('Deseja fazer em quantas parcelas? '))

    if parcela <= 3:
        valorProduto = valorProduto * 1.05
        valorParcela = valorProduto / parcela
        print('Certo! {} vezes. Nesse caso, você receberá um acréscimo de 5% sobre o valor do produto.\nTotalizando {} parcelas de R${:.2f} com o preço final do produto de R${:.2f}'.format(parcela, parcela, valorParcela, valorProduto))

    elif parcela <= 6:
        valorProduto = valorProduto * 1.10
        valorParcela = valorProduto / parcela
        print('Certo! {} vezes. Nesse caso, você receberá um acréscimo de 10% sobre o valor do produto.\nTotalizando {} parcelas de R${:.2f} com o preço final do produto de R${:.2f}'.format(parcela, parcela, valorParcela, valorProduto))

    elif parcela <= 10:
        valorProduto = valorProduto * 1.15
        valorParcela = valorProduto / parcela
        print('Certo! {} vezes. Nesse caso, você receberá um acréscimo de 15% sobre o valor do produto.\nTotalizando {} parcelas de R${:.2f} com o preço final do produto de R${:.2f}'.format(parcela, parcela, valorParcela, valorProduto))

    elif parcela > 10:
        valorProduto = valorProduto * 1.25
        valorParcela = valorProduto / parcela
        print('Certo! {} vezes. Nesse caso, você receberá um acréscimo de 25% sobre o valor do produto.\nTotalizando {} parcelas de R${:.2f} com o preço final do produto de R${:.2f}'.format(parcela, parcela, valorParcela, valorProduto))

Espero ter conseguido te ajudar.

Erro de condição do PyCharm


Various definitions for a branch of logarithm

Question: I am confused by the definitions put up for a branch of logarithm. I have two questions in mind.

Why do some books define a branch on just an open subset whereas some books define it on an open connected subset?
Why some texts define a branch to be continuous but then some texts take the extra leap and define the branch to be a holomorphic function?

Here are some examples.
In Sarason's Complex Function Theory, it states the definition:

Let $G$ be an open connected subset of $\mathbb{C}-\{0\}$. A branch of $\log z$ in $G$ is a continuous function $\ell$ in $G$ such that for each $z \in G$, $\ell(z)$ is a logarithm of $z$.

In Ivan Wilde's Lecture Notes on Complex Analysis, we have:

A branch of the logarithm is a pair $(D, f)$, where $D$ is a domain (an open connected subset of $\mathbb{C}$) such that $0 \notin D$ and $f: D \to \mathbb{C}$ is continuous and satisfies $e^{f(z)} = z$ for all $z \in D$.

In Stein-Shakarchi's Complex Analysis, we have:

Suppose that $\Omega$ is simply connected with $1 \in \Omega$, and $0 \notin \Omega$. Then, in $\Omega$ there is a branch of logarithm $F(z) = \log_\Omega z$ so that $F$ is holomorphic in $\Omega$ and $e^{F(z)} = z$ for all $z \in \Omega$.

In lecture notes I found online:

Let $\Omega \subset \mathbb{C} - \{0 \}$ be open. Then, a branch of $\log z$ on $\Omega$ is a holomorphic function $L: \Omega \to \mathbb{C}$ such that $e^{L(z)} = z$ for every $z \in \Omega$.

A lot of the definitions assume that the logarithm is defined on a domain/region/open-connected subset of $\mathbb{C}$. Why is this so? Moreover, what do we lose if we define it on just an open, not necessarily connected subset of $\mathbb{C}$? Would this be the same case to as why we sometimes define holomorphic functions just on an open set rather than on a domain?
The only thing that I could think why assuming connectedness is important is to be more careful in the sense that the branch wouldn't take two different values on different subsets whose union is the subset where the branch is defined.
Similarly, what do we lose if we define the branch to be just a continuous function rather than a holomorphic one?
Comment: Arguments and logarithms of functions don't have to be holomorphic. In fact, functions can be defined general spaces, for example $g:X\rightarrow\mathbb{C}\setminus\{0\}$ with $X$ a nice topological space, and define logarithms of $g$ as a function $f:X\rightarrow\mathbb{C}$ such that $\exp\circ f=g$. For $X=\mathbb{R}^n$ and $X=[a,b]$, this objects exists.
Answer: This is a old question for which I would like to add a few things. I will focus on the first two definitions outlined in the OP for they are not fully discussed in many courses in Complex Analysis where the main objective is the study of analytic (holomorphic) functions, and also because that are more general in nature.
Overview of basic concepts:

Recall that any $w\in\mathbb{C}\setminus\{0\}$ can be expressed as
$$w=|w|e^{i\theta}$$
for some $\theta\in\mathbb{R}$, where $|w|=\sqrt{\operatorname{Re}^2(w) +\operatorname{Im}^2(w)}$. The set
$$\operatorname{Arg}_w:=\{\theta\in\mathbb{R}: w=|w|e^{i\theta}\}$$
is the called the set of arguments of $w$. It is easy to check that if $\theta_1,\theta_2\in\operatorname{Arg}_w$, then $\theta_1-\theta_2\in 2\pi i\mathbb{Z}$. One may think of the argument as a relation $\operatorname{Arg}=\{(w,\theta)\in(\mathbb{C}\setminus\{0\})\times\mathbb{R}:w=|w|e^{i\theta}\}$.
Give $\theta_0$, for any $w\in\mathbb{C}\setminus\{0\}$, there is a unique $\theta_w\in[\theta_0,\theta_0+2\pi)\cap\operatorname{Arg}_w$. The map $\operatorname{arg}_{\theta_0}:\mathbb{C}\setminus\{0\}\rightarrow[\theta_0,\theta_0+2\pi)$ given by $w\mapsto\theta_w$ is called a branch of the argument.
The relation  $\operatorname{Log}$ from $\mathbb{C}\setminus\{0\}$ to $\mathbb{C}$ such that $(w,z)\in \operatorname{Log}$ iff $e^z=w$ is called logarithm. For $w\in\mathbb{C}\setminus\{0\}$, the set $\operatorname{Log}_w=\{z\in\mathbb{C}: (w,z)\in\operatorname{Log}\}$ is called the set of logarithms of $w$. It is easy to check that
$$\operatorname{Log}_w =\{ \ln|w|+i\theta:\theta\in\operatorname{Arg}_w\}$$
where $\ln:(0,\infty)\rightarrow\mathbb{R}$ is the natural logarithm function from Calculus or Real analysis.
Selecting a brach $\theta_0$ of $\operatorname{Arg}$ yields a function $\log_{\theta_0}:\mathbb{C}\setminus\{0\}\rightarrow\mathbb{C}$, given as $w\mapsto \ln|w|+i\operatorname{arg}_{\theta_0}(w)$, where $\theta\in[\theta_0,\theta_0+2\pi)$. The map $\log_{\theta_0}$ is called a branch of logarithm.

Continuous logarithm:
In many applications, one is interested in the possibility of selecting a single choice of $\operatorname{Arg}_z$ for each element $z$ on a domain $D\subset\mathbb{C}\setminus\{0\}$ continuously. This is not always possible, for example, there is not continuous choice of argument for $D=\mathbb{C}\setminus\{0\}$.

For $\theta_0\in\mathbb{R}$, define $L_{\theta_0}=\{re^{\theta_0 i}:r\geq0\}$. Using the properties of the exponential function along with the inverse function theorem from multivariate Calculus, it is easy to check that $\log_{\theta_0}:\mathbb{C}\setminus L_{\theta_0}\rightarrow(\mathbb{R}\times(\theta_0,\theta_0+2\pi)$, given by $w\mapsto\ln|w|+i\operatorname{arg}_{\theta_0}(w)$ is holomorphic and its inverse is the exponential function $\exp$.  This fact can be used to construct continuous choices of arguments (and thus of logarithms).

Example 1: Suppose $w\in\mathbb{C}\setminus\{0\}$, and let $\alpha\in\operatorname{Arg}_w$. Then $B(w;|w|)\subset\mathbb{C}\setminus L_{\alpha+\pi}$. This means that the restriction of $\log_{\alpha+\pi}$ to $B(w;|w|)$ is continuous (in fact, holomorphic) and $\exp(\log_{\alpha+\pi}(z))=z$ for all $z\in B(w;|w|)$. Consequently,  the map $\arg_{\alpha+\pi}(z)=\log_{\alpha+\pi}(z)-\ln(|z|)$ on $B(w;|w|)$ is a continuous function such that $\arg_{\alpha+\pi}(z)\in\operatorname{Arg}_z$ for all $z\in B(w;|w|)$.

The following is a slightly more general definition to definition in Ivan Wilde's Lecture Notes on Complex Analysis.

Definition Suppose $X$ is a path connected topological space, and $\phi:X\rightarrow\mathbb{C}\setminus\{0\}$ a continuous function. A continuous  branch of $\operatorname{Log}_\phi$ is continuous function $f:X\rightarrow\mathbb{C}$ such that $\exp\circ f=\phi$. Similarly, a continuous brach of $\operatorname{Arg}_\phi$ is a function $\alpha:X\rightarrow\mathbb{R}$ such that $\alpha(x)\in\operatorname{Arg}_{\phi(x)}$ (equivalently $f(x)=\ln(|\phi(x)|)+i\alpha(x)\in\operatorname{Log}_{\phi(x)}$).

It is a well known and important result in Complex Analysis that when  $g$ is a Holomorphic function on a simply connected domain $D$ and $g\geq0$, then there is a Holomorphic function $f$ on $D$ such the $\exp\circ f=g$. The function $f$ is of course a continuous choice of logarithm of $g$. Any other continuous choice $h$ of $\operatorname{Log}_g$  will differ from $f$ by a integer multiple of $2\pi$ and so $h$ will also be Holomorphic on $D$.

I will present two situations of continuous logarithms that are found in applications: logarithms of paths in $\mathbb{C}\setminus\{0\}$, and distinguished logarithms of continuous functions from $\mathbb{R}^n\rightarrow\mathbb{C}\setminus\{0\}$. I will only focused on the former for they form the foundation of the latter, and of many other results in complex analysis.
The key to define logarithm branches of functions is the following result for paths:

Theorem 1: Let $\gamma:[a,b]\rightarrow\mathbb{C}\setminus\{0\}$ a path (continuous function). There exists a continuous function $\theta:[a,b]\rightarrow\mathbb{R}$ such that $\theta(t)\in\operatorname{Arg}_{\gamma(t)}$ for all $t\in[a,b]$. Furthermore, if $\psi:[a,b]\rightarrow\mathbb{R}$ is another continuous choice of argument of $\gamma$, then
$$\theta(b)-\theta(a)=\psi(b)-\psi(a)$$
If in addition $\gamma$ is a closed path ($\gamma(a)=\gamma(b)$), then $\frac{\theta(b)-\theta(a)}{2\pi}$ is an integer that depends only on $\gamma$.

Before giving some details about the proof of this important result, I state one important consequence of Theorem 1. Denone by $\gamma^*=\gamma([a,b])$. Notice that for any $w\in\mathbb{C}$, $w\notin \gamma^*$ iff $0\notin (\gamma-w)^*$.

Definition: Let $\gamma:[a,b]\rightarrow\mathbb{C}$ a path and suppose $w\notin\gamma^*$. The index of $\gamma$ around $w$ is defined by
$$\operatorname{Ind}_\gamma(w)=\frac{\theta(b)-\theta(a)}{2\pi}$$
where $\theta$ is any branch of $\operatorname{Arg}_{\gamma-w}$ on $[a,b]$. If $\gamma$ is closed, then $\operatorname{Ind}_\gamma(w)$ is an integer also known as the winding number of $\gamma$ around $w$.

Remark: when $\gamma$ in the definition above is continuous and piecewise differentiable, it can be seen that for any $w\notin\gamma^*$
$$ \operatorname{Ind}_\gamma(w)=\frac{1}{2\pi i}\int_{\gamma}\frac{1}{z-w}\,dz=\frac{1}{2\pi i}\int^b_a\frac{\gamma'(s)}{\gamma(s)-w}\,ds$$
and the for any $p\in\operatorname{Log}_{\gamma(a)-w}$, $f(t)=\int^t_a\frac{\gamma'(s)}{\gamma(s)-w}\,ds+p$ is a continuous branch of $\log_{\gamma-w}$.

Sketch of proof of Theorem 1: Since $\gamma$ is continuous on $[a,b]$ and $0\notin\gamma^*$,
$$d(0,\gamma^*)=\inf_{a\leq t\leq b}|\gamma(t)|>0,$$
and $\gamma$ is uniformly continuous. Fix $0<\varepsilon<d(0,\gamma^*)$. There is $\delta>0$ such that $|t-s|<\delta$ implies $|\gamma(t)-\gamma(s)|<\varepsilon$. Let $a=t_0<t_1<\ldots<t_n=b$ be a partition of $[a,b]$ such that $|t_{j+1}-t_j|<\delta$ for $0\leq j<n$. Let $z_j=\gamma(t_j)$. The choice of the partition implies that $\gamma([t_j,t_{j+1}])\subset B(z_j;\varepsilon)$, and that $0\notin B(z_j;\varepsilon)$ for all $0\leq j <n$.
As in Example 1, for each $0\leq j\leq n$ there is a continuous choice $\operatorname{arg}_j$ of argument on $B(z_j;\varepsilon)$. Hence $\theta_j=\arg_j\circ \gamma$ on $[t_j,t_{j+1}]$ is a continuous branch of $\operatorname{Arg}_\gamma$ on $[t_j,t_{j+1}]$.
$\theta_0$ and $\theta_1$ may not coincide at $t_1$; however, since $\theta_0(t_1)$ and $\theta_1(t_1)$ are both arguments of $z_1$, $$\theta_0(t_1)-\theta_1(t_1)=2\pi n_1$$
for some $n_1\in\mathbb{Z}$. Define
$$\theta(t)=\left\{\begin{matrix} \theta_0(t) & t_0\leq t\leq t_1\\
\theta_1(t)+2\pi n_1 & t_1\leq t\leq t_2\end{matrix}\right.$$
This defines a continuous choice of argument for $\gamma$ on $[t_0,t_2]$. We extend $\theta$ continuously as follows. Suppose we have extended $\theta$ continuously on $[t_0,t_k]$, $k<n$, so that $\theta$ on $[t_0,t_k]$ is a continuous choice of argument of $\gamma$ on $[t_0,t_k]$, Since $\theta(t_k)$ and $\theta_k(t_k)$ are both arguments of $z_k$,
$$\theta(t_k)-\theta_k(t_k)=2\pi n_k$$
for some $n_k\in\mathbb{Z}$. Then, defining $\theta(t)=\theta_k(t)+2\pi n_k$ for $t\in[t_k,t_{k+1}]$ yields a continuous choice of argument for $\gamma$ on $[t_0,t_{k+1}]$. Proceeding this way, we obtain a continuous choice of $\operatorname{Arg}_\gamma$ $\Box$.

A nice treatment of Complex Analysis that exploits the concept of arguments is Beardon, A. F., Complex Analysis: The Argument Principle in Analysis and Topology, John Wiley & Sons. New York, 1979.

Here I only state a more general result about distinguished logarithms.

Theorem 2: Suppose $g:\mathbb{R}^n\rightarrow\mathbb{C}\setminus\{0\}$ is a continuous function an that $g(\boldsymbol{0})=1$. There exists a unique continuous function $f:\mathbb{R}^d\rightarrow\mathbb{C}$ such that $f(\boldsymbol{0})=0$ and $\exp\circ f= g$.
The function $f$ is called a distinguished logarithm of $g$.

A proof of this result may be found in Sato, K. Levy Processes and Infinitely Divisible Distributions, Cambridge University Press, 1999. pp. 33-34. Distinguished logarithms  are used in the analysis of characteristic functions and the study of infinitely divisible measures in Probability.
Answer: Usually, the domain of a holomorphic function is connected. Otherwise, what happens in a connected component is disconnected (pun intended) with what happens in the other ones. But no harm is done if we just assume that the domain is any non-empty open set.
And, in this context, being holomorphic and being continuous is the same thing. That's so because any branch of the logarithm has a left inverse (the exponential function) which is holomorphic and whose derivative is non-zero everywhere; every continuous map with such a left inverse is holomorphic. So, there is, in fact, no difference between these two definitions.
Comment: It may be useful to note that any open set in $\mathbb{C}$ can be seen as the disjoint countable union of connected open sets,  which is why the two definitions are equivalent
Comment: since any open set can be partitioned into countably infinite many open connected sets, does this imply that the phenomenon "the branch take different values on different open connected subsets whose union is where the branch is defined" would never happen? Or it is still possible that this could happen? If this could happen, then why is there no harm done here? Thanks in advance!


In Euclidean space, can open ball be written as the direct product of open sets?

Question: Let $a=(a_1,\cdots,a_n)\in \mathbb R^n, $ $B(a,r)=\{ x\in \mathbb R^n \mid \| x-a\|<r \}$.
Can $B(a,r)$ be written as the direct product of open sets in $\mathbb R$,
i.e., are there $U_1, \cdots, U_n \in \mathcal O_{\mathbb R}$ s.t. $B(a,r)=U_1\times \cdots \times U_n$ ?
$B(a,r)$ is $B(a,r)=\{(x_1,\cdots,x_n)\mid x_i\in \mathbb R, \sqrt{(x_1-a_1)^2+\cdots+(x_n-a_n)^2}<r\}$, and I have difficulty in finding such $U_i.$ For example, $U_i=\{y\in \mathbb R \mid |y-a_i|<r\}$ doesn't work.
Comment: @SassatelliGiulio Do not answer questions via commments, write proper answers. Copy and paste will do here.
Comment: @PaulFrost 1) No, for my standards it wouldn't have been enough. 2) I want my answers on this site to be easily accessible to me, so I can't quite answer frequently. 3) When I leave a sketch of proof like it was (and isn't anymore) in this case, people can just take the idea and use it themselves: I sure don't mind.
Answer: It can't.
For convenience, assume that $n=2$. And assume that there exists open sets
$U, V$ in $\mathbb{R}$ such that $B(0,1) = U \times V$, i.e.,
$$ B(0,1) = \{ (u,v) ~ : ~ u \in U, ~ v \in V \} . $$
If $-1 < x < -1$, then there exists $-1 < y_x < 1$ such that $(x, y_x) \in B(0,1)$.
Thus $(x, y_x) \in \{ (u,v) ~ : ~ u \in U, ~ v \in V \}$ for every $-1< x< 1$.
It implies that the open interval $(-1, 1) \subset U$.
(Because if $-1 < t < 1$, then $(t, y_t) \in U \times V$,
which implies that $t \in U$ and $y_t \in V$.
Thus $(-1,1) \subset U$.)
In the same way, we obtain that $(-1, 1) \subset V$.
However, we know that $B(0,1) \subsetneq (-1,1) \times (-1,1)$.
Thus, it can't.


Recommend a DB to process large data from MySQL

Question: Basically, right now I'm working with data that has reached 1+ TB on MySQL and I need to run a statistical algorithm on it in the future. I also need to process the data as well.
What I'm hoping to do is port it over to a NoSQL database. I was looking either at Redis or MongoDB. Another thought would be to use Hadoop.
The data itself is composed of some JSON fields and also int values mainly. The data does not need to stay in the same form, actually I will change it anyway so I can work(hopefully) with the transformations needed to go to NoSQL.
I was wondering what recommendations people had to do this? Advantages/disadvantages? I will be creating the algorithm itself in Python or R by the way.
Thanks
Comment: That will be a tough problem to do in R (open source) or Python. Try to build your algo on a sample instead.
Comment: The [datascience](http://datascience.stackexchange.com/) SE may be a better venue for this question?
Answer: At 1TB, I'd say Hadoop is an overkill. MongoDb is ok, you can get reasonable query performance and at the same time also be setup to scale reasonably easily. Mongo has bindings for Python for sure. But remember that Mongo is a general purpose NoSQL database and you will not find out of the box support for many ML tasks like the Hadoop ecosystem does.
It is therefore a tradeoff between convenience (Mongo is easy to get to from MySQL) and long term requirements.
I don't have any personal experience with redis, but it is primarily an in memory store.


Autodesk.Forge : Design automation App Bundle not loaded

Question: i'm working on this tutorial here and also used the one on github here
All works fine but the web app is not loading (in UI) the zip into "bundles" folder, but when i call /api/appbundles/ i got this
<code>[
  "UpdateDWGParam",
  "UpdateIPTParam",
  "UpdateMAXParam",
  "UpdateRVTParam"
]
</code>
Any idea ?
Comment: This seems interesting, the UI uses same endpoint as /api/appbundles/, quick idea, did you debug into the code to see if any issues? Or maybe a refresh to see if help?
Comment: Hi thank you, i tryed debugging but nothing special, i thought that something was missing on js (who make the ui i think) then found that the filename was not spelled well ^^ sorry
Answer: Make sure that the js file is loaded correctly, check the file name and path.


Simplenews Scheduler - only send newsletter when attached EVA view contains results

Question: Simplenews Scheduler is working well for me to send a weekly email which contains an attached view (using EVA) of nodes.
I would like the newsletter to only send if the attached view contains nodes, so that empty newsletters are not sent.
I can see that this should be possible using the 'Additionally only create newsletter edition if the following code returns true' field on the Newsletter > Send newsletter according to schedule page.
I am currently using this (which always produces a newsletter regardless of whether nodes are displayed in the view):
if(views_get_view('job_type_c_list')) {
      return true;
}

I have tried using the overall length of the node body to try to work out if a view is present. (I don't know if the tokens can be used in this field or not):
if(views_get_view('job_type_c_list')) {
     $myvar = [node:body:?];
     if(strlen($myvar) >= 30) {
           return true;
      }
}

When i was working with PHP in the body of the node I was able to evaluate whether EVA was returning nodes by using
<?php
    $view = views_get_view('job_type_c_list');
    $printedview = $view->preview('default');

    $myvar = (string)$printedview;

    if(strlen($myvar) >= 1000) {
           print "VIEW ATTACHED";
    }

    else if(strlen($myvar) < 1000) {
           print "NO VIEW ATTACHED";
    }
?>

The above code is clearly not the most elegant, but it worked in the node itself. Unfortunately it didn't work in the 'Additionally only create newsletter edition if the following code returns true' Simple news scheduler field.
I have struggled with this for quite some time and would really appreciate some help.
Code suggestions would be great, but failing that knowing 'If I can use tokens in the field?' and 'why does the PHP in this field behaves differently to PHP the node itself?' would also be very helpful.
I have had an issue open in the module issues page for a few days now, but it has not received any responses.
Answer: did you find out a way to do it? In your example, using views_get_view will always return true, because even if the view has no result, the result of the function will be an object, so will not be empty. If you're using views_get_view, you will always have a
 inside.
You should get the view, then do a preview and then check if there is results or not.
Like this:
 $view = views_get_view('view_id');
 $print_view = $view->preview('display_id');
 if(!empty($view->result)) {
   print $print_view;
 }

I would be happy to know if you found a solution to this because I will face the same problem in a couple of days, thanks!


App Store: Problem with UIRequiredDeviceCapabilities

Question: I've uploaded my first App to App Store, but I did NOT put on the UIRequiredDeviceCapabilities that my App requires location-services and wifi. RESULT: the app does not start looking for the coordinates as it should do. (When I've installed the App through XCode in my iPhone 4 it works perfectly).
So, I've tryed to upload a new version with this UIRequiredDeviceCapabilities correctly set, and I got following error message after trying to Upload the new version:
"The Bundle is invalid. The key UIRequiredDeviceCapabilities in the Info.plist may not contain values that would prevent this Application from running on devices that were supported by previous versions."
So, as I understood, I am NOT able to set the UIRequiredDeviceCapabilities to this App anymore, is that right?
My idea was: I delete this App, and after that I go through all the steps to submitt the App to the App Store again. But when I clicked on the "Delete this App" button, I got following error message:
"Deleting it will permanent remove it from iTunes Connect along with any associated in App Purchases. The Application Name and SKU will not be reusable, even once the application is deleted."
That's very bad, cause I can't change the name of my App. What Can I do to be able to upload a new version of my App with the new UIRequiredDeviceCapabilities?
Comment: have you find the answer mate as i am facing the same problem..thanxs bro
Answer: For me I ran into this issue when I recently added HealthKit to my app. I fixed it by removing this row on info.plist.
Answer:
Rename your app in iTunes Connect by submitting a new update which changes the App name.
Create a new App in iTunes Connect and enter the original name of your App. (The original name of the App you renamed in step 1)
Delete your old app which you have renamed in step 1

Using that trick you can realize your idea. ;-)
The only loss is that you have to enter all your app's meta data again. And don't forget that you will loose the reviews and ratings your customers left on the App Store. (BTW, a good way to get rid of bad reviews. ;-) )
Comment: Yeah, you are right. I forgot to mention that: You have to rename your app by submitting an update. I have already done that, so I'm pretty sure it will work. I updated my answer. Thanks.
Comment: create a whole new app!?!? is that a real solution for something like this? what's really going on here?
Comment: I just gained this problem but you can't rename apps in itunes connect. At least I can't. I can rename the pending update but not the actual app.
Comment: i am facing the same problem but my client will never entertain making a new app with new name..


How to use the definition of supremum to prove that $\sup{S} = 2$?

Question: Let $S$ $=$ {$2-\frac{3}{n+1} | n\in \mathbb{N}$}. Use the definition of supremum to prove that $\sup{S} = 2$.
Here's what I have so far. We want to show that $2$ is an upper bound, and it is also the least upper bound.
We know $2$ is an upper bound because, $2 - \frac{3}{n+1} < 2 \text{, for all } n \in \mathbb{N}$
But how do I show it's the least upper bound? Someone tried explaining it to me, and I still don't really understand.
Comment: Pick any $c < 2$ and show that $c$ is not an upper bound. Writing $c = 2-\varepsilon$ may help finding a proof.
Comment: Here is a useful characterization of a supremum: given any $\varepsilon > 0$, there exists an $x \in S$ such that $\sup S - x < \varepsilon$. Does that help you?
Answer: Assume that there is a LOWER bound, $2-\epsilon$, $\epsilon>0$. Then for all $n\in\mathbb{N}$
$$2-\frac{3}{n+1}<2-\epsilon$$
or
$$\epsilon<\frac{3}{n+1}$$ for ALL $n$. Can you take it from here?
Edit, let me do more algebra for you. This is equivalent to:
$$n<\frac{3}{\epsilon}-1$$
You're assuming this is true for ALL natural numbers. What's the problem?
Comment: I did some more algebra for you, it should be clear now.
Comment: Someone tried explaining it to me similar to this, but like I said, I still wasn't able to follow :( can you elaborate some more for me please?
Comment: So by that algebra, this tells us that $2-\epsilon$ can't be an upper bound? Which has to make $2$ the least upper bound?
Comment: Why though? Explain more.
Comment: Is it because that since it shows $2-\epsilon$ < $2 - \frac{3}{n+1}$, it contradicts our assumption that $2-\epsilon$ is an upper bound for the set?
Comment: You're just restating the conclusion. Why is the final statement a contradiction?
Comment: I'm not sure then :(
Comment: The final statement is: For all natural numbers $n$, $n<something$. Why is this not correct?
Answer: HINT:
Use method of contradiction :assume there is some number less than 2 which is supremum and contradict by showing a number in set can always be found greater than this assumed supremum.


Meu tipo struct não é reconhecido dentro da minha classe

Question: Gente, estou fazendo a implementação de uma pilha com ponteiros em C++ e tenho o seguinte código por enquanto:
template <class T>
struct Node {
    T item;
    Node *prox;
};

class Pilha {
    private:
    int tamanho;
    Node *topo;

    public:
    Pilha() {
    this->topo=NULL;
    this->tamanho=0;
}

No atributo privado topo, o tipo Node não está sendo reconhecido dentro da minha classe Pilha. O eclipse retorna o seguinte erro: Type 'Node' could not be resolved.
O que pode ser? Obrigada!
Answer: O problema é que a sua estrutura Node tem um template, que vai ser utilizado para criar um Node de qualquer tipo, logo é preciso utilizar também esse padrão na classe Pilha para o compilador saber que o tipo de Node pode variar:
template <class T>
struct Node {
    T item;
    Node *prox;
};

template <class T> // indicação que esta classe tambem usa template
class Pilha {
private:
    int tamanho;
    Node<T> *topo; //aqui o Node é indicado com <T>

public:
    Pilha() {
        this->topo=NULL;
        this->tamanho=0;
    }
};

No código acima, comentei apenas nos locais que alterei.
Vale lembrar que quando for instanciar um nó tem usar a de notação do template. Exemplo:
Node<T> *novoNo = new Node<T>();

Em c++ também tem uma melhor alternativa para NULL que é nullptr e que é um literal de ponteiro e lhe evita algumas conversões implícitas que em determinadas situações geram problemas.
Comment: Eu tenho que colocar o **** no **Node *topo** , tanto na struct qnt no atributo privado na pilha? Obg!
Comment: @lineOut Sim, porque sempre que usa um valor com template numa classe, a classe tem de passar a usar template também, senão não tinha como especificar que queria uma `Pilha` ou uma `Pilha`. Nesse caso quando instância `Pilha` vai forçar `Node`.
Comment: Eu fiz isso mas dentro da pilha ta retornando erro: **Type 'Node' could not be resolved** ... mesmo eu tendo colocado também a indicação de template na Pilha. Na struct não deu erro.
Comment: @lineOut Veja o exemplo do código na minha resposta sem erros [no Ideone](https://ideone.com/1zDfIA). Deixei inclusivamente uma instanciação de um novo nó no construtor a titulo de exemplo.
Comment: Funcionou... Obrigada @Isac !! ^^


How can I find the value of this Maclaurin Series.

Question: Using the four non-zero terms of Maclaurin Series how can I find the value of
$$\int_0^1 2x \cos ^2 x dx$$
When I solved I got Maclaurin Series as $2x-2x^3+\frac{2}{3}x^5$.
But I don't know how to apply the intervals.
Can anyone show how to do this.
Comment: Please format your questions with [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) so we can read them easily.
Comment: I don't think Maclaurin series are the right approach to compute that integral.
Comment: But, I need to solve this using maclaurin series only. I have done this far and I don't know how to app those intervals.
Answer: The right term should be approximation.
After you found the four non-zero terms,
$$2x\cos^2(x) \approx \sum_{i=1}^7 a_i x^i$$
Integrate it term by term.
$$\int_0^12x\cos^2(x)\, dx \approx \sum_{i=1}^7 a_i \int_0^1x^i\, dx$$
Answer: First note that the first 4 (four) terms are
$$2 x-2 x^3+\frac{2}{3} x^5 - \frac{4}{45} x^7$$
and the integral from this approximation is $\frac{3}{5}$. This is not too bad compared to the exact value
$$\cos(1) \sin(1)+\frac{1}{2}\cos(1)^2 \approx 0.600612004276\approx 0.6 = \frac{3}{5}$$
Edit: An antiderivative of the four term expression is
$$F(x) = x^2-\frac{1}{2}x^4+\frac{1}{9}x^6-\frac{1}{90}x^8$$
and therefore you get the integal as $F(1)-F(0) = \frac{3}{5} - 0$.
Comment: Can you please explain it elaborately about how to use upper and lower limits.
Comment: @sam: See the edit.
Comment: So, if upper limit is 2, then I just need to substitute 2 in place of x. right
Comment: Yes, that's right. But note  the approximation  is getting worse and worse if you increase the upper limit.
Answer: $I =\int_0^12x\cos^2(x)\,dx$
The MacLaurin  series of $f(x) = 2x\cos^2(x) $ is $2x - 2x^3 +\frac23x^5-\frac4{45}x^7 + \frac2{315}x^9........$
$I \approx \int_0^12x - 2x^3 +\frac23x^5-\frac4{45}x^7 \,dx$
$I\approx x^2-\frac12x^4 +\frac19x^6-\frac1{90}x^8\bigg]_0^1$
$I\approx 1-\frac12+\frac19-\frac1{90}$
$I \approx \frac35$
NOTE: im not sure if MacLaurin series are the best way to solve this integral ,I'd much rather use integration by parts
$I  =  (\frac{2x (\sin(2x)+x)+\cos(2x)}4)\bigg]_0^1$
$I = \frac{2.(\sin(2)+1)+\cos(2)}{4}-\frac{\cos(0)}4$
$I=0.600612$
Comment: Double-check your integration by parts.
Comment: @gammatester thank you ,i had taken 2 in degrees rather than radians. the rest was proper.


How to optionally redirect to a payment page after adding a node?

Question: I want to add an option to the node add form so that the user who creates the node can choose if the node will be " promoted " or not. If the promoted option is selected, then I want to redirect the user to a payment page, so that the option charges can be payed.
Any suggestions about how to do so?
Answer: Step 1a: Optional redirect to payment page
Add a Boolean field to each content type for which you want to offer such "Promoted" option, say its allowed options are Yes or No.
Then use the Rules module like so:

Event: After saving a node
Condition: (both conditions must be true)

Entity has field "Promoted"
Data Comparison "Promoted" = "Yes"

Action: Perform a page Redirect to your Payment Page

Step 1b: Limit node access while payment is not completed
To wait for the payment to be completed (and not "submit" the node yet), you could use the Content Access module, and the Content Access Rules Integrations module.
So that "After saving content" (= Event), you "Give 'authenticated user' the permission to 'view own content' for the specific node" (= Action). This additional "Action" can be added is a 2nd action to the same rumle suggested above.
This would be a variation of what is explained in this article also (within "Access Control Customized for Your Needs").
Step 2: Promote the node (after payment)
After the payment is received, you could use that "Event" to trigger another rule, which basically consists of these actions:

Mark the node as "Promoted".
Remove the node access restriction, so that all appropriate roles can view the node.

Step 3: Stop the promotion of the node
If at some point in the future the "Promoted" node no longer should be promoted, then you could use the Rules Scheduler ( a sub-module of the Rules scheduler) to trigger a rule to no longer mark the node as "Promoted.
Note: If you're not familiar (enough/yet) with Rules, the checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.
Comment: thank you so much, but i want not to submit the node till the payment is made
Comment: I updated my answer as per your most recent comment to my answer. Does this help?


jTable não adiciona a segunda string que eu coloquei numa array

Question: Eu criei uma array com dois valores e queria colocar ela numa tabela... com um botão inserir (inserir várias linhas)
1- eu declarei a string linha[] e os valores abaixo;
2- achei que um 'for each' fosse resolver, adicionando uma linha (add.row) a cada passada.
mas nao.
3- para teste, o sout esta ok.
4 como resultado,ele imprime duas vezes a primeira string "primeira linha"
String[] linha = {"primeira linha", "segunda linha"};
  for(String linhas : linha){
    ((DefaultTableModel) jTable.getModel()).addRow(linha);
    System.out.println(linha);
  }

para remover as linhas, eu fiz isso aqui e resolveu;
pois se trata de "int" no "removeRow"
// limpar todas as linhas da tabela jTable
        for(int i = jTable.getRowCount(); i>0 ; i--){
            ((DefaultTableModel) jTable.getModel()).removeRow(0);
        }

Comment: Traduza a pergunta, Luke. Do contrário ela será fechada
Comment: eu ja saquei que no foreach eu tenho que usar a string "linhas" mas o addRow pede um object array... portanto não sei como.
Comment: tentei esse aqui também
```
String[] linha = {"primeira linha","segunda linha"};
        for (int i = 0 ; i<linha.length ; i++){
            ((DefaultTableModel) jTableListaObstaculos.getModel()).addRow(linha);
        }
```
Answer: Ola,
Você pode inicializar o JTable de outra forma, passando um array com as colunas, e um array com os dados (que voce pode montar com o que voce precisa)
Adicione tambem o Jtable em um JScrollPane para exibir o header das colunas
Fica parecido com isso
String[] colunas = new String[] { "Nome", "Sobrenome", "Idade" };

Object[][] dados = new Object[][] { { "Jose", "Silva", 44 }, { "Manuel", "Bento", 44 }, };

JTable table = new JTable(dados, colunas);

JFrame frame = new JFrame();
frame.add(new JScrollPane(table));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);

Comment: ele só adiciona o "primeira linha" na tabela
Answer: O erro está no foreach
String[] linha = {"primeira linha", "segunda linha"};
for(String linhas : linha){
((DefaultTableModel) jTable.getModel()).addRow(linha);
System.out.println(linha);
}

Na terceira linha voce está adicionando o ARRAY LINHA, e não o elemento linhas como você queria fazer.O método está acessando diretamente o array e pegando o primeiro elemento somente.
Para corrigir basta trocar linha por linhas dentro dos comandos do foreach:
String[] linha = {"primeira linha", "segunda linha"};
  for(String linhas : linha){
    ((DefaultTableModel) jTable.getModel()).addRow(linhas);
    System.out.println(linhas);
  }


How do I send webform submission data to a google sheet?

Question: I have implemented the webform module on my Drupal 8.4 site. I have some forms that I would like to submit the data to a google spreadsheet, instead of the drupal database.
Can someone help me get started with this?
Do I need to create a custom module to implement this functionality? What hooks do I need to use? Is there any documentation/tutorials out there on how to do this?
Answer: Right now the only available solution is to use Zapier.
Ivan Zugec did a great screencast showing How to Create Forms using Webform and Contact in Drupal 8 and includes a demo showing how to push webform submissions into a Google Sheet using Zapier.
Hopefully, someone will port the Webform to Google Docs module from D7 to D8.
Comment: Thank you! I will follow any progress on the module and use Zapier in the interm.
Answer: Zapier only allows a few 100 submissions per month on the free plan. Not worth it for us.
I've started using the google script editor to send webform data as a GET request through the webform remote post feature. Unlimited requests and offers better customization, at no cost.
I used How to Submit an HTML Form to Google Sheets…without Google Forms to implement the feature.
Answer: i have a better way and did myself.
Create google web form using google apps script and their provided code interface.
and then embed this form into any webpage or can also be used independently.
Answer: Apart from Zapier, theres a contrib module which do this.
Webform GoogleSheets


change gridview colour when checkbox selected

Question: I have a gridview with some data bound to it. I also have different background for alternating rows, so the table is more readable... How do I change the color of the row background when checkbox in the first column is checked and change it back to original when it is unchecked. The problem I'm having is, how to know if original background (after unchecking the checkbox) is for normal row or for alternating row?
I know how to change row attributes like this:
protected void gvUser_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
    {
        e.Row.Attributes.Add("onmouseover", "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#D9ECFB'");
        e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.originalstyle;");
    }
}

But, what if there are more checkboxes selected, how do I know which is the original background?
Answer: I will give a jQuery solution and I hope you like it. What I do here is to find all the checkbox that are inside the GridView control, and then when you click on one of them I get the full line and change the color, but keeping the old one to bring it back. Only one note, you must place on the rows the style .row
function InitTheChecks()
{
    var updateButtons = jQuery('#<%=GridView.ClientID%> input[type=checkbox]');

    updateButtons.each(function (){
        jQuery(this).attr('onclick', null).click(function ()
        {
            var ThisCheckBox = jQuery(this);

            if(ThisCheckBox.is(':checked'))
            {
                ThisCheckBox.attr('oldBackColor', ThisCheckBox.parents(".row").css("background-color"));
                ThisCheckBox.parents(".row").css("background-color", "#FFD8CE");
            }
            else
            {
                ThisCheckBox.parents(".row").css("background-color", ThisCheckBox.attr('oldBackColor'));
            }
        });
    });
}

and run the InitTheChecks() OnPage load.
how to know if original background

To answer to this question, what I do is that I place the old color in an attribute on the tag before I change it, something like a memory keeper :)
Answer: This worked for me.

private void setrowcolor()
   {
       bool checkSelected = false;
       foreach (DataGridViewRow row in gridgencsv.Rows)
       {
          checkSelected =Convert.ToBoolean(row.Cells["select_check"].Value);
            if (checkSelected == true)
              {
                    row.DefaultCellStyle.BackColor = System.Drawing.Color.CadetBlue;
              }
            else
              {
                    row.DefaultCellStyle.BackColor = System.Drawing.Color.White;
              }

        }
   }


Alternative to evaluating a string using a function

Question: I'm trying to output a list of records but some may not have a value in the subject column.
I have an altSubject column that would specify what to output instead.
simplified for example
insert all
    into myTable
        (id, subject, altSubject, partNumber, serialNumber, startDate, endDate)
        values
        (1, 'test',null,'xyz','123','1/1/2019', '1/5/2019')
    into myTable
        (id, subject, altSubject, partNumber, serialNumber, startDate, endDate)
        values
        (2, null, '''SN: '' || serialNumber','abc','789','1/1/2019', '1/5/2019')

output should look like:
subject | Part Number | Start Date | End Date
test    | xyz         | 1/1/2019   | 1/5/2019
SN: 789 | abc         | 1/1/2019   | 1/5/2019

I've been able to do this using a case with a function below but the problem I'm having is it takes 5 minutes to run on a 40k row table.
select
    ...
    ...
    case when altSubject is not null then
        fAltSubject(id,altSubject)
    else
      subject
    end subject
from
    myTable
where
    status = 'closed'

the function:
create or replace function fAltSubject
    (pID in number
    , pAltSubject in varchar2)
    return varchar2
  as
    vNewSubject varchar2(400) := '';
  begin
    vSql := 'select ' ||
      pAltSubject ||
      ' from
          myTable
        where
          id = ' || pID;
    execute immediate vSql
     into
       vNewSubject;
    return vNewSubject;
end faltsubject;

Is there a better way to do this that doesn't take 5 minutes?
Thanks in advance.
Comment: Using *bind arguments* (see [this](https://docs.oracle.com/cd/B12037_01/appdev.101/b10807/13_elems017.htm)) will allow you to speed up you function. And see also [this](https://blogs.oracle.com/sql/improve-sql-query-performance-by-using-bind-variables)
Comment: @SternK thank you. I tried `execute immediate 'select :newSubject from myTable where id = :id' into vNewSubject using pAltSubject, pID` but the result was `'SN: ' ||  serialNumber` instead of `SN: 789` am I missing something?
Comment: See [this](https://dba.stackexchange.com/questions/158489/native-dynamic-sql-execute-immediate-with-column-and-table-names). A bind variable is a value or value address, not a table or column name.
Comment: so looking at my example and desired solution, how were you suggesting I use the bind variables?
Comment: Something like this `execute immediate 'select ' || pAltSubject || ' from myTable where id = :id' into vNewSubject using pID`.
Comment: I appreciate the suggestion but it still took 5 and a half minutes.
Comment: Is it correct assumption that all columns from your mask belong to the `myTable` table?
Comment: What is the percentage rows with filled `subject` and `altSubject`?
Comment: @sternk of the 10k that return only 18 have an altSubject which is why I'm disappointed that the original case + function takes 5 minutes to run.
Answer: "how to use a user defined mask in a column when the mask could be a combination of fields and text".
This is the best I can do and get good performance.
The table defines Subject, AltSubject and DisplaySubject.
A trigger sets the DisplaySubject based on the other two fields.
The trigger must reference the specific column names, so it needs to be regenerated every time columns are added. Maybe a nightly job?
create table myTable (
  id number,
  subject varchar2(64),
  altSubject varchar2(128),
  displaySubject varchar2(128),
  partNumber varchar2(16),
  serialNumber varchar2(16),
  startDate date,
  endDate date
);

create or replace procedure generate_mytable_trigger is
l_newline constant varchar2(1) := chr(10);
l_text clob := to_clob(
'create or replace trigger mytable_displaysubject
before insert or update on mytable
for each row
declare
  lt_column_names sys.odcivarchar2list;
begin
  if :new.subject is not null then
    :new.altsubject := null;
    :new.displaysubject := :new.subject;
    return;
  end if;
  :new.displaysubject := :new.altsubject;
  -- start lines to be generated');
l_end_text constant varchar2(4000) :=
'-- end lines to be generated
  return;
end mytable_displaysubject;';
begin
  for rec in (
    select l_newline ||
      ':new.displaysubject := replace(:new.displaysubject, ''#'||column_name||'#'', :new.'||column_name||');'
      as text
    from user_tab_columns where table_name = 'MYTABLE'
    and column_name not in ('SUBJECT','ALTSUBJECT','DISPLAYSUBJECT')
  ) loop
    l_text := l_text || rec.text;
  end loop;
  l_text := l_text || l_newline || l_end_text;
  execute immediate l_text;
end;
/

exec generate_mytable_trigger;

Now a little test:
insert into mytable(id, subject, altsubject, partnumber, serialnumber, startdate, enddate)
select 1, 'test',null,'xyz','123',sysdate, sysdate+1 from dual
union all
select 2, null,'PN: #PARTNUMBER#','abc','789',sysdate, sysdate+1 from dual
union all
select 3, null,'PN: #PARTNUMBER#, SN: #SERIALNUMBER#','qsdf','789',sysdate, sysdate+1 from dual
union all
select 3, null,'PN: #PARTNUMBER#, ??: #BADCOLUMN#','qsdf','789',sysdate, sysdate+1 from dual;
commit;

select subject, altsubject, displaysubject from mytable;

SUBJECT   ALTSUBJECT                             DISPLAYSUBJECT
test                                               test
           PN: #PARTNUMBER#                        PN: abc
           PN: #PARTNUMBER#, SN: #SERIALNUMBER#    PN: qsdf, SN: 789
           PN: #PARTNUMBER#, ??: #BADCOLUMN#       PN: qsdf, ??: #BADCOLUMN#

Comment: This has potential. I like the coldfusion #variable# parse thing you've got going. I'm not a huge fan of the display column, we tossed that idea around and decided it would be a list resort. Currently I've got it running in a few seconds using a temp table but there is potential for performance problems as the rows with masks grows as it builds the temp table. **psudo:** `insert into temp select id, subject where altSubject is null` then I add the masked rows in one at a time in a loop. join temp table to get the subject in the query. 15 seconds @ 10k records. slow but not 5 minutes.
Answer: You have a recent version of Oracle: congratulations. So use it: virtual columns!
create table myTable (
  id number,
  subject varchar2(32),
  altSubject varchar2(64)
    generated always as (case when subject is null then 'SN: '||serialnumber end),
  partNumber varchar2(16),
  serialNumber varchar2(16),
  startDate date,
  endDate date
);

insert into mytable(id, subject, partnumber, serialnumber, startdate, enddate)
select 1, 'test','xyz','123',sysdate, sysdate+1 from dual
union all
select 2, null,'abc','789',sysdate, sysdate+1 from dual;

select ID, coalesce(SUBJECT, ALTSUBJECT) subject,
  PARTNUMBER, SERIALNUMBER, STARTDATE, ENDDATE
from mytable;

ID SUBJECT  PARTNUMBER  SERIALNUMBER  STARTDATE           ENDDATE
-- -------- ----------- ------------- ------------------- -------------------
 1 test     xyz         123           2019-12-18 13:09:10 2019-12-19 13:09:10
 2 SN: 789  abc         789           2019-12-18 13:09:10 2019-12-19 13:09:10

That may very well be overkill. You could always get rid of the extra column and say:
select ID, coalesce(SUBJECT, 'SN: '||serialnumber) subject,
  PARTNUMBER, SERIALNUMBER, STARTDATE, ENDDATE
from mytable;

Best regards,
Stew Ashton
Comment: my issue is that depending on what type of document I'm looking at the altSubject is different so I'm trying to pull it from the table as an optional setting to the document. It might be `'SN: '|| serialnumber` or `someColumn || '[' || anotherColumn || ']'` or whatever the customer would like to see as the alt subject.
Comment: I thought so. Don't do that. That is code, not data. Ask the customer to define document types and what they want to see as the alternate subject for each type. Then code those alternatives in a CASE expression.  Good grief, if the alternate subject varies with each document then why not just enter 'SN: 789' as the subject???
Comment: the application allows me to add a document, sometimes it has a subject, sometimes it doesn't. sometimes I have to add a column to suite the document requirement but it's all done automatically. if the document doesn't have a subject the system needs to be able to substitute it with something else without having to change the code every time a new document type is created. (it's not actually a "document" it's a bit more complicated than that, i.e. a dynamic ticketing system) I'm open to suggestions but modifying the code every week isn't an option.
Comment: "if the alternate subject varies with each document then why not just enter 'SN: 789' as the subject" as I was saying it's a simple example. Ticket types may not have a "subject" but the main subject might be `manual number` or `service instruction` which is selected from a drop down, or a combination of fields. The majority of tickets use the `subject` field but some do not and I need a way to handle it without having to modify the application every time a customer adds a new ticket type with custom fields.
Comment: "the main subject might be manual number or service instruction which is selected from a drop down, or a combination of fields." Then the user "enters" a value through the choice of a drop down! So just calculate the result of that choice and put it in the field, instead of putting a bit of code in the field to calculate the result every time. By the way, how are you going to add new custom fields to the drop down without changing the application??
Comment: they are added as the user defines them, this application uses ddl, another uses json columns. My question isn't how to add the columns (I've asked other questions about showing data that may or may not be in the form) I just need to know how to use a user defined mask in a column when the mask could be a combination of fields and text.
Comment: OK, I'll add another answer on "how to use a user defined mask in a column when the mask could be a combination of fields and text".


Instancia do axios não retorna no export do nodejs

Question: Estou tentando retornar a instancia criada através do axios pelo module.exports,
porém quando tento usa-lá me da esse erro:

http(...).get is not a function

Meu arquivo http-common.js
var axios = require('axios');

var instancia = axios.create({
    baseURL: `http://jsonplaceholder.typicode.com/`,
});

module.exports = instancia;

Meu index.js
var http = require('./app/infraestrutura/http-common')();
http.get('/users')
        .then(function(response){
            console.log(response)
        }).
        catch(function(err){
            console.log(response)
        })

Comment: Mas isso é exatamente o que está acontecendo. Como você chama o método `get` imediatamente após importar o módulo, ele faz a requisição logo de cara. Se você queria chamar essa requisição mais tarde, talvez seja o caso de coloca-la dentro de uma função e chamar essa função somente quando necessário.
Comment: Remova os parenteses do require em `require('./app/infraestrutura/http-common')()`. Deveria ser `require('./app/infraestrutura/http-common')`
Comment: @user140828 funcionou, porém não como eu queria, a ideia era ele só executar o `request`, quando eu chamasse o método `.get()` ou `.post()`
Comment: @user140828 é você tem razão, a melhor forma de fazer isso é exportar a própria instância do axios e setar a `baseURL` ( através do axios.defaults )  antes de exporta-lá
Answer: A solução foi exportar o própria instancia do axios por inteiro, e fazer a modificações antes de exporta-lo:
var axios = require('axios');
axios.defaults.baseURL = 'http://jsonplaceholder.typicode.com/';

module.exports = axios;


How to get the JSON/array value property name for a field instance?

Question: Given a Drupal\Core\Field\BaseFieldDefinition  how do you get whether the value is stored by target_id, or value or uri or color or ....
it seems getMainPropertyName() is what i'm looking, for but it returns null for the majority of fields. in my case it's only returning target_id or value for for created, status, and entity_id.
Answer: I just tested using a variety of field types, and it seems to work OK for me. Here's the code I used for testing:
$node = \Drupal\node\Entity\Node::load($nid);

print $node->get('field_test')->getFieldDefinition()->getFieldStorageDefinition()->getMainPropertyName();
print $node->get('field_test_image')->getFieldDefinition()->getFieldStorageDefinition()->getMainPropertyName();
print $node->get('field_test_link')->getFieldDefinition()->getFieldStorageDefinition()->getMainPropertyName();
print $node->get('field_test_email')->getFieldDefinition()->getFieldStorageDefinition()->getMainPropertyName();

This returns value, target_id, uri and value as one would have expected. What kind of fields are giving you trouble? How do you get you BaseFieldDefinition class? What kind of entity are they connected to?
I notice that the Views way of getting the property name is also pretty pragmatic:
// EntityField.php line 1111
if ($main_property_name = $field_item->mainPropertyName()) {
  $values[] = $field_item->{$main_property_name};
}
else {
  $values[] = $field_item->value;
}

Clearly it's not completely unexpected to have this method return null.
Comment: perfect. I was using executing the method on `getFieldDefinition()` and not `getFieldStorageDefinition()`
Answer: This code works for getting the main property name of the field for a particular content type
$entityFieldManager = \Drupal::service('entity_field.manager');
$fields = $entityFieldManager->getFieldDefinitions('node', 'article');
foreach ($fields as $field_name => $field_definition) {
  if (!empty($field_definition->getTargetBundle())) {
    $storage[$field_name]['storage_value'] = $field_definition->getFieldStorageDefinition()->getMainPropertyName();
  }
}