Series expansion for iterated function

Question: I would like to find the MacLaurin expansion of an iterated function.  Finding the first few terms is not hard, but it doesn't take long before Mathematica runs out of memory using the straightforward program.
Is there some good way to find terms with reasonable time and space?
My problem allows some flexibility with the number of iterations and terms—but obviously more of both would be better.  The goal is to be able to compute the terms at some high precision without loosing precision.  This will only work when the input happens to be small, of course.  The more iterations the more work is done per iteration but the smaller the range to which it applies; the more terms the larger the range.
At the moment I'm using 100 iterations and 150 terms (though this function is odd so it's only half that many coefficients).  The eventual precision will be tens of thousands of digits, which causes some difficulties since the coefficients are large (on the order of $10^{133}$) even out to $x^{149}.$
Comment: I'm guessing it will be quite complicated. Faa di Bruno for the case of $f(f(x))$ already looks quite complicated for me.
Comment: @J.M.: Indeed, your intuition is spot-on.  Mine is a simple formula, before iteration, but it takes over two gigabytes of memory and about an hour to get the terms mentioned above.
Comment: In any event, you'd probably be interested in the matrix Bell polynomials. What version of *Mathematica* are you using?
Comment: @J.M.: 8.0.1. What is this about matrix Bell polynomials?  Haven't heard of those before.
Comment: To use *Mathematica* notation: `D[Nest[f, z, k], {z, n}] == BellY[Table[Map[Derivative[j][f], Reverse[NestList[f, z, k - 1]]], {j, n}]]`. The only reason I know these is that I had been fiddling around with Faa di Bruno lately. I'm new to this myself, that's why I upvoted your question. :)
Comment: Trott gave a recursion relation for the matrix Bell polynomial [here](http://books.google.com/books?id=Do1Opir9guIC&pg=PA1074); unfortunately, I can't see the reference [416] he is pointing to. At the very least, this looks to be related to the Carleman approach Gottfried is espousing in his answer.
Comment: In fact, the described procedere below resembles the Bell polynomials (the "second kind" in http://mathworld.wolfram.com/BellPolynomial.html); while the official Carleman -definition (due to wikipedia) is a bit more general since it relates to the derivatives of more general functions. Sometimes the Bell-matrices are also thought of taking the coefficients excluding the reciprocal factorials - but this is only a similarity scaling and does nothing principally different. The basic idea "Bell-polynomials" was developed around the function $\small f(x)=exp(x)-1 $ and is thus a bit more focused.
Comment: Ruben Aldrovandi gave -somehow as an open letter- a compilation of hints for the Carleman/Bell-matrix to be used in math'ica which I think can be distributed to interested people. I've uploaded a copy of his pdf-file here: http://go.helms-net.de/math/tetdocs/_mo/_lit/Aldrovandi_Carleman.pdf
Comment: Given the new bits with *Mathematica* today, there's a lot that could be done to streamline Aldrovandi's routines, I reckon.
Comment: Ah, found it! [Here](http://dx.doi.org/10.1016/S0898-1221(04)90059-4) is the paper that tackled those matrix Bell polynomials...
Answer: I don't really know about the general parameters of your problems at hand; but possibly my method using Pari/GP allows rather flexible work with up to 128 (or:why not 160) terms of a series and my standard precision is 200 dec digits. I've built a set of routines to express functional iteration as matrix-operations, and a flexible handling for that iterations (sometimes even fractional) by diagonalization, if applicable. If I encounter series with coefficients of 1e100, but signs are alternating then I can -in the same environment- use Euler-summation to arrive at results anyway.
In principle, what I'm doing is to construct a vector A1 containing the leading, say 128, coefficients of a power series of a function under consideration. Then I create the same way the vectors $\small A_2,A_3, \ldots $ having the coefficients of the according powers of the function, easily done by a standard call in Pari/Gp, but can also easily programmed. For the zeroth power it is just the vector $\small A_0= [ 1 ,0,0,...] $ up to the selected dimension. Then all the vectors are concatenated to a matrix $\small A = [A_0, A_1,A_2, \ldots A_n] $ (Such matrices are called Carleman-Matrix btw)
With a vector $V(x)$ which contains the consecutive powers of x (or its current value) I get then by the call $ \small V(x) \cdot A $ the result $\small V(f(x)) $ to a certain approximation.
Then function composition reduces down do matrix-multiplication $\small V(x) \cdot A \cdot B$ gives $\small V(g(f(x))$ if $\small B$ is the Carlemanmatrix of the function $\small g(x)$ , and iteration to matrix-powers $\small f(f(x)) = V(x) \cdot A^2 $ . In Pari/GP this can be done to a certain simple extent also with symbolic coefficients (but then not big matrix-size, say up to 64 x 64 at most.)
Unfortunately I don't have mathematica, so I can't be helpful with this, but I could post my couple of basic routines to show how this is done in principle.
There is a lot of finetuning, whereabouts, types of possible functions etc so I really do not know, how far this all is meaningful for your current problem at all.
[added] With a small set of basic matrices and the concept of matrix-decomposition this formalism allows a very handy upn-like environment for manipulating/analyzing powerseries. Having the basic algebraic operations at hand:
Operation of increment, or when repeated of addition, equivalents recentering of power series. It uses the Pascalmatrix P and its powers as Carlemanoperator
$ \qquad \small \begin{eqnarray}
V(x) \cdot P^\tau &=& V(x+1) \\
V(x) \cdot (P^\tau)^{-1} &=& V(x-1) \\
V(x) \cdot (P^\tau)^y &=& V(x+y) \\
\end{eqnarray}$
Operation of multiplication, equvalents rescaling of powerseries, when a small prefix d indicates the diagonal-matrix use of a vector
$ \qquad \small \begin{eqnarray}
V(x) \cdot dV(y) &=& V(x*y) \\
V(x) \cdot dV(y)^h &=& V(x*y^h) \\
\end{eqnarray}$
Operation of exponentiation, basically uses the matrix of Bell-polynomials, and logarithmizing using the factorially rescaled matrix of Stirling numbers second and first kind respectively
$ \qquad \small \begin{eqnarray}
V(x) \cdot fS2F &=& V(\exp(x)-1) \\
V(x) \cdot fS1F &=& V(\log(1+x)) \\
\end{eqnarray}$
one can then - just like with an upn-calculator - define the operation for the "square-root" Carleman-matrix for $\small f(x) = \sqrt{x} $ by
$ \qquad \small \begin{eqnarray}
V(x) &\cdot& {P^\tau} ^{-1} &=& V(x-1) \\
V(x-1) &\cdot& fS1F &=& V(\log(x)) \\
V(\log(x)) &\cdot& dV(1/2) &=& V(\log(x)/2) \\
V(\log(x)/2) &\cdot& fS2F &=& V(\exp(\log(x)/2)-1) \\
V(\exp(\log(x)/2)-1) &\cdot& P^\tau &=& V(\exp(\log(x)/2)) \\
   \end{eqnarray} $
all together
$\qquad  \small(V(x) \cdot {P^\tau}^{-1}) \cdot (fS1F \cdot dV(1/2)\cdot fS2F \cdot P^\tau )= V(\sqrt x )
$
somehow like $\small x \circ \text{DEC } \circ \text{LOGPLUS } \circ \text{MUL } 1/2
\circ \text{EXPMINUS } \circ \text{INC }  \equiv x \circ \text{SQRT }   $
and one shall see, that extracting the middle part into a separate matrix $\small SQ = fS1F \cdot dV(1/2) \cdot fS2F $ provides the carleman-matrix for $\small V(x)\cdot SQ = V(\sqrt{1+x}-1) $ with the expected coefficients for that function.
So to have a set of basic matrix-constants and basic procedures that is a toolbox for a very flexible handling of composition and iteration of functions which allow representation as power series.
Even more: if one needs fractional arguments, like with addition of fractional y in the formula above, one can introduce the general method of fractional powers of that matrices using the matrix-logarithm or diagonalization; especially the fractional power of P for fractionally-often increments is easy to define/implement.
All the above gives only an overview of the idea; there are some caveats, since we deal with matrix-products of matrices, which are ideally of infinite size, and for instance the partial product in the above formula for the sqrt of x, $\small {P\tau}^{-1} fS1F$ cannot be taken out and be made explicite (the associativity "breaks") due to occuring singularities. However, taking $\small V(x) \cdot {P^\tau}^{-1} =V(x-1) $ first allows to proceed - which means nothing else than that for the definition of power series for certain operations we need the recentering essentially .
[end additions]

For advanced handling with that problematic there is online-available material of R.P.Brent, who has in-depth analyzed composition of power series in its algorithmical implementation. I found for instance R.P.Brent "Fast Algorithms for Manipulating formal Power series" in "Journal of the Association for Computing Machinery, Vol 25, No 4, October 1978, pp 581-595" or "on the complexity of composition (...)" in "Siam J. Comput. Vol. 9, No.1 Feb 1980" and a handful related articles, but Brent's books should be present in many math-dept. libraries.
Comment: I doubted at first but it looks like PARI/GP vastly outperforms Mathematica in this calculation.  For some reason Mathematica gives the wrong answer, and PARI the right answer, when intermediate precision is the same as final precision.  Math'ca gives the right answer when it's given the result in symbolic mode but it takes forever.
Comment: Yes, that may be, as long as we work numerically. With symbolic coefficients a 64x64-Carlemanmatrix in Pari/GP needs also quite a time. Moreover, Mathematica has the ability to sometimes find analytical closed-form expressions when only finitely many leading coefficients of a powerseries are given which is impossible in Pari/GP, thus allows exact results in a wider class of functions.
Comment: Concerning coefficients of huge size there is sometimes the possibility to handle (and then evaluate) using methods of Euler- or Noerlund summation. This can easily introduced as simple matrix-multiplications in the same environment as sketched above. A worked example dealing with a question in MO is here http://go.helms-net.de/math/tetdocs/_mo/mo_101217/CoefficientsFxxFx.htm ; in that example the powerseries/Carlemanmatrix has coefficients of 1e100 and Noerlund-summation can define an equivalent which means to reduce them to 1e-120 or so...
Comment: Whew! `Power[]` was a bit tough to handle... anyway, for those who want to play around with Carleman matrices in *Mathematica*: `CarlemanMatrix[f_, {x_, x0_}, {m_Integer, n_Integer}] := Prepend[Table[If[k == 0, Function[x, f][x0]^j, BellY[Table[{FactorialPower[j, i] (Which[#2 == 0, 1, #1 == 0, 0, True, #1^#2]) &[Function[x, f][x0], j - i], Derivative[i][Function[x, f]][x0]}, {i, k}]]/k!], {j, m}, {k, 0, n}], UnitVector[n + 1, 1]]`

Series expansion for iterated function


SQL Friends (Connections) JOIN Statement

Question: tbl_Connections:

uc_Id   uc_User uc_Connection   uc_IsPending    uc_DateTime
72  jasonramia  jeffreyramia    0   2011-10-29 16:42:49.000
74  jasonramia  beta    0   2011-10-29 16:55:38.000
75  jeffreyramia    beta    0   2011-10-29 20:36:11.000

tbl_LiveStream:

ls_Id   ls_Story    ls_User ls_Connection   ls_DateTime
30  test    jeffreyramia    jasonramia  2011-10-29 19:16:48.000
31  aheln   jasonramia  jasonramia  2011-10-29 19:17:48.000
32  test    jasonramia  beta    2011-10-29 19:27:02.000

I need to return * from LiveStream for jeffreyramia (or any other user) only if ls_User or ls_Connection is friends is conncted to jeffreyramia from table tbl_Connections (uc_User or uc_Connection)
More details here: SQL SELECT From two tables (friendship) statement
Thank you in advance. :)
Comment: Nothing yet as I have no clue on how to do this... :/
Answer: Use a Union. This should get close.
SELECT *
FROM tbl_Connections AS connect
INNER JOIN
tbl_LiveStream AS live
WHERE connect.us_User = live.ls_User
UNION
SELECT *
FROM tbl_Connections AS connect
INNER JOIN
tbl_LiveStream AS live
WHERE connect.us_User = live.ls_Connection

You could also use LINQ to SQL if you have C# available with classes that encapsulate these tables, but you haven't shown a lot of detail here.
Comment: Hi, thanks for the answer. I've posted more info on this page here: http://stackoverflow.com/questions/7955971/sql-select-from-two-tables-friendship-statement i'm getting this error when executing the query Incorrect syntax near the keyword 'WHERE'. ln5 and 11
Comment: @JeffreyRamia: Replacing `WHERE` (both) with `ON` should eliminate *that* error (but might uncover another one).


Status of Apache-Commons Commons-Functor

Question: When I look at the commons-functor website website, it appears to be out of sandbox state, but it also says there is no official binary release?  But I thought I saw it in some Maven repository somewhere and can't find it now.  Does anyone know what the status is and whether there is an official binary release?  I suspect I am just poor at navigating the Commons website.
Answer: I have absolutely no idea what the release or maintenance state of this library is. My apologies.
But what i do know is that the world needs another functional programming library for Java like it needs a hole in the, er, head. Ozone layer? There are already quite a number in circulation - Functional Java, the functional parts of Guava, LambdaJ, and others - all doing much the same thing (or at least having overlapping bits doing much the same thing). What we need to do now is to start coalescing our attention around two or three of these libraries, developing common styles and idioms for using them.</rant>
At the company where i work, where there are a lot of big fans of functional programming, we seem to have settled on Functional Java, having had LambdaJ, Guava, and a couple of homebrewed functional frameworks in our codebase (and having rewritten bits of it in Scala!). That decision was made by people with deeper understanding of functional style than me, and before i joined the company, so i can't explain the reasoning, merely report that it was made. Functional Java is actively developed, and it's in Maven. I would urge you to have a look at it, and see if it meets your needs.
Comment: I appreciate the sentiment, and honestly I am not looking to start using commons-functor myself.  My interest has to do with a library-agnostic open-source add-on I am writing that is meant to support whichever library other users choose, which already has support for Functional Java (if interested you can check it out in my profile, but I'll leave direct advertising out of this comment).
Comment: Ha! I came across Funcito the other day. Cool stuff. Please excuse my presumption in trying to scare you off.
Answer: Looks like the last development was three weeks ago (see this) and their "release notes" for 1.0 are just a skeleton (see here).
A couple quick searches show that Apache Commons Lang used to have a package org.apache.commons.lang.functor - but this was removed some time ago, it seems (like 2003 or so)
As a side note, it appears that Apache Commons Collections has a package org.apache.commons.collections.functors - but this might not be what you're looking for.
Comment: I think your links at the top are what I had seen before and somehow couldn't make my way back to, thanks for finding them.  I don't think it gives a definitive answer, but it helps.  And no, I'm not interested in the old functors package.
Comment: I'd still like to know something more definitive, but you gave me the most info. so thanks.
Answer: Commons Functor is heading toward it's first official release. You can give it a try by using the nightly snapshot from the Apache repository:
https://repository.apache.org/content/groups/snapshots/org/apache/commons/commons-functor/1.0-SNAPSHOT/


iOS How to set application reminders

Question: We are creating an app which reminds a user about certain tasks.
The user can choose to recieve the reminder on the following bases:
One Time, Daily, Weekly, Weekly (on a specific week day), Every Two weeks, Once a Month
The reminders should be a custom popup in the app and/or a popup if the application is closed. My question is, what is the best way to go about setting up reminders like these?
The way I'm thinking about doing it is to load it into the phone's SQLite database and then checking for reminders each time the app starts up, and if a reminder is, let's say a daily one, the app would automatically set the next reminder. I have no idea how I'm going to do the rest yet.
Thanks
Answer: I do this in my app by using NSLocalNotification
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
if (localNotification == nil)
    return;
localNotification.fireDate = dateToRemindOn;
localNotification.timeZone = [NSTimeZone defaultTimeZone];

// details
localNotification.alertBody = @"Alert Message";
// Set the button title
localNotification.alertAction = @"View";
localNotification.soundName = UILocalNotificationDefaultSoundName;

// custom data for the notification to use later
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:reminderID forKey:@"remindID"];
localNotification.userInfo = infoDict;

// Schedule notification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

This will create the local notification and you can store any information you might need in the user info dictionary and that will be available to you when it is received or opened.
Use this method in your AppDelegate to check if the app was opened from your local notification.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Handle launching from a notification
    UILocalNotification *localNotification =
    [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
    if (localNotification) {
        //handle local notification
    }
}

And use this method in your App Delegate to catch when a local notification is received while the app is open
- (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)notif {
    // Handle notification when app is running
}

Comment: Thanks, will this notification show if the app is completely closed (not even suspended)? Or does the app need to be open? If the user presses a button on the notification I need the app to open and run a specific method inside the app.
Comment: Yeah they will receive a notification if the app is closed and if they open that notification while the app is closed then you will check for it in the didFinishLaunching method. If the notification is received while the app is running then the method didReceiveRemoteNotification will be called and you can handle it however you want.
Answer: You can setup a NSLocalNotification and handle the application states : when you are inside the app you can push your custom view, when you are outside the app you'll receive the standard alert.

iOS How to set application reminders


How do I add default values to a database table using hook_install()?

Question: I am creating a custom module with its own schema of a few tables. These tables need to have some values pre-populated into them for the module to work (default locations, select options, etc).
What's the best practices way to insert default values into these tables during hook_install?
Since drupal_write_record is not available, I can use db_query, but I just want to make sure that I'm not breaking any cardinal rules by doing so.
Answer: The better way is to do it inside hook_enable(); at the time the hook is invoked, the module is already installed, and the schema of its database is available to Drupal, and to drupal_write_record(). As the hook is invoked all times a module is enabled, and not just when the module is installed, the hook implementation should check if it didn't added those database rows already (e.g., it should use a Drupal variable containing a boolean value).
As example of module that uses hook_enable() for a similar purpose, you can check forum_enable(), or php_enable() (which adds the "PHP code" input format).
function php_enable() {
  $format_exists = (bool) db_query_range('SELECT 1 FROM {filter_format} WHERE name = :name', 0, 1, array(':name' => 'PHP code'))->fetchField();
  // Add a PHP code text format, if it does not exist. Do this only for the
  // first install (or if the format has been manually deleted) as there is no
  // reliable method to identify the format in an uninstall hook or in
  // subsequent clean installs.
  if (!$format_exists) {
    $php_format = array(
      'format' => 'php_code',
      'name' => 'PHP code',
      // 'Plain text' format is installed with a weight of 10 by default. Use a
      // higher weight here to ensure that this format will not be the default
      // format for anyone.
      'weight' => 11,
      'filters' => array(
        // Enable the PHP evaluator filter.
        'php_code' => array(
          'weight' => 0,
          'status' => 1,
        ),
      ),
    );
    $php_format = (object) $php_format;
    filter_format_save($php_format);

    drupal_set_message(t('A PHP code text format has been created.', array('@php-code' => url('admin/config/content/formats/' . $php_format->format))));
  }
}

As shown from those hook implementations, the code could necessarily need to be executed all times the hook is executed; it could also be the code needs to just executed once, as in the case the default values added to the database cannot be altered from the user, who doesn't have a user interface to alter/delete those values.
Comment: That is why I wrote, "the hook implementation should check if it didn't add those database rows already." This means that it should check if the values are already in the database table, or use a Drupal variable to check if it is has already done that task. Checking the database table would be done if those values necessarily needs to be in the database; for example, this is the case if the values are required from the module, and the users are not allowed to remove the default values.
Comment: If I did this in hook_enable(), that means the default values would be reset every time that the module is enabled and disabled. I think that is fairly common, as opposed to completely un-installing and re-installing (at which point it is expected that the database gets reset).
Comment: Thanks for the clarification. Is there any difference in storing these values in my own custom table vs. just using variable_set to store them in a persistent variable? It's just an array of values for custom select boxes.
Comment: All the values set using `variable_set()`, which are not deleted with `variable_del()`, are loaded in memory when Drupal bootstraps, and saved in a global variable; this means that they are in memory whatever the module is using those values, or not. Using a custom database table, you can be sure those values are only loaded when the module really needs it. You should not use `variable_set()` if the Drupal variable contains an array to which you keep adding a new array index all times, for example.
Comment: Looking at the code (D7). I only see 2 lines of code between the invocation of hook_install and hook_enable: an update to a local variable and a call to watchdog. So, during a real install, there is no difference whatsoever between these 2 hooks about what is available and registered and what not. The only difference is whether this is a first time install or just re-enabling the module.
Comment: @fietserwin That is correct. Consider that a module is enabled, when it is first installed; this means `hook_enable()` is invoked also for the first installation of the module.
Answer: I'd go with db_query / db_insert (D6 / D7) in hook_install().
It's not considered bad practice (and nobody is ever forcing you to use drupal_write_record()).
It is not uncommon for people to disable and re-enable modules, and in that case your code in hook_enable() would fire each time. which is not nice.


Search for terms in the index which are a prefix of the search term or vice versa (!)

Question: I would like for Lucene to find a document containing a term "bahnhofstr" if I search for "bahnhofstrasse", i.e., I don't only want to find documents containing terms of which my search term is a prefix but also documents that contain terms that are themselves a prefix of my search term...
How would I go about this?
Comment: Did not see the vice-versa part. So you also want to hit "b"? is there a minimum length?
Comment: Related (but without a proper answer for you, just says "Yes, you can"): http://stackoverflow.com/questions/10671755/lucene-prefix-search-for-indexed-data-through-standard-analyzer
Comment: Yes, there are cases where I'd also like to hit "b". Imagine a field "first_name" with just the content "D."...
Answer: If I understand you correctly, and your search string is an exact string, you can set queryParser.setAllowLeadingWildcard(true); in Lucene to allow for leading-wildcard searches (which may or may not be slow -- I have seen them reasonably fast but in a case where there were only 60,000+ Lucene documents).
Your example query syntax could look something like:
*bahnhofstr bahnhofstr*

or possibly (have not tested this) just:
*bahnhofstr*

Answer: I think a fuzzy query might be most helpful for you.  This will score terms based on the Levenshtein distance from your query.  Without a minimum similarity specified, it will effectively match every term available.  This can make it less than performant, but does accomplish what you are looking for.
A fuzzy query is signalled by the ~ character, such as:
firstname:bahnhofstr~

Or with a minimum similarity (a number between 0 and 1, 0 being the loosest with no minimum)
firstname:bahnhofstr~0.4

Or if you are constructing your own queries, use the FuzzyQuery
This isn't quite Exactly what you specified, but is the easiest way to get close.
As far as exactly what you are looking for, I don't know of a simple Lucene call to accomplish it.  I would probably just split the term into a series of termqueries, that you could represent in a query string something like:
firstname:b
firstname:ba
firstname:bah
firstname:bahn
firstname:bahnh
firstname:bahnho
firstname:bahnhof
firstname:bahnhofs
firstname:bahnhofst
firstname:bahnhofstr*

I wouldn't actually generate a query string for it myself, by the way.  I'd just construct the TermQuery and PrefixQuery objects myself.
Scoring would be bit warped, and I'dd probably boost longer queries more highly to get better ordering out of it, but that's the method that comes to mind to accomplish exactly what you're looking for fairly easily.  A DisjunctionMaxQuery would help you use something like this with other terms and acquire more reasonable scoring.
Hopefully a fuzzy query works well for you though.  Seems a much nicer solution.
Another option, if you have a lot of need for queries of this nature, might be, when indexing, tokenize fields into n-grams (see NGramTokenizer), which would allow you to effectively use an NGramPhraseQuery to achieve the results you want.


what does map! do in ruby

Question: I'm fairly new to ruby and I'm a bit confused by what the map! syntax does. I see the following line on the codebase
b.map(&:values).uniq!.map!

b.map(&:values).uniq! gives me the following output:
[["us"],
 ["au"],
 ["fr"],
 ["mx"],
 ["ad",
  "ae",
  "af",
  "al",
  "am",
  "ao",
  "aq"]]

When I add a .map! to the end of b.map(&:values).uniq! I get #<Enumerator: ...>. I'm not really sure what is happening. If anyone could explain to me what is going on that would be very helpful.
Answer: From the documentation:

Invokes the given block once for each element of self, replacing the element with the value returned by the block.
See also Enumerable#collect.
If no block is given, an Enumerator is returned instead.

This means that if you have used map! with a block - the array would have replaced all its elements with the return value of the block:
b.map(&:values).uniq!.map!(&:first)
# => ["us", "au", "fr", "mx", "ad"]

Since you did not add a block, you got an Enumerator, which is like a delayed action cursor, where you can add your block later on:
enum = b.map(&:values).uniq!.map!
enum.each(&:first)
# => ["us", "au", "fr", "mx", "ad"]

Comment: so what is the Enumerator?
Comment: check out this SO answer: http://stackoverflow.com/questions/16973624/what-is-the-purpose-of-the-enumerator-class-in-ruby

what does map! do in ruby


Panel pane visibility based on user entity reference

Question: I have a content type called 'company' with an entity reference field called 'company_managers' referencing users who will be allowed to add and edit other content types relating to this company.
The company node is displayed using panels. What I am struggling with is to create a visibility rule which will only show a panel-pane if the logged in user is referenced in the entity field 'company_managers' this will allow me to show panel panes specific to users in the 'company_managers' field.
So the psudo logic for the visibility rule would be: Check if logged in user is contained in 'company_managers' If yes show panel-pane if no dont show pane.
This seems such a simple use case that i dont want to create custom code it must be achievable 'out the box' I just cant seem to get to the answer. So after two days of researching am asking for help.
NOTE: have spoofed this behavior using the visibility rule content manager and manually selecting a user on this site. All I would need is to put in the logged in user but I dont think you can put in dynamic variables or tokens.
Help much appreciated.
Answer: Ok figured this out. On the relevant panel pane used:

Add New Rule:
Select PHP Code:

Then put in the following:
foreach( $contexts['argument_entity_id:node_1']->data->field_managers['und'] as $key => $value) { $array []=  $value['target_id']; }
return in_array($contexts['logged-in-user']->data->uid ,$array);

Commentary:
This piece of code loops through my entity reference field called field_managers on this node which references users and creates an array of user IDS.
foreach( $contexts['argument_entity_id:node_1']->data->field_managers['und'] as $key => $value) { $array []=  $value['target_id']; }

This line returns true if the logged-in-user ID is part of the array created by the code above. Uses the in_array php function.
return in_array($contexts['logged-in-user']->data->uid ,$array);

The following discussion was useful to finding the solution listed above.
https://drupal.org/node/1198282
NOTE: in the above example if you replace field_managers with the name of your user entity reference field that should be the only alteration you will need to make this work for you.
Comment: Saving PHP code in the database is generally discouraged since this is a security issue. The best way to solve this is to create a CTools access plugin. See here for an example: http://ramlev.dk/blog/2012/03/30/create-a-ctools-access-plugin/


PuTTY pscp directory listing - can you specify a different file date/time format?

Question: I'm using pscp.exe from PuTTY with the -ls option to get a directory listing via STDOUT to a perl script.
The output I get is this:
Listing directory /path/to/my/directory
drwxr-sr-x    2 234      11           4096 Feb  4 11:11 .
drwxrwxrwx   21 root     root         4096 Jan 28 17:50 ..
-rw-r--r--    1 root     11         415570 Jan 10 12:27 009800D2-10003ACC.log
-rw-r--r--    1 root     11         131072 Dec 15 09:59 MCP.20101215_095929_644.snapshot.log
-rw-r--r--    1 root     11         131072 Jan 19 13:32 MCP.20110119_133211_032.snapshot.log
-rw-r--r--    1 root     11       10240105 Feb  2 22:32 MCP.20110202_173304_750.log
-rw-r--r--    1 root     11       10240077 Feb  3 04:07 MCP.20110202_223257_159.log
-rw-r--r--    1 root     11       10240094 Feb  3 06:29 MCP.20110203_040754_861.log
-rw-r--r--    1 root     11       10240095 Feb  3 07:43 MCP.20110203_062936_730.log
-rw-r--r--    1 root     11       10240066 Feb  3 10:20 MCP.20110203_074353_058.log

However, the format of the date/time is a pain to work with. Ideally I want it to be 2011-02-04 10:02:33 instead of `Feb  4 10:02'. The main problem is there is no year or seconds.
Is there a way to specify the date/time format?
Answer: Why dont you just use plink.exe instead to execute remotely the "ls" command ?
There are plenty of ls command-line switches that will format the output as you wish. Moreover, you can remotely pipe its output into awk, sed, etc.
plink.exe user@remotehost "ls -l --full-time /my/remote/directory
Comment: plink comes with PuTTY as does pscp
Comment: ah cool... I didn't think of using that! I've just tried it and it works fine. Thank you.
Answer: I cannot comment, plink usage is the way to go, I just suggest using --time-style="+%Y-%m-%d %H:%M:%S" instead of --full-time, it gets you rid of the unwanted stuff displayed after the seconds
Comment: Thanks, but --full-time works fine. I'm using a perl regex to read the lines, so the unwanted stuff isn't a problem. It just gets ignored.
Comment: Well, in that case nevermind :)


Accessing Dictionary values inside a list

Question: I'm trying to replicate some functionality found in MATLAB in python and am looking for a pythonic way to solve this problem.
Consider the following example.
import io
import csv

data = """name,age,height
scott,31,175
bob,45,180
george,2,100
"""

f = io.StringIO(data)
reader = csv.reader(f, delimiter=',')
fields = next(reader)
table = []

for row in reader:
    item = dict(zip(fields, row))
    table.append(item)

Some data is imported, each row is an item in a list and each column is paired up with it's field name in a dictionary.
Accessing a single field of a specific element is simple
>>> table[1]['name']
'bob'

How can I return all values of the 'name' field in the table aside from using either a for loop or a list comprehension?
ages = [x['age'] for x in table]

In MATLAB I could do the following
ages = [table(:).age]

which would return an array containing everyone's age.
Is there a way to return all of the elements of a single field from a list of items? Or is the list comprehension the best way?
[EDIT]:How about if I want to access only the first 2 elements and get their fields? Or the last 2 elements?
List Comprehension still the best way to go?
Perhaps there is a better data structure to allow this?
Comment: What is wrong with the list comprehension?
Comment: You should probably be using a pandas `DataFrame` for this.  It is the equivalent of a MATLAB table (in fact MATLAB tables are based on either pandas dataframes or a similar data structure from R).
Comment: What if I only want to select 'only the last 3 items'?
Answer: A list comprehension is your best bet for creating your list.
That said, you should be using a DictReader instead of the vanilla reader in your code:
...
f = io.StringIO(data)
reader = csv.DictReader(f) # default delimiter is ,
table = list(reader)

ages = [x['age'] for x in table]
names = [x['name'] for x in table]

Comment: What if I only want to select 'only the last 3 items'? Can I use slicing to get only the age field of the last 3 items for example?
Comment: Yes, why not. `[x['age'] for x in table[-3:]]`
Comment: Guess I was hoping for a more succinct syntax. Does the job though!
Comment: Well, if you wrote the entire code in matlab, reading the strings into objects and all, I'm not sure you'll get something crispier than this :)
Answer: Just an alternative approach if you are wanting to do more complex things with tables then there is pandas which is basically programmatic spreadsheet for Python:
>>> f = io.StringIO(data)
>>> import pandas as pd
>>> df = pd.DataFrame.from_csv(f)
>>> df.age
name
scott     31
bob       45
george     2
Name: age, dtype: int64
>>> df.age.values
array([31, 45,  2])
>>> df.age[-2:]
name
bob       45
george     2
Name: age, dtype: int64
>>> df.index
Index(['scott', 'bob', 'george'], dtype='object', name='name')

Answer: You may use collections.defaultdict() as:
from collections import defaultdict
d = defaultdict(list)

for data in table:
    for k, v in data.items():
        d[k].append(v)

d will contain the list of all values as key. For example, for accessing all the ages, do:
d['ages']


Is Duckworth–Lewis applied differently in T20 and ODI

Question: I want to know: is there any difference between ODIs and T20 matches in applying the Duckworth–Lewis method?
Answer: There is no difference in the method of application of Duckworth-Lewis, between matches.
The only potential difference could be in the tables or equivalent that are used to generate the targets, which should reflect different scoring rates and potentials between the two match types.
However as suggested by http://www.espncricinfo.com/magazine/content/story/459431.html, the 50 over curves are used by the 20 over version.
Comment: On the ICC's website, in the document [The D/L methodology: answers to frequently asked questions](http://icc-live.s3.amazonaws.com/cms/media/about_docs/542b84d41b3c2-The%20D_L%20methodology%20-%20Answers%20to%20Frequently%20Asked%20Questions.docx), there is a section ("Twenty20 issues") that discusses how the method is applied in T20.


Confidence Interval for Introduction to Statistics

Question:
Hi there,
I am in an introduction to statistics class, and I really need help with problem 19.
For problem 19, I think the answer is A because Since this referring this two populations, and the conditions for constructing a confidence interval is satisfied, where the sample is random and independent, large sample, and big population, am I right to think that we are able to construct a 95% confidence interval? I am not sure about how to tie in the proportion of samples being asked in part III.
If you guys could help me with this problem, I would greatly appreciate it. Thanks.
Comment: Statements I and II only use information derived from the sample of size 27. They are not using the large population! Personally I would not attempt to derive 95% confidence intervals from that small a sample, where each individual is contributing nearly 4% of the infomation. However, as the question is stated, they can be derived (though expect them to be wide :-)
Statement III is directly calculable. As the base sample is large we may assume that any sub-sample is distributed as Bin($27,0.59$), so calculate the right tail of $27*0.36$
Answer: Perhaps I am being dim-witted, but every one of those looks like it can be calculated to me.
A different set of issues arises with respect to how to calculate them; how 'crisp' are the confidence intervals; etc.
Technically, a 'statistic' is something/anything you can calculate from the data you have.  We are all taught that, if we measure the height of 100 people, the way to estimate the average height is to add them all and divide by 100.  We call that process - the add and divide - a 'statistic'.
But a statistic can be anything.  For example, you could estimate the average height by measuring only the first person, and ignoring the 99 others.  That is also a 'statistic'.  Or you could measure every other person, or the last one.  You could also use the median (the height of the person who has equally many people taller and shorter) or the mode (the most common height).  All of these are 'statistics'.
There are different qualities that one looks for in 'statistics'.  For example, being unbiased is one (which, roughly, means that on average it gets you the right answer).  Amazingly, just measuring a single person will, with normally distributed heights, be unbiased - as will the average we are all taught to calculate.  However, the traditional average will have lower variance, which is why we use it.
Note that many distributions are not symmetrical.  So, for example, when we measure average wealth we typically use the median - the person who has as many people richer than he or she as there are poorer.  Why?  It's the old joke: when Bill Gates walks into a bar, the average person in the bar just got billions of dollars richer.  Clearly, the typical average is the wrong measure.
By the way, I hate cute questions like this that seem to show how smart the professor is relative to the students.  It really does not help anyone learn anything.


Profiling what is normal with categorical data

Question: I need some pointers / suggestions ... I like to profile a whole bunch of categorical user data - i.e. things like who talks to who, who deals with what product categories typically, and identify ones that don't follow a norm. An anomaly detection problem perhaps ...  but what sort of algos should I be looking at? Should I be hot encoding my fields to achieve this?
All the examples I read (k means, one class SVM) are focused on numerical datasets ...
Comment: What do you mean by "profile" in the second sentence? I think you may be interested in topics like "Contingency tables" and "Chi Squared test" but your question is too vague/imprecise to really know what you want to do.
Comment: Thx.  Profile, I was basically meaning 'learning what normal is'. I.e. statistically this happens reguarlly or not..
Answer: It depends entirely upon the meaning of your data attributes, which is left out in your question. You should provide more information about the data if you want more detailed help.
Whether a certain encoding "works" or not depends entirely upon the situation at hand, so you will have to reason about what you are trying to find out. You may even have to use different transformations for different attributes.
For example, if there are 10 "product categories" and we encode them into numbers [1, 2, ..., 10], then a numerical anomaly detection method based on Euclidean distance will say that product 1 is "farther" away from product 10 than product 2 is, which may or may not be nonsensical.
There is plenty of reading on categorical clustering available, for example, search for "categorical k-means", and you will probably find problems similar to yours. If you prefer books, Aggarwal's recent book on outlier detection (www.springer.com/us/book/9781461463955) has a chapter on categorical variables.


Dificuldade em realizar CRUD de dados com FullCalendar e Django/Python

Question: Estou tentando utilizar o FullCalendar no meu projeto Django e estou com dificuldades em fazer o CRUD dos dados.
Eu gostaria que tudo funcionasse na mesma tela,ou seja, quando o usuário seleciona datas no calendário, o modal aparece para inserir os valor (título e datas), quando clica em um evento, aparece o modal para editar o evento e um botão para removê-lo.
Até agora o que eu consegui fazer foi o seguinte:


Finding Mean And Standard Deviation Given the Values for the Top 25% and Bottom 25%

Question: I essentially have a situation where heights are normally distributed and I'm given the top 25% of heights and bottom 25% of heights. How would I find the mean and stdev? This is my first week of stats so I haven't learned much yet and we use python for a lot of the questions (I also don't know much about python yet). Is there a simple way to understand how to find these values either by hand or using python? I've looked for similar questions but they often include z-score calculations and we haven't gotten to z-score tables yet, so I assume I need to figure out how to code this situation in python. I'd appreciate any help.
Comment: You either need z-score tables or the cumulative error function, which are really ways of expressing the same thing.  You can read about z-scores in [wikipedia](https://en.wikipedia.org/wiki/Standard_normal_table)
Answer: It is very strange for a statistics class to be taught without $z$-score.
To find the mean, recall that the normal distribution is symmetrical. Hence you just have to average out the two numbers.
As for standard deviation, if one refuse to use $z$-score directly, another possible way is that by fixing the mean,  the CDF is monotonic, hence you can consider solving the problem using binary search.


How do I move this drop down menu arrow - HTML/CSS

Question: How do I move this drop down menu arrow so it's not too close to the edge of the drop down menu?

    .footer_dropdown select {
        color:white;
        font-size:18px;
          -webkit-appearance:auto!important;
  /*webkit browsers */
  -moz-appearance: auto!important;
  /*Firefox */
  appearance: auto !important;
    }

Answer: You can't really style the default styling of browsers.
Simply remove the default styling from the select box by using appearance: none;
Then, add a background-image to the select tag and give it the proper styling you want. Take a look at my example. You can play a little with the settings.
Giving the position of the background-image with calc, where we place it 100% from the left, and subtract 20px from that; giving it basically the right: 20px; property. Placing it horizontally in the middle is what the 50% does after that.
Then we give it the background-size width and height both 15px; And we don't want it to repeat, so no-repeat.

select{
  position: relative;
  padding: 20px;
  border: 2px solid black;
  width: 400px;

  appearance: none;
  -webkit-appearance: none;
  -moz-appearance: none;
  -ms-appearance: none;

  background: #f9f9fa url('https://image.flaticon.com/icons/png/512/32/32195.png') calc(100% - 20px) 50% / 15px 15px no-repeat;
}
<select>
    <option value="">--Please choose an option--</option>
</select>


Website redirection intermittently work in Firefox but not work at all in IE

Question: After few try an error in website redirection, I manage to perform website redirection but it intermittently works in Firefox but not work at all in IE. I manage to clear all cache and retry in Firefox and it works, but weirdly it does not work after that. I confirmed that I wasn't doing any changes on any files at that time. Did anyone have any idea or face this before? I was sooooo happy that my website finally redirects even I was happy like 2 minutes then it turns up wasn't redirect again. :(( I just need it to redirect when I type http://example.com it redirect to https://www.example.com
Below is my redirection in .htaccess file:
RewriteEngine On
#Options +FollowSymLinks
RewriteCond %{HTTPS} !on [OR]
RewriteCond %{HTTP_HOST} ^example\.com$[OR]
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule .* https://www.example.com%{REQUEST_URI} [R=301,L]

Below are my logs:
init rewrite engine with requested uri /
pass through /
[perdir D:/wamp64/www/example/] strip per-dir prefix: D:/wamp64/www/example/ ->
[perdir D:/wamp64/www/example/] applying pattern '.*' to uri ''
[perdir D:/wamp64/www/example/] RewriteCond: input='off' pattern='!on' => matched
[perdir D:/wamp64/www/example/] RewriteCond: input='www.example.com' pattern='^www\\.example\\.com$' => matched
[perdir D:/wamp64/www/example/] rewrite '' -> 'https://www.example.com/'
[perdir D:/wamp64/www/example/] explicitly forcing redirect with https://www.example.com/
[perdir D:/wamp64/www/example/] escaping https://www.example.com/ for redirect
[perdir D:/wamp64/www/example/] redirect to https://www.example.com/ [REDIRECT/301]

I also found that my website only redirect when I logout from VPN(I need to VPN so that I can connect to the server to fix or get the info that I have done for redirection)
Below is the item that I added in .htaccess file:
    RewriteCond %{HTTPS} !on [OR]
    RewriteCond %{HTTP_HOST} ^example\.com$
    RewriteCond %{HTTP_HOST] ^www\.example\.com$
    RewriteRule .* https://www.example.com%{REQUEST_URI} [R=301,L]

Below are my httpd-vhosts.conf:
<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot "d:/wamp64/www/example"
    <Directory  "d:/wamp64/www/example/">
        Options +Indexes +Includes +FollowSymLinks +MultiViews
        AllowOverride All
        Order allow,deny
        Allow from all
        Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains"
    </Directory>
</VirtualHost>

My SSL certificate was configured in httpd-ssl.conf so I point my httpd-vhosts.conf as VirtualHost *:80
Below are my httpd-vhosts.conf:
<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot "d:/wamp64/www/example"
    <Directory  "d:/wamp64/www/example/">
        Options +Indexes +Includes +FollowSymLinks +MultiViews
        AllowOverride All
        Order allow,deny
        Allow from all
        Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains"
    </Directory>
</VirtualHost>

Update
Below is what I update in .htaccess by adding [OR]:
RewriteCond %{HTTPS} !on [OR]
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule .* https://www.example.com%{REQUEST_URI} [R=301,L]

And below are the logs that I got:
strip per-dir prefix: D:/wamp64/www/example/ ->
applying pattern '.*' to uri ''
RewriteCond: input='off' pattern='!on' => matched
rewrite '' -> 'https://www.example.com/'
explicitly forcing redirect with https://www.example.com/
escaping https://www.example.com/ for redirect
redirect to https://www.example.com/ [REDIRECT/301]

I have tried it again in browser but it wasn't redirected. I also try to debug in firefox and host I got is example.com
This is what I got by removing [OR]
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule .* https://www.example.com%{REQUEST_URI} [R=301,L]

Logs:
RewriteCond: input='off' pattern='!on' => matched
RewriteCond: input='www.example.com' pattern='^example\\.com$' => not-matched

Please tell me that my redirection is working cuz I've been work in this for months and getting out of idea now(I hope is not because of my silly mistake...praying!). Please help me and thanks in advance!
Comment: Is `ServerAlias` option for your case? If yes than you could just put under Virtual host configuration  `ServerName  www.example.com  ServerAlias example.com  Redirect permanent / https://www.example.com/`.
Comment: I did add server alias in my vhosts. but my ServerName is example.com and ServerAlias is www.example.com but actually what is the difference between these two?
Answer: I believe you don't actually want this condition:
RewriteCond %{HTTP_HOST} ^www\.example\.com$

Because that would cause an infinite redirect loop to itself, given this is from the .htaccess that applies to the https://www version, too:
RewriteRule .* https://www.example.com%{REQUEST_URI} [R=301,L]

Comment: That's not necessary, because you have `RewriteCond %{HTTPS} !on [OR]`. If you removed the line, remember to remove the `[OR]` from the previous condition, too.
Comment: I thought the same thing at first, but that line is actually necessary in order to rewrite `http://www.example.com/` as `https://www.example.com/`. The infinite redirect loop ([which is definitely a real thing](https://cwiki.apache.org/confluence/display/HTTPD/RewriteLooping)) is prevented in this case by [lack of inheritance of mod_rewrite directives between VirtualHosts](http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewriteengine). Most of the Linux distributions that I have seen configure the default SSL-enabled website using a separate VirtualHost.
Comment: I tried to remove the above lines and remain this line(RewriteCond %{HTTP_HOST} ^example\.com$[OR]) but when tried in IE, my website still not redirecting when I type http+example.com
Comment: Hi Esa, nice to meet you! Here is what I got after remove line(RewriteCond %{HTTP_HOST} ^www\.example\.com$) and remain line(RewriteCond %{HTTP_HOST} ^example\.com$), result->>([perdir D:/wamp64/www/example/] RewriteCond: input='off' pattern='!on' => matched
[perdir D:/wamp64/www/example/] RewriteCond: input='' pattern='^example\\.com$' => not-matched)
Comment: @EsaJokinen you are correct, the "!on" RewriteCond covers the `http://www.example.com/` to `https://www.example.com/` redirect. And the "redirected you too many times" message shows that I incorrectly assumed the VirtualHost setup in WAMP.
Comment: Hi, liverwust, nice to meet you! How are you doing today? I have added the item as requested.
Comment: Hello Petri, I am well. Based on your update, I think that you removed one too many [OR]s. Esa meant that you shouldn't have a "hanging" [OR] on the last RewriteCond. You still need it _between_ the RewriteConds. Please add [OR] to the %{HTTPS} !on condition.
Comment: I already update [OR] to the %{HTTPS} !on condition, but the website still didn't redirect when I type 'example.com' in the browser. I have update .htaccess and logs as above. It seems to ignore this condition:RewriteCond %{HTTP_HOST} ^example\.com$ I also added another info where rewritecond without [OR] and rewritecond input from logs is www.example.com but when I try it in Firefox debugger, the host that I got is example.com instead. I feel like the solution was so close yet so far.
Answer: I believe it is a missing space character. Please change this:
RewriteCond %{HTTP_HOST} ^example\.com$[OR]

to this:
RewriteCond %{HTTP_HOST} ^example\.com$ [OR]

Your logfile entries proved that http://www.example.com was successfully rewritten to https://www.example.com/. They didn't prove anything about http://example.com. Adding the space character should fix the latter.
Comment: I did try to add space but it ends up my website show www.example.com redirected you too many times.
Comment: I think you need to do this *plus* @EsaJokinen's suggestion. I see that you posted new log entries in the other comment thread, but if it is still not working then it might be more readable to add an "Update:" section to the question instead.
Answer: Instead of mod_rewrite you should use something like this in Virtualhost definition:
ServerName  www.example.com
ServerAlias example.com
Redirect permanent / https://www.example.com/

According to  Apache httpd documentation.

mod_rewrite should be considered a last resort, when other alternatives are found wanting. Using it when there are simpler alternatives leads to configurations which are confusing, fragile, and hard to maintain.
Comment: This is true. Also, if you have access to the server configuration, you should avoid using `.htaccess`. However, this answer is incomplete, because it's far from the question, and doesn't explain all the required steps.
Comment: Yes, is another solution as well but my configuration already using httpd-ssl.conf so I might think to stick with it unless I still can't work it out.


R - Inflação acumulada

Question: Olá, gostaria de uma ajuda na seguinte missão, com base na tabela do IPCA-mensal (série histórica), adicionar um campo com a inflação acumulada anual, onde o processo recomeça a cada ano.
Para o cáluclo da inflação acumulada, usa-se o juros composto, onde temos a seguinte fórmula:
Inflação Acumulado = (((1 + (inflação do mês/100)) * inflação acumulada anterior) + inflação do mes)
Tentei usar o soma simples, mas o resultado final é divergente do resultado anual final, por isso, a necessidade de usar juros composto.
Meu dataset, ou data.frame, (listaDF) de entrada tem o seguintes campos:
1- Data: (mes de apuração)
2- Inflação: Inflaçlão do mês.
Neste caso gostaria de ter como saída, uma data set igual o de entrada acrescentado de uma coluna com o juros acumulado, onde ele seria apurado por ano, ou seja, a cada inicio de ano, a contagem recomeça.
Dataset final:
1- Data: (mes de apuração)
2- Inflação: Inflaçlão do mês.
3 - Inflação acumulada: Inflação acumulada durante o ano de apuração.
Tentei usar o script abaixo no RStudio, mas ele não cria o campo, e nem da mensagem de erro.
Como irei realizar o processo em várias fontes, imaginei usar uma função para deixar mais limpo e funcional.
Dataset de entrada (exemplo):
lista <- list(a = c('1991-10-01', '1991-11-01', '1991-12-01', '1992-01-01','1992-02-01'),
              b = c(0.5, 0.6, 0.8, 1.2, 1.4))

Onde "a" é o mês de refência e "b" é a inflação.
tentativa utilizada sem sucesso (Não cria o campo) e não dá mensagem de erro.
Obs.1: Gostaria que fosse via função pois o processo vai ser realizado em várias tabelas.
Obs.2: Não achei uma função/pacote com essa função
lista <- list(a = c('1991-10-01', '1991-11-01', '1991-12-01', '1992-01-01','1992-02-01'),
              b = c(0.5, 0.6, 0.8, 1.2, 1.4))
lista

listaDF <- as.data.frame(lista)

Acum <- function(){
  ano1 = format(df$Data[1], format = "%Y")
  ano1 = as.integer(ano1)
  anomes <- paste(ano1, mes)
  anomes
  jur1 = 0
  acum_jur = 0
  #df$acum_jur <- vector(df, length(df$data))
  #i = 1;
  for (x in df$Data){
    dia3 = as.Date(x)
    ano2 = (format(dia3, format = "%Y"))
    ano2 <- as.integer(ano2)
    mes <- format(dia3, format = "%m")
    jur = df$tx_jur[df$Data == dia3]
    if (ano2 == ano1)
    {
      anomes <- paste(ano2, mes)
      acum_jur1 = (((1 + (jur/100)) * acum_jur) + jur)
      acum_jur <- acum_jur1
      df$tx_acum[df$Data == dia3] <- round(acum_jur1, 2)
      #df$acum_jur[[i]] <- round(acum_jur1, 2)
    }
    else
    {
      ano1 = ano1 + 1
      anomes <- paste(ano2, mes)
      acum_jur1 = df$tx_jur[df$Data == dia3]
      acum_jur <- acum_jur1
      df$tx_acum[df$Data == dia3] <- round(acum_jur1, 2)
      #df$acum_jur[[i]] <- round(acum_jur1, 2)
    }
  }
}

listaDF$new_column <- Acum()
listaDF

Comment: Olá PNETO. Coloque um exemplo do `data.frame` completo que você precisa como saída. Essa função que você fez: Ela calcula errado? Não calcula? A inflação do ano não é só somar todos os valores do ano? Veja dicas de como melhorar a sua pergunta [aqui](https://pt.meta.stackoverflow.com/questions/8045/guia-de-sobreviv%C3%AAncia-do-stack-overflow-em-portugu%C3%AAs) e [aqui](https://pt.meta.stackoverflow.com/questions/824/como-criar-um-exemplo-m%c3%adnimo-reproduz%c3%advel-em-r)
Answer: Eu acredito que a função cumprod já faz o cálculo da taxa acumulada que você procura:
taxas <- c(0.5, 0.6, 0.8)
taxas
# [1] 0.5 0.6 0.8
taxas_acumuladas <- cumprod((taxas/100) + 1) - 1
taxas_acumuladas
# [1] 0.00500000 0.01103000 0.01911824

Então a parte difícil do seu problema seria a divisão dos dados em blocos. Eu fiz uma solução dividindo em blocos com split que aparece mais abaixo, mas depois percebi que se obtém o mesmo resultado de forma mais simples simplesmente agrupando por ano:
library(tidyverse)

df <- tibble(
    a = c('1991-10-01','1991-11-01','1991-12-01','1992-01-01','1992-02-01'),
    b = c(0.5, 0.6, 0.8, 1.2, 1.4)
  )

df <- df %>%
  mutate(a = as.Date(a),
         y = year(a)) %>%
  arrange(a)

# solução agrupando...
sol1 <- df %>%
  group_by(y) %>%
  mutate(
    tx_acum = cumprod((b/100)+1)-1
  )

# ou dividindo em blocos...
split_df <- split(df, df$y)
cum_taxes <- map(split_df, ~ (cumprod((.$b/100) + 1) - 1))
sol2 <- do.call(rbind,
              map2(split_df, cum_taxes, ~ tibble(.x, cum_taxes = .y)))

R - Inflação acumulada


Create and assign separate subnet to each namespace

Question: I have one master and one worker and 10 namespaces in k8s. I want to create and assign subnet to each namespace using by pods. for example I want to create and assign 10.0.0.0/24 to namespace 1, create and assign 10.1.0.0/24 to namespace 2 and...
I played with network policies but it did not any results. How can I do this?
Answer: Kubernetes itself doesn't offer such a functionality natively to map namespaces to pod CIDR ranges.
Network policies define ingress/egress rules for pods and not CIDR ranges for namespaces.
The closest solutions I could think of:

CNI-specific solution like Calico IPAM.

https://docs.tigera.io/calico/latest/networking/ipam/
https://docs.tigera.io/calico/latest/reference/configure-cni-plugins#using-kubernetes-annotations

Making use of the fact that different nodes will have different pod IP ranges, and scheduling selected pods to run on specific node(s). Not something I'd recommend.

https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/

Making use of the fact that static pods and daemonset pods will have the IP address of the node they are running on. Again, not something I'd recommend.


Installation issue (drush problem?)

Question: I was trying to install Aegir following the Automatic install guide, but I get an error. I've tried to install Aegir 2, then tried also Aegir 3, but the error is the same. Any clues?
Here's the message:

The following settings will be used:
    Aegir frontend URL: site.dev.local
    Master server FQDN: site.dev.local
    Aegir root: /var/aegir
    Aegir user: aegir
    Web group: www-data
    Web server: apache
    Web server port: 80
    Aegir DB host: localhost
    Aegir DB user: root
    Aegir DB password:
    Aegir DB port: 3306
    Aegir version: 7.x-3.x
    Aegir platform path: /var/aegir/hostmaster-7.x-3.x
    Admin email: firstname.lastname@example.com
Aegir install profile: hostmaster
Do you really want to proceed with the install (y/n): y
  Enabling hosting-queued daemon
The drush command '@hostmaster pm-enable hosting_queued' could not be found.  Run drush cache-clear drush to clear the commandfile cache if you have installed new extensions.                       [error]
  A Drupal installation directory could not be found                                                                                [error]
dpkg: error processing package aegir3-hostmaster (--configure):
   subprocess installed post-installation script returned error exit status 1
  dpkg: dependency problems prevent configuration of aegir3:
   aegir3 depends on aegir3-hostmaster (>= 3.0.1); however:
    Package aegir3-hostmaster is not configured yet.
dpkg: error processing package aegir3 (--configure):
   dependency problems - leaving unconfigured
  No apport report written because the error message indicates its a followup error from a previous failure.
                                                                                Errors were encountered while processing:
   aegir3-hostmaster
   aegir3
  E: Sub-process /usr/bin/dpkg returned an error code (1)

Thanks!
Answer: The most common problem that could cause this is a broken mail setup.
Please the if you can sent an email from the server's cli to firstname.lastname@example.com
Answer: Ran into this today, here's how I solved it:
Set -x in the script which is failing.
You can do this by editing the .postinst script, eg /var/lib/dpkg/info/aegir3-hostmaster.postinst in my situation. Replace #! /bin/sh with #! /bin/sh -x at the top of the script; when executed, the postinst script will then print out each line as it's executed.
Set DPKG_DEBUG=developer.
export DPKG_DEBUG=developer

This will activate debug output in various script commands.
Re-run the installation.
For me, this was dpkg --configure --pending as I'd already attempted to install the package and it had failed during configuration.
Read the output.
Seems obvious, but the first couple times I didn't read back far enough, and there was a useful error message further up.
In my case (quite possibly not yours, dear reader), the issue was that the permissions of /var/aegir/platforms in my Vagrant environment did not permit the aegir user to create the directory to install its hostmaster install. Thus no @hostmaster alias, no way to enable hosting_queued, and an error message which didn't clearly point to a resolvable situation.
Fix the root problem.
This will vary, as the error in this question is associated with many different causes documented across the internet, including:

MySQL validate password plugin not accepting the generated password. (Generate a better password, or reconfigure / disable that plugin.)
The aegir hostname not being resolvable, so the site being inaccessible. (Add the aegir hostname in /etc/hosts)
Filesystem permissions preventing installation. (Make sure aegir owns the platforms directory.)

HTH

Installation issue (drush problem?)


Magento Error — Too many request

Question: I got this error just a while ago:
Kindly refer to the image below

Why I got this kind of error?  Is it wrong to always visit this site? Or are there any rules that says, users are not allowed to always visit MSE? I'm just doing a normal or usual browsing.
Answer: I had same issue, I wrote to support and they replied me like below

If you are still facing issue after one day you should write at email@example.com with X-id and IP so team will resolve it.
Thanks.

Magento Error — Too many request


Independence of events 3

Question:
If $A$ is independent of $B$ and $A$ is independent of $C$ then is $A$ independent of $BC$?

Is this true? Dealing with probability
Answer: No.
Think of when $A=B \oplus C$ where $\oplus$ is $XOR$ (Sum modulo 2)
When $B,C$ are independent Bernolli random variables. i.e. are $0,1$ with equal probabilities.
Answer: Here is a simple example using the common coinflipping scenario.
Let our experiment be flipping a fair coin twice in succession.  We have an equiprobable sample space: $\{HH,HT,TH,TT\}$
Let $A$ be the event "The first coin is a heads", i.e. the event $\{HH,HT\}$
Let $B$ be the event "The second coin is a heads", i.e. the event $\{HH,TH\}$
Let $C$ be the event "The total number of heads is odd", i.e. the event $\{TH,HT\}$
Each of these occur with probability $\frac{1}{2}$ individually.  One can see that these are each pairwise independent as well, $A\cap B, A\cap C,$ and $B\cap C$ each occur with probability $\frac{1}{4}$
However, $A\cap B\cap C=\emptyset$ so $0=Pr(A\cap (B\cap C))\neq Pr(A)\cdot Pr(B\cap C)=\frac{1}{8}$ so we see that $A$ is not independent of $B\cap C$
This example also shows that pairwise independence does not imply mutual independence.

Independence of events 3


Erro na conversão de valor decimal no Insert C#

Question: Tenho um insert que recebe alguns parâmetros, mais no momento que montar a instrução sql esta dando erro de conversão:

Error converting data type varchar to numeric.

        //http://localhost:7630/api/AspNetWebApi/cadastrar/jogo/4512/20.01/20.10/5
        [HttpPost]
        [Route("cadastrar/jogo/{nJogo}/{valor}/{total}/{idusuario}")]
        public HttpResponseMessage Cadastro(int nJogo, decimal valor, decimal total, int idusuario)
        {
            try
            {
                var tTabela = new JogoDetalheAplicacao();
                tTabela.Inseri(nJogo, valor,total,idusuario);
                return Request.CreateResponse(HttpStatusCode.OK, "Cadastro realizado.");
            }
            catch (Exception ex)
            {

                return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
            }
        }

    public void Inseri(int nJogo, decimal valor, decimal total, int idusuario)
    {
        var strQuery = "";
        strQuery += "INSERT INTO TB_JOGO_DETALHE_TEMP (NUMERO_JOGO, VALOR_JOGO,VALOR_TOTAL,IDUSUARIO)";
        strQuery += string.Format(" VALUES (");
        strQuery += string.Format(" {0}, ", nJogo);
        strQuery += string.Format(CultureInfo.InvariantCulture, " {0:0.00}, ", valor);
        strQuery += string.Format(CultureInfo.InvariantCulture, " {0:0.00}, ", total);
        strQuery += string.Format(" {0} ", idusuario);
        strQuery += string.Format(" ) ");

        using (contexto = new Contexto())
        {
            contexto.ExecutaComando(strQuery);
        }

    }

Resultado da consulta sql final:
INSERT INTO TB_JOGO_DETALHE_TEMP (NUMERO_JOGO, VALOR_JOGO,VALOR_TOTAL,IDUSUARIO) VALUES ('4512','20,01','20,10','5' )

O correto seria vir assim:
INSERT INTO TB_JOGO_DETALHE_TEMP (NUMERO_JOGO, VALOR_JOGO,VALOR_TOTAL,IDUSUARIO) VALUES ('4512',20.01,20.10,'5' )

Comment: Testei aqui e a consulta ficou como esperado, da uma olhada : https://dotnetfiddle.net/0On7LU
Comment: @JoelRamosMichaliszen, no seu exemplo da certo, mais no meu já fiz vários tipos de conversão é não deu certo
Comment: Quais são os tipos dos campos??: **(NUMERO_JOGO, VALOR_JOGO,VALOR_TOTAL,IDUSUARIO)**
Comment: @JoelRamosMichaliszen,
int nJogo, decimal valor, decimal total, int idusuario
Comment: Sim, mas tipo do campo no banco, ex: decima(10,2)
Comment: numeric(8, 2) para os valores, o restante é int
Answer: O seu problema é que o string.Format usa as informações da cultura atual para decidir como converter um número para string.
Isso geralmente não é um problema para números inteiros, porém para números com casas decimais ele é bem problemático, pois em um SO em português ele vai usar a vírgula como separador decimal, enquanto que em inglês ele vai usar o ponto.
Se tratando de montar uma SQL isso se torna um problema maior, já que em uma SQL você precisa sempre usar ponto como separador decimal, felizmente isso é bem simples de resolver já que o string.Format aceita um IFormatProvider como primeiro parâmetro, o qual ele vai usar para definir como efetuar a conversão, e convenientemente o CultureInfo implementa esta interface, então você pode forçar ele a usar um CultureInfo específico, no caso podendo ser o CultureInfo.InvariantCulture que sempre formata números com ponto como separador decimal.
strQuery += string.Format(CultureInfo.InvariantCulture, " VALUES ({0},{1},{2},{3})", nJogo, valor, total, idusuario);

E como todos os seus valores são numéricos então não se deve usar as aspas na SQL.
Agora apenas como observação, a forma como você está fazendo é praticamente o mesmo que concatenar valores em uma SQL, o que não é recomendado, o ideal é sempre utilizar parâmetros em qualquer consulta SQL, e o uso deles também evitaria esse erro já que você poderia passar os valores já no tipo correto para o banco de dados, sem precisar converter para string.
Comment: eu alterei a minha pergunta com o código ajustado com a sua resposta, mesmo assim eu recebo os valores com virgula
Answer: Como os campos são inteiros e numeric(8,2), não é preciso das aspas, Tenta este format:
strQuery += string.Format(CultureInfo.InvariantCulture," VALUES ({0},{1:0.00},{2:0.00},{3})", nJogo, valor, total, idusuario);

Comment: o resultado final: INSERT INTO TB_JOGO_DETALHE_TEMP (NUMERO_JOGO, VALOR_JOGO,VALOR_TOTAL,IDUSUARIO) VALUES ('4512',20,01,20,10,'5' ), ainda da erro, por causa da virgula
Comment: @itasouza editei a resposta e tira as aspas dos int's tambem
Comment: @itasouza Testou o format que coloquei na minha resposta?
Comment: sim, eu fiz o seu exemplo mais não deu certo, eu postei na pergunta como ficou o código
Comment: @itasouza Esse format ````strQuery += string.Format(" VALUES ({0},{1:0.00},{2:0.00},{3})", nJogo, valor, total, idusuario);````?
Comment: eu conseguir resolver:
strQuery += string.Format(CultureInfo.InvariantCulture, " {0:0.00}, ", valor);
Comment: é preciso adicionar o CultureInfo.InvariantCulture em cada linha
Comment: @itasouza  Veja minha resposta agora, e marque como correta xD
Comment: faz assim, pega o código correto, adiciona na sua pergunta é ai eu marco como resposta, o código esta na minha pergunta.
Comment: @itasouza usa o meu código, tem menos linha e é mais performático.


Why this linked list program to insert a node at the end is not giving any output?

Question: This code is not giving any output.
There can be different ways to implement linked list. But I want to find my error in this one.
I can't find any error in this code.
Here is my complete code
#include <iostream>
using namespace std;
 class node{
    public:
    int data;
    node* next;

    node(int val){
      data=val;
      next=NULL;
    }
 };

 void insertAtTail (node* &head, int val){
   node * n=new node(val);

   if(head==NULL){
     head=n;
   }
   node * temp= head;
   while(temp->next != NULL){
     temp=temp->next;
   }
   temp->next=n;

 }

void display(node* head){
  node * temp= head;
  while(temp!=NULL){
    cout<<temp->data<< "->";
    temp=temp->next;
  }
  cout<<"NULL"<<endl;
}

 int main(){
   node *head=NULL;
   insertAtTail(head,1);
   insertAtTail(head,2);
   insertAtTail(head,3);
   display(head);
   return 0;
 }

Comment: You're missing an else (or return) in the initial head assignment aftermath of insertAtTail. After assigning head, it *then* assigns the same node to itself, which results in a circular linked list of one node. The next insert will spin forever because `next` is never null. An alternative, btw: [here](https://pastebin.com/CKvsKxfS).
Comment: What did you observe whe you stepped through your cod line by line with the debugger?
Comment: The debugger isn't supposed to show errors. You probably confuse that with the _compiiler_.
Comment: What is `node`? What does its constructor do? How does the constructor initialize the cobject? Please [edit] your question to show us a [mcve].
Comment: added complete code
Comment: The lesson for today: Learn how to use a *debugger* (or just general debugging techniques, like [rubber duck debugging](https://en.wikipedia.org/wiki/Rubber_duck_debugging)). Using a debugger you would have found out the problem quite quickly. Being able to debug your programs is a crucial skill to learn and know.
Comment: @Someprogrammerdude Yes I will learn it today.
Answer:
But I want to find my error in this one.

Following step by step of your insertAtTail function, you'll find that your head and your head->next pointers are pointing to the same memory location.
After assigning your initial head pointer you are assigning the same value to the next node.
A simple fix to your code is to return after initializing the head.
void insertAtTail(node*& head, const int val) {
  node* n = new node(val);

  if(head==nullptr){
    head=n;
    return;  // head is initialized, we don't need to do more here
  }
  node* temp= head;
  while(temp->next != nullptr){
    temp = temp->next;
  }
  temp->next = n;
}

An alternative way to implement this function is
void insertAtTailRec(node*& head, const int val) {
  if(head == nullptr) {
    head = new node(val);
    return;
  }
  insertAtTailRec(head->next, val);
}

Or the solution pointed out by @WhozCraig. I suggest you experiment with different ways to implement this function.


Sum of dependent Binomial distributions

Question: In one of my classes, we stated that if $X_i$ are independent Bernoulli random variables with p proportion of success, then the distribution of the sum $\sum X_i$ is Binomial(n,p). I already proved this, but it got me thinking: if there is a distribution for the sum of these n Bernoulli random variables, is there a special distribution of the sum of n Binomial random variables?
I know there is a relationship between the Binomial distribution and the Binomial coefficient, and moreover that there is a relation between the Binomial coefficient and the Multinomial coefficient (i.e. the Binomial coefficient is a special case of the Multinomial coefficient). I know there is also such a thing as the Multinomial distribution, so my suspicion is that this distribution of the sum of Binomial random variables is somehow Multinomial. But, that's well beyond the scope of my class, so I was curious if there was some intuitive explanation about why it is or is not the Multinomial distribution.
Thanks so much!
Answer: Consider the sequence $(X_k)_{k=1}^m$ where  $\forall k\in\Bbb N\cap [1;m] : X_k\sim\mathcal{Bin}(n,p)$ .
Each $X_k$ is a count of successes among $n$ independent Bernoulli distributions with identical success rate $p$.
Therefore $\sum\limits_{k=1}^m X_k$ is the count of successes among $m$ times $n$ independent Bernoulli distributions with identical success rate $p$.
Thus the sum on $m$ random variables with distribution $\mathcal{Bin}(n,p)$, is a random variable with a distribution of $\mathcal{Bin}(nm,p)$.

Remark: it is somewhat more complicated when the success rate is not identical.
Comment: Is this what OP wants? The title talks specifically about **dependent** random variables!
Comment: The body talks about independent variables, so  I presumed the title was a typo.
Comment: Kavi is right, this is not necessarily what I had in mind, but it's on me for not being clear! What does happen in the dependent case? Is it still as simple as $\mathcal{Bin}(n,p)$?
Comment: It should not be.  Independence is a key criteria.  So, how are the variables dependent? @aldricvonbourghe

Sum of dependent Binomial distributions


logistic regression in R, problem with output

Question: I am trying to  predict logistic regression.
For instance
fit <- glm(TARGET~ x+y, data=trainData,family=binomial)

The data (TARGET) has a label of 0 and 1.
I want to get an output of 0 and 1 from the prediction.
if I run
predict(fit,ValData, type="response"),
I can a bunch of 0.001 something like that. How do I get a binary output ? What is that 0.001 represent? (Probability of equal to 1 is 0.001?)
Thanks
Comment: Could you please articulate your question more clearly?
Answer: Yes, your output is the probability of the target variable being 1. See ?predict.glm.
If you want to output 0-1 predictions, you can simply use a threshold and label each predicted probability that exceeds this threshold as a predicted 1. A threshold of 0.5 is most often used, but it is not set in stone - a different one may yield a better tradeoff between errors of the two kinds.
However, I'd recommend you think about whether you really only want 0-1 predictions. This would lose all the information that one instance was only slightly above the threshold (prediction of 0.51) while another one was far above (prediction of 0.99). If possible, it's usually more enlightening to stay with predicted probabilitiy. (Plus, it allows you to assess your predictions' quality more finely, using scoring-rules or similar.)
Answer: As you said, predict(fit,ValData, type="response") will give you the probability of 1 for each case. If you want a 0-1 prediction, depending on your threshold you can use:
(predict(fit, ValData, type="response") > 0.5) * 1

That should give a 0 or 1 depending of the cut-off point (0.5 here).


Localization/Validation - MVC C# model only taking my default resource file instead of my other language selected

Question: I am currently trying to get the validation from the backend models to the razor view using resource files. I have 2 languages setup, (en, fr) but even though French is selected, the error message is always in English.
I have tried multiple online tutorial / looking at other people having similar problem but none of the fixes worked for me.
my viewmodel example:
[Required(ErrorMessageResourceName = "RequiredField", ErrorMessageResourceType = typeof(GlobalRes))]
[Display(Name = "Username", ResourceType = typeof(GlobalRes))]
public string Username { get; set; }

[Required(ErrorMessageResourceName = "RequiredField", ErrorMessageResourceType = typeof(GlobalRes))]
[DataType(DataType.Password)]
[Display(Name = "Password", ResourceType = typeof(GlobalRes))]
public string Password { get; set; }

Razor view:

   @Html.LabelFor(m => m.Username, new { @class = "col-md-12" })

      @Html.TextBoxFor(m => m.Username, new { @class = "form-control" })
      @Html.ValidationMessageFor(m => m.Username, "", new { @class = "text-danger"})

    @Html.LabelFor(m => m.Password, new { @class = "col-md-12" })

       @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
       @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })

Inspecting the html in your browser after changing the language and submitting the form.
<input class="input-validation-error form-control" data-val="true" data-val-required="Ce champ est requis." id="Username" name="Username" type="text" value="">
This field is required.

<input class="input-validation-error form-control" data-val="true" data-val-required="Ce champ est requis." id="Password" name="Password" type="password">
This field is required.

What the expected results should be is, based on the language selected, the error message should be in french. If you inspect the input box, you can see the correct value being added in french. When submitting the form, you actually only get the english value instead of the expected one.
Thank you in advance!
Answer: I had this problem also but I find a simple way, I controller add this code.
if (ModelState.IsValid)
{

}
else
{
    ModelState.Clear();
    TryValidateModel(Model);
}

Answer: I was having the exactly same issue. For me putting the resource files in App_GlobalResources folder solved my problem!
If that folder does not exist already you can create it.
I am using localization on Asp.Net MVC application.


How can I set a data breakpoint in a C# program in Visual Studio 2015?

Question: How can I set a data breakpoint in a C# program in Visual Studio 2015?
https://stackoverflow.com/a/621537/156458 says that for C++

How to Set a Memory Change Breakpoint
From the Debug Menu, choose New Breakpoint and click New Data
  Breakpoint
—or—
in the Breakpoints window Menu, click the New dropdown and choose New
  Data Breakpoint.

But neither exists in Visual Studio 2015.
Is data breakpoint not supported for C#?
Why is it supported for C++, but not for C#?
Is it technically difficult to implement?
Any way to work around?
Answer: It doesn't appear to be possible unfortunately: https://msdn.microsoft.com/en-us/library/350dyxd0%28v=vs.100%29.aspx
Edit: It's a much requested feature with some discussion about it: https://visualstudio.uservoice.com/forums/121579-visual-studio-ide/suggestions/6097301-support-data-breakpoints-for-c
Comment: any way to work around?
Comment: Is it technically difficult to implement? Why is it implemented for C++ but not for C#?
Comment: See my edit, there is much conversation around it.
Comment: @Tim  Likely because C++ natively exposes addresses, and C# doesn't
Comment: Maybe, depends what you want to do, would "watches" work for you?  See number 4:  https://blogs.msdn.microsoft.com/visualstudioalm/2016/07/15/7-ways-to-look-at-the-values-of-variables-while-debugging-in-visual-studio/


Field template in theme based on Garland

Question: I have problem with template for field "field_is_new" in Drupal 7.
My_Theme is a modification of the Garland theme. (I don't know if it's important.)
I have created a template for this field in my theme folder ("My_Theme/templates/field--field-is-new.tpl.php").
In template.php, I added:
function My_Theme_preprocess_field(&$variables, $hook) {
  // Add specific suggestions that can override the default implementation.
  array_unshift($variables['theme_hook_suggestions'], 'field__' . $variables['element']['#field_name']);
}

I cleared the cache, and rebuilt the theme.
I was thinking it's good way to do this, but it's not working.
What's wrong?
Answer: Your preprocess function is not necessary in this situation because Drupal's default behavior is using this sort of files. Try print_r($variables['theme_hook_suggestions']); and see all relevant suggestions.
Your problem is the wrong filename; try field--field_is_new.tpl.php instead.
The general recommendation is using theme functions:
function theme_field__field_taxonomy($vars) {
  $output = '';

  foreach ($vars['items'] as $delta => $item) {
    $array = explode(';',$item['#markup']);

    if (count($array)) {
      $output = '
';
      foreach ($array as $value) {
          $output .= '
' . trim($value) . '
';
      }
      $output .= '
';
    };
  }

  return $output;
}


Error 1 Error 2 on Conference MVC Tutorial

Question: Hi there im following the series of MVC tutorials given by microsoft and i came across this problem:

Error 1   The best overloaded method match for
  'System.Data.Entity.DbSet.Add(Conference.Models.Session)'
  has some invalid arguments    visual studio
  2013\Projects\Conference\Conference\Models\ConferenceContextInitializer.cs    18  31  Conference
Error 2   Argument 1: cannot convert from 'Conference.Models.Speaker' to
  'Conference.Models.Session'   visual studio
  2013\Projects\Conference\Conference\Models\ConferenceContextInitializer.cs    19  34  Conference

ConferenceModelInitializer

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace Conference.Models
{
    public class ConferenceContextInitializer : DropCreateDatabaseAlways<ConferenceContext>
    {
        protected override void Seed(ConferenceContext context)
        {
            context.Sessions.Add(
                new Session()
                {
                    Title = "I Want Spaghetti",
                    Abstract = "The Life and times of a spaghetti lover",
                    Speaker = context.Speakers.Add(
                                 new Speaker()
                                 {
                                     Name = "Jon Pepe",
                                     EmailAddress = "firstname.lastname@example.com"
                                 })
                });
            context.SaveChanges();
        }
    }
}

ConferenceContext

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace Conference.Models
{
    public class ConferenceContext : DbContext
    {
        public DbSet<Session> Sessions { get; set; }
        public DbSet<Session> Speakers { get; set; }
    }
}

Thank you!
Comment: The second line should be `public DbSet Speakers { get; set; }`
Answer: replace:
public class ConferenceContext : DbContext
{
    public DbSet<Session> Sessions { get; set; }
    public DbSet<Session> Speakers { get; set; }
}

with:
public class ConferenceContext : DbContext
{
    public DbSet<Session> Sessions { get; set; }
    public DbSet<Speaker> Speakers { get; set; } //since you are referencing the speaker class here
}


Minecraft forge mod version 1.7.10 crashes constantly after adding new recipes

Question: I'm currently having some issues developing my first hand-written mod. I am currently using Eclipse Photon as my IDE, am running Windows 10 Home on a 64 bit machine, and have 4 GB of ram.
Here is my code:
package com.haxium.basicmod.obsidian.armor;

import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.util.EnumHelper;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.Item.ToolMaterial;
import net.minecraft.item.ItemArmor.ArmorMaterial;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.registry.GameRegistry;
import com.haxium.basicmod.obsidian.armor.ItemObsidianGeneric;
import com.haxium.basicmod.obsidian.armor.ItemObsidianArmor;
@Mod(modid = ObsidianArmor.MODID, version = ObsidianArmor.VERSION, name = ObsidianArmor.NAME)
public class ObsidianArmor {
    public static final String MODID = "obsidian_armor";
    public static final String VERSION = "1.7.10-Stable-126.96.36.199";
    public static final String NAME = "HaxCraft Obsidian Edition";
    //tools
    public static Item obsidian_pickaxe;
    public static Item obsidian_sword;
    public static Item obsidian_ingot;
    ToolMaterial obsidian = EnumHelper.addToolMaterial("obsidian", 3, 4500, 10.1F, 4.5F, 10);
    //armor
    public static Item obsidian_helmet;
    public static Item obsidian_chest;
    public static Item obsidian_leggings;
    public static Item obsidian_boots;
    ArmorMaterial hardened_obsidian = EnumHelper.addArmorMaterial("hardened_obsidian", 20, new int[] {3, 7, 6, 3}, 25);
    @EventHandler
    public void preInit(FMLPreInitializationEvent event) {
        //tools
        obsidian_pickaxe = new ItemObsidianPickaxe(obsidian, "obsidian_pickaxe");
        obsidian_sword = new ItemObsidianSword(obsidian, "obsidian_sword");
        obsidian_ingot = new ItemObsidianGeneric("obsidian_ingot");
        GameRegistry.registerItem(obsidian_ingot, "Obsidian Ingot");
        GameRegistry.registerItem(obsidian_sword, "Obsidian Sword");
        GameRegistry.registerItem(obsidian_pickaxe, "Obsidian Pickaxe");
        //Armor
        obsidian_boots =  new ItemObsidianArmor(hardened_obsidian, 3, "obsidian_boots");
        obsidian_helmet = new ItemObsidianArmor(hardened_obsidian, 0, "obsidian_helmet");
        obsidian_chest = new ItemObsidianArmor(hardened_obsidian, 1, "obsidian_chest");
        obsidian_leggings = new ItemObsidianArmor(hardened_obsidian, 2, "obsidian_leggings");
        GameRegistry.registerItem(obsidian_helmet, "Obsidian Helmet");
        GameRegistry.registerItem(obsidian_chest, "Obsidian Chestplate");
        GameRegistry.registerItem(obsidian_leggings, "Obsidian Leggings");
        GameRegistry.registerItem(obsidian_boots, "Obsidian Boots");
    }
    @EventHandler
    public void init(FMLInitializationEvent event) {
        GameRegistry.addRecipe(new ItemStack(Items.apple, 9),
                "XXX",
                "XXX",
                "XXX",
                'X', Blocks.leaves
        );
        GameRegistry.addRecipe(new ItemStack(ObsidianArmor.obsidian_ingot, 9),
                "X",
                'X', Blocks.obsidian
        );
        GameRegistry.addRecipe(new ItemStack(ObsidianArmor.obsidian_pickaxe),
                "ABC",
                "E",
                "H",
                'A', ObsidianArmor.obsidian_ingot, 'B', ObsidianArmor.obsidian_ingot, 'C', ObsidianArmor.obsidian_ingot,  'E', Items.stick, 'H', Items.stick
        );
        GameRegistry.addRecipe(new ItemStack(ObsidianArmor.obsidian_sword),
                "B",
                "E",
                "HI",
                'B', ObsidianArmor.obsidian_ingot, 'E', ObsidianArmor.obsidian_ingot, 'H', Items.stick
        );
        GameRegistry.addRecipe(new ItemStack(ObsidianArmor.obsidian_helmet),
                "ABC",
                "DF",
                'A', ObsidianArmor.obsidian_ingot, 'B', ObsidianArmor.obsidian_ingot, 'C', ObsidianArmor.obsidian_ingot, 'D', ObsidianArmor.obsidian_ingot, 'F', ObsidianArmor.obsidian_ingot
        );
        GameRegistry.addRecipe(new ItemStack(ObsidianArmor.obsidian_chest),
                "AC",
                "DEF",
                "GHI",
                'A', ObsidianArmor.obsidian_ingot, 'C', ObsidianArmor.obsidian_ingot, 'D', ObsidianArmor.obsidian_ingot, 'E', ObsidianArmor.obsidian_ingot, 'F', ObsidianArmor.obsidian_ingot, 'G', ObsidianArmor.obsidian_ingot, 'H', ObsidianArmor.obsidian_ingot, 'I', ObsidianArmor.obsidian_ingot
        );
        GameRegistry.addRecipe(new ItemStack(ObsidianArmor.obsidian_leggings),
                "ABC",
                "DF",
                "GI",
                'A', ObsidianArmor.obsidian_ingot, 'B', ObsidianArmor.obsidian_ingot, 'C', ObsidianArmor.obsidian_ingot, 'D', ObsidianArmor.obsidian_ingot, 'F', ObsidianArmor.obsidian_ingot, 'G', ObsidianArmor.obsidian_ingot, 'I', ObsidianArmor.obsidian_ingot
        );
        GameRegistry.addRecipe(new ItemStack(ObsidianArmor.obsidian_boots),
                "AC",
                "DF",
                'A', ObsidianArmor.obsidian_ingot, "C", ObsidianArmor.obsidian_ingot, 'D', ObsidianArmor.obsidian_ingot, 'F', ObsidianArmor.obsidian_ingot
        );
    }
}

Any suggestions as to why this keeps failing? If needed, I do have a local copy of the crash log.
Comment: Here is the link to the crashlog: https://pastebin.com/tiy8qBMH
Comment: Which line is line 69?
Answer: The shape of characters in your recipes need to be rectangles. If the recipes themselves aren't rectangles, add spaces where you don't need items. For example, this:
            "ABC",
            "E",
            "H",

should be this:
            "ABC",
            " E ",
            " H ",

Make that change in all of your recipes and the error will go away.
Answer: At
GameRegistry.addRecipe(new ItemStack(ObsidianArmor.obsidian_sword),
            "B",
            "E",
            "HI",
            'B', ObsidianArmor.obsidian_ingot, 'E', ObsidianArmor.obsidian_ingot, 'H', Items.stick
    );

You're lacking what I should be.
At the new code at line 69 you are missing a few spaces to make the re ipe square. You should always fill in a 3x3 grid. Or make sure each item in the array that defines the recipe contains an equal number of items.
 "B " // lacks a space
 "E ", // lacks a space
 "H  ", // proper amount of spaces

In those crash logs, always find the class that is your class that will give you the line number in your class that caused it

com.haxium.basicmod.obsidian.armor.ObsidianArmor.init(ObsidianArmor.java:69)

This gives us line 69 in file ObsidianArmour.java
and the error at the top

java.lang.StringIndexOutOfBoundsException: String index out of range: 7

Tells us that the problem lies in strings. There were too few characters instead of the expected 9.
Comment: Can you update the question with the new code and a link to a new crash log?
Comment: @Draco18s Brainfart on my side, had the 9 total stuck in my head, typed that, meant 3x3. Fixed it now
Comment: Awesome! Thanks for your help. I will make those changes to the code
Comment: Joseph Sible, I made the appropriate changes and the code is still producing the same errors
Comment: In those crash logs, always find the class that is your class `com.haxium.basicmod.obsidian.armor.ObsidianArmor.init(ObsidianArmor.java:69)` and the error at the top `java.lang.StringIndexOutOfBoundsException: String index out of range: 7`
Comment: That is where I am starting to define some of the recipes to craft the items I have created in the mod. Why would it throw an IndexOutOfBounds exception when no index is being referenced?
Comment: Is it possible that I am using the method out of context and Forge just doesn't recognize the method call?
Comment: So, the grid definition was the index it was referring to. That is good to know. I've run the code again and noticed some more errors in my code, but I think your suggestions did the trick. Thanks again!
Comment: The game will now load, but crafting these items doesn't. Any ideas as to what I need to do to correct the problem?
Comment: @ConnorTozer that you need to ask in a new question
Comment: @Tschallacka Note that recipes do not HAVE to be 3x3. `"B","E","H"` is perfectly valid. They *do* have to be rectangular, though.
Comment: @Draco18s i know it is valid, ophad put spaces there so i just went with it.


Show uniform convergence on a compact set given local comparison

Question: For $z \in \Bbb{C}$, $n\geq 1$ let,
$$a_n(z) := e^{-z/n}\left(e^{z/n}-1-\dfrac{z}{n}\right)$$
Then, for $z \neq 0$, $$ \left(\dfrac{n}{z}\right)^2 a_n(z) \xrightarrow[n\rightarrow +\infty]{} \dfrac{1}{2}
 \quad \text{ therefore }\quad |a_n(z)| \underset{n\rightarrow +\infty}{\sim} \dfrac{1}{2} \dfrac{|z|^2}{n^2} $$
Hence the series $\sum_{n = 1}^{+\infty} a_n(z)$ converges absolutely, but given a compact subset $K$ of $\Bbb{C}$, I feel one can get more, namely,
$$\sup_{z \in K} \{ |a_n(z)| \} =: \Vert a_n\Vert_{\infty}^K = \mathcal{O} \left( \dfrac{1}{n^2} \right) $$
that would give us the uniform convergence of $\sum a_n(z)$ on any compact subset. But I cannot think of any proper explanation at the moment. Any help would be gladly appreciated.

Edit: After thinking about it, I might have found a more general approach. Let $K$ be a compact subset of $\Bbb{C}$, then as $$ f(w) := \dfrac{e^{-w}}{w^2}(e^w-1-w) \xrightarrow[w\rightarrow 0]{} \dfrac{1}{2} $$
there is $r>0$ such that $$\forall w \in D(0,r), |f(w)|\leq 1$$
As $K$ is compact, it is bounded therefore there is some $M_K>0$ such that $K \subset D(0,M_K)$. Therefore, there exists $N_K \in \Bbb{N}$ such that,
$$\forall n \geq N_K, \forall z \in K, \left| \dfrac{z}{n} \right| \leq r.$$
Hence,
$$\forall n \geq N_K, \forall z \in K, \quad \left|f\left(\dfrac{z}{n}\right)\right| \leq 1,$$
which yields,
$$\forall n \geq N_K, \forall z \in K, \quad |a_n(z)| \leq \dfrac{|z|^2}{n^2} \leq \dfrac{M_K^2}{n^2}.$$
Therefore, $$ \forall n \geq N_K, \quad \sup_{z \in K} |a_n(z)| \leq \dfrac{M_K^2}{n^2}.$$
Whence the normal convergence of $\sum a_n(z)$ on any compact subset of $\Bbb{C}$.
Answer: One can show that the function
$$
 f(w) = e^{-w}(e^w-1-w)
$$
satisfies
$$ \tag{$*$}
 |f(w)| \le \frac 12 |w|^2 e^{|w|}
$$
for all $w \in \Bbb C$. Setting $w = z/n$ then gives the estimate
$$
 |a_n(z)| \le \frac 12 \frac{|z|^2}{n^2} e^{|z|/n}
\le \frac 12 \frac{|z|^2}{n^2} e^{|z|}
$$
and since $|z|^2e^{|z|}$ is bounded on a compact set $K$, the desired conclusion
$$
\sup_{z \in K} \{ |a_n(z)| \}  = \mathcal{O} \left( \dfrac{1}{n^2} \right)
$$
follows.
It remains to prove $(*)$: First we determine the power series of the function $f$:
$$
\begin{align}
f(w) &= 1-e^{-w}(1+w) \\
& = 1 - \left( \sum_{k=0}^\infty \frac{(-1)^k}{k!}w^k\right) \cdot (1+w) \\
& = \sum_{k=2}^\infty (-1)^k\left( -\frac{1}{k!}+\frac{1}{(k-1)!}\right) w^k \\
& = \sum_{k=2}^\infty (-1)^k \frac{k-1}{k!} w^k \, .
\end{align}
$$
Now we can estimate the absolute value:
$$
\begin{align}
 |f(w)| &\le \sum_{k=2}^\infty  \frac{k-1}{k!} |w|^k \\
& = \frac 12 |w|^2 \sum_{k=2}^\infty  \frac{2(k-1)}{k!} |w|^{k-2} \\
& = \frac 12 |w|^2 \sum_{k=0}^\infty  \frac{2(k+1)}{(k+2)!} |w|^{k} \\
& \le \frac 12 |w|^2 \sum_{k=0}^\infty  \frac{1}{k!} |w|^{k} \\
& = \frac 12 |w|^2 e^{|w|} \, .
\end{align}
$$
Comment: Thank you for this clear and well-written answer. It perfectly solves the problem. Before marking your answer as accepted, I would like to take some time to think about this problem more thoroughly, and try to come with another approach if possible, my intuition tells me there must be another way to tackle it, but I might be wrong. Thank you again, have a nice evening.
Comment: I tried answering my question in the edit, do you think it is correct?
Comment: @Axel: Yes, I think it is.


What test should I use for my data?

Question: I have one categorical predictor coded as 0 or 1 for a sample of about 290.
Based on some research, I want to control for 4 covariates. One is continuous (age) and the rest are categorical (gender, ever having used certain drugs as either yes or no).
My outcome is number of violent acts - this is what I'm having trouble with. According to a professor at my university this isn't a true continuous variable as it is an interval variable. This confused me as I've used interval variables as continuous in other tests.
What type of test would I use if my outcome was continuous? Do I need to use a different one for my interval data?
I am using SPSS to analyze my data. After finding base associations (using t-tests) between my predictor and outcome and covariates and outcome, I tried to go further.
I did a univariate analysis of variance (under general linear models) with my predictor as a fixed factor. This seems logical as there's a section for covariates, but I honestly have no idea. Any guidance would be much appreciated.
Answer: If you have counts of a type of event as your dependent variable then you should use an analysis that is designed for that type of dependent variable. Poisson regression is the simplest choice to start. Your predictor of main interest and the covariates would be the independent variables, similarly to the standard multiple linear regression you might perform with a truly continuous dependent variable, but they now help predict the probability of an event's occurrence.
Several Cross Validated pages explain the advantages of Poisson regression or related count-specific analyses, for example here and here. Unless you have so many events that your dependent variable is very close to continuous, then a multiple regression treating your dependent variable as having Poisson, overdispersed Poisson, or negative binomial characteristics would seem to make the most sense.  (These are examples of generalized linear models; be careful with the choice of terminology.)

What test should I use for my data?