How can i update a table based on a count of another table while using LIKE statement

Question: I know how to update one table's field from another table's count using t1.id=t2.id etc.. but i have somewhat typical issue. I have to use LIKE STATEMENT in WHERE clause.
This is something similar i wanted to do.
UPDATE `CATEGORIES`
SET    `num_listings` = (SELECT COUNT(*)
                         FROM   `LISTINGS`
                         WHERE  `LISTINGS`.`CATEGORY` LIKE
                                ws_concat('', "%-", `CATEGORIES`.`ID`, "-%"));

(Example: I have CATEGORY stored as -25- in the LISTINGS table as a field name CATEGORY)
I understand that i cannot use ws_contact here but is there another way to achieve it?
Thanks in advance.
Comment: This kind of query would probably be easier if you normalised your database structure and added a new association table of `listings_categories`
Comment: Well.. Martin this is not possible right now as i am working on bug fixes/updates for an existing website having thousands of entries.
Answer: Unless there is a good reason for the category ID to be represented only by a part of a string in the listings table, the best way to handle such a structure of data is to add a category_id column to the LISTINGS table, and make sure that when adding or editing a listing this column is populated properly.
This would allow to simply JOIN the two tables ON categories.id = listings.category_id and makes much more sense. This would also give better performance by far.
If you do want to keep the DB structure as is, you can use a temporary table, with LIKE and CONCAT:
DROP TABLE IF EXISTS temp;

CREATE TABLE temp AS
       SELECT categories.id, COUNT(*) AS c
       FROM categories
       JOIN listings ON listings.category LIKE CONCAT('%',categories.id,'%')
       GROUP BY categories.id;

UPDATE categories, temp
SET categories.num_listings = temp.c
WHERE categories.id = temp.id;

Comment: Thanks a millions Galz! This is exactly what i was looking for. You rocks!


Guitar overdubbing with headphones problem

Question: I practise guitar at home with my headphones and using Boss micro BR 80 amp modeling device and its effects.
It works ok with one guitar but when I use a looper/delay to harmonize my solos or record a short riff and want to play solo over it, the overdubbed distorted guitars just sound terrible. I can't even hear the notes. When I play clean or play one guitar its ok, but when 2 distortion guitars played over each other, it is just trash.
I do not use extreme distortion, that's mild overdrive tone.
Comment: Have you tried turning it down?  If there's clipping anywhere on the signal path, reducing levels at the right point could help.
Answer: This is almost certainly down to signal levels, as @crystal commented. You are adding another guitar into the mix so you are probably clipping at the input to your amp
Drop your signal levels by half on the input by turning down whatever pre-amp or gain settings you have, and see if the distortion goes away.
Another possibility, in re-reading your question, is down to where you have your looper. If you are taking output from your BR80 then looping its output back into its input then you will definitely have issues, as you will be passing the distorted backing and your solo to a distortion together - a guaranteed recipe for noise.
If you are using a looper or delay to give you a backing track, you need it on a separate effects path from your solo, or at least after your effects - ie you can not feed both into a distortion. Well, you can, but it sounds very messy - which could well be what you are getting here.
Comment: tnx, when i put the delay pedal after micro br, then get a very low volume and one channel sound hear from my headphones, I also can not use splitter because my microbr has only 1 input
Answer: I suspect you are feeding the output of your looper into your effects pedal. With more layers, you get more volume, and that causes the distortion.
Make it guitar -> effects -> looper -> headphones.
Check with a clean setting on the effects unit, and set the levels so you get a clean sound when you strum hard. It's most important that the effects unit's output is at the same level expected by the looper's input.
With this setup, you have the advantage that you can apply different effects to each layer: e.g. loop a clean chord sequence, play a distorted solo over it.
To play this at volume, instead of through headphones, use a clean channel on your amp, or even better use a PA amp rather than a guitar amp: your amp modelling effects unit is giving the sound character.
Edit: All of this assumes your looper works at line level or headphone volume. If your looper is designed to work at instrument level, which is much quieter than line level, that has two repercussions:

You'll need to turn the output level of the multi-fx unit down to instrument level
The output of the looper will be quiet. You'll need to amplify it. If you don't have an amp with a headphone output, you could spend $20 on a headphone amp. This will also deal with splitting the mono signal into both stereo headphone channels.
Comment: tnx, when i put the delay pedal after micro br, then get a very low volume and one channel sound I hear from my headphones, It is also slightly distorted and not good quality. I also can not use splitter because my microbr has only 1 input


Meaning of $r^2n$ for a large dataset

Question: I have a large astronomical dataset, showing the OLS regression value $r$ between two continuous variables, and the number of observations $n$. My research supervisor has told me to include the value of $r^2n$ as part of my analysis of the dataset. Here's a quick example:
<code>    Colour  &   |r|>0.5     &   n       &   r^2n > 1000
    --------------------------------------------------------------
    (U-V)   &   0.558545    &   11640   &   3631.36
    (U-R)   &   0.567270    &   11632   &   3743.12
    (U-I)   &   0.579188    &   11626   &   3900.04
    (U-J)   &   0.536106    &   3709    &   1066
    (U-K)   &   0.535644    &   3730    &   1070.19
    (B-V)   &   0.580019    &   11884   &   3998.04
    (B-R)   &   0.574867    &   11763   &   3887.34
    (B-I)   &   0.591288    &   11749   &   4107.7
</code>
What's the significance or meaning behind this particular statistic?
EDIT: I'm trying to find a tightly fitting and highly correlated relationship between the combinations of magnitudes (colours) in the rightmost column, with the distance to the galaxy emitting that colour. I've got some very high $r$ $>0.8$ in some cases, but some of these have only a couple of thousand data points due to missing or invalid data for some sources. There may be up to $\sim 29000$ data points for any particular fit, so the more, the better. The only reason I can think of for including this statistic is that it's a way to filter out highly correlated variables (high $r$) that have only a few observations (low $n$).
Answer: This is a non-standard statistic to report in regression analysis.  It does not strike me as having any particularly useful properties that could not be done better with some other statistic, but perhaps your supervisor has some use for it in mind that we are not aware of.  The statistic $R^2$ measures the proportion of the variability in the response variable that is attributable to variations in the explanatory variable, so if you multiply it by $n$ then I suppose you are now just extending this from a proportionality measure between zero and one to a measure from zero up to the number of data points.  That does not strike me as being useful for anything, but since you have not specified the purpose and justification for this statistic proposed by your supervisor, it is hard to say.
Ultimately, the onus is on your supervisor to tell you what he wants you to do with this statistic and why he thinks it is useful.  People on this forum can speculate on this, and can look at some of the properties of this statistic, but it is not sensible for us to speculate when you could just ask your supervisor what significance and meaning he claims that this statistic has.  Once you have an explanation for how and why your supervisor proposes to use this statistic, you can then ask us if that is a sensible usage.
Comment: As I said, I think the first step is to speak to your supervisor and find out what the *claimed rationale* actually is.  It is not very useful for us to speculate on this -- the onus of proof is on the person asserting usefulness of a statistic.
Comment: Hmmm ok, thanks for that. I was worried that there was some obscure use that I'd missed in my rarefied undergrad statistics courses. I'll edit the question to include a little background on the data.
Comment: Since it has already been answered, rather than editing this question, it would be better to ask a new question (and link back to this one if you want).  If you make a major edit to a question after it has been answered then the existing answers become obsolete and don't make sense.
Comment: After rereading your answer, I realised that it might help if you knew a little about the data. I've upvoted your answer, as it helps me, but I still wonder if there's a rationale behind using $r^2n$.

Meaning of $r^2n$ for a large dataset


Let $A$ be a square matrix that commutes with its transpose. Show that the nullspaces of $A$ and $A^T$ coincide.

Question: Am completely stuck on this, any help would be appreciated.
Comment: How can this question possibly deserve an upvote?
Comment: I appreciate that this isn't the right way to go about things, but I am completely flummoxed. Don't even know how to start this question :(
Answer: Hint: Suppose $Ax = 0$ and look at $\|A^Tx\|^2 = x^T A A^T x$


How to preserve a docstring of a decorated class for sphinx documentation?

Question: I have a decorator that has a nested definition of the wrapping class.
Wrapper maintains as the attribute the original class that it wraps.
Toy example looks like this:
def decorator(cls):
    class Wrapper(object):
        original = cls

        def __init__(self):
            self.__doc__ = self.original.__doc__
            self.__name__ = self.original.__name__

        def do_something_with_cls(cls):
            pass

    return Wrapper

Now I want to decorate the Foo class with this decorator in the other module and generate sphinx documentation for the Foo class before it has been decorated. It looks like this:
from .bar import decorator

@decorator
class Foo(object):
    """The docstring I want to preserve."""
    def __init__(self):
        pass

I was trying to achieve this with use of the autoclass functionality but it didn't work out. What i wanted to do was to create a class instance and take its docstring:
.. autoclass:: package.baz.Foo()
   :members:

but it returned this in the html documentation of the package.baz.Foo class: alias of package.bar.decorator.<locals>.Wrapper
I want to achieve that when I am documenting the baz module I am able to generate a documentation of the Foo class before its decoration. Is it possible?
EDIT:
This looks like a similar problem but here what I would like to achieve is to pass to the Wrapper instance the docstring that Sphinx will see and generate a documentation basing on the original Foo docstring or I will be able to call a Wrapper.original and make a documentation of this, but the following didn't work out:
.. autoclass package.baz.Foo.original
   :members:

Comment: Use [**`wraps`**](https://docs.python.org/3/library/functools.html#functools.wraps)
Comment: Possible duplicate of [Python functools.wraps equivalent for classes](https://stackoverflow.com/questions/6394511/python-functools-wraps-equivalent-for-classes)
Comment: Both solutions will not work out because:

1. wraps are not compatible for the class passed as the parameter
2. I am here decorating the whole class with the function that defines the Wrapper class inside. In the attached problem there is the class that decorates the function.

Or maybe I am missing something?
Answer: If @wraps is not working you can update __doc__ manually.
Do something like:
def decorator(cls):
    class Wrapper(object):
        original = cls

        def __init__(self):
            self.__doc__ = self.original.__doc__
            self.__name__ = self.original.__name__

        def do_something_with_cls(cls):
            pass

    Wrapper.__doc__ = cls.__doc__
    return Wrapper

@decorator
class Foo(object):
    """The docstring I want to preserve."""
    def __init__(self):
        pass

print(Foo.__doc__)

'The docstring I want to preserve.'
Comment: You are my hero! I don't know why I didn't figure out that I need to specify this outside of the class definition and did the same but in the __init__ phase... Thank you very much, works perfectly!


Predicting football match winner based only on the outcome of previous matches between the two teams

Question: I'm a huge football (soccer) fan and interested in machine learning too. As a project for my ML course I'm trying to build a model that would predict the chance of winning for the home team, given the names of the home and away team. (I query my dataset and accordingly create datapoints based on previous matches between those 2 teams)
I have data for several seasons for all teams however I have the following issues that I would like some advice with. The EPL (English Premier League) has 20 teams which play each other at home and away (380 total games in a season). Thus, each season, any two teams play each other only twice.
I have data for the past 10+ years, resulting in 2*10=20 datapoints for the two teams. However I do not want to go past 3 years since I believe teams change quite considerably over time (ManCity, Liverpool) and this would only introduce more error into the system.
So this results in just around 6-8 data points for each pair of team. However, I do have several features (up to 20+) for each data point like full-time goals, half time goals, passes, shots, yellows, reds, etc. for both teams so I can include features like recent form, recent home form, recent away form etc.
However the idea of just having only 6-8 datapoints to train with seems incorrect to me. Any thoughts on how I could counter this problem? (if this is a problem in the first place)
Comment: If you really only want to use the names of the teams, you could use the kind of rating system which is used for chess or other two-player games, for example [Elo][1] or [Trueskill][2]. There was also a [Kaggle contest][3] about this. You could perhaps start with one of these systems and then enhance it using the other covariates.

  [1]: http://en.wikipedia.org/wiki/Elo_rating_system
  [2]: http://en.wikipedia.org/wiki/TrueSkill
  [3]: http://www.kaggle.com/c/chess
Comment: The home field advantage seems pretty important to me based on the studies I have read (I'm an engineer/economist and a BVB fan). You might also consider PKs; they don't change the long-term match outcomes on average (read [Soccernomics](http://www.amazon.com/Soccernomics-Australia-Turkey-Iraq-Are-Destined/dp/1568584253) ), but may heavily influence an individual match.
Comment: The only think that you will know prior to a match is the previous results and the ranking. You wont have info about shoots, corners ets, hence you need to create features that are plausible and given.
Answer: What about improving your dataset by means of taking into consideration also some data about the matches vs the same opponent?
Example:
<code>TeamA vs TeamC: 1-0
TeamB vs TeamC: 2-0
=> "infer" the fake outcome: TeamA vs TeamB: 1-2
</code>
Furthermore, in my opinion this kind of date are better than the data that you proposed, because the last year teams are often very different teams.
Comment: Excellent suggestion! Thanks Aslan986..
However, I believe this would contribute to the features list. I don't see how we could use this data as a 'datapoint'.
Nevertheless, thanks, I will definitely try this out.


Dapper : Reading directly nth item from the GridReader

Question: This what i found in dapper blog
var sql =
@"
select * from Customers where CustomerId = @id
select * from Orders where CustomerId = @id
select * from Returns where CustomerId = @id";

using (var multi = connection.QueryMultiple(sql, new {id=selectedId}))
{
   var customer = multi.Read<Customer>().Single();
   var returns = multi.Read<Return>().ToList();
   var orders = multi.Read<Order>().ToList();
   ...
}

My requirement is I want to directly read only "orders"    . Can I do that ?
Answer: If you don't want the other two, you can call Read without ever iterating that sequence: no objects will be materialized:
var customer = multi.Read<Customer>(); // not consumed
var returns = multi.Read<Return>(); // not consumed
var orders = multi.Read<Order>().ToList();

Comment: @KuntadyNithesh I suppose we could add some kind of `Skip()` method, but currently: no. How would it know to skip them? You could use the non-generic API, though, i.e. `multi.Read();`
Comment: is there any way that I could avoid writing first 2 lines
Answer: You can use Query extension to read single, e.g.
const string sql = "select * from Orders where CustomerId = @id";
var orders = connection.Query<Order>(sql, new {id = 1}).ToList();

Edit:
To execute stored procedure:
var orders = connection.Query<Order>("GetOrders", new {id = 1}, commandType: CommandType.StoredProcedure).ToList();

Comment: I know this . but my actual sql is a stored procedure
Comment: I guess your question was unclear. I have edited my answer for SP as well.
Comment: but my first read is of type Customer not Order ? does this work?
Comment: I'm a little lost, your questions was: " I want to directly read only "orders"", but now the Customer is in play. Can you maybe edit your question to make it clear so we know what you are trying to do?
Comment: According to ma question my reader will have 3 item collections . first is of Customer . second is of Return and third is Order . Does your solution directly reads orders ? . even though my reader contains customer and return i dont want to read first 2 colections . I directly want to read third one .


C code to Haskell

Question: So, i would like to convert a part of C code to Haskell. I wrote this part (it's a simplified example of what I want to do) in C, but being the newbie I am in Haskell, I can't really make it work.
float g(int n, float a, float p, float s)
{
    int c;
    while (n>0)
    {
        c = n % 2;
        if (!c) s += p;
        else s -= p;
        p *= a;
        n--;
    }
    return s;
}

Anyone got any ideas/solutions?
Comment: Usually you look at problems in a totally different way in Haskell than in C. Try to solve problems in Haskell, not to translate what you already have, else you get clumsy and awkward solutions, and you don't experience all that crazy Zen moments when you actually grok something. Actually the most important thing you can do in order to learn Haskel is to *forget* everything you know about C.
Comment: [This might also help you.](http://stackoverflow.com/questions/4344305/do-while-loop-in-haskell)
Answer: Lee's translation is already pretty good (well, he confused the odd and even cases(1)), but he fell into a couple of performance traps.
g n a p s =
  if n > 0
  then
    let c = n `mod` 2
        s' = (if c == 0 then (-) else (+)) s p
        p' = p * a
    in g (n-1) a p' s'
  else s

He used mod instead of rem. The latter maps to machine division, the former performs additional checks to ensure a non-negative result. Thus mod is a bit slower than rem, and if either satisfies the needs - because they yield identical results in the case where both arguments are non-negative; or because the result is only compared to 0 (both conditions are satisfied here) - rem is preferable. Even better, and a bit more idiomatic is to use even (which uses rem for the reasons mentioned above). The difference is not huge, though.
No type signature. That means that the code is (type-class) polymorphic, and thus no strictness analysis is possible, nor any specialisations. If the code is used in the same module at a specific type, GHC can (and usually will, if optimisations are enabled) create a specialised version for that specific type that allows strictness analysis and some other optimisations (inlining of class methods like (+) etc.), in that case, one does not pay the polymorhism penalty. But if the use site is in a different module, that cannot happen. If (type-class) polymorphic code is desired, one should mark it INLINABLE or INLINE (for GHC < 7), so that its unfolding is exposed in the .hi file and the function can be specialised and optimised at the use site.
Since g is recursive, it cannot be inlined [meaning, GHC cannot inline it; in principle it is possible] at use sites, which often would enable more optimisations than a mere specialisation.
One technique that often allows better optimisation for recursive functions is the worker/wrapper transformation. One creates a wrapper that calls a recursive (local) worker, then the non-recursive wrapper can be inlined, and when the worker is called with known arguments, that can enable further optimisations like constant folding or, in the case of function arguments, inlining. In particular the latter often has an enormous impact, when combined with a static-argument-transformation (arguments that never change in the recursive calls are not passed as arguments to the recursive worker).
In this case, we only have one static argument of type Float, so a worker/wrapper transformation with a SAT typically makes no difference (as a rule of thumb, a SAT pays off when

the static argument is a function
several non-function arguments are static

so by this rule, we shouldn't expect any benefit from w/w + SAT, and in general, there is none). Here we have one special case where w/w + SAT can make a big difference, and that is when the factor a is 1. GHC has {-# RULES #-} that eliminate multiplication by 1 for various types, and with such a short loop body, a multiplication more or less per iteration makes a difference, the running time is reduced by about 40% after points 3 and 4 have been applied. (There are no RULES for multiplication by 0 or by -1 for floating point types because 0*x = 0 resp. (-1)*x = -x don't hold for NaNs.) For all other a, the w/w + SATed
{-# INLINABLE g #-}
g n a p s = worker n p s
  where
    worker n p s
      | n <= 0    = s
      | otherwise = let s' = if even n then s + p else s - p
                    in worker (n-1) a (p*a) s'

does not perform measurably different from the top-level recursive version with the same optimisations done.
Strictness. GHC's strictness analyser is good, but not perfect. It cannot see far enough through the algorithm to determine that the function is

strict in p if n >= 1  (assuming addition - (+) - is strict in both arguments)
also strict in a if n >= 2 (assuming strictness of (*) in both arguments)

and then produce a worker that is strict in both. Instead you get a worker that uses an unboxed Int# for n and an unboxed Float# for s (I'm using the type Int -> Float -> Float -> Float -> Float here, corresponding to the C), and boxed Floats for a and p. Thus in each iteration you get two unboxings and a re-boxing. That costs (relatively) a lot of time, since besides that it's just a bit of simple arithmetic and tests.
Help GHC along a bit, and make the worker (or g itself, if you don't do the worker/wrapper transform) strict in p (bang pattern for example). That is enough to allow GHC producing a worker using unboxed values throughout.
Using division to test parity (not applicable if the type is Int and the LLVM backend is used).
GHC's optimiser hasn't got down to the low-level bits very much yet, so the native code generator emits a division instruction for
x `rem` 2 == 0

and, when the rest of the loop body is as cheap as it is here, that costs a lot of time. LLVM's optimiser has already been taught to replace that with a bitmasking at type Int, so with ghc -O2 -fllvm you don't need to do that manually. With the native code generator, substituting that with
x .&. 1 == 0

(needs import Data.Bits of course) produces a significant speedup (on normal platforms where a bitwise and is much faster than a division).

The final result
{-# INLINABLE g #-}
g n a p s = worker n p s
  where
    worker k !ap acc
        | k > 0 = worker (k-1) (ap*a) (if k .&. (1 :: Int) == 0 then acc + ap else acc - ap)
        | otherwise = acc

performs not measurably different (for the tested values) from the result of gcc -O3 -msse2 loop.c, except for a = -1, where gcc replaces the multiplication with a negation (assuming all NaNs equivalent).

(1) He's not alone in that,
c = n % 2;
if (!c) s += p;
else s -= p;

seems to be really tricky, as far as I can see everybody(2) got that wrong.
(2) With one exception ;)
Comment: I'd also remove the `a` argument from `worker` since it stays constant. Or was that intentional?
Comment: I wanted it to be as close to the starting point as possible. Otherwise I'd have removed it too. A static argument transformation for a single (strict) `Float` argument doesn't make much difference, though, so there's no real harm in leaving it in.
Answer: As a first step, let's simplify your code:
float g(int n, float a, float p, float s) {
    if (n <= 0) return s;

    float s2 = n % 2 == 0 ? s + p : s - p;
    return g(n - 1, a, a*p, s2)
}

We have turned your original function into a recursive one that exhibits a certain structure.  It's a sequence!  We can turn this into Haskell conveniently:
gs :: Bool -> Float -> Float -> Float -> [Float]
gs nb a p s = s : gs (not nb) a (a*p) (if nb then s - p else s + p)

Finally we just need to index this list:
g :: Integer -> Float -> Float -> Float -> Float
g n a p s = gs (even n) a p s !! (n - 1)

The code is not tested, but it should work.  If not, it's probably just an off-by-one error.
Comment: Your transformation to the recursive version is not trivial for someone unfamiliar with FP, and it's an important part of the learning process which deserves more than just doing it for him.  (I personally prefer it when answerers give guided exercises)
Answer: Here is how I would tackle this problem in Haskell. First, I observe that there are several loops merged into one here: we are

forming a geometric sequence (whose factor is a suitably negative version of p)
taking a prefix of the sequence
summing the result

So my solution follows this structure as well, with a tiny bit of s and p thrown in for good measure because that's what your code does. In a from-scratch version, I'd probably drop those two parameters entirely.
g n a p s = sum (s : take n (iterate (*(-a)) start)) where
    start | odd n     = -p
          | otherwise = p

Comment: Two minor defects, 1. your `start` has the wrong sign, 2. `factor` is simply `a`.
Comment: Unfortunately, the lists aren't fused away, and `sum` isn't specialised for `Float` (wtf?) so it's not efficient and stack- (or heap, I got a "heap exhausted", urgh?) overflows for large `n`. Pity, because it's really nice.
Comment: @DanielFischer Hm, I thought since he is alternately adding and subtracting that the factor had better be made certainly negative. I'm not surprised I got other things wrong, though, as I didn't test it at all; I just wanted to put the idea of the transformation out there. =)
Comment: @DanielWagner Oh, `factor` should be unconditionally `-a`, I got that wrong too.
Comment: @DanielFischer I think you're still wrong, it should be `-abs a`. I have now done some tests and fixed the post. =)
Comment: No. If `n` is even, the addends are `p, -(a*p), a^2*p, -(a^3*p), ...`. If `n` is odd, the negatives of them. Each differs from the previous by a factor of `-a`.
Comment: @DanielFischer err... my tests used negative values for `n` as well, which obviously didn't test what I was thinking it would test -_- Fixed, thanks.
Comment: ++ for unearthing what's _really_ going on there, with fission (though shouldn't it be fused back now, for efficiency?). With more "dots" it's even clearer IMO, `g n a p s = sum . (s:) . take n . iterate (*(-a)) ...`.
Comment: OTOH it is not easy (took you and DanielFischer few iterations, right?), not automatic, involves creative coding. And you've changed the algorithm... (no testing on each step). So this was more like writing an algo/code anew, less like "converting".
Comment: @WillNess If the goal is to learn Haskell, I don't think that it's a bad thing that it requires some thought and rewiring. Haskell and C are fundamentally different languages, and you use fundamentally different techniques when writing code in them. And yes, it takes a few iterations -- there will always be debugging to do, no matter how you write your code or what language you use.
Answer: A fairly direct translation would be:
g n a p s =
  if n > 0
  then
    let c = n `mod` 2
        s' = (if c == 0 then (-) else (+)) s p
        p' = p * a
    in g (n-1) a p' s'
  else s

Answer: Look at the signature of the g function (i.e., float g (int n, float a, float p, float s)) you know that your Haskell function will receive 4 elements and return a float, thus:
g :: Integer -> Float -> Float -> Float -> Float

let us now look into the loop, we see that n > 0 is the stop case, and n--; will be the decreasing step used on the recursive call. Therefore:
g :: Integer -> Float -> Float -> Float -> Float
g n a p s | n <= 0 = s

to n > 0, you have another conditional if (!(n % 2)) s += p; else s -= p; inside the loop. If n is odd than you will do s += p, p *= a and n--. In Haskell it will be:
g :: Integer -> Float -> Float -> Float -> Float
g n a p s | n <= 0 = s
          | odd n = g (n-1) a (p*a) (s+p)

If n is even than you will do s-=p, p*=a; and n--. Thus:
g :: Integer -> Float -> Float -> Float -> Float
g n a p s | n <= 0 = s
          | odd n = g (n-1) a (p*a) (s+p)
          | otherwise = g (n-1) a (p*a) (s-p)

Answer: You can encode loops almost-naturally with the Haskell Prelude function until :: (a -> Bool) -> (a -> a) -> a -> a:
g :: Int -> Float -> Float -> Float -> Float
g n a p s =
  fst.snd $
    until ((<= 0).fst)
          (\(n,(!s,!p)) -> (n-1, (if even n then s+p else s-p, p*a)))
          (n,(s,p))

The bang-patterns !s and !p mark strictly-calculated intermediate variables, to prevent excessive laziness which would otherwise harm efficiency.
until pred step start repeatedly applies the step function until pred called with the last generated value will hold, starting with initial value start. It can be represented by the pseudocode:
def until (pred, step, start):             // well, actually,
  while( true ):                         def until (pred, step, start):
    if pred(start): return(start)          if pred(start): return(start)
    start := step(start)                   call until(pred, step, step(start))

The first pseudocode is equivalent to the second (which is how until is actually implemented) in the presence of tail call optimization, which is why in many functional languages where TCO is present loops are encoded via recursion.
So in Haskell, until is coded as
until p f x  | p x       = x
             | otherwise = until p f (f x)

But it could have been coded differently, making explicit the interim results:
until p f x = last $ go x     -- or, last (go x)
  where go x | p x       = [x]
             | otherwise = x : go (f x)

Using the Haskell standard higher-order functions break and iterate this could be written as a stream-processing code,
until p f x = let (_,(r:_)) = break p (iterate f x) in r
                       -- or: span (not.p) ....

or just
until p f x = head $ dropWhile (not.p) $ iterate f x    -- or, equivalently,
           -- head . dropWhile (not.p) . iterate f $ x

If TCO weren't present in a given Haskell implementation, the last version would be the one to use.

Hopefully this makes clearer how the stream-processing code from Daniel Wagner's answer comes about,
g n a p s = s + (sum . take n . iterate (*(-a)) $ if odd n then (-p) else p)

because the predicate involved is about counting down from n, and
fst . snd . head . dropWhile ((> 0).fst) $
  iterate (\(n,(!s,!p)) -> (n-1, (if even n then s+p else s-p, p*a)))
          (n,(s,p))
===
fst . snd . head . dropWhile ((> 0).fst) $
  iterate (\(n,(!s,!p)) -> (n-1, (s+p, p*(-a))))
          (n,(s, if odd n then (-p) else p))          -- 0 is even
===
fst . (!! n) $
  iterate (\(!s,!p) -> (s+p, p*(-a)))
          (s, if odd n then (-p) else p)
===
foldl' (+) s . take n . iterate (*(-a)) $ if odd n then (-p) else p

In pure FP, the stream-processing paradigm makes all history of a computation available, as a stream (list) of values.
Answer: To expand on @Landei and @MathematicalOrchid 's comments below the question: The algorithm proposed to solve the problem at hand is always O(n). However, if you realize that what you're actually doing is computing a partial sum of the geometric series, you can use the well-known summation formula:
g n a p s = s + (-1)**n * p * ((-a)**n-1) / (-a-1)

This will be faster as the exponentiation can be done faster than O(n) by repeated squaring or other clever methods, which are likely automatically employed for integer powers by modern compilers.

C code to Haskell


Solving a complex, sparse, linear system using the Schur complement

Question: Solution method
I am repetitively solving sparse linear systems (for the need of ARNOLDI iterations) of the type:
$$\underbrace{\begin{bmatrix}
J_1 & J_2 \\
J_3 & J_4
\end{bmatrix}}_J
\underbrace{\begin{bmatrix}
x \\
y
\end{bmatrix}}_z=
\underbrace{\begin{bmatrix}
b_x \\
b_y
\end{bmatrix}}_b$$
I build the Schur-complement ($J_4$ is non-singular):
$$J_D=J_1-J_2J_4^{-1}J_3$$
Then, I solve for $x$:
$$J_Dx=b_x-J_2J_4^{-1}b_y$$
and then for $y$:
$$J_4y=b_y-J_3x$$
At this point I have a full solution of $z$.
Intermediate calculations
To calculate $J_2J_4^{-1}J_3$, I first compute $\tilde{J_2}=J_2J_4^{-1}$ as follows:
$$\tilde{J_2}^T=(J_2J_4^{-1})^T=(J_4^{-1})^TJ_2^T$$
Thus, I get $\tilde{J_2}$ by solving the system:
$$J_4^T\tilde{J_2}^T=J_2^T$$
and tacking the transpose.
Edit:
The above is implemented in Matlab and I use the conjugate transpose ' (mathworks.com/help/matlab/ref/ctranspose.html) for both the real and the complex. Also I use dot (mathworks.com/help/matlab/ref/dot.html) for the dot products.
Problem
This way of solving works perfectly when $J$ is real (even if $b$ is complex). That is, solving $Jz=b$ directly or by building the Schur-complement gives the same $z$ as expected. However, when $J_4$ becomes complex, then I get different results...
I suspect that I did something really wrong when taking the transpose for $\tilde{J_2}$ or doing the dot product for $J_2J_4^{-1}b_y$. Yet, I fail to detect my error.
Note: The reason I solve using the Schur-complement is that matrices $J_2,J_3,J_4$ have some particular structures that allow for good parallelization of the operations involved. E.g. $J_4$ is block diagonal and non-singular.
Comment: Interesting! Do you have any reference of how this method works?
Comment: Hi, there is nothing really complicated, just linear algebra manipulations. At the wiki article (https://en.wikipedia.org/wiki/Schur_complement) there is a section "Application to solving linear equations". If you need more help, let me know!
Answer: Your approach looks good, so you may have a bug somewhere in your implementation. As a validation, I ran the following simple test case involving a randomly generated dense complex matrix $J$ and a randomly generated real right-hand side $b$.
<code>N = 100;
M = 30;
J = exp(2i*pi*rand(N));
b = rand(N,1);
Jd = (J(M+1:end,M+1:end)' \ J(1:M,M+1:end)')';
x = b(1:M) - Jd*b(M+1:end);
Jd = J(1:M,1:M) - Jd*J(M+1:end,1:M);
x = Jd \ x;
y = b(M+1:end) - J(M+1:end,1:M)*x;
y = J(M+1:end,M+1:end) \ y;
z = [x; y];
ztrue = J \ b;
err = norm(ztrue - z) / norm(ztrue);
res = norm(J*z - b) / norm(b);
restrue = norm(J*ztrue - b) / norm(b);
</code>
Running this code multiple times the approximate averaged values for $\texttt{err}$, $\texttt{res}$, and $\texttt{restrue}$ were $1\times 10^{-13}$, $1\times 10^{-13}$, and $4\times 10^{-14}$, respectively.
Comment: Thank you! Indeed it was a bug and your program showed me the problem. In several places of the algorithm, I was using the dot product instead of *. Changing the latter fixed my problem!


Probability of detector working

Question: The number of elements that fall into detector is Poisson probability with expectation equal to 1 element per day.If less than 3 elements fall into the detector , the detector works.If 3 elements fall into the detector the probability of the detector to works is $\frac{1}{2}$.If more than 3 elements fall into the detector, it stops working.
1)What is the probability the detector to stop working?
2)If a unit contains 1000 detectors,what is the probability at least 200 to stop working?
My attempt : We have $Po(1)$ In order the detector to work the probability is
:$$\sum_{n=1}^{2}  \frac{1^ke^{-1}}{k!}  + \frac{1^3e^{-1}}{3!}*\frac{1}{2} = A$$
So in order not to work the probability will be $1-A$
for 2) the answer should be $$\sum_{n=200}^{1000} (1-A)^n*A^{1000-n} $$
Answer: For (1) it should be $$\sum_{n=0}^{2}  \frac{1^ke^{-1}}{k!}  + \frac{1^3e^{-1}}{3!}*\frac{1}{2} = A$$
for (2) the given answer is worng. The probability that $n$ detectors stop working is $$\binom{1000}{n}(1-A)^nA^{1000-n}$$ and the desired probability is
$$\sum_{n=200}^{1000}\binom{1000}{n}(1-A)^nA^{1000-n}$$

Probability of detector working


Is this Monoid Finitely Generated?

Question: Let $G$ be a finitely generated  abelian group, $H\leq G$, and $S = \{g_1, \dots, g_n\}$ be some finite generating set for $G$.
Let $G'$ be the set of negative-free linear combinations of elements of $S$. i.e. $G' = \{a_1g_1 + \dots + a_ng_n | a_1,\dots, a_n \in \mathbb{N}\}$, and let $H'= G' \cap H$.
Is $H'$ finitely generated as a monoid i.e. is there some finite subset of $H'$, $S'$ such that every element of $H'$ is a nonnegative linear combination of $S'$?
Comment: It's a good question. I hope that it doesn't get closed. Have you looked at some examples already?
Comment: Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or be closed. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognise and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Comment: First things first: are submonoids of finitely generated commutative monoids also finitely generated? If not, what is an example?
Comment: @MartinBrandenburg: A counterexample is the submonoid of $\mathbb{N}^2$ generated by $(1,n)$ for all $n$.  That can't give a counterexample for this question though since it isn't closed under subtraction.
Answer: The answer appears to be yes.
$\textbf{Lemma:}$ Let $A$ be a non-empty subset of $\mathbb{N}^n$ equipped with the partial order $(a_1, \ldots ,a_n)\leq(b_1, \ldots, b_n)$ iff $a_i\leq b_i$ for all $i=1, \ldots ,n$. Then $A$ has only finitely many minimial elements.
Let us prove this by induction on $n$. For $n=1$ this is just the well-ordering principle. Assume the lemma holds for $n\geq 1$ and let $A\subseteq \mathbb{N}^{n+1}$ be non-empty. Clearly $A$ has some minimal element, say $\mathbf{x}=(x_1, \ldots ,x_{n+1})\in A$. Then any other minimal element of $A$ must have at least one coordinate that is less than the corresponding $\mathbf{x}$ coordinate. More precisely, any other minimal element of $A$ is contained in the union
$$\bigcup\limits_{i=1}^{n+1}\bigcup\limits_{j=0}^{x_i-1} \{(a_1, \ldots ,a_{n+1})\in A: a_i=j\}.$$
Moreover, a minimal element of $A$ is in particular a minimal element of the corresponding $\{(a_1, \ldots ,a_{n+1})\in A: a_i=j\}$ set to which it belongs and by the induction hypothesis there are only finitely many of these. Since the union is finite it follows that $A$ has only finitely many minimal elements. $\square$
Now we use the lemma to show that $H'$ is finitely generated. Consider $$\bar{H}=\{(a_1, \ldots, a_n)\in \mathbb{N}^n\backslash\{\mathbf{0}\} : \sum\limits_{i=1}^n a_ig_i\in H\}.$$ This set has finitely many minimal elements, say $\mathbf{a_1}, \ldots ,\mathbf{a_m}$. Let $h_1, \ldots h_m\in H'$ be the corresponding group elements, more precisely, $h_i=\sum\limits_{j=1}^n a_{i, j}g_j$ where $\mathbf{a_i}=(a_{i, 1}, \ldots ,a_{i, n})$.
We claim that the $h_i$'s generate $H'$ as a monoid so let $h=\sum\limits_{i=1}^n a_ig_i\in H'\backslash\{e\}$. If $\mathbf{a}=(a_1, \ldots ,a_n)$ is a minimal element of $\bar{H}$ then $h$ is one of the $h_i$'s and we are done. If not, then there is a minimal element, say $\mathbf{a_{i_1}}$, with $\mathbf{a_{i_1}}<\mathbf{a}$. Since $H$ is a subgroup, we have $\mathbf{a}-\mathbf{a_{i_1}}\in \bar{H}$. If this element is minimal, say $\mathbf{a}-\mathbf{a_{i_1}}=\mathbf{a_{i_2}}$ then $h=h_{i_1}+h_{i_2}$ and we are done. If not, we continue as before. Eventually the process must terminate and we obtain that $h=\sum\limits_{j=1}^k h_{i_j}$ for some $i_j$'s.
Comment: Your lemma is known as [Dickson's Lemma](https://en.wikipedia.org/wiki/Dickson%27s_lemma). See Kruskal, Joseph B. (1972). [The theory of well-quasi-ordering: A frequently discovered concept.](https://www.sciencedirect.com/science/article/pii/0097316572900635?via%3Dihub) Journal of Combinatorial Theory. Series A. 13 (3): 298 for related results. The [graph minor theorem](https://en.wikipedia.org/wiki/Robertson–Seymour_theorem) is a further (and much more difficult) extension of [Kruskal's tree theorem](https://en.wikipedia.org/wiki/Kruskal%27s_tree_theorem).

Is this Monoid Finitely Generated?


Programmatically execute an action set (Rules module)

Question: I want to use Rules UI to define some action sets, but want to execute those actions programmatically from a custom module.
How to I execute the action by code and pass the needed arguments (just a node in this case).
Thanks!
Answer: If you have set it up as a rules component, you can use rules_invoke_component, alternative you can invoke an event, which could trigger mutiple rules by using rules_invoke_event.
Both is similar in that you pass first a name/id and the rest of the args is passed along, so something like
 rules_invoke_component('name', $node);

if your custom component rule has several parameters pass them one by one and separate them with comma as example
rules_invoke_component('rules_save_search_send_activation_sms',  'paramval1', 'paramval2', ....);

is properly how you need to do it. This again depends on how the rule/component is defined and configured.
Comment: Thanks, that was exactly the function I was looking for. I had to pass the argument directly, though - probably because I just have one arg configured in the component.

`rules_invoke_component('rules_mycomponent', $node);`
Comment: @valderama, great I updated my answer in case others need the same info.
Comment: Does this work for drupal 6?
Comment: @landing Rules have changed a lot from 6 to 7, but `rules_invoke_event` exists in 6 `rules_invoke_component` does not, but I don't believe rules in 6 has the concept of components.
Comment: if you have custom rule compoent ,pass parameters one by one and separate them with comma example `rules_invoke_component('rules_save_search_send_activation_sms',  'test ', '93333333333');`


Square integrable functions with singularities

Question: Is an $L^2(\mathbb{R})$ function allowed to have a singularity? For example, think of the following
$$
f(x)=\frac{e^{-x^2}}{x^{1/3}}.
$$
In principle, $f$ is square-integrable if we split the interval of integration into the two intervals $(-\infty,0)$ and $(0,\infty)$. Is $f$ in $L^2(\mathbb{R})$?
I understand a function can have a singularity at one of the endpoint of the interval as long as it is square integrable. For example
$$g(x)=\frac{1}{x^{1/3}}$$
is in $L^2((0,1))$.
So really, my question is not only restricted to $L^2(\mathbb{R})$ but rather applies to any $L^2(I)$, where $I$ is an open interval of the reals. I am wondering if a square-integrable singularity is in the interior of the interval, then is the function in $L^2(\mathbb{R})$?
Answer: In any interval $(a,b)$ take  a point $c$ and consider $f(x)=\frac 1 {|x-c|^{t}}$ where $0<t<1/2$. Then $f$ is square integrable with a singilarity.
Comment: So to rephrase my question in terms of the example you give above: is f as you give it in the Hilbert space L^2((a,b))?
Comment: Yes, the function I have defined is in $L^{2}(a,b)$.
Answer: Yes, you can have singularities anywhere, even infinitely many of them, as long as $|f|^2$ is Lebesgue integrable on $\mathbb R$ (or $I$ as the case may be).  Just look at the definition of $L^2$.


How to use async Task to get data and show in a view?

Question: I have a web API and i want to get some data in a controller and show on a view.
this is my main class:
public class APISrv
{
   public string result = string.Empty;
    public async Task<string> GetIT()
    {
        try
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:2474/");
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Accept.Add(new
                 MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage Res = await
                client.GetAsync("api/Test/Get");

                if (Res.IsSuccessStatusCode)
                {
                    result = Res.Content.ReadAsStringAsync().Result;
                }
            }

        }
        catch (Exception err)
        {
            result=err.Message;
        }
        return result;
    }
}

i tested my class with two controllers:
one:
public ActionResult Index()
    {
        APISrv aPISrv = new APISrv();
        aPISrv.GetIT();
        ViewData["mydata"] = aPISrv.result;
        return View();
    }

in this cause "result" is a public field and always is empty,it seems main thread does not wait for async method done its work.i can see my view but "ViewData["mydata"]" is empty.
on second:
public ActionResult Index()
    {
        APISrv aPISrv = new APISrv();
        ViewData["mydata"] = aPISrv.GetIT().Result;
        return View();
    }

in this cause my page stay in "waiting for local..." mode and does not work anything.
how can i and what is the best way to get data from my class?
Answer: You are mixing Blocking calls (.Result) with async/await, which can lead to deadlocks. That is what you are not getting back results when you call the controller action.
Reference Async/Await - Best Practices in Asynchronous Programming
Either go async all the way or synchronous all the way. Try not to mix them.
result = await Res.Content.ReadAsStringAsync();

Also update the action to be async as well
public async Task<ActionResult> Index() {
    var aPISrv = new APISrv();
    ViewData["mydata"] = await aPISrv.GetIT();
    return View();
}

Additionally that service should be abstracted out and injected via constructor injection, but that is outside of the scope of this question.
Comment: Thanks for helping, your codes work nice, but can u write me in short plz, how can i handle it if i do not want to change my controller from a normal mode, i mean my controller just return "ActionResult" not "Task" ?


Lucas-Kanade Optical Flow: Turning U and V into pixel locations

Question: I am working on implementing Lucas-Kanade in python for an assignment but I am having trouble understanding how to turn the outputs (u and v) into a pixel location as seen in the first example (moving cars) on the tutorial page. In the example, the outputs of cv2.calcOpticalFlowPyrLK are automatically turned into pixel locations, but my code gives me u and v values that are mostly very small (less than 1). I can't post the code I wrote, but it is very similar to this implementation:
import numpy as np
import scipy.signal as si
from PIL import Image

def gauss_kern():
   h1 = 15
   h2 = 15
   x, y = np.mgrid[0:h2, 0:h1]
   x = x-h2/2
   y = y-h1/2
   sigma = 1.5
   g = np.exp( -( x**2 + y**2 ) / (2*sigma**2) );
   return g / g.sum()

def deriv(im1, im2):
   g = gauss_kern()
   Img_smooth = si.convolve(im1,g,mode='same')
   fx,fy=np.gradient(Img_smooth)
   ft = si.convolve2d(im1, 0.25 * np.ones((2,2))) + \
       si.convolve2d(im2, -0.25 * np.ones((2,2)))

   fx = fx[0:fx.shape[0]-1, 0:fx.shape[1]-1]
   fy = fy[0:fy.shape[0]-1, 0:fy.shape[1]-1];
   ft = ft[0:ft.shape[0]-1, 0:ft.shape[1]-1];
   return fx, fy, ft

import matplotlib.pyplot as plt
import numpy as np
import scipy.signal as si
from PIL import Image
import deriv
import numpy.linalg as lin

def lk(im1, im2, i, j, window_size) :
   fx, fy, ft = deriv.deriv(im1, im2)
   halfWindow = np.floor(window_size/2)
   curFx = fx[i-halfWindow-1:i+halfWindow,
              j-halfWindow-1:j+halfWindow]
   curFy = fy[i-halfWindow-1:i+halfWindow,
              j-halfWindow-1:j+halfWindow]
   curFt = ft[i-halfWindow-1:i+halfWindow,
              j-halfWindow-1:j+halfWindow]
   curFx = curFx.T
   curFy = curFy.T
   curFt = curFt.T

   curFx = curFx.flatten(order='F')
   curFy = curFy.flatten(order='F')
   curFt = -curFt.flatten(order='F')

   A = np.vstack((curFx, curFy)).T
   U = np.dot(np.dot(lin.pinv(np.dot(A.T,A)),A.T),curFt)
   return U[0], U[1]

Comment: Did you ever figure it out? I am working on an optical flow implementation from scratch as well and am running into the same problem.
Answer: That's expected. I am working on the same problem. If you check calcOpticalFlowPyrLK, you'll see that it has some small deltas as well.
Just make sure you don't lose those floating points by rounding them in every iteration.


What's the contrapositive to the statement: a quadrilateral is a parallelogram if it is a rectangle

Question: my hypothesis: a quadrilateral is a rectangle (p)
my conclusion: a quadrilateral is a parallelogram (q)
in other words:
if a quadrilateral is a rectangle then it is a parallelogram (p implies q) (which is a true statement)
so my contrapositive would be:
if a quadrilateral is not a parallelogram then it is not a rectangle (not q implies not p)
which to me seems like it's a false statement because a diamond would be a parallelogram but it is not a rectangle
so where do I go wrong? thanks for the help
Comment: Your example is not a counter example. You have to say : "A diamond is not a parallelogram then it's not a rectangle".
"$\text{not} (p) \rightarrow \text{not}(q)$" and not "$p \rightarrow \text{not}(q)$".
Comment: The statement "if a quadrilateral is not a parallelogram then it is not a rectangle" is correct.
Comment: Thanks that makes sense
Comment: Why is that a contradiction?  You statement is about quadrilaterals that are not rectangles.  As a diamond is not a quadrilateral that is not a rectangle your statement doesn't have anything at all to say about diamonds. .... Are you confusing your "if" statements with "if and only if" statements?  Or are you assuming $\lnot p\to \lnot q\implies p \to q$?  It doesn't.  "If I am not a mammal then I am not a walrus"  most certainly does *not* mean "If I *am* a mammal then I am a walrus".
Answer:
if a quadrilateral is a rectangle then it is a parallelogram (p
implies q) (which is a true statement)
so my contrapositive would be: if a quadrilateral is not a
parallelogram then it is not a rectangle (not q implies not p)

The above statements are indeed contrapositive of each other, but note that your natural-language sentences (which refer to any quadrilateral) actually translate as $$∀x\;(Px{\implies}Qx)\\∀x\;(\lnot Qx{\implies}\lnot Px)$$ instead.

which to me seems like it's a false statement because a diamond would
be a parallelogram but it is not a rectangle
so where do I go wrong?

A diamond isn't a counterexample to your contrapositive statement; a legitimate counterexample (to either statement) would be some rectangle that isn't a parallelogram.


CA Rally - Concurrency conflict: [Object has been modified since being read for update in this context] Error

Question: I have an array of testcases that I am attempting to add to a testset in Rally using the rally api's.
I iterate through the array and call this method for every testcase in the array.  They are all being added to the same testset.

RallyConnect.prototype.addTestCaseToSet = function (tcObjectID, tcRef, tsObjectID, tsRef) {
    return new Promise((resolve, reject) => {

        // check to make sure it doesn't already exist
        rallyApi.query({
            ref: '/testset/' + tsObjectID + '/testcases',
            fetch: "true",
            query: queryUtils.where('ObjectID', '=', tcObjectID)
        }, function (error, result) {
            if (error) {
                reject(error);
            } else {
                if (result.TotalResultCount > 0) {
                   resolve({ tsRef: tsRef, tcRef: tcRef, action: 'exists' });
                } else {
                        rallyApi.add({
                            ref: tsRef,
                            collection: 'TestCases',
                            data: [{ _ref: refUtils.getRelative(tcRef) }]
                        }, function (error, result) {
                            if (error) {
                                reject(error);
                            } else {
                                resolve({ tsRef: tsRef, tcRef: tcRef, action:
 'added' });
                            }
                        });
                }
            }
        });
        //});
    });
}

I get the following error quite a bit and the process fails

Error: Could not add artifact to collection
    at generateError (C:\src\testing_utility\node_modules\rally\dist\request.js:38:11)
    at Request._callback (C:\src\testing_utility\node_modules\rally\dist\request.js:118:22)
    at Request.self.callback (C:\src\testing_utility\node_modules\rally\node_modules\request\request.js:187:22)
    at emitTwo (events.js:125:13)
    at Request.emit (events.js:213:7)
    at Request.<anonymous> (C:\src\testing_utility\node_modules\rally\node_modules\request\request.js:1044:10)
    at emitOne (events.js:115:13)
    at Request.emit (events.js:210:7)
    at Gunzip.<anonymous> (C:\src\testing_utility\node_modules\rally\node_modules\request\request.js:965:12)
    at emitNone (events.js:110:20)
  errors:
   [ 'Could not add artifact to collection',
     'Concurrency conflict: [Object has been modified since being read for update in this context] - ConcurrencyConflictException : Modified since read on update
: Object Class : com.f4tech.slm.domain.TestSet : ObjectID : 203533554680' ] }

Has anyone else run into this issues and know what I can do to ensure I don't get it.
Answer: Rather than looping and adding the test cases one at a time, can you add them in a batch?
rallyApi.add({
    ref: tsRef,
    collection: 'TestCases',
    data: [
        { _ref: refUtils.getRelative(tcRef1) },
        { _ref: refUtils.getRelative(tcRef2) }, //include multiples here
        { _ref: refUtils.getRelative(tcRef3) },
        { _ref: refUtils.getRelative(tcRef4) },
    ]
});

Note, this approach is limited to 25 records per batch I think, so depending on how much data you're generally associating to a test set you may have to break it up into chunks of 25.
The other thing to check, is are you using the same rallyApi instance for each of the calls?  From your code it seems like it.  As long as this is true, and as long as cookies are enabled I think you should be pinned to the same app server for all your requests and shouldn't be seeing these exceptions (which are usually caused by quick updates to related objects during background cache syncing across all the server nodes).
You can also try adding this config when newing up your rallyApi instance:
{
    requestOptions: { jar: true }
}

That should ensure your requests are maintaining cookies.
Comment: @psysane, the java toolkit should support cookies by default.  It also exposes an updateCollection method to be able to bulk add/remove items from a collection.  I'd suggest posting a new question if you continue to run into issues.
Comment: Is there any Java alternative @Kyle?
Answer: For the benefit of the community...  I also got this error message, but for a somewhat different reason.  I'll put it here, because it's the only place it's been discussed on the wider web.  (If there's a discussion of it hidden away somewhere in in Rally's own forums, feel free to link!)
I got the error when attempting to save a Portfolio Feature item on which I had been making edits for a long time without saving (because it was a large field, and I don't like scrolling through endless miles of revision history).
I had four image.pngs on the item -- from things I'd pasted directly inline instead of including as attachments via an 'Image' button inset, and one or more of which the editor had vanished (as it sometimes does).
It was one or more of the missing image.png 'attachments' that it couldn't place, preventing it from saving.  I deleted the image.png files from the attachments (without the actual images disappearing from the body of the field!) and it saved fine after that.
Answer: https://rally1.rallydev.com/slm/doc/webservice/
specifically: https://rally1.rallydev.com/slm/doc/webservice/bulk.jsp
unfortunately, I've not figured out how to add items to collections via bulk upload.  I'm specifically adding defect references to a defect suite.
I am not using any lib....rather, I'm just calling the rally API (which is downright awful and reminds me of the 90s)
Comment: in Java / Spring, I ended up using https://stackoverflow.com/a/55165057/526664 as a guide...worked great.  This solution causes all RestTemplate calls to go to the same Rally server (remember, this is all 90s tech and uses sticky sessions via cookies).  This allows you to do a GET immediately after a CREATE


Problems in testing telnet using postfix

Question: i am quite new so please be a bit patient XD
i am trying to configure a mail server using postfix (which implements a database for aliases, domains and mailboxes) and courrier on ubuntu. I have this problem when i test the command telnet:
451 4.3.0 : Temporary lookup failure
I followed this guide: http://guide.debianizzati.org/index.php/Postfix-mysql#Postfix
Do you know how can i solve this problem? Tell me which log and configuration file do you needn to know.
Thanks for help.
Answer: What are you trying to do? Send a test email through telnet? The syntax is "telnet $host $port" and in your case, "telnet localhost 25" if you've got postfix configured correctly as your default MTA and it is working correctly.
Comment: yes i am trying to send a test mail but it doesnt seem to be correct and i dont know why. the process is listening but when i try
mail from:
and mail to: i receveid that error.


How to use Form API #attached and module's own scripts with jQuery Multi module?

Question: I was using jQuery Update module, but it conflicts with Views and feature requests for library version per page or per theme are consistently killed. On the other side, Views maintainers seems to assume that if UI works with distribution's jQuery, it isn't broken. Long story short, I was forced to forget about jQuery Update the way we know it.
Solution I found is jQuery Multi module, as it allows load updated jQuery only, if there is a library that requires it in use on the page. And for things like Chosen (when jQuery Update is hacked out of requirements) it works great. Now, I have problem with javascripts directly attached to forms:
$form['#attached']['js'] = array(
  drupal_get_path('module', 'aat_pc_product') . '/js/tag.js',
  drupal_get_path('module', 'aat_pc_product') . '/js/tabs.js',
  drupal_get_path('module', 'aat_pc_product') . '/js/categories.js',
);

jQuery Multi claims it can be used on any js file, but it's documentation says:

C) Put the JS anywhere else, like in a custom module, and use hook_jqmulti_files() to load it. No need to use the alias.
  38
D) Put the JS anywhere, use the provided alias, and don't use the jqmulti hooks or UI. Simply load with drupal_add_js() or something similar. If you're only using this method, make sure to select the 'Load Always' checkbox in the jQuery Multi config.

Now, I can't do C) as I'm using Form API and I can't do D) as it breaks Views.
Form API for #attached says:

Description: Allows loading of CSS, Javascript, libraries,

Converting my scripts to a libraries would help, as A) and B) options for jQuery Multi are for libraries, but only examples provided by Form API are for JS and CSS files.
There is one use-case for libraries provided:
$form['#attached']['library'][] = array('system', 'jquery.cookie');

but it's there without description.
I can make my scripts library:
function amymodule_library() {
  $module_path = drupal_get_path('module', 'mymodule');
  $items = array();
  $items['mymodule_form'] = array(
    'title' => t('My Module Form'),
    'version' => '1.0.0',
    'js' => array(
        $module_path . '/js/tag.js' => array(),
        $module_path . '/js/tabs.js' => array(),
        $module_path . '/js/categories.js' => array(),
    ),
    'css' => array(
      $module_path . '/css/mymodule_form.css' => array(),
    ),
  );
  // dpr($items);
  // die();
  return $items;
}

And attach it as a library to a form:
$form['#attached']['library'] = array(
  array('mymodule', 'mymodule_form'),
);

Sadly this does not make it appear on the configuration screen:

I know it's due to the first 2 methods described in documentation:

A) Put the JS in sites/all/libraries/ and use the UI at admin/config/system/jqmulti to select your library. All the library's JS files will be loaded with the jqmulti jQuery version. There is no need to use the alias in this case. This is ideal if you're using a prepackaged jQuery library or plugin.
B) Put the JS in sites/all/libraries/ and use hook_jqmulti_libraries() to include the library. No need to use the alias. This is ideal if you're using a prepackaged jQuery library or plugin, and is equivalent to method A.

Of course I cannot put my scripts there, they are built in part of my module.
Now, I'm perfectly open to module hacking, if that's what needed, but if there is a way to "pretend" that my module's library is in the folder jQuery Multi wants it to be, I would be grateful to know it.
Comment: When I was doing my best to ask a wise question, I made this work. So answer below. But I hope to see other answers, if there is something fundamental I'm missing.
Answer: Solution seems to be to hack jQuery Multi module.
First, we want to add module-provided libraries to the list in configuration options. Function responsible for it is jqmulti_get_available_libraries():
/**
 * Returns available libraries to be used in the admin form.
 */
function jqmulti_get_available_libraries() {
  $libs = libraries_get_libraries();

  unset($libs['jquery']);
  foreach ($libs as $key => $value) {
    $libs[$key] = $key;
  }
  return $libs;
}

To display module-provided libraries, we need to add following line:
$libs += module_invoke_all('library');

Of course now it looks ugly:

List is long and hard to understand, because these are machine names only. Red colour used to distinguish element I added by hand after taking screenshot, it's all black folks.
Form element is defined in jqmulti.admin.inc, but it's the only place that ever uses jqmulti_get_available_libraries(), so we may stay inside it instead, to limit changes to narrow area. If we change this:
  foreach ($libs as $key => $value) {
    $libs[$key] = $key;
  }

to this:
foreach ($libs as $key => $value) {
  if(isset($value['title'])) {
    $libs[$key] = '' . $value['title'] . ' ' . @$value[version] . ' (' . $key . ')';
  } else {
    $libs[$key] = '' . $key . ' (' . $value . ')';
  }
}

output will get a lot more readable:

Again, blanked a project-related row but it is there all right.
But now the fun part begins. I can save, but logic is all wrong:

Warning: scandir(sites/all/libraries/product_form): failed to open dir: No such file or directory in jqmulti_find_all_js_files() (line 180 of /var/www/sites/all/modules/jqmulti/jqmulti.module).
Warning: scandir(): (errno 0): Success in jqmulti_find_all_js_files() (line 180 of /var/www/sites/all/modules/jqmulti/jqmulti.module).
Warning: Invalid argument supplied for foreach() in jqmulti_find_all_js_files() (line 181 of /var/www/sites/all/modules/jqmulti/jqmulti.module).

Error is located in function jqmulti_find_all_js_files($dir) function. Obviously module still tries to use old way of scanning /sites/all/libraries even when I clicked a library that is not there. Function is called from jqmulti_get_library_files($library, $reset = FALSE) that blindly assume all files are in 'sites/all/libraries'. First, it's a bug in it's own right, second it's not sufficient. We need to change:
$base_path = 'sites/all/libraries';

to something smarter. For example:
if(isset($libraries_libraries[$library])) { // Give precedent to old way
  $path = $libraries_libraries[$library];
} elseif(isset($module_libraries[$library])) {
  $path = NULL;
  $files = array_keys($module_libraries[$library]['js']);
} else { // Fallback to the old way, for what it's worth
   $path = $base_path . '/' . $library;
}

As you can see, if module gave us files already, there is no need to play with $path, we may use it directly. So code below needs to be wrapped in if.
That's all, now it works. Without conflict with Views, but with all jQuery Multi's own issues, some especially urgent for me.


Como funciona um teste de caixa preta?

Question: Na minha aula de teste de software o professor falou a respeito desse tipo de teste bem superficialmente e acabei não conseguindo perguntar para ele mais detalhes em relação ao teste.
Portanto, eu gostaria de saber como funciona o teste de caixa preta, quais componentes estão envolvidos nele e como ele é executado?
Answer: Tem 3 tipo de testes:

Caixa preta
Caixa branca
Caixa cinza

Testar em caixa preta
Significa testar apenas as funcionalidades do aplicativo, ou seja, ver se ele faz o que deve fazer, sem ver o código. Tem input, tem output e conforme no input você deve ter o output esperado.
Neste caso, quem faz o teste tem o perfil do usuário.
Para isso, ele deve preparar planos de testes a fim de "simular" o que um usuário vai fazer: coisas certas e também coisas erradas, por exemplo: colocar um CPF no campo data de nascimento.
Testar em caixa branca
Significa testar visualizando o código. Precisa de uma pessoa que sabe ler o código e precisa também de ferramentas para analisar o código.
Testar em caixa cinza
Mistura o teste em caixa preta com o teste em caixa branca.
Exemplos
Exemplo básico para entender melhor, com o teste de um veiculo:

Caixa preta:

Ligar o motor
Ligar as luzes
Buzinar.
Dá certo? O carro esta OK.

Caixa branca:

Levamos o carro na oficina onde o mecânico vai olhar o
motor
O mecânico verificará se a bateria esta OK.
Dá certo? O carro esta OK.

Caixa cinza:

Levamos o carro na oficina e quando o mecânico esta
olhando o motor, nos ligamos.
Answer: O teste de caixa preta é o mais fácil que existe porque ele não depende de detalhes de implementação de como o que está sendo testado trabalha. Para aplicar o teste de caixa preta basta saber interagir com a API pública daquilo, então se for um método basta saber que argumentos passar para ele e que resultado ele te dará. Se for uma classe, poderá fazer o teste apenas entendendo o funcionamento geral dela, como constrói e manipula seu comportamento e estado.
Ele se chama de caixa preta porque você não vê o que tem dentro da caixa.

Black box testing é apenas uma técnica que pode ser aplicada para qualquer tipo de teste que esteja fazendo, seja um teste de unidade, de integração ou outros.
O teste de caixa preta testa apenas se certos conjuntos produzem o resultado esperado. Ele pega a especificação obtida do problema e aplica seus conceitos para ver se acontece o que se esperava, não importa como ele faz internamente.
Este teste pode ser aplicado por alguém muito ligado em desenvolvimento de software mas que não programa correntemente já que ele não exige conhecimentos específicos avançados de programação, ele não cuida do código.
Ele é fácil de ser aplicado mas difícil de ser feito corretamente pelo mesmo motivo da dificuldade de desenvolver software, ter os requisitos certos e modelar algo que atenda esses requisitos sempre é mais difícil que escrever código que qualquer pode aprender em dias, modelar depende de muita experiência e raciocínio amplo.
Uma das críticas que faço aos testes é que se pode falhar tanto na modelagem, provavelmente você falhará nos testes. Isto não é motivo para não testar, mas é motivo para não dar crédito tão grande aos testes como bala de prata para se obter qualidade em software.
No mundo ideal haveria uma pessoa especificando, outra escreve os códigos e uma terceira criando os testes que garantem que tudo está correto, mas se essa terceira fizer burocraticamente partindo do trabalho da primeira, pouca vantagem tem. E seria bom ter uma que questiona o trabalho de todos, assim é mais fácil achar erros, mas sai caro. Na prática isto raramente acontece e diminui seu valor.
A parte ruim dele é que não garante que tudo o que pode ser executado será. Não se sabe o que pode dar errado por razões variadas. E teste bom é o que testa o que pode dar errado e não testar se dá certo o que se espera. Com o teste de caixa preta você pode tentar valores ruins, mas não pode forçar certas partes executarem de determinada forma porque não sabe o que está lá.
Caixa Branca
Ele se opõe ao teste de caixa branca que procura avaliar cada detalhe do código. Bem grosso modo (isto está tecnicamente errado, só para fazer uma analogia) podemos dizer que o teste de caixa preta é como programar orientado a objeto e o teste de caixa branca é como programa imperativo. O primeiro cuida da estrutura geral o segundo cuida do detalhe de implementação. O teste de caixa branca cuida do controle de fluxo e as decisões específicas tomadas, mudança de estado interno dos objetos e dos dados locais dos métodos. Ou seja, é o oposto do que a outra resposta cita como exemplo. O exemplo correto ali seria testar cada fio, cada engrenagem no motor, se cada mínimo elemento está se comportando como deveria.
Claro, tem uma infinidade de coisas pra falar sobre isto, mas a seria uma resposta muito ampla.
Coloquei no GitHub para referência futura.

Como funciona um teste de caixa preta?


Alias not updated after using source .bashrc

Question: I am testing the bash behavior on login (terminal 1), but I got confused about its interaction with alias:
I opened with vim .bashrc and add this line :
alias ls='ls -l'

and save it with :x
then  I used source .bashrc to simulate a new login session and I found it in the aliases list
But I removed the alias from .bashrc and use source .bashrc again I saw that alias ls='ls -l' was still available. On the other hand, opening new shell terminal (terminal 2) the problem was solved.
Question: Why alias ls='ls -l' was not removed on the first terminal ?
Comment: `source` does not "simulate a new login" it just executes the operations in the file in the current shell.  None of those operations removed the alias.
Comment: `source .bashrc` is basically the same as copy-pasting the contents `.bashrc` into your shell. If you copy-paste `echo Hello; alias ls='ls -l'` then you would expect Hello to be written and an alias to be defined. If you afterwards copy-paste `echo Hello`, you would NOT expect the `ls` alias to disappear. Same thing here.
Comment: I mean instead of login again I used source. But the rest of your sentence is not understood, could you please explain more ?
Comment: Thank you so so much, now it is clear :)
Comment: Please note the comment in the bash man page, which I believe predates 1996: "For almost every purpose, aliases are superseded by shell functions."  IMO, "almost every purpose" is an understatement; there is no need to use aliases.
Comment: @WilliamPursell With some effort, I can find some corner cases where there may still be useful, hence the "almost every", but TBH I do agree with your "there is no need to use aliases"
Answer: Sourcing .bashrc doesn't clear what you have defined so far. It just adds the definitions it contains to your current environment.
If you want to undefine a given alias, just type:
$ unalias ls
$ source .bashrc

If you want to undefine all aliases:
$ unalias -a
$ source .bashrc

Finally, if you want to start over with a brand new shell, you can of course close your session and reopen one, but here is an almost identical command in case this is not that easy (ssh) or undesirable:
$ exec bash

(you may also add the -l option to simulate a login shell, thus reading your ~/.bash_profile file)


Error using fit in sklearn for covariance estimation

Question: I have a variable xcin which contains data in form of an array . I am trying to fit this data using fit() present in GraphLassoCV .
Data present in xcin :
[ 0.722    0.32202  0.70102  0.7414   0.18204  0.01132  0.171    0.723
  0.722    0.52605  0.70102  0.7414   0.29253  0.95     0.729    0.7414
  0.74999  0.7412   0.454    0.7414   0.15122  0.7414   0.65992  0.723
  0.70102  0.45209  0.521    0.7412   0.92412  0.01403  0.45203  0.723
  0.9303   0.454    0.74999  0.5232   0.6309   0.1712   0.7414   0.221
  0.70102  0.851    0.241    0.01122  0.749    0.749    0.24232  0.454
  0.80904  0.454    0.40106  0.74999  0.74999  0.17123  0.74999  0.7412
  0.271    0.7414   0.55204  0.7414   0.5259   0.7414   0.749    0.7414
  0.722    0.28133  0.9219   0.749    0.729    0.749    0.3311   0.45201
  0.9303   0.45201  0.722    0.6304   0.722    0.40106  0.45205  0.18109
  0.722    0.749    0.749    0.5259   0.40107  0.40106  0.36911  0.7414
  0.7412   0.74999  0.154    0.851    0.722    0.154    0.722    0.74999
  0.29253  0.729    0.7412   0.6309 ]

I tried using the following code :
xcin =np.array([df['xcin']])/100000.0
# Learn a graphical structure from the correlations
edge_model = covariance.GraphLassoCV()
X = xcin.copy().T
X /= X.std(axis=0)
edge_model.fit(X)

But I am getting an error on edge_model.fit() line :
ValueError: Found array with 1 feature(s) (shape=(100, 1)) while a minimum of 2 is required by GraphLassoCV.

Can someone explain how to resolve this .
I am trying to follow the approach as demonstrated here (http://scikit-learn.org/stable/auto_examples/applications/plot_stock_market.html#sphx-glr-auto-examples-applications-plot-stock-market-py ) to generate a similar type of visualization .
Comment: sklearn tells you what the problem is. The shape of the input is wrong (100 samples with 1 feature; sklearn wants >= 2 features). But i don't understand your combination of data & algorithm here so it would be a good idea to add some more information before someone can help.
Comment: I am trying to do clustering based on industry codes . These 100 data points correspond to different types of industries which are present . I wanted to use affinity propagation because the number of clusters is not known from the beginning . What can I do in this case
Answer: Your data is 100x1 meaning that you have 100 numbers. So this is either 100 samples of 1dim data or 1 sample of 100 dim data. Either way there is no concept of covariance matrix with such data, you need at least 2 samples and 2 dimensions. With just one dimension the only things you can compute is a variance. In particular this behaviour is commented in the source code
# Covariance does not make sense for a single feature
X = check_array(X, ensure_min_features=2, estimator=self)

Comment: I am trying to do clustering based on industry codes . These 100 data points correspond to different types of industries which are present . I wanted to use affinity propagation because the number of clusters is not known from the beginning . What can I do in this case
Comment: Ml is really not for one domensional data. Something that simple can be achieved woth simple scripts, drawing your data etc.
Answer: use sklearn.preprocessing.PolynomialFeatures(2).fit_transform(X)  to make more features
Comment: Please elaborate little more about the solution you have given. Use formatting for your line of source code. Consider reading https://stackoverflow.com/help/how-to-answer


jQuery / ajax, set select option

Question: I am looking at setting the option for my select dropdown which has been passed back from the DB.
 "<select id=\"sel" + res.sku.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-') + "\"><option>True</option><option>False</option></select>	" +

I have it passing over the option true or false, how would i go about setting this on the option please?
Thanks in advance.
Comment: Do you want to select one of the two automatically? Try ``.
Comment: @thattuxguy Did you have a chance to try any of the answers that were posted?
Comment: Sorry, i chose to go down a different route. Basically it was silly to use a drop down as most items would be false as true is not displayed. So  i simply added a update button, which then updates the DB and removes the row from the table.

Seemed to be the best way for this. I was only going to use a dropdown as the person who made the previous version of the software did so.
Answer: Please see the article: .prop() vs .attr()
 $('#sel').prop('checked', false)

Or you could change the false to a true, depending upon your application's logic.
Comment: You're right, @pimvdb.  I just reasoned that since it was a true or false, it would was a radio button, not a pull down (my mistake).  I might suggest that thatuxguy use a Radio button since true and false are mutually exclusive.
Comment: I'm not sure what checking a select element means. You'd at least need to specify the option.
Answer: I agree with Sable that a radio button might be a better choice in this situation, but if you're determined to use a drop down list, you can try something like this:
"<option" + (myValue === true ? " selected" : "") + ">True</option><option" + (myValue === false? " selected" : "") + ">False</option></select>	"

Comment: tested using this, and it worked well however i used a update button instead which made more sense. Thanks though, i will no doubt use this somewhere in the app :)

jQuery / ajax, set select option


Criar um atalho da aplicação em um onLogClickListener?

Question: O código abaixo, cria um atalho na tela inicial do aparelho, mas ao clicar neste atalho, ele me retorna um erro "O app não está instalado"
Como resolver?
Gostaria que esta mainactivity fosse aberta com parametro especifico, para disparar um evento ao ser aberta por este atalho criado.
Segue abaixo o código utilizado:
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />

fabEmergencia.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        createShortCut();
        return true;
    }
});

private void createShortCut() {
    Intent shortcutIntent = new Intent(activity,MainActivity.class);
    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    Intent addIntent = new Intent();
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "YourAppName");
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(activity, R.drawable.ic_launcher));
    addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
    activity.sendBroadcast(addIntent);
}

Answer: Geralmente quando uso, faço desta forma abaixo:
public void criarAtalho(){
    // cria intent para criar atalho
    Intent shortcutintent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
    // nega atalho repetido
    shortcutintent.putExtra("duplicate", false);
    // define um nome para o atalho
    shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Nome do atalho");
    // define do icone do atalho
    Parcelable icon = Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.mipmap.ic_launcher);
    shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
    // define atividade que será iniciada ao clicar no atalho
    shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(getApplicationContext() , MainActivity.class));
    // envia broadcast
    sendBroadcast(shortcutintent);
}

Aí no método setOnLongClickListener, você faz desta forma abaixo:
fabEmergencia.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        criarAtalho();
        return true;
    }
});

E como você já comentou na questão, deves dar permissão no AndroidManifest. Veja:
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>

Abaixo como deve estar sua <activity> no AndroidManifest:
<activity
    android:name=".MainActivity"
    android:label="@string/title"
    .
    .
    .
    >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

Comment: Entendi meu erro, a launcher, é uma splashactvity, ela deve ser chamada. :/
Comment: O erro acontece, ele cria o atalho, mas ao clicar neste atalho aparece "O app não está instalado"
Comment: Aqui comigo funciona normalmente! Seu intent está apontado para classe principal?
Comment: Sim, está apontando para MainActivity. Mas o botão também está na MainActivity. shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(this, MainActivity.class));
Comment: @HenriqueMendes exatamente isso que eu ia falar!


Specify Chef provider for windows_feature

Question: I originally asked this question on StackOverflow, but did not receive any working answers: https://stackoverflow.com/questions/18648713/specify-chef-provider-for-windows-feature.
I'm trying to use Chef (chef-solo) to manage my Windows Server 2008 R2 installation. Chef provides windows_feature to add roles/features to a Windows server. By default, windows_feature uses DISM to install roles (if available). However, to my knowledge, not all roles (e.g., RDS-RD-Server) are able to be added via DISM.
I could presumably use Chef::Provider::WindowsFeature::ServerManagerCmd (identified in the Windows cookbook readme: https://github.com/opscode-cookbooks/windows), but it doesn't look like that is a real class (browsing the source code there). Also, servermanagercmd is deprecated (though it would work).
I wouldn't mind even using a powershell block to add the role, but I'm having a hard time ensuring idempotence. It seems like the not_if command shell is some weird mingwin shell rather than CMD.
Here's a sample of what I've tried using powershell (doesn't work):
powershell "install_rds_server" do
  code %Q{
    Import-Module Servermanager
    Add-WindowsFeature RDS-RD-Server
  }.strip
  not_if %Q{
    powershell "Import-Module Servermanager; $check = get-windowsfeature -name RDS-RD-Server; if ($check.Installed -ne \"True\") { exit 1 }"
  }.strip
end

I've also tried the following:
windows_feature 'RDS-RD-Server' do
  provider Chef::Provider::WindowsFeature::ServerManagerCmd
end

which returns the following error:
FATAL: NameError: uninitialized constant Chef::Provider::WindowsFeature::ServerManagerCmd

What would be the recommended Chef way of adding this role?
Answer: Based on the Chef documentation for LWRPs, I think the actual class name for the LWRP in the windows cookbook is
Chef::Provider::WindowsFeatureServermanagercmd

As such, you should use something like
windows_feature 'RDS-RD-Server' do
  provider Chef::Provider::WindowsFeatureServermanagercmd
end

Comment: Thanks again for your help. I'm accepting your answer because it answered my primary question, but I also posted as an answer the solution I ended up using.
Comment: Thanks! Wow, what an ugly class name--`Chef::Provider::WindowsFeatureServermanagercmd`. You are right, though, and all of the Chef Windows docs (on their website and Github)  are wrong (e.g., http://docs.opscode.com/lwrp_windows.html).
Comment: The first (kind of) works, the second returns an error: `undefined method 'windows_feature_servermanagercmd' for Chef::Resource::WindowsFeature`. I say "kind of" works because the deprecation warning for servermanagercmd is causing a fatal error in Chef: `Expected process to exit with [0, 42, 127], but received '1003'`.
Comment: You are right, the "short" name doesn't work. I misinterpreted some blog posts and have subsequently removed the wrong information now. Why the remote call from the provider still fails is beyond my knowledge as I have never used Chef on Windows (or even used Windows at all in the last 2 years :) You might want to debug [the process invocation](https://github.com/opscode-cookbooks/windows/blob/master/providers/feature_servermanagercmd.rb#L25-L27) yourself (and maybe provide a patch for the cookbook).
Answer: Holger Just's solution works, more or less, though the servermanagercmd.exe deprecation message causes some issues. Here is how I ended up resolving the issue:
ps_64 = 'C:\Windows\sysnative\WindowsPowershell\v1.0\powershell.exe'

powershell "install_rds_server" do
  code %Q{
    Import-Module Servermanager
    Add-WindowsFeature RDS-RD-Server
  }.strip
  not_if %Q{
    #{ps_64} "Import-Module Servermanager; $check = get-windowsfeature -name RDS-RD-Server; if ($check.Installed -ne 'True') { exit 1 }"
  }.strip
end

My initial Powershell based solution wasn't working because the generic powershell command was launching the 32-bit Powershell. This solution is still very hacky, but I prefer it over using the deprecated servermanagercmd.exe.


Which F1 driver has won races at the most tracks?

Question: I know that Lewis Hamilton has more than 100 wins, but how many different tracks has he won at? And is he the driver that has won at the most different tracks?. For example, Lewis has won 8 times at Silverstone, but let's count as one particular track win.
Answer: Yes, at time of writing, Lewis Hamilton has won at the most different Grand Prix, as well as individual circuits - 31 for both.
Different Grand Prix (source)

Number
Grand Prix
Year of First Win
Number of Wins

1
Canada
2007
7

2
USA
2007
6

3
Hungary
2007
8

4
Japan
2007
5

5
Australia
2008
2

6
Monaco
2008
3

7
Britain
2008
8

8
Germany
2008
4

9
China
2008
6

10
Singapore
2009
4

11
Turkey
2010
2

12
Belgium
2010
4

13
Abu Dhabi
2011
5

14
Italy
2012
5

15
Malaysia
2014
1

16
Bahrain
2014
5

17
Spain
2014
6

18
Russia
2014
5

19
Austria
2016
1

20
Mexico
2016
2

21
Brazil
2016
2

22
Azerbaijan
2018
1

23
France
2018
2

24
Styria1
2020
1

25
Tuscany
2020
1

26
Eifel
2020
1

27
Portugal
2020
2

28
Emilia-Romagna
2020
1

29
São Paulo2
2021
1

30
Qatar
2021
1

31
Saudi Arabia
2021
1

This was the second race held at the Red Bull Ring in Austria in a COVID-19 impacted season.
Officially the 2021 Brazilian GP was called the 2021 São Paulo Grand Prix - hence the differential between the two. Even if you count these together LH is still well clear of Schumacher, 30 to 22.

Different Circuits (source)

Number
Circuit / Location
Year of First Win
Number of Wins

1
Montréal
2007
7

2
Indianapolis
2007
1

3
Hungaroring
2007
8

4
Fuji
2007
1

5
Melbourne
2008
2

6
Monaco
2008
3

7
Silverstone
2008
8

8
Hockenheim
2008
3

9
Shanghai
2008
6

10
Singapore
2009
4

11
Istanbul
2010
2

12
Spa-Francorchamps
2010
4

13
Nürburgring
2011
2

14
Yas Marina
2011
5

15
Monza
2012
5

16
Austin
2012
5

17
Kuala Lumpur
2014
1

18
Sakhir
2014
5

19
Barcelona
2014
6

20
Suzuka
2014
4

21
Sochi
2014
5

22
Spielberg
2016
2

23
Mexico City
2016
2

24
Interlagos
2016
3

25
Bakou
2018
1

26
Le Castellet
2018
2

27
Mugello
2020
1

28
Portimão
2020
2

29
Imola
2020
1

30
Losail
2021
1

31
Djeddah
2021
1
Answer: According to Stats F1, Lewis Hamilton does indeed hold the record for the most wins at different tracks, having won races at 31 different tracks. The next-best is Max Verstappen, who has won races at 24 different tracks.


Property of modular arithmetic.

Question:
(a / b) % c = ((a % c) * (b^{-1} % c)) % c

How to calculate b^{-1}? I know it is not 1/b. Is there more than one way to calculate this?
Answer: Well, one generally uses the generalized Euclidean algorithm. If the gcd between $b$ and $c\geq 2$ is $1$, the algorithm yields
$$sb+tc=1$$
for some integers $s,t$. Then the inverse of $b$ modulo $c$ is $s$, since $sb\equiv 1\mod c$.
Answer: The naive approach, of course, would be to simply go through the numbers $1,2,...,c-1$ and see which, upon being multiplied by $b$, gives you something congruent to $1$ mod $c$. This number will be, by definition, $b^{-1}$.
A better approach would be to use the Extended Euclidean Algorithm to find integers $x,y$ such that $$bx+cy=\gcd(b,c).$$ Assuming $b$ and $c$ are relatively prime, an inverse of $b$ modulo $c$ will be $x$.

Property of modular arithmetic.


How can I exclude pages created from a specific template from the CQ5 dispatcher cache?

Question: I have a specific Adobe CQ5 (5.5) content template that authors will use to create pages.  I want to exclude any page that is created from this template from the dispatcher cache.  As I understand it currently, the only way I know to prevent caching is to configure dispatcher.any to not cache a particular URL.  But in this case, the URL isn't known until a web author uses the template to create a page.  I don't want to have to go back and modify dispatcher.any every time a page is created--or at least I want to automate this if there is no other way.  I am using IIS for the dispatcher.  The reason I don't want to cache the pages is because the underlying JSPs that render the content for these pages produce dynamic content, and the pages don't use querystrings and won't carry authentication headers.  The pages will be created in unpredictable directories, so I don't know the URL pattern ahead of time.
How can I configure things so that any page that is created from a certain template will be automatically excluded from the dispatcher cache?
It seems like CQ ought to have some mechanism to respect HTTP response/caching headers.  If the HTTP response headers specify that the response shouldn't be cached, it seems like the dispatcher shouldn't cache it--regardless of what dispatcher.any says.  This is the CQ5 documentation I have been referencing.
Answer: I don't know about the IIS verson of the Dispatcher, but certainly with the Apache module if you add a custom HTTP header "dispatcher: nocache" it will not cache the page in the Dispatcher. You would need to change the code to add this, which would be something like:
<code>    request.setHeader("Dispatcher", "nocache");
</code>
It might also work as meta tags in the html, but I've not tried this.
This is documented here: http://dev.day.com/content/kb/home/Dispatcher/faq-s/DispatcherNoCache.html
Comment: Perfect, exactly what I was looking for.
Answer: You might use cache control tags in the template's head.   See info on PRAGMA and Cache-Control meta tags here: HTTP Cache- Control.


Is this a gradient field?

Question: Let $$R = \begin{pmatrix} -1/2 &  -\sqrt{3}/2 \\ \sqrt{3}/2 & -1/2 \end{pmatrix}$$
be a rotation matrix and $A(x) = -x_2 dx_1 + x_1 dx_2$ a differential form, then since $dA = 2 dx_1 \wedge dx_2$ we have $dA = R^* dA.$
Consequently, we have that there is $f$, a $1$-form such that
$$ A - R^*A = df,$$
where $R^*$ denotes the pullback.
However, somehow this computation does not work out for me when I plug in numbers:
I get using vector notation $R^*A(x) =A(Rx) (-\sqrt{3} x/2 + y/2, -x/2 - \sqrt{3} y/2 )$ and thus
$$ A(x)-R^*A(x) = \begin{pmatrix} 1/2 (\sqrt{3} x - 3 y)\\ 1/2 (3 x + \sqrt{3} y) \end{pmatrix}$$
but this is not a gradient field
What am I doing wrong?
Answer: I believe there is a mistake in your computation. Your transformation is actually a rotation of the plane (in your case, of angle $2\pi/3$):
$$
R_\theta=\begin{pmatrix} \cos\theta &  -\sin\theta \\ \sin\theta & \cos\theta \end{pmatrix}.
$$
For any choice of $\theta$, you get $R_\theta^*A=A$:
$$\begin{aligned} R_\theta^*(-ydx+xdy)&=(x\sin\theta+y\cos\theta)d(x\cos\theta-y\sin\theta)+(x\cos\theta-y\sin\theta)d(x\sin\theta+y\cos\theta)\\
&=(\dots)\\
&=-ydx+xdy.
\end{aligned}$$
But then $R_\theta^*A-A=0$, and indeed this is of the form $df$ (for some constant function $f$).

Is this a gradient field?


How to I return a null value to to a database using c#

Question: I have created a function that should send a null value back to my database if the field length of the string is less than 2 characters but instead, it changes it to 00-00-00 on the database. Can someone please point me in the right direction.
public string dateChanger(string txtBox)
     if (txtBox.Length < 2)
            {
                return DBNull.Value.ToString();

            }
            else
            {
                var date = txtBox;

                var name = date.Substring(6, 4) + "-" + date.Substring(3, 2) + "-" + date.Substring(0, 2);
                return name;
            }
}

Below is the code I used to call function "dateChanger" and insert into database
     [HttpPost]
        public JsonResult AjaxMethodSaveStudent(string cboStudentName = "", string cboStudentSurname = "", string txtStudentMiddleName = "", string txtStudentNumber = "", string txtStudentDOB = "", string txtStudentPreferredName = "", string txtStudentPropertyName = "", string txtStudentRegImmiCardNumber = "")
        {
            long studentId = 0;
            string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
            using (MySqlConnection con = new MySqlConnection(constr))
            {
                string queryStudent = "INSERT INTO `STUDENT REGISTER` " +
                    "(`first name`, " +
                    "`surname`, " +
                    "`Middle Names`," +
                    "`DATE OF BIRTH`," +
                    "`ImmiCardNumber`) " +
                    "VALUES" +
                    "('" + cboStudentName + "'," +
"'" + cboStudentSurname + "'," +
"'" + txtStudentMiddleName + "'," +
"'" + dateChanger(txtStudentDOB) + "'," +
"'" + txtStudentRegImmiCardNumber + "') ";
                using (MySqlCommand cmd = new MySqlCommand(queryStudent))
                {
                    cmd.Connection = con;
                    con.Open();
                    cmd.ExecuteNonQuery();

                    studentId = cmd.LastInsertedId;

                    con.Close();
                }
            }

            return Json(new { success = true, studentId = studentId }, JsonRequestBehavior.AllowGet);
        }

Comment: How do you actually insert those values? You should be using Paramtized queries. Not only are they immune to SQL Injections, they can also inform you off issues. In this case it is less then clear what thoes values repesent. Some kind of String Encoded date? If so, how and when are you parsing it into the proper types?
Comment: Building quers via string conaction is just a bad idea all around. Parametised Querries give you immunity to SQL Injections, Type Safety, as well as a execution speed advantage. You should not be using strings unless it is for user facing I/O. Parse whatever string you got into a proper fitting type (int, float, DateTime) ASAP. Also is the Column in the DB actually marked as "allows null value"?
Comment: Need to emphasize parameterized queries again. The code as written is crazy-vulnerable to sql injection attacks. They will also remove any need to use or maintain the `dateChanger()` function, which makes to whole question irrelevant.
Comment: I have updated the code to show how I pass the information to the database.
Answer: The naive solution to the problem is to change the function like this:
public string dateChanger(string txtBox)
{
    if (txtBox.Length < 2) return "NULL";

    return txtBox.Substring(6, 4) + "-" + txtBox.Substring(3, 2) + "-" + txtBox.Substring(0, 2);
}

A slightly improved version of the function looks like this:
public string dateChanger(string txtBox)
{
    if (txtBox.Length < 2) return "NULL";

    return "'" + DateTime.Parse(txtBox).ToString("yyyy-MM-dd") + "'";
}

Note both of these require moving the responsibility for the SQL single quotes to the function. Otherwise there is nothing you could possibly return from this function that would ever put a NULL value into the database, because the database would treat it as a string literal. Rather than + "'" + dateChanger(...) + "'" + you just want + dateChanger(...) +. You also need to think about how to handle the need for IS rather than = when comparing to NULL.
But don't do either of these!
Both those possibilities pander to the poor practice of providing parameter data as strings. This has negative consequences for performance, maintainability, and security. Just don't do it.
The best option removes the dateChanger() function from the project completely, in favor of something like this:
[HttpPost]
public JsonResult AjaxMethodSaveStudent(string cboStudentName = "", string cboStudentSurname = "", string txtStudentMiddleName = "", string txtStudentNumber = "", string txtStudentDOB = "", string txtStudentPreferredName = "", string txtStudentPropertyName = "", string txtStudentRegImmiCardNumber = "")
{
    long studentId = 0;
    string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
    string queryStudent =
       "INSERT INTO `STUDENT REGISTER` " +
             "(`first name`, `surname`, `Middle Names`,`DATE OF BIRTH`, `ImmiCardNumber`) " +
       "VALUES (@StudentName, @Surname, @MiddleName, @DOB, @ImmiCardNumber);";

    using (MySqlConnection con = new MySqlConnection(constr))
    using (MySqlCommand cmd = new MySqlCommand(queryStudent, con))
    {
        //Use actual types and lengths from the database here.
        // Do NOT use AddWithValue() to skip setting parameter types.
        cmd.Parameters.Add("@StudentName", MySqlDbType.VarChar, 30).Value = cboStudentName;
        cmd.Parameters.Add("@Surname", MySqlDbType.VarChar, 30).Value = cboStudentSurname;
        cmd.Parameters.Add("@MiddleName", MySqlDbType.VarChar, 30).Value = txtStudentMiddleName;
        cmd.Parameters.Add("@DOB", MySqlDbType.DateTime).Value =  (txtStudentDOB.Length > 2) ? DateTime.Parse(txtStudentDOB.Substring(6, 4) + "-" + txtStudentDOB.Substring(3, 2) + "-" + txtStudentDOB.Substring(0, 2)) : (object)DBNull.Value;

        cmd.Parameters.Add("@ImmiCardNumber", MySqlDbType.VarChar, 30).Value = txtStudentRegImmiCardNumber;

        con.Open();
        cmd.ExecuteNonQuery();
        studentId = cmd.LastInsertedId;
    }

    return Json(new { success = true, studentId = studentId }, JsonRequestBehavior.AllowGet);
}

Comment: thanks for the feedback. I will change it over and hopefully, it works. FYI the date changer function still didn't work with your changes but if it's a bad idea, I am just going to leave it alone and work with your improvements.