text:
<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="//core.codekraft.it/public/wordpress/main-sitemap.xsl"?>
<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
	<url>
		<loc>http://localhost:8040/contact</loc>
		<lastmod>2017-01-10T00:52:37+01:00</lastmod>
	</url>
	<url>
		<loc>http://localhost:8040/services/bad</loc>
		<lastmod>2017-01-10T00:52:37+01:00</lastmod>
	</url>
</urlset>
<!-- XML Sitemap generated by Yoast SEO -->
<!-- 24.04MB | Served from transient cache -->


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--                                                                -->
<!--   W4F: Copyright Arnaud Sahuguet and Fabien Azavant, 1998-99   -->
<!--   URL: http://db.cis.upenn.edu/W4F                             -->
<!--                                                                -->
<!DOCTYPE W4F_DOC  SYSTEM "movies.dtd">
<W4F_DOC>
  <Movie>
    <Title>Fight Club</Title>
    <Year>1999</Year>
    <Directed_By>
      <Director>David Fincher</Director>
    </Directed_By>
    <Genres>
      <Genre>Comedy</Genre>
      <Genre>Drama</Genre>
      <Genre>(more)</Genre>
    </Genres>
    <Cast>
      <Actor>
        <FirstName>Brad</FirstName>
        <LastName>Pitt</LastName>
      </Actor>
      <Actor>
        <FirstName>Edward</FirstName>
        <LastName>Norton</LastName>
      </Actor>
      <Actor>
        <FirstName>Helena</FirstName>
        <LastName>Bonham Carter</LastName>
      </Actor>
      <Actor>
        <FirstName>Meat</FirstName>
        <LastName>Loaf</LastName>
      </Actor>
      <Actor>
        <FirstName>Jared</FirstName>
        <LastName>Leto</LastName>
      </Actor>
      <Actor>
        <FirstName>Zach</FirstName>
        <LastName>Grenier</LastName>
      </Actor>
      <Actor>
        <FirstName>Eion</FirstName>
        <LastName>Bailey</LastName>
      </Actor>
      <Actor>
        <FirstName>Ezra</FirstName>
        <LastName>Buzzington</LastName>
      </Actor>
      <Actor>
        <FirstName>Richmond</FirstName>
        <LastName>Arquette</LastName>
      </Actor>
      <Actor>
        <FirstName>Joel</FirstName>
        <LastName>Bissonnette</LastName>
      </Actor>
      <Actor>
        <FirstName>Stuart</FirstName>
        <LastName>Blumberg</LastName>
      </Actor>
      <Actor>
        <FirstName>Paul</FirstName>
        <LastName>Dillon (I)</LastName>
      </Actor>
      <Actor>
        <FirstName>Peter</FirstName>
        <LastName>Iacangelo</LastName>
      </Actor>
      <Actor>
        <FirstName>Joon</FirstName>
        <LastName>B. Kim</LastName>
      </Actor>
      <Actor>
        <FirstName>Edward</FirstName>
        <LastName>Kowalczyk</LastName>
      </Actor>
      <Actor>
        <FirstName>Kevin</FirstName>
        <LastName>Scott Mack</LastName>
      </Actor>
      <Actor>
        <FirstName>George</FirstName>
        <LastName>Maguire</LastName>
      </Actor>
      <Actor>
        <FirstName>Holt</FirstName>
        <LastName>McCallany</LastName>
      </Actor>
      <Actor>
        <FirstName>Evan</FirstName>
        <LastName>Mirand</LastName>
      </Actor>
      <Actor>
        <FirstName>Rachel</FirstName>
        <LastName>Singer</LastName>
      </Actor>
    </Cast>
  </Movie>
</W4F_DOC>

redpajama_set_name: RedPajamaGithub


text:
package zhongqiu.javautils;

import java.util.HashMap;
import java.util.Map;

public class JavaEnumUtil {
    private static Map<String, Object> cache = new HashMap();

    public static void put(String key, Object value) {
        cache.put(key, value);
    }

    public static Object get(String key) {
        return cache.get(key);
    }
}


text:
using System;

using NUnit.Framework;

using System.Net;

namespace DataUriTests
{
	[TestFixture]
	public class DataUriTypeConverterTests
	{
		[Test]
		public void CanConvertFrom_String_Returns_True()
		{
			//arrange
			DataUriTypeConverter c = Create_DataUriTypeConverter();

			//act
			var actual = c.CanConvertFrom(typeof(string));

			//assert
			Assert.That(actual, Is.EqualTo(true));

		}

		[Test]
		public void ConvertTo_DataUri()
		{
			//arrange
			var value = "data:image/jpeg;base64,QUJDREVGRw==";

			var expected_DataUri = new DataUri("image/jpeg", new byte[] { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47 });

			//act
			var typeconverter = Create_DataUriTypeConverter();
			var actual_DataUri = (DataUri)typeconverter.ConvertFrom(value);

			//assert
			Assert.That(actual_DataUri, Is.Not.Null);
			Assert.That(actual_DataUri, Is.TypeOf<System.DataUri>());
			//Assert.That(actual_DataUri.MediaType, Is.EqualTo("image/jpeg"));
			//Assert.That(actual_DataUri.Bytes, Is.EqualTo(expected_DataUri.Bytes));
		}

		DataUriTypeConverter Create_DataUriTypeConverter()
		{
			return new DataUriTypeConverter();
		}
	}
}


text:
package org.opencb.opencga.storage.benchmark.variant.samplers;

import com.google.common.base.Throwables;
import org.apache.jmeter.protocol.http.sampler.HTTPSampleResult;
import org.apache.jmeter.protocol.http.sampler.HTTPSampler;
import org.apache.jmeter.protocol.http.util.HTTPArgument;
import org.opencb.commons.datastore.core.Query;
import org.opencb.commons.datastore.core.QueryOptions;
import org.opencb.opencga.storage.benchmark.variant.generators.QueryGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Created on 06/04/17.
 *
 * @author Jacobo Coll <jacobo167@gmail.com>
 */
public class VariantStorageEngineRestSampler extends HTTPSampler implements VariantStorageEngineSampler {

    public static final String REST_PATH = "/webservices/rest/v1/analysis/variant/query";
    public static final String STORAGE_REST_PATH = "/webservices/rest/variants/query";
    private Logger logger = LoggerFactory.getLogger(getClass());
    private QueryGenerator queryGenerator;

    public VariantStorageEngineRestSampler() {
        setPath(STORAGE_REST_PATH);
        setMethod("GET");
    }

    public VariantStorageEngineRestSampler(String host, int port) {
        this();
        setDomain(host);
        setPort(port);
    }

    public VariantStorageEngineRestSampler(String host, String path, int port) {
        setDomain(host);
        setPort(port);
        setPath(path);
        setMethod("GET");
    }

    @Override
    public String getQueryString(String contentEncoding) {
        StringBuilder sb = new StringBuilder(super.getQueryString(contentEncoding));

        if (sb.length() != 0) {
            sb.append('&');
        }

        Query query = getQueryGenerator().generateQuery(new Query());
        query.forEach((key, value) -> sb.append(key).append('=').append(value).append('&'));
        return encodedString(sb.toString());
    }

    @Override
    protected HTTPSampleResult sample(java.net.URL u, String method, boolean areFollowingRedirect, int depth) {
        HTTPSampleResult sample = super.sample(u, method, areFollowingRedirect, depth);
        sample.setSampleLabel(queryGenerator.getQueryId());

        if (getArguments().getArgumentsAsMap().get(QueryOptions.COUNT).equalsIgnoreCase("true")) {
            String str = sample.getResponseDataAsString();
            sample.setResponseMessage(str.substring(str.lastIndexOf("[") + 1, str.indexOf("]")));
        }
        return sample;
    }

    @Override
    public VariantStorageEngineRestSampler setStorageEngine(String storageEngine) {
        getArguments().addArgument(new HTTPArgument("storageEngine", storageEngine, "="));
        return this;
    }

    @Override
    public VariantStorageEngineRestSampler setDBName(String dbname) {
        getArguments().addArgument(new HTTPArgument("dbName", dbname, "="));
        return this;
    }

    @Override
    public VariantStorageEngineRestSampler setLimit(int limit) {
        getArguments().addArgument(new HTTPArgument(QueryOptions.LIMIT, String.valueOf(limit), "="));
        return this;
    }

    @Override
    public VariantStorageEngineSampler setCount(boolean count) {
        getArguments().addArgument(new HTTPArgument(QueryOptions.COUNT, String.valueOf(count), "="));
        return this;
    }

    @Override
    public VariantStorageEngineRestSampler setQueryGenerator(Class<? extends QueryGenerator> queryGenerator) {
        setProperty("VariantStorageEngineSamples." + VariantStorageEngineSampler.QUERY_GENERATOR, queryGenerator.getName());
        return this;
    }

    private String getQueryGeneratorClassName() {
        return getPropertyAsString("VariantStorageEngineSamples." + VariantStorageEngineSampler.QUERY_GENERATOR);
    }

    @Override
    public VariantStorageEngineSampler setQueryGeneratorConfig(String key, String value) {
        setProperty(QueryGenerator.class.getName() + '.' + key, value);
        return this;
    }

    private QueryGenerator getQueryGenerator() {
        if (Objects.isNull(queryGenerator)) {
            String queryGeneratorClassName = getQueryGeneratorClassName();
            try {
                Map<String, String> map = new HashMap<>();
                String queryGeneratorProperties = QueryGenerator.class.getName() + ".";
                propertyIterator().forEachRemaining(property -> {
                    if (property.getName().startsWith(queryGeneratorProperties)) {
                        map.put(property.getName().substring(queryGeneratorProperties.length()), property.getStringValue());
                    }
                });
                queryGenerator = (QueryGenerator) Class.forName(queryGeneratorClassName).newInstance();
                queryGenerator.setUp(map);
                logger.debug("Using query generator " + queryGenerator.getClass());
            } catch (Throwable e) {
                logger.error("Error creating QueryGenerator!", e);
                Throwables.propagate(e);
            }
        }
        return queryGenerator;
    }

    private String encodedString(String string) {
        string = string.replaceAll(">=", "%3E%3D").replaceAll("<=", "%3C%3D");
        return string.replaceAll(">", "%3E").replaceAll("<", "%3C");
    }
}


text:
package org.igniterealtime.smack.inttest;

import java.lang.reflect.Method;
import java.util.List;

public abstract class TestResult {

    public final Method testMethod;
    public final long startTime;
    public final long endTime;
    public final long duration;
    public final List<String> logMessages;

    public TestResult(Method testMethod, long startTime, long endTime, List<String> logMessages) {
        this.testMethod = testMethod;
        assert (endTime >= startTime);
        this.startTime = startTime;
        this.endTime = endTime;
        this.duration = endTime - startTime;
        this.logMessages = logMessages;
    }
}


text:
<?php

namespace LolEspCal\Cacher;

/**
 * Description of AbstractCacher
 *
 * @author Jeremy
 */
abstract class AbstractCacher
{
    /**
     * @var string
     */
    private $cacheDir = 'cache/';

    /**
     * @param mixed $id
     *
     * @return bool
     */
    abstract public function has($id);

    /**
     * @param mixed $id
     *
     * @return string
     */
    abstract public function get($id);

    /**
     * @param mixed     $id
     * @param string    $content
     */
    abstract public function set($id, $content);

    /**
     * @return string
     */
    abstract public function getCacheFilename($param);

    /**
     * @param string $cacheDir
     */
    public function setCacheDir($cacheDir)
    {
        $this->cacheDir = $cacheDir;
    }

    /**
     * @return string
     */
    public function getCacheDir()
    {
        return $this->cacheDir;
    }
}


text:
<?php
/* Prototype  : proto void ob_implicit_flush([int flag])
 * Description: Turn implicit flush on/off and is equivalent to calling flush() after every output call
 * Source code: main/output.c
 * Alias to functions:
 */

echo "*** Testing ob_implicit_flush() : error conditions ***\n";

//Test ob_implicit_flush with one more than the expected number of arguments
echo "\n-- Testing ob_implicit_flush() function with more than expected no. of arguments --\n";
$flag = 10;
$extra_arg = 10;
var_dump( ob_implicit_flush($flag, $extra_arg) );

echo "Done";
?>


text:
A javascript library for voice driven web apps

vCommander is **"Proof Of Concept"** application for voice driven web apps using chrome speech to text APIs.

Please refer Google Developer for more details : https://developers.google.com/web/updates/2013/01/Voice-Driven-Web-Apps-Introduction-to-the-Web-Speech-API?hl=en


text:
:orphan:

=====
Usage
=====

To use editquality in a project::

    import editquality

Take a look at the Jupyter notebooks to see how you can use the various
modules.

This package also contains a CLI tool which can be used in the terminal::

    Usage:
        editquality (-h | --help)
        editquality <utility> [-h | --help]

    Options:
        -h | --help  Prints this documentation
        <utility>    The name of the utility to run

The CLI provides access to a set of utilities for extracting features and
building edit quality predictors. Check out the tutorials to see examples on
how to use the utilities to train a model.

Local Development
--------------------
If you are working from the project root directory, you can invoke the CLI as
follows::

    ./utility <util-name> [-h]


text:
<!DOCTYPE HTML>

    <title>wait test</title>

foo

bar

    show bar
    hide foo
    remove foo
    add foobar

      <button id="btn" type="button" onclick="setDisabled('btn', true, 0)" disabled>Click To Disable!</button>
      enable btn
      <button id="btn2" style="display:none;" type="button" disabled>Hidden and Disabled</button>

        show and enable btn

      change select list
      show select list

    <form>
      <fieldset>
        <select name="languages" id="languages", style="display: none">
          <option id="danish" value="1">Danish</option>
          <option selected="selected" value="2">English</option>
          <option selected="selected" value="3">Norwegian</option>
          <option value="4" disabled>Russian</option>
          <option>Swedish</option>
        </select>

      </fieldset>
    </form>

Nothing to see here


text:
'''
A collection of utility functions for spideTor

Created on Aug 2, 2014

@author: Noah
'''

import os
import re

def windowsPathLengthLimitWorkaround(path):
    '''
    Windows API causes trouble again...
    If we're running on windows and not rooted in a UNC path,
    prepend "//?/" to allow paths > 260 chars, and insert slash after the colon
    '''
    if os.name == "nt" or os.name == "ce":
        #Try to find drive identifier
        if re.match(r'^[A-Z]:', path):
            #we're accessing a drive letter path and need UNC prefix
            path = "\\\\?\\" + path
        else:
            path = re.sub(r'^\\\\(?!\?\\UNC\\)', r'\\\\?\\UNC\\', path)
    return path


text:
package acd

import (
	"net/http"
	"net/url"
	"time"
)

// AccountService provides access to the account related functions
// in the Amazon Cloud Drive API.
//
// See: https://developer.amazon.com/public/apis/experience/cloud-drive/content/account
type AccountService struct {
	client *Client
}

// AccountEndpoints represents information about the current customer's endpoints
type AccountEndpoints struct {
	CustomerExists bool   `json:"customerExists"`
	ContentURL     string `json:"contentUrl"`
	MetadataURL    string `json:"metadataUrl"`
}

// GetEndpoints retrives the current endpoints for this customer
//
// It also updates the endpoints in the client
func (s *AccountService) GetEndpoints() (*AccountEndpoints, *http.Response, error) {
	req, err := s.client.NewMetadataRequest("GET", "account/endpoint", nil)
	if err != nil {
		return nil, nil, err
	}

	endpoints := &AccountEndpoints{}
	resp, err := s.client.Do(req, endpoints)
	if err != nil {
		return nil, resp, err
	}

	// Update the client endpoints
	if endpoints.MetadataURL != "" {
		u, err := url.Parse(endpoints.MetadataURL)
		if err == nil {
			s.client.MetadataURL = u
		}
	}
	if endpoints.ContentURL != "" {
		u, err := url.Parse(endpoints.ContentURL)
		if err == nil {
			s.client.ContentURL = u
		}
	}

	return endpoints, resp, err
}

// AccountInfo represents information about an Amazon Cloud Drive account.
type AccountInfo struct {
	TermsOfUse *string `json:"termsOfUse"`
	Status     *string `json:"status"`
}

// GetInfo provides information about the current user account like
// the status and the accepted "Terms Of Use".
func (s *AccountService) GetInfo() (*AccountInfo, *http.Response, error) {
	req, err := s.client.NewMetadataRequest("GET", "account/info", nil)
	if err != nil {
		return nil, nil, err
	}

	accountInfo := &AccountInfo{}
	resp, err := s.client.Do(req, accountInfo)
	if err != nil {
		return nil, resp, err
	}

	return accountInfo, resp, err
}

// AccountQuota represents information about the account quotas.
type AccountQuota struct {
	Quota          *uint64    `json:"quota"`
	LastCalculated *time.Time `json:"lastCalculated"`
	Available      *uint64    `json:"available"`
}

// GetQuota gets account quota and storage availability information.
func (s *AccountService) GetQuota() (*AccountQuota, *http.Response, error) {
	req, err := s.client.NewMetadataRequest("GET", "account/quota", nil)
	if err != nil {
		return nil, nil, err
	}

	accountQuota := &AccountQuota{}
	resp, err := s.client.Do(req, accountQuota)
	if err != nil {
		return nil, resp, err
	}

	return accountQuota, resp, err
}

// AccountUsage represents information about the account usage.
type AccountUsage struct {
	LastCalculated *time.Time     `json:"lastCalculated"`
	Other          *CategoryUsage `json:"other"`
	Doc            *CategoryUsage `json:"doc"`
	Photo          *CategoryUsage `json:"photo"`
	Video          *CategoryUsage `json:"video"`
}

// CategoryUsage defines Total and Billable UsageNumbers
type CategoryUsage struct {
	Total    *UsageNumbers `json:"total"`
	Billable *UsageNumbers `json:"billable"`
}

// UsageNumbers defines Bytes and Count for a metered count
type UsageNumbers struct {
	Bytes *uint64 `json:"bytes"`
	Count *uint64 `json:"count"`
}

// GetUsage gets Account Usage information broken down by content category.
func (s *AccountService) GetUsage() (*AccountUsage, *http.Response, error) {
	req, err := s.client.NewMetadataRequest("GET", "account/usage", nil)
	if err != nil {
		return nil, nil, err
	}

	accountUsage := &AccountUsage{}
	resp, err := s.client.Do(req, accountUsage)
	if err != nil {
		return nil, resp, err
	}

	return accountUsage, resp, err
}


text:
from core import perf_benchmark

from telemetry import benchmark
from telemetry.timeline import chrome_trace_category_filter
from telemetry.web_perf import timeline_based_measurement

import page_sets

BLOB_CATEGORY = 'Blob'
TIMELINE_REQUIRED_CATEGORY = 'blink.console'

# http://crbug.com/499325
# http://crbug.com/595069
@benchmark.Disabled('android', 'win')
class BlobStorage(perf_benchmark.PerfBenchmark):
  """Timeline based measurement benchmark for Blob Storage."""

  page_set = page_sets.BlobWorkshopPageSet

  def CreateTimelineBasedMeasurementOptions(self):
    cat_filter = chrome_trace_category_filter.ChromeTraceCategoryFilter()
    cat_filter.AddIncludedCategory(BLOB_CATEGORY)
    cat_filter.AddIncludedCategory(TIMELINE_REQUIRED_CATEGORY)

    return timeline_based_measurement.Options(
        overhead_level=cat_filter)

  # Necessary until crbug.com/544306 is finished.
  def SetExtraBrowserOptions(self, options):
    options.AppendExtraBrowserArgs(
        ['--enable-experimental-web-platform-features'])

  @classmethod
  def Name(cls):
    return 'blob_storage.blob_storage'

  @classmethod
  def ValueCanBeAddedPredicate(cls, value, is_first_result):
    if ('blob-writes' not in value.name and
        'blob-reads' not in value.name):
      return False
    return value.values != None


text:
basedir=`dirname $0`/..
. $basedir/bin/common.sh

if [ $# -lt 3 ]; then
    echo "usage: $0 [nova_flavor_id] [hostname] [files_dir]"
    echo
    echo "Available flavors:"
    nova flavor-list
    exit 1
fi

flavor=$1
host=$2
filesdir=$3

# bootup the node and install software
echo "booting up node and installing software..."
$basedir/bin/bootup_node_and_sync.sh $flavor $host $filesdir
echo "done"

ip=`get_ip $host`

# add this node as a hbase regionserver and start daemons on it
echo "starting hbase daemons on $host ($ip)"
$basedir/bin/sshexec.sh $host gtstream-scripts/bin/add_self_to_hbase.sh

echo
echo "New HBase regionserver started (hostname=$host, ip=$ip)"


text:
{% extends "app_base.html" %}

{% load static %}
{% block css %}
<link rel="stylesheet" href="{% static 'css/contact.css' %}">
{% endblock %}

{% block appmenu %}

Persons

Organizations

Memberships

Phone Types

Phone Numbers

Website Types

Websites

Sales Order

{% endblock %}


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

package main

import (
	"encoding/json"
	"io"
	"time"
)

// A xlMetaV1 represents a metadata header mapping keys to sets of values.
type xlMetaV1 struct {
	Version string `json:"version"`
	Stat    struct {
		Size    int64     `json:"size"`
		ModTime time.Time `json:"modTime"`
		Version int64     `json:"version"`
	} `json:"stat"`
	Erasure struct {
		DataBlocks   int   `json:"data"`
		ParityBlocks int   `json:"parity"`
		BlockSize    int64 `json:"blockSize"`
	} `json:"erasure"`
	Minio struct {
		Release string `json:"release"`
	} `json:"minio"`
}

// Write writes a metadata in wire format.
func (m xlMetaV1) Write(writer io.Writer) error {
	metadataBytes, err := json.Marshal(m)
	if err != nil {
		return err
	}
	_, err = writer.Write(metadataBytes)
	return err
}

// xlMetaV1Decode - file metadata decode.
func xlMetaV1Decode(reader io.Reader) (metadata xlMetaV1, err error) {
	decoder := json.NewDecoder(reader)
	// Unmarshalling failed, file possibly corrupted.
	if err = decoder.Decode(&metadata); err != nil {
		return xlMetaV1{}, err
	}
	return metadata, nil
}


text:
#ifndef SIDEFINE_H
#define SIDEFINE_H

#include "dcmtk/config/osconfig.h"

#include "dcmtk/ofstd/ofdefine.h"

#ifdef dcmdsig_EXPORTS
#define DCMTK_DCMSIGN_EXPORT DCMTK_DECL_EXPORT
#else
#define DCMTK_DCMSIGN_EXPORT DCMTK_DECL_IMPORT
#endif

#endif


text:
<!DOCTYPE html>
<html style="height: 100%; width: 100%">
<head>
  <meta charset="utf-8">
  <title>Dart VM Observatory Timeline</title>
  <script src="timeline_message_handler.js"></script>
  <script src="third_party/webcomponents.min.js"></script>
  <link rel="import" href="third_party/trace_viewer_full.html">
  <script src="timeline.js"></script>
  <style>
html, body {
  box-sizing: border-box;
  overflow: hidden;
  margin: 0px;
  padding: 0;
  width: 100%;
  height: 100%;
}
#trace-viewer {
  width: 100%;
  height: 100%;
}
#trace-viewer:focus {
  outline: none;
}
  </style>
</head>
<body>
</body>
</html>


text:
using System;
using DotNetNuke.Entities.Users;
using JS.Modules.JSFAQ.Components;
using DotNetNuke.Services.Exceptions;
using System.Web.UI.WebControls;
using DotNetNuke.Entities.Tabs;

namespace JS.Modules.JSFAQ
{
    public partial class AddFAQ : JSFAQModuleBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    lnkManage.NavigateUrl = EditUrl("ManageCategories");
                    string PageName = TabController.CurrentPage.TabPath.Remove(0, 1);
                    lnkSettings.NavigateUrl = "javascript:dnnModal.show('http://" + Request.Url.Host + PageName + "/ctl/Module/ModuleId/" + ModuleId + "?ReturnURL=" + PageName + "&popUp=true#msSpecificSettings',/*showReturn*/false,550,950,true,'')";
                    bool categoryPresent = false;
                    var cc = new CategoryController();
                    var ac = cc.GetCategories(ModuleId);
                    foreach (Category c in ac)
                    {
                        if (c != null)
                        {
                            categoryPresent = true;
                            ddCategory.Items.Add(c.CategoryName);
                        }
                    }
                    var fc = new FAQController();
                    if (FaqId > 0)
                    {
                        btnSave.Text = "Update";
                        btnSave.CssClass = "btnSubmit btn btn-primary";
                        btnSaveClose.Text = "Update and Close";
                        btnSaveClose.CssClass = "btnSubmit btn btn-primary";
                        lblGroupStatusHolder.CssClass = "group-stat-holder link-save";
                        var f = fc.GetFAQ(FaqId, ModuleId);
                        if (f != null)
                        {
                            if (f.FaqCategory == "NotCategorized")
                            {
                                rblCategoryOption.SelectedValue = "empty";
                                txtQuestion.Text = f.FaqQuestion;
                                txtAnswer.Text = f.FaqAnswer;
                                cbHideFAQ.Checked = !f.ShowFaq;
                            }
                            else
                            {
                                rblCategoryOption.SelectedValue = "list";
                                ddCategory.SelectedValue = f.FaqCategory;
                                txtQuestion.Text = f.FaqQuestion;
                                txtAnswer.Text = f.FaqAnswer;
                                cbHideFAQ.Checked = !f.ShowFaq;
                            }
                        }
                        else
                        {
                            if (categoryPresent)
                            {
                                rblCategoryOption.SelectedValue = "list";
                            }
                            else
                            {
                                rblCategoryOption.SelectedValue = "new";
                                foreach (ListItem li in rblCategoryOption.Items)
                                {
                                    if (li.Value == "list")
                                    {
                                        li.Enabled = false;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        btnSave.Text = "Add";
                        btnSave.CssClass = "btnSubmit btn btn-primary";
                        btnSaveClose.Text = "Add and Close";
                        btnSaveClose.CssClass = "btnSubmit btn btn-primary";
                        lblGroupStatusHolder.CssClass = "group-stat-holder link-add";
                        if (categoryPresent)
                        {
                            rblCategoryOption.SelectedValue = "list";
                        }
                        else
                        {
                            rblCategoryOption.SelectedValue = "new";
                            foreach (ListItem li in rblCategoryOption.Items)
                            {
                                if (li.Value == "list")
                                {
                                    li.Enabled = false;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            Save();
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(DotNetNuke.Common.Globals.NavigateURL());
        }

        protected void btnSaveClose_Click(object sender, EventArgs e)
        {
            Save();
            Response.Redirect(DotNetNuke.Common.Globals.NavigateURL());
        }

        protected void Save()
        {
            var cc = new CategoryController();
            var fc = new FAQController();
            string status;
            if (FaqId > 0)
            {
                switch (rblCategoryOption.SelectedValue)
                {
                    case "new":
                        var c = new Category()
                        {
                            CategoryName = txtCategoryName.Text.Trim(),
                            CategoryDescription = txtCategoryDescription.Text.Trim(),
                            ShowCategory = true,
                            ModuleId = ModuleId
                        };
                        cc.CreateCategory(c);
                        var f = fc.GetFAQ(FaqId, ModuleId);
                        f.FaqCategory = txtCategoryName.Text.Trim();
                        f.FaqQuestion = txtQuestion.Text.Trim();
                        f.FaqAnswer = txtAnswer.Text.Trim();
                        f.ShowFaq = !cbHideFAQ.Checked;
                        f.Categorized = true;
                        f.ModuleId = ModuleId;
                        fc.UpdateFAQ(f);
                        break;
                    case "list":
                        var lf = fc.GetFAQ(FaqId, ModuleId);
                        lf.FaqCategory = ddCategory.SelectedValue;
                        lf.FaqQuestion = txtQuestion.Text.Trim();
                        lf.FaqAnswer = txtAnswer.Text.Trim();
                        lf.ShowFaq = !cbHideFAQ.Checked;
                        lf.Categorized = true;
                        lf.ModuleId = ModuleId;
                        fc.UpdateFAQ(lf);
                        break;
                    case "empty":
                        var ef = fc.GetFAQ(FaqId, ModuleId);
                        ef.FaqCategory = "NotCategorized";
                        ef.FaqQuestion = txtQuestion.Text.Trim();
                        ef.FaqAnswer = txtAnswer.Text.Trim();
                        ef.ShowFaq = !cbHideFAQ.Checked;
                        ef.Categorized = false;
                        ef.ModuleId = ModuleId;
                        fc.UpdateFAQ(ef);
                        break;
                    default:
                        break;
                }
                lblSubTitle.Text = "FAQ Entry Updated!";
                status = "success";
            }
            else
            {
                bool faqExists = false;
                foreach (var faq in fc.GetFAQs(ModuleId))
                {
                    if (faq.FaqQuestion == txtQuestion.Text.Trim())
                    {
                        faqExists = true;
                    }
                }
                if (!faqExists)
                {
                    switch (rblCategoryOption.SelectedValue)
                    {
                        case "new":
                            var c = new Category()
                            {
                                CategoryName = txtCategoryName.Text.Trim(),
                                CategoryDescription = txtCategoryDescription.Text.Trim(),
                                ShowCategory = true,
                                ModuleId = ModuleId
                            };
                            cc.CreateCategory(c);
                            var f = new FAQ()
                            {
                                FaqCategory = txtCategoryName.Text.Trim(),
                                FaqQuestion = txtQuestion.Text.Trim(),
                                FaqAnswer = txtAnswer.Text.Trim(),
                                ShowFaq = !cbHideFAQ.Checked,
                                Categorized = true,
                                ModuleId = ModuleId
                            };
                            fc.CreateFAQ(f);
                            break;
                        case "list":
                            var lf = new FAQ()
                            {
                                FaqCategory = ddCategory.SelectedValue,
                                FaqQuestion = txtQuestion.Text.Trim(),
                                FaqAnswer = txtAnswer.Text.Trim(),
                                ShowFaq = !cbHideFAQ.Checked,
                                Categorized = true,
                                ModuleId = ModuleId
                            };
                            fc.CreateFAQ(lf);
                            break;
                        case "empty":
                            var ef = new FAQ()
                            {
                                FaqCategory = "NotCategorized",
                                FaqQuestion = txtQuestion.Text.Trim(),
                                FaqAnswer = txtAnswer.Text.Trim(),
                                ShowFaq = !cbHideFAQ.Checked,
                                Categorized = false,
                                ModuleId = ModuleId
                            };
                            fc.CreateFAQ(ef);
                            break;
                        default:
                            break;
                    }
                    lblSubTitle.Text = "FAQ Entry Added!";
                    status = "success";
                }
                else
                {
                    lblSubTitle.Text = "FAQ with that Question already Exists!!";
                    status = "error";
                }
            }
            headerMenu.CssClass = "dnnFormMessage two-controls dnnFormTitle no-spacing " + status;
            lnkManage.CssClass = "btn btn-primary link-manage no-txt " + status;
            lnkSettings.CssClass = "btn btn-primary link-settings no-txt " + status;
        }
    }
}


text:
import {
  Component,
  ViewEncapsulation,
  ChangeDetectionStrategy,
  OnInit,
  OnDestroy
} from 'angular2/core';

import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { Subscription } from 'rxjs/Subscription';
import { Store } from '@ngrx/store';
import { SagaRunner } from 'store-saga';

// interfaces
import { IAuth } from './_auth/interfaces/IAuth';

// sagas
import { APP_SAGAS } from './sagas/sagas';

// services
import { Ng2Permission } from './services/Ng2Permission';

// action creators
import { checkAuth, logout } from './_auth/services/auth-actions.service';

// selectors
import { isAuthenticated$, getAuth$ } from './_auth/services/auth-selectors.service';

// components / containers
import { NotificationsContainer } from './containers/notifications.container/notifications.container';

// TODO: temp
import { START_NOTIFICATIONS } from './reducers/notifications.reducer';

@Component({
  selector: 'app',
  styles: [ require('./styles/app.scss') ],
  template: require('./app.component.html'),
  directives: [ NotificationsContainer ],
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent implements OnInit {
  // data
  public isAuthenticated$: Observable<boolean> = this._store.let(isAuthenticated$());
  public userData$: Observable<IAuth> = this._store.let(getAuth$());

  // dom event streams
  public onLogout$ = new Subject<any>();
  public onInit$ = new Subject<any>();

  // actions
  public logoutAction$ = this.onLogout$.map(logout());
  public initAction$ = this.onInit$.map(checkAuth());

  // subscription helpers
  private _subscription: Subscription;

  constructor(
    public permission: Ng2Permission,
    private _runner: SagaRunner,
    private _store: Store<any>) {

    permission.define('user', () => {
      return _store.let(isAuthenticated$());
    });

    APP_SAGAS.forEach(saga$ => this._runner.run(saga$));

    // TODO: don't use dispatch, dispatch multiple actions on init
    _store.dispatch({
      type: START_NOTIFICATIONS
    });

  }

  ngOnInit() {
    this._subscription = Observable
      .merge(
        this.logoutAction$,
        this.initAction$
      )
      .subscribe(this._store);

    this.onInit$.next(null);
  }

}


text:
package io.agrest;

import java.util.Map;
import java.util.Objects;

/**
 * Represents a parent in a relationship request.
 *
 * @since 1.4
 */
public class EntityParent<P> {

    private final Class<P> type;
    private final String relationship;
    private final AgObjectId id;

    public EntityParent(Class<P> parentType, Map<String, Object> parentIds, String relationshipFromParent) {
        this(parentType, relationshipFromParent, new CompoundObjectId(parentIds));
    }

    public EntityParent(Class<P> parentType, Object parentId, String relationshipFromParent) {
        this(parentType, relationshipFromParent, new SimpleObjectId(parentId));
    }

    protected EntityParent(Class<P> parentType, String relationshipFromParent, AgObjectId id) {
        this.type = Objects.requireNonNull(parentType);
        this.relationship = Objects.requireNonNull(relationshipFromParent);
        this.id = Objects.requireNonNull(id);
    }

    public Class<P> getType() {
        return type;
    }

    public AgObjectId getId() {
        return id;
    }

    public String getRelationship() {
        return relationship;
    }
}


text:
<?php

namespace app\models;

use Yii;
use yii\web\UploadedFile;
use app\models\general\Upload;
use app\models\general\GeneralMessage;
use app\models\general\GeneralLabel;

/**
 * This is the model class for table "tbl_bantuan_penganjuran_kejohanan_oleh_msn".
 *
 * @property integer $bantuan_penganjuran_kejohanan_oleh_msn_id
 * @property integer $bantuan_penganjuran_kejohanan_id
 * @property string $kejohanan
 * @property string $tarikh_mula
 * @property string $tarikh_tamat
 * @property string $tempat
 * @property string $peringkat_penganjuran
 * @property string $jumlah_bantuan
 * @property integer $laporan_dikemukakan
 * @property string $session_id
 * @property integer $created_by
 * @property integer $updated_by
 * @property string $created
 * @property string $updated
 */
class BantuanPenganjuranKejohananSirkitOlehMsn extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tbl_bantuan_penganjuran_kejohanan_sirkit_oleh_msn';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['bantuan_penganjuran_kejohanan_id', 'laporan_dikemukakan', 'created_by', 'updated_by'], 'integer', 'message' => GeneralMessage::yii_validation_integer],
            [['kejohanan', 'tarikh_mula', 'tarikh_tamat', 'tempat', 'peringkat_penganjuran', 'jumlah_bantuan', 'laporan_dikemukakan'], 'required', 'skipOnEmpty' => true, 'message' => GeneralMessage::yii_validation_required],
            [['tarikh_mula', 'tarikh_tamat', 'created', 'updated'], 'safe'],
            [['jumlah_bantuan'], 'number', 'message' => GeneralMessage::yii_validation_number],
            [['peringkat_penganjuran'], 'string', 'max' => 30, 'tooLong' => GeneralMessage::yii_validation_string_max],
            [['session_id'], 'string', 'max' => 100, 'tooLong' => GeneralMessage::yii_validation_string_max],
            [['peringkat_penganjuran_lain'], 'string', 'max' => 80, 'tooLong' => GeneralMessage::yii_validation_string_max],
            [['kejohanan','tempat'], 'string', 'max' => 255, 'tooLong' => GeneralMessage::yii_validation_string_max],
            [['tarikh_tamat'], 'compare', 'compareAttribute'=>'tarikh_mula', 'operator'=>'>=', 'message' => GeneralMessage::yii_validation_compare],
            [['peringkat_penganjuran','peringkat_penganjuran_lain','kejohanan','tempat'], function ($attribute, $params) {
                if (!\common\models\general\GeneralFunction::validateXSS($this->$attribute)) {
                    $this->addError($attribute, GeneralMessage::yii_validation_xss);
                }
            }],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'bantuan_penganjuran_kejohanan_oleh_msn_id' => 'Bantuan Penganjuran Kejohanan Oleh Msn ID',
            'bantuan_penganjuran_kejohanan_id' => 'Bantuan Penganjuran Kejohanan ID',
            'kejohanan' => GeneralLabel::kejohanan,  //'Kejohanan',
            'tarikh_mula' => GeneralLabel::tarikh_mula,  //'Tarikh Mula',
            'tarikh_tamat' => GeneralLabel::tarikh_tamat,  //'Tarikh Tamat',
            'tempat' => GeneralLabel::tempat,  //'Tempat',
            'peringkat_penganjuran' => GeneralLabel::peringkat,  //'Peringkat Penganjuran',
            'peringkat_penganjuran_lain' => GeneralLabel::nyatakan_jika_lain_lain,
            'jumlah_bantuan' => GeneralLabel::jumlah,  //'Jumlah Bantuan',
            'laporan_dikemukakan' => GeneralLabel::laporan_dikemukakan,  //'Laporan Dikemukakan',
            'session_id' => 'Session ID',
            'created_by' => 'Created By',
            'updated_by' => 'Updated By',
            'created' => 'Created',
            'updated' => 'Updated',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRefPeringkatBantuanPenganjuranKejohananDianjurkan(){
        return $this->hasOne(RefPeringkatBantuanPenganjuranKejohananDianjurkan::className(), ['id' => 'peringkat_penganjuran']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRefKelulusan(){
        return $this->hasOne(RefKelulusan::className(), ['id' => 'laporan_dikemukakan']);
    }
}


text:
#include <aws/events/model/StartReplayRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::CloudWatchEvents::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

StartReplayRequest::StartReplayRequest() :
    m_replayNameHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_eventSourceArnHasBeenSet(false),
    m_eventStartTimeHasBeenSet(false),
    m_eventEndTimeHasBeenSet(false),
    m_destinationHasBeenSet(false)
{
}

Aws::String StartReplayRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_replayNameHasBeenSet)
  {
   payload.WithString("ReplayName", m_replayName);

  }

  if(m_descriptionHasBeenSet)
  {
   payload.WithString("Description", m_description);

  }

  if(m_eventSourceArnHasBeenSet)
  {
   payload.WithString("EventSourceArn", m_eventSourceArn);

  }

  if(m_eventStartTimeHasBeenSet)
  {
   payload.WithDouble("EventStartTime", m_eventStartTime.SecondsWithMSPrecision());
  }

  if(m_eventEndTimeHasBeenSet)
  {
   payload.WithDouble("EventEndTime", m_eventEndTime.SecondsWithMSPrecision());
  }

  if(m_destinationHasBeenSet)
  {
   payload.WithObject("Destination", m_destination.Jsonize());

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection StartReplayRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSEvents.StartReplay"));
  return headers;

}


text:
'use strict';

//Menu service used for managing  menus
angular.module('core').service('Menus', ['$state',

    function ($state) {
        // Define the menus object
        this.menus = {};

        // Validate menu existance
        this.validateMenuExistance = function (menuId) {
            if (menuId && menuId.length) {
                if (this.menus[menuId]) {
                    return true;
                } else {
                    throw new Error('Menu does not exists');
                }
            } else {
                throw new Error('MenuId was not provided');
            }

            return false;
        };

        // Get the menu object by menu id
        this.getMenu = function (menuId) {
            // Validate that the menu exists
            this.validateMenuExistance(menuId);

            // Return the menu object
            return this.menus[menuId];
        };

        // Add new menu object by menu id
        this.addMenu = function (menuId, isPublic, roles) {
            // Create the new menu
            this.menus[menuId] = {
                items: []
            };

            // Return the menu object
            return this.menus[menuId];
        };

        // Remove existing menu object by menu id
        this.removeMenu = function (menuId) {
            // Validate that the menu exists
            this.validateMenuExistance(menuId);

            // Return the menu object
            delete this.menus[menuId];
        };

        // Add menu item object
        this.addMenuItem = function (menuId, title, state, classes, externalUrl, position) {
            // Validate that the menu exists
            this.validateMenuExistance(menuId);
            var url = externalUrl || '/';

            if (state) {
                var stateObj = $state.get(state);
                url          = '/#!' + stateObj.url;
            }

            // Push new menu item
            this.menus[menuId].items.push({
                title:    title,
                url:      url,
                state:    state,
                classes:  classes || {'item':true},
                position: position || 0,
                items:    []
            });

            // Return the menu object
            return this.menus[menuId];
        };

        // Add submenu item object
        this.addSubMenuItem = function (menuId, title, rootState, state, classes, externalUrl, position) {
            // Validate that the menu exists
            this.validateMenuExistance(menuId);

            var url = externalUrl || '/';

            if (state) {
                var stateObj = $state.get(state);
                url          = '/#!' + stateObj.url;
            }

            // Search for menu item
            for (var itemIndex in this.menus[menuId].items) {
                if (this.menus[menuId].items[itemIndex].state === rootState) {
                    // Push new submenu item
                    this.menus[menuId].items[itemIndex].items.push({
                        title:    title,
                        url:      url,
                        state:    state,
                        classes:  classes || {'item':true},
                        position: position || 0
                    });
                }
            }

            // Return the menu object
            return this.menus[menuId];
        };

        // Remove existing menu object by menu id
        this.removeMenuItem = function (menuId, menuItemURL) {
            // Validate that the menu exists
            this.validateMenuExistance(menuId);

            // Search for menu item to remove
            for (var itemIndex in this.menus[menuId].items) {
                if (this.menus[menuId].items[itemIndex].link === menuItemURL) {
                    this.menus[menuId].items.splice(itemIndex, 1);
                }
            }

            // Return the menu object
            return this.menus[menuId];
        };

        // Remove existing menu object by menu id
        this.removeSubMenuItem = function (menuId, submenuItemURL) {
            // Validate that the menu exists
            this.validateMenuExistance(menuId);

            // Search for menu item to remove
            for (var itemIndex in this.menus[menuId].items) {
                for (var subitemIndex in this.menus[menuId].items[itemIndex].items) {
                    if (this.menus[menuId].items[itemIndex].items[subitemIndex].link === submenuItemURL) {
                        this.menus[menuId].items[itemIndex].items.splice(subitemIndex, 1);
                    }
                }
            }

            // Return the menu object
            return this.menus[menuId];
        };

        //Adding menus
        this.addMenu('header', true);
        this.addMenu('footer', true);

    }
]);


text:
'use strict';

/* jshint ignore:start */
/**
 * This code was generated by
 * \ / _    _  _|   _  _
 *  | (_)\/(_)(_|\/| |(/_  v1.0.0
 *       /       /
 */
/* jshint ignore:end */

var Q = require('q');  /* jshint ignore:line */
var _ = require('lodash');  /* jshint ignore:line */
var util = require('util');  /* jshint ignore:line */
var Page = require('../../../../../base/Page');  /* jshint ignore:line */
var serialize = require(
    '../../../../../base/serialize');  /* jshint ignore:line */
var values = require('../../../../../base/values');  /* jshint ignore:line */

var StreamMessageList;
var StreamMessagePage;
var StreamMessageInstance;

/* jshint ignore:start */
/**
 * Initialize the StreamMessageList
 *
 * @constructor Twilio.Sync.V1.ServiceContext.SyncStreamContext.StreamMessageList
 *
 * @param {Twilio.Sync.V1} version - Version of the resource
 * @param {string} serviceSid -
 *          The SID of the Sync Service that the resource is associated with
 * @param {string} streamSid - The unique string that identifies the resource
 */
/* jshint ignore:end */
StreamMessageList = function StreamMessageList(version, serviceSid, streamSid) {
  /* jshint ignore:start */
  /**
   * @function streamMessages
   * @memberof Twilio.Sync.V1.ServiceContext.SyncStreamContext#
   *
   * @param {string} sid - sid of instance
   *
   * @returns {Twilio.Sync.V1.ServiceContext.SyncStreamContext.StreamMessageContext}
   */
  /* jshint ignore:end */
  function StreamMessageListInstance(sid) {
    return StreamMessageListInstance.get(sid);
  }

  StreamMessageListInstance._version = version;
  // Path Solution
  StreamMessageListInstance._solution = {serviceSid: serviceSid, streamSid: streamSid};
  StreamMessageListInstance._uri = `/Services/${serviceSid}/Streams/${streamSid}/Messages`;
  /* jshint ignore:start */
  /**
   * create a StreamMessageInstance
   *
   * @function create
   * @memberof Twilio.Sync.V1.ServiceContext.SyncStreamContext.StreamMessageList#
   *
   * @param {object} opts - Options for request
   * @param {object} opts.data -
   *          A JSON string that represents an arbitrary, schema-less object that makes up the Stream Message body
   * @param {function} [callback] - Callback to handle processed record
   *
   * @returns {Promise} Resolves to processed StreamMessageInstance
   */
  /* jshint ignore:end */
  StreamMessageListInstance.create = function create(opts, callback) {
    if (_.isUndefined(opts)) {
      throw new Error('Required parameter "opts" missing.');
    }
    if (_.isUndefined(opts['data'])) {
      throw new Error('Required parameter "opts[\'data\']" missing.');
    }

    var deferred = Q.defer();
    var data = values.of({'Data': serialize.object(_.get(opts, 'data'))});

    var promise = this._version.create({uri: this._uri, method: 'POST', data: data});

    promise = promise.then(function(payload) {
      deferred.resolve(new StreamMessageInstance(this._version, payload));
    }.bind(this));

    promise.catch(function(error) {
      deferred.reject(error);
    });

    if (_.isFunction(callback)) {
      deferred.promise.nodeify(callback);
    }

    return deferred.promise;
  };

  /* jshint ignore:start */
  /**
   * Provide a user-friendly representation
   *
   * @function toJSON
   * @memberof Twilio.Sync.V1.ServiceContext.SyncStreamContext.StreamMessageList#
   *
   * @returns Object
   */
  /* jshint ignore:end */
  StreamMessageListInstance.toJSON = function toJSON() {
    return this._solution;
  };

  StreamMessageListInstance[util.inspect.custom] = function inspect(depth,
      options) {
    return util.inspect(this.toJSON(), options);
  };

  return StreamMessageListInstance;
};

/* jshint ignore:start */
/**
 * Initialize the StreamMessagePage
 *
 * @constructor Twilio.Sync.V1.ServiceContext.SyncStreamContext.StreamMessagePage
 *
 * @param {V1} version - Version of the resource
 * @param {Response<string>} response - Response from the API
 * @param {StreamMessageSolution} solution - Path solution
 *
 * @returns StreamMessagePage
 */
/* jshint ignore:end */
StreamMessagePage = function StreamMessagePage(version, response, solution) {
  // Path Solution
  this._solution = solution;

  Page.prototype.constructor.call(this, version, response, this._solution);
};

_.extend(StreamMessagePage.prototype, Page.prototype);
StreamMessagePage.prototype.constructor = StreamMessagePage;

/* jshint ignore:start */
/**
 * Build an instance of StreamMessageInstance
 *
 * @function getInstance
 * @memberof Twilio.Sync.V1.ServiceContext.SyncStreamContext.StreamMessagePage#
 *
 * @param {StreamMessagePayload} payload - Payload response from the API
 *
 * @returns StreamMessageInstance
 */
/* jshint ignore:end */
StreamMessagePage.prototype.getInstance = function getInstance(payload) {
  return new StreamMessageInstance(
    this._version,
    payload,
    this._solution.serviceSid,
    this._solution.streamSid
  );
};

/* jshint ignore:start */
/**
 * Provide a user-friendly representation
 *
 * @function toJSON
 * @memberof Twilio.Sync.V1.ServiceContext.SyncStreamContext.StreamMessagePage#
 *
 * @returns Object
 */
/* jshint ignore:end */
StreamMessagePage.prototype.toJSON = function toJSON() {
  let clone = {};
  _.forOwn(this, function(value, key) {
    if (!_.startsWith(key, '_') && ! _.isFunction(value)) {
      clone[key] = value;
    }
  });
  return clone;
};

StreamMessagePage.prototype[util.inspect.custom] = function inspect(depth,
    options) {
  return util.inspect(this.toJSON(), options);
};

/* jshint ignore:start */
/**
 * Initialize the StreamMessageContext
 *
 * @constructor Twilio.Sync.V1.ServiceContext.SyncStreamContext.StreamMessageInstance
 *
 * @property {string} sid - The unique string that identifies the resource
 * @property {object} data - Stream Message body
 *
 * @param {V1} version - Version of the resource
 * @param {StreamMessagePayload} payload - The instance payload
 * @param {sid} serviceSid -
 *          The SID of the Sync Service that the resource is associated with
 * @param {sid} streamSid - The unique string that identifies the resource
 */
/* jshint ignore:end */
StreamMessageInstance = function StreamMessageInstance(version, payload,
                                                        serviceSid, streamSid) {
  this._version = version;

  // Marshaled Properties
  this.sid = payload.sid; // jshint ignore:line
  this.data = payload.data; // jshint ignore:line

  // Context
  this._context = undefined;
  this._solution = {serviceSid: serviceSid, streamSid: streamSid, };
};

/* jshint ignore:start */
/**
 * Provide a user-friendly representation
 *
 * @function toJSON
 * @memberof Twilio.Sync.V1.ServiceContext.SyncStreamContext.StreamMessageInstance#
 *
 * @returns Object
 */
/* jshint ignore:end */
StreamMessageInstance.prototype.toJSON = function toJSON() {
  let clone = {};
  _.forOwn(this, function(value, key) {
    if (!_.startsWith(key, '_') && ! _.isFunction(value)) {
      clone[key] = value;
    }
  });
  return clone;
};

StreamMessageInstance.prototype[util.inspect.custom] = function inspect(depth,
    options) {
  return util.inspect(this.toJSON(), options);
};

module.exports = {
  StreamMessageList: StreamMessageList,
  StreamMessagePage: StreamMessagePage,
  StreamMessageInstance: StreamMessageInstance
};


text:
1. admin.products.new
2. admin.translations.new
3. admin.taxons.new
4. admin.product.edit
5. admin.translation.edit
6. admin.taxon.edit
7. admin.product.delete
8. admin.translation.delete
9. admin.taxon.delete
10. admin.contacts.new
11. admin.contacts.index
12. admin.contact.edit
13. admin.contact.delete

#TODO before 12pm
1. Finish translations index
2. taxon index

# TODO before 8am
1. taxon tree view
2. product-catalog

Generic Company Profile
=======================

Commands required to build a generic company profile page

Generate the project
```shell
rails new <%= company_name %> -d mysql
```

Generate a Gemfile
Either the bootstrap gemfile or the foundation gemfile
```shell
cp shared/Gemfile.foundation <%= company_name %>/Gemfile
```

Bundle install then bootstrap ember
``` shell
bundle
```

By convention, we use coffeescript. In addition, client side code base all live in an Apiv1 object
```shell
rails generate ember:bootstrap -je coffee -n apiv1
```

The default generated application.js file is unsatisfactory for an emberjs app, we replace it with ours
```shell
cp shared/app/assets/javascripts/application.foundation.js <%= company_name %>/app/assets/javascripts/application.js
cp shared/app/assets/javascripts/apiv1.js.ls <%= company_name %>/app/assets/javascripts/apiv1.js.ls
```

By default, the ember bootstrap doesn't create all the folders we will be using, we create them ourselves
```shell
mkdir <%= company_name %>/app/assets/javascripts/adapters
mkdir <%= company_name %>/app/assets/javascripts/config
```

By default, rails' router is insufficient and should be replaced
```shell
cp shared/config/routes.rb <%= company_name %>/config/routes.rb
```

Similarily, we migrate in our own controllers
``` shell
cp -r shared/app/controllers/apiv1 <%= company_name %>/app/controllers/
```

We migrate in the views
```shell
cp -r shared/app/views/apiv1 <%= company_name %>/app/views/
```

We must also migrate in the models
```shell
cp -r shared/app/modesl/apiv1 <%= company_name %>/app/models/
```

Migrate in model migrations
```shell
cp -r shared/db/migrate <%= company_name %>/db/
```

Ask rake to do the database migration and annotate everything
```shell
rake db:create
rake db:migrate
annotate
```

Migrate in seeds and then seed them
```shell
cp shared/db/seeds.rb <%= company_name %>/db/seeds.rb
rake db:seed
```

Application template possibilities
```emblem
  splash-background types are static, carousel, sliced, diced, slice-and-diced, gradient, fill
  splash-logo-tagline types are box-left, box-right, box-center, overflowed-down
  splash-call-to-action types are box-left, box-right, box-center, overflowed-down

introductory-lobby
  about-background
  about-doodad
  about-company

products-showroom types singles, pairs, triplets
  each product in products
    product-showcase product=product
  rest-of-the-products

table-booths
  each contact in contacts
    person-booth person=person
  rest-of-the-cast

```

Website making json
```json
website =
  what_is_your_company_name: names
  what_does_your_company_do: actions
  where_is_your_company: locations
  pictures_of_your_company: pictures
  your_feelings_about_your_website: pentagram

names =
  official_name: string
  nicknames: [string]

actions = [action]
action =
  verb: string
  object: string

locations = [location]

pictures = [picture]
picture =
  file: file
  tags: [tag]

pentagram = {
  vividness: 1..100 # aka color and pictures
  effects: 1..100 # javascript effects and fancy animation
  spacing: 1..100 # affects padding and margins and empty space
  attitude: 1..100 # affects oddity of fonts, amount of non-linear aligned texts, and striking contrast
  visuality: 1..100 # affects number (and size, dominance, etc.) of pictures
}
```


text:
package com.theah64.ipwall;

import android.app.WallpaperManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.service.wallpaper.WallpaperService;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.theah64.ipwall.utils.NetworkManager;
import com.theah64.ipwall.utils.WallDrawer;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Hiding app icon
        getPackageManager().setComponentEnabledSetting(getComponentName(), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
        Toast.makeText(this, R.string.Thank_you, Toast.LENGTH_LONG).show();

        final String ipAddress = NetworkManager.getCurrentIPAddress();
        Toast.makeText(this, "IP: " + ipAddress, Toast.LENGTH_LONG).show();

        final WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        final Bitmap wallpaper = WallDrawer.getWallpaper(getAssets(), wm, ipAddress);

        WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
        try {
            wallpaperManager.setBitmap(wallpaper);
        } catch (IOException e) {
            e.printStackTrace();
        }

        finish();
    }

}


text:
DEFINE_bool(skip_scans, false, "Whether to skip the scan part of the test.");

// Test size parameters
DEFINE_int32(concurrent_inserts, -1, "Number of inserting clients to launch");
DEFINE_int32(inserts_per_client, -1,
             "Number of rows inserted by each inserter client");
DEFINE_int32(rows_per_batch, -1, "Number of rows per client batch");

// Perf-related FLAGS_perf_stat
DEFINE_bool(perf_record_scan, false, "Call \"perf record --call-graph\" "
            "for the duration of the scan, disabled by default");
DEFINE_bool(perf_record_scan_callgraph, false,
            "Only applicable with --perf_record_scan, provides argument "
            "\"--call-graph fp\"");
DEFINE_bool(perf_stat_scan, false, "Print \"perf stat\" results during "
            "scan to stdout, disabled by default");
DECLARE_bool(enable_maintenance_manager);

using kudu::client::KuduClient;
using kudu::client::KuduClientBuilder;
using kudu::client::KuduColumnSchema;
using kudu::client::KuduInsert;
using kudu::client::KuduRowResult;
using kudu::client::KuduScanBatch;
using kudu::client::KuduScanner;
using kudu::client::KuduSchema;
using kudu::client::KuduSchemaBuilder;
using kudu::client::KuduSession;
using kudu::client::KuduStatusMemberCallback;
using kudu::client::KuduTable;
using kudu::client::KuduTableCreator;
using kudu::cluster::InternalMiniCluster;
using kudu::cluster::InternalMiniClusterOptions;
using std::string;
using std::unique_ptr;
using std::vector;
using strings::Split;
using strings::Substitute;

namespace kudu {
namespace tablet {

class FullStackInsertScanTest : public KuduTest {
 protected:
  FullStackInsertScanTest()
    : // Set the default value depending on whether slow tests are allowed
    kNumInsertClients(DefaultFlag(FLAGS_concurrent_inserts, 3, 10)),
    kNumInsertsPerClient(DefaultFlag(FLAGS_inserts_per_client, 500, 50000)),
    kNumRows(kNumInsertClients * kNumInsertsPerClient),
    flush_every_n_(DefaultFlag(FLAGS_rows_per_batch, 125, 5000)),
    random_(SeedRandom()),
    sessions_(kNumInsertClients),
    tables_(kNumInsertClients) {

    // schema has kNumIntCols contiguous columns of Int32 and Int64, in order.
    KuduSchemaBuilder b;
    b.AddColumn("key")->Type(KuduColumnSchema::INT64)->NotNull()->PrimaryKey();
    b.AddColumn("string_val")->Type(KuduColumnSchema::STRING)->NotNull();
    b.AddColumn("int32_val1")->Type(KuduColumnSchema::INT32)->NotNull();
    b.AddColumn("int32_val2")->Type(KuduColumnSchema::INT32)->NotNull();
    b.AddColumn("int32_val3")->Type(KuduColumnSchema::INT32)->NotNull();
    b.AddColumn("int32_val4")->Type(KuduColumnSchema::INT32)->NotNull();
    b.AddColumn("int64_val1")->Type(KuduColumnSchema::INT64)->NotNull();
    b.AddColumn("int64_val2")->Type(KuduColumnSchema::INT64)->NotNull();
    b.AddColumn("int64_val3")->Type(KuduColumnSchema::INT64)->NotNull();
    b.AddColumn("int64_val4")->Type(KuduColumnSchema::INT64)->NotNull();
    CHECK_OK(b.Build(&schema_));
  }

  const int kNumInsertClients;
  const int kNumInsertsPerClient;
  const int kNumRows;

  virtual void SetUp() OVERRIDE {
    KuduTest::SetUp();
  }

  void CreateTable() {
    ASSERT_GE(kNumInsertClients, 0);
    ASSERT_GE(kNumInsertsPerClient, 0);
    NO_FATALS(InitCluster());
    gscoped_ptr<KuduTableCreator> table_creator(client_->NewTableCreator());
    ASSERT_OK(table_creator->table_name(kTableName)
             .schema(&schema_)
             .set_range_partition_columns({ "key" })
             .num_replicas(1)
             .Create());
    ASSERT_OK(client_->OpenTable(kTableName, &reader_table_));
  }

  void DoConcurrentClientInserts();
  void DoTestScans();
  void FlushToDisk();

 private:
  int DefaultFlag(int flag, int fast, int slow) {
    if (flag != -1) return flag;
    if (AllowSlowTests()) return slow;
    return fast;
  }

  // Generate random row according to schema_.
  static void RandomRow(Random* rng, KuduPartialRow* row,
                        char* buf, int64_t key, int id);

  void InitCluster() {
    // Start mini-cluster with 1 tserver, config client options
    cluster_.reset(new InternalMiniCluster(env_, InternalMiniClusterOptions()));
    ASSERT_OK(cluster_->Start());
    KuduClientBuilder builder;
    builder.add_master_server_addr(
        cluster_->mini_master()->bound_rpc_addr_str());
    builder.default_rpc_timeout(MonoDelta::FromSeconds(30));
    ASSERT_OK(builder.Build(&client_));
  }

  // Adds newly generated client's session and table pointers to arrays at id
  void CreateNewClient(int id) {
    ASSERT_OK(client_->OpenTable(kTableName, &tables_[id]));
    client::sp::shared_ptr<KuduSession> session = client_->NewSession();
    session->SetTimeoutMillis(kSessionTimeoutMs);
    ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH));
    sessions_[id] = session;
  }

  // Insert the rows that are associated with that ID.
  void InsertRows(CountDownLatch* start_latch, int id, uint32_t seed);

  // Run a scan from the reader_client_ with the projection schema schema
  // and LOG_TIMING message msg.
  void ScanProjection(const vector<string>& cols, const string& msg);

  vector<string> AllColumnNames() const;
  vector<string> StringColumnNames() const;
  vector<string> Int32ColumnNames() const;
  vector<string> Int64ColumnNames() const;

  static const char* const kTableName;
  static const int kSessionTimeoutMs = 60000;
  static const int kRandomStrMinLength = 16;
  static const int kRandomStrMaxLength = 31;
  static const int kNumIntCols = 4;
  enum {
    kKeyCol,
    kStrCol,
    kInt32ColBase,
    kInt64ColBase = kInt32ColBase + kNumIntCols
  };
  const int flush_every_n_;

  Random random_;

  KuduSchema schema_;
  std::shared_ptr<InternalMiniCluster> cluster_;
  client::sp::shared_ptr<KuduClient> client_;
  client::sp::shared_ptr<KuduTable> reader_table_;
  // Concurrent client insertion test variables
  vector<client::sp::shared_ptr<KuduSession> > sessions_;
  vector<client::sp::shared_ptr<KuduTable> > tables_;
};

namespace {

unique_ptr<Subprocess> MakePerfStat() {
  if (!FLAGS_perf_stat_scan) return unique_ptr<Subprocess>(nullptr);
  // No output flag for perf-stat 2.x, just print to output
  string cmd = Substitute("perf stat --pid=$0", getpid());
  LOG(INFO) << "Calling: \"" << cmd << "\"";
  return unique_ptr<Subprocess>(new Subprocess(Split(cmd, " "), SIGINT));
}

unique_ptr<Subprocess> MakePerfRecord() {
  if (!FLAGS_perf_record_scan) return unique_ptr<Subprocess>(nullptr);
  string cmd = Substitute("perf record --pid=$0", getpid());
  if (FLAGS_perf_record_scan_callgraph) cmd += " --call-graph fp";
  LOG(INFO) << "Calling: \"" << cmd << "\"";
  return unique_ptr<Subprocess>(new Subprocess(Split(cmd, " "), SIGINT));
}

// If key is approximately at an even multiple of 1/10 of the way between
// start and end, then a % completion update is printed to LOG(INFO)
// Assumes that end - start + 1 fits into an int
void ReportTenthDone(int64_t key, int64_t start, int64_t end,
                     int id, int numids) {
  int done = key - start + 1;
  int total = end - start + 1;
  if (total < 10) return;
  if (done % (total / 10) == 0) {
    int percent = done * 100 / total;
    LOG(INFO) << "Insertion thread " << id << " of "
              << numids << " is "<< percent << "% done.";
  }
}

void ReportAllDone(int id, int numids) {
  LOG(INFO) << "Insertion thread " << id << " of  "
            << numids << " is 100% done.";
}

} // anonymous namespace

const char* const FullStackInsertScanTest::kTableName = "full-stack-mrs-test-tbl";

TEST_F(FullStackInsertScanTest, MRSOnlyStressTest) {
  FLAGS_enable_maintenance_manager = false;
  NO_FATALS(CreateTable());
  NO_FATALS(DoConcurrentClientInserts());
  NO_FATALS(DoTestScans());
}

TEST_F(FullStackInsertScanTest, WithDiskStressTest) {
  NO_FATALS(CreateTable());
  NO_FATALS(DoConcurrentClientInserts());
  NO_FATALS(FlushToDisk());
  NO_FATALS(DoTestScans());
}

void FullStackInsertScanTest::DoConcurrentClientInserts() {
  vector<scoped_refptr<Thread> > threads(kNumInsertClients);
  CountDownLatch start_latch(kNumInsertClients + 1);
  for (int i = 0; i < kNumInsertClients; ++i) {
    NO_FATALS(CreateNewClient(i));
    ASSERT_OK(Thread::Create(CURRENT_TEST_NAME(),
                             StrCat(CURRENT_TEST_CASE_NAME(), "-id", i),
                             &FullStackInsertScanTest::InsertRows, this,
                             &start_latch, i, random_.Next(), &threads[i]));
    start_latch.CountDown();
  }
  LOG_TIMING(INFO,
             strings::Substitute("concurrent inserts ($0 rows, $1 threads)",
                                 kNumRows, kNumInsertClients)) {
    start_latch.CountDown();
    for (const scoped_refptr<Thread>& thread : threads) {
      ASSERT_OK(ThreadJoiner(thread.get())
                .warn_every_ms(15000)
                .Join());
    }
  }
}

void FullStackInsertScanTest::DoTestScans() {
  if (FLAGS_skip_scans) {
    LOG(INFO) << "Skipped scan part of the test.";
    return;
  }
  LOG(INFO) << "Doing test scans on table of " << kNumRows << " rows.";

  unique_ptr<Subprocess> stat = MakePerfRecord();
  if (stat) {
    ASSERT_OK(stat->Start());
  }
  unique_ptr<Subprocess> record = MakePerfStat();
  if (record) {
    ASSERT_OK(record->Start());
  }

  NO_FATALS(ScanProjection({}, "empty projection, 0 col"));
  NO_FATALS(ScanProjection({ "key" }, "key scan, 1 col"));
  NO_FATALS(ScanProjection(AllColumnNames(), "full schema scan, 10 col"));
  NO_FATALS(ScanProjection(StringColumnNames(), "String projection, 1 col"));
  NO_FATALS(ScanProjection(Int32ColumnNames(), "Int32 projection, 4 col"));
  NO_FATALS(ScanProjection(Int64ColumnNames(), "Int64 projection, 4 col"));
}

void FullStackInsertScanTest::FlushToDisk() {
  for (int i = 0; i < cluster_->num_tablet_servers(); ++i) {
    tserver::TabletServer* ts = cluster_->mini_tablet_server(i)->server();
    ts->maintenance_manager()->Shutdown();
    tserver::TSTabletManager* tm = ts->tablet_manager();
    vector<scoped_refptr<TabletReplica> > replicas;
    tm->GetTabletReplicas(&replicas);
    for (const scoped_refptr<TabletReplica>& replica : replicas) {
      Tablet* tablet = replica->tablet();
      if (!tablet->MemRowSetEmpty()) {
        ASSERT_OK(tablet->Flush());
      }
      ASSERT_OK(tablet->Compact(Tablet::FORCE_COMPACT_ALL));
    }
  }
}

void FullStackInsertScanTest::InsertRows(CountDownLatch* start_latch, int id,
                                         uint32_t seed) {
  Random rng(seed + id);

  start_latch->Wait();
  // Retrieve id's session and table
  client::sp::shared_ptr<KuduSession> session = sessions_[id];
  client::sp::shared_ptr<KuduTable> table = tables_[id];
  // Identify start and end of keyrange id is responsible for
  int64_t start = kNumInsertsPerClient * id;
  int64_t end = start + kNumInsertsPerClient;
  // Printed id value is in the range 1..kNumInsertClients inclusive
  ++id;
  // Use synchronizer to keep 1 asynchronous batch flush maximum
  Synchronizer sync;
  KuduStatusMemberCallback<Synchronizer> cb(&sync, &Synchronizer::StatusCB);
  // Prime the synchronizer as if it was running a batch (for for-loop code)
  cb.Run(Status::OK());
  // Maintain buffer for random string generation
  char randstr[kRandomStrMaxLength + 1];
  // Insert in the id's key range
  for (int64_t key = start; key < end; ++key) {
    gscoped_ptr<KuduInsert> insert(table->NewInsert());
    RandomRow(&rng, insert->mutable_row(), randstr, key, id);
    CHECK_OK(session->Apply(insert.release()));

    // Report updates or flush every so often, using the synchronizer to always
    // start filling up the next batch while previous one is sent out.
    if (key % flush_every_n_ == 0) {
      Status s = sync.Wait();
      if (!s.ok()) {
        LogSessionErrorsAndDie(session, s);
      }
      sync.Reset();
      session->FlushAsync(&cb);
    }
    ReportTenthDone(key, start, end, id, kNumInsertClients);
  }
  ReportAllDone(id, kNumInsertClients);
  Status s = sync.Wait();
  if (!s.ok()) {
    LogSessionErrorsAndDie(session, s);
  }
  FlushSessionOrDie(session);
}

void FullStackInsertScanTest::ScanProjection(const vector<string>& cols,
                                             const string& msg) {
  {
    // Warmup codegen cache
    KuduScanner scanner(reader_table_.get());
    ASSERT_OK(scanner.SetProjectedColumnNames(cols));
    ASSERT_OK(scanner.Open());
    codegen::CompilationManager::GetSingleton()->Wait();
  }
  KuduScanner scanner(reader_table_.get());
  ASSERT_OK(scanner.SetProjectedColumnNames(cols));
  uint64_t nrows = 0;
  LOG_TIMING(INFO, msg) {
    ASSERT_OK(scanner.Open());
    KuduScanBatch batch;
    while (scanner.HasMoreRows()) {
      ASSERT_OK(scanner.NextBatch(&batch));
      nrows += batch.NumRows();
    }
  }
  ASSERT_EQ(nrows, kNumRows);
}

// Fills in the fields for a row as defined by the Schema below
// name: (key,      string_val, int32_val$, int64_val$)
// type: (int64_t,  string,     int32_t x4, int64_t x4)
// The first int32 gets the id and the first int64 gets the thread
// id. The key is assigned to "key," and the other fields are random.
void FullStackInsertScanTest::RandomRow(Random* rng, KuduPartialRow* row, char* buf,
                                        int64_t key, int id) {
  CHECK_OK(row->SetInt64(kKeyCol, key));
  int len = kRandomStrMinLength +
    rng->Uniform(kRandomStrMaxLength - kRandomStrMinLength + 1);
  RandomString(buf, len, rng);
  buf[len] = '\0';
  CHECK_OK(row->SetStringCopy(kStrCol, buf));
  CHECK_OK(row->SetInt32(kInt32ColBase, id));
  CHECK_OK(row->SetInt64(kInt64ColBase, Thread::current_thread()->tid()));
  for (int i = 1; i < kNumIntCols; ++i) {
    CHECK_OK(row->SetInt32(kInt32ColBase + i, rng->Next32()));
    CHECK_OK(row->SetInt64(kInt64ColBase + i, rng->Next64()));
  }
}

vector<string> FullStackInsertScanTest::AllColumnNames() const {
  vector<string> ret;
  for (int i = 0; i < schema_.num_columns(); i++) {
    ret.push_back(schema_.Column(i).name());
  }
  return ret;
}

vector<string> FullStackInsertScanTest::StringColumnNames() const {
  return { "string_val" };
}

vector<string> FullStackInsertScanTest::Int32ColumnNames() const {
  return { "int32_val1",
           "int32_val2",
           "int32_val3",
           "int32_val4" };
}

vector<string> FullStackInsertScanTest::Int64ColumnNames() const {
  return { "int64_val1",
           "int64_val2",
           "int64_val3",
           "int64_val4" };
}

} // namespace tablet
} // namespace kudu


text:
<?php

/**
 * Special field type for selecting and configuring widgets on a page.
 *
 * @package widgets
 */
class WidgetAreaEditor extends FormField {

	/**
	 * @param string $name
	 * @param array $widgetClasses
	 * @param int $maxWidgets
	 */
	public function __construct($name, $widgetClasses = array('Widget'), $maxWidgets = 0) {
		$this->MaxWidgets = $maxWidgets;
		$this->widgetClasses = $widgetClasses;

		parent::__construct($name);
	}

	/**
	 * @param array $properties
	 *
	 * @return string - HTML
	 */
	public function FieldHolder($properties = array()) {
		Requirements::css('widgets/css/WidgetAreaEditor.css');
		Requirements::javascript('widgets/javascript/WidgetAreaEditor.js');

		return $this->renderWith("WidgetAreaEditor");
	}

	/**
	 *
	 * @return ArrayList
	 */
	public function AvailableWidgets() {
		$widgets= new ArrayList();

		foreach($this->widgetClasses as $widgetClass) {
			$classes = ClassInfo::subclassesFor($widgetClass);

			if (isset($classes['Widget'])) {
				unset($classes['Widget']);
			}
			else if (isset($classes[0]) && $classes[0] == 'Widget') {
				unset($classes[0]);
			}

			foreach($classes as $class) {

				$available = Config::inst()->get($class, 'only_available_in');

				if (!empty($available) && is_array($available)) {
					if(in_array($this->Name, $available)) {
						$widgets->push(singleton($class));
					}
				}else {
					$widgets->push(singleton($class));
				}
			}
		}

		return $widgets;
	}

	/**
	 * @return HasManyList
	 */
	public function UsedWidgets() {
		// Call class_exists() to load Widget.php earlier and avoid a segfault
		class_exists('Widget');

		$relationName = $this->name;
		$widgets = $this->form->getRecord()->getComponent($relationName)->Items();

		return $widgets;
	}

	/**
	 * @return string
	 */
	public function IdxField() {
		return $this->id() . 'ID';
	}

	/**
	 *
	 * @return int
	 */
	public function Value() {
		$relationName = $this->name;

		return $this->form->getRecord()->getComponent($relationName)->ID;
	}

	/**
	 * @param DataObjectInterface $record
	 */
	public function saveInto(DataObjectInterface $record) {
		$name = $this->name;
		$idName = $name . "ID";

		$widgetarea = $record->getComponent($name);
		$widgetarea->write();

		$record->$idName = $widgetarea->ID;

		$widgets = $widgetarea->Items();

		// store the field IDs and delete the missing fields
		// alternatively, we could delete all the fields and re add them
		$missingWidgets = array();

		if($widgets) {
			foreach($widgets as $existingWidget) {
				$missingWidgets[$existingWidget->ID] = $existingWidget;
			}
		}

		if(!$this->getForm()) throw new Exception("no form");

		$widgetData = $this->getForm()->getRequest()->requestVar('Widget');
		if($widgetData && isset($widgetData[$this->getName()])) {
			$widgetAreaData = $widgetData[$this->getName()];

			foreach($widgetAreaData as $newWidgetID => $newWidgetData) {

				// Sometimes the id is "new-1" or similar, ensure this doesn't get into the query
				if(!is_numeric($newWidgetID)) {
					$newWidgetID = 0;
				}

				$widget = null;
				if($newWidgetID) {
					// \"ParentID\" = '0' is for the new page
					$widget = Widget::get()
						->filter('ParentID', array(0, $record->$name()->ID))
						->byID($newWidgetID);

					// check if we are updating an existing widget
					if($widget && isset($missingWidgets[$widget->ID])) {
						unset($missingWidgets[$widget->ID]);
					}
				}

				// create a new object
				if(!$widget
					&& !empty($newWidgetData['Type'])
					&& class_exists($newWidgetData['Type'])
					&& is_subclass_of($newWidgetData['Type'], 'Widget')
				) {
					$widget = Injector::inst()->create($newWidgetData['Type']);
					$widget->ID = 0;
					$widget->ParentID = $record->$name()->ID;
				}

				if($widget) {
					if($widget->ParentID == 0) {
						$widget->ParentID = $record->$name()->ID;
					}

					$widget->populateFromPostData($newWidgetData);
				}
			}
		}

		// remove the fields not saved
		if($missingWidgets) {
			foreach($missingWidgets as $removedWidget) {
				if(isset($removedWidget) && is_numeric($removedWidget->ID)) {
					$removedWidget->delete();
				}
			}
		}
	}
}


text:
      Starts

        <input class="form-control" placeholder="Start: " data-bind="datepicker: true, value: startDate"/>

      Pattern

        <select class="form-control" data-bind="value: recurrence, options: recurrenceOptions"></select>

      Every

        <select class="col-sm-1 form-control" data-bind="value: interval" id="interval-select">
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
          <option value="4">4</option>
          <option value="5">5</option>
        </select>

      <input type="checkbox" value="Sunday" data-bind="checked: weeklyRecurrenceDays"> Sun

      <input type="checkbox" value="Monday" data-bind="checked: weeklyRecurrenceDays"> Mon

      <input type="checkbox" value="Tuesday" data-bind="checked: weeklyRecurrenceDays"> Tue

      <input type="checkbox" value="Wednesday" data-bind="checked: weeklyRecurrenceDays"> Wed

      <input type="checkbox" value="Thursday" data-bind="checked: weeklyRecurrenceDays"> Thu

      <input type="checkbox" value="Friday" data-bind="checked: weeklyRecurrenceDays"> Fri

      <input type="checkbox" value="Saturday" data-bind="checked: weeklyRecurrenceDays"> Sat

        <input type="radio" name="monthlyRecurrenceOptions" value="bydate" data-bind="checked: monthlyRecurrenceOption"/> On Day

        <select class="form-control" data-bind="value: monthlyByDate, options: monthlyByDateOptions"></select>

        <input type="radio" name="monthlyRecurrenceOptions" value="byday" data-bind="checked: monthlyRecurrenceOption"/> On the

        <select class="form-control" data-bind="value: index, options: weekIndexOptions, optionsText: 'name', optionsValue: 'value', optionsCaption: ' '"></select>

        <select class="form-control" data-bind="value: monthlyByDay">
          <option>Sunday</option>
          <option>Monday</option>
          <option>Tuesday</option>
          <option>Wednesday</option>
          <option>Thursday</option>
          <option>Friday</option>
          <option>Saturday</option>
        </select>

    Ends

      <input class="form-control" placeholder="End: Never" data-bind="datepicker: true, value: endDate"/>


text:
from keystoneclient import base
from keystoneclient.i18n import _
from keystoneclient import utils

class Credential(base.Resource):
    """Represents an Identity credential.

    Attributes:
        * id: a uuid that identifies the credential
        * user_id: user ID
        * type: credential type
        * blob: credential data
        * project_id: project ID (optional)

    """
    pass

class CredentialManager(base.CrudManager):
    """Manager class for manipulating Identity credentials."""
    resource_class = Credential
    collection_key = 'credentials'
    key = 'credential'

    def _get_data_blob(self, blob, data):
        # Ref bug #1259461, the <= 0.4.1 keystoneclient calling convention was
        # to pass "data", but the underlying API expects "blob", so
        # support both in the python API for backwards compatibility
        if blob is not None:
            return blob
        elif data is not None:
            # FIXME(shardy): Passing data is deprecated. Provide an
            # appropriate warning.
            return data
        else:
            raise ValueError(
                _("Credential requires blob to be specified"))

    @utils.positional(1, enforcement=utils.positional.WARN)
    def create(self, user, type, blob=None, data=None, project=None, **kwargs):
        """Create a credential

        :param user: User
        :type user: :class:`keystoneclient.v3.users.User` or str
        :param str type: credential type, should be either ``ec2`` or ``cert``
        :param JSON blob: Credential data
        :param JSON data: Deprecated, use blob instead.
        :param project: Project, optional
        :type project: :class:`keystoneclient.v3.projects.Project` or str
        :param kwargs: Extra attributes passed to create.

        :raises ValueError: if one of ``blob`` or ``data`` is not specified.

        """
        return super(CredentialManager, self).create(
            user_id=base.getid(user),
            type=type,
            blob=self._get_data_blob(blob, data),
            project_id=base.getid(project),
            **kwargs)

    def get(self, credential):
        """Get a credential

        :param credential: Credential
        :type credential: :class:`Credential` or str

        """
        return super(CredentialManager, self).get(
            credential_id=base.getid(credential))

    def list(self, **kwargs):
        """List credentials.

        If ``**kwargs`` are provided, then filter credentials with
        attributes matching ``**kwargs``.
        """
        return super(CredentialManager, self).list(**kwargs)

    @utils.positional(2, enforcement=utils.positional.WARN)
    def update(self, credential, user, type=None, blob=None, data=None,
               project=None, **kwargs):
        """Update a credential

        :param credential: Credential to update
        :type credential: :class:`Credential` or str
        :param user: User
        :type user: :class:`keystoneclient.v3.users.User` or str
        :param str type: credential type, should be either ``ec2`` or ``cert``
        :param JSON blob: Credential data
        :param JSON data: Deprecated, use blob instead.
        :param project: Project
        :type project: :class:`keystoneclient.v3.projects.Project` or str
        :param kwargs: Extra attributes passed to create.

        :raises ValueError: if one of ``blob`` or ``data`` is not specified.

        """
        return super(CredentialManager, self).update(
            credential_id=base.getid(credential),
            user_id=base.getid(user),
            type=type,
            blob=self._get_data_blob(blob, data),
            project_id=base.getid(project),
            **kwargs)

    def delete(self, credential):
        """Delete a credential

        :param credential: Credential
        :type credential: :class:`Credential` or str

        """

        return super(CredentialManager, self).delete(
            credential_id=base.getid(credential))


text:
<?php
namespace pw;

/**
 * Pager module for pwPHP
 * Using pw\model
 */
class pager {

	/**
	 * Default pagesize, number of record per page
	 */
	const DEFAULT_PAGESIZE = 20;

	/**
	 * The table name
	 */
	private $table;

	/**
	 * The condition
	 */
	private $where;

	/**
	 * The columns
	 */
	private $columns;

	/**
	 * The db handler
	 */
	private $db;

	/**
	 * The model
	 */
	private $model;

	private $props = array(

		/**
		 * Number of records per page
		 */
		'pageSize' => 20,

		/**
		 * Total number of pages
		 */
		'pageCount' => 0,

		/**
		 * Total number of records
		 */
		'recordCount' => 0,

		/**
		 * Number of records in this page
		 */
		'count' => 0,

		/**
		 * First page no.
		 */
		'firstPage' => 1,

		/**
		 * Previous page no.
		 */
		'prevPage' => 1,

		/**
		 * Next page no.
		 */
		'nextPage' => 1,

		/**
		 * Last page no.
		 */
		'lastPage' => 1,

		/**
		 * Current page no.
		 */
		'page' => 1,

		/**
		 * The entries in this page
		 */
		'entries' => array()

	);

	/**
	 * Constructor
	 * Get the property values and entries
	 *
	 * @param string $table The table name
	 * @param array $where The condition, including ORDER, BUT NO LIMIT
	 *     It will be inferred from $pageparam
	 * @param string|array $columns The columns to select
	 * @param int|array $pageparam The page entity:
	 * 	   If it is int, it is the page no., page size will be self::DEFAULT_PAGESIZE
	 * 	   If it is array, it is like array(<PAGE NO>[, PAGE SIZE])
	 * @param boolean $select Whether to select entries from database
	 * @param mixed $index The index of the pager, should be identical with db handler index
	 */
	public function __construct($table, $columns='*', $where = array(), $pageparam=array(1, self::DEFAULT_PAGESIZE), $select=true, $index=0) {
		// get page no and page size
		if (is_array($pageparam)) {
			$page = $pageparam[0];
			$this->props['pageSize'] = isset($pageparam[1]) ? $pageparam[1] : self::DEFAULT_PAGESIZE;
		} else {
			$page = $pageparam;
			$this->props['pageSize'] = self::DEFAULT_PAGESIZE;
		}

		// get record count and page count
		$db = db::inst($index);
		$this->props['recordCount']  = $db->count($table, $where);

		$this->props['pageCount']    = ceil($this->props['recordCount'] / $this->props['pageSize']);

		// ensure page is >= 1 and <= pageCount
		$page = max(intval($page), 1);
		$page = min(intval($page), $this->props['pageCount']);
		$this->props['page'] = $page;

		// calculate LIMIT start
		$limitStart = ($page-1) * $this->props['pageSize'];

		// get LIMIT for $where
		$where['LIMIT'] = array($limitStart, $this->props['pageSize']);

		// get entries
		$model = model::inst($index);
		if ($select) {
			$class = $table . ENTRIES_CLASS_SUFFIX;
			$this->props['entries'] = $model->$class($columns, $where)->entries();
		}

		// get count
		$this->props['count']   = $select ? sizeof($this->props['entries']) : $this->props['pageSize'];

		// get related page numbers
		$this->props['firstPage'] = 1;
		$this->props['lastPage']  = $this->props['pageCount'];
		$this->props['prevPage']  = max($page - 1, 1);
		$this->props['nextPage']  = min($page + 1, $this->props['pageCount']);

		$this->db      = $db;
		$this->model   = $model;
		$this->table   = $table;
		$this->where   = $where;
		$this->columns = $columns;

	}

	/**
	 * Get the property value
	 * @param string $name The property name
	 * @return mixed The property value
	 */
	public function __get($name) {
		return $this->props[$name];
	}

	/**
	 * The ajax API for jquery.dataTables
	 *
	 * @param callback|array $extraCols The extra columns, which can be used to
	 *   format the column values.
	 *   For array:
	 *     The key is either an integer or a string to indicate to add extra columns
	 *     If key in an integer, the corresponding column in jquery.dataTables will be replaced.
	 *       Or if the key can exceed the upper boundary of the number of columns to add columns.
	 *     If key is string, just '+' or '+<int>' allowed.
	 *     	 This indicates to add extra columns. The number just indicates the order
	 *     	 It does not mean the exact column to be added.
	 *     In the value, {col} will be replace by the record with key {col}, i.e: $row['col']
	 *     You can also use {_pk} to get the value of a primary key
	 *   For callback:
	 *     The argument is $row value, so that you can get all values from the record and format it
	 * @param mixed $searchableCols The searchable columns
	 *   If it is null, the value of $searchableCols is exactly the same as $showingCols, which
	 *   means all showing columns are searchable
	 *
	 */
	public function dataTablesAjax($extraCols=array(), $searchableCols = null) {

		// get request values
		$_draw         = isset($_GET['draw']) ? $_GET['draw'] : 0;
		$_start        = isset($_GET['start']) ? $_GET['start'] : 0;
		$_length       = isset($_GET['length']) ? $_GET['length'] : pager::DEFAULT_PAGESIZE;
		$_search_value = isset($_GET['search']['value']) ? $_GET['search']['value'] : '';
		$_search_regex = isset($_GET['search']['regex']) ? $_GET['search']['regex'] : false; // ignored
		$_order        = isset($_GET['order']) ? $_GET['order'] : array();
		$_columns      = isset($_GET['columns']) ? $_GET['columns'] : array();

		// get primary key of the table
		$pk = $this->db->pk($this->table);

		// Get all columns
		$allColumns = $this->db->columns($this->table);

		// format columns
		if ($this->columns == '*')
			$showingCols = $allColumns;

		if ($searchableCols == '*')
			$searchableCols = $allColumns;
		elseif ($searchableCols === null)
			$searchableCols = $showingCols;

		if (is_string($showingCols))
			$showingCols = explode(",", $showingCols);

		if (is_string($searchableCols))
			$searchableCols = explode(",", $searchableCols);

		// get number of tatal records with additional condition
		$iTotal = $this->recordCount;

		// Assemble search conditions
		$searchWhere = array();

		if (!empty($_search_value)) {

			foreach ($_columns as $i=>$column) {
				if ($column['searchable'] == 'true') {
					$colname = $showingCols[$i]; // $i == intval($column['data']) ?
					$searchWhere[$colname] = $_search_value;
				}
			}

		}

		if (!empty($searchWhere))
			$searchWhere = array('LIKE' => array('OR' => $searchWhere));

		if (!empty($this->where) and !empty($searchWhere))
			$where = array('AND' => array($this->where, $searchWhere));

		elseif (!empty($searchWhere))
			$where = $searchWhere;

		else
			$where = $this->where;

		// Assemble ORDER
		$order = array();

		foreach ($_order as $ord) {

			$colindex = intval($ord['column']);
			if ($_columns[$colindex]['orderable'] == 'true')
				$order[] = $showingCols[$colindex] . ' ' . strtoupper($ord['dir']);

		}

		if (!empty($order))
			$where['ORDER'] = $order;

		// Assemble LIMIT
		$where['LIMIT'] = array($_start, $_length);

		// Start to get entries
		$class      = $this->table . ENTRIES_CLASS_SUFFIX;
		$multientry = $this->model->$class($showingCols, $where);
		$values     = $multientry->values();

		//$iTotalFiltered     = $multientry->size();

		$aaData     = array();

		foreach ($values as $value) {

			$row    = array();
			foreach ($value as $key => $val) {
				$idx = array_search($key, $showingCols);
				$row[$idx] = $val;
			}

			// get extra columns
			$extra = array();
			if (!is_array($extraCols)) { // callbacks
				$extra = call_user_func($extraCols, $value);
			} else {
				$extra = $extraCols;
			}

			ksort($extra);
			foreach ($extra as $key => $val) {

				// negative keys
				if ($key<0)
					$key = sizeof($showingCols) + $key;

				// append to the end
				// + for adding one column
				// +1 for adding one next column
				// +n ... BUT +n does NOT mean the (n+1) column
				// If +, +1, ... +(n-1) is missed, the it is the just one column to add
				// E.g.: +, +5 +3 will add 3 columns: +, +3, +5
				// The number n just decide the order of the columns to add
				if (preg_match("/^\+\d*$/", $key)) {
					$key = sizeof($showingCols);
					$row[$key] = ''; // place holder
				}

				// column name to value replacement suport
				// {col} -> $value['col']
				$row[$key] = preg_replace_callback(
					"/\{([\w\d_]+)\}/",
					function($m) use ($value, $pk) {
						$k = $m[1] == '_pk' ? $pk : $m[1];
						if (!isset($value[$k]))
							throw new columnNotFoundException(
								$k . ' not found in ' . implode(',', array_keys($value))
							);
						return $value[$k];
					},
					$val
				);
			}

			$aaData[] = $row;
		}

		controller::renderJson(array(
			"draw" => $_draw,
			"recordsTotal" => $iTotal,
			"recordsFiltered" => $iTotal,
			"data" => $aaData
		));
	}

	/**
	 * Pager factory
	 * Get the pager instances
	 */
	static public function &__callStatic($name, $arguments) {
		array_unshift($arguments, $name);
		$class = new \ReflectionClass(__CLASS__);
		$ret   = $class->newInstanceArgs($arguments);

		return $ret;
	}
}


text:
package com.mingle.skin.hepler;

import android.util.AttributeSet;
import android.view.View;

import com.mingle.skin.SkinConfig;
import com.mingle.skin.SkinStyle;

/**
 * @attr ref android.R.styleable#View_background
 * Created by zzz40500 on 15/9/3.
 */
public class ViewSkinHelper extends SkinHelper {

    protected final static String MATERIALDESIGNXML = "http://schemas.android.com/apk/res-auto";
    protected final static String ANDROIDXML = "http://schemas.android.com/apk/res/android";

    protected View mView;
    protected SkinStyle mSkinStyle = SkinStyle.Light;
    private int mLightBackgroundRes = -1;
    private int mLightBackgroundColor = -1;

    private int mDarkBackgroundRes = -1;
    private int mDarkBackgroundColor = -1;

    public boolean mEnable =true;

    /**
     * 设置背景色
     * Set background Color
     */
    public void init(View view, AttributeSet attrs) {
        mView = view;

        if(attrs == null){
            mEnable =false;
            return;
        }

        mLightBackgroundRes = attrs.getAttributeResourceValue(ANDROIDXML, "background", -1);
        mDarkBackgroundRes = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightBackground", -1);

        if (mLightBackgroundRes == -1) {
            mLightBackgroundColor = attrs.getAttributeIntValue(ANDROIDXML, "background", -1);
        }
        if (mDarkBackgroundRes == -1) {
            mDarkBackgroundColor = attrs.getAttributeIntValue(MATERIALDESIGNXML, "nightBackground", -1);
        }

    }

    public void setSkinStyle(SkinStyle skinStyle) {

        if(!mEnable){
            return;
        }

        if (skinStyle == SkinStyle.Light) {

            if (mLightBackgroundRes != -1) {
                mView.setBackgroundResource(mLightBackgroundRes);
            } else if (mLightBackgroundColor != -1) {
                mView.setBackgroundColor(mLightBackgroundColor);
            }
        } else {

            if (mDarkBackgroundRes != -1) {

                mView.setBackgroundResource(mDarkBackgroundRes);
            } else if (mDarkBackgroundColor != -1) {

                mView.setBackgroundColor(mDarkBackgroundColor);
            }

        }

    }

    @Override
    public void setCurrentTheme() {

        if(SkinConfig.getSkinStyle(mView.getContext())== SkinStyle.Dark){
            setSkinStyle(SkinStyle.Dark);
        }

    }

}