text:
layout: post
title: Zaanse Schans for windmills
categories:
- Learning
---

- **Place**: [Zaanse Schans](http://www.zaanseschans.nl/) beside river Zaan, North Netherlands
- **Famous**: Windmills... there are still 6 working mills there
- **Best Time to go**: anytime

**How to go**: some [suggestions](http://www.virtualtourist.com/travel/Europe/Netherlands/Provincie_Noord_Holland/Zaanse_Schans-2271918/Transportation-Zaanse_Schans-BR-1.html)...

1. Amsterdam Central station to Koog-Zaankijk station
2. 15 min walk from the station by following the signs

or

1. Take bus 91 from Amsterdam Central station in 50 min

**Cost**: Round-trip in train costs about 7.5 Euro. Viewing the windmills is free.

**Some links**:

- [link 1](http://www.amsterdam.info/excursions/zaanse-schans/)
- [a blog entry](http://notourist.wordpress.com/2007/07/11/zaanse-schans/)
- [some more related links](http://www.uky.edu/OtherOrgs/KPS/pages/conferences/netherlands/pages/zaanseschans.htm)


text:
\documentclass[a4paper, 11pt]{article}

\usepackage[utf8]{inputenc}
\usepackage{booktabs}

\begin{document}

\section*{Summary so far}

\section*{Creighton study}

\subsection*{Intro and methods}

Creighton et al. found obesity-associated genetic signature that is specific to obese samples, but not in the lean or overweight samples.
The study used pretreatment breast tumour biopsies from 103 patient (77 Caucasian, 16 Black, and 10 Asian patients).
They noticed that the Black patients were more likely to be obese compared to the Caucasian patients (13/16 vs. 22/77).

The quality of the tumour (tumour cell enrichment per biopsy - i.e. ratio of tumour cells and normal cells) was controlled by trimming the sample in such a way that the tumour cells in each sample were $\geq$ 70\% enriched.
Expression of genes from these samples were quantified using an affymetrix HG-U133A microarray chip.

The samples were split into three groups using the patient BMI status.
``Tumours from obese patients were not particularly enriched for a specific molecular subtype, as defined by ER and HER2 status''.

\subsection*{Results}

First, they looked for any genes that were differentially expressed in any of the three BMI groups.
Unsupervised hierarchical clustering of the genes separated the tumours based on the ER status rather than BMI status.
They used ANOVA to look for any genes differentially expressed in any of the three BMI groups.
From this, they got 658 probes at p \textless 0.01, which greatly exceeded the number you would get by chance (approx. 22000 genes $\times$ 0.01 = 220 genes).
In a heatmap of these 658 gene probes, they noticed that almost all of the genes were differentially expressed in the obese group compared with both overweight and lean group (overweight and lean group appeared homogeneous).

Since the overweight and lean groups looked similar to each other, they grouped these two into a single group and looked for differentially expressed genes between the obese and non-obese groups.
They found 799 gene probes that were p \textless 0.01 and fold change \textgreater 1.2.
They only found a median of 82 gene probes when they chose random samples to do gene expression analysis (1000 permutations done), showing that the 799 gene probes were statistically significant.

The heatmap with these genes (fig1 of their paper) showed that the expression was uniform in the obese group, and not specific to tumour grade, ER/PR/HER2 status.
This was validated in the supplementary figure 4 (haven't looked at it, but I assume it's a figure of box plots showing no significant difference between obese and non-obese groups).\\

They then decided to to use other publicly available breast tumour data to see the relevance of their signature in other data.
They ranked each sample according to the obesity-associated gene signature they have found (metagene and transformation matrix on other data).
The results showed that high obesity gene signature scores correlated with a shorter time to metastasis and may represent genes that promote cancer progression only in van de Vijver dataset.
``... this association with worse outcome may be dependent on the specific patient population under consideration.''

There was no overlap in the genes activated by insulin growth factor (IGF-1) and other oncogenic pathways (MAPK and PI3K) and the genes highly expressed in obesity-associated tumours.
There was some overlap (\textless 12\%) in genes repressed by IGF1/MAPK/PI3K pathways and the genes low in obese samples.
They concluded that the obesity-associated genetic signature was distinct from oncogenic pathway signature (different oncogenic mechanism in obese samples?).

They did a metagene analysis with their data and other data with the IGF-1 signature.
With their dataset, high IGF-1 score was observed in obese tumour group, compared to the rest of the tumours.
In other publicly available datasets, they found that high IGF-1 scores correlated with high obesity-associated scores (table 2 in their paper).
They didn't mention the correlation of obesity-associated scores and IGF-1 scores in their original data.
Shows that both IGF1 and obesity-associated signatures are able to split the samples based on their BMI status, and/or contribute to cancer progression, but in an independent way?
Maybe IGF1 uses mechanism x, whereas obesity-associated genes use mechanism y, but both contribute to cancer progression.

\section*{Fuentes-Mattei study}

coming soon

\section*{What I have been doing (chronologically)}

\subsection*{Data access and processing}

First, I downloaded all the clinical data for all cancer types available online from the ICGC database and checked which cancer types had patient height and weight data.
There were 14 cancer types in total that had both height and weight data, but only 8 cancer types from this list had RNA-seq data available.
This gave me 8 cancer types to work with:
\begin{description}
	\item[BLCA] Bladder urothelial carcinoma
	\item[CESC] Cervical squamous cell carcinoma and endocervical adenocarcinoma
	\item[COAD] Colon adenocarcinoma
	\item[KIRP] Kidney renal papillary cell carcinoma
	\item[LIHC] Liver hepatocellular carcinoma
	\item[READ] Rectal adenocarcinoma
	\item[SKCM] Skin cutaneous melanoma
	\item[UCEC] Uterine corpus endometrial carcinoma
\end{description}

The RNA-seq data for these cancer types were downloaded from TCGA database.

\subsubsection*{Normalisation and standardisation}

Creighton and Fuentes-Mattei data were imported into R and normalised using rma function.
These data were standardised to have a mean of 0 and standard deviation of 1.

The cancer data were imported into R and checked for the samples that had both height and weight data.
Any samples without height and/or weight data were removed from the analysis (removed from both the clinical data and RNA-seq data).
After this, all of the cancer data were normalised using Voom function  from limma (after it has been logged to the base 10).
These were then standardised just like the Creighton and Fuentes-Mattei data (mean = 0, sd = 1).

\subsection*{Metagene analysis and transformation matrix}

\subsubsection*{Creighton's obesity-associated genes}

799 gene probes identified by the study were used to see if the obesity-associated genetic signature was able to separate the samples based on their BMI status in different cancer types.
First, I checked that these gene probes were able to separate the samples based on their BMI status like they have said in their paper.
After normalising and standardising the data, a metagene  was made using SVD.
Metagene represented each of the sample's obesity-associated gene expression level (i.e. obesity-associated gene scores that was described in the Creighton paper).

The overall gene expression level of each sample correlated with their metagene score (i.e. high/low expression of the genes when metagene was high/low).
To confirm that the metagene score was actually separating the samples based on the BMI status, a boxplot was made with the BMI status against the metagene score, as well as a scatter plot of the metagene against raw BMI value of each sample.
These plots showed that the metagene scores were able to separate the samples into obese or non-obese groups, showing that the obesity-associated gene signature was real in their data.

\subsubsection*{Transformation of Creighton obesity genes to TCGA cancer types}

To transform the cancer data using a list of genes from another data, the transformation matrix from the SVD must have the same number of genes in both datasets (due to matrix multiplications).
So, to make sure that both the Creighton and TCGA data had the same genes, the probe IDs of the obesity-associated genes were converted into gene symbols first (as TCGA data is RNA-seq data, not microarray).

The gene symbols were matched against the genes present in one of the cancer types downloaded (all cancer types had the same genes, so the resulting gene list was applicable to other types).
Any duplicates of gene symbols or gene probe IDs  were removed using the collapseRows function from WGCNA package.

Transformation matrix was formed from the resulting list of genes that were common in both the Creighton and TCGA cancer data.
The cancer data were transformed using this matrix, and the first column of the resulting matrix was used as the metagene for that cancer type.

Heatmaps were made for each cancer type, using the metagene from the transformation.
The overall gene expression profile for each cancer type correlated with the metagene score (i.e. high/low metagene score corresponded to high/low expression level of the selected genes).
To confirm whether this association was based on the BMI status of the samples, a boxplot and a scatter plot was plotted with the metagene scores against the BMI status and raw BMI value of the samples.

Surprisingly, the apparent correlation of the overall gene expression level with metagene scores were not related to the sample BMI status -- the metagene scores were not able to separate the samples based on their BMI status like in the Creighton dataset.

Since clinical data was not available  for Fuentes-Mattei  dataset, it was not possible to validate the Creighton obesity-associated genes on this dataset.
However, assuming that the genetic signatures identified by Fuentes-Mattei were obesity-associated, it was possible to see whether their signature was able to separate the samples based on BMI status.

\subsubsection*{Transformation of Fuentes-Mattei obesity genes to Creighton and TCGA cancer types}

Like with Creighton data, the gene signature from Fuentes-Mattei study was used to make a metagene and a transformation matrix.
Again, any genes not present in the TCGA data were removed from the signature to make sure that both data sets had the same genes for transformation.

Metagene was created in the Fuentes-Mattei data first and heatmap was produced.
The heatmap showed that the overall gene expression for each sample correlated with the metagene score, which was expected.
Since there was no clinical data available for the data set, the ability for the signature to separate the samples into obese or non-obese was not checked.

To see if the Fuentes-Mattei signature was able to be used in other data, Creighton and TCGA data were transformed using the Fuentes-Mattei signature.
Data was transformed and heatmaps, boxplot, and scatter plots were made for each data set to see if the signature correlated with overall gene expression and/or BMI status.

The heatmaps for all the data showed similar results as before, in that the overall gene expression of the samples correlated with the signature, but was not able to separate the obese samples from non-obese samples.
This result showed that the signature from Fuentes-Mattei study captured the overall gene expression of the samples, but the signature was not specific to the BMI status of the samples.

These results suggested that the signatures from previous studies are not able to identify the obese samples from the non-obese samples in different cancer types, and possibly not even in the same tumour type.

\subsubsection*{What I think about the results}

The lack of identification in different tumour types can be explained by different tumour biology in different tumours, together with tumour heterogeneity and other factors that are specific to the local environment of the tumour.

However, the lack of evidence in the same tumour types was unexpected, as the tumour biology should be similar to one another, if not the same.
Obvious difference between the two data sets was that Fuentes-Mattei study used tumour samples from ER positive patients, whereas the Creighton study used all the tumour types available at the time.
It could be that the Fuentes-Mattei signature was specific to ER+ samples (Note: repeat the same analysis but use only ER+ samples from Creighton data).

Another reason could be that, since the tumours are known to be heterogeneous, the samples used in either studies were significantly different from each other.
This may result in signatures that they thought was ``tumour specific'', but in fact it was quite different to what they have expected.
I guess if those studies used more samples, you might be able to capture the effect of tumour heterogeneity more and dampen the effect that is complicating the signature's ability to identify obese samples.
(Creighton's group did mention that their signature ``may be dependent on the specific patient population under consideration''.)\\
\newline

Since the signatures identified by either studies could not separate the obese samples from non-obese samples, we decided to see whether there were any differentially expressed genes common in all cancer types (that are specific to obesity).
If there was any, then use these genes to see if it can identify the obese samples from non-obese samples in Creighton data set.

\subsection*{Gene expression analysis}

\subsubsection*{Creighton data}

I first started the analysis on the Creighton data to check their results.
I have splitted the samples into two groups like in the study, but in two different ways: lean vs. overweight/obese, and lean/overweight vs. obese.

\begin{center}
	\begin{tabular}{ccc}
                                  & P \textless{} 0.05 & P \textless{} 0.01 \\
		\hline
		Lean vs. overweight/obese & 759              & 104              \\
		Lean/overweight vs obese  & 5278             & 1781             \\
	\end{tabular}
\end{center}

The adjusted p-values were not used, as no genes showed up when adjusted.
These results were different from the original Creighton data, which was mildly concerning...
(Didn't check for the overlaps of the obesity-associated genes with the genes I found, but I did that later on).

\subsubsection*{Common genes in TCGA cancer types}

To see if there were any genes common across all cancer types, I did a gene expression analysis on each cancer type.
The samples were split into two groups as in the Creighton study: obese vs. non-obese.
Each cancer type was logged to the base 10 and Voom normalised before a linear model was fitted to the data.
The names of the significantly expressed genes with p-value \textless{} 0.01 for each cancer type was recorded and compared with the other cancer types (forgot to check the fold changes).

\begin{center}
	\begin{tabular}{cccc}
             & Lean & Overweight & Obese \\
		BLCA & 103    & 97         & 61 \\
		CESC & 85     & 62         & 77 \\
		COAD & 75     & 80         & 71 \\
		KIRP & 26     & 53         & 45 \\
		LIHC & 140    & 75         & 49 \\
		READ & 22     & 36         & 15 \\
		SKCM & 72     & 73         & 73 \\
		UCEC & 90     & 106        & 286 \\
	\end{tabular}
\end{center}

The number of genes that were present in any two cancer types were noted down, and was repeated for the genes present in any three cancer types, and so on.
This was repeated for groups with randomly chosen samples and were repeated 100 times (the proportion of the groups were kept the same - refer to the table above).

\begin{center}
	\begin{tabular}{ccccccccc}
		& \multicolumn{8}{c}{Number of cancer types the gene overlapped} \\
                                     &    1 &    2 &   3 &  4 & 5 & 6 & 7 & 8 \\
		\midrule
		         Obese vs. non-obese & 6865 & 1907 & 289 & 26 & 1 & 0 & 0 & 0 \\
		Randomly split sample groups & 5012 &  870 &  89 &  6 & 0 & 0 & 0 & 0 \\
	\end{tabular}
\end{center}

This table showed how the number of differentially expressed genes across all cancer types were consistently greater  than the amount of genes found between randomly split groups of samples.
I think I had a number for the 95$^{th}$ percentile, but I can't find it right now -- might have to re-do it... (I think the result shown was still over the 95$^{th}$ percentile mark).
(I think I have a result from 1000 iterations somewhere -- still looking for the results).

This result shows that the number of differentially expressed genes observed between the obese and non-obese groups were greater than the number of genes one would expect by chance.
However, as you can see from the table, there were no differentially expressed genes that were common across all cancer types, suggesting that there may be no general cancer markers that are specific to obesity.\\

After this, we decided to see whether there were any significant pathways expressed in any of the cancer types, and if there is any, check the relevance of the pathway in obesity and/or cancer and use the genes that are involved in those pathways as a starting point for further analysis.

\subsection*{Pathway enrichment analysis}

First, I made a matrix of genes by pathway for each of the pathway databases (reactome, KEGG, and GO).
Since the GO database had the most pathways and genes recorded, I decided to use this for the analysis.
For each cancer type, I listed all of the significantly expressed genes between obese vs. non-obese groups.
These genes were used to pull out the relevant genes from the matrix that I have made, which was used to do Fisher's exact test on.
The results were corrected for multiple testing, using FDR control.

The results (not shown) showed that there were  no significantly enriched pathway in any of the cancer types investigated.
To see whether this was due to the genes being ``almost'' significant (and thus not included in the Fisher's test), I used the rank-based approach.
I used the camera function from the limma package (as geneSetTest function was ``out-dated'' according to the manual).
However, this still gave the same result as the Fisher's test, where none of the pathways were significantly enriched in any of the cancer types.

At this point, we went back to the Creighton data to see whether their obesity-associated genes were actually related to obesity and no other clinical variables were not affecting the signature.

\subsection*{Creighton data revisited}

Firstly, I re-did the gene expression analysis on the Creighton data and compared the genes that I found significant with their obesity-associated genes.
Although all of Creighton's obesity-associated genes showed up in the list of genes that were p \textless{} 0.01, not all gene were in the top 799 genes in that list.

The 799 genes that I have found were able to separate the obese group from the non-obese group like in the Creighton paper, even though the genes that were present in the list were quite different to the obesity-associated genes from Creighton's paper.
To support this, the metagene scores from my 799 genes were compared with the metagene scores from the Creighton's obesity-associated genes by plotting it on a scatter plot.
This showed that both metagene scores were similar to one another, showing how both sets of genes are ``markers'' for obese patients' cancer, even if the genes they are derived from are different.

When the genes that were common in both sets of genes (my genes and Creighton's genes) were used, it showed slightly better seapration of the obese samples from the non-obese samples (239 genes used).\\

To make sure that the genes were not affected by any other clinical variables that are not related to obesity, a linear model was constructed with those variables included in the model.
The variables included age, race, menopause status, tumour grade, LN status, ER status, PR status, and HER2 status.
The residual data (remaining data after controlling for these varaibles) were used to get the differentially expressed genes between the obese and non-obese groups.

In Creighton's study, they stated that they found 799 gene probes that were p \textless{} 0.01 and fold change \textgreater{} 1.2 between the obese and non-obese groups.
However, there were not many gene probes with fold change greater than 1.2 (132 genes) even after logging/exponentiating, and there were significantly greater number of genes with p \textless{} 0.01 (more than 799 gene probes).
Again, all of the genes that Creighton's team had identified were in the list of significant genes, but not all of them showed up in the top 799 genes.

The heatmaps of the metagene scores from the top 799 genes (from residual data), Creighton genes that were in the top 799 genes (216 genes) showed similar results as the genes identified before controlling for other clinical variables.
There were 140 genes present in the 799 residual genes that were also in the 239 genes found to be common in both Creighton and my 799 genes (from raw data).
The metagene scores generated from these genes showed better separation of the groups compared to either one on its own, similar to the results with 239 genes.\\

To completely control for the effect of race in the analysis, differentially expressed genes were also obtained using only the Caucasian samples (n = 77).
The top 799 genes were obtained, as well as the common genes from the Creighton genes that were in those 799 genes (x genes).\\

Now, all of the genes mentioned above were used to construct a transformation matrix in the raw data (unadjusted for clinical variables).
These matrices were used to transform the cancer data and metagene scores were obtained as described in previous section.
Unfortunately, none of the gene sets used were able to separate the samples based on their BMI status.

\section*{Summary (of a summary)}

It seems like that none of the genes that are differentially expressed in obese samples can not be used as a marker for obesity in other cancer types, nor in the same cancer type but with a different sample population.
This was mentioned (very briefly) in the Creighton paper, when they were talking about other publicly available human breast tumour data.

As mentioned earlier, this could be due to different cancer types having different tumour biology to one another, together with the tumour heterogeneity within and between the samples.
Sample quality of the tumours used in the studies may have been problematic as well, especially in the TCGA cancer data, as we don't know how those samples were taken and sequenced.
Greater sample size and/or quality of the samples would help us focus on the true obesity-associated gene signature. (maybe).\\

I guess the results from the pathway enrichment analysis support the idea of sample variability and quality.
If all the cancer samples were developing in a similar fashion to one another, then there would be at least a single pathway coming up as significant.
Seeing that there are no pathways coming up as significant, it suggests that the sample size and/or quality was too poor to find anything in common.

An alternative explanation (or together with poor sample quality and size) could be that there were no significantly enriched pathways because the samples were so different from one another.
It could be that each tumour sample has different pathways activated compared to other samples, but still getting the same net result (cancer progression).
If this was true, this would suggest that there are a huge number of independent pathways that a tumour could take to progress through cancer, with no overlap or ``bottleneck'' pathway.
However, I doubt that this would be the case as there are very limited number of major oncogenic pathways for cell cycle/proliferation/transcription which the cancer will eventually have to take.\\

Although all of Creighton's obesity-associated genes came up in the list of significantly differentially expressed genes, it was concerning to find that not all genes found by Creighton were not in the top 799 genes of the genes that I have found.
Also, there were not many genes that were expressed at a fold change greater than 1.2 like they have claimed in their paper.
The difference in these results was probably due to the difference in the methods used, rather than other clinical variables affecting the analysis.

The fact that none of the obesity-associated gene sets found in the analyses (with or without controlling for other clinical variables) were able to separate the obese samples from the non-obese samples strongly suggests that there may not be any obesity-associated genetic signature for cancer that can be applied in general (at least in the samples currently available to us).\\

\section*{Future directions}

\begin{itemize}
	\item (Re-)do everything that I have missed so far -- i.e. side notes throughout this summary.
		\item Still working on what to do next.
\end{itemize}

\end{document}

redpajama_set_name: RedPajamaGithub


text:
/**
 * Search Tool
 *
 * @class search-vm
 */

(function() {

    "use strict";

    define([
            "dojo/dom-construct",
            "dojo/_base/array",
            "dojo/_base/lang",
            "dojo/on",
            "dojo/dom-style",
            "esri/dijit/Search",
            "esri/layers/FeatureLayer",
            "esri/tasks/locator",
            "esri/geometry/Extent",
            "esri/graphic",
            "esri/symbols/PictureMarkerSymbol",
            "esri/symbols/SimpleFillSymbol",

            "dojo/text!app/views/search-view.html",
            "app/models/map-model",
            "app/config/searchConfig",
            "app/vm/demographic-vm",
            "dojo/domReady!"
        ],
        function(dc, da, lang, on, ds, Search, FeatureLayer, Locator, Extent, Graphic, PictureMarkerSymbol, SimpleFillSymbol, view, mapModel, searchConfig, demographicVM) {

            var SearchVM = new function() {

                /**
                 * Store reference to module this object.
                 *
                 * @property self
                 * @type {*}
                 */
                var self = this;

                /**
                 * Initialize the class.
                 *
                 * @method init
                 */
                self.init = function() {
                    dc.place(view, "titlebar", "after");

                    var s = new Search({
                        enableLabel: false,
                        autoNavigate: false,
                        maxSuggestions: 4,
                        enableInfoWindow: true,
                        showInfoWindowOnSelect: false,
                        sources: [],
                        map: mapModel.getMap()
                    }, "search");

                    s.set("sources", searchConfig.Sources);
                    s.startup();

                    on(s, "select-result", function(e) {
                        mapModel.clearGraphics();
                        self.UpdateMap(e);
                    });
                    on(s, "clear-search", function(e) {
                        mapModel.clearGraphics();
                        //self.UpdateMap(e);
                    });

                }; //end init

                self.UpdateMap = function(e) {
                    // console.log(e);
                    if (e.result.name) {
                        var communityName = e.result.name;
                    }
                    var searchType = "";

                    switch (e.sourceIndex) {
                        case 1:
                            searchType = "county";
                            break;
                        case 2:
                            searchType = "supervisor";
                            break;
                        case 3:
                            searchType = "place";
                            break;
                        case 4:
                            searchType = "council";
                            break;
                        case 5:
                            searchType = "zip";
                            break;
                    }
                    if (e.sourceIndex === 6) {
                        $("#summaryLink").show();
                        var symbol = mapModel.getSymbol(e.result.feature.geometry, "cyan");
                        var graphic = new Graphic(e.result.feature.geometry, symbol);
                        mapModel.addGraphic(graphic, undefined, true, true);
                    } else if (e.sourceIndex === 0) {
                        $("#summaryLink").hide();
                        var symbol = new PictureMarkerSymbol("app/resources/img/Point.png", 36, 36).setOffset(9, 18);
                        var graphic = new Graphic(e.result.feature.geometry, symbol);
                        mapModel.addGraphic(graphic, undefined, true, true);
                    } else {
                        $("#summaryLink").show();
                        demographicVM.openWindow(communityName, searchType);
                    }
                };
            }; //end
            return SearchVM;
        }
    );
}());


text:
var args = require("system").args;
var page = require("webpage").create();

var url = args[1]
var options = JSON.parse(args[2]);
var src = args[3];

page.open(url, function (status) {
    var result = page.evaluate(function (options, src) {
        var div = document.querySelector("div");
        var renderer = new Vex.Flow.Renderer(div, Vex.Flow.Renderer.Backends.RAPHAEL);
        var artist = new Vex.Flow.Artist(0, 0, options.width);
        Vex.Flow.Artist.NOLOGO = !options.logo;
        var vextab = new Vex.Flow.VexTab(artist);

        vextab.reset();
        artist.reset();
        vextab.parse(src);
        artist.render(renderer);
        return div.innerHTML;
    }, options, src);
    console.log(result);
    phantom.exit();
});


text:
/* .navbar { position:static !important; margin:0px !important;} */

/* #nav { */
/*   float: left; */
/*   width: 250px; */
/*   background: green; */
/* } */
/*#content .header { position:absolute; background:rgba(255,255,255,0.9); left:250px; right:15px; padding:0px 12px; border-bottom:1px solid #EEE;}*/
/*#content .body { padding-top:80px;}*/

/* .doc { margin-top:16px; } */
.toggle-hide { display:block; }
.toggle-show { display:none; }
.toggle-on .toggle-hide { display:none !important; }
.toggle-on .toggle-show { display:block !important; }
.related-types .toggle-hide { padding-top:4px; }
/* .availability { margin-left:14px; color:#93a1a1; } */
/* .doc { margin-left:14px; } */

/* #nav li { list-style-type: none; } */
#nav .expando > ul { display:none; }
#nav .expando.expanded > ul { display:inherit; }
/* #nav ul, #nav li li { margin-left: 10px; } */
#nav img { padding-right:4px; }
#nav .pack { display:none; }

/* .nav .nav li { margin-left: 14px; } */

#nav.searching .expando > ul { display:inherit; }
#nav.searching .expando > a { display:none; }
#nav.searching ul { margin-left:0px; }
#nav.searching .pack { display:inline; }
#nav.searching .nav-list .nav-list { padding-left: 0; padding-right: 0; }

/* h1 code { padding:4px; font-size:15px; } */
/* h3 code { padding:4px; font-size:13px; } */
code {
  border: 0;
  font-weight: normal;
  color: #666666;
  background: none;
}
code .identifier, code.type {
  font-weight: bold;
}

/* code { background:#FDF6E3; color:#002b36; tab-size:4; } [> light <] */
code a { text-decoration:none; }
code a:hover { text-decoration:underline; }

/*code.dark { background:#272822; color:#F8F8F2; border:none; } */
code .identifier { color:#002b36; }
code .type { color:#268bd2; }
/* code .keyword { color:#dc322f; } */
/* code .directive { color:#2aa198; } */
/* code .constant { color:#AE81FF; } */
/* code .comment { color:#75715E; } */
/* code .string { color:#E6DB74; } */
/* code .macro { color:#A6E22A; } */
/* code .inactive { color:#75715E; } */

/* .navbar-fixed-top { position: fixed; } */
/* .navbar-fixed-top .navbar-inner, */
/* .navbar-fixed-bottom .navbar-inner { padding: 0; } */

body {
  padding-top: 20px;
}

.sidebar-nav {
  padding: 9px 0;
}

#searchForm {
  padding: 0 9px;
}

#searchForm .control-group {
  margin: 0;
}

.indent {
  margin-left: 40px;
}

.doc-main {
  margin-bottom: 40px;
}

.section {
  border-bottom: 1px solid #eee;
}

.javadoc {
  /* font-weight: normal; */
  /* font-size: small; */
  margin-top: 20px;
  font-style: italic;
}
.inline-content * {
  display: inline;
}

/**
 * Stuff for input-block-level:
 * http://stackoverflow.com/questions/13306670/bootstrap-prepended-and-appended-input-how-to-max-input-field-width
 */
.input-append.input-block-level,
.input-prepend.input-block-level {
  display: table;
}
.input-append.input-block-level .add-on,
.input-prepend.input-block-level .add-on {
  display: table-cell;
}
.input-append.input-block-level > input,
.input-prepend.input-block-level > input {
  box-sizing: border-box; /* use bootstrap mixin or include vendor variants */
  -moz-box-sizing: border-box; /* for Firefox */
  -webkit-box-sizing: border-box; /* for Firefox */
  -ms-box-sizing: border-box; /* for Firefox */
  -o-box-sizing: border-box; /* for Firefox */
  display: table; /* table-cell is not working well in Chrome for small widths */
  min-height: inherit;
  width: 100%;
}
.input-append.input-block-level > input {
  border-right: 0;
}
.input-prepend.input-block-level > input {
  border-left: 0;
}

.field {
  padding-bottom: 10px;
}
.field + .field {
  border-top: 1px solid #eee;
}
.fields {
  margin-left: 40px;
}
.field-source {
  margin-top: 15px;
  visibility: hidden;
}
.field:hover .field-source {
  visibility: inherit;
}

pre.example {
  position: relative;
  padding-top: 34.5px;
}
pre.example:before {
  position: absolute;
  top: -1px;
  left: -1px;

  content: "Example";
  color: #999;
  padding: 2px 6px;
  background: #fff;
  font-weight: bold;
  font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;

  -moz-border-radius: 4px 0;
  -ms-border-radius: 4px 0;
  -webkit-border-radius: 4px 0;
  border-radius: 4px 0;
  border: 1px solid rgba(0,0,0,0.15);
}


text:
const cluster = require('cluster');
const http = require('http');
let numCPUs = require('os').cpus().length;

numCPUs = numCPUs < 3 ? 3 : numCPUs;

if (cluster.isMaster) {
  console.log(`Master ${process.pid} is running, ${numCPUs}`);

  // Fork workers.
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker, code, signal) => {
    console.log(`worker ${worker.process.pid} died`);
  });
} else {
  // Workers can share any TCP connection
  // In this case it is an HTTP server
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end('hello world\n');
  }).listen(8000);

  console.log(`Worker ${process.pid} started`);
}


text:
from uliweb import expose, functions
from uliweb.i18n import ugettext_lazy as _
import logging

log = logging.getLogger(__name__)

def __begin__():
    functions.require_login()

@expose('/admin/models_config')
class AdminModelsConfigView(object):
    """
    Model administration config app
    """

    def __init__(self):
        self.model = functions.get_model('model_config')
        self.model_his = functions.get_model('model_config_his')

    @expose('')
    def index(self):
        fields = [
            {'name':'display_name', 'width':200},
            {'name':'model_name', 'width':200},
            {'name':'is_published', 'verbose_name':_('Is Published'), 'width':100},
            'description',
            {'name':'published_time', 'width':150},
            {'name':'action', 'verbose_name':_('Action'), 'width':120}
        ]

        def _action(value, obj):
            from uliweb.core.html import Tag

            actions = [
                Tag('a', '', title=_('View'),
                    href=url_for(self.__class__.view, model_name=obj.model_name),
                    _class="btn btn-xs btn-primary"),
                Tag('a', '', title=_('Delete'),
                    href=url_for(self.__class__.delete, model_name=obj.model_name),
                    _class="btn btn-xs btn-danger action-delete"),

            ]
            if obj.uuid:
                actions.insert(1, Tag('a', '', title=_('Unpublish'),
                    href=url_for(self.__class__.unpublish, model_name=obj.model_name),
                    _class="btn btn-xs btn-warning action-unpublish"))
            return ' '.join(map(str, actions))

        def _is_published(value, obj):
            if obj.uuid:
                return ' (%s)' % obj.uuid
            else:
                return ''

        fields_convert_map = {'action':_action, 'is_published':_is_published}

        view =functions.ListView(self.model, fields=fields,
                                 fields_convert_map=fields_convert_map)
        objects = view.objects()
        return {'view':view, 'objects':objects, 'total':view.total}

    def add(self):
        from forms import AddForm

        fields = ['model_name', 'display_name', 'table_name', 'description',
                  'basemodel', 'has_extension', 'extension_model']

        def post_created_form(fcls, model):
            from uliweb.form.widgets import Button

            fcls.layout_class = 'bs3t'
            fcls.form_buttons = [
                str(Button(value=_('Save'), _class="btn btn-primary btn-sm",
                    name="submit", type="submit")),
                ]

        def pre_save(data):
            from uliweb.utils.common import get_uuid, import_attr
            from uliweb.contrib.model_config import get_model_fields, get_model_indexes

            data['uuid'] = get_uuid()[:6]
            if not data['table_name']:
                data['table_name'] = data['model_name'].lower()

            if not data['display_name']:
                data['display_name'] = data['model_name']

            #add import basemodel support
            if data['basemodel']:
                BM = import_attr(data['basemodel'])
                data['fields'] = get_model_fields(BM)
                data['indexes'] = get_model_indexes(BM)

            if data['extension_model']:
                EM = import_attr(data['extension_model'])
                data['extension_fields'] = get_model_fields(EM)
                data['extension_indexes'] = get_model_indexes(EM)

        def post_save(obj, data):
            r = self.model(model_name=obj.model_name,
                           display_name=obj.display_name,
                           description=obj.description,
                           modified_user=request.user.id)
            r.save(version=True)

        view = functions.AddView(self.model_his, ok_url=url_for(self.__class__.index),
                                 post_created_form=post_created_form,
                                 form_cls=AddForm,
                                 pre_save=pre_save,
                                 post_save=post_save,
                                 fields=fields, version=True)
        return view.run()

    def _get_model(self, model_name, uuid):
        return self.model_his.get((self.model_his.c.model_name==model_name) &
                                    (self.model_his.c.uuid==uuid))

    def view(self, model_name):
        model = self.model.get(self.model.c.model_name==model_name)

        uuid = request.GET.get('uuid')
        uuids = [row.uuid for row in
                    self.model_his.filter(self.model_his.c.model_name==model_name)\
                        .fields(self.model_his.c.uuid)\
                        .order_by(self.model_his.c.create_time.desc())]

        obj = None
        if not uuid and len(uuids)>0:
            uuid = uuids[0]

        if uuid in uuids:
            obj = self._get_model(model_name, uuid)

        template_data = {'uuids':uuids, 'model_name':model_name,
                         'uuid':uuid, 'object':obj, 'published_uuid':model.uuid if model else ''}
        if obj:
            template_data['columns'] = eval(obj.fields or '[]')
            template_data['indexes'] = eval(obj.indexes or '[]')
            template_data['extension_columns'] = eval(obj.extension_fields or '[]')
            template_data['extension_indexes'] = eval(obj.extension_indexes or '[]')
            fields = ['model_name', 'display_name', 'table_name', 'basemodel', 'has_extension', 'extension_model']
            view = functions.DetailView(self.model_his, obj=obj, fields=fields,
                                        template_data=template_data)
            return view.run()
        else:
            template_data['view'] = ''
            template_data['columns'] = []
            template_data['indexes'] = []
            template_data['extension_columns'] = []
            template_data['extension_indexes'] = []
            return template_data

    def save(self, model_name):
        import json as JSON
        from uliweb.utils.common import get_uuid

        column_name = request.GET.get('column_name')
        column = JSON.loads(request.POST[column_name])
        uuid = request.GET.get('uuid')
        action = request.GET.get('action')

        obj = self._get_model(model_name, uuid)
        old_column = getattr(obj, column_name)

        list_columns = column_name in ('fields', 'indexes', 'extension_fields',
                                       'extension_indexes')
        if list_columns:
            old_column = eval(old_column or '[]')

        index = -1
        if action in ('edit', 'delete'):
            for x in range(len(old_column)):
                if old_column[x]['name'] == column['name']:
                    index = x
                    break

        if index >= 0:
            reserved = old_column[index].pop('_reserved', False)
        else:
            reserved = None

        if action in ('add', 'delete') or (index>=0 and old_column[index] != column):
            #if not published, then directly use current record
            if obj.status == '1':
                data = obj.to_dict()
                data.pop('id')
                data.pop('create_time')
                data['status'] = '0'
                obj = self.model_his(**data)
                obj.uuid = get_uuid()[:6]

            if list_columns:
                if action == 'add':
                    old_column.append(column)
                elif action == 'edit':
                    column['_reserved'] = reserved
                    old_column[index] = column
                else:
                    del old_column[index]
            else:
                old_column = column

            setattr(obj, column_name, old_column)
            obj.save(version=True)
            uuid = obj.uuid
        return json({'success':True, 'message':'Success!', 'data':{'uuid':uuid}})

    def publish(self, model_name):
        from uliweb.utils import date
        from uliweb.orm import Begin, Commit, Rollback

        Begin()
        uuid = request.GET.get('uuid')
        obj = self._get_model(model_name, uuid)
        if not obj:
            return json({'success':False, 'message':"Model %s(%s) can't be found" % (model_name, uuid)})
        obj.status = '1'
        obj.published_time = date.now()
        if len(obj.extension_fields) > 0:
            obj.has_extension = True
        obj.save(version=True)

        row = self.model.get(self.model.c.model_name==model_name)
        row.uuid = uuid
        row.published_time = date.now()
        row.modified_user = request.user.id
        row.modified_time = obj.published_time
        row.display_name = obj.display_name
        row.description = obj.description
        row.save(version=True)

        try:
            M = functions.get_model(model_name)
            M.migrate()
            if obj.has_extension:
                M.ext._model.migrate()
            Commit()

        except Exception as e:
            Rollback()
            log.exception(e)
            return json({'success':False, 'message':'Migrate Model %s(%s) Failed!' % (model_name, uuid)})
        return json({'success':True, 'message':'Model %s(%s) has been published successfully!' % (model_name, uuid)})

    def unpublish(self, model_name):
        count = self.model_his.filter(self.model_his.c.model_name==model_name).count()
        if count <= 1:
            return json({'success':False, 'message':'There should be at lastest one version existed'})
        row = self.model.get(self.model.c.model_name==model_name)
        row.uuid = ''
        row.published_time = None
        row.save(version=True)
        return json({'success':True})

    def delete(self, model_name):
        row = self.model.get(self.model.c.model_name==model_name)
        row.delete()

        for obj in self.model_his.filter(self.model_his.c.model_name==model_name):
            obj.delete()
        return json({'success':True})

    def delete_version(self, model_name):
        uuid = request.GET.get('uuid')
        row = self.model.get(self.model.c.model_name==model_name)

        version = self._get_model(model_name, uuid)
        if version.uuid != row.uuid:
            version.delete()
        else:
            return json({'success':False, 'message':"You can't delete published version"})

        return json({'success':True})


text:
<title>OGRE: Ogre::ResourceGroupManager::ResourceGroup Struct Reference - OGRE Documentation</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link type="text/css" rel="stylesheet" href="doxygen.css">
<link type="text/css" rel="stylesheet" href="tabs.css">

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Directories

Class List

Class Index

Class Hierarchy

Class Members

Ogre

ResourceGroupManager

ResourceGroup

Public Types |
Public Member Functions |
Public Attributes

Ogre::ResourceGroupManager::ResourceGroup Struct Reference

Resource group entry.
 More...

#include <OgreResourceGroupManager.h>

List of all members.

Public Types

enum  	Status {

  UNINITIALSED =  0,
INITIALISING =  1,
INITIALISED =  2,
LOADING =  3,

  LOADED =  4

 }

typedef map< Real,

LoadUnloadResourceList * >

::type 	LoadResourceOrderMap

 	Created resources which are ready to be loaded / unloaded.

Public Member Functions

void 	addToIndex (const String &filename, Archive *arch)

void 	removeFromIndex (const String &filename, Archive *arch)

void 	removeFromIndex (Archive *arch)

Public Attributes

OGRE_AUTO_MUTEX String 	name

 	General mutex for dealing with group content.

Status 	groupStatus

 	Group status.

LocationList 	locationList

 	List of possible locations to search.

ResourceLocationIndex 	resourceIndexCaseSensitive

 	Index of resource names to locations, built for speedy access (case sensitive archives)

ResourceLocationIndex 	resourceIndexCaseInsensitive

 	Index of resource names to locations, built for speedy access (case insensitive archives)

ResourceDeclarationList 	resourceDeclarations

 	Pre-declared resources, ready to be created.

LoadResourceOrderMap 	loadResourceOrderMap

String 	worldGeometry

 	Linked world geometry, as passed to setWorldGeometry.

SceneManager * 	worldGeometrySceneManager

 	Scene manager to use with linked world geometry.

bool 	inGlobalPool

Detailed Description

Resource group entry.

Definition at line 306 of file OgreResourceGroupManager.h.

Member Typedef Documentation

          typedef map<Real, LoadUnloadResourceList*>::type Ogre::ResourceGroupManager::ResourceGroup::LoadResourceOrderMap

Created resources which are ready to be loaded / unloaded.

Definition at line 335 of file OgreResourceGroupManager.h.

Member Enumeration Documentation

          enum Ogre::ResourceGroupManager::ResourceGroup::Status

Enumerator:

UNINITIALSED

INITIALISING

INITIALISED

LOADING

LOADED

Definition at line 308 of file OgreResourceGroupManager.h.

Member Function Documentation

          void Ogre::ResourceGroupManager::ResourceGroup::addToIndex
          (
          const String &
          filename,

          Archive *
          arch

          )

          void Ogre::ResourceGroupManager::ResourceGroup::removeFromIndex
          (
          Archive *
          arch	)

          void Ogre::ResourceGroupManager::ResourceGroup::removeFromIndex
          (
          const String &
          filename,

          Archive *
          arch

          )

Member Data Documentation

          Status Ogre::ResourceGroupManager::ResourceGroup::groupStatus

Group status.

Definition at line 323 of file OgreResourceGroupManager.h.

          bool Ogre::ResourceGroupManager::ResourceGroup::inGlobalPool

Definition at line 342 of file OgreResourceGroupManager.h.

          LoadResourceOrderMap Ogre::ResourceGroupManager::ResourceGroup::loadResourceOrderMap

Definition at line 336 of file OgreResourceGroupManager.h.

          LocationList Ogre::ResourceGroupManager::ResourceGroup::locationList

List of possible locations to search.

Definition at line 325 of file OgreResourceGroupManager.h.

          OGRE_AUTO_MUTEX String Ogre::ResourceGroupManager::ResourceGroup::name

General mutex for dealing with group content.

Status-specific mutex, separate from content-changing mutex Group name

Definition at line 321 of file OgreResourceGroupManager.h.

          ResourceDeclarationList Ogre::ResourceGroupManager::ResourceGroup::resourceDeclarations

Pre-declared resources, ready to be created.

Definition at line 331 of file OgreResourceGroupManager.h.

          ResourceLocationIndex Ogre::ResourceGroupManager::ResourceGroup::resourceIndexCaseInsensitive

Index of resource names to locations, built for speedy access (case insensitive archives)

Definition at line 329 of file OgreResourceGroupManager.h.

          ResourceLocationIndex Ogre::ResourceGroupManager::ResourceGroup::resourceIndexCaseSensitive

Index of resource names to locations, built for speedy access (case sensitive archives)

Definition at line 327 of file OgreResourceGroupManager.h.

          String Ogre::ResourceGroupManager::ResourceGroup::worldGeometry

Linked world geometry, as passed to setWorldGeometry.

Definition at line 338 of file OgreResourceGroupManager.h.

          SceneManager* Ogre::ResourceGroupManager::ResourceGroup::worldGeometrySceneManager

Scene manager to use with linked world geometry.

Definition at line 340 of file OgreResourceGroupManager.h.

The documentation for this struct was generated from the following file:

OgreResourceGroupManager.h

Copyright © 2008 Torus Knot Software Ltd

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

Last modified Sat Jan 14 2012 18:40:52