Sort list of lists creating another mapping list with index values

Question: So i have an original list of lists oList, child lists are sequences of numbers. I create another list srt to manipulate the data like that:
#...
srt = []
for i in range(len(oList)):
    srt.append([ int(oList[i][0]), int(oList[i][2]), i ])

So each element of srt is [n0,n2,idx] (or something like that, main point is that i keep index of original element from oList as last element)...
Now i want to sort it via(n0,n2...ni) with indexing as creation of another mapping list of idx. srt.sort() does the first part just fine, but generating mapping manually seems inefficient to me.
So i want srt to be sorted by both n0, n1 ... ni and another list map to contain indexes of original elements.
And while processing data in a loop i want to be able (when i need to) to get some element from srt via idx like that: something = srt[map[idx]][0]
Example:
# srt=[ [12,8,0], [-4,4,1], [-4,-2,2], [6,8,3], ]
map, srt = custom_sort_here(srt)
# srt=[ [-4,-2,2], [-4,4,1], [6,8,3], [12,8,0], ]
# map=[ 3, 1, 0, 2, ]
# here i can get element with idx=2 from srt like:
el = srt[map[2]]

P.S. atm i have my indexing performed AFTER the sorting as a loop:
#...
srt.sort()
map = range(len)
for x in range(len):
    map[srt[x][2]]=x #for 2-number lists where idx at [2]

So it is very inefficient, and that's the reason for my question - i mean it's definitely possible to create mapping structure WHILE sorting, and i just don't know how cuz i'm new to Python...
P.P.S. if u wonder why i want such weird behaviour - it has something to do with 3D mesh processing, so i really need to keep original point values + polygon data while manipulating duplicate point array of projected [2]coords and/or discreet (approximated) [3]coord values of the original points. Looping thru them along the axis/vectors while sometimes still get some points via indexes according to polygon edge connections. So i REALLY need that kind of data layout.
Comment: -Is- it very inefficient?  You're doing the hard work, the O(nlogn) part, at C speed.  Then you have an O(n) part afterward at CPython (?) speed.  You could modify one of the sorts at http://stromberg.dnsalias.org/~strombrg/sort-comparison/ , to change how the indexing and swaps are done (at CPython speed), to eliminate the O(n) step (doing the sort in time O(nlogn), but at CPython speed) but you may find you're better off with what you have already.  Keep in mind that although a little complicated, Timsort is often "supernaturally fast" and stable.
Comment: Well nice point, it's just that i want to optimize EVERYTHING i can cuz the other parts already pretty complex =)) As to CPython - i don't sure how it works, it is a python plugin for Cinema4D i work on. It is definitely gets compiled, but i don't know if it's a bytecode or pure binary...
Answer: This may be what you are looking for, but to be sure would need a complete worked example with expected output.
srt= [ [12,8,0], [-4,4,1], [-4,-2,2], [6,8,3] ]

srt_enum = dict(sorted(enumerate(srt), key=lambda x: x[1]))

# {2: [-4, -2, 2], 1: [-4, 4, 1], 3: [6, 8, 3], 0: [12, 8, 0]}

srt_enum_lst = sorted(srt_enum.items(), key=lambda x: x[1])

# [(2, [-4, -2, 2]), (1, [-4, 4, 1]), (3, [6, 8, 3]), (0, [12, 8, 0])]

srt_enum[2]

# [-4, -2, 2]

Comment: Well, it works, but it's not the *indexing*. Such approach has a dict structure + list structure with duplicate data + also list has excessive extra hierarchy level with duplicate indexes. I like my manual indexing much more, even tho it's ineffective cuz performed AFTER sorting and i guess it is done in nonpythonish way, cuz im newbie in Python...
Comment: @Markus_13, if the performance of these tasks is poor, consider Cyton or just plain C for customised structures. But first I'd confirm that this really is a  bottleneck for your application.
Comment: Well as i said in the comment to main post: i want to optimize EVERYTHING i can cuz the other parts already pretty complex =))
Obviously it's not the bottleneck, but the thing is - i simply CAN'T simplify or optimize the mesh processing part, so i want to optimize everything else what i can. + also it's for learning purposes cuz i study Python, and i can't believe there r no way to create indexing structures on the fly while sorting...


How do you add a site to the Internet Explorer Trusted Zone through GPO in server 2003?

Question: How do you add a site to the Internet Explorer Trusted Zones through GPO in server 2003?
If you do push a site through a GPO does it erase other Trusted Sites that may have been entered on the end users computer?
Thank You,
Keith
Answer: This does clear all the users prevoiusly added sites to ALL their securitys lists.

Open Group Policy Manager
Create New GPO and Link it.
Edit GPO.
Browse to User Config -> Admin Temp -> Windows Components -> Internet Explorer -> Internet Control Panel -> Security Page
Open "Site to Zone Assignment List"
Enable it
Click Show and add your site name and the value 2 for the Trusted Zones list

Keith
Answer: To set a trusted site, in Group Policy editor:
Navigate to
User Config\Admin Templates\Windows Components\Internet Control Panel\Security Page\
Policy: Site to Zone Assignment List
Any site you add to the list with a value to 2, will be in the trusted sites zone.
I think it will merge with existing sites if you have not locked down the zone
see Internet Explorer security zones registry entries for advanced users
and Group Policy and Internet Explorer 8
Comment: Thank you... I was typing my answer and didnt see yours.


Android - give indication that menu is available

Question: Is there any functionality baked into Android SDK that will give user visual clue that menu is available? Or has anybody worked on this problem?
Currently, I need to rely on user clicking Menu button and sometimes it's just not so obvious that certain Activity has Menu.
So, any suggestions?
Answer:
Is there any functionality baked into Android SDK that will give user visual clue that menu is available?

No.

So, any suggestions?

I consider three tiers of UI:

The #1 point behind the activity should be accessible directly on the screen, without any menus.
Things that somebody might want to do on the activity but are not quite as important can go in an options menu. The MENU button is always there -- users will learn to press it from time to time.
If you have a ListView, and you want to have a context menu for operations on individual list items, that's cool...for power users. For ordinary people, have some more discoverable path they can take that will let them do the same things. So, for example, if a context menu offers Edit and Delete options, a simple tap on the same item should lead to an activity where the user can get to Edit and Delete options menu items.

Also, try a few different ways of offering help, in hopes that some users will, one way or another, RTFM:

Traditional help screen (e.g., HTML in a WebView)
Tip-of-the-day on startup
Screencasts in the app (make them entertaining, and users will consider them "content" as much as "docs")
Docs/screencasts on your Web site (for those who are more comfortable with long-form material on a bigger screen than their device offers)
Comment: Well, I can honestly say you are right on all accounts... just I'm lazy kind of programmer (not sure if there is non-lazy kind of programmer ;) - and in my app I have simple ListView; and all options (find additional items, help, logout) are put into Menu. So, I'm looking for a way to say - hey if you want to populate that ListView, tap Menu. Or if you wish to logout, tap Menu. I know MOST of the Android users will know to press Menu, but it's just not intuitive for some. Guess my option is to either put buttons directly in Activity, or develop "visual clue" myself...


method as goal function in Microsoft Solver Foundation?

Question: Here is a typical optimization formulation with MSF:
using Microsoft.SolverFoundation.Services;

SolverContext context = SolverContext.GetContext();
Model model = context.CreateModel();

//decisions
Decision xs = new Decision(Domain.Real, "Number_of_small_chess_boards");
Decision xl = new Decision(Domain.Real, "Number_of_large_chess_boards");

model.AddDecisions(xs, xl);

//constraints
model.AddConstraints("limits", 0 <= xs, 0 <= xl);
model.AddConstraint("BoxWood", 1 * xs + 3 * xl <= 200);
model.AddConstraint("Lathe", 3 * xs + 2 * xl <= 160);

//Goals
model.AddGoal("Profit", GoalKind.Maximize, 5 * xs + 20 * xl);

// This doesn't work!
// model.AddGoal("Profit", GoalKind.Maximize, objfunc(xs, xl));

Solution sol = context.Solve(new SimplexDirective());
Report report = sol.GetReport();
Console.WriteLine(report);

Is it possible to use a separate method instead of a statement like "5 * xs + 20 * xl" as goal function? For example, a method like the following? How?
// this method doesn't work!
static double objfunc(Decision x, Decision y)
{
    return 5 * x.ToDouble() + 20 * y.ToDouble();
}

Comment: Seems like `objfunc` should return a `Term` -- or maybe you just need to add the cast explicitly
Answer: It is as simple as that:
 static Term objfunc(Decision x, Decision y)
        {
            return 5 * x + 20 * y;
        }

Rather than returning a double, the function has to return a Term.
Comment: How can I use decision variables in a separate method if they are defined as a set of values like: Set setMonths = new Set(Domain.IntegerRange(1,12) , "Months"); Decision dPrice = new Decision(Domain.RealNonnegative, "Price", setMonths); I can now pass dPrice as a Decision to a method, but how can I read the individual values (like dPrice[month])? I couldn't yet find a way. Thanks
Comment: Indexed Decision variables are explained here: http://nathanbrixius.wordpress.com/2011/07/18/getting-solution-values-using-solver-foundation-services/
Comment: How can I get indexed values before executing solve()? dPrice.GetDouble(i) produces an error if I call it before solve().
Comment: I would like to know this as well :-)
Comment: @Fiffe: The syntax is dPrice[i]  like a typical array index access. Consult Natan Brixius' blog via the link of my comment above.
Answer: Note The function does not return a numerical answer, but a method to evaluate the answer. If you were to recode as
Term Test = 5 * x + 20 * y;
String strTest = Test.ToString();
Then strTest would by something like (Add(mult(5,x), mult(20,y));


How to check if cursor is on an empty line inside textarea?

Question: How do I check if the cursor is on an empty line inside a textarea?
I don't care about word wrapping. I care about lines that were created by hitting Enter.
$('textarea').on("change keyup", function() {
  if (cursor is on an empty line or the the line has just spaces) {
    console.log("empty");
  } else {
    console.log("has stuff");
  }
});

For example:

This would log "has stuff"
The line above would log "empty" and this line would log "has stuff"
Comment: As i know javascript it is not possible
Comment: An empty line can be due to word-wrapping as well as one that was generated by a CR/LF. Which do you care about?
Comment: The only approach I can think of (count the characters) depends on the browser using a monospace font inside the textarea, which can't be guaranteed anymore.
Comment: @Diodeus I care about any linebreak that takes the cursor to a blank line that has nothing in it or just whitespace.
Comment: @Diodeus I don't care about word wrapping.
Comment: Look at the ASCII value of the character before the cursor, if it's 10 or 13, you have a new line.
Answer: The following should work, but won't in older versions of IE.
// on(..., function() {
if( this.value.substr(0,this.selectionStart).match(/(?:^|\r?\n\s*)$/)
 && this.value.substr(this.selectionStart).match(/^(?:\s*\r?\n|$)/)) {
    console.log("empty");
}

EDIT search now explicitly looks for a newline, with further whitespace optional.
Comment: The first `substr` gets everything before the cursor, and the regex tests to ensure that it ends with a newline (ie. there is no text before the cursor or a newline). The second `substr` gets everything after the cursor, and does the same kind of check.
Comment: What does `this` refer to here, the value of the textarea?
Comment: It refers to the element on which the event is bound. In this case, the textarea itself.
Comment: Actually, scratch that. If the textarea has any text at all it wont work :/
Comment: That's because you changed my code... But you're right about the first and last line stuff. I've edited my answer and [updated your Fiddle](http://jsfiddle.net/5uZjV/1/)
Comment: That's great thanks. There is only one issue. If you start a line, for example, `hello   `, then add a space or more, the console will log `empty`. If the line has any text at all, I want it to log `has stuff`. Is that not possible? I tried tweaking the regex, but no luck.
Comment: Great, thank you. The first `substr()` looks at the start and end of line, right? What's the second `substr()` for? The one after the `&&`.
Answer: Another solution would be:
function is_cursor_on_empty_line(textarea)
{
    // line where cursor is now
    var line_number = textarea.value.substr(0, textarea.selectionStart).split("\n").length;

    // split all lines of the textarea
    var lines = textarea.value.split("\n");

    // current line is empty or not
    return (lines[line_number-1] == '');
}

Example usage with Jquery:
var textarea = $('textarea');

if (is_cursor_on_empty_line(textarea[0]))
{
   // ...
}


Skip length check for a specified $_POST

Question: I'm checking if each POST's length is above 5.
foreach ($_POST as $val) {
    if (strlen($val) < 5) {
        $go= true;
        break;
    }
}

How can I skip one perticualr POST from being checked for a lengh of above 5.
Basically I need to check all POST's are above 5 in length but I want it to ignore checking $_POST['Yes'];
Answer: The above answer is not actually correct, as you are comparing the value.
It will fail, for example, on input:
$_POST = array('Yes'=>'a', 'SomethingElse'=>'a');

This will ignore $_POST['SomethingElse'] even though it should not.
Correct Solution:
To find the solution correctly, you should also loop over the keys:
foreach ($_POST as $key=>$val) {
  if ($key === 'Yes')
    continue;
  if (strlen($val) < 5) {
    $go= true;
    break;
  }
}

Multiple Values:
If you want to do this for multiple keys, you can store them in an array:
$ignores = array('Yes',);
foreach ($_POST as $key=>$val) {
  if (in_array($key, $ignores))
    continue;
  if (strlen($val) < 5) {
    $go= true;
    break;
  }
}

Answer: You can use continue
if($val == $_POST['Yes']) continue;

This will skip the counting of $_POST['Yes'].
Thus, your code should be like this:
foreach ($_POST as $val) {
    if($val == $_POST['Yes']) continue;
    if (strlen($val) < 5) {
        $go= true;
        break;
    }
}

Comment: It should be after your `foreach ` statement
Comment: @Becky Updated code, I forgot to equate it initially, it should work now, thanks
Comment: Thanks. Should that go within the if statement or just below the `foreach()`?
Comment: Thanks. Let me give it a try.


In which spaces,$F$ is irreducible iff $F=\overline{\{x\}}$, for all closed $F$?

Question: I'm wondering which spaces $X$ meet the following condition:

For any closed $F\subseteq X$, $F$ is irreducible if and only if $F=\overline{\{x\}}$ for some $x\in X$.

Where $F$ is irreducible if and only if for all closed sets $F_1,F_2$ such that $F\subseteq F_1\cup F_2$, we have that $F\subseteq F_1$ or $F\subseteq F_2$.
Thanks.
Answer: A point $x\in F$ whose closure is $F$ is called a generic point of $F$ (note that the closure of an irreducible subspace of topological space is always irreducible). A sober topological space is one in which every irreducible closed subset has a unique generic point. Any such space has the property you ask about (the existence of a generic point for each irreducible closed subset). Schemes (e.g. spectra of rings) are sober.
The uniqueness in the definition of sobriety is equivalent to requiring that for distinct points $x\neq y$ in the space, there is either a neighborhood of $x$ not containing $y$, or a neighborhood of $y$ not containing $x$ (I believe this is called $T_0$ or Kolmogorov); more succinctly, $\overline{\{x\}}\neq\overline{\{y\}}$. The indiscrete topology on a set with two elements $X=\{x,y\}$ is such that every irreducible closed set has a generic point, but the generic point is not unique (the space is not $T_0$). So this is another example of a space having the property you ask about, but which is not sober.
I'm not sure what can be said more generally about spaces satisfying your condition.


Why is using $\mathbf{\eta}^T \mathbf{\mu_\mathscr{l}}$ to calculate Fisher's rule easier than using $\mu_\mathscr{l}$?

Question: I am currently studying discriminant analysis. Fisher's discriminant $\mathscr{D}$ is defined as follows:

$$\mathscr{D} = \max_{\{ \mathbf{e} \ : \ \vert\vert \mathbf{e} \vert \vert = 1 \}} \mathscr{q} ( \mathbf{e} ) = \max_{\{ \mathbf{e} \ : \ \vert\vert \mathbf{e} \vert \vert = 1 \}} \dfrac{\mathscr{b} ( \mathbf{e} )}{\mathscr{w} ( \mathbf{e} )}$$

where $\mathbf{e}$ is a $d$-dimensional unit vector, $\mathscr{b}$ is the between-class variability, and $\mathscr{w}$ is the within-class variability.
Now, I am told that, if $W$ is invertible, then the following hold:

the between-class variability $\mathscr{b}$ is related to $B$ by $\mathscr{b} ( \mathbf{e} ) = \mathbf{e}^T B \mathbf{e}$;
the within-class variability $\mathscr{w}$ is related to $W$ by $\mathscr{w}(\mathbf{e}) = \mathbf{e}^T W \mathbf{e}$;
Fisher's discriminant $\mathscr{D}$ equals the largest eigenvalue of $W^{-1} B$; and
the unit vector $\mathbf{\eta}$ which maximises the quotient $\mathscr{q}$ is the eigenvector of $W^{-1}B$ which corresponds to $\mathscr{D}$.

I am told that Fisher's rule $\mathcal{R}_F$ is defined as follows:

$$\mathcal{R}_F = \mathscr{l} \ \ \ \ \text{if} \ \ \ \  \vert \mathbf{\eta}^T\mathbf{X} - \mathbf{\eta}^T \mathbf{\mu_{\mathscr{l}}} \vert < \vert \mathbf{\eta}^T \mathbf{X} - \mathbf{\eta}^T \mathbf{\mu_\nu} \vert \ \ \ \ \text{for all $\nu \not= \mathscr{l}$}$$

The following is then said:

Fisher's rule assigns $\mathbf{X}$ the number $\mathscr{l}$ if the scalar $\mathbf{\eta}^T \mathbf{X}$ is closest to the scalar mean $\mathbf{\eta}^T \mathbf{\mu_\mathscr{l}}$. Thus instead of looking for the true mean $\mathbf{\mu_\mathscr{l}}$ which is closest to $\mathbf{X}$, we pick the simpler scalar quantity $\mathbf{\eta}^T \mathbf{\mu_\mathscr{l}}$ which is closest to $\mathbf{\eta^T} \mathbf{X}$.

I am interested in this part:

Thus instead of looking for the true mean $\mathbf{\mu_\mathscr{l}}$ which is closest to $\mathbf{X}$, we pick the simpler scalar quantity $\mathbf{\eta}^T \mathbf{\mu_\mathscr{l}}$ which is closest to $\mathbf{\eta^T} \mathbf{X}$.

Why does using $\mathbf{\eta}^T \mathbf{\mu_\mathscr{l}}$ instead of $\mathbf{\mu_\mathscr{l}}$ make this easier? If $\mathbf{\mu_\mathscr{l}}$ is difficult to calculate, then why would simply multiplying it by $\mathbf{\eta}^T$ suddenly make it easier to calculate? What is the mathematical reasoning behind this?
Answer: This material on discriminant analysis is, I think, taken from the book Analysis of Multivariate and High-Dimensional Data by Inge Koch.
I think you are absolutely right that $\eta^T \mu_l$ is no easier to calculate than $\mu_l$ itself. In fact, $\eta^T \mu_l$ requires more calculations to obtain than $\mu_l$. However, I think that the word 'simpler' in the sentence you highlight is just emphasising that $\eta^T \mu_l$ is a scalar rather than a vector.
The author then goes on to explain two advantages of using the scalar $\eta^T \mathbf{X}$ to classify rather than the original vector $\mathbf{X}$...

It reduces/simplifies the multivariate comparisons to univariate comparisons. To classify a vector $\mathbf{X}$ using $\eta^T \mathbf{X}$, we would need $d+\kappa$ arithmetical operations, where $d$ is the dimensionality and $\kappa$ is the number of classes: $d$ operations to compute $\eta^T \mathbf{X}$, then a further $\kappa$ operations for the univariate comparisons. To classify using the original vector $\mathbf{X}$, we would need at least $d\kappa$ operations, given that we'd need to compute $\|\mathbf{X}-\mu_l\|$ for every class. So using $\eta^T \mathbf{X}$ can be much more efficient.

It gives more weight to the important variables. This is probably a bigger issue. In the two class scenario, classifying based on computing $\|\mathbf{X}-\mu_1\|$ and $\|\mathbf{X}-\mu_2\|$ is equivalent to classifying with $\eta^T \mathbf{X}$ where $\eta=(\mu_1-\mu_2)/\|\mu_1-\mu_2\|$, but this $\eta$ is in general suboptimal, as can be seen from the example below. Finding the optimal $\eta$ can give a much better classifier.
From: Pattern Recognition and Machine Learning by Bishop (Fig 4.6)

Additional details for 1: the univariate comparisons involve computing $|\eta^T \mathbf{X}-\eta^T \mu_l|$ for each class $l$ in turn, making a note of which class $l$ minimises this quantity. The procedure will take longer if there are more classes, but the computation time is not affected by the dimensionality $d$.
Additional details for 2: In the two class scenario, if we classify using $\mathbf{X}$ then we assign $\mathbf{X}$ to class $1$ if $\|\mathbf{X}-\mu_1\|<\|\mathbf{X}-\mu_2\|$. Define $\eta=(\mu_1-\mu_2)/\|\mu_1-\mu_2\|$. Then $\{\eta\}$ is an orthonormal subset of the underlying vector space, so it can be extended to an orthonormal basis for the entire vector space $\{\eta,e_2,\cdots,e_d\}$. So, for $i=1,2$, $$\|\mathbf{X}-\mu_i\|^2=|\eta^T(\mathbf{X}-\mu_i)|^2+\sum_{k=2}^d |e_k^T(\mathbf{X}-\mu_i)|^2$$ Each $e_k$ is orthogonal to $\eta$, so $e_k^T(\mathbf{X}-\mu_1)=e_k^T(\mathbf{X}-\mu_2)$. Therefore $\|\mathbf{X}-\mu_1\|<\|\mathbf{X}-\mu_2\|$ precisely when $|\eta^T(\mathbf{X}-\mu_1)|<|\eta^T(\mathbf{X}-\mu_2)|$. So we're really just classifying using $\eta^T \mathbf{X}$ for this specific suboptimal $\eta$.
Comment: Thanks for the answer. With regards to 1., can you please clarify what the "univariate comparisons" are? With regards to 2., can you please elaborate on why classifying based on computing $\|\mathbf{X}-\mu_1\|$ and $\|\mathbf{X}-\mu_2\|$ is equivalent to classifying with $\|\mathbf{X}-\mu_2\|$?
Comment: Sorry, I meant equivalent to classifying with $\eta^T \mathbf{X}$ in my comment above with regards to 2. Thank you for the additional details edit.
Comment: Why does each $e_k$ being orthogonal to $\eta$ imply that $e_k^T(\mathbf{X}-\mu_1)=e_k^T(\mathbf{X}-\mu_2)$? I don't understand anything after this part.
Comment: Substract one side of this equality from the other and you're left with $e_k^T(\mu_1-\mu_2)=0$, which is just saying that $e_k$ is orthogonal to $\mu_1-\mu_2$ and hence to $\eta$.
Comment: I don't understand the point of 2. You say "it gives more weight to the important variables", as if that's supposed to improve performance, so why are we using $\eta^T \mathbf{X}$ if it's still suboptimal? Also, note that, in my post, I use $\mathbf{\eta}^T \mathbf{\mu_\mathscr{l}}$ and $\mathbf{\mu_\mathscr{l}}$, which is different than $\eta^T \mathbf{X}$, which is what you're addressing in your answer.
Comment: Also, you say that $e_k$ is orthogonal to $\eta$, and so $e_k^T(\mathbf{X}-\mu_1)=e_k^T(\mathbf{X}-\mu_2)$. But how does this then imply that "$\|\mathbf{X}-\mu_1\|<\|\mathbf{X}-\mu_2\|$ precisely when $|\eta^T(\mathbf{X}-\mu_1)|<|\eta^T(\mathbf{X}-\mu_2)|$"?
Comment: The point of 2 is that classifying using $\|\mathbf{X}-\mu_i\|$, which naively seems sensible, is implicitly classifying using $\eta^T\mathbf{X}$ for a specific $\eta$ (at least in the two class scenario). Fisher's rule optimises over all possible $\eta$ so you generally get a better classifier i.e. a better $\eta$.
Comment: Regarding your other comment, look at the displayed equation for $\|\mathbf{X}-\mu_i\|^2$. Each component of the sum has the same value for $i=1,2$, so the only way we could have $\|\mathbf{X}-\mu_1\|<\|\mathbf{X}-\mu_2\|$ is if $|\eta^T(\mathbf{X}-\mu_i)|^2$ differed for $i=1,2$.
Comment: How can it be over all possible $\eta$ when we're using $\eta=(\mu_1-\mu_2)/\|\mu_1-\mu_2\|$, which is a single $\eta$? I don't see any iteration over many possible $\eta$ going on here.
Comment: The 'naive' classification based on $\|\mathbf{X}-\mu_i\|$ uses a single suboptimal $\eta=(\mu_1-\mu_2)/\|\mu_1-\mu_2\|$. Fisher's rule optimises over all $\eta$: but this is not done by iteration, it's done by calculation of the eigenvectors of $W^{-1}B$.


Recursion from inside IIFE

Question: I have a piece of code which generates all the possible strings that can be made by placing spaces in-between the letters of a given string, the code uses recursion to achieve this. Here is the code I have (it's a C++ source I have adapted to JavaScript and it works as expected):
    var genStringsUtil = function (str,buf,i,j,n){
      if(n == i){
        buf[j] = " ";
        console.log(buf.join(""));
        return;
      }
        buf[j] = str[i];
        genStringsUtil (str,buf,i+1,j+1,n);
        buf[j] = " ";
        buf[j+1] = str[i];
        genStringsUtil (str,buf,i+1,j+2,n);
    }

   var genStrings = function(s){
      var str = s;
      var n =str.length;
      var buf = [];
      buf[0] = str[0];

      genStringsUtil (str,buf,1,1,n);
    };

   function main(){
    genStrings("ABCDE");
   }

   main();

Now, I have modified it like this and it still works:
var genStrings = function (str,buf,i,j,n){
  if(n == i){
    buf[j] = " ";
    console.log(buf.join(""));
    return;
  }
  buf[j] = str[i];
  genStrings (str,buf,i+1,j+1,n);
  buf[j] = " ";
  buf[j+1] = str[i];
  genStrings (str,buf,i+1,j+2,n);
}

!function(s){
  var str = s;
  var n =str.length;
  var buf = [];
  buf[0] = str[0];

  genStrings (str,buf,1,1,n);
}("ABCDE");

However, when I change the last part to (IIFE with parentheses):
(function(s){
  var str = s;
  var n =str.length;
  var buf = [];
  buf[0] = str[0];

  genStrings (str,buf,1,1,n);
})("ABCDE");

I get an error :

TypeError: j is undefined

If I put the closing parenthesis after ("ABCDE") like so:
(function(s){
  var str = s;
  var n =str.length;
  var buf = [];
  buf[0] = str[0];

  genStrings (str,buf,1,1,n);
}("ABCDE"));

I get another error :

TypeError: genStrings is not a function

I always thought that IIFEs declared with ! or the parentheses were the same thing, but obviously not. So my question is basically what is going on that is different in those three cases? Is recursion the issue?
I hope my message is not too long.
Thank you for your help.
Comment: You forgot a semicolon, so `genStrings` is being invoked immediately because of your parentheses. VTC'ing as typo. Consider using a linter
Comment: Thank you. I don't see where I'm missing a semi-colon? I get two different error messages depending on where the closing parenthesis is. If it's before the argument **("ABCDE")**, I get  _j is undefined_ even if I add a semi-colon before **("ABCDE")**. For the second case I don't see where I'm missing the semicolon.
Comment: You need a semicolon after the whole `genStrings` function, else it will be invoked immediately because the `function() { }` is immediately followed by `(...)` (interpreted as a call)
Comment: Sorry I just realized what you meant as I validated my answer. It works now. Thank you for your help. One last question, what do you mean by _VTC'ing as typo_
Comment: VTC = voting to close. (Typo questions are off-topic for SO and should be closed)
Answer: C++ has several limitations that JavaScript does not have. There are countless ways to encode your function in JavaScript, but here is one that uses continuation-passing style.
In this style, a second parameter send is added to your genStrings function's signature and accepts the default identity continuation. This effectively turns return into a user-configurable function. The name send is used because return is a reserved keyword.
Another notable aspect of this implementation is the use of referential transparency, a property of functional style, where a function always returns the same result for the same inputs. As recursion is a functional heritage, we are sure to maintain this property to yield the best result.

const identity = x =>
  x

const concat = (xs, ys) =>
  xs .concat (ys)

const genStrings = ([ char, ...rest ], send = identity) =>
  // base case: return empty set
  char === undefined
    ? send ([])

  // if there is only one char, return singleton result
  : rest.length === 0
    ? send ([char])

  // otherwise recur on rest
  // 1) add char plus space to each combination
  // 2) add char without space to each combination
  // 3) concat the result
  : genStrings
      ( rest
      , combs =>
          send ( concat ( combs .map (c => char + ' ' + c)
                        , combs .map (c => char + c)
                        )
               )
      )

console.log (genStrings ('ABC'))
// [ 'A B C'
// , 'A BC'
// , 'AB C'
// , 'ABC'
// ]

You'll also notice that there's no need for keeping track of several other state variables like n, i, and j, nor the need to increment them with different values. Programs using fewer expressions and variables are easier to maintain and easier to debug.
genStrings works with larger inputs too, like the example in your question
console.log (genStrings ('ABCDE'))
// [ 'A B C D E'
// , 'A B C DE'
// , 'A B CD E'
// , 'A B CDE'
// , 'A BC D E'
// , 'A BC DE'
// , 'A BCD E'
// , 'A BCDE'
// , 'AB C D E'
// , 'AB C DE'
// , 'AB CD E'
// , 'AB CDE'
// , 'ABC D E'
// , 'ABC DE'
// , 'ABCD E'
// , 'ABCDE'
// ]

We were also careful to make genStrings a total program, meaning it returns a valid result, even when the input string is empty
console.log (genStrings (''))
// []

Because genStrings is defined using continuation-passing style, we can specify a user-configurable continuation at the call site as well
genStrings ('ABC', console.log)
// [ 'A B C', 'A BC', 'AB C', 'ABC' ]

genStrings ('ABC', combs => combs.length)
// 4

genStrings ('ABC', combs => combs .join (', '))
// 'A B C, A BC, AB C, ABC'

As genStrings is a pure function with a well-defined domain (input) and codomain (output), there's no need for an immediately-invoked function expression (IIFE), let alone the need to debug one.

I started studying it but I cannot understand what is the : colon syntax before rest.length === 0 and genStrings?

?: is JavaScript's conditional operator, also called the ternary operator. The syntax is conditionExpression ? trueExpression : falseExpression. When conditionExpression evaluates to a truthy value, only trueExpression is evaluated, and falseExpression is skipped. Contrarily, if conditionExpression evaluates to a non-truthy value, the trueExpression is skipped and only the falseExpression is evaluated.
It is the expressional equivalent of the if-else statement, but instead of relying upon side-effects, it evaluates to a value, as do all other expressions.
// conditional expression
let someValue =
  n === 0                // expression
    ? "n is zero"        // expression
    : "n is not zero"    // expression

// if statement
let someValue
if (n === 0)
  someValue = "n is zero"         // side effect
else
  someValue = "n is not zero"     // side effect

Above, the if statement is more verbose and relies upon side effects to set the value for someValue. The conditional expression evaluates to a value and can be directly assigned to a variable.
Similar to if-else if-else statements, conditional expressions can also be chained together. This is the syntax you're seeing in the answer above.
const animalSound =
  animal === "dog"    // if
    ? "woof"          // then

  : animal === "cat"  // else if
    ? "meow"          // then

  : "unknown"         // else

It helps me to see the same program represented in a variety of ways. Below, we rewrite the original answer using imperative-style if statements

const identity = x =>
  x

const concat = (xs, ys) =>
  xs .concat (ys)

const genStrings = ([ char, ...rest ], send = identity) =>
{ if (char === undefined)
    return send ([])

  else if (rest.length === 0)
    return send ([char])

  else
    return genStrings
             ( rest
             , combs =>
                 send ( concat ( combs .map (c => char + ' ' + c)
                               , combs .map (c => char + c)
                               )
                      )
             )
}

console.log (genStrings ('ABC'))
// [ 'A B C'
// , 'A BC'
// , 'AB C'
// , 'ABC'
// ]
Comment: thank you for the response. I started studying it but I cannot understand what is the : colon syntax before _rest.length === 0_ and _genStrings_?
Comment: you're welcome. I made an update to the answer to reply to your comment.
Comment: thank you! I knew about the ternary operator but I didn't know you could do _else if_-like structures by chaining them. Great :)

Recursion from inside IIFE


Mover lista de arquivos entre pastas

Question: Tenho um método que copia arquivos de uma pasta para outra, deletando o arquivo em seguida. Até me atende perfeitamente, mas gostaria de saber se há alguma forma de se fazer isso sem precisar recorrer a InputStream e OutputStream, pois já tive alguns problemas com escrita utilizando estas classes.
Vi que no java 8 há funções que facilitam operações com arquivos utilizando a classe Files. É possível fazer essa operação de "mover arquivos" de forma mais simples e direta, utilizando outros métodos, como por exemplo, a classe Files?
Segue o código atual:
private static void copiarArquivos() throws IOException {

    File src = new File(".");
    String dstPath = "C:\\java\\";
    File dst;

    File[] files = src.listFiles();

    for (File f : files) {
        String fileName = f.getName();

        if (fileName.contains("File")) {

            dst = new File(dstPath + fileName);
            InputStream in = new FileInputStream(f);
            OutputStream out = new FileOutputStream(dst);
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
            f.delete();
        }
    }
}

Comment: Não sei se quer saber alguma coisa específica, mas em qualquer Java dá para fazer melhor que isso se quer apenas mover os arquivos, pode deixar o sistema operacional fazer isso sem copiar um byte sequer.
Comment: @bigown usando a própria classe File? Sinceramente eu não faço ideia de como faz, pensei que era coisa da classe Files, desse pacote novo que foi adicionado nas versões mais novas. Editei a pergunta para não se fechar apenas ao java 8 ou a classe citada.
Comment: `java.nio.file.Files` tem um `move` desde a versão 7, não serve pra você?
Answer: A primeira grande mudança a fazer é só mover o arquivo e não copiá-lo, isso é um enorme desperdício de recurso. Você pode apenas pedir para o sistema operacional rearranjar sua organização do sistema de arquivos, sem sequer copiar, ou mesmo mover um byte dele, basta mudar os metadados dele para indicar que está em outra pasta. Não precisa saber de nada como isso funciona, basta saber qual o método chamar.
private static void copiarArquivos() throws IOException {
    File src = new File(".");
    String dstPath = "C:\\java\\";
    for (File f : src.listFiles()) {
        String fileName = f.getName();
        if (fileName.contains("File")) Files.move(f.toPath(), Paths.get(dstPath, fileName), REPLACE_EXISTING);
    }
}

Coloquei no GitHub para referência futura.
Java 8 ainda permite usar streams (exemplos) e o código pode ficar mais declarativo. Nem sempre gosto, acho que assim é simples e compreensível.
Dá para matar duas variáveis, mas deixei.
Comment: Não tem problema algum. Mover significa mudar os metadados do sistema de arquivo, não mexe no conteúdo, então você muda o *path*  todo dele, não há distinção entre nome do arquivo e da pasta, o que está fazendo é trocar o nome de um objeto, parte do nome é o sobrenome dele, ou seja, é a pasta. Renomear é justamente mover, para a mesma ou outra pasta.
Comment: A titulo de curiosidade, ao inves de copiar com o mesmo nome e renomear depois, posso renomear ao mover alterando dentro do `Path.get`?
Comment: Não está copiando nada, está movendo.
Comment: Então não tem problema mover com nome diferente?
Comment: Só uma pequena correção(só pude testar hoje kkk), o método `move` espera 3 parametros, sendo 2 do tipo Path e um terceiro opcional do tipo `CopyOption`. Como fileName é *String*, foi necessário trocar por `f.toPath()` para funcionar corretamente.
Comment: @diegofm Verdade, eu fiz sem me atentar a esses detalhes. Estou corrigindo.
Answer: Apenas a título de curiosidade em versões anteriores ao 7.
Renomeando:
import java.io.File;

public class Movendo {

  public static void main(String[] args) {
    try {
      File arquivo = new File("C:/pasta1/arquivo.txt");

      if (arquivo.renameTo(new File("C:/pastab/" + arquivo.getName()))) {
        System.out.println("Arquivo movido com sucesso!");
      } else {
        System.out.println("Falha ao mover arquivo!");
      }
    } catch (Exception e) {
      System.out.println("Falha ao mover arquivo!");
    }
  }
}

Mover lista de arquivos entre pastas


How to prevent granting Userpoints again after a user already passed a Quiz?

Question: I'm using the Quiz and the User Points module.
After a user takes a quiz, the points are granted. But if the quiz is taken multiple times, the points are granted multiple times also. For example;

points balance: 0
after quiz (1st time), point balance: 10
take the same quiz again, point balance becomes: 10+10=20

I don't want it to be cumulative. How can I prevent this?
Answer: You might use the Rules module to take away the role which has the permission to take the quiz once the quiz has been completed.
Answer: Using the Rules module, as suggested in the prior answer, is indeed a way to answer this question. Especially now that there is the 7.x-5.x release of the Quiz module, which enables all sorts of Rules logic to be implemented for quizes. However, if you have many quizes, you'd also end up with many roles if you'd use the approach suggested in the prior answer.
Therefor, I suggest you rather use a combination of the Rules module with the Flag module. Here is a summary of how to do so:

Use the Flag module to create a flag for tracking Passed Quizes.
Use the Rules module to implement this logic: if the quiz node (to which this quiz result relates) is not yet flagged (by the flag that was created for it), and the quiz result is that it is at least equal to the pass rate of that quiz, then it is the very first time this user passed the quiz. At which time the quiz node gets flagged. From then on use a Rules Condition to check if the quiz node was flagged or not by the current user. And based on that Rules Condition, you decide to yes or no perform some Rules Action(s), e.g to grant points (but only 1 time).

For more details, refer to my answer to "How to check if user has passed the quiz already before granting user points?", which also includes an export of the configuration of the flag and the rule to get this to work.
PS: I'm assuming this question is about D7.


D-Calibration for Survival Models with imbalanced outcomes

Question: I am building an accelerated time failure (AFT) model on a highly imbalanced data set 90% survival 10% death. I understand that we can not use Brier score because of the outcome imbalance, Brier score dose not fair well with imbalanced data, and I am looking at the C-index and D-calibration to help validate my model. I am struggling to understand how to interpret the D-calibration score. The following paper is the best resource I could find explaining D-calibration but I am still confused on interpreting the outcome. If the p value is close to significant, e.g., 0.052, what is that saying?
Effective Ways to Build and Evaluate Individual Survival Distributions pg.16
https://arxiv.org/pdf/1811.11347.pdf
Using this package to calculate the D-Calibration with the following output options

statistic returns the chi squared test statistic
pval returns the chi squared test p value
max_deviation returns the maximum percentage deviation from the expected value, calculated as abs(expected_percentage - real_percentage), where expected_percentage = 1.0/n_bins
histogram returns the full calibration histogram per bin
all returns all of the above in a dictionary

https://loft-br.github.io/xgboost-survival-embeddings/modules/metrics.html
Comment: Brier score does can not handle imbalanced data outcome from my understanding. "A noted shortcoming of the Brier score is that it doesn't fare well when the classes are imbalanced."  https://statisticaloddsandends.wordpress.com/2019/12/29/what-is-a-brier-score/
Comment: Please say more about the nature of your data and your analysis: how many cases total, how many predictors you are evaluating, why you are choosing an AFT model, what type of AFT model your are building, why you are using `xgboost`, how you intend to use your model, whether you are interested specifically in trying to estimate individual survival curves (as in the linked paper) or if population-level analysis is adequate, etc. The best way to proceed might depend on that information. Please edit your question to include that information, as comments can be easily overlooked or deleted.
Comment: What's wrong with Brier score? // What about log loss?
Comment: Is there some text that backs up the use of log loss for survival models
Answer: For D-calibration, we use Pearson's χ2 goodness-of-fit test, which generates a p-value to say if patients should believe the results.
If your results are closed to the threshold, I strongly recommend you do multiple tests and check how many experiments the p-value is more than the threshold.
It is the same with other p-values, if the p-value is greater than one threshold, we can have statistically significant. So I asked my statistical professor, and in the empirical project, we check if we passed the p-value threshold.


add checkbox content to text field

Question: New to rails, also not great in english... I need some advice please.
I have a form with a non-exhaustive list of drugs. The user can select drugs with check-boxes.
There is a check-box called "Other" which makes a text field appear (with a JS script).
The content of this text field is saved in my database under the column :taken_drugs
Here is the code I got until now :
<code>= form_for @quizz, :url => { :action => "create" } do |f|

h4 Which drugs did you take ?
h5 (You can answer more than one)
.field class="list-group"
  div class="list-group-item"
    = check_box("LSD", "yes")
    = label_tag 'LSD'
  div class="list-group-item"
    = check_box("Psilocybine", "yes")
    = label_tag 'Psilocybine (mushrooms)'
  div class="list-group-item"
    = check_box("DMT", "yes")
    = label_tag 'DMT (ayahuasca)'
  div class="list-group-item"
    = check_box("other", "other", {}, "yes", "no")
    = label_tag 'other'
    div id="disappear_consomme" style="display:none"
      p Which other drugs did you take ?
      = f.text_field :taken_drugs
    =f.submit
</code>
How can I have a result where I save to :taken_drugs the drugs that are checked AND the drugs that are added to the text field ?
Examples of what I need :

if the user check "LSD" and "DMT" I have "LSD DMT"
if the user check "LSD" and write "CANNABIS VALIUM" I have "LSD CANNABIS VALIUM"
Answer: You have two options, you can either catch this data in the front end with javascript or you can catch it in the back end with Ruby before it is posted to your database.
The js way:
<code>var text = "";
for (var i = 0; i < form.elements.length; i++ ) {
    if (form.elements[i].type == 'checkbox') {
        if (form.elements[i].checked == true) {
            text += form.elements[i].value + ' ';
        }
    }

}
</code>
Stick that in a function. Call it from your submit button with an onClick or onSubmit event handler.
The ruby way would be handled in your rails controller create method and parsing through whatever you are passing up in your params hash.

add checkbox content to text field


Qual a diferença entre Simple Factory, Factory Method, Abstract Factory?

Question: Quais são as principais diferenças entre esses padrões de projeto? Em qual situação um padrão pode ser melhor do que o outro?
Answer: Todos padrões costumam ser abusados. Só devem ser usados quando realmente é uma solução para um problema real.
Já vi fábricas sendo usadas onde não precisava, onde o código podia construir os objetos sem intermediários.
Simple Factory
É interessante quando você não sabe bem qual é o tipo do objeto que será usado. Normalmente uma classe de fábrica é criada para gerenciar isso. Nela teria um método que retorna o objeto do tipo correto de acordo com algum critério. Há casos que este método pode até ser estático e dispensar instanciar alguma coisa só para consumir a fábrica. Dá até mesmo para fazer sem uma classe. Claro que cada caso tem vantagem e desvantagem.
Há casos que um método estático é criado em uma classe, possivelmente abstrata, que é a base das classes que serão usadas para fabricar o objeto.
Uma forma comum é a seleção ser feita por um switch, recebendo uma string ou algo externo. Costuma ser um erro quando recebe uma enumeração. Se você sabe em tempo de desenvolvimento o que passar, então instancie logo o que precisa. Claro que tem casos legítimos para seu uso, por exemplo a enumeração ter sido gerada por um dado externo.
public class PizzaFactory {
    public Pizza CreatePizza(String sabor) {
        if (sabor == "Portuguesa")
            return new Portuguesa();
        if (sabor == "Calabreza")
            return new Calabreza();
        return null;
    }
    ...
}

Todos os sabores derivam de Pizza. Então onde precisa da Pizza chamaria assim:
PizzaFactory fabricaDePizza = new PizzaFactory()
Pizza pizza = fabricaDePizza.createPizza(textBoxPizza);

O texto pode vir de vários lugares, esse que coloquei é óbvio, mas provavelmente inadequado em aplicação real.
Há quem prefira fazer a classe estática, assim não precisa instanciar nada, só para criar o que realmente deseja.
Claro que isso tem um problema de manutenção. Se criar uma sabor novo tem que mexer na classe da fábrica para adicioná-lo. Isso não é o fim do mundo em grande parte das aplicações, mas é em algumas.
A solução é criar um mecanismo de registro das classes de sabores na classe de fábrica ou fazer reflexão em casos bem padronizados. O primeiro seria algo assim:
class static PizzaFactory {
    private Dictionary<string, Pizza> pizzas = new Dictionary<string, Pizza>();
    public static void registerPizza(String nome, Pizza pizza) => pizzas[nome] = pizza;
    public static Pizza createPizza(String nome) => pizzas[nome].createPizza();
}

Aí cada classe de sabor vai se registrar e ter uma forma de instanciar. A classe de fábrica não precisa conhecer cada um dos sabores.
class Portuguesa : Pizza {
    ...
    static Pizza() => PizzaFactory.registerPizza("Portuguesa", new Portuguesa());
    public override Pizza createPizza() => new Portuguesa();
    ...
}

Obviamente que este não é o código completo e mais robusto possível, mas no geral essa solução é adequada em vários casos.
Method Factory
Este padrão é usado para o caso que precisa construir instâncias de um jeito específico, fazer algo a mais que a construção normalmente faria, ou seja, você não precisa ter ciência de como consumir a construção do objeto de uma forma específica. Obviamente você pode ter várias linhas de fabricação diferentes para uma mesma classe, permitindo flexibilidade.
Isso é feito através de subclasse. Note que cada subclasse pode ter sua própria implementação, não interessa para o consumidor desse padrão qual é o objeto e como ele foi construído, ele só quer o resultado.
Assim como o padrão anterior É uma forma de poder ter a possibilidade de construção de objetos novos sem conhecer todos os existentes. Uma manutenção que crie um tipo novo pode ser consumido sem que qualquer parte do código a não ser o novo tipo seja escrito.
Note que a classe a ser fabricada também não precisa ter ciência que ela terá uma fábrica.
public abstract class PizzaFactory {
    protected abstract Pizza Make();
    public Pizza GetPizza() => this.Make(); //este é o método de fábrica
}

public class PortuguesaFactory : PizzaFactory {
    protected override Pizza Make() {
        Portuguesa pizza = new Portuguesa();
        pizza.GetHam();
        pizza.GetPea();
        pizza.GetOnion();
        pizza.GetEgg();
        return (Pizza)pizza;
    }
}

Desta forma pode chamar uma pizza que já faz pega os ingredientes específicos sem ter que se preocupar com isso. Em outro sabor os ingredientes são outros, mas não é problema seu, a fábrica de cada um sabe o que fazer, basta chamar o GetPizza() que vale para todos sabores. Algo assim:
PizzaFactory fabrica = new PortuguesaFactory();
Pizza pizza = fabrica.getPizza();

Há algumas versões diferentes de como é o jeito correto de fazer. É comum as pessoas alegarem que o jeito que elas gostam é o correto. Sinceramente eu não sei qual é o correto quando há tantas fontes. Esta é uma forma de implementar que funciona.
Abstract Factory
Essencialmente é uma fábrica de fábricas. Ele é usado quando temos uma matriz de itens que se relacionam e precisam de uma criação abstrata que atenda qualquer item. Ele permite criar diversas configurações com itens relacionados. Assim é possível montar novas opções de forma independente sem uma ter ciência da outra.
Neste exemplo mais complexo criamos sabores e tipos de pizzas diferentes:
public interface IPizzaIngredientFactory {
    public Massa createMassa();
    public Molho createMolho();
    public Queijo createQueijo();
    public Acessorios[] createAcessorios();
    public Carne createCarne();
}

public class PremiumPizzaIngredientFactory : IPizzaIngredientFactory {
    public Massa createMassa() => new MassaFinaCrocante();
    public Molho createMolho() => new MolhoTomateEspecial();
    public Queijo createQueijo() => new QueijoMussarela();

    public Acessorios[] createAcessorios() => new Acessorios { new MiniAzeitona(), new CebolaRoxa() };
    public Carne createCarne() => new CarneRalada();
}

public abstract class Pizza {
    public string Nome;
    protected IMassa Massa;
    protected IMolho Molho;
    protected IAcessorios[] Acessorios;
    protected IQueijo Queijo;
    protected ICarne Carne;
    public abstract void Prepare();
}

public class Calabreza : Pizza {
    IPizzaIngredientFactory ingredientFactory;
    public CheesePizza(IPizzaIngredientFactory ingredientFactory) ingredientFactory = ingredientFactory;
    public override void Prepare() {
        Massa = ingredientFactory.CreateMassa();
        Molho = ingredientFactory.CreateMolho();
        Queijo = ingredientFactory.CreateQueijo();
        Carne = ingredientFactory.CreateCarne();
    }
}

public class PremiumPizza {
    protected override Pizza CreatePizza(string sabor) {
        Pizza pizza;
        IPizzaIngredientFactory ingredientFactory = new PremiumPizzaIngredientFactory();
        switch (sabor) {
        case "Portuguesa":
            pizza = new Portuguesa(ingredientFactory);
            pizza.Nome = "Pizza Premium Portuguesa";
            break;
        case "Calabreza":
            pizza = new Calabreza(ingredientFactory);
            pizza.Nome = "Pizza Premium Calabreza";
            break;
        }
        return pizza;
    }
}

Coloquei no GitHub para referência futura.
Comment: Quando a pessoa não entende onde é para aplicar, provavelmente significa que não é p/ aplicar. É a necessidade que deve fazer a procura pelo padrão, não o padrão procurar uma necessidade.
Comment: obrigado pela resposta. eu entendi o Simple Factory mas não consegui entender os outros dois, talvez porque tenha código faltando. Mas a minha dúvida era em saber mais quando um é apropriado do que o outro. Quando eu to programando eu tento isolar as instancias de objeto, criando factories, mas sempre faço a simple factory porque eu não consigo entender a motivação da factory method e abstract factory... então a minha dúvida era mais sobre as diferentes motivações do que como que as coda
Comment: Posso tentar melhorar, mas coloquei esses exemplos até para entender na prática quando é usado. De fato o último é mais difíceis de entender, o Method Factory é bem simples também, vou tentar por algo mais, mas é aquilo que está escrito, usa-se quando precisa construir o objeto de um jeito específico e não quer ficar repetindo todo código toda vez que deseja criá-lo. Talvez seja difícil entender porque ele é simples demais e todo mundo espera algo complicado. O Simple Factory é o mais fácil de usar, mas também o mais mal usado.
Comment: Eu partilho de uma opinião diferente. Eu acho que é aceitável a pessoa não entender onde é para aplicar um padrão porque eles são complexos e exigem um domínio profundo da orientação a objetos que demora a se adquirir. Então, a situação pode estar lá, mas ele não sabe que se pode aplicar um padrão naquela situação porque ele não domina o padrão ou a linguagem. Na minha visão, não é sempre que é aplicado um padrão quando lhe é conveniente. Mas, de qualquer maneira, é muito bom que tenhamos opiniões diferentes porque isso enriquece o fórum e incita nos outros leitores o pensamento e a crítica.
Answer:
Esta resposta é uma junção dos artigos do Vinícius Thiengo sobre Simple Factory, Factory Method e Abstract Factory.

De forma geral todos os padrões Factory (Simple Factory, Factory Method, Abstract Factory) encapsulam a criação de objetos.
Simple Factory
Simple Factory permite interfaces para criar objetos sem expor a criação lógica para o cliente.
O Simple Factory é um bom ponto de início para separar a criação de objetos do seu uso, poucas classes são criadas e a estrutura do padrão é bem simples. Se o seu contexto permite isolar a maneira como objetos são criados e você tiver que lidar apenas com um tipo de objeto, o Simple Factory é uma excelente maneira de resolver o problema.
Apesar de simples, existem situações onde utilizar o padrão Simple Factory não ajuda muito. Um sinal bem claro de que o padrão não está sendo efetivo é quando a classe fábrica começa a crescer e ter vários métodos para criar os mesmos produtos de maneiras diferentes. Essa talvez seja uma boa hora para aplicar outros padrões fábrica.
Factory Method
Factory Method define uma interface para criar um objeto, mas deixa que subclasses decidam que classe instanciar.
Factory Method pode ser usado quando uma classe não pode antecipar a classe de objetos que criam ou quando a classe quer que suas subclasses especifiquem os objetos que criam. Pode ser utilizado também quando as classes delegam responsabilidade para uma dentre várias subclasses auxiliares, e você quer localizar o conhecimento de qual subclasse auxiliar que é a delegada.
Abstract Factory
Abstract Factory provê interface para criar famílias de objetos relacionados ou dependentes sem especificar suas classes concretas.
O Abstract Factory pode ser utilizado quando um sistema deve ser independente de como seus produtos são criados, compostos ou representados e o sistema deve ser configurado como um produto de uma família de múltiplos produtos. Pode ser utilizado também quando uma família de objetos for projetada para ser usada em conjunto, e você necessita garantir esta restrição e quando você quer fornecer uma biblioteca de classes e quer revelar somente suas interfaces, não suas implementações.
Vale lembrar que não há uma versão melhor do Factory, cada uma se encaixa de maneira mais otimizada em problemas específicos de projeto de software. E isso vale para qualquer padrão de projeto.

Referências:

Simple Factory
Factory Method
Abstract Factory


prove that |A| = $\aleph _0 $ for a set A which meets the following conditions:

Question: given a set $A \subseteq \mathbb{R}$ which follows:
1) $\mathbb{N} \subseteq A$
2) $\forall x \in A \ \forall n \in \mathbb{N} \exists y\in A \ : y^n = +x \ or \ y^n = -x $
3)if a set $A'$ follows the conditions 1 and 2 than $A \subseteq A' $
show that $|A| = \aleph _0$.

thanks ahead.
Comment: Was $A'\subseteq A$ a typo for $A\subseteq A'$? All three of your conditions are satisfied if $A=\mathbb R$ but $|\mathbb R|\ne\aleph_0.$
Comment: Condition 2 is vacuous.  For x in A, take y = x, n = 1.
Comment: For 3, is the set A' a subset of R?   The only set that has 1,2, 3 is R.  The symbol i is the sqrt of -1.  The word I is pronoun for a person;  use it.
Comment: yes of course i changed it , thanks
Answer: Let $${\Bbb N}^{\frac{1}{k}} = \{ l^\frac{1}{k} \;|\; l \in \Bbb N\}$$ be the set of all k-th roots from the naturals which is obviously countable for all $k\in \Bbb N$ and $$A' = \bigcup_{k\in \Bbb N} {\Bbb N}^{\frac{1}{k}}$$ be the union of all those sets which is countable as a countable union of countable sets.
Then $A'$ fulfills 1.) and 2.) by definition because 1.) is clear by construction and for $x \in A'$ it has to hold $x\in {\Bbb N}^{\frac{1}{k}}$ for some $k$ hence $$x=l^\frac{1}{k}$$ for some $l,k \in \Bbb N$. Taking $$y = l^\frac{1}{kn} \in {\Bbb N}^{\frac{1}{kn}} \subseteq A'$$ gives us $$y^n = l^\frac{n}{kn} = l^\frac{1}{k} = x$$ as wanted.
Hence $A'$ fulfills 1.) & 2.) and is countable so we get as a result $$\Bbb N \subseteq A \subseteq A'$$ and $A$ is sandwiched by countable sets so it's countable itself.


How can I limit the login times in linux for certain users?

Question: How can I limit the login times in linux for certain users? For example I have to a user that only needs to be enabled from 8am till 5pm? Is there a way of automating this. My environment is a Centos server administered via webmin.
Answer: You need to configure one of the PAM subsystem's modules, called "pam_time". It's pretty simple to do by hand, just by editing the text file that controls the module's behavior. I don't know about webmin, specifically—there may be webmin interface option for this, already.
In short, you'll edit the file '/etc/security/time.conf' and add some configuration options that describe what user you want to restrict, and exactly when you want him to be restricted. Since this is a security-related system file, you'll need root privileges in order to make the edit.
Here's an example of the text you'd add to that file, on a set of new lines (quoted directly from the example in the tutorial I link to, below):
<code>login ; * ; !bobby ; MoTuWeThFr0800-2000
login ; * ; !root ; !Al0000-2400
http ; * ; !bobby ; MoTuWeThFr0800-2000
http ; * ; !root; !Al0000-2400
</code>
"These rules restrict user bobby from logging on between the hours of 0800 and 2000, and they also restrict Internet access during these hours. Root would be able to logon at any time and browse the Internet during all times as well."
The complete pam_time documentation is here, and it explains the rest of the possible config options and controls:

http://www.linux-pam.org/Linux-PAM-html/sag-pam_time.html

and there is an easy-to-follow tutorial, here, with step by step instructions, where I found the example I quoted, above:

http://blogs.techrepublic.com/security/?p=319
Comment: Seems that you also have to edit the files in `/etc/pam.d/`. See the answer on https://ask.fedoraproject.org/en/question/7260/how-to-configure-user-restriction-with-pam-a-kind-of-parental-control/?answer=104977#post-id-104977
Comment: Updated, archive link of comment above: [askbot.fedoraproject.org](https://askbot.fedoraproject.org/en/question/7260/how-to-configure-user-restriction-with-pam-a-kind-of-parental-control/)
Comment: the updated, archive link from Sep 26 '19 doesn't work - how to update /etc/pam.d/ ?


Como eu crio uma estrutura CRUD com PHP

Question: Quero criar uma comunicação CRUD em PHP, levando informações do painel administrativo para a página principal.
Como um blog, porém, com todos os códigos editáveis.
Comment: Se você ainda precisa aprender tudo o que disse na [sua outra pergunta](http://pt.stackoverflow.com/questions/46430/gostaria-de-uma-apostila-sobre-php-completa-para-criar-um-site-de-compras), as explicações aqui teriam de ser longas demais para o formato deste site. Sugiro que escolha um ponto de partida (dê uma olhada no [Wordpress](http://br.forums.wordpress.org)), e volte aqui com dúvidas mais pontuais.
Comment: Você viu o link que coloquei com a documentação do WordPress? E por favor não use a área de respostas mais abaixo para responder aos comentários aqui. Use o link de adicionar comentário.  Obrigado.
Comment: Deixa eu ver se entendi, você quer criar um blog simples em PHP aonde as informações do blog (como postagens e comentários) estão em um banco de dados. É isso?
Comment: Meu site: www.jaguaribeparacristo.com.br
Comment: Eu aderi a uma template interessante, porem não estou encontrando onde edito estas informações. As informações que edito no painel não são capazes de alterar algumas coisas, talvez, tem que ser alterado no html central.
Comment: Sim, Victtor.
É está estrutura que queria. Se tive-se alguma pronta, para eu ter uma noção e começar a desenvolver.
Answer: Você já ouviu falar sobre Static Site Generator?
"Falando de forma resumida, geradores estáticos usam várias funcionalidades que estamos acostumados a utilizar nas linguagens de programação, como includes, loopings, templates, entre outras coisas legais. Mas... gera um HTML, sem banco de dados, sem dependências server-side, tudo é gerado em um HTML puro e simples."
Fonte: felipefialho
Eles são perfeitos para construção de blogs ou semelhantes. Eu uso o Jekyll pra gerenciar meu blog. Mas ele é feito em Ruby, já que você usa PHP eu recomendo o Sculpin. É muito simples de usar. Olha a documentação. Em menos de 3 minutos você tem seu conteúdo publicado na web!

Como eu crio uma estrutura CRUD com PHP


Are these two definitions of cofibration the same?

Question: $\newcommand{\cgh}{\mathsf{CGHaus}}$I'm reading through Goerss/Jardine's simplicial homotopy theory, and came across the word 'cofibration' for the first time. I tried to do some reading from other sources, but Goerss/Jardine seem to be using an ostensibly 'different' notion of cofibration to the rest of the world. I use notation standard to simplicial sets throughout.
I'll be specific now. Let $\cgh$ be the category of compactly generated Hausdorff spaces. The authors were discussing the 'closed model structure' of $\cgh$, wherein a fibration is defined to be a Serre fibration:

A (Serre) fibration is a map $f\in\cgh(U,V)$ such that for all integer $n>0$ and all $0\le k\le n$, $f$ has the right lifting property against the inclusion $|\Lambda^n_k|\hookrightarrow|\Delta^n|$.

I'm fairly sure this definition is equivalent to the (seemingly) more standard definition of the same in terms of lifting against $|\Delta^n|\hookrightarrow|\Delta^n|\times|\Delta^1|$.
They define:

A cofibration $i\in\cgh(U,V)$ is a map that has the left lifting property against all trivial fibrations.

A 'trivial' fibration is a fibration that is also a weak homotopy equivalence. This definition seems very removed from the definitions of the same on nLab: I could hardly even parse those!
My first question:

Is the Goerss-Jardine definition equivalent to the standard meaning of cofibration (whatever that is?)?

On another note, they proved (for simplicial fibrations) that a map is a trivial fibration iff. it has the right lifting property against all inclusions $\partial\Delta^n\hookrightarrow\Delta^n,n\ge0$. According to nLab, this holds in the topological world - a map is a Serre fibration iff. it has the lifting property against the inclusions $S^{n-1}\hookrightarrow D^n,n\ge0$.

Is there a similar characterisation of the trivial cofibrations? (in either the 'standard' sense or in the sense of Goerss-Jardine?)
Comment: Are you familiar with model categories generally?
Comment: @Randall No, my first encounter with them has been this page of Goerss-Jardine
Answer: The answer to your question is yes.
The general setup is as follows: in order to do homotopy theory, the basic framework is a model category (and we can focus on the two examples of simplicial sets and an appropriate category of topological spaces, like $\mathsf{CGHaus}$). To define a model category, we need three classes of maps:

cofibrations (which you can think of as "nice inclusions")
fibrations ("nice surjections")
weak equivalences

As you say, the "trivial fibrations" are the maps that are both fibrations and weak equivalences, and similarly for the trivial cofibrations.
The weak equivalences are the maps we want to invert, and we typically know those ahead of time: they are weak homotopy equivalences in our two examples. However we define the other two, we need the cofibrations to have the left lifting property with respect to trivial fibrations, and we need the fibrations to have the right lifting property with respect to trivial cofibrations.
Of the other two, sometimes it's easier to define cofibrations, sometimes fibrations. For simplicial sets, it is easiest to define cofibrations — they're just inclusions. For topological spaces, it is easiest to first define some maps that you want to be trivial cofibrations (the inclusions  $i_0: D^n \to D^n \times I$) and then define the fibrations in terms of a lifting property with respect to those, and then define the cofibrations in terms of a lifting property with respect to the trivial fibrations. You can choose different families for these "generating cofibrations," and the ones that Goerss and Jardine use are just as good as $D^n \to D^n \times I$. With some work, you can then say that certain families of maps, like the inclusions of subcomplexes into CW complexes, are cofibrations. I don't know how easy it is to give a self-contained description of all cofibrations, though. (By "self-contained," I mean without reference to the fibrations.)
(To make the "generating cofibration" approach work, you should also define some maps that you know that you want to be cofibrations. A good choice is the family $S^{n-1} \to D^n$, also known as $|\partial \Delta^n| \to |\Delta^n|$. See Lemma 9.4 in Goerss-Jardine, for example.)
Comment: And must we define fibrations and cofibrations relative to each other in this way because of abstract nonsense involving model categories (i.e. that is the convenient, 'correct' way)?
Comment: You don't have to define them this way, but it tends to be really awkward to define each class of morphisms separately. For simplicial sets, the cofibrations are the inclusions, and that's fine, but it's hard to give a nice description of the fibrations. For topological spaces, the Hurewicz fibrations are not so hard to describe, but it's hard to give a nice description of the complete class of cofibrations.
Comment: Right, thanks. Does it then follow from the lifting definition that the trivial cofibrations of Kan complexes are precisely the anodyne extensions (between Kan complexes)?
Comment: It seems that way, given the proof on p. 68: any trivial cofibration $i$ seems to be a retract of an anodyne extension, and hence is anodyne itself. The nLab people say (https://ncatlab.org/nlab/show/anodyne+morphism) that when the small object argument applies (and it does in simplicial sets), then the anodyne morphisms are those with the left lifting property with respect to all fibrations, and hence they are the trivial cofibrations.
Comment: Sorry to bother you again. Do you know how to show Goerss-Jardine's definition of Serre fibration is equivalent to the usual one (right lifting property against inclusions $I^n\times\{0\}\hookrightarrow I^n\times I$)? The usual way to prove such things is via taking suitable coproducts and pushouts, CW-complex style, but it's not obvious to me how to build a horn in this way (or visa versa)
Comment: One approach is that of "cofibrantly generated model categories," which is what my post starts to describe. That should provide the structure to verify that the various definitions match up, although it may be difficult to work out all of the details. Hovey's book "Model Categories" is one resource.


Problema com Bootstrap Modal

Question: Olá!
Meu problema é o seguinte:

Esse é botão que chama o Modal Bootstrap:
<button class="btn btn-default details" data-id="@item.nome"></button>

Essa é a página Modal Bootstrap;

        <button type="button" class="close" data-dismiss="modal">×Close</button>

Visitado em:

@Html.DisplayName("Nome")

@Html.DisplayName("Data")

@Html.DisplayName("Relatório")

@Html.DisplayName("Cod Visita")

        @foreach (var item in Model)
        {

@Html.DisplayFor(modelItem => item.nome)

@Html.DisplayFor(modelItem => item.Fecha)

@Html.DisplayFor(modelItem => item.Relatorio)

@Html.DisplayFor(modelItem => item.id_visita)

        }

        <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>

Esse é meu controlador;
 DB_A3B4A6_estrangeirosEntities db2 = new DB_A3B4A6_estrangeirosEntities();
    public ActionResult IndexVisitas(string searchString)
    {
        var estrangeiros = from e in db2.Vw_RegistroVisita select e;
        if (!String.IsNullOrEmpty(searchString))
        {
            estrangeiros = estrangeiros.Where(s => s.nome.Contains(searchString));
        }

        return View(estrangeiros.ToList());
        //return View(db2.Vw_RegistroVisita.ToList());
    }

Peço desculpas se não ficou muito claro ou se faltou mais informação. Sou novato em programação.
Preciso fazer funcionar usando a variável.
Answer: Primeiro voce deveria testar se o valor esta vindo correto no $(this).attr("data-id"), voce tambem pode testar $(this).data("id") caso seu jQuery seja maior que a versao 1.4.3
caso nao funcione confirar o valor que esta vindo nessa parte data-id="@item.nome"
Comment: É isso mesmo, alterei para $(this).data("id") . Obrigado!
Comment: @DPWSReceptivo nao esquece de marca como respondido :)
Comment: Onde marca "Respondido"?
Comment: no lado esquerdo da resposta, abaixo dos pontos tem uma imagem de checkin, so clikar nela :)

Problema com Bootstrap Modal


How can we just apply the updates to a single module using composer without apply patches for other modules?

Question: We have the following composer.json file. When we want to update a module such as  Environment Indicator, we run the suggested composer command composer require drupal/environment_indicator:^3.7'.
In doing so it also applies the patches for core and other modules because the patches is defined in our composer.json file.
What we tried this as well but it had the same results.
composer update drupal/environment_indicator --with-dependencies
composer.json
{
    "name": "drupal/drupal",
    "description": "Drupal is an open source content management platform powering millions of websites and applications.",
    "type": "project",
    "license": "GPL-2.0-or-later",
    "require": {
        "composer/installers": "^1.0.24",
        "drupal/core" : "^8.6",
        "wikimedia/composer-merge-plugin": "^1.4"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "preferred-install": "dist",
        "autoloader-suffix": "Drupal8"
    },
    "extra": {
        "_readme": [
            "By default Drupal loads the autoloader from ./vendor/autoload.php.",
            "To change the autoloader you can edit ./autoload.php.",
            "This file specifies the packages.drupal.org repository.",
            "You can read more about this composer repository at:",
            "https://www.drupal.org/node/2718229"
        ],
        "merge-plugin": {
            "include": [
                "core/composer.json"
            ],
            "recurse": true,
            "replace": false,
            "merge-extra": false
        },
        "installer-paths": {
            "core": ["type:drupal-core"],
            "modules/contrib/{$name}": ["type:drupal-module"],
            "profiles/contrib/{$name}": ["type:drupal-profile"],
            "themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/contrib/{$name}": ["type:drupal-drush"],
            "modules/custom/{$name}": ["type:drupal-custom-module"],
            "themes/custom/{$name}": ["type:drupal-custom-theme"]
        },
        "enable-patching": true,
        "patches" : {
            "drupal/core": {
               "issuenumber1" : "path/to/patch.patch",
             },
            "drupal/eck": {
               "issuenumber2" : "path/to/patch.patch",
             },
        }
    },
}

Answer: Unfortunately, composer is always going to apply any patches you have defined that are not already applied whenever it runs. You can comment out the patches, run your composer command, and then uncomment them.
Comment: What is the point of commenting out patches and putting it back, though? I am not sure if this is the full picture of the question, because I can require a new module just fine without any previously applied patches being applied again.
Comment: I mean, what is the point of having patches defined in composer but not wanting them applied? He asked how to do it, they way I suggested would work.
Comment: @IsaiahNixon It sounds like you are saying there is not way to do it without commenting out? I did think about doing that, but that did not seem like a sustainable way to do it since the goal is to apply a patch for a single module when that module is updated, rather than apply to all modules.
Comment: @usernameabc From what I can tell, composer will always make sure the patches defined in your `composer.json` are applied every time you run an install or update. If you do not want certain patches applied, you need to remove them (or comment them out) from your `composer.json`. Out of curiosity, why do you have patches defined that you do not want applied?


Eigenvalue of linear operator iff eigenvalue of matrix representation.

Question: I'm trying to prove the following theorem, which seems straightforward enough, but I'm confused about the wording and proving the converse:
Let T be a linear operator on a finite-dimensional vector space V, and let B be an ordered basis for V.  Prove that t is an eigenvalue of T iff t is an eigenvalue of the matrix representation of $T_B$.  (Sorry; I don't know how to make the subscript of B with [T].)
Here's my confusion:  don't we have to have that V is a vector space consisting of column vectors in order for us to even speak of eigenvalues and eigenvectors of matrices?  This isn't specified in the theorem.
Moreover, even if this were specified, I'm not sure how to get from the matrix multiplication form back to the linear operator form with my proof.  Any suggestions?
Comment: I still have not received an adequate (to my mind) answer to my questions.  Does anybody have any suggestions?
Answer: There is no need to have column vectors or the such. Basically, what it's asking is the following: if you have an abstract vector space $V$ and a linear transformation $T:V\to V$ you can fix a basis $B$ of $V$. This basis allows you to form an isomorphism $V\cong F^n$, and under this isomorphism $T$ becomes a new linear transformation, in matrix form if you like. It's asking you to show that $T$ has the eigenvalue $\lambda$ (there exists a non-trivial solution to $T-\lambda\text{id}$ if and only if the transformed matrix transformation has that same eigenvalue.
My hint goes as follows: any two matrix realizations of the same linear transformation are just conjugates (they are similar) to one another. Since it's clear that having the eigenvalue $\lambda$ is invariant under similarity, that it suffices to prove this for a single basis $B$. There is a pretty obvious one that should make this easy (consider a basis containing $x$ where $x$ is an eigenvector for $\lambda$).
Comment: @JohnDaley It means that if it is an eigenvalue of $A$, it is also an eigenvalue of $CAC^{-1}$ for some $C$ invertible. Note that $$CAC^{-1}-\lambda I=CAC^{-1}-\lambda CIC^{-1}=C(A-\lambda I)C^{-1}$$ and invertibility takes the wheels.
Comment: I'm still not sure I understand why we don't need to specify in the theorem that the vectors are being changed to column vectors.  As for the proof: I don't see that there is necessarily a basis consisting of eigenvectors, if that's what you mean.  Don't we first have to guarantee that?
Answer: if $\lambda$ is an eigenvalue of $T:V\to V, \exists v\not=0,v\in V,$ so $\phi_\beta(v)=[v]_\beta\not= 0.$
Now since $T(v)=\lambda v\iff [T(v)]_\beta=[\lambda v]_\beta\iff[T]_\beta[v]_\beta=\lambda[v]_\beta,$ then we got it: $\lambda$ is an eigenvalue of $[T]_\beta,$ where $\beta$ can be any ordered basis of $T$.
Answer: Suppose that $\lambda$ is an eigenvalue for $T$. This means that there exists nonzero $v\in V$ with $Tv=\lambda v$. We can write this as $(T-\lambda\,I)v=0$. If we write $B=\{b_1,\ldots,b_n\}$, we can express $v$ as $v=\sum_jv_jb_j$ for certain scalars $\{v_j\}$, with at least one of them nonzero. So
$$
0=(T-\lambda\,I)v=\sum_j v_j\,(T-\lambda\,I)b_j=\sum_j\sum_kv_j\,[(T-\lambda\,I)_B]_{kj}b_k=\sum_k\left(\sum_jv_j\,[(T-\lambda\,I)_B]_{kj}\right)b_k.
$$
As the $b_k$ are a basis, we get
$$
\sum_j\,[(T-\lambda\,I)_B]_{jk}\,v_j=0
$$
for all $k$. This is exactly the equation $(T-\lambda\,I)_B\,v'=0$, where $v'$ is the column vector with entries $v_1,\ldots,v_n$. As $v'$ has at least one nonzero entry, this implies that $(T-\lambda\,I)$ is not invertible (if it were, we would be able to deduce $v'=0$ by multiplying by its inverse on the left), so $\det(T-\lambda\,I)=0$. That is, $\lambda$ is an eigenvalue of $T_B$ (after the easy fact that $(T-\lambda\,I)_B=T_B-\lambda\,I_B$).
If you think about it, all the steps we did are reversible, so they can be used to prove the converse (i.e. if you start with an eigenvalue $\lambda$  of the  matrix, you can use the ideas above to produce an eigenvector for $T$ in $V$ with that eigenvalue $\lambda$).


Is Changepoint Detection valid if the process is not piecewise stationary?

Question: I have seen these two definitions:

Let us consider a multivariate non-stationary random process
$y=\left\{y_1, \ldots, y_T\right\}$ that takes value in
$\mathbb{R}^d(d \geq 1)$ and has $T$ samples. The signal $y$ is
assumed to be piecewise stationary, meaning that some characteristics
of the process change abruptly at some unknown instants
$t_1^*<t_2^*<\cdots<t_{K^*}^*$. Change point detection consists in
estimating the indexes $t_k^*$. Depending on the context, the number
$K^*$ of changes may or may not be known, in which case it has to be
estimated too.

source

1 Change point detection
A particular change point test seeks to
identify the specific period of time that relates to a change in the
probability distribution of a stochastic process or time series. In
general, the problem concerns both detecting whether or not a change
has occurred, or whether several changes might have occurred, and
identifying the times of any such changes.
To establish a relatively general framework for the detection of a
change point, we can assume that we have an ordered sequence of data,
$y_t=\{y_1, \ldots, y_T\}$. A change point is then said to
arise within this dataset when there exists a time, $\tau \in\{1, \ldots, T-1\}$, such that the statistical properties of $\{y_1, \ldots, y_\tau\}$ and $\{y_{\tau+1}, \ldots, y_T\}$
are different in some way. Extending this idea for a single change
point to multiple changes, we can allow for $m$ change points, that
are associated with positions, $\tau_{1: m}=\{\tau_1, \ldots, \tau_m\}$. Each change point position is then ordered so that
$\tau_i<\tau_j$ if, and only if, $i<j$. Consequently the $m$ change
points will split the data into $m+1$ segments, where the $i$ th
segment may be summarised by a set of parameters. The parameters
associated with the $i$ th segment will be denoted $\{\theta_i, \phi_i\}$, where $\phi_i$ is a possible set of nuisance
parameters and $\theta_i$ is the set of parameters that may describe
the change. In this case, we typically want to test how many segments
are needed to provide the best representation of the data generating
process.

They also discuss tests for finding changes in mean and/or variance.
source
So the 1st definition specifically states the signal is assumed to be piecewise stationary. The 2nd one does not, but it does say changepoint detection algorithms have been developed to look for changes in the mean,variance, etc.
But  a weakly stationary process has a constant mean and variance, so it seems like that definition also implicitly assumes it will split it into a piecewise stationary process.
I have also tried some changepoint detection on a time series and each segment was still nonstationary (under the ADF test).
Is Changepoint Detection valid if the process is not piecewise stationary?
Also if you had another form of nonstationarity(such as unit roots or deterministic trends), and then a structural break/changepoint, how would you deal with that?
Answer: Generally for changepoint detection the null case is there is no change in the quantity of interest (e.g. mean or variance) and the alternative case is the quantity of interest is piecewise constant. If you run a changepoint detection method which assumes a piecewise constant mean on something that is not piecewise constant you will likely detect many spurious changepoints.
There are some methods which relax this assumption and assume piecewise linear (Bardwell et al. 2019) or piecewise smooth (Wu and Zhou 2023) for the mean function. This is sometimes referred to as jump detection.


SMTP login only works via AUTH PLAIN

Question: This is my first time using telnet; I'm using it to debug PHPMailer. Here's what I get when logged in:
EHLO localserver.com
250-mx.zohomail.com Hello localserver.com (18.104.22.168 (188.8.131.52))
250-AUTH LOGIN PLAIN
250 SIZE 53477376

Following this tutorial, I try logging in via AUTH LOGIN.
When I give my password, it fails.
However, if I AUTH PLAIN, it works.
PHPMailer (I'm using the basic template provided at their git page with debugging set to 4) debugging shows me that they are using AUTH LOGIN.
So it seems that there are two ways to solve my problem.
-figure out why AUTH LOGIN doesn't work
-figure out how to get PHPMailer to use AUTH PLAIN.
Thanks
Answer: You can set the authentication type with the AuthType property. Just set it to PLAIN.
You don't need to use SMTPDebug = 4; 2 should be enough for this.
Comment: For those total newbs like myself, it goes like this: $mail->AuthType = 'PLAIN';
Comment: I messed around with this; being an amateur, I added $->authtype=PLAIN; (below $mail ->Host), which did nothing. I had a hard time finding examples via google, too. Thanks for the debug tip (4 helped me realize that the problem might be authtype; 3 didn't show enough info for that).
Comment: PHP is case sensitive for vars and property names. Use *exactly* what I said and it should work. It's all in the docs too.

SMTP login only works via AUTH PLAIN


different output with compilers?

Question: I was solving a programming problem on a site. On my machine (Visual Studio 2010) a test case gives wrong result, while gives correct result on the site. I am not sure what is the compiler of the site's judge, but I think it is something like gcc or cygwin.
THE CODE
A graph problem. The graph here is represnted as a tree. The graph is directed, and doesn't contain loops. The solution is (2 * sum of all edges - max path length from root)
//     to-vertex & edge-length
vector<pair<int, int> > pr[100];
int dfs(int i) // to find max path length from root
{
    int mx = 0;
    for (int j = 0; j < pr[i].size(); ++j)
        mx = max(mx, dfs(pr[i][j].first) + pr[i][j].second);
    return mx;
}

int PowerOutage::estimateTimeOut(vector <int> from_vertex,
                 vector <int> to_vertex, vector <int> edge_length)
{
    int tot = 0;
    for (int i = 0; i < from_vertex.size(); ++i)
    {
        pr[from_vertex[i]].push_back(make_pair(to_vertex[i], edge_length[i]));
        tot += (2 * edge_length[i]);
    }
    return tot - dfs(0);
}

THE TEST CASE
from_vertex   {0,     0,   0,   0,   0}
to_vertex     {1,     2,   3,   4,   5}
edge_length   {100, 200, 300, 400, 500}

Visual Studio returns: 2493, While the site's compiler returns the correct answer: 2500.
Why the two results are different? I think there is some hidden bug (in my code) that appears in VS giving wrong answer but disapper in the other compiler. Should I determine the site's compiler and use it instead?
Comment: @BenjaminLindley I have removed this macro
Comment: What is your fpu option selected? Precise, fast, strict?
Comment: @tuğrulbüyükışık Sorry, what do you mean by "fpu option" ?
Comment: *"Should I determine the site's compiler and use it instead?"* -- Definitely not.  You should determine the problem with the code.
Comment: I meant what i gave in the answer below
Comment: VS2010 produces the result of 2500 here regardless of optimization/fpu settings. However, we can't see your `main()` or an [SSCCE](http://meta.stackexchange.com/questions/22754/sscce-how-to-provide-examples-for-programming-questions)...
Answer: Despite my first(wrong) assumption, OP has found out that it was 2500 already but the test-function had the flaw after i asked him "where is 2500 printed?".
Comment: How can you know rest of the program? Where is main() ?
Comment: Thaks. I didn't change anything of "fpu", since I have learned what is it only now.
Comment: How are you printing 2500 ?. Did changing the fpu option worked?
Comment: @tuğrulbüyükışık Your last comment was the answer !! :) :) The function was returning 2500 in fact. The wrong was in testing code. I'm trying to know what was the wrong this it
Comment: @tuğrulbüyükışık How mush stupidness !! The wrong was that when the test cases are consecutive `pr` is not `clear()`ed from previous results!!
Comment: @Desolator: Do you mean the void test_case_4() part?

different output with compilers?


Could someone explain the 'hit' and 'miss' status in memcache per page output?

Question: I've instructed memcache to append stats to each page. Someone did an excellent job explaining the memcache reporting page. However, I've since stumbled upon this appended information shown below and am curious.
Specifically what are miss and hit status?
(enlarge picture)
Answer: The hit/miss statuses are the result of the cache being touched as the result of the operation. For the given operations:

Get: (for a single key) Hit: data was retrieved from the cache; Miss: data was found not in the cache.
Set: Hit: data was stored in the cache; Miss: data was not stored in the cache.
GetMulti: (for multiple keys) Hit: data was retrieved in the cache; Miss: data was found  not in the cache.
Delete: Hit: data was removed from the cache; Miss: data was not removed (for a missing key) in the cache.
Comment: So hits > miss is good.
Comment: For gets, yes, you want the hit/miss ratio to be as high as possible.


Finding the dimensions of a hexagon inscribed by a circle

Question: I have a large backyard tree around which I want to build a regular hexagonal picnic table.
The tree trunk circumference is 96 inches. How can I figure out the minimum dimensions of the center hexagonal hole for the trunk?
Mathematically, this is asking the dimensions of a hexagonal polygon when inscribed by a circle of given circumference.
Answer:
If the radius of the inscribed circle is $r$ then the circumference is $c=2\pi r$ while a side of the hexagon is $s=\frac2{\sqrt{3}}r$ so $$s=\frac1{\sqrt{3}\pi}c$$  and with $c=96$ you would get $s \approx 17.643$ while $r \approx 15.279$.
$s$ is also the radius of the circumscribing circle.
The hexagon has circumference $6s \approx 105.86$
Answer: The diameter of the tree circle is $\frac{96}{\pi}$ and the radius is half this. Then the radius of the outer circle circumscribing the hexagon is $$\frac{48}{\pi}\times \sec 30=\frac{96}{\pi\sqrt{3}}$$
This is the same as the side of the required hexagon.


How to prove the absorption law in a lattice?

Question: It is easy to prove the absorption law in a lattice by taking particular example. Let $(A, \mid)$ be a lattice where $A=\{2, 4, 8\}$. Then $2\wedge(2\vee 4)=2\wedge\sup\{2, 4\}=2\wedge 4=\inf\{2, 4\}=2$. Similarly,  $2\vee(2\wedge 4)=2$ holds. But instead of taking $2$ and $4$, if we take any pair of elements $a$ and $b$ in lattice $L$ then how do we prove that

$a\wedge(a\vee b)=a$ and
$a\vee(a\wedge b)=a$ ?
Answer: Assuming you're using the poset definition of lattice . . .

Let $c = a \land (a \lor b)$.

The goal is to show $c=a$.

From $c = a \land (a \lor b)$, it's immediate that $c \le a$.

But also, $a \le a$, and $a \le a\lor b$, hence $a \le c$.

Therefore $c = a$.

An analogous argument proves the other absorption law.

You try it.
Comment: @gete The best way to thank a useful answer is not to say thanks (nothing wrong with that), but to mark it as the accepted answer (and maybe also to upvote it).
Comment: Thank you.  It really works.
Answer: $a\vee (a\wedge b) \\ = (a\wedge T) \vee (a \wedge b) \\= a \wedge (T \vee b) \\= a \wedge T \\= a$
Note : in the third line i used the inverse of distributive law
Comment: A lattice does not have the distributive law, unless it is a distributive lattice (which OP did not specify), I think.


How to implement Back Button in Android

Question: Am working on an app where previously I have disabled all the back button of my app but now I need to enable the back buttons of my app. When I click on the back button it should go to the previously visited activity.
If any one know the right implementation let me know.
Comment: override onbackpressed method in activity and pass your intent.
Comment: Use onBackPressed() method in activity and pass intent of the activity you want to go.
Comment: Just call super.onBackPressed() in your implemented onBackPressed. It will take the user to the previously visited activity.
Answer: Simply override onBackPressed method in your activity.
@Override
public void onBackPressed() {
      super.onBackPressed();  //Takes you to the previous activity by default
}

Answer: You don't need to do anything specific to handle the back button press. Actually, if you are opening the activities in a standard way (here you have an example: How to start new activity on button click), you just have to remove your methods implementing onBackPressed (http://developer.android.com/intl/es/reference/android/app/Activity.html#onBackPressed())
This way Android will handle the stack of Activities for you, closing the current one and going back to the previous one, until you leave the app (that would happen if you press back in the 1st activity: for that specific case you might want to have a confirmation dialog shown, in the onBackPressed method).
Answer: If you have manually overridden the back button in every Activity, then you must go to every activity and remove your manual override from there.
A better approach is to create your own Activity which has the back button overridden. Then you can extend this Activity throughout your application. And if you later need to enable/disable onBackPressed(), you just have to change it in your custom Activity and it would get reflected everywhere.

How to implement Back Button in Android


Magento - Import pending orders through excel or csv files

Question: Is it possible to import pending  orders through an Excel or CSV file in Magento? If yes, how can I do that?
Thanks.
Answer: There seems to be an existing and dedicated module
 for this, I used Google to find this. There will probably be more!
Answer: you can do it,but it is to hard.
that use cart & checkou object to finish.
1.analyze data from xls
2.add product to cart
3.setting billing address & shipping address
4.checkout


bind9 response over network card has delay

Question: Im install bind9.8  cache recursion in ubuntu16.04
whet i dig @127.0.0.1 google.com it answer quickly
;; Query time: 0 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Sun Oct 08 23:06:50 IRST 2017
;; MSG SIZE  rcvd: 191

when query over network its very slow
dig @172.16.133.100 google.com
;; Query time: 3597 msec
;; SERVER: 172.16.133.100#53(172.16.133.100)
;; WHEN: Sun Oct 08 23:08:42 IRST 2017
;; MSG SIZE  rcvd: 191

How can i troublshooting this delay
Answer: First you do not compare two equivalent things, in first case you query nameserver 127.0.0.1 and in second case it is 172.16.133.100
You should have a look at your log files, examine the forward directives you have in your bind configuration, and if not sufficient you will need to sniff your network to see what happens with your DNS packets.
Comment: my problem is load over network and i don no howto resolve and toubleshoot. Service is ok and response fast locally but over network is too slow.
Comment: Please read my answer for troubleshooting tips.


Display none/block on div is not working

Question: i'm trying to get this working but i cant figure out why it wont, is there a way of troubleshooting this i.e to see errors
What i am trying to achieve is to show the info in the showhim div when i hover over  the stat1 div but it aint happening.
I put it here:
http://jsfiddle.net/ksvrY/39/

        This is some example test

        This is another line

        And another one

        And a final one

        Hover over this div

.showhim
{
    display: none;
    margin-bottom: 30px;
}

.stat1:hover .showhim
{
    display: block;
}

Comment: You can't do what you're trying to do with css. You'll have to use JavaScript. CSS can only affect child elements or elements sitting beside each other - not parent elements.
Comment: Don't you think a style rule called `showhim` that has `display:none` is a little misleading..?
Comment: well if you think putting text in a div that is set to display:none is also misleading then i guess your right.
Comment: no, I think hiding an element by applying a class called `showhim` is misleading
Answer: Edit: As pointed out by Paul, you can use the sibling selector.  So there is actually a way to do this with pure css in this case
.stat1 is not a parent of .showhim.
You can use javascript.  So something like (using jQuery):
$('.stat1').mouseover(function(){
  $('.showhim').show();
}).mouseout(function(){
  $('.showhim').hide();
});

See http://jsfiddle.net/ksvrY/50/
Comment: wow that was quick, that sounds logical but how do i fix it, i must put .stat1 in inside the other div? that isn't ideal is there another way to do it and keep them as separate divs
Comment: Perfect, i did already find the solution once people pointed out my errors however your's is much cleaner, for reference this is what i used:

And then:

Thanks so much for everyones help
Answer: For it to work, the .showhim needs to be a child element of .stat1.
Answer: You could do a sibling select.

    Hover over this div

    This is some example test

    This is another line

    And another one

    And a final one

.showhim
{
  display: none;
  margin-bottom: 30px;
}

.stat1:hover ~ .showhim
{
  display: block;
}

Answer: agree with paul
and here's another solution:
move .showhim into #stat1:

        Hover over this div

            This is some example test

            This is another line

            And another one

            And a final one


Check normality assumption for a 3 by 2 within-between (mixed) ANOVA

Question: I'm conducting a 3 (within) x 2 (between) mixed ANOVA in SPSS and would like to assess whether my data satisfy normality assumptions. Do to so, I have saved the unstandardized residuals from the repeated measures module after specifying my model following the syntax below. This gives me 3 sets of residuals - one for each participant for each level of my within-group factor.
<code>GLM @level1 @level2 @level3 BY group
  /WSFACTOR=timepoint 3 Polynomial
  /METHOD=SSTYPE(3)
  /SAVE=RESID
  /CRITERIA=ALPHA(.05)
  /WSDESIGN=timepoint
  /DESIGN=group.
</code>
Question
To assess normality, do I generate QQ-plots and/or perform Shapiro-Wilk tests for each within-subject factor (1 within-factor with 3 levels = 3 plots & 3 tests)
OR
Do I do this for every cell mean (1 within-factor with 3 levels and 2 groups = 3 x 2 groups = 6 plots and 6 tests)?
Answer: This is going to be a very pedantic reply, but I hope it helps.   Basically, you are saying that your data are realised from the following model:
Y = global mean + group_mean_1 + group_mean_2 + error
If you are using this model, the big assumptions are about random errors (not data per se).   You need to assume that errors are:
- independent
- mean of 0
- constant variance (given by say, sigma^2)
You don't have to assume errors are Normal, although many people do.
You might make assumptions about the conditional distribution of Y - that it is Normal(global_mean + group_mean_1 + group_mean_2, sigma^2), but it is important to note that this is a conditional distribution.  It won't have a Normal distribution.
The errors are some fictional entity, but you hope that the residuals are very similar to the errors, and you will carry out checks on the residuals.   Constant variance (at all values of group_mean_1 and group_mean_2) is the most important check.
If you want to do a Normality check, you can look at a qq plot of all the residuals in one go.   IMHO, any formal testing of Normality is overkill.  The residuals can't actually be Normal, even if the errors are Normal.
Allowing for my pedantry over residuals =! errors, this webpage gives you a few practical ideas about model assumptions that may be helpful:
https://www.theanalysisfactor.com/assumptions-of-linear-models/
Comment: Thank you for clarifying this for me. I appreciate your pedantry. I just want to ensure that my _p_ values and _F_ statistics are valid, which I understand rely on normally distributed residuals. That I should perform a QQ plot of all the residuals in one go answers my question.


Procurar arquivo em diretório

Question: Tenho um diretório na rede com milhares de arquivos TXT gerados por um outro software contratado na empresa.
O arquivo é nomeado com a seguinte lógica:
 (cpf do cliente)(data da insercao)(hora insercao).txt
 1234567894120150501142024.txt

Preciso selecionar o txt correspondente ao CPF do cliente informado, porém não estou conseguindo procurar o arquivo.
Comment: Você possui as informações necessárias pra buscar este arquivo?(cpf ,data e hora de inserção)
Comment: Possuo apenas o cpf, e este arquivo é único, gerado somente ao inserir um novo cliente.
Queria algo tipo LIKE do mysql, para que assim buscasse todos os arquivos com o cpf no inicio.
Comment: publiquei minha resposta
Answer: Utiliza a função glob() para isso.
foreach (glob("00000000000*") as $file) {
    $user = $file;
}

Note que na definição do padrão existe um * que serve para definir que tudo o que vier após o $cpf é irrelevante para a busca, sendo assim você receberá como retorno todos os arquivos que possuam no início um valor que seja igual ao CPF igual ao buscado.
Answer: Não testei, mas acredito que o glob() vai resolver o problema. Se você sabe o CPF, pode fazer algo como
$cpf = "12345678900*";
    foreach (glob($cpf) as $arq) {
    echo "$arq" ."\n";
}

ele devolve o nome do arquivo que tem o cpf que você passou.

Procurar arquivo em diretório