text:
package thrift_interface

import (
	"fmt"
	"git.apache.org/thrift.git/lib/go/thrift"
	"math"
)

// (needed to ensure safety because of naive import list construction.)
var _ = math.MinInt32
var _ = thrift.ZERO
var _ = fmt.Printf

type CityWeatherInfoService interface {
	CommonService

	// Parameters:
	//  - CommonRequest
	//  - CityInfo
	GetCityWeatherInfo(commonRequest *CommonRequest, cityInfo *CityWeatherInfoRequest) (r string, err error)
}

type CityWeatherInfoServiceClient struct {
	*CommonServiceClient
}

func NewCityWeatherInfoServiceClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *CityWeatherInfoServiceClient {
	return &CityWeatherInfoServiceClient{CommonServiceClient: NewCommonServiceClientFactory(t, f)}
}

func NewCityWeatherInfoServiceClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *CityWeatherInfoServiceClient {
	return &CityWeatherInfoServiceClient{CommonServiceClient: NewCommonServiceClientProtocol(t, iprot, oprot)}
}

// Parameters:
//  - CommonRequest
//  - CityInfo
func (p *CityWeatherInfoServiceClient) GetCityWeatherInfo(commonRequest *CommonRequest, cityInfo *CityWeatherInfoRequest) (r string, err error) {
	if err = p.sendGetCityWeatherInfo(commonRequest, cityInfo); err != nil {
		return
	}
	return p.recvGetCityWeatherInfo()
}

func (p *CityWeatherInfoServiceClient) sendGetCityWeatherInfo(commonRequest *CommonRequest, cityInfo *CityWeatherInfoRequest) (err error) {
	oprot := p.OutputProtocol
	if oprot == nil {
		oprot = p.ProtocolFactory.GetProtocol(p.Transport)
		p.OutputProtocol = oprot
	}
	p.SeqId++
	oprot.WriteMessageBegin("getCityWeatherInfo", thrift.CALL, p.SeqId)
	args12 := NewGetCityWeatherInfoArgs()
	args12.CommonRequest = commonRequest
	args12.CityInfo = cityInfo
	err = args12.Write(oprot)
	oprot.WriteMessageEnd()
	oprot.Flush()
	return
}

func (p *CityWeatherInfoServiceClient) recvGetCityWeatherInfo() (value string, err error) {
	iprot := p.InputProtocol
	if iprot == nil {
		iprot = p.ProtocolFactory.GetProtocol(p.Transport)
		p.InputProtocol = iprot
	}
	_, mTypeId, seqId, err := iprot.ReadMessageBegin()
	if err != nil {
		return
	}
	if mTypeId == thrift.EXCEPTION {
		error14 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception")
		var error15 error
		error15, err = error14.Read(iprot)
		if err != nil {
			return
		}
		if err = iprot.ReadMessageEnd(); err != nil {
			return
		}
		err = error15
		return
	}
	if p.SeqId != seqId {
		err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "ping failed: out of sequence response")
		return
	}
	result13 := NewGetCityWeatherInfoResult()
	err = result13.Read(iprot)
	iprot.ReadMessageEnd()
	value = result13.Success
	return
}

type CityWeatherInfoServiceProcessor struct {
	*CommonServiceProcessor
}

func NewCityWeatherInfoServiceProcessor(handler CityWeatherInfoService) *CityWeatherInfoServiceProcessor {
	self16 := &CityWeatherInfoServiceProcessor{NewCommonServiceProcessor(handler)}
	self16.AddToProcessorMap("getCityWeatherInfo", &cityWeatherInfoServiceProcessorGetCityWeatherInfo{handler: handler})
	return self16
}

type cityWeatherInfoServiceProcessorGetCityWeatherInfo struct {
	handler CityWeatherInfoService
}

func (p *cityWeatherInfoServiceProcessorGetCityWeatherInfo) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) {
	args := NewGetCityWeatherInfoArgs()
	if err = args.Read(iprot); err != nil {
		iprot.ReadMessageEnd()
		x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error())
		oprot.WriteMessageBegin("getCityWeatherInfo", thrift.EXCEPTION, seqId)
		x.Write(oprot)
		oprot.WriteMessageEnd()
		oprot.Flush()
		return
	}
	iprot.ReadMessageEnd()
	result := NewGetCityWeatherInfoResult()
	if result.Success, err = p.handler.GetCityWeatherInfo(args.CommonRequest, args.CityInfo); err != nil {
		x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getCityWeatherInfo: "+err.Error())
		oprot.WriteMessageBegin("getCityWeatherInfo", thrift.EXCEPTION, seqId)
		x.Write(oprot)
		oprot.WriteMessageEnd()
		oprot.Flush()
		return
	}
	if err2 := oprot.WriteMessageBegin("getCityWeatherInfo", thrift.REPLY, seqId); err2 != nil {
		err = err2
	}
	if err2 := result.Write(oprot); err == nil && err2 != nil {
		err = err2
	}
	if err2 := oprot.WriteMessageEnd(); err == nil && err2 != nil {
		err = err2
	}
	if err2 := oprot.Flush(); err == nil && err2 != nil {
		err = err2
	}
	if err != nil {
		return
	}
	return true, err
}

// HELPER FUNCTIONS AND STRUCTURES

type GetCityWeatherInfoArgs struct {
	CommonRequest *CommonRequest          `thrift:"commonRequest,1"`
	CityInfo      *CityWeatherInfoRequest `thrift:"cityInfo,2"`
}

func NewGetCityWeatherInfoArgs() *GetCityWeatherInfoArgs {
	return &GetCityWeatherInfoArgs{}
}

func (p *GetCityWeatherInfoArgs) Read(iprot thrift.TProtocol) error {
	if _, err := iprot.ReadStructBegin(); err != nil {
		return fmt.Errorf("%T read error", p)
	}
	for {
		_, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
		if err != nil {
			return fmt.Errorf("%T field %d read error: %s", p, fieldId, err)
		}
		if fieldTypeId == thrift.STOP {
			break
		}
		switch fieldId {
		case 1:
			if err := p.readField1(iprot); err != nil {
				return err
			}
		case 2:
			if err := p.readField2(iprot); err != nil {
				return err
			}
		default:
			if err := iprot.Skip(fieldTypeId); err != nil {
				return err
			}
		}
		if err := iprot.ReadFieldEnd(); err != nil {
			return err
		}
	}
	if err := iprot.ReadStructEnd(); err != nil {
		return fmt.Errorf("%T read struct end error: %s", p, err)
	}
	return nil
}

func (p *GetCityWeatherInfoArgs) readField1(iprot thrift.TProtocol) error {
	p.CommonRequest = NewCommonRequest()
	if err := p.CommonRequest.Read(iprot); err != nil {
		return fmt.Errorf("%T error reading struct: %s", p.CommonRequest)
	}
	return nil
}

func (p *GetCityWeatherInfoArgs) readField2(iprot thrift.TProtocol) error {
	p.CityInfo = NewCityWeatherInfoRequest()
	if err := p.CityInfo.Read(iprot); err != nil {
		return fmt.Errorf("%T error reading struct: %s", p.CityInfo)
	}
	return nil
}

func (p *GetCityWeatherInfoArgs) Write(oprot thrift.TProtocol) error {
	if err := oprot.WriteStructBegin("getCityWeatherInfo_args"); err != nil {
		return fmt.Errorf("%T write struct begin error: %s", p, err)
	}
	if err := p.writeField1(oprot); err != nil {
		return err
	}
	if err := p.writeField2(oprot); err != nil {
		return err
	}
	if err := oprot.WriteFieldStop(); err != nil {
		return fmt.Errorf("%T write field stop error: %s", err)
	}
	if err := oprot.WriteStructEnd(); err != nil {
		return fmt.Errorf("%T write struct stop error: %s", err)
	}
	return nil
}

func (p *GetCityWeatherInfoArgs) writeField1(oprot thrift.TProtocol) (err error) {
	if p.CommonRequest != nil {
		if err := oprot.WriteFieldBegin("commonRequest", thrift.STRUCT, 1); err != nil {
			return fmt.Errorf("%T write field begin error 1:commonRequest: %s", p, err)
		}
		if err := p.CommonRequest.Write(oprot); err != nil {
			return fmt.Errorf("%T error writing struct: %s", p.CommonRequest)
		}
		if err := oprot.WriteFieldEnd(); err != nil {
			return fmt.Errorf("%T write field end error 1:commonRequest: %s", p, err)
		}
	}
	return err
}

func (p *GetCityWeatherInfoArgs) writeField2(oprot thrift.TProtocol) (err error) {
	if p.CityInfo != nil {
		if err := oprot.WriteFieldBegin("cityInfo", thrift.STRUCT, 2); err != nil {
			return fmt.Errorf("%T write field begin error 2:cityInfo: %s", p, err)
		}
		if err := p.CityInfo.Write(oprot); err != nil {
			return fmt.Errorf("%T error writing struct: %s", p.CityInfo)
		}
		if err := oprot.WriteFieldEnd(); err != nil {
			return fmt.Errorf("%T write field end error 2:cityInfo: %s", p, err)
		}
	}
	return err
}

func (p *GetCityWeatherInfoArgs) String() string {
	if p == nil {
		return "<nil>"
	}
	return fmt.Sprintf("GetCityWeatherInfoArgs(%+v)", *p)
}

type GetCityWeatherInfoResult struct {
	Success string `thrift:"success,0"`
}

func NewGetCityWeatherInfoResult() *GetCityWeatherInfoResult {
	return &GetCityWeatherInfoResult{}
}

func (p *GetCityWeatherInfoResult) Read(iprot thrift.TProtocol) error {
	if _, err := iprot.ReadStructBegin(); err != nil {
		return fmt.Errorf("%T read error", p)
	}
	for {
		_, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
		if err != nil {
			return fmt.Errorf("%T field %d read error: %s", p, fieldId, err)
		}
		if fieldTypeId == thrift.STOP {
			break
		}
		switch fieldId {
		case 0:
			if err := p.readField0(iprot); err != nil {
				return err
			}
		default:
			if err := iprot.Skip(fieldTypeId); err != nil {
				return err
			}
		}
		if err := iprot.ReadFieldEnd(); err != nil {
			return err
		}
	}
	if err := iprot.ReadStructEnd(); err != nil {
		return fmt.Errorf("%T read struct end error: %s", p, err)
	}
	return nil
}

func (p *GetCityWeatherInfoResult) readField0(iprot thrift.TProtocol) error {
	if v, err := iprot.ReadString(); err != nil {
		return fmt.Errorf("error reading field 0: %s")
	} else {
		p.Success = v
	}
	return nil
}

func (p *GetCityWeatherInfoResult) Write(oprot thrift.TProtocol) error {
	if err := oprot.WriteStructBegin("getCityWeatherInfo_result"); err != nil {
		return fmt.Errorf("%T write struct begin error: %s", p, err)
	}
	switch {
	default:
		if err := p.writeField0(oprot); err != nil {
			return err
		}
	}
	if err := oprot.WriteFieldStop(); err != nil {
		return fmt.Errorf("%T write field stop error: %s", err)
	}
	if err := oprot.WriteStructEnd(); err != nil {
		return fmt.Errorf("%T write struct stop error: %s", err)
	}
	return nil
}

func (p *GetCityWeatherInfoResult) writeField0(oprot thrift.TProtocol) (err error) {
	if err := oprot.WriteFieldBegin("success", thrift.STRING, 0); err != nil {
		return fmt.Errorf("%T write field begin error 0:success: %s", p, err)
	}
	if err := oprot.WriteString(string(p.Success)); err != nil {
		return fmt.Errorf("%T.success (0) field write error: %s", p)
	}
	if err := oprot.WriteFieldEnd(); err != nil {
		return fmt.Errorf("%T write field end error 0:success: %s", p, err)
	}
	return err
}

func (p *GetCityWeatherInfoResult) String() string {
	if p == nil {
		return "<nil>"
	}
	return fmt.Sprintf("GetCityWeatherInfoResult(%+v)", *p)
}


text:
class Search {

    /**
     * Constructs Search
     * @param {Navigation} mainController The main navigation controller
     * @param {DOMElement} element The DOMElement to bind to
     */
    constructor(mainController, element) {
        this.mainController = mainController;
        this.element = element;

        if (this.element) {
            this.init();
        }
    }

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

    /**
     * Initlaises the sidebar search
     * @returns {Search}
     */
    init() {
        this.element
            .addEventListener('keyup', (e) => {
                clearTimeout(this.debounce);
                this.debounce = setTimeout(() => {
                    let keywords = this.normaliseSearchString(e.srcElement.value);
                    if (this.keywords !== keywords) {
                        this.keywords = keywords;
                        this.search(keywords);
                    }
                }, 250);
            });

        return this;
    }

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

    /**
     * Performs a search
     * @param {string} keywords The search keywords
     * @returns {Search}
     */
    search(keywords) {
        if (keywords.length) {
            this.filter(keywords);
        } else {
            this.reset();
        }

        return this;
    }

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

    /**
     * Filters the sidebar sections by the given keywords
     * @param {string} keywords
     * @returns {Search}
     */
    filter(keywords) {
        this.mainController.adminController.log(`Filtering nav sections by: ${keywords}`);
        this.mainController
            .disableAnimation()
            .disableSorting();

        this.hideToggles();

        let regex = new RegExp(keywords, 'i');

        this.mainController
            .sections
            .forEach((section) => {

                section.instance.box.container
                    .querySelectorAll('li')
                    .forEach((item) => {

                        let link = item.querySelector('a');
                        let text = this.normaliseSearchString(
                            [link.textContent, link.dataset['search-terms']].join('')
                        );

                        if (regex.test(text)) {
                            item.classList.remove('hidden');
                        } else {
                            item.classList.add('hidden');
                        }
                    });

                //  If there are no visible options, hide the box
                let visible = section.instance.box.container
                    .querySelectorAll('li:not(.hidden)')

                if (visible.length) {

                    section.instance.box.element.classList.remove('hidden', 'closed');

                    //  Size the box to accommodate visible options
                    let height = section.instance.box.container.querySelector('ul').offsetHeight;
                    section.instance.box.container.style.height = `${height}px`;

                } else {
                    section.instance.box.element.classList.add('hidden');
                }
            });

        return this;
    }

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

    /**
     * Resets the sidebar to how it was prior to searching
     * @returns {Search}
     */
    reset() {

        this.mainController.adminController.log('Resetting...');

        this.mainController
            .sections
            .forEach((section) => {

                section.instance.box.element
                    .classList.remove('hidden');

                section.instance.box.container
                    .querySelectorAll('li')
                    .forEach((item) => {
                        item.classList.remove('hidden');
                    });

                if (section.instance.isOpen()) {
                    section.instance.open();
                } else {
                    section.instance.close();
                }
            });

        this.showToggles();

        this.mainController
            .enableAnimation()
            .enableSorting();

        return this;
    }

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

    /**
     * Normalises the search term
     * @param searchString
     * @returns {string}
     */
    normaliseSearchString(searchString) {
        return searchString.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
    };

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

    /**
     * Hides all the section tiggles
     * @returns {Search}
     */
    hideToggles() {
        this.mainController
            .sections
            .forEach((section) => {
                section.instance.hideToggles();
            });

        return this;
    }

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

    /**
     * Shows all the section tiggles
     * @returns {Search}
     */
    showToggles() {
        this.mainController
            .sections
            .forEach((section) => {
                section.instance.showToggles();
            });

        return this;
    }
}

export default Search;

redpajama_set_name: RedPajamaGithub


text:
@interface EPubViewController () <
	RDPackageResourceServerDelegate,
	UIAlertViewDelegate,
	UIPopoverControllerDelegate,
	UIWebViewDelegate>
{
	@private UIAlertView *m_alertAddBookmark;
	@private RDContainer *m_container;
	@private BOOL m_currentPageCanGoLeft;
	@private BOOL m_currentPageCanGoRight;
	@private BOOL m_currentPageIsFixedLayout;
	@private NSArray* m_currentPageOpenPagesArray;
	@private BOOL m_currentPageProgressionIsLTR;
	@private int m_currentPageSpineItemCount;
	@private NSString *m_initialCFI;
	@private BOOL m_moIsPlaying;
	@private RDNavigationElement *m_navElement;
	@private RDPackage *m_package;
	@private UIPopoverController *m_popover;
	@private RDPackageResourceServer *m_resourceServer;
	@private NSData *m_specialPayload_AnnotationsCSS;
	@private NSData *m_specialPayload_MathJaxJS;
	@private RDSpineItem *m_spineItem;
	@private __weak UIWebView *m_webView;
}

- (void)passSettingsToJavaScript;
- (void)updateNavigationItems;
- (void)updateToolbar;

@end

@implementation EPubViewController

- (void)initializeSpecialPayloads {

    // May be left to NIL if desired (in which case MathJax and annotations.css functionality will be disabled).

    m_specialPayload_AnnotationsCSS = nil;
    m_specialPayload_MathJaxJS = nil;

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"MathJax" ofType:@"js" inDirectory:@"mathjax"];
    if (filePath != nil) {
        NSString *code = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
        if (code != nil) {
            NSData *data = [code dataUsingEncoding:NSUTF8StringEncoding];
            if (data != nil) {
                m_specialPayload_MathJaxJS = data;
            }
        }
    }

    filePath = [[NSBundle mainBundle] pathForResource:@"annotations" ofType:@"css"];
    if (filePath != nil) {
        NSString *code = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
        if (code != nil) {
            NSData *data = [code dataUsingEncoding:NSUTF8StringEncoding];
            if (data != nil) {
                m_specialPayload_AnnotationsCSS = data;
            }
        }
    }
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
	m_alertAddBookmark = nil;

	if (buttonIndex == 1) {
		UITextField *textField = [alertView textFieldAtIndex:0];

		NSString *title = [textField.text stringByTrimmingCharactersInSet:
			[NSCharacterSet whitespaceAndNewlineCharacterSet]];

		NSString *response = [m_webView stringByEvaluatingJavaScriptFromString:
			@"ReadiumSDK.reader.bookmarkCurrentPage()"];

		if (response != nil && response.length > 0) {
			NSData *data = [response dataUsingEncoding:NSUTF8StringEncoding];
			NSError *error;

			NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data
				options:0 error:&error];

			Bookmark *bookmark = [[Bookmark alloc]
				initWithCFI:[dict objectForKey:@"contentCFI"]
				containerPath:m_container.path
				idref:[dict objectForKey:@"idref"]
				title:title];

			if (bookmark == nil) {
				NSLog(@"The bookmark is nil!");
			}
			else {
				[[BookmarkDatabase shared] addBookmark:bookmark];
			}
		}
	}
}

- (void)cleanUp {
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	m_moIsPlaying = NO;

	if (m_alertAddBookmark != nil) {
		m_alertAddBookmark.delegate = nil;
		[m_alertAddBookmark dismissWithClickedButtonIndex:999 animated:NO];
		m_alertAddBookmark = nil;
	}

	if (m_popover != nil) {
		[m_popover dismissPopoverAnimated:NO];
		m_popover = nil;
	}
}

- (instancetype)
	initWithContainer:(RDContainer *)container
	package:(RDPackage *)package
{
	return [self initWithContainer:container package:package spineItem:nil cfi:nil];
}

- (instancetype)
	initWithContainer:(RDContainer *)container
	package:(RDPackage *)package
	bookmark:(Bookmark *)bookmark
{
	RDSpineItem *spineItem = nil;

	for (RDSpineItem *currSpineItem in package.spineItems) {
		if ([currSpineItem.idref isEqualToString:bookmark.idref]) {
			spineItem = currSpineItem;
			break;
		}
	}

	return [self
		initWithContainer:container
		package:package
		spineItem:spineItem
		cfi:bookmark.cfi];
}

- (instancetype)
	initWithContainer:(RDContainer *)container
	package:(RDPackage *)package
	navElement:(RDNavigationElement *)navElement
{
	if (container == nil || package == nil) {
		return nil;
	}

	// Clear the root URL since its port may have changed.
	package.rootURL = nil;

	RDSpineItem *spineItem = nil;

	if (package.spineItems.count > 0) {
		spineItem = [package.spineItems objectAtIndex:0];
	}

	if (spineItem == nil) {
		return nil;
	}

	if (self = [super initWithTitle:package.title navBarHidden:NO]) {
		m_container = container;
		m_navElement = navElement;
		m_package = package;
		m_spineItem = spineItem;

		[self initializeSpecialPayloads];

		m_resourceServer = [[RDPackageResourceServer alloc]
			initWithDelegate:self
			package:package
			specialPayloadAnnotationsCSS:m_specialPayload_AnnotationsCSS
			specialPayloadMathJaxJS:m_specialPayload_MathJaxJS];

		if (m_resourceServer == nil) {
			return nil;
		}

		[self updateNavigationItems];
	}

	return self;
}

- (instancetype)
	initWithContainer:(RDContainer *)container
	package:(RDPackage *)package
	spineItem:(RDSpineItem *)spineItem
	cfi:(NSString *)cfi
{
	if (container == nil || package == nil) {
		return nil;
	}

	// Clear the root URL since its port may have changed.
	package.rootURL = nil;

	if (spineItem == nil && package.spineItems.count > 0) {
		spineItem = [package.spineItems objectAtIndex:0];
	}

	if (spineItem == nil) {
		return nil;
	}

    if (self = [super initWithTitle:package.title navBarHidden:NO]) {
		m_container = container;
		m_initialCFI = cfi;
		m_package = package;
		m_spineItem = spineItem;

		[self initializeSpecialPayloads];

		m_resourceServer = [[RDPackageResourceServer alloc]
			initWithDelegate:self
			package:package
			specialPayloadAnnotationsCSS:m_specialPayload_AnnotationsCSS
			specialPayloadMathJaxJS:m_specialPayload_MathJaxJS];

		if (m_resourceServer == nil) {
			return nil;
		}

		[self updateNavigationItems];
	}

	return self;
}

- (void)loadView {
	self.view = [[UIView alloc] init];
	self.view.backgroundColor = [UIColor whiteColor];

	// Notifications

	NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];

	[nc addObserver:self selector:@selector(onEPubSettingsDidChange:)
		name:kSDKLauncherEPubSettingsDidChange object:nil];

	// Web view

	UIWebView *webView = [[UIWebView alloc] init];
	m_webView = webView;
	webView.delegate = self;
	webView.hidden = YES;
	webView.scalesPageToFit = YES;
	webView.scrollView.bounces = NO;
	webView.allowsInlineMediaPlayback = YES;
	webView.mediaPlaybackRequiresUserAction = NO;
	[self.view addSubview:webView];

    // The "no optimize" RequireJS option means that the entire "readium-shared-js" folder must be copied in to the OSX app bundle's "scripts" folder! (including "node_modules" subfolder, which is populated when invoking the "npm run prepare" build command) There is therefore some significant filesystem / size overhead, but the benefits are significant too: no need for the WebView to fetch sourcemaps, and to attempt to un-mangle the obfuscated Javascript during debugging.
    // However, the recommended development-time pattern is to invoke "npm run build" in order to refresh the "build-output" folder, with the RJS_UGLY environment variable set to "false" or "no". This way, the RequireJS single/multiple bundle(s) will be in readable uncompressed form.
    //NSString* readerFileName = @"reader_RequireJS-no-optimize.html";

    NSString* readerFileName = @"reader_RequireJS-multiple-bundles.html";
    //NSString* readerFileName = @"reader_RequireJS-single-bundle.html";

	NSURL *url = [[NSBundle mainBundle] URLForResource:readerFileName withExtension:nil];
	[webView loadRequest:[NSURLRequest requestWithURL:url]];
}

- (void)onClickAddBookmark {
	if (m_alertAddBookmark == nil) {
		m_alertAddBookmark = [[UIAlertView alloc]
			initWithTitle:LocStr(@"ADD_BOOKMARK_PROMPT_TITLE")
			message:nil
			delegate:self
			cancelButtonTitle:LocStr(@"GENERIC_CANCEL")
			otherButtonTitles:LocStr(@"GENERIC_OK"), nil];
		m_alertAddBookmark.alertViewStyle = UIAlertViewStylePlainTextInput;
		UITextField *textField = [m_alertAddBookmark textFieldAtIndex:0];
		textField.placeholder = LocStr(@"ADD_BOOKMARK_PROMPT_PLACEHOLDER");
		[m_alertAddBookmark show];
	}
}

- (void)onClickMONext {
	[m_webView stringByEvaluatingJavaScriptFromString:@"ReadiumSDK.reader.nextMediaOverlay()"];
}

- (void)onClickMOPause {
	[m_webView stringByEvaluatingJavaScriptFromString:@"ReadiumSDK.reader.toggleMediaOverlay()"];
}

- (void)onClickMOPlay {
	[m_webView stringByEvaluatingJavaScriptFromString:@"ReadiumSDK.reader.toggleMediaOverlay()"];
}

- (void)onClickMOPrev {
	[m_webView stringByEvaluatingJavaScriptFromString:@"ReadiumSDK.reader.previousMediaOverlay()"];
}

- (void)onClickNext {
	[m_webView stringByEvaluatingJavaScriptFromString:@"ReadiumSDK.reader.openPageNext()"];
}

- (void)onClickPrev {
	[m_webView stringByEvaluatingJavaScriptFromString:@"ReadiumSDK.reader.openPagePrev()"];
}

- (void)onClickSettings {
	EPubSettingsController *c = [[EPubSettingsController alloc] init];
	UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:c];

	if (IS_IPAD) {
		if (m_popover == nil) {
			m_popover = [[UIPopoverController alloc] initWithContentViewController:nav];
			m_popover.delegate = self;
			[m_popover presentPopoverFromBarButtonItem:self.navigationItem.rightBarButtonItem
				permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
		}
	}
	else {
		[self presentViewController:nav animated:YES completion:nil];
	}
}

- (void)onEPubSettingsDidChange:(NSNotification *)notification {
	[self passSettingsToJavaScript];
}

- (void)
	packageResourceServer:(RDPackageResourceServer *)packageResourceServer
	executeJavaScript:(NSString *)javaScript
{
	dispatch_async(dispatch_get_main_queue(), ^{
		[m_webView stringByEvaluatingJavaScriptFromString:javaScript];
	});
}

- (void)passSettingsToJavaScript {
	NSData *data = [NSJSONSerialization dataWithJSONObject:[EPubSettings shared].dictionary
		options:0 error:nil];

	if (data == nil) {
		return;
	}

	NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

	if (s == nil || s.length == 0) {
		return;
	}

	[m_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:
		@"ReadiumSDK.reader.updateSettings(%@)", s]];
}

- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController {
	m_popover = nil;
}

- (void)updateNavigationItems {
	self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
		initWithBarButtonSystemItem:UIBarButtonSystemItemAction
		target:self
		action:@selector(onClickSettings)];
}

- (void)updateToolbar {
	if (m_webView.hidden) {
		self.toolbarItems = nil;
		return;
	}

	NSMutableArray *items = [NSMutableArray arrayWithCapacity:8];

	UIBarButtonItem *itemFixed = [[UIBarButtonItem alloc]
		initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
		target:nil
		action:nil];

	itemFixed.width = 12;

	static NSString *arrowL = @"\u2190";
	static NSString *arrowR = @"\u2192";

	UIBarButtonItem *itemNext = [[UIBarButtonItem alloc]
		initWithTitle:m_currentPageProgressionIsLTR ? arrowR : arrowL
		style:UIBarButtonItemStylePlain
		target:self
		action:@selector(onClickNext)];

	UIBarButtonItem *itemPrev = [[UIBarButtonItem alloc]
		initWithTitle:m_currentPageProgressionIsLTR ? arrowL : arrowR
		style:UIBarButtonItemStylePlain
		target:self
		action:@selector(onClickPrev)];

	if (m_currentPageProgressionIsLTR) {
		[items addObject:itemPrev];
		[items addObject:itemFixed];
		[items addObject:itemNext];
	}
	else {
		[items addObject:itemNext];
		[items addObject:itemFixed];
		[items addObject:itemPrev];
	}

	[items addObject:itemFixed];

	UILabel *label = [[UILabel alloc] init];
	label.backgroundColor = [UIColor clearColor];
	label.font = [UIFont systemFontOfSize:16];
	label.textColor = [UIColor blackColor];

    BOOL canGoNext = m_currentPageProgressionIsLTR ? m_currentPageCanGoRight : m_currentPageCanGoLeft;
    BOOL canGoPrevious = m_currentPageProgressionIsLTR ? m_currentPageCanGoLeft : m_currentPageCanGoRight;

    itemNext.enabled = canGoNext;
    itemPrev.enabled = canGoPrevious;

	if (m_currentPageOpenPagesArray == nil || [m_currentPageOpenPagesArray count] <= 0) {
		label.text = @"";
	}
	else {

        NSMutableArray *pageNumbers = [NSMutableArray array];

        for (NSDictionary *pageDict in m_currentPageOpenPagesArray) {

            NSNumber *spineItemIndex = [pageDict valueForKey:@"spineItemIndex"];
            NSNumber *spineItemPageIndex = [pageDict valueForKey:@"spineItemPageIndex"];

            int pageIndex = m_currentPageIsFixedLayout ? spineItemIndex.intValue : spineItemPageIndex.intValue;

            [pageNumbers addObject: [NSNumber numberWithInt:pageIndex + 1]];
        }

        NSString* currentPages = [NSString stringWithFormat:@"%@", [pageNumbers componentsJoinedByString:@"-"]];

        int pageCount = 0;
        if ([m_currentPageOpenPagesArray count] > 0)
        {
            NSDictionary *firstOpenPageDict = [m_currentPageOpenPagesArray objectAtIndex:0];
            NSNumber *number = [firstOpenPageDict valueForKey:@"spineItemPageCount"];

            pageCount = m_currentPageIsFixedLayout ? m_currentPageSpineItemCount: number.intValue;
        }
        NSString* totalPages = [NSString stringWithFormat:@"%d", pageCount];

        label.text = LocStr(@"PAGE_X_OF_Y", [currentPages UTF8String], [totalPages UTF8String], m_currentPageIsFixedLayout?[@"FXL" UTF8String]:[@"reflow" UTF8String]);
	}

	[label sizeToFit];

	[items addObject:[[UIBarButtonItem alloc] initWithCustomView:label]];

	[items addObject:[[UIBarButtonItem alloc]
		initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
		target:nil
		action:nil]
	];

	NSString *response = [m_webView stringByEvaluatingJavaScriptFromString:
		@"ReadiumSDK.reader.isMediaOverlayAvailable()"];

	if (response != nil && [response isEqualToString:@"true"]) {
		[items addObject:[[UIBarButtonItem alloc]
			initWithTitle:@"<"
			style:UIBarButtonItemStylePlain
			target:self
			action:@selector(onClickMOPrev)]
		];

		if (m_moIsPlaying) {
			[items addObject:[[UIBarButtonItem alloc]
				initWithBarButtonSystemItem:UIBarButtonSystemItemPause
				target:self
				action:@selector(onClickMOPause)]
			];
		}
		else {
			[items addObject:[[UIBarButtonItem alloc]
				initWithBarButtonSystemItem:UIBarButtonSystemItemPlay
				target:self
				action:@selector(onClickMOPlay)]
			];
		}

		[items addObject:[[UIBarButtonItem alloc]
			initWithTitle:@">"
			style:UIBarButtonItemStylePlain
			target:self
			action:@selector(onClickMONext)]
		];

		[items addObject:itemFixed];
	}

	[items addObject:[[UIBarButtonItem alloc]
		initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
		target:self
		action:@selector(onClickAddBookmark)]
	];

	self.toolbarItems = items;
}

- (void)viewDidLayoutSubviews {
	m_webView.frame = self.view.bounds;
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];

	if (self.navigationController != nil) {
		[self.navigationController setToolbarHidden:NO animated:YES];
	}
}

- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];

	if (self.navigationController != nil) {
		[self.navigationController setToolbarHidden:YES animated:YES];
	}
}

- (BOOL)
	webView:(UIWebView *)webView
	shouldStartLoadWithRequest:(NSURLRequest *)request
	navigationType:(UIWebViewNavigationType)navigationType
{
	BOOL shouldLoad = YES;
	NSString *url = request.URL.absoluteString;
	NSString *s = @"epubobjc:";

	if ([url hasPrefix:s]) {
		url = [url substringFromIndex:s.length];
		shouldLoad = NO;

		if ([url isEqualToString:@"readerDidInitialize"]) {
			NSMutableDictionary *dict = [NSMutableDictionary dictionary];

			//
			// Important!  Rather than "localhost", "127.0.0.1" is specified in the following URL to work
			// around an issue introduced in iOS 7.0.  When an iOS 7 device is offline (Wi-Fi off, or
			// airplane mode on), audio and video refuses to be served by UIWebView / QuickTime, even
			// though being offline is irrelevant for an embedded HTTP server like ours.  Daniel suggested
			// trying 127.0.0.1 in case the underlying issue was host name resolution, and it worked!
			//
			//   -- Shane
			//

			if (m_package.rootURL == nil || m_package.rootURL.length == 0) {
				m_package.rootURL = [NSString stringWithFormat:
					@"http://127.0.0.1:%d/", m_resourceServer.port];
			}

			[dict setObject:m_package.dictionary forKey:@"package"];
			[dict setObject:[EPubSettings shared].dictionary forKey:@"settings"];

			NSDictionary *pageDict = nil;

			if (m_spineItem == nil) {
			}
			else if (m_initialCFI != nil && m_initialCFI.length > 0) {
				pageDict = @{
					@"idref" : m_spineItem.idref,
					@"elementCfi" : m_initialCFI
				};
			}
			else if (m_navElement.content != nil && m_navElement.content.length > 0) {
				pageDict = @{
					@"contentRefUrl" : m_navElement.content,
					@"sourceFileHref" : (m_navElement.sourceHref == nil ?
						@"" : m_navElement.sourceHref)
				};
			}
			else {
				pageDict = @{
					@"idref" : m_spineItem.idref
				};
			}

			if (pageDict != nil) {
				[dict setObject:pageDict forKey:@"openPageRequest"];
			}

			NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];

			if (data != nil) {
				NSString *arg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
				[m_webView stringByEvaluatingJavaScriptFromString:[NSString
					stringWithFormat:@"ReadiumSDK.reader.openBook(%@)", arg]];
			}

			return shouldLoad;
		}

		s = @"pageDidChange?q=";

		if ([url hasPrefix:s]) {
			s = [url substringFromIndex:s.length];
			s = [s stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

			NSData *data = [s dataUsingEncoding:NSUTF8StringEncoding];
			NSError *error;

			NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data
				options:0 error:&error];

            m_currentPageCanGoLeft = ([[dict valueForKey:@"canGoLeft_"] isEqual:[NSNumber numberWithBool:YES]] ? YES : NO);
            m_currentPageCanGoRight = ([[dict valueForKey:@"canGoRight_"] isEqual:[NSNumber numberWithBool:YES]] ? YES : NO);

            m_currentPageProgressionIsLTR = ([[dict valueForKey:@"isRightToLeft"] isEqual:[NSNumber numberWithBool:YES]] ? NO : YES);

            m_currentPageIsFixedLayout = ([[dict valueForKey:@"isFixedLayout"] isEqual:[NSNumber numberWithBool:YES]] ? YES : NO);

            m_currentPageSpineItemCount = [((NSNumber*)[dict valueForKey:@"spineItemCount"]) intValue];

            m_currentPageOpenPagesArray = (NSArray*)[dict objectForKey:@"openPages"];

			m_webView.hidden = NO;
			[self updateToolbar];
			return shouldLoad;
		}

		s = @"mediaOverlayStatusDidChange?q=";

		if ([url hasPrefix:s]) {
			s = [url substringFromIndex:s.length];
			s = [s stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

			NSData *data = [s dataUsingEncoding:NSUTF8StringEncoding];
			NSError *error;

			NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data
				options:0 error:&error];

			NSNumber *number = [dict objectForKey:@"isPlaying"];

			if (number != nil) {
				m_moIsPlaying = number.boolValue;
			}

			[self updateToolbar];
			return shouldLoad;
		}
	}

	return shouldLoad;
}

@end


text:
module Chain2Dupe where

import Chain1 ()

chain2Dupe f = appendFile f "e"


text:
<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 9/30/2017
 * Time: 9:52 PM
 */

class Grocery_Home_Ranking4_CRUD extends Grocery_Home_CRUD
{
    protected function set_default_Model()
    {
        $db_driver = 'postgre';
        $model_name = 'Grocery_crud_model_' . $db_driver;

        unset($this->{$model_name});

        $ci = &get_instance();

        $ci->load->model('Grocery_crud_model');
        $ci->load->model('Grocery_crud_generic_model');
        $ci->load->model('Grocery_crud_model_postgre');
        $ci->load->model('Grocery_crud_home_ranking4_model');
        $this->basic_model = new Grocery_crud_home_ranking4_model();
    }
}


text:
var express = require('express')
  , routes = require('./routes')
  , http = require('http')
  , request = require('request')
  , cons = require('consolidate')
  , path = require('path');

var app = express();

app.configure(function(){
  app.set('port', process.env.PORT || 5000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'html');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.cookieParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.engine('html', cons.swig);
  app.use(express.static(path.join(__dirname, 'public')));
  app.use(express.urlencoded());
  app.use(express.json);
  app.locals.cache = "memory"
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

app.get('/', routes.index);

var server = http.createServer(app).listen(process.env.PORT || app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});


text:
package main

import (
	"bytes"
	"database/sql"
	"fmt"
	"regexp"
	"time"
)

// assumes first column is unique ID
func updateRecords(db *sql.DB, table string, cols []string, records [][]string, logger chan<- string) error {
	updateErrors := 0

	// create insert statement string
	var queryStringBuf bytes.Buffer
	queryStringBuf.WriteString("UPDATE " + table + " SET ")
	for i := 1; i < len(cols); i++ {
		queryStringBuf.WriteString(cols[i] + " = " + DB_PREPARE_RUNE)
		if i < len(cols)-1 {
			queryStringBuf.WriteString(", ")
		}
	}
	queryStringBuf.WriteString(" WHERE " + cols[0] + " = ?")
	query := queryStringBuf.String()

	// create prepared statement
	stmt, err := db.Prepare(query)
	if err != nil {
		logger <- fmt.Sprintf("ERROR: Unable to prepare statement: \"%s\" --- Database returned: %s", query, err)
		return fmt.Errorf("ERROR: Unable to prepare statement. See log for details")
	}

	logger <- fmt.Sprintf("INFO: Using prepared statement \"%s\"", query)

	// watch for dates in parsed data
	dateRegex, _ := regexp.Compile(DATE_REGEX)

	// insert each record
	for recNum, singleRecord := range records {
		lastIndex := len(singleRecord) - 1
		// create pointers to parsed data
		preparedValues := make([]interface{}, len(singleRecord))
		// set last field in preparedValues (the WHERE = ? interpolation) = first field in record (ID)
		preparedValues[lastIndex] = singleRecord[0]
		// set data fields in preparedValues (all but last)
		for i := 0; i < len(singleRecord)-1; i++ {
			// offset one since singleRecord[0] is ID used above
			val := singleRecord[i+1]
			// convert strings to dates if identified
			if dateRegex.MatchString(val) {
				preparedValues[i], _ = time.Parse(DATE_FORMAT, val)
			} else {
				preparedValues[i] = val
			}
		}
		// execute insert
		_, err := stmt.Exec(preparedValues...)
		if err != nil {
			logger <- fmt.Sprintf("ERROR: Unable to update record #%d %q --- Database returned: \"%s\"", recNum+1, singleRecord, err)
			updateErrors++
		}
		logger <- fmt.Sprintf("INFO: Updated record %q", singleRecord)
	}

	if updateErrors > 0 {
		return fmt.Errorf("ERROR: Unable to update %d records. See log.txt for error details", updateErrors)
	} else {
		return nil
	}
}


text:
import path from 'path'
import webpack from 'webpack'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import postCssnext from 'postcss-cssnext'

const env = process.env.NODE_ENV

const config = {
  entry: [
    'webpack-hot-middleware/client',
    'babel-polyfill',
    './index.jsx',
  ],
  output: {
    path: path.join(__dirname, '../dist'),
    filename: 'index.js',
    publicPath: '/',
  },
  resolve: {
    root: path.join(__dirname, 'node_modules'),
    extensions: ['', '.jsx', '.js'],
  },
  module: {
    loaders: [{
      test: /(\.js|\.jsx)$/,
      exclude: /(node_modules)/,
      loader: 'babel',
    }, {
      test: /\.css$/,
      loader: 'style?sourceMap!css?sourceMap!postcss?sourceMap',
    }],
  },
  externals: {},
  postcss: [postCssnext],
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new HtmlWebpackPlugin({
      title: 'reactmvc example',
      filename: 'index.html',
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(env),
    }),
  ],
  devtool: 'inline-source-map',
  resolveLoader: {
    root: path.join(__dirname, 'node_modules'),
  },
}

export default config


text:
package org.testifyproject.di.spring;

import static org.springframework.beans.factory.BeanFactoryUtils.beanNamesForTypeIncludingAncestors;
import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE;

import java.lang.annotation.Annotation;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedDeque;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Controller;
import org.testifyproject.Instance;
import org.testifyproject.TestContext;
import org.testifyproject.core.util.ServiceLocatorUtil;
import org.testifyproject.extension.InstanceProvider;
import org.testifyproject.extension.ProxyInstanceController;

/**
 * A class that is called after the application context is refreshed to initialize the test as
 * well as start and stop test resources.
 *
 * @author saden
 */
public class SpringBeanFactoryPostProcessor implements BeanFactoryPostProcessor, Ordered {

    private final TestContext testContext;

    public SpringBeanFactoryPostProcessor(TestContext testContext) {
        this.testContext = testContext;
    }

    @Override
    public int getOrder() {
        return LOWEST_PRECEDENCE;
    }

    @Override
    public void postProcessBeanFactory(
            ConfigurableListableBeanFactory configurableListableBeanFactory) {
        DefaultListableBeanFactory beanFactory =
                (DefaultListableBeanFactory) configurableListableBeanFactory;

        Queue<Instance<?>> instances = getInstances(testContext);

        removeInstances(instances, beanFactory);
        addInstances(instances, beanFactory);

        for (String beanName : beanFactory.getBeanDefinitionNames()) {
            BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
            //mark all beans as lazy beans so we don't needlessly
            //instianticate them during testing
            beanDefinition.setLazyInit(true);

            Class<?> beanType = beanFactory.getType(beanName);

            if (beanDefinition.isPrimary()) {
                processPrimary(beanFactory, beanDefinition, beanName, beanType);
            }

            //by default spring eagerly initilizes singleton scoped beans such as
            //controllers so lets insure that controller entry points are prototype
            //scoped and thus make them lazy.
            boolean isController = isController(beanType);

            if (isController) {
                beanDefinition.setScope(SCOPE_PROTOTYPE);
            }
        }

        beanFactory.addBeanPostProcessor(new SpringReifierPostProcessor(testContext));

    }

    Queue<Instance<?>> getInstances(TestContext testContext) {
        //add instances
        ConcurrentLinkedDeque<Instance<?>> instances = new ConcurrentLinkedDeque<>();
        ServiceLocatorUtil.INSTANCE.findAllWithFilter(InstanceProvider.class)
                .stream()
                .map(p -> p.get(testContext))
                .flatMap(p -> p.stream())
                .forEach(p -> instances.addLast(p));

        ServiceLocatorUtil.INSTANCE.findAllWithFilter(ProxyInstanceController.class)
                .stream()
                .map(p -> p.create(testContext))
                .flatMap(p -> p.stream())
                .forEach(p -> instances.addLast(p));

        return instances;
    }

    void removeInstances(Queue<Instance<?>> instances, DefaultListableBeanFactory beanFactory) {
        //remove existing instances
        instances.forEach(instance -> {
            String name = instance.getName();
            Class contract = instance.getContract();

            if (name != null && contract != null) {
                if (beanFactory.containsBean(name)) {
                    beanFactory.removeBeanDefinition(name);
                }

                //XXX: find and remove all the beans that implment the given contract
                String[] contractBeanNames = beanNamesForTypeIncludingAncestors(
                        beanFactory,
                        contract, true, false);

                for (String beanName : contractBeanNames) {
                    beanFactory.removeBeanDefinition(beanName);
                }
            } else if (name != null) {
                if (beanFactory.containsBean(name)) {
                    beanFactory.removeBeanDefinition(name);
                }
            } else if (contract != null) {
                //XXX: find and remove all the beans that implment the given contract
                String[] contractBeanNames = beanNamesForTypeIncludingAncestors(
                        beanFactory,
                        contract, true, false);

                for (String beanName : contractBeanNames) {
                    beanFactory.removeBeanDefinition(beanName);
                }
            } else {
                //XXX: find and remove all the beans of the given instance type
                String[] typeBeanNames = beanNamesForTypeIncludingAncestors(beanFactory,
                        instance.getClass(), true, false);
                for (String beanName : typeBeanNames) {
                    beanFactory.removeBeanDefinition(beanName);
                }
            }

        });
    }

    void addInstances(Queue<Instance<?>> instances, DefaultListableBeanFactory beanFactory) {
        //add new instances
        instances.forEach(instance -> {
            Object value = instance.getValue();
            String name = instance.getName();
            Class contract = value.getClass();

            if (name == null) {
                beanFactory.registerSingleton(contract.getSimpleName(), value);
            } else {
                beanFactory.registerSingleton(name, value);
            }
        });
    }

    void processPrimary(DefaultListableBeanFactory beanFactory,
            BeanDefinition beanDefinition, String beanName, Class<?> beanType) {
        String[] beanNamesForType = beanFactory.getBeanNamesForType(beanType);

        if (beanNamesForType.length == 2) {
            for (String beanNameForType : beanNamesForType) {
                if (beanNameForType.equals(beanName)) {
                    beanFactory.removeBeanDefinition(beanNameForType);
                } else {
                    beanFactory.removeBeanDefinition(beanNameForType);

                    GenericBeanDefinition replacementBeanDefinition =
                            new GenericBeanDefinition(beanDefinition);
                    replacementBeanDefinition.setPrimary(false);
                    replacementBeanDefinition.setLazyInit(true);
                    beanFactory.registerBeanDefinition(beanNameForType,
                            replacementBeanDefinition);
                }
            }
        }
    }

    private boolean isController(Class<?> beanType) {
        Controller controller = beanType.getAnnotation(Controller.class);

        if (controller == null) {
            Annotation[] annotations = beanType.getAnnotations();

            for (Annotation annotation : annotations) {
                Class<? extends Annotation> annotationType = annotation.annotationType();

                controller = annotationType.getAnnotation(Controller.class);

                if (controller != null) {
                    break;
                }

            }
        }

        return controller != null;
    }

}


text:
@implementation CBStoreHouseTransitionAnimator

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.duration = 0.55;
        self.rotateAngle = M_PI_4;
        self.relativeDelayLeftView = 0.09;
        self.relativeDelayRightView = 0.12;
    }
    return self;
}

-(void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{
    UIView *containerView = [transitionContext containerView];
    UIViewController *fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    toViewController.view.layer.zPosition = fromViewController.view.layer.zPosition + 1;

    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;

    CATransform3D leftViewTransfrom = CATransform3DIdentity;
    leftViewTransfrom.m34 = 1.0 / -500;
    leftViewTransfrom = CATransform3DRotate(leftViewTransfrom, self.rotateAngle, 0, 1, 0);
    leftViewTransfrom = CATransform3DTranslate(leftViewTransfrom, -screenWidth/2, 0, -screenWidth/2);

    CATransform3D rightViewTransfrom = CATransform3DIdentity;
    rightViewTransfrom.m34 = 1.0 / -500;
    rightViewTransfrom = CATransform3DTranslate(rightViewTransfrom, screenWidth, 0, 0);
    rightViewTransfrom = CATransform3DTranslate(rightViewTransfrom, -screenWidth/2, 0, 0);
    rightViewTransfrom = CATransform3DRotate(rightViewTransfrom, -self.rotateAngle, 0, 1, 0);
    rightViewTransfrom = CATransform3DTranslate(rightViewTransfrom, screenWidth/2, 0, 0);

    if (self.type == AnimationTypePush) {
        [containerView insertSubview:toViewController.view belowSubview:fromViewController.view];
        toViewController.view.layer.transform = rightViewTransfrom;
        fromViewController.view.alpha = 1;

        [UIView animateKeyframesWithDuration:self.duration delay:0.0 options:0 animations:^{

            [UIView addKeyframeWithRelativeStartTime:0 relativeDuration:1 animations:^{
                fromViewController.view.layer.transform = leftViewTransfrom;
                fromViewController.view.alpha = 0;
            }];

            [UIView addKeyframeWithRelativeStartTime:self.relativeDelayLeftView/self.duration relativeDuration:1 - self.relativeDelayLeftView/self.duration animations:^{
                toViewController.view.layer.transform = CATransform3DIdentity;
            }];

        } completion:^(BOOL finished) {
            if ([transitionContext transitionWasCancelled])
                [transitionContext completeTransition:NO];
            else
                [transitionContext completeTransition:YES];
        }];
    }
    else {
        [containerView insertSubview:toViewController.view belowSubview:fromViewController.view];
        toViewController.view.layer.transform = leftViewTransfrom;
        toViewController.view.alpha = 0;

        [UIView animateKeyframesWithDuration:self.duration delay:0.0 options:0 animations:^{

            [UIView addKeyframeWithRelativeStartTime:0 relativeDuration:1 animations:^{
                fromViewController.view.layer.transform = rightViewTransfrom;
            }];

            [UIView addKeyframeWithRelativeStartTime:self.relativeDelayRightView/self.duration relativeDuration:1 - self.relativeDelayRightView/self.duration animations:^{
                toViewController.view.layer.transform = CATransform3DIdentity;
            }];

            [UIView addKeyframeWithRelativeStartTime:0 relativeDuration:0.85 animations:^{
                toViewController.view.alpha = 0.5;
            }];

            [UIView addKeyframeWithRelativeStartTime:0.85 relativeDuration:0.15 animations:^{
                toViewController.view.alpha = 1;
            }];

        } completion:^(BOOL finished) {
            if ([transitionContext transitionWasCancelled])
                [transitionContext completeTransition:NO];
            else
                [transitionContext completeTransition:YES];
        }];
    }
}

-(NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext
{
    return self.duration;
}

@end

#pragma mark - Interactive Transitioning

@implementation CBStoreHouseTransitionInteractiveTransition

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.percentageAdjustFactor = 2.5;
    }
    return self;
}

- (void)attachToViewController:(UIViewController*)viewController
{
    self.parentViewController = viewController;
    UIScreenEdgePanGestureRecognizer *edgePanRecognizer = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(handleEdgePanRecognizer:)];
    edgePanRecognizer.edges = UIRectEdgeLeft;
    [self.parentViewController.view addGestureRecognizer:edgePanRecognizer];
}

- (void)handleEdgePanRecognizer:(UIScreenEdgePanGestureRecognizer*)recognizer
{
    NSAssert(self.parentViewController != nil, @"parent view controller was not set");
    CGFloat progress = [recognizer translationInView:self.parentViewController.view].x / self.parentViewController.view.bounds.size.width / self.percentageAdjustFactor;
    progress = MIN(1.0, MAX(0.0, progress));
    switch (recognizer.state) {
        case UIGestureRecognizerStateBegan:
            [self.parentViewController.navigationController popViewControllerAnimated:YES];
            break;
        case UIGestureRecognizerStateChanged: {
            [self updateInteractiveTransition:progress];
            break;
        }
        default:
            if ([recognizer velocityInView:self.parentViewController.view].x >= 0) {
                [self finishInteractiveTransition];
                [self.parentViewController.view removeGestureRecognizer:recognizer];
            }
            else
                [self cancelInteractiveTransition];
            break;
    }
}

@end


text:
package soot.block.overrides;

import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import soot.tile.overrides.TileEntityMixerBottomImproved;
import soot.util.EmberUtil;
import soot.util.IMigrateable;
import soot.util.MigrationUtil;
import teamroots.embers.RegistryManager;
import teamroots.embers.block.BlockMixer;
import teamroots.embers.item.ItemTinkerHammer;
import teamroots.embers.tileentity.TileEntityMixerTop;

import javax.annotation.Nullable;

public class BlockMixerImproved extends BlockMixer implements IMigrateable {
    public BlockMixerImproved(Material material, String name, boolean addToTab) {
        super(material, name, addToTab);
        EmberUtil.overrideRegistryLocation(this,name);
    }

    @Override
    public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing facing, float x, float y, float z) {
        ItemStack heldItem = player.getHeldItem(hand);
        if (heldItem.getItem() instanceof ItemTinkerHammer && state.getBlock() == this){
            MigrationUtil.migrateBlock(world,pos);
            return true;
        }
        return super.onBlockActivated(world, pos, state, player, hand, facing, x, y, z);
    }

    @Nullable
    @Override
    public TileEntity createNewTileEntity(World worldIn, int meta) {
        if(meta == 1)
            return new TileEntityMixerTop();
        else
            return new TileEntityMixerBottomImproved();
    }

    @Override
    public IBlockState getReplacementState(IBlockState state) {
        return RegistryManager.mixer.getDefaultState().withProperty(isTop,state.getValue(isTop));
    }
}


text:
namespace DAVA
{
class QtAction : public QAction
{
public:
    QtAction(ContextAccessor* accessor, QObject* parent = nullptr);
    QtAction(ContextAccessor* accessor, const QString& text, QObject* parent = nullptr);
    QtAction(ContextAccessor* accessor, const QIcon& icon, const QString& text, QObject* parent = nullptr);

    enum eActionState
    {
        Enabled, // call back should return Any that can be casted to bool
        Visible,
        Checked,
        Text, // String
        Tooltip, // String
        Icon // String
    };

    void SetStateUpdationFunction(eActionState state, const FieldDescriptor& fieldDescr, const Function<Any(const Any&)>& fn);
    void SetStateUpdationFunction(eActionState state, const Reflection& model, const FastName& name, const Function<Any(const Any&)>& fn);

private:
    void OnFieldValueChanged(const Any& value, eActionState state);
    void OnActionTriggered(bool checked, eActionState state, const FieldDescriptor& fieldDescr);

private:
    FieldBinder fieldBinder;
    UnorderedMap<eActionState, Function<Any(const Any&)>> functorsMap;
};

class QtActionSeparator : public QAction
{
public:
    QtActionSeparator(const QString& name, QObject* parent = nullptr);
};
} // namespace DAVA


text:
package bboss.org.jgroups.protocols.pbcast;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Vector;

import bboss.org.jgroups.Address;
import bboss.org.jgroups.Event;
import bboss.org.jgroups.Message;
import bboss.org.jgroups.View;
import bboss.org.jgroups.ViewId;
import bboss.org.jgroups.util.Digest;
import bboss.org.jgroups.util.Promise;

/**
 * @author Bela Ban
 * @version $Id: ParticipantGmsImpl.java,v 1.38 2010/03/05 09:04:35 belaban Exp $
 */
public class ParticipantGmsImpl extends ServerGmsImpl {
    private final Vector<Address>   suspected_mbrs=new Vector<Address>(11);
    private final Promise<Boolean>  leave_promise=new Promise<Boolean>();

    public ParticipantGmsImpl(GMS g) {
        super(g);
    }

    public void init() throws Exception {
        super.init();
        suspected_mbrs.removeAllElements();
        leave_promise.reset();
    }

    public void join(Address mbr, boolean useFlushIfPresent) {
        wrongMethod("join");
    }

    public void joinWithStateTransfer(Address mbr,boolean useFlushIfPresent) {
        wrongMethod("join");
    }

    /**
     * Loop: determine coord. If coord is me --> handleLeave().
     * Else send handleLeave() to coord until success
     */
    public void leave(Address mbr) {
        Address coord;
        int max_tries=3;
        Boolean result;

        leave_promise.reset();

        if(mbr.equals(gms.local_addr))
            leaving=true;

        while((coord=gms.determineCoordinator()) != null && max_tries-- > 0) {
            if(gms.local_addr.equals(coord)) {            // I'm the coordinator
                gms.becomeCoordinator();
                // gms.getImpl().handleLeave(mbr, false);    // regular leave
                gms.getImpl().leave(mbr);    // regular leave
                return;
            }

            if(log.isDebugEnabled()) log.debug("sending LEAVE request to " + coord + " (local_addr=" + gms.local_addr + ")");
            sendLeaveMessage(coord, mbr);
            result=leave_promise.getResult(gms.leave_timeout);
            if(result != null)
                break;
        }
        gms.becomeClient();
    }

    /** In case we get a different JOIN_RSP from a previous JOIN_REQ sent by us (as a client), we simply apply the
     * new view if it is greater than ours
     *
     * @param join_rsp
     */
    public void handleJoinResponse(JoinRsp join_rsp) {
        View v=join_rsp.getView();
        ViewId tmp_vid=v != null? v.getVid() : null;
        if(tmp_vid != null && gms.view_id != null && tmp_vid.compareTo(gms.view_id) > 0) {
            gms.installView(v);
        }
    }

    public void handleLeaveResponse() {
        leave_promise.setResult(true);  // unblocks thread waiting in leave()
    }

    public void suspect(Address mbr) {
        Collection<Request> suspected=new LinkedHashSet<Request>(1);
        suspected.add(new Request(Request.SUSPECT,mbr,true));
        handleMembershipChange(suspected);
    }

    /** Removes previously suspected member from list of currently suspected members */
    public void unsuspect(Address mbr) {
        if(mbr != null)
            suspected_mbrs.remove(mbr);
    }

    public void handleMembershipChange(Collection<Request> requests) {
        Collection<Address> suspectedMembers=new LinkedHashSet<Address>(requests.size());
        for(Request req: requests) {
            if(req.type == Request.SUSPECT)
                suspectedMembers.add(req.mbr);
        }

        if(suspectedMembers.isEmpty())
            return;

        for(Address mbr: suspectedMembers) {
            if(!suspected_mbrs.contains(mbr))
                suspected_mbrs.addElement(mbr);
        }

        if(log.isDebugEnabled())
            log.debug("suspected members=" + suspectedMembers + ", suspected_mbrs=" + suspected_mbrs);

        if(wouldIBeCoordinator()) {
            if(log.isDebugEnabled())
                log.debug("members are " + gms.members + ", coord=" + gms.local_addr + ": I'm the new coord !");

            suspected_mbrs.removeAllElements();
            gms.becomeCoordinator();
            for(Address mbr: suspectedMembers) {
                gms.getViewHandler().add(new Request(Request.SUSPECT, mbr, true));
                gms.ack_collector.suspect(mbr);
            }
        }
    }

    /**
     * If we are leaving, we have to wait for the view change (last msg in the current view) that
     * excludes us before we can leave.
     * @param new_view The view to be installed
     * @param digest   If view is a MergeView, digest contains the seqno digest of all members and has to
     *                 be set by GMS
     */
    public void handleViewChange(View new_view, Digest digest) {
        Vector<Address> mbrs=new_view.getMembers();
        suspected_mbrs.removeAllElements();
        if(leaving && !mbrs.contains(gms.local_addr)) { // received a view in which I'm not member: ignore
            return;
        }
        gms.installView(new_view, digest);
    }

    /* ---------------------------------- Private Methods --------------------------------------- */

    /**
     * Determines whether this member is the new coordinator given a list of suspected members.  This is
     * computed as follows: the list of currently suspected members (suspected_mbrs) is removed from the current
     * membership. If the first member of the resulting list is equals to the local_addr, then it is true,
     * otherwise false. Example: own address is B, current membership is {A, B, C, D}, suspected members are {A,
     * D}. The resulting list is {B, C}. The first member of {B, C} is B, which is equal to the
     * local_addr. Therefore, true is returned.
     */
    boolean wouldIBeCoordinator() {
        Address new_coord;
        Vector<Address> mbrs=gms.members.getMembers(); // getMembers() returns a *copy* of the membership vector
        mbrs.removeAll(suspected_mbrs);
        if(mbrs.size() < 1) return false;
        new_coord=mbrs.firstElement();
        return gms.local_addr.equals(new_coord);
    }

    void sendLeaveMessage(Address coord, Address mbr) {
        Message msg=new Message(coord, null, null);
        msg.setFlag(Message.OOB);
        GMS.GmsHeader hdr=new GMS.GmsHeader(GMS.GmsHeader.LEAVE_REQ, mbr);

        msg.putHeader(gms.getId(), hdr);
        gms.getDownProtocol().down(new Event(Event.MSG, msg));
    }

    /* ------------------------------ End of Private Methods ------------------------------------ */

}


text:
<?php

namespace Blackshawk\SymfonyReactorBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    protected static $runCount = 0;

    public function indexAction($name)
    {
        self::$runCount++;

        return $this->render('BlackshawkSymfonyReactorBundle:Default:index.html.twig', array('name' => $name, 'runcount' => self::$runCount));
    }
}


text: body{background-color:#005081;text-align:center;float:center;}


text:
/* eslint-disable no-await-in-loop */

import cache from 'webext-storage-cache';
import React from 'dom-chef';
import select from 'select-dom';
import clockIcon from 'octicon/clock.svg';
import features from '../libs/features';
import * as api from '../libs/api';
import observeElement from '../libs/simplified-element-observer';
import {getUsername} from '../libs/utils';

interface Commit {
	url: string;
	sha: string;
}

const timeFormatter = new Intl.DateTimeFormat('en-US', {
	hour: 'numeric',
	minute: 'numeric',
	hour12: false
});

async function loadCommitPatch(commitUrl: string): Promise<string> {
	const {textContent} = await api.v3(commitUrl, {
		json: false,
		headers: {
			Accept: 'application/vnd.github.v3.patch'
		}
	});

	return textContent;
}

const getLastCommitDate = cache.function(async (login: string): Promise<string | false> => {
	for await (const page of api.v3paginated(`users/${login}/events`)) {
		for (const event of page as any) { // eslint-disable-line @typescript-eslint/no-explicit-any
			if (event.type !== 'PushEvent') {
				continue;
			}

			// Start from the latest commit, which is the last one in the list
			for (const commit of event.payload.commits.reverse() as Commit[]) {
				const response = await api.v3(commit.url, {ignoreHTTPStatus: true});
				// Commits might not exist anymore even if they are listed in the events
				// This can happen if the repository was deleted so we can also skip all other commits
				if (response.httpStatus === 404) {
					break;
				}

				if (!response.ok) {
					throw await api.getError(response);
				}

				// `response.author` only appears if GitHub can match the email to a GitHub user
				if (response.author?.id !== event.actor.id) {
					continue;
				}

				const patch = await loadCommitPatch(commit.url);
				// The patch of merge commits doesn't include the commit sha so the date might be from another user
				if (patch.startsWith(`From ${commit.sha} `)) {
					return /^Date: (.*)$/m.exec(patch)?.[1] ?? false;
				}
			}
		}
	}

	return false;
}, {
	expiration: 10,
	cacheKey: ([login]) => __featureName__ + ':' + login
});

function parseOffset(date: string): number {
	const [, hourString, minuteString] = (/([-+]\d\d)(\d\d)$/).exec(date) ?? [];

	const hours = parseInt(hourString, 10);
	const minutes = parseInt(minuteString, 10);
	return (hours * 60) + (hours < 0 ? -minutes : minutes);
}

function init(): void {
	const hovercard = select('.js-hovercard-content > .Popover-message')!;

	observeElement(hovercard, async () => {
		if (hovercard.childElementCount === 0 || select.exists('.rgh-local-user-time', hovercard)) {
			return;
		}

		const login = select<HTMLAnchorElement>('a[data-octo-dimensions="link_type:profile"]', hovercard)?.pathname.slice(1);
		if (!login || login === getUsername()) {
			return;
		}

		const placeholder = Guessing local time…;
		const container = (

				{clockIcon()} {placeholder}

		);

		// Adding the time element might change the height of the hovercard and thus break its positioning
		const hovercardHeight = hovercard.offsetHeight;
		select('div.d-flex.mt-3 > div.overflow-hidden.ml-3:not([data-hovercard-type="contributors"]', hovercard)!.append(container);

		if (hovercard.matches('.Popover-message--bottom-right, .Popover-message--bottom-left')) {
			const diff = hovercard.offsetHeight - hovercardHeight;
			if (diff > 0) {
				const parent = hovercard.parentElement!;
				const top = parseInt(parent.style.top, 10);
				parent.style.top = `${top - diff}px`;
			}
		}

		const date = await getLastCommitDate(login);
		if (!date) {
			placeholder.textContent = '-';
			container.title = 'Timezone couldn't be determined from their last commits';
			return;
		}

		const now = new Date();
		now.setMinutes(parseOffset(date) + now.getTimezoneOffset() + now.getMinutes());
		placeholder.textContent = timeFormatter.format(now);
		container.title = `Timezone guessed from their last commit: ${date}`;
	});
}

features.add({
	id: __featureName__,
	description: 'Shows the user local time in their hovercard (based on their last commit).',
	screenshot: 'https://user-images.githubusercontent.com/1402241/69863648-ef449180-12cf-11ea-8f36-7c92fc487f31.gif',
	load: features.onDomReady,
	init
});


text:
clever-elixir-algorithms
========================

Elixir implementations of code from Brownlee's book

[Clever Algorithms: Nature-Inspired Programming Recipes](http://www.cleveralgorithms.com/)


text:
$(document).ready(function() {

	$(".inspect").hide();
	$(".screenshot").hide();

	$(".inspect-show").live("click", function() {
		var renderElement = $(this).closest("tr").next(".inspect");

		if(renderElement.is(":visible")) {
			renderElement.slideUp(100);
		} else {
			renderElement.slideDown(100);
		}

	});

	$(".show-window").click(function() {
		$(".screenshot").toggle();
	});

});


text:
package com.aimx.androidpubnub;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import pubnub.PubnubCrypto;
/**
 * PubNub 3.0 Real-time Push Cloud API
 *
 * @author Stephen Blum
 * @package pubnub
 */
public class Pubnub {
    private String ORIGIN        = "pubsub.pubnub.com";
    private String PUBLISH_KEY   = "";
    private String SUBSCRIBE_KEY = "";
    private String SECRET_KEY    = "";
    private String CIPHER_KEY    = "";
    private boolean SSL          = false;

    /**
     * Added constructor to share cipher_key
     * With cipher_key (plaintext)
     *
     * @param String Publish Key.
     * @param String Subscribe Key.
     * @param String Secret Key.
     * @param String Cipher Key.
     * @param boolean SSL Enabled.
     */
    public Pubnub(
        String publish_key,
        String subscribe_key,
        String secret_key,
        String cipher_key,
        boolean ssl_on
    ) {
        this.init( publish_key, subscribe_key, secret_key, cipher_key, ssl_on );
    }

    /**
     * PubNub 3.0
     *
     * Prepare PubNub Class State.
     *
     * @param String Publish Key.
     * @param String Subscribe Key.
     * @param String Secret Key.
     * @param boolean SSL Enabled.
     */
    public Pubnub(
        String publish_key,
        String subscribe_key,
        String secret_key,
        boolean ssl_on
    ) {
        this.init( publish_key, subscribe_key, secret_key, "", ssl_on );
    }

    /**
     * PubNub 2.0 Compatibility
     *
     * Prepare PubNub Class State.
     *
     * @param String Publish Key.
     * @param String Subscribe Key.
     */
    public Pubnub(
        String publish_key,
        String subscribe_key
    ) {
        this.init( publish_key, subscribe_key, "", "", false );
    }

    /**
     * PubNub 3.0 without SSL
     *
     * Prepare PubNub Class State.
     *
     * @param String Publish Key.
     * @param String Subscribe Key.
     * @param String Secret Key.
     */
    public Pubnub(
        String publish_key,
        String subscribe_key,
        String secret_key
    ) {
        this.init( publish_key, subscribe_key, secret_key, "", false );
    }

    /**
     * Init
     *
     * Prepare PubNub Class State.
     *
     * @param String Publish Key.
     * @param String Subscribe Key.
     * @param String Secret Key.
     * @param String Cipher Key.
     * @param boolean SSL Enabled.
     */
    public void init(
        String publish_key,
        String subscribe_key,
        String secret_key,
        String cipher_key,
        boolean ssl_on
    ) {
        this.PUBLISH_KEY   = publish_key;
        this.SUBSCRIBE_KEY = subscribe_key;
        this.SECRET_KEY    = secret_key;
        this.CIPHER_KEY    = cipher_key;
        this.SSL           = ssl_on;

        // SSL On?
        if (this.SSL) {
            this.ORIGIN = "https://" + this.ORIGIN;
        }
        else {
            this.ORIGIN = "http://" + this.ORIGIN;
        }
    }

    /**
     * Publish
     *
     * Send a message to a channel.
     *
     * @param String channel name.
     * @param JSONObject message.
     * @return JSONArray.
     */
    public JSONArray publish( String channel, JSONObject message ) {
        HashMap<String, Object> args = new HashMap<String, Object>(2);
        args.put("channel", channel);
        args.put("message", message);
        return publish( args );
    }

    /**
     * Publish
     *
     * Send a message to a channel.
     *
     * @param HashMap<String, Object> containing channel name, message.
     * @return JSONArray.
     */
    public JSONArray publish( HashMap<String, Object> args ) {

        String channel = (String) args.get("channel");
        Object message =  args.get("message");

          if(message instanceof JSONObject)
          {
              JSONObject obj=(JSONObject)message;
              if(this.CIPHER_KEY.length() > 0){
                  // Encrypt Message
                  PubnubCrypto pc = new PubnubCrypto(this.CIPHER_KEY);
                  message = pc.encrypt(obj);
              }else
              {
              message=obj;
              }
              //System.out.println();
          }else if(message instanceof String )
          {
              String obj=(String)message;
              if(this.CIPHER_KEY.length() > 0){
                  // Encrypt Message
                  PubnubCrypto pc = new PubnubCrypto(this.CIPHER_KEY);
                  try {
                      message = pc.encrypt(obj);
                  } catch (Exception e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }
              }else
              {
              message=obj;
              }

              message="\""+message+"\"";

          }else if(message instanceof JSONArray)
          {
              JSONArray obj=(JSONArray)message;

              if(this.CIPHER_KEY.length() > 0){
                  // Encrypt Message
                  PubnubCrypto pc = new PubnubCrypto(this.CIPHER_KEY);
                  message = pc.encryptJSONArray(obj);
              }
              else
              {
              message=obj;
              }

              System.out.println();

          }

        // Generate String to Sign
        String signature = "0";

        if (this.SECRET_KEY.length() > 0) {
            StringBuilder string_to_sign = new StringBuilder();
            string_to_sign
                .append(this.PUBLISH_KEY)
                .append('/')
                .append(this.SUBSCRIBE_KEY)
                .append('/')
                .append(this.SECRET_KEY)
                .append('/')
                .append(channel)
                .append('/')
                .append(message.toString());

            // Sign Message
            signature = PubnubCrypto.getHMacSHA256(this.SECRET_KEY, string_to_sign.toString());
        }

        // Build URL
        List<String> url = new ArrayList<String>();
        url.add("publish");
        url.add(this.PUBLISH_KEY);
        url.add(this.SUBSCRIBE_KEY);
        url.add(signature);
        url.add(channel);
        url.add("0");
        url.add(message.toString());

        // Return JSONArray
        return _request(url);
    }

    /**
     * Subscribe
     *
     * Listen for a message on a channel.
     *
     * @param String channel name.
     * @param Callback function callback.
     */
    public void subscribe( String channel, Callback callback ) {
        HashMap<String, Object> args = new HashMap<String, Object>(2);
        args.put("channel", channel);
        args.put("callback", callback);
        subscribe( args );
    }
    /**
     * Subscribe
     *
     * Listen for a message on a channel.
     *
     * @param HashMap<String, Object> containing channel name, function callback.
     */
    public void subscribe( HashMap<String, Object> args ) {
        args.put("timetoken", "0");
        this._subscribe( args );
    }

    /**
     * Subscribe - Private Interface
     *
     * Patch provided by petereddy on GitHub
     *
     * @param HashMap<String, Object> containing channel name, function callback, timetoken.
     */
    private void _subscribe( HashMap<String, Object> args ) {

        String   channel = (String) args.get("channel");
        Callback callback = (Callback) args.get("callback");
        String   timetoken = (String) args.get("timetoken");
        if(channel == null||channel== "")
        {
            JSONArray jsono = new JSONArray();

            try { jsono.put("Invalid Channel."); }
            catch (Exception jsone) {}
            return;
        }
        if(callback == null)
        {
            JSONArray jsono = new JSONArray();

            try { jsono.put("Invalid Callback."); }
            catch (Exception jsone) {}
            return;
        }
        while (true) {
            try {
                // Build URL
                List<String> url = java.util.Arrays.asList(
                    "subscribe", this.SUBSCRIBE_KEY, channel, "0", timetoken
                );

                // Wait for Message
                JSONArray response = _request(url);

                JSONArray messages = response.optJSONArray(0);

                // Update TimeToken
                if (response.optString(1).length() > 0)
                    timetoken = response.optString(1);

                // Run user Callback and Reconnect if user permits. If
                // there's a timeout then messages.length() == 0.
                for ( int i = 0; messages.length() > i; i++ ) {
                     JSONObject message = messages.optJSONObject(i);

                     if(message == null)
                     {
                         JSONArray arr=    messages.optJSONArray(i);
                         if(arr == null)
                         {
                             String msgs=messages.getString(0);

                             if(this.CIPHER_KEY.length() > 0){
                                 PubnubCrypto pc = new PubnubCrypto(this.CIPHER_KEY);
                                 msgs=pc.decrypt(msgs);

                             }
                             if(callback !=null)
                             {
                                 callback.execute(msgs);
                             }
                         }
                         else
                         {
                             if(this.CIPHER_KEY.length() > 0){
                                 PubnubCrypto pc = new PubnubCrypto(this.CIPHER_KEY);

                                 // System.out.println("ARRAY::"+arr.toString());
                                 arr=pc.decryptJSONArray(arr); ;
                             }
                             if(callback !=null)
                             {
                                 callback.execute(arr);
                             }

                         }

                     }else
                     {
                         if(this.CIPHER_KEY.length() > 0){
                             // Decrypt Message
                             PubnubCrypto pc = new PubnubCrypto(this.CIPHER_KEY);
                             message = pc.decrypt(message);
                         }
                         if(callback !=null)
                         {
                             callback.execute(message);
                         }
                     }
                }
            }
            catch (Exception e) {
                try { Thread.sleep(1000); }
                catch(InterruptedException ie) {}
            }
        }
    }

    /**
     * History
     *
     * Load history from a channel.
     *
     * @param String channel name.
     * @param int limit history count response.
     * @return JSONArray of history.
     */
    public JSONArray history( String channel, int limit ) {
        HashMap<String, Object> args = new HashMap<String, Object>(2);
        args.put("channel", channel);
        args.put("limit", limit);
        return history( args );
    }

    /**
     * History
     *
     * Load history from a channel.
     *
     * @param HashMap<String, Object> containing channel name, limit history count response.
     * @return JSONArray of history.
     */
    public JSONArray history( HashMap<String, Object> args ) {

        String channel = (String) args.get("channel");
        int limit = Integer.parseInt(args.get("limit").toString());

        List<String> url = new ArrayList<String>();

        url.add("history");
        url.add(this.SUBSCRIBE_KEY);
        url.add(channel);
        url.add("0");
        url.add(Integer.toString(limit));

        if (this.CIPHER_KEY.length() > 0) {
            // Decrpyt Messages
            PubnubCrypto pc = new PubnubCrypto(this.CIPHER_KEY);
            return pc.decryptJSONArray(_request(url));
        } else {
            return _request(url);
        }
    }

    /**
     * Time
     *
     * Timestamp from PubNub Cloud.
     *
     * @return double timestamp.
     */
    public double time() {
        List<String> url = new ArrayList<String>();

        url.add("time");
        url.add("0");

        JSONArray response = _request(url);
        return response.optDouble(0);
    }

    /**
     * UUID
     *
     * 32 digit UUID generation at client side.
     *
     * @return String uuid.
     */
    public static String uuid() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString();
    }

    /**
     * Request URL
     *
     * @param List<String> request of url directories.
     * @return JSONArray from JSON response.
     */
    private JSONArray _request(List<String> url_components) {
        String   json         = "";
        StringBuilder url     = new StringBuilder();
        Iterator<String> url_iterator = url_components.iterator();

        url.append(this.ORIGIN);

        // Generate URL with UTF-8 Encoding
        while (url_iterator.hasNext()) {
            try {
                String url_bit = (String) url_iterator.next();
                url.append("/").append(_encodeURIcomponent(url_bit));
            }
            catch(Exception e) {
                e.printStackTrace();
                JSONArray jsono = new JSONArray();
                try { jsono.put("Failed UTF-8 Encoding URL."); }
                catch (Exception jsone) {}
                return jsono;
            }
        }

        try {
            PubnubHttpRequest request = new PubnubHttpRequest(url.toString());
            FutureTask<String> task = new FutureTask<String>(request);
            Thread t = new Thread(task);
            t.start();
            try
            {
               json = task.get();
            }
            catch (Exception e)
            {
                JSONArray jsono = new JSONArray();

                try { jsono.put("Failed to Concurrent HTTP Request."); }
                catch (Exception jsone) {}

                e.printStackTrace();
                System.out.println(e);

                return jsono;
            }

        } catch (Exception e) {

            JSONArray jsono = new JSONArray();

            try { jsono.put("Failed JSONP HTTP Request."); }
            catch (Exception jsone) {}

            e.printStackTrace();
            System.out.println(e);

            return jsono;
        }

        // Parse JSON String
        try { return new JSONArray(json); }
        catch (Exception e) {
            JSONArray jsono = new JSONArray();

            try { jsono.put("Failed JSON Parsing."); }
            catch (Exception jsone) {}

            e.printStackTrace();
            System.out.println(e);

            // Return Failure to Parse
            return jsono;
        }
    }

    private class PubnubHttpRequest implements Callable<String> {

        String url;

        public PubnubHttpRequest(String url){
            this.url = url;
        }

        @Override
        public String call() throws Exception {
            // Prepare request
            String     line    = "", json = "";
            HttpClient httpclient = new DefaultHttpClient();
            HttpUriRequest request = new HttpGet(url);
            request.setHeader("V", "3.1");
            request.setHeader("User-Agent", "Android");
            request.setHeader("Accept-Encoding", "gzip");

            // Execute request
            HttpResponse response;
            response = httpclient.execute(request);

            HttpEntity entity = response.getEntity();
            if (entity != null) {

                // A Simple JSON Response Read
                InputStream instream = entity.getContent();
                BufferedReader reader = null;

                // Gzip decoding
                Header contentEncoding = response.getFirstHeader("Content-Encoding");
                if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                    reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(instream)));
                } else {
                    reader = new BufferedReader(new InputStreamReader(instream));
                }

                // Read JSON Message
                while ((line = reader.readLine()) != null) { json += line; }
                reader.close();
            }

            return json;
        }
    }

    private String _encodeURIcomponent(String s) {
        StringBuilder o = new StringBuilder();
        for (char ch : s.toCharArray()) {
            if (isUnsafe(ch)) {
                o.append('%');
                o.append(toHex(ch / 16));
                o.append(toHex(ch % 16));
            }
            else o.append(ch);
        }
        return o.toString();
    }

    private char toHex(int ch) {
        return (char)(ch < 10 ? '0' + ch : 'A' + ch - 10);
    }

    private boolean isUnsafe(char ch) {
        return " ~`!@#$%^&*()+=[]\\{}|;':\",./<>?ɂ顶".indexOf(ch) >= 0;
    }
}


text:
require 'spec_helper'

describe "User pages" do
  subject { page }

  describe "index" do
    let(:user) { FactoryGirl.create(:user) }

    before(:each) do
      sign_in user
      visit users_path
    end

    it { should have_title('All users') }
    it { should have_content('All users') }

    describe "pagination" do
      before(:all) { 30.times { FactoryGirl.create(:user) } }
      after(:all) { User.delete_all }

      it "should list each user" do
        User.paginate(page: 1).each do |user|
          expect(page).to have_selector('li', text: user.name)
        end
      end
    end

    describe "delete links" do
      it { should_not have_link('delete') }

      describe "as an admin user" do
        let(:admin) { FactoryGirl.create(:admin) }

        before do
          sign_in admin
          visit users_path
        end

        it { should have_link('delete', href: user_path(User.first)) }
        it "should be able to delete another user" do
          expect do
            click_link('delete', match: :first)
          end.to change(User, :count).by(-1)
        end
        it { should_not have_link('delete', href: user_path(admin)) }
      end
    end
  end

  describe "profile page" do
    let(:user) { FactoryGirl.create(:user) }

    let!(:m1) { FactoryGirl.create(:tweet, user: user, content: "Foo") }
    let!(:m2) { FactoryGirl.create(:tweet, user: user, content: "Bar") }

    before { visit user_path(user) }

    it { should have_content(user.name) }
    it { should have_title(user.name) }

    describe "tweets" do
      it { should have_content(m1.content) }
      it { should have_content(m2.content) }
      it { should have_content(user.tweets.count) }
    end

    describe "follow/unfollow buttons" do
      let(:other_user) { FactoryGirl.create(:user) }
      before { sign_in user }

      describe "following a user" do
        before { visit user_path(other_user) }

        it "should increment the followed user count" do
          expect do
            click_button "Follow"
          end.to change(user.followed_users, :count).by(1)
        end

        it "should increment the other user's followers count" do
          expect do
            click_button "Follow"
          end.to change(other_user.followers, :count).by(1)
        end

        describe "toggling the button" do
          before { click_button "Follow" }
          it { should have_xpath("//input[@value='Unfollow']") }
        end
      end

      describe "unfollowing a user" do
        before do
          user.follow!(other_user)
          visit user_path(other_user)
        end

        it "should decrement the followed user count" do
          expect do
            click_button "Unfollow"
          end.to change(user.followed_users, :count).by(-1)
        end

        it "should decrement the other user's followers count" do
          expect do
            click_button "Unfollow"
          end.to change(other_user.followers, :count).by(-1)
        end

        describe "toggling the button" do
          before { click_button "Unfollow" }
          it { should have_xpath("//input[@value='Follow']") }
        end
      end
    end
  end

  describe "Sign up" do
    before { visit signup_path }

    let(:submit) { "Create account" }

    it { should have_content('Create an account') }
    it { should have_title('Create an account') }

    describe "with invalid information" do
      it "should not create a user" do
        expect { click_button submit }.not_to change(User, :count)
      end
    end

    describe "with invalid email" do
      it "should display appropriate error message" do
        fill_in "Name",                with: "Example User"
        fill_in "E-mail",              with: "user_example.com"
        fill_in "Password",            with: "foobar"
        fill_in "Password (repeat)",   with: "foobar"
        click_button submit

        expect(page).to have_content('Email is invalid')
      end
    end

    describe "with valid information" do
      before do
        fill_in "Name",                with: "Example User"
        fill_in "E-mail",              with: "user@example.com"
        fill_in "Password",            with: "foobar"
        fill_in "Password (repeat)",   with: "foobar"
      end

      it "should create a user" do
        expect { click_button submit }.to change(User, :count).by(1)
      end

      describe "after saving the user" do
        before { click_button submit }
        let(:user) { User.find_by(email: "user@example.com") }

        it { should have_link('Sign out') }
        it { should have_title(user.name) }
        it { should have_selector('div.alert.alert-success', text: 'Welcome') }
      end
    end
  end

  describe "edit" do
    let(:user) { FactoryGirl.create(:user) }

    before do
      sign_in user
      visit edit_user_path(user)
    end

    describe "page" do
      it { should have_content("Update your profile") }
      it { should have_title("Edit profile") }
      it { should have_link("change", href: "https://gravatar.com/emails") }
    end

    describe "with invalid information" do
      before { click_button "Save changes" }

      it { should have_content('error') }
    end

    describe "with valid information" do
      let(:new_name) { "New name" }
      let(:new_email) { "new@exmaple.com" }

      before do
        fill_in "Name", with: new_name
        fill_in "E-mail", with: new_email
        fill_in "Password", with: user.password
        fill_in "Password (repeat)", with: user.password
        click_button "Save changes"
      end

      it { should have_title(new_name) }
      it { should have_selector('div.alert.alert-success') }
      it { should have_link('Sign out', href: signout_path) }
      specify { expect(user.reload.name).to eq new_name }
      specify { expect(user.reload.email).to eq new_email }
    end

    describe "cannot become an admin" do
      before do
        before { patch user_path(user) }
      end
    end
  end
end