text:
package com.bplow.look.bass.autoCreate;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.ArrayUtil;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import com.bplow.look.bass.annotation.fieldDesc;

import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

public class StartHere {

	private Configuration cfg;
	Properties prop = new Properties();
	String propertyName = "temlFile.properties";//属性文件的文件名
	String WebRootPath = null;//WebRoot路径
	String classPath = null;//当前类所在的路径
	String moduleName = null;
	String voname = null;//实体类名称
	String voFullName = null;//实体类全路径
	List classProField = new ArrayList<FieldAttribute>();

	String jspQueryListPageTempl = null;
	String jspAddPageTempl = null;
	String jspEditorPageTempl = null;

	String classDaoHibernateTempl = null;
	String classDaoJdbcTempl = null;
	String classServiceTempl = null;
	String classActionTempl = null;
	String classToolKitsTempl = null;

	/**
	 * 获取类的全路径
	 * 初始化模板类的定义
	 */
	public StartHere() {
		super();
		classPath = this.getClass().getClassLoader().getResource("").getPath();

		cfg = new Configuration();
		//cfg.setServletContextForTemplateLoading(getServletContext(), "WEB-INF/templates");
		cfg.setClassForTemplateLoading(this.getClass(), "/");
		cfg.setTemplateUpdateDelay(0);
		cfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
		cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
		cfg.setDefaultEncoding("UTF-8");//ISO-8859-1
		cfg.setOutputEncoding("UTF-8");//UTF-8
		cfg.setLocale(Locale.ENGLISH);
		System.out.println(classPath);
	}

	/**
	 * 读取属性配置文件
	 * @throws IOException
	 */
	public void loadPropertyFile(String filePath) throws IOException{

		InputStream inStream = new BufferedInputStream (new FileInputStream(classPath+"/"+propertyName));
		prop.load(inStream);

		WebRootPath = prop.getProperty("WebRootPath");
		moduleName = prop.getProperty("moduleName");
		voname =  prop.getProperty("vo_name");
		voFullName = prop.getProperty("vo_full_name");

		jspQueryListPageTempl = prop.getProperty("jspQueryListPageTempl");
		jspAddPageTempl = prop.getProperty("jspAddPageTempl");
		jspEditorPageTempl = prop.getProperty("jspEditorPageTempl");

		classDaoHibernateTempl = prop.getProperty("ClassDaoHibernateTempl");
		classDaoJdbcTempl = prop.getProperty("ClassDaoJdbcTempl");
		classServiceTempl = prop.getProperty("ClassServiceTempl");
		classActionTempl = prop.getProperty("ClassActionTempl");
		classToolKitsTempl = prop.getProperty("ClassToolKitsTempl");
		//System.out.println(prop.get("web_jsp_path"));
	}

	/***
	 * 读取实体类的属性字段 封装到指定的对象中
	 * @throws ClassNotFoundException
	 * @throws SecurityException
	 */
	public void readClassProperty() throws SecurityException, ClassNotFoundException{

		Class tmpclass = Class.forName(voFullName);
		Field[] f = tmpclass.getDeclaredFields();
		for(Field fld : f){
			FieldAttribute fa = new FieldAttribute();
			fa.setFieldNo(fld.getName());
			fa.setFieldType(fld.getType().toString());

			classProField.add(fa);
			Annotation[] annotation = fld.getDeclaredAnnotations();
			for(Annotation atn : annotation){
//				TypeVariable[] type =atn.annotationType().getTypeParameters();
				fieldDesc vo = (fieldDesc)atn;
				fa.setFieldName(vo.fldDesc());
				fa.setIsNeedVerify(vo.isNeedVerify());
//				System.out.println(vo.fldDesc());
			}
			//System.out.println(fld.getName());
		}

	}
	//--------------------------------生成JSP页面---------------------------------------------
	/**
	 * 生成页面文件
	 * @throws IOException
	 * @throws TemplateException
	 */
	public void createTemplFile() throws IOException, TemplateException{
		Writer out = null;
		String preJsppath = "WEB-INF/content/"+moduleName+"/";
		File newF = new File(WebRootPath+preJsppath);
		if(!newF.exists()){
			newF.mkdir();
		}

		//配置列表页面的数据
		Map rootMap=new HashMap();
		rootMap.put("classProField", classProField);
		rootMap.put("voname", voname);
		rootMap.put("vonameF", changeFirstCharToupper(voname));
		rootMap.put("moduleName", moduleName);
		rootMap.put("moduleNameLower", moduleName.toLowerCase());
		Template tpl = null;
		//生成list Page
		if(prop.getProperty("isCreateListJsp").equals("0")){
			out = createWriterObj(WebRootPath +preJsppath+voname+"QueryList.jsp");
			tpl = cfg.getTemplate(jspQueryListPageTempl);
			tpl.setEncoding("UTF-8");
			tpl.process(rootMap, out);
			System.out.println("-----------List JSP文件生成成功---------------");
		}

		//生成添加页面
		if(prop.getProperty("isCreateAddJsp").equals("0")){
		out = createWriterObj(WebRootPath +preJsppath+"Add"+changeFirstCharToupper(voname)+".jsp");
		tpl = cfg.getTemplate(jspAddPageTempl);
		tpl.process(rootMap, out);
		System.out.println("-----------ADD JSP文件生成成功---------------");
		}

		//生成修改页面
		if(prop.getProperty("isCreateEditorJsp").equals("0")){
		out = createWriterObj(WebRootPath +preJsppath+"Editor"+changeFirstCharToupper(voname)+".jsp");
		tpl = cfg.getTemplate(jspEditorPageTempl);
		tpl.process(rootMap, out);
		System.out.println("-----------EDITOR JSP文件生成成功---------------");
		}
	}

	/**
	 * 创建jsp文件
	 */
	public Writer createWriterObj(String fileName)throws IOException{
		String outputfileName = fileName;// classPath
		File file = new File(outputfileName);
//		if(!file.isFile()){
//			file.createNewFile();
//		}
		OutputStream outstream = new FileOutputStream(file);
		Writer out = new OutputStreamWriter(outstream,"UTF-8");

		return out;
	}
	//------------------------------以下是生成类 begin---------------------------------------
	/**
	 * 生成类文件的目录结构
	 * @throws IOException
	 * @throws TemplateException
	 */
	public void createClassPathDir() throws IOException, TemplateException{
		File webRootFile = new File(WebRootPath);
		File bfjFile = webRootFile.getParentFile();
		String templateDir = "/src_"+moduleName+"/com/bplow/look/"+moduleName.toLowerCase()+"/";

		String bfjDir = bfjFile.getAbsolutePath();
		File daoDirFile = new File(bfjDir+templateDir+"dao");
		if(!daoDirFile.exists()){
			daoDirFile.mkdir();
		}
		daoDirFile = new File(bfjDir+templateDir+"service");
		if(!daoDirFile.exists()){
			daoDirFile.mkdir();
		}
		daoDirFile = new File(bfjDir+templateDir+"utils");
		if(!daoDirFile.exists()){
			daoDirFile.mkdir();
		}
		daoDirFile = new File(bfjDir+templateDir+"web");
		if(!daoDirFile.exists()){
			daoDirFile.mkdir();
		}

		//dao class file
		Writer out = null;
		Map rootMap=new HashMap();
		Template tpl = null;
		rootMap.put("moduleName", moduleName);
		rootMap.put("moduleNameLower", moduleName.toLowerCase());
		rootMap.put("moduleNameAction", changeFirstCharToupper(moduleName.toLowerCase()));
		rootMap.put("moduleNameF", changeFirstCharToupper(moduleName));
		rootMap.put("voname", changeFirstCharToupper(voname));
		rootMap.put("vonameF", voname);
		rootMap.put("voFullName", voFullName);

		if(prop.getProperty("isCreateDaoHibernateClass").equals("0")){
		out = createWriterObj(bfjDir+templateDir+"dao/"+changeFirstCharToupper(moduleName)+"Hibernate.java");
		tpl = cfg.getTemplate(classDaoHibernateTempl);
		tpl.setEncoding("UTF-8");
		tpl.process(rootMap, out);
		System.out.println("-----------dao 文件生成成功---------------");
		}

		if(prop.getProperty("isCreateDaoJdbcClass").equals("0")){
		out = createWriterObj(bfjDir+templateDir+"dao/"+changeFirstCharToupper(moduleName)+"JdbcDao.java");
		tpl = cfg.getTemplate(classDaoJdbcTempl);
		tpl.setEncoding("UTF-8");
		tpl.process(rootMap, out);
		System.out.println("-----------jdbc 文件生成成功---------------");
		}

		if(prop.getProperty("isCreateServiceClass").equals("0")){
		out = createWriterObj(bfjDir+templateDir+"service/"+changeFirstCharToupper(moduleName)+"Service.java");
		tpl = cfg.getTemplate(classServiceTempl);
		tpl.setEncoding("UTF-8");
		tpl.process(rootMap, out);
		System.out.println("-----------service 文件生成成功---------------");
		}
		if(prop.getProperty("isCreateActionClass").equals("0")){
		out = createWriterObj(bfjDir+templateDir+"web/"+changeFirstCharToupper(moduleName)+"Action.java");
		tpl = cfg.getTemplate(classActionTempl);
		tpl.setEncoding("UTF-8");
		tpl.process(rootMap, out);
		System.out.println("-----------action 文件生成成功---------------");
		}
		if(prop.getProperty("isCreateToolkitsClass").equals("0")){
		out = createWriterObj(bfjDir+templateDir+"utils/"+"Tooltiks.java");
		tpl = cfg.getTemplate(classToolKitsTempl);
		tpl.setEncoding("UTF-8");
		tpl.process(rootMap, out);
		System.out.println("-----------toolkits 文件生成成功---------------");
		}

		System.out.println("查询列表页面URL:"+moduleName+"/"+moduleName.toLowerCase()+"!"+moduleName+"ListWeb.action");
		//System.out.println(bfjDir);

	}

	//--------------------------------------以下是生成配置-----------------------------------------------------\\
	//-------------------------------------------------------------------------------------------------------\\
	/**
	 * 生成hibernate 配置文件
	 * @throws IOException
	 */
	public void createHibernateConfigFile() throws IOException{
		Document document = structureHibernateConfDocument();
		Element sessionE = document.getRootElement().element("session-factory");
		File configfile = new File(WebRootPath+"WEB-INF/framework/hibernate-config/hibernate."+moduleName+".cfg.xml");//实体类的存放路径
		String preVoPath = StringUtils.substringBeforeLast(voFullName, ".").replace(".", "/");//实体类在Class文件下的路径
		//给document添加实体类映射元素
		String voEntityDir =classPath+preVoPath;
		File tmpfile = new File(voEntityDir);
		if(tmpfile.isDirectory()){
			File[] voFile = tmpfile.listFiles();
			for(File voEntityfile : voFile){

				if(voEntityfile.getName().indexOf("hbm")>0){
					Element element = sessionE.addElement("mapping");
					element.setAttributeValue("resource",preVoPath+"/"+ voEntityfile.getName());
				}
			}
		}

		saveDocumentToFile(document,configfile);
		System.out.println("-----------hibernate文件生成成功---------------");
	}

	/**
	 * 生成hibernate 配置文件
	 * @throws IOException
	 */
	public void createSpringConfigFile() throws IOException{
		Document document = structureSpringConfDocument();

		File configfile = new File(WebRootPath+"WEB-INF/framework/spring-config/applicationContext-"+moduleName+".xml");//实体类的存放路径

		saveDocumentToFile(document,configfile);
		System.out.println("-----------hibernate文件生成成功---------------");
	}

	/**
	 * 定义hibernate配置文件 document
	 */
	public Document structureHibernateConfDocument(){

		Document document = DocumentHelper.createDocument();
		document.addDocType("hibernate-configuration", "-//Hibernate/Hibernate Configuration DTD 3.0//EN",
				"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd");
		Element rootElement =document.addElement("hibernate-configuration");
		Element sessionfactoryElement =rootElement.addElement("session-factory");

		return document;

	}

	/**
	 * 定义spring配置文件 document
	 * @throws UnsupportedEncodingException
	 */
	public Document structureSpringConfDocument() throws UnsupportedEncodingException{

		Document document = DocumentHelper.createDocument();
		Element rootElement =document.addElement("beans");
		rootElement.addAttribute("xmlns", "http://www.springframework.org/schema/beans").
		            addAttribute("xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance").
		            addAttribute("xsi:schemaLocation","http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd")
		            .addAttribute("default-lazy-init","true");
		Element descElement =rootElement.addElement("description");
		descElement.setText("");
		Element beanE = rootElement.addElement("bean");
		beanE.addAttribute("id", changeFirstCharLower(moduleName+"JdbcDao")).addAttribute("class", "com.bplow.look."+moduleName.toLowerCase()+".dao."+changeFirstCharToupper(moduleName)+"JdbcDao").addAttribute("parent", "baseJdbcDao");
		Element beanHibernateE = rootElement.addElement("bean");
		beanHibernateE.addAttribute("id", changeFirstCharLower(moduleName+"Hibernate")).
		   addAttribute("class", "com.bplow.look."+moduleName.toLowerCase()+".dao."+changeFirstCharToupper(moduleName+"Hibernate"));
		Element beanServiceE = rootElement.addElement("bean");
		beanServiceE.addAttribute("id", changeFirstCharLower(moduleName+"Service")).
		   addAttribute("class", "com.bplow.look."+moduleName.toLowerCase()+".service."+changeFirstCharToupper(moduleName+"Service"));
		return document;

	}

	/**
	 * 生成xml文件
	 * @throws IOException
	 */
	public void saveDocumentToFile(Document document ,File file) throws IOException{
		// 美化格式
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");
		//document.setXMLEncoding("UTF-8");
		XMLWriter output = new XMLWriter(new FileWriter(file), format);
        output.write(document);
        output.close();

	}

	/*
	 * 将字符串首字母改为大写
	 */
	public String changeFirstCharToupper(String str){
//		byte tmp[]= str.getBytes();
		char charArray[] = new char[str.length()];
		char dst[] =new char[str.length()];
		str.getChars(0, str.length() , charArray, 0);
		String.valueOf(charArray[0]).toUpperCase().getChars(0, 1, dst, 0);
		charArray[0] = dst[0];

		return String.valueOf(charArray);
	}
	/*
	 * 将字符串首字母改为小写
	 */
	public String changeFirstCharLower(String str){
//		byte tmp[]= str.getBytes();
		char charArray[] = new char[str.length()];
		char dst[] =new char[str.length()];
		str.getChars(0, str.length() , charArray, 0);
		String.valueOf(charArray[0]).toLowerCase().getChars(0, 1, dst, 0);
		charArray[0] = dst[0];

		return String.valueOf(charArray);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		String classpath = null;
		StartHere sh = new StartHere();
		try {
			sh.loadPropertyFile("");

			sh.readClassProperty();

			if(sh.prop.getProperty("isCreateJsp").equals("0") )sh.createTemplFile();

			//生成hibernate配置文件
			if(sh.prop.getProperty("isCreateHibernate").equals("0") )sh.createHibernateConfigFile();
			//生成spring配置文件
			if(sh.prop.getProperty("isCreateSpring").equals("0") )sh.createSpringConfigFile();

			sh.createClassPathDir();

			//System.out.println(sh.changeFirstCharToupper("wangXiaoLei"));

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}


text:
package client

const (
	InternalNodeSpecType               = "internalNodeSpec"
	InternalNodeSpecFieldPodCidr       = "podCidr"
	InternalNodeSpecFieldProviderId    = "providerId"
	InternalNodeSpecFieldTaints        = "taints"
	InternalNodeSpecFieldUnschedulable = "unschedulable"
)

type InternalNodeSpec struct {
	PodCidr       string  `json:"podCidr,omitempty" yaml:"podCidr,omitempty"`
	ProviderId    string  `json:"providerId,omitempty" yaml:"providerId,omitempty"`
	Taints        []Taint `json:"taints,omitempty" yaml:"taints,omitempty"`
	Unschedulable bool    `json:"unschedulable,omitempty" yaml:"unschedulable,omitempty"`
}

redpajama_set_name: RedPajamaGithub


text:
using SimpleMvc.Framework.Attributes.Method;

namespace SimpleMvc.Framework.Attributes
{
    public class HttpPostAttribute : HttpMethodAttribute
    {
        public override bool IsValid(string requestMethod)
        {
            if (requestMethod.ToUpper().Equals("POST"))
            {
                return true;
            }

            return false;
        }
    }
}


text:
<?php

/**
 * Load the base TDbMetaData class.
 */
Prado::using('System.Data.Common.TDbMetaData');
Prado::using('System.Data.Common.Pgsql.TPgsqlTableInfo');

/**
 * TPgsqlMetaData loads PostgreSQL database table and column information.
 *
 * @author Wei Zhuo <weizho[at]gmail[dot]com>
 * @version $Id: TPgsqlMetaData.php 3031 2011-08-28 06:24:03Z GODZilla0480@gmail.com $
 * @package System.Data.Common.Pgsql
 * @since 3.1
 */
class TPgsqlMetaData extends TDbMetaData
{
	private $_defaultSchema = 'public';

	/**
	 * @return string TDbTableInfo class name.
	 */
	protected function getTableInfoClass()
	{
		return 'TPgsqlTableInfo';
	}

	/**
	 * Quotes a table name for use in a query.
	 * @param string $name table name
	 * @return string the properly quoted table name
	 */
	public function quoteTableName($name)
	{
		return parent::quoteTableName($name, '"', '"');
	}

	/**
	 * Quotes a column name for use in a query.
	 * @param string $name column name
	 * @return string the properly quoted column name
	 */
	public function quoteColumnName($name)
	{
		return parent::quoteColumnName($name, '"', '"');
	}

	/**
	 * Quotes a column alias for use in a query.
	 * @param string $name column alias
	 * @return string the properly quoted column alias
	 */
	public function quoteColumnAlias($name)
	{
		return parent::quoteColumnAlias($name, '"', '"');
	}

	/**
	 * @param string default schema.
	 */
	public function setDefaultSchema($schema)
	{
		$this->_defaultSchema=$schema;
	}

	/**
	 * @return string default schema.
	 */
	public function getDefaultSchema()
	{
		return $this->_defaultSchema;
	}

	/**
	 * @param string table name with optional schema name prefix, uses default schema name prefix is not provided.
	 * @return array tuple as ($schemaName,$tableName)
	 */
	protected function getSchemaTableName($table)
	{
		if(count($parts= explode('.', str_replace('"','',$table))) > 1)
			return array($parts[0], $parts[1]);
		else
			return array($this->getDefaultSchema(),$parts[0]);
	}

	/**
	 * Get the column definitions for given table.
	 * @param string table name.
	 * @return TPgsqlTableInfo table information.
	 */
	protected function createTableInfo($table)
	{
		list($schemaName,$tableName) = $this->getSchemaTableName($table);

		// This query is made much more complex by the addition of the 'attisserial' field.
		// The subquery to get that field checks to see if there is an internally dependent
		// sequence on the field.
		$sql =
<<<EOD
		SELECT
			a.attname,
			pg_catalog.format_type(a.atttypid, a.atttypmod) as type,
			a.atttypmod,
			a.attnotnull, a.atthasdef, adef.adsrc,
			(
				SELECT 1 FROM pg_catalog.pg_depend pd, pg_catalog.pg_class pc
				WHERE pd.objid=pc.oid
				AND pd.classid=pc.tableoid
				AND pd.refclassid=pc.tableoid
				AND pd.refobjid=a.attrelid
				AND pd.refobjsubid=a.attnum
				AND pd.deptype='i'
				AND pc.relkind='S'
			) IS NOT NULL AS attisserial

		FROM
			pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_attrdef adef
			ON a.attrelid=adef.adrelid
			AND a.attnum=adef.adnum
			LEFT JOIN pg_catalog.pg_type t ON a.atttypid=t.oid
		WHERE
			a.attrelid = (SELECT oid FROM pg_catalog.pg_class WHERE relname=:table
				AND relnamespace = (SELECT oid FROM pg_catalog.pg_namespace WHERE
				nspname = :schema))
			AND a.attnum > 0 AND NOT a.attisdropped
		ORDER BY a.attnum
EOD;
		$this->getDbConnection()->setActive(true);
		$command = $this->getDbConnection()->createCommand($sql);
		$command->bindValue(':table', $tableName);
		$command->bindValue(':schema', $schemaName);
		$tableInfo = $this->createNewTableInfo($schemaName, $tableName);
		$index=0;
		foreach($command->query() as $col)
		{
			$col['index'] = $index++;
			$this->processColumn($tableInfo, $col);
		}
		if($index===0)
			throw new TDbException('dbmetadata_invalid_table_view', $table);
		return $tableInfo;
	}

	/**
	 * @param string table schema name
	 * @param string table name.
	 * @return TPgsqlTableInfo
	 */
	protected function createNewTableInfo($schemaName,$tableName)
	{
		$info['SchemaName'] = $this->assertIdentifier($schemaName);
		$info['TableName'] = $this->assertIdentifier($tableName);
		if($this->getIsView($schemaName,$tableName))
			$info['IsView'] = true;
		list($primary, $foreign) = $this->getConstraintKeys($schemaName, $tableName);
		$class = $this->getTableInfoClass();
		return new $class($info,$primary,$foreign);
	}

	/**
	 * @param string table name, schema name or column name.
	 * @return string a valid identifier.
	 * @throws TDbException when table name contains a double quote (").
	 */
	protected function assertIdentifier($name)
	{
		if(strpos($name, '"')!==false)
		{
			$ref = 'http://www.postgresql.org/docs/7.4/static/sql-syntax.html#SQL-SYNTAX-IDENTIFIERS';
			throw new TDbException('dbcommon_invalid_identifier_name', $name, $ref);
		}
		return $name;
	}

	/**
	 * @param string table schema name
	 * @param string table name.
	 * @return boolean true if the table is a view.
	 */
	protected function getIsView($schemaName,$tableName)
	{
		$sql =
<<<EOD
		SELECT count(c.relname) FROM pg_catalog.pg_class c
		LEFT JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace)
		WHERE (n.nspname=:schema) AND (c.relkind = 'v'::"char") AND c.relname = :table
EOD;
		$this->getDbConnection()->setActive(true);
		$command = $this->getDbConnection()->createCommand($sql);
		$command->bindValue(':schema',$schemaName);
		$command->bindValue(':table', $tableName);
		return intval($command->queryScalar()) === 1;
	}

	/**
	 * @param TPgsqlTableInfo table information.
	 * @param array column information.
	 */
	protected function processColumn($tableInfo, $col)
	{
		$columnId = $col['attname']; //use column name as column Id

		$info['ColumnName'] = '"'.$columnId.'"'; //quote the column names!
		$info['ColumnId'] = $columnId;
		$info['ColumnIndex'] = $col['index'];
		if(!$col['attnotnull'])
			$info['AllowNull'] = true;
		if(in_array($columnId, $tableInfo->getPrimaryKeys()))
			$info['IsPrimaryKey'] = true;
		if($this->isForeignKeyColumn($columnId, $tableInfo))
			$info['IsForeignKey'] = true;

		if($col['atttypmod'] > 0)
			$info['ColumnSize'] =  $col['atttypmod'] - 4;
		if($col['atthasdef'])
			$info['DefaultValue'] = $col['adsrc'];
		if($col['attisserial'] || substr($col['adsrc'],0,8) === 'nextval(')
		{
			if(($sequence = $this->getSequenceName($tableInfo, $col['adsrc']))!==null)
			{
				$info['SequenceName'] = $sequence;
				unset($info['DefaultValue']);
			}
		}
		$matches = array();
		if(preg_match('/\((\d+)(?:,(\d+))?+\)/', $col['type'], $matches))
		{
			$info['DbType'] = preg_replace('/\(\d+(?:,\d+)?\)/','',$col['type']);
			if($this->isPrecisionType($info['DbType']))
			{
				$info['NumericPrecision'] = intval($matches[1]);
				if(count($matches) > 2)
					$info['NumericScale'] = intval($matches[2]);
			}
			else
				$info['ColumnSize'] = intval($matches[1]);
		}
		else
			$info['DbType'] = $col['type'];

		$tableInfo->Columns[$columnId] = new TPgsqlTableColumn($info);
	}

	/**
	 * @return string serial name if found, null otherwise.
	 */
	protected function getSequenceName($tableInfo,$src)
	{
		$matches = array();
		if(preg_match('/nextval\([^\']*\'([^\']+)\'[^\)]*\)/i',$src,$matches))
		{
			if(is_int(strpos($matches[1], '.')))
				return $matches[1];
			else
				return $tableInfo->getSchemaName().'.'.$matches[1];
		}
	}

	/**
	 * @return boolean true if column type if "numeric", "interval" or begins with "time".
	 */
	protected function isPrecisionType($type)
	{
		$type = strtolower(trim($type));
		return $type==='numeric' || $type==='interval' || strpos($type, 'time')===0;
	}

	/**
	 * Gets the primary and foreign key column details for the given table.
	 * @param string schema name
	 * @param string table name.
	 * @return array tuple ($primary, $foreign)
	 */
	protected function getConstraintKeys($schemaName, $tableName)
	{
		$sql =
<<<EOD
	SELECT conname, consrc, contype, indkey, indisclustered FROM (
			SELECT
					conname,
					CASE WHEN contype='f' THEN
							pg_catalog.pg_get_constraintdef(oid)
					ELSE
							'CHECK (' || consrc || ')'
					END AS consrc,
					contype,
					conrelid AS relid,
					NULL AS indkey,
					FALSE AS indisclustered
			FROM
					pg_catalog.pg_constraint
			WHERE
					contype IN ('f', 'c')
			UNION ALL
			SELECT
					pc.relname,
					NULL,
					CASE WHEN indisprimary THEN
							'p'
					ELSE
							'u'
					END,
					pi.indrelid,
					indkey,
					pi.indisclustered
			FROM
					pg_catalog.pg_class pc,
					pg_catalog.pg_index pi
			WHERE
					pc.oid=pi.indexrelid
					AND EXISTS (
							SELECT 1 FROM pg_catalog.pg_depend d JOIN pg_catalog.pg_constraint c
							ON (d.refclassid = c.tableoid AND d.refobjid = c.oid)
							WHERE d.classid = pc.tableoid AND d.objid = pc.oid AND d.deptype = 'i' AND c.contype IN ('u', 'p')
			)
	) AS sub
	WHERE relid = (SELECT oid FROM pg_catalog.pg_class WHERE relname=:table
					AND relnamespace = (SELECT oid FROM pg_catalog.pg_namespace
					WHERE nspname=:schema))
	ORDER BY
			1
EOD;
		$this->getDbConnection()->setActive(true);
		$command = $this->getDbConnection()->createCommand($sql);
		$command->bindValue(':table', $tableName);
		$command->bindValue(':schema', $schemaName);
		$primary = array();
		$foreign = array();
		foreach($command->query() as $row)
		{
			switch($row['contype'])
			{
				case 'p':
					$primary = $this->getPrimaryKeys($tableName, $schemaName, $row['indkey']);
					break;
				case 'f':
					if(($fkey = $this->getForeignKeys($row['consrc']))!==null)
						$foreign[] = $fkey;
					break;
			}
		}
		return array($primary,$foreign);
	}

	/**
	 * Gets the primary key field names
	 * @param string pgsql primary key definition
	 * @return array primary key field names.
	 */
	protected function getPrimaryKeys($tableName, $schemaName, $columnIndex)
	{
		$index = join(', ', explode(' ', $columnIndex));
		$sql =
<<<EOD
		SELECT attnum, attname FROM pg_catalog.pg_attribute WHERE
		attrelid=(
			SELECT oid FROM pg_catalog.pg_class WHERE relname=:table AND relnamespace=(
				SELECT oid FROM pg_catalog.pg_namespace WHERE nspname=:schema
			)
		)
				AND attnum IN ({$index})
EOD;
		$command = $this->getDbConnection()->createCommand($sql);
		$command->bindValue(':table', $tableName);
		$command->bindValue(':schema', $schemaName);
//		$command->bindValue(':columnIndex', join(', ', explode(' ', $columnIndex)));
		$primary = array();
		foreach($command->query() as $row)
		{
						$primary[] = $row['attname'];
		}

		return $primary;
	}

	/**
	 * Gets foreign relationship constraint keys and table name
	 * @param string pgsql foreign key definition
	 * @return array foreign relationship table name and keys, null otherwise
	 */
	protected function getForeignKeys($src)
	{
		$matches = array();
		$brackets = '\(([^\)]+)\)';
		$find = "/FOREIGN\s+KEY\s+{$brackets}\s+REFERENCES\s+([^\(]+){$brackets}/i";
		if(preg_match($find, $src, $matches))
		{
			$keys = preg_split('/,\s+/', $matches[1]);
			$fkeys = array();
			foreach(preg_split('/,\s+/', $matches[3]) as $i => $fkey)
				$fkeys[$keys[$i]] = $fkey;
			return array('table' => str_replace('"','',$matches[2]), 'keys' => $fkeys);
		}
	}

	/**
	 * @param string column name.
	 * @param TPgsqlTableInfo table information.
	 * @return boolean true if column is a foreign key.
	 */
	protected function isForeignKeyColumn($columnId, $tableInfo)
	{
		foreach($tableInfo->getForeignKeys() as $fk)
		{
			if(in_array($columnId, array_keys($fk['keys'])))
				return true;
		}
		return false;
	}
}


text:
@implementation GCManager

+ (GCManager *)sharedManager
{
    static GCManager * _sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedManager = [GCManager new];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if(![fileManager fileExistsAtPath:kGCManagerDataPath]) {
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            NSData *saveData = [[NSKeyedArchiver archivedDataWithRootObject:dict] encryptedWithKey:kGCManagerKey];
            [saveData writeToFile:kGCManagerDataPath atomically:YES];
        }
        [_sharedManager initGameCenter];
    });

    return _sharedManager;
}

#pragma mark - Methods

- (void)initGameCenter
{
    // Check for presence of GKLocalPlayer class.
    BOOL localPlayerClassAvailable = (NSClassFromString(@"GKLocalPlayer")) != nil;

    // The device must be running iOS 4.1 or later.
    NSString *reqSysVer = @"4.1";
    NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
    BOOL osVersionSupported = ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending);

    BOOL isGameCenterAPIAvailable = (localPlayerClassAvailable && osVersionSupported);

    if(isGameCenterAPIAvailable) {
        _isGameCenterAvailable = YES;

        [[GKLocalPlayer localPlayer] authenticateWithCompletionHandler:^(NSError *error) {
            if(error == nil) {
                if(![[NSUserDefaults standardUserDefaults] boolForKey:[@"scoresSynced" stringByAppendingString:[[GCManager sharedManager] localPlayerId]]] ||
                   ![[NSUserDefaults standardUserDefaults] boolForKey:[@"achievementsSynced" stringByAppendingString:[[GCManager sharedManager] localPlayerId]]]) {
                    [[GCManager sharedManager] syncGameCenter];
                }
                else {
                    [[GCManager sharedManager] reportSavedScoresAndAchievements];
                }
            }
            else {
                if(error.code == GKErrorNotSupported) {
                    _isGameCenterAvailable = NO;
                }
            }
            NSMutableDictionary * userInfo = [NSMutableDictionary new];
            if (error) [userInfo setObject:error forKey:@"error"];
            [[NSNotificationCenter defaultCenter] postNotificationName:kGCManagerAvailabilityNotification
                                                                object:[GCManager sharedManager]
                                                              userInfo:userInfo];
        }];
    }
}

- (void)syncGameCenter
{
    if(_isGameCenterAvailable) {
        if(![[NSUserDefaults standardUserDefaults] boolForKey:[@"scoresSynced" stringByAppendingString:[[GCManager sharedManager] localPlayerId]]]) {
            if(leaderboards == nil) {
                [GKLeaderboard loadCategoriesWithCompletionHandler:^(NSArray *categories, NSArray *titles, NSError *error) {
                    if(error == nil) {
                        leaderboards = [[NSMutableArray alloc] initWithArray:categories];
                        [[GCManager sharedManager] syncGameCenter];
                    }
                }];
                return;
            }

            if(leaderboards.count > 0) {
                GKLeaderboard *leaderboardRequest = [[GKLeaderboard alloc] initWithPlayerIDs:[NSArray arrayWithObject:[[GCManager sharedManager] localPlayerId]]];
                [leaderboardRequest setCategory:[leaderboards objectAtIndex:0]];
                [leaderboardRequest loadScoresWithCompletionHandler:^(NSArray *scores, NSError *error) {
                    if(error == nil) {
                        if(scores.count > 0) {
                            NSData *GCManagerData = [[NSData dataWithContentsOfFile:kGCManagerDataPath] decryptedWithKey:kGCManagerKey];
                            NSMutableDictionary *plistDict = [NSKeyedUnarchiver unarchiveObjectWithData:GCManagerData];
                            NSMutableDictionary *playerDict = [plistDict objectForKey:[[GCManager sharedManager] localPlayerId]];
                            if(playerDict == nil) {
                                playerDict = [NSMutableDictionary dictionary];
                            }
                            int savedHighScoreValue = 0;
                            NSNumber *savedHighScore = [playerDict objectForKey:leaderboardRequest.localPlayerScore.category];
                            if(savedHighScore != nil) {
                                savedHighScoreValue = [savedHighScore intValue];
                            }
                            [playerDict setObject:[NSNumber numberWithInt:MAX(leaderboardRequest.localPlayerScore.value, savedHighScoreValue)] forKey:leaderboardRequest.localPlayerScore.category];
                            [plistDict setObject:playerDict forKey:[[GCManager sharedManager] localPlayerId]];
                            NSData *saveData = [[NSKeyedArchiver archivedDataWithRootObject:plistDict] encryptedWithKey:kGCManagerKey];
                            [saveData writeToFile:kGCManagerDataPath atomically:YES];
                        }

                        [leaderboards removeObjectAtIndex:0];
                        [[GCManager sharedManager] syncGameCenter];
                    }
                }];
            }
            else {
                [[NSUserDefaults standardUserDefaults] setBool:YES forKey:[@"scoresSynced" stringByAppendingString:[[GCManager sharedManager] localPlayerId]]];
                [[GCManager sharedManager] syncGameCenter];
            }
        }
        else if(![[NSUserDefaults standardUserDefaults] boolForKey:[@"achievementsSynced" stringByAppendingString:[[GCManager sharedManager] localPlayerId]]]) {
            [GKAchievement loadAchievementsWithCompletionHandler:^(NSArray *achievements, NSError *error) {
                if(error == nil) {
                    if(achievements.count > 0) {
                        NSData *GCManagerData = [[NSData dataWithContentsOfFile:kGCManagerDataPath] decryptedWithKey:kGCManagerKey];
                        NSMutableDictionary *plistDict = [NSKeyedUnarchiver unarchiveObjectWithData:GCManagerData];
                        NSMutableDictionary *playerDict = [plistDict objectForKey:[[GCManager sharedManager] localPlayerId]];
                        if(playerDict == nil) {
                            playerDict = [NSMutableDictionary dictionary];
                        }
                        for(GKAchievement *achievement in achievements) {
                            [playerDict setObject:[NSNumber numberWithDouble:achievement.percentComplete] forKey:achievement.identifier];
                        }
                        [plistDict setObject:playerDict forKey:[[GCManager sharedManager] localPlayerId]];
                        NSData *saveData = [[NSKeyedArchiver archivedDataWithRootObject:plistDict] encryptedWithKey:kGCManagerKey];
                        [saveData writeToFile:kGCManagerDataPath atomically:YES];
                    }

                    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:[@"achievementsSynced" stringByAppendingString:[[GCManager sharedManager] localPlayerId]]];
                    [[GCManager sharedManager] syncGameCenter];
                }
            }];
        }
    }
}

- (void)saveAndReportScore:(int)score leaderboard:(NSString *)identifier
{
    if (!_isGameCenterAvailable)
        return;
    NSData *GCManagerData = [[NSData dataWithContentsOfFile:kGCManagerDataPath] decryptedWithKey:kGCManagerKey];
    NSMutableDictionary *plistDict = [NSKeyedUnarchiver unarchiveObjectWithData:GCManagerData];
    NSMutableDictionary *playerDict = [plistDict objectForKey:[[GCManager sharedManager] localPlayerId]];
    if(playerDict == nil) {
        playerDict = [NSMutableDictionary dictionary];
    }
    NSNumber *savedHighScore = [playerDict objectForKey:identifier];
    if(savedHighScore == nil) {
        savedHighScore = [NSNumber numberWithInt:0];
    }
    int savedHighScoreValue = [savedHighScore intValue];
    if(score > savedHighScoreValue) {
        [playerDict setObject:[NSNumber numberWithInt:score] forKey:identifier];
        [plistDict setObject:playerDict forKey:[[GCManager sharedManager] localPlayerId]];
        NSData *saveData = [[NSKeyedArchiver archivedDataWithRootObject:plistDict] encryptedWithKey:kGCManagerKey];
        [saveData writeToFile:kGCManagerDataPath atomically:YES];
    }

    if([[GCManager sharedManager] isGameCenterAvailable]) {
        if([GKLocalPlayer localPlayer].authenticated) {
            GKScore *gkScore = [[GKScore alloc] initWithCategory:identifier];
            gkScore.value = score;
            [gkScore reportScoreWithCompletionHandler:^(NSError *error) {
                NSDictionary *dict = nil;
                if(error == nil) {
                    dict = [NSDictionary dictionary];
                }
                else {
                    dict = [NSDictionary dictionaryWithObject:error.localizedDescription forKey:@"error"];
                    [[GCManager sharedManager] saveScoreToReportLater:gkScore];
                }
                [[NSNotificationCenter defaultCenter] postNotificationName:kGCManagerReportScoreNotification
                                                                    object:[GCManager sharedManager]
                                                                  userInfo:dict];
            }];
        }
    }
}

- (void)saveAndReportAchievement:(NSString *)identifier percentComplete:(double)percentComplete
{
    if (!_isGameCenterAvailable)
        return;
    NSData *GCManagerData = [[NSData dataWithContentsOfFile:kGCManagerDataPath] decryptedWithKey:kGCManagerKey];
    NSMutableDictionary *plistDict = [NSKeyedUnarchiver unarchiveObjectWithData:GCManagerData];
    NSMutableDictionary *playerDict = [plistDict objectForKey:[[GCManager sharedManager] localPlayerId]];
    if(playerDict == nil) {
        playerDict = [NSMutableDictionary dictionary];
    }
    NSNumber *savedPercentComplete = [playerDict objectForKey:identifier];
    if(savedPercentComplete == nil) {
        savedPercentComplete = [NSNumber numberWithDouble:0];
    }
    double savedPercentCompleteValue = [savedPercentComplete doubleValue];
    if(percentComplete > savedPercentCompleteValue) {
        [playerDict setObject:[NSNumber numberWithDouble:percentComplete] forKey:identifier];
        [plistDict setObject:playerDict forKey:[[GCManager sharedManager] localPlayerId]];
        NSData *saveData = [[NSKeyedArchiver archivedDataWithRootObject:plistDict] encryptedWithKey:kGCManagerKey];
        [saveData writeToFile:kGCManagerDataPath atomically:YES];
    }

    if([[GCManager sharedManager] isGameCenterAvailable]) {
        if([GKLocalPlayer localPlayer].authenticated) {
            GKAchievement *achievement = [[GKAchievement alloc] initWithIdentifier:identifier];
            achievement.percentComplete = percentComplete;
            [achievement reportAchievementWithCompletionHandler:^(NSError *error) {
                NSDictionary *dict = nil;
                if(error == nil) {
                    dict = [NSDictionary dictionary];
                }
                else {
                    dict = [NSDictionary dictionaryWithObject:error.localizedDescription forKey:@"error"];
                    [[GCManager sharedManager] saveAchievementToReportLater:identifier percentComplete:percentComplete];
                }
                [[NSNotificationCenter defaultCenter] postNotificationName:kGCManagerReportAchievementNotification
                                                                    object:[GCManager sharedManager]
                                                                  userInfo:dict];
            }];
        }
    }
}

- (void)saveScoreToReportLater:(GKScore *)score
{
    if (!_isGameCenterAvailable)
        return;
    NSData *scoreData = [NSKeyedArchiver archivedDataWithRootObject:score];
    NSData *GCManagerData = [[NSData dataWithContentsOfFile:kGCManagerDataPath] decryptedWithKey:kGCManagerKey];
    NSMutableDictionary *plistDict = [NSKeyedUnarchiver unarchiveObjectWithData:GCManagerData];
    NSMutableArray *savedScores = [plistDict objectForKey:@"SavedScores"];
    if(savedScores != nil) {
        [savedScores addObject:scoreData];
    }
    else {
        savedScores = [NSMutableArray arrayWithObject:scoreData];
    }
    [plistDict setObject:savedScores forKey:@"SavedScores"];
    NSData *saveData = [[NSKeyedArchiver archivedDataWithRootObject:plistDict] encryptedWithKey:kGCManagerKey];
    [saveData writeToFile:kGCManagerDataPath atomically:YES];
}

- (void)saveAchievementToReportLater:(NSString *)identifier percentComplete:(double)percentComplete
{
    if (!_isGameCenterAvailable)
        return;
    NSData *GCManagerData = [[NSData dataWithContentsOfFile:kGCManagerDataPath] decryptedWithKey:kGCManagerKey];
    NSMutableDictionary *plistDict = [NSKeyedUnarchiver unarchiveObjectWithData:GCManagerData];
    NSMutableDictionary *playerDict = [plistDict objectForKey:[[GCManager sharedManager] localPlayerId]];
    if(playerDict != nil) {
        NSMutableDictionary *savedAchievements = [playerDict objectForKey:@"SavedAchievements"];
        if(savedAchievements != nil) {
            double savedPercentCompleteValue = 0;
            NSNumber *savedPercentComplete = [savedAchievements objectForKey:identifier];
            if(savedPercentComplete != nil) {
                savedPercentCompleteValue = [savedPercentComplete doubleValue];
            }
            savedPercentComplete = [NSNumber numberWithDouble:percentComplete + savedPercentCompleteValue];
            [savedAchievements setObject:savedPercentComplete forKey:identifier];
        }
        else {
            savedAchievements = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithDouble:percentComplete], identifier, nil];
            [playerDict setObject:savedAchievements forKey:@"SavedAchievements"];
        }
    }
    else {
        NSMutableDictionary *savedAchievements = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithDouble:percentComplete], identifier, nil];
        playerDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:savedAchievements, @"SavedAchievements", nil];
    }
    [plistDict setObject:playerDict forKey:[[GCManager sharedManager] localPlayerId]];
    NSData *saveData = [[NSKeyedArchiver archivedDataWithRootObject:plistDict] encryptedWithKey:kGCManagerKey];
    [saveData writeToFile:kGCManagerDataPath atomically:YES];
}

- (int)highScoreForLeaderboard:(NSString *)identifier
{
    if (!_isGameCenterAvailable)
        return -1;
    NSData *GCManagerData = [[NSData dataWithContentsOfFile:kGCManagerDataPath] decryptedWithKey:kGCManagerKey];
    NSMutableDictionary *plistDict = [NSKeyedUnarchiver unarchiveObjectWithData:GCManagerData];
    NSMutableDictionary *playerDict = [plistDict objectForKey:[[GCManager sharedManager] localPlayerId]];
    if(playerDict != nil) {
        NSNumber *savedHighScore = [playerDict objectForKey:identifier];
        if(savedHighScore != nil) {
            return [savedHighScore intValue];
        }
    }
    return 0;
}

- (NSDictionary *)highScoreForLeaderboards:(NSArray *)identifiers
{
    if (!_isGameCenterAvailable)
        return nil;
    NSData *GCManagerData = [[NSData dataWithContentsOfFile:kGCManagerDataPath] decryptedWithKey:kGCManagerKey];
    NSMutableDictionary *plistDict = [NSKeyedUnarchiver unarchiveObjectWithData:GCManagerData];
    NSMutableDictionary *playerDict = [plistDict objectForKey:[[GCManager sharedManager] localPlayerId]];
    NSMutableDictionary *highScores = [[NSMutableDictionary alloc] initWithCapacity:identifiers.count];
    for(NSString *identifier in identifiers) {
        if(playerDict != nil) {
            NSNumber *savedHighScore = [playerDict objectForKey:identifier];
            if(savedHighScore != nil) {
                [highScores setObject:[NSNumber numberWithInt:[savedHighScore intValue]] forKey:identifier];
                continue;
            }
        }
        [highScores setObject:[NSNumber numberWithInt:0] forKey:identifier];
    }

    NSDictionary *highScoreDict = [NSDictionary dictionaryWithDictionary:highScores];

    return highScoreDict;
}

- (double)progressForAchievement:(NSString *)identifier
{
    if (!_isGameCenterAvailable)
        return -1;
    NSData *GCManagerData = [[NSData dataWithContentsOfFile:kGCManagerDataPath] decryptedWithKey:kGCManagerKey];
    NSMutableDictionary *plistDict = [NSKeyedUnarchiver unarchiveObjectWithData:GCManagerData];
    NSMutableDictionary *playerDict = [plistDict objectForKey:[[GCManager sharedManager] localPlayerId]];
    if(playerDict != nil) {
        NSNumber *savedPercentComplete = [playerDict objectForKey:identifier];
        if(savedPercentComplete != nil) {
            return [savedPercentComplete doubleValue];
        }
    }
    return 0;
}

- (NSDictionary *)progressForAchievements:(NSArray *)identifiers
{
    if (!_isGameCenterAvailable)
        return nil;
    NSData *GCManagerData = [[NSData dataWithContentsOfFile:kGCManagerDataPath] decryptedWithKey:kGCManagerKey];
    NSMutableDictionary *plistDict = [NSKeyedUnarchiver unarchiveObjectWithData:GCManagerData];
    NSMutableDictionary *playerDict = [plistDict objectForKey:[[GCManager sharedManager] localPlayerId]];
    NSMutableDictionary *percent = [[NSMutableDictionary alloc] initWithCapacity:identifiers.count];
    for(NSString *identifier in identifiers) {
        if(playerDict != nil) {
            NSNumber *savedPercentComplete = [playerDict objectForKey:identifier];
            if(savedPercentComplete != nil) {
                [percent setObject:[NSNumber numberWithDouble:[savedPercentComplete doubleValue]] forKey:identifier];
                continue;
            }
        }
        [percent setObject:[NSNumber numberWithDouble:0] forKey:identifier];
    }

    NSDictionary *percentDict = [NSDictionary dictionaryWithDictionary:percent];

    return percentDict;
}

- (void)reportSavedScoresAndAchievements
{
    if(_isGameCenterAvailable) {
        GKScore *gkScore = nil;

        NSData *GCManagerData = [[NSData dataWithContentsOfFile:kGCManagerDataPath] decryptedWithKey:kGCManagerKey];
        NSMutableDictionary *plistDict = [NSKeyedUnarchiver unarchiveObjectWithData:GCManagerData];
        NSMutableArray *savedScores = [plistDict objectForKey:@"SavedScores"];
        if(savedScores != nil) {
            if(savedScores.count > 0) {
                gkScore = [NSKeyedUnarchiver unarchiveObjectWithData:[savedScores objectAtIndex:0]];
                [savedScores removeObjectAtIndex:0];
                [plistDict setObject:savedScores forKey:@"SavedScores"];
                NSData *saveData = [[NSKeyedArchiver archivedDataWithRootObject:plistDict] encryptedWithKey:kGCManagerKey];
                [saveData writeToFile:kGCManagerDataPath atomically:YES];
            }
        }

        if(gkScore != nil) {
            [gkScore reportScoreWithCompletionHandler:^(NSError *error) {
                if(error == nil) {
                    [[GCManager sharedManager] reportSavedScoresAndAchievements];
                }
                else {
                    [[GCManager sharedManager] saveScoreToReportLater:gkScore];
                }
            }];
        }
        else {
            if([GKLocalPlayer localPlayer].authenticated) {
                NSString *identifier = nil;
                double percentComplete = 0;

                NSData *GCManagerData = [[NSData dataWithContentsOfFile:kGCManagerDataPath] decryptedWithKey:kGCManagerKey];
                NSMutableDictionary *plistDict = [NSKeyedUnarchiver unarchiveObjectWithData:GCManagerData];
                NSMutableDictionary *playerDict = [plistDict objectForKey:[[GCManager sharedManager] localPlayerId]];
                if(playerDict != nil) {
                    NSMutableDictionary *savedAchievements = [playerDict objectForKey:@"SavedAchievements"];
                    if(savedAchievements != nil) {
                        if(savedAchievements.count > 0) {
                            identifier = [[savedAchievements allKeys] objectAtIndex:0];
                            percentComplete = [[savedAchievements objectForKey:identifier] doubleValue];
                            [savedAchievements removeObjectForKey:identifier];
                            [playerDict setObject:savedAchievements forKey:@"SavedAchievements"];
                            [plistDict setObject:playerDict forKey:[[GCManager sharedManager] localPlayerId]];
                            NSData *saveData = [[NSKeyedArchiver archivedDataWithRootObject:plistDict] encryptedWithKey:kGCManagerKey];
                            [saveData writeToFile:kGCManagerDataPath atomically:YES];
                        }
                    }
                }

                if(identifier != nil) {
                    GKAchievement *achievement = [[GKAchievement alloc] initWithIdentifier:identifier];
                    achievement.percentComplete = percentComplete;
                    [achievement reportAchievementWithCompletionHandler:^(NSError *error) {
                        if(error == nil) {
                            [[GCManager sharedManager] reportSavedScoresAndAchievements];
                        }
                        else {
                            [[GCManager sharedManager] saveAchievementToReportLater:achievement.identifier percentComplete:achievement.percentComplete];
                        }
                    }];
                }
            }
        }
    }
}

- (void) resetAchievements
{
    if(_isGameCenterAvailable) {
        [GKAchievement resetAchievementsWithCompletionHandler:^(NSError *error) {
            NSDictionary *dict = nil;
            if(error == nil) {
                dict = [NSDictionary dictionary];
            }
            else {
                dict = [NSDictionary dictionaryWithObject:error forKey:@"error"];
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:kGCManagerResetAchievementNotification
                                                                object:[GCManager sharedManager]
                                                              userInfo:dict];
        }];
    }
}

- (NSString *)localPlayerId
{
    if(_isGameCenterAvailable) {
        if([GKLocalPlayer localPlayer].authenticated) {
            return [GKLocalPlayer localPlayer].playerID;
        }
    }
    return @"unknownPlayer";
}

- (GKLeaderboardViewController *) gkLeaderBoardControllerWithTimeScope: (GKLeaderboardTimeScope) scope
                                                              category: (NSString *) category
                                                              delegate: (id<GKLeaderboardViewControllerDelegate>) delegate
{
    GKLeaderboardViewController * leaderboardViewController = [GKLeaderboardViewController new];
    leaderboardViewController.timeScope = GKLeaderboardTimeScopeAllTime;
    leaderboardViewController.leaderboardDelegate = delegate;
    leaderboardViewController.category = category;
    return leaderboardViewController;
}

- (GKAchievementViewController *) gkAchievementControllerWithDelegate: (id<GKAchievementViewControllerDelegate>) delegate
{
    GKAchievementViewController *achievementViewController = [GKAchievementViewController new];
    achievementViewController.achievementDelegate = delegate;
    return achievementViewController;
}

@end


text:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

    <script>
        function Promise(executor) {
            let self = this
            this.status = 'pending' //当前状态
            this.value = undefined  //存储成功的值
            this.reason = undefined //存储失败的原因
            this.onFullfilledCallback=undefined;
            this.onRejectedCallback=undefined;
            function resolve(value) {
                if (self.status == 'pending') {
                    self.status = 'resolved'
                    self.value = value;
                    console.log( self.onFullfilledCallback)
                    self.onFullfilledCallback(value)
                }
            }
            function reject(error) {
                if (self.status == 'pending') {
                    self.status = 'rejected'
                    self.reason = error
                    self.onRejectedCallback(error)
                }
            }
            executor(resolve, reject)
        }
        Promise.prototype.then = function (infulfilled, inrejected) {
            //由status決定,只有一个方法会被执行
            if (this.status == 'resolved') {
                infulfilled(this.value)
            }
            if (this.status == 'rejected') {
                inrejected(this.reason)
            }
            if(this.status == 'pending'){
                console.log(111,infulfilled)

                this.onFullfilledCallback = infulfilled;
                this.onRejectedCallback =inrejected;
            }
        }
        let p = new Promise(function (resolve, reject) {
            setTimeout(() => {
                resolve(100)
            }, 1000)
        })
        //控制台没有打印任何东西
        p.then(function (data) {
            console.log(data, 'resolve')
        }, function (error) {
            console.log(error, 'reject')
        })

    </script>

</body>

</html>


text:
<?php
namespace Roots\Sage\Extras;
use Roots\Sage\Setup;

function body_class($classes) {
  // Add page slug if it doesn't exist
  if (is_single() || is_page() && !is_front_page()) {
    if (!in_array(basename(get_permalink()), $classes)) {
      $classes[] = basename(get_permalink());
    }
  }

  // Add class if sidebar is active
  if (Setup\display_sidebar()) {
    $classes[] = 'sidebar-primary';
  }

  return $classes;
}
add_filter('body_class', __NAMESPACE__ . '\\body_class');

/**
 * Clean up the_excerpt()
 */
function excerpt_more() {
  return ' … ' . __('Continued', 'sage') . '';
}
add_filter('excerpt_more', __NAMESPACE__ . '\\excerpt_more');

function get_post_args($category) {

    $labels = array(
        'name'               => _x( $category, 'post type general name', 'your-plugin-textdomain' ),
        'singular_name'      => _x( $category, 'post type singular name', 'your-plugin-textdomain' ),
        'menu_name'          => _x( $category, 'admin menu', 'your-plugin-textdomain' ),
        'name_admin_bar'     => _x( $category, ' add new on admin bar', 'your-plugin-textdomain' ),
        'add_new'            => _x( 'Add New ', $category, 'your-plugin-textdomain' ),
        'add_new_item'       => __( 'Add New '. $category, 'your-plugin-textdomain' ),
        'new_item'           => __( 'New ' . $category, 'your-plugin-textdomain' ),
        'edit_item'          => __( 'Edit ' . $category, 'your-plugin-textdomain' ),
        'view_item'          => __( 'View ' . $category, 'your-plugin-textdomain' ),
        'all_items'          => __( 'All '.$category, 'your-plugin-textdomain' ),
        'search_items'       => __( "Search $category", 'your-plugin-textdomain' ),
        'parent_item_colon'  => __( "Parent $category".":", 'your-plugin-textdomain' ),
        'not_found'          => __( 'No '.$category.' found.', 'your-plugin-textdomain' ),
        'not_found_in_trash' => __( 'No '.$category.' found in Trash.', 'your-plugin-textdomain' )
    );

    $args = array(
        'labels'             => $labels,
               'description'        => __( 'Description.', 'your-plugin-textdomain' ),
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'query_var'          => true,
        // 'rewrite'            => array( 'slug' => $category ),
        'capability_type'    => 'post',
        'has_archive'        => true,
        'hierarchical'       => true,
        'menu_position'      => null,
        'supports'           => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments', 'custom-fields' )
    );

    return $args;
}


text:
var hyperlog = require('../')
var memdb = require('memdb')

var log = hyperlog(memdb())
var clone = hyperlog(memdb())

var sync = function (a, b) {
  a = a.createReplicationStream({mode: 'push'})
  b = b.createReplicationStream({mode: 'pull'})

  a.on('push', function () {
    console.log('a pushed')
  })

  a.on('pull', function () {
    console.log('a pulled')
  })

  a.on('end', function () {
    console.log('a ended')
  })

  b.on('push', function () {
    console.log('b pushed')
  })

  b.on('pull', function () {
    console.log('b pulled')
  })

  b.on('end', function () {
    console.log('b ended')
  })

  a.pipe(b).pipe(a)
}

clone.createReadStream({live: true}).on('data', function (data) {
  console.log('change: (%d) %s', data.change, data.key)
})

log.add(null, 'hello', function (err, node) {
  if (err) throw err
  log.add(node, 'world', function (err, node) {
    if (err) throw err
    sync(log, clone)
    log.add(null, 'meh')
  })
})


text:
import Members from '../index';
import { shallow } from 'enzyme';
import { shallowToJson } from 'enzyme-to-json';
import React from 'react';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { initialState } from '../reducer';

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

describe('<Members />', () => {
  it('should render with default props', () => {
    const store = mockStore(initialState);
    const wrapper = shallow(
      <Members store={store} />
    );
    expect(shallowToJson(wrapper)).toMatchSnapshot();
  });
});


text:
/*
  This software is provided 'as-is', without any express or implied
  warranty.  In no event will the authors be held liable for any damages
  arising from the use of this software.

  Permission is granted to anyone to use this software for any purpose,
  including commercial applications, and to alter it and redistribute it
  freely, subject to the following restrictions:

  1. The origin of this software must not be misrepresented; you must not
     claim that you wrote the original software. If you use this software
     in a product, an acknowledgment in the product documentation would be
     appreciated but is not required.
  2. Altered source versions must be plainly marked as such, and must not be
     misrepresented as being the original software.
  3. This notice may not be removed or altered from any source distribution.

  Ronen Ness
  ronenness@gmail.com

*/

#pragma once
#include <math.h>
#include <stdlib.h>

namespace Ness
{
	#define PI 3.14159265f
	#define DEGREE_TO_RADIAN(__degree) (__degree * (PI/180.0f))
	#define RADIAN_TO_DEGREE(__radian) (__radian * (180.0f/PI))
	#define POW2(__val) ((__val)*(__val))

	class Math
	{
	public:

		// convert degree to radian
		NESSENGINE_API inline static float degree_to_radian(int degree)
		{
			return (float)DEGREE_TO_RADIAN(degree);
		}

		// convert degree to radian
		NESSENGINE_API inline static int radian_to_degree(float radian)
		{
			return (int)RADIAN_TO_DEGREE(radian);
		}

		// constrain angle to be between 0 to 360
		NESSENGINE_API inline static int constrain_angle_0_360(int x)
		{
			x = (int)fmod((float)x, (float)360);
			if (x < 0) x += 360;
			return x;
		}

		// constrain angle to be between -180 to 180
		NESSENGINE_API inline static int constrain_angle_180(int x)
		{
			x = (int)fmod((float)x + 180, (float)360);
			if (x < 0) x += 360;
			return x - 180;
		}

		// return a random float number between min and max
		NESSENGINE_API inline static float rand_float(float min = 0.0f, float max = 1.0f)
		{
			return min + static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/(max-min)));
		}

		// return a random int number between min and max
		NESSENGINE_API inline static int rand_int(unsigned int min = 0, unsigned int max = 100)
		{
			return min + (rand() % (max - min));
		}

		// return either +1 or -1
		NESSENGINE_API inline static int rand_direction()
		{
			return (rand() % 100) < 50 ? 1 : -1;
		}
	};
};


text:
package com.alejandrocelaya.fragmentos;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by cta on 27/04/2015.
 */
public class Fragmento2 extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment2, container, false);
    }
}


text:
public class NegativeProcessor implements Chain {

	private Chain nextInChain;

	public void setNext(Chain c) {
		nextInChain = c;
	}

	public void process(Number request) {
		if (request.getNumber() < 0) {
			System.out.println("NegativeProcessor : " + request.getNumber());
		} else {
			nextInChain.process(request);
		}
	}
}


text:
class AppDelegate

  def applicationDidFinishLaunching(notification)
    NSApp.mainMenu = MainMenu.new.menu

    @controller = TrackWindowController.alloc.init
    @controller.showWindow(self)
    @controller.window.orderFrontRegardless
  end

end


text:
[Docker Hub](https://registry.hub.docker.com/u/jairhenrique/silvia/)

![Silvia](http://i.imgur.com/vDhxGJE.jpg?1)

A base Docker image with:
 - python2.7
 - python2.7-dev
 - python-setuptools
 - pip
 - libmysqlclient-dev
 - supervisor
 - nginx
 - newrelic-sysmond


text:
% Creates new portfolio
%
%
% Creates new empty portfolio.
% To add positions use portfolio_addPosition( ).
% To remove positions use portfolio_removePosition( ).
% Function connect() should be called before any other requests to the server are made.
%
% Usage
%
% portfolio_create(index, fromTime, toTime)
% portfolio_create(priceDataIx)
%
% index
%     Index symbol that should be used in the Single Index Model. Defaults to "SPY".
% fromTime
%     Start of market data interval in "yyyy-MM-dd hh:mm:ss" format when internal market data is used.
%    Offset from last available date/time by N days is denoted as "t-N" (e.g. "t-7" denotes offset by 7 days).
% toTime
%     End of market data interval in "yyyy-MM-dd hh:mm:ss" format when internal market data is used.
%    Offset from last available date/time by N days is denoted as "t-N" (e.g. "t-7" denotes offset by 7 days).
% priceDataIx
%     Vector of (time, price) observations for market index asset when external market data is used.
%
% Return Value
%
% portfolio object
%
% Note
%
% PortfolioEffect - Matlab Interface to Quant API
%
% Copyright (C) 2010 - 2015 Snowfall Systems, Inc.
%
%
% Examples
%
% data_goog=importdata('data_goog.mat');
% data_aapl=importdata('data_aapl.mat');
% data_spy=importdata('data_spy.mat');
% portfolioExample=portfolio_create('priceDataIx',data_spy);
% portfolio_addPosition(portfolioExample,'GOOG',100,'priceData',data_goog);
% portfolio_addPosition(portfolioExample,'AAPL',300,'priceData',data_aapl);
% portfolio_addPosition(portfolioExample,'SPY',150,'priceData',data_spy);
% portfolio_settings(portfolioExample,'portfolioMetricsMode','price','windowLength','3600s');
% portfolioExample
%
% portfolioExample=portfolio_create('priceDataIx',data_spy);
% portfolio_settings(portfolioExample,'windowLength','3600s');
% portfolio_addPosition(portfolioExample,'GOOG',[100,200],'time',[1412256601000,1412266600000],'priceData',data_goog) ;
% portfolio_addPosition(portfolioExample,'AAPL',[300,150],'time',[1412266600000,1412276600000],'priceData',data_aapl) ;
% portfolio_addPosition(portfolioExample,'SPY',150,'priceData',data_spy);
% portfolioExample
%
% portfolioExample=portfolio_create('index','SPY','fromTime','2014-09-10 09:30:01','toTime','2014-09-14 16:00:00');
% portfolio_addPosition(portfolioExample,'GOOG',200);
% portfolio_addPosition(portfolioExample,'AAPL',100);
% portfolio_addPosition(portfolioExample,'SPY',100);
% portfolio_settings(portfolioExample,'portfolioMetricsMode','price','windowLength','3600s');
% portfolioExample
%
% portfolioExample=portfolio_create('index','SPY','fromTime','2014-10-02 09:30:01','toTime','2014-10-02 16:00:00');
% portfolio_addPosition(portfolioExample,'GOOG',[100,200],'time',[1412256601000,1412266600000]);
% portfolio_addPosition(portfolioExample,'AAPL',100,'priceData',data_aapl);
% portfolio_addPosition(portfolioExample,'SPY',100);
% portfolio_settings(portfolioExample,'windowLength','3600s');
% portfolioExample
%
% portfolioExample=portfolio_create('index','SPY','fromTime','t-7','toTime','t');
% portfolio_addPosition(portfolioExample,'GOOG',200);
% portfolio_addPosition(portfolioExample,'AAPL',100);
% portfolio_addPosition(portfolioExample,'SPY',100);
% portfolio_settings(portfolioExample,'portfolioMetricsMode','price','windowLength','3600s');
% portfolioExample
%
% dateStart = '2014-11-17 09:30:00';
% dateEnd = '2014-11-19 16:00:00';
% portfolioExample=portfolio_create('index','SPY','fromTime',dateStart ,'toTime',dateEnd );
% portfolio_addPosition(portfolioExample,'AAPL',100);
% portfolio_addPosition(portfolioExample,'C',300);
% portfolio_addPosition(portfolioExample,'GOOG',150);
% util_plot2d(portfolio_variance(portfolioExample),'Portfolio Variance')
function [portfolio] = portfolio_create(varargin)

global clientConnection
if ~util_validateConnection()
    return;
end

if isa(varargin{1},'portfolioContainer')
    portfolio=portfolioContainer();
    portfolio_create=com.portfolioeffect.quant.client.portfolio.Portfolio(varargin{1}.java);
    portfolio=setJava(portfolio,portfolio_create);
else
    p = inputParser;
    defaultIndex = 'SPY';
    defaultFromTime = true;
    defaultToTime = true;
    defaultPriceDataIx = true;

    addParamValue(p,'index',defaultIndex,@ischar);
    addParamValue(p,'fromTime',defaultFromTime,@ischar);
    addParamValue(p,'toTime',defaultToTime,@ischar);
    addParamValue(p,'priceDataIx',defaultPriceDataIx,@isnumeric);

    parse(p,varargin{:});
    portfolio=portfolioContainer();
    portfolio_create=com.portfolioeffect.quant.client.portfolio.Portfolio(clientConnection);
    if ischar(p.Results.fromTime) && ischar(p.Results.toTime) && p.Results.priceDataIx
        Results=portfolio_create.setFromTime(p.Results.fromTime);
        if Results.hasError()
            disp(Results.getErrorMessage())
            error(char(Results.getErrorMessage()));
        end
        Results=portfolio_create.setToTime(p.Results.toTime);
        if Results.hasError()
            disp(Results.getErrorMessage())
            error(char(Results.getErrorMessage()));
        end
        Results=portfolio_create.addIndex(p.Results.index);
    elseif p.Results.fromTime && p.Results.toTime && isnumeric(p.Results.priceDataIx)
        data=p.Results.priceDataIx;
        Results=portfolio_create.addIndex(double(data(:,2)),int64(data(:,1)));
    end
    if Results.hasError()
        msgbox(char(Results.getErrorMessage()));
        error(char(Results.getErrorMessage()));
    end
    portfolio=setJava(portfolio,portfolio_create);
    portfolio_defaultSettings(portfolio)
end
end


text:
require 'RMagick'
require 'kaleidoscope/version'

require 'kaleidoscope/railtie' if defined?(Rails)

require 'kaleidoscope/configuration'
require 'kaleidoscope/color'
require 'kaleidoscope/instance_methods'
require 'kaleidoscope/logger'
require 'kaleidoscope/glue'

module Kaleidoscope
  extend Logger

  def self.options
    @options ||= {
      log: true
    }
  end

  module ClassMethods
    def has_colors
      include InstanceMethods

      after_commit :generate_colors
      after_destroy :destroy_colors
    end

    def matching_color(hex)
      hex = hex.delete('#').downcase
      query = "#{color_table_name}.reference_color = ?"
      photos = self.joins(color_table_name.to_sym).where(query, hex).order("frequency DESC")
      photos
    end

    private

    def class_name
      self.name
    end

    def class_table_name
      "#{class_name}".tableize.singularize
    end

    def color_key
      "#{class_name}_color_id".downcase
    end

    def color_class_name
      "#{class_name}Color"
    end

    def color_table_name
      "#{class_table_name}_colors"
    end

    def color_class
      Object.const_get(color_class_name)
    end
  end
end


text:
require "circleci_notify/version"
require "circleci_notify/notifier"

module CircleciNotify
  def self.run
    notifier = CircleciNotify::Notifier.new(ARGV.first)
    notifier.notify
  end
end


text:
<!DOCTYPE html>

  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title>

       · Carl V. Lewis

  </title>

  <link rel="stylesheet" href="/public/css/poole.css">
  <link rel="stylesheet" href="/public/css/syntax.css">
  <link rel="stylesheet" href="/public/css/lanyon.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=PT+Serif:400,400italic,700%7CPT+Sans:400">

  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/apple-touch-icon-precomposed.png">
  <link rel="shortcut icon" href="/public/favicon.ico">

  <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">

<input type="checkbox" class="sidebar-checkbox" id="sidebar-checkbox">

Data and visual journalist; UX designer and full-stack dev.; digital educator.

    Home

          About

    Download
    GitHub project
    Currently v

      © 2015. All rights reserved.

            Carl V. Lewis

Recent Posts

        April 05, 2012

Critique: "Salubrious Nation: a game-y look at U.S. health"

In keeping with our recent weekly reading about the growing 'gamification' of data, I wanted to focus my critique this week on a map-styled data-driven game made my a group of researchers at Rutgers University called Salubrious Nation. The game at...

        April 04, 2012

Why news organizations should stop differeniating blogs from articles

    Andy Boyle (@andymboyle) of The Boston Globe made an impassioned plea to news organizations earlier this week that they stop differentiating between blogs and articles because they're both equally forms of content. Someone's been needing to pu...

        April 03, 2012

INTERACTIVE: Why is the South the most obese part of the country? Five theories

This map displays the obesity rate of each U.S. state in 2010. The darker shade red represents a higher percentage of obese residents, while the green represents states with lower obesity rates. Click on each state to see the exact totals of each ...

        April 03, 2012

Critique: Curbwise.com

    Lately I've been trying to get my feet wet with Django, an open-source Python web framework that's well-suited to producing complex news apps under  tight deadlines. I haven't had enough free time yet to get into the nitty gritty of it, but I'...

        April 03, 2012

On the importance of localism

A decade before the rise of the Internet set in motion the disruption of legacy news business models, Kaniss foresaw the growing need for local and regional news to unite increasingly fragmented, suburbanized communities.

      Newer Posts

      Older Posts


text:
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/include/autoprepend.php');
/* [Begin patch] */

// patch de migration
if (!ispatched('news_theme')){
	$rs = $db->Execute('SHOW COLUMNS FROM `news_theme`');
	if ($rs) {
		$names = Array();
		while(!$rs->EOF) {
			$names[] = $rs->fields["Field"];
			$rs->MoveNext();
		}
		if (!in_array('theme_abon_criteres', $names)) {
			$rs = $db->Execute("ALTER TABLE `news_theme` ADD `theme_abon_criteres` ENUM ('Y','N') CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL DEFAULT 'N' AFTER `theme_libelle`;");
		}
		if (!in_array('theme_abon_multiple', $names)) {
			$rs = $db->Execute("ALTER TABLE `news_theme` ADD `theme_abon_multiple` ENUM ('Y','N') CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL DEFAULT 'N' AFTER `theme_abon_criteres`;");
		}
		if (!in_array('theme_allow_edit', $names)) {
			$rs = $db->Execute("ALTER TABLE `news_theme` ADD `theme_allow_edit` ENUM ('Y','N') CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL DEFAULT 'Y' AFTER `theme_abon_criteres`;");
		}
	}
}

/* [End patch] */
if(file_exists($_SERVER['DOCUMENT_ROOT'].'/include/bo/class/news_theme.class.php')  && (strpos(__FILE__,'/include/bo/class/news_theme.class.php')===FALSE) ){
		include_once($_SERVER['DOCUMENT_ROOT'].'/include/bo/class/news_theme.class.php');
}else{
/*======================================

objet de BDD news_theme :: class news_theme

SQL mySQL:

DROP TABLE IF EXISTS news_theme;
CREATE TABLE news_theme
(
	theme_id			int (11) PRIMARY KEY not null,
	theme_libelle			varchar (255),
	theme_abon_criteres			enum ('Y','N') not null default 'N',
	theme_allow_edit			enum ('Y','N') not null default 'Y',
	theme_abon_multiple			enum ('Y','N') not null default 'N',
	theme_html_fichier			varchar (255),
	theme_date_crea			date,
	theme_statut			int (11) not null
)

SQL Oracle:

DROP TABLE news_theme
CREATE TABLE news_theme
(
	theme_id			number (11) constraint theme_pk PRIMARY KEY not null,
	theme_libelle			varchar2 (255),
	theme_abon_criteres			enum ('Y','N') not null default 'N',
	theme_allow_edit			enum ('Y','N') not null default 'Y',
	theme_abon_multiple			enum ('Y','N') not null default 'N',
	theme_html_fichier			varchar2 (255),
	theme_date_crea			date,
	theme_statut			number (11) not null
)

<?xml version="1.0" encoding="ISO-8859-1" ?>
<class name="news_theme" libelle="Catégorie" prefix="theme" display="libelle" abstract="libelle">
<item name="id" type="int" length="11" isprimary="true" notnull="true" default="-1" list="true" order="true" />
<item name="libelle" libelle="Libellé de la catégorie" type="varchar" length="255" list="true" order="true" nohtml="true" />
<item name="abon_criteres" libelle="Utiliser les critères d'abonnement" type="enum" length="'Y','N'" notnull="true" default="N" />
<item name="allow_edit" libelle="Autoriser l'édition wysiwyg" type="enum" length="'Y','N'" notnull="true" default="Y" />
<item name="abon_multiple" libelle="Permettre les abonnements multiples" type="enum" length="'Y','N'" notnull="true" default="N" />
<item name="html_fichier" libelle="Nom du fichier html" type="varchar" length="255" list="true" order="true"  nohtml="true"/>
<item name="date_crea" type="date" list="true" order="false" />
<item name="statut" libelle="statut" type="int" length="11" notnull="true" default="DEF_CODE_STATUT_DEFAUT" list="true" order="true" />
</class>

==========================================*/

class news_theme
{
var $inherited_list = array();
var $inherited = array();
var $id;
var $libelle;
var $abon_criteres;
var $allow_edit;
var $abon_multiple;
var $html_fichier;
var $date_crea;
var $statut;

var $XML = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>
<class name=\"news_theme\" libelle=\"Catégorie\" prefix=\"theme\" display=\"libelle\" abstract=\"libelle\">
<item name=\"id\" type=\"int\" length=\"11\" isprimary=\"true\" notnull=\"true\" default=\"-1\" list=\"true\" order=\"true\" />
<item name=\"libelle\" libelle=\"Libellé de la catégorie\" type=\"varchar\" length=\"255\" list=\"true\" order=\"true\" nohtml=\"true\" />
<item name=\"abon_criteres\" libelle=\"Utiliser les critères d'abonnement\" type=\"enum\" length=\"'Y','N'\" notnull=\"true\" default=\"N\" />
<item name=\"allow_edit\" libelle=\"Autoriser l'édition wysiwyg\" type=\"enum\" length=\"'Y','N'\" notnull=\"true\" default=\"Y\" />
<item name=\"abon_multiple\" libelle=\"Permettre les abonnements multiples\" type=\"enum\" length=\"'Y','N'\" notnull=\"true\" default=\"N\" />
<item name=\"html_fichier\" libelle=\"Nom du fichier html\" type=\"varchar\" length=\"255\" list=\"true\" order=\"true\"  nohtml=\"true\"/>
<item name=\"date_crea\" type=\"date\" list=\"true\" order=\"false\" />
<item name=\"statut\" libelle=\"statut\" type=\"int\" length=\"11\" notnull=\"true\" default=\"DEF_CODE_STATUT_DEFAUT\" list=\"true\" order=\"true\" />
</class>";

var $XML_inherited = null;

var $sMySql = "CREATE TABLE news_theme
(
	theme_id			int (11) PRIMARY KEY not null,
	theme_libelle			varchar (255),
	theme_abon_criteres			enum ('Y','N') not null default 'N',
	theme_allow_edit			enum ('Y','N') not null default 'Y',
	theme_abon_multiple			enum ('Y','N') not null default 'N',
	theme_html_fichier			varchar (255),
	theme_date_crea			date,
	theme_statut			int (11) not null
)

";

// constructeur
function news_theme($id=null)
{
	if (istable(get_class($this)) == false){
		dbExecuteQuery($this->sMySql);
	}

	if($id!=null) {
		$tempThis = dbGetObjectFromPK(get_class($this), $id);
		foreach ($tempThis as $tempKey => $tempValue){
			$this->$tempKey = $tempValue;
		}
		$tempThis = null;
		if(array_key_exists('0',$this->inherited_list)){
			foreach($this->inherited_list as $class){
				if(!is_object($class))
					$this->inherited[$class] = dbGetObjectFromPK($class, $id);
			}
		}
	} else {
		$this->id = -1;
		$this->libelle = "";
		$this->abon_criteres = "N";
		$this->allow_edit = "Y";
		$this->abon_multiple = "N";
		$this->html_fichier = "";
		$this->date_crea = date("d/m/Y");
		$this->statut = DEF_CODE_STATUT_DEFAUT;
		if(array_key_exists('0',$this->inherited_list)){
			foreach($this->inherited_list as $class){
				if(!is_object($class))
					$this->inherited[$class] = new $class();
			}
		}
	}
}

// liste des champs de l'objet
function getListeChamps()
{
	// ATTENTION, respecter l'ordre des champs de la table dans la base de données pour construire laListeChamp
	$laListeChamps[]=new dbChamp("Theme_id", "entier", "get_id", "set_id");
	$laListeChamps[]=new dbChamp("Theme_libelle", "text", "get_libelle", "set_libelle");
	$laListeChamps[]=new dbChamp("Theme_abon_criteres", "text", "get_abon_criteres", "set_abon_criteres");
	$laListeChamps[]=new dbChamp("Theme_allow_edit", "text", "get_allow_edit", "set_allow_edit");
	$laListeChamps[]=new dbChamp("Theme_abon_multiple", "text", "get_abon_multiple", "set_abon_multiple");
	$laListeChamps[]=new dbChamp("Theme_html_fichier", "text", "get_html_fichier", "set_html_fichier");
	$laListeChamps[]=new dbChamp("Theme_date_crea", "date_formatee", "get_date_crea", "set_date_crea");
	$laListeChamps[]=new dbChamp("Theme_statut", "entier", "get_statut", "set_statut");
	return($laListeChamps);
}

// getters
function get_id() { return($this->id); }
function get_libelle() { return($this->libelle); }
function get_abon_criteres() { return($this->abon_criteres); }
function get_allow_edit() { return($this->allow_edit); }
function get_abon_multiple() { return($this->abon_multiple); }
function get_html_fichier() { return($this->html_fichier); }
function get_date_crea() { return($this->date_crea); }
function get_statut() { return($this->statut); }

// setters
function set_id($c_theme_id) { return($this->id=$c_theme_id); }
function set_libelle($c_theme_libelle) { return($this->libelle=$c_theme_libelle); }
function set_abon_criteres($c_theme_abon_criteres) { return($this->abon_criteres=$c_theme_abon_criteres); }
function set_allow_edit($c_theme_allow_edit) { return($this->allow_edit=$c_theme_allow_edit); }
function set_abon_multiple($c_theme_abon_multiple) { return($this->abon_multiple=$c_theme_abon_multiple); }
function set_html_fichier($c_theme_html_fichier) { return($this->html_fichier=$c_theme_html_fichier); }
function set_date_crea($c_theme_date_crea) { return($this->date_crea=$c_theme_date_crea); }
function set_statut($c_theme_statut) { return($this->statut=$c_theme_statut); }

// autres getters
function getGetterPK() { return("get_id"); }
function getSetterPK() { return("set_id"); }
function getFieldPK() { return("theme_id"); }
// statut
function getGetterStatut() {return("get_statut"); }
function getFieldStatut() {return("theme_statut"); }
//
function getTable() { return("news_theme"); }
function getClasse() { return("news_theme"); }
function getPrefix() { return(""); }
function getDisplay() { return("libelle"); }
function getAbstract() { return("libelle"); }

} //class

// ecriture des fichiers
if (!is_dir($_SERVER['DOCUMENT_ROOT']."/backoffice/cms/news_theme")){
	mkdir($_SERVER['DOCUMENT_ROOT']."/backoffice/cms/news_theme");
	$list = fopen($_SERVER['DOCUMENT_ROOT']."/backoffice/cms/news_theme/list_news_theme.php", "w");
	$listContent = "<"."?php

\$"."script = explode('/',\$"."_SERVER['PHP_SELF']);
\$"."script = \$"."script[sizeof(\$"."script)-1];

if (is_file(\$"."_SERVER['DOCUMENT_ROOT'].'/include/bo/cms/prepend.'.\$"."script))
	require_once('include/bo/cms/prepend.'.\$"."script);

include('cms-inc/autoClass/list.php');
?".">";
	fwrite($list, $listContent);
	fclose($list);
	$maj = fopen($_SERVER['DOCUMENT_ROOT']."/backoffice/cms/news_theme/maj_news_theme.php", "w");
	$majContent = "<"."?php include('cms-inc/autoClass/maj.php'); ?".">";
	fwrite($maj, $majContent);
	fclose($maj);
	$show = fopen($_SERVER['DOCUMENT_ROOT']."/backoffice/cms/news_theme/show_news_theme.php", "w");
	$showContent = "<"."?php include('cms-inc/autoClass/show.php'); ?".">";
	fwrite($show, $showContent);
	fclose($show);
	$rss = fopen($_SERVER['DOCUMENT_ROOT']."/backoffice/cms/news_theme/rss_news_theme.php", "w");
	$rssContent = "<"."?php include('cms-inc/autoClass/rss.php'); ?".">";
	fwrite($rss, $rssContent);
	fclose($rss);
	$xml = fopen($_SERVER['DOCUMENT_ROOT']."/backoffice/cms/news_theme/xml_news_theme.php", "w");
	$xmlContent = "<"."?php include('cms-inc/autoClass/xml.php'); ?".">";
	fwrite($xml, $xmlContent);
	fclose($xml);
	$xmlxls = fopen($_SERVER['DOCUMENT_ROOT']."/backoffice/cms/news_theme/xlsx_news_theme.php", "w");
	$xmlxlsContent = "<"."?php include('cms-inc/autoClass/xlsx.php'); ?".">";
	fwrite($xmlxls, $xmlxlsContent);
	fclose($xmlxls);
	$export = fopen($_SERVER['DOCUMENT_ROOT']."/backoffice/cms/news_theme/export_news_theme.php", "w");
	$exportContent = "<"."?php include('cms-inc/autoClass/export.php'); ?".">";
	fwrite($export, $exportContent);
	fclose($export);
	$import = fopen($_SERVER['DOCUMENT_ROOT']."/backoffice/cms/news_theme/import_news_theme.php", "w");
	$importContent = "<"."?php include('cms-inc/autoClass/import.php'); ?".">";
	fwrite($import, $importContent);
	fclose($import);
}
}
?>


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

<title>io.rapid Class Hierarchy (Rapid.io Android API Reference)</title>
<meta name="date" content="2017-07-28">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package io.rapid

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

io.rapid.BaseCollectionSubscription<T>

io.rapid.RapidCollectionSubscription<T>

io.rapid.RapidDocumentSubscription<T>

io.rapid.Etag

io.rapid.JsonConverterProvider

io.rapid.ListUpdate

io.rapid.Rapid

io.rapid.RapidCallback

io.rapid.RapidChannelPrefixReference<T>

io.rapid.RapidChannelReference<T>

io.rapid.RapidChannelSubscription<T>

io.rapid.RapidCollectionMapReference<T,S>

io.rapid.RapidCollectionReference<T>

io.rapid.RapidDocument<T> (implements java.lang.Comparable<T>)

io.rapid.RapidDocumentExecutor<T>

io.rapid.RapidDocumentExecutor.Result<T>

io.rapid.RapidDocumentReference<T>

io.rapid.RapidFuture

io.rapid.RapidMessage<T>

io.rapid.RapidMutateOptions

io.rapid.RapidMutateOptions.Builder

java.lang.Throwable (implements java.io.Serializable)

java.lang.Error

io.rapid.RapidError

Interface Hierarchy

io.rapid.RapidCallback.Collection<T>

io.rapid.RapidCallback.CollectionMapped<T>

io.rapid.RapidCallback.CollectionUpdates<T>

io.rapid.RapidCallback.Document<T>

io.rapid.RapidCallback.Error

io.rapid.RapidCallback.Message<T>

io.rapid.RapidCallback.TimeOffset

io.rapid.RapidCollectionMapReference.MapCollectionUpdatesCallback<T>

io.rapid.RapidCollectionMapReference.MapFunction<T,S>

io.rapid.RapidCollectionMapReference.MapInnerFunction<T,S>

io.rapid.RapidConnectionStateListener

io.rapid.RapidDocumentExecutor.Callback<T>

io.rapid.RapidFuture.CompleteCallback

io.rapid.RapidFuture.ErrorCallback

io.rapid.RapidFuture.SuccessCallback

Annotation Type Hierarchy

io.rapid.LogLevel (implements java.lang.annotation.Annotation)

Enum Hierarchy

java.lang.Object

java.lang.Enum<E> (implements java.lang.Comparable<T>, java.io.Serializable)

io.rapid.Sorting

io.rapid.RapidError.ErrorType

io.rapid.BaseCollectionSubscription.DataState

io.rapid.ListUpdate.Type

io.rapid.ConnectionState

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
package com.cloudera.oryx.app.serving.als;

import java.util.List;

import javax.ws.rs.core.MediaType;

import org.junit.Assert;
import org.junit.Test;

import com.cloudera.oryx.app.serving.IDCount;

public final class MostPopularItemsTest extends AbstractALSServingTest {

  @Test
  public void testMostPopular() {
    List<IDCount> top = target("/mostPopularItems").request()
        .accept(MediaType.APPLICATION_JSON_TYPE).get(LIST_ID_COUNT_TYPE);
    Assert.assertEquals(9, top.size());
    for (int i = 0; i < top.size(); i++) {
      int thisCount = top.get(i).getValue();
      Assert.assertTrue(thisCount >= 1);
      if (i > 0) {
        Assert.assertTrue(top.get(i - 1).getValue() >= thisCount);
      }
    }
    Assert.assertEquals(6, top.get(0).getValue());
    Assert.assertEquals(6, top.get(1).getValue());
  }

  @Test
  public void testMostPopularCSV() {
    String response = target("/mostPopularItems").request().get(String.class);
    testCSVTopByCount(9, response);
  }

  @Test
  public void testRescorer() {
    List<IDCount> top = target("/mostPopularItems").queryParam("rescorerParams", "foo").request()
        .accept(MediaType.APPLICATION_JSON_TYPE).get(LIST_ID_COUNT_TYPE);
    Assert.assertEquals(4, top.size());
    Assert.assertEquals(6, top.get(0).getValue());
    Assert.assertEquals(5, top.get(1).getValue());
  }

}


text:
#include "net/instaweb/rewriter/public/rewritten_content_scanning_filter.h"

#include <memory>

#include "net/instaweb/rewriter/public/resource_tag_scanner.h"
#include "net/instaweb/rewriter/public/rewrite_driver.h"
#include "net/instaweb/rewriter/public/server_context.h"
#include "net/instaweb/rewriter/public/url_namer.h"
#include "net/instaweb/util/public/property_cache.h"
#include "pagespeed/kernel/base/string_util.h"
#include "pagespeed/kernel/html/html_element.h"
#include "pagespeed/kernel/http/google_url.h"
#include "pagespeed/kernel/http/semantic_type.h"

namespace net_instaweb {

const char
    RewrittenContentScanningFilter::kNumProxiedRewrittenResourcesProperty[] =
        "num_proxied_rewritten_resources";

RewrittenContentScanningFilter::RewrittenContentScanningFilter(
    RewriteDriver* driver)
    : driver_(driver), num_proxied_rewritten_resources_(0) {}

RewrittenContentScanningFilter::~RewrittenContentScanningFilter() {}

void RewrittenContentScanningFilter::StartDocument() {
  num_proxied_rewritten_resources_ = 0;
}

void RewrittenContentScanningFilter::EndDocument() {
  // Update number of rewritten resources in the property cahce.
  driver_->UpdatePropertyValueInDomCohort(
      driver_->property_page(), kNumProxiedRewrittenResourcesProperty,
      IntegerToString(num_proxied_rewritten_resources_));
}

void RewrittenContentScanningFilter::StartElement(HtmlElement* element) {
  resource_tag_scanner::UrlCategoryVector attributes;
  resource_tag_scanner::ScanElement(element, driver_->options(), &attributes);
  for (int i = 0, n = attributes.size(); i < n; ++i) {
    StringPiece url(attributes[i].url->DecodedValueOrNull());
    if (url.empty()) {
      continue;
    }
    switch (attributes[i].category) {
      case semantic_type::kImage:
      case semantic_type::kScript:
      case semantic_type::kStylesheet:
      case semantic_type::kOtherResource: {
        GoogleUrl gurl(driver_->base_url(), url);
        if (driver_->server_context()->url_namer()->IsProxyEncoded(gurl)) {
          ++num_proxied_rewritten_resources_;
        }
        break;
      }
      case semantic_type::kPrefetch:
      case semantic_type::kHyperlink:
      case semantic_type::kUndefined:
        break;
    }
  }
}

}  // namespace net_instaweb


text:
var parseQueryString = (function () {
	"use strict";
	var params = {},
		qs = location.search.substring(1, location.search.length),
		i = 0,
		args,
		pair,
		name,
		value,
		getKeys = function () {
			var keys = [],
				key;
			for (key in params) {
				if (typeof key === "string") {
					keys.push(key);
				}
			}
			return keys;
		},
		getValue = function (key, defaultText) {
			var value = params[key];
			return (value !== null) ? value : defaultText;
		},
		contains = function (key) {
			window.console.log("Key Exists: " + params[key]);
			return (params[key] !== undefined);
		};

	if (qs.length > 0) {
		// Turn <plus> back to <space>
		// See:
		// http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
		qs = qs.replace(/\+/g, ' ');
		// parse out name/value pairs separated via &
		args = qs.split('&');
		// split out each name=value pair
		for (i = 0; i < args.length; i = i + 1) {
			pair = args[i].split('=');
			name = decodeURIComponent(pair[0]);
			value = (pair.length === 2) ? decodeURIComponent(pair[1]) : null;
			params[name] = value;
		}
	}

	return {
		getKeys: getKeys,
		getValue: getValue,
		contains: contains
	};
}());