Probability of event given evidence

Question: We have a stable with 4 empty spots for horses, A1, A2, A3, A4. We also have 5 horses of different sizes, H1 is size 5, H2 is also size 5, H3 is size 8 and H4 is size 9 and H5 is size 6.
We know that H5 has a 4/5 possibility of occupying a spot and H3 has a 1/5 possibility of occupying a spot.
We know that at a specific point in time, the time of the incident, H2 was occupying A1 and that the sum of the sizes of all stable spots is 23.
Furthermore, we assign a size of 5 to an unoccupied space, so say if A1 is occupied by H2, A2 is empty, A3 is empty and A4 is occupied by H3, then the overall size is 5+5+5+8=23.
The question is, what are the possible contents of the stable at the time of the incident?
Answer: Well, $H_2$ is in $A_1$. I don't see any way to get $23$ using $H_4$ or $H_5$, but we need $H_3$ in one of the places. Then, $H_1$ is in one of the other two places, or not.
So, there are $9$ possibilities. $A_1$ always has $H_2$. $H_3$ is in one of the three remaining spots. For each of these, $H_1$ can be in either of the two remaining positions, or absent entirely.
(The probabilities in the second paragraph appear to be inconsequential to solving the problem.)
Comment: Hi, thanks for the answer. Why are they inconsequential? 4/5 possibility of occupying the spot = the horse is in a stable spot 4/5 days a week. We don't know if at the time of the incident the horse is there or not...
Comment: Also, if I were to write this in mathematical notation, how would I go about it?
Comment: You asked for *possible* contents of the stable at the time of the incident. None are especially *likely* given the high probability assigned to $H_5$, but the sum of sizes restriction doesn't support using $H_5$. (There's no way to use exactly $3$ of $(5,5,5,8,9)$ to add up to $17$.) As for mathematical notation, you're just enumerating configurations, so pick a way that's clear.
Comment: If we know that there is only 9 possibilities of the sum being 23, how can we assign a probability to that? Is it enough by saying all the possible outcomes are n! so this possibility is 9/n!?
Comment: You didn't ask for probability; you asked for possible combinations.
Comment: Yes but I cannot just say I thought about it and it's 9 possibilities. When I say possible/probable contents I mean I need to express this in a mathematical way.
Comment: If you have other questions you need to work through, then I'm not sure what they are. If you are looking for probabilities, then you need to make assumptions, or you need more information. If you need just to state possibilities, then just reason it through like l did. There's nothing wrong with that. But I'm not understanding what you really need, sorry.

Probability of event given evidence


How to Facebook login with registration

Question: I am new in Ruby on Rails And i am using Ruby 1.9.3 and Rails 3.2.12
I want to user login registration with face book.
I am using omniauth for facebook login.
if i am login as facebook user the facebook given error
Error
App Not Setup: The developers of this app have not set up this app properly for Facebook Login.
i have create tow app also in facebook.
Fitst App
And Follow the rules:-
Domain name : localhost
Choose website section:
Site Url: localhost:3000/ with http
Second App
And Follow the rules:-
Domain name : demo.com
Choose website section:
Site Url: demo.com:3000/ with http
Note:
I have change my host name locahost to demo.com
My local site working fine with localhost:3000/ and demo.com:3000/
facebook given same error in every App
Error
App Not Setup: The developers of this app have not set up this app properly for Facebook Login.
please help
Comment: Have you disabled sandbox mode …?
Answer: I have seen this happen when the app is still in sandbox mode and the Facebook user trying to log in has not been given authorisation to use the app.  In the app admin page on Facebook, make sure that the user trying to log in is listed on the Roles page/tab as an admin or developer or tester.  Alternatively, if you want anyone to be able to log in, turn off sandbox mode (make it "available to the general public" on the "Status and Review" page in app admin on Facebook).
Also, double-check those urls!  By the way, when you say "demo.com:3000/ with http" I assume you mean the url is "http://demo.com:3000/"?
I set up things so that I have a single Facebook app set up for a rails app, with a single domain under "App Domains" e.g. mydomain.com.  Then I have live/staging servers like www.mydomain.com and staging.mydomain.com and on my local machine I have dev.mydomain.com as an alias for localhost.  Note that I don't bother defining separate Websites for each of my subdomains for the App; I just have the production URL listed.
Comment: Thanks! I had the same problem and this helped. Wish I were the OP so I could check it!
Comment: Glad it helped!  By the way, a few weeks ago Facebook introduced "Test Apps", so at some point I intend to switch over to separate test apps for staging/dev instead of my approach above.  Here's the link: https://developers.facebook.com/docs/apps/test-apps - it looks like there are a few rough edges they'll smooth out according to the FAQs there, but it looks good, and it should be a nice way to try out different app settings in staging/dev without affecting production (and without having to maintain completely separate 'real' apps for staging/dev).

How to Facebook login with registration


view to list already added referenced nodes to all content types by user

Question: I have a content type of DELIVERY, and another content type of BOOK. Now each user has 3 DELIVERY content types that they are the author of. What i do is then edit a users DELIVERY content and add a BOOK to it (i have added a entity reference, referencing BOOK in DELIVERY).
All works fine, what i want to do is create a View, so that when i edit a users DELIVERY it lists the BOOKS i have already assigned to all the other DELIVERY's from that user. is this possible? been playing around with it but cant figure it out.
Answer: OK i managed to do it, for anyone curious heres how i did it:
I created a new View
I filtere it to show content of type DELIVERY
i added 2 Relationships
First relationship being the BOOK Reference field and the other being Author relationship
I then added a Contexiual Filter of NID and set it to default value and NID From URL
That was it, and i added the Book ref field to show the books


What is the default value of the IsReadyToPayRequest.existingPaymentMethodRequired property?

Question: The existingPaymentMethodRequired property in the IsReadyToPayRequest object is marked as optional but the documentation does not state what the property's default value is.
What value does this property fall back to if I don't specify it?
Answer: The existingPaymentMethodRequired property's default value, at the time of writing, is false.
You can validate this by calling the PaymentsClient.isReadyToPay(request:) method with an IsReadyToPayRequest object which omits the existingPaymentMethodRequired property and with the following setup:

The Google Pay environment is set to PRODUCTION.
The IsReadyToPayRequest.allowedAuthMethods array is set to ["PAN_ONLY","CRYPTOGRAM_3DS"].
Neither your Android device nor your Google account has a payment method added to it.

You will see that the PaymentsClient.isReadyToPay(request:) method returns true with this setup just as it does when the IsReadyToPayRequest.existingPaymentMethodRequired property is specified and set to false.


HTTP gzip compression not working for css or javascript in tomcat 6

Question: Connector settings:
<Connector ...
compression="2048"
noCompressionUserAgents="gozilla, traviata"
compressionMimeType="text/html,text/xml,text/plain,text/css,text/javascript"/>

This seems to work for html, but not for css or javascript. compression="force" does work, but compression="on" doesn't. compression="2" doesn't work either, so I don't know what "force" is really doing.
The files in question are about 6k, I've cleared the browser cache, etc.
Comment: Note that in Tomcat 7 this is the default setting, with the addition of `application/javascript`.
Answer: You should use compressableMimeType, not compressionMimeType, so
<Connector ...
compression="1400"
noCompressionUserAgents="gozilla, traviata"
compressableMimeType ="text/html,text/xml,text/plain,text/css,text/javascript"/>

Should do the trick.
Answer: http://tomcat.apache.org/tomcat-7.0-doc/config/http.html
Please use application/javascript instead of text/javascript, as given below:
compressableMimeType="text/html,text/xml,text/plain,text/css,application/javascript"


how can I download an svn from blender version 2.79b

Question: I do not want the current version: this is part of my school learning, learn to download previous versions.
But I can not find blender svn 2.79b, there is no longer the document that had the link of this svn, and I do not know how to navigate in its repository SVN.
https://svn.blender.org/svnroot/bf-blender/
try to navigate here and find what I'm looking for but I do not know much about this topic and how to differentiate branches and versions
reference image
Answer:
https://svn.blender.org/svnroot/bf-blender/ shows you branches and tags.
https://svn.blender.org/svnroot/bf-blender/tags/ shows you tags

There is no 2.79b, only 2.79a: https://svn.blender.org/svnroot/bf-blender/tags/blender-2.79a-release/
The "Building Blender on Windows" has the commands for trunk, but in your case, you need to checkout a specific revision:
svn checkout -r 62253 https://svn.blender.org/svnroot/bf-blender/tags/blender-2.79a-release/lib/win64_vc14/

For 2.79b and later, you need to git clone the repository, not svn checkout.
See developer.blender.org/diffusion/B/, which has the tag 2.79b
git clone git://git.blender.org/blender.git --branch v2.79b

Comment: @BlenderBlackened I have found the 2.79b tag and sources, this time in a Git repository. See my edited answer.
Comment: in the direct download you find this tablet with the source code of blender 2.79b http://download.blender.org/source/blender-2.79b.tar.gz How can you assemble this as your repository?
Comment: blender.org home page https://www.blender.org/download/
under the download button there is a line of text with links, the last one says INFO, click on info and see the last option, SOURCE, there download this blender file 2.79b in tar.gz how do you install this as a master repository?
Comment: I can convert the previous comment into a question or it is ok here as a comment, enter this topic or it would be better to turn it into a separate question ?


ggplot plot boxplot by label per column?

Question: I have the following data frame:
x1 x2  x3    y1 y2  y3 z1 z2   z3    label
1  54  -9    45 323 1  9  12  -0.1   1
5  21  -33.3 54 0.9 98 12 -87  5     2
12 1.3  0    23  12 65  7 -8   15    1

I want to plot a faceted plot that will compare each column by label.
For example x1 values: 2 boxplots one for label == 1, and label == 2.
9 facets, each own 2 box plots for each label.
I am trying to do this like this:
test <- gather(df, key, value, -label)

ggplot(test, aes(x = factor(label), y = value)) +
  geom_boxplot() +
  facet_wrap(~ key)

Please advise how to this right?
Comment: I don't understand your problem, IMO your code (since edit) produces exactly the output you describe.
Comment: @jaySf I just thought I am missing something, maybe there is command for such tasks. Everyday learning something new from the experts.
Answer: You must have the data frame in the long format. With package reshape2 you can do it like this.
m <- reshape2::melt(df, id.vars = "label")

ggplot(m, aes(x = label, y = variable)) +
  geom_boxplot() +
  facet_wrap( ~ variable)

Like the OP said in a comment, with package tidyr this would be done as follows.
test <- tidyr::gather(df, key, value, -label)

ggplot(test, aes(x = label, y = key)) +
  geom_boxplot() +
  facet_wrap( ~ key)

Data.
df <- read.table(text = "
x1 x2  x3    y1 y2  y3 z1 z2   z3    label
1  54  -9    45 323 1  9  12  -0.1   1
5  21  -33.3 54 0.9 98 12 -87  5     2
12 1.3  0    23  12 65  7 -8   15    1
", header = TRUE)

Comment: Same with tidyr::gather?
Comment: "Error in match.names(clabs, names(xi)) : names do not match previous names"
Comment: @steves With the data you have posted, I am not getting errors, everything works as expected.
Comment: @RuiBarradas Your code does not produce OP's expected output, there's only one boxplot for each label.
Comment: @jaySf Apparently it does, the OP has accepted the answer... And I really don't know whether there is just one boxplot or two touching each other. I would be able to see only with more data.


how can i acces to my session of type System.Collections.Generic.List`1 [mySolution.Models.PermissionsModel] and do some tests

Question: how can i acces to my session of type System.Collections.Generic.List`1 [mySolution.Models.Permis...
1 minute ago|LINK|22.214.171.124
I have a web service which returns a list of objects to me. indeed it is a list of permissions according to the logged in user which includes the modules of my application with the permissions (Visible / read / create / delete / modify)
I used this service, I got the list well and I saved it in a session at the time of Login.
To apply these permissions, I would like to access my session and know in the permissions list if the user has the right to do for example a delete or create action ..etc
How I can access my session knowing of type System.Collections.Generic.List`1 [mySolution.Models.PermissionsModel]
i develop in c #, asp.net mvc
Could you please help me on this!
Answer: Fetching an item from Session
List<Models.PermissionsModel> permissions = (List<Models.PermissionsModel>)Session["mySessionKey"];


Getting jQuery array into php form

Question: I have a form that includes several input text fields and a list that's sortable (se code below). The function below retrieves the new positions that's saved to an array (order). However, what I want is to include the array in the form so that when the user is finished with the sorting, has filled in the text fields and submits the form this array will be apart of the form.
So, how could I get this array into the form with AJAX?
<code>$('#listElements').sortable({
            //revert: true,
            update: function(event, ui) {

                var order = [];
                $('.listObject li').each(function (e) {
                    order.push($(this).attr('id'));
                });
                $.ajax({
                    url: "/index.php?type=list&action=showList&listId=1",
                    type: "post",
                    data: {
                        order_data: order
                    }
                }).success(function (data) {
                    console.log(data);
                });
            }
        });
</code>
NOTE: To make it clear, I want to get the array into the form.
Comment: possible duplication of `http://stackoverflow.com/questions/4239460/serializing-an-array-in-jquery`
Comment: You want to get array (from order) into form, or You want to get it into index.php ?
Answer: send it as a JSON encoded string and decode it serverside. As far as I know jquery has a array to JSON function and php got json_decode()

Getting jQuery array into php form


Extract Android application icon using aapt

Question: I need to extract the application icon in a APK file.
I'm using aapt to know the icon location inside the APK file.
I'm running aapt dump badging com.example.app.apk:
this command returns me:
<code>(...)
application-icon-120:'res/drawable-anydpi-v26/ic_launcher.xml'
application-icon-160:'res/drawable-anydpi-v26/ic_launcher.xml'
application-icon-240:'res/drawable-anydpi-v26/ic_launcher.xml'
application-icon-320:'res/drawable-anydpi-v26/ic_launcher.xml'
application-icon-480:'res/drawable-anydpi-v26/ic_launcher.xml'
application-icon-640:'res/drawable-anydpi-v26/ic_launcher.xml'
application-icon-65534:'res/drawable-anydpi-v26/ic_launcher.xml'
(...)
</code>
but as you can see it returns me the location of an XML file which in some way is encrypted. I know this XML file has the real path for the PNG file icon, but I don't know how can I get that real path (or how can I decrypt the XML and then parse it).
Is there any way to get the real path for an application icon inside a APK file with a XML pointing to other location?
Thanks!
Answer: Check out this project,

https://github.com/iBotPeaches/Apktool

It can be used to unarchive an APK, including the assets.
<code>apktool d <your>.apk
</code>
Answer: try extract  your apk file with 7-zip and you will get res foulder
Answer: Run this small script in a folder with your apk and it will extract the icon for you.
<code>#!/bin/bash
APK_FILE="$(find . -name *.apk)"
eval ICON_PATH="$(aapt d --values badging "${APK_FILE}" | grep "application:" | awk -F "icon=" '{print $2}')"
unzip -j "$APK_FILE" $ICON_PATH
</code>


Good Adjusted r square

Question: what is a good adjusted R square value for any multiple regression model or it depends? If it depends then what are the conditions?
Comment: "Good" for what purpose?
Answer: At the least, there is no universally $\textit{good}$ $R_{a}^2$ value  ; it can vary greatly depending on what type of data you are modeling. In certain social science fields one might find that an $R_{a}^2$ as low as 0.300 or so will suffice. On the other hand, if you are physicist testing a model or mathematical equation derived from physical laws, you are probably looking for something on the order of 0.900 or higher, where the remainder would account for measurement error or the like (I'm not a physicist but this is what I've heard from those in natural science fields).
Any undergraduate regression textbook worth its salt will surely contain a more in-depth examination of the issues related to using $R_{a}^2$ as a measure of goodness of fit, such as multicollinearity, etc...; or you could read the Wikipedia page. In short, $R_{a}^2$ will likely be one of the first things you glance at when you check the output of your model summary, but there are many other (arguably more robust) criteria you should be checking after this.
Comment: Did you notice that the question concerns the *adjusted* $R^2$? These values eventually *decrease* as new variables are entered into the model.
Comment: @whuber Wow I completely missed that; I edited the post and left what should still be relevant for $R_{a}^2$. Thank you.
Answer: Note that $R^2$ and $R^2_a$ can be highly influenced by the range and structure of the predictor variables.  This is one reason that many people are placing less importance on this measure (it can still be useful for a quick idea, but using it as a cutoff for decisions is probably not a good idea).
You can see this by simulating a dataset with a reasonable relationship and good sample size and computing $R^2_a$, then drop the half of the points that are closes to the mean(s) of the predictor variable(s) and recomputed $R^2_a$. I did a quick simulation with $n=100$ and 1 predictor variable.  Removing the central 50 data points (I just kept 25 on each end) increased $R^2_a$ from 0.51 to 0.70.
The F-statistic for testing for an overall relationship can be computed from $R^2$ and the degrees of freedom and therefore (if assumptions are reasonable) the statistical significance can be computed.  $R^2_a$ would be similar.  So if "good" means statistically significant then you could work out what is good based on your d.f. and significance level, but you could then also look at the p-value on the computer output to see the same information.
Comment: This interesting answer, which seems more like a comment to the question, might be more appropriate at [Is R2 useful or dangerous?](http://stats.stackexchange.com/questions/13314).

Good Adjusted r square


Why would the "View Dependencies" not show foreign keys between tables on 2 databases?

Question: I have something minor, yet very odd happening in SQL Server Management Studio 2005. I have 2 database catalogs which are essentially identical. There is a Market table with a foreign key to other several other tables for example the "Project" table has a MarketID column with an FK reference from dbo.Market. in both db catalogs the MarketID is not null, the datatype is the same (int - obviously) and in both db catalogs there is a foreign key created between the two tables (from dbo.Market to dbo.Project).
on the PRD catalog if I right click the Market table and choose "View Dependencies" from the context menu I will see the tables where MarketId is a foreign key on other tables (e.g. dbo.Project will appear under "Objects that depend upon Market"). If I do the same thing on the other db catalog (TST) it does not show that there are any foreign keys. PRD and TST catalogs are hosted on the same db server, so it's not a case of one catalog has a different version or SP of SS Management Studio or something... what gives?
What is even more strange is if I create a database diagram on both catalogs, the foreign keys look the same for all the tables compared, but the behaviour of the "View Dependencies" is different. If I look at the "Indexes" and "Statistics" for the tables on each catalog they are essentially identical too... I am baffled.
Can anyone suggest what things would impact the visibility of foreign key relationships in the tree that is shown when you choose the "View Dependencies"
Initially we thought wtf who removed the foreign keys, but when we look at a data diagram or the foreign keys folder they are there...
Comment: what does `select * from sys.foreign_keys where referenced_object_id = object_id('dbo.Market')` return for both?
Answer: From SQL Profiler this is the script SSMS uses. I guess it's just a question of running it your end to see what's different between the two databases.
<code>USE TST

CREATE TABLE #tempdep (objid int NOT NULL, objtype smallint NOT NULL);

INSERT INTO #tempdep

SELECT
tbl.object_id AS [ID],
3
FROM
sys.tables AS tbl
WHERE
(tbl.name=N'Market' and SCHEMA_NAME(tbl.schema_id)=N'dbo');

declare @find_referencing_objects int
set @find_referencing_objects = 1
-- parameters:
-- 1. create table #tempdep (objid int NOT NULL, objtype smallint NOT NULL)
--    contains source objects
-- 2. @find_referencing_objects defines ordering
--    1 order for drop
--    0 order for script

declare @must_set_nocount_off bit
set @must_set_nocount_off = 0

IF @@OPTIONS & 512 = 0
   set @must_set_nocount_off = 1
set nocount on

declare @u int
declare @udf int
declare @v int
declare @sp int
declare @def int
declare @rule int
declare @tr int
declare @uda int
declare @uddt int
declare @xml int
declare @udt int
declare @assm int
declare @part_sch int
declare @part_func int
declare @synonym int

set @u = 3
set @udf = 0
set @v = 2
set @sp = 4
set @def = 6
set @rule = 7
set @tr = 8
set @uda = 11
set @synonym = 12
--above 100 -> not in sys.objects
set @uddt = 101
set @xml = 102
set @udt = 103
set @assm = 1000
set @part_sch = 201
set @part_func = 202

/*
 * Create #t1 as temp object holding areas.  Columns are:
 *  object_id     - temp object id
 *  object_type    - temp object type
 *  relative_id      - parent or child object id
 *  relative_type  - parent or child object type
 *  rank  - NULL means dependencies not yet evaluated, else nonNULL.
 *   soft_link - this row should not be used to compute ordering among objects
 *   object_name - name of the temp object
 *   object_schema - name the temp object's schema (if any)
 *   relative_name - name of the relative object
 *   relative_schema - name of the relative object's schema (if any)
 *   degree - the number of relatives that the object has, will be used for computing the rank
 *   object_key - surrogate key that combines object_id and object_type
 *   relative_key - surrogate key that combines relative_id and relative_type
 */
create table #t1(
   object_id         int         NULL,
   object_type       smallint    NULL,
   relative_id       int         NULL,
   relative_type        smallint    NULL,
   rank        smallint    NULL,
   soft_link      bit      NULL,
   object_name       sysname     NULL,
   object_schema        sysname     NULL,
   relative_name     sysname     NULL,
   relative_schema      sysname     NULL,
   degree            int NULL,
   object_key bigint NULL,
   relative_key bigint NULL
)

create unique clustered index i1 on #t1(object_id, object_type, relative_id, relative_type) with IGNORE_DUP_KEY

declare @iter_no int
set @iter_no = 1

declare @rows int
set @rows = 1

declare @rowcount_ck int
set @rowcount_ck = 0

insert #t1 (relative_id, relative_type, rank)
   select l.objid, l.objtype, @iter_no from #tempdep l

while @rows > 0
begin
   set @rows = 0
   if( 1 = @find_referencing_objects )
   begin
      --tables that reference uddts or udts (parameters that reference types are in sql_dependencies )
      insert #t1 (object_id, object_type, relative_id, relative_type, rank)
         select t.relative_id, t.relative_type, c.object_id, @u, @iter_no + 1
         from #t1 as t
         join sys.columns as c on  c.user_type_id = t.relative_id
         join sys.tables as tbl on tbl.object_id = c.object_id -- eliminate views
         where @iter_no = t.rank and (t.relative_type=@uddt OR t.relative_type=@udt)
      set @rows = @rows + @@rowcount

      --tables that reference defaults ( only default objects )
      insert #t1 (object_id, object_type, relative_id, relative_type, rank)
         select t.relative_id, t.relative_type, clmns.object_id, @u, @iter_no + 1
         from #t1 as t
         join sys.columns as clmns on clmns.default_object_id = t.relative_id
         join sys.objects as o on o.object_id = t.relative_id and 0 = isnull(o.parent_object_id, 0)
         where @iter_no = t.rank and t.relative_type = @def
      set @rows = @rows + @@rowcount

      --types that reference defaults ( only default objects )
      insert #t1 (object_id, object_type, relative_id, relative_type, rank)
         select t.relative_id, t.relative_type, tp.user_type_id, @uddt, @iter_no + 1
         from #t1 as t
         join sys.types as tp on tp.default_object_id = t.relative_id
         join sys.objects as o on o.object_id = t.relative_id and 0 = isnull(o.parent_object_id, 0)
         where @iter_no = t.rank and t.relative_type = @def
      set @rows = @rows + @@rowcount

      --tables that reference rules
      insert #t1 (object_id, object_type, relative_id, relative_type, rank)
         select t.relative_id, t.relative_type, clmns.object_id, @u, @iter_no + 1
         from #t1 as t
         join sys.columns as clmns on clmns.rule_object_id = t.relative_id
         where @iter_no = t.rank and t.relative_type = @rule
      set @rows = @rows + @@rowcount

      --types that reference rules
      insert #t1 (object_id, object_type, relative_id, relative_type, rank)
         select t.relative_id, t.relative_type, tp.user_type_id, @uddt, @iter_no + 1
         from #t1 as t
         join sys.types as tp on tp.rule_object_id = t.relative_id
         where @iter_no = t.rank and t.relative_type = @rule
      set @rows = @rows + @@rowcount

      --tables that reference XmlSchemaCollections
      insert #t1 (object_id, object_type, relative_id, relative_type, rank)
         select t.relative_id, t.relative_type, c.object_id, @u, @iter_no + 1
         from #t1 as t
         join sys.columns as c on c.xml_collection_id = t.relative_id
         join sys.tables as tbl on tbl.object_id = c.object_id -- eliminate views
         where @iter_no = t.rank and t.relative_type = @xml
      set @rows = @rows + @@rowcount

      --procedures that reference XmlSchemaCollections
      insert #t1 (object_id, object_type, relative_id, relative_type, rank)
         select t.relative_id, t.relative_type, c.object_id, case when o.type in ( 'P', 'RF', 'PC' ) then @sp else @udf end, @iter_no + 1
         from #t1 as t
         join sys.parameters as c on c.xml_collection_id = t.relative_id
         join sys.objects as o on o.object_id = c.object_id
         where @iter_no = t.rank and t.relative_type = @xml
      set @rows = @rows + @@rowcount

      --udf, sp, uda, trigger all that reference assembly
      insert #t1 (object_id, object_type, relative_id, relative_type, rank)
         select t.relative_id, t.relative_type, am.object_id, (case o.type when 'AF' then @uda when 'PC' then @sp when 'FS' then @udf when 'FT' then @udf when 'TA' then @tr else @udf end), @iter_no + 1
         from #t1 as t
         join sys.assembly_modules as am on am.assembly_id = t.relative_id
         join sys.objects as o on am.object_id = o.object_id
         where @iter_no = t.rank and t.relative_type = @assm
      set @rows = @rows + @@rowcount

      -- CLR udf, sp, uda that reference udt
      insert #t1 (object_id, object_type, relative_id, relative_type, rank)
         select distinct t.relative_id,
               t.relative_type,
               am.object_id,
               (case o.type
                  when 'AF' then @uda
                  when 'PC' then @sp
                  when 'FS' then @udf
                  when 'FT' then @udf
                  when 'TA' then @tr
                  else @udf end),
               @iter_no + 1
         from #t1 as t
         join sys.parameters as sp on sp.user_type_id = t.relative_id
         join sys.assembly_modules as am on sp.object_id = am.object_id
         join sys.objects as o on sp.object_id = o.object_id
         where @iter_no = t.rank and t.relative_type = @udt
      set @rows = @rows + @@rowcount

      --udt that reference assembly
      insert #t1 (object_id, object_type, relative_id, relative_type, rank)
         select t.relative_id, t.relative_type, at.user_type_id, @udt, @iter_no + 1
         from #t1 as t
         join sys.assembly_types as at on at.assembly_id = t.relative_id
         where @iter_no = t.rank and t.relative_type = @assm
      set @rows = @rows + @@rowcount

      --assembly that reference assembly
      insert #t1 (object_id, object_type, relative_id, relative_type, rank)
         select t.relative_id, t.relative_type, ar.assembly_id, @assm, @iter_no + 1
         from #t1 as t
         join sys.assembly_references as ar on ar.referenced_assembly_id = t.relative_id
         where @iter_no = t.rank and t.relative_type = @assm
      set @rows = @rows + @@rowcount

      --table references table
      insert #t1 (object_id, object_type, relative_id, relative_type, rank)
         select t.relative_id, t.relative_type, fk.parent_object_id, @u, @iter_no + 1
         from #t1 as t
         join sys.foreign_keys as fk on fk.referenced_object_id = t.relative_id
         where @iter_no = t.rank and t.relative_type = @u
      set @rows = @rows + @@rowcount

      --table,view references partition scheme
      insert #t1 (object_id, object_type, relative_id, relative_type, rank)
         select t.relative_id, t.relative_type, idx.object_id, case o.type when 'V' then @v else @u end, @iter_no + 1
         from #t1 as t
         join sys.indexes as idx on idx.data_space_id = t.relative_id
         join sys.objects as o on o.object_id = idx.object_id
         where @iter_no = t.rank and t.relative_type = @part_sch
      set @rows = @rows + @@rowcount

      --partition scheme references partition function
      insert #t1 (object_id, object_type, relative_id, relative_type, rank)
         select t.relative_id, t.relative_type, ps.data_space_id, @part_sch, @iter_no + 1
         from #t1 as t
         join sys.partition_schemes as ps on ps.function_id = t.relative_id
         where @iter_no = t.rank and t.relative_type = @part_func
      set @rows = @rows + @@rowcount

      --non-schema-bound parameter references type
      insert #t1 (object_id, object_type, relative_id, relative_type, rank)
         select t.relative_id, t.relative_type, p.object_id,
               case when obj.type in ( 'P', 'PC' ) then @sp else @udf
               end, @iter_no + 1
         from #t1 as t
         join sys.parameters as p on
             p.user_type_id = t.relative_id and  t.relative_type in (@uddt, @udt)
         join sys.objects as obj on obj.object_id = p.object_id and obj.type in ( 'P',  'PC', 'TF', 'FN', 'IF', 'FS', 'FT')
         and ISNULL(objectproperty(obj.object_id, 'isschemabound'), 0) = 0
         where @iter_no = t.rank
      set @rows = @rows + @@rowcount

      --view, procedure references table, view, procedure
      --procedure references type
      --table(check) references procedure
      --trigger references table, procedure
      insert #t1 (object_id, object_type, relative_id, relative_type, rank)
         select t.relative_id, t.relative_type, case when 'C' = obj.type then obj.parent_object_id else dp.object_id end,
               case when obj.type  in ('U', 'C') then @u when 'V' = obj.type then @v when 'TR' = obj.type then @tr
               when obj.type in ( 'P', 'RF', 'PC' ) then @sp
               when obj.type in ( 'TF', 'FN', 'IF', 'FS', 'FT' ) then @udf
               end, @iter_no + 1
         from #t1 as t
         join sys.sql_dependencies as dp on
            -- reference table, view procedure
            ( class < 2 and dp.referenced_major_id = t.relative_id and t.relative_type in ( @u, @v, @sp, @udf) )
            --reference type
             or ( 2 = class  and dp.referenced_major_id = t.relative_id and  t.relative_type in (@uddt, @udt))
            --reference xml namespace ( not supported by server right now )
            --or ( 3 = class  and dp.referenced_major_id = t.relative_id and @xml = t.relative_type )
         join sys.objects as obj on obj.object_id = dp.object_id and obj.type in ( 'U', 'V', 'P', 'RF', 'PC', 'TR', 'TF', 'FN', 'IF', 'FS', 'FT', 'C')
         where @iter_no = t.rank
      set @rows = @rows + @@rowcount

   end -- 1 = @find_referencing_objects
   else
   begin -- find referenced objects
      --check references table
      insert #t1 (object_id, object_type, relative_id, relative_type, rank)
         select t.relative_id, t.relative_type, dp.object_id, 77 /*place holder for check*/, @iter_no
         from #t1 as t
         join sys.sql_dependencies as dp on
            -- reference table
            class < 2 and dp.referenced_major_id = t.relative_id and t.relative_type = @u
         join sys.objects as obj on obj.object_id = dp.object_id and obj.type  = 'C'
         where @iter_no = t.rank
      set @rowcount_ck = @@rowcount

      --non-schema-bound parameter references type
      insert #t1 (object_id, object_type, relative_id, relative_type, rank)
         select distinct
            t.relative_id,  -- object_id
            t.relative_type,    -- object_type
            p.user_type_id, -- relative_id
            case p.system_type_id when 240 then @udt else @uddt end,
            @iter_no + 1
         from #t1 as t
         join sys.parameters as p on
             p.object_id = t.relative_id and p.user_type_id > 256 and t.relative_type in ( @sp, @udf )
             and ISNULL(objectproperty(p.object_id, 'isschemabound'), 0) = 0
         where @iter_no = t.rank
      set @rows = @rows + @@rowcount

      --view, procedure referenced by table, view, procedure
      --type referenced by procedure
      --check referenced by table
      insert #t1 (object_id, object_type, relative_id, relative_type, rank)
         select distinct
            case when 77 = t.relative_type then obj2.parent_object_id else t.relative_id end,   -- object_id
            case when 77 = t.relative_type then @u else relative_type end,                -- object_type
            dp.referenced_major_id,                                              -- relative_id
            case                                                           -- relative_type
               when dp.class < 2 then
                  case when 'U' = obj.type then @u
                  when 'V' = obj.type then @v
                  when 'TR' = obj.type then @tr
                  when 'AF' = obj.type then @uda
                  when obj.type in ( 'P', 'RF', 'PC' ) then @sp
                  when obj.type in ( 'TF', 'FN', 'IF', 'FS', 'FT' ) then @udf
                  when exists (select * from sys.synonyms syn where syn.object_id = dp.referenced_major_id ) then @synonym
                  end
               when dp.class = 2 then (case
                                    when exists (select * from sys.assembly_types sat where sat.user_type_id = dp.referenced_major_id) then @udt
                                    else @uddt
                                 end)
            end,
            @iter_no + 1
         from #t1 as t
         join sys.sql_dependencies as dp on
            -- reference table, view procedure
            ( class < 2 and dp.object_id = t.relative_id and t.relative_type in ( @u, @v, @sp, @udf, @tr, @uda, 77) )
            --reference type
             or ( 2 = class  and dp.object_id = t.relative_id ) -- t.relative_type?
            --reference xml namespace ( not supported by server right now )
            --or ( 3 = class  and dp.referenced_major_id = t.relative_id and @xml = t.relative_type )
         left join sys.objects as obj on obj.object_id = dp.referenced_major_id and dp.class < 2 and obj.type in ( 'U', 'V', 'P', 'RF', 'PC', 'TF', 'FN', 'IF', 'FS', 'FT', 'TR', 'AF')
         left join sys.objects as obj2 on obj2.object_id = t.relative_id and 77 = t.relative_type
         where @iter_no = t.rank
      set @rows = @rows + @@rowcount

      if @rowcount_ck > 0
      begin
         delete from #t1 where relative_type = 77
      end

      --table or view referenced by trigger
      insert #t1 (object_id, object_type, relative_id, relative_type, rank)
         select t.relative_id, t.relative_type, tr.parent_id, case o.type when 'V' then @v else @u end, @iter_no + 1
         from #t1 as t
         join sys.triggers as tr on tr.object_id = t.relative_id
         join sys.objects as o on o.object_id = tr.parent_id
         where @iter_no = t.rank and t.relative_type = @tr
      set @rows = @rows + @@rowcount

      --table referenced by table
      insert #t1 (object_id, object_type, relative_id, relative_type, rank)
         select t.relative_id, t.relative_type, fk.referenced_object_id, @u, @iter_no + 1
         from #t1 as t
         join sys.foreign_keys as fk on fk.parent_object_id = t.relative_id
         where @iter_no = t.rank and t.relative_type = @u
      set @rows = @rows + @@rowcount

      --assembly referenced by assembly
      insert #t1 (object_id, object_type, relative_id, relative_type, rank)
         select t.relative_id, t.relative_type, ar.referenced_assembly_id, @assm, @iter_no + 1
         from #t1 as t
         join sys.assembly_references as ar on ar.assembly_id = t.relative_id
         where @iter_no = t.rank and t.relative_type = @assm
      set @rows = @rows + @@rowcount

      --assembly referenced by udt
      insert #t1 (object_id, object_type, relative_id, relative_type, rank)
         select t.relative_id, t.relative_type, at.assembly_id, @assm, @iter_no + 1
         from #t1 as t
         join sys.assembly_types as at on at.user_type_id = t.relative_id
         where @iter_no = t.rank and t.relative_type = @udt
      set @rows = @rows + @@rowcount

      -- assembly referenced by udf, sp, uda, trigger
      insert #t1 (object_id, object_type, relative_id, relative_type, rank)
         select t.relative_id, t.relative_type, am.assembly_id, @assm, @iter_no + 1
         from #t1 as t
         join sys.assembly_modules as am on am.object_id = t.relative_id
         where @iter_no = t.rank and t.relative_type in ( @udf, @sp, @uda, @tr)
      set @rows = @rows + @@rowcount

      -- udt referenced by CLR udf, sp, uda
      insert #t1 (object_id, object_type, relative_id, relative_type, rank)
         select distinct
               t.relative_id,
               t.relative_type,
               at.user_type_id,
               @udt,
               @iter_no + 1
         from #t1 as t
         join sys.parameters as sp on sp.object_id = t.relative_id
         join sys.assembly_modules as am on am.object_id = sp.object_id
         join sys.assembly_types as at on sp.user_type_id = at.user_type_id
         where @iter_no = t.rank and t.relative_type in (@udf, @sp, @uda)
      set @rows = @rows + @@rowcount

      --clr types referenced by tables ( types referenced by parameters are in sql_dependencies )
      insert #t1 (object_id, object_type, relative_id, relative_type, rank)
         select t.relative_id, t.relative_type, c.user_type_id, @udt, @iter_no + 1
         from #t1 as t
         join sys.columns as c on  c.object_id = t.relative_id
         join sys.assembly_types as tp on tp.user_type_id = c.user_type_id
         where @iter_no = t.rank and t.relative_type = @u
      set @rows = @rows + @@rowcount

   end
   set @iter_no = @iter_no + 1
end --main loop

--objects that don't need to be in the loop because they don't reference anybody
if( 0 = @find_referencing_objects )
begin
   --alias types referenced by tables ( types referenced by parameters are in sql_dependencies )
   insert #t1 (object_id, object_type, relative_id, relative_type, rank)
      select t.relative_id, t.relative_type, c.user_type_id, @uddt, @iter_no + 1
      from #t1 as t
      join sys.columns as c on  c.object_id = t.relative_id
      join sys.types as tp on tp.user_type_id = c.user_type_id and tp.is_user_defined = 1
      where t.relative_type = @u and tp.is_assembly_type = 0

   if @@rowcount > 0
   begin
      set @iter_no = @iter_no + 1
   end

   --defaults referenced by types
   insert #t1 (object_id, object_type, relative_id, relative_type, rank)
      select t.relative_id, t.relative_type, tp.default_object_id, @def, @iter_no + 1
      from #t1 as t
      join sys.types as tp on tp.user_type_id = t.relative_id and tp.default_object_id > 0
      join sys.objects as o on o.object_id = tp.default_object_id and 0 = isnull(o.parent_object_id, 0)
      where t.relative_type = @uddt

   --defaults referenced by tables( only default objects )
   insert #t1 (object_id, object_type, relative_id, relative_type, rank)
      select t.relative_id, t.relative_type, clmns.default_object_id, @def, @iter_no + 1
      from #t1 as t
      join sys.columns as clmns on clmns.object_id = t.relative_id
      join sys.objects as o on o.object_id = clmns.default_object_id and 0 = isnull(o.parent_object_id, 0)
      where t.relative_type = @u

   --rules referenced by types
   insert #t1 (object_id, object_type, relative_id, relative_type, rank)
      select t.relative_id, t.relative_type, tp.rule_object_id, @rule, @iter_no + 1
      from #t1 as t
      join sys.types as tp on tp.user_type_id = t.relative_id and tp.rule_object_id > 0
      where t.relative_type = @uddt

   --rules referenced by tables
   insert #t1 (object_id, object_type, relative_id, relative_type, rank)
      select t.relative_id, t.relative_type, clmns.rule_object_id, @rule, @iter_no + 1
      from #t1 as t
      join sys.columns as clmns on clmns.object_id = t.relative_id and clmns.rule_object_id > 0
      where t.relative_type = @u

   --XmlSchemaCollections referenced by table
   insert #t1 (object_id, object_type, relative_id, relative_type, rank)
      select t.relative_id, t.relative_type, c.xml_collection_id, @xml, @iter_no + 1
      from #t1 as t
      join sys.columns as c on c.object_id = t.relative_id and c.xml_collection_id > 0
      where t.relative_type = @u

   --XmlSchemaCollections referenced by procedures
   insert #t1 (object_id, object_type, relative_id, relative_type, rank)
      select t.relative_id, t.relative_type, c.xml_collection_id, @xml, @iter_no + 1
      from #t1 as t
      join sys.parameters as c on c.object_id = t.relative_id and c.xml_collection_id > 0
      where t.relative_type in ( @sp, @udf)

   --partition scheme referenced by table,view
   insert #t1 (object_id, object_type, relative_id, relative_type, rank)
      select t.relative_id, t.relative_type, ps.data_space_id, @part_sch, @iter_no + 1
      from #t1 as t
      join sys.indexes as idx on idx.object_id = t.relative_id
      join sys.partition_schemes as ps on ps.data_space_id = idx.data_space_id
      where t.relative_type in (@u, @v)

   --partition function referenced by partition scheme
   insert #t1 (object_id, object_type, relative_id, relative_type, rank)
      select t.relative_id, t.relative_type, ps.function_id, @part_func, @iter_no + 1
      from #t1 as t
      join sys.partition_schemes as ps on ps.data_space_id = t.relative_id
      where t.relative_type = @part_sch

end

--cleanup circular references
delete #t1 where object_id = relative_id and object_type=relative_type

--allow circular dependencies by cuting one of the branches
--mark as soft links dependencies between tables
-- at script time we will need to take care to script fks and checks separately
update #t1 set soft_link = 1 where ( object_type = @u and relative_type = @u )

--add independent objects first in the list
insert #t1 ( object_id, object_type, rank)
   select t.relative_id, t.relative_type, 1 from #t1 t where t.relative_id not in ( select t2.object_id from #t1 t2 where not t2.object_id is null )

--delete initial objects
delete #t1 where object_id is null

-- compute the surrogate keys to make sorting easier
update #t1 set object_key = object_id + convert(bigint, 0xfFFFFFFF) * object_type
update #t1 set relative_key = relative_id + convert(bigint, 0xfFFFFFFF) * relative_type

create index index_key on #t1 (object_key, relative_key)

update #t1 set rank = 0
-- computing the degree of the nodes
update #t1 set degree = (
      select count(*)
      from #t1 t_alias
      where t_alias.object_key = #t1.object_key and
            t_alias.relative_id is not null and
            t_alias.soft_link is null)

-- perform topological sorting
set @iter_no=1
while 1=1
begin
   update #t1 set rank=@iter_no where degree=0
   -- end the loop if no more rows left to process
   if (@@rowcount=0) break
   update #t1 set degree=NULL where rank = @iter_no

   update #t1 set degree = (
      select count(*)
         from #t1 t_alias
         where t_alias.object_key = #t1.object_key and
            t_alias.relative_key is not null and
            t_alias.relative_key in (select t_alias2.object_key from #t1 t_alias2 where t_alias2.rank=0 and t_alias2.soft_link is null) and
            t_alias.rank=0 and t_alias.soft_link is null)
      where degree is not null

   set @iter_no=@iter_no+1
end

--add name schema
update #t1 set object_name = o.name, object_schema = schema_name(o.schema_id)
from sys.objects AS o
where o.object_id = #t1.object_id and object_type in ( @u, @udf, @v, @sp, @def, @rule, @uda)

update #t1 set relative_type = case op.type when 'V' then @v else @u end, object_name = o.name, object_schema = schema_name(o.schema_id), relative_name = op.name, relative_schema = schema_name(op.schema_id)
from sys.objects AS o
join sys.objects AS op on op.object_id = o.parent_object_id
where o.object_id = #t1.object_id and object_type = @tr

update #t1 set object_name = t.name, object_schema = schema_name(t.schema_id)
from sys.types AS t
where t.user_type_id = #t1.object_id and object_type in ( @uddt, @udt )

update #t1 set object_name = x.name, object_schema = schema_name(x.schema_id)
from sys.xml_schema_collections AS x
where x.xml_collection_id = #t1.object_id and object_type = @xml

update #t1 set object_name = p.name, object_schema = null
from sys.partition_schemes AS p
where p.data_space_id = #t1.object_id and object_type = @part_sch

update #t1 set object_name = p.name, object_schema = null
from sys.partition_functions AS p
where p.function_id = #t1.object_id and object_type = @part_func

update #t1 set object_name = a.name, object_schema = null
from sys.assemblies AS a
where a.assembly_id = #t1.object_id and object_type = @assm

update #t1 set object_name = syn.name, object_schema = schema_name(syn.schema_id)
from sys.synonyms AS syn
where syn.object_id = #t1.object_id and object_type = @synonym

-- delete objects for which we could not resolve the table name or schema
-- because we may not have enough privileges
delete from #t1
where
    object_name is null or
    (object_schema is null  and object_type not in (@assm, @part_func, @part_sch))

--final select
select object_id, object_type, relative_id, relative_type, object_name, object_schema, relative_name, relative_schema
 from #t1
 order by rank, relative_id

drop table #t1
drop table #tempdep

IF @must_set_nocount_off > 0
   set nocount off
</code>


Prove that a perfect square (also a perfect square backwards) is divisible by 121

Question: Suppose that $n=x^2$ is a perfect square with an even number of base-10 digits. Assume that when n is written backwards, you get another perfect square $y^2$. Prove that 121|n. (Use the mod 11 divisibility test, and the fact that -1 is a quadratic non-residue mod 11.)
I know by using the mod 11 divisibility test (where you add and subtract alternating digits) that $x^2 \equiv -y^2$ (mod 11). I believe, also, that since $x^2$ is a quadratic residue mod 11 and $-y^2$ is a quadratic non-residue mod 11, by the properties of Legendre symbols it can't be true that $gcd(x^2,11)=gcd(y^2,11)=1$, so 11 divides $x^2$ and $y^2$. But after that, I'm stuck, and I don't know how to get to the conclusion that 121|n. Help, please?
Comment: If a prime $p$ divides a square, then so does $p^2$.
Comment: If $11$ divides $x^2$ then $11$ must divide $x$, since $11$ is prime. That means $11^2=121$ must divide $n=x^2$.
Comment: Both $x^2$ and $y^2$ _must be_ quadratic residues modulo _anything_, by definition of quadratic residue.
Comment: @Arthur Oops, I meant $-y^2$ is a quadratic non-residue mod 11. Obviously $y^2$ is a quadratic residue. I fixed my original post.
Comment: this is easy if the number of digits is even.
Comment: @ZubinMukerjee Oh, okay. Thank you!
Answer: as you said, It is easy to see that if $n$ has an even number of digits then the number obtained when reversing the digits is congruent to $-n\bmod 11$.
Therefore $n$ and $-n$ are quadratic residues. Suppose $n$ is not $0\bmod 11$. Now use the fact the quadratic residues form a subgroup of the multiplicative group $\mathbb Z_{11}^*$. So $n^{-1}$ is a quadratic residue, and subsequently $n^{-1}(-n)\equiv -1$ is a quadratic residue $\bmod 11$. This is a contradiction, the quadratic residues $\bmod 11$ are $0,1,4,9,5,3$.
We conclude $n\equiv 0 \bmod 11$. So $11|n$, and since $n$ is a square $11^2|n$ (since $11$ is a prime).


How can I render my output in a series of DIVs rather than an "item_list"?

Question: The following code works in the sense that it outputs my series of photos in an unordered list. My question is - What changes would I need to make in order to render my output in a series of DIVs with class IDs? I plan to hook this up to JQuery Masonry and I'd prefer to break away from the limitations of them being in a list.
The following code pulls in my data.
function photo_gallery_contents($display) {
  $max_num = variable_get('photo_gallery_max', 3);
  $query = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->condition('status', 1) //Published.
    ->condition('type','portfolio') // Only want our photos aka Portfolio content type
    ->orderBy('created', 'DESC'); //Most recent first.

  if ($display == 'block') {
    // Restrict the range if called with 'block' argument
    $query->range(0, $max_num);
  }
  // Now proceeds to execute().
  // If called by peg, query proceeds directly to execute().

  // Fetch the results for the nid field into an array.
  $nids = $query->execute()->fetchCol();

  // Load the node objects and return.
  return node_load_multiple($nids);

}
The code that renders all (but would like it to create a series of DIVs) is the following one.
function _photo_gallery_page() {
  $result = photo_gallery_contents('page');

  // Array to contain items for the page to render.
  $items = array();

  //Iterate over the resultset and format as links.
  foreach ($result as $node) {
    // Build a render array based on the field's display settings.
    $image = field_view_field('node', $node, 'field_image',array('label' => 'hidden',   'settings' => array('image_style' => 'thumbnail')));

    // Render the array down to the image HTML.
    $image_html = drupal_render($image);

    $items[] = array(
      'data' => l($image_html, 'node/' . $node->nid, array('html' => TRUE)),
    );
  }

  if (empty($items)) {
    // No content in the last 2 weeks.
    $page_array['photo_gallery_arguments'] = array(
      //Title serves as page subtitle.
      '#title' => t('All photos from ever'),
      '#markup' => t('No photos available.'),
    );
    return $page_array;
  }
  else {
    $page_array['photo_gallery_arguments'] = array(
      '#title' => t('All photos from ever'),
      '#items' => $items,
      // Theme hook with suggestion.
      '#theme' => 'item_list',
      '#type' => 'div',
    );

    return $page_array;
  }
}

Answer: As far I understood you want render the following code in multiple <divs>.
$page_array['photo_gallery_arguments'] = array(
  '#title' => t('All photos from ever'),
  '#items' => $items,
  // Theme hook with suggestion.
  '#theme' => 'item_list',
  '#type' => 'div',
);

Replace it with the following code.
   foreach($items as $item_key => $item) {
     $page_array['photo_gallery_arguments'][$item_key] = array(
       '#type' => 'container',
       '#attributes' => array(
         'class' => array(
           'my-class-' . $item_key,
         ),
       ),
     );

     $page_array['photo_gallery_arguments'][$item_key]['content'] = array(
       '#type' => 'markup',
       '#markup' => $item,
     );
   }

Or use the following code.
   foreach($items as $item_key => $item){
     $page_array['photo_gallery_arguments'][$item_key] = array(
       '#type' => 'markup',
       '#markup' => '
' . $item . '
',
     );
   }

Alternatively, you can use the following code.
   foreach($items as $item_key => $item){
     $page_array['photo_gallery_arguments'][$item_key] = array(
       '#type' => 'item',
       '#markup' => $item,
     );
   }

You can find more information about rendering arrays, and Form API.


SemanticException adding partiton Hive table

Question: Attempting to create a partition on a Hive table with the following:
> alter table stock_ticker add if not exists
> partition(stock_symbol='ASP')
> location 'data/stock_ticker_sample/stock_symbol=ASP/'

Which produces the following output
FAILED : SemanticException table is not partitioned but partition spec exists: {stock_symbol=ASP}

There are no partitions on this table prior to this addition attempt
> show partitions stock_ticker;

which results in
FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask.
Table stock_ticker_sample is not a partitioned table

There is no question that the stock_symbol column exists and is of type string.
The query is what steps need to be taken in order to add this partition?
Answer: Solution would be to add partitioning info into the definition of stock_ticker table:
CREATE EXTERNAL TABLE stock_ticker (
...
)
PARTITIONED BY (stock_symbol STRING);

Then easily you can add external data to your table by:
> alter table stock_ticker add if not exists
> partition(stock_symbol='ASP')
> location 'data/stock_ticker_sample/stock_symbol=ASP/'

GL!
Comment: It would appear that partitioning must be done on external tables.
Comment: Is not, I assumed that you wanted to specify the existing location for this partition so making it manageable table might endanger the source data in case of drop.
Comment: What I mean is that when performed on an external table pointing to the location of my internal table that the partition operation succeeds. Not that partitioning on internal tables is not possible per se.
Comment: Specifying location for given partition for internal table would work as well. But generally is a bad idea. For managed tables automatic folder assign seems to be right way to follow. Gl with partitioning stuff!
Comment: I got similar error for a external table and couldn't find a reason of why it happens. Ended up removing the table and recreating the table again. Since it was external table it didn't matter much for me to delete and recreate it again.
Comment: Is there anyway of doing this WITHOUT re-creating the table?  See also my question:  https://stackoverflow.com/questions/66821768/add-new-partition-scheme-to-existing-table-in-athena-with-sql-code?noredirect=1&lq=1


Delete log files on Virtual Host

Question: I have a few virtualhosts set up on my machine, and the server keeps crashing because of the disk space being too full. I've checked out and it seems that one of my virtual host log folder is 2Gb. In it there are hundreds of log files, either gzipped or not.
My question is, is there an easy way to delete all that without deleting the current logs being used? Also, while at it, is there a way to tell the server to keep say 5 logs files at all time and delete the others?
Server is Debian.
thanks for your help
Comment: Why don't you just use logrotate?
Comment: Debain ships with [`logrotate`](http://packages.debian.org/stable/admin/logrotate).
Comment: Coz I didn't know it was available, and not sure how to use it. Now how can I delete all these files that are already there?
Comment: And I see that logrotate would restart the server every night? Is that true?
Answer: take a look for logrotate , you have many tutorial available on Internet, a quick search on Google and I found this tutorial.
Logrotate run every day with cron.daily, the script read /etc/logrotate.conf , this file contain all default configuration. Logrotate read other file in the directory /etc/logrotate.d.
So you can perform log rotation every day and keep only 5 day, to set this configuration you must define , in the file /etc/logrotate.conf:
<code># see "man logrotate" for details
# rotate log files weekly
daily
# keep 5 days worth of backlogs
rotate 5
</code>
You can add the option compress to compress rotated files.
Take a look in files under /etc/logrotate.d to be sure your configuration is not overwrite.
you can do many things with logrotate take few time to read the documentation.

Delete log files on Virtual Host


Normalizer of a quotient

Question: Suppose that $G$ is a group and $A, B$ and $H$ are subgroups of $G$ with $B\unlhd A$.
In a paper I have read, they say that the normalizer of $A/B$ in $H$ is $N_H(A/B) = N_H(A) \cap N_H(B)$. I am having a difficulty showing this as I am not sure what an element looks like in $N_H(A/B)$
My second question is what can we say about the induced automorphisms of $A/B$ using $N_H(A/B)$
Comment: Yes, if I was asked to define it I would just do it like that! An element $g \in N_H(A/B)$ induces an automorphisms of $A/B$ by conjugation, by $aB \mapsto gag^{-1}B$ for $a \in A$. I don't think you can say much more in general. You could also define $C_H(A/B)$ as those $g \in N_H(A/B)$ that map to the identity automorphism. That is $g \in C_H(A/B) \Leftrightarrow gag^{-1} \in aB$ for all $a \in A$.
Comment: What's the definition of $N_H(A/B)$?
Comment: They just say that it is the normalizer of $A/B$ in $H$. Do you think it is defined as $N_H(A/B) = N_H(A) \cap N_H(B)$? This makes more sense
Answer: If $H, A$  any  subgroups of $G$, the normalizer of $A$ relatively to $H$ is the intersection of $H$ with the normalizer of $A$ in $G$, that  is  $h \in H$ such that
$hAh ^ {-1} = A$. If $B$ is a subgroup normal in $A$, the normalizer of the quotient group  $A/B$  relatively  to $H$ is  the set of elements $h$ of $H$ that define automorphism passing  at the quotient ie element $h$  such that the morphism composit $p_B \gamma_h$ factorises via $P_B$ where  $p_B$ is the canonical projection and $\gamma_h$ the automorphism of conjugation by $h$ of $G$, ie  such  element $h$ is in the normalizer of $B$ relatively to $H$. Thus, it has the desired equality.

Normalizer of a quotient


Unable to update CentOS 6.5 & OpenSSL

Question: When trying to update OpenSSL on CentOS I am getting some odd errors.
#rpm -qi openssl-libs
Name        : openssl-libs                 Relocations: (not relocatable)
Version     : 1.0.1e                            Vendor: (none)
Release     : 19.el6                        Build Date: Thu 02 Jan 2014 07:35:50 PM UTC
Install Date: Thu 02 Jan 2014 07:42:06 PM UTC      Build Host: xxxxxx
Group       : System Environment/Libraries   Source RPM: openssl-1.0.1e-19.el6.src.rpm
Size        : 2668401                          License: OpenSSL
Signature   : (none)
URL         : http://www.openssl.org/
Summary     : A general purpose cryptography library with TLS implementation
Description :
OpenSSL is a toolkit for supporting cryptography. The openssl-libs
package contains the libraries that are used by various applications which
support cryptographic algorithms and protocols.

# yum info openssl
Loaded plugins: aliases, replace, security
Installed Packages
Name        : openssl
Arch        : x86_64
Version     : 1.0.1e
Release     : 16.el6_5.4
Size        : 4.0 M
Repo        : installed
Summary     : A general purpose cryptography library with TLS implementation
URL         : http://www.openssl.org/
License     : OpenSSL
Description : The OpenSSL toolkit provides support for secure communications between
            : machines. OpenSSL includes a certificate management tool and shared
            : libraries which provide various cryptographic algorithms and
            : protocols.

Available Packages
Name        : openssl
Arch        : i686
Version     : 1.0.1e
Release     : 30.el6_5.2
Size        : 1.5 M
Repo        : updates
Summary     : A general purpose cryptography library with TLS implementation
URL         : http://www.openssl.org/
License     : OpenSSL
Description : The OpenSSL toolkit provides support for secure communications between
            : machines. OpenSSL includes a certificate management tool and shared
            : libraries which provide various cryptographic algorithms and
            : protocols.

Name        : openssl
Arch        : x86_64
Version     : 1.0.1e
Release     : 30.el6_5.2
Size        : 1.5 M
Repo        : updates
Summary     : A general purpose cryptography library with TLS implementation
URL         : http://www.openssl.org/
License     : OpenSSL
Description : The OpenSSL toolkit provides support for secure communications between
            : machines. OpenSSL includes a certificate management tool and shared
            : libraries which provide various cryptographic algorithms and
            : protocols.

#openssl version -a
OpenSSL 1.0.1e-fips 11 Feb 2013
built on: Wed Jan  8 18:40:59 UTC 2014
platform: linux-x86_64
options:  bn(64,64) md2(int) rc4(8x,int) des(idx,cisc,16,int) idea(int) blowfish(idx)
compiler: gcc -fPIC -DOPENSSL_PIC -DZLIB -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -DKRB5_MIT -m64 -DL_ENDIAN -DTERMIO -Wall -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -Wa,--noexecstack -DPURIFY -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DWHIRLPOOL_ASM -DGHASH_ASM
OPENSSLDIR: "/etc/pki/tls"
engines:  dynamic

But when I try and run yum to update it there are conflicts:
#yum -y install openssl
Loaded plugins: aliases, replace, security
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package openssl.x86_64 0:1.0.1e-16.el6_5.4 will be updated
---> Package openssl.x86_64 0:1.0.1e-30.el6_5.2 will be an update
--> Finished Dependency Resolution

Dependencies Resolved

=======================================================================================================
 Package              Arch                Version                           Repository            Size
=======================================================================================================
Updating:
 openssl              x86_64              1.0.1e-30.el6_5.2                 updates              1.5 M

Transaction Summary
=======================================================================================================
Upgrade       1 Package(s)

Total size: 1.5 M
Downloading Packages:
Running rpm_check_debug
Running Transaction Test

Transaction Check Error:
  file /usr/lib64/libcrypto.so.1.0.1e from install of openssl-1.0.1e-30.el6_5.2.x86_64 conflicts with file from package openssl-libs-1:1.0.1e-19.el6.x86_64
  file /usr/lib64/libssl.so.1.0.1e from install of openssl-1.0.1e-30.el6_5.2.x86_64 conflicts with file from package openssl-libs-1:1.0.1e-19.el6.x86_64
  file /usr/lib64/openssl/engines/lib4758cca.so from install of openssl-1.0.1e-30.el6_5.2.x86_64 conflicts with file from package openssl-libs-1:1.0.1e-19.el6.x86_64
  file /usr/lib64/openssl/engines/libaep.so from install of openssl-1.0.1e-30.el6_5.2.x86_64 conflicts with file from package openssl-libs-1:1.0.1e-19.el6.x86_64
  file /usr/lib64/openssl/engines/libatalla.so from install of openssl-1.0.1e-30.el6_5.2.x86_64 conflicts with file from package openssl-libs-1:1.0.1e-19.el6.x86_64
  file /usr/lib64/openssl/engines/libcapi.so from install of openssl-1.0.1e-30.el6_5.2.x86_64 conflicts with file from package openssl-libs-1:1.0.1e-19.el6.x86_64
  file /usr/lib64/openssl/engines/libchil.so from install of openssl-1.0.1e-30.el6_5.2.x86_64 conflicts with file from package openssl-libs-1:1.0.1e-19.el6.x86_64
  file /usr/lib64/openssl/engines/libcswift.so from install of openssl-1.0.1e-30.el6_5.2.x86_64 conflicts with file from package openssl-libs-1:1.0.1e-19.el6.x86_64
  file /usr/lib64/openssl/engines/libgmp.so from install of openssl-1.0.1e-30.el6_5.2.x86_64 conflicts with file from package openssl-libs-1:1.0.1e-19.el6.x86_64
  file /usr/lib64/openssl/engines/libnuron.so from install of openssl-1.0.1e-30.el6_5.2.x86_64 conflicts with file from package openssl-libs-1:1.0.1e-19.el6.x86_64
  file /usr/lib64/openssl/engines/libpadlock.so from install of openssl-1.0.1e-30.el6_5.2.x86_64 conflicts with file from package openssl-libs-1:1.0.1e-19.el6.x86_64
  file /usr/lib64/openssl/engines/libsureware.so from install of openssl-1.0.1e-30.el6_5.2.x86_64 conflicts with file from package openssl-libs-1:1.0.1e-19.el6.x86_64
  file /usr/lib64/openssl/engines/libubsec.so from install of openssl-1.0.1e-30.el6_5.2.x86_64 conflicts with file from package openssl-libs-1:1.0.1e-19.el6.x86_64

Any help on how to correct this??
UPDATE
Using @Michael's suggestion, I was able to update OpenSSL
Installed Packages
Name        : openssl
Arch        : x86_64
Version     : 1.0.1e
Release     : 30.el6_5.2
Size        : 4.0 M
Repo        : installed
From repo   : updates

Comment: I'm a bit confused about that `openssl-libs-1` package.  Could you do a `yum info openssl-libs*` and paste the output into your answer?
Comment: @MadHatter The package is `openssl-libs`, not `openssl-libs-1`. The 1 is the epoch.
Comment: Fair point.  I wasn't sure, so I crafted a `yum` query that should catch either.  My concern is that none of the C6 boxes I've just asked know of such a package; I'm suspicious that someone's gone *off piste* with the packages on this particular system.
Comment: @MadHatter It's a new dependency; the package was recently split up. Though it shouldn't be present in EL6, only EL7... hm, something strange is going on here.
Comment: I hate to sound like a tool, but are you sure?  The version number on his `-libs` package is 1.0.1e-19, but my systems are at 1.0.1e-30 - which presumably is later than the `-libs` split you mention - and yet `yum list openssl*` isn't admitting to their existence.  http://mirror.centos.org also doesn't seem to know about them under `6.5/` - neither `os/` nor `updates/` .
Comment: @MadHatter Um, am I sure about what exactly?
Comment: Updated main Q with info rpm -qi openssl-libs
Comment: Michael: it's irrelevant now, but I was asking if you were sure that openssl-libs was a valid C6 package, as I was fairly sure it wasn't.  I have a feeling that you updated your comment, adding the second sentence, while I was writing mine; *c'est la vie*.
Answer: You have a package openssl-libs installed on your system, but its provenance is highly questionable. No such binary package was distributed for EL6, as far as I know. While there was a package split, it applies to EL7 only.
To resolve this, you'll need to remove the questionable openssl-libs package and update the openssl package at the same time. For this you can use yum shell.
# yum shell
> remove openssl-libs
> update openssl
> run

Before you do that, you may want to look at the information for that suspicious package to see if you can identify where it might have come from. Having such packages on the system may be an indication of compromise.
rpm -qi openssl-libs

The information you posted about this package confirms that it isn't an official package but says nothing about where it came from. You almost certainly want to get rid of it immediately, and initiate a security incident, treating the system as potentially compromised.
Comment: OK, I can get behind that idea!  +1 from me, anyway.

Unable to update CentOS 6.5 & OpenSSL


Is a concurrency approach a good idea for speeding a long iteration?

Question: I have an app that does an iteration to create points on a graph over time.
While I'm gathering data for each point across the x-axis I also must execute a recursive lookup which effectually means I have a loop inside another loop. This is not scaling too well. I don't see a lot of examples of using a "divide and conquer" solution on iterations. I was thinking of using Java's Executor concurrency framework to run each loop in it's own thread, await the answers, gather the results and return them. The initial test results I'm getting don't seem that much faster. I know I should show some code but what I want to know first is if this approach has merit compared to better methods that I may not be familiar with.
Thanks in advance!
Adding some groovyish/javaish pseudo code to assist thinking about this:
class Car {
    id
    model
    make
    weight
}

for (number in listOfImportantCarIDs) {
    Car car = carsMap.get(number) // find the car we care about
    String maker = car.make //get it's 'parent'

    // get amount of all related cars
    Iterator<Car> allcars = carsMap.values().iterator();
    while (allcars.hasNext()) {
        Car aCar = alldocs.next();
        if (maker.equals(aCar.make)) {
            totalCarCount++;  // increment total related cars
            BigDecimal totalWeightofAllCars = totalWeightofAllCars.add(aCar.getWeight()); // add weight to total

            // a ghetto cache to prevent double  counting
            countedMaufacturers.add(make);
        }
    }
}

Answer: If the task for computing the y value for each x value is completely atomic for each x value, then I would think this is a good fit for an executor service. Most performance questions simply require measure, even after great lengths of reasoning about the solution. The optimal number of threads for CPU bound problems is p or p+1, keep that in mind.
Have you looked at a Dynamic Programming approach? Is it applicable for your problem? Essentially, recursion means you are solving the same problem over and over again but for slightly smaller input values. When running multiple iterations of the same recursive algorithm a program tends to often re-solve the same exact problem. Instead, a dynamic programming approach might store the solution in a cache and reference the cache before calculation the solution a second time.
Without knowing your exact problem, it is difficult to give an exact answer.
Comment: This is interesting and definitely an approach to look into. To be honest there are probably things that are being solved over and over again. A result cache/array could be useful.
Answer: It depends on what's making your loops slow.  Are they executing database queries?  Accessing a hard disk?  Otherwise doing something that causes them to wait around for an external I/O operation?  In that case, your best bet is to start adding threads until you stop seeing returns on them, you basically have to tune it.
If they're slow simply because of raw processing taking place in memory in Java, then you could try adding a thread per CPU core on your machine, but probably won't see much benefit beyond that.
Comment: I'm actually not making db calls, just iterating through a List (outer loop) and a Map of POJOs (inner loop)
Answer: Using threads will speed up your application by some small constant factor, at the price of significant added complexity for inter-thread communication. If a better algorithm exists, that can save you orders of magnitude. Therefore, I strongly recommend that you first verify that there indeed isn't a sub-quadratic algorithm to solve your problem.
Perhaps if you detailed the problem you are trying to solve and your current solution, we could assist here.
Edit: Goodness, finding a much better algorithm isn't hard at all:
for (Car car : cars {
    Stats s = stats.get(car.maker);
    if (s == null) {
        s = new Stats();
        stats.put(car.maker, s);
    }
    stats.count++;
    stats.totalWeight+=car.weight;
}

for (Car car in importantCars) {
    stats.get(car.maker);
}

There really is no need to iterate, for each important car, over all cars just to find those with identical maker ...
Answer: If your "Source" data isn't modified by your algorithm or each iteration only operates on it's own data (doesn't change nearby data) it could give you a (max) 2x speed boost on a dual-core.
That's not a great solution and as the time grows for your current solution, this will grow at 1/2 which is still quite expensive if you are in a double-nested loop.  O(X^2/2) still pretty much equals O(X^2).
If you can find a way to optimize your algorithm that has a much higher potential of real success and much less of a potential for an amazing amount of time sunk into bug fixing.
Answer: Can each point along the X-axis be computed in parallel? If so, that's your opportunity for performance improvements via multi-threading.
The Fork-Join framework will make this kind of program simple. You can get an early access version, or imitate it yourself to some extent.
Comment: I saw this but thought I'd have to wait for Java 7 to use it. Didn't realize there were early access editions.
Comment: @Vinny - Look [here](http://www.oracle.com/technetwork/java/javase/downloads/ea-jsp-142245.html) for Java 7.
Comment: Thanks for that link but I'm limited to 1.6 for production.
Answer: "a loop inside another loop" that should ring bells ;). The outer loop is always waiting for the inner one. So this is a serial execution and using threads wont change a bit. Unless each loop writes the result to a central service which can be consulted by a following event (loop) on your x-axis. So the service would be stateful...
Comment: actually the inner loop is the one writing out the result using data from the outer loop. But I get what you are saying.
Answer: i don't think concurrency can make your application faster. it can help you to run multiple task in your application, but it won't make them faster.
my experience:
try to get rid of recursive calls, that's the best way to make the app faster.
Comment: -1 for "try to get rid of recursive calls, that's the best way to make the app faster".
Comment: @z5h: what's your idea about recursive methods?
Comment: My feeling is that in many cases recursion is very useful and very fast. For example, Java's Arrays.sort is implemented with a recursive mergesort. The best way to make an app faster is "measure, don't guess". Use a profiler that TELLS you what's slow. Don't guess at what is slow.
Comment: @z5h: as you said, its your feeling. also my term was my experience.

if you can convert a recursive method to a normal method,(by using loops and sometimes stack)  the second method will be faster.

if you don't believe it, try with simple example: factorial
Comment: @m.s. yes, it will often be faster. It might also be much harder to read & debug. And the speed difference might be insignificant compared to other bottlenecks in you application. So if someone has profiled their app, and determined the *only* way to speed it up significantly is to convert a recursive algorithm to a loop/stack-based variant, then yes, go ahead. But I still think converting recursive calls to loop/stack-based as a *general rule* is poor advice.


How can I retrieve a document with a defined amount of sorted nested fields?

Question: Here is my problem: let's assume I have a Facebook post indexed on ElasticSearch. This post has many comments as nested fields, which, themselves, have a "likes" count. So, the mapping would be something like this:
<code>"mappings": {
    "post": {
        "properties": {
            "id": {
                "type": "integer"
            },
            "comments": {
                "type": "nested",
                "properties": {
                    "like_count": {
                        "type": "integer"
                    }
                }
            }
        }
    }
}
</code>
A post could have thousands of comments, but what if I want to retrieve only the 10 most liked comments from a certain post (so I'd have to define the post's id, limit a size for the field array and define a sort rule)? Is it possible? I've tried many ways using the "nested" query, but with no success.
Any ideas?
Edit: one of the queries I tried, in case anyone still has a doubt about what I want:
<code>{
    "query": {
        "match": {
            "id": 81500
        }
    },
    "sort": [
        {
            "comments.like_count":
                {
                    "order": "desc"
                }
        }
    ],
    "nested": {
        "path": "comments",
        "inner_hits": {
            "size": 10
        }
    }
}
</code>
Comment: Can you share your query?
Comment: @kiran.koduru Added one of the queries I tried.
Comment: What do you get if you remove the `nested` field? I believe it needs to go inside the `query` field according to the [docs](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-nested-query.html) and [this](https://www.elastic.co/guide/en/elasticsearch/reference/current/nested.html).
Comment: If I remove the nested field, I get all of the comments. I only want 10 of them
Answer: Try this query:
<code>{
    "query": {
        "match": {
            "id": 81500
        }
    },
    "sort": [
        {
            "comments.like_count":
                {
                    "order": "desc"
                }
        }
    ],
    "size": 10
}
</code>
Comment: Not what I need. This query brings me 10 posts, not 10 comments.


Give the values of "a" where the linear system has no solutions. Using Gauss elimination.

Question: I am having problems trying to row reduce this matrix. Particularily because of the zero in the first row. Could someone help me? I am not allowed to calculate the values of a using the determinant. I was having a bit of problems with latex so I will just write the system in text. I already made it into an augmented matrix.
$$x - 3z = -3 \\ 2x + ay -1 = -2 \\x + 2y + az = -1$$
Answer: We are going to use Gauss elimination. Suppose for now $a\ne0$.
\begin{align}
\left(\begin{matrix}1&0&-3&-3\\2&a&-1&-2\\1&2&a&-1\end{matrix}\right)&\xrightarrow{Row(2)\rightarrow Row(2)-2Row(1)}\left(\begin{matrix}1&0&-3&-3\\0&a&5&4\\1&2&a&-1\end{matrix}\right)\\
&\xrightarrow{Row(3)\rightarrow Row(3)-Row(1)\ \ }\left(\begin{matrix}1&0&-3&-3\\0&a&5&4\\0&2&a+3&2\end{matrix}\right)\\
&\xrightarrow{Row(3)\rightarrow a Row(3)-2Row(2)}\left(\begin{matrix}1&0&-3&-3\\0&a&5&4\\0&0&a^2+3a-10&2a-8\end{matrix}\right).\\
\end{align}
$a^2+3a-10=0$ for $a=\frac{-3\pm\sqrt{49}}{2}$, and so for $a=-5$ or $a=2$ the third equation has no solution and so the system has no solution.
Suppose now $a=0$; then
\begin{align}
\left(\begin{matrix}1&0&-3&-3\\2&0&-1&-2\\1&2&0&-1\end{matrix}\right)&\xrightarrow{Row(2)\rightarrow Row(2)-2Row(1)}\left(\begin{matrix}1&0&-3&-3\\0&0&5&4\\1&2&0&-1\end{matrix}\right)\\
&\xrightarrow{Row(3)\rightarrow Row(3)-Row(1)\ \ }\left(\begin{matrix}1&0&-3&-3\\0&0&5&4\\0&2&3&2\end{matrix}\right)\\
&\xrightarrow{\ \ \ \ \ \ \ \ Row(2)\longleftrightarrow Row(3)\ \ \ \ \ \ \ }\left(\begin{matrix}1&0&-3&-3\\0&2&3&2\\0&0&5&4\end{matrix}\right).\\
\end{align}
And so the system has solution for $a=0$.
Comment: Thank you, I hadn't thought of multiplying a row by "a".


Find an orthonormal basis for the eigenspace of a matrix containing a specific vector

Question: For part (b), I don't understand that given a vector v, if we already know the basis of a eigenspace $\{[1,0,0,1],[0,1,1,0]\}$, how can we know $\{v,[1,0,0,1]\}$ is also the basis of the eigenspace? and what about $\{v,[0,1,1,0]\}$?
Comment: $\mathbf{v}$ has eigenvalue 5. So you want one or more linearly independent vectors that also have eigenvalue 5. Yes both $(1,0,0,1)$ and $(0,1,1,0)$ have eigenvalue 5, And yes, $\mathbf{v}$ is a linear combination of them. So it does not matter which you use. But you need to end up with a vector which has magnitude 1 and is orthogonal to $\mathbf{v}$.
Comment: @almagest but for getting an eigenspace containing $v$, should the basis we work on be $\{v,[1,0,0,1]\}$ or $\{v,[0,1,1,0]\}$ or they are the same?
Answer: We know that the eigenspace $E$ containing the eigenvector $\mathbf{v}$ is
$$
E = \text{Span}\Bigg \{ \begin{bmatrix} 1 \\ 0 \\ 0 \\ 1 \end{bmatrix}, \begin{bmatrix} 0 \\ 1 \\ 1 \\ 0 \end{bmatrix} \Bigg \}.
$$
We know want to find a vector, let's say $\mathbf{u}$, such that $\{ \mathbf{u}, \mathbf{v} \}$ is a basis for $E$. We know that this is the case if the following criteria hold.

$\mathbf{u} \in E$
$\mathbf{u}$ is linearly independent from $\mathbf{v}$.

If we let $\mathbf{u} = (1, 0, 0, 1)^{T}$, and since there is no such $c \in \mathbb{R}$ such that $c \mathbf{v} = \mathbf{u}$, we can conclude that $\mathbf{u}$ is linearly independent from $\mathbf{v}$. Since it is also clear that $\mathbf{u} \in E$, it follows that $\{ \mathbf{u}, \mathbf{v} \}$ is a basis for the eigenspace $E$.
As you suggest, it is also the case that  $\{ \mathbf{u}, \mathbf{v} \}$ is a basis when we let $\mathbf{u} = (0, 1, 1, 0)^{T}$, since it is clearly an element of $E$, and clearly linearly independent of $\mathbf{v}$. There are in fact an infinite number of vectors that hold the criteria for vector the $\mathbf{u}$, we can just pick an element of the eigenspace $E$ that is linearly independent from $\mathbf{v}$.
Answer: Since $\{[1,0,0,1],[0,1,1,0] \}$is a basis, so is $\{[1,1,1,1],[1,0,0,1]\} $
Let r=[1,1,1,1], s=[1,0,0,1] Then $\{r,s-(r\bullet s/r\bullet r)r\} $
$$=\{[1,1,1,1],[1/2,-1/2,-1/2,1/2]\} $$ is an orthogonal basis by the Gram, Schmidt procedure. Normalizing the first vector, we obtain the desired orthonormal basis containing
v, viz $$\{[1/2,1/2,1/2,1/2],[1/2,-1/2,-1/2,1/2]\} $$ The other part is done similarily.


Import registry file to registry using windows API

Question: I am trying to write some C/C++ code that will import a .reg file into the registry. The MSDN has functions for importing a file for specific keys but I want to import for example the entire HKCU hive.
Comment: "I want to import for example the entire HKCU hive" is a recipe for disaster.  Significant portions of the per-user registry take permanent values at the time of user profile creation and should not be overwritten.  You could talk about a backup and restore operation, but not "import".
Answer: There is no Win32 API for importing a .reg file into the Registry 1. You will have to parse the file yourself and translate the instructions into appropriate Registry API function calls as needed - Reg(Open|Create)KeyEx(), RegSetValueEx(), RegDelete(Key|Value)(), etc.
1: don't be confused by the existence of RegLoadKey(), RegReplaceKey(), and RegRestoreKey().  They are intended for loading files created by RegSaveKey/Ex(), which are not text-based .reg files.
Otherwise, you can just use ShellExecute/Ex() or CreateProcess() to execute regedit.exe /s <filename> or reg.exe import <filename> with the path to the .reg file as a command-line parameter, letting regedit/reg handle the import for you.  This would be the easiest way to go.
Comment: There's also `reg.exe` with its `/import` switch, if you're going to spawn an external tool.  Notably `reg.exe` doesn't require admin rights unless the registry operations require them, whereas `regedit.exe` is marked to always elevate.
Comment: @BenVoigt Thanks, I have updated my answer


WINAPI: Get a List of Devices by their NT name

Question: This article explains how to Query logical DOS names for their NT naming convention using QueryDosDevice. It explains how to add and remove Logical Device names using their NT naming convention using DefineDosDevice. The article explains that a DOS name is required to access various devices.

"Win32 programs cannot use internal
  Windows NT device names to access
  devices because the Win32 subsystem
  and Win32 API require the more
  familiar drive letters and MS-DOS
  device names, such as A:, C:, COM1:,
  and LPT1"

I found this interesting article that gets all the available DOS Names and then queries for the NT Name using the function GetLogicalDriveString. This article does not explain how to return all defined DOS names for devices, just drives.
However, I would like to know how to do the reverse. How would I get a list of NT device names. I am not looking for just drives but all devices. For example LPT1 and COM1 are reserved DOS names that correspond to specific NT names. I would like to map additional devices they may not have a DOS name so that I can use the WINAPI function CreateFile.
How do I get a list of all NT device names oppose to DOS Names?
Comment: Is this even possible without using the Windows Driver Development Kit? I would like to keep with the regular WINAPI if possible.
Answer: Well underneath the hood the DosDevice's are symbolic links in the NT Object Manager database pointing to the underlying devices. I would recommend playing with WinObj to get a feel for how things are put together.
Unfortunately to do the enumeration yourself and to add your own custom symbolic links you would need to use the native NT apis (see this for abit on enumerating stuff). You can sometimes play some tricks with the DefineDosDevice function to do some mappings, however you don't actually need to do that if you just want to access objects through CreateFile. You can use the NT native escape syntax to access anything in the NT Object Manager database, just prefix your native path with \\?\GLOBALROOT and pass that to the CreateFile, e.g. if you want to access the floppy drive use CreateFile(L"\\?\GLOBALROOT\Device\Floppy0", ...);
Comment: What if the symbolic link does not exist? I would like to create symbolic links dynamically. Perhaps a create a symbolic link for each device.
Comment: That is it NtQueryDirectoryObject where the buffer is set to OBJECT_DIRECTORY_INFORMATION 'Device'
Answer: The docs for QueryDosDevice mention:

lpDeviceName - This parameter can be NULL. In that case, the QueryDosDevice function will store a list of all existing MS-DOS device names into the buffer pointed to by lpTargetPath.
lpTargetPath - If lpDeviceName is NULL, the function retrieves a list of all existing MS-DOS device names. Each null-terminated string stored into the buffer is the name of an existing MS-DOS device, for example, \Device\HarddiskVolume1 or \Device\Floppy0.

So have you tried doing:
QueryDosDevice(NULL, buffer, buffer_size);

That should get you a list of device names in the buffer.
Comment: That is definitely better than GetLogicalDriveStrings for MS-DOS names but it does not return the NT names.
Comment: @Shiftbit: What other devices are you looking for?
Answer: The API you are looking for is WMI. Incidentally, that was already answered as well: How do I list device types using WMI?


Merging output of Print.module's printpdf with existing PDFs

Question: Recently, I created an output template for the Print module, such that it dynamically generates a measurement sheet when a certain content type is parsed by its PDF functionality (using dompdf in this case).
Everything works great, but the client's requested file attachment fields for PDFs, such that existing PDFs are added to the end of dompdf's output. For instance, a PDF of a CAD drawing would be attached in Drupal, printpdf/$nid generates the template I've created, and the file locations given from the file upload fields are used to merge the files at those locations with the generated PDF.
dompdf apparently cannot merge PDF documents, so I'm thinking a workaround would be to generate the PDF and save to disk somewhere, run another PDF merger script, then present the merged output to the user.
How would one go about programmatically saving the output of Print.module's PDF generator to somewhere on the server, then running an external class on that saved output?
(Alternately, if you know of a way for dompdf to read PDFs and append them to the document, that'd work even better.)
Answer: I hacked print_pdf.pages.inc to merge PDFs after creation based on the existence of a filefield:
Starting at line 209, in function _print_pdf_dompdf();
<code>    $node = $print['node'];
    if ($node->field_pdf[0]) {
        $meas_pdf = $dompdf->output();
        file_put_contents($base_path . 'sites/default/files/pdf_temp.pdf', $meas_pdf);
        include $base_path . 'sites/all/libraries/PDFMerger/PDFMerger.php';
        $newpdf = new PDFMerger;
        $newpdf->addPDF($base_path . 'sites/default/files/pdf_temp.pdf', 'all');
        foreach ($node->field_pdf as $attach) {
        $newpdf->addPDF($base_path . $attach['filepath'], 'all');
        }
        $newpdf->merge('download', 'measurements.pdf');
    }
    else {$dompdf->stream($filename, array('Attachment' => ($print_pdf_content_disposition == 2))); }
}
</code>
It'd be great to write a module that undefines Print.module's private _print_pdf_dompdf(); function and replaces it with my own (so I'm not hacking a contrib module); any idea how I'd go about that?


Ajuda com uma consulta mysql

Question: pessoal to quebrando a cabeça aqui com uma consulta que montei onde pego as datas informadas no formulário e busco no banco de dados.
ele faz a consulta só que não traz todos os dados
Se eu informo a data inicial de 01/01/2017 até a data de hoje 15/11/17 ele somente traz até o dia 13/10/2017.
se informo apenas a data inicial ele traz todas as informações, se informo apenas a data final ele não traz nada, então o meu problema está na data fim <=
como arrumo isso?
o meu select está assim:
<code>SELECT c.dia, c.mes, c.ano, c.id id_pedido, c.total total_pedido, c.tipo, d.cat_id id_prod,
SUM( d.valor_total ) total_prod
FROM lc_controle c
INNER JOIN lc_detalhe d ON d.controle_id = c.id
WHERE c.tipo =  '0'  and
        ano >= '$anoIni' AND
        mes >= '$mesIni' AND
        dia >= '$diaIni' AND
        ano <= '$anoFim' AND
        mes <= '$mesFim' AND
        dia <= '$diaFim'
    GROUP BY
        c.id,
        c.total,
        d.cat_id
</code>
Answer: O correto é você usar o BETWEEN:
<code>$data_inicial = "2017-01-01";
$data_final = "2018-01-01";

SELECT c.dia, c.mes, c.ano, c.id id_pedido, c.total total_pedido, c.tipo, d.cat_id id_prod,
SUM( d.valor_total ) total_prod
FROM lc_controle c
INNER JOIN lc_detalhe d ON d.controle_id = c.id
WHERE data BETWEEN '".$data_inicial."' AND '".$data_final."'
AND WHERE c.tipo =  '0'
    GROUP BY
        c.id,
        c.total,
        d.cat_id
</code>

Ajuda com uma consulta mysql


Azure Resource Manager Virtual Machines LUN limit of 4?

Question: Add-AzureVMDataDisk (for classic VMs) allowed me to specify a LUN from 0-15. Now Add-AzureRmVMDataDisk (for ARM VMs) has a limit of 0-3.

Why the change?
How can I add more that 4 disks to my ARM VM?
Answer: the number of data disks you can add to an ARM VM is dependent on its family and size, so a A2 VM can have 4 data disks but an A3 VM can have up to 8 data disks. at the top end some of the D and G family VMs can have up to 32 data disks. if you use the ARM portal http://Portal.Azure.com to create a virtual machine you can see all the details of the VM including the number of Processors, the amount of RAM and the number of data disks you can have.


Python count Null and not Null values in Dataframe

Question: I have a dataframe
Date  Name
1995  Harry
1995  John
1997  NaN
1995  NaN
1998  Nina
1998  NaN
1997  Carrie

I need to count a NaN/(not NaN) values for each Date. So the output should be
Date Nan/NaN+notNaN
1995 1/3
1997 1/2
1998 1/2

I was trying with
df.groupby(['Date']).agg({'Name' : 'count'})
but can i do the same with
df.groupby(['Date']).agg({'df.Name.isnull()' : 'count'}) or smth like that?
Answer: What about something like that:
In [52]: df.groupby('Date').agg({'Name': lambda x: x.isnull().sum(), 'Date': 'count'})
Out[52]:
      Name  Date
Date
1995     1     3
1997     1     2
1998     1     2

Or you could do following:
In [60]: df.groupby('Date').agg({'Name': lambda x: x.isnull().sum().astype(str) + '/' + str(x.size)})
Out[60]:
     Name
Date
1995  1/3
1997  1/2
1998  1/2

Or with format:
In [62]: df.groupby('Date').agg({'Name': lambda x: '{}/{}'.format(x.isnull().sum(), len(x))})
Out[62]:
     Name
Date
1995  1/3
1997  1/2
1998  1/2


With the route generated by the Vanity gem, what is the Rails route helper I can use?

Question: This is the route the Vanity gem generates:
controller :vanities do
  match ':vname' => :show, :via => :get, :constraints => {:vname => /[A-Za-z0-9\-\+]+/}
end

This is the rake routes:
GET    /:vname(.:format)                       {:vname=>/[A-Za-z0-9\-\+]+/, :controller=>"vanities", :action=>"show"}

How do I use the Rails link helper to link directly to URL mydomain.com/vname?
Answer: From the top of my head (sorry, I don't really have the time to test it right now):
controller :vanities do
  match ':vname' => :show, :via => :get, :constraints => {:vname => /[A-Za-z0-9\-\+]+/}, :as => :vanity
end

which you would use like this:
vanity_path(:vname => "marcamillion")

Comment: DUDE!!! You are on FIRE tonight. Thanks much. This is exactly what I needed. Thank you, thank you, thank you :)
Comment: Funny, mornings usually aren't my thing ;-)
Comment: Btw Mr. Fireman, how about this one: http://stackoverflow.com/questions/7394701/how-do-i-render-a-partial-for-a-view-of-a-nested-resource-rails-3-1  :)


How to get values from Deserialized JSON object?

Question: I'm trying to import JSON, parse it and be able to use it throughout my app. For example I would like to loop through and be able to print out the years. How would I go about doing that?
Code:
var result = await content.ReadAsStringAsync ();

try
{
    List<RootObject> list = (List<RootObject>)JsonConvert.DeserializeObject<List<RootObject>>(result);

}

catch (Exception e) {
    Console.WriteLine (e);
}

JSON:
{
    "ROWCOUNT": 3,
    "COLUMNS": [
        "YEARMFG",
        "MAKE",
        "MODEL",
        "ENGINE",
        "TOWLIMIT",
        "NOTE1",
        "NOTE2"
    ],
    "DATA": {
        "YEARMFG": [
            2012,
            2012,
            2012
        ],
        "MAKE": [
            "Chevrolet/GMC",
            "Chevrolet/GMC",
            "Chevrolet/GMC"
        ],
        "MODEL": [
            "Avalanche 1500 4WD",
            "Avalanche 1500 4WD",
            "Avalanche 1500 4WD"
        ],
        "ENGINE": [
            "5.3L V-8",
            "5.3L V-8",
            "5.3L V-8"
        ],
        "TOWLIMIT": [
            5000,
            5500,
            8000
        ],
        "NOTE1": [
            "3.08 axle ratio",
            "3.42 axle ratio",
            "3.42 axle ratio"
        ],
        "NOTE2": [
            "",
            "",
            "Cooling or other accessory package required "
        ]
    }
}

Classes:
public class DATA
{
    public List<int> YEARMFG { get; set; }
    public List<string> MAKE { get; set; }
    public List<string> MODEL { get; set; }
    public List<string> ENGINE { get; set; }
    public List<int> TOWLIMIT { get; set; }
    public List<string> NOTE1 { get; set; }
    public List<string> NOTE2 { get; set; }
}

public class RootObject
{
    public int ROWCOUNT { get; set; }
    public List<string> COLUMNS { get; set; }
    public DATA DATA { get; set; }
}

Comment: What problem are you currently having? Is there an exception?
Comment: What happens when you run the code you've given us? You appear to be on the right track, so its hard to tell what is currently tripping you up.
Comment: based on what he has shown it appears that he's trying to parse it and it doesn't look correct from first glance - http://stackoverflow.com/questions/6620165/how-to-parse-json-in-c
Comment: I was told to add some classes from the JSON using json2csharp. My thought was I would be able to do list.YEARMFG or something like that. How do I access my values from json in the list?
Answer: Assuming your objects and GetJson() just returns the JSON string:
var obj = JsonConvert.DeserializeObject<RootObject>(GetJSON());
foreach (var year in obj.DATA.YEARMFG)
{
    Console.WriteLine("Year: {0}", year);
}

Which should output (based on your sample data):
Year: 2012
Year: 2012
Year: 2012

Side note: You don't have to deserialize to a List<RootObject>. RootObject should be a single entity (as it wraps your entire JSON data). So simply deserialize it to a single instance, then access the DATA property and iterate over YEARMFG.
Comment: Thanks Brad. This worked for me. I'm not sure if this is the semantic way of doing this, but it did work. Seems like I could just get away with having a DATA class instead of both DATA and RootObject.
Comment: You need `root` to decipher the `DATA` property within. You could just use `class RootObject { public DATA DATA { get; set; } }` if that's all you care about though.
Answer: You are deserializing a List<RootObject>, so each element in the List is a RootObject.  You can see in your class that RootObject has a DATA property, which contains a List<string> of the YEARMFG.
You should be able to access the items in your list like so:
list.DATA.YEARMFG will give you a list of the years for a given item.
If you would like to display them individually, you can loop through the list:
foreach (var yr in list.DATA.YEARMFG)
{
    // handle individual year info here
}

Comment: I thought that as well. But it only appears I can use `list` to Add, Count, Add Range, etc...normal Collections.List properties.