text:
function varargout = BatScreen(varargin)
% BATSCREEN MATLAB code for BatScreen.fig
%      BATSCREEN, by itself, creates a new BATSCREEN or raises the existing
%      singleton*.
%
%      H = BATSCREEN returns the handle to a new BATSCREEN or the handle to
%      the existing singleton*.
%
%      BATSCREEN('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in BATSCREEN.M with the given input arguments.
%
%      BATSCREEN('Property','Value',...) creates a new BATSCREEN or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before BatScreen_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to BatScreen_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help BatScreen

% Last Modified by GUIDE v2.5 31-Jul-2015 19:59:31

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
    'gui_Singleton',  gui_Singleton, ...
    'gui_OpeningFcn', @BatScreen_OpeningFcn, ...
    'gui_OutputFcn',  @BatScreen_OutputFcn, ...
    'gui_LayoutFcn',  [] , ...
    'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before BatScreen is made visible.
function BatScreen_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to BatScreen (see VARARGIN)

% Choose default command line output for BatScreen
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% If there is currently a schedule loaded, show that it is loaded and
% enable the start button
if (isappdata(0,'fileName') == 1 && ...
        isappdata(0,'courses') == 1 && ...
        isappdata(0,'students') == 1 && ...
        isappdata(0,'rooms') == 1 && ...
        isappdata(0,'teachers') == 1 && ...
        isappdata(0,'days') == 1 && ...
        isappdata(0,'timeslots') == 1)

    set(handles.FileName_Text,'String', getappdata(0,'fileName'));
    set(handles.BAT_Start,'Enable', 'on')

end

% UIWAIT makes BatScreen wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = BatScreen_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

% GLOBAL VARIABLES
% population size
function r = getPopSize
global popSize
r = popSize;

% number of iterations
function r = getNumIterations
global numIterations
r = numIterations;

% loudness
function r = getLoudness
global loudness
r = loudness;

% pulse rate
function r = getPulseRate
global pulseRate
r = pulseRate;

% Used to load an input file into the program
function Load_File_Callback(hObject, eventdata, handles)
% hObject    handle to Load_File (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% show a browser with CSV files as the type
[filename, pathname] = uigetfile({'*.csv','csv files'});

% if the user did not click cancel
if ~isequal(filename,0)

    % set the file name and read in the file
    set(handles.FileName_Text,'String', fullfile(pathname, filename))
    [courses students rooms teachers days timeslots] = ReadInput(fullfile(pathname, filename));

    %set appdata variables to be passed to other guis
    setappdata(0,'courses',courses);
    setappdata(0,'students',students);
    setappdata(0,'rooms',rooms);
    setappdata(0,'teachers',teachers);
    setappdata(0,'days',days);
    setappdata(0,'timeslots',timeslots);
    setappdata(0,'fileName',fullfile(pathname, filename));

    % allow the user to run the program if there was no error reading in
    % the file
    set(handles.BAT_Start,'Enable', 'on')
end

% Take the user back to the main screen
function Back_Button_Callback(hObject, eventdata, handles)
% hObject    handle to Back_Button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% create a handle/open the main screen, and close the current screen
WS_handle = WelcomeScreen;      % open main screen
delete(get(hObject, 'parent')); % close this screen

% Executes the bat algorithm with the given input parameters
function BAT_Start_Callback(hObject, eventdata, handles)
% hObject    handle to BAT_Start (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% get the input data from appdata
courses = getappdata(0,'courses');
students = getappdata(0,'students');
rooms = getappdata(0,'rooms');
teachers = getappdata(0,'teachers');
days = getappdata(0,'days');
timeslots = getappdata(0,'timeslots');

[ values, valid ] = ValidateNumbers(getPopSize(), getNumIterations(), getLoudness(), getPulseRate());
if ~valid, return; end

% disable buttons while the algorithm is running
set(handles.BAT_Start,'Enable', 'off')
set(handles.Back_Button,'Enable', 'off')
set(handles.Cur_Best_label,'String', 'Current Best Fitness:');

% run the algorithm
[ bestFitness bestSolution fitnesses solutions ] = BatAlgorithm(...
    days, timeslots, courses, rooms, students, ...
    values(1), values(2), values(3), values(4), handles);

% change the label to best fitness when the algorithm is complete
set(handles.Cur_Best_label,'String', 'Best Fitness:');

% print the schedule of the best solution
PrintSchedule(bestSolution);

% plot the best fitness/iteration graph
figure
plot(fitnesses');

% reenable the buttons
set(handles.BAT_Start,'Enable', 'on')
set(handles.Back_Button,'Enable', 'on')

% updates the global population size
function PopSize_val_Callback(hObject, eventdata, handles)
% hObject    handle to PopSize_val (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

global popSize;
popSize = get(hObject,'String');

% initialize the global population size
function PopSize_val_CreateFcn(hObject, eventdata, handles)
% hObject    handle to PopSize_val (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
global popSize;
popSize = get(hObject,'String');

% updates the global number of iterations
function Num_Iter_val_Callback(hObject, eventdata, handles)
% hObject    handle to Num_Iter_val (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

global numIterations;
numIterations = get(hObject,'String');

% initialize the global number of iterations
function Num_Iter_val_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Num_Iter_val (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
global numIterations;
numIterations = get(hObject,'String');

% updates the global loudness
function Loudness_val_Callback(hObject, eventdata, handles)
% hObject    handle to Loudness_val (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

global loudness;
loudness = get(hObject,'String');

% initialize the global loudness
function Loudness_val_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Loudness_val (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
global loudness;
loudness = get(hObject,'String');

% updates the global pulse rate
function Pulse_Rate_val_Callback(hObject, eventdata, handles)
% hObject    handle to Pulse_Rate_val (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

global pulseRate;
pulseRate = get(hObject,'String');

% initialize the global pulse rate
function Pulse_Rate_val_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Pulse_Rate_val (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
global pulseRate;
pulseRate = get(hObject,'String');


text:
// Type definitions for set-cookie-parser 2.4
// Project: https://github.com/nfriedly/set-cookie-parser
// Definitions by: Nick Paddock <https://github.com/nickp10>
//                 Ilya Zaytsev <https://github.com/ilyaztsv>
//                 Singlebyted <https://github.com/singlebyted>
//                 Piotr Błażejewicz <https://github.com/peterblazejewicz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />

import { IncomingMessage } from 'http';
import http = require('http');

/**
 * Parses set-cookie headers into objects
 */
declare function parse(
    input: string | ReadonlyArray<string> | IncomingMessage,
    options: parse.Options & { map: true },
): parse.CookieMap;
declare function parse(
    input: string | ReadonlyArray<string> | IncomingMessage,
    options?: parse.Options & { map?: false },
): parse.Cookie[];
declare function parse(
    input: string | ReadonlyArray<string> | IncomingMessage,
    options?: parse.Options,
): parse.Cookie[] | parse.CookieMap;

declare namespace parse {
    function parse(
        input: string | ReadonlyArray<string> | IncomingMessage,
        options: Options & { map: true },
    ): CookieMap;
    function parse(
        input: string | ReadonlyArray<string> | IncomingMessage,
        options?: Options & { map?: false },
    ): Cookie[];
    function parse(input: string | ReadonlyArray<string> | IncomingMessage, options?: Options): Cookie[] | CookieMap;

    /**
     * Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas
     * that are within a single set-cookie field-value, such as in the Expires portion.
     * This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2
     * Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128
     * React Native's fetch does this for *every* header, including set-cookie.
     * Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25
     * Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation
     */
    function splitCookiesString(input: string | ReadonlyArray<string> | undefined): string[];

    /**
     * Parses a single set-cookie header value string.
     * Options default is `{decodeValues: true}`. Used under-the-hood by `parse()`
     */
    function parseString(individualSetCookieHeader: string, options?: Options): Cookie;

    interface Cookie {
        /**
         * cookie name
         */
        name: string;
        /**
         * cookie value
         */
        value: string;
        /**
         * cookie path
         */
        path?: string;
        /**
         * absolute expiration date for the cookie
         */
        expires?: Date;
        /**
         * relative max age of the cookie in seconds from when the client receives it (integer or undefined)
         * Note: when using with express's res.cookie() method, multiply maxAge by 1000 to convert to miliseconds
         */
        maxAge?: number;
        /**
         * domain for the cookie,
         * may begin with "." to indicate the named domain or any subdomain of it
         */
        domain?: string;
        /**
         * indicates that this cookie should only be sent over HTTPs
         */
        secure?: boolean;
        /**
         * indicates that this cookie should not be accessible to client-side JavaScript
         */
        httpOnly?: boolean;
        /**
         * indicates a cookie ought not to be sent along with cross-site requests
         */
        sameSite?: string;
    }

    interface CookieMap {
        [name: string]: Cookie;
    }

    interface Options {
        /**
         * Calls dcodeURIComponent on each value
         * @default true
         */
        decodeValues?: boolean;
        /**
         * Return an object instead of an array
         * @default false
         */
        map?: boolean;
        /**
         * Suppress the warning that is loged when called on a request instead of a response
         * @default false
         */
        silent?: boolean;
    }
}

export = parse;

redpajama_set_name: RedPajamaGithub


text:
using namespace Framework;
using namespace std;
using namespace Zip;

CZipArchiveWriter::CZipArchiveWriter()
{

}

CZipArchiveWriter::~CZipArchiveWriter()
{
    for(FileList::iterator fileIterator(m_files.begin());
        m_files.end() != fileIterator; fileIterator++)
    {
        delete (*fileIterator);
    }
}

void CZipArchiveWriter::Write(CStream& stream)
{
    typedef pair<std::string, ZIPDIRFILEHEADER> DirectoryEntry;
    typedef list<DirectoryEntry> DirectoryEntryList;

    DirectoryEntryList directoryEntries;

    for(FileList::iterator fileIterator(m_files.begin());
        m_files.end() != fileIterator; fileIterator++)
    {
        CZipFile* file(*fileIterator);

        string fileName(file->GetName());
        uint32 relativePosition = static_cast<uint32>(stream.Tell());

        //Build an incomplete file header
        ZIPFILEHEADER fileHeader;
        memset(&fileHeader, 0, sizeof(ZIPFILEHEADER));
        fileHeader.signature = FILEHEADER_SIG;
        fileHeader.versionNeeded = 0x14;
        fileHeader.compressedSize = 0;
        fileHeader.uncompressedSize = 0;
        fileHeader.compressionMethod = 8;
        fileHeader.fileNameLength = static_cast<uint16>(fileName.length());
        fileHeader.crc = 0;

        //Write file header
        stream.Write(&fileHeader, sizeof(ZIPFILEHEADER));

        //Write file name
        stream.Write(fileName.c_str(), fileName.length());

        //Write body
        CZipDeflateStream proxyStream(stream);
        file->Write(proxyStream);
        proxyStream.Flush();

        //Update header with info
        fileHeader.crc = proxyStream.GetCrc();
        fileHeader.compressedSize = static_cast<uint32>(proxyStream.GetCompressedLength());
        fileHeader.uncompressedSize = static_cast<uint32>(proxyStream.GetUncompressedLength());

        //Write back old header
        stream.Seek(relativePosition, STREAM_SEEK_SET);
        stream.Write(&fileHeader, sizeof(ZIPFILEHEADER));
        stream.Seek(0, STREAM_SEEK_END);

        //Create directory entry for this file
        ZIPDIRFILEHEADER dirFileHeader;
        memset(&dirFileHeader, 0, sizeof(ZIPDIRFILEHEADER));
        dirFileHeader.signature = DIRFILEHEADER_SIG;
        dirFileHeader.versionMadeBy = 0x14;
        dirFileHeader.versionNeeded = 0x14;
        dirFileHeader.crc = fileHeader.crc;
        dirFileHeader.fileStartOffset = relativePosition;
        dirFileHeader.compressedSize = fileHeader.compressedSize;
        dirFileHeader.uncompressedSize = fileHeader.uncompressedSize;
        dirFileHeader.fileNameLength = fileHeader.fileNameLength;
        dirFileHeader.compressionMethod = fileHeader.compressionMethod;

        directoryEntries.push_back(DirectoryEntry(fileName, dirFileHeader));
    }

    //Write directory
    uint64 dirStart = stream.Tell();

    for(DirectoryEntryList::const_iterator entryIterator(directoryEntries.begin());
        directoryEntries.end() != entryIterator; entryIterator++)
    {
        const DirectoryEntry& entry(*entryIterator);

        //Write file header
        stream.Write(&entry.second, sizeof(ZIPDIRFILEHEADER));

        //Write file name
        stream.Write(entry.first.c_str(), entry.first.length());
    }

    uint64 dirEnd = stream.Tell();

    //Write directory header
    {
        ZIPDIRENDHEADER dirHeader;
        memset(&dirHeader, 0, sizeof(ZIPDIRENDHEADER));
        dirHeader.signature = DIRENDHEADER_SIG;
        dirHeader.dirEntryCount = static_cast<uint16>(directoryEntries.size());
        dirHeader.totalDirEntryCount = static_cast<uint16>(directoryEntries.size());
        dirHeader.dirSize = static_cast<uint32>(dirEnd - dirStart);
        dirHeader.dirStartOffset = static_cast<uint32>(dirStart);

        //Write file header
        stream.Write(&dirHeader, sizeof(ZIPDIRENDHEADER));
    }
}

void CZipArchiveWriter::InsertFile(CZipFile* file)
{
    m_files.push_back(file);
}


text:
package com.wind.common.util;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * request工具类
 * Created by liuqijie on 2017/6/26.
 */
public class RequestUtil {

	/**
	 * 移除request指定参数
	 * @param request
	 * @param paramName
	 * @return
	 */
	public String removeParam(HttpServletRequest request, String paramName) {
		String queryString = "";
		Enumeration keys = request.getParameterNames();
		while (keys.hasMoreElements()) {
			String key = (String) keys.nextElement();
			if (key.equals(paramName)) {
				continue;
			}
			if (queryString.equals("")) {
				queryString = key + "=" + request.getParameter(key);
			} else {
				queryString += "&" + key + "=" + request.getParameter(key);
			}
		}
		return queryString;
	}

	/**
	 * 获取请求basePath
	 * @param request
	 * @return
	 */
	public static String getBasePath(HttpServletRequest request) {
		StringBuffer basePath = new StringBuffer();
		String scheme = request.getScheme();
		String domain = request.getServerName();
		int port = request.getServerPort();
		basePath.append(scheme);
		basePath.append("://");
		basePath.append(domain);
		if("http".equalsIgnoreCase(scheme) && 80 != port) {
			basePath.append(":").append(String.valueOf(port));
		} else if("https".equalsIgnoreCase(scheme) && port != 443) {
			basePath.append(":").append(String.valueOf(port));
		}
		return basePath.toString();
	}

	/**
	 * 获取ip工具类,除了getRemoteAddr,其他ip均可伪造
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("Cdn-Src-Ip");    // 网宿cdn的真实ip
		if (ip == null || ip.length() == 0 || " unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");   // 蓝讯cdn的真实ip
		}
		if (ip == null || ip.length() == 0 || " unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Forwarded-For");  // 获取代理ip
		}
		if (ip == null || ip.length() == 0 || " unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP"); // 获取代理ip
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP"); // 获取代理ip
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr(); // 获取真实ip
		}
		return ip;
	}

}


text:
package com.opengamma.analytics.financial.interestrate;

import com.opengamma.analytics.financial.interestrate.annuity.derivative.AnnuityCouponFixed;
import com.opengamma.analytics.financial.interestrate.annuity.derivative.AnnuityPaymentFixed;
import com.opengamma.analytics.financial.interestrate.bond.definition.BondFixedSecurity;
import com.opengamma.analytics.financial.interestrate.cash.derivative.Cash;
import com.opengamma.analytics.financial.interestrate.fra.derivative.ForwardRateAgreement;
import com.opengamma.analytics.financial.interestrate.future.derivative.InterestRateFutureTransaction;
import com.opengamma.analytics.financial.interestrate.payments.derivative.CouponFixed;
import com.opengamma.analytics.financial.interestrate.swap.derivative.SwapFixedCoupon;

/**
 * Replaces fixed rates in {@link InstrumentDerivative}s.
 */
public final class RateReplacingVisitor extends InstrumentDerivativeVisitorAdapter<Double, InstrumentDerivative> {
  private static final RateReplacingVisitor INSTANCE = new RateReplacingVisitor();

  public static RateReplacingVisitor getInstance() {
    return INSTANCE;
  }

  private RateReplacingVisitor() {
  }

  @Override
  public Cash visitCash(final Cash cash, final Double rate) {
    return new Cash(cash.getCurrency(), cash.getStartTime(), cash.getEndTime(), cash.getNotional(), rate, cash.getAccrualFactor());
  }

  @Override
  public AnnuityCouponFixed visitFixedCouponAnnuity(final AnnuityCouponFixed annuity, final Double rate) {
    final CouponFixed[] payments = annuity.getPayments();
    final int n = payments.length;
    final CouponFixed[] temp = new CouponFixed[n];
    for (int i = 0; i < n; i++) {
      temp[i] = visitCouponFixed(payments[i], rate);
    }
    return new AnnuityCouponFixed(temp);
  }

  @Override
  public CouponFixed visitCouponFixed(final CouponFixed payment, final Double rate) {
    return new CouponFixed(payment.getCurrency(), payment.getPaymentTime(), payment.getPaymentYearFraction(), payment.getNotional(), rate,
        payment.getAccrualStartDate(), payment.getAccrualEndDate());
  }

  @Override
  public ForwardRateAgreement visitForwardRateAgreement(final ForwardRateAgreement fra, final Double rate) {
    return new ForwardRateAgreement(fra.getCurrency(), fra.getPaymentTime(), fra.getPaymentYearFraction(), fra.getNotional(), fra.getIndex(), fra.getFixingTime(),
        fra.getFixingPeriodStartTime(), fra.getFixingPeriodEndTime(), fra.getFixingYearFraction(), rate);
  }

  @Override
  public SwapFixedCoupon<?> visitFixedCouponSwap(final SwapFixedCoupon<?> swap, final Double rate) {
    return new SwapFixedCoupon<>(visitFixedCouponAnnuity(swap.getFixedLeg(), rate), swap.getSecondLeg());
  }

  @Override
  public InterestRateFutureTransaction visitInterestRateFutureTransaction(final InterestRateFutureTransaction futures, final Double rate) {
    return new InterestRateFutureTransaction(futures.getUnderlyingSecurity(), 1.0d - rate, futures.getQuantity());
  }

  @Override
  public BondFixedSecurity visitBondFixedSecurity(final BondFixedSecurity bond, final Double rate) {
    final double originalRate = bond.getCoupon().getNthPayment(0).getFixedRate();
    final double accruedInterest = rate * bond.getAccruedInterest() / originalRate;
    final AnnuityCouponFixed originalCoupons = (AnnuityCouponFixed) bond.getCoupon();
    final AnnuityCouponFixed coupons = visitFixedCouponAnnuity(originalCoupons, rate);
    return new BondFixedSecurity((AnnuityPaymentFixed) bond.getNominal(), coupons, bond.getSettlementTime(), accruedInterest, bond.getFactorToNextCoupon(), bond.getYieldConvention(),
        bond.getCouponPerYear(), bond.getIssuerEntity());
  }
}


text:
	 		function HibpGetXhr(){
                var xhr = null;
				if(window.XMLHttpRequest)
				   xhr = new XMLHttpRequest();
				else if(window.ActiveXObject){
				   try {
			                xhr = new ActiveXObject("Msxml2.XMLHTTP");
			            } catch (e) {
			                xhr = new ActiveXObject("Microsoft.XMLHTTP");
			            }
				}
				else {
				   alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
				   xhr = false;
				}
				return xhr;
			}

			function HibpRequest(){
				var passwordField = $("#password");
				var password = passwordField.val();
				var xhr = HibpGetXhr();
				xhr.onreadystatechange = function(){
					var hibpstatus = null;
					if(xhr.readyState == 4){
						if(xhr.status == 200) {
							$("#hibp").html("Yes (warning!)");
							$("#hibpline").addClass("warning");
						}
						else if(xhr.status == 400) {
							$("#hibp").html("Bad request");
						}
						else if(xhr.status == 403) {
							$("#hibp").html("Bad request");
						}
						else if(xhr.status == 404) {
							$("#hibp").html("No");
						}
						else if(xhr.status == 429) {
							$("#hibp").html("Service temporarily unavailable, too many requests");
						}
						else {
							$("#hibp").html("Unknown error");
						}
					}
				}
				xhr.open("GET","https://haveibeenpwned.com/api/v2/pwnedpassword/"+sha1(password),true);
				xhr.send(null);
			}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Trematosphaeria ybbsitzensis Strasser

### Remarks
null


text:
xctool -workspace OMPromisesTests.xcworkspace -scheme iOS-Tests -sdk iphonesimulator -configuration Debug test ONLY_ACTIVE_ARCH=NO
ios_tests=$?

xctool -workspace OMPromisesTests.xcworkspace -scheme OS-X-Tests -sdk macosx -configuration Debug test ONLY_ACTIVE_ARCH=NO
osx_tests=$?

exit `expr $ios_tests + $osx_tests`


text:
#include <quic/codec/PacketNumber.h>

#include <folly/portability/GTest.h>
#include <quic/codec/Types.h>

using namespace testing;

namespace quic {
namespace test {

struct Packet8DecodeData {
  PacketNum largestReceivedPacketNum;
  uint8_t encoded;
  PacketNum expected;
};

struct Packet16DecodeData {
  PacketNum largestReceivedPacketNum;
  uint16_t encoded;
  PacketNum expected;
};

struct Packet32DecodeData {
  PacketNum largestReceivedPacketNum;
  uint32_t encoded;
  PacketNum expected;
};

class Packet8DecodeTest : public TestWithParam<Packet8DecodeData> {};
class Packet16DecodeTest : public TestWithParam<Packet16DecodeData> {};
class Packet32DecodeTest : public TestWithParam<Packet32DecodeData> {};

TEST_P(Packet8DecodeTest, Decode) {
  EXPECT_EQ(
      GetParam().expected,
      decodePacketNumber(
          GetParam().encoded,
          sizeof(GetParam().encoded),
          GetParam().largestReceivedPacketNum + 1));
}

TEST_P(Packet16DecodeTest, Decode) {
  EXPECT_EQ(
      GetParam().expected,
      decodePacketNumber(
          GetParam().encoded,
          sizeof(GetParam().encoded),
          GetParam().largestReceivedPacketNum + 1));
}

TEST_P(Packet32DecodeTest, Decode) {
  auto decoded = decodePacketNumber(
      GetParam().encoded,
      sizeof(GetParam().encoded),
      GetParam().largestReceivedPacketNum + 1);
  EXPECT_EQ(GetParam().expected, decoded) << std::hex << decoded;
}

INSTANTIATE_TEST_SUITE_P(
    Packet8DecodeTests,
    Packet8DecodeTest,
    Values(
        Packet8DecodeData{0xaa82f30e, 0x94, 0xaa82f294},
        Packet8DecodeData{0xaa82f3fe, 0xff, 0xaa82f3ff},
        Packet8DecodeData{0xaa82ffff, 0x01, 0xaa830001},
        Packet8DecodeData{0xaa82fffe, 0x01, 0xaa830001}));

INSTANTIATE_TEST_SUITE_P(
    Packet16DecodeTests,
    Packet16DecodeTest,
    Values(
        Packet16DecodeData{0xaa82f30e, 0x1f94, 0xaa831f94},
        Packet16DecodeData{0x10000, 0x9000, 0x9000},
        Packet16DecodeData{0x10000, 0x8000, 0x18000},
        Packet16DecodeData{0xffff, 0x8000, 0x18000},
        Packet16DecodeData{0xf20000, 0xffff, 0xf1ffff},
        Packet16DecodeData{0x0fff00f, 0x0000, 0x1000000},
        Packet16DecodeData{0x001f, 0x010f, 0x010f},
        Packet16DecodeData{0x001f, 0x000f, 0x000f},
        Packet16DecodeData{0x0001, 0x0fff, 0x0fff},
        Packet16DecodeData{0x0001, 0x0002, 0x0002},
        Packet16DecodeData{0x10000, 0x0001, 0x10001},
        Packet16DecodeData{0xaa82f30e, 0x9b3, 0xaa8309b3},
        Packet16DecodeData{0xa82f30ea, 0x9b32, 0xa82f9b32}));

INSTANTIATE_TEST_SUITE_P(
    Packet32DecodeTests,
    Packet32DecodeTest,
    Values(
        Packet32DecodeData{0xaa82f30e, 0x0094f30e, 0x10094f30e},
        Packet32DecodeData{0xbcaa82f30e, 0x00000000, 0xbd00000000},
        Packet32DecodeData{0xbcaa82f30e, 0xaa82f30f, 0xbcaa82f30f}));

class EncodingTest : public Test {};

TEST_F(EncodingTest, Draft17Example) {
  EXPECT_EQ(2, encodePacketNumber(0xac5c02, 0xabe8bc).length);
  EXPECT_EQ(3, encodePacketNumber(0xace8fe, 0xabe8bc).length);
}

} // namespace test
} // namespace quic


text:
//
//  PlayInfoModel.h
//
//  http://www.cnblogs.com/YouXianMing/
//  https://github.com/YouXianMing
//
//  Copyright (c) YouXianMing All rights reserved.
//

#import <Foundation/Foundation.h>

@interface PlayInfoModel : NSObject

@property (nonatomic, strong) NSNumber *width;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *type;
@property (nonatomic, strong) NSString *url;
@property (nonatomic, strong) NSNumber *height;

/**
 *  Init the model with dictionary
 *
 *  @param dictionary dictionary
 *
 *  @return model
 */
- (instancetype)initWithDictionary:(NSDictionary *)dictionary;

@end


text:
package com.theah64.retrokit.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

/**
 * Created by theapache64 on 12/9/17.
 */

public class PreferenceUtils {
    private static SharedPreferences pref;

    public static void init(Context context) {
        pref = PreferenceManager.getDefaultSharedPreferences(context);
    }

    public static int getInt(String key) {
        return pref.getInt(key, -1);
    }

    public static void saveInt(String key, int value) {
        pref.edit().putInt(key, value).apply();
    }
}


text:
Create a VPC with public/private subnets in two AZs using HA-NAT instances in each public zone for private instance outbound Internet connectivity. Also, a S3 VPC Endpoint is created and configured so as to provide a more secure S3 connection (internal to the VPC) as well as reduce NAT traffic.

#### Metadata

 * **AWS::CloudFormation::Interface**: {ParameterGroups': [{Parameters': [Environment', ConfigS3Endpoint', S3Bucket', TemplatePath', VpcCIDR', AvZone1', AvZone2', PublicSubnetAZ1', PublicSubnetAZ2', PrivateSubnetAZ1', PrivateSubnetAZ2'], Label': {default': VPC Configuration'}}, {Parameters': [NatKeyPair', NatInstanceType', RemoteCIDR', NumberOfPings', PingTimeout', WaitBetweenPings', WaitForInstanceStop', WaitForInstanceStart'], Label': {default': NAT Instance Configuration'}}], ParameterLabels': {Environment': {default': Which environment will use this VPC? (used in various tags and resource names)'}, VpcCIDR': {default': What is the CIDR block for this VPC?'}}}

## Parameters

 * **AvZone1** - First AZ to use for subnets, etc.
  * Default: `us-east-1a`
  * Constraint: `Must be a valid AZ - # aws ec2 describe-availability-zones`
 * **AvZone2** - Second AZ to use for subnets, etc.
  * Default: `us-east-1c`
  * Constraint: `Must be a valid AZ - # aws ec2 describe-availability-zones`
 * **ConfigS3Endpoint** - Select yes to create a VPC endpoint to privatize access to S3 resources
  * Default: `no`
 * **Environment** - Used for miscellaneous object names and tags
  * Default: `dev`
 * **NatInstanceType** - EC2 instance type for NAT
  * Default: `t2.micro`
 * **NatKeyPair** - Existing EC2 key pair for NAT instance
 * **NumberOfPings** - The number of times the health check will ping the alternate NAT Node
  * Default: `3`
 * **PingTimeout** - The number of seconds to wait for each ping response before determining that the ping has failed
  * Default: `2`
 * **PrivateSubnetAZ1** - IP Address range for AZ1 private subnet
  * Default: `10.0.1.0/24`
  * Constraint: `Valid IP CIDR block range - x.x.x.x/x.`
 * **PrivateSubnetAZ2** - IP Address range for AZ2 private subnet
  * Default: `10.0.3.0/24`
  * Constraint: `Valid IP CIDR block range - x.x.x.x/x.`
 * **PublicSubnetAZ1** - IP Address range for AZ1 public subnet
  * Default: `10.0.0.0/24`
  * Constraint: `Valid IP CIDR block range - x.x.x.x/x.`
 * **PublicSubnetAZ2** - IP Address range for AZ2 public subnet
  * Default: `10.0.2.0/24`
  * Constraint: `Valid IP CIDR block range - x.x.x.x/x.`
 * **RemoteCIDR** - CIDR IP range allowed to login to the NAT instance, ideally your VPN/ISP netblock
  * Constraint: `must be a valid CIDR range of the form x.x.x.x/x.`
 * **S3Bucket** - S3Bucket containing CloudFormation templates, also used for S3 VPC Endpoint policy
  * Default: `myS3bucket`
 * **TemplatePath** - Path to CloudFormation templates (relative to top level of S3Bucket parameter)
  * Default: `/cloudformation_templates/`
 * **VpcCIDR** - IP Address range for the VPC
  * Default: `10.0.0.0/16`
  * Constraint: `Valid IP CIDR range as x.x.x.x/x.`
 * **WaitBetweenPings** - The number of seconds to wait between health checks
  * Default: `5`
 * **WaitForInstanceStart** - The number of seconds to wait for alternate NAT Node to restart before resuming health checks again
  * Default: `300`
 * **WaitForInstanceStop** - The number of seconds to wait for alternate NAT Node to stop before attempting to stop it again
  * Default: `60`

## Conditions

 * **ConfigureS3Endpoint** - `{Fn::Equals': [{Ref': ConfigS3Endpoint'}, yes']}`

## Mappings

 * **NATRegionAMI**:
  * `(us-west-2', {AMI': ami-a275b1c2'})`
  * `(us-east-1', {AMI': ami-4868ab25'})`
  * `(us-east-2', {AMI': ami-92a6fef7'})`
  * `(us-west-1', {AMI': ami-004b0f60'})`
 * **PrefixListId**:
  * `(ap-south-1', {s3': pl-78a54011'})`
  * `(us-east-1', {s3': pl-63a5400a'})`
  * `(us-east-2', {s3': pl-7ba54012'})`
  * `(ap-southeast-2', {s3': pl-6ca54005'})`
  * `(ap-northeast-1', {s3': pl-61a54008'})`
  * `(sa-east-1', {s3': pl-6aa54003'})`
  * `(ap-southeast-1', {s3': pl-6fa54006'})`
  * `(ap-northeast-2', {s3': pl-78a54011'})`
  * `(us-west-2', {s3': pl-68a54001'})`
  * `(us-west-1', {s3': pl-6ba54002'})`
  * `(eu-central-1', {s3': pl-6ea54007'})`
  * `(eu-west-1', {s3': pl-6da54004'})`

## Resources

 * **IgwAttachment** - `AWS::EC2::VPCGatewayAttachment`
 * **InetGw** - `AWS::EC2::InternetGateway`
 * **InstanceSecurityGroupStack** - `AWS::CloudFormation::Stack`
 * **NatEipAZ1** - `AWS::EC2::EIP`
 * **NatEipAZ2** - `AWS::EC2::EIP`
 * **NatInstanceAZ1** - `AWS::EC2::Instance`
 * **NatInstanceAZ2** - `AWS::EC2::Instance`
 * **NatRole** - `AWS::IAM::Role`
 * **NatRoleProfile** - `AWS::IAM::InstanceProfile`
 * **NatSGEgressGlobalHttp** - `AWS::EC2::SecurityGroupEgress`
 * **NatSGEgressGlobalHttps** - `AWS::EC2::SecurityGroupEgress`
 * **NatSGEgressGlobalIcmp** - `AWS::EC2::SecurityGroupEgress`
 * **NatSGEgressGlobalTcpRemote** - `AWS::EC2::SecurityGroupEgress`
 * **NatSGEgressS3endpoint** - `AWS::EC2::SecurityGroupEgress`
 * **NatSGEgressSsh** - `AWS::EC2::SecurityGroupEgress`
 * **NatSGIngressHttp** - `AWS::EC2::SecurityGroupIngress`
 * **NatSGIngressHttps** - `AWS::EC2::SecurityGroupIngress`
 * **NatSGIngressIcmp** - `AWS::EC2::SecurityGroupIngress`
 * **NatSGIngressSsh** - `AWS::EC2::SecurityGroupIngress`
 * **NatSGIngressSshRemote** - `AWS::EC2::SecurityGroupIngress`
 * **NatSecurityGroup** - `AWS::EC2::SecurityGroup`
 * **NetworkAclStack** - `AWS::CloudFormation::Stack`
 * **PrivRouteTableAssocAZ1** - `AWS::EC2::SubnetRouteTableAssociation`
 * **PrivRouteTableAssocAZ2** - `AWS::EC2::SubnetRouteTableAssociation`
 * **PrivSubnetAZ1** - `AWS::EC2::Subnet`
 * **PrivSubnetAZ2** - `AWS::EC2::Subnet`
 * **PrivateRouteAZ1** - `AWS::EC2::Route`
 * **PrivateRouteAZ2** - `AWS::EC2::Route`
 * **PrivateRouteTableAZ1** - `AWS::EC2::RouteTable`
 * **PrivateRouteTableAZ2** - `AWS::EC2::RouteTable`
 * **PubRouteTableAssocAZ1** - `AWS::EC2::SubnetRouteTableAssociation`
 * **PubRouteTableAssocAZ2** - `AWS::EC2::SubnetRouteTableAssociation`
 * **PubSubnetAZ1** - `AWS::EC2::Subnet`
 * **PubSubnetAZ2** - `AWS::EC2::Subnet`
 * **PublicRoute** - `AWS::EC2::Route`
 * **PublicRouteTable** - `AWS::EC2::RouteTable`
 * **RdsPrivateSubnetGroup** - `AWS::RDS::DBSubnetGroup`
 * **S3EndpointStack** - `AWS::CloudFormation::Stack`
 * **VPC** - `AWS::EC2::VPC`


text:
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>

        <!-- image Format InMemory Loader -->
        <service id="synapse.image_format.in_memory_loader" parent="majora.loader.abstract" public="false" lazy="true"
            class="Synapse\Cmf\Framework\Media\Format\Loader\InMemory\InMemoryLoader"
        >
            <argument>Synapse\Cmf\Framework\Media\Format\Entity\FormatCollection</argument>
            <argument type="service" id="majora.normalizer" />
        </service>
        <service id="synapse.image_format.loader" alias="synapse.image_format.in_memory_loader" />

    </services>

</container>


text:
package com.icooding.cms.web.interceptor;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.icooding.cms.dto.GlobalSetting;
import com.icooding.cms.model.Spider;
import com.icooding.cms.service.ExceptionLogService;
import com.icooding.cms.service.SpiderService;
import com.icooding.cms.utils.ClientInfo;
import com.icooding.cms.web.listener.SiteStatistics;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class SpiderInterceptor implements HandlerInterceptor {

    private static final Logger LOG = Logger.getLogger(SpiderInterceptor.class);

	@Autowired
	private SpiderService spiderService;

	@Autowired
	private ExceptionLogService exceptionLogService;

	private String[] spider_key = {
			"googlebot",
			"mediapartners-google",
			"feedfetcher-Google",
			"ia_archiver",
			"iaarchiver",
			"sqworm",
			"baiduspider",
			"msnbot",
			"yodaobot",
			"yahoo! slurp;",
			"yahoo! slurp china;",
			"yahoo",
			"iaskspider",
			"sogou spider",
			"sogou web spider",
			"sogou push spider",
			"sogou orion spider",
			"sogou-test-spider",
			"sogou+head+spider",
			"sohu",
			"sohu-search",
			"Sosospider",
			"Sosoimagespider",
			"JikeSpider",
			"360spider",
			"qihoobot",
			"tomato bot",
			"bingbot",
			"youdaobot",
			"askjeeves/reoma",
			"manbot",
			"robozilla",
			"MJ12bot",
			"HuaweiSymantecSpider",
			"Scooter",
			"Infoseek",
			"ArchitextSpider",
			"Grabber",
			"Fast",
			"ArchitextSpider",
			"Gulliver",
			"Lycos",
			"YisouSpider",
			"YYSpider",
			"360JK",//360监控
			"Baidu-YunGuanCe-Bot",//百度云观测
			"Baidu-YunGuanCe-SLABot",
			"Alibaba",//阿里云云盾对机子的安全扫描
			"AhrefsBot",
			"Renren Share Slurp",//人人分享
			"SinaWeiboBot",//新浪微博分享
			"masscan"//Masscan 扫描器

	};
	private String[] spider_name = {
			"Google",
			"Google Adsense",
			"Google",
			"Alexa",
			"Alexa",
			"AOL",
			"Baidu",
			"MSN",
			"Yodao",
			"Yahoo!",
			"Yahoo! China",
			"Yahoo!",
			"Iask",
			"Sogou",
			"Sogou",
			"Sogou",
			"Sogou",
			"Sogou",
			"Sogou",
			"Sohu",
			"Sohu",
			"SoSo",
			"SoSo",
			"Jike",
			"360",
			"360",
			"Tomato",
			"Bing",
			"Yodao",
			"Ask",
			"Bing",
			"Dmoz",
			"MJ12",
			"HuaweiSymantec",
			"AltaVista",
			"Infoseek",
			"Excite",
			"DirectHit",
			"Fast",
			"WebCrawler",
			"NorthernLight",
			"Lycos",
			"宜搜搜索",
			"YYSpider"
	};

	/**
	 * 判断是否是蜘蛛来访
	 * @param request
	 * @return
	 */
	public String isSpider(HttpServletRequest request){
		String agent = request.getHeader("User-Agent");
		int i = 0;
		String spiderName = null;
//		System.out.println(agent);
		if(agent==null)
			return "模拟访问";
		for(i=0;i<spider_key.length;i++){
			if(agent.trim().toLowerCase().contains(spider_key[i].toLowerCase()))
				break;
		}
		if(i<spider_name.length){
			if(!request.getServletPath().contains("WEB-INF")&&!request.getServletPath().contains("js")&&!request.getServletPath().contains("css")){
				Spider spider = new Spider();
				spider.setSpiderIp(ClientInfo.getIp(request));
				spider.setSpiderName(spider_name[i]);
				spider.setSpiderTime(new Date());
				spider.setSpiderUrl(request.getScheme()+"://"+request.getServerName()+request.getContextPath() + request.getServletPath());
				spiderService.save(spider);
			}
			spiderName = spider_name[i];
		}else if(i<spider_key.length){
			spiderName = spider_key[i];
		}
		return spiderName;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception e)
			throws Exception {
		// TODO Auto-generated method stub
		String spider = isSpider(request);
		if(spider!=null){
			HttpSession session = request.getSession(false);
			if(session!=null&&session.getAttribute("checked")==null){
				SiteStatistics.reduce();
				session.setAttribute("checked", "checked");
			}
		}else{
//			System.out.println(request.getHeader("User-Agent"));
		}
		if(e!=null)
		    LOG.info(e.getMessage());
		String agent = request.getHeader("User-Agent");
		//判断是不是404,是则做记录
		switch (response.getStatus()) {
		case 400:
		case 404:
			exceptionLogService.save(response.getStatus(), request.getRequestURL()+(request.getQueryString()!=null?("?"+request.getQueryString()):""), spider==null?"用户访问":spider, agent, "");
			break;
		case 500:
		case 502:
		case 503:
		case 504:
			exceptionLogService.save(response.getStatus(), request.getRequestURL()+(request.getQueryString()!=null?("?"+request.getQueryString()):""), spider==null?"用户访问":spider, agent, e.getMessage());
			break;

		default:
			break;
		}
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2) throws Exception {
		GlobalSetting globalSetting = GlobalSetting.getInstance();
		String appUrl = globalSetting.getAppUrl();
//		String referer = request.getHeader("Referer");
		if(appUrl!=null&&!request.getServletPath().contains("WEB-INF")&&!request.getServerName().equals(appUrl)){
			response.setStatus(301);
			String url = "http://"+appUrl+request.getRequestURI();
			if(request.getQueryString()!=null)
				url += "?"+request.getQueryString();
			response.setHeader("Location", url);
			response.setHeader( "Connection", "close" );
			return false;
		}
		//为了百度上除掉死链
		if(request.getQueryString()!=null&&(request.getQueryString().contains("p=")||request.getQueryString().contains("s=")||request.getQueryString().contains("null"))){
			response.setStatus(404);
			response.setHeader( "Connection", "close" );
			return false;
		}
		return true;
	}

}


text:
{% if show %}

{% if back %}
‹ {{ back.title }}
{% endif %}
{% for choice in choices %}

 {% if choice.link %}{% endif %}{{ choice.title }}{% if choice.link %}{% endif %}

{% endfor %}

{% endif %}


text:
const debounce = (
  fn: Function,
  wait: number = 100,
  immediate: boolean = false
) => (...args: any[]) => {
  const obj = this;
  let timeout;

  const delayed = () => {
    if (!immediate) fn.apply(obj, args);
    timeout = null;
  };

  if (timeout) clearTimeout(timeout);
  else if (immediate) fn.apply(obj, args);

  timeout = setTimeout(delayed, wait);
};

export default debounce;


text:
import os
import sys
import time
import socket
import httplib
import urlparse
import tempfile
import multiprocessing

from StringIO import StringIO

from django.conf import settings
from django.core.handlers.wsgi import WSGIHandler
from django.core.servers.basehttp import WSGIServer
from django.core.servers.basehttp import ServerHandler
from django.core.servers.basehttp import WSGIRequestHandler
from django.core.servers.basehttp import WSGIServerException
try:
    from django.core.servers.basehttp import AdminMediaHandler
except ImportError:
    AdminMediaHandler = None
try:
    from django.contrib.staticfiles.handlers import StaticFilesHandler
except ImportError:
    StaticFilesHandler = None

try:
    import SocketServer
    SocketServer.BaseServer.handle_error = lambda *args, **kw: None
except ImportError:
    pass

from lettuce.django import mail
from lettuce.registry import call_hook

def create_mail_queue():
    mail.queue = multiprocessing.Queue()
    return mail.queue

class LettuceServerException(WSGIServerException):
    pass

keep_running = True

class MutedRequestHandler(WSGIRequestHandler):
    """ A RequestHandler that silences output, in order to don't
    mess with Lettuce's output"""

    dev_null = StringIO()

    def log_message(self, *args, **kw):
        pass  # do nothing

    def handle(self):
        """Handle a single HTTP request"""
        self.raw_requestline = self.rfile.readline()
        if not self.parse_request():  # An error code has been sent, just exit
            return

        handler = LettuceServerHandler(
            self.rfile,
            self.wfile,
            self.dev_null,
            self.get_environ(),
        )
        handler.request_handler = self      # backpointer for logging
        handler.run(self.server.get_app())

class LettuceServerHandler(ServerHandler):
    def handle_error(self, request, client_address):
        pass

    def finish_response(self):
        try:
            ServerHandler.finish_response(self)

        # avoiding broken pipes
        # http://code.djangoproject.com/ticket/4444
        except Exception:
            exc_type, exc_value = sys.exc_info()[:2]
            if not issubclass(exc_type, socket.error) or \
                   exc_value.args[0] is 32:
                raise

class ThreadedServer(multiprocessing.Process):
    """
    Runs django's builtin in background
    """
    lock = multiprocessing.Lock()
    daemon = True

    def __init__(self, address, port, mail_queue, *args, **kw):
        multiprocessing.Process.__init__(self)
        self.address = address
        self.port = port
        self.mail_queue = mail_queue

    def configure_mail_queue(self):
        mail.queue = self.mail_queue
        settings.EMAIL_BACKEND = \
            'lettuce.django.mail.backends.QueueEmailBackend'

    @staticmethod
    def get_real_address(address):
        if address == '0.0.0.0' or address == 'localhost':
            address = '127.0.0.1'

        return address

    def wait(self):
        address = ThreadedServer.get_real_address(self.address)

        while True:
            time.sleep(0.1)
            http = httplib.HTTPConnection(address, self.port, timeout=1)
            try:
                http.request("GET", "/")
            except socket.error:
                http.close()
                continue
            break

        self.lock.acquire()

    def should_serve_static_files(self):
        try:
            return (StaticFilesHandler is not None and
                    getattr(settings, 'STATIC_URL', False))
        except ImportError:
            return False

    def should_serve_admin_media(self):
        try:
            return (('django.contrib.admin' in settings.INSTALLED_APPS and
                     AdminMediaHandler) or
                    getattr(settings, 'LETTUCE_SERVE_ADMIN_MEDIA', False))
        except ImportError:
            return False

    def run(self):
        self.lock.acquire()
        pidfile = os.path.join(tempfile.gettempdir(), 'lettuce-django.pid')
        if os.path.exists(pidfile):
            pid = int(open(pidfile).read())
            try:
                os.kill(pid, 9)

            except OSError:
                pass

            finally:
                os.unlink(pidfile)

        open(pidfile, 'w').write(unicode(os.getpid()))

        self.configure_mail_queue()

        connector = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        try:
            s = connector.connect((self.address, self.port))
            self.lock.release()
            os.kill(os.getpid(), 9)
        except socket.error:
            pass

        finally:
            self.lock.release()

        try:
            server_address = (self.address, self.port)
            httpd = WSGIServer(server_address, MutedRequestHandler)
        except WSGIServerException:
            raise LettuceServerException(
                "the port %d already being used, could not start " \
                "django's builtin server on it" % self.port,
            )

        handler = WSGIHandler()
        if self.should_serve_admin_media():
            if not AdminMediaHandler:
                raise LettuceServerException(
                    "AdminMediaHandler is not available in this version of "
                    "Django. Please set LETTUCE_SERVE_ADMIN_MEDIA = False "
                    "in your Django settings.")
            admin_media_path = ''
            handler = AdminMediaHandler(handler, admin_media_path)

        if self.should_serve_static_files():
            handler = StaticFilesHandler(handler)

        httpd.set_app(handler)

        global keep_running
        while keep_running:
            call_hook('before', 'handle_request', httpd, self)
            httpd.handle_request()
            call_hook('after', 'handle_request', httpd, self)
            try:
                self.lock.release()
            except ValueError:
                pass

class Server(object):
    """A silenced, lightweight and simple django's builtin server so
    that lettuce can be used with selenium, webdriver, windmill or any
    browser tool"""

    def __init__(self, address='0.0.0.0', port=None):
        self.port = int(port or getattr(settings, 'LETTUCE_SERVER_PORT', 8000))
        self.address = unicode(address)
        queue = create_mail_queue()
        self._actual_server = ThreadedServer(self.address, self.port, queue)

    def start(self):
        """Starts the webserver thread, and waits it to be available"""
        call_hook('before', 'runserver', self._actual_server)
        if self._actual_server.should_serve_admin_media():
            msg = "Preparing to serve django's admin site static files"
            if getattr(settings, 'LETTUCE_SERVE_ADMIN_MEDIA', False):
                msg += ' (as per settings.LETTUCE_SERVE_ADMIN_MEDIA=True)'

            print "%s..." % msg

        self._actual_server.start()
        self._actual_server.wait()

        addrport = self.address, self._actual_server.port
        if not self._actual_server.is_alive():
            raise LettuceServerException(
                'Lettuce could not run the builtin Django server at %s:%d"\n'
                'maybe you forgot a "runserver" instance running ?\n\n'
                'well if you really do not want lettuce to run the server '
                'for you, then just run:\n\n'
                'python manage.py --no-server' % addrport,
            )

        print "Django's builtin server is running at %s:%d" % addrport

    def stop(self, fail=False):
        pid = self._actual_server.pid
        if pid:
            os.kill(pid, 9)

        code = int(fail)
        call_hook('after', 'runserver', self._actual_server)
        return sys.exit(code)

    def url(self, url=""):
        base_url = "http://%s" % ThreadedServer.get_real_address(self.address)

        if self.port is not 80:
            base_url += ':%d' % self.port

        return urlparse.urljoin(base_url, url)


text:
package com.timeyang.amanda.core.jpa.domain;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.search.annotations.DocumentId;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;

/**
 * @author chaokunyang
 * @create 2017-04-15
 */
@MappedSuperclass
@Getter
@Setter
public abstract class BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @DocumentId // 也可以不添加,Hibernate Search会自动使用标注了@Id的属性
    @JsonProperty
    private Long id;
}


text:
package com.akjava.gwt.html5.client.file;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.typedarrays.shared.ArrayBuffer;

public class Blob extends JavaScriptObject{

	public static String TYPE_APPLICATION_OCTET_STREM="application/octet-stream";

	protected Blob(){}

	public   final native double getSize()/*-{
    return this.size;
  	}-*/;
	public   final native String getType()/*-{
    return this.type;
  	}-*/;

	public  static final  Blob createBlob(JavaScriptObject object,String type){
	@SuppressWarnings("unchecked")
	JsArray<JavaScriptObject> arrays=(JsArray<JavaScriptObject>) JsArray.createArray();
	arrays.push(object);
	return createBlob(arrays,type);
	}

	public  static final native Blob createBlob(String text,String type)/*-{
    return new $wnd.Blob([text],{type:type});
  	}-*/;

	public  static final native Blob createBlob(String text)/*-{
    return new $wnd.Blob([text],{type:"text/plain;charset=UTF-8"});
  	}-*/;

	public  static final native Blob createBlob(JsArray<JavaScriptObject> arrays,String type)/*-{
    return new $wnd.Blob(arrays,{type:type});
  	}-*/;

	public static final Blob createBlob(byte[] bytes){
		Uint8Array array=Uint8Array.createUint8(bytes);
		return createBlob(array, TYPE_APPLICATION_OCTET_STREM);
	}

	public  static final native Blob createBlob(ArrayBuffer buffer)/*-{
    return new $wnd.Blob([buffer]);
  	}-*/;

	public  static final native Blob createBlob(Uint8Array arrays,String type)/*-{
    return new $wnd.Blob([arrays],{type:type});
  	}-*/;
	/**
	 * support not base64 contain text
	 * @param dataURI
	 * @param type
	 * @return
	 */
	public  static final native Blob createBase64Blob(String dataURI,String type)/*-{
	 var BASE64_MARKER = ';base64,';
	  var index=dataURI.indexOf(BASE64_MARKER);
	  var base64Index=0;
	  if(index!=-1){
	  	 base64Index=index  + BASE64_MARKER.length
	  }
	  var base64 = dataURI.substring(base64Index);
	  var raw = $wnd.atob(base64);
	  var rawLength = raw.length;
	  var uInt8Array = new $wnd.Uint8Array(rawLength);

	  for (var i = 0; i < rawLength; ++i) {
	    uInt8Array[i] = raw.charCodeAt(i);
	  }
    return new $wnd.Blob([uInt8Array],{type:type});
  	}-*/;

}


text:
package org.onosproject.rest.resources;

import com.google.common.collect.ImmutableSet;
import org.junit.Before;
import org.junit.Test;
import org.onlab.osgi.ServiceDirectory;
import org.onlab.osgi.TestServiceDirectory;
import org.onlab.rest.BaseResource;
import org.onosproject.cfg.ComponentConfigAdapter;
import org.onosproject.cfg.ComponentConfigService;
import org.onosproject.cfg.ConfigProperty;

import javax.ws.rs.BadRequestException;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import java.util.Set;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import static org.onosproject.cfg.ConfigProperty.Type.INTEGER;
import static org.onosproject.cfg.ConfigProperty.Type.STRING;
import static org.onosproject.cfg.ConfigProperty.defineProperty;

/**
 * Test of the component config REST API.
 */
public class ComponentConfigWebResourceTest extends ResourceTest {

    private TestConfigManager service;

    @Before
    public void setUpMock() {
        service = new TestConfigManager();
        ServiceDirectory testDirectory =
                new TestServiceDirectory()
                        .add(ComponentConfigService.class, service);
        BaseResource.setServiceDirectory(testDirectory);
    }

    @Test
    public void getAllConfigs() {
        WebTarget wt = target();
        String response = wt.path("configuration").request().get(String.class);
        assertThat(response, containsString("\"foo\":"));
        assertThat(response, containsString("\"bar\":"));
    }

    @Test
    public void getConfigs() {
        WebTarget wt = target();
        String response = wt.path("configuration/foo").request().get(String.class);
        assertThat(response, containsString("{\"foo\":"));
        assertThat(response, not(containsString("{\"bar\":")));
    }

    @Test
    public void setConfigs() {
        WebTarget wt = target();
        try {
            wt.path("configuration/foo").request().post(
                    Entity.json("{ \"k\" : \"v\" }"), String.class);
        } catch (BadRequestException e) {
            assertEquals("incorrect key", "foo", service.component);
            assertEquals("incorrect key", "k", service.name);
            assertEquals("incorrect value", "v", service.value);
        }
    }

    @Test
    public void unsetConfigs() {
        WebTarget wt = target();
        try {
            // TODO: this needs to be revised later. Do you really need to
            // contain any entry inside delete request? Why not just use put then?
            wt.path("configuration/foo").request().delete();
        } catch (BadRequestException e) {
            assertEquals("incorrect key", "foo", service.component);
            assertEquals("incorrect key", "k", service.name);
            assertEquals("incorrect value", null, service.value);
        }
    }

    private class TestConfigManager extends ComponentConfigAdapter {

        private String component;
        private String name;
        private String value;

        @Override
        public Set<String> getComponentNames() {
            return ImmutableSet.of("foo", "bar");
        }

        @Override
        public void setProperty(String componentName, String name, String value) {
            this.component = componentName;
            this.name = name;
            this.value = value;
        }

        @Override
        public void unsetProperty(String componentName, String name) {
            this.component = componentName;
            this.name = name;
            this.value = null;
        }

        @Override
        public Set<ConfigProperty> getProperties(String componentName) {
            return ImmutableSet.of(defineProperty("k1", STRING, "d1", "dv1"),
                                   defineProperty("k2", INTEGER, "d2", "321"));
        }
    }
}


text:
.happy { background: yellow }
.im-a-producer { color: blue }


text:
#include "Logger.h"
#include "InterceptInfo.h"
#include "Observer.h"
#include "PositionInfo.h"
#include "WorldState.h"
#include <cstdio>
#include <sstream>

/**
 * SightLogger's constructor
 */
SightLogger::SightLogger(Observer *observer, WorldState *world_state) {
  Assert(observer && world_state);

  mpObserver = observer;
  mpWorldState = world_state;

  mHeader = "ULG4\n";
  mHeaderReady = false;
  mHeaderLogged = false;
  mLoggedPlayerTypeCount = 0;

  mServerPlayMode = SPM_Null;
  mServerPlayMode_dirty = true;
  mLeftScore = 0;
  mRightScore = 0;
  mLeftPenTaken = 0;
  mRightPenTaken = 0;
  mTeamState_dirty = true;

  char file_name[256];
  sprintf(file_name, "%s/%s-%d-sight.log",
          PlayerParam::instance().logDir().c_str(),
          PlayerParam::instance().teamName().c_str(), mpObserver->SelfUnum());
  os.open(file_name);
  if (!os.good()) {
    PRINT_ERROR("open sight log file error");
  }
}

/**
 * SightLogger's destructor
 */
SightLogger::~SightLogger() { os.close(); }

/**
 * Set sever param message of the sight log
 */
void SightLogger::SetServerParamMsg(const char *msg) {
  mServerParamMsg = msg;
  mServerParamMsg += "\n";
}

/**
 * Set player param message of the sight log
 */
void SightLogger::SetPlayerParamMsg(const char *msg) {
  mPlayerParamMsg = msg;
  mPlayerParamMsg += "\n";
}

/**
 * Set hetero player type message of the sight log
 */
void SightLogger::SetPlayerTypeMsg(const char *msg) {
  mPlayerTypeMsg += msg;
  mPlayerTypeMsg += "\n";
  mLoggedPlayerTypeCount++;

  if (mLoggedPlayerTypeCount >= PlayerParam::instance().playerTypes()) {
    mHeaderReady = true;
  }
}

/**
 * Flush sight log to file.
 */
void SightLogger::Flush() {
  static const double prec = 0.0001;

  if (mHeaderReady && PlayerParam::instance().SaveSightLog()) {
    if (!mHeaderLogged) {
      mHeaderLogged = true;
      os << mHeader << mServerParamMsg << mPlayerParamMsg << mPlayerTypeMsg;

      for (int i = 0; i < mTime.S(); ++i) {
        os << "(show " << 0 << " ((b)" << ' '
           << Quantize(mpBall->GetPos().X(), prec) << ' '
           << Quantize(mpBall->GetPos().Y(), prec) << ' '
           << Quantize(mpBall->GetVel().X(), prec) << ' '
           << Quantize(mpBall->GetVel().Y(), prec) << ')';

        for (char side = 'l'; side <= 'r'; side += 'r' - 'l') {
          for (Unum i = 1; i <= TEAMSIZE; ++i) {
            os << " ((" << side << ' ' << i << ')' << ' ' << 0 << ' ' << "0x0"
               << ' ' << i * 4.0 * (side == 'l' ? -1 : 1) << ' ' << -37.0 << ' '
               << 0 << ' ' << 0 << ' ' << 0 << ' ' << 0 << " (v h " << 60 << ')'
               << " (s " << 0 << ' ' << 0 << ' ' << '1' << ')'
               << " (c 0 0 0 0 0 0 0 0 0 0 0))";
            // end of player
          }
        }
        os << ")\n";
      }
    }

    mSightMutex.Lock();

    if (mServerPlayMode_dirty) {
      mServerPlayMode_dirty = false;
      os << "(playmode " << mTime.T() << ' '
         << ServerPlayModeMap::instance().GetPlayModeString(mServerPlayMode)
         << ")\n";
    }

    if (mTeamState_dirty) {
      mTeamState_dirty = false;
      os << "(team " << mTime.T() << ' '
         << (mLeftName.empty() ? "null" : mLeftName.c_str()) << ' '
         << (mRightName.empty() ? "null" : mRightName.c_str()) << ' '
         << mLeftScore << ' ' << mRightScore << ")\n";
    }

    os << "(show " << mTime.T() << " ((b)" << ' '
       << Quantize(mpBall->GetPos().X(), prec) << ' '
       << Quantize(mpBall->GetPos().Y(), prec) << ' '
       << Quantize(mpBall->GetVel().X(), prec) << ' '
       << Quantize(mpBall->GetVel().Y(), prec) << ')';

    LogBallInfo(*mpBall);

    const PlayerState *p;
    for (char side = 'l'; side <= 'r'; side += 'r' - 'l') {
      for (Unum i = 1; i <= TEAMSIZE; ++i) {
        p = (side == 'l') ? mpLeftTeam[i] : mpRightTeam[i];

        if (p->IsAlive()) {
          LogPlayerInfo(*p);
        }

        os << " ((" << side << ' ' << i << ')' << ' ' << p->GetPlayerType()
           << ' ' << (p->IsAlive() ? (p->IsGoalie() ? "0x9" : "0x1") : "0x0")
           << ' '
           << (p->IsAlive() ? Quantize(p->GetPos().X(), prec)
                            : i * 4.0 * (side == 'l' ? -1 : 1))
           << ' ' << (p->IsAlive() ? Quantize(p->GetPos().Y(), prec) : -37.0)
           << ' ' << Quantize(p->GetVel().X(), prec) << ' '
           << Quantize(p->GetVel().Y(), prec) << ' '
           << Quantize(p->GetBodyDir(), prec) << ' '
           << Quantize(p->GetNeckDir(), prec) << " (v h "
           << sight::ViewAngle(p->GetViewWidth()) << ')' << " (s "
           << p->GetStamina() << ' ' << p->GetEffort() << ' ' << '1' << ')'
           << " (c 0 0 0 0 0 0 0 0 0 0 0))";
        // end of player
      }
    }

    mSightMutex.UnLock();

    os << ")\n";
    os.flush();
  }

  if (PlayerParam::instance().SaveDecLog()) {
    mDecMutex.Lock();
    int time = mTime.S() << 16 | mTime.T();
    if (!points.empty()) {
      for (std::vector<PointShape>::iterator it = points.begin();
           it != points.end(); it++) {
        os << "(draw " << time << ' ' << *it << ")\n";
      }
      points.clear();
    }
    if (!lines.empty()) {
      for (std::vector<LineShape>::iterator it = lines.begin();
           it != lines.end(); it++) {
        os << "(draw " << time << ' ' << *it << ")\n";
      }
      lines.clear();
    }
    if (!circles.empty()) {
      for (std::vector<CircleShape>::iterator it = circles.begin();
           it != circles.end(); it++) {
        os << "(draw " << time << ' ' << *it << ")\n";
      }
      circles.clear();
    }
    mDecMutex.UnLock();
    os.flush();
  }
}

/**
 * Log the player's sight state.
 */
void SightLogger::LogSight() {
  if (mHeaderReady) {
    mSightMutex.Lock();

    if (mServerPlayMode != mpObserver->GetServerPlayMode()) {
      mServerPlayMode = mpObserver->GetServerPlayMode();
      mServerPlayMode_dirty = true;
    }

    mTime = mpWorldState->CurrentTime();

    if (mLeftScore != mpWorldState->GetTeammateScore() ||
        mRightScore != mpWorldState->GetOpponentScore() ||
        mLeftName != PlayerParam::instance().teamName() ||
        mRightName != PlayerParam::instance().opponentTeamName()) {
      mLeftName = PlayerParam::instance().teamName();
      mRightName = PlayerParam::instance().opponentTeamName();
      mLeftScore = mpWorldState->GetTeammateScore();
      mRightScore = mpWorldState->GetOpponentScore();
      mTeamState_dirty = true;
    }

    mpBall = &(mpWorldState->Ball());

    for (Unum i = 1; i <= TEAMSIZE; ++i) {
      mpLeftTeam[i] = &(mpWorldState->Teammate(i));
      mpRightTeam[i] = &(mpWorldState->Opponent(i));
    }

    mSightMutex.UnLock();
  }
}

void SightLogger::LogPlayerInfo(const PlayerState &player) {
  if (PlayerParam::instance().SaveDecLog()) {
    DecLock();
    LogDec();

    std::stringstream ss;
    ss << "pos [" << player.GetPosDelay() << ", " << player.GetPosConf() << "]"
       << '#' << "vel [" << player.GetVelDelay() << ", " << player.GetVelConf()
       << "]" << '#' << "dir [" << player.GetBodyDirDelay() << ", "
       << player.GetBodyDirConf() << "]" << '#' << "neck ["
       << player.GetNeckDirDelay() << ", " << player.GetNeckDirConf() << "]";
    AddPoint(player.GetPos(), ss.str().c_str(), White);

    DecUnLock();
  }
}

void SightLogger::LogBallInfo(const BallState &ball) {
  if (PlayerParam::instance().SaveDecLog()) {
    DecLock();
    LogDec();

    std::stringstream ss;
    ss << "pos [" << ball.GetPosDelay() << ", " << ball.GetPosConf() << "]"
       << '#' << "vel [" << ball.GetVelDelay() << ", " << ball.GetVelConf()
       << "]" << '#';
    AddPoint(ball.GetPos(), ss.str().c_str(), White);

    DecUnLock();
  }
}

/**
 * TextLogger's constructor
 * The name of the log file will be "team_name-unum-log_name.log".
 * \param observer for getting player's unum
 * \param log_name
 */
TextLogger::TextLogger(Observer *observer, const char *log_name) {
  char file_name[256];

  Assert(std::string(log_name) != std::string("msg"));
  Assert(std::string(log_name) != std::string("sight"));

  sprintf(file_name, "Logfiles/%s-%d-%s.log",
          PlayerParam::instance().teamName().c_str(), observer->SelfUnum(),
          log_name);
  os.open(file_name);
  if (!os.good()) {
    PRINT_ERROR("open log file error");
  }
}

/**
 * TextLogger's constructor
 * Construct a null logger.
 */
TextLogger::TextLogger() {}

/**
 * TextLogger's destructor
 */
TextLogger::~TextLogger() {
  os.flush();
  os.close();
}

/**
 * Flush log to file
 */
void TextLogger::Flush() {
  if (PlayerParam::instance().SaveTextLog()) {
    os << mBuffer.str();
    os.flush();
  }
  mBuffer.str("");
}

/**
 * Operator <<
 * Usage is the same as ostream.
 */
// template<typename T>
// TextLogger& operator<<(TextLogger& logger, const T &value)
//{
//	if (PlayerParam::instance().SaveTextLog())
//	{
//		logger.mBuffer << value;
//	}
//	return logger;
// }

/**
 * Return an static instance of Logger
 * Usage of Logger should be Logger::instance().blablabla
 */
Logger &Logger::instance() {
  static Logger logger;
  return logger;
}

/**
 * Logger's real constructor
 * \param observer
 * \param world_state
 */
void Logger::Initial(Observer *observer, WorldState *world_state) {
  mpObserver = observer;
  mpWorldState = world_state;
}

/**
 * Logger's destructor
 */
Logger::~Logger() {
  delete mpSightLogger;
  for (std::map<std::string, TextLogger *>::iterator i = mTextLoggers.begin();
       i != mTextLoggers.end(); ++i) {
    delete i->second;
  }
}

TextLogger Logger::mTextLoggerNull;

/**
 * Logger's main loop
 */
void Logger::StartRoutine() {
  while (!mCondFlush.Wait(PlayerParam::instance().WaitTimeOut() * 1000)) {
    Flush();
  }
  Flush();
}

/**
 * Get the sight logger. If it does not exsit, construct one.
 * This method MUST be called AFTER the player's unum has been known.
 * \return a pointer to sight logger.
 */
SightLogger *Logger::GetSightLogger() {
  if (!mpSightLogger) {
    mpSightLogger = new SightLogger(mpObserver, mpWorldState);
  }
  return mpSightLogger;
}

/**
 * Get a text logger named log_name. If it does not exsit, create one.
 * You may use this method as:
 * Logger::instance().GetTextLogger("log_name")<<"log_text"; \param log_name
 * name of the text logger, which the log file will be named after. \return the
 * logger.
 */
TextLogger &Logger::GetTextLogger(const char *log_name) {
  if (PlayerParam::instance().SaveTextLog()) {
    std::map<std::string, TextLogger *>::iterator logger =
        mTextLoggers.find(log_name);
    if (logger == mTextLoggers.end()) {
      logger = mTextLoggers
                   .insert(std::make_pair(log_name,
                                          new TextLogger(mpObserver, log_name)))
                   .first;
    }
    return *(logger->second);
  } else {
    return mTextLoggerNull;
  }
}

/**
 * flush logs
 */
void Logger::Flush() {
  if (mpSightLogger) {
    mpSightLogger->Flush();
  }

  for (std::map<std::string, TextLogger *>::iterator i = mTextLoggers.begin();
       i != mTextLoggers.end(); ++i) {
    i->second->Flush();
  }
}

/**
 * set mCondFlush to let LoggerLoop flush logs.
 */
void Logger::SetFlushCond() {
  if (PlayerParam::instance().SaveSightLog() ||
      PlayerParam::instance().SaveDecLog() ||
      PlayerParam::instance().SaveTextLog())
    mCondFlush.Set();
}

/**
 * Initalize the sight logger
 * Should be called several times by parser.
 * \param msg_type type of the msg
 * \param msg
 */
void Logger::InitSightLogger(ServerMsgType msg_type, const char *msg) {
  if (PlayerParam::instance().SaveSightLog()) {
    switch (msg_type) {
    case ServerParam_Msg:
      GetSightLogger()->SetServerParamMsg(msg);
      break;
    case PlayerParam_Msg:
      GetSightLogger()->SetPlayerParamMsg(msg);
      break;
    case PlayerType_Msg:
      GetSightLogger()->SetPlayerTypeMsg(msg);
      break;
    default:
      break;
    }
  }
}

/**
 * Log the player's sight state
 */
void Logger::LogSight() {
  if (PlayerParam::instance().SaveSightLog()) {
    GetSightLogger()->LogSight();
  }
}

void Logger::LogPoint(const Vector &target, SightLogger::Color color,
                      const char *comment) {
  if (PlayerParam::instance().SaveDecLog()) {
    SightLogger *pSightLogger = GetSightLogger();
    pSightLogger->DecLock();
    pSightLogger->LogDec();
    pSightLogger->AddPoint(target, comment, color);
    pSightLogger->DecUnLock();
  }
}

void Logger::LogGoToPoint(const Vector &start, const Vector &target,
                          const char *comment) {
  if (PlayerParam::instance().SaveDecLog()) {
    SightLogger *pSightLogger = GetSightLogger();
    pSightLogger->DecLock();
    pSightLogger->LogDec();
    pSightLogger->AddPoint(target, comment, SightLogger::Red);
    pSightLogger->AddCircle(target, 0.2, SightLogger::Red);
    pSightLogger->AddLine(start, target, SightLogger::Red);
    pSightLogger->DecUnLock();
  }
}

void Logger::LogShoot(const Vector &start, const Vector &target,
                      const char *comment) {
  if (PlayerParam::instance().SaveDecLog()) {
    SightLogger *pSightLogger = GetSightLogger();
    pSightLogger->DecLock();
    pSightLogger->LogDec();
    pSightLogger->AddPoint(target, comment, SightLogger::Purple);
    pSightLogger->AddLine(start, target, SightLogger::Purple);
    pSightLogger->DecUnLock();
  }
}

void Logger::LogIntercept(const Vector &interpt, const char *comment) {
  if (PlayerParam::instance().SaveDecLog()) {
    SightLogger *pSightLogger = GetSightLogger();
    pSightLogger->DecLock();
    pSightLogger->LogDec();
    pSightLogger->AddPoint(interpt, comment, SightLogger::Cyan);
    pSightLogger->AddCircle(interpt, 0.1, SightLogger::Cyan);
    pSightLogger->DecUnLock();
  }
}

void Logger::LogLine(const Vector &begin, const Vector &end,
                     SightLogger::Color color, const char *comment) {
  if (PlayerParam::instance().SaveDecLog()) {
    SightLogger *pSightLogger = GetSightLogger();
    pSightLogger->DecLock();
    pSightLogger->LogDec();
    pSightLogger->AddPoint(end, comment, color);
    pSightLogger->AddLine(begin, end, color);
    pSightLogger->DecUnLock();
  }
}

void Logger::LogCircle(const Vector &o, const double &r,
                       SightLogger::Color color) {
  if (PlayerParam::instance().SaveDecLog()) {
    SightLogger *pSightLogger = GetSightLogger();
    pSightLogger->DecLock();
    pSightLogger->LogDec();
    pSightLogger->AddCircle(o, r, color);
    pSightLogger->DecUnLock();
  }
}

void Logger::LogRectangular(const Rectangular &rect, SightLogger::Color color) {
  if (PlayerParam::instance().SaveDecLog()) {
    SightLogger *pSightLogger = GetSightLogger();
    pSightLogger->DecLock();
    pSightLogger->LogDec();

    pSightLogger->AddLine(rect.TopLeftCorner(), rect.TopRightCorner(), color);
    pSightLogger->AddLine(rect.TopLeftCorner(), rect.BottomLeftCorner(), color);
    pSightLogger->AddLine(rect.BottomLeftCorner(), rect.BottomRightCorner(),
                          color);
    pSightLogger->AddLine(rect.BottomRightCorner(), rect.TopRightCorner(),
                          color);

    pSightLogger->DecUnLock();
  }
}

void Logger::LogDribble(const Vector &start, const Vector &target,
                        const char *comment, bool is_execute) {
  if (PlayerParam::instance().SaveDecLog()) {
    SightLogger *pSightLogger = GetSightLogger();
    pSightLogger->DecLock();
    pSightLogger->LogDec();

    pSightLogger->AddPoint(target, comment, SightLogger::Blue);
    if (is_execute) {
      pSightLogger->AddLine(start, target, SightLogger::Blue);
    }

    pSightLogger->DecUnLock();
  }
}

void Logger::LogPass(const bool reverse, const Vector &start,
                     const Vector &target, const char *comment,
                     bool is_execute) {
  if (PlayerParam::instance().SaveDecLog()) {
    SightLogger *pSightLogger = GetSightLogger();
    pSightLogger->DecLock();
    pSightLogger->LogDec();

    pSightLogger->AddPoint(reverse ? target.Rotate(180.0) : target, comment,
                           SightLogger::Red);
    if (is_execute) {
      pSightLogger->AddLine(reverse ? start.Rotate(180.0) : start,
                            reverse ? target.Rotate(180.0) : target,
                            SightLogger::Red);
    }

    pSightLogger->DecUnLock();
  }
}

const Time &Logger::CurrentTime() { return mpWorldState->CurrentTime(); }


text:
#ifndef _VIDEO_PROCESSOR_SERVICE_H_
#define _VIDEO_PROCESSOR_SERVICE_H_

struct __declspec(uuid("1528A4D4-1DA1-4228-B7BE-E13A6ED18970")) IVideoProcessor;
struct __declspec(uuid("F8754C9E-0965-49db-ADE6-16D5AFFC34CA")) IVideoProcessorEffect;
struct __declspec(uuid("2AEB3B70-CBBA-4372-B319-D55ADD4F7CE1")) IVideoProcessorTrimensionAll2HD;
struct __declspec(uuid("61C75C2D-E08D-44e2-98B8-80CC6D88D9D2")) IVideoProcessorEventListener;

#ifndef MAKEFOURCC
#define MAKEFOURCC(ch0, ch1, ch2, ch3) ((DWORD)(BYTE)(ch0) | ((DWORD)(BYTE)(ch1) << 8) | ((DWORD)(BYTE)(ch2) << 16) | ((DWORD)(BYTE)(ch3) << 24 ))
#endif	// MAKEFOURCC

namespace VideoProcessor
{
	enum EVENT_VIDEOPROCESSOR
	{
		EVENT_VIDEOPROCESSORBLT_RENDERTARGET_READY,
		EVENT_VIDEOPROCESSORBLT_ERROR
	};

	enum VIDEO_FORMAT
	{
		VIDEO_FORMAT_UNKNOW = 0,
		VIDEO_FORMAT_8BPP,
		VIDEO_FORMAT_RGB555,
		VIDEO_FORMAT_RGB565,
		VIDEO_FORMAT_RGB888,
		VIDEO_FORMAT_RGB32,
		VIDEO_FORMAT_PRIVATE_IYUV, //< Y U V, I420 or YUV420
		VIDEO_FORMAT_PRIVATE_YV12, //< Y V U
		VIDEO_FORMAT_PRIVATE_NV12, //< Y UV
		VIDEO_FORMAT_PRIVATE_SUBPICTURE,
		VIDEO_FORMAT_ARGB = MAKEFOURCC('A', 'R', 'G', 'B'),	//< 32 bit, A8R8G8B8
		VIDEO_FORMAT_AYUV = MAKEFOURCC('A', 'Y', 'U', 'V'),	//< 32 bit, A8Y8U8V8
		VIDEO_FORMAT_AV12 = MAKEFOURCC('A', 'V', '1', '2'),	//< 20 bit, NV12 4:2:0 + A8, or ANV12
		VIDEO_FORMAT_NV12 = MAKEFOURCC('N', 'V', '1', '2'),	//< 12 bit, 4:2:0
		VIDEO_FORMAT_NV24 = MAKEFOURCC('N', 'V', '2', '4'),	//< 12 bit, 4:2:0
		VIDEO_FORMAT_IMC3 = MAKEFOURCC('I', 'M', 'C', '3'),	//< 12 bit, 4:2:0
		VIDEO_FORMAT_YV12 = MAKEFOURCC('Y', 'V', '1', '2'),	//< 12 bit, 4:2:0
		VIDEO_FORMAT_YUY2 = MAKEFOURCC('Y', 'U', 'Y', '2'),	//< 16 bit, YUV 4:2:2
		VIDEO_FORMAT_AIP8 = MAKEFOURCC('A', 'I', 'P', '8'),	//< 8 bit, I8 indexed
		VIDEO_FORMAT_PPA8 = MAKEFOURCC('P', 'P', 'A', '8')	//< 16 bit, A8I8 indexed
	};

	enum FRAME_STRUCTURE
	{
		FRAME_STRUCTURE_PROGRESSIVE				= 0,
		FRAME_STRUCTURE_INTERLACED_EVEN_FIRST	= 0x1,
		FRAME_STRUCTURE_INTERLACED_ODD_FIRST	= 0x2,
		FRAME_STRUCTURE_REPEAT_FIRST_FIELD		= 0x4
	};

	// 0: Auto, 1: Force interlaced, 2: Force progressive.
	enum PROCESS_MODE
	{
		PROCESS_MODE_AUTO,
		PROCESS_MODE_FORCE_DEINTERLACING,
		PROCESS_MODE_FORCE_PROGRESSIVE
	};

	enum NOISEFILTER_TECH
	{
		NOISEFILTER_TECH_UNSUPPORTED	= 0,
		NOISEFILTER_TECH_Unknown		= 0x01,
		NOISEFILTER_TECH_Median			= 0x02,
		NOISEFILTER_TECH_Temporal		= 0x04,
		NOISEFILTER_TECH_BlockNoise		= 0x08,
		NOISEFILTER_TECH_MosquitoNoise	= 0x10,
		NOISEFILTER_TECH_Mask			= 0x1f
	};

	enum DEINTERLACE_TECH
	{
		DEINTERLACE_TECH_UNKNOW					= 0,
		DEINTERLACE_TECH_BOBLineReplicate		= 0x001,
		DEINTERLACE_TECH_BOBVerticalStretch		= 0x002,
		DEINTERLACE_TECH_BOBVerticalStretch4Tap	= 0x004,
		DEINTERLACE_TECH_MedianFiltering		= 0x008,
		DEINTERLACE_TECH_EdgeFiltering			= 0x010,
		DEINTERLACE_TECH_FieldAdaptive			= 0x020,
		DEINTERLACE_TECH_PixelAdaptive			= 0x040,
		DEINTERLACE_TECH_MotionVectorSteered	= 0x080,
		DEINTERLACE_TECH_InverseTelecine		= 0x100,
		DEINTERLACE_TECH_MASK					= 0x1ff
	};

	enum DETAILFILTER_TECH
	{
		DETAILFILTER_TECH_UNSUPPORTED	= 0,
		DETAILFILTER_TECH_Unknown		= 0x1,
		DETAILFILTER_TECH_Edge			= 0x2,
		DETAILFILTER_TECH_Sharpening	= 0x4,
		DETAILFILTER_TECH_Mask			= 0x7
	};

	enum VIDEO_FILTER
	{
		NoiseFilterLumaLevel		= 0,
		NoiseFilterLumaThreshold,
		NoiseFilterLumaRadius,
		NoiseFilterChromaLevel,
		NoiseFilterChromaThreshold,
		NoiseFilterChromaRadius,
		DetailFilterLumaLevel,
		DetailFilterLumaThreshold,
		DetailFilterLumaRadius,
		DetailFilterChromaLevel,
		DetailFilterChromaThreshold,
		DetailFilterChromaRadius
	};

	enum PROCAMP_CONTROL
	{
		PROCAMP_CONTROL_BRIGHTNESS	= 0x001,
		PROCAMP_CONTROL_CONTRAST	= 0x002,
		PROCAMP_CONTROL_SATURATION	= 0x004,
		PROCAMP_CONTROL_HUE			= 0x008,
		PROCAMP_CONTROL_GAMMA		= 0x010,
		PROCAMP_CONTROL_CGAMMA		= 0x020,
		PROCAMP_CONTROL_SHARPNESS	= 0x040,
		PROCAMP_CONTROL_UOFFSET		= 0x080,
		PROCAMP_CONTROL_VOFFSET		= 0x100
	};

	enum VIDEOEFFECT_TECH
	{
		VIDEOEFFECT_TECH_UNSUPPORTED		= 0,
		VIDEOEFFECT_TECH_VIDEOENHANCEMENT	= 0x1, // video effect dmo and video smart stretch dmo.
		VIDEOEFFECT_TECH_TRIMENSIONAll2HD	= 0x2  // trimension All2HD.
	};

	typedef LONGLONG VIDEO_TIME;

	struct VideoProcessorCaps
	{
		VIDEO_FORMAT	dwSrcFormat;
		VIDEO_FORMAT	dwRenderTargetFormat;
		DWORD			dwDeinterlaceTechnology;
		DWORD			dwProcAmpControlCaps;
		DWORD			dwNoiseFilterTechnology;
		DWORD			dwDetailFilterTechnology;
		DWORD			dwVideoEffectOperations;
		DWORD			uReserved[6];
	};

	struct VideoProcessorModes
	{
		DWORD	dwDeinterlaceTechnology;
		DWORD	dwNoiseFilterTechnology;
		DWORD	dwDetailFilterTechnology;
		DWORD	dwVideoEffectOperations;	// video effect.

		DWORD	dwReserved[11];
	};

	struct VideoBuffer
	{
		VIDEO_FORMAT VideoFormat;
		union
		{
			struct
			{
				UCHAR	*pVideoPlane[3];	// pointers to Y,U,V planes
				INT		iStride[3];			// input buffer stride
				INT		iWidth[3];			// decoded width
				INT		iHeight[3];			// decoded height
			} Video;

			struct
			{
				DWORD	dwFlags;			// status flags
				UCHAR	*pPixel;			// pixel array returned by GetSpic (short for YUY2, 16bpp, char for RGB 8bpp, 24bpp)
				UCHAR	*pAlpha;			// alpha array returned by GetSpic
				ULONG	*pPalette;			// yuv palette used (16 entries) -- useful for 8bpp.
			} Subtitle;
		};
	};

	struct VideoSample
	{
		DWORD				dwFrameStucture;
		VIDEO_TIME			vtStartTime;		// frame pts
		VIDEO_TIME			vtEndTime;			// frame pte
		VideoBuffer			Surface;
		RECT				rcDisplayRect;

		UINT				uReserved[16];
	};

	struct ProcAmpValueRange
	{
		INT iMinValue;			// Minimum supported value.
		INT iMaxValue;			// Maximum supported value.
		INT iDefaultValue;		// Default value.
		INT iStepSize;			// Minimum increment between values.
	};

	struct FilterValueRange
	{
		FLOAT fMinValue;		// Minimum supported value.
		FLOAT fMaxValue;		// Maximum supported value.
		FLOAT fDefaultValue;	// Default value.
		FLOAT fStepSize;		// Minimum increment between values.
	};

	struct ProcAmpValues
	{
		INT		iHue;
		INT		iSaturation;
		INT		iBrightness;
		INT		iContrast;
		INT		iSharpness;
		INT		iGamma;
		INT		iCGamma;
		INT		iUOffset;
		INT		iVOffset;
		UINT	uReserved[16];
	};

	struct FilterValues
	{
		INT iLevel;
		INT iThreshold;
		INT iRadius;
	};

	struct VideoProcessBltParams
	{
		PROCESS_MODE	ProcessMode;
		VIDEO_TIME		vtTargetFrame;
		ProcAmpValues	sProcAmpValues;
		FilterValues	sNoiseFilterLuma;
		FilterValues	sNoiseFilterChroma;
		FilterValues	sDetailFilterLuma;
		FilterValues	sDetailFilterChroma;
		UINT			uReserved[16];
	};
}

// A callback interface for those who want to be notified.
interface IVideoProcessorEventListener : public IUnknown
{
	STDMETHOD(Notify)(DWORD dwEvent, DWORD dwParam1, DWORD dwParam2) = 0;
};

interface IVideoProcessor : public IUnknown
{
	STDMETHOD(QueryVideoProcessorCaps) (
		/* [out] */
		VideoProcessor::VideoProcessorCaps **ppCaps) = 0;

	STDMETHOD(GetFilterPropertyRange) (
		/* [in] */
		VideoProcessor::VIDEO_FILTER VideoFilter,
		/* [out] */
		VideoProcessor::FilterValueRange* pFilterRange) = 0;

	STDMETHOD(GetProcAmpRange) (
		/* [in] */
		VideoProcessor::PROCAMP_CONTROL ProcAmpControl,
		/* [out] */
		VideoProcessor::ProcAmpValueRange* pProcAmpRange) = 0;

	STDMETHOD(SetVideoProcessorMode) (
		/* [in] */
		const VideoProcessor::VideoProcessorModes *pVPMode) = 0;

	STDMETHOD(GetVideoProcessorMode) (
		/* [out] */
		VideoProcessor::VideoProcessorModes *pVPMode) = 0;

	STDMETHOD(GetNumReferentSamples) (
		/* [out] */
		DWORD	*pNumBackwardRefSamples,
		/* [out] */
		DWORD	*pNumForwardRefSamples) = 0;

	STDMETHOD(VideoProcessBlt) (
		/* [in] */
		VideoProcessor::VideoBuffer *pRenderTarget,
		/* [in] */
		const VideoProcessor::VideoProcessBltParams *pBltParams,
		/* [size_is][in] */
		const VideoProcessor::VideoSample *pVideoSamples,
		/* [in] */
		UINT uNumSamples) = 0;
};

#ifdef VIDEOPROCESSOR_EXPORTS
#define VIDEOPROCESSOR_API __declspec(dllexport)
#else
#define VIDEOPROCESSOR_API __declspec(dllimport)
#endif

extern "C" VIDEOPROCESSOR_API int CreateVideoProcessor(
	/*[in]*/	VideoProcessor::VIDEO_FORMAT InputVideoFormat,
	/*[in]*/	VideoProcessor::VIDEO_FORMAT RenderTargetFormat,
	/*[in]*/	IVideoProcessorEventListener *pEvenListener,
	/*[out]*/	void** ppVideoProcessor
	);

#endif


text:
package org.cryptoworkshop.ximix.common.util;

/**
 * General interface for the generation of streams of index numbers.
 */
public interface IndexNumberGenerator
{
    /**
     * Return true if there is another index number available
     *
     * @return true if another index number, false otherwise.
     */
    boolean hasNext();

    /**
     * Return the next index number
     *
     * @return an index number.
     */
    int nextIndex();
}


text:
/* Empty. Add your own CSS if you like */

.center-content {
    top: 50%;
    -webkit-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    -o-transform: translateY(-50%);
    transform: translateY(-50%);
    position: absolute !important;
    margin:0 auto;
    width:100%;
}

::first-letter {
  text-transform: capitalize;
}

/**
 * This CSS uses adjacent selectors instead of general sibling (~) selectors
 * for ion radio that are broken in iOS 9 UIWebView.
 *
 * To apply the patch, include this CSS after your ionic.css include.
 */
  .item-radio input:checked + .radio-content .item-content {
    /* style the item content when its checked */
    background: #f7f7f7;

  }

  .item-radio input:checked + .radio-content .radio-icon {
    /* show the checkmark icon when its checked */
    visibility: visible;

  }

  /**
  Histogram Stuff!
  */

.graph-bar rect {
  fill: steelblue;
  shape-rendering: crispEdges;
}
.graph-bar rect:hover{
  fill: rgba(0,0,0,.8);
}
.axis path, .axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}
.arc text {
  font: 10px sans-serif;
  text-anchor: middle;
}

.arc path {
  stroke: #fff;
}


text:
package org.blitzem.provider.api;

import static org.jclouds.compute.options.TemplateOptions.Builder.authorizePublicKey;

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

import org.blitzem.commands.CommandException;
import org.blitzem.model.LoadBalancer;
import org.blitzem.model.Node;
import org.blitzem.model.Provisioning;
import org.jclouds.compute.ComputeService;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.ComputeServiceContextFactory;
import org.jclouds.compute.RunNodesException;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.loadbalancer.LoadBalancerService;
import org.jclouds.loadbalancer.LoadBalancerServiceContext;
import org.jclouds.loadbalancer.LoadBalancerServiceContextFactory;
import org.jclouds.loadbalancer.domain.LoadBalancerMetadata;
import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
import org.jclouds.scriptbuilder.domain.Statement;
import org.jclouds.scriptbuilder.domain.StatementList;
import org.jclouds.ssh.jsch.config.JschSshClientModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Charsets;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.io.Files;
import com.google.inject.Module;

/**
 * @author Richard North <rich.north@gmail.com>
 *
 */
public class GenericDriver implements Driver {

	private static final Logger CONSOLE_LOG = LoggerFactory.getLogger(GenericDriver.class);
	protected ComputeService computeService;
	protected LoadBalancerService loadBalancerService;

	public GenericDriver(String cloudComputeAccessKeyId, String cloudComputeSecretKey, String cloudLBAccessKeyId, String cloudLBSecretKey, String cloudComputeProvider, String cloudLBProvider, File cloudConfigFile) {

		ComputeServiceContext computeServiceContext = null;
		if (cloudComputeProvider == null || cloudComputeAccessKeyId == null || cloudComputeSecretKey == null) {
			CONSOLE_LOG.warn("Did not find expected compute-provider, compute-accesskeyid or compute-secretkey defined in " + cloudConfigFile);
			CONSOLE_LOG.warn("No Cloud Compute nodes will be managed!");

		} else {
			computeServiceContext = new ComputeServiceContextFactory().createContext(cloudComputeProvider, cloudComputeAccessKeyId, cloudComputeSecretKey,
					ImmutableSet.<Module> of(new JschSshClientModule(), new SLF4JLoggingModule()));
		}
		this.computeService = computeServiceContext!=null ? computeServiceContext.getComputeService() : null;

		LoadBalancerServiceContext loadBalancerServiceContext = null;
		if (cloudLBProvider == null || cloudLBAccessKeyId == null || cloudLBSecretKey == null) {
			CONSOLE_LOG.warn("Did not find expected loadbalancer-provider, loadbalancer-accesskeyid or loadbalancer-secretkey defined in " + cloudConfigFile);
			CONSOLE_LOG.warn("No Cloud Load Balancers will be managed!");

		} else {
			loadBalancerServiceContext = new LoadBalancerServiceContextFactory().createContext(cloudLBProvider, cloudLBAccessKeyId, cloudLBSecretKey,
					ImmutableSet.<Module> of(new JschSshClientModule(), new SLF4JLoggingModule()));
		}
		this.loadBalancerService = loadBalancerServiceContext!=null ? loadBalancerServiceContext.getLoadBalancerService() : null;
	}

	/**
	 * {@inheritDoc}
	 */
	public void removeNodeFromLoadBalancer(Node node, LoadBalancer loadBalancer) {
		CONSOLE_LOG.warn("removeNodeFromLoadBalancer requested but not supported by GenericDriver (may not be supported by the cloud provider API)");
	}

	/**
	 * {@inheritDoc}
	 * @throws CommandException
	 */
	public void nodeUp(Node node) throws CommandException {

        final TemplateBuilder templateBuilder = computeService
				.templateBuilder();

		TemplateOptions options = new TemplateOptions();
		File sshKeyFile = null;
		try {
			sshKeyFile = new File(System.getProperty("user.home") + "/.ssh/id_rsa.pub");
			options  = authorizePublicKey(Files.toString(sshKeyFile, Charsets.UTF_8));
		} catch (IOException e) {
			CONSOLE_LOG.error("Could not load public SSH key from file: {}. Please create an SSH public/private key pair (with `ssh-keygen -t rsa`) and try again.", sshKeyFile.getAbsoluteFile());
			throw new RuntimeException(e);
		}

		List<Statement> statements = Lists.newArrayList();
		for (Provisioning provisioning : node.getProvisioning()) {
			statements.add(provisioning.asStatement());
		}
		options.runScript(new StatementList(statements));

		templateBuilder
			.minRam(node.getSize().getMinRam())
			.minCores(node.getSize().getMinCores())
			.osFamily(OsFamily.valueOf(node.getOs().getFamily()))
			.osVersionMatches(node.getOs().getVersion())
			.os64Bit(node.getOs().getOs64Bit())
			.options(options);

		Template template = templateBuilder.build();
		CONSOLE_LOG.info("Creating node with template: {}", template);
		try {
			Set<? extends NodeMetadata> nodesInGroup = computeService.createNodesInGroup(node.getName(), 1, template);
			for (NodeMetadata createdNode : nodesInGroup) {
				String loginUsername = createdNode.getCredentials().getUser();
				CONSOLE_LOG.info("SUCCESS - Created node {} at {}. Standard login username is "+ loginUsername, node.getName(), createdNode.getPublicAddresses());
			}

		} catch (RunNodesException e) {
			throw new CommandException("Could not create node!", e);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public void nodeDown(Node node) {

        Set<? extends NodeMetadata> existingNodes = this.getNodeMetadataForNodesMatching(node);

		for (NodeMetadata existingNode : existingNodes) {
			CONSOLE_LOG.info("Bringing down node {}", existingNode.getName());
			computeService.destroyNode(existingNode.getId());
			CONSOLE_LOG.info("SUCCESS - Node destroyed");
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public void loadBalancerDown(LoadBalancer loadBalancer) {

		Set<? extends LoadBalancerMetadata> existingLBs = this.getLoadMetadataForLoadBalancersMatching(loadBalancer);

		for (LoadBalancerMetadata existingLB : existingLBs) {
			CONSOLE_LOG.info("Bringing down load balancer {}", existingLB.getName());
			loadBalancerService.destroyLoadBalancer(existingLB.getId());
			CONSOLE_LOG.info("SUCCESS - Load balancer destroyed");
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public Set<? extends NodeMetadata> getNodeMetadataForNodesMatching(final Node node) {

		return computeService.listNodesDetailsMatching(new Predicate<ComputeMetadata>() {

            public boolean apply(ComputeMetadata arg0) {

            	final NodeState state = computeService.getNodeMetadata(arg0.getId()).getState();
				boolean isUp = (state == NodeState.RUNNING) || (state == NodeState.PENDING);
            	String name = arg0.getName();
            	if (name==null) {
            		name = computeService.getNodeMetadata(arg0.getId()).getGroup();
            	}

                if (name.contains("-")) {
                    String trimmedName = name.substring(0, name.lastIndexOf('-'));
                    return trimmedName.equals(node.getName()) && isUp;
                } else {
                    return name.equals(node.getName()) && isUp;
                }

            }

        });
	}

	/**
	 * {@inheritDoc}
	 */
	public Set<? extends LoadBalancerMetadata> getLoadMetadataForLoadBalancersMatching(LoadBalancer loadBalancer) {

		if (loadBalancerService==null) {
			CONSOLE_LOG.warn("Load balancer services have not been configured - cannot list available load balancers");
			return Sets.newHashSet();
		}

		Set<? extends LoadBalancerMetadata> loadBalancers = loadBalancerService.listLoadBalancers();
		Set<LoadBalancerMetadata> matchingLoadBalancers = Sets.newHashSet();

		for (LoadBalancerMetadata lbInstance : loadBalancers) {
			final String name = lbInstance.getName();
			if (name.equals(loadBalancer.getName())) {
				matchingLoadBalancers.add(lbInstance);
			}
		}

		return matchingLoadBalancers;
	}

	/**
	 * {@inheritDoc}
	 */
	public void addNodeToLoadBalancer(Node node, LoadBalancer loadBalancer) {
		CONSOLE_LOG.warn("removeNodeFromLoadBalancer requested but not supported by GenericDriver (may not be supported by the cloud provider API)");

	}

	/**
	 * {@inheritDoc}
	 */
	public boolean isUp(LoadBalancer loadBalancer) {
		return ! this.getLoadMetadataForLoadBalancersMatching(loadBalancer).isEmpty();

	}

	/**
	 * {@inheritDoc}
	 */
	public boolean isUp(Node node) {
		return ! this.getNodeMetadataForNodesMatching(node).isEmpty();
	}

	/**
	 * {@inheritDoc}
	 */
	public void loadBalancerUp(LoadBalancer loadBalancer, Iterable<Node> associatedNodes) {

        Set<NodeMetadata> associatedNodeMetadata = Sets.newHashSet();
		for (Node node : associatedNodes) {
			associatedNodeMetadata.addAll(this.getNodeMetadataForNodesMatching(node));
        }

        loadBalancerService.createLoadBalancerInLocation(
                null,
                loadBalancer.getName(),
                loadBalancer.getProtocol(),
                loadBalancer.getPort(),
                loadBalancer.getNodePort(),
                associatedNodeMetadata);
	}

	/**
	 * @param node
	 * @return
	 */
	protected Set<String> getPublicIPAddressesForNode(Node node) {
		Set<? extends NodeMetadata> nodeMetadatas = this.getNodeMetadataForNodesMatching(node);
		Set<String> publicAddresses = Sets.newHashSet();

		for (NodeMetadata nodeMetadata : nodeMetadatas) {
			publicAddresses.addAll(nodeMetadata.getPublicAddresses());
		}
		return publicAddresses;
	}

	/**
	 * @param node
	 * @return
	 */
	protected Set<String> getPrivateIPAddressesForNode(Node node) {
		Set<? extends NodeMetadata> nodeMetadatas = this.getNodeMetadataForNodesMatching(node);
		Set<String> privateAddresses = Sets.newHashSet();

		for (NodeMetadata nodeMetadata : nodeMetadatas) {
			privateAddresses.addAll(nodeMetadata.getPrivateAddresses());
		}
		return privateAddresses;
	}

	/**
	 * {@inheritDoc}
	 */
	public void close() {
		if (null!=computeService && null!=computeService.getContext()) {
			computeService.getContext().close();
		}
		if (null!=loadBalancerService && null!=loadBalancerService.getContext()) {
			loadBalancerService.getContext().close();
		}
	}
}


text:
package io.craft.atom.lock.api;

import io.craft.atom.lock.Redis24DLock;
import io.craft.atom.lock.Redis26DLock;
import io.craft.atom.lock.ShardedRedis24DLock;
import io.craft.atom.lock.ShardedRedis26DLock;
import io.craft.atom.redis.api.RedisCommand;
import io.craft.atom.redis.api.ShardedRedisCommand;

/**
 * Distributed lock factory
 *
 * @author mindwind
 * @version 1.0, Jul 16, 2013
 */
public class DLockFactory {

	/**
	 * @param redis
	 * @return new distributed lock base on singleton redis version 2.4.x
	 */
	public static DLock newRedis24DLock(RedisCommand redis) {
		return new Redis24DLock(redis);
	}

	/**
	 * @param redis
	 * @return new distributed lock base on sharded redis version 2.4.x
	 */
	public static DLock newRedis24DLock(ShardedRedisCommand redis) {
		return new ShardedRedis24DLock(redis);
	}

	/**
	 * @param redis
	 * @return new distributed lock base on singleton redis version 2.6.12+
	 */
	public static DLock newRedis26DLock(RedisCommand redis) {
		return new Redis26DLock(redis);
	}

	/**
	 * @param redis
	 * @return new distributed lock base on sharded redis version 2.6.x
	 */
	public static DLock newRedis26DLock(ShardedRedisCommand redis) {
		return new ShardedRedis26DLock(redis);
	}

	/**
	 * @deprecated replace by {@link #newRedis24DLock(ShardedRedisCommand)}
	 * @param redis
	 * @return new distributed lock base on sharded redis version 2.4.x
	 */
	public static DLock newShardedRedis24DLock(ShardedRedisCommand redis) {
		return new ShardedRedis24DLock(redis);
	}

	/**
	 * @deprecated replace by {@link #newRedis26DLock(ShardedRedisCommand)}
	 * @param redis
	 * @return new distributed lock base on sharded redis version 2.6.12+
	 */
	public static DLock newShardedRedis26DLock(ShardedRedisCommand redis) {
		return new ShardedRedis26DLock(redis);
	}

}


text:
import logging
from typing import Any, List

from absl import flags
from injector import Binder, Module, inject, singleton

from rep0st.framework import app
from rep0st.framework.scheduler import Scheduler, SchedulerModule
from rep0st.service.feature_service import FeatureService, FeatureServiceModule
from rep0st.db.post import Type as PostType

log = logging.getLogger(__name__)
FLAGS = flags.FLAGS
flags.DEFINE_string(
    'rep0st_update_features_job_schedule', '* * * * * *',
    'Schedule in crontab format for running the feature update job.')
flags.DEFINE_enum_class(
    'rep0st_update_features_post_type', PostType.IMAGE, PostType,
    'The post type (image, video, ...) this job should index.')

class UpdateFeaturesJobModule(Module):

  def configure(self, binder: Binder):
    binder.install(FeatureServiceModule)
    binder.install(SchedulerModule)
    binder.bind(UpdateFeaturesJob)

@singleton
class UpdateFeaturesJob:
  feature_service: FeatureService

  @inject
  def __init__(self, feature_service: FeatureService, scheduler: Scheduler):
    self.feature_service = feature_service
    scheduler.schedule(FLAGS.rep0st_update_features_job_schedule,
                       self.update_feature_job)

  def update_feature_job(self):
    self.feature_service.update_features(FLAGS.rep0st_update_features_post_type)

def modules() -> List[Any]:
  return [UpdateFeaturesJobModule]

if __name__ == "__main__":
  app.run(modules)


text:
<!DOCTYPE html>

    <title>GanttChartView Custom Scale Sample</title>
    <link rel="Stylesheet" href="app.css" type="text/css" />

...