text:
/*

	html.c -- HTML writer

	(c) 2013-2016 Fletcher T. Penney (http://fletcherpenney.net/).

	Derived from peg-multimarkdown, which was forked from peg-markdown,
	which is (c) 2008 John MacFarlane (jgm at berkeley dot edu), and
	licensed under GNU GPL or MIT.

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License or the MIT
	license.  See LICENSE for details.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

*/

#include "html.h"

/* #define DEBUG_ON */

bool is_html_complete_doc(node *meta);
void print_col_group(GString *out,scratch_pad *scratch);

/* print_html_node_tree -- convert node tree to HTML */
void print_html_node_tree(GString *out, node *list, scratch_pad *scratch) {
	while (list != NULL) {
		print_html_node(out, list, scratch);
		list = list->next;
	}
}

/* print_html_node -- convert given node to HTML and append */
void print_html_node(GString *out, node *n, scratch_pad *scratch) {
	node *temp_node;
	link_data *temp_link_data = NULL;
	char *temp;
	int lev;
	int random;
	char temp_type;
	char *width = NULL;
	char *height = NULL;
	GString *temp_str;
	size_t temp_size;

	if (n == NULL)
		return;

	/* debugging statement */
#ifdef DEBUG_ON
	fprintf(stderr, "print_html_node: %d\n",n->key);
#endif

	/* If we are forcing a complete document, and METADATA isn't the first thing,
		we need to close  */
	if ((scratch->extensions & EXT_COMPLETE)
		&& !(scratch->extensions & EXT_HEAD_CLOSED) &&
		!((n->key == FOOTER) || (n->key == METADATA))) {
			g_string_append_printf(out, "\n\n");
			scratch->extensions = scratch->extensions | EXT_HEAD_CLOSED;
		}
	switch (n->key) {
		case NO_TYPE:
			break;
		case LIST:
			print_html_node_tree(out,n->children,scratch);
			break;
		case STR:
			/* fprintf(stderr, "str: '%s'\n", n->str); */
			print_html_string(out,n->str, scratch);
			break;
		case ABBR:
			if (strlen(n->children->str) == 0) {
				g_string_append_printf(out, "");
			} else {
				g_string_append_printf(out, "children->str, scratch);
				g_string_append_printf(out, "\">");
			}
			print_html_string(out,n->str, scratch);
			g_string_append_printf(out, "");
			break;
		case ABBRSTART:
			if (strlen(n->children->str) == 0) {
				g_string_append_printf(out, "");
			} else {
				g_string_append_printf(out, "children->str, scratch);
				g_string_append_printf(out, "\">");
			}
			print_html_string(out,n->str, scratch);
			break;
		case ABBRSTOP:
			print_html_string(out,n->str, scratch);
			g_string_append_printf(out, "");
			break;
		case SPACE:
			g_string_append_printf(out,"%s",n->str);
			break;
		case PLAIN:
			pad(out,1, scratch);
			print_html_node_tree(out,n->children, scratch);
			scratch->padded = 0;
			break;
		case PARA:
			pad(out, 2, scratch);
			g_string_append_printf(out, "
");
			print_html_node_tree(out,n->children,scratch);
			if (scratch->footnote_to_print != 0){
				scratch->footnote_para_counter --;
				if (scratch->footnote_para_counter == 0) {
					if (scratch->extensions & EXT_RANDOM_FOOT) {
						srand(scratch->random_seed_base + scratch->footnote_to_print);
						random = rand() % 99999 + 1;
					} else {
						random = scratch->footnote_to_print;
					}

					g_string_append_printf(out, "  ↩", random);
					scratch->footnote_to_print = 0;
				}
			}
			g_string_append_printf(out, "
");
			scratch->padded = 0;
			break;
		case HRULE:
			pad(out, 2, scratch);
			g_string_append_printf(out, "
");
			scratch->padded = 0;
			break;
		case HTMLBLOCK:
			pad(out, 2, scratch);
			g_string_append_printf(out, "%s", n->str);
			scratch->padded = 0;
			break;
		case VERBATIM:
		case VERBATIMFENCE:
			pad(out, 2, scratch);
			if ((n->children != NULL) && (n->children->key == VERBATIMTYPE)) {
				trim_trailing_whitespace(n->children->str);
				if (strlen(n->children->str) > 0)
					g_string_append_printf(out, "
", n->children->str);
				else
					g_string_append_printf(out, "%s", "
");
			} else {
				g_string_append_printf(out, "%s", "
");
			}
			print_html_string(out, n->str, scratch);
			g_string_append_printf(out, "%s", "
");
			scratch->padded = 0;
			break;
		case BULLETLIST:
			pad(out, 2, scratch);
			g_string_append_printf(out, "%s", "
");
			scratch->padded = 0;
			print_html_node_tree(out, n->children, scratch);
			pad(out, 1, scratch);
			g_string_append_printf(out, "%s", "
");
			scratch->padded = 0;
			break;
		case ORDEREDLIST:
			pad(out, 2, scratch);
			g_string_append_printf(out, "%s", "
");
			scratch->padded = 0;
			print_html_node_tree(out, n->children, scratch);
			pad(out, 1, scratch);
			g_string_append_printf(out, "
");
			scratch->padded = 0;
			break;
		case LISTITEM:
			pad(out, 1, scratch);
			g_string_append_printf(out, "
");
			scratch->padded = 2;
			print_html_node_tree(out, n->children, scratch);
			g_string_append_printf(out, "
");
			scratch->padded = 0;
			break;
		case METADATA:
			/* Not if snippet only */
			if (scratch->extensions & EXT_SNIPPET) {
				is_html_complete_doc(n);
				print_html_node_tree(out,n->children, scratch);
				break;
			}

			if (!(scratch->extensions & EXT_COMPLETE) && (is_html_complete_doc(n))) {
				/* We have metadata to include, and didn't already force complete */
				temp = metavalue_for_key("lang", scratch->result_tree);
				if (temp != NULL) {
				    g_string_append_printf(out,
					"<!DOCTYPE html>\n\n\n\t<meta charset=\"utf-8\"/>\n",temp);
					free(temp);
				} else {
				    g_string_append_printf(out,
					"<!DOCTYPE html>\n\n\n\t<meta charset=\"utf-8\"/>\n");
				}
				/* either way, now we need to be a complete doc */
				scratch->extensions = scratch->extensions | EXT_COMPLETE;
			} else {
				/* Ensure we lowercase metadata */
				is_html_complete_doc(n);
			}
			/* print the metadata */
			scratch->extensions = scratch->extensions | EXT_HEAD_CLOSED;
			print_html_node_tree(out,n->children, scratch);
			if (scratch->extensions & EXT_COMPLETE) {
				/* need to close head and open body */
				g_string_append_printf(out, "\n\n\n");
			}
			break;
		case METAKEY:
			if (strcmp(n->str, "baseheaderlevel") == 0) {
				scratch->baseheaderlevel = atoi(n->children->str);
				break;
			} else if (strcmp(n->str, "xhtmlheaderlevel") == 0) {
				scratch->baseheaderlevel = atoi(n->children->str);
				break;
			} else if (strcmp(n->str, "htmlheaderlevel") == 0) {
				scratch->baseheaderlevel = atoi(n->children->str);
				break;
			} else if (strcmp(n->str, "htmlfooter") == 0) {
				trim_trailing_whitespace(n->children->str);
				scratch->html_footer = strdup(n->children->str);
				break;
			} else if (strcmp(n->str, "quoteslanguage") == 0) {
				temp = label_from_node_tree(n->children);
				if ((strcmp(temp, "nl") == 0) || (strcmp(temp, "dutch") == 0)) { scratch->language = DUTCH; }   else
				if ((strcmp(temp, "de") == 0) || (strcmp(temp, "german") == 0)) { scratch->language = GERMAN; } else
				if (strcmp(temp, "germanguillemets") == 0) { scratch->language = GERMANGUILL; } else
				if ((strcmp(temp, "fr") == 0) || (strcmp(temp, "french") == 0)) { scratch->language = FRENCH; } else
				if ((strcmp(temp, "sv") == 0) || (strcmp(temp, "swedish") == 0)) { scratch->language = SWEDISH; }
				free(temp);
				break;
			}

			/* Don't handle other metadata if we're snippet only */
			if (scratch->extensions & EXT_SNIPPET)
				break;

			if (strcmp(n->str, "title") == 0) {
				g_string_append_printf(out, "\t<title>");
				print_html_node(out, n->children, scratch);
				g_string_append_printf(out, "</title>\n");
			} else if (strcmp(n->str, "css") == 0) {
				g_string_append_printf(out, "\t<link type=\"text/css\" rel=\"stylesheet\" href=\"");
				print_html_node(out, n->children, scratch);
				g_string_append_printf(out, "\"/>\n");
			} else if (strcmp(n->str, "xhtmlheader") == 0) {
				trim_trailing_whitespace(n->children->str);
				print_raw_node(out, n->children);
				g_string_append_printf(out, "\n");
			} else if (strcmp(n->str, "htmlheader") == 0) {
				trim_trailing_whitespace(n->children->str);
				print_raw_node(out, n->children);
				g_string_append_printf(out, "\n");
			} else if (strcmp(n->str, "mmdfooter") == 0) {
			} else if (strcmp(n->str, "mmdheader") == 0) {
			} else if (strcmp(n->str, "lang") == 0) {
			} else if (strcmp(n->str, "transcludebase") == 0) {
			} else if (strcmp(n->str, "htmlfooter") == 0) {
			} else if (strcmp(n->str, "latexmode") == 0) {
			} else if (strcmp(n->str, "latexinput") == 0) {
			} else if (strcmp(n->str, "latexfooter") == 0) {
			} else if (strcmp(n->str, "bibtex") == 0) {
			} else {
				g_string_append_printf(out,"\t<meta name=\"%s\" content=\"",n->str);
				print_html_node(out,n->children,scratch);
				g_string_append_printf(out,"\"/>\n");
			}
			break;
		case METAVALUE:
			trim_trailing_whitespace(n->str);
			print_html_string(out,n->str, scratch);
			break;
		case FOOTER:
			break;
		case HEADINGSECTION:
			print_html_node_tree(out,n->children,scratch);
			break;
		case H1: case H2: case H3: case H4: case H5: case H6:
			lev = n->key - H1 + scratch->baseheaderlevel;  /* assumes H1 ... H6 are in order */
			if (lev > 6)
				lev = 6;	/* Max at level 6 */
			pad(out, 2, scratch);
			if ( scratch->extensions & EXT_COMPATIBILITY ) {
				/* Use regular Markdown header format */
				g_string_append_printf(out, "<h%1d>", lev);
				print_html_node_tree(out, n->children, scratch);
			} else if (n->children->key == AUTOLABEL) {
				temp = label_from_string(n->children->str);
				/* use label for header since one was specified (MMD)*/
				g_string_append_printf(out, "<h%d id=\"%s\">", lev,temp);
				print_html_node_tree(out, n->children->next, scratch);
				free(temp);
			} else if ( scratch->extensions & EXT_NO_LABELS ) {
				/* Don't generate a label */
				g_string_append_printf(out, "<h%1d>", lev);
				print_html_node_tree(out, n->children, scratch);
			} else {
				/* generate a label by default for MMD */
				temp = label_from_node_tree(n->children);
				g_string_append_printf(out, "<h%d id=\"%s\">", lev, temp);
				print_html_node_tree(out, n->children, scratch);
				free(temp);
			}
			g_string_append_printf(out, "</h%1d>", lev);
			scratch->padded = 0;
			break;
		case APOSTROPHE:
			print_html_localized_typography(out, APOS, scratch);
			break;
		case ELLIPSIS:
			print_html_localized_typography(out, ELLIP, scratch);
			break;
		case EMDASH:
			print_html_localized_typography(out, MDASH, scratch);
			break;
		case ENDASH:
			print_html_localized_typography(out, NDASH, scratch);
			break;
		case SINGLEQUOTED:
			print_html_localized_typography(out, LSQUOTE, scratch);
			print_html_node_tree(out, n->children, scratch);
			print_html_localized_typography(out, RSQUOTE, scratch);
			break;
		case DOUBLEQUOTED:
			print_html_localized_typography(out, LDQUOTE, scratch);
			print_html_node_tree(out, n->children, scratch);
			print_html_localized_typography(out, RDQUOTE, scratch);
			break;
		case LINEBREAK:
			g_string_append_printf(out, "
\n");
			break;
		case MATHSPAN:
			temp = strdup(n->str);
			if (temp[0] == '$') {
				temp[strlen(temp)-1] = '\0';
				if (temp[1] == '$') {
					temp[strlen(temp)-1] = '\0';
					g_string_append_printf(out, "\\[%s\\]",&temp[2]);
				} else {
					g_string_append_printf(out, "\\(%s\\)",&temp[1]);
				}
			} else if (temp[strlen(temp) - 1] == ']') {
				temp[strlen(temp) - 3] = '\0';
				g_string_append_printf(out, "%s\\]",temp);
			} else {
				temp[strlen(temp) - 3] = '\0';
				g_string_append_printf(out, "%s\\)",temp);
			}
			free(temp);
			break;
		case STRONG:
			g_string_append_printf(out, "");
			print_html_node_tree(out,n->children,scratch);
			g_string_append_printf(out, "");
		break;
		case EMPH:
			g_string_append_printf(out, "");
			print_html_node_tree(out,n->children,scratch);
			g_string_append_printf(out, "");
		break;
		case LINKREFERENCE:
			break;
		case LINK:
#ifdef DEBUG_ON
	fprintf(stderr, "print html link: '%s'\n",n->str);
#endif
			/* Stash a copy of the link data */
			if (n->link_data != NULL)
				temp_link_data = mk_link_data(n->link_data->label, n->link_data->source, n->link_data->title, n->link_data->attr);

			/* Do we have proper info? */
			if ((n->link_data->label == NULL) &&
			(n->link_data->source == NULL)) {
				/* we seem to be a [foo][] style link */
				/* so load a label */
				temp_str = g_string_new("");
				print_raw_node_tree(temp_str, n->children);
				n->link_data->label = temp_str->str;
				g_string_free(temp_str, FALSE);
			}
			/* Load reference data */
			if (n->link_data->label != NULL) {
				temp = strdup(n->link_data->label);

#ifdef DEBUG_ON
	fprintf(stderr, "print html link: '%s'\n",n->link_data->title);
	fprintf(stderr, "print html link: '%s'\n",temp);
#endif
				n->link_data->attr = NULL;
				free_link_data(n->link_data);

				n->link_data = extract_link_data(temp, scratch);
				if (n->link_data == NULL) {
					/* replace original text since no definition found */
					g_string_append_printf(out, "[");
					print_html_node(out, n->children, scratch);
					g_string_append_printf(out,"]");
					if (n->children->next != NULL) {
						g_string_append_printf(out, "[");
						print_html_node_tree(out, n->children->next, scratch);
						g_string_append_printf(out,"]");
					} else if (n->str != NULL) {
						/* no title label, so see if we stashed str*/
						g_string_append_printf(out, "%s", n->str);
					} else {
						g_string_append_printf(out, "[%s]",temp);
					}

					free(temp);

					/* Restore stashed copy */
					n->link_data = temp_link_data;

					break;
				}
				free(temp);
			}
			g_string_append_printf(out, "link_data->source != NULL) {
				g_string_append_printf(out, " href=\"");
				if (strncmp(n->link_data->source,"mailto:", 6) == 0) {
					scratch->obfuscate = 1;		/* flag obfuscated */
				}
				print_html_string(out,n->link_data->source, scratch);
				g_string_append_printf(out, "\"");
			}
			if ((n->link_data->title != NULL) && (strlen(n->link_data->title) > 0)) {
				g_string_append_printf(out, " title=\"");
				print_html_string(out, n->link_data->title, scratch);
				g_string_append_printf(out, "\"");
			}
			print_html_node_tree(out, n->link_data->attr, scratch);
			g_string_append_printf(out, ">");
			if (n->children != NULL)
				print_html_node_tree(out,n->children,scratch);
			g_string_append_printf(out, "");
			scratch->obfuscate = 0;

			/* Restore stashed copy */
			n->link_data->attr = NULL;
			free_link_data(n->link_data);
			n->link_data = temp_link_data;

			break;
		case ATTRKEY:
			if ( (strcmp(n->str,"height") == 0) || (strcmp(n->str, "width") == 0)) {
			} else {
				g_string_append_printf(out, " %s=\"%s\"", n->str,
					n->children->str);
			}
			break;
		case REFNAME:
		case SOURCE:
		case TITLE:
			break;
		case IMAGEBLOCK:
			pad(out,2, scratch);
		case IMAGE:
#ifdef DEBUG_ON
	fprintf(stderr, "print image\n");
#endif
            /* Verify all is well */
            if (n->link_data == NULL) {
                fprintf(stderr, "Invalid IMAGEBLOCK or IMAGE -- (null) link_data\n");
                exit(EXIT_FAILURE);
            }

			/* Stash a copy of the link data */
			if (n->link_data != NULL)
				temp_link_data = mk_link_data(n->link_data->label, n->link_data->source, n->link_data->title, n->link_data->attr);

			/* Do we have proper info? */
			if ((n->link_data->label == NULL) &&
			(n->link_data->source == NULL)) {
				/* we seem to be a [foo][] style link */
				/* so load a label */
				temp_str = g_string_new("");
				print_raw_node_tree(temp_str, n->children);
				n->link_data->label = temp_str->str;
				g_string_free(temp_str, FALSE);
			}
#ifdef DEBUG_ON
	fprintf(stderr, "load reference data\n");
#endif
			/* Load reference data */
			if (n->link_data->label != NULL) {
				temp = strdup(n->link_data->label);

				n->link_data->attr = NULL;
				free_link_data(n->link_data);

				n->link_data = extract_link_data(temp, scratch);

				if (n->link_data == NULL) {
					g_string_append_printf(out, "![");
					print_html_node_tree(out, n->children, scratch);
					g_string_append_printf(out,"][%s]",temp);

					/* Restore stashed copy */
					n->link_data = temp_link_data;

					free(temp);

					break;
				} else {
					if (n->key == IMAGEBLOCK)
						g_string_append_printf(out, "
\n");
				}
				free(temp);
			} else {
				if (n->key == IMAGEBLOCK)
						g_string_append_printf(out, "
\n");
			}
#ifdef DEBUG_ON
	fprintf(stderr, "create img\n");
#endif
			g_string_append_printf(out, "link_data->source != NULL)
				g_string_append_printf(out, " src=\"%s\"",n->link_data->source);
			if (n->children != NULL) {
				g_string_append_printf(out, " alt=\"");
				temp_str = g_string_new("");
				print_raw_node_tree(temp_str, n->children);
				print_html_string(out, temp_str->str, scratch);
				g_string_free(temp_str, true);
				g_string_append_printf(out, "\"");
			} else {
				g_string_append_printf(out, " alt=\"%s\"",n->link_data->title);
			}
			if (!(scratch->extensions & EXT_COMPATIBILITY)) {
				if (n->link_data->label != NULL) {
					temp = label_from_string(n->link_data->label);
					g_string_append_printf(out, " id=\"%s\"",temp);
					free(temp);
				}
			}
			if ((n->link_data->title != NULL) && (strlen(n->link_data->title) > 0)) {
				g_string_append_printf(out, " title=\"");
				print_html_string(out, n->link_data->title, scratch);
				g_string_append_printf(out, "\"");
			}
#ifdef DEBUG_ON
	fprintf(stderr, "attributes\n");
#endif
			if (n->link_data->attr != NULL) {
				temp_node = node_for_attribute("height",n->link_data->attr);
				if (temp_node != NULL)
					height = strdup(temp_node->children->str);
				temp_node = node_for_attribute("width",n->link_data->attr);
				if (temp_node != NULL)
					width = strdup(temp_node->children->str);
				if ((height != NULL) || (width != NULL)) {
	#ifdef DEBUG_ON
		fprintf(stderr, "width/height\n");
	#endif
				g_string_append_printf(out, " style=\"");
				if (height != NULL)
					g_string_append_printf(out, "height:%s;", height);
				if (width != NULL)
					g_string_append_printf(out, "width:%s;", width);
				g_string_append_printf(out, "\"");
			}
	#ifdef DEBUG_ON
		fprintf(stderr, "other attributes\n");
	#endif
				print_html_node_tree(out, n->link_data->attr, scratch);
				free(height);
				free(width);
			}
			g_string_append_printf(out, " />");
			if (n->key == IMAGEBLOCK) {
				if (n->children != NULL) {
					temp_str = g_string_new("");
					print_html_node(temp_str,n->children,scratch);
					if (temp_str->currentStringLength > 0) {
						g_string_append_printf(out, "\n
");
						g_string_append(out, temp_str->str);
						g_string_append_printf(out, "
");
					}
					g_string_free(temp_str, true);
				}
				g_string_append_printf(out,"\n
");
				scratch->padded = 0;
			}

			/* Restore stashed copy */
			n->link_data->attr = NULL;
			free_link_data(n->link_data);
			n->link_data = temp_link_data;

			break;
#ifdef DEBUG_ON
	fprintf(stderr, "finish image\n");
#endif
		case NOTEREFERENCE:
			lev = note_number_for_node(n, scratch);
			temp_node = node_for_count(scratch->used_notes, lev);

			if (scratch->extensions & EXT_RANDOM_FOOT) {
				srand(scratch->random_seed_base + lev);
				random = rand() % 99999 + 1;
			} else {
				random = lev;
			}

			if (temp_node->key == GLOSSARYSOURCE) {
				if (lev > scratch->max_footnote_num) {
					g_string_append_printf(out, "[%d]",
						random, random, lev);
						scratch->max_footnote_num = lev;
				} else {
					g_string_append_printf(out, "[%d]",
						random, lev);
				}
			} else {
				if (lev > scratch->max_footnote_num) {
					g_string_append_printf(out, "[%d]",
						random, random, lev);
						scratch->max_footnote_num = lev;
				} else {
					g_string_append_printf(out, "[%d]",
						random, lev);
				}
			}
			break;
		case NOCITATION:
		case CITATION:
#ifdef DEBUG_ON
	fprintf(stderr, "print cite\n");
#endif
			if ((n->link_data != NULL) && (strncmp(n->link_data->label,"[#",2) == 0)) {
				fprintf(stderr, "external cite\n");
				/* external citation (e.g. BibTeX) */
				if (n->key == NOCITATION) {
					g_string_append_printf(out, "",n->str);
				} else {
					g_string_append_printf(out, "");
					g_string_append_printf(out, "");
				}
			} else {
#ifdef DEBUG_ON
				fprintf(stderr, "internal cite\n");
#endif
				/* MMD citation, so output as footnote */
				/* TODO: create separate stream from footnotes */
				lev = 0;
				if (n->link_data != NULL)
					lev = note_number_for_label(n->link_data->label, scratch);
				if (lev != 0) {
#ifdef DEBUG_ON
					fprintf(stderr, "matching cite found - %d\n",lev);
#endif
					if (scratch->extensions & EXT_RANDOM_FOOT) {
						srand(scratch->random_seed_base + lev);
						random = rand() % 99999 + 1;
					} else {
						random = lev;
					}

					temp_node = node_for_count(scratch->used_notes, lev);
					/* flag that this is used as a citation */
					temp_node->key = CITATIONSOURCE;
					if (lev > scratch->max_footnote_num) {
						scratch->max_footnote_num = lev;
					}
					if (n->key == NOCITATION) {
						g_string_append_printf(out, "",random);
					} else {
						g_string_append_printf(out, "[",
							random);
							if (n->children != NULL) {
								g_string_append_printf(out, "");
								print_html_node(out, n->children, scratch);
								g_string_append_printf(out, ", %d]", lev);
							} else {
								g_string_append_printf(out, "%d]", lev);
							}
					}
					g_string_append_printf(out, "%s", n->link_data->label);
					if (n->key == NOCITATION) {
						g_string_append_printf(out, "");
					} else {
						g_string_append_printf(out, "");
					}
				} else {
					/* not located -- this is external cite */
#ifdef DEBUG_ON
				fprintf(stderr, "no match for cite: '%s'\n",n->link_data->label);
#endif
					if ((n->link_data != NULL) && (n->key == NOCITATION)) {
						g_string_append_printf(out, "",n->link_data->label);
					} else if (n->link_data != NULL) {
						g_string_append_printf(out, "[");
						if (n->children != NULL) {
							print_html_node(out, n->children, scratch);
							g_string_append_printf(out, "][");
						}
						g_string_append_printf(out, "#%s]",n->link_data->label);
					}
				}
			}
#ifdef DEBUG_ON
		fprintf(stderr, "finish cite\n");
#endif
			break;
		case VARIABLE:
			temp = metavalue_for_key(n->str,scratch->result_tree);
			if (temp == NULL) {
				g_string_append_printf(out, "[%%%s]",n->str);
			} else {
				print_html_string(out, temp, scratch);
				free(temp);
			}
			break;
		case GLOSSARYTERM:
			g_string_append_printf(out,"");
			print_html_string(out, n->children->str, scratch);
			g_string_append_printf(out, "");
			if ((n->next != NULL) && (n->next->key == GLOSSARYSORTKEY) ) {
				g_string_append_printf(out, "");
				print_html_string(out, n->next->str, scratch);
				g_string_append_printf(out, "");
			}
			g_string_append_printf(out, ": ");
			break;
		case GLOSSARYSORTKEY:
			break;
		case CODE:
			g_string_append_printf(out, "");
			print_html_string(out, n->str, scratch);
			g_string_append_printf(out, "");
			break;
		case BLOCKQUOTEMARKER:
			print_html_node_tree(out, n->children, scratch);
			break;
		case BLOCKQUOTE:
			pad(out,2, scratch);
			g_string_append_printf(out, "
\n");
			scratch->padded = 2;
			print_html_node_tree(out, n->children, scratch);
			pad(out,1, scratch);
			g_string_append_printf(out, "
");
			scratch->padded = 0;
			break;
		case RAW:
			g_string_append_printf(out, "RAW:");
			g_string_append_printf(out,"%s",n->str);
			break;
		case HTML:
			g_string_append_printf(out, "%s", n->str);
			break;
		case DEFLIST:
			pad(out,2, scratch);
			scratch->padded = 1;
			g_string_append_printf(out, "
\n");
			print_html_node_tree(out, n->children, scratch);
			g_string_append_printf(out, "
");
			scratch->padded = 0;
			break;
		case TERM:
			pad(out,1, scratch);
			g_string_append_printf(out, "
");
			print_html_node_tree(out, n->children, scratch);
			g_string_append_printf(out, "
\n");
			scratch->padded = 1;
			break;
		case DEFINITION:
			pad(out,1, scratch);
			scratch->padded = 1;
			g_string_append_printf(out, "
");
			print_html_node_tree(out, n->children, scratch);
			g_string_append_printf(out, "
\n");
			scratch->padded = 0;
			break;
		case TABLE:
			pad(out,2, scratch);
			g_string_append_printf(out, "
\n");
			print_html_node_tree(out, n->children, scratch);
			g_string_append_printf(out, "
\n");
			scratch->cell_type = 0;
			scratch->padded = 1;
			scratch->table_alignment = NULL;
			scratch->header_column = 0;
			break;
		case TABLESEPARATOR:
			scratch->table_alignment = n->str;
			if (scratch->cell_type == 0)
				print_col_group(out, scratch);
			scratch->cell_type = 'd';
			break;
		case TABLECAPTION:
			if ((n->children != NULL) && (n->children->key == TABLELABEL)) {
				temp = label_from_string(n->children->str);
			} else {
				temp = label_from_node_tree(n->children);
			}
			g_string_append_printf(out, "
", temp);
			print_html_node_tree(out, n->children, scratch);
			g_string_append_printf(out, "
\n");
			free(temp);
			break;
		case TABLELABEL:
			break;
		case TABLEHEAD:
			/* print column alignment for XSLT processing if needed */
			if (scratch->cell_type == 0)
				print_col_group(out, scratch);
			scratch->cell_type = 'h';
			g_string_append_printf(out, "\n
\n");
			print_html_node_tree(out, n->children, scratch);
			g_string_append_printf(out, "
\n");
			scratch->cell_type = 'd';
			break;
		case TABLEBODY:
			g_string_append_printf(out, "\n
\n");
			print_html_node_tree(out, n->children, scratch);
			g_string_append_printf(out, "
\n");
			break;
		case TABLEROW:
			g_string_append_printf(out, "
\n");
			scratch->table_column = 0;
			print_html_node_tree(out, n->children, scratch);
			g_string_append_printf(out, "
\n");
			break;
		case TABLECELL:
			temp = scratch->table_alignment;
			if (strncmp(&temp[scratch->table_column],"h",1) == 0) {
				temp_type = 'h';
				scratch->table_column++;
			} else {
				temp_type = scratch->cell_type;
			}

			if (scratch->header_column && (scratch->table_column == 0))
				temp_type = 'h';

			lev = scratch->table_column;
			if ( strncmp(&temp[lev],"r",1) == 0) {
				g_string_append_printf(out, "\t<t%c style=\"text-align:right;\"", temp_type);
			} else if ( strncmp(&temp[lev],"R",1) == 0) {
				g_string_append_printf(out, "\t<t%c style=\"text-align:right;\"", temp_type);
			} else if ( strncmp(&temp[lev],"c",1) == 0) {
				g_string_append_printf(out, "\t<t%c style=\"text-align:center;\"", temp_type);
			} else if ( strncmp(&temp[lev],"C",1) == 0) {
				g_string_append_printf(out, "\t<t%c style=\"text-align:center;\"", temp_type);
			} else if ( strncmp(&temp[lev],"N",1) == 0) {
				g_string_append_printf(out, "\t<t%c", temp_type);
			} else if ( strncmp(&temp[lev],"n",1) == 0) {
				g_string_append_printf(out, "\t<t%c", temp_type);
			} else {
				g_string_append_printf(out, "\t<t%c style=\"text-align:left;\"", temp_type);
			}
			if ((n->children != NULL) && (n->children->key == CELLSPAN)) {
				g_string_append_printf(out, " colspan=\"%d\"",(int)strlen(n->children->str)+1);
				scratch->table_column += (int)strlen(n->children->str);
			}
			g_string_append_printf(out, ">");
			scratch->padded = 2;
			temp_size = out->currentStringLength;
			print_html_node_tree(out, n->children, scratch);

			/* We have an empty leading cell, so first column is shown as headers */
			/* Disabled for now while I decide whether this should be reimplemented -- was in v2 */
			/* if (scratch->table_column == 0) {
				if (temp_size == out->currentStringLength) {
					scratch->header_column = 1;
				}
			}
			*/

			g_string_append_printf(out, "</t%c>\n", temp_type);
			scratch->table_column++;
			break;
		case CELLSPAN:
			break;
		case GLOSSARYSOURCE:
			if (scratch->printing_notes)
				print_html_node_tree(out, n->children, scratch);
			break;
		case CITATIONSOURCE:
		case NOTESOURCE:
			if (scratch->printing_notes)
				print_html_node_tree(out, n->children, scratch);
			break;
		case SOURCEBRANCH:
			fprintf(stderr,"SOURCEBRANCH\n");
			break;
		case NOTELABEL:
		case GLOSSARYLABEL:
			break;
		case SUPERSCRIPT:
			g_string_append_printf(out, "%s",n->str);
			break;
		case SUBSCRIPT:
			g_string_append_printf(out, "%s",n->str);
			break;
		case ABBREVIATION:
		case KEY_COUNTER:
			break;
		case TOC:
			g_string_append_printf(out, "
\n");
			print_html_node_tree(out,n->children, scratch);
			g_string_append_printf(out, "\n
");
			break;
		default:
			fprintf(stderr, "print_html_node encountered unknown node key = %d\n",n->key);
			exit(EXIT_FAILURE);
	}
}

/* print_html_endnotes */
void print_html_endnotes(GString *out, scratch_pad *scratch) {
	int counter = 0;
	int random;
	node *reversed = copy_node_tree(scratch->used_notes);

	reversed = reverse_list(reversed);

	scratch->printing_notes = 1;

	node *note = reversed;
#ifdef DEBUG_ON
	fprintf(stderr, "start endnotes\n");
#endif

	if ((note == NULL) || ((note->key == KEY_COUNTER) && (note->next == NULL))) {
		free_node_tree(reversed);
		return;
	}

#ifdef DEBUG_ON
	fprintf(stderr, "there are endnotes to print\n");
#endif

	pad(out,2, scratch);
	g_string_append_printf(out, "
\n
\n
");
	while ( note != NULL) {
		if (note->key == KEY_COUNTER) {
			note = note->next;
			continue;
		}

		counter++;
		pad(out, 1, scratch);

		if (scratch->extensions & EXT_RANDOM_FOOT) {
			srand(scratch->random_seed_base + counter);
			random = rand() % 99999 + 1;
		} else {
			random = counter;
		}

		if (note->key == CITATIONSOURCE) {
			g_string_append_printf(out, "
%s",
				random, note->str);
		} else {
			g_string_append_printf(out, "
\n", random);
		}

		scratch->padded = 2;
		if ((note->key == NOTESOURCE) || (note->key == GLOSSARYSOURCE))
			scratch->footnote_to_print = counter;
		scratch->footnote_para_counter = tree_contains_key_count(note->children,PARA);
		print_html_node(out, note, scratch);
		pad(out, 1, scratch);
		g_string_append_printf(out, "
");

		note = note->next;
	}
	pad(out,1, scratch);
	g_string_append_printf(out, "
\n
\n");
	scratch->padded = 0;

	free_node_tree(reversed);
#ifdef DEBUG_ON
	fprintf(stderr, "finish endnotes\n");
#endif
}

/* Check metadata keys and determine if we need a complete document */
/* We also preconvert metadata keys to proper formatting -- lowercase with no spaces */
bool is_html_complete_doc(node *meta) {
	node *step;
	char *temp;
	step = meta->children;

	while (step != NULL) {
		/* process key to proper label */
		temp = step->str;	/* store pointer to original str */
		step->str = label_from_string(step->str);
		free(temp);			/* free original since we don't need it */
		step = step->next;
	}

	step = meta->children;
	while (step != NULL) {
		/* the following types of metadata do not require a complete document */
		if ((strcmp(step->str, "baseheaderlevel")  != 0) &&
			(strcmp(step->str, "xhtmlheaderlevel") != 0) &&
			(strcmp(step->str, "htmlheaderlevel")  != 0) &&
			(strcmp(step->str, "latexheaderlevel") != 0) &&
			(strcmp(step->str, "odfheaderlevel")   != 0) &&
			(strcmp(step->str, "quoteslanguage")   != 0))
			{ return TRUE;}
		step = step->next;
	}

	return FALSE;
}

/* print_html_localized_typography -- convert to "smart" typography */
void print_html_localized_typography(GString *out, int character, scratch_pad *scratch) {
	if (!extension(EXT_SMART, scratch->extensions)) {
		g_string_append_c(out, character);
		return;
	}
	switch (character) {
		case LSQUOTE:
			switch (scratch->language) {
				case SWEDISH:
					g_string_append_printf(out, "’");
					break;
				case FRENCH:
					g_string_append_printf(out,"'");
					break;
				case GERMAN:
					g_string_append_printf(out,"‚");
					break;
				case GERMANGUILL:
					g_string_append_printf(out,"›");
					break;
				default:
					g_string_append_printf(out,"‘");
				}
			break;
		case RSQUOTE:
			switch (scratch->language) {
				case GERMAN:
					g_string_append_printf(out,"‘");
					break;
				case GERMANGUILL:
					g_string_append_printf(out,"‹");
					break;
				default:
					g_string_append_printf(out,"’");
				}
			break;
		case APOS:
			g_string_append_printf(out,"’");
			break;
		case LDQUOTE:
			switch (scratch->language) {
				case DUTCH:
				case GERMAN:
					g_string_append_printf(out,"„");
					break;
				case GERMANGUILL:
					g_string_append_printf(out,"»");
					break;
				case FRENCH:
					g_string_append_printf(out,"«");
					break;
				case SWEDISH:
					g_string_append_printf(out, "”");
					break;
				default:
					g_string_append_printf(out,"“");
				}
			break;
		case RDQUOTE:
			switch (scratch->language) {
				case SWEDISH:
				case DUTCH:
					g_string_append_printf(out,"”");
					break;
				case GERMAN:
					g_string_append_printf(out,"“");
					break;
				case GERMANGUILL:
					g_string_append_printf(out,"«");
					break;
				case FRENCH:
					g_string_append_printf(out,"»");
					break;
				default:
					g_string_append_printf(out,"”");
				}
			break;
		case NDASH:
			g_string_append_printf(out,"–");
			break;
		case MDASH:
			g_string_append_printf(out,"—");
			break;
		case ELLIP:
			g_string_append_printf(out,"…");
			break;
			default:;
	}
}

/* print_html_string - print string, escaping for HTML */
long ran_num_next();	/* Use Knuth's pseudo random generator */

void print_html_string(GString *out, char *str, scratch_pad *scratch) {
	if (str == NULL)
		return;
	while (*str != '\0') {
		switch (*str) {
			case '&':
				g_string_append_printf(out, "&");
				break;
			case '<':
				g_string_append_printf(out, "<");
				break;
			case '>':
				g_string_append_printf(out, ">");
				break;
			case '"':
				g_string_append_printf(out, """);
				break;
			default:
				if ((scratch->obfuscate == true) && (extension(EXT_OBFUSCATE, scratch->extensions))
					&& ((int) *str == (((int) *str) & 127))) {
						if (ran_num_next() % 2 == 0)
						g_string_append_printf(out, "&#%d;", (int) *str);
					else
						g_string_append_printf(out, "&#x%x;", (unsigned int) *str);
				} else {
					g_string_append_c(out, *str);
				}
		}
		str++;
	}
}

/* print_col_group - print column alignment config (used in XSLT processing) */
void print_col_group(GString *out,scratch_pad *scratch) {
	char *temp;
	int lev;
	g_string_append_printf(out, "<colgroup>\n");
	temp = scratch->table_alignment;
	for (lev=0;lev<strlen(temp);lev++) {
		if ( strncmp(&temp[lev],"r",1) == 0) {
			g_string_append_printf(out, "<col style=\"text-align:right;\"/>\n");
		} else if ( strncmp(&temp[lev],"R",1) == 0) {
			g_string_append_printf(out, "<col style=\"text-align:right;\" class=\"extended\"/>\n");
		} else if ( strncmp(&temp[lev],"c",1) == 0) {
			g_string_append_printf(out, "<col style=\"text-align:center;\"/>\n");
		} else if ( strncmp(&temp[lev],"C",1) == 0) {
			g_string_append_printf(out, "<col style=\"text-align:center;\" class=\"extended\"/>\n");
		} else if ( strncmp(&temp[lev],"L",1) == 0) {
			g_string_append_printf(out, "<col style=\"text-align:left;\" class=\"extended\"/>\n");
		} else if ( strncmp(&temp[lev],"N",1) == 0) {
			g_string_append_printf(out, "<col class=\"extended\"/>\n");
		} else if ( strncmp(&temp[lev],"n",1) == 0) {
			g_string_append_printf(out, "<col/>\n");
		} else {
			g_string_append_printf(out, "<col style=\"text-align:left;\"/>\n");
		}
	}
	g_string_append_printf(out, "</colgroup>\n");
}


text:
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using EntityFramework.Triggers;

namespace EntityFramework.SoftDeletable {
	public static class SoftDeletableExtensions {
		private class Setters {
			public readonly Action<ISoftDeletable, DateTime?> DeletedPropertySetter;
			public readonly Action<ISoftDeletable> DeletedChangedByIdPropertySetter;

			public Setters(Type softDeletableType) {
				DeletedPropertySetter = PropertyReflection.GetValueSetter<ISoftDeletable, DateTime?>(softDeletableType.GetProperty(nameof(ISoftDeletable.Deleted)));
				DeletedChangedByIdPropertySetter = GetDeletedChangedByIdPropertySetter(softDeletableType);
			}

			private static Action<ISoftDeletable> GetDeletedChangedByIdPropertySetter(Type softDeletableType) {
				var @interface = softDeletableType.GetInterfaces().SingleOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IUserSoftDeletable<>));
				if (@interface == null)
					return null;

				var userIdType = @interface.GenericTypeArguments.Single();
				var setDeletedChangedByIdMethod = typeof(SoftDeletableExtensions).GetMethod(nameof(SetDeletedChangedById), BindingFlags.Static | BindingFlags.NonPublic).MakeGenericMethod(softDeletableType, userIdType);

				var instance = Expression.Parameter(typeof(ISoftDeletable));
				var softDeletable = Expression.Convert(instance, softDeletableType);
				var setterCall = Expression.Call(setDeletedChangedByIdMethod, softDeletable);
				return Expression.Lambda<Action<ISoftDeletable>>(setterCall, instance).Compile();
			}
		}

		private static readonly ConcurrentDictionary<Type, Setters> setterCache = new ConcurrentDictionary<Type, Setters>();

		private static Setters GetSetters(this ISoftDeletable softDeletable) {
			return setterCache.GetOrAdd(softDeletable.GetType(), t => new Setters(t));
		}

		private static class SetterCache<TUserSoftDeletable, TUserId> where TUserSoftDeletable : class, IUserSoftDeletable<TUserId> {
			public static readonly Action<TUserSoftDeletable, TUserId> DeletedChangedByIdPropertySetter = PropertyReflection.GetValueSetter<TUserSoftDeletable, TUserId>(
				typeof(TUserSoftDeletable).GetProperty(nameof(IUserSoftDeletable<TUserId>.DeletedChangedById))
			);
		}

		private static void SetDeletedChangedById<TUserSoftDeletable, TUserId>(this TUserSoftDeletable userSoftDeletable) where TUserSoftDeletable : class, IUserSoftDeletable<TUserId> {
			SetterCache<TUserSoftDeletable, TUserId>.DeletedChangedByIdPropertySetter(userSoftDeletable, userSoftDeletable.GetCurrentUserId());
		}

		public static Boolean IsDeleted(this ISoftDeletable softDeletable) {
			if (softDeletable == null)
				throw new ArgumentNullException(nameof(softDeletable));
			return softDeletable.Deleted != null;
		}

		public static void SoftDelete(this ISoftDeletable softDeletable) {
			if (softDeletable == null)
				throw new ArgumentNullException(nameof(softDeletable));
			if (!softDeletable.IsDeleted())
				softDeletable.SetSoftDeletable(markAsDeleted: true);
		}

		public static void Restore(this ISoftDeletable softDeletable) {
			if (softDeletable == null)
				throw new ArgumentNullException(nameof(softDeletable));
			if (softDeletable.IsDeleted())
				softDeletable.SetSoftDeletable(markAsDeleted: false);
		}

		private static void SetSoftDeletable(this ISoftDeletable softDeletable, Boolean markAsDeleted) {
			var setters = softDeletable.GetSetters();
			setters.DeletedPropertySetter(softDeletable, markAsDeleted ? DateTime.UtcNow : (DateTime?)null);
			setters.DeletedChangedByIdPropertySetter?.Invoke(softDeletable);
		}
	}
};

redpajama_set_name: RedPajamaGithub


text:
<?php get_header(); ?>

        <?php if (have_posts()) : ?>

          <?php while (have_posts()) : the_post(); ?>

              <div id="post-<?php the_ID(); ?>" <?php post_class( 'entry' ); ?>>

<a href="<?php echo get_permalink($post->post_parent); ?>" rev="attachment"><?php echo get_the_title($post->post_parent); ?> » <?php the_title(); ?>

<a href="<?php echo wp_get_attachment_url($post->ID); ?>"><?php echo wp_get_attachment_image( $post->ID, 'auto' ); ?>

<?php if ( !empty($post->post_excerpt) ) the_excerpt(); ?>

<?php if ( !empty($post->post_content) ) the_content(); ?>

<?php previous_image_link() ?>

<?php next_image_link() ?>

			<?php edit_post_link(__('Edit','andreas04'),' | ',''); ?>

              <?php comments_template(); ?>
          <?php endwhile; ?>

        <?php else : ?>

        <?php endif; ?>

      <?php get_sidebar(); ?>

      <?php get_footer(); ?>


text:
namespace Machete.X12Schema.V5010.Segments.Maps
{
    using Machete.X12;
    using Machete.X12.Configuration;

    public class EBMap : X12SegmentMap<EB, X12Entity>
    {
        public EBMap()
        {
            Id = "EB";
            Name = "Eligibility Or Benefit Information";
            Value(x => x.EligibilityOrBenefitInformationCode, 1, x => x.MinLength(1));
            Value(x => x.CoverageLevelCode, 2, x => x.MinLength(1));
            Value(x => x.ServiceTypeCode, 3, x => x.MinLength(1));
            Value(x => x.InsuranceTypeCode, 4, x => x.MinLength(1));
            Value(x => x.PlanCoverageDescription, 5, x => x.MinLength(1));
            Value(x => x.TimePeriodQualifier, 6, x => x.MinLength(1));
            Value(x => x.MonetaryAmount, 7, x => x.MinLength(1));
            Value(x => x.Percent, 8, x => x.MinLength(1));
            Value(x => x.QuantityQualifier, 9, x => x.MinLength(1));
            Value(x => x.Quantity, 10, x => x.MinLength(1));
            Value(x => x.ConditionOrResponseCode1, 11, x => x.MinLength(1));
            Value(x => x.ConditionOrResponseCode2, 12, x => x.MinLength(1));
            Value(x => x.CompositeMedicalProcedureIdentifier, 13, x => x.MinLength(1));
        }
    }
}


text:
//
//  ARSessionImpl.h
//  ARKitTest
//
//  Created by Felix Faire on 11/08/2017.
//

#ifndef ARSessionImpl_h
#define ARSessionImpl_h

#include "cinder/gl/gl.h"
#include "ARAnchorTypes.h"

using namespace ci;

namespace ARKit {

enum TrackingType
{
    OrientationTracking,
    WorldTracking
};

enum PlaneDetection
{
    None,
    Horizontal,
    Vertical,
};

class SessionConfiguration
{
public:
    SessionConfiguration(){}

    SessionConfiguration& trackingType( TrackingType newType )           { mTrackingType = newType; return *this; }
    SessionConfiguration& planeDetection( PlaneDetection detectionType ) { mPlaneDetection = detectionType; return *this; }
    SessionConfiguration& imageTrackingEnabled( bool enabled )           { mImageTrackingEnabled = enabled; return *this; }

    TrackingType          mTrackingType = TrackingType::WorldTracking;
    PlaneDetection        mPlaneDetection = PlaneDetection::None;
    bool                  mImageTrackingEnabled = false;
};

class SessionImpl
{
public:

    SessionImpl();
    ~SessionImpl();

    void runConfiguration( SessionConfiguration config );
    void pause();

    /**  Adds an anchor point to the ARSession relative to the current world orientation.
         Returns the AnchorID of the anchor to reference later on.
    */
    const AnchorID addAnchorRelativeToWorld( vec3 position );

    /**  Adds an anchor point to the ARSession relative from the current camera position
         and orienation. Returns the AnchorID of the anchor to reference later on.
    */
    const AnchorID addAnchorRelativeToCamera( vec3 offset );

    /**  Returns true if the interface / app is running in portrait orientation.
    */
    bool isInterfaceInPortraitOrientation() const;

    std::vector<Anchor>       mAnchors;
    std::vector<PlaneAnchor>  mPlaneAnchors;
    std::vector<ImageAnchor>  mImageAnchors;

    bool                   mRGBCaptureEnabled = true;
    Channel8u              mFrameYChannel;
    Channel8u              mFrameCbChannel;
    Channel8u              mFrameCrChannel;

    mat4                   mViewMatrix;
    mat4                   mProjectionMatrix;

    float                  mAmbientLightIntensity;
    float                  mAmbientColorTemperature;

    bool                   mIsRunning = false;

    vec2                   mCameraSize = vec2( 1.0f );
};

} // namespace ARKit

#endif /* ARSessionImpl_h */


text:
from django.test.client import RequestFactory

from nose.tools import eq_

import mkt
import mkt.site.tests
from mkt.account.utils import purchase_list
from mkt.constants import apps
from mkt.site.fixtures import fixture
from mkt.site.utils import app_factory
from mkt.users.models import UserProfile
from mkt.webapps.models import Webapp

class TestUtils(mkt.site.tests.TestCase):
    fixtures = fixture('user_2519', 'webapp_337141')

    def setUp(self):
        self.user = UserProfile.objects.get(pk=2519)
        self.app = Webapp.objects.get(pk=337141)
        self.req = RequestFactory().get('/')

    def test_user(self):
        self.user.installed_set.create(
            webapp=self.app,
            install_type=apps.INSTALL_TYPE_USER)
        eq_(list(purchase_list(self.req, self.user).object_list), [self.app])

    def test_developer(self):
        self.user.installed_set.create(
            webapp=self.app,
            install_type=apps.INSTALL_TYPE_DEVELOPER)
        eq_(list(purchase_list(self.req, self.user).object_list), [self.app])

    def test_reviewer(self):
        self.user.installed_set.create(
            webapp=self.app,
            install_type=apps.INSTALL_TYPE_REVIEWER)
        eq_(list(purchase_list(self.req, self.user).object_list), [])

    def test_ordering(self):
        self.user.installed_set.create(
            webapp=self.app,
            install_type=apps.INSTALL_TYPE_USER)
        app2 = app_factory()
        self.user.installed_set.create(
            webapp=app2,
            install_type=apps.INSTALL_TYPE_USER)
        eq_(list(purchase_list(self.req, self.user).object_list),
            [app2, self.app])

    def test_contribution_purchase(self):
        self.user.contribution_set.create(
            webapp=self.app,
            type=mkt.CONTRIB_PURCHASE)
        eq_(list(purchase_list(self.req, self.user).object_list), [self.app])

    def test_contribution_refund(self):
        self.user.contribution_set.create(
            webapp=self.app,
            type=mkt.CONTRIB_REFUND)
        eq_(list(purchase_list(self.req, self.user).object_list), [self.app])

    def test_contribution_chargeback(self):
        self.user.contribution_set.create(
            webapp=self.app,
            type=mkt.CONTRIB_CHARGEBACK)
        eq_(list(purchase_list(self.req, self.user).object_list), [self.app])

    def test_contribution_installed_same_app(self):
        self.user.installed_set.create(
            webapp=self.app,
            install_type=apps.INSTALL_TYPE_USER)
        self.user.contribution_set.create(
            webapp=self.app,
            type=mkt.CONTRIB_PURCHASE)
        eq_(list(purchase_list(self.req, self.user).object_list), [self.app])


text:
package com.asu.cse545.group12.email;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/*import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMessage;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;*/

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import com.asu.cse545.group12.domain.Users;

@Service("emailSenderService")
public class EmailSenderAPI {

	@Autowired
	private JavaMailSenderImpl  emailSender;

	private String toEmailAddress = "";
	private String fromEmailAddress = "admin@bankoftempe.com";
	private String body = "";
	private String subject = "";

	public EmailSenderAPI(JavaMailSenderImpl mailSender) {
		emailSender = mailSender;
	}

	public void setMailSender(JavaMailSenderImpl emailSender) {
		this.emailSender = emailSender;
	}

	public void setToEmailAddress(String toEmailAddress) {
		this.toEmailAddress = toEmailAddress;
	}

	public void setFromEmailAddress(String fromEmailAddress) {
		this.fromEmailAddress = fromEmailAddress;
	}

	public void setBody(String body) {
		this.body = body;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public JavaMailSenderImpl getEmailSender() {
		return emailSender;
	}

	public void setEmailSender(JavaMailSenderImpl emailSender) {
		this.emailSender = emailSender;
	}

	public void sendEmail() {

		try {
		 MimeMessage mimemessage = emailSender.createMimeMessage();

			MimeMessageHelper emailMessage = new MimeMessageHelper(mimemessage, true);
			//SimpleMailMessage emailMessage = new SimpleMailMessage();
			emailMessage.setFrom(fromEmailAddress);
			emailMessage.setTo(toEmailAddress);
			emailMessage.setSubject(subject);
			emailMessage.setText(body);
			//emailSender.send(emailMessage);
			emailSender.send(mimemessage);
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void sendEmail(String filename, FileSystemResource file) {

		try {
		 MimeMessage mimemessage = emailSender.createMimeMessage();

			MimeMessageHelper emailMessage = new MimeMessageHelper(mimemessage, true);
			//SimpleMailMessage emailMessage = new SimpleMailMessage();
			emailMessage.setFrom(fromEmailAddress);
			emailMessage.setTo(toEmailAddress);
			emailMessage.setSubject(subject);
			emailMessage.setText(body);
			//emailSender.send(emailMessage);
			emailMessage.addAttachment(filename, file);
			emailSender.send(mimemessage);
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}


text:
<?php

namespace Ardi;

/**
 * Provides mechanisms to generate URLs to different resources
 *
 * @package Ardi
 */
class UrlHelper
{
    private static $cachedBaseUrl;
    private static $cachedViewUrls = array();

    /**
     * Generates the URL to the website relative to the server.
     *
     * @return string Base URL of the website, without trailing slash
     */
    public static function buildBaseUrl()
    {
        if (!isset(self::$cachedBaseUrl)) {
            // All requests go to public/index.php
            $path = explode('/public/index.php', filter_var($_SERVER['PHP_SELF'], FILTER_SANITIZE_STRING));
            self::$cachedBaseUrl = $path[0];
        }
        return self::$cachedBaseUrl;
    }

    /**
     * Generates the url to a view in a specific language.
     *
     * @param string $viewName Global name of the view (usually in English)
     * @param string $lang Language the view will be showed in
     * @param string $queryString (optional) Query string to append to the URL
     * @return string|null The URL to the view or null if not found
     */
    public static function buildViewUrl($viewName, $lang, $queryString = '')
    {
        $cacheKey = $viewName.'-'.$lang;
        if (!isset(self::$cachedViewUrls[$cacheKey])) {
            $routeConfig = ConfigReader::getReader('routes');
            $routes = $routeConfig->get($lang);
            $translatedName = array_search($viewName, $routes);
            if (!$translatedName) {
                return null;
            }
            $builtUrl = self::buildBaseUrl() . "/$lang";
            $builtUrl .= ($translatedName === 'root') ? '' : '/'.$translatedName;
            self::$cachedViewUrls[$cacheKey] = $builtUrl;
        }
        return self::$cachedViewUrls[$cacheKey].$queryString;
    }

    /**
     * Removes the cached urls.
     */
    public static function clearCache()
    {
        self::$cachedBaseUrl = null;
        self::$cachedViewUrls = array();
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <title>Archives - 778477</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description">
<meta property="og:type" content="website">
<meta property="og:title" content="778477">
<meta property="og:url" content="http://yoursite.com/archives/index.html">
<meta property="og:site_name" content="778477">
<meta property="og:description">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="778477">
<meta name="twitter:description">

    <link rel="icon" href="/favicon.png">

  <link href="/webfonts/ptserif/main.css" rel='stylesheet' type='text/css'>
  <link href="/webfonts/source-code-pro/main.css" rel="stylesheet" type="text/css">
  <link rel="stylesheet" href="/css/style.css">

      778477

          Home

          Archives

          Categories

          Tags

          About

          <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" results="0" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit"></button><input type="hidden" name="sitesearch" value="http://yoursite.com"></form>

          2018

  <time datetime="2018-02-23T00:00:00.000Z" itemprop="datePublished">Feb 23</time>

      iOS客户端稳定性体系

          2017

  <time datetime="2017-11-06T00:00:00.000Z" itemprop="datePublished">Nov 6</time>

      UTF8 编码识别

  <time datetime="2017-11-02T00:00:00.000Z" itemprop="datePublished">Nov 2</time>

      Leetcode Attempted Algorithms

  <time datetime="2017-08-29T00:00:00.000Z" itemprop="datePublished">Aug 29</time>

      Spring Boot

  <time datetime="2017-06-19T00:00:00.000Z" itemprop="datePublished">Jun 19</time>

      为什么iOS更新UI操作必须在主线程

  <time datetime="2017-04-20T00:00:00.000Z" itemprop="datePublished">Apr 20</time>

      Core Animation Profile Symbols Not Found

  <time datetime="2017-04-20T00:00:00.000Z" itemprop="datePublished">Apr 20</time>

      iClean 一款Mac OS 软件的诞生

  <time datetime="2017-04-20T00:00:00.000Z" itemprop="datePublished">Apr 20</time>

      iClean

  <time datetime="2017-03-07T00:00:00.000Z" itemprop="datePublished">Mar 7</time>

      TinyURL的生成

  <time datetime="2017-02-27T00:00:00.000Z" itemprop="datePublished">Feb 27</time>

      WebSocket

        123…5Next »

      © 2018 miaoyou.gmy
      Powered by Hexo, theme by PPOffice

  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">


text:
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NPOIHelper.NPOI.Excel
{
    public class ExcelCellSetter
    {
        /// <summary>
        /// 设置单元格样式
        /// </summary>
        /// <param name="cell"></param>
        /// <param name="cellstyle"></param>
        public static void SetCellStyle(ICell cell, ICellStyle cellstyle)
        {
            cell.CellStyle = cellstyle;
        }

        /// <summary>
        /// 获取默认单元格样式
        /// </summary>
        /// <param name="wb"></param>
        /// <returns></returns>
        public static ICellStyle GetDefaultCellStyle(IWorkbook wb)
        {
            ICellStyle cellStyle = wb.CreateCellStyle();
            IFont ifont = wb.CreateFont();
            ifont.FontName = "宋体";
            ifont.FontHeightInPoints = 9;
            ifont.Boldweight = (short)FontBoldWeight.Normal;
            ifont.Color = HSSFColor.Grey50Percent.Index;
            cellStyle.BorderLeft = BorderStyle.Thin;
            cellStyle.BorderRight = BorderStyle.Thin;
            cellStyle.BorderTop = BorderStyle.Thin;
            cellStyle.BorderBottom = BorderStyle.Thin;
            cellStyle.LeftBorderColor = HSSFColor.Black.Index;
            //水平对齐
            cellStyle.Alignment = HorizontalAlignment.Center;
            //垂直对齐
            cellStyle.VerticalAlignment = VerticalAlignment.Center;
            return cellStyle;
        }

        /// <summary>
        /// 设置默认单元格样式
        /// </summary>
        /// <param name="workbook"></param>
        /// <param name="cell"></param>
        public static void SetDefaultCellStyle(IWorkbook workbook, ICell cell)
        {
            ICellStyle cellStyle = GetDefaultCellStyle(workbook);
            cell.CellStyle = cellStyle;
        }

        /// <summary>
        /// 设置默认标题样式
        /// </summary>
        /// <param name="workbook"></param>
        /// <param name="cell"></param>
        public static void SetDefaultTitleCellStyle(IWorkbook workbook, ICell cell)
        {
            ICellStyle cellStyle = GetDefaultCellStyle(workbook);
            //边框
            cellStyle.BorderLeft = BorderStyle.None;
            cellStyle.BorderRight = BorderStyle.None;
            cellStyle.BorderTop = BorderStyle.None;
            cellStyle.BorderBottom = BorderStyle.None;

            IFont ifont = workbook.CreateFont();//cellStyle.GetFont(workbook);

            cellStyle.VerticalAlignment = VerticalAlignment.Center;
            cellStyle.Alignment = HorizontalAlignment.Center;
            cellStyle.WrapText = true;
            ifont.FontName = "方正姚体";
            ifont.FontHeightInPoints = 20;
            ifont.Boldweight = (short)FontBoldWeight.Bold;
            ifont.Color = HSSFColor.Grey50Percent.Index;
            cellStyle.SetFont(ifont);

            cell.CellStyle = cellStyle;
        }

        /// <summary>
        /// 获取默认表头样式
        /// </summary>
        /// <param name="workbook"></param>
        /// <returns></returns>
        public static ICellStyle GetDefaultTableHeaderCellStyle(IWorkbook workbook)
        {
            ICellStyle cellStyle = GetDefaultCellStyle(workbook);
            IFont ifont = workbook.CreateFont();//cellStyle.GetFont(workbook);
            //背景
            cellStyle.FillPattern = FillPattern.SolidForeground;
            cellStyle.FillForegroundColor = HSSFColor.Grey25Percent.Index;
            //水平对齐
            cellStyle.Alignment = HorizontalAlignment.Center;
            //垂直对齐
            cellStyle.VerticalAlignment = VerticalAlignment.Center;
            cellStyle.WrapText = true;

            //字体样式
            ifont.FontName = "方正姚体";
            ifont.FontHeightInPoints = 12;
            ifont.Boldweight = (short)FontBoldWeight.Bold;
            ifont.Color = HSSFColor.Black.Index;
            cellStyle.SetFont(ifont);

            return cellStyle;
        }

        /// <summary>
        /// 设置默认表头样式
        /// </summary>
        /// <param name="workbook"></param>
        /// <param name="cell"></param>
        public static void SetDefaultTableHeaderCellStyle(IWorkbook workbook, ICell cell)
        {
            ICellStyle cellStyle = GetDefaultTableHeaderCellStyle(workbook);
            cell.CellStyle = cellStyle;
        }

        /// <summary>
        /// 设置默认表体样式
        /// </summary>
        /// <param name="workbook"></param>
        /// <param name="cell"></param>
        public static void SetDefaultTableBodyCellStyle(IWorkbook workbook, ICell cell)
        {

        }

        /// <summary>
        /// 设置默认表尾样式
        /// </summary>
        /// <param name="workbook"></param>
        /// <param name="cell"></param>
        public static void SetDefaultTableFooterCellStyle(IWorkbook workbook, ICell cell)
        {

        }

        /// <summary>
        /// 获取默认页头样式
        /// </summary>
        /// <param name="workbook"></param>
        /// <returns></returns>
        public static ICellStyle GetDefaultHeaderCellStyle(IWorkbook workbook)
        {
            ICellStyle cellStyle = GetDefaultCellStyle(workbook);
            //边框
            cellStyle.BorderLeft = BorderStyle.None;
            cellStyle.BorderRight = BorderStyle.None;
            cellStyle.BorderTop = BorderStyle.None;
            cellStyle.BorderBottom = BorderStyle.None;

            IFont ifont = workbook.CreateFont();//cellStyle.GetFont(workbook);

            //水平对齐
            cellStyle.Alignment = HorizontalAlignment.Left;
            //垂直对齐
            cellStyle.VerticalAlignment = VerticalAlignment.Center;
            cellStyle.WrapText = true;

            //字体样式
            ifont.FontName = "宋体";
            ifont.FontHeightInPoints = 10;
            ifont.Boldweight = (short)FontBoldWeight.Normal;
            ifont.Color = HSSFColor.Grey40Percent.Index;
            cellStyle.SetFont(ifont);

            return cellStyle;
        }

        /// <summary>
        /// 设置默认页头样式
        /// </summary>
        /// <param name="workbook"></param>
        /// <param name="cell"></param>
        public static void SetDefaultHeaderCellStyle(IWorkbook workbook, ICell cell)
        {
            ICellStyle cellStyle = GetDefaultHeaderCellStyle(workbook);
            cell.CellStyle = cellStyle;
        }

        public static ICellStyle GetDefaultFooterCellStyle(IWorkbook workbook)
        {
            ICellStyle cellStyle = GetDefaultCellStyle(workbook);
            //边框
            cellStyle.BorderLeft = BorderStyle.None;
            cellStyle.BorderRight = BorderStyle.None;
            cellStyle.BorderTop = BorderStyle.None;
            cellStyle.BorderBottom = BorderStyle.None;
            //水平对齐
            cellStyle.Alignment = HorizontalAlignment.Center;
            //垂直对齐
            cellStyle.VerticalAlignment = VerticalAlignment.Center;
            return cellStyle;
        }

        /// <summary>
        /// 设置默认页尾样式
        /// </summary>
        /// <param name="workbook"></param>
        /// <param name="cell"></param>
        public static void SetDefaultFooterCellStyle(IWorkbook workbook, ICell cell)
        {
            ICellStyle cellStyle = GetDefaultFooterCellStyle(workbook);
            cell.CellStyle = cellStyle;
        }
    }
}


text:
<!DOCTYPE html >

    <link rel="stylesheet" href="demos.css" type="text/css" media="screen" />

    <meta name="description" content="A demonstration of the Scatter chart with a Chrome-only (currently) dotted and dashed background grid" />

A demo of the Chrome-only dotted or dashed background grid

        This uses the newer addition to canvas from the canvas v5 specification - native dotted and dashed lines.
        As browsers add support you will be able to use the option in those too but initially it's only supported in Chrome.

obj.Set('background.grid.dashed', true);
obj.Set('background.grid.dotted', true);

    <canvas id="cvs1" width="600" height="250">[No canvas support]</canvas>
    <canvas id="cvs2" width="600" height="250">[No canvas support]</canvas>


text:
require "rubygems"
require "bundler"
Bundler.setup(:default)

$:.unshift(File.expand_path('../../lib', __FILE__))

require 'rspec'
require 'nokogiri'

require 'ruby-plsql-spec'

DATABASE_NAME = ENV['DATABASE_NAME'] || 'orcl'
DATABASE_SERVICE_NAME = (defined?(JRUBY_VERSION) ? "/" : "") +
                        (ENV['DATABASE_SERVICE_NAME'] || DATABASE_NAME)
DATABASE_HOST = ENV['DATABASE_HOST'] || 'localhost'
DATABASE_PORT = (ENV['DATABASE_PORT'] || 1521).to_i
DATABASE_USER = ENV['DATABASE_USER'] || 'hr'
DATABASE_PASSWORD = ENV['DATABASE_PASSWORD'] || 'hr'

CONNECTION_PARAMS = {
  :username => DATABASE_USER,
  :password => DATABASE_PASSWORD,
  :database => DATABASE_SERVICE_NAME
}
CONNECTION_PARAMS[:host] = DATABASE_HOST if defined?(DATABASE_HOST)
CONNECTION_PARAMS[:port] = DATABASE_PORT if defined?(DATABASE_PORT)

RSpec.configure do |config|
  # taken from thor specs
  def capture(stream)
    begin
      stream = stream.to_s
      eval "$#{stream} = StringIO.new"
      yield
      result = eval("$#{stream}").string
    ensure
      eval("$#{stream} = #{stream.upcase}")
    end

    result
  end
  alias :silence :capture

  def source_root
    File.join(File.dirname(__FILE__), 'fixtures')
  end

  def destination_root
    File.join(File.dirname(__FILE__), 'sandbox')
  end

end

# set default time zone in TZ environment variable
# which will be used to set session time zone
ENV['TZ'] ||= 'Europe/Riga'
# ENV['TZ'] ||= 'UTC'


text:
int main()
{
    Window window;
    window.Initialize();
    window.Run();
    return 0;
}


text:
package com.netflix.priam.backup;

import com.google.inject.ImplementedBy;
import java.time.Instant;

@ImplementedBy(BackupDynamicRateLimiter.class)
public interface DynamicRateLimiter {
    void acquire(AbstractBackupPath dir, Instant target, int tokens);
}


text:
// Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gerrit.server.config;

import com.google.common.flogger.FluentLogger;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.plugins.Plugin;
import com.google.gerrit.server.plugins.ReloadPluginListener;
import com.google.gerrit.server.project.NoSuchProjectException;
import com.google.gerrit.server.project.ProjectCache;
import com.google.gerrit.server.project.ProjectLevelConfig;
import com.google.gerrit.server.project.ProjectState;
import com.google.gerrit.server.securestore.SecureStore;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.internal.storage.file.FileSnapshot;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.storage.file.FileBasedConfig;
import org.eclipse.jgit.util.FS;

@Singleton
public class PluginConfigFactory implements ReloadPluginListener {
  private static final FluentLogger logger = FluentLogger.forEnclosingClass();

  private static final String EXTENSION = ".config";

  private final SitePaths site;
  private final Provider<Config> cfgProvider;
  private final ProjectCache projectCache;
  private final ProjectState.Factory projectStateFactory;
  private final SecureStore secureStore;
  private final Map<String, Config> pluginConfigs;

  private volatile FileSnapshot cfgSnapshot;
  private volatile Config cfg;

  @Inject
  PluginConfigFactory(
      SitePaths site,
      @GerritServerConfig Provider<Config> cfgProvider,
      ProjectCache projectCache,
      ProjectState.Factory projectStateFactory,
      SecureStore secureStore) {
    this.site = site;
    this.cfgProvider = cfgProvider;
    this.projectCache = projectCache;
    this.projectStateFactory = projectStateFactory;
    this.secureStore = secureStore;

    this.pluginConfigs = new HashMap<>();
    this.cfgSnapshot = FileSnapshot.save(site.gerrit_config.toFile());
    this.cfg = cfgProvider.get();
  }

  /**
   * Returns the configuration for the specified plugin that is stored in the 'gerrit.config' file.
   *
   *
The returned plugin configuration provides access to all parameters of the 'gerrit.config'
   * file that are set in the 'plugin' subsection of the specified plugin.
   *
   *
E.g.: [plugin "my-plugin"] myKey = myValue
   *
   * @param pluginName the name of the plugin for which the configuration should be returned
   * @return the plugin configuration from the 'gerrit.config' file
   */
  public PluginConfig getFromGerritConfig(String pluginName) {
    return getFromGerritConfig(pluginName, false);
  }

  /**
   * Returns the configuration for the specified plugin that is stored in the 'gerrit.config' file.
   *
   *
The returned plugin configuration provides access to all parameters of the 'gerrit.config'
   * file that are set in the 'plugin' subsection of the specified plugin.
   *
   *
E.g.: [plugin "my-plugin"] myKey = myValue
   *
   * @param pluginName the name of the plugin for which the configuration should be returned
   * @param refresh if true it is checked if the 'gerrit.config' file was modified and
   *     if yes the Gerrit configuration is reloaded, if false the cached Gerrit
   *     configuration is used
   * @return the plugin configuration from the 'gerrit.config' file
   */
  public PluginConfig getFromGerritConfig(String pluginName, boolean refresh) {
    if (refresh && secureStore.isOutdated()) {
      secureStore.reload();
    }
    File configFile = site.gerrit_config.toFile();
    if (refresh && cfgSnapshot.isModified(configFile)) {
      cfgSnapshot = FileSnapshot.save(configFile);
      cfg = cfgProvider.get();
    }
    return new PluginConfig(pluginName, cfg);
  }

  /**
   * Returns the configuration for the specified plugin that is stored in the 'project.config' file
   * of the specified project.
   *
   *
The returned plugin configuration provides access to all parameters of the 'project.config'
   * file that are set in the 'plugin' subsection of the specified plugin.
   *
   *
E.g.: [plugin "my-plugin"] myKey = myValue
   *
   * @param projectName the name of the project for which the plugin configuration should be
   *     returned
   * @param pluginName the name of the plugin for which the configuration should be returned
   * @return the plugin configuration from the 'project.config' file of the specified project
   * @throws NoSuchProjectException thrown if the specified project does not exist
   */
  public PluginConfig getFromProjectConfig(Project.NameKey projectName, String pluginName)
      throws NoSuchProjectException {
    ProjectState projectState = projectCache.get(projectName);
    if (projectState == null) {
      throw new NoSuchProjectException(projectName);
    }
    return getFromProjectConfig(projectState, pluginName);
  }

  /**
   * Returns the configuration for the specified plugin that is stored in the 'project.config' file
   * of the specified project.
   *
   *
The returned plugin configuration provides access to all parameters of the 'project.config'
   * file that are set in the 'plugin' subsection of the specified plugin.
   *
   *
E.g.: [plugin "my-plugin"] myKey = myValue
   *
   * @param projectState the project for which the plugin configuration should be returned
   * @param pluginName the name of the plugin for which the configuration should be returned
   * @return the plugin configuration from the 'project.config' file of the specified project
   */
  public PluginConfig getFromProjectConfig(ProjectState projectState, String pluginName) {
    return projectState.getConfig().getPluginConfig(pluginName);
  }

  /**
   * Returns the configuration for the specified plugin that is stored in the 'project.config' file
   * of the specified project. Parameters which are not set in the 'project.config' of this project
   * are inherited from the parent project's 'project.config' files.
   *
   *
The returned plugin configuration provides access to all parameters of the 'project.config'
   * file that are set in the 'plugin' subsection of the specified plugin.
   *
   *
E.g.: child project: [plugin "my-plugin"] myKey = childValue
   *
   *
parent project: [plugin "my-plugin"] myKey = parentValue anotherKey = someValue
   *
   *
return: [plugin "my-plugin"] myKey = childValue anotherKey = someValue
   *
   * @param projectName the name of the project for which the plugin configuration should be
   *     returned
   * @param pluginName the name of the plugin for which the configuration should be returned
   * @return the plugin configuration from the 'project.config' file of the specified project with
   *     inherited non-set parameters from the parent projects
   * @throws NoSuchProjectException thrown if the specified project does not exist
   */
  public PluginConfig getFromProjectConfigWithInheritance(
      Project.NameKey projectName, String pluginName) throws NoSuchProjectException {
    return getFromProjectConfig(projectName, pluginName).withInheritance(projectStateFactory);
  }

  /**
   * Returns the configuration for the specified plugin that is stored in the 'project.config' file
   * of the specified project. Parameters which are not set in the 'project.config' of this project
   * are inherited from the parent project's 'project.config' files.
   *
   *
The returned plugin configuration provides access to all parameters of the 'project.config'
   * file that are set in the 'plugin' subsection of the specified plugin.
   *
   *
E.g.: child project: [plugin "my-plugin"] myKey = childValue
   *
   *
parent project: [plugin "my-plugin"] myKey = parentValue anotherKey = someValue
   *
   *
return: [plugin "my-plugin"] myKey = childValue anotherKey = someValue
   *
   * @param projectState the project for which the plugin configuration should be returned
   * @param pluginName the name of the plugin for which the configuration should be returned
   * @return the plugin configuration from the 'project.config' file of the specified project with
   *     inherited non-set parameters from the parent projects
   */
  public PluginConfig getFromProjectConfigWithInheritance(
      ProjectState projectState, String pluginName) {
    return getFromProjectConfig(projectState, pluginName).withInheritance(projectStateFactory);
  }

  /**
   * Returns the configuration for the specified plugin that is stored in the plugin configuration
   * file '{@code etc/<plugin-name>.config}'.
   *
   *
The plugin configuration is only loaded once and is then cached.
   *
   * @param pluginName the name of the plugin for which the configuration should be returned
   * @return the plugin configuration from the '{@code etc/<plugin-name>.config}' file
   */
  public synchronized Config getGlobalPluginConfig(String pluginName) {
    if (pluginConfigs.containsKey(pluginName)) {
      return pluginConfigs.get(pluginName);
    }

    Path pluginConfigFile = site.etc_dir.resolve(pluginName + ".config");
    FileBasedConfig cfg = new FileBasedConfig(pluginConfigFile.toFile(), FS.DETECTED);
    GlobalPluginConfig pluginConfig = new GlobalPluginConfig(pluginName, cfg, secureStore);
    pluginConfigs.put(pluginName, pluginConfig);
    if (!cfg.getFile().exists()) {
      logger.atInfo().log("No %s; assuming defaults", pluginConfigFile.toAbsolutePath());
      return pluginConfig;
    }

    try {
      cfg.load();
    } catch (ConfigInvalidException e) {
      // This is an error in user input, don't spam logs with a stack trace.
      logger.atWarning().log("Failed to load %s: %s", pluginConfigFile.toAbsolutePath(), e);
    } catch (IOException e) {
      logger.atWarning().withCause(e).log("Failed to load %s", pluginConfigFile.toAbsolutePath());
    }

    return pluginConfig;
  }

  /**
   * Returns the configuration for the specified plugin that is stored in the '{@code
   * <plugin-name>.config}' file in the 'refs/meta/config' branch of the specified project.
   *
   * @param projectName the name of the project for which the plugin configuration should be
   *     returned
   * @param pluginName the name of the plugin for which the configuration should be returned
   * @return the plugin configuration from the '{@code <plugin-name>.config}' file of the specified
   *     project
   * @throws NoSuchProjectException thrown if the specified project does not exist
   */
  public Config getProjectPluginConfig(Project.NameKey projectName, String pluginName)
      throws NoSuchProjectException {
    return getPluginConfig(projectName, pluginName).get();
  }

  /**
   * Returns the configuration for the specified plugin that is stored in the '{@code
   * <plugin-name>.config}' file in the 'refs/meta/config' branch of the specified project.
   *
   * @param projectState the project for which the plugin configuration should be returned
   * @param pluginName the name of the plugin for which the configuration should be returned
   * @return the plugin configuration from the '{@code <plugin-name>.config}' file of the specified
   *     project
   */
  public Config getProjectPluginConfig(ProjectState projectState, String pluginName) {
    return projectState.getConfig(pluginName + EXTENSION).get();
  }

  /**
   * Returns the configuration for the specified plugin that is stored in the '{@code
   * <plugin-name>.config}' file in the 'refs/meta/config' branch of the specified project.
   * Parameters which are not set in the '{@code <plugin-name>.config}' of this project are
   * inherited from the parent project's '{@code <plugin-name>.config}' files.
   *
   *
E.g.: child project: [mySection "mySubsection"] myKey = childValue
   *
   *
parent project: [mySection "mySubsection"] myKey = parentValue anotherKey = someValue
   *
   *
return: [mySection "mySubsection"] myKey = childValue anotherKey = someValue
   *
   * @param projectName the name of the project for which the plugin configuration should be
   *     returned
   * @param pluginName the name of the plugin for which the configuration should be returned
   * @return the plugin configuration from the '{@code <plugin-name>.config}' file of the specified
   *     project with inheriting non-set parameters from the parent projects
   * @throws NoSuchProjectException thrown if the specified project does not exist
   */
  public Config getProjectPluginConfigWithInheritance(
      Project.NameKey projectName, String pluginName) throws NoSuchProjectException {
    return getPluginConfig(projectName, pluginName).getWithInheritance(false);
  }

  /**
   * Returns the configuration for the specified plugin that is stored in the '{@code
   * <plugin-name>.config}' file in the 'refs/meta/config' branch of the specified project.
   * Parameters which are not set in the '{@code <plugin-name>.config}' of this project are
   * inherited from the parent project's '{@code <plugin-name>.config}' files.
   *
   *
E.g.: child project: [mySection "mySubsection"] myKey = childValue
   *
   *
parent project: [mySection "mySubsection"] myKey = parentValue anotherKey = someValue
   *
   *
return: [mySection "mySubsection"] myKey = childValue anotherKey = someValue
   *
   * @param projectState the project for which the plugin configuration should be returned
   * @param pluginName the name of the plugin for which the configuration should be returned
   * @return the plugin configuration from the '{@code <plugin-name>.config}' file of the specified
   *     project with inheriting non-set parameters from the parent projects
   */
  public Config getProjectPluginConfigWithInheritance(
      ProjectState projectState, String pluginName) {
    return projectState.getConfig(pluginName + EXTENSION).getWithInheritance(false);
  }

  /**
   * Returns the configuration for the specified plugin that is stored in the '{@code
   * <plugin-name>.config}' file in the 'refs/meta/config' branch of the specified project.
   * Parameters from the '{@code <plugin-name>.config}' of the parent project are appended to this
   * project's '{@code <plugin-name>.config}' files.
   *
   *
E.g.: child project: [mySection "mySubsection"] myKey = childValue
   *
   *
parent project: [mySection "mySubsection"] myKey = parentValue anotherKey = someValue
   *
   *
return: [mySection "mySubsection"] myKey = childValue myKey = parentValue anotherKey =
   * someValue
   *
   * @param projectName the name of the project for which the plugin configuration should be
   *     returned
   * @param pluginName the name of the plugin for which the configuration should be returned
   * @return the plugin configuration from the '{@code <plugin-name>.config}' file of the specified
   *     project with parameters from the parent projects appended to the project values
   * @throws NoSuchProjectException thrown if the specified project does not exist
   */
  public Config getProjectPluginConfigWithMergedInheritance(
      Project.NameKey projectName, String pluginName) throws NoSuchProjectException {
    return getPluginConfig(projectName, pluginName).getWithInheritance(true);
  }

  /**
   * Returns the configuration for the specified plugin that is stored in the '{@code
   * <plugin-name>.config}' file in the 'refs/meta/config' branch of the specified project.
   * Parameters from the '{@code <plugin-name>.config}' of the parent project are appended to this
   * project's '{@code <plugin-name>.config}' files.
   *
   *
E.g.: child project: [mySection "mySubsection"] myKey = childValue
   *
   *
parent project: [mySection "mySubsection"] myKey = parentValue anotherKey = someValue
   *
   *
return: [mySection "mySubsection"] myKey = childValue myKey = parentValue anotherKey =
   * someValue
   *
   * @param projectState the project for which the plugin configuration should be returned
   * @param pluginName the name of the plugin for which the configuration should be returned
   * @return the plugin configuration from the '{@code <plugin-name>.config}' file of the specified
   *     project with inheriting non-set parameters from the parent projects
   */
  public Config getProjectPluginConfigWithMergedInheritance(
      ProjectState projectState, String pluginName) {
    return projectState.getConfig(pluginName + EXTENSION).getWithInheritance(true);
  }

  private ProjectLevelConfig getPluginConfig(Project.NameKey projectName, String pluginName)
      throws NoSuchProjectException {
    ProjectState projectState = projectCache.get(projectName);
    if (projectState == null) {
      throw new NoSuchProjectException(projectName);
    }
    return projectState.getConfig(pluginName + EXTENSION);
  }

  @Override
  public synchronized void onReloadPlugin(Plugin oldPlugin, Plugin newPlugin) {
    pluginConfigs.remove(oldPlugin.getName());
  }
}


text:
class CreateDevices < ActiveRecord::Migration
  def change
    create_table :devices do |t|
      t.string :name
      t.text :description
      t.text :notes

      t.integer :lock_version, default: 0
      t.timestamps null: false
    end

    add_index :devices, :name, unique: true
  end
end


text:
using System.Data;
using System.Diagnostics;
using FluidDbClient.Sql;

namespace FluidDbClient.Sandbox.Demos.ParameterSpecification
{
    public class DemoNullParameters2
    {
        public static void Start()
        {
            /*--------------------------------------------------------------------------------------
                The SqlParamDef class is in the FluidDbClient Sql Server provider.

                It allows a Sql parameter to be *partially* defined :
                    * name is NOT specified
                    * value can be specified, otherwise null assumed
                    * auxillary properties (direction, size, etc.) are optional

                Nulls are automatically converted into DBNull objects.
            ----------------------------------------------------------------------------------------*/

            var cmd = new ScriptDbCommand("UPDATE Robot SET DateDestroyed = @dd WHERE Name = @name;",
                                          new { name = "Terminator", dd = new SqlParamDef(SqlDbType.Date) });

            // NOTE: the @dd parameter is now semantically correct even with the null value
            Debug.WriteLine(cmd.ToDiagnosticString());

            cmd.Execute();
        }
    }
}


text:
<?php
/*
KOIVI HTML Form to FDF Parser for PHP (C) 2004 Justin Koivisto
Version 2.0
Last Modified: 2/1/2005 8:18AM

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation; either version 2.1 of the License, or (at
    your option) any later version.

    This library is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
    License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this library; if not, write to the Free Software Foundation,
    Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

    Full license agreement notice can be found in the LICENSE file contained
    within this distribution package.

    Justin Koivisto
    justin.koivisto@gmail.com
    http://koivi.com
*/

    include dirname(__FILE__).'/pdf_process.php';
    echo '<?xml version="1.0" encoding="iso-8859-1"?>',"\n";    // because short_open_tags = On causes a parse error.
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Tutorial: Fill in PDF Fields With Submitted Form Data</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta name="description" content="A PHP solution to filling a PDF file's form fields with data from a submitted HTML form." />

Tutorial: Fill in PDF Fields With Submitted Form Data

     Due to recent popularity of my original article (and a couple donations!), I was able to find
     some extra time to write out a tutorial on how to implement my original createFDF function into your website using both
     PDF as well as HTML forms to populate your PDF documents with submitted data. In order to follow this tutorial in whole,
     you will need to have the Adobe Acrobat software (not
     the reader, but the full application) and a web server that supports PHP. So without
     further delay, let's get down and dirty.

Back to article

Submitting Data to a PDF from via HTML and/or PDF forms

     This is a short tutorial about how to implement my original createFDF function into your website OR web application
     so you can import user-submitted data into your PDF files. The most popular reason for using a method like this is
     so the data can be represented in a standard format that is easy to comprehend. This method can be useful for things
     like employment applications where you not only accept them online, but also through the mail. A single PDF document
     allows your web users to provide you with information in a variety of ways, but all are formatted to the way yout
     Human Resources department will expect to see them.

Create your PDF document that you want the submitted data imported to.

       To do this, I had used Quark to create the initial document, but you can use pretty much any application to produce
       it. Since I am using Microsoft Windows, I just printed my document to the "Adobe PDF" entry in my printer control
       panel that was created when installing Acrobat. Initial PDF document (5.7 KB).

Once you have your initial PDF document ready, it is time to add fields to import the data into.

Open your PDF document, and select the Text Field Tool.

You can also access the Text Field Tool via the Tools » Advanced Editing » Forms menu.

         Draw your first text field. When you do, a window will pop up prompting for field information. There are
         quite a few options for each of the fields, but the only one we are concerned with for this tutorial is
         the "Name" property under the Genera; tab.

         Enter a name for this field name. Keep in mind that when submitted, PHP will automatically convert spaces to
         underscores when data is posted. Therefore, it's best not to use spaces in the first place (to save time later).

         Repeat this step for the rest of your text fields. Notice that the Comments field would be a great place to use
         an HTML textarea field element. Therefore, in Acrobat's field properties, under the options tab, I have selected
         the "Multi-line" option.

         Save your PDF form. Notice that when you open it up again, it looks the same as the initial document. The only
         difference is that you can now place the cursor over the fields and actually type in information.
         PDF document with form (8.2 KB).

Create the form that the users will fill in to submit the data.

Using an HTML form to allow users to fill in the data.

         Create your HTML form for your web visitors to fill out. You do not have to include all the fields that
         your PDF uses. For instance, in this tutorial, I will automatically fill in the date field when the form
         is processed. Below is an example HTML form to use with this tutorial.

<?php show_source('example_form.html'); ?>

Here is how that would look in your borwser:

<?php include 'example_form.html'; ?>

Using a PDF form to allow users to fill in the data.

         When using multi-page or long forms (a job application form for example), you may want to allow your visitors
         to simply fill in the PDF file to preserve formatting. You have 3 options:

Have the users print the PDF and fill it in by hand and mail it,

Have the users type in the information using the PDF, print it and mail it or

Have the users type in the information using the PDF and submit it online.

         Because of the nature of PDF documents, you can be fairly certain that any of these options will produce
         similar results.  We can cover all three options without additional effort (assuming you want to be able
         to accept the submission online in the first place).

         Create the PDF that your visitors will fill out. In most cases, this will be the exact PDF that you
         created earlier with an added submit button, so let's add that.

Open your PDF document that has the form and select the button tool.

Draw the button in the document. This is what the users will click to submit the form.

Select the Actions tab of the field properties.

Select the Submit a Form option under the Select Action field and click the Add button.

Select the HTML Export Format.

Enter the URL of the processing script.

Select All fields option for the Field Selection

Select All fields option for the Field Selection

Click OK

Save your visitor PDF file. PDF document with user form (9.0 KB).

Add your data-processing PHP script to handle the posted data.

       The very first thing you will want to do is check that you are getting the data you expect when a form is submitted.
       The best way to do this is to create your processing script with the only following code:

      <?php echo '<pre>'; print_r($_POST); echo '</pre>'; ?>

       This will show you how your submitted data is coming across, field names and all. Check the field names against
       the names used in your PDF file that the data will be imported to. An example output may look like this:

Array
    (
        [Text2] => Justin Kovisto
        [Text3] => Purple
        [Text4] => 28
        [Text5] => This tutorial is taking more time than I thought! ;)
        [Button6] => Submit Online
    )

       Once you have verified that the field names are the same as in your PDF file, you can start writing your processing
       script. For this example, we will simply take the submitted information and write an fdf file to the server's
       filesystem to use later. (I also have created versions of this processing script to store the FDF data in a database
       for later retrieval as well as emailing the file as an attachment.)

       Firstly, you only want to attempt to process if a form was posted and the information you wanted was there. Add your
       custom verification routines and errors as you see fit. I will keep this very simple (and probably not that secure)
       for illustration purposes. Here is an example processing script:

<?php show_source('submit_form.php'); ?>

You will also need the createFDF.php file in the same directory. This file has the following contents:

<?php show_source('createFDF.php'); ?>

Code Download

This tutorial is now included in the source code that is available for download as part of the first article.

<?php include_once 'site_menu.php'; ?>


text:
package daemon

import (
	"net"
	"os"
	"path/filepath"

	"github.com/pkg/errors"
)

func (d *Daemon) createListener() (net.Listener, error) {
	var location string

	if xdgRuntimeDir := os.Getenv("XDG_RUNTIME_DIR"); xdgRuntimeDir != "" {
		location = filepath.Join(xdgRuntimeDir, "trustless", "daemon.sock")
	} else {
		location = filepath.Join(os.Getenv("HOME"), ".trustless", "daemon.sock")
	}

	if err := os.MkdirAll(filepath.Dir(location), 0700); err != nil {
		return nil, errors.Wrap(err, "Failed to create socket dir")
	}

	listener, err := net.ListenUnix("unix", &net.UnixAddr{
		Net:  "unix",
		Name: location,
	})
	if err != nil {
		return nil, errors.Wrap(err, "Failed to create listener")
	}
	listener.SetUnlinkOnClose(true)
	if err := os.Chmod(location, 0700); err != nil {
		return nil, errors.Wrap(err, "Failed to chmod")
	}

	return listener, nil
}


text:
<?php

declare(strict_types=1);

namespace bizley\tests\functional\pgsql;

use bizley\tests\functional\DbLoaderTestCase;
use bizley\tests\stubs\MigrationControllerStub;
use Yii;
use yii\base\Exception;
use yii\base\InvalidRouteException;
use yii\base\NotSupportedException;
use yii\console\Exception as ConsoleException;
use yii\console\ExitCode;
use yii\db\Exception as DbException;

/** @group pgsql */
class UpdaterSchemasTest extends DbLoaderTestCase
{
    /** @var MigrationControllerStub */
    protected $controller;
    /** @var string */
    public static $schema = 'pgsql';

    /**
     * @throws NotSupportedException
     * @throws DbException
     */
    protected function setUp(): void
    {
        $this->controller = new MigrationControllerStub('migration', Yii::$app);
        $this->controller->migrationPath = '@bizley/tests/migrations';
        MigrationControllerStub::$stdout = '';
        MigrationControllerStub::$content = '';
        MigrationControllerStub::$confirmControl = true;

        $this->addSchemasBase();
    }

    /**
     * @test
     * @throws ConsoleException
     * @throws InvalidRouteException
     * @throws Exception
     */
    public function shouldFindMatchingSchemasTables(): void
    {
        MigrationControllerStub::$confirmControl = false;
        self::assertEquals(ExitCode::OK, $this->controller->runAction('update', ['schema*']));
        self::assertStringContainsString(
            ' > 1 table excluded by the config.
 > Are you sure you want to generate migrations for the following tables?
   - schema1.table1
   - schema2.table1
 Operation cancelled by user.
',
            MigrationControllerStub::$stdout
        );
    }

    /**
     * @test
     * @throws ConsoleException
     * @throws InvalidRouteException
     * @throws Exception
     */
    public function shouldFindMatchingTablesWithoutSchemasToo(): void
    {
        $this->createTables([
            'schematable' => ['col' => $this->integer()]
        ]);

        MigrationControllerStub::$confirmControl = false;
        self::assertEquals(ExitCode::OK, $this->controller->runAction('update', ['schema*']));
        self::assertStringContainsString(
            ' > 1 table excluded by the config.
 > Are you sure you want to generate migrations for the following tables?
   - schematable
   - schema1.table1
   - schema2.table1
 Operation cancelled by user.
',
            MigrationControllerStub::$stdout
        );

        $this->getDb()->createCommand()->dropTable('schematable')->execute();
    }

    /**
     * @test
     * @throws ConsoleException
     * @throws InvalidRouteException
     * @throws Exception
     */
    public function shouldCreateNewSchemaTable(): void
    {
        $this->createSchema('test');
        $this->createTables([
            'test.table' => ['col' => $this->integer()]
        ]);
        $transaction = $this->getDb()->getTransaction();
        if ($transaction) {
            $transaction->commit();
        }

        self::assertEquals(ExitCode::OK, $this->controller->runAction('update', ['test.table']));
        self::assertStringContainsString(
            ' > 1 table excluded by the config.

 > Comparing current table \'test.table\' with its migrations ...DONE!

 > Generating migration for creating table \'test.table\' ...DONE!
 > Saved as \'',
            MigrationControllerStub::$stdout
        );

        self::assertStringContainsString(
            '_create_table_test_table.php\'

 Generated 1 file
 (!) Remember to verify files before applying migration.
',
            MigrationControllerStub::$stdout
        );
        self::assertStringContainsString(
            '_create_table_test_table extends Migration',
            MigrationControllerStub::$content
        );
        self::assertStringContainsString(
            '
        $this->createTable(
            \'{{%test.table}}\',
            [
                \'col\' => $this->integer(),
            ],
            $tableOptions
        );
    }

    public function safeDown()
    {
        $this->dropTable(\'{{%test.table}}\');
    }',
            MigrationControllerStub::$content
        );
    }

    /**
     * @test
     * @throws ConsoleException
     * @throws InvalidRouteException
     * @throws Exception
     */
    public function shouldUpdateSchemaTable(): void
    {
        $this->getDb()->createCommand()->addColumn('schema1.table1', 'added', $this->integer())->execute();

        self::assertEquals(ExitCode::OK, $this->controller->runAction('update', ['schema1.table1']));
        self::assertStringContainsString(
            ' > 1 table excluded by the config.

 > Comparing current table \'schema1.table1\' with its migrations ...DONE!

 > Generating migration for updating table \'schema1.table1\' ...DONE!
 > Saved as \'',
            MigrationControllerStub::$stdout
        );
        self::assertStringContainsString(
            '_update_table_schema1_table1.php\'

 Generated 1 file
 (!) Remember to verify files before applying migration.
',
            MigrationControllerStub::$stdout
        );
        self::assertStringContainsString(
            '_update_table_schema1_table1 extends Migration',
            MigrationControllerStub::$content
        );
        self::assertStringContainsString(
            'public function safeUp()
    {
        $this->addColumn(\'{{%schema1.table1}}\', \'added\', $this->integer()->after(\'col2\'));
    }

    public function safeDown()
    {
        $this->dropColumn(\'{{%schema1.table1}}\', \'added\');
    }',
            MigrationControllerStub::$content
        );
    }
}