text:
#include <string.h>
#include <gtk/gtk.h>
#include <webkit/webkit.h>
#include <glib/gprintf.h>
#include "hydra.h"
#include "config.h"
#include "tab.h"
#include "browser.h"
#include "utils.h"

#define DOWNLOAD_LOCATION g_get_home_dir()

/* callbacks */
static void tab_close_button_clicked_cb(GtkWidget *widget, Tab *t);
static void tab_search_entry_activated_cb(GtkWidget *entry, Tab *t);
static void tab_search_previous_cb(GtkWidget *widget, Tab *t);
static void tab_search_next_cb(GtkWidget *widget, Tab *t);
static void tab_search_highlight_cb(GtkWidget *widget, Tab *t);
static void tab_search_case_cb(GtkWidget *widget, Tab *t);
static void tab_icon_loaded_cb(WebKitWebView *view, char *icon_uri, Tab *t);
static WebKitWebView *tab_new_requested(WebKitWebView *v, WebKitWebFrame *f, Tab *t);
static void tab_download_cb(WebKitWebView *web_view, GObject *d, gpointer user_data);
static void tab_title_changed(WebKitWebView *view, GParamSpec *pspec, Tab *t);
static void tab_load_status_changed(WebKitWebView *view, GParamSpec *pspec, Tab *t);
static void tab_progress_changed_cb(WebKitWebView *view, GParamSpec *pspec, Tab *t);
static void tab_search(Tab *t, const char *str, gboolean forward, gboolean case_sensitive);

/*
static void tab_close_button_style_set_cb(GtkWidget *button, GtkRcStyle *prev_style, gpointer data)
{
	int w, h;

	gtk_icon_size_lookup_for_settings(gtk_widget_get_settings(button), GTK_ICON_SIZE_MENU, &w, &h);
	gtk_widget_set_size_request(button, w, h);
}
*/

static void tab_close_button_clicked_cb(GtkWidget *widget, Tab *t)
{
	/* use browser_close_tab - tab_close doesn't close after last tab */
	browser_close_tab(t->parent, t);
}

/* search-entry callback */
static void tab_search_entry_activated_cb(GtkWidget *entry, Tab *t)
{
	tab_search_forward(t, gtk_entry_get_text(GTK_ENTRY(t->search_entry)),
		gtk_toggle_tool_button_get_active(GTK_TOGGLE_TOOL_BUTTON(t->search_case)));
}

static void tab_search_entry_text_inserted_cb(GtkEditable *editable, char *new_text, int new_length, gpointer position, Tab *t)
{
	/* update text matches */
	tab_update_search_highlight(t);
}

static void tab_search_entry_text_deleted_cb(GtkEditable *editable, int start, int end, Tab *t)
{
	/* update text matches */
	tab_update_search_highlight(t);
}

static void tab_search_previous_cb(GtkWidget *widget, Tab *t)
{
	tab_search_reverse(t, gtk_entry_get_text(GTK_ENTRY(t->search_entry)),
		gtk_toggle_tool_button_get_active(GTK_TOGGLE_TOOL_BUTTON(t->search_case)));
}

static void tab_search_next_cb(GtkWidget *widget, Tab *t)
{
	tab_search_forward(t, gtk_entry_get_text(GTK_ENTRY(t->search_entry)),
		gtk_toggle_tool_button_get_active(GTK_TOGGLE_TOOL_BUTTON(t->search_case)));
}

static void tab_search_highlight_cb(GtkWidget *widget, Tab *t)
{
	/* update text matches */
	tab_update_search_highlight(t);
	/* toggle highlighting */
	webkit_web_view_set_highlight_text_matches(t->view,
		gtk_toggle_tool_button_get_active(GTK_TOGGLE_TOOL_BUTTON(t->search_highlight)));
}

static void tab_search_case_cb(GtkWidget *widget, Tab *t)
{
	/* update text matches */
	tab_update_search_highlight(t);
}

/* create new Tab with parent Browser */
Tab *tab_new(Browser *b, char *title)
{
	Tab *t;
	GtkWidget *hbox, *close_button, *align;
	GtkToolItem *search_hide;
	GtkRcStyle *rcstyle;
	GtkToolItem *tool_item;

	t = g_new0(Tab, 1);

	t->parent = b;
	t->vbox = gtk_vbox_new(FALSE, 0);

	/* tab notebook label */
	t->ebox = gtk_event_box_new();
	gtk_widget_set_events(t->ebox, GDK_BUTTON_PRESS_MASK);
	hbox = gtk_hbox_new(FALSE, 0);
	gtk_container_add(GTK_CONTAINER(t->ebox), hbox);
	/* empty tab icon */
	t->icon = gtk_image_new();
	/* tab spinner */
	t->spinner = gtk_spinner_new();
	/* tab label */
	t->label = gtk_label_new(title);
	gtk_widget_set_size_request(t->label, TAB_LABEL_WIDTH, -1);
	gtk_label_set_ellipsize(GTK_LABEL(t->label), PANGO_ELLIPSIZE_END);
	/* align label to left and remove padding */
	gtk_misc_set_alignment(GTK_MISC(t->label), 0.0, 0.5);
	gtk_misc_set_padding(GTK_MISC(t->label), 0, 0);
	/* tab close button */
	close_button = gtk_button_new();
	gtk_button_set_relief(GTK_BUTTON(close_button), GTK_RELIEF_NONE);
	gtk_button_set_focus_on_click(GTK_BUTTON(close_button), FALSE);
	gtk_container_add(GTK_CONTAINER(close_button),
		gtk_image_new_from_stock(GTK_STOCK_CLOSE, GTK_ICON_SIZE_MENU));
	/* pack button in alignment widget - prevents button from
	   getting larger when it is on the current tab */
	align = gtk_alignment_new(0.5, 0.5, 0.0, 0.0);
	gtk_alignment_set_padding(GTK_ALIGNMENT(align), 0, 0, 0, 0);
	gtk_container_add(GTK_CONTAINER(align), close_button);
	/* make button as small as possible */
	rcstyle = gtk_rc_style_new();
	rcstyle->xthickness = rcstyle->ythickness = 0;
	gtk_widget_modify_style(close_button, rcstyle);
	/* connect to style changes to keep button **really** small */
	//g_signal_connect(G_OBJECT(close_button), "style-set", G_CALLBACK(tab_close_button_style_set_cb), NULL);
	/* pack and show all */
	gtk_box_pack_start(GTK_BOX(hbox), t->icon, FALSE, FALSE, 0);
	gtk_box_pack_start(GTK_BOX(hbox), t->spinner, FALSE, FALSE, 0);
	gtk_box_pack_start(GTK_BOX(hbox), t->label, TRUE, TRUE, 4);
	gtk_box_pack_start(GTK_BOX(hbox), align, FALSE, FALSE, 0);
	gtk_widget_show_all(t->ebox);
	/* hide icon and spinner initially */
	gtk_widget_hide(t->icon);
	gtk_widget_hide(t->spinner);

	/* scrolled webview */
	t->scroll = gtk_scrolled_window_new(NULL, NULL);
	t->view = WEBKIT_WEB_VIEW(webkit_web_view_new());
	gtk_container_add(GTK_CONTAINER(t->scroll), GTK_WIDGET(t->view));

	gtk_box_pack_start(GTK_BOX(t->vbox), t->scroll, TRUE, TRUE, 0);

	/* searchbar */
	t->searchbar = gtk_toolbar_new();
	gtk_orientable_set_orientation(GTK_ORIENTABLE(t->searchbar), GTK_ORIENTATION_HORIZONTAL);
	gtk_toolbar_set_icon_size(GTK_TOOLBAR(t->searchbar), GTK_ICON_SIZE_MENU);
	gtk_toolbar_set_show_arrow(GTK_TOOLBAR(t->searchbar), FALSE);
	/* search label */
	t->search_label = gtk_label_new("Search:");
	tool_item = gtk_tool_item_new();
	gtk_container_set_border_width(GTK_CONTAINER(tool_item), 5);
	gtk_container_add(GTK_CONTAINER(tool_item), t->search_label);
	gtk_toolbar_insert(GTK_TOOLBAR(t->searchbar), GTK_TOOL_ITEM(tool_item), -1);
	/* search entry */
	t->search_entry = gtk_entry_new();
	tool_item = gtk_tool_item_new();
	gtk_container_set_border_width(GTK_CONTAINER(tool_item), 1);
	gtk_container_add(GTK_CONTAINER(tool_item), t->search_entry);
	gtk_tool_item_set_expand(tool_item, TRUE);	// allow search_entry to expand
	gtk_toolbar_insert(GTK_TOOLBAR(t->searchbar), GTK_TOOL_ITEM(tool_item), -1);
	/* search previous button */
	t->search_previous = gtk_tool_button_new_from_stock(GTK_STOCK_GO_UP);
	gtk_toolbar_insert(GTK_TOOLBAR(t->searchbar), GTK_TOOL_ITEM(t->search_previous), -1);
	/* search next button */
	t->search_next = gtk_tool_button_new_from_stock(GTK_STOCK_GO_DOWN);
	gtk_toolbar_insert(GTK_TOOLBAR(t->searchbar), GTK_TOOL_ITEM(t->search_next), -1);
	/* toggle highlight all matches button */
	t->search_highlight = gtk_toggle_tool_button_new();
	gtk_tool_button_set_label(GTK_TOOL_BUTTON(t->search_highlight), "Highlight All");
	gtk_toolbar_insert(GTK_TOOLBAR(t->searchbar), GTK_TOOL_ITEM(t->search_highlight), -1);
	/* toggle search case sensitivity button */
	t->search_case = gtk_toggle_tool_button_new();
	gtk_tool_button_set_label(GTK_TOOL_BUTTON(t->search_case), "Match Case");
	gtk_toolbar_insert(GTK_TOOLBAR(t->searchbar), GTK_TOOL_ITEM(t->search_case), -1);
	/* separator item - separates search items from close button */
	tool_item = gtk_separator_tool_item_new();
	gtk_tool_item_set_expand(tool_item, TRUE);
	gtk_toolbar_insert(GTK_TOOLBAR(t->searchbar), GTK_TOOL_ITEM(tool_item), -1);
	/* searchbar hide button */
	search_hide = gtk_tool_button_new_from_stock(GTK_STOCK_CLOSE);
	gtk_toolbar_insert(GTK_TOOLBAR(t->searchbar), GTK_TOOL_ITEM(search_hide), -1);

	gtk_box_pack_start(GTK_BOX(t->vbox), t->searchbar, FALSE, FALSE, 0);

	/*callbacks*/
	g_signal_connect(G_OBJECT(close_button), "clicked", G_CALLBACK(tab_close_button_clicked_cb), t);
	g_signal_connect(G_OBJECT(t->view), "notify::title", G_CALLBACK(tab_title_changed), t);
	g_signal_connect(G_OBJECT(t->view), "notify::load-status", G_CALLBACK(tab_load_status_changed), t);
	g_signal_connect(G_OBJECT(t->view), "notify::progress", G_CALLBACK(tab_progress_changed_cb), t);
	g_signal_connect(G_OBJECT(t->view), "icon-loaded", G_CALLBACK(tab_icon_loaded_cb), t);
	g_signal_connect(G_OBJECT(t->view), "hovering-over-link", G_CALLBACK(browser_link_hover_cb), b);
	g_signal_connect(G_OBJECT(t->view), "create-web-view", G_CALLBACK(tab_new_requested), t);
	g_signal_connect(G_OBJECT(t->view), "download-requested", G_CALLBACK(tab_download_cb), t->view);
	g_signal_connect(G_OBJECT(t->search_entry), "activate", G_CALLBACK(tab_search_entry_activated_cb), t);
	g_signal_connect_after(G_OBJECT(t->search_entry), "insert-text", G_CALLBACK(tab_search_entry_text_inserted_cb), t);
	g_signal_connect_after(G_OBJECT(t->search_entry), "delete-text", G_CALLBACK(tab_search_entry_text_deleted_cb), t);
	g_signal_connect(G_OBJECT(t->search_previous), "clicked", G_CALLBACK(tab_search_previous_cb), t);
	g_signal_connect(G_OBJECT(t->search_next), "clicked", G_CALLBACK(tab_search_next_cb), t);
	g_signal_connect(G_OBJECT(t->search_highlight), "toggled", G_CALLBACK(tab_search_highlight_cb), t);
	g_signal_connect(G_OBJECT(t->search_case), "toggled", G_CALLBACK(tab_search_case_cb), t);
	g_signal_connect_swapped(G_OBJECT(search_hide), "clicked", G_CALLBACK(gtk_widget_hide), t->searchbar);

	/* apply webkit settings */
	//webkit_web_view_set_settings(t->view, b->webkit_settings);
	webkit_web_view_set_zoom_level(t->view, DEFAULT_ZOOM_LEVEL);

	/* scrolled window settings */
	gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(t->scroll), GTK_POLICY_NEVER, GTK_POLICY_NEVER);
	gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(t->scroll), GTK_SHADOW_NONE);

	/* add to notebook */
	gtk_notebook_append_page(GTK_NOTEBOOK(b->notebook), t->vbox, t->ebox);
	/* enable DnD */
	gtk_notebook_set_tab_reorderable(GTK_NOTEBOOK(b->notebook), t->vbox, TRUE);

	/* add to parent's tabs list */
	b->tabs = g_list_append(b->tabs, t);

	/*
	gtk_statusbar_pop(GTK_STATUSBAR(b->statusbar), b->status_context_id);
	gtk_statusbar_push(GTK_STATUSBAR(b->statusbar), b->status_context_id, "");
	*/

	/* hide searchbar initally */
	gtk_widget_show_all(t->vbox);
	gtk_widget_hide(t->searchbar);

	return t;
}

/* close tab, and quit if there are no tabs */
void tab_close(Tab *t)
{
	Browser *b = t->parent;
	/* remove from notebook and tabs list */
	gtk_notebook_remove_page(GTK_NOTEBOOK(b->notebook), browser_get_tab_num(b, t));
	b->tabs = g_list_remove(b->tabs, t);
	/* free data */
	g_free(t->title);
	g_free(t);
}

/* check for protocol and load uri */
void tab_load_uri(Tab *t, char *uri)
{
	char *uri_real;

	uri_real = g_strrstr(uri, "://") ? g_strdup(uri) : g_strdup_printf("http://%s", uri);
	webkit_web_view_load_uri(t->view, uri_real);

	g_free(uri_real);

	gtk_widget_grab_focus(GTK_WIDGET(t->view));
}

void tab_forward(Tab *t)
{
	webkit_web_view_go_forward(t->view);
}

void tab_back(Tab *t)
{
	webkit_web_view_go_back(t->view);
}

/* basic reload function */
void tab_reload(Tab *t, gboolean bypass_cache)
{
	if (!bypass_cache) {
		webkit_web_view_reload(t->view);
	} else {
		webkit_web_view_reload_bypass_cache(t->view);
	}
}

void tab_stop_loading(Tab *t)
{
	/* stop loading page */
	webkit_web_view_stop_loading(t->view);
	/* stop and hide spinner */
	gtk_spinner_stop(GTK_SPINNER(t->spinner));
	gtk_widget_hide(t->spinner);
}

void tab_home(Tab *t)
{
	tab_load_uri(t, DEFAULT_HOME);
}

/* increase or decrease the zoom of the page */
void tab_zoom(Tab *t, gboolean zoom_in)
{
	if (zoom_in) {
		webkit_web_view_zoom_in(t->view);
	} else {
		webkit_web_view_zoom_out(t->view);
	}
}

/* reset the zoom of the page */
void tab_zoom_reset(Tab *t)
{
	webkit_web_view_set_zoom_level(t->view, DEFAULT_ZOOM_LEVEL);
}

static void tab_icon_loaded_cb(WebKitWebView *view, char *icon_uri, Tab *t)
{
	GdkPixbuf *favicon;

	if ((favicon = webkit_web_view_try_get_favicon_pixbuf(t->view, 16, 16))) {
		/* set tab icon */
		gtk_image_set_from_pixbuf(GTK_IMAGE(t->icon), favicon);
		/* remove reference */
		g_object_unref(favicon);
	}
}

/* when a new tab is requested, return the t->view */
static WebKitWebView *tab_new_requested(WebKitWebView *v, WebKitWebFrame *f, Tab *t)
{
	Browser *b = t->parent;
	Tab *t_new = tab_new(b, "Loading...");
	gtk_widget_grab_focus(GTK_WIDGET(t_new->view));
	return t_new->view;
}

/* download callback */
static void tab_download_cb(WebKitWebView *web_view, GObject *d, gpointer user_data)
{
	char *command;

	const char *download_url = webkit_download_get_uri(WEBKIT_DOWNLOAD(d));
	const char *requested_name = webkit_download_get_suggested_filename(WEBKIT_DOWNLOAD(d));

	command = g_new0(char, strlen(DOWNLOAD_COMMAND) + strlen(DOWNLOAD_LOCATION) + strlen(requested_name) + strlen(download_url) + 1);
	g_sprintf(command, DOWNLOAD_COMMAND, DOWNLOAD_LOCATION, requested_name, download_url);
	g_spawn_command_line_async(command, NULL);

	g_free(command);
}

/* title change callback */
static void tab_title_changed(WebKitWebView *view, GParamSpec *pspec, Tab *t)
{
	const char *title = webkit_web_view_get_title(view);;

	if (title) {
		t->title = str_copy(&t->title, title);
		tab_update_title(t);
	}
}

void tab_update_title(Tab *t)
{
	Browser *b = t->parent;

	/* update window title if this is the current tab */
	if (browser_get_current_tab_num(b) == browser_get_tab_num(b, t)) {
		gtk_window_set_title(GTK_WINDOW(b->window), (t->title) ? t->title : "");
	}

	/* set tab label */
	gtk_label_set_text(GTK_LABEL(t->label), (t->title) ? t->title : "");
}

void tab_update_search_highlight(Tab *t)
{
	/* update highlighted matches, if button is set */
	if (gtk_toggle_tool_button_get_active(GTK_TOGGLE_TOOL_BUTTON(t->search_highlight))) {
		/* remove previous highlighting */
		webkit_web_view_unmark_text_matches(t->view);
		/* highlight new text */
		webkit_web_view_mark_text_matches(t->view, gtk_entry_get_text(GTK_ENTRY(t->search_entry)),
			gtk_toggle_tool_button_get_active(GTK_TOGGLE_TOOL_BUTTON(t->search_case)), 0);
		webkit_web_view_set_highlight_text_matches(t->view, TRUE);
	}
}

static void tab_load_status_changed(WebKitWebView *view, GParamSpec *pspec, Tab *t)
{
	Browser *b = t->parent;
	const char *uri;

	switch(webkit_web_view_get_load_status(t->view)) {
	case WEBKIT_LOAD_PROVISIONAL:
		gtk_label_set_text(GTK_LABEL(t->label), "Loading...");
		/* clear and hide icon */
		gtk_image_clear(GTK_IMAGE(t->icon));
		gtk_widget_hide(t->icon);
		/* start and show spinner */
		gtk_spinner_start(GTK_SPINNER(t->spinner));
		gtk_widget_show(t->spinner);
		break;
	case WEBKIT_LOAD_COMMITTED:
		uri = webkit_web_view_get_uri(t->view);

		/* update uri-bar if this is the current tab */
		if (browser_get_current_tab_num(b) == browser_get_tab_num(b, t)) {
			gtk_entry_set_text(GTK_ENTRY(b->uri_entry), uri);
		}

		/* FIXME: update history */
		FILE *history = fopen(g_build_filename(g_get_home_dir(), DEFAULT_HISTORY_FILE, NULL), "a+");

		if (history) {
			fprintf(history, "%s \n", uri);
			fclose(history);
		}

		break;
	case WEBKIT_LOAD_FAILED:
		gtk_label_set_text(GTK_LABEL(t->label), "Error");
	case WEBKIT_LOAD_FINISHED:
		t->progress = 1.0;
		/* hide and stop spinner */
		gtk_widget_hide(t->spinner);
		gtk_spinner_stop(GTK_SPINNER(t->spinner));
		/* show icon */
		gtk_widget_show(t->icon);
		break;
	default:
		break;
	}

	/* update toolbar buttons if current tab */
	if (browser_get_current_tab_num(b) == browser_get_tab_num(b, t)) {
		gtk_widget_set_sensitive(GTK_WIDGET(b->back_button), webkit_web_view_can_go_back(t->view));
		gtk_widget_set_sensitive(GTK_WIDGET(b->forward_button), webkit_web_view_can_go_forward(t->view));
		gtk_widget_set_visible(GTK_WIDGET(b->refresh_button), (t->progress == 1.0 || t->progress == 0.0));
		gtk_widget_set_visible(GTK_WIDGET(b->stop_button), (t->progress < 1.0 && t->progress > 0.0));
	}
}

static void tab_progress_changed_cb(WebKitWebView *view, GParamSpec *pspec, Tab *t)
{
	t->progress = webkit_web_view_get_progress(t->view);
}

/* toggle view source mode */
void tab_view_source(Tab *t)
{
	webkit_web_view_set_view_source_mode(t->view, !webkit_web_view_get_view_source_mode(t->view));
	webkit_web_view_reload(t->view);
}

/* show searchbar and give focus to entry */
void tab_show_search_entry(Tab *t)
{
	gtk_widget_show(t->searchbar);
	gtk_widget_grab_focus(t->search_entry);
}

static void tab_search(Tab *t, const char *str, gboolean forward, gboolean case_sensitive)
{
	webkit_web_view_search_text(t->view, str, case_sensitive, forward, TRUE);
}

void tab_search_forward(Tab *t, const char *str, gboolean case_sensitive)
{
	tab_search(t, str, TRUE, case_sensitive);
}

void tab_search_reverse(Tab *t, const char *str, gboolean case_sensitive)
{
	tab_search(t, str, FALSE, case_sensitive);
}


text:
/*
 * Powered By wufuwei
 */

package com.osp.biz.dao;

import java.util.*;

import javacommon.base.*;

import cn.org.rapid_framework.page.Page;
import cn.org.rapid_framework.page.PageRequest;

/**
 * @author David Wu email:oradb(a)163.com
 * @version 1.0
 * @since 1.0
 */

import com.osp.biz.model.OspContentPublish;

public interface IOspContentPublishDao extends EntityDao<OspContentPublish,java.lang.Long>{

	public Class getEntityClass();

}

redpajama_set_name: RedPajamaGithub


text:
//
// ImageDbTransform.cs
//
// Author:
//       Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2014
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Web;
using Microsoft.ApplicationBlocks.Data;

namespace R7.ImageHandler
{
	public class ImageDbTransform : ImageTransformBase
	{
		/// <summary>
		/// Sets the Connectionstring Descriptor from web.config. Defaultvalue is empty
		/// </summary>
		[DefaultValue("")]
		[Category("Behavior")]
		public string ConnectionString { get; set; }

		/// <summary>
		/// Sets the Table to select from. Defaultvalue is empty
		/// </summary>
		[DefaultValue("")]
		[Category("Behavior")]
		public string Table { get; set; }

		/// <summary>
		/// Sets the ID Field name to select from. Defaultvalue is empty
		/// </summary>
		[DefaultValue("")]
		[Category("Behavior")]
		public string IdFieldName { get; set; }

		/// <summary>
		/// Sets the ID Field value to select from. Defaultvalue is empty
		/// </summary>
		[DefaultValue("")]
		[Category("Behavior")]
		public int IdFieldValue { get; set; }

        /// <summary>
        /// Sets the ID Field value to select from. Defaultvalue is empty
        /// </summary>
        [DefaultValue("")]
        [Category("Behavior")]
        public int UserId { get; set; }

        /// <summary>
        /// Sets the ID Field value to select from. Defaultvalue is empty
        /// </summary>
        [DefaultValue("")]
        [Category("Behavior")]
        public int PortalId { get; set; }

		/// <summary>
		/// Sets the Image Field name to select from. Defaultvalue is empty
		/// </summary>
		[DefaultValue("")]
		[Category("Behavior")]
		public string ImageFieldName { get; set; }

        /// <summary>
        /// Sets the empty Image
        /// </summary>
        [DefaultValue("")]
        [Category("Behavior")]
        public Image EmptyImage { get; set; }

		public override string UniqueString
		{
			get
			{
				return base.UniqueString + "-" + this.ConnectionString + "-" + this.Table + "-" +
                       this.IdFieldName + "-" + this.IdFieldValue + "-" + this.ImageFieldName + "-" + this.UserId.ToString() + this.PortalId.ToString();
			}
		}

		public ImageDbTransform()
		{
			InterpolationMode = InterpolationMode.HighQualityBicubic;
			SmoothingMode = SmoothingMode.Default;
			PixelOffsetMode = PixelOffsetMode.Default;
			CompositingQuality = CompositingQuality.HighSpeed;
		}

		public override Image ProcessImage(Image image)
		{
		    string sqlCmd;

			if (UserId > 0)
            {
                sqlCmd = "SELECT RTRIM(Files.Folder) + RTRIM(LTRIM(Files.FileName)) AS profilepic"+
                         " FROM UserProfile " +
                         " INNER JOIN ProfilePropertydefinition on ProfilePropertydefinition.PropertyDefinitionID = UserProfile.PropertyDefinitionID" +
                         " INNER JOIN Files on UserProfile.PropertyValue = Files.FileId" +
                         " WHERE ProfilePropertydefinition.Propertyname = 'Photo'" +
                         " AND ProfilePropertydefinition.PortalId = " + this.PortalId.ToString() +
                         " AND Userprofile.UserId = " + this.UserId.ToString();

                object result = SqlHelper.ExecuteScalar(this.ConnectionString, CommandType.Text, sqlCmd);
                if (result != null)
                {
                    string imgFile = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, "Portals\\" + this.PortalId.ToString());
                    imgFile = Path.Combine(imgFile, ((string) result).Replace('/', '\\'));
                    if (File.Exists(imgFile) == true)
                    {
                        return new Bitmap(imgFile);
                    }
                 }
            }
            else
            {
                sqlCmd = "SELECT " + this.ImageFieldName + " FROM " +
                         this.Table + " WHERE " + this.IdFieldName + " = @Value";

		        object result = SqlHelper.ExecuteScalar(this.ConnectionString, CommandType.Text, sqlCmd, new SqlParameter("Value", this.IdFieldValue));
		        if (result != null)
		        {
		            MemoryStream ms = new MemoryStream((byte[]) result);
		            return Image.FromStream(ms);
		        }

		    }
            return EmptyImage;
		}
	}
}


text:
package classpackage;

import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

import java.util.ArrayList;

/**
 * Created by paul thomas on 16.03.2016.
 */

public class Dish {
    private IntegerProperty dishId = new SimpleIntegerProperty();
    private DoubleProperty price = new SimpleDoubleProperty();
    private StringProperty dishName = new SimpleStringProperty();
    private ObservableList<DishLine> dishLines = FXCollections.observableArrayList();

    /**
     * Creates the Dish object from the database
     *
     * @param dishId the unique identifier for the dish object
     * @param price the price for the dish
     * @param dishName the name of the dish
     * @param dishLines
     */
    public Dish(int dishId, double price, String dishName, ObservableList dishLines) {
        this.dishId.set(dishId);
        this.price.set(price);
        this.dishName.set(dishName);
        this.dishLines = dishLines;
    }

    /**
     * Creates the Dish object to the database
     *
     * @param price the price for the dish
     * @param dishName the name of the dish
     * @param dishLines
     */
    public Dish(double price, String dishName, ObservableList dishLines) {
        this.price.set(price);
        this.dishName.set(dishName);
        this.dishLines = dishLines;
    }

    /**
     * Returns the unique dish identifier
     *
     * @return int ID of the dish
     */
    public int getDishId() {
        return dishId.get();
    }

    /**
     * Returns the unique dish identifier in style for JavaFX (IntegerProperty)
     *
     * @return IntegerProperty ID of the dish
     */
    public IntegerProperty dishIdProperty() {
        return dishId;
    }

    /**
     * Sets the unique dish identifier
     *
     * @param dishId the Id to be set
     */
    public void setDishId(int dishId) {
        this.dishId.set(dishId);
    }

    /**
     * Returns the price of the dish
     *
     * @return double price of the dish
     */
    public double getPrice() {
        return price.get();
    }

    /**
     * Returns the price of the dish in style for JavaFX (DoubleProperty)
     *
     * @return double price of the dish
     */
    public DoubleProperty priceProperty() {
        return price;
    }

    /**
     * Sets the price of the dish
     *
     * @param price the price to be set
     */
    public void setPrice(double price) {
        this.price.set(price);
    }

    /**
     * Returns the dish name
     *
     * @return string the dish name
     */
    public String getDishName() {
        return dishName.get();
    }

    /**
     * Returns the dish name in style for JavaFX (StringProperty)
     *
     * @return string the dish name
     */
    public StringProperty dishNameProperty() {
        return dishName;
    }

    /**
     * Sets the name of the dish
     *
     * @param dishName the name to be set
     */
    public void setDishName(String dishName) {
        this.dishName.set(dishName);
    }

    /**
     * Gets the dish line of the object
     *
     * @return the ObservableList DishLine of the object
     */
    public ObservableList<DishLine> getAllDishLinesForThisDish() {
        return dishLines;
    }

    /**
     * Set all dish lines for the current object
     *
     * @param dishLines dish line to be set
     */
    public void setAllDishLinesForThisDish(ObservableList<DishLine> dishLines) {
        this.dishLines = dishLines;
    }

    /**
     * String representation of the object (returns the name of the dish)
     */
    @Override
    public String toString() {
        return dishName.get();
    }

}


text:
package com.diffplug.common.rx;

import kotlinx.coroutines.flow.Flow;

/**
 * An object which can be supplied in an {@link io.reactivex.Observable} form.
 *
 * Ideally, `io.reactivex.Observable` would be an interface, which would make this interface unnecessary.  But
 * so long as it isn't, this (combined with {@link Rx}) makes it fairly seamless to fix this.
 */
public interface IObservable<T> {
	Flow<T> asObservable();

	/** Wraps an actual observable as an IObservable. */
	public static <T> IObservable<T> wrap(Flow<T> observable) {
		return () -> observable;
	}
}


text:
<?php

namespace Graze\TelnetClient;

use Socket\Raw\Socket;

interface TelnetClientInterface
{
    /**
     * @param string $dsn
     * @param string $prompt
     * @param string $promptError
     * @param string $lineEnding
     */
    public function connect($dsn, $prompt = null, $promptError = null, $lineEnding = null);

    /**
     * @param string $command
     * @param string $prompt
     *
     * @return TelnetResponseInterface
     */
    public function execute($command, $prompt = null);

    /**
     * @return Socket
     */
    public function getSocket();
}


text:
"""Imports for Python API.

This file is MACHINE GENERATED! Do not edit.
Generated by: tensorflow/tools/api/generator/create_python_api.py script.
"""
from tensorflow.python.keras._impl.keras.applications import VGG16
from tensorflow.python.keras._impl.keras.applications.densenet import decode_predictions
from tensorflow.python.keras._impl.keras.applications.imagenet_utils import preprocess_input


text:
ByteMail TODO List
====

Short Term
----------

* GUI

Long Term
---------

* Going Mobile
* Create a Wiki

If you have any suggestions as to how we can make ByteMail great send me a message, my address is: a01ab3df05f64bf4ba0b18044162d7f0


text:
<?php

namespace Rhubarb\Leaf\Tabs\Examples\SearchPanelTabsExample;

use Rhubarb\Leaf\Controls\Common\Checkbox\Checkbox;
use Rhubarb\Leaf\Controls\Common\SelectionControls\DropDown\DropDown;
use Rhubarb\Leaf\SearchPanel\Leaves\SearchPanel;
use Rhubarb\Stem\Filters\Equals;
use Rhubarb\Stem\Filters\Group;

class JobSearchPanel extends SearchPanel
{
    protected function createSearchControls()
    {
        $status = new DropDown("Status");
        $status->setSelectionItems([
            ["", "Any Status"],
            ["Incoming"],
            ["Outgoing"],
            ["Stale"]
        ]);

        return [
            $status,
            new Checkbox("Sent")
        ];
    }

    public function populateFilterGroup(Group $filterGroup)
    {
        $searchValues = $this->getSearchControlValues();

        if ($searchValues["Status"]) {
            $filterGroup->addFilters(new Equals("Status", $searchValues["Status"]));
        }

        $filterGroup->addFilters(new Equals("Sent", (bool)$searchValues["Sent"]));
    }
}


text:
Big Data System

## Yarn
1. environments
    * setup ssh ForwardAgent to access master and slaves
    * config `/etc/hosts`
    * config `/home/ubuntu/*`, replace the MASTER_IP with `group-2-vm1`
- `sudo apt-get update --fix-missing`
- `sudo apt-get install openjdk-7-jdk pdsh`
- `sudo apt-get install git`
    * `git clone https://github.com/luozhaoyu/big-data-system.git`
- `./mkdirs_configs.sh`
    * it would download hadoop
- untar hadoop
- `source run.sh`
- `hadoop namenode -format`
- `start_all`
- debug
    * `hadoop jar ~/software/hadoop-2.6.0/share/hadoop/mapreduce/hadoop-mapreduce-examples-2.6.0.jar pi 1 2`

## Tez
1. `./tez.sh`
- test
    1. `hadoop dfs -copyFromLocal ~/wcount_input.txt /`
    - `hadoop jar /home/ubuntu/software/tez-0.7.1-SNAPSHOT-minimal/tez-examples-0.7.1-SNAPSHOT.jar orderedwordcount -Dtez.runtime.io.sort.mb=220 /wcount_input.txt /wcount_output.txt`

### Attention
There maybe collection4 class not found error, please do

1. `sudo apt-get install libcommons-collections4-java`
- add hadoop class path `/usr/share/java/commons-collections4.jar` into `run.sh`
- `source ./run.sh`
- run again

## Hive
1. Start hive console
    - Because run.sh already sets $HIVE_HOME=/home/ubuntu/software/hive-1.2.1 and
    exports $HIVE_HOME/bin to $PATH, directly start hive console by typing
    `hive`
2. Here we set a mysql-user 'hive' and bind it to the master-ip 10.0.1.27 (group-2-vm1)

3. `./hive_workload.sh`
    - The script is placed under the repository (/home/ubuntu/big-data-system)
    - The script will run all the workload (creating a 10Gb database; running a MapReduce job on Hive for the database; and then running a Tez job on Hive for the database). It shows the elasped-time of the MR job and the Tez job.

## Experiment
* `./run_all.sh`
* collect all dstat.csv and outputs from run_all `./collect.sh`

## Monitor
* `jps`
* HDFS <http://130.127.132.234:50070>
* YARN <http://130.127.132.234:8088>
* MapReduce job history <http://130.127.132.234:19888>
* application history <http://130.127.132.234:8188>
* Spark Master <http://130.127.132.234:8080/>
* Spark Worker <http://130.127.132.234:8081/>
* Storm UI <http://130.127.132.234:8085/>


text:
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef EIGEN_TRANSLATION_H
#define EIGEN_TRANSLATION_H

namespace Eigen {

/** \geometry_module \ingroup Geometry_Module
  *
  * \class Translation
  *
  * \brief Represents a translation transformation
  *
  * \param _Scalar the scalar type, i.e., the type of the coefficients.
  * \param _Dim the  dimension of the space, can be a compile time value or Dynamic
  *
  * \note This class is not aimed to be used to store a translation transformation,
  * but rather to make easier the constructions and updates of Transform objects.
  *
  * \sa class Scaling, class Transform
  */
template<typename _Scalar, int _Dim>
class Translation
{
public:
  EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF_VECTORIZABLE_FIXED_SIZE(_Scalar,_Dim)
  /** dimension of the space */
  enum { Dim = _Dim };
  /** the scalar type of the coefficients */
  typedef _Scalar Scalar;
  /** corresponding vector type */
  typedef Matrix<Scalar,Dim,1> VectorType;
  /** corresponding linear transformation matrix type */
  typedef Matrix<Scalar,Dim,Dim> LinearMatrixType;
  /** corresponding affine transformation type */
  typedef Transform<Scalar,Dim,Affine> AffineTransformType;
  /** corresponding isometric transformation type */
  typedef Transform<Scalar,Dim,Isometry> IsometryTransformType;

protected:

  VectorType m_coeffs;

public:

  /** Default constructor without initialization. */
  Translation() {}
  /**  */
  inline Translation(const Scalar& sx, const Scalar& sy)
  {
    eigen_assert(Dim==2);
    m_coeffs.x() = sx;
    m_coeffs.y() = sy;
  }
  /**  */
  inline Translation(const Scalar& sx, const Scalar& sy, const Scalar& sz)
  {
    eigen_assert(Dim==3);
    m_coeffs.x() = sx;
    m_coeffs.y() = sy;
    m_coeffs.z() = sz;
  }
  /** Constructs and initialize the translation transformation from a vector of translation coefficients */
  explicit inline Translation(const VectorType& vector) : m_coeffs(vector) {}

  /** \brief Retruns the x-translation by value. **/
  inline Scalar x() const { return m_coeffs.x(); }
  /** \brief Retruns the y-translation by value. **/
  inline Scalar y() const { return m_coeffs.y(); }
  /** \brief Retruns the z-translation by value. **/
  inline Scalar z() const { return m_coeffs.z(); }

  /** \brief Retruns the x-translation as a reference. **/
  inline Scalar& x() { return m_coeffs.x(); }
  /** \brief Retruns the y-translation as a reference. **/
  inline Scalar& y() { return m_coeffs.y(); }
  /** \brief Retruns the z-translation as a reference. **/
  inline Scalar& z() { return m_coeffs.z(); }

  const VectorType& vector() const { return m_coeffs; }
  VectorType& vector() { return m_coeffs; }

  const VectorType& translation() const { return m_coeffs; }
  VectorType& translation() { return m_coeffs; }

  /** Concatenates two translation */
  inline Translation operator* (const Translation& other) const
  { return Translation(m_coeffs + other.m_coeffs); }

  /** Concatenates a translation and a uniform scaling */
  inline AffineTransformType operator* (const UniformScaling<Scalar>& other) const;

  /** Concatenates a translation and a linear transformation */
  template<typename OtherDerived>
  inline AffineTransformType operator* (const EigenBase<OtherDerived>& linear) const;

  /** Concatenates a translation and a rotation */
  template<typename Derived>
  inline IsometryTransformType operator*(const RotationBase<Derived,Dim>& r) const
  { return *this * IsometryTransformType(r); }

  /** \returns the concatenation of a linear transformation \a l with the translation \a t */
  // its a nightmare to define a templated friend function outside its declaration
  template<typename OtherDerived> friend
  inline AffineTransformType operator*(const EigenBase<OtherDerived>& linear, const Translation& t)
  {
    AffineTransformType res;
    res.matrix().setZero();
    res.linear() = linear.derived();
    res.translation() = linear.derived() * t.m_coeffs;
    res.matrix().row(Dim).setZero();
    res(Dim,Dim) = Scalar(1);
    return res;
  }

  /** Concatenates a translation and a transformation */
  template<int Mode, int Options>
  inline Transform<Scalar,Dim,Mode> operator* (const Transform<Scalar,Dim,Mode,Options>& t) const
  {
    Transform<Scalar,Dim,Mode> res = t;
    res.pretranslate(m_coeffs);
    return res;
  }

  /** Applies translation to vector */
  template<typename Derived>
  inline typename internal::enable_if<Derived::IsVectorAtCompileTime,VectorType>::type
  operator* (const MatrixBase<Derived>& vec) const
  { return m_coeffs + vec.derived(); }

  /** \returns the inverse translation (opposite) */
  Translation inverse() const { return Translation(-m_coeffs); }

  Translation& operator=(const Translation& other)
  {
    m_coeffs = other.m_coeffs;
    return *this;
  }

  static const Translation Identity() { return Translation(VectorType::Zero()); }

  /** \returns \c *this with scalar type casted to \a NewScalarType
    *
    * Note that if \a NewScalarType is equal to the current scalar type of \c *this
    * then this function smartly returns a const reference to \c *this.
    */
  template<typename NewScalarType>
  inline typename internal::cast_return_type<Translation,Translation<NewScalarType,Dim> >::type cast() const
  { return typename internal::cast_return_type<Translation,Translation<NewScalarType,Dim> >::type(*this); }

  /** Copy constructor with scalar type conversion */
  template<typename OtherScalarType>
  inline explicit Translation(const Translation<OtherScalarType,Dim>& other)
  { m_coeffs = other.vector().template cast<Scalar>(); }

  /** \returns \c true if \c *this is approximately equal to \a other, within the precision
    * determined by \a prec.
    *
    * \sa MatrixBase::isApprox() */
  bool isApprox(const Translation& other, const typename NumTraits<Scalar>::Real& prec = NumTraits<Scalar>::dummy_precision()) const
  { return m_coeffs.isApprox(other.m_coeffs, prec); }

};

/** \addtogroup Geometry_Module */
//@{
typedef Translation<float, 2> Translation2f;
typedef Translation<double,2> Translation2d;
typedef Translation<float, 3> Translation3f;
typedef Translation<double,3> Translation3d;
//@}

template<typename Scalar, int Dim>
inline typename Translation<Scalar,Dim>::AffineTransformType
Translation<Scalar,Dim>::operator* (const UniformScaling<Scalar>& other) const
{
  AffineTransformType res;
  res.matrix().setZero();
  res.linear().diagonal().fill(other.factor());
  res.translation() = m_coeffs;
  res(Dim,Dim) = Scalar(1);
  return res;
}

template<typename Scalar, int Dim>
template<typename OtherDerived>
inline typename Translation<Scalar,Dim>::AffineTransformType
Translation<Scalar,Dim>::operator* (const EigenBase<OtherDerived>& linear) const
{
  AffineTransformType res;
  res.matrix().setZero();
  res.linear() = linear.derived();
  res.translation() = m_coeffs;
  res.matrix().row(Dim).setZero();
  res(Dim,Dim) = Scalar(1);
  return res;
}

} // end namespace Eigen

#endif // EIGEN_TRANSLATION_H


text:
@implementation ICVehicleSelectionSliderView {
    NSArray *_vehicleViews;
    ICVehicleSelectionSliderButton *_button;
    UIImageView *_sliderBackgroundView;
    int _segmentWidth;
    int _selectedIndex;
    int _buttonLeftCenterBound;
    int _buttonRightCenterBound;
    CGPoint _buttonOffsetPoint;
    NSMutableArray *_labelViews;
    NSDictionary *_availableVehicleViewIdMap;
}

NSInteger const kWidthPx = 320;
NSInteger const kTopMargin = 40;
NSInteger const kButtonSize = 48;
NSInteger const kNodeSize = 16;
NSInteger const kVehicleLabelSelectedY = 10;
NSInteger const kVehicleLabelUnselectedY = 18;
NSInteger const kNodeTapTag = 2;

- (id)init
{
    self = [super initWithFrame:CGRectMake(0, 0, 320, 80)];
    if (self) {
        // Initialization code
        _labelViews = [[NSMutableArray alloc] init];
        _selectedIndex = -1;

        // Add background with two nodes
        UIImage *image = [[UIImage imageNamed:@"vehicle_picker_slider_background"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 16, 0, 16) resizingMode:UIImageResizingModeStretch];
        _sliderBackgroundView = [[UIImageView alloc] initWithImage:image];
        [self addSubview:_sliderBackgroundView];

        _button = [[ICVehicleSelectionSliderButton alloc] initWithFrame:CGRectMake(0, kTopMargin - (kButtonSize / 2) + kNodeSize / 2, kButtonSize, kButtonSize)];

        [_button addTarget:self action:@selector(touchDown:withEvent:) forControlEvents:UIControlEventTouchDown];
        [_button addTarget:self action:@selector(touchUp:) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside];
        [_button addTarget:self action:@selector(touchMove:withEvent:) forControlEvents: UIControlEventTouchDragOutside | UIControlEventTouchDragInside];

        [self addSubview:_button];

        // Listen for node taps
        UITapGestureRecognizer *gest = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(nodeTapped:)];
        [self addGestureRecognizer:gest];
    }
    return self;
}

//- (void)layoutSubviews {
//    if (_shouldFixPositions)
//    {
//        _shouldFixPositions = NO;
//        [self fixPositions];
//    }
//}

- (void)fixPositions:(NSArray *)vehicleViews {
    _segmentWidth = (kWidthPx / vehicleViews.count);
    int leftMargin = _segmentWidth / 2 - 8;
    _buttonLeftCenterBound = (_segmentWidth / 2);
    _buttonRightCenterBound = (kWidthPx - _segmentWidth / 2);

    _sliderBackgroundView.frame = CGRectMake(leftMargin, kTopMargin, kWidthPx - 2 * leftMargin, 16.0f);

    if (_selectedIndex >= 0) {
        [self moveButtonToIndex:_selectedIndex slowAnimation:NO];
        [self moveLabel:_selectedIndex y:kVehicleLabelSelectedY];
    }
}

- (void)moveButtonToIndex:(int)index slowAnimation:(BOOL)slowAnimate {
    if (index < 0) return;

    float x = index * _segmentWidth + _segmentWidth / 2 - kButtonSize / 2;
    NSTimeInterval duration = slowAnimate ? 0.2 : 0.01;

    [UIView animateWithDuration:duration animations:^{
        _button.x = x;
    }];
}

#pragma mark - Gestures

-(void)nodeTapped: (UITapGestureRecognizer *)tap {
    CGPoint point = [tap locationInView:self];
    int vehicleViewIndex = (int)(point.x / _segmentWidth);

    [self selectVehicleView:vehicleViewIndex slowAnimation:YES];
}

- (void)touchDown:(UIButton *)button withEvent:(UIEvent *)event {

}

-(void)touchUp:(UIButton *) button{
    [self moveButtonToIndex:button.centerX / _segmentWidth slowAnimation:YES];
}

// Button being dragged to the side
- (void)touchMove:(UIButton *)button withEvent:(UIEvent *)event {
    int newCenterX = [[[event allTouches] anyObject] locationInView:self].x;

    [self selectVehicleView:newCenterX / _segmentWidth slowAnimation:NO];

    if (newCenterX < _buttonLeftCenterBound) {
        newCenterX = _buttonLeftCenterBound;
    }
    else if (newCenterX > _buttonRightCenterBound) {
        newCenterX = _buttonRightCenterBound;
    }

    button.centerX = newCenterX;
}

#pragma mark - Properties

- (ICVehicleView *)selectedVehicleView {
    if (_selectedIndex < 0 || _selectedIndex >= _vehicleViews.count) return nil;

    return _vehicleViews[_selectedIndex];
}

-(CGPoint)getCenterPointForIndex:(int)index {
    float x = index * _segmentWidth + _segmentWidth / 2;
    return CGPointMake(x, kTopMargin + kNodeSize / 2);
}

-(void)clearLabelViews {
    for (ICVehicleSelectionSliderLabel *label in _labelViews) {
        [label removeFromSuperview];
    }
    [_labelViews removeAllObjects];
}

-(void)clearNodeTapViews {
    for (UIView *view in self.subviews) {
        if (view.tag == kNodeTapTag)
            [view removeFromSuperview];
    }
}

-(BOOL)isVehicleViewAvailable:(NSInteger)index {
    if (!_availableVehicleViewIdMap) return NO;

    ICVehicleView *view = _vehicleViews[index];
    return [_availableVehicleViewIdMap objectForKey:view.uniqueId] != nil;
}

-(void)setAvailableVehicleViewIdMap:(NSDictionary *)map {
    _availableVehicleViewIdMap = map;
    [_labelViews enumerateObjectsUsingBlock:^(ICVehicleSelectionSliderLabel *label, NSUInteger idx, BOOL *stop) {
        label.available = [self isVehicleViewAvailable:idx];
    }];
    [self updateVehicleSliderIcon];
}

- (void)updateOrderedVehicleViews:(NSArray *)vehicleViews selectedIndex:(int)selectedIndex {
    if (_vehicleViews.count != vehicleViews.count) {
        _selectedIndex = -1;
        [self fixPositions:vehicleViews];
    }

    [self clearLabelViews];
    [self clearNodeTapViews];

    _vehicleViews = [vehicleViews copy];

    UIImage *sliderPointImage = [UIImage imageNamed:@"vehicle_picker_slider_point.png"];

    long vehicleViewsCount = _vehicleViews.count;
    for (int vehicleViewIndex = 0; vehicleViewIndex < vehicleViewsCount; vehicleViewIndex++)
    {
        CGPoint centerPoint = [self getCenterPointForIndex:vehicleViewIndex];

        // Add middle nodes if > 2
        if ((vehicleViewIndex > 0) && (vehicleViewIndex < vehicleViewsCount - 1))
        {
            UIImageView *nodeView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 16, 16)];
            nodeView.image = sliderPointImage;
            nodeView.center = centerPoint;
            nodeView.tag = kNodeTapTag;
            [self insertSubview:nodeView belowSubview:_button];
        }

        ICVehicleView *vehicleView = (ICVehicleView *)_vehicleViews[vehicleViewIndex];
        ICVehicleSelectionSliderLabel *label = [[ICVehicleSelectionSliderLabel alloc] init];
        label.text = vehicleView.name;
        label.centerX = centerPoint.x;
        label.y = selectedIndex == vehicleViewIndex ? kVehicleLabelSelectedY : kVehicleLabelUnselectedY;

        [_labelViews addObject:label];
        [self addSubview:label];
    }

    [self selectVehicleView:selectedIndex slowAnimation:NO];
}

-(void)selectVehicleView:(int)index slowAnimation:(BOOL)slowAnimate {
    if (index == _selectedIndex) return;

    [self moveLabel:_selectedIndex y:kVehicleLabelUnselectedY];
    [self moveLabel:index y:kVehicleLabelSelectedY];
    [self moveButtonToIndex:index slowAnimation:slowAnimate];
    _selectedIndex = index;
    [self updateVehicleSliderIcon];

    [ICSession sharedInstance].currentVehicleViewId = [self.selectedVehicleView.uniqueId intValue];

    // TODO: При первой установке VehicleViews не нужно сообщать delegate что Vehicle View изменился!
    if ([self.delegate respondsToSelector:@selector(vehicleViewChanged)]) {
        [self.delegate vehicleViewChanged];
    }
}

-(void)moveLabel:(int)index y:(int)y {
    if (index < 0 || index >= _labelViews.count) return;

    ICVehicleSelectionSliderLabel *label = _labelViews[index];
    [UIView animateWithDuration:0.2 animations:^{
        label.y = y;
    }];
}

-(void)updateVehicleSliderIcon {
    if (_selectedIndex < 0 || _selectedIndex >= _vehicleViews.count) return;

    ICVehicleView *vehicleView = _vehicleViews[_selectedIndex];
    [vehicleView loadMonoImage:^(UIImage *image) {
        [_button updateIcon:image available:[self isVehicleViewAvailable:_selectedIndex]];
    }];
}

-(void)dealloc{
    [_button removeTarget:self action:@selector(touchDown:withEvent:) forControlEvents:UIControlEventTouchDown];
    [_button removeTarget:self action:@selector(touchUp:) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside];
    [_button removeTarget:self action:@selector(touchMove:withEvent:) forControlEvents: UIControlEventTouchDragOutside | UIControlEventTouchDragInside];
}

@end


text:
@interface MILMineController : UITableViewController

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <dimen name="widget_padding">8dp</dimen>
    <dimen name="calender_padding">8dp</dimen>
    <dimen name="day_header_title">14dp</dimen>
    <dimen name="event_entry_title">18dp</dimen>
    <dimen name="event_entry_details">14dp</dimen>
    <dimen name="entry_bottom_padding">2dp</dimen>
    <dimen name="day_header_padding_bottom">2dp</dimen>
    <dimen name="day_header_padding_right">10dp</dimen>
    <dimen name="day_header_padding_top">12dp</dimen>

</resources>


text:
package com.github.kaiwinter.exifrename.ui;

import java.io.File;
import java.util.Set;

import com.github.kaiwinter.exifrename.type.RenameOperation;
import com.github.kaiwinter.exifrename.uc.RenameUc;

import de.saxsys.mvvmfx.ViewModel;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;

/**
 * The view model with the logic of the main view.
 */
public final class MainViewModel implements ViewModel {

    private RenameUc renameUc = new RenameUc();
    private final ListProperty<TableModel> files = new SimpleListProperty<>();
    private Set<RenameOperation> renameOperations;

    public ListProperty<TableModel> filesProperty() {
        return this.files;
    }

    public void pathChoosen(File selectedDirectory) {
        renameOperations = renameUc.createRenameOperationsForDirectory(selectedDirectory.toPath());

        for (RenameOperation renameOperation : renameOperations) {
            TableModel tm = new TableModel();
            tm.setOriginalName(renameOperation.getOldFilename().getFileName().toString());
            tm.setExifOriginalDate(renameOperation.getExifOriginalDate());
            tm.setNewName(renameOperation.getNewFilenamePath().getFileName().toString());

            files.add(tm);
        }
    }

    public void rename() {
        renameUc.executeRenameOperations(renameOperations);
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('sites', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='CustomArticle',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('title', models.CharField(max_length=50)),
                ('places_this_article_should_appear', models.ForeignKey('sites.Site', models.CASCADE)),
            ],
            options={
                'abstract': False,
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='ExclusiveArticle',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('title', models.CharField(max_length=50)),
                ('site', models.ForeignKey('sites.Site', models.CASCADE)),
            ],
            options={
                'abstract': False,
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='SyndicatedArticle',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('title', models.CharField(max_length=50)),
                ('sites', models.ManyToManyField('sites.Site')),
            ],
            options={
                'abstract': False,
            },
            bases=(models.Model,),
        ),
    ]


text:
function imagePlate(ipdiv){
	var currentpic;
	var picbefore;
	var imageplate;
	var mousetracker;
	var imagecount;
	var loadedimages = 0;
	var imagescheme;
	var images = new Array();
	var mousedown = false;
	var prevmouseposx;
	var stack = 0;
	var stacksize = 4;

	/* Display nice log messages */
	function log(message){
		console.log("Instance "+ipdiv+" says: "+message);
	}

	function removeLoadingScreen(){
		log("Removing loading screen ...");
		loadingscreen = imageplate.getElementsByClassName('ip-loading')[0];
	    imageplate.removeChild(loadingscreen);
	}

	/* Loads the images into browser cache and removes the loading screen when finished. */
	function preloadImages(imgarr) {
	    if (!preloadImages.list) {
	        preloadImages.list = [];
	    }
	    for (var i = 0; i < imgarr.length; i++) {
	        var img = new Image();
	        img.onload = function() {
	            var index = preloadImages.list.indexOf(this);
	            loadedimages++;
	            loadingscreen = imageplate.getElementsByClassName('ip-loading')[0];
	            loadingscreen_html = "
ImagePlate is loading images ("+loadedimages+" of "+imagecount+")
";
	            loadingscreen.innerHTML = loadingscreen_html;
	            if(loadedimages == imagecount){
	            	// Remove the loading screen
	            	log("All images loaded and ready.");
	            	removeLoadingScreen();
	            }
	        };
	        preloadImages.list.push(img);
	        img.src = imgarr[i];
	    }
	}

	this.setupImageplate = function(){
		log("Setting up imageplate with DIV ID "+ipdiv);
		imageplate = document.getElementById(ipdiv);
		imagescheme = imageplate.getElementsByClassName('imagescheme')[0].innerHTML;
		imagecount = imageplate.getElementsByClassName('imagecount')[0].innerHTML.valueOf();
		imagecount = parseInt(imagecount);

		// Remove Spaces in front of the HTML
		imagescheme = imagescheme.replace(/\s+/g, '');

		log("Image scheme: "+imagescheme);
		log("ImagePlate div ID: "+ipdiv);
		log("Number of images: "+imagecount);

		// Fill up the array
		log("Filling up the images array.");
		for(i=0; i<imagecount; i++){
			images[i] = imagescheme.replace("{num}", i+1);
		}

		/* Pre-load images into browser cache */
		preloadImages(images);
	};

	function changePicTo(num){
		//log("Changing Pic.");

		if(num >= imagecount || num < 0){
			alert("Impossible to change picture to number "+num+"!");
		}

		// give current picture "show" CSS class
		currentpic_element = document.getElementById(ipdiv+"-img-"+num);
		currentpic_element.className = "show";

		// remove "show" CSS class from picture before
		picbefore_element = document.getElementById(ipdiv+"-img-"+picbefore);
		if(!!picbefore_element){picbefore_element.className = "";}
	}

	function forwards(){
		//log("moving forwards");
		picbefore = currentpic;
		currentpic++;
		if(currentpic > imagecount-1){
			currentpic = 0;
		}
		changePicTo(currentpic);
	}

	function backwards(){
		//log("moving backwards");
		picbefore = currentpic;
		currentpic--;
		if(currentpic < 0){
			currentpic = imagecount-1;
		}
		changePicTo(currentpic);
	}

	// How many pixels of movement are needed to perform a "forward/Backward step?"
	function addToMovementStack(direction){
		if(direction == "forwards"){
			stack++;
		}

		else{
			stack--;
		}

		if(stack == stacksize){
			forwards();
			stack = 0;
		}
		else if(stack == -stacksize){
			backwards();
			stack = 0;
		}
	}

	/* Compute mouse direction */
	function processMouseActions(currentClientX){
		// current Client X contains the X-Coord of the present mouse position
		if(prevmouseposx > currentClientX){
			//console.log("Forward");
			addToMovementStack("forwards");
		}

		else if(prevmouseposx < currentClientX){
			//console.log("Backwards");
			addToMovementStack("backwards");
		}
	}

	/* Load more HTML into DOM */
	function loadDOM(){
		var html = "";

		for(i=0; i < images.length; i++){
			html = html+" ";
		}

		html = html+"

ImagePlate is loading images (0 of "+imagecount+")

";
		html = html+"

";

		imageplate.innerHTML = html;
	}

	this.initialize = function(){
		log("Initializing imageplate with DIV ID "+ipdiv);
		log("Loading images into DOM");
		loadDOM();

		log("Showing first pic");
		changePicTo(0);
		currentpic = 0;
		picbefore = imagecount-1;

		mousetracker = imageplate.getElementsByClassName('mouse-tracker')[0];

		mousetracker.onmousedown = function(event){
			event.preventDefault();
			//log("mousedown");
			mousedown = true;
		};

		mousetracker.onmouseup = function(event){
			event.preventDefault();
			//log("mouseup");
			mousedown = false;
			stack = 0; // Make stack neutral
		};

		mousetracker.onmousemove = function(event){
				//log("Mouse move event");
				if(mousedown){
					//log("Mouse drag");
					processMouseActions(event.clientX);
					prevmouseposx = event.clientX;
				}
		};

		mousetracker.onmouseleave = function(event){
			log("mouseout, disabling movement");
			mousedown = false;
			stack = 0; // Make stack neutral
		};
	};

	this.setupImageplate();
	this.initialize();
};

/* Detect ImagePlate HTML and make new instances */
function detect_imageplates(){
	imageplates = document.getElementsByClassName("imageplate");
	instances = new Array();

	for(ic=0; ic<imageplates.length;ic++){
		imageplateid = "imageplate-"+ic;
		console.log("Detected new instance nr. "+ic+" ... giving DIV ID "+imageplateid);
		imageplates[ic].id = imageplateid;
		instances[ic] = new imagePlate(imageplateid);
	}
}

/* Show loading screen for every ImagePlate */
loadingscreens = document.getElementsByClassName("ip-loading");
for(i=0; i<loadingscreens.length; i++){
	loadingscreens[i].style.display = "block";
}

window.onload=detect_imageplates;


text:
<?php

/**
 * Page Select Service
 *
 * Wrapper service for \TYPO3\CMS\Frontend\Page\PageRepository including static caches for
 * menus, rootlines, pages and page overlays to be implemented in
 * viewhelpers by replacing calls to \TYPO3\CMS\Frontend\Page\PageRepository::getMenu()
 * and the like.
 *
 * @author Björn Fromme <fromme@dreipunktnull.com>, dreipunktnull
 * @package Vhs
 * @subpackage Service
 */
class Tx_Vhs_Service_PageSelectService implements \TYPO3\CMS\Core\SingletonInterface {

	/**
	 * @var \TYPO3\CMS\Frontend\Page\PageRepository
	 */
	protected static $pageSelect;

	/**
	 * @var \TYPO3\CMS\Frontend\Page\PageRepository
	 */
	protected static $pageSelectHidden;

	/**
	 * @var array
	 */
	protected static $cachedPages = array();

	/**
	 * @var array
	 */
	protected static $cachedOverlays = array();

	/**
	 * @var array
	 */
	protected static $cachedMenus = array();

	/**
	 * @var array
	 */
	protected static $cachedRootLines = array();

	/**
	 * Initialize \TYPO3\CMS\Frontend\Page\PageRepository objects
	 */
	public function initializeObject() {
		self::$pageSelect = $this->createPageSelectInstance(FALSE);
		self::$pageSelectHidden = $this->createPageSelectInstance(TRUE);
	}

	/**
	 * @param boolean $showHidden
	 * @return \TYPO3\CMS\Frontend\Page\PageRepository
	 */
	private function createPageSelectInstance($showHidden = FALSE) {
		if (TRUE === is_array($GLOBALS['TSFE']->fe_user->user)) {
			$groups = array(-2, 0);
			$groups = array_merge($groups, (array) array_values($GLOBALS['TSFE']->fe_user->groupData['uid']));
		} else {
			$groups = array(-1, 0);
		}
		$pageSelect = new \TYPO3\CMS\Frontend\Page\PageRepository();
		$pageSelect->init((boolean) $showHidden);
		$clauses = array();
		foreach ($groups as $group) {
			$clause = "fe_group = '" . $group . "' OR fe_group LIKE '" .
				$group . ",%' OR fe_group LIKE '%," . $group . "' OR fe_group LIKE '%," . $group . ",%'";
			array_push($clauses, $clause);
		}
		array_push($clauses, "fe_group = '' OR fe_group = '0'");
		$pageSelect->where_groupAccess = ' AND (' . implode(' OR ', $clauses) .  ')';
		return $pageSelect;
	}

	/**
	 * Wrapper for \TYPO3\CMS\Frontend\Page\PageRepository::getPage()
	 *
	 * @param integer $pageUid
	 * @return array
	 */
	public function getPage($pageUid = NULL) {
		if (NULL === $pageUid) {
			$pageUid = $GLOBALS['TSFE']->id;
		}
		if (FALSE === isset(self::$cachedPages[$pageUid])) {
			self::$cachedPages[$pageUid] = self::$pageSelect->getPage($pageUid);
		}
		return self::$cachedPages[$pageUid];
	}

	/**
	 * Wrapper for \TYPO3\CMS\Frontend\Page\PageRepository::getPageOverlay()
	 *
	 * @param mixed $pageInput
	 * @param integer $languageUid
	 * @return array
	 */
	public function getPageOverlay($pageInput, $languageUid = -1) {
		$key = md5(serialize($pageInput) . $languageUid);
		if (FALSE === isset(self::$cachedOverlays[$key])) {
			self::$cachedOverlays[$key] = self::$pageSelect->getPageOverlay($pageInput, $languageUid);
		}
		return self::$cachedOverlays[$key];
	}

	/**
	 * Wrapper for \TYPO3\CMS\Frontend\Page\PageRepository::getMenu()
	 * Caution: different signature
	 *
	 * @param integer $pageUid
	 * @param boolean $showHidden
	 * @param array $excludePages
	 * @param string $where
	 * @param boolean $showHiddenInMenu
	 * @param boolean $checkShortcuts
	 * @return array
	 */
	public function getMenu($pageUid = NULL, $showHidden = FALSE, $excludePages = array(), $where = '', $showHiddenInMenu = FALSE, $checkShortcuts = FALSE) {
		if (NULL === $pageUid) {
			$pageUid = $GLOBALS['TSFE']->id;
		}
		$addWhere = 'AND doktype!=254';
		if (0 < count($excludePages)) {
			$addWhere .= ' AND uid NOT IN (' . implode(',', $excludePages) . ')';
		}
		if (FALSE === (boolean) $showHiddenInMenu) {
			$addWhere .= ' AND nav_hide=0';
		}
		if ('' !== $where) {
			$addWhere = $where . ' ' . $addWhere;
		}
		$key = md5(intval($showHidden) . $pageUid . $addWhere . intval($checkShortcuts));
		if (FALSE === isset(self::$cachedMenus[$key])) {
			if (TRUE === $showHidden) {
				self::$cachedMenus[$key] = self::$pageSelectHidden->getMenu($pageUid, '*', 'sorting', $addWhere, $checkShortcuts);
			} else {
				self::$cachedMenus[$key] = self::$pageSelect->getMenu($pageUid, '*', 'sorting', $addWhere, $checkShortcuts);
			}
		}
		return self::$cachedMenus[$key];
	}

	/**
	 * Wrapper for \TYPO3\CMS\Frontend\Page\PageRepository::getRootLine()
	 *
	 * @param integer $pageUid
	 * @param string $MP
	 * @param boolean $reverse
	 * @return array
	 */
	public function getRootLine($pageUid = NULL, $MP = NULL, $reverse = FALSE) {
		if (NULL === $pageUid) {
			$pageUid = $GLOBALS['TSFE']->id;
		}
		if (NULL === $MP) {
			$MP = \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('MP');
			if (TRUE === empty($MP)) {
				$MP = '';
			}
		}
		$key = md5($pageUid . $MP);
		if (FALSE === isset(self::$cachedRootLines[$key])) {
			$rootLine = self::$pageSelect->getRootLine($pageUid, $MP);
			if (TRUE === $reverse) {
				$rootLine = array_reverse($rootLine);
			}
			self::$cachedRootLines[$key] = $rootLine;
		}
		return self::$cachedRootLines[$key];
	}

	/**
	 * Checks if a page for a specific language should be hidden
	 *
	 * @param integer $pageUid
	 * @param integer $languageUid
	 * @param boolean $normalWhenNoLanguage
	 * @return boolean
	 */
	public function hidePageForLanguageUid($pageUid = 0, $languageUid = -1, $normalWhenNoLanguage = TRUE) {
		if (0 === $pageUid) {
			$pageUid = $pageUid = $GLOBALS['TSFE']->id;
		}
		if (-1 === $languageUid) {
			$languageUid = $GLOBALS['TSFE']->sys_language_uid;
		}
		$page = $this->getPage($pageUid);
		$l18nCfg = TRUE === isset($page['l18n_cfg']) ? $page['l18n_cfg'] : 0;
		$hideIfNotTranslated = (boolean) \TYPO3\CMS\Core\Utility\GeneralUtility::hideIfNotTranslated($l18nCfg);
		$hideIfDefaultLanguage = (boolean) \TYPO3\CMS\Core\Utility\GeneralUtility::hideIfDefaultLanguage($l18nCfg);
		$pageOverlay = 0 !== $languageUid ? $this->getPageOverlay($pageUid, $languageUid) : array();
		$translationAvailable = 0 !== count($pageOverlay);
		return
			(TRUE === $hideIfNotTranslated && 0 !== $languageUid && FALSE === $translationAvailable) ||
			(TRUE === $hideIfDefaultLanguage && (0 === $languageUid || FALSE === $translationAvailable)) ||
			(FALSE === $normalWhenNoLanguage && 0 !== $languageUid && FALSE === $translationAvailable);
	}

}


text:
title: Procedural Language, Machine Learning, and Geospatial Extensions
---

*Optional.* Use the Greenplum package manager \(`gppkg`\) to install Greenplum Database extensions such as PL/Java, PL/R, PostGIS, and MADlib, along with their dependencies, across an entire cluster. The package manager also integrates with existing scripts so that any packages are automatically installed on any new hosts introduced into the system following cluster expansion or segment host recovery.

See [gppkg](../utility_guide/ref/gppkg.html) for more information, including usage.

Extension packages can be downloaded from the Greenplum Database page on [VMware Tanzu Network](https://network.pivotal.io/products/pivotal-gpdb). The extension documentation in the *[Greenplum Database Reference Guide](../ref_guide/ref_guide.html)* contains information about installing extension packages and using extensions.

-   [Greenplum PL/R Language Extension](../analytics/pl_r.html)
-   [Greenplum PL/Java Language Extension](../analytics/pl_java.html)
-   [Greenplum MADlib Extension for Analytics](../analytics/madlib.html)
-   [Greenplum PostGIS Extension](../analytics/postGIS.html)

**Important:** If you intend to use an extension package with Greenplum Database 6 you must install and use a Greenplum Database extension package \(gppkg files and contrib modules\) that is built for Greenplum Database 6. Any custom modules that were used with earlier versions must be rebuilt for use with Greenplum Database 6.

**Parent topic:** [Installing Optional Extensions \(Tanzu Greenplum\)](data_sci_pkgs.html)


text:
/* @flow weak */
/**
 * Sakugawa
 * https://github.com/paazmaya/sakugawa
 *
 * Copyright (c) Juga Paazmaya
 * Licensed under the MIT license.
 */

'use strict';

var css = require('css');
// var postcss = require('postcss');

function Sakugawa(styles, options) {
  if (typeof styles !== 'string') {
    throw new Error('styles must be a string');
  }

  if (styles.length < 1) {
    throw new Error('styles must not be empty');
  }

  options = options || {};
  this.maxSelectors = options.maxSelectors || 4090;
  this.mediaQueries = options.mediaQueries || 'normal';
  this.filename = options.filename || 'input.css';
  this.minSheets = options.minSheets || 1;

  this.ast = css.parse(styles);
}

Sakugawa.prototype._clone = function createClone(ast) {

  // Store temporarily elsewhere to speed up JSON conversion
  var origRules = ast.stylesheet.rules;
  ast.stylesheet.rules = [];
  var clone = JSON.parse(JSON.stringify(ast));
  ast.stylesheet.rules = origRules;

  clone.stylesheet.rules = [];

  // Handle charset copying, if such exists
  var charsetRules = origRules.filter(function filterCharsetRules(rule) {
    return rule.type === 'charset';
  });
  if (charsetRules.length > 0) {
    clone.stylesheet.rules = charsetRules;
  }
  return clone;
};

Sakugawa.prototype._countSelectors = function countSelectors(rule, includeMedia) {
  var total = 0,
    _self = this;

  if (rule.type === 'rule' && typeof rule.selectors === 'object') {
    total += rule.selectors.length;
  }
  else if (includeMedia && rule.type === 'media' && rule.rules) {
    rule.rules.forEach(function eachMediaRule(media) {
      total += _self._countSelectors(media, true); // even while media should not contain media...
    });
  }

  return total;
};

Sakugawa.prototype._generatePages = function generatePages(rules, ast) {
  var pages = [],
    _self = this,
    clone,
    selectorsForThisPage = 0;

  // Remove charset rules since they are added when clone is created
  rules = rules.filter(function filterNonCharsetRules(rule) {
    return rule.type !== 'charset';
  });

  rules.forEach(function eachRule(rule) {
    var selectorCount = _self._countSelectors(rule, true);

    if (clone && selectorsForThisPage + selectorCount <= _self.maxSelectors) {
      selectorsForThisPage += selectorCount;
      clone.stylesheet.rules.push(rule);
    }
    else {
      // Restart
      selectorsForThisPage = selectorCount;
      clone = _self._clone(ast);
      clone.stylesheet.rules.push(rule);
      pages.push(clone);
    }
  });

  return pages;
};

Sakugawa.prototype.createPages = function createPages() {
  var pages = [],
    rules = this.ast.stylesheet.rules;

  // Remove media queries from the first iteration when not needed there
  if (this.mediaQueries !== 'normal') {
    rules = rules.filter(function filterNonMediaRules(rule) {
      return rule.type !== 'media';
    });
  }

  pages = this._generatePages(rules, this.ast);

  // Separate media queries
  if (this.mediaQueries === 'separate') {
    var mediaRules = this.ast.stylesheet.rules.filter(function filterMediaRules(rule) {
      return rule.type === 'media';
    });

    pages = pages.concat(this._generatePages(mediaRules, this.ast));
  }

  return pages;
};

Sakugawa.prototype.getPages = function getPages() {
  var pages = this.createPages();
  var sheets = pages.map(function mapPages(page) {
    var str = css.stringify(page);
    return str;
  });
  while (sheets.length < this.minSheets) {
    sheets.push('');
  }
  return sheets;
};

module.exports = function exports(styles, options) {
  var s = new Sakugawa(styles, options);
  return s.getPages();
};


text:
package searchutil

import (
	"sort"

	"github.com/tsiemens/gmail-tools/prnt"
	"github.com/tsiemens/gmail-tools/util"
)

type CountedString struct {
	Str   string
	Count int
}

func MapToSortedCountedStrings(countMap map[string]int) []CountedString {
	stringsSorted := make([]CountedString, 0, len(countMap))
	for data, count := range countMap {
		stringsSorted = append(stringsSorted, CountedString{data, count})
	}
	sort.Slice(
		stringsSorted,
		func(i, j int) bool { return stringsSorted[i].Count > stringsSorted[j].Count })

	return stringsSorted
}

type CountedStringDefaultMap struct {
	Map map[string]int
}

func NewCountedStringDefaultMap() *CountedStringDefaultMap {
	return &CountedStringDefaultMap{make(map[string]int)}
}

func (m *CountedStringDefaultMap) Inc(key string) {
	var count int
	var ok bool
	if count, ok = m.Map[key]; !ok {
		count = 0
	}
	count++
	m.Map[key] = count
}

// header: Any string
// skippedFmt: a format string with a single %d in it
// threshPercent: Limit shown entries to be above x% of the first 3
//                larges entries. 0 to show all.
func PrintCountsWithThresholdOfMax(header string, skippedNoun string,
	minShown int, threshPercent int, countMap map[string]int) {

	sortedTups := MapToSortedCountedStrings(countMap)
	prnt.Hum.Always.Ln(header)

	countThreshold := 0
	if len(sortedTups) > 0 {
		largestFewCnt := util.IntMin(len(sortedTups), 3)
		largestFewTotal := 0
		for i := 0; i < largestFewCnt; i++ {
			largestFewTotal += sortedTups[i].Count
		}
		largestFewAvg := largestFewTotal / largestFewCnt

		// Limit to x% of biggest few
		countThreshold = int(float32(largestFewAvg) * float32(threshPercent) / 100.0)
	}
	skippedCnt := 0
	for i, tup := range sortedTups {
		if i < minShown ||
			tup.Count >= countThreshold {
			prnt.Hum.Always.F("%-40s %d\n", tup.Str, tup.Count)
		} else {
			skippedCnt++
		}
	}
	if skippedCnt > 0 {
		prnt.Hum.Always.F("(%d additional %s skipped; counts too low)\n",
			skippedCnt, skippedNoun)

	}
}


text:
"""This class extends pexpect.spawn to specialize setting up SSH connections.
This adds methods for login, logout, and expecting the shell prompt.

$Id: pxssh.py 513 2008-02-09 18:26:13Z noah $
"""

from pexpect import *
import pexpect
import time

__all__ = ['ExceptionPxssh', 'pxssh']

# Exception classes used by this module.

class ExceptionPxssh(ExceptionPexpect):
    """Raised for pxssh exceptions.
    """

class pxssh (spawn):

    """This class extends pexpect.spawn to specialize setting up SSH
    connections. This adds methods for login, logout, and expecting the shell
    prompt. It does various tricky things to handle many situations in the SSH
    login process. For example, if the session is your first login, then pxssh
    automatically accepts the remote certificate; or if you have public key
    authentication setup then pxssh won't wait for the password prompt.

    pxssh uses the shell prompt to synchronize output from the remote host. In
    order to make this more robust it sets the shell prompt to something more
    unique than just $ or #. This should work on most Borne/Bash or Csh style
    shells.

    Example that runs a few commands on a remote server and prints the result::

        import pxssh
        import getpass
        try:
            s = pxssh.pxssh()
            hostname = raw_input('hostname: ')
            username = raw_input('username: ')
            password = getpass.getpass('password: ')
            s.login (hostname, username, password)
            s.sendline ('uptime')  # run a command
            s.prompt()             # match the prompt
            print s.before         # print everything before the prompt.
            s.sendline ('ls -l')
            s.prompt()
            print s.before
            s.sendline ('df')
            s.prompt()
            print s.before
            s.logout()
        except pxssh.ExceptionPxssh, e:
            print "pxssh failed on login."
            print str(e)

    Note that if you have ssh-agent running while doing development with pxssh
    then this can lead to a lot of confusion. Many X display managers (xdm,
    gdm, kdm, etc.) will automatically start a GUI agent. You may see a GUI
    dialog box popup asking for a password during development. You should turn
    off any key agents during testing. The 'force_password' attribute will turn
    off public key authentication. This will only work if the remote SSH server
    is configured to allow password logins. Example of using 'force_password'
    attribute::

            s = pxssh.pxssh()
            s.force_password = True
            hostname = raw_input('hostname: ')
            username = raw_input('username: ')
            password = getpass.getpass('password: ')
            s.login (hostname, username, password)
    """

    def __init__(
            self,
            timeout=30,
            maxread=2000,
            searchwindowsize=None,
            logfile=None,
            cwd=None,
            env=None):
        spawn.__init__(
            self,
            None,
            timeout=timeout,
            maxread=maxread,
            searchwindowsize=searchwindowsize,
            logfile=logfile,
            cwd=cwd,
            env=env)

        self.name = '<pxssh>'

        # SUBTLE HACK ALERT! Note that the command to set the prompt uses a
        # slightly different string than the regular expression to match it. This
        # is because when you set the prompt the command will echo back, but we
        # don't want to match the echoed command. So if we make the set command
        # slightly different than the regex we eliminate the problem. To make the
        # set command different we add a backslash in front of $. The $ doesn't
        # need to be escaped, but it doesn't hurt and serves to make the set
        # prompt command different than the regex.

        # used to match the command-line prompt
        self.UNIQUE_PROMPT = "\[PEXPECT\][\$\#] "
        self.PROMPT = self.UNIQUE_PROMPT

        # used to set shell command-line prompt to UNIQUE_PROMPT.
        self.PROMPT_SET_SH = "PS1='[PEXPECT]\$ '"
        self.PROMPT_SET_CSH = "set prompt='[PEXPECT]\$ '"
        self.SSH_OPTS = "-o'RSAAuthentication=no' -o 'PubkeyAuthentication=no'"
        # Disabling X11 forwarding gets rid of the annoying SSH_ASKPASS from
        # displaying a GUI password dialog. I have not figured out how to
        # disable only SSH_ASKPASS without also disabling X11 forwarding.
        # Unsetting SSH_ASKPASS on the remote side doesn't disable it! Annoying!
        #self.SSH_OPTS = "-x -o'RSAAuthentication=no' -o 'PubkeyAuthentication=no'"
        self.force_password = False
        self.auto_prompt_reset = True

    def levenshtein_distance(self, a, b):
        """This calculates the Levenshtein distance between a and b.
        """

        n, m = len(a), len(b)
        if n > m:
            a, b = b, a
            n, m = m, n
        current = range(n + 1)
        for i in range(1, m + 1):
            previous, current = current, [i] + [0] * n
            for j in range(1, n + 1):
                add, delete = previous[j] + 1, current[j - 1] + 1
                change = previous[j - 1]
                if a[j - 1] != b[i - 1]:
                    change = change + 1
                current[j] = min(add, delete, change)
        return current[n]

    def sync_original_prompt(self):
        """This attempts to find the prompt. Basically, press enter and record
        the response; press enter again and record the response; if the two
        responses are similar then assume we are at the original prompt. This
        is a slow function. It can take over 10 seconds. """

        # All of these timing pace values are magic.
        # I came up with these based on what seemed reliable for
        # connecting to a heavily loaded machine I have.
        # If latency is worse than these values then this will fail.

        try:
            # GAS: Clear out the cache before getting the prompt
            self.read_nonblocking(size=10000, timeout=1)
        except TIMEOUT:
            pass
        time.sleep(0.1)
        self.sendline()
        time.sleep(0.5)
        x = self.read_nonblocking(size=1000, timeout=1)
        time.sleep(0.1)
        self.sendline()
        time.sleep(0.5)
        a = self.read_nonblocking(size=1000, timeout=1)
        time.sleep(0.1)
        self.sendline()
        time.sleep(0.5)
        b = self.read_nonblocking(size=1000, timeout=1)
        ld = self.levenshtein_distance(a, b)
        len_a = len(a)
        if len_a == 0:
            return False
        if float(ld) / len_a < 0.4:
            return True
        return False

    # TODO: This is getting messy and I'm pretty sure this isn't perfect.
    # TODO: I need to draw a flow chart for this.
    def login(
            self,
            server,
            username,
            password='',
            terminal_type='ansi',
            original_prompt=r"[#$]",
            login_timeout=10,
            port=None,
            auto_prompt_reset=True):
        """This logs the user into the given server. It uses the
        'original_prompt' to try to find the prompt right after login. When it
        finds the prompt it immediately tries to reset the prompt to something
        more easily matched. The default 'original_prompt' is very optimistic
        and is easily fooled. It's more reliable to try to match the original
        prompt as exactly as possible to prevent false matches by server
        strings such as the "Message Of The Day". On many systems you can
        disable the MOTD on the remote server by creating a zero-length file
        called "~/.hushlogin" on the remote server. If a prompt cannot be found
        then this will not necessarily cause the login to fail. In the case of
        a timeout when looking for the prompt we assume that the original
        prompt was so weird that we could not match it, so we use a few tricks
        to guess when we have reached the prompt. Then we hope for the best and
        blindly try to reset the prompt to something more unique. If that fails
        then login() raises an ExceptionPxssh exception.

        In some situations it is not possible or desirable to reset the
        original prompt. In this case, set 'auto_prompt_reset' to False to
        inhibit setting the prompt to the UNIQUE_PROMPT. Remember that pxssh
        uses a unique prompt in the prompt() method. If the original prompt is
        not reset then this will disable the prompt() method unless you
        manually set the PROMPT attribute. """

        ssh_options = '-q'
        if self.force_password:
            ssh_options = ssh_options + ' ' + self.SSH_OPTS
        if port is not None:
            ssh_options = ssh_options + ' -p %s' % (str(port))
        cmd = "ssh %s -l %s %s" % (ssh_options, username, server)

        # This does not distinguish between a remote server 'password' prompt
        # and a local ssh 'passphrase' prompt (for unlocking a private key).
        spawn._spawn(self, cmd)
        i = self.expect(
            [
                "(?i)are you sure you want to continue connecting",
                original_prompt,
                "(?i)(?:password)|(?:passphrase for key)",
                "(?i)permission denied",
                "(?i)terminal type",
                TIMEOUT,
                "(?i)connection closed by remote host"],
            timeout=login_timeout)

        # First phase
        if i == 0:
            # New certificate -- always accept it.
            # This is what you get if SSH does not have the remote host's
            # public key stored in the 'known_hosts' cache.
            self.sendline("yes")
            i = self.expect(
                [
                    "(?i)are you sure you want to continue connecting",
                    original_prompt,
                    "(?i)(?:password)|(?:passphrase for key)",
                    "(?i)permission denied",
                    "(?i)terminal type",
                    TIMEOUT])
        if i == 2:  # password or passphrase
            self.sendline(password)
            i = self.expect(
                [
                    "(?i)are you sure you want to continue connecting",
                    original_prompt,
                    "(?i)(?:password)|(?:passphrase for key)",
                    "(?i)permission denied",
                    "(?i)terminal type",
                    TIMEOUT])
        if i == 4:
            self.sendline(terminal_type)
            i = self.expect(
                [
                    "(?i)are you sure you want to continue connecting",
                    original_prompt,
                    "(?i)(?:password)|(?:passphrase for key)",
                    "(?i)permission denied",
                    "(?i)terminal type",
                    TIMEOUT])

        # Second phase
        if i == 0:
            # This is weird. This should not happen twice in a row.
            self.close()
            raise ExceptionPxssh(
                'Weird error. Got "are you sure" prompt twice.')
        elif i == 1:  # can occur if you have a public key pair set to authenticate.
            # TODO: May NOT be OK if expect() got tricked and matched a false
            # prompt.
            pass
        elif i == 2:  # password prompt again
            # For incorrect passwords, some ssh servers will
            # ask for the password again, others return 'denied' right away.
            # If we get the password prompt again then this means
            # we didn't get the password right the first time.
            self.close()
            raise ExceptionPxssh('password refused')
        elif i == 3:  # permission denied -- password was bad.
            self.close()
            raise ExceptionPxssh('permission denied')
        elif i == 4:  # terminal type again? WTF?
            self.close()
            raise ExceptionPxssh(
                'Weird error. Got "terminal type" prompt twice.')
        elif i == 5:  # Timeout
            # This is tricky... I presume that we are at the command-line prompt.
            # It may be that the shell prompt was so weird that we couldn't match
            # it. Or it may be that we couldn't log in for some other reason. I
            # can't be sure, but it's safe to guess that we did login because if
            # I presume wrong and we are not logged in then this should be caught
            # later when I try to set the shell prompt.
            pass
        elif i == 6:  # Connection closed by remote host
            self.close()
            raise ExceptionPxssh('connection closed')
        else:  # Unexpected
            self.close()
            raise ExceptionPxssh('unexpected login response')
        if not self.sync_original_prompt():
            self.close()
            raise ExceptionPxssh('could not synchronize with original prompt')
        # We appear to be in.
        # set shell prompt to something unique.
        if auto_prompt_reset:
            if not self.set_unique_prompt():
                self.close()
                raise ExceptionPxssh(
                    'could not set shell prompt\n' + self.before)
        return True

    def logout(self):
        """This sends exit to the remote shell. If there are stopped jobs then
        this automatically sends exit twice. """

        self.sendline("exit")
        index = self.expect([EOF, "(?i)there are stopped jobs"])
        if index == 1:
            self.sendline("exit")
            self.expect(EOF)
        self.close()

    def prompt(self, timeout=20):
        """This matches the shell prompt. This is little more than a short-cut
        to the expect() method. This returns True if the shell prompt was
        matched. This returns False if there was a timeout. Note that if you
        called login() with auto_prompt_reset set to False then you should have
        manually set the PROMPT attribute to a regex pattern for matching the
        prompt. """

        i = self.expect([self.PROMPT, TIMEOUT], timeout=timeout)
        if i == 1:
            return False
        return True

    def set_unique_prompt(self):
        """This sets the remote prompt to something more unique than # or $.
        This makes it easier for the prompt() method to match the shell prompt
        unambiguously. This method is called automatically by the login()
        method, but you may want to call it manually if you somehow reset the
        shell prompt. For example, if you 'su' to a different user then you
        will need to manually reset the prompt. This sends shell commands to
        the remote host to set the prompt, so this assumes the remote host is
        ready to receive commands.

        Alternatively, you may use your own prompt pattern. Just set the PROMPT
        attribute to a regular expression that matches it. In this case you
        should call login() with auto_prompt_reset=False; then set the PROMPT
        attribute. After that the prompt() method will try to match your prompt
        pattern."""

        self.sendline("unset PROMPT_COMMAND")
        self.sendline(self.PROMPT_SET_SH)  # sh-style
        i = self.expect([TIMEOUT, self.PROMPT], timeout=10)
        if i == 0:  # csh-style
            self.sendline(self.PROMPT_SET_CSH)
            i = self.expect([TIMEOUT, self.PROMPT], timeout=10)
            if i == 0:
                return False
        return True

# vi:ts=4:sw=4:expandtab:ft=python:


text:
var MSG = {
  title: "Código",
  blocks: "Blocos",
  linkTooltip: "Salvar e ligar aos blocos.",
  runTooltip: "Execute o programa definido pelos blocos na área de trabalho.",
  badCode: "Erro no programa:\n%1",
  timeout: "Máximo de iterações de execução excedido.",
  discard: "Apagar todos os %1 blocos?",
  trashTooltip: "Descartar todos os blocos.",
  catMinecraft:'Minecraft',
  catLogic: "Lógica",
  catLoops: "Laços",
  catMath: "Matemática",
  catText: "Texto",
  catLists: "Listas",
  catColour: "Cor",
  catVariables: "Variáveis",
  catFunctions: "Funções",
  listVariable: "lista",
  textVariable: "texto",
  httpRequestError: "Houve um problema com a requisição.",
  linkAlert: "Compartilhe seus blocos com este link:\n\n(Ctrl-C or Cmd-C to copy link)",
  hashError: "Desculpe, '%1' não corresponde a um programa salvo.",
  xmlError: "Não foi possível carregar seu arquivo salvo. Talvez ele tenha sido criado com uma versão diferente do Blockly?",
  badXml: "Erro de análise XML:\n%1\n\nSelecione 'OK' para abandonar suas mudanças ou 'Cancelar' para editar o XML."
};


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class org.apache.pig.data.BagFactory (Pig 0.8.0-CDH3B4-SNAPSHOT API)
</TITLE>

<META NAME="date" CONTENT="2011-02-16">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.pig.data.BagFactory

Packages that use BagFactory

org.apache.pig.backend.hadoop.executionengine.physicalLayer.expressionOperators

org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators

org.apache.pig.builtin

This package contains builtin Pig UDFs.

org.apache.pig.data

This package contains implementations of Pig specific data types as well as
support functions for reading, writing, and using all Pig data types.

Uses of BagFactory in org.apache.pig.backend.hadoop.executionengine.physicalLayer.expressionOperators

Fields in org.apache.pig.backend.hadoop.executionengine.physicalLayer.expressionOperators declared as BagFactory

protected static BagFactory
POProject.bagFactory

Uses of BagFactory in org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators

Fields in org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators declared as BagFactory

protected static BagFactory
POPreCombinerLocalRearrange.mBagFactory

protected static BagFactory
POPartitionRearrange.mBagFactory

protected static BagFactory
POPackage.mBagFactory

Uses of BagFactory in org.apache.pig.builtin

Fields in org.apache.pig.builtin declared as BagFactory

protected  BagFactory
Utf8StorageConverter.mBagFactory

Uses of BagFactory in org.apache.pig.data

Subclasses of BagFactory in org.apache.pig.data

 class
DefaultBagFactory

          Default implementation of BagFactory.

Methods in org.apache.pig.data that return BagFactory

static BagFactory
BagFactory.getInstance()

          Get a reference to the singleton factory.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © ${year} The Apache Software Foundation


text:
typedef void (^ChangeSuccessBlock)(void);
typedef void (^ChangeFailBlock)(NSError *failError);
@interface STWPersonService : NSObject
+(void)changePersonInfo:(STWLoginUserDetail *)detailModel success: (void(^)(STWLoginUserDetail* resultModel))successBlock failed:(void(^)(NSError *failError))failedBlock;

+(void)changePersonPsw:(NSString *)oldPSW newPsw:(NSString *)newPsw staff_id:(NSString *)staff_id  success: (ChangeSuccessBlock)successBlock failed:(ChangeFailBlock)failedBlock;
@end


text: More info at: https://meta.discourse.org/t/sams-personal-minimal-topic-list-design/23552?u=sam


text:
package de.othsoft.codeGen.requirements.jdbc.utils;

import de.othsoft.codeGen.requirements.CmdData;
import de.othsoft.codeGen.requirements.DaoException;
import de.othsoft.codeGen.requirements.QueryRestr;
import de.othsoft.codeGen.requirements.QuerySort;
import de.othsoft.codeGen.requirements.UserData;
import de.othsoft.codeGen.requirements.jdbc.JdbcCmdData;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;

/**
 *
 * @author eiko
 */
public class SQLExecWrapper<T> extends SQLWrapperBase {
    public static boolean isChanged(String oldValue,String newValue) {
        if (oldValue==null && newValue!=null) return true;
        if (oldValue!=null && newValue==null) return true;
        if (oldValue==null && newValue==null) return false;
        return oldValue.equals(newValue);
    }

    public static boolean isChanged(Integer oldValue,Integer newValue) {
        if (oldValue==null && newValue!=null) return true;
        if (oldValue!=null && newValue==null) return true;
        if (oldValue==null && newValue==null) return false;
        return oldValue.equals(newValue);
    }

    public static boolean isChanged(Double oldValue,Double newValue) {
        if (oldValue==null && newValue!=null) return true;
        if (oldValue!=null && newValue==null) return true;
        if (oldValue==null && newValue==null) return false;
        return oldValue.equals(newValue);
    }

    public static boolean isChanged(Date oldValue,Date newValue) {
        if (oldValue==null && newValue!=null) return true;
        if (oldValue!=null && newValue==null) return true;
        if (oldValue==null && newValue==null) return false;
        return oldValue.equals(newValue);
    }

    public static boolean isChanged(Boolean oldValue,Boolean newValue) {
        if (oldValue==null && newValue!=null) return true;
        if (oldValue!=null && newValue==null) return true;
        if (oldValue==null && newValue==null) return false;
        return oldValue.equals(newValue);
    }

    public static boolean isChanged(BigDecimal oldValue,BigDecimal newValue) {
        if (oldValue==null && newValue!=null) return true;
        if (oldValue!=null && newValue==null) return true;
        if (oldValue==null && newValue==null) return false;
        return oldValue.equals(newValue);
    }

    public SQLExecWrapper (Logger log) {
        super(log);
    }

    public Integer insert(ISQLInsWrapperUser<T> wrapperUser, T data, IJdbcDataFactoryBase dataFactory,UserData userData,CmdData cmdData) throws DaoException {
        PreparedStatement ps=null;
        ResultSet rs=null;
        Connection con = ((cmdData!=null) && (cmdData instanceof JdbcCmdData))? ((JdbcCmdData)cmdData).getCon() : dataFactory.getConnectionFactory().getCon();
        try {
            String sql = wrapperUser.getInsSql();
            log.info(sql);
            ps=con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
            wrapperUser.setInsValues(ps,data);
            ps.execute();
            rs = ps.getGeneratedKeys();
            rs.next();
            return rs.getInt(1);
        }
        catch(SQLException e) {
            throw new DaoException(log,e);
        }
        finally {
            ggfCloseResultSet(rs);
            ggfCloseStatement(ps);
            ggfCloseConnection(cmdData,con);
        }
    }

    public void delete(ISQLDelWrapperUser wrapperUser, int id, IJdbcDataFactoryBase dataFactory,UserData userData,CmdData cmdData) throws DaoException {
        PreparedStatement ps=null;
        Connection con = ((cmdData!=null) && (cmdData instanceof JdbcCmdData))? ((JdbcCmdData)cmdData).getCon() : dataFactory.getConnectionFactory().getCon();
        try {
            String sql = wrapperUser.getDelSql();
            log.info(sql);
            ps=con.prepareStatement(sql);
            ps.setInt(1, id);
            ps.execute();
        }
        catch(SQLException e) {
            throw new DaoException(log,e);
        }
        finally {
            ggfCloseStatement(ps);
            ggfCloseConnection(cmdData,con);
        }
    }

    public void update(ISQLUpdWrapperUser<T> wrapperUser, T data, IJdbcDataFactoryBase dataFactory,UserData userData,CmdData cmdData) throws DaoException {
        PreparedStatement ps=null;
        Connection con = ((cmdData!=null) && (cmdData instanceof JdbcCmdData))? ((JdbcCmdData)cmdData).getCon() : dataFactory.getConnectionFactory().getCon();
        try {
            String sql = wrapperUser.getUpdSql(data);
            log.info(sql);
            ps=con.prepareStatement(sql);
            wrapperUser.setUpdValues(ps,data);
            ps.execute();
        }
        catch(SQLException e) {
            throw new DaoException(log,e);
        }
        finally {
            ggfCloseStatement(ps);
            ggfCloseConnection(cmdData,con);
        }
    }

    public int count(ISQLQueryWrapperUser<T> wrapperUser,IJdbcDataFactoryBase dataFactory,UserData userData,CmdData cmdData,List<QueryRestr> restr) throws DaoException {
        PreparedStatement ps=null;
        ResultSet rs=null;
        Connection con = ((cmdData!=null) && (cmdData instanceof JdbcCmdData))? ((JdbcCmdData)cmdData).getCon() : dataFactory.getConnectionFactory().getCon();
        try {
            String sql = wrapperUser.getSelectBaseSql();
            sql=wrapperUser.appendFilterToSql(sql, restr);
            sql=addCountToSql(sql);
            log.info(sql);
            ps=con.prepareStatement(sql);
            dataFactory.setFilterValues(ps,restr);
            rs = ps.executeQuery();
            rs.next();
            return rs.getInt(1);
        }
        catch(SQLException e) {
            throw new DaoException(log,e);
        }
        finally {
            ggfCloseResultSet(rs);
            ggfCloseStatement(ps);
            ggfCloseConnection(cmdData,con);
        }
    }

    public List<T> get(ISQLQueryWrapperUser<T> wrapperUser,IJdbcDataFactoryBase dataFactory,UserData userData,CmdData cmdData,List<QueryRestr> restr,List<QuerySort> sort,int offset,int count)
            throws DaoException {
        PreparedStatement ps=null;
        ResultSet rs=null;
        Connection con = ((cmdData!=null) && (cmdData instanceof JdbcCmdData))? ((JdbcCmdData)cmdData).getCon() : dataFactory.getConnectionFactory().getCon();
        try {
            String sql = wrapperUser.getSelectBaseSql();
            sql=wrapperUser.appendFilterToSql(sql, restr);
            if (offset==0 && count==0)
                // this code depends from used database, so I link to a special implementation
                sql=dataFactory.getSetPagingImpl().appendPagingToSql(sql,offset,count);
            log.info(sql);
            ps=con.prepareStatement(sql);
            dataFactory.setFilterValues(ps,restr);
            rs = ps.executeQuery();
            List<T> ret = new ArrayList();
            while (rs.next()) {
                ret.add(wrapperUser.initFromResultSet(dataFactory,rs));
            }
            return ret;
        }
        catch(SQLException e) {
            throw new DaoException(log,e);
        }
        finally {
            ggfCloseResultSet(rs);
            ggfCloseStatement(ps);
            ggfCloseConnection(cmdData,con);
        }
    }

    public T byId(ISQLQueryWrapperUser<T> wrapperUser,IJdbcDataFactoryBase dataFactory,UserData userData,CmdData cmdData,int id) throws DaoException {
        PreparedStatement ps=null;
        ResultSet rs=null;
        Connection con = ((cmdData!=null) && (cmdData instanceof JdbcCmdData))? ((JdbcCmdData)cmdData).getCon() : dataFactory.getConnectionFactory().getCon();
        try {
            String sql = wrapperUser.getSelectBaseSql();
            sql+=StringConsts.WHERE_SQL;
            sql+=wrapperUser.getIdRestr();
            log.info(sql);
            ps=con.prepareStatement(sql);
            ps.setInt(1, id);
            if (log.isDebugEnabled())
                log.debug("id="+id);
            rs = ps.executeQuery();
            if (rs.next())
                return wrapperUser.initFromResultSet(dataFactory,rs);
            else
                return null;
        }
        catch(SQLException e) {
            throw new DaoException(log,e);
        }
        finally {
            ggfCloseResultSet(rs);
            ggfCloseStatement(ps);
            ggfCloseConnection(cmdData,con);
        }
    }
}