Removing fill from google-maps KmlLayers

Question: I notice this morning that KmlLayers that I use to identify the boundary of Bullitt County KY are now being filled in with a blue color. Example is at http://bullittcountyhistory.org/if/andersonx.html . Is there a way to turn off the fill? All I want is the county boundary in blue.
The kml file is located at http://bullittcountyhistory.org/places/bullittboundary.kml and fill is set to 0 and outline to 1. Thanks.
Answer: See http://groups.google.com/group/google-maps-js-api-v3/browse_frm/thread/17afaa377a5abc25#
Star this issue:
http://code.google.com/p/gmaps-api-issues/issues/detail?id=4187
Comment: This was a bug and is now fixed
Comment: This is not true anymore
Comment: What isn't true?  Is it broken again?  The link in the original question still works and shows it working correctly (for at least that sample)


Setting the default front page setting to be translatable

Question: I've enabled the following multilingual modules:

Configuration Translation
Content Translation
Interface Translation
Language

Configuration translation enables me to translate the site title and slogan, but how can I translate the default front page setting to have a different front page per language?
I can see the setting in system.site.yml:

page:
  403: ''
  404: ''
  front: /node

but overriding it in language/de/system.site.yml doesn't seem to help.
Is there anyway I can activate the setting for translation?
Answer: I created a proof of concept Drupal (latest - 8.3.5) instance on simplytest.me earlier today to check if this is actually something you cannot override in language//system.site.yml. I had no problem to differentiate frontpage for default (english) language and additional language.
Just remember that front property is nested under page key.
Answer: I just ran into the same situation and like described by @zaporylie, the workaround to set the value directly in the translated configuration works perfectly. Did the author perhaps forget to import the changed configuration?
I now opened an issue to expose these values in UI. Please help to contribute: https://www.drupal.org/project/drupal/issues/3097497
Comment: "forget to import the changed configuration?" Not sure. It was four years ago.


Regression analysis with small data set

Question: We've performed a regression analysis with 14 data points (Y's) that originate from 9 X's (plant batches were split up).
I'm well aware that this is a small data set and there are caveats. However, the regression we have gives a R-sqrd (pred) of 85%,  residuals are all good, there are no anomalous points or residuals outside two SD; lack of fit is 0.43.
Some of the data is subjective - growers assigned a rating of pest infestation on the plants from 1 (bad) to (5) barely any. We've counted the number of weeks of pest attack of score 1,2 or 3 to balance out this subjectivity (only scores of 3 or more are flagged); this makes one X.
Given this background and R-sqrd, can we say we have good correlation and provide justification to put the multiple X's we've identified under more scrutiny?
Comment: You have nine observations of your independent variable and 14 observations of your dependent variable? In any event, I suggest reading my post here: https://datascience.stackexchange.com/a/64148/73930. I have another post where I show how to do the F-test for a regression: https://stats.stackexchange.com/a/439341/247274. As I mentioned in the first, though, such a high $R^2$ almost doesn't require math to say that it's higher than 0.
Answer: Overfit Model
Because you have such few observations in your model relative to the number of predictor variables, your model is likely an overfit model. An overfit model is too complex for the data - it has too many predictor variables for the number of observations.
Problems with R Squared in an Overfit Model
A symptom of an overfit model is a high R squared value, as explained by Jim Frost in his article on "Five Reasons Why Your R-squared can be Too High"
(https://statisticsbyjim.com/regression/r-squared-too-high/):
"While the R2 looks good, there can be serious problems with an overfit model. For one thing, the regression coefficients represent the noise rather than the genuine relationships in the population. Additionally, an overfit regression model is tailor-made to fit the random quirks of one sample and is unlikely to fit the random quirks of another sample. Thus, overfitting a regression model reduces its generalizability outside the original dataset."
Investigate If Model Overfits the Data
So before you make any decisions based on your current model, you need to investigate further whether your current model is an overfit model, since an overfit model can produce misleading R squared values, as well as misleading regression coefficients and p-values.  If you'll base your decisions on misleading values, everything you do further down the road will be questionable.
Jim Frost has another nice article on Overfitting Regression Models: Problems, Detection, and Avoidance you can refer to (https://statisticsbyjim.com/regression/overfitting-regression-models/). In this article, he explains that you can use a different kind of R squared to detect overfitting: the predicted R squared.
Predicted R Squared Versus Regular R Squared
If you are able to compute the predicted R squared for your model, you can then compare the predicted R-squared to the regular R-squared and see if there is a large discrepancy between their values (e.g., predicted R squared could be equal to almost 0% while regular R squared could be equal to 85%). To quote Jim Frost:
"If there is a large discrepancy between the two values, your model doesn't predict new observations as well as it fits the original dataset. The results are not generalizable, and there's a good chance you're overfitting the model."
In a separate article, titled How to Interpret Adjusted R-Squared and Predicted R-Squared in Regression Analysis
(https://statisticsbyjim.com/regression/interpret-adjusted-r-squared-predicted-r-squared-regression/), Jim Frost states:
"Predicted R-squared helps you determine whether you are overfitting a regression model. Again, an overfit model includes an excessive number of terms, and it begins to fit the random noise in your sample.
By its very definition, it is not possible to predict random noise. Consequently, if your model fits a lot of random noise, the predicted R-squared value must fall. A predicted R-squared that is distinctly smaller than R-squared is a warning sign that you are overfitting the model. Try reducing the number of terms."
Comment: Oh, I missed that bracket clarification about the predicted R squared. What was the regular R squared?
Comment: That was my concern @Isabella Ghement,  but that's why I mentioned that predicted R-sqrd was 85%
Comment: 93% adjusted,  95% regular

Regression analysis with small data set


Is there a solution for parker's square?

Question: From wiki: Mathematician Matt Parker attempted to create a 3x3 magic square using square numbers in a YouTube video on the Numberphile channel. His failed attempt is known as the Parker Square.
I wonder , if there's a solution or proof that there is none?
Comment: You would have found the answer by actually watching that Numberphile episode ...
Comment: Direct link to the time in the video when Parker states that this is an open problem: https://youtu.be/aOT_bG-vWyg?t=36
Comment: Here's a some of the reason why it's so difficult to prove/disprove.A magic square of squares could be transformed into 8 elliptic curve solutions (and similarly such elliptic curve solutions could be turned into a MSOS). This relates the problem to more high-level mathematics. For example, some possible diagonals, rows, and columns of the MSOS can be ruled out if the Birch and Swinnerton-Dyer conjecture, a millennial problem, is proven.
Comment: @ChristianWoll fascinating... may i ask what is MSOS?
Comment: @athos Magic Square of Squares :) More about elliptic curves and square numbers: http://www.math.uconn.edu/~kconrad/blurbs/ugradnumthy/congnumber.pdf
Comment: @ChristianWoll thanks for the explanation!
Comment: I read somewhere last year that there was a formula for finding $3\times 3$ magic squares, where each entry is a squared number and no rules are relaxed apart from how one diagonal does not add up to the magic constant, however I cannot find it. All I remember was that by letting each entry equal $n_1^2, n_2^2,\ldots, n_9^2$, the value $n$ was a polynomial expression containing all degrees up to $4$ and a single indeterminate $k$.
Answer: This is an open problem.  No example is known; nor is a proof that there is none.
Open Problem Garden says:

This question was first asked in 1984 by Martin LaBar and popularized in 1996 by Martin Gardner, who offered \$100 to the first person to construct such a square. In 2005 Christian Boyer offered €1,000 and a bottle of champagne for a solution to a somewhat easier problem. For a review of the history of research, see […]. For basic facts about the anticipated $ 3\times 3 $ magic square of squares, see […].

Some discussion is given on mathpages.com.
Comment: Ok, so it's still open...


AJAX append content via link on existing page

Question: I am trying to recreate the functionality of the ajax_link example in the Examples for Developers module.  Here is the code I have so far:
In animal_licence.module:
function animal_licence_menu() {
  $items['buy-animal-licence/animal'] = array(
    'page callback' => 'ajax_link_response',
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    'file' => 'animal_licence.inc',
  );
  return $items;
}

In animal_licence.inc
function ajax_link_response($type = 'ajax') {
      if ($type == 'ajax') {
        $output = t("This is some content delivered via AJAX");
        $commands = array();
        $commands[] = ajax_command_append('#content', $output);
        $page = array('#type' => 'ajax', '#commands' => $commands);
        ajax_deliver($page);
      }
      else {
        $output = t("This is some content delivered via a page load.");
        return $output;
      }
    }

The ajax link on-page is:
Click here

When I visit /buy-animal-licence/animal/ and click the link I get the ajax spinner and it eventually times out with the following:
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /buy-animal-licence/animal/ajax/
StatusText: OK
ResponseText:...

I'm not sure where to go from here, any suggestions would be much appreciated.
Comment: Welcome to Drupal Answers :) Your hook_menu implementation is missing `return $items;` - add that line at the end, clear Drupal's cache, and try the link again
Comment: Thanks for the response!  Unfortunately I truncated the code to make it more legible (there are other items within the same hook_menu function) and accidentally omitted the return.  I'll edit the question to include it but unfortunately this is not the solution.
Answer: you need to add the nojs uri part in your menu item like:
$items['buy-animal-licence/animal/%ctools_js']

also, to make all more clear - your type argument in the callback should default to NULL
function ajax_link_response($type = NULL) {


Effectiveness of learning drums by playing Rock Band

Question: For a few years I have been an avid Rock Band 3 player. For the last year, I have been taking more and more interest in playing drums on the game. My favourite bands to play on the game right now are Metallica and Dream Theater.
Even without the cymbal extension (so base pedal and 4 pads), this already feels very realistic. Definitely more so than playing the guitar on the game would.
I have been enjoying this so much that I am considering buying an electric drumkit, but I am holding it off, mostly due to space issues.
For the time being, playing Rock Band it is.
I wonder though, would there be lots of things I would have to relearn when/if I would switch to a real drumkit? In other words, how effective is playing Rock Band (on expert level of course) for actually learning to play drums?
Answer: One only has to hear Roy 'Future Man' Wooten perform to know the facility and fluidity that can be achieved in pad controller-based playing, but Wooten was already an accomplished drummer when he started on pads. No doubt you will have developed your reflexes, coordination and stick control and learned something about tempo and the role of drums in the ensemble, but the single most valuable activity to promote your development as a drummer would be to start learning your drum rudiments.
Drummers of all styles speak in rudiments as guitarists speak in scales. Without rudiments you are copying patterns; with rudiments you are making your own music and understanding how the drummers of Metallica and Dream Theater come up with their grooves and fills.
The good news is that you can practise drum rudiments on a table top, the sole of your shoe or just with your hands on your thighs-no other equipment necessary. This clip,

 shows just what can be done with one drum and a mastery of rudiments.
Rock Band certainly won't hurt your drumming, but rudiments will make you a drummer.
Answer: Playing Rock Band develops one core skill of drumming, which is coordination. Other musical skills will have to be developed from scratch. A major difference between Rock Band and playing music is that Rock Band is reactive (the notes and rhythms fly out at you from the screen), while playing music alone or in a group, you have to provide the pacing and feel internally.
This will be especially true if you start drumming. Your internal tempo and feel for the groove will be critical to the sound of the group, and will take time to develop. You will also need to learn to strike a drum correctly to produce good tone, something that Rock Band cannot teach you.
If you want to get a sense of what drum practice will be like without spending any more money, use a free metronome app and start practicing drum rudiments. Rudiments are rhythm patterns designed to develop the fundamental skills of drumming. These are the building blocks of drum skills, and can be practiced just with sticks on any surface (or with your hands and feet). If you are passionate about music and willing to dedicate the time and effort, you will be able to transition from video game drumming to real drumming. But be prepared to be a beginner, even if you are an excellent Rock Band player.
Comment: Also real drumming on real drums involves a lot of subtleties of playing that are not possible in rock band. Exactly where and how hard and with what part of the stick you hit each kit piece has a huge effect on the sound.
Comment: To add to Todd Wilcox's point, this applies even with electronic drum kits.


When is the exponential map between matrices injective?

Question: Consider a complex matrix $A$. When does $e^A=e^B$ imply $A=B$?
Is there any general statement that can be made as to when this holds?
It is clearly not true in general, a trivial example being when $A$ and $B$ are diagonal in the same basis but with eigenvalues differing by $2\pi i\mathbb Z$. This is also mentioned in this question.
This answer also seems to provide an answer to this question, but I'm not familiar with the theory of Lie algebras so I'm not sure, and I wouldn't know how to translate it into more elementary statements about matrices (if that is even possible).
Comment: The answer of Yves *does* really provide an answer, in my opinion. This question should be considered within the area of Lie groups and Lie algebras.
Comment: @DietrichBurde if you are referring to the answer I linked, I'm not saying it doesn't. Rather, I'm asking whether that answer can be translated into the language of matrices for someone not familiar with Lie theory
Comment: No, you need "solvable" and "simply connected" and other properties from Lie groups, which should not be explained only with matrices, I think. There is topology and algebra, after all, not only matrices.
Comment: See [loup blanc's answer](https://math.stackexchange.com/a/756282).
Answer: This was addressed in loup blanc's answer to another question, although that question has a narrower setting than the current one.


Do I have to munmap() a mmap() file?

Question: I have relatively new to C++ and I am learning from another guy's code.
His code reads from a mmapped file, but does not free any mapped memory in the end. In my understanding, mmap() map files into virtual memory. Don't I need to release those mapped memory in some way, like, calling munmap()?
Answer: I believe you should release mapped memory with munmap. But it will be released automatically (like close syscall for regular files or sockets) after exit(). Remember, that implicit closing/unmapping is bad style!
Answer: munmap happens automatically on exit
So if the program is going to exit anyways, you don't really need to do it.
man munmap 4.15 says:

The munmap() system call deletes the mappings for the specified address range, and causes further references to addresses within the range to generate invalid memory references.  The region is  also
         automatically unmapped when the process is terminated.  On the other hand, closing the file descriptor does not unmap the region.

If the program doesn't exit, of course, you leak memory, just as with malloc (which nowadays uses mmap).
Answer: When you are done just use munmap() unless your program is exiting, then there is no need, it will unmap the segment(s) automatically at exit.

Do I have to munmap() a mmap() file?


advice on memory purchase for AMD 6134 2P server

Question: HP DL165G7 with 2x AMD 6134 CPU.
target RAM: 48GB
options:

2GB dual rank registered DIMM  - 24 Qty HP-2GB 2Rx8 PC3-10600R-9 Kit
4Gb single rank registered DIMM - 12 Qty HP-4GB 1Rx4 PC3-10600R-9 Kit

which of the above is recommended for performance (ESX server)? AMD CPUs suffer any downgrade on mem bandwidth like Xeons?
Answer: The machine has 4 channels, each with 3 slots per processor - for a dual processor config then purely for performance you should go for 24 x 2GB (593907-Bxx) but I'd personally go for the 12 x 4GB so I can easily double my memory without having to throw anything away - it will be slightly slower but no more than ~10%
Comment: There rarely is but these things do have a habit of coming along! if you're certain then you have your answer.
Comment: there are no plans to upgrade memory on this server
Comment: sure that perf hit is only lesser than 10%?


What's the difference between a Page and a Slide in Google Slides?

Question: The API for Google Slides has two classes:

Slide
Page

The documentation merely states "An X in a presentation" (where X is the class in question).
What's the difference conceptually? Is a page something you get when you are printing the presentation?
I see an "New Slide" function in the menu, but how does one use Pages in Google Slides?
Answer: This suggests that a Page can be a

Slide,
Layout or
Master

And the description of the methods listed for Layout seem to support this idea.
But I have not seen any documentation say this specifically.


Scaling features for neural network input

Question: I have a df with many features that take both negative and positive values.For example a feature may have values in range (-10 , 10).For each feature which has negative values the negative sign means direction and this -10 is actually a larger value than - 5.
After finilizing my model i tried many scaling techniques such as Minmaxscaler from (0,1) and mean max scaler from (-1,1),robust scaler,standarization and found the minmaxscaler from (0,1) has the best results.
My concern is this:
Scaling the data with this technique does not account for the true meaning of my feature as seen belo and -2 will be smaller than -1 after scaling to (0,1).
Is there a way to enforce this rule(negative means only direction) during my scaling process?
Answer: Peculiar to your case, you can scale the absolute values of your features, and then apply your directions, i.e. some sort of magnitude scaling, though I'm not sure it'll provide you performance uplift. In addition, don't expect properties like zero mean, unit variance etc. after performing the scaling this way.
Comment: I meant just applying the signs after the scaling
Comment: I got the first part,but i can't understand how direction would be applied by magnitude scaling.Could you explain a bit more?
Answer: You could distinguish direction and magnitude by re-expressing the two components of your data format.

$| x |$ captures magnitude, reflecting that $-10$ is "larger" than $-5$.
the sign $\text{sgn}(x)$ captures directing, with $+1$ indicating one direction and $-1$ the opposite.

This will double the number of features you have, which might not be desirable.


Convertiny Mysql_Query to Mysqli

Question: I am trying to adapt the below function from using Mysql_Query to Mysqli.
I seem to be going wrong somewhere, but I don't get any errors it just doesn't pull through any results.
Can anyone help with what I am doing wrong please?
Original Code
<?php
function get_product_name($pid){
$result=mysql_query("select Product_Name from Products where Product_ID=$pid")  or die("select Product_Name from Products where Product_ID=$pid"."

".mysql_error());
$row=mysql_fetch_array($result);
return $row['Product_Name'];
}
function get_price($pid){
$result=mysql_query("select ProductPrice from Products where Product_ID=$pid") or die("select ProductPrice from Products where Product_ID=$pid"."

".mysql_error());
$row=mysql_fetch_array($result);
return $row['ProductPrice'];
}
?>

Updated Code
<?php
function get_product_name($pid){
$result=$mysqli->query("select Product_Name from Products where Product_ID=$pid") or die("select Product_Name from Products where Product_ID=$pid"."

".mysql_error());
$row=$result->fetch_array();
return $row['Product_Name'];
}
function get_price($pid){
$result=$mysqli->query("select ProductPrice from Products where Product_ID=$pid") or die("select ProductPrice from Products where Product_ID=$pid"."

".mysql_error());
$row=$result->fetch_array();
return $row['ProductPrice'];
}
?>

Comment: Awesome thank you. Now works perfectly :)
Comment: inside function declare `global $mysqli;` to call the global variable mysqli object
Answer: inside function declare global $mysqli; to call the global variable mysqli object
<?php
function get_product_name($pid){
global $mysqli;
$result=$mysqli->query("select Product_Name from Products where Product_ID=$pid") or die("select Product_Name from Products where Product_ID=$pid"."

".mysql_error());
$row=$result->fetch_array();
return $row['Product_Name'];
}
function get_price($pid){
global $mysqli;
$result=$mysqli->query("select ProductPrice from Products where Product_ID=$pid") or die("select ProductPrice from Products where Product_ID=$pid"."

".mysql_error());
$row=$result->fetch_array();
return $row['ProductPrice'];
}
?>

Convertiny Mysql_Query to Mysqli


select all p:selectManyCheckbox

Question: I'd like to create a button to select all checkboxes but I couldn't find one example that works for me. I'm using primefaces.

        <f:selectItem itemLabel="12:00" itemValue="Sexta-12:00" />
        <f:selectItem itemLabel="12:30" itemValue="Sexta-12:30" />
        <f:selectItem itemLabel="13:00" itemValue="Sexta-13:00" />
        <f:selectItem itemLabel="13:30" itemValue="Sexta-13:30" />
        <f:selectItem itemLabel="14:00" itemValue="Sexta-14:00" />
        <f:selectItem itemLabel="14:30" itemValue="Sexta-14:30" />
        <f:selectItem itemLabel="15:00" itemValue="Sexta-15:00" />
        <f:selectItem itemLabel="16:00" itemValue="Sexta-16:00" />
        <f:selectItem itemLabel="16:30" itemValue="Sexta-16:30" />
        <f:selectItem itemLabel="17:00" itemValue="Sexta-17:00" />
        <f:selectItem itemLabel="17:30" itemValue="Sexta-17:30" />
        <f:selectItem itemLabel="18:00" itemValue="Sexta-18:00" />
        <f:selectItem itemLabel="18:30" itemValue="Sexta-18:30" />
        <f:selectItem itemLabel="19:00" itemValue="Sexta-19:00" />
        <f:selectItem itemLabel="19:30" itemValue="Sexta-19:30" />
        <f:selectItem itemLabel="20:00" itemValue="Sexta-20:00" />
        <f:selectItem itemLabel="20:30" itemValue="Sexta-20:30" />
        <f:selectItem itemLabel="21:00" itemValue="Sexta-21:00" />
        <f:selectItem itemLabel="21:30" itemValue="Sexta-21:30" />
        <f:selectItem itemLabel="22:00" itemValue="Sexta-22:00" />
        <f:selectItem itemLabel="22:30" itemValue="Sexta-22:30" />

Answer: You can add commandLink

  <h:outputText value="Select all" />

And method in Java (in yourBean class):
public void selectAll(ActionEvent actionEvent) {
    selectedHorariosSexta.clear();
    int startHour = 12;
    for (int i = 0; i < 22; i++) {
        if (i % 2 == 0) {
            selectedHorariosSexta.add("Sexta-" + startHour + ":00");
        }else {
            selectedHorariosSexta.add("Sexta-" + startHour + ":30");
            startHour++;
        }
    }
}

select all p:selectManyCheckbox


Very Simple Edge Detection

Question: I have a simple, high-contrast, black & white video image on which I need to find the X value of a vertical edge and the Y value of a horizontal edge. I also need to know the direction of the edges (white->black or black->white).
There will be:

Zero or one horizontal edge
Zero or one vertical edge.
The edges are perfectly straight.
The edges will be defined by a sharp(ish) transition from black to white or white to black.

I've been reading about edge detection algorithms and understanding very little of it, but what I do understand is that they are all far more complex than my requirements. They are all designed to produce an image of simple edges from a complex image. My requirements (my images) are much simpler, I only need the X and a Y value of zero to two edges.
If I plot say one row of pixels on a graph (X=pixel index, Y=pixel intensity), I will get something like a line, a rising slope, and another line. The center point of the slope would be what I need. But the lines are not perfect. They are noisy and there can be small bumps or dips, or it can be (mostly) flat if no edge is visible.
So is there a simple algorithm to smooth that plot and produce both the direction and the center point of "the slope"?
Comment: It would help a lot if you showed us a couple of sample images and also said what OS and what tools you plan to use...
Answer: I would approach this using ImageMagick straight from the command line - it is installed on most Linux distros and is available for OSX and Windows too.
So, firstly, I would go to greyscale and normalise the contrast so that you are less susceptible to variations in exposure or lighting. Then I would threshold at 50% so that all the pixels are forced to either black or white.
convert line.png -colorspace gray -normalize -threshold 50% result.png

Then I would run a tall, thin median filter (say 100 pixels tall and 1 pixel wide) to smooth the image in the vertical direction (so I can find the horizontal edges).
convert line.png -colorspace gray -normalize -threshold 50% -virtual-pixel mirror -statistic median 1x100 result.png

I would then resize the image to 1 pixel wide and 100 pixels tall to reduce the volume of output and because I would say that to find the edge within 1% of the image height is as much as you can hope for with such a noisy image.
convert line.png -colorspace gray -normalize -threshold 50% -virtual-pixel mirror -statistic median 1x100 -resize 1x100! txt:

# ImageMagick pixel enumeration: 1,100,255,srgb
0,0: (32496,32496,32496)  #7E7E7E  srgb(126,126,126)
0,1: (32969,32969,32969)  #808080  srgb(128,128,128)
0,2: (33498,33498,33498)  #828282  srgb(130,130,130)
0,3: (32632,32632,32632)  #7F7F7F  srgb(127,127,127)
0,4: (32708,32708,32708)  #7F7F7F  srgb(127,127,127)
0,5: (32787,32787,32787)  #808080  srgb(128,128,128)
0,6: (32615,32615,32615)  #7F7F7F  srgb(127,127,127)
0,7: (33186,33186,33186)  #818181  srgb(129,129,129)
0,8: (33786,33786,33786)  #838383  srgb(131,131,131)
0,9: (33610,33610,33610)  #838383  srgb(131,131,131)
0,10: (32577,32577,32577)  #7F7F7F  srgb(127,127,127)
0,11: (33159,33159,33159)  #818181  srgb(129,129,129)
0,12: (33578,33578,33578)  #838383  srgb(131,131,131)
0,13: (33276,33276,33276)  #818181  srgb(129,129,129)
0,14: (33259,33259,33259)  #818181  srgb(129,129,129)
0,15: (32620,32620,32620)  #7F7F7F  srgb(127,127,127)
0,16: (32624,32624,32624)  #7F7F7F  srgb(127,127,127)
0,17: (33131,33131,33131)  #818181  srgb(129,129,129)
0,18: (33278,33278,33278)  #818181  srgb(129,129,129)
0,19: (32680,32680,32680)  #7F7F7F  srgb(127,127,127)
0,20: (33136,33136,33136)  #818181  srgb(129,129,129)
0,21: (32707,32707,32707)  #7F7F7F  srgb(127,127,127)
0,22: (33051,33051,33051)  #818181  srgb(129,129,129)
0,23: (33794,33794,33794)  #838383  srgb(131,131,131)
0,24: (33704,33704,33704)  #838383  srgb(131,131,131)
0,25: (33028,33028,33028)  #818181  srgb(129,129,129)
0,26: (33605,33605,33605)  #838383  srgb(131,131,131)
0,27: (33785,33785,33785)  #838383  srgb(131,131,131)
0,28: (33290,33290,33290)  #828282  srgb(130,130,130)
0,29: (33079,33079,33079)  #818181  srgb(129,129,129)
0,30: (33430,33430,33430)  #828282  srgb(130,130,130)
0,31: (33246,33246,33246)  #818181  srgb(129,129,129)
0,32: (33102,33102,33102)  #818181  srgb(129,129,129)
0,33: (33248,33248,33248)  #818181  srgb(129,129,129)
0,34: (33823,33823,33823)  #848484  srgb(132,132,132)
0,35: (33678,33678,33678)  #838383  srgb(131,131,131)
0,36: (33497,33497,33497)  #828282  srgb(130,130,130)
0,37: (33960,33960,33960)  #848484  srgb(132,132,132)
0,38: (33520,33520,33520)  #828282  srgb(130,130,130)
0,39: (33235,33235,33235)  #818181  srgb(129,129,129)
0,40: (32655,32655,32655)  #7F7F7F  srgb(127,127,127)
0,41: (32825,32825,32825)  #808080  srgb(128,128,128)
0,42: (32847,32847,32847)  #808080  srgb(128,128,128)
0,43: (33214,33214,33214)  #818181  srgb(129,129,129)
0,44: (32966,32966,32966)  #808080  srgb(128,128,128)
0,45: (33262,33262,33262)  #818181  srgb(129,129,129)
0,46: (33178,33178,33178)  #818181  srgb(129,129,129)
0,47: (32501,32501,32501)  #7E7E7E  srgb(126,126,126)
0,48: (32499,32499,32499)  #7E7E7E  srgb(126,126,126)
0,49: (31982,31982,31982)  #7C7C7C  srgb(124,124,124)
0,50: (32564,32564,32564)  #7F7F7F  srgb(127,127,127)
0,51: (32336,32336,32336)  #7E7E7E  srgb(126,126,126)
0,52: (30311,30311,30311)  #767676  srgb(118,118,118)
0,53: (27119,27119,27119)  #6A6A6A  srgb(106,106,106)
0,54: (13002,13002,13002)  #333333  srgb(51,51,51)
0,55: (1855,1855,1855)  #070707  srgb(7,7,7)
0,56: (187,187,187)  #010101  srgb(1,1,1)           <--- This is your edge at 56% of the image height down from the top
0,57: (72,72,72)  #000000  srgb(0,0,0)
0,58: (0,0,0)  #000000  black
0,59: (0,0,0)  #000000  black
0,60: (0,0,0)  #000000  black
0,61: (0,0,0)  #000000  black
0,62: (0,0,0)  #000000  black
0,63: (0,0,0)  #000000  black
0,64: (0,0,0)  #000000  black
0,65: (0,0,0)  #000000  black
0,66: (0,0,0)  #000000  black
0,67: (0,0,0)  #000000  black
0,68: (0,0,0)  #000000  black
0,69: (0,0,0)  #000000  black
0,70: (0,0,0)  #000000  black
0,71: (0,0,0)  #000000  black
0,72: (0,0,0)  #000000  black
0,73: (0,0,0)  #000000  black
0,74: (0,0,0)  #000000  black
0,75: (0,0,0)  #000000  black
0,76: (0,0,0)  #000000  black
0,77: (0,0,0)  #000000  black
0,78: (0,0,0)  #000000  black
0,79: (0,0,0)  #000000  black
0,80: (0,0,0)  #000000  black
0,81: (0,0,0)  #000000  black
0,82: (0,0,0)  #000000  black
0,83: (0,0,0)  #000000  black
0,84: (0,0,0)  #000000  black
0,85: (0,0,0)  #000000  black
0,86: (0,0,0)  #000000  black
0,87: (0,0,0)  #000000  black
0,88: (0,0,0)  #000000  black
0,89: (0,0,0)  #000000  black
0,90: (0,0,0)  #000000  black
0,91: (0,0,0)  #000000  black
0,92: (0,0,0)  #000000  black
0,93: (0,0,0)  #000000  black
0,94: (0,0,0)  #000000  black
0,95: (0,0,0)  #000000  black
0,96: (0,0,0)  #000000  black
0,97: (0,0,0)  #000000  black
0,98: (0,0,0)  #000000  black
0,99: (0,0,0)  #000000  black

Likewise for your vertical edge...
convert line.png -colorspace gray -normalize -threshold 50% -virtual-pixel mirror -statistic median 100x1 -resize 100x1! txt:

# ImageMagick pixel enumeration: 100,1,255,srgb
0,0: (0,0,0)  #000000  black
1,0: (0,0,0)  #000000  black
2,0: (0,0,0)  #000000  black
3,0: (0,0,0)  #000000  black
4,0: (0,0,0)  #000000  black
5,0: (0,0,0)  #000000  black
6,0: (0,0,0)  #000000  black
7,0: (0,0,0)  #000000  black
8,0: (0,0,0)  #000000  black
9,0: (0,0,0)  #000000  black
10,0: (0,0,0)  #000000  black
11,0: (0,0,0)  #000000  black
12,0: (0,0,0)  #000000  black
13,0: (0,0,0)  #000000  black
14,0: (0,0,0)  #000000  black
15,0: (0,0,0)  #000000  black
16,0: (0,0,0)  #000000  black
17,0: (0,0,0)  #000000  black
18,0: (0,0,0)  #000000  black
19,0: (0,0,0)  #000000  black
20,0: (0,0,0)  #000000  black
21,0: (0,0,0)  #000000  black
22,0: (0,0,0)  #000000  black
23,0: (0,0,0)  #000000  black
24,0: (0,0,0)  #000000  black
25,0: (0,0,0)  #000000  black
26,0: (0,0,0)  #000000  black
27,0: (0,0,0)  #000000  black
28,0: (0,0,0)  #000000  black
29,0: (0,0,0)  #000000  black
30,0: (0,0,0)  #000000  black
31,0: (0,0,0)  #000000  black
32,0: (0,0,0)  #000000  black
33,0: (0,0,0)  #000000  black
34,0: (0,0,0)  #000000  black
35,0: (0,0,0)  #000000  black
36,0: (0,0,0)  #000000  black
37,0: (0,0,0)  #000000  black
38,0: (0,0,0)  #000000  black
39,0: (0,0,0)  #000000  black
40,0: (0,0,0)  #000000  black
41,0: (0,0,0)  #000000  black
42,0: (0,0,0)  #000000  black
43,0: (0,0,0)  #000000  black
44,0: (0,0,0)  #000000  black
45,0: (7,7,7)  #000000  srgb(0,0,0)
46,0: (87,87,87)  #000000  srgb(0,0,0)
47,0: (342,342,342)  #010101  srgb(1,1,1)
48,0: (3623,3623,3623)  #0E0E0E  srgb(14,14,14)
49,0: (16943,16943,16943)  #424242  srgb(66,66,66)      <-- This is your vertical edge, 49% of the image width across from the left side
50,0: (29779,29779,29779)  #747474  srgb(116,116,116)
51,0: (33852,33852,33852)  #848484  srgb(132,132,132)
52,0: (34745,34745,34745)  #878787  srgb(135,135,135)
53,0: (35643,35643,35643)  #8B8B8B  srgb(139,139,139)
54,0: (35893,35893,35893)  #8C8C8C  srgb(140,140,140)
55,0: (35932,35932,35932)  #8C8C8C  srgb(140,140,140)
56,0: (35934,35934,35934)  #8C8C8C  srgb(140,140,140)
57,0: (36041,36041,36041)  #8C8C8C  srgb(140,140,140)
58,0: (36095,36095,36095)  #8C8C8C  srgb(140,140,140)
59,0: (35975,35975,35975)  #8C8C8C  srgb(140,140,140)
60,0: (35937,35937,35937)  #8C8C8C  srgb(140,140,140)
61,0: (35937,35937,35937)  #8C8C8C  srgb(140,140,140)
62,0: (36042,36042,36042)  #8C8C8C  srgb(140,140,140)
63,0: (36094,36094,36094)  #8C8C8C  srgb(140,140,140)
64,0: (36148,36148,36148)  #8D8D8D  srgb(141,141,141)
65,0: (36409,36409,36409)  #8E8E8E  srgb(142,142,142)
66,0: (36409,36409,36409)  #8E8E8E  srgb(142,142,142)
67,0: (36375,36375,36375)  #8E8E8E  srgb(142,142,142)
68,0: (36252,36252,36252)  #8D8D8D  srgb(141,141,141)
69,0: (36214,36214,36214)  #8D8D8D  srgb(141,141,141)
70,0: (36176,36176,36176)  #8D8D8D  srgb(141,141,141)
71,0: (36274,36274,36274)  #8D8D8D  srgb(141,141,141)
72,0: (36406,36406,36406)  #8E8E8E  srgb(142,142,142)
73,0: (36366,36366,36366)  #8E8E8E  srgb(142,142,142)
74,0: (36128,36128,36128)  #8D8D8D  srgb(141,141,141)
75,0: (36004,36004,36004)  #8C8C8C  srgb(140,140,140)
76,0: (35900,35900,35900)  #8C8C8C  srgb(140,140,140)
77,0: (35872,35872,35872)  #8C8C8C  srgb(140,140,140)
78,0: (35855,35855,35855)  #8C8C8C  srgb(140,140,140)
79,0: (35779,35779,35779)  #8B8B8B  srgb(139,139,139)
80,0: (35777,35777,35777)  #8B8B8B  srgb(139,139,139)
81,0: (35664,35664,35664)  #8B8B8B  srgb(139,139,139)
82,0: (35774,35774,35774)  #8B8B8B  srgb(139,139,139)
83,0: (35785,35785,35785)  #8B8B8B  srgb(139,139,139)
84,0: (35753,35753,35753)  #8B8B8B  srgb(139,139,139)
85,0: (35671,35671,35671)  #8B8B8B  srgb(139,139,139)
86,0: (35675,35675,35675)  #8B8B8B  srgb(139,139,139)
87,0: (35694,35694,35694)  #8B8B8B  srgb(139,139,139)
88,0: (35621,35621,35621)  #8B8B8B  srgb(139,139,139)
89,0: (35819,35819,35819)  #8B8B8B  srgb(139,139,139)
90,0: (36080,36080,36080)  #8C8C8C  srgb(140,140,140)
91,0: (36300,36300,36300)  #8D8D8D  srgb(141,141,141)
92,0: (36550,36550,36550)  #8E8E8E  srgb(142,142,142)
93,0: (36561,36561,36561)  #8E8E8E  srgb(142,142,142)
94,0: (36425,36425,36425)  #8E8E8E  srgb(142,142,142)
95,0: (36268,36268,36268)  #8D8D8D  srgb(141,141,141)
96,0: (36317,36317,36317)  #8D8D8D  srgb(141,141,141)
97,0: (36409,36409,36409)  #8E8E8E  srgb(142,142,142)
98,0: (36521,36521,36521)  #8E8E8E  srgb(142,142,142)
99,0: (36568,36568,36568)  #8E8E8E  srgb(142,142,142)

This is your median filtered image for the vertical edge:

And, I can draw the detected edges on in red like this:
convert line.png -stroke red -draw "line 0,268 640,268" -draw "line 313,0 313,480" result.png

So, in summary, the two commands you would run in Terminal, without writing or compiling and linking any code, are as follows:
# Find horizontal edges
convert line.png -colorspace gray -normalize -threshold 50% -virtual-pixel mirror -statistic median 1x100 -resize 1x100! txt:

# Find vertical edges
convert line.png -colorspace gray -normalize -threshold 50% -virtual-pixel mirror -statistic median 100x1 -resize 100x1! txt:

Comment: I wish I had posted an image earlier! Thank you for this.
Comment: My pleasure. I hope the ideas work well for your other images. If any issues arise, remember that questions are free on SO, so just ask away :-) Good luck with your project!
Answer: If you want to smooth the edges, the 2D-Convolution filter from OpenCV could help you. I don't know if you are already using OpenCV-libraries. That's one of the most useful libraries in Image Processing.
If you want to fill the gaps in your line, you could use the Opening Filter again from OpenCV.
To use the Edge Detection Algorithms, you don't need to understand them. The advantage is that you can simply test it and see if it gives you the result you want. I personally use the Canny Edge Detection to detect the edges in a Black White X-Ray image.
include "opencv2/imgproc/imgproc.hpp"
    //// find out largest gradient in image
    //edgeDetection( m_data->m_originalXRay , m_data->m_segmentedXRay, m_data->m_width, m_data->m_height);
    //double largestGradient = 0;
    //for (int y = 0; y<m_data->m_height; y++)
    //  for (int x = 0; x<m_data->m_width; x++)
    //      if (m_data->m_segmentedXRay[y*m_data->m_width + x] > largestGradient)
    //          largestGradient = m_data->m_segmentedXRay[y*m_data->m_width + x];

    //upper = 0.2 * largestGradient;
    //lower = 0.08 * largestGradient;

in above I've written an Algorithm to find the upper and lower threshold of canny automaticlly what you could set of course manually.
    //cv::morphologyEx(imageVector, imageVector, cv::MORPH_OPEN,     cv::Mat(5,5,CV_8UC1));

Thats where i use the Opening Filter to fill the small gaps in the edges.
int blurSize = 3;
    cv::blur(imageVector, imageVector, cv::Size(blurSize,blurSize));

I just used the smoothing filter Blur.
    bool L2gradient = false;
    cv::Canny(imageVector , imageVector, lower, upper, kernelSize, L2gradient);

Answer: What I've come up with works quite well for this particular application so I thought I would share it.
First I perform a binary filter of the image with an adjustable threshold.
Then I run a "smoothing" operation. I'm sure there is a technical term for this I don't know. I examine every pixel's neighbors (number of neighbors is adjustable) to decide whether that pixel should be black or white.
Then I grab a rectangle area (for each top, bottom, left, and right part of the image) and note the first transition (black to white or white to black) of each row(vertical)/column(horizontal).
If the number of transitions found is significantly less than the number of rows/columns in the area, there is no line.
I generate the mean and population standard deviation of these transitions.
If deviation is greater than some adjustable value, there is no line.
If deviation is less, the mean is used as the position of the line.
Comment: It would be so much better if you showed an image of what you are actually doing! You might benefit too by potentially receiving a more robust or faster method...
Comment: @MarkSetchell I've added a sample image.

Very Simple Edge Detection


How to calculate P(X=x|Y=y) using copula functions?

Question: I want to get the conditional probability of P(U=u|V=v) or P(X=x|Y=y) using copulas.However, I found that if I use the copulapdf function of Matlab, the result is bigger than 1! I don't know why. any one could help me? thank very much for your help!
the formulas are following:
Comment: Show your code, maybe? My guess is that you're obtaining PDF with copula, not the probability.
Comment: may be I know my mistake: If a probability distribution admits a density, then the probability of every one-point set {a} is zero;
Comment: Sorry, what is the different between PDF and probability? I want to know the probability of P(U=u|V=v). Thanks!
Comment: Probability is the area under [PDF](http://en.wikipedia.org/wiki/Probability_density_function). I'm suspecting that you're getting the value of PDF, not the area. That's why you should post your code.
Comment: Sorry, I don't have code. I am just constructing the formulas. Do you mean I can't get the probability of (U=u|V=v) directly. But I can get the probability of (U<u|V=v).
Comment: Show us how you construct these formulas.
Comment: Sorry, do you understand my meaning?
Answer: You probably got the problem by now: any probability of a point on real line for continuous distribution is going to be 0. So your denominator in last equation is 0.
Comment: Yes, that is my mistake. So  should I calculate the probability in an interval instead of one point?
Comment: @eric, you can compute the probability of one point for discrete distributions and discontinuous distributions (in some cases). For continuous, they're all going to be zeros, and only the intervals make a sense.
Comment: Thanks very much for your help! I think I should change the "=" to"<" or">". Thanks again!


What is the correct way to update an element in elements list?

Question: I created a list of elements and I want to update one of the list elements
This is the call to the update method:
companies_list = self.create_list("xpath", self.txt_company_name)
self.update_elem(companies_list[0], company1_name)

And this is the update method:
def update_elem(self, elem, text):
    elem.send_keys(text)

At the method I'm getting warning "Make function from method" and a suggestion "Method 'update_elem' may be 'static'"
What is the correct way to update the list element without getting warnings?
Comment: That method could indeed be static, or just a function, because it _doesn't use `self`_. Or just inline it, it's only one line anyway.
Comment: You don't use `self` in the method body so it's a function. Use `@staticmethod` and remove self to fix the warning.
Answer: Assuming you're using Pycharm, it thinks you wanted to declare the 'update_elem' as static as it does not change in the body of the method the class instance.
take a look at this answer, you basically need to add @staticmethod decorator or have 'update_elem' change the instance of the class.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: @Liorp either add `@staticmethod` decorator before `update_elem` method or have `update_elem` method change an attribute of the class - something like `self.elem.send_keys(text)` or `self.elem = elem.send_keys(text)`
Comment: What further details do i need to add?


maximum principle for harmonic functions (equivalence)

Question: If $f$ is harmonic on an open set then the maximum and minimum principle ($M$) applys to $f$. Are there non trivial known properties $A(f)$ s.t. following holds:
Let $U\subset\mathbb R^n$ open and $f:U\rightarrow\mathbb R$ then $A(f)\wedge M(f)\Leftrightarrow f$ is harmonic.
Answer: Nothing interesting in this direction. The maximum and minimum principles are so much weaker than harmonicity that one would need $A(f)$ to encapsulate harmonicity.
E.g., the composition of a harmonic function with any homeomorphism of $\mathbb{R}^n$ satisfies the maximum and minimum principles, but can be very far from being harmonic. What else would we need this function to satisfy in order to conclude it's harmonic... uh, the Laplace equation, probably.
There are nontrivial results of the form "what should be added to the mean value property to get harmonicity".
Comment: Thanks for the answer! I've just read now that any continuous function which satisfies the mean value property is smooth. Would you know a reference for that?


Drupal queue item not being processed

Question: I am creating queue items from a cronjob. But it seems they are not getting processed. Any ideas why?
Do we need to process the items separately? I mean i have created the worker class and everything.
Thanks
BR/Pratip
Comment: Unfortunately, we cannot debug a site to which we don't have access as administrators. If you showed the code, we could tell you what is wrong in the code, but that could not be sufficient to tell you why the code doesn't work on the site where you are testing it.
Answer:
Make sure cron is running on your site.
Make sure cron time is set on your QueueWorker

<code>/**
 * Create node object from the imported XML content
 *  * @QueueWorker(
 *   id = "import_content_from_xml",
 *   title = @Translation("Import Content From XML"),
 *   cron = {"time" = 60}
 * )
 */
</code>
Source: An example module to help understanding the Queue API and the Batch API in Drupal 8.
I highly recommend using Queue UI to monitor the queue from there. If it is not running, check your database log and try running the process as a batch (sometimes that is easier to troubleshoot).
Comment: Thanks for your answer. The problem was something with the annotation of my queue worker class. But for others who find a similar problem of queue execution, you can take Isaiah's advice and create this direct route to process all the queue items in batch. That will show you if there are any errors. Running a cron might not always return you the exact error. Like in my case.

Drupal queue item not being processed


ESX(i) Interface Bonding ala Linux?

Question: I'm planning to virtualize some Linux hosts that I've got, and I'm going to be putting ESXi on the physical machines. Currently, I've got two switches set up for redundancy, and I've got bonding setup in mode 1 (active/backup).
Here's the simple logical layout:

Essentially, any switch, NIC, or firewall can die and everything still maintains connectivity.
I would very much like to continue this when I move to ESXi, but I haven't seen any evidence that it's possible (in fact, Duncan Epping from Yellowbricks indicates that it might not be possible, if I'm understanding the question and answers correctly).
Since I am relatively new to this whole "bare-metal virtualization" thing, I figured I'd ask people who knew more than me.
Can you set up your NICs in ESXi to be highly available? And if so, how?
Answer: It's SO easy it's not true, you simply define your vswitches and attach two or more physical NICs to them using the GUI, each NIC is then capable of carrying the traffic from your VMs (which don't need to know that their underlying networks are protected) or the service console. There are a number of load-balancing policies to choose, from a simple failover option to ones that truly balance your traffic across as many NICs as you've assigned.
I'm sure you'll find it very easy but if you have any queries just ask ok.
EDIT - here's how it appears on one of my boxes, showing two vswitches (one for management, one for VM traffic), it really is that simple.
alt text http://www.buckley-mellor.com/phil/sf/esx4ivswitchnics.jpg
Comment: @dunxd, that method works for v3 and v4 and covers both redundant connections to the same or different switches as well as multiple-member trunks to single or multiple switches - basically pretty much any config you want :)
Comment: I also enjoy The Great vSwitch Debate.
http://kensvirtualreality.wordpress.com/2009/03/29/the-great-vswitch-debate-part-1/
Comment: That sounds super simple indeed.  I guess that this only works for redundancy - can you do bonding where each interface is connected to a different switch.

vSwitches are only on vSphere (ESX 4.0) right?  Gotta upgrade our clusters!

ESX(i) Interface Bonding ala Linux?


Programmatically create a node with a menu link

Question: I created a node programmatically with the following code.
<code>$data = array(
  'type' => 'inception_article',
  'title' => $msg->name,
  'body' => array(
    'value' => $msg->body,
    'format' => 'full_html'
  )
);

$node = Node::create($data);
$node->save();
</code>
I would now also like to create the menu link for the node, but I cannot figure out how to do that in Drupal 8.
How can I programmatically create a menu link for a node I create?
Answer: You can save menu link Separately using the below code on node save.
<code> $menu_link = MenuLinkContent::create(array(
      'title' => 'Menu Title', // Menu title is your title of menu, in this case node title
      'path' => '/path/to/node', // Menu link something like '/node/'.$nid, replace $nid with your node id
      'menu_name' => 'navigation',
      'weight' => 0,
      'bundle' => 'menu_link_content',
 ));

 $menu_link->save();
</code>
Comment: Yes Its creating the menu link, and working fine. But while editing the node its not present under  "Menu Settings". How can i Do this ?
Answer: To have the menu also on the node entity, you need to pass the link uri as entity:
<code>MenuLinkContent::create([
  'title' => 'Menu title', // Menu title is your title of menu, in this case node title
  'link' => ['uri' => 'entity:node/' . $node->id()],
  'menu_name' => 'main',
  'weight' => 0,
])->save();
</code>


Are Vector Spaces over non-commutative fields ever studied?

Question: Are Vector Spaces over non-commutative fields ever studied?
If not, why?
If they are, I'd like to learn a bit about them, could you guys recommend me a good book on the subject?
Cheers.
Comment: I thought this would be a place to start : http://www.encyclopediaofmath.org/index.php/Skew-field
Answer: The expression "vector space" is usually reserved to the case when the coefficients form a field.
When the coefficients only form a ring (such as a skew field), the corresponding structure is called a module.
Comment: And yes, modules over skew fields (aka division rings) are studied.  See e.g. https://en.wikipedia.org/wiki/Division_ring#Relation_to_fields_and_linear_algebra
Comment: @MattSamuel, I was not aware that modules over skew fields can also be known as vector spaces. All material I've ever come across would have called them only modules. I added a word "usually" to my answer to reflect the fact that it might not always be as I wrote.
Comment: Bourbaki calls a module over a (not necessarily commutative) field a vector space.
Answer: Yes, they are studied, if only because the endomorphism ring of a simple module over a (unital) ring $R$ is a division ring or skew-field, if you prefer. The term "non-commutative field" is rarely used.
Wedderburn's theorem says that a semisimple artinian ring is the product of (full) matrix rings over division rings, generally non commutative.
However, the structure of vector spaces over a division ring $D$ is quite easy: $D$ is a semisimple ring and has a unique simple module, up to isomorphisms (the same $D$ as a vector space over itself). So any module over a division ring $D$ is just a direct sum of copies of $D$, just like for vector spaces over fields.
The theorems about linear independence and bases extend to this setting and also the duality for finite dimensional vector spaces.
Comment: For the record, I think this answer is much more helpful, even ignoring the vector space module business.


Destroy instantiated prefabs with a same tag, one by one, from last instantiated to first?

Question: I am trying to destroy instantiated prefabs with a same tag, one by one, from last instantiated to first, and I am stuck on how to accomplish this.
The idea is that I want to have a custom editor, which would allow me to instantiate multiple prefabs and then "undo" the last instantiation with two GUI buttons - "Place object" and "Undo", respectively.
As of now, I am able to successfully instantiate prefabs, add the same tag to them, and then destroy them one by one, but they are getting destroyed from first to last instantiated.
The code I have so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectInstantiateControl : MonoBehaviour {

 public List<GameObject> prefabList = new List<GameObject>();
 [HideInInspector]
 public int objectSelectionIndex = 0;
 GameObject instance;

public void PlaceObject()
 {
     switch (objectSelectionIndex)
     {
         case 1:

             Debug.Log("Just received a number 1 from the editor");
             GameObject object_A = Resources.Load("Object_A") as GameObject;
             instance = Instantiate(object_A, this.transform.position, this.transform.rotation,  this.transform);

             instance.tag = "UsedObject";
             prefabList.Add(instance);

             break;

         case 2:

             Debug.Log("Just received a number 2 from the editor");
             GameObject object_B = Resources.Load("Object_B") as GameObject;
             instance = Instantiate(object_B, this.transform.position, this.transform.rotation,  this.transform);

             instance.tag = "UsedObject";
             prefabList.Add(instance);
             break;

         case 3:

             Debug.Log("Just received a number 3 from the editor");
             GameObject object_C = Resources.Load("Object_C") as GameObject;
             instance = Instantiate(object_C, this.transform.position, this.transform.rotation,  this.transform);

             instance.tag = "UsedObject";
             prefabList.Add(instance);
             break;

         case 4:

             Debug.Log("Just received a number 4 from the editor, deleting the object");

             prefabList.Remove(GameObject.FindWithTag("UsedObject"));
             DestroyImmediate(GameObject.FindWithTag("UsedObject"));
             break;
     }
 }

And the part from the editor script for GUI buttons "Place object" and "Undo" :
                     GUILayout.BeginHorizontal();

                     if (GUILayout.Button("Place object", GUILayout.Height(25)))
                     {
                         ObjectInstantiateControl myScript = (ObjectInstantiateControl)target;
                         myScript.objectSelectionIndex = 1;
                         myScript.PlaceObject()();

                     }

                     if (GUILayout.Button("Undo", GUILayout.Height(25)))
                     {
                         ObjectInstantiateControl myScript = (ObjectInstantiateControl)target;
                         myScript.objectSelectionIndex = 4;
                         myScript.PlaceObject();

                     }
                     GUILayout.EndHorizontal();

Really need help on this, any ideas or suggestions are welcome. Thanks in advance ;)
Comment: the "Undo" part looks exactly the same as the "Place object" part?
Comment: Is there a reason you're using `FindWithTag` instead of just popping the last item off of the list and destroying that one?
Answer: In this case i will choose Queue or LinkList. You can add all game object into it and management it will simple and fine in other way.
https://msdn.microsoft.com/en-us/library/system.collections.queue(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/he2s3bh7(v=vs.110).aspx


Show $nx_n \to 1$ for sequence defined by $x_{n+1}=\frac{x_n}{1+nx_n^2}$

Question: Let $a>0$. Consider the sequence $x_{n+1}=\frac{x_n}{1+nx_n^2},~x_1=a,~n\in\mathbb{N}^*$. Study the convergence of $(x_n)_{n\ge1}$ and $(nx_n)_{n\ge1}$.
It was easy for me to prove that $(x_n)_n$ is convergent with the limit equal to $0$, but couldn't find a straightforward approach for $(nx_n)_n$. I first proved that $x_n\le\frac{1}{n}$, or equivalently, $nx_n\le1$, for $n\ge2$, using induction. Then I showed that $(nx_n)_n$ is a nondecreasing sequence: $$\frac{(n+1)x_{n+1}}{nx_n}=\frac{n+1}{n+n^2x_n^2}\ge 1$$ Thus $(nx_n)_n$ is nondecreasing and upper bounded, so it is convergent with positive finite limit $l$.
Now consider $a_n=n$ and $b_n=\frac{1}{x_n}$, so $(b_n)_n$ is a positive, increasing sequence with infinite limit. We have that $$\frac{a_{n+1}-a_n}{b_{n+1}-b_n}=\bigg(\frac{1}{x_{n+1}}-\frac{1}{x_n}\bigg)^{-1}=\frac{1}{nx_n}\to\frac{1}{l}$$
By the Stolz–Cesàro theorem, we obtain the identity $l=\frac{1}{l}$, so the only possible value for $l$ is $l=1$.
The hardest part was to prove the convergence of $(nx_n)_n$, which took me a long time. I feel like I am missing an easier solution. Please let me know if there's an elegant proof for $nx_n\to1$. Thanks in advance.
Answer: Once you have shown that $nx_n \le 1$ for $n \ge 2$ you can use the general form of the Stolz–Cesàro theorem:
$$
\frac{1}{\liminf_{n \to \infty} nx_n} =
\limsup_{n \to \infty} \frac{1}{nx_n} = \limsup_{n \to \infty} \frac{1/x_n}{n} \\ \le \limsup_{n \to \infty} \frac{1/x_{n+1}-1/x_n}{(n+1)-n}
 = \limsup_{n \to \infty} n x_n  \le 1
$$
implies that $\liminf_{n \to \infty} n x_n \ge 1$, so that the limit exists and is equal to one.
Comment: @Kroki: That was my stupid error – hopefully it is correct now.
Comment: I think you forgot $^{-1}$ on the last $\liminf$
Comment: It is fixed. By the way, I find a way without using the Stolz-Cesaro theorem.
Answer: Once you have $(nx_n)_n$ converges to a limit $l>0$, suppose $l\neq 1$ : then as $\displaystyle (n+1)x_{n+1}-nx_n=\frac{x_n(1-n^2x_n^2)}{1+nx_n^2} (1)$ you get
$\displaystyle (n+1)x_{n+1}-nx_n\sim\frac{l}{n}(1-l^2)$ hence the serie $\sum ((n+1)x_{n+1}-nx_n)$ is divergent hence $(nx_n)_n$ is divergent : contradiction.
Answer: Let $a_n = \frac1{nx_n}$ then,
\begin{align}
a_{n+1} &= \frac1{n+1} \times \frac1{x_{n+1}}\\
&= \frac1{n+1} \left(\frac{1+nx_n^2}{x_n}\right)\\
&= \frac1{n+1} \left(\frac{n}{nx_n} + nx_n\right)\\
&= \frac{n}{n+1} a_n + \frac1{n+1}\times \frac1{a_n}
\end{align}
Let $b_2 = a_2$ and $$b_{n+1} = \frac{n}{n+1} b_n + \frac1{n+1}$$
Using very simple induction, one can easily prove that for $n \ge 2$, $$1 \le a_n \le b_n.$$
It remains to compute the limit of $b_n$. Indeed for $n\ge 3$
\begin{align}
b_n = \frac1n \times nb_n &= \frac1n \left(b_2 + \sum_{k=2}^{n-1} \left((k+1)b_{k+1} - kb_k\right)\right)\\
&= \frac{b_2}n + \frac1n  \sum_{k=2}^n 1 = 1 + \frac{b_2}{n} \to 1.
\end{align}
Can you finish the proof?
Answer: Motivation. Let $y_n = \frac{1}{x_n}$. Then the recurrence relation reads as:
$$ y_{n+1} - y_n = \frac{n}{y_n} $$
The continuum analog of the relation is the differential equation
$$ y' = \frac{x}{y}. $$
This can be solved by rearranging the equation in the form
$$ y\,\mathrm{d}y = x\,\mathrm{d}x,\qquad\text{or equivalently,}\qquad \mathrm{d}(y^2) = \mathrm{d}(x^2). $$
The last equality tells that the quantity $\mathrm{d}(y^2)$ is of central importance in solving the differential equation, and we can expect that the same is true for the original recurrence relation.

Actual Proof. Note that $\frac{1}{x_{n+1}} = \frac{1}{x_n} + nx_n$. Using this, we can expand $\frac{1}{x_n^2}$ as:
\begin{align*}
\frac{1}{x_n^2}
&= \frac{1}{x_1^2} + \sum_{k=1}^{n-1} \biggl( \frac{1}{x_{k+1}^2} - \frac{1}{x_k^2} \biggr)
\\
&= \frac{1}{x_1^2} + \sum_{k=1}^{n-1} \biggl[ \biggl( \frac{1}{x_{k}} + kx_k \biggr)^2 - \frac{1}{x_k^2} \biggr]
\\
&= \frac{1}{x_1^2} + \sum_{k=1}^{n-1} \bigl( 2k + (kx_k)^2 \bigr)
\\
&= a^{-2} + n(n-1) + \sum_{k=1}^{n-1} (kx_k)^2 \tag{1}\label{e:int}
\end{align*}
Here, $a = x_1$. From this, we observe the following:

Using $\eqref{e:int}$ and noting that $x_n > 0$ for all $n$, we get
$$ \frac{1}{x_n^2} \geq a^{-2} + n(n-1), \qquad\text{i.e.,}\qquad nx_n \leq \frac{n}{\sqrt{a^{-2} + n(n-1)}}. \tag{2}\label{e:u} $$

$\eqref{e:u}$ shows that $C := \sup_{n\geq 1} nx_n$ is bounded. Hence by $\eqref{e:int}$ again,
$$ \frac{1}{x_n^2} \leq a^{-2} + n(n-1) + C^2(n-1). \tag{3}\label{e:l} $$

Combining $\eqref{e:u}$ and $\eqref{e:l}$, we get
$$ \frac{n}{\sqrt{a^{-2} + n(n-1) + C^2(n-1)}} \leq nx_n \leq \frac{n}{\sqrt{a^{-2} + n(n-1)}}. $$
Therefore the desired conclusion follows by the squeeze lemma.


Ridge regression -- why does the model only care to control large outliers?

Question: One of the purposes of ridge regression is to curb the effects of outliers which may cause the regression coefficients to be so large and hence cause a highly biased model.
That's why the constraint $\Sigma\beta_j^2<s$ is imposed, forcing the coefficients to not exceed a certain value.
Here is my issue. An outlier could be a value that is either too large or too small. I think this should mean than outliers could cause the $\beta_j$'s to be too small or too large. The formulation of this constraint inequality seems to only care about controlling those outliers which might make the $\beta_j$'s too large.
I believe Ordinary Least Squares Regression equally suffers from the effects of very small outliers.
Can someone please explain if or how Ridge regression controls the "small" outliers as well?
Comment: its not for outliers at all. you are right that outliers have a disproportionate effect on the regression coefficients. but  ridge regression is to prevent large coefficients mainly from collinearity.
Comment: By "small outlier" do you mean "negative number with large absolute value" or "small in absolute value"?
Comment: Or maybe, more precisely "far away from the mean in the positive direction, or in the negative direction" is what you mean?
Comment: If the signal values are 1, 2, 4, 2, 2, 1, 3, 5, 100, -200; then 100 and -200 are candidates for being outliers. That's my context of an outlier.
Answer: The ridge estimator is very susceptible to outliers, much like the OLS estimator. The reason for that is that we still depend on the least squares minimization technique and this does not allow large residuals. Hence the regression line, plane or hyperplane will be drawn towards the outliers.
There has been considerable work in recent years in order to "robustify" ridge regression. In case you want to read further, here is one paper that advocates an approach based on M-estimators.

Maronna, Ricardo A. "Robust ridge regression for high-dimensional data." Technometrics 53.1 (2011): 44-53.
Answer: Ridge regression is a modification of linear regression. Linear regression is the best linear unbiased estimator (BLUE). They key word is "unbiased." Linear regression should give the smallest mean square error (MSE) of any unbiased linear estimator. Ridge regression adds bias in exchange to reduce variance, thus creating a biased estimator with potentially lower MSE. It does this with a regularization or "smoothing" parameter to shrink the coefficients as you describe. This has the effect of decorrellating variables for differering values along the parameter.
Techniques that are based on the squared loss function are particularly sensitive to outliers. To alleviate this, least absolute square error or even least median squares can be used as the loss function. However, ridge regression by itself is not meant to be used to reduce the effect of outliers because it is just a slightly modified version of linear regression estimated with an identical loss function, but penalized to adjust some of the assumptions in the linear regression model.  There is nothing here that explicitly deals with outliers.
Comment: @orbis I would disagree with "Multicollinearity can cause one coefficient to be large and the other small". Its more that multicollinearity can cause a large negative and (an 'offsetting') large positive coefficient [I assume throughout that two or more inputs are positively correlated with each other]. since ridge regression penalises the squared coefficients ridge regression favours smaller same sign weights (ie averaging inputs)
Comment: @JohnK  But my question would still hold , albeit slightly modified. Does multicollinearity only cause regression coefficients to be large? cant it cause them to be so small as well? If so, ridge regression only seems to care about the former problem.
Comment: The regularization/coefficient path from ridge regression is a continuous path that leads to the least squares coefficients. It becomes similar to a feature reduction technique, reducing or even removing the influence of correlated variables. The maximum value the ridge regression coefficients should take is the least squares estimate.
Comment: Multicollinearity can cause one coefficient to be large and the other small. Ridge Regression coefficient path would start with only one of these variables and then as it moves towards the LS coefficients it should add the less relevant correlated variable.


To find the Joint distribution

Question: $f(x,y)=(1+x^3\,y^3)/4 \quad \Big[(x,y)\in[-1,1]^2\Big]$
How to find the joint distribution of $f(x^2,y^2)$??
Well this one is completely new for me as I am a begginer. Any help would b appreciated.
Comment: The support for the pdf is required. $~$ Is it $(x,y)\in[-1;1]^2$?
Comment: Have you tried applying the Jacobian change of variables theorem?
Comment: @GrahamKemp is there another way??
Comment: Double integrate to find $\mathsf P(X^2<u,Y^2<v)$, then double differentiate with respect to $u,v$.
Answer: Double integrate to find $\mathsf P(X^2\leqslant u,Y^2\leqslant v)$, then double differentiate with respect to $u,v$.
Hint: Actually, use the Fundamental Theorem of Calculus to avoid integrating and differentiating back.   It should then simplify greatly in just a few steps.
$\begin{split}\qquad f_{\small X^2,Y^2}(u,v)=~&\begin{vmatrix}\dfrac{\mathsf d^2 \mathsf P(X^2\leqslant u, Y^2\leqslant v)}{\mathsf du~\mathsf d v\hspace{16ex}}\end{vmatrix}\\[1ex]=~& \begin{vmatrix}\displaystyle\dfrac{\mathsf d^2 ~~~~~}{\mathsf d u~\mathsf d v}\int_{-\surd u}^{\surd u}\int_{-\surd v}^{\surd v} \dfrac{1+(xy)^3}{4}~\mathsf d y~\mathsf d x\end{vmatrix}\mathbf 1_{(u,v)\in[0;1]^2}\\[1ex]=~& \phantom{ \dfrac{1}{4\surd(uv)}\left(\dfrac{1+(uv)^{3/2}}{4}+\dfrac{1-(uv)^{3/2}}{4}+\dfrac{1-(uv)^{3/2}}{4}+\dfrac{1+(uv)^{3/2}}{4}\right)\mathbf 1_{(u,v)\in[0;1]^2}}\\ =~&\phantom{\dfrac{1}{4\surd(uv)}\mathbf 1_{(u,v)\in[0;1]^2}}\end{split}$

To find the Joint distribution


Contagem de Pagina

Question: Pessoal estou tentando fazer um sistema de contagem de paginas,que ele conta o total de paginas e qual pagina atual o usuario se encontra.
Eu consegui fazer a contagem total de pagina porem não estou conseguindo achar um modo para mostra a pagina atual dele ,tentei usar o metodo de position() mas nao consegui.
var arrMenuInterno = [
{ titulo: "Introdução",
    telas: [
        {arquivo: "ambev_VPO_gente_sld002.swf", tipo:""},
        {arquivo: "ambev_VPO_gente_sld005.swf", tipo:""},
        {arquivo: "ambev_VPO_gente_sld007.swf", tipo:""},
        {arquivo: "ambev_VPO_gente_sld009.swf", tipo:""},
        {arquivo: "ambev_VPO_gente_sld010.swf", tipo:""}

    ]
}

];
for(var i = 0;i < arrMenuInterno.length;i++){
            _totalTelas = arrMenuInterno[i].telas.length;

        }

        $("#qtdTelas").html(+ localizaTelaAtual + " de " + _totalTelas + "");

Answer: Você pode utilizar a atributo Data do HTML5 para armazenar os índices do seu array de páginas. Segue um exemplo de implementação.

var arrMenuInterno = [
{ titulo: "Introdução",
    telas: [
        {arquivo: "ambev_VPO_gente_sld002.swf", tipo:""},
        {arquivo: "ambev_VPO_gente_sld005.swf", tipo:""},
        {arquivo: "ambev_VPO_gente_sld007.swf", tipo:""},
        {arquivo: "ambev_VPO_gente_sld009.swf", tipo:""},
        {arquivo: "ambev_VPO_gente_sld010.swf", tipo:""}
    ]
}]

function getNextContent(){
  var $conteudo = $("#conteudo");
  var titleIndex = $conteudo.data("titleIndex");
  var fileIndex = $conteudo.data("fileIndex") + 1;
  var content = arrMenuInterno[titleIndex].telas[fileIndex];
  var countDescription = " [" + fileIndex + " de " + arrMenuInterno[titleIndex].telas.length + "]";

  if (content !== undefined){
   $conteudo.data("fileIndex", fileIndex);
   var $span = $("");
   $span.append(content.arquivo + countDescription);
   $("#conteudo").html($span);
  }
}

function getPreviousContent(){
  var $conteudo = $("#conteudo");
  var titleIndex = $conteudo.data("titleIndex");
  var fileIndex = $conteudo.data("fileIndex")  - 1;
  var content = arrMenuInterno[titleIndex].telas[fileIndex];
  var countDescription = " [" + fileIndex + " de " + arrMenuInterno[titleIndex].telas.length + "]";

  if (content !== undefined){
   $conteudo.data("fileIndex", fileIndex);
   var $span = $("");
   $span.append(content.arquivo + countDescription);
   $("#conteudo").html($span);
  }
}

.content {
  width: 100%;
  background-color: black;
  vertical-align: middle;
}

#conteudo {
  display: table-cell;
  height: 150px;
}

span {
  color: #fff;
}

   Introdução

Anterior
Próximo

Contagem de Pagina


I am trying to query a firebase database in while the user is typing, but I keep getting this error

Question: So I found this code to query your database while the user is still typing, but the code was outdated and I've been updating it, but there's an error that I don't know how to fix.
func findFriends(text: String) -> Void {

    let ref = Database.database().reference()
    ref.child("users").queryOrdered(byChild: "username").queryStarting(atValue: text).queryEnding(atValue: text+"\u{f8ff}").observe(.value, with: { snapshot in

        let user = User()
        let userArray = [User]()

            for u in snapshot.children{
                user.name = u.value!["name"] as? String
        }
    })

I get an error in the last line and it says:

Value of type 'Any' has no member 'value'
Comment: Seems like the same issue as in [this question](https://stackoverflow.com/q/42026284/4916627) although thats a different swift version.
Comment: Possible duplicate of [Type 'Any' has no subscript members (firebase)](https://stackoverflow.com/questions/39136026/type-any-has-no-subscript-members-firebase)
Comment: @AndréKool Looks similar, but I'm not to sure how i would implement this with my for loop.
Answer: The elements in snapshot.children are of type Any, which doesn't have a value property. To get at the value property you need to cast u to a DataSnapshot:
for userSnapshot in snapshot.children{
    let userSnapshot = userSnapshot as! DataSnapshot
    guard let dictionary = userSnapshot.value as? [String: Any] else { return }
    user.name = dictionary["name"] as? String
}

Alternatively, you put the cast in the loop:
for userSnapshot in in snapshot.children.allObjects as? [DataSnapshot] ?? [] {
    guard let dictionary = userSnapshot.value as? [String: Any] else { return }
    user.name = dictionary["name"] as? String
}

Comment: I get this error when I try the first code. " Ambiguous reference to member 'value' "


Does Neuton framework offer better ML algorithms than the ones currently known to the public?

Question: I came across an article about new proprietary 'Neuton' framework.
I can't find educated opinions from professionals in the field. What the framework promises feels 'too good to be true'. Is it?
Answer: There is not enough information freely available to make an intelligent discussion on the topic.
That said, do not take any benchmarks seriously unless coming from an independent and authoritative source. For example, on Neuton's homepage benchmarks, XGBoost is always better than Catboost; but if we check Yandex's arXiv paper on Catboost, Catboost is always better than XGBoost. Clearly, these two scenarios are contradictory on face value! While I do not believe anyone intentionally obscures the truth, reality might be a bit too complex to justify statements like: "in the vast majority of cases, (algorithm X) achieves a higher level of accuracy than algorithms traditionally used for regression and classification problems." The marketing department might had a say there too... ;)
Don't stop studying ML just yet.
Comment: (For the record I have voted this question to close as primarily opinion-based.)


multilevel logistic regression via maximum likelihood in R

Question: I want to develop a mixed effect logistic regression in R using likelihood function and compare the results (estimated parameters) with the output of glmer function. I couldn't find a good material for the likelihood formulation. So, just explain my panel dataset and put the code I have written for simple logistic regression. My panel dataset is "try" and the response variable is "happy" which is binary and has two levels (yes=1 or No=0). I have started with adding one independent variable (x) to model. I have ïd" column in my data which shows the observations who belong to same individual (observations are nested within individuals).  Here is the code for binary logit model without random effect. How can I add random effect for id column to my code and get same results as glmer gives.
my data is something like:

happy
x
id

0
1
1

0
2
1

0
1
2

1
1
2

0
1
3

1
2
3

0
1
2

0
1
3

1
1
3

.
.
.

.
.
.

'LL<-function(b_00,b_11,b_22){
     data<- try%>%mutate(p=1/(1+exp(-b_00-b_11*x)))
     data<-data%>%mutate(loglik=happy*log(p)+(1-happy)*log(1-p))
     return(-sum(data$loglik))}'

I want to write the code with same results as below function:
model = glmer(happy~x+ (1 |id),
          data=try, family = binomial)

Comment: Thanks for the reference Ben. I have done this for continuous response variable and got same results as lmer function. Just want to add random error to the likelihood function and give the likelihood to a optim() to get the results
Answer: Unlike for linear mixed models, the likelihood doesn't collapse to a penalized sum of squares that can be computed by closed-form linear algebra. The details of glmer's algorithms are described in this incomplete manuscript (it builds on the 2015 Bates et al. J. Stat. Software paper, which you may need to read for some of the notation).
The implementation of the likelihood involves a penalized iteratively reweighted least squares (PIRLS) step (described in the manuscript linked above), which has been implemented by Steve Walker in pure R here; that will be easier than reading the C++ code in the lme4 package ...


Dynamic Menu from folders

Question: In my program I want to create a menu with submenus based on a folder and its subfolders.
The first function menu_fromfiles works fine.
But the second function menu_fromfolders keeps giving me an error: submenu does not exist - and I can't figure it out.  Any clues?
Here is my code:
 #SingleInstance force

RButton::
menu_fromfolders("filelist", "File List", "c:\test", "*.txt", "thismenu")
menu, thismenu, show

Return
-------------------------------------------------------------------

menu_fromfolders(submenuname, menutitle, whatdir, filemask="*", parentmenu="", whatsub="DONOTATHING"){
    global
        loop, %whatdir%\*, 1, 0
        {
            if(file_isfolder(A_LoopFileFullPath)){
                menu_fromfiles(a_loopfilename, a_loopfilename, A_LoopFileFullPath, filemask, "", whatsub)
                menu, %submenuname%, add, %a_loopfilename%, :%a_loopfilename%
            }else{
                menu, %submenuname%, add, %a_loopfilename%, %whatsub%
            }
        }
        if(parentmenu){
            menu, %parentmenu%, add, %menutitle%, :%submenuname%
        }
        return submenuname
}

menu_fromfiles(submenuname, menutitle, whatdir, filemask="*", parentmenu="", whatsub="DONOTATHING"){
        loop, %whatdir%\%filemask%, 0, 0
        {
            menu, %submenuname%, add, %a_loopfilename%, %whatsub%
        }
        if(parentmenu){
            menu, %parentmenu%, add, %menutitle%, :%submenuname%
        }
        return submenuname
}

;returns true if the item is a folder, false if is a file
file_isfolder(whatfile){
    lastchar := substr(whatfile, 0, 1) ;fetch the last character from the string
    if(lastchar != "\")
        whatfile := whatfile . "\"
    if(fileexist(whatfile))
        return true
}

;empty command for the menu title
DONOTATHING:
return

Here is a more detailed error message:
Error in ...script.ahk
Submenu does not exist

-->menu, %submenuname%, add, %a_loopfilename%, :%a_loopfilename%

[update]
Please see my solution below.  You can find the complete and refined script here: http://www.autohotkey.com/board/topic/95219-dynamicfilemenuahk/
Comment: Please post a more detailed error message. Post a sscce. You are missing the function `file_exist(whatdir)`.
Comment: Sorry about that.  I added both of what you requested.
Comment: Let me rephrase that: write an example that reproduces the error, but is as small as possible.
Comment: Okay, this should work if you paste it into a script file - there are no more dependencies.
Comment: I've gone over it quickly, i think your handlers,submenus.. are mixed up/missing.
Comment: Thanks for looking.  I've tried different combinations and can't get it to work.  The error is only in the two lines just below `if(file_isfolder(A_LoopFileFullPath)){`  - if I comment them out, the menu_fromfolder function will at least display the files.  I just can't get it to create the submenus from the folders.  I've already spent hours.
Comment: Are you aware that `lastchar := substr(whatfile, 1, 1)` extracts not the last, but the **first** character? I don't quite get what you're doing at that point.
Comment: Well, I had it all wrapped up in another function, and in my haste to simply things for this post, I miscoded it.  It's supposed to test the last character for a slash.  I fixed it.
Comment: Your code actually works on my machine. It shows every dir, subdir and file without an error.
Comment: Strange! It works for me too as long as I don't parse the folder that contains my script includes.
Comment: Actually, it works on some folders and not on others; I can't figure it out.
Comment: Look for differences between the working and the non-working ones, I bet there's a pattern. Maybe it has something to do with illegal chars / special chars.
Comment: The submenu names are taken from the folder names themselves.  How can an illegal character be gotten from the name?
Answer: Ah, figured it out.
When the menu_fromfiles loop searches for files, if no files matching the mask are discovered, it does not add anything to the menu.
Now, you can't create a submenu with nothing in it. So if no items were added to the submenu, no submenu is created.
It was working intermittently only for directories that had folders containing files matching the mask.  When there were no matching files (or the directory was empty), the function was trying to add a non-existent menu.
The solution is to add a method of detecting that a menuitem was, indeed created:
menu_fromfiles(submenuname, menutitle, whatdir, filemask="*", parentmenu="", whatsub="DONOTATHING"){
        menucount := 0
        loop, %whatdir%\%filemask%, 0, 0
        {
            menu, %submenuname%, add, %a_loopfilename%, %whatsub%
            menucount++
        }
        if(parentmenu && menucount){
            menu, %parentmenu%, add, %menutitle%, :%submenuname%
        }
        return submenuname
}

If anyone is interested, I refined this code to display all the folders.  You will find the full script here: http://www.autohotkey.com/board/topic/95219-dynamicfilemenuahk/

Dynamic Menu from folders


What can be said about the smallest $N$ where $N^2 \not\equiv 1$ mod $p_x$; for all $x : 1 \leq x \leq y$

Question: Choose any value for $y : y \in \mathbb{N}$
Let
$N(y)$ be the smallest natural number that satisfies the following system of quadratic congruences:
$N^2 \not\equiv 1$ mod $p_x$; for all $x : 1 \leq x \leq y$.
($p_x$ are consecutive prime numbers)
Is it true that
$N(y) \leq p_y^2$
Answer: It's likely (although of course not proven) that there is always a twin prime pair $q, q+2$ with $p_y < q < p_y^2-1$, in which case
$N(y) \le q+1 < p_y^2$.  Conversely, all prime factors of $N(y)\pm 1$
are greater than $p_y$, so if $N(y) < p_y^2$, $N(y)\pm 1$ will be twin primes.  Thus your conjecture implies that there are infinitely many twin primes.  Don't expect to see a proof any time soon!
Empirically, $N(y)$ tends to be quite close to $p_y$.
Comment: I'm wondering if the problem is accessible by working from the fact that the natural numbers up to $p_y \times p_{y-1}$ consist of all unique values of ($N$ mod $p_{y}$, $N$ mod $p_{y-1}$)-"space". By representing this space as a cuboid, and *trimming the width*, we eradicate positions where $N^2 \equiv 1$ mod $p_y$ and we are left with another cuboid. If we trim it enough we are left with a cuboid of width $p_{y-1}$. By rotating the rows individually, we can create a cuboid whose left and right edges represent $N^2 \equiv 1$ mod $p_{y-1}$. Trim as before and repeat for all primes....
Comment: We can continue this as long as we are dealing with prime numbers $p_z : p_z>2z$. Once we reach a prime number in which that property is not true for, hopefully we can prove by exhaustion that there exists anyway, an $N: N^2 \not \equiv 1$ mod $p_i$, for all $i: 1 \leq i \leq z$ ???
Comment: As I mentioned, if you could prove your conjecture you would have proved that there are infinitely many twin primes.  This is a very famous conjecture on which many very smart people have worked very hard, and it's still out of reach.  You're not likely to succeed by elementary methods.


Dependant Dropdowns

Question: I'm working on a project in order to be able to make a bespoke customizer for PC hardware in order to ensure everything is compatible. I am able to make the dropdowns and have validated that they can both be submitted successfully, although I need to pull 2 values and store them in 2 variables so I can use them to A (Store the ID of the CPU) and B (Store the appropriate socket).
<code><select id="pcat" name="pcat" onchange="autoSubmit();">
    <option value="">-- Select Parent Category --</option>
    <?php
    //select parent categories. parent categories are with parent_id=0
        $sql = "SELECT * FROM `cpus` ORDER BY `cpus`.`CPUName` ASC";
        $result = dbQuery($sql);
        while ($row = dbFetchAssoc($result)) {
            echo ("<option value=\"{$row['CPUID']}\" " . ($pmenu == $row['CPUID'] ? " selected" : "") . ">{$row['CPUName']} ({$row['Cores']} Cores | {$row['Threads']}  Threads | {$row['Frequency']}GHz)</option>");
        }
    ?>
</select>
</code>
I would like to also add in the ability to store a variable called $sockets which would relate to the row called 'CPUSoc' in my database implementation.
Comment: I suggest searching on Google first how to make a dependant dropdown with PHP, JavaScript (Ajax) and MySQL. There should be tutorials out there that explains the basics
Comment: Already tried to use Google but I haven't been able to find appropriate articles and the ones I have found don't cover what I require (or at least from what I have read)
Answer: Figured this out myself in a kind of... Strangely easy but stupid workaround. All I needed to do in order to pull out an additional variable was to have another query running with the CPUID like so:
<code>$sql = "SELECT * FROM cpus WHERE CPUID = $cpumenu";
$result = dbQuery($sql);
while ($row = dbFetchAssoc ($result)){
    ($socket = $row['CPUSoc']);
}
</code>
And then using the stored $socket variable in the following query to use the stored result in the next query:
<code>$sql = "SELECT * FROM `motherboards` WHERE Socket = '$socket' ORDER BY `motherboards`.`MoboName` ASC";
</code>

Dependant Dropdowns


Question about proof for intersection of a set family with union of a set

Question: I am studying this proof and there are a few things I need help understanding.
Let $A$ be a set and $B_i$, for $i \in I$ be a family of sets
Prove
$ A \cup (\cap_{i \in I}B_i)$=$\cap_{i \in I}(A \cup B_i)$
proof: suppose $x \in A$ then $x \in (A \cup B_i)$ for all $i \in I$
Also if $x \in \cap_{i \in I}B_i$, $x \in (A \cup B_i)$ for all $i \in I$
thus $x \in \cap_{i \in I}(A \cup B_i)$.
Can someone please explain to me what's in the set  $ \cap_{i \in I}(A \cup B_i)$.
Is it the intersection of $A$ included with the intersection of all the $B_i's$
or is it the intersection of all the $B_i's$ with the union of A
In other words is it the intersection of B included with the intersection of the family
Or is it the intersection of the family added with the set A??
I don't get most why the set A can be incorporated in the parenthesis with the intersection of the family!
It just doesn't seem right to me, I need to know if the notation $\cap_{i \in I}B_i$, the intersection of all these sets  is restricted to the family.
Comment: $\cap_{i \in I}(A \cup B_i)$ is the set of all elements in $(A \cup B_i)$ for each $i\in I$
Comment: @saulspatz so A is not included in any form of intersection right? Is the notation for the intersection restricted to intersecting the family of sets or is A also in that intersection?
Comment: I don't understand what you are asking.  What does "A is not included in any form of intersection" mean?
Comment: @saulspatz I was wondering if the set $ \cap_{i \in I}(A \cup B_i)$ contains either the elements from the intersection of the family intersected with the elements in the loan set A, or is it the set intersection of the family included with every element of the set A?
Comment: @saulspatz I would assume its the latter
Comment: I still don't know what you mean.  What is a "loan set"?  Look at Corman's answer for an explanation.
Comment: @saulspatz I just call A a loan set since it is not in the family
Answer:
I don't get most why the set A can be incorporated in the parenthesis with the intersection of the family!

How you state the question: "Let $A$ be a set and $B_i$, for $i\in I$ be a family of sets", it is not clear, why you can make 'sense' out of $A\cup B_i$ or other set operations. I suppose, that $A$ and $B_i$ are subsets of the same set $X$. Else you can not really compare these sets in general, and the results might be trivial.
So you might check that first.
$\bigcap_{i\in I} (A\cup B_i)$ is the intersection of $(A\cup B_i)$ for every $i\in I$.
For example: Take $I=\{1,2,3\}$ And let $A, B_1,B_2, B_3\subseteq X$ with $X=\{1,2,3\}$. And $A=\{1,2,3\}, B_1=\{1\}, B_2=\{1,2\}, B_3=\{1,2,3\}$, then:
$\bigcap_{i=1}^3 (A\cup B_i)=(A\cup B_1)\cap (A\cup B_2)\cap (A\cup B_3)=A$.
The example given is not really insightful, but I just wanted to show, how this intersection works.
Answer: $x\in\bigcap_{i\in I}(A\cup B_i)$ exactly when $\forall i\in I~[x\in(A\cup B_i)]$. That is $\forall i\in I~[x\in A\lor x\in B_i]$.
In words: For all $i$ in the indices $I$, $x$ is in $A$ or $x$ is in $B_i$.
Comment: That is what it says, yes.   Essentially: $(A\cup B_1)\cap(A\cup B_2)\cap\cdots$
Comment: So essentially $ \cap_{i \in I}(A \cup B_i)$ is all the elements in the intersection of all the sets in the family added with all the elements of the set A?


Store a digit larger than 9 in array

Question: I am wondering if it is possible to store a digit larger than 9 in an array. For example is
Int myarray[0] =  1234567898
From what I know about arrays they can only be integers in which the highest number will be a 9 digit number.
Is it possible to change the data type or have a larger digit. If not what are other ways to do it
Comment: I... you... I mean... um.... what?
Comment: did you try long datatype?
Comment: http://stackoverflow.com/a/589684/402706 - there are more datatypes than just int.
Comment: The question is poorly phrased but I see no reason to believe that the OP is an idiot. He wants to store >32bit and wants to know if there's a technique for that using an array or a larger data type.
Comment: @PhilippClaßen 10^9 has ten digits.
Comment: Yes.  I have an array int term[100] . term[44] = 701408733 but when term[45] it is suppose To equal 1134903170, it does not. I've tried double term[100] but I get compiler error and long data type gave me the same result as int
Comment: I guess maybe somebody gave the OP a cheap rule of thumb that int can safely store any number up to 9 digits, ie 999,999,999. This would be a mostly true cheap rule of thumb if you don't want to memorize approximate powers of 2.
Comment: Decimal has no digit larger than 9. If you mean hexadecimal then even char can contain all of its digits. A 9-digit number is not *a digit*
Answer: It is quite possible. C++11 adds support for long long which is typically 64bit (much larger) that can store up to 19 digits and many compilers supported it before this as an extension. You can store arbitrarily large numbers in an array provided the array is large enough and you have the requisite mathematics. However, it's not pleasant and an easier bet is to download a library to do it for you. These are known as bignum or arbitrary size integer libraries and they use arrays to store integers of any size your machine can handle.
It's still not possible to express a literal above long long though.
Comment: He does, it's just poorly phrased.
Comment: Good information, though I dont think this really answers the question. I dont really think the asker understands that integral types are bits at all. You may want to introduce what an int actually is first.
Comment: I assumed otherwise from the "I am wondering if it is possible to store a digit larger than 9 in an array." But now I read it again I think you could be right, looking at the second paragraph.
Comment: It's pretty poorly written but I think he does know what he's talking about and what he wants.
Comment: If you download a "bignum" library, it might very well add bignum literals. You'd have to check the documentation.
Answer: A 32bit int has a max value of 2147483647 - that is 10 digits.  If you need values higher than that, you need to use a 64bit int (long long, __int64, int64_t, etc depending on your compiler).
Answer: I am afraid that your idea that ints can only represent a single decimal digit is incorrect. In addition your idea that arrays can only hold ints is incorrect. An int is usually the computer's most efficient integral type. This is on most machines 16, 32 or 64 bits of binary data, thus can go up to 2^16 (65k), 2^32 (4million), or 2^64(very big). It is most likely 32 bits on your machine, thus numbers up to just over 4million can be stored. If you need more than that types such as long and long long are available.
Finally, arrays can hold any type, you just declare them as:
type myarray[arraysize];

Store a digit larger than 9 in array


Is there a meaningful distinction between "direct" and "iterative" methods for solving equations?

Question: I'll motivate this question with an example.
The Abel-Ruffini theorem states that there is no general "formula" for the roots of polynomials of degree greater than 4. (Specifically it states that there is no solution that can be expressed in terms of radicals.) This lack of a direct formula means that, in order to compute the roots for e.g. a generic quintic, we have must resort to iterative root-finding algorithms.
The distinction occurs in other problems as well, such as in linear algebra. "Direct" techniques use a "formula", whereas "indirect" techniques iterate until convergence. Same thing for the solutions of ordinary linear differential equations—which have direct "formulas" in terms of complex exponentials—and other systems, which don't.
But as much as I like to pretend I understand that, I simply don't understand the distinction between direct and iterative methods. The way I see it, pretty much every numerical method is iterative—even computing square roots requires an iterative method such as Newton's method in order to converge to the answer with the error bounded by a desired tolerance ϵ. I just don't see why it's such a big deal that there is no "formula" for quintics—even if there were, the computer would still have to use an iterative method like Newton's method until it converged anyway. And I'm not even sure how to make a meaningful definition for the word "formula" to distinguish between the two in the first place.
So where exactly is the distinction and why is it such a big deal?
Comment: The distinction is exactly what you say in your question: an iterative method is not a formula expressed in radicals. If I say $x=1+\sqrt 2$ I have expressed $x$ using a formula expressed in radicals. If I say "$x$ is the limit of $x_{n+1}=f(x_n)$ when $x_0\in[-1, 2]$, I haven't.
Comment: @JackM: That addresses the distinction but not why it's a big deal (or even a useful or interesting one to make at all), at least from a numerical standpoint.
Answer: I wouldn't agree that direct techniques always use a "formula". For instance, in solving linear systems of equations "directly", one typically doesn't use a closed-form solution, but instead something like LU or Cholesky decomposition.
Iterative solvers, on the other hand, would be things like Gauss-Seidel iteration, SOR (successive over-relaxation), Krylov subspace methods like conjugate gradients, or multilevel methods.
So what's the big difference? In the case of linear systems, I'd say the following are two of the main differences:
With a direct method, you have to do a certain amount of work, and then you obtain your solution. For instance, if you're doing LU factorization, you can't stop halfway through and say "alright, that's good enough". (Although there is something called incomplete LU, but it's actually used in iterative methods!) To get a solution, you need to run the algorithm to the end. Typically, the solution you get will then be close to the exact one.
With iterative methods, you always update your old guess and get (hopefully) a bit closer to the true solution. This means that you can decide how much work you want to invest depending on how accurate you need your solution. For instance, CG is known to converge to the exact solution in $n$ steps for a matrix of size $n$, and was historically first seen as a direct method because of this. However, after a while people figured out that it works really well if you just stop the iteration much earlier - often you will get a very good approximation after much fewer than $n$ steps. In fact, we can analyze how fast CG converges. The end result is that CG is used as an iterative method for large linear systems today.
The second big difference is that, for a direct method, you generally need to have the entire matrix stored in memory. Not so in iterative methods: here, you typically only need a way to compute the application of the matrix to a vector, i.e., the matrix-vector product. So if you have a very large matrix, but you can relatively quickly compute its application to a vector (for instance, because the matrix is very sparse or has some other kind of structure), you can use this to your advantage.