text:
%{
MIT License

Copyright (c) [2016] [Mallory Ann Jensen, jensenma@alum.mit.edu]

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
%}

%Read a .txt file which has been output from a measurement and store the
%RAW DATA. Put this into a format which will be accepted by other scripts.
function [data_now,time,PC,PL,gen] = format_QSSPL_rawdata(data_filename,savename)
%Open the text file
fileID = fopen(data_filename);
%Read line-by-line
tline = fgetl(fileID);
line = 1;
sample_count = 1;
new_line = 0;
while ischar(tline)
    %If we have numbers, str2num should give us a 1D array
    this_line_num = str2num(tline);
    %Check whether this is the header. If not, proceed.
    if isempty(this_line_num)==0
        if line == 2 || new_line == 1
            %We need to start the data_now storage
            data_now = [this_line_num(1,1) this_line_num(1,2) this_line_num(1,3) this_line_num(1,4)];
            new_line = 0;
        else
            %Then we just add this line to our existing structure
            data_now(end+1,:) = [this_line_num(1,1) this_line_num(1,2) this_line_num(1,3) this_line_num(1,4)];
        end
    end
    tline = fgetl(fileID);
    %Increment the line counter
    line = line+1;
end
%close the file
fclose(fileID);
%Plot our results for the visual check
figure;
plot(data_now(:,1),data_now(:,2));
hold all;
plot(data_now(:,1),data_now(:,3));
hold all;
plot(data_now(:,1),data_now(:,4));
xlabel('Time [s]','FontSize',20);
ylabel('Voltage [V]','FontSize',20);
legend('Generation','PC','PL');
time = data_now(:,1);
PC = data_now(:,3);
gen = data_now(:,2);
PL = data_now(:,4);
dataSave{1} = data_now;
%Now we should have read the entire file. Save.
save(savename,'dataSave','PC','time','PL','gen');


text:
import re,sys,collections

def get_stacks(f):
    """
    get_stacks parses file f and yields all lines in go stackrace as one array
    """
    accum = []
    for line in f:
        line = line.rstrip()
        if line.startswith("goroutine"):
            yield accum
            accum = []
        else:
            accum.append(line)

# Regexes used to find and remove addresses, ids and age
strip_addresses = re.compile(r"0x[0-9a-fA-F]+")
strip_goroutine_id = re.compile(r"goroutine [0-9]+")
strip_goroutine_time = re.compile(r", [0-9]+ minutes")
def strip_stack(stack):
    """
    strip_stack replaces addresses, goroutine IDs and ages with a fixed sentinel
    """
    stack = [strip_addresses.sub("0x?", l) for l in stack]
    stack = [strip_goroutine_id.sub("?", l) for l in stack]
    stack = [strip_goroutine_time.sub("", l) for l in stack]
    return stack

def get_hashable_stack_value(stack):
    """
    get_hashable_stack_value transforms stack (and array of strings) into
    something that can be used as a map key
    """
    return "".join(strip_stack(stack))

def print_usage():
    print """usage: {} [-h | path/to/file]
        -h:         This help.
        path/to/file:   Read and parse file with go stacktraces
        "-" or no params: Read and parse stdin""".format(sys.argv[0])

if __name__ == "__main__":
    # Handle arguments. We only support a file path, or stdin on "-" or no
    # parameter
    infile = sys.argv[1] if len(sys.argv) > 1 else ""
    if infile in ["-h", "help"]:
        print_usage()
        sys.exit(0)
    elif infile in ["-", "", None]:
        f = sys.stdin
    else:
        f = open(infile)

    # collect stacktraces into groups, each keyed by a version of the stack
    # where unwanted fields have been made into sentinels
    consolidated = collections.defaultdict(list)
    for stack in get_stacks(f):
        h = get_hashable_stack_value(stack)
        consolidated[h].append(stack)

    # print count of each unique stack, and a sample, sorted by frequency
    print "{} unique stack traces".format(len(consolidated))
    for stack in sorted(consolidated.values(), cmp=lambda a,b: len(a)-len(b), reverse=True):
        print "{} occurences. Sample stack trace:".format(len(stack))
        print "\n".join(stack[0])

    if f != sys.stdin:
        f.close()

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals

import collections
import collections.abc
import enum
import importlib
import logging

import termineter.errors
import termineter.options

import pluginbase

_ModuleReference = collections.namedtuple('_ModuleReference', ('instance', 'pymodule'))

class ConnectionState(enum.Enum):
	none = 'none'
	connected = 'connected'
	authenticated = 'authenticated'

class ManagerManager(collections.abc.Mapping):
	def __init__(self, frmwk, searchpath):
		self.logger = logging.getLogger('termineter.module_manager')
		self.frmwk = frmwk
		self.source = pluginbase.PluginBase(package='termineter.modules').make_plugin_source(
			searchpath=searchpath
		)
		self._modules = {}
		for module_id in self.source.list_plugins():
			self._init_pymodule(self.source.load_plugin(module_id))

	def __getitem__(self, item):
		return self._modules[item].instance

	def __iter__(self):
		return iter(self._modules)

	def __len__(self):
		return len(self._modules)

	def _init_pymodule(self, pymodule):
		module_id = pymodule.__name__.split('.', 3)[-1]
		if not hasattr(pymodule, 'Module'):
			self.logger.error('module: ' + module_id + ' is missing the Module class')
			return
		if not issubclass(pymodule.Module, TermineterModule):
			self.logger.error('module: ' + module_id + ' is not derived from the TermineterModule class')
			return

		module_instance = pymodule.Module(self.frmwk)
		if not isinstance(module_instance.options, termineter.options.Options):
			self.logger.critical('module: ' + module_id + ' options must be an Options instance')
			raise termineter.errors.FrameworkRuntimeError('options must be a termineter.options.Options instance')
		if not isinstance(module_instance.advanced_options, termineter.options.Options):
			self.logger.critical('module: ' + module_id + ' advanced_options must be an Options instance')
			raise termineter.errors.FrameworkRuntimeError('advanced_options must be a termineter.options.Options instance')

		self._modules[module_instance.name] = _ModuleReference(instance=module_instance, pymodule=pymodule)
		return module_instance

	def reload(self, module_path):
		modref = self._modules[module_path]
		importlib.reload(modref.pymodule)
		return self._init_pymodule(modref.pymodule)

class TermineterModule(object):
	frmwk_required_options = ()
	def __init__(self, frmwk):
		self.frmwk = frmwk
		self.author = ['Anonymous']
		self.description = 'This module is undocumented.'
		self.detailed_description = 'This module is undocumented.'
		self.options = termineter.options.Options(frmwk.directories)
		self.advanced_options = termineter.options.AdvancedOptions(frmwk.directories)

	def __repr__(self):
		return '<' + self.__class__.__name__ + ' ' + self.name + ' >'

	def get_missing_options(self):
		frmwk_missing_options = self.frmwk.options.get_missing_options()
		frmwk_missing_options.extend(self.frmwk.advanced_options.get_missing_options())

		missing_options = []
		for required_option in self.frmwk_required_options:
			if required_option in frmwk_missing_options:
				missing_options.append(required_option)
		missing_options.extend(self.options.get_missing_options())
		missing_options.extend(self.advanced_options.get_missing_options())
		return missing_options

	@property
	def logger(self):
		return self.frmwk.get_module_logger(self.name)

	@property
	def name(self):
		return self.path.split('/')[-1]

	@property
	def path(self):
		return self.__module__.split('.', 3)[-1].replace('.', '/')

	def run(self):
		raise NotImplementedError()

class TermineterModuleOptical(TermineterModule):
	frmwk_required_options = (
		'SERIAL_CONNECTION',
		'USERNAME',
		'USER_ID',
		'PASSWORD',
		'PASSWORD_HEX',
		'SERIAL_BAUD_RATE',
		'SERIAL_BYTE_SIZE',
		'CACHE_TABLES',
		'SERIAL_STOP_BITS',
		'NUMBER_PACKETS',
		'PACKET_SIZE'
	)
	connection_state = ConnectionState.authenticated
	connection_states = ConnectionState
	def __init__(self, *args, **kwargs):
		super(TermineterModuleOptical, self).__init__(*args, **kwargs)

	@property
	def connection(self):
		return self.frmwk.serial_connection


text:
<?php
/**
 * Creates a basket set up in an ecommerce environment. Returns an instance of this class, using sessions to return the
 * basket.
 *
 * Created by PhpStorm.
 * User: ciaran
 * Date: 02/07/14
 * Time: 09:23
 */

class Nova_Basket
{

    /**
     * @var array
     */
    protected $_items = array ();

    /**
     * @var array
     */
    protected $_itemRules = array ();

    /**
     * @param $itemRules
     * @return $this
     */
    public function setItemRules($itemRules)
    {
        $this->_itemRules = $itemRules;
        return $this;
    }

    /**
     * @return array
     */
    public function getItemRules()
    {
        return $this->_itemRules;
    }

    /**
     * @return mixed
     */
    public function getBasket()
    {
        return Session_Base::get('basket');
    }

    /**
     * Add an item to the basket
     *
     * @param array $item
     * @return $this
     */
    public function add(array $item)
    {
        //Check for an existing basket
        if (NovaSession::get('basket') !== false)
        {
            $this->_items = NovaSession::get('basket');
        }

        $item['name'] = key($item);
        $item['quantity'] = $item[key($item)];
        unset($item[key($item)]);

        //Check for any existing items. If there are, add the quantity on.
        foreach ($this->_items as $key=>$value)
        {
            if ($item['name'] == $value['name'])
            {
                $item['quantity'] += $value['quantity'];
                unset($this->_items[$key]);
            }
        }

        array_push($this->_items, $item);

        NovaSession::set('basket', $this->_items);
        return $this;
    }

    /**
     * Remove an item from the basket
     *
     * @param $item
     * @return $this
     */
    public function remove($item)
    {
        if(($key = array_search($item, NovaSession::get('basket'))) !== false) {
            NovaSession::destroyKey('basket', $key);
            return $this;
        }
        else
        {
            echo 'That item was not found in the basket';
        }
    }
}


text:
import jinja2
import os
import webapp2

template_dir = os.path.join(os.path.dirname(__file__), "templates")
jinja_env = jinja2.Environment(
    loader = jinja2.FileSystemLoader(template_dir),
    autoescape = True)

class BaseHandler(webapp2.RequestHandler):

    def write(self, *a, **kw):
        self.response.out.write(*a, **kw)

    def render_str(self, file_name, **params):
        template = jinja_env.get_template(file_name)
        return template.render(params)

    def render(self, file_name, **kw):
        self.write(self.render_str(file_name, **kw))

class MainHandler(BaseHandler):
    def get(self):
        self.render("main.html", title = "AI Experiments")

class SearchHandler(BaseHandler):
    def get(self):
        self.render("search.html", title = "AI Experiments - Search")

class SlidePuzzleHandler(BaseHandler):
    def get(self):
        self.render("slide-puzzle.html", title = "AI Experiments - Slide Puzzle")

app = webapp2.WSGIApplication([
    ('/', MainHandler),
    ('/search', SearchHandler),
    # search.html should be kept since the page was initially served statically
    # maybe in the future it can be removed. (March, 25, 2014)
    ('/search.html', SearchHandler),
    ('/slide-puzzle', SlidePuzzleHandler)
], debug=True)


text:
{{{
  "title": "Deploy Microsoft SQL Server using Blueprint",
  "date": "12-01-2016",
  "author": "Chris Little",
  "attachments": [],
  "contentIsHTML": false
}}}

### **IMPORTANT NOTICE**
**As of December 1, 2016, the service fees for Microsoft SQL Licensing on CenturyLink Cloud changed from 1 vCPU minimum to a 4 vCPU minimum, and moved from hourly usage based billing to fixed monthly billing. If you have questions about this change or did not receive notifications on this change please contact customer care at help@ctl.io.**

### Table of Contents
* [Overview](#overview)
* [Socket to vCPU Allocation](#socket-to-vcpu-allocation)
* [Prerequisites](#prerequisites)
* [Exceptions](#exceptions)
* [General Notes](#general-notes)
* [Installing Microsoft SQL Server using Execute Package](#installing-microsoft-sql-server-using-execute-package)
* [Installing Microsoft SQL Server using Blueprint Library](#installing-microsoft-sql-server-using-blueprint-library)

### Overview
CenturyLink Cloud customers can procure and deploy Microsoft SQL Server licensing within the Control Portal. Microsoft SQL Server is licensed via the Microsoft SPLA program. By using the CenturyLink Cloud public Blueprint customers have multiple ways to consume and install this business critical database software.

### Socket to vCPU Allocation
It is recommended customers review our delivery model for [Sockets to vCPU](../Servers/platform-socket-to-vcpu-allocation.md) prior to deploying Microsoft SQL Server to be fully aware of the platform default operations when allocating vCPUs for use with the database service.

### Prerequisites
* A CenturyLink Cloud Account
* ~15 GB Free Storage on C:\
* Operating System and SQL Server Edition aligns in a supported fashion:

SQL Server Edition|Supported Operating Systems
------------------|---------------------------
SQL Server 2008 R2 Web Edition 64-bit
SQL Server 2008 R2 Standard Edition 64-bit
SQL Server 2008 R2 Enterprise Edition 64-bit|Windows 2008 R2 Standard 64-bit
Windows 2008 R2 Enterprise 64-bit
Windows 2008 R2 Datacenter 64-bit
Windows 2012 Datacenter 64-bit
Windows 2012 R2 Datacenter 64-bit
SQL Server 2012 Web Edition 64-bit
SQL Server 2012 Standard Edition 64-bit
SQL Server 2012 Enterprise Edition 64-bit|Windows 2008 R2 Standard 64-bit
Windows 2008 R2 Enterprise 64-bit
Windows 2008 R2 Datacenter 64-bit
Windows 2012 Datacenter 64-bit
Windows 2012 R2 Datacenter 64-bit
SQL Server 2014 Web Edition 64-bit
SQL Server 2014 Standard Edition 64-bit
SQL Server 2014 Enterprise Edition 64-bit|Windows 2008 R2 Standard 64-bit
Windows 2008 R2 Enterprise 64-bit
Windows 2008 R2 Datacenter 64-bit
Windows 2012 Datacenter 64-bit
Windows 2012 R2 Datacenter 64-bit
SQL Server 2016 Web Edition 64-bit
SQL Server 2016 Standard Edition 64-bit
SQL Server 2016 Enterprise Edition 64-bit|Windows 2012 Datacenter 64-bit
Windows 2012 R2 Datacenter 64-bit

* Validate the Hardware and Software Requirements for Installing SQL Server are met:
    * [SQL Server 2008 R2](//msdn.microsoft.com/en-us/library/ms143506%28v=sql.105%29.aspx)
    * [SQL Server 2012](//msdn.microsoft.com/en-us/library/ms143506%28v=sql.110%29.aspx)
    * [SQL Server 2014](//msdn.microsoft.com/en-us/library/ms143506%28v=sql.120%29.aspx)
    * [SQL Server 2016](//msdn.microsoft.com/en-us/library/ms143506%28v=sql.130%29.aspx)

### Exceptions
This KB does not apply to [Managed Microsoft SQL Customers](//www.ctl.io/managed-services/ms-sql).

### General Notes
The following are quick tips/notes based on past experiences with customers leveraging this Blueprint.

* It is not possible at the current time to install SQL to a drive other than C:\ via Blueprint. Customers can modify the SQL database, tempdb, log locations post install to other volumes using SQL tools
* The fee's for Microsoft SQL server will be applied automatically to the customers invoice when using the public Blueprint. These fee's are available in the [Pricing Catalog](//www.ctl.io/pricing). If you are unsure what these fee's are please contact your account manager.
* Licensing fee's are adjusted based on number of vCPU allocated to a virtual machine with a minimum of 4 vCPU license fees incurred.  Customers billing will be modified as vCPU configurations change.
* Customers can **add features** to an existing SQL instance by running the Blueprint multiple times on the same server and only selecting the additional features required.
* Customers can **add new** SQL instances by running the Blueprint multiple times on the same server.
* Due to Microsoft's licensing constraints, changing the version/edition is not possible. Customers who want to change this must create a new server and SQL instance with the version/edition desired and migrate their data.

### Installing Microsoft SQL Server using Execute Package
1. Navigate to **Orchestration, Scripts** in Control.

  ![servers menu in control portal](../images/deploy-microsoft-sql-server-using-blueprint-01.png)

2. Browse to the Group that houses the VM(s) you want to deploy SQL. Select **Execute Package**.

  ![select execute package](../images/deploy-microsoft-sql-server-using-blueprint-02.png)

3. Search for **Install SQL** and select the **Install SQL Server on Windows** (for version 2008/2012/2014) or **Install SQL Server 2016 on Windows** (for version 2016) script.

  ![search for SQL and choose script](../images/deploy-microsoft-sql-server-using-blueprint-03.png)

4. Select SQL Installation Options.
   * Input the appropriate parameters based on the SQL server requirements for your application.
   * Select the VM(s) in the Group you want to deploy SQL. Customers can choose an individual VM or multiple. (Quick Tip: Only supported Guest Operating Systems will be shown.)

  ![select installation options](../images/deploy-microsoft-sql-server-using-blueprint-04.png)

### Installing Microsoft SQL Server using Blueprint Library
1. Navigate to **Orchestration, Blueprint Library** in Control.

  ![navigate to Blueprint library](../images/deploy-microsoft-sql-server-using-blueprint-05.png)

2. Search for **Install SQL** and select **Install SQL Server on Existing Server** (for version 2008/2012/2014) or **Install SQL Server 2016 on Existing Server** (for version 2016). Select the appropriate Blueprint.

  ![search menu with Blueprint choices](../images/deploy-microsoft-sql-server-using-blueprint-06.png)

3. Select Deploy Blueprint.

  ![deploy Blueprint](../images/deploy-microsoft-sql-server-using-blueprint-07.png)

4. Input the appropriate parameters based on the SQL server requirements for your application and select the Virtual Machine you wish to execute the install against.

  ![input parameters](../images/deploy-microsoft-sql-server-using-blueprint-08.png)

5. Confirm the virtual machine(s), features and select Deploy Blueprint.

  ![confirm inputs and deploy](../images/deploy-microsoft-sql-server-using-blueprint-09.png)


text:
from . import Model

class Account (Model):
    def __init__(self, data):
        Model.__init__(self, data)


text:
package com.pddstudio.substratum.template.patcher.internal.model;

import com.google.gson.annotations.SerializedName;
import com.pddstudio.substratum.template.patcher.TemplateConfiguration;
import com.pddstudio.substratum.template.patcher.ThemeConfiguration;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import java8.util.Objects;
import java8.util.stream.StreamSupport;

/**
 * Created by pddstudio on 25/04/2017.
 */

public class JsonConfigModel implements Serializable, ThemeConfiguration {

	@SerializedName("themeName")
	private String themeName;

	@SerializedName("themeAuthor")
	private String themeAuthor;

	@SerializedName("themeTemplates")
	private List<Template> templateList;

	@Override
	public String getThemeName() {
		return themeName;
	}

	@Override
	public String getThemeAuthor() {
		return themeAuthor;
	}

	@Override
	public List<TemplateConfiguration> getThemeTemplates() {
		List<TemplateConfiguration> configurations = new ArrayList<>();
		StreamSupport.stream(templateList).filter(Objects::nonNull).forEach(configurations::add);
		return configurations;
	}

}


text:
import path from 'path';
import url from 'url';

const paths = {};

const resolvePath = (request) => {
    return new Promise((resolve, reject) => {
        const { previous } = request;
        let { current } = request;
        if (current.substr(0, 5) === 'jspm:') {
            current = current.replace(/^jspm:/, '');
            if (!current.match(/\.s(c|a)ss/))
                current += '.scss';
            System.normalize(current)
                .then(file => {
                  resolve(file.replace(/\.js$|\.ts$/, ''));
                })
                .catch(e => { reject(e); });
        } else {
            const prevBase = path.dirname(previous) + '/';
            const base = (previous === 'stdin') ? request.options.urlBase : paths[previous] || prevBase;
            let resolved = url.resolve(base, current);
            if (previous !== 'stdin') paths[current] = path.dirname(resolved) + '/';
            if (!resolved.match(/\.s(c|a)ss/))
                resolved += '.scss';

            resolve(resolved);
        }
    });
};

export default resolvePath;


text:
package org.sleuthkit.autopsy.modules.embeddedfileextractor;

import org.openide.util.NbBundle;
import org.openide.util.lookup.ServiceProvider;
import org.sleuthkit.autopsy.coreutils.Version;
import org.sleuthkit.autopsy.ingest.FileIngestModule;
import org.sleuthkit.autopsy.ingest.IngestModuleFactory;
import org.sleuthkit.autopsy.ingest.IngestModuleFactoryAdapter;
import org.sleuthkit.autopsy.ingest.IngestModuleIngestJobSettings;

/**
 * A factory for creating file level ingest module that extracts embedded files
 * from supported archive and document formats.
 */
@NbBundle.Messages({
    "EmbeddedFileExtractorIngestModule.ArchiveExtractor.moduleName=Embedded File Extractor",
    "EmbeddedFileExtractorIngestModule.ArchiveExtractor.moduleDesc.text=Extracts embedded files (doc, docx, ppt, pptx, xls, xlsx, zip, rar, arj, 7z, gzip, bzip2, tar), schedules them for ingestion, and populates the directory tree with them."
})
@ServiceProvider(service = IngestModuleFactory.class)
public class EmbeddedFileExtractorModuleFactory extends IngestModuleFactoryAdapter {

    static String getModuleName() {
        return Bundle.EmbeddedFileExtractorIngestModule_ArchiveExtractor_moduleName();
    }

    @Override
    public String getModuleDisplayName() {
        return getModuleName();
    }

    static String getOutputFolderName() {
        return "EFE";
    }

    @Override
    public String getModuleDescription() {
        return Bundle.EmbeddedFileExtractorIngestModule_ArchiveExtractor_moduleDesc_text();
    }

    @Override
    public String getModuleVersionNumber() {
        return Version.getVersion();
    }

    @Override
    public boolean isFileIngestModuleFactory() {
        return true;
    }

    @Override
    public FileIngestModule createFileIngestModule(IngestModuleIngestJobSettings ingestOptions) {
        return new EmbeddedFileExtractorIngestModule();
    }

}


text:
import os, datetime
from numpy import array
import pylab as pl
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.dates import DateFormatter
from matplotlib.widgets import MultiCursor

import const
from rwlogging import log

class Trader():
	def __init__(self, strategyName):
		self.initBalance = const.INITIAL_BAL

		plt.rcParams.update({'axes.labelsize':10})
		plt.rcParams.update({'xtick.labelsize':8})
		plt.rcParams.update({'ytick.labelsize':8})

		self.strategyName = strategyName
		self.balance = self.initBalance
		self.equity = self.initBalance
		self.position = 0
		self.args = []

		self.stats = {}
		self.stats['lastDate'] = '1900-01-01'
		self.stats['lastEquity'] = self.initBalance
		self.stats['downDays'] = 0
		self.stats['date'] = []
		self.stats['equity'] = []
		self.stats['balance'] = []
		self.stats['position'] = []
		self.stats['price'] = []
		self.stats['buy'] = {}
		self.stats['buy']['date'] = []
		self.stats['buy']['price'] = []
		self.stats['sell'] = {}
		self.stats['sell']['date'] = []
		self.stats['sell']['price'] = []
		self.stats['log'] = []

	def processOrder(self, dt, price, volume, notes=''):

		opos = self.position
		self.position += volume

		if const.FEE_TYPE == 1:
			fee = volume * const.FEE_RATE
		elif const.FEE_TYPE == 2:
			fee = price * volume * const.FEE_RATE

		if volume > 0:
			self.balance = self.balance - volume * price - fee
			self.stats['buy']['date'].append(dt)
			self.stats['buy']['price'].append(price)
		elif volume < 0:
			self.balance = self.balance - volume * price + fee
			self.stats['sell']['date'].append(dt)
			self.stats['sell']['price'].append(price)

		self.calcEquity(price)
		dtstr = dt.strftime('%Y-%m-%d')
		self.stats['log'].append('ORDER,' + self.strategyName + ',' + dtstr + ',' + str(price) + ',' + str(volume) + ',POS: ' + str(opos) + '->' + str(self.position) + ',' + str(round(self.equity, 2)) + ',' + notes)

		self.summary(dt, price)

	def calcEquity(self, price):
		if const.FEE_TYPE == 1:
			fee = self.position * const.FEE_RATE
		elif const.FEE_TYPE == 2:
			fee = price * self.position * const.FEE_RATE

		if self.position < 0:
			self.equity = self.balance + self.position * price + fee
		else:
			self.equity = self.balance + self.position * price - fee

	def summary(self, dt, price):
		ddate = dt.strftime('%Y-%m-%d')

		if ddate == self.stats['lastDate']: return
		self.stats['lastDate'] = ddate

		self.calcEquity(price)
		if self.equity < self.stats['lastEquity']: self.stats['downDays'] += 1
		self.stats['lastEquity'] = self.equity
		self.stats['date'].append(dt)
		self.stats['equity'].append(self.equity)
		self.stats['balance'].append(self.balance)
		self.stats['position'].append(self.position)
		self.stats['price'].append(price)

	def generateGraph(self, resultPath, rate = 0):
		emax = max(self.stats['equity'])
		emin = min(self.stats['equity'])

		fig = plt.figure()
		ax1 = fig.add_subplot(211)
		#ax1 = plt.subplot2grid((7, 1), (0, 0), rowspan=3)
		ax1.set_ylabel('Equity')
		ax1.plot_date(self.stats['date'], self.stats['equity'], color='r', linestyle='-', marker='', label='Equity')
		#ax1.grid()
		ax1.xaxis.set_major_formatter(DateFormatter('%m-%d'))
		ax1.vlines(self.stats['buy']['date'], emin, emax, color='y', linestyles ='dotted')
		ax1.vlines(self.stats['sell']['date'], emin, emax, color='g', linestyles ='dotted')

		ax2 = fig.add_subplot(212)
		#ax2 = plt.subplot2grid((7, 1), (3, 0), rowspan=3)
		ax2.set_ylabel('Price')
		ax2.plot_date(self.stats['date'], self.stats['price'], color='black', linestyle='-', marker='', label='Price')
		ax2.plot_date(self.stats['buy']['date'], self.stats['buy']['price'], color='r', linestyle='', marker='^')
		ax2.plot_date(self.stats['sell']['date'], self.stats['sell']['price'], color='b', linestyle='', marker='v')
		#ax2.grid()
		ax2.xaxis.set_major_formatter(DateFormatter('%m-%d'))

		if rate > 0:
			fname = str(rate) + '_' + self.strategyName
		else:
			fname = self.strategyName

		plt.savefig(os.path.join(resultPath, fname + '.png'), dpi=150)
		plt.close(fig)
		return


text:
PLEASE NOTE: This document applies to the HEAD of the source tree

If you are using a released version of Kubernetes, you should
refer to the docs that go with that version.

The latest 1.0.x release of this document can be found
[here](http://releases.k8s.io/release-1.0/docs/user-guide/replication-controller.md).

Documentation for other releases can be found at
[releases.k8s.io](http://releases.k8s.io).

--

# Replication Controller

**Table of Contents**

- [Replication Controller](#replication-controller)
  - [What is a _replication controller_?](#what-is-a-replication-controller)
  - [How does a replication controller work?](#how-does-a-replication-controller-work)
    - [Pod template](#pod-template)
    - [Labels](#labels)
  - [Responsibilities of the replication controller](#responsibilities-of-the-replication-controller)
  - [Common usage patterns](#common-usage-patterns)
    - [Rescheduling](#rescheduling)
    - [Scaling](#scaling)
    - [Rolling updates](#rolling-updates)
    - [Multiple release tracks](#multiple-release-tracks)
  - [API Object](#api-object)

## What is a _replication controller_?

A _replication controller_ ensures that a specified number of pod "replicas" are running at any one time.  If there are too many, it will kill some.  If there are too few, it will start more. Unlike in the case where a user directly created pods, a replication controller replaces pods that are deleted or terminated for any reason, such as in the case of node failure or disruptive node maintenance, such as a kernel upgrade. For this reason, we recommend that you use a replication controller even if your application requires only a single pod. Think of it similarly to a process supervisor, only it supervises multiple pods across multiple nodes instead of individual processes on a single node.  A replication controller delegates local container restarts to some agent on the node (e.g., Kubelet or Docker).

As discussed in [life of a pod](pod-states.md), `ReplicationController` is *only* appropriate for pods with `RestartPolicy = Always`. (Note: If `RestartPolicy` is not set, the default value is `Always`.)  `ReplicationController` should refuse to instantiate any pod that has a different restart policy. As discussed in [issue #503](http://issue.k8s.io/503#issuecomment-50169443), we expect other types of controllers to be added to Kubernetes to handle other types of workloads, such as build/test and batch workloads, in the future.

A replication controller will never terminate on its own, but it isn't expected to be as long-lived as services. Services may be composed of pods controlled by multiple replication controllers, and it is expected that many replication controllers may be created and destroyed over the lifetime of a service (for instance, to perform an update of pods that run the service). Both services themselves and their clients should remain oblivious to the replication controllers that maintain the pods of the services.

## How does a replication controller work?

### Pod template

A replication controller creates new pods from a template, which is currently inline in the `ReplicationController` object, but which we plan to extract into its own resource [#170](http://issue.k8s.io/170).

Rather than specifying the current desired state of all replicas, pod templates are like cookie cutters. Once a cookie has been cut, the cookie has no relationship to the cutter. There is no quantum entanglement. Subsequent changes to the template or even switching to a new template has no direct effect on the pods already created. Similarly, pods created by a replication controller may subsequently be updated directly. This is in deliberate contrast to pods, which do specify the current desired state of all containers belonging to the pod. This approach radically simplifies system semantics and increases the flexibility of the primitive, as demonstrated by the use cases explained below.

Pods created by a replication controller are intended to be fungible and semantically identical, though their configurations may become heterogeneous over time. This is an obvious fit for replicated stateless servers, but replication controllers can also be used to maintain availability of master-elected, sharded, and worker-pool applications. Such applications should use dynamic work assignment mechanisms, such as the [etcd lock module](https://coreos.com/docs/distributed-configuration/etcd-modules/) or [RabbitMQ work queues](https://www.rabbitmq.com/tutorials/tutorial-two-python.html), as opposed to static/one-time customization of the configuration of each pod, which is considered an anti-pattern. Any pod customization performed, such as vertical auto-sizing of resources (e.g., cpu or memory), should be performed by another online controller process, not unlike the replication controller itself.

### Labels

The population of pods that a replication controller is monitoring is defined with a [label selector](labels.md#label-selectors), which creates a loosely coupled relationship between the controller and the pods controlled, in contrast to pods, which are more tightly coupled to their definition. We deliberately chose not to represent the set of pods controlled using a fixed-length array of pod specifications, because our experience is that approach increases complexity of management operations, for both clients and the system.

The replication controller should verify that the pods created from the specified template have labels that match its label selector. Though it isn't verified yet, you should also ensure that only one replication controller controls any given pod, by ensuring that the label selectors of replication controllers do not target overlapping sets. If you do end up with multiple controllers that have overlapping selectors, you will have to manage the deletion yourself with --cascade=false until there are no controllers with an overlapping superset of selectors.

Note that replication controllers may themselves have labels and would generally carry the labels their corresponding pods have in common, but these labels do not affect the behavior of the replication controllers.

Pods may be removed from a replication controller's target set by changing their labels. This technique may be used to remove pods from service for debugging, data recovery, etc. Pods that are removed in this way will be replaced automatically (assuming that the number of replicas is not also changed).

Similarly, deleting a replication controller does not affect the pods it created. Its `replicas` field must first be set to 0 in order to delete the pods controlled. (Note that the client tool, kubectl, provides a single operation, [stop](kubectl/kubectl_stop.md) to delete both the replication controller and the pods it controls. However, there is no such operation in the API at the moment)

## Responsibilities of the replication controller

The replication controller simply ensures that the desired number of pods matches its label selector and are operational. Currently, only terminated pods are excluded from its count. In the future, [readiness](http://issue.k8s.io/620) and other information available from the system may be taken into account, we may add more controls over the replacement policy, and we plan to emit events that could be used by external clients to implement arbitrarily sophisticated replacement and/or scale-down policies.

The replication controller is forever constrained to this narrow responsibility. It itself will not perform readiness nor liveness probes. Rather than performing auto-scaling, it is intended to be controlled by an external auto-scaler (as discussed in [#492](http://issue.k8s.io/492)), which would change its `replicas` field. We will not add scheduling policies (e.g., [spreading](http://issue.k8s.io/367#issuecomment-48428019)) to the replication controller. Nor should it verify that the pods controlled match the currently specified template, as that would obstruct auto-sizing and other automated processes. Similarly, completion deadlines, ordering dependencies, configuration expansion, and other features belong elsewhere. We even plan to factor out the mechanism for bulk pod creation ([#170](http://issue.k8s.io/170)).

The replication controller is intended to be a composable building-block primitive. We expect higher-level APIs and/or tools to be built on top of it and other complementary primitives for user convenience in the future. The "macro" operations currently supported by kubectl (run, stop, scale, rolling-update) are proof-of-concept examples of this. For instance, we could imagine something like [Asgard](http://techblog.netflix.com/2012/06/asgard-web-based-cloud-management-and.html) managing replication controllers, auto-scalers, services, scheduling policies, canaries, etc.

## Common usage patterns

### Rescheduling

As mentioned above, whether you have 1 pod you want to keep running, or 1000, a replication controller will ensure that the specified number of pods exists, even in the event of node failure or pod termination (e.g., due to an action by another control agent).

### Scaling

The replication controller makes it easy to scale the number of replicas up or down, either manually or by an auto-scaling control agent, by simply updating the `replicas` field.

### Rolling updates

The replication controller is designed to facilitate rolling updates to a service by replacing pods one-by-one.

As explained in [#1353](http://issue.k8s.io/1353), the recommended approach is to create a new replication controller with 1 replica, scale the new (+1) and old (-1) controllers one by one, and then delete the old controller after it reaches 0 replicas. This predictably updates the set of pods regardless of unexpected failures.

Ideally, the rolling update controller would take application readiness into account, and would ensure that a sufficient number of pods were productively serving at any given time.

The two replication controllers would need to create pods with at least one differentiating label, such as the image tag of the primary container of the pod, since it is typically image updates that motivate rolling updates.

Rolling update is implemented in the client tool
[kubectl](kubectl/kubectl_rolling-update.md)

### Multiple release tracks

In addition to running multiple releases of an application while a rolling update is in progress, it's common to run multiple releases for an extended period of time, or even continuously, using multiple release tracks. The tracks would be differentiated by labels.

For instance, a service might target all pods with `tier in (frontend), environment in (prod)`.  Now say you have 10 replicated pods that make up this tier.  But you want to be able to 'canary' a new version of this component.  You could set up a replication controller with `replicas` set to 9 for the bulk of the replicas, with labels `tier=frontend, environment=prod, track=stable`, and another replication controller with `replicas` set to 1 for the canary, with labels `tier=frontend, environment=prod, track=canary`.  Now the service is covering both the canary and non-canary pods.  But you can mess with the replication controllers separately to test things out, monitor the results, etc.

## API Object

Replication controller is a top-level resource in the kubernetes REST API. More details about the
API object can be found at: [ReplicationController API
object](https://htmlpreview.github.io/?https://github.com/kubernetes/kubernetes/HEAD/docs/api-reference/definitions.html#_v1_replicationcontroller).

[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/user-guide/replication-controller.md?pixel)]()


text:
#import "NSObject.h"

#import "NSCopying-Protocol.h"

@class MLContentRating, MLMovieProperties, NSArray, NSData, NSDictionary, NSMutableDictionary, NSString;

@interface MLTrackImport : NSObject <NSCopying>
{
    NSData *_artworkData;
    NSString *_assetFilePath;
    NSArray *_chapters;
    NSMutableDictionary *_properties;
    _Bool _shouldAddToPurchasedPlaylist;
    _Bool _assignArtworkCacheIDFromAlbum;
}

+ (void)initialize;
@property(nonatomic) _Bool shouldAddToPurchasedPlaylist; // @synthesize shouldAddToPurchasedPlaylist=_shouldAddToPurchasedPlaylist;
@property(copy, nonatomic) NSArray *chapters; // @synthesize chapters=_chapters;
@property(nonatomic) _Bool assignArtworkCacheIDFromAlbum; // @synthesize assignArtworkCacheIDFromAlbum=_assignArtworkCacheIDFromAlbum;
@property(copy, nonatomic) NSString *assetFilePath; // @synthesize assetFilePath=_assetFilePath;
@property(copy, nonatomic) NSData *artworkData; // @synthesize artworkData=_artworkData;
- (void).cxx_destruct;
- (void)_addSortStrings;
- (void)normalizeEntityProperties;
- (id)copyEntityProperties;
- (id)valueForEntityProperty:(id)arg1;
- (void)setValue:(id)arg1 forEntityProperty:(id)arg2;
@property(copy, nonatomic) MLMovieProperties *movieProperties;
@property(nonatomic) unsigned int mediaType;
@property(copy, nonatomic) MLContentRating *contentRating;
@property(readonly, nonatomic) NSDictionary *entityProperties;
- (id)copyWithZone:(struct _NSZone *)arg1;
- (id)init;

@end


text:
'use strict';

function Detector() {
  this.data = {};

  // Store the current time
  this.data.time = new Date();
}

Detector.prototype.collect = function (property, collector) {

  if (property === undefined || typeof property === 'number') {
    throw new Error('Properties must be a string property name or an array of property names');
  }

  if (Object.prototype.toString.call(property) === '[object Array]') {
    for (var i = 0; i < property.length; i++) {
      this.data[property[i]] = this[this.getMethodByProperty(property[i])]();
    }
  } else if (typeof property === 'string' && collector !== undefined && typeof collector === 'function') {
    this.data[property] = collector();
  } else {
    this.data[property] = (this[this.getMethodByProperty(property)]());
  }

  return this;

};

Detector.prototype.getMethodByProperty = function (method) {

  return 'get' + method.charAt(0).toUpperCase() + method.substr(1).toLowerCase();

};

Detector.prototype.getBrowser = function () {

  return navigator.userAgent;

};

Detector.prototype.getFlash = function () {

  if (window.swfobject === undefined) {
    throw new Error('SWFObject is not available. SWFObject is required for Adobe Flash detection.');
  } else {
    return window.swfobject.getFlashPlayerVersion();
  }

};


text:
    <ng-content select=".field-title"></ng-content>

<ng-container *ngIf="tipable">

</ng-container>

<ng-container *ngIf="sortable">

</ng-container>

<ng-template #tip>
    <ng-content select=".tip-content"></ng-content>
</ng-template>

<ng-template #filter>
    <ng-content select="[nb-table-filter]"></ng-content>

        <button size="sm" theme="primary" nb-button (click)="onFilter()">筛选</button>
        <button size="sm" theme="default" nb-button (click)="onCancel()">重置</button>

</ng-template>

<nb-overlay #overlay placement="bottom-left" (closeHandler)="onFilterPanelHide($event)">

        <ng-container *ngTemplateOutlet="filter"></ng-container>

</nb-overlay>


text:
//-----------------------------------------------------------------------
// <copyright file="SetVelocity.cs" company="https://github.com/marked-one/EasyStateMachine">
//     Copyright © 2014-2015 Vladimir Klubkov. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace EasyStateMachine.Functions.Physics2d
{
    using UnityEngine;

    /// Sets velocity to Rigidbody2D.
    [AddComponentMenu("Easy State Machine/Functions/Physics2d/Set Velocity")]
    public sealed class SetVelocity : Function
    {
        [Header("Set")]
        [SerializeField]
        bool global = false;

        [SerializeField,]
        string vector2 = null;

        [Header("as velocity")]
        [SerializeField]
        Rigidbody2D to = null;

#pragma warning disable 0414
        [Space(8)]
        [SerializeField]
        [Tooltip("Choose where the job should be done.")]
        In @in = In.FixedUpdate;
#pragma warning restore 0414

        void Do()
        {
            Vector2 velocity;
            if (TryGet(global, vector2, out velocity, Vector2.zero))
                to.velocity = velocity;
        }
    }
}


text:
namespace FakeWin8.Conditions
{
    using System;

    internal class ParametersCondition<T>
    {
        private readonly Func<T, bool> parameterPredicate;

        internal ParametersCondition(Func<T, bool> parameterPredicate)
        {
            this.parameterPredicate = parameterPredicate;
        }

        internal bool IsMet(T parameter)
        {
            return this.parameterPredicate.Invoke(parameter);
        }
    }
}


text:
using System.Collections.Generic;

using BolfTracker.Models;

namespace BolfTracker.Services
{
    public interface IPlayerService
    {
        Player GetPlayer(int id);

        IEnumerable<Player> GetPlayers();

        Player Create(string name);

        Player Update(int id, string name);

        void Delete(int id);

        void CalculatePlayerStatistics();

        void CalculatePlayerStatistics(int month, int year, bool calculateCareerStatistics);

        PlayerStatistics GetPlayerStatistics(int playerId, int month, int year);

        IEnumerable<PlayerStatistics> GetPlayerStatistics(int playerId);

        IEnumerable<PlayerStatistics> GetPlayerStatistics(int month, int year);

        IEnumerable<PlayerGameStatistics> GetPlayerGameStatistics(int playerId);

        IEnumerable<PlayerGameStatistics> GetPlayerGameStatistics(int month, int year);

        IEnumerable<PlayerGameStatistics> GetPlayerGameStatistics(int playerId, int month, int year);

        PlayerCareerStatistics GetPlayerCareerStatistics(int playerId);

        IEnumerable<PlayerCareerStatistics> GetPlayerCareerStatistics();

        IEnumerable<PlayerHoleStatistics> GetPlayerHoleStatistics(int month, int year);

        IEnumerable<PlayerHoleStatistics> GetPlayerHoleStatistics(int playerId, int month, int year);
    }
}


text:
package com.manning.nettyinaction.chapter8;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpRequestEncoder;
import io.netty.handler.codec.http.HttpResponseDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;

/**
 * Listing 8.2 of Netty in Action
 *
 * @author Norman Maurer
 */
public class HttpDecoderEncoderInitializer extends ChannelInitializer<Channel> {

    private final boolean client;

    public HttpDecoderEncoderInitializer(boolean client) {
        this.client = client;
    }

    @Override
    protected void initChannel(Channel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        if (client) {
            pipeline.addLast("decoder", new HttpResponseDecoder());
            pipeline.addLast("encoder", new HttpRequestEncoder());
        } else {
            pipeline.addLast("decoder", new HttpRequestDecoder());
            pipeline.addLast("encoder", new HttpResponseEncoder());
        }
    }
}


text:
package org.teavm.devserver.deobfuscate;

import java.io.InputStream;
import org.teavm.jso.typedarrays.Int8Array;

public class Int8ArrayInputStream extends InputStream {
    private Int8Array array;
    private int pos;

    public Int8ArrayInputStream(Int8Array array) {
        this.array = array;
    }

    @Override
    public int read() {
        if (pos >= array.getLength()) {
            return -1;
        }
        return array.get(pos++) & 0xFF;
    }

    @Override
    public int read(byte[] b, int off, int len) {
        if (pos >= array.getLength()) {
            return -1;
        }
        int count = Math.min(len, array.getLength() - pos);
        for (int i = 0; i < count; ++i) {
            b[off++] = array.get(pos++);
        }
        return count;
    }
}


text:
import re
import sys

try:
    from setuptools import setup, find_packages
    packages = find_packages(exclude=('tests',))
except ImportError:
    if sys.version_info[0] == 3:
        raise RuntimeError('distribute is required to install this package.')
    from distutils.core import setup
    packages = ['sqlparse', 'sqlparse.engine']

def get_version():
    """Parse __init__.py for version number instead of importing the file."""
    VERSIONFILE = 'sqlparse/__init__.py'
    verstrline = open(VERSIONFILE, "rt").read()
    VSRE = r'^__version__ = [\'"]([^\'"]*)[\'"]'
    mo = re.search(VSRE, verstrline, re.M)
    if mo:
        return mo.group(1)
    else:
        raise RuntimeError('Unable to find version string in %s.'
                           % (VERSIONFILE,))

LONG_DESCRIPTION = """
``sqlparse`` is a non-validating SQL parser module.
It provides support for parsing, splitting and formatting SQL statements.

Visit the `project page <https://github.com/andialbrecht/sqlparse>`_ for
additional information and documentation.

**Example Usage**

Splitting SQL statements::

   >>> import sqlparse
   >>> sqlparse.split('select * from foo; select * from bar;')
   [u'select * from foo; ', u'select * from bar;']

Formatting statemtents::

   >>> sql = 'select * from foo where id in (select id from bar);'
   >>> print sqlparse.format(sql, reindent=True, keyword_case='upper')
   SELECT *
   FROM foo
   WHERE id IN
     (SELECT id
      FROM bar);

Parsing::

   >>> sql = 'select * from someschema.mytable where id = 1'
   >>> res = sqlparse.parse(sql)
   >>> res
   (<Statement 'select...' at 0x9ad08ec>,)
   >>> stmt = res[0]
   >>> str(stmt)  # converting it back to unicode
   'select * from someschema.mytable where id = 1'
   >>> # This is how the internal representation looks like:
   >>> stmt.tokens
   (<DML 'select' at 0x9b63c34>,
    <Whitespace ' ' at 0x9b63e8c>,
    <Operator '*' at 0x9b63e64>,
    <Whitespace ' ' at 0x9b63c5c>,
    <Keyword 'from' at 0x9b63c84>,
    <Whitespace ' ' at 0x9b63cd4>,
    <Identifier 'somes...' at 0x9b5c62c>,
    <Whitespace ' ' at 0x9b63f04>,
    <Where 'where ...' at 0x9b5caac>)

"""

VERSION = get_version()

kwargs = {}
if sys.version_info[0] == 3:
    kwargs['use_2to3'] = True

setup(
    name='sqlparse',
    version=VERSION,
    packages=packages,
    description='Non-validating SQL parser',
    author='Andi Albrecht',
    author_email='albrecht.andi@gmail.com',
    long_description=LONG_DESCRIPTION,
    license='BSD',
    url='https://github.com/andialbrecht/sqlparse',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Topic :: Database',
        'Topic :: Software Development'
    ],
    scripts=['bin/sqlformat'],
    **kwargs
)


text:
package org.wso2.carbon.apimgt.gateway.utils.redis;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.util.Map;

/**
 * Utility class singleton to connect to Redis Server, and perform general operations
 */
public class RedisCacheUtils {

    private static final Log log = LogFactory.getLog(RedisCacheUtils.class);

    private static JedisPool jedisPool;

    /**
     * RedisCacheUtils constructor to create new JedisPool instance
     * with a Redis Server
     *
     * @param host Host name of the Redis Server
     * @param port Port used by the Redis Server
     */
    public RedisCacheUtils(String host, int port) {

        jedisPool = new JedisPool(new JedisPoolConfig(), host, port);
    }

    /**
     * RedisCacheUtils constructor to create new JedisPool instance
     * with a Redis Server requiring authorization
     *
     * @param host     Host name of the Redis Server
     * @param port     Port used by the Redis Server
     * @param timeout  Timeout of the Redis Server connection
     * @param username Username of the user of the Redis Server
     * @param password Password of the user of the Redis Server
     * @param database Database ID in the Redis Server
     * @param ssl      Boolean value to check if ssl is enabled or not
     */
    public RedisCacheUtils(String host, int port, int timeout, String username, char[] password,
                           int database, boolean ssl) {

        jedisPool = new JedisPool(new JedisPoolConfig(), host, port,
                timeout, username, String.valueOf(password), database, ssl);
    }

    /**
     * Save a string key-value pair in Redis.
     *
     * @param key   Key of the value to be saved
     * @param value Value to be saved
     */
    public void setValue(String key, String value) {

        try (Jedis jedis = jedisPool.getResource()) {
            jedis.set(key, value);
        }
    }

    /**
     * Retrieve a string key-value pair in Redis.
     *
     * @param key Key of the value to be retrieved
     * @return String value retrieved
     */
    public String getValue(String key) {

        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.get(key);
        }
    }

    /**
     * Check whether key exists in Redis.
     *
     * @param key Key to be searched
     * @return boolean value whether key exists or not
     */
    public boolean exists(String key) {

        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.exists(key);
        }
    }

    /**
     * Delete key from Redis if it exists.
     *
     * @param key Key to be deleted
     * @return Returns 1 if deleted, 0 if not
     */
    public Long deleteKey(String key) {

        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.del(key);
        }
    }

    /**
     * Rename key in Redis if exists.
     *
     * @param oldKey Existing key value
     * @param newKey New key value
     */
    public void renameKey(String oldKey, String newKey) {

        try (Jedis jedis = jedisPool.getResource()) {
            jedis.rename(oldKey, newKey);
        }
    }

    /**
     * Set timeout for a key so that after the timeout has
     * expired, the key will automatically be deleted.
     *
     * @param key     Key to be set a timeout value
     * @param seconds Timeout value in seconds
     * @return Return 1 if timeout was set successfully, 0 if not
     */
    public Long expireKeyIn(String key, int seconds) {

        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.expire(key, seconds);
        }
    }

    /**
     * Get the time to live for a specific key
     *
     * @param key Key to check the time to live
     * @return Returns 2 if the key does not exist,
     * 1 if it does exist but has not expire set,
     * or any other value indicating the time to live
     * in seconds
     */
    public Long getTimeToLive(String key) {

        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.ttl(key);
        }
    }

    /**
     * Add a field with a value for a specific key
     *
     * @param key   Key to be updated with the field
     * @param field Field to be updated with a value
     * @param value Value of the specified field
     */
    public void addFieldValue(String key, String field, String value) {

        try (Jedis jedis = jedisPool.getResource()) {
            jedis.hset(key, field, value);
        }
    }

    /**
     * Get the value associated with a field stored at the key
     *
     * @param key   Key at which the field-value pair is stored
     * @param field Field which contains the value to be retrieved
     * @return Value associated with the field
     */
    public String getFieldValue(String key, String field) {

        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.hget(key, field);
        }
    }

    /**
     * Add a map into Redis
     *
     * @param key Key at which the map should be saved
     * @param map Map to be saved
     */
    public void addMap(String key, Map<String, String> map) {

        try (Jedis jedis = jedisPool.getResource()) {
            jedis.hset(key, map);
        }
    }

    /**
     * Get map associated with a key
     *
     * @param key Key at which the map is saved
     * @return Map associated with the key
     */
    public Map<String, String> getMap(String key) {

        try (Jedis jedis = jedisPool.getResource()) {
            Map<String, String> map = jedis.hgetAll(key);
            if (map.size() != 0) {
                return map;
            } else {
                return null;
            }
        }
    }

    /**
     * Add object into Redis
     *
     * @param key    Key at which the object should be associated with
     * @param object object to be saved
     */
    public void addObject(String key, Object object) {

        try (Jedis jedis = jedisPool.getResource()) {
            byte[] data = new ObjectMapper().writeValueAsBytes(object);
            jedis.set(key.getBytes(), data);
        } catch (JsonProcessingException e) {
            log.error("Error while converting object to byte array", e);
        }
    }

    /**
     * Get object from Redis
     *
     * @param key Key at which the object is saved
     * @return object associated with the key
     */
    public Object getObject(String key, Class objectType) {

        try (Jedis jedis = jedisPool.getResource()) {
            byte[] objectBytes = jedis.get(key.getBytes());
            if (objectBytes != null) {
                return new ObjectMapper().readValue(objectBytes, objectType);
            } else {
                return null;
            }
        } catch (JsonParseException e) {
            log.error("Error while parsing object from Redis Cache", e);
        } catch (JsonMappingException e) {
            log.error("Error while mapping object to provided class type: " + objectType, e);
        } catch (IOException e) {
            log.error("Error while reading value from Redis Cache", e);
        }
        return null;
    }

    /**
     * Drop the Redis Server connection
     */
    public void stopRedisCacheSession() {

        jedisPool.destroy();
    }
}


text:
namespace base {

#ifdef OS_WIN

inline uint32 NowMSTime() { return GetTickCount(); }

#else

inline uint32 NowMSTime() {
	struct timeval tv;
	gettimeofday(&tv, NULL);
	return (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
}

#endif

}

#endif


text:
namespace FluentScheduler
{
    using System;

    /// <summary>
    /// Unit of time in weeks.
    /// </summary>
    public sealed class WeekUnit
    {
        private readonly int _duration;

        internal WeekUnit(Schedule schedule, int duration)
        {
            _duration = duration < 0 ? 0 : duration;
            Schedule = schedule;
            Schedule.CalculateNextRun = x =>
            {
                var nextRun = x.Date.AddDays(_duration * 7);
                return x > nextRun ? nextRun.AddDays(Math.Max(_duration, 1) * 7) : nextRun;
            };
        }

        internal Schedule Schedule { get; private set; }

        /// <summary>
        /// Runs the job at the given time of day.
        /// </summary>
        /// <param name="hours">The hours (0 through 23).</param>
        /// <param name="minutes">The minutes (0 through 59).</param>
        public void At(int hours, int minutes)
        {
            Schedule.CalculateNextRun = x =>
            {
                var nextRun = x.Date.AddHours(hours).AddMinutes(minutes);
                return x > nextRun ? nextRun.AddDays(Math.Max(_duration, 1) * 7) : nextRun;
            };
        }

        /// <summary>
        /// Runs the job on the given day of the week.
        /// </summary>
        /// <param name="day">The day of the week.</param>
        public WeeklyDayOfWeekUnit On(DayOfWeek day)
        {
            return new WeeklyDayOfWeekUnit(Schedule, _duration, day);
        }
    }
}


text:
FunWith::Files adds a bit of whimsy to your file manipulations, if that's what you're looking for.

To the code!

    require 'fun_with_files'

    include FunWith::Files

    class Project; end

    RootPath.rootify( Project, "/home/user/path/to/project" )

    Project.root  # => <FunWith::Files::FilePath:/home/user/path/to/project>
    Project.root("hello", "subdir") # => <FunWith::Files::FilePath:/home/user/path/to/project/hello/subdir>

    home = FilePath.home
    music = FilePath.home( "Music" )

    music.touch_dir( "sinead_o_connor" ) do |dir|
      dir.touch_dir( "sean_nos_nua" ) do |subdir|
        subdir.touch( "03-lord_franklin.mp3" )
      end

      dir.touch_dir( "theology" ) do |subdir|
        subdir.touch( "05-darker_than_blue.mp3" )
      end
    end

    mp3s = music.glob( "**/*.mp3" ) # => [<FunWith::Files::FilePath:/home/user/Music/sinead_o_connor/sean_nos_nua/03-lord_franklin.mp3>,
                            # <FunWith::Files::FilePath:/home/user/Music/sinead_o_connor/theology/05-darker_than_blue.mp3>]
    mp3s.last.write( Hypothetical::MP3::Source.new.read )

    # whole buchcha other goodies, yet to be documented.

### Linking files ###

While fwf.symlink and fwf.link are both backed by FileUtils.ln / FileUtils.ln_s, the defaults are somewhat different

## DirectoryBuilder ##

DirectoryBuilder is a class for defining and populating a file hierarchy with relative ease.  DirectoryBuilder is probably most easily demonstrated by example.  Sample code:

    # starts by creating directory.  If parent directories don't exist, they will soon.
    DirectoryBuilder.create( '~/project' ) do |b|
      b.dir("images") do                      # creates subdirectory "images", which gets populated within the block
        for img in src_dir.entries.select{|img| img.extension == ".png"}
        b.copy( src_dir.join( img.filename ) )         # copies a bunch of files from another directory
      end    # rises back to the initial '~/project directory

      b.copy( src_dir.join( "rorshach.xml" ) )                  # Copies a file from a source file.
      b.download( "dest.bash", "http://get.rvm.io" )            # downloads file directly beneath '~/project'
                                                                # maybe someday, though

      b.dir("text", "scenes") do   # creates ~/project/text/scenes subdir (creating two new directories text/ and text/scene/)
        b.file( "adventure_time.txt" ) do |f|
          f << "Fill this in later"             # text is written to the file
        end

        # calling .file without feeding it a block leaves it open for writing,
        # until either the enclosing block terminates, or b.file is called again
        # with a filename argument.  While it's open, b.file can be treated like
        # any IO object.
        b.file( "another_brick.txt" )
        b.file << "Hey, you!"
        b.file << "Yes, you!"
        b.file.push "Stand still, laddie!"

        # TODO: Make sure this works.
        #
        # Set a bunch of vars to apply to the template.  Template gets copied into DirectoryBuilder's current
        # directory, with the template's filename (minus the .template extension).
        #
        # Inside the templates, you can use Ruby code in the usual ERB style.  The vars you declare will be
        # available within the template as (see example below) @fname, @lname, @graduated, etc.
        #
        # See FunWith::Templates for a better understanding of templates.  You must require the 'fun_with_templates'
        # gem to use the template function.
        b.template( templates_dir.join("blue_template.txt.template") ) do |t|
          # t is a VarCollector, which is just a hash with a couple of added methods, shown here.
          # I recommend sticking to t.var and t.vars for setting variables, in case the interface
          # changes.
          t.var(:fname, "John")
          t.vars(graduated: "2003", blackmailed: "2004")   # set multiple variables at a time
          t[:lname] = "Macey"
          t.var(:state, "Ohio")
          t.vars(quot: "That wasn't my duck.", photo: "john.png", css: "font-family: arial")
        end

        b.copy( [src_dir.join("abba.txt"), "baab.txt"] )  # contents of abba.txt copied into baab.txt

        b.file( ".lockfile" )   # creates an empty file, closing it to further writing at the end of the block.
      end
    end

## Contributing to fun_with_files ##

Boilerplate from Juwelier, but seems to make sense.

* Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet.
* Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it.
* Fork the project.
* Start a feature/bugfix branch.
* Commit and push until you are happy with your contribution.
* Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
* Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.

## Copyright ##

Copyright (c) 2020 Bryce Anderson. See LICENSE.txt for further details.


text:
namespace content {

// Implements a Bluetooth chooser that selects the first added device, or
// cancels if no device is added before discovery stops. This is used as a
// default chooser implementation for testing.
class LayoutTestFirstDeviceBluetoothChooser : public BluetoothChooser {
 public:
  // See the BluetoothChooser::EventHandler comments for how |event_handler| is
  // used.
  explicit LayoutTestFirstDeviceBluetoothChooser(
      const EventHandler& event_handler);
  ~LayoutTestFirstDeviceBluetoothChooser() override;

  // BluetoothChooser:
  void SetAdapterPresence(AdapterPresence presence) override;
  void ShowDiscoveryState(DiscoveryState state) override;
  void AddOrUpdateDevice(const std::string& device_id,
                         bool should_update_name,
                         const base::string16& device_name,
                         bool is_gatt_connected,
                         bool is_paired,
                         const int8_t* rssi) override;
  void RemoveDevice(const std::string& device_id) override {}

 private:
  EventHandler event_handler_;

  DISALLOW_COPY_AND_ASSIGN(LayoutTestFirstDeviceBluetoothChooser);
};

}  // namespace content

#endif  // CONTENT_SHELL_BROWSER_LAYOUT_TEST_LAYOUT_TEST_FIRST_DEVICE_BLUETOOTH_CHOOSER_H_


text:
<?php

/**
 * Admin class that handles admin meta boxes.
 */
final class Papi_Admin_Meta_Box {

	/**
	 * The core box.
	 *
	 * @var Papi_Core_Box
	 */
	protected $box;

	/**
	 * The constructor.
	 *
	 * @param Papi_Core_Box $box
	 */
	public function __construct( Papi_Core_Box $box ) {
		// Check if the current user is allowed to view this box.
		if ( ! papi_current_user_is_allowed( $box->capabilities ) ) {
			return;
		}

		if ( $box->display ) {
			$this->box = $box;
			$this->setup_actions();
		}
	}

	/**
	 * Add custom css for hiding boxes with no frame in screen options.
	 *
	 * @return string
	 */
	public function admin_head() {
		if ( ! $this->box->frame ) {
			echo sprintf(
				'<style type="text/css">label[for="%s-hide"],#%s>h2,#%s>button{display:none !important}</style>',
				esc_attr( $this->box->id ),
				esc_attr( $this->box->id ),
				esc_attr( $this->box->id )
			);
		}
	}

	/**
	 * Add css classes to meta box.
	 *
	 * @param  array $classes
	 *
	 * @return string[]
	 */
	public function meta_box_css_classes( array $classes ) {
		return array_merge( $classes, [
			'papi-box'
		] );
	}

	/**
	 * Move meta boxes after title.
	 */
	public function move_meta_box_after_title() {
		global $post, $wp_meta_boxes;
		do_meta_boxes( get_current_screen(), $this->box->context, $post );
		unset( $wp_meta_boxes[get_post_type( $post )][$this->box->context] );
	}

	/**
	 * Get meta post type.
	 *
	 * @return string
	 */
	protected function get_post_type() {
		if ( papi_get_meta_type() === 'post' ) {
			if ( $post_id = papi_get_post_id() ) {
				return get_post_type( $post_id );
			}

			if ( $post_type = papi_get_post_type() ) {
				return $post_type;
			}
		}

		return $this->box->id;
	}

	/**
	 * Get meta box title.
	 *
	 * @return string
	 */
	protected function get_title() {
		$title = $this->box->title;

		if ( $this->box->get_option( 'required' ) ) {
			$title .= papi_property_required_html(
				$this->box->properties[0],
				true
			);
		}

		return $title;
	}

	/**
	 * Render the meta box
	 *
	 * @param array $post
	 * @param array $args
	 */
	public function render_meta_box( $post, array $args ) {
		if ( ! isset( $args['args'] ) ) {
			return;
		}

		// Do a last check before all properties is rendered.
		$args['args'] = array_filter( $args['args'], 'papi_is_property' );

		// Inherit options from the box.
		foreach ( $args['args'] as $index => $property ) {
			if ( $property->layout === 'horizontal' ) {
				$args['args'][$index]->layout = $this->box->layout;
			}
		}

		// Render the properties.
		papi_render_properties( papi_sort_order( array_reverse( $args['args'] ) ) );
	}

	/**
	 * Setup action hooks.
	 */
	protected function setup_actions() {
		if ( post_type_exists( $this->get_post_type() ) && papi_get_meta_type() === 'post' ) {
			add_action( 'add_meta_boxes', [$this, 'setup_meta_box'] );

			if ( $this->box->context === 'after_title' ) {
				add_action( 'edit_form_after_title', [$this, 'move_meta_box_after_title'] );
			}
		} else {
			$this->setup_meta_box();
		}

		// Will be called on when you call do_meta_boxes
		// even without a real post type.
		add_action(
			sprintf(
				'postbox_classes_%s_%s',
				strtolower( $this->get_post_type() ),
				$this->box->id
			),
			[$this, 'meta_box_css_classes']
		);

		add_action( 'admin_head', [$this, 'admin_head'] );
	}

	/**
	 * Setup meta box.
	 */
	public function setup_meta_box() {
		$properties = $this->box->properties;

		// Check all properties and remove them that can't be rendered.
		foreach ( $properties as $index => $property ) {
			if ( $property instanceof Papi_Property && ! $property->can_render() ) {
				unset( $properties[$index] );
			}
		}

		// Bail if properties array is empty,
		// no need to render a empty meta box.
		if ( empty( $properties ) ) {
			return;
		}

		add_meta_box(
			$this->box->id,
			$this->get_title(),
			[$this, 'render_meta_box'],
			$this->get_post_type(),
			$this->box->context,
			$this->box->priority,
			$properties
		);
	}
}


text:
#ifndef EX_EXE_STMT_GLOBALS_H
#define EX_EXE_STMT_GLOBALS_H

/* -*-C++-*-
 *****************************************************************************
 *
 * File:         ex_exe_stmt_globals.h
 * Description:  Statement globals for stmts executed in master exe or esp.
 *
 *
 * Created:      7/10/95
 * Language:     C++
 *
 *
 *
 *
 *****************************************************************************
 */

// -----------------------------------------------------------------------

#include <sys/types.h>
#include <sys/syscall.h>
#include "Platform.h"

#include "Globals.h"
#include "ex_globals.h"
#include "FragDir.h"
#include "ex_frag_inst.h"
#include "Int64.h"
#include "ExCollections.h"
#include "timeout_data.h"
#include "ex_esp_frag_dir.h"

// forward
class SequenceValueGenerator;

// Comment in and build to trace an ESPAccess ESP process
//
//#define TRACE_ESP_ACCESS 1

#if defined(_DEBUG) && defined(TRACE_ESP_ACCESS)

class ESPTraceEntry
{
public:
  ESPTraceEntry(ex_globals *glob, char *t1);

  ESPTraceEntry(ex_globals *glob, Lng32 espNum,
		Lng32 pid,
		Int64 currentTS,
		char* t1);

  ~ESPTraceEntry();

  void createMessage(char *msg);

  // get the espNum from (int) espGlob->getMyInstanceNumber();
  ULng32 espNum_;

  // from  ExEspStmtGlobals->getPid()
  pid_t pid_;

  // gotten from doing NA_JulianTimestamp()
  Int64 timestamp_;

  // A message
  char *msgtext1_;

  ex_globals *globals_;
};

// List of ESPTraceEntry
class ESPTraceList : public LIST(ESPTraceEntry *)
{
public:

  ESPTraceList(ex_globals *globals,
	       CollHeap* h/*=0*/)
    : LIST(ESPTraceEntry *)(h),
    globals_(globals),
    traceOn_(FALSE)
    {
    }

  ~ESPTraceList();

  void insertNewTraceEntry(char *msg);

  void logESPTraceToFile(char *fn, char *signature, ESPTraceList &traceList);

  // Remove all entries the list and call their destructors
  void clearAndDestroy();

  ex_globals *globals_;
  NABoolean traceOn_;

}; // class ESPTraceList

#endif

// -----------------------------------------------------------------------
// Contents of this file
// -----------------------------------------------------------------------

class ExExeStmtGlobals;
class ExMasterStmtGlobals;
class ExEspStmtGlobals;

// forward references
class ExRtFragTable;
class ExProcessIdsOfFragList;
class ExEspFragInstanceDir;
class ComDiagsArea;
class IpcEnvironment;
class IpcProcessId;
class ExEspManager;
class ExFragDir;
class ContextCli;
class CliGlobals;
class ResolvedNameList;
class MemoryMonitor;
class ExMsgResourceInfo;
class ExScratchFileOptions;
class ComTdbRoot;
class Statement;
class ExUdrServer;
class ExRsInfo;
class ex_send_top_tcb;
class StmtStats;
class SMConnection;
class ExSMDownloadInfo;

class ExExeStmtGlobals : public ex_globals
{
public:

  ExExeStmtGlobals(short num_temps,
                   CliGlobals *cliGlobals,
		   short create_gui_sched = 0,
		   Space * space = NULL,
		   CollHeap * heap = NULL);

  // Deletes objects this object points to... does NOT destroy
  // this object
  virtual void deleteMe(NABoolean fatalError);

  virtual ExExeStmtGlobals * castToExExeStmtGlobals();
  virtual ExMasterStmtGlobals * castToExMasterStmtGlobals();
  virtual ExEspStmtGlobals * castToExEspStmtGlobals();

  // ---------------------------------------------------------------------
  // Information about fragments belonging to this statement
  // ---------------------------------------------------------------------

  // get the pointer to a fragment of the statement (or NULL if the
  // fragment isn't available) and the fragment length
  virtual char * getFragmentPtr(ExFragId fragId) const = 0;
  virtual IpcMessageObjSize getFragmentLength(ExFragId fragId) const = 0;

  // get the fragment key for a given fragment of this statement
  virtual ExFragKey getFragmentKey(ExFragId fragId) const = 0;

  // simple method to get number of instances for my fragment id
  // (this method is rooted in the base class, ex_globals)
  virtual Lng32 getNumOfInstances() const;

  // get the number of instances for a given fragment and get the process
  // id for one of the instances, or find out how many processes are
  // in the local node and which of them I am
  virtual Lng32 getNumOfInstances(ExFragId fragId) const = 0;
  virtual const IpcProcessId & getInstanceProcessId(
       ExFragId fragId,
       Lng32 instanceNum) const = 0;
  virtual Lng32 getMyInstanceNumber() const = 0;
  virtual void getMyNodeLocalInstanceNumber(
       Lng32 &myNodeLocalInstanceNumber,
       Lng32 &numOfLocalInstances) const = 0;

  // Virtual methods to retrieve SeaMonster settings. These methods
  // will be implemented in the master and ESP subclasses.
  virtual Int64 getSMQueryID() const = 0;
  virtual Int32 getSMTraceLevel() const = 0;
  virtual const char *getSMTraceFilePrefix() const = 0;

  inline IpcPriority getMyProcessPriority()
    { return cliGlobals_->myPriority(); }

  // get resource info
  virtual const ExScratchFileOptions *getScratchFileOptions() const = 0;

  // there is one SQL diagnostics area for the statement; to be used only
  // for fatal errors that aren't related to a single row
  inline ComDiagsArea *getDiagsArea() const           { return diagsArea_; }
  void setGlobDiagsArea(ComDiagsArea *da);

#if defined(_DEBUG) && defined (TRACE_ESP_ACCESS)
  inline ESPTraceList *getESPTraceList() const {return espTraceList_; }
  void setESPTraceList(ESPTraceList *traceList) {espTraceList_ = traceList;}
#endif

  // update the input parameter diags area with the (non-queue) error
  // info from globals, if there is any
  void takeGlobalDiagsArea(ComDiagsArea &cliDA);

  void setCliGlobals(CliGlobals * cg)                  { cliGlobals_ = cg; }
  inline CliGlobals * getCliGlobals()                { return cliGlobals_; }

  // return of TRUE means error, FALSE means all Ok.
  virtual NABoolean closeTables();
  virtual NABoolean reOpenTables();

  // This method adds a Condition to the statement's diags area
  // to complain about memory alloc errors.
  void makeMemoryCondition(Lng32 errCode);

  inline ContextCli *getContext() const
    { return cliGlobals_->currContext(); }

  SequenceValueGenerator * seqGen();

  // the IPC environment is used by the IPC routines and contains useful
  // information (such as a dynamic heap) for other code as well
  inline IpcEnvironment * getIpcEnvironment() const
    { return cliGlobals_->getEnvironment(); }

  inline MemoryMonitor * getMemoryMonitor () const
    { return cliGlobals_->getMemoryMonitor(); }

  ExUdrServer *acquireUdrServer(const char *runtimeOptions,
                                const char *optionDelimiters,
				NABoolean dedicated = FALSE);

  inline ExUdrServer * getUdrServer() const { return udrServer_; }

  inline LIST(ExUdrServer *) getUdrServersD() const { return udrServersD_; }

  void setUdrConnection(IpcConnection *conn) { udrIpcConnection_ = conn; }
  IpcConnection *getUdrConnection();

  void incrementUdrTxMsgsOut();
  void decrementUdrTxMsgsOut();

  void incrementUdrNonTxMsgsOut();
  void decrementUdrNonTxMsgsOut();

  Lng32 numUdrMsgsOut() const { return numUdrTxMsgsOut_ + numUdrNonTxMsgsOut_; }
  Lng32 numUdrTxMsgsOut() const { return numUdrTxMsgsOut_; }
  Lng32 numUdrNonTxMsgsOut() const { return numUdrNonTxMsgsOut_; }

  inline Int64 &getTransid()                         { return transid_; }

  inline Int64 &getSavepointId()                     { return savepointId_; }

  ResolvedNameList* &resolvedNameList() { return resolvedNameList_; };
  // for accounting for unanswered send top messages sent.
  virtual void decrementSendTopMsgesOut();
  inline void incrementSendTopMsgesOut()   { numSendTopMsgesOut_++; };
  inline NABoolean  anySendTopMsgesOut()   { return numSendTopMsgesOut_ != 0; }
  inline Lng32 numSendTopMsgesOut()        { return numSendTopMsgesOut_; }

  // for accounting for unanswered cancel messages sent thru IPC & ArkFs.
  void decrementCancelMsgesOut();
  inline void incrementCancelMsgesOut()    { numCancelMsgesOut_++; };
  inline NABoolean  anyCancelMsgesOut()    { return numCancelMsgesOut_ != 0; }
  inline Lng32 numCancelMsgesOut()         { return numCancelMsgesOut_; }

  inline NABoolean noNewRequest() { return noNewRequest_; }
  inline virtual void setNoNewRequest(NABoolean n) { noNewRequest_ = n; }

  void setCloseAllOpens(NABoolean v)         { closeAllOpens_ = v; }
  NABoolean closeAllOpens()                  { return closeAllOpens_; }

  // return TRUE iff this timeout was set, and then put value in timeoutValue
  inline NABoolean getLockTimeout( char * tableName, Lng32 & timeoutValue )
  {
    if ( NULL == timeouts_ ) return FALSE;
    return timeouts_->getLockTimeout( tableName, timeoutValue );
  } ;

  // returns a reference to the internal pointer (used inter alia for setting)
  TimeoutData  ** getTimeoutData() { return & timeouts_; } ;

  inline NABoolean grabMemoryQuotaIfAvailable(ULng32 size)
  {
    CliGlobals *cli_globals = GetCliGlobals();
    if (cli_globals->isEspProcess())
       return cli_globals->grabMemoryQuotaIfAvailable(size);
    if ( unusedBMOsMemoryQuota_ < size ) return FALSE;
    unusedBMOsMemoryQuota_ -= size ;
    return TRUE;
  }

  inline void resetMemoryQuota()
  {
    CliGlobals *cli_globals = GetCliGlobals();
    if (cli_globals->isEspProcess())
       return cli_globals->resetMemoryQuota();
    unusedBMOsMemoryQuota_ = 0 ;
  }

  inline ULng32 unusedMemoryQuota()
  {
    CliGlobals *cli_globals = GetCliGlobals();
    if (cli_globals->isEspProcess())
       return cli_globals->unusedMemoryQuota();
    return unusedBMOsMemoryQuota_;
  }

  inline void yieldMemoryQuota(ULng32 size)
  {
    CliGlobals *cli_globals = GetCliGlobals();
    if (cli_globals->isEspProcess())
       return cli_globals->yieldMemoryQuota(size);
    unusedBMOsMemoryQuota_ += size;
  }

  // getStreamTimeout: return TRUE (FALSE) if the stream-timeout was set (was
  // not set). If set, the timeoutValue parameter would return that value
  virtual NABoolean getStreamTimeout( Lng32 & timeoutValue );

  // Whenever a (prepared) statement is re-executed, the executionCount_
  // is incremented. Right now this counter is used only by the
  // partition access to let the EID session know if a new input buffer
  // represents a continuation of an earlier execution of the statement.
  // This helps dp2 CPU limits work properly if the statement in both
  // scenarios: 1) the statement is re-exec'd; and 2) the statement has
  // multiple input buffers to DP2.
  // The increment is done by the root and by the split bottom.
  // NOTE: This is another place where the code assume that an ESP is never
  // on the right-hand side of a flow node (TF, or ONLJ).  Some would say the
  // correct solution would be to maintain the exec count in the master,
  // and then pass it to ESPs as dataflow input.

  void incExecutionCount() { executionCount_++; }

  ULng32 getExecutionCount() { return executionCount_; }

  virtual void initSMGlobals();

private:

  // SQL Diagnostics area for this statement
  ComDiagsArea *diagsArea_;

  // Pointer to shared udr server used by scalar udfs
  ExUdrServer *udrServer_;

  // List of dedicated UDR servers associated with this statement
  // Note that this list does not contain the shared udr server
  // pointed to by udrServer_ defined above.This set of dedicated
  // udr servers is used by tmudfs and accessed in statement.cpp
  // when a statement want to assertain that all IO with these servers
  // are completed.
  LIST(ExUdrServer *) udrServersD_;

  // IpcConnection to the UDR Server
  IpcConnection *udrIpcConnection_;

  // transaction identifier, if this statement is running under
  // a transaction. -1, if it is not.
  Int64 transid_;

  // savepoint id, if dp2 savepoints are enabled and in use.
  // -1, if not.
  Int64 savepointId_;

  ResolvedNameList * resolvedNameList_;

  // Keep a count of unanswered send top messages.
  Lng32  numSendTopMsgesOut_;

  // Keep a count of unanswered cancel messages sent thru IPC & ArkFs.
  Lng32  numCancelMsgesOut_;

  // Keep a count of unanswered transactional UDR messages
  Lng32 numUdrTxMsgsOut_;

  // Keep a count of unanswered non-transactional UDR messages
  Lng32 numUdrNonTxMsgsOut_;

  // Set when split bottom gets release transaction
  // Reset when split bottom gets work messge
  NABoolean noNewRequest_;

  NABoolean closeAllOpens_;

  // Hold all the dynamicly set timeout data (relevant to this statement)
  // (Note: This pointer is NULL when there are no relevant timeouts set.)
  TimeoutData  * timeouts_;

  // memory quota allocation given back by BMOs to be used by other BMOs
  ULng32 unusedBMOsMemoryQuota_;

#if defined(_DEBUG) && defined (TRACE_ESP_ACCESS)
  ESPTraceList *espTraceList_;
#endif

  ULng32 executionCount_;

protected:
  inline void setUdrServer(ExUdrServer *udrServ)      { udrServer_ = udrServ; }

  // points to the executor global object. There is only one
  // executor global for the whole executor session.
  CliGlobals * cliGlobals_;

  // Keep track of whether the SeaMonster query ID was registered
  bool smQueryIDRegistered_;

public:
  enum StmtType {
    DYNAMIC = 0, STATIC = 1};

private:
  StmtType stmtType_;

public:
  StmtType getStmtType();
  void setStmtType(StmtType stmtType);
};

// -----------------------------------------------------------------------
// Both the main thread and the cancel thread can set the state.
// The only state that can be set to by the cancel thread is
// CLI_CANCEL_REQUESTED.
// The main thread can set the remaining 3 states.
//
// statement::cancel acts based on the state.
// -----------------------------------------------------------------------

typedef enum CancelStateEnum
{
  CLI_CANCEL_TCB_INVALID = 1,    // cancel enable but no tcb.
  CLI_CANCEL_TCB_READY   = 2,    // cancel enable and tcb built.
  CLI_CANCEL_REQUESTED   = 3,    // set by cancel thread to request cancel.
  CLI_CANCEL_DISABLE     = 4     // reject async cancel.  Not retryable.
} CancelState;

class ExMasterStmtGlobals : public ExExeStmtGlobals
{
public:

  ExMasterStmtGlobals(short num_temps,
		      CliGlobals *cliGlobals,
                      Statement *statement,
		      short create_gui_sched = 0,
		      Space * space = NULL,
		      CollHeap * heap = NULL);

  // Deletes objects this object points to... does NOT destroy
  // this object
  virtual void deleteMe(NABoolean fatalError);

  virtual ExMasterStmtGlobals * castToExMasterStmtGlobals();

  virtual char * getFragmentPtr(ExFragId fragId) const;
  virtual IpcMessageObjSize getFragmentLength(ExFragId fragId) const;
  virtual ExFragKey getFragmentKey(ExFragId fragId) const;
  virtual ExFragId getMyFragId() const;
  virtual Lng32 getNumOfInstances() const // avoid warning - hidden virtual func
  { return ExExeStmtGlobals::getNumOfInstances(); }
  virtual Lng32 getNumOfInstances(ExFragId fragId) const;
  virtual const IpcProcessId & getInstanceProcessId(ExFragId fragId,
						    Lng32 instanceNum) const;
  virtual Lng32 getMyInstanceNumber() const;
  virtual void getMyNodeLocalInstanceNumber(
                                       Lng32 &myNodeLocalInstanceNumber,
                                       Lng32 &numOfLocalInstances) const;

  // Virtual methods to retrieve SeaMonster settings
  //
  // In the master executor these settings come from:
  //  Query ID: from statement globals
  //  Trace level: from session defaults
  //  Trace file prefix: from session defaults
  virtual Int64 getSMQueryID() const { return smQueryID_; }
  virtual Int32 getSMTraceLevel() const;
  virtual const char *getSMTraceFilePrefix() const;

  // In the master we allow root_tdb::build() to assign a SeaMonster
  // ID to the query
  void setSMQueryID(Int64 id) { smQueryID_ = id; }

  virtual const ExScratchFileOptions *getScratchFileOptions() const;

  // the frag table is only set in the master executor
  inline void setFragDir(ExFragDir * frag_dir)        {fragDir_ = frag_dir;}
  inline ExFragDir * getFragDir() const                   {return fragDir_;}

  inline void setStartAddr(void * start_addr)       {startAddr_ = start_addr;}
  inline void * getStartAddr() const                      {return startAddr_;}

  inline ExRtFragTable *getRtFragTable() const        { return fragTable_; }
  inline void setRtFragTable(ExRtFragTable *m)           { fragTable_ = m; }

  inline ExEspManager * getEspManager() const {
    return cliGlobals_->getEspManager();
  }

  NABoolean udrRuntimeOptionsChanged() const;

  Int64 getRowsAffected() const           {return rowsAffected_;}
  void setRowsAffected(Int64 newRows)             {rowsAffected_ = newRows;}

  inline Statement *getStatement()                 { return statement_; }

  // For asynchronous CLI cancel.
  inline CancelState getCancelState() const           {return cancelState_;}
  CancelState setCancelState(CancelState newState);
  inline void clearCancelState()   {setCancelState(CLI_CANCEL_TCB_INVALID);}
  void resetCancelState();

  // The following two methods are called in /cli/Statement.cpp :
  // copy timeout data relevant to this stmt (from the global CLI context)
  // (This method is called after the statement was fixed up)
  void      setLocalTimeoutData(ComTdbRoot * rootTdb);
  // check if a previous SET TIMEOUT statement affects this fixedup statement
  // (This method is called before executing a previously fixedup statement)
  NABoolean timeoutSettingChanged();

  ExRsInfo *getResultSetInfo(NABoolean createIfNecessary = FALSE);
  void deleteResultSetInfo();
  void acquireRSInfoFromParent(ULng32 &rsIndex,   // OUT
                               Int64 &udrHandle,         // OUT
                               ExUdrServer *&udrServer,  // OUT
                               IpcProcessId &pid,        // OUT
                               ExRsInfo *&rsInfo);       // OUT

 StatsGlobals *getStatsGlobals()
 { return (cliGlobals_ ?  cliGlobals_->getStatsGlobals() : NULL); }
 Long getSemId()
 { return (cliGlobals_ ?  cliGlobals_->getSemId() : (short)0);}
 pid_t getPid()
 { return (cliGlobals_ ?  cliGlobals_->myPin() : (short)0);}
 pid_t getTid()
 {
    return syscall(SYS_gettid);
 }

 Lng32 myNodeNumber() { return (cliGlobals_ ?  cliGlobals_->myNodeNumber() : (short)0);}

  inline NABoolean verifyESP() { return verifyESP_; }
  inline void setVerifyESP() { verifyESP_ = TRUE; }
  inline void resetVerifyESP() { verifyESP_ = FALSE; }

  // Methods to manage information related to the top-level ESPs
  // involved in a parallel extract operation
  void insertExtractEsp(const IpcProcessId &);
  void insertExtractSecurityKey(const char *key);
  short getExtractEspCpu(ULng32 index) const;
  Lng32 getExtractEspNodeNumber(ULng32 index) const;
  const char *getExtractEspPhandleText(ULng32 index) const;
  const char *getExtractSecurityKey() const;

  inline void addSMConnection(SMConnection *conn)
            { allSMConnections_.insert(conn); }
  inline void removeSMConnection(SMConnection *conn)
            { allSMConnections_.remove(conn); }
  const LIST(SMConnection *) &allSMConnections() const
            { return allSMConnections_; }
  void setAqrWnrInsertCleanedup() { aqrWnrCleanedup_ = true; }
  void resetAqrWnrInsertCleanedup() { aqrWnrCleanedup_ = false; }
  bool getAqrWnrInsertCleanedup() const { return aqrWnrCleanedup_; }

private:

  // directory containing offsets and types of all fragments.
  ExFragDir * fragDir_;

  // pointer to the generated code for all fragments
  void * startAddr_;

  // fragment instance directory for the current statement
  ExRtFragTable *fragTable_;

  // Current statement
  Statement *statement_;

  // rows affected during the execution of this statement.
  // Applies to rows updated/deleted/inserted ONLY.
  Int64 rowsAffected_;

  // Used exclusively by asynchronous CLI cancel.
  CancelState cancelState_;

  // local snapshot of the global timeout-change-counter at the time this
  // stmt was fixed up (speeds up checking that timeout values are up-to-date)
  ULng32  localSnapshotOfTimeoutChangeCounter_;

  // Store Procedure Result Set Info
  // will always be NULL except for CALL statements that produce result sets.
  ExRsInfo *resultSetInfo_;

  // If TRUE, check every existing ESP before reassigning them
  NABoolean verifyESP_;

  // For a parallel extract producer query we need to manage
  // information that describes the collection of top-level ESPs. The
  // collection remains empty if this is not an extract producer query
  struct ExExtractEspInfo
  {
    // Each ESP will be described by one instance of this struct
    short cpu_;
    Lng32 nodeNumber_;
    char *phandleText_;
  };
  struct ExExtractProducerInfo
  {
    // One instance of this struct represents the entire collection of ESPs
    ARRAY(ExExtractEspInfo*) *esps_;
    char *securityKey_;
  };
  ExExtractProducerInfo *extractInfo_;

  // A list of all SM connections used by this master executor. Used
  // for error reporting when an ESP control connection is lost. Each
  // SM connection will be informed of the error and will go into an
  // error state rather than continuing to wait for arrivals.
  LIST(SMConnection *) allSMConnections_;

  // In the master we store the SeaMonster query ID here
  Int64 smQueryID_;

  // Let cli layer know that an NO ROLLBACK insert can be AQR'd.
  bool aqrWnrCleanedup_;
};

class ExEspStmtGlobals : public ExExeStmtGlobals
{
public:

  ExEspStmtGlobals(short num_temps,
                   CliGlobals *cliGlobals,
		   short create_gui_sched,
		   Space * space,
		   CollHeap * heap,
		   ExEspFragInstanceDir *espFragInstanceDir,
		   ExFragInstanceHandle handle,
                   ULng32 injectErrorAtExprFreq,
                   char *queryId = NULL,
                   Lng32 queryIdLen = 0);

  virtual void deleteMe(NABoolean fatalError);
  virtual ExEspStmtGlobals * castToExEspStmtGlobals();

  virtual char * getFragmentPtr(ExFragId fragId) const;
  virtual IpcMessageObjSize getFragmentLength(ExFragId fragId) const;
  virtual ExFragKey getFragmentKey(ExFragId fragId) const;
  virtual ExFragId getMyFragId() const;
  virtual Lng32 getNumOfInstances() const // avoid warning - hidden virtual func
  { return ExExeStmtGlobals::getNumOfInstances(); }
  virtual Lng32 getNumOfInstances(ExFragId fragId) const;
  virtual const IpcProcessId & getInstanceProcessId(ExFragId fragId,
						    Lng32 instanceNum) const;
  virtual Lng32 getMyInstanceNumber() const;
  virtual void getMyNodeLocalInstanceNumber(
       Lng32 &myNodeLocalInstanceNumber,
       Lng32 &numOfLocalInstances) const;

  // Virtual methods to retrieve SeaMonster settings
  //
  // In an ESP these settings come from an ExSMDownloadInfo object
  // that was sent with the fragment download message and is pointed
  // to by statement globals
  virtual Int64 getSMQueryID() const;
  virtual Int32 getSMTraceLevel() const;
  virtual const char *getSMTraceFilePrefix() const;

  // This method will store a pointer to an object containing
  // SeaMonster info for this query (e.g., query ID, trace level,
  // ...). The object is sent from the master executor as part of the
  // download message.
  void setSMDownloadInfo(ExSMDownloadInfo *info)
  { smDownloadInfo_ = info; }

  virtual const ExScratchFileOptions *getScratchFileOptions() const;

  // a Process Ids of Fragments list gets only sent to ESP fragment instances
  inline ExProcessIdsOfFragList *getPidFragList() const
                                           { return processIdsOfFragList_; }
  inline void setPidFragList(ExProcessIdsOfFragList *p)
                                              { processIdsOfFragList_ = p; }

  inline const ExMsgResourceInfo * getResourceInfo() const
                                                   { return resourceInfo_; }
  inline void setResourceInfo(ExMsgResourceInfo *r)   { resourceInfo_ = r; }

  // deal with the transaction ids that come in with client requests

  // set the reply tag that is associate with the transaction work request
  // for this instance
  void setReplyTag(Int64 transid, short replyTag);

  // restore the transid associated with this instance and return whether
  // this was possible (not possible if no current transaction work request)
  NABoolean restoreTransaction();

  // manage a list of the send top TCBs in this fragment instance, so that
  // dependent ESPs can be notified if we lose interest in this statement
  // because of a cancel operation
  CollIndex registerSendTopTcb(ex_send_top_tcb *st);
  void setSendTopTcbActivated(CollIndex id) { activatedSendTopTcbs_ += id; }
  void setSendTopTcbLateCancelling();
  void clearAllActivatedSendTopTcbs()     { activatedSendTopTcbs_.clear(); }
  void resetSendTopTcbLateCancelling();

  ex_send_top_tcb * getFirstNonActivatedSendTop(CollIndex &i)
                            { i = 0; return getNextNonActivatedSendTop(i); }
  ex_send_top_tcb * getNextNonActivatedSendTop(CollIndex &i);

  virtual void setNoNewRequest(NABoolean n);

  virtual void decrementSendTopMsgesOut();

 StatsGlobals *getStatsGlobals()
      { return espFragInstanceDir_->getStatsGlobals(); }
 Long getSemId()
      { return espFragInstanceDir_->getSemId();}
 pid_t getPid()
      { return espFragInstanceDir_->getPid();}
pid_t getTid()
      { return espFragInstanceDir_->getTid();}

  NABoolean isAnESPAccess() {return isAnESPAccess_;}
  void setIsAnESPAccess(NABoolean a) { isAnESPAccess_ = a;}

  char *getQueryId() { return queryId_; }
  Lng32 getQueryIdLen() { return queryIdLen_; }
  inline StmtStats *getStmtStats() { return stmtStats_; }
  StmtStats *setStmtStats();
  void setMyFixupPriority(IpcPriority v)     { myFixupPriority_ = v; }
  IpcPriority getMyFixupPriority()           { return myFixupPriority_; }

private:

  // my own fragment instance handle
  // (using a long here to avoid exposing the entire ESP frag instance
  // dir class to this header file)
  ExFragInstanceHandle myHandle_;

  // pointer back the the ESP's fragment instance directory
  // (use this only to get pointers to fragments)
  ExEspFragInstanceDir *espFragInstanceDir_;

  // fragment instances of input fragments to this ESP (used in ESPs)
  ExProcessIdsOfFragList *processIdsOfFragList_;

  // downloaded resource info
  ExMsgResourceInfo *resourceInfo_;

  // reply tag is used to restore the transid for this reply tag
  short replyTag_;

  // list of the send top TCBs in this fragment instance, needed for
  // cancel propagation to producer ESPs
  ARRAY(ex_send_top_tcb *) sendTopTcbs_;
  // the subset of the send top TCBs that got a request
  SUBARRAY(ex_send_top_tcb *) activatedSendTopTcbs_;

  // This is the priority ESPs run at when waiting for a 'fixup' message.
  // After fixup message is received, the priority is changed to its
  // 'execute' priority which is sent as part of the fixup message.
  // Once ESPs are done executing and the release transaction msg is
  // received, priority is changed back to the 'fixup' priority value.
  IpcPriority myFixupPriority_;

  char *queryId_;
  Lng32 queryIdLen_;
  StmtStats *stmtStats_;
  NAHeap *heap_;

  NABoolean isAnESPAccess_;

  // A pointer to an object containing SeaMonster properties for the
  // query
  ExSMDownloadInfo *smDownloadInfo_;
};

#endif


text:
#import "NSObject.h"

// Not exported
@interface TSWPCTTypesetterCache : NSObject
{
    struct map<unsigned long, boost::shared_ptr<TSWPParagraphTypesetter>, std::__1::less<unsigned long>, std::__1::allocator<std::__1::pair<const unsigned long, boost::shared_ptr<TSWPParagraphTypesetter>>>> _typesetters;
}

- (id).cxx_construct;
- (void).cxx_destruct;
- (void)p_limitCacheSize:(unsigned long long)arg1;
- (void)clearCache;
- (void)removeTypesetterForParagraphIndex:(unsigned long long)arg1;
- (void)addTypesetterForParagraphIdentifier:(unsigned long long)arg1 typesetter:(shared_ptr_6f812b7d)arg2;
- (shared_ptr_6f812b7d)cachedTypesetterForParagraphIdentifier:(unsigned long long)arg1;
- (void)dealloc;

@end