text:
import functools
import inspect
import unittest

import end

try:
    import builtins
except ImportError:
    import __builtin__ as builtins
end

class SyntaxCheckTest(unittest.TestCase):
    def test_if(self):
        import cases.if_ok
        with self.assertRaises(SyntaxError):
            import cases.if_ng
        end
        with self.assertRaises(SyntaxError):
            import cases.if_else
        end
        # TODO: Fix this nested case.
        # with self.assertRaises(SyntaxError):
        #     import cases.if_nested
        # end
    end

    def test_while(self):
        import cases.while_ok
        with self.assertRaises(SyntaxError):
            import cases.while_ng
        end
        with self.assertRaises(SyntaxError):
            import cases.while_else
        end
    end

    def test_for(self):
        import cases.for_ok
        with self.assertRaises(SyntaxError):
            import cases.for_ng
        end
        with self.assertRaises(SyntaxError):
            import cases.for_else
        end
    end

    def test_try(self):
        import cases.try_ok
        with self.assertRaises(SyntaxError):
            import cases.try_ng
        end
        with self.assertRaises(SyntaxError):
            import cases.try_except
        end
        with self.assertRaises(SyntaxError):
            import cases.try_finally
        end
        with self.assertRaises(SyntaxError):
            import cases.try_else
        end
        # TODO: Fix this tricky case.
        # with self.assertRaises(SyntaxError):
        #     import cases.try_tricky
        # end
    end

    def test_with(self):
        import cases.with_ok
        with self.assertRaises(SyntaxError):
            import cases.with_ng
        end
    end

    def test_func(self):
        import cases.func_ok
        with self.assertRaises(SyntaxError):
            import cases.func_ng
        end
    end

    def test_class(self):
        import cases.class_ok
        with self.assertRaises(SyntaxError):
            import cases.class_ng
        end
    end

    def test_hooked_import(self):
        # It should work even if __import__ is hooked by someone else.
        saved_import = builtins.__import__
        @functools.wraps(saved_import)
        def my_import(*args, **kwargs):
            return saved_import(*args, **kwargs)
        end
        builtins.__import__ = my_import
        try:
            with self.assertRaises(SyntaxError) as cm:
                import cases.hooked_import
            end
            self.assertTrue('hooked_import.py' in str(cm.exception))
        finally:
            builtins.__import__ = saved_import
        end
    end

    def test_inspect_import(self):
        import cases.import_call
    end

    def test_stray_end(self):
        with self.assertRaises(SyntaxError):
            import cases.stray_end
        end
    end

    def test_regression_multi_bodies(self):
        import cases.multi_bodies
    end
end

if __name__ == '__main__':
    unittest.main()
end


text:
<!DOCTYPE html>

        <title>Resume</title>

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">

 <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/solarized-dark.min.css">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

 <meta name="generator" content="Hugo 0.32.2" />

        <meta charset="utf-8">

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

                    Resume

                    <button class="navbar-toggle" data-target=".navbar-collapse" data-toggle="collapse">

                    </button>

Home

Posts

Projects

Resume

Resume

Professional Attributes

Comfortable with customer-facing roles including support and documentation.

Experience running and developing on multiple flavors of Linux.

Strong understanding of the Web including, HTML, CSS, and JavaScript.

Analytical problem-solver, able to proactively address possible issues

Skilled in building excellent rapport with clients and team members

Uncanny ability to find bugs and delight in squashing them. Has google-fu.

Technical Skills

Languages: Ruby, JavaScript, PHP, HTML5, CSS3; React (in progress)

Frameworks: Rails, ActiveRecord, Sinatra, Bootstrap, Materialize

SaaS: Git/Github, Heroku, Amazon Web Services(AWS)

Databases: SQLite, PostgreSQL

TDD/BDD: RSpec, MiniTest (novice)

Operating Systems/Administration: Linux (Ubuntu, GalliumOS, CentOS, Mint), Windows (Server 2008|2012,  XP|7|8|10), SQL Server 2008|2012, Active Directory

Other: Documentation, Project Management, Google-Fu, and a love of finding, researching, and squashing bugs

Experience

Austin GiveCamp – Project Team: The Seed        2016

Project Team: The Seed | theseedaustin.org

GiveCamp is a weekend-long event where technology professionals donate their time to provide solutions for non-profit organizations. Since its inception in 2007, the GiveCamp program has provided benefits to hundreds of charities, worth millions of dollars of developer and designer time in services!

Languages/Skills: HTML/CSS, Project Management, QA

eStrategy Solutions – Austin, TX        2016

Consultant

Analyzed policies with regard to customer service and efficiency, recommending policy changes and process improvements as needed while aligning projects with client goals and expectations.

Languages/Skills: Project Management, Documentation

Lowe's Digital Challenge        2016

2nd Place Award

A Hackathon to develop a mobile application that helps Lowe's customers love where they live by connecting Lowe's digital channels with people, products, and services Lowe's offers to deliver customers' home improvement projects.

Languages/Skills: React, QA, Project Management

Austin Diversity hackathon        2016

Organizer

Women Who Code Austin's inaugural hackathon was a resounding success. We attracted a good number of people, were able to provide prizes and food to our participants, reached communities traditionally underrepresented in tech and had women for the majority of participants. In addition, we made the local news, and most importantly? We received reports from the participants of being really happy to have participated.

Languages/Skills: Mentoring, Troubleshooting, Project Management.

mindSHIFT Technologies – Austin, TX        2014 – 2016

Onboarding Engineer

Successfully overhauled region onboarding process - saving money and satisfying customer needs. Accountable for training of new onboarding engineers and project managers.

Languages/Skills: Project Management, System Administration, Documentation

Education

Flatiron School – New York, NY        2016 - 2017

Full Stack Web Development

Languages/Skills: Ruby, HTML/CSS, Object Orientation, SQL, Sinatra, Rails, JavaScript, React/Redux

hack reactor's makerprep at makersquare – Austin, TX        2016

Javascript Programming

Languages/Skills: HTML/CSS, JavaScript, jQuery, Bootstrap

University of Southern Mississippi – Hattiesburg, MS        2005

BSBA, Marketing

Languages/Skills: C++, Visual Basic .NET

Awards & Projects

Women Who Code Scholarship Winner         2016

Awarded a full scholarship to the Flatiron School Online Web Developer Program

© Tracy P Holmes. All rights reserved.

redpajama_set_name: RedPajamaGithub


text: python ../google-cloud-sdk/platform/google_appengine/dev_appserver.py ./web_app/ --host=0.0.0.0


text:
import type {JSONValue, ResponseBase} from 'react-client/src/ReactFlightClient';

import type {JSResourceReference} from 'JSResourceReference';

import type {ModuleMetaData} from 'ReactFlightDOMRelayClientIntegration';

export type ModuleReference<T> = JSResourceReference<T>;

import {
  parseModelString,
  parseModelTuple,
} from 'react-client/src/ReactFlightClient';

export {
  preloadModule,
  requireModule,
} from 'ReactFlightDOMRelayClientIntegration';

import {resolveModuleReference as resolveModuleReferenceImpl} from 'ReactFlightDOMRelayClientIntegration';

import isArray from 'shared/isArray';

export type {ModuleMetaData} from 'ReactFlightDOMRelayClientIntegration';

export type BundlerConfig = null;

export type UninitializedModel = JSONValue;

export type Response = ResponseBase;

export function resolveModuleReference<T>(
  bundlerConfig: BundlerConfig,
  moduleData: ModuleMetaData,
): ModuleReference<T> {
  return resolveModuleReferenceImpl(moduleData);
}

function parseModelRecursively(response: Response, parentObj, key, value) {
  if (typeof value === 'string') {
    return parseModelString(response, parentObj, key, value);
  }
  if (typeof value === 'object' && value !== null) {
    if (isArray(value)) {
      const parsedValue = [];
      for (let i = 0; i < value.length; i++) {
        (parsedValue: any)[i] = parseModelRecursively(
          response,
          value,
          '' + i,
          value[i],
        );
      }
      return parseModelTuple(response, parsedValue);
    } else {
      const parsedValue = {};
      for (const innerKey in value) {
        (parsedValue: any)[innerKey] = parseModelRecursively(
          response,
          value,
          innerKey,
          value[innerKey],
        );
      }
      return parsedValue;
    }
  }
  return value;
}

const dummy = {};

export function parseModel<T>(response: Response, json: UninitializedModel): T {
  return (parseModelRecursively(response, dummy, '', json): any);
}


text:
@class XPowerModePreferences;

@protocol XPowerModePreferencesDelegate <NSObject>
@optional
- (void)didXPowerModePreferencesSetup:(nonnull XPowerModePreferences *)preferences;
- (void)didXPowerModePreferencesUpdate:(nonnull XPowerModePreferences *)preferences;
- (void)didXPowerModeMenusSetup:(nonnull XPowerModePreferences *)preferences;
- (void)didXPowerModeMenusUpdate:(nonnull XPowerModePreferences *)preferences;
@end

@interface XPowerModePreferences : NSObject

@property (nullable, readonly) NSMenu * menu;
@property (nullable, weak) id<XPowerModePreferencesDelegate> delegate;

@property (nonatomic, assign) BOOL enabled;

+ (nonnull instancetype)standardPrefreneces;

- (void)initialize;

- (nullable id)objectForKeyedSubscript:(nonnull id)key;
- (void)setObject:(nullable id)obj forKeyedSubscript:(nonnull id <NSCopying>)key;

@end


text:
#include "SybCTnewDAImplTest.h"
#include "SybCTnewDAImpl.h"
#include "TestSuite.h"
#include "TimeStamp.h"
#include "Context.h"

//---- SybCTnewDAImplTest ----------------------------------------------------------------
SybCTnewDAImplTest::SybCTnewDAImplTest(TString tstrName)
	: TestCaseType(tstrName)
	, fbWasInitialized(false)
{
	StartTrace(SybCTnewDAImplTest.Ctor);
}

SybCTnewDAImplTest::~SybCTnewDAImplTest()
{
	StartTrace(SybCTnewDAImplTest.Dtor);
}

void SybCTnewDAImplTest::setUp()
{
	StartTrace(SybCTnewDAImplTest.setUp);
	fbWasInitialized = SybCTnewDAImpl::fgInitialized;
	if ( fbWasInitialized ) {
		SybCTnewDAImpl::Finis();
	}
}

void SybCTnewDAImplTest::tearDown()
{
	StartTrace(SybCTnewDAImplTest.tearDown);
	// set initialized state back here
	if ( fbWasInitialized ) {
		Anything anyConfig;
		if ( t_assert(coast::system::LoadConfigFile(anyConfig, "Config")) ) {
			t_assert(SybCTnewDAImpl::Init(anyConfig));
		}
	}
}

void SybCTnewDAImplTest::UninitializedExecTest()
{
	StartTrace(SybCTnewDAImplTest.UninitializedExecTest);

	Anything params;
	params["SybDBUser"] = GetConfig()["SybDBUser"].AsString();
	params["SybDBPW"] = GetConfig()["SybDBPW"].AsString();
	params["SybDBHost"] = GetConfig()["SybDBHost"].AsString();
	params["SybDBApp"] = "SybCTnewDAImplTest";
	params["SQL"] = "select au_fname, au_lname from authors where au_lname='Bennet'";

	TraceAny(params, "Input params:");
	Context ctx;
	Context::PushPopEntry<Anything> aEntry(ctx, "Params", params);

	SybCTnewDAImpl da("SybSearchTestCoded");
	da.Initialize("SybCTnewDAImpl");
	ParameterMapper	inpMapper("SybSearchTestCoded");
	inpMapper.Initialize("ParameterMapper");
	ResultMapper outMapper("SybSearchTestCoded");
	outMapper.Initialize("ResultMapper");

	ctx.Push("DataAccess", &da);
	t_assertm( da.Exec(ctx, &inpMapper, &outMapper) == false, "DataAccess should have failed due to uninitialized SybCTnewDAImpl!");
	ctx.Remove("DataAccess");

	TraceAny(ctx.GetTmpStore(), "resulting tmpstore: ");
}

void SybCTnewDAImplTest::InitTest()
{
	StartTrace(SybCTnewDAImplTest.InitTest);
	Anything anyCfg, anyTmp;
	anyCfg["SybaseModule"] = Anything(Anything::ArrayMarker());
	anyTmp = anyCfg["SybaseModule"];
	if ( t_assert(SybCTnewDAImpl::Init(anyCfg)) ) {
		assertEqualm(5L, SybCTnewDAImpl::fgListOfSybCT["Size"].AsLong(-1L), "default coded size should be 5");
		t_assertm(SybCTnewDAImpl::fgpPeriodicAction != NULL, "expected PeriodicAction to be initialized");
		t_assert(SybCTnewDAImpl::Finis());
		t_assertm(SybCTnewDAImpl::fgpPeriodicAction == NULL, "expected PeriodicAction to be terminated");
	}
	anyTmp["SybCTnewDAImpl"] = Anything(Anything::ArrayMarker());
	anyTmp = anyTmp["SybCTnewDAImpl"];
	anyTmp["ParallelQueries"] = 2L;
	if ( t_assert(SybCTnewDAImpl::Init(anyCfg)) ) {
		assertEqualm(2L, SybCTnewDAImpl::fgListOfSybCT["Size"].AsLong(-1L), "size should now be 2");
		t_assertm(SybCTnewDAImpl::fgpPeriodicAction != NULL, "expected PeriodicAction to be initialized");
		t_assert(SybCTnewDAImpl::Finis());
		t_assertm(SybCTnewDAImpl::fgpPeriodicAction == NULL, "expected PeriodicAction to be terminated");
	}
}

void SybCTnewDAImplTest::DoGetConnectionTest()
{
	StartTrace(SybCTnewDAImplTest.DoGetConnectionTest);
	Anything anyCfg, anyTmp;
	anyTmp["ParallelQueries"] = 2L;
	anyCfg["SybaseModule"]["SybCTnewDAImpl"] = anyTmp;
	if ( t_assert(SybCTnewDAImpl::Init(anyCfg)) ) {
		assertEqualm(2L, SybCTnewDAImpl::fgListOfSybCT["Size"].AsLong(-1L), "size should now be 2");
		SybCTnewDA *pSyb[3L] = { 0 };
		bool bIsOpen;
		String server, user;
		assertEqual(2L, SybCTnewDAImpl::fgListOfSybCT["Unused"].GetSize());
		t_assertm(SybCTnewDAImpl::DoGetConnection(pSyb[0L], bIsOpen, server, user), "expected valid connection");
		t_assertm( !bIsOpen, "expected unopen connection");
		t_assertm( pSyb[0L] != NULL, "expected valid SybCTnewDA *");
		assertEqual(1L, SybCTnewDAImpl::fgListOfSybCT["Unused"].GetSize());
		t_assertm(SybCTnewDAImpl::DoGetConnection(pSyb[1L], bIsOpen, server, user), "expected valid connection");
		t_assertm( !bIsOpen, "expected unopen connection");
		t_assertm( pSyb[1L] != NULL, "expected valid SybCTnewDA *");
		assertEqual(0L, SybCTnewDAImpl::fgListOfSybCT["Unused"].GetSize());
		// the following call would block so we can not test it easy
//		t_assertm( !SybCTnewDAImpl::DoGetConnection(pSyb[2L], bIsOpen, server, user), "expected invalid connection");
//		t_assertm( pSyb[2L] == NULL, "expected invalid SybCTnewDA *");
		t_assert(SybCTnewDAImpl::Finis());
	}
	if ( t_assert(SybCTnewDAImpl::Init(anyCfg)) ) {
		assertEqualm(2L, SybCTnewDAImpl::fgListOfSybCT["Size"].AsLong(-1L), "size should now be 2");
		assertEqual(2L, SybCTnewDAImpl::fgListOfSybCT["Unused"].GetSize());
		SybCTnewDA *pSyb[3L] = { 0 };
		bool bIsOpen;
		String server("SRV1"), user("USR1");
		t_assertm(SybCTnewDAImpl::DoGetConnection(pSyb[0L], bIsOpen, server, user), "expected valid connection");
		t_assertm( !bIsOpen, "expected unopen connection");
		t_assertm( pSyb[0L] != NULL, "expected valid SybCTnewDA *");
		SybCTnewDAImpl::DoPutbackConnection(pSyb[0L], true, server, user);
		assertEqual(1L, SybCTnewDAImpl::fgListOfSybCT["Unused"].GetSize());
		assertEqual(1L, SybCTnewDAImpl::fgListOfSybCT["Open"].GetSize());
		t_assertm(SybCTnewDAImpl::DoGetConnection(pSyb[0L], bIsOpen, server, user), "expected valid connection");
		t_assertm( bIsOpen, "expected open connection");
		t_assertm( pSyb[0L] != NULL, "expected valid SybCTnewDA *");
		SybCTnewDAImpl::DoPutbackConnection(pSyb[0L], true, server, user);
		user = "USR2";
		t_assertm(SybCTnewDAImpl::DoGetConnection(pSyb[0L], bIsOpen, server, user), "expected valid connection");
		t_assertm( !bIsOpen, "expected unopen connection");
		t_assertm( pSyb[0L] != NULL, "expected valid SybCTnewDA *");

		t_assert(SybCTnewDAImpl::Finis());
	}
}

void SybCTnewDAImplTest::DoPutbackConnectionTest()
{
	StartTrace(SybCTnewDAImplTest.DoPutbackConnectionTest);
	Anything anyCfg, anyTmp;
	anyTmp["ParallelQueries"] = 2L;
	anyCfg["SybaseModule"]["SybCTnewDAImpl"] = anyTmp;
	if ( t_assert(SybCTnewDAImpl::Init(anyCfg)) ) {
		assertEqualm(2L, SybCTnewDAImpl::fgListOfSybCT["Size"].AsLong(-1L), "size should now be 2");
		assertEqual(2L, SybCTnewDAImpl::fgListOfSybCT["Unused"].GetSize());
		SybCTnewDA *pSyb[3L] = { 0 };
		bool bIsOpen;
		String server("SRV1"), user("USR1");
		t_assertm(SybCTnewDAImpl::DoGetConnection(pSyb[0L], bIsOpen, server, user), "expected valid connection");
		t_assertm( !bIsOpen, "expected unopen connection");
		t_assertm( pSyb[0L] != NULL, "expected valid SybCTnewDA *");
		t_assertm(SybCTnewDAImpl::DoGetConnection(pSyb[1L], bIsOpen, server, user), "expected valid connection");
		t_assertm( !bIsOpen, "expected unopen connection");
		t_assertm( pSyb[1L] != NULL, "expected valid SybCTnewDA *");

		SybCTnewDAImpl::DoPutbackConnection(pSyb[0L], true, server, user);
		assertEqual(1L, SybCTnewDAImpl::fgListOfSybCT["Open"].GetSize());
		Thread::Wait(1L);
		user = "USR2";
		SybCTnewDAImpl::DoPutbackConnection(pSyb[1L], true, server, user);
		assertEqual(2L, SybCTnewDAImpl::fgListOfSybCT["Open"].GetSize());

		assertEqualm("SRV1.USR1", SybCTnewDAImpl::fgListOfSybCT["Open"][0L][0L][1L].AsString(), "expected SRV1.USR1");
		assertEqualm("SRV1.USR2", SybCTnewDAImpl::fgListOfSybCT["Open"][1L][0L][1L].AsString(), "expected SRV1.USR2");

		t_assertm( TimeStamp(SybCTnewDAImpl::fgListOfSybCT["Open"].SlotName(0L)) < TimeStamp(SybCTnewDAImpl::fgListOfSybCT["Open"].SlotName(1L)), "expected timestamps to be different");
		t_assert(SybCTnewDAImpl::Finis());
	}
}

// builds up a suite of testcases, add a line for each testmethod
Test *SybCTnewDAImplTest::suite ()
{
	StartTrace(SybCTnewDAImplTest.suite);
	TestSuite *testSuite = new TestSuite;

	ADD_CASE(testSuite, SybCTnewDAImplTest, UninitializedExecTest);
	ADD_CASE(testSuite, SybCTnewDAImplTest, InitTest);
	ADD_CASE(testSuite, SybCTnewDAImplTest, DoGetConnectionTest);
	ADD_CASE(testSuite, SybCTnewDAImplTest, DoPutbackConnectionTest);
	return testSuite;

}


text:
import { createDriver } from './fetch-api-driver';

describe('fetchApiDriver', () => {
  class DummyAbortController {
    constructor() {
      this.signal = 'signal';
      this.abort = jest.fn();
    }
  }

  it('throws when responseType is of incorrect type', async () => {
    const getResponse = jest.fn().mockResolvedValue('error');
    const requestInstance = jest.fn().mockResolvedValue({
      ok: true,
      json: getResponse,
    });
    const driver = createDriver(requestInstance);
    let error;

    try {
      await driver({ url: '/', responseType: 'notValidType' });
    } catch (e) {
      error = e;
    }

    expect(error.message).toBe(
      "responseType must be one of the following: 'arraybuffer', 'blob', 'formData', 'json', 'text', null",
    );
  });

  it('returns response with data for successful request', async () => {
    const requestInstance = jest.fn().mockResolvedValue({
      ok: true,
      json: jest.fn().mockResolvedValue('data'),
    });
    const driver = createDriver(requestInstance);
    const response = await driver({ url: '/' });

    expect(response).toEqual({
      data: 'data',
    });
  });

  it('returns response with data null for successful request when responseType as null', async () => {
    const requestInstance = jest.fn().mockResolvedValue({
      ok: true,
    });
    const driver = createDriver(requestInstance);
    const response = await driver({
      url: '/',
      responseType: null,
    });

    expect(response).toEqual({
      data: null,
    });
  });

  it('throws response with data for error request', async () => {
    const getResponse = jest.fn().mockResolvedValue('error');
    const requestInstance = jest.fn().mockResolvedValue({
      ok: false,
      json: getResponse,
    });
    const driver = createDriver(requestInstance);
    let error;

    try {
      await driver({ url: '/' });
    } catch (e) {
      error = e;
    }

    expect(error).toEqual({
      ok: false,
      json: getResponse,
      data: 'error',
    });
  });

  it('throws response without data for error request and errored json', async () => {
    const getResponse = jest.fn().mockRejectedValue('error');
    const requestInstance = jest.fn().mockResolvedValue({
      ok: false,
      json: getResponse,
    });
    const driver = createDriver(requestInstance);
    let error;

    try {
      await driver({ url: '/' });
    } catch (e) {
      error = e;
    }

    expect(error).toEqual({
      ok: false,
      json: getResponse,
    });
  });

  it('calls fetchInstance with proper object', async () => {
    const requestInstance = jest.fn().mockResolvedValue({
      ok: true,
      json: jest.fn().mockResolvedValue('data'),
    });
    const driver = createDriver(requestInstance, {
      AbortController: DummyAbortController,
    });
    await driver({ url: '/' });
    expect(requestInstance).toBeCalledWith('/', { signal: 'signal' });
  });

  it('calls fetchInstance without signal with default AbortController', async () => {
    const requestInstance = jest.fn().mockResolvedValue({
      ok: true,
      json: jest.fn().mockResolvedValue('data'),
    });
    const driver = createDriver(requestInstance);
    await driver({ url: '/' });
    expect(requestInstance).toBeCalledWith('/', { signal: undefined });
  });

  it('returns promise with cancel function which aborts request', () => {
    const abort = jest.fn();

    class LocalDummyAbortController {
      constructor() {
        this.signal = 'signal';
        this.abort = abort;
      }
    }

    const requestInstance = jest.fn().mockResolvedValue({
      ok: true,
      json: jest.fn().mockResolvedValue('data'),
    });
    const driver = createDriver(requestInstance, {
      AbortController: LocalDummyAbortController,
    });
    const promise = driver({ url: '/' });
    expect(abort).not.toHaveBeenCalled();
    promise.cancel();
    expect(abort).toHaveBeenCalledTimes(1);
  });

  it('uses baseURL for relative urls', async () => {
    const requestInstance = jest.fn().mockResolvedValue({
      ok: true,
      json: jest.fn().mockResolvedValue('data'),
    });
    const driver = createDriver(requestInstance, {
      baseURL: 'http://domain.com',
      AbortController: DummyAbortController,
    });
    await driver({ url: '/' });
    expect(requestInstance).toBeCalledWith('http://domain.com/', {
      signal: 'signal',
    });
  });

  it('doesnt use baseURL for absolute urls', async () => {
    const requestInstance = jest.fn().mockResolvedValue({
      ok: true,
      json: jest.fn().mockResolvedValue('data'),
    });
    const driver = createDriver(requestInstance, {
      baseURL: 'http://domain.com',
      AbortController: DummyAbortController,
    });
    await driver({ url: 'http://another-domain.com/' });
    expect(requestInstance).toBeCalledWith('http://another-domain.com/', {
      signal: 'signal',
    });
  });
});


text:
package com.voxelgameslib.voxelgameslib.api.exception;

import java.io.IOException;
import javax.annotation.Nonnull;

/**
 * Thrown when something is wrong related to lang stuff
 */
public class LangException extends VoxelGameLibException {

    /**
     * @param message the message that explains the issue
     */
    public LangException(@Nonnull String message) {
        super(message);
    }

    /**
     * Used for IO related exceptions
     *
     * @param message the message that explains the issue
     * @param ex      the root issue that was thrown
     */
    public LangException(@Nonnull String message, @Nonnull IOException ex) {
        super(message, ex);
    }
}


text:
/*
 * Copyright (c) 1987, 1993
 *    The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 * 	This product includes software developed by the University of
 * 	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*! \file herror.c
   lwres_herror() prints the string s on stderr followed by the string
   generated by lwres_hstrerror() for the error code stored in the global
   variable lwres_h_errno.

   lwres_hstrerror() returns an appropriate string for the error code
   gievn by err. The values of the error codes and messages are as
   follows:

\li   #NETDB_SUCCESS: Resolver Error 0 (no error)

\li   #HOST_NOT_FOUND: Unknown host

\li #TRY_AGAIN: Host name lookup failure

\li   #NO_RECOVERY: Unknown server error

\li   #NO_DATA: No address associated with name

 */

#if defined(LIBC_SCCS) && !defined(lint)
static const char sccsid[] = "@(#)herror.c	8.1 (Berkeley) 6/4/93";
static const char rcsid[] =
	"$Id$";
#endif /* LIBC_SCCS and not lint */

#include <config.h>

#include <stdio.h>

#include <lwres/netdb.h>
#include <lwres/platform.h>

LIBLWRES_EXTERNAL_DATA int	lwres_h_errno;

/*!
 * these have never been declared in any header file so make them static
 */

static const char *h_errlist[] = {
	"Resolver Error 0 (no error)",		/*%< 0 no error */
	"Unknown host",				/*%< 1 HOST_NOT_FOUND */
	"Host name lookup failure",		/*%< 2 TRY_AGAIN */
	"Unknown server error",			/*%< 3 NO_RECOVERY */
	"No address associated with name",	/*%< 4 NO_ADDRESS */
};

static int	h_nerr = sizeof(h_errlist) / sizeof(h_errlist[0]);

/*!
 * herror --
 *	print the error indicated by the h_errno value.
 */
void
lwres_herror(const char *s) {
	fprintf(stderr, "%s: %s\n", s, lwres_hstrerror(lwres_h_errno));
}

/*!
 * hstrerror --
 *	return the string associated with a given "host" errno value.
 */
const char *
lwres_hstrerror(int err) {
	if (err < 0)
		return ("Resolver internal error");
	else if (err < h_nerr)
		return (h_errlist[err]);
	return ("Unknown resolver error");
}


text:
RubyReactor
===========

My implementation of Reactor pattern in Ruby. It acts as a TCP server on port 2000, handling incoming connections. See the code in Reactor folder.


text:
This is a defunct module in the Prolific logging framework. It has been replaced
by the `prolific.resolver` module.

See [Prolific](http://github.com/bigeasy/prolific).


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Novitates Mycologicae Novissimae 46 (1947)

#### Original name
Delicatula rigida Velen.

### Remarks
null


text:
require 'stringio'
require 'thread'

class StringIO
  def retrieve_and_clear
    s = self.string
    self.string = ""
    s
  end
end

class ApplicationController
  include ApplicationHelper
  attr_accessor :params
  class << self
    attr_writer :layouts_conditions

    def filters
      @filters ||= {:before => [], :after => []}
    end

    def before_filter(method)
      filters[:before] << [method, nil]
    end

    def layouts_conditions
      @layouts_conditions ||= []
    end

    def layout(layout, conditions = {})
      layout = "/layouts/#{layout}" if layout && !layout.to_s.include?("/")
      raise "bad params!" unless conditions.is_a?(Hash)
      layouts_conditions << [layout, conditions]
    end

    def layout_for_action(action)
      return "/layouts/application" if layouts_conditions.empty?

      layouts_conditions.each do |layout, condition|
        if condition[:except]
          next if [condition[:except]].flatten.map{|c| c.to_s}.include?(action.to_s)
        end

        if condition[:only]
          next unless [condition[:only]].flatten.map{|c| c.to_s}.include?(action.to_s)
        end

        return layout
      end
      nil
    end
  end

  def initialize
    @output_buffer = StringIO.new
    @params = {}
  end

  def puts(*args)
    @output_buffer.puts(*args)
  end

  def flush
    return if @capturing
    start_layout
    Object::STDOUT << @output_buffer.string
    Object::flush
    @output_buffer.truncate(0)
  end

  def start_layout
    return if @layout_rendered
    @layout_rendered = true
    this_actions_layout = self.class.layout_for_action(params[:action])
    return unless this_actions_layout

    current_body_output = @output_buffer.retrieve_and_clear
    render(this_actions_layout) { @layout_text_begin = @output_buffer.retrieve_and_clear }
    @layout_text_end = @output_buffer.retrieve_and_clear
    @output_buffer << @layout_text_begin << current_body_output
    @layout_text_begin = nil
  end

  def end_layout
    return unless @layout_rendered && @layout_text_end
    @output_buffer << @layout_text_end
    @layout_text_end = nil
  end

  def with_filters(&block)
    self.class.filters[:before].each do |method, options|
      return false unless send(method)
    end
    yield
    self.class.filters[:after].each do |method, options|
      return false unless send(method)
    end
  end

  def call(action, _params = {})
    at_exit { flush }
    self.params = _params
    params[:action] = action.to_s
    @output_buffer = params.delete(:__output_buffer__) if params[:__output_buffer__]
    with_filters { send(action) }
    flush
    end_layout
    flush
  end

  def self.call(action, params = {})
    new.call(action, params)
  end

  def render(__name__, __options__ = {}, &block)
    __name__ = "#{__name__}.html.erb" unless __name__.include?(".")
    __sub_dir__ = __name__.include?("/") ? "" : self.class.template_root
    __template_path__ = File.join( VIEWS_ROOT, __sub_dir__, __name__)
    ___template___ = File.read( __template_path__)

    __binding__ = binding
    if __options__[:locals]
      __v__ = __options__[:locals].values
      __binding__.send(:eval, __options__[:locals].keys * ", " + ", = *__v__")
    end

    __erb__ = ERBStdout.new(___template___, nil, "-", "@output_buffer")
    __erb__.filename = __template_path__
    __erb__.run(__binding__)
  end

  def render_component(_params = {})
    flush
    _params[:controller] ||= params[:controller]
    dispatch(_params.merge(:layout => false, :__output_buffer__  => @output_buffer))
  end

  def self.template_root
    to_s.gsub("::", "/").underscore.gsub(/_controller$/, "")
  end

  def content_for(name, &block)
    var_name = "@content_for_#{name}"
    content = instance_variable_get(var_name) || ""
    @capturing = true
    previous_content = @output_buffer.retrieve_and_clear
    yield
    content << @output_buffer.retrieve_and_clear
    @output_buffer << previous_content
    instance_variable_set(var_name, content)
    @capturing = false
    ""
  end

  def output_discard
    $exit_status = EXIT_DISCARD
  end

  def output_show_html
    $exit_status = EXIT_SHOW_HTML
  end

  def output_show_tool_tip
    $exit_status = EXIT_SHOW_TOOL_TIP
  end
end


text:
package org.ehcache.impl.internal.store.disk;

import org.ehcache.config.EvictionAdvisor;
import org.ehcache.impl.internal.store.disk.factories.EhcachePersistentSegmentFactory;
import org.ehcache.impl.internal.store.offheap.EhcacheOffHeapBackingMap;
import org.terracotta.offheapstore.Metadata;
import org.terracotta.offheapstore.MetadataTuple;
import org.terracotta.offheapstore.Segment;
import org.terracotta.offheapstore.disk.persistent.AbstractPersistentConcurrentOffHeapCache;

import java.io.IOException;
import java.io.ObjectInput;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiFunction;
import java.util.function.Function;

import static org.ehcache.impl.internal.store.offheap.factories.EhcacheSegmentFactory.EhcacheSegment.ADVISED_AGAINST_EVICTION;
import static org.terracotta.offheapstore.Metadata.PINNED;
import static org.terracotta.offheapstore.MetadataTuple.metadataTuple;

/**
 *
 * @author Chris Dennis
 */
public class EhcachePersistentConcurrentOffHeapClockCache<K, V> extends AbstractPersistentConcurrentOffHeapCache<K, V> implements EhcacheOffHeapBackingMap<K, V> {

  private final EvictionAdvisor<? super K, ? super V> evictionAdvisor;
  private final AtomicLong[] counters;

  public EhcachePersistentConcurrentOffHeapClockCache(ObjectInput input, EvictionAdvisor<? super K, ? super V> evictionAdvisor, EhcachePersistentSegmentFactory<K, V> segmentFactory) throws IOException {
    this(evictionAdvisor, segmentFactory, readSegmentCount(input));
  }

  public EhcachePersistentConcurrentOffHeapClockCache(EvictionAdvisor<? super K, ? super V> evictionAdvisor, EhcachePersistentSegmentFactory<K, V> segmentFactory, int concurrency) {
    super(segmentFactory, concurrency);
    this.evictionAdvisor = evictionAdvisor;
    this.counters = new AtomicLong[segments.length];
    for(int i = 0; i < segments.length; i++) {
      counters[i] = new AtomicLong();
    }
  }

  public long allocatedMemory() {
    long total = 0L;
    for (Segment<K, V> segment : segments) {
      total += segment.getAllocatedMemory();
    }
    return total;
  }

  public long occupiedMemory() {
    long total = 0L;
    for (Segment<K, V> segment : segments) {
      total += segment.getOccupiedMemory();
    }
    return total;
  }

  public long dataAllocatedMemory() {
    long total = 0L;
    for (Segment<K, V> segment : segments) {
      total += segment.getDataAllocatedMemory();
    }
    return total;
  }

  public long dataOccupiedMemory() {
    long total = 0L;
    for (Segment<K, V> segment : segments) {
      total += segment.getDataOccupiedMemory();
    }
    return total;
  }

  public long dataSize() {
    long total = 0L;
    for (Segment<K, V> segment : segments) {
      total += segment.getDataSize();
    }
    return total;
  }

  public long longSize() {
    long total = 0L;
    for (Segment<K, V> segment : segments) {
      total += segment.getSize();
    }
    return total;
  }

  public long tableCapacity() {
    long total = 0L;
    for (Segment<K, V> segment : segments) {
      total += segment.getTableCapacity();
    }
    return total;
  }

  public long usedSlotCount() {
    long total = 0L;
    for (Segment<K, V> segment : segments) {
      total += segment.getUsedSlotCount();
    }
    return total;
  }

  public long removedSlotCount() {
    long total = 0L;
    for (Segment<K, V> segment : segments) {
      total += segment.getRemovedSlotCount();
    }
    return total;
  }

  public long reprobeLength() {
    long total = 0L;
    for (Segment<K, V> segment : segments) {
      total += segment.getReprobeLength();
    }
    return total;
  }

  public long vitalMemory() {
    long total = 0L;
    for (Segment<K, V> segment : segments) {
      total += segment.getVitalMemory();
    }
    return total;
  }

  public long dataVitalMemory() {
    long total = 0L;
    for (Segment<K, V> segment : segments) {
      total += segment.getDataVitalMemory();
    }
    return total;
  }

  @Override
  public V compute(K key, final BiFunction<K, V, V> mappingFunction, final boolean pin) {
    MetadataTuple<V> result = computeWithMetadata(key, (k, current) -> {
      V oldValue = current == null ? null : current.value();
      V newValue = mappingFunction.apply(k, oldValue);

      if (newValue == null) {
        return null;
      } else if (oldValue == newValue) {
        return metadataTuple(newValue, (pin ? PINNED : 0) | current.metadata());
      } else {
        return metadataTuple(newValue, (pin ? PINNED : 0) | (evictionAdvisor.adviseAgainstEviction(k, newValue) ? ADVISED_AGAINST_EVICTION : 0));
      }
    });
    return result == null ? null : result.value();
  }

  @Override
  public V computeIfPresent(K key, final BiFunction<? super K, ? super V, ? extends V> mappingFunction) {
    MetadataTuple<V> result = computeIfPresentWithMetadata(key, (k, current) -> {
      V oldValue = current.value();
      V newValue = mappingFunction.apply(k, oldValue);

      if (newValue == null) {
        return null;
      } else if (oldValue == newValue) {
        return current;
      } else {
        return metadataTuple(newValue, (evictionAdvisor.adviseAgainstEviction(k, newValue) ? ADVISED_AGAINST_EVICTION : 0));
      }
    });
    return result == null ? null : result.value();
  }

  @Override
  public V computeIfPresentAndPin(final K key, final BiFunction<K, V, V> mappingFunction) {
    MetadataTuple<V> result = computeIfPresentWithMetadata(key, (k, current) -> {
      V oldValue = current.value();
      V newValue = mappingFunction.apply(k, oldValue);

      if (newValue == null) {
        return null;
      } else if (oldValue == newValue) {
        return metadataTuple(newValue, PINNED | current.metadata());
      } else {
        return metadataTuple(newValue, PINNED | (evictionAdvisor.adviseAgainstEviction(k, newValue) ? ADVISED_AGAINST_EVICTION : 0));
      }
    });
    return result == null ? null : result.value();
  }

  @Override
  public boolean computeIfPinned(final K key, final BiFunction<K,V,V> remappingFunction, final Function<V,Boolean> unpinFunction) {
    final AtomicBoolean unpin = new AtomicBoolean();
    computeIfPresentWithMetadata(key, (k, current) -> {
      if ((current.metadata() & Metadata.PINNED) != 0) {
        V oldValue = current.value();
        V newValue = remappingFunction.apply(k, oldValue);
        Boolean unpinLocal = unpinFunction.apply(oldValue);

        if (newValue == null) {
          unpin.set(true);
          return null;
        } else if (oldValue == newValue) {
          unpin.set(unpinLocal);
          return metadataTuple(oldValue, current.metadata() & (unpinLocal ? ~Metadata.PINNED : -1));
        } else {
          unpin.set(false);
          return metadataTuple(newValue, (evictionAdvisor.adviseAgainstEviction(k, newValue) ? ADVISED_AGAINST_EVICTION : 0));
        }
      } else {
        return current;
      }
    });
    return unpin.get();
  }

  @Override
  public long nextIdFor(final K key) {
    return counters[getIndexFor(key.hashCode())].getAndIncrement();
  }
}


text:
import assert from 'assert';
import EaselContainer from '../src/components/EaselContainer.vue';
import easeljs from '../easeljs/easel.js';
import Vue from 'vue';
import isAnEaselParent from './includes/is-an-easel-parent.js';
import EaselFake from './fixtures/EaselFake.js';
import isADisplayObject from './includes/is-a-display-object.js';
import canCache from './includes/can-cache.js';
import canFilter from './includes/can-filter.js';
const {deepStrictEqual: equal} = assert;

describe('EaselContainer', function () {

    describe('is an easel parent that', isAnEaselParent(EaselContainer));

    describe('is a display object that', isADisplayObject(EaselContainer));

    describe('is cacheable and', canCache(EaselContainer, {}, []));

    describe('can filter and', canFilter(EaselContainer));

    const buildVm = function () {
        const easel = {
            addChild(vueChild) {
            },
            removeChild(vueChild) {
            },
        };

        const vm = new Vue({
            template: `
                <easel-container ref="container">
                    <easel-fake ref="fake"
                        v-if="showFake"
                        :x="x"
                        :y="y"
                        :shadow="shadow"
                    >
                    </easel-fake>
                </easel-container>
            `,
            provide() {
                return {
                    easelParent: easel,
                    easelCanvas: easel,
                };
            },
            data() {
                return {
                    showFake: true,
                    x: 3,
                    y: 4,
                    shadow: null,
                };
            },
            components: {
                'easel-fake': EaselFake,
                'easel-container': EaselContainer,
            },
        }).$mount();

        const container = vm.$refs.container;
        const fake = vm.$refs.fake;

        return {vm, container, fake};
    };

    it('should exist', function () {
        const {vm, container, fake} = buildVm();
        assert(container);
    });

    it('should have an easel', function () {
        const {vm, container, fake} = buildVm();
        assert(container.easelParent);
    });

    it('should have component field', function () {
        const {vm, container, fake} = buildVm();
        assert(container.component);
    });

    it('should be the parent of the fake', function (done) {
        const {vm, container, fake} = buildVm();
        Vue.nextTick()
            .then(() => {
                assert(fake.component.parent === container.component);
            })
            .then(done, done);
    });

    it('should get cache dimensions including the fake', function (done) {
        const {vm, container, fake} = buildVm();
        Vue.nextTick()
            .then(() => {
                vm.x = 0;
                vm.y = 0;
                return Vue.nextTick();
            })
            .then(() => {
                return Promise.all([
                        fake.getCacheBounds(),
                        container.getCacheBounds(),
                    ]);
            })
            .then(([fakeBounds, containerBounds]) => {
                // from EaselFake fixture
                equal(
                    {
                        x: -10,
                        y: -20,
                        width: 30,
                        height: 40,
                    },
                    fakeBounds
                );
                // The square that surrounds a rotating EaselFake
                // The square is calculated using the hypotenuse of the above
                // rectangle.
                // √(30² + 40²) = 50, a super-convenient exact number
                equal(
                    {
                        x: -50,
                        y: -50,
                        width: 100,
                        height: 100,
                    },
                    {
                        x: containerBounds.x,
                        y: containerBounds.y,
                        width: containerBounds.width,
                        height: containerBounds.height,
                    }
                );
            })
            .then(done, done);
    });

    it('should get cache dimensions including the shadow', function (done) {
        const {vm, container, fake} = buildVm();
        Vue.nextTick()
            .then(() => {
                vm.x = 0;
                vm.y = 0;
                vm.shadow = ['black', 5, 10, 5];
                return Vue.nextTick();
            })
            .then(() => {
                return Promise.all([
                        fake.getCacheBounds(),
                        container.getCacheBounds(),
                    ]);
            })
            .then(([fakeBounds, containerBounds]) => {
                // from EaselFake fixture
                equal(
                    {
                        x: -10,
                        y: -20,
                        width: 30,
                        height: 40,
                    },
                    fakeBounds
                );
                // The square that surrounds a rotating EaselFake
                // First the shadow's padding is added to all sides.
                // The shadow padding is done by adding its longest offset and
                // the blurriness amount. In this case 10 and 5. Since it's on
                // all sides, it's applied twice to width and height. That
                // makes an addition of 30 to both.
                // The square is calculated using the hypotenuse of the
                // resulting rectangle.
                // √((30 + 30)² + (40 + 30)²) ~= 92
                equal(
                    {
                        x: -92,
                        y: -92,
                        width: 184,
                        height: 184,
                    },
                    {
                        x: Math.round(containerBounds.x),
                        y: Math.round(containerBounds.y),
                        width: Math.round(containerBounds.width),
                        height: Math.round(containerBounds.height),
                    }
                );
            })
            .then(done, done);
    });

    it('should update cache when children disappear', function (done) {
        const {vm, container, fake} = buildVm();
        Vue.nextTick()
            .then(() => {
                container.cacheNeedsUpdate = false;
                vm.showFake = false;
                return Vue.nextTick();
            })
            .then(() => {
                assert(container.cacheNeedsUpdate);
            })
            .then(done, done);
    });

    it('should update cache when children reappear', function (done) {
        const {vm, container, fake} = buildVm();
        Vue.nextTick()
            .then(() => {
                vm.showFake = false;
                return Vue.nextTick();
            })
            .then(() => {
                container.cacheNeedsUpdate = false;
                vm.showFake = true;
                return Vue.nextTick();
            })
            .then(() => {
                assert(container.cacheNeedsUpdate);
            })
            .then(done, done);
    });
});


text:
<!DOCTYPE html>

        <title>Leaflet TimeDimension</title>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
        <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.fullscreen/1.4.2/Control.FullScreen.min.css">
        <link rel="stylesheet" href="../src/leaflet.timedimension.control.css" />
        <link rel="stylesheet" href="css/style.css" />

Leaflet TimeDimension example 11

Sea Surface Temperature from NOAA Operational Climate Data Records

Code

                Example 10: ImageOverlay and custom control

                Example 12: Noise-Commercial complaints from NYC OpenData

                Leaflet.TimeDimension examples
                Fork Leaflet.TimeDimension at GitHub


text:
<?php

namespace SetBased\Abc\Core\Page\Company;

use SetBased\Abc\Abc;
use SetBased\Abc\C;

/**
 * Page for inserting a new role.
 */
class RoleInsertPage extends RoleBasePage
{
  //--------------------------------------------------------------------------------------------------------------------
  /**
   * Object constructor.
   */
  public function __construct()
  {
    parent::__construct();

    $this->buttonWrdId = C::WRD_ID_BUTTON_INSERT;
  }

  //--------------------------------------------------------------------------------------------------------------------
  /**
   * Returns the relative URL for this page.
   *
   * @param int $targetCmpId The ID of the target company.
   *
   * @return string
   */
  public static function getUrl(int $targetCmpId): string
  {
    $url = Abc::$cgi->putLeader();
    $url .= Abc::$cgi->putId('pag', C::PAG_ID_COMPANY_ROLE_INSERT, 'pag');
    $url .= Abc::$cgi->putId('cmp', $targetCmpId, 'cmp');

    return $url;
  }

  //--------------------------------------------------------------------------------------------------------------------
  /**
   * Inserts a new role.
   */
  protected function databaseAction(): void
  {
    $values = $this->form->getValues();

    $this->rolId = Abc::$DL->abcCompanyRoleInsert($this->targetCmpId,
                                                  $values['rlg_id'],
                                                  $values['rol_name'],
                                                  $values['rol_weight'],
                                                  $values['rol_label']);
  }

  //--------------------------------------------------------------------------------------------------------------------
  /**
   * @inheritdoc
   */
  protected function loadValues(): void
  {
    // Nothing to do.
  }

  //--------------------------------------------------------------------------------------------------------------------
}

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


text:
There are scenarios in which you may want to change the injecting object based on the object that is
being constructed. This is called contextual injection. There are two solutions to this problem. The following two examples
should make clear which solution is preferable for a problem.

## Example: four levels deep

An example could be a logger class that you inject into a database connection class. If the
connection class is injected to a console application class, you want to inject a plain text logger. In case the
connection is injected to a web application class, you may want to inject a Redis logger. The connection class itself
requires a config class, that in its turn requires the logger class.

### Solution 1: pass overwriting params to the `lazyNew` method.

```php
// define the default situation
$di->params['Vendor\Package\ConsoleApplication']['database'] = $di->lazyNew('Vendor\Package\DatabaseConnection');
$di->params['Vendor\Package\DatabaseConnection']['config'] = $di->lazyNew('Vendor\Package\Config');
$di->params['Vendor\Package\Config']['logger'] = $di->lazyNew('Vendor\Package\PlainTextLogger');
$di->params['Vendor\Package\PlainTextLogger']['param1'] = 'value1';

// define the web application context
$di->params['Vendor\Package\RedisLogger']['username'] = 'a';
$di->params['Vendor\Package\RedisLogger']['password'] = 'b';
$di->params['Vendor\Package\RedisLogger']['host'] = 'c';
$di->params['Vendor\Package\WebApplication']['config'] = $di->lazyNew('Vendor\Package\DatabaseConnection', [
    'config' => $di->lazyNew(Config::class, [
        'logger' => $di->lazyNew(RedisLogger::class)
    ])
]);
```

This solution also works with `newInstance`.

## Solution 2: contextual parameters

For this problem there is also another solution. You can pass a `withContext` to the `lazyNew` method for the database
connection injection into the web application class.

```php
// define the default situation
$di->params['Vendor\Package\ConsoleApplication']['database'] = $di->lazyNew('Vendor\Package\DatabaseConnection');
$di->params['Vendor\Package\DatabaseConnection']['config'] = $di->lazyNew('Vendor\Package\Config');
$di->params['Vendor\Package\Config']['logger'] = $di->lazyNew('Vendor\Package\PlainTextLogger');
$di->params['Vendor\Package\PlainTextLogger']['param1'] = 'value1';

// define the web application context
$di->params['Vendor\Package\RedisLogger']['username'] = 'a';
$di->params['Vendor\Package\RedisLogger']['password'] = 'b';
$di->params['Vendor\Package\RedisLogger']['host'] = 'c';
$di->params['Vendor\Package\WebApplication']['config'] = $di->lazyNew('Vendor\Package\DatabaseConnection')
    ->withContext(new Blueprint(Config::class, [
        'logger' => $di->lazyNew(RedisLogger::class)
    ]));
```

This solution does not work with `newInstance`.

## Example, five levels deep

The latter solution becomes more preferable to the former when the context of the dependency tree becomes
larger and larger, because in the latter solution one does not need to know the complete dependency tree. This is clear
in the following scenario. Suppose the console and the web application both require the Redis logger, but with
different parameters (e.g. different host name).

Then we can have the following two solutions.

### Solution based on overwriting params

```php
// define the default situation
$di->params['Vendor\Package\ConsoleApplication']['database'] = $di->lazyNew('Vendor\Package\DatabaseConnection');
$di->params['Vendor\Package\DatabaseConnection']['config'] = $di->lazyNew('Vendor\Package\Config');
$di->params['Vendor\Package\Config']['logger'] = $di->lazyNew('Vendor\Package\RedisLogger');
$di->params['Vendor\Package\RedisLogger']['username'] = 'x';
$di->params['Vendor\Package\RedisLogger']['password'] = 'y';
$di->params['Vendor\Package\RedisLogger']['host'] = 'z';

// define the web application context
$di->params['Vendor\Package\WebApplication']['config'] = $di->lazyNew('Vendor\Package\DatabaseConnection', [
    'config' => $di->lazyNew(Config::class, [
        'logger' => $di->lazyNew(RedisLogger::class, [
            'username' => 'a'
            'password' => 'b'
            'host' => 'c'
        ])
    ])
]);
```

As becomes very clear here, the overwriting context of the web application requires defining the complete tree to
the change the username, password and host parameters.

### Solution based on contextual params

```php
// define the default situation
$di->params['Vendor\Package\ConsoleApplication']['database'] = $di->lazyNew('Vendor\Package\DatabaseConnection');
$di->params['Vendor\Package\DatabaseConnection']['config'] = $di->lazyNew('Vendor\Package\Config');
$di->params['Vendor\Package\Config']['logger'] = $di->lazyNew('Vendor\Package\RedisLogger');
$di->params['Vendor\Package\RedisLogger']['username'] = 'x';
$di->params['Vendor\Package\RedisLogger']['password'] = 'y';
$di->params['Vendor\Package\RedisLogger']['host'] = 'z';

// define the web application context
$di->params['Vendor\Package\WebApplication']['config'] = $di->lazyNew('Vendor\Package\DatabaseConnection')
    ->withContext(new Blueprint(RedisLogger::class, [
         'username' => 'a'
         'password' => 'b'
         'host' => 'c'
     ]));
```

Here you can see that whenever WebApplication requires a Redis logger through the database connection, it passes
different values and there is no need to define the whole dependency tree again.


text:
package algs.model.kdtree;

import java.util.Iterator;
import java.util.Stack;

import algs.model.IMultiPoint;

/**
 * Provides in-order traversal of n-dimensional KD-Tree.
 *
 * @author George Heineman
 * @version 1.0, 6/15/08
 * @since 1.0
 */
public class DimensionalNodeIterator implements Iterator<IMultiPoint> {

	/** Binary traversals have three phases. */
	public enum Phase {
		/** Left phase. */
		LEFT,

		/** Self phase. */
		SELF,

		/** Right phase. */
		RIGHT,

		/** Done phase. */
		DONE
	};

	/** Left phase of traversal. */
	public static final Phase left = Phase.LEFT;

	/** Self phase of traversal. */
	public static final Phase self = Phase.SELF;

	/** Right phase of traversal. */
	public static final Phase right = Phase.RIGHT;

	/** Done phase of traversal. */
	public static final Phase done = Phase.DONE;

	/** A moment in the computation of the traversal. */
	class Moment {
		DimensionalNode node = null;

		Phase phase = done;

		Moment (DimensionalNode node, Phase phase) {
			this.node = node;
			this.phase = phase;
		}
	}

	/**
	 * Current point in the computation.
	 *
	 * The current node is always the top one on the stack (if stack is empty we are done).
	 *
	 * Make private so subclasses can't mess it up.
	 */
	private Stack<Moment> stack = new Stack<Moment>();

	/**
	 * Start the traversal at the given node.
	 *
	 * @param node    starting point of traversal.
	 */
	public DimensionalNodeIterator(DimensionalNode node) {
		if (node == null) {
			throw new NullPointerException ("DimensionalNodeIterator received null starting point");
		}

		stack.add(new Moment (node, left));

		// advance as far as we need to until we have a value to be returned.
		advance();
	}

	/**
	 * Advance phase to follow inorder traversal.
	 * @param phase   determines the current step in the traversal.
	 * @return        next phase in the inorder traversal
	 */
	public Phase advancePhase(Phase phase) {
		if (phase == left) { return self; }
		if (phase == right) { return done; }

		// must be self, so go right.
		return right;
	}

	/**
	 * Advance the traversal, returning the SELF node once found or null when all is done.
	 *
	 * Will never be called with empty stack.
	 */
	void advance() {
		Moment m = stack.peek();

		// build up stack and keep track of the phase of the computation at each of the
		// inner nodes.
		while (m != null) {
			if (m.phase == done) {
				stack.pop();
				if (stack.isEmpty()) {
					// DONE
					break;
				}

				// must continue to move forward, so we update phase.
				m = stack.peek();
				m.phase = advancePhase(m.phase);
			} else if (m.phase == left) {
				if (m.node.above != null) {
					m = new Moment (m.node.above, left);
					stack.push(m);
				} else {
					// advance before returning node.
					m.phase = advancePhase (m.phase);
				}
			} else if (m.phase == self) {
				// advance before completing the phase.
				m.phase = advancePhase (m.phase);
				break;
			} else {
				// must be BELOW
				if (m.node.below != null) {
					m = new Moment (m.node.below, left);
					stack.push(m);
				} else {
					// advance before returning node.
					m.phase = advancePhase (m.phase);
				}
			}
		}
	}

	/**
	 * Determines if there are more steps in the traversal.
	 * @return true if more steps in traversal; false otherwise
	 */
	public boolean hasNext() {
		return !stack.isEmpty();
	}

	/**
	 * Returns the next point in the traversal.
	 * @return next IMultiPoint in the traversal.
	 */
	public IMultiPoint next() {

		// there must be something on the stack.
		if (stack.empty()) {
			throw new java.util.NoSuchElementException("Dimensional Traversal Iterator has no more elements");
		}

		Moment m = stack.peek();

		// now advance.
		advance();

		// return the most recent one.
		return m.node.point;
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException("Remove not supported");
	}

}


text:
#include "board.h"
#include "erpc_client_setup.h"
#include "erpc_error_handler.h"
#include "erpc_matrix_multiply.h"
#include "fsl_debug_console.h"
#include <stdlib.h>

#if BOARD_DEBUG_UART_TYPE == DEBUG_CONSOLE_DEVICE_TYPE_UART
#include "fsl_uart_cmsis.h"
#elif BOARD_DEBUG_UART_TYPE == DEBUG_CONSOLE_DEVICE_TYPE_LPUART
#include "fsl_lpuart_cmsis.h"
#elif BOARD_DEBUG_UART_TYPE == DEBUG_CONSOLE_DEVICE_TYPE_LPSCI
#include "fsl_lpsci_cmsis.h"
#endif

#include "pin_mux.h"
#include "clock_config.h"
/*******************************************************************************
 * Definitions
 ******************************************************************************/
#define BUTTON_INIT() GPIO_PinInit(BOARD_SW3_GPIO, BOARD_SW3_GPIO_PIN, &button_config)
#define IS_BUTTON_PRESSED() !GPIO_ReadPinInput(BOARD_SW3_GPIO, BOARD_SW3_GPIO_PIN)
#define ERPC_DEMO_UART Driver_USART0
#define MATRIX_ITEM_MAX_VALUE 50

/*******************************************************************************
 * Variables
 ******************************************************************************/

extern bool g_erpc_error_occurred;

/*******************************************************************************
 * Prototypes
 ******************************************************************************/

/*******************************************************************************
 * Code
 ******************************************************************************/

uint32_t UART0_GetFreq(void)
{
    return CLOCK_GetFreq(UART0_CLK_SRC);
}

uint32_t UART1_GetFreq(void)
{
    return CLOCK_GetFreq(UART1_CLK_SRC);
}

uint32_t UART2_GetFreq(void)
{
    return CLOCK_GetFreq(UART2_CLK_SRC);
}

uint32_t UART3_GetFreq(void)
{
    return CLOCK_GetFreq(UART3_CLK_SRC);
}

uint32_t UART4_GetFreq(void)
{
    return CLOCK_GetFreq(UART4_CLK_SRC);
}

/*!
 * @brief Fill matrices by random values
 */
static void fill_matrices(Matrix *matrix1_ptr, Matrix *matrix2_ptr)
{
    int32_t a, b;

    /* Fill both matrices by random values */
    for (a = 0; a < matrix_size; ++a)
    {
        for (b = 0; b < matrix_size; ++b)
        {
            (*matrix1_ptr)[a][b] = rand() % MATRIX_ITEM_MAX_VALUE;
            (*matrix2_ptr)[a][b] = rand() % MATRIX_ITEM_MAX_VALUE;
        }
    }
}

/*!
 * @brief Printing a matrix to the console
 */
static void print_matrix(Matrix *matrix_ptr)
{
    int32_t a, b;

    for (a = 0; a < matrix_size; ++a)
    {
        for (b = 0; b < matrix_size; ++b)
        {
            PRINTF("%4i ", (*matrix_ptr)[a][b]);
        }
        PRINTF("\r\n");
    }
}

/*!
 * @brief Main function
 */
int main()
{
    Matrix matrix1, matrix2, result_matrix = {{0}};

    BOARD_InitPins();
    BOARD_BootClockRUN();

#if defined(BOARD_SW1_GPIO) || defined(BOARD_SW2_GPIO) || defined(BOARD_SW3_GPIO)
    /* Define the init structure for the input switch pin */
    gpio_pin_config_t button_config = {
        kGPIO_DigitalInput, 0,
    };
    /* Configure BUTTON */
    BUTTON_INIT();
#endif

    /* UART transport layer initialization */
    erpc_transport_t transport;

    transport = erpc_transport_cmsis_uart_init((void *)&ERPC_DEMO_UART);

    /* eRPC client side initialization */
    erpc_client_init(transport);

    /* Set default error handler */
    erpc_client_set_error_handler(erpc_error_handler);

    /* Fill both matrices by random values */
    fill_matrices(&matrix1, &matrix2);

    /* Print both matrices on the console */
    PRINTF("\r\nMatrix #1");
    PRINTF("\r\n=========\r\n");
    print_matrix(&matrix1);

    PRINTF("\r\nMatrix #2");
    PRINTF("\r\n=========\r\n");
    print_matrix(&matrix2);

    while (1)
    {
        PRINTF("\r\neRPC request is sent to the server\r\n");

        erpcMatrixMultiply((const Matrix *)&matrix1, (const Matrix *)&matrix2, &result_matrix);

        /* Check if some error occured in eRPC */
        if (g_erpc_error_occurred)
        {
            /* Exit program loop */
            break;
        }

        PRINTF("\r\nResult matrix");
        PRINTF("\r\n=============\r\n");
        print_matrix(&result_matrix);

#if defined(BOARD_SW1_GPIO) || defined(BOARD_SW2_GPIO) || defined(BOARD_SW3_GPIO)
        PRINTF("\r\nPress the button to initiate the next matrix multiplication\r\n");
        /* Check for button push. Pin is grounded when button is pushed. */
        while (1 != IS_BUTTON_PRESSED())
        {
        }

        /* Wait for a moment to eliminate the button glitch */
        int32_t i;
        for (i = 0; i < 2500000; ++i)
        {
            __NOP();
        }

        /* Fill both matrices by random values */
        fill_matrices(&matrix1, &matrix2);

        /* Print both matrices on the console */
        PRINTF("\r\nMatrix #1");
        PRINTF("\r\n=========\r\n");
        print_matrix(&matrix1);

        PRINTF("\r\nMatrix #2");
        PRINTF("\r\n=========\r\n");
        print_matrix(&matrix2);
#else
        PRINTF("\r\nEnd of example.\r\n");
        while (1)
        {
        }
#endif
    }
    while (1)
    {
    }
}


text:
using docsFunctions.Shared.Models;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace DocFunctions.Markdown.Transformers
{
    public class GistTransformer : BaseTransformer
    {
        public GistTransformer() : base()
        {

        }

        public GistTransformer(ITransformer innerTransformer) : base(innerTransformer)
        {

        }

        protected override string PostTransform(Blog meta, string markdown)
        {
            return Regex.Replace(markdown, "%\\[(.*?)\\]", m => "<script src=\"" + m.Groups[1].Value + "\"></script>");
        }
    }
}


text:
/*
 */

(function (can) {
  var path = GGRC.mustache_path + "/risk_assessments";

  can.Model.Cacheable("CMS.Models.RiskAssessment", {
    root_object: "risk_assessment",
    root_collection: "risk_assessments",
    category: "risk_assessment",
    mixins: ['ca_update', 'timeboxed'],
    findAll: "GET /api/risk_assessments",
    findOne: "GET /api/risk_assessments/{id}",
    create: "POST /api/risk_assessments",
    update: "PUT /api/risk_assessments/{id}",
    destroy: "DELETE /api/risk_assessments/{id}",
    is_custom_attributable: true,
    attributes: {
      ra_manager: "CMS.Models.Person.stub",
      ra_counsel: "CMS.Models.Person.stub",
      context: "CMS.Models.Context.stub",
      documents: "CMS.Models.Document.stubs",
      program: "CMS.Models.Program.stub",
      modified_by: "CMS.Models.Person.stub",
      object_documents: "CMS.Models.ObjectDocument.stubs",
      custom_attribute_values : "CMS.Models.CustomAttributeValue.stubs"
    },
    tree_view_options: {
      attr_list: [
        {attr_title: 'Title', attr_name: 'title'},
        {attr_title: 'Code', attr_name: 'slug'},
        {attr_title: 'Start Date', attr_name: 'start_date'},
        {attr_title: 'Stop Date', attr_name: 'end_date'},
        {
          attr_title: 'Risk Manager',
          attr_name: 'ra_manager',
          attr_sort_field: 'ra_manager'
        },
        {
          attr_title: 'Risk Counsel',
          attr_name: 'ra_counsel',
          attr_sort_field: 'ra_counsel'
        }
      ],
      add_item_view: path + '/tree_add_item.mustache'
    },
    init: function () {
      this._super && this._super.apply(this, arguments);
      this.validateNonBlank("title");
      this.validateNonBlank("start_date");
      this.validateNonBlank("end_date");
    }
  }, {
    save: function () {
      // Make sure the context is always set to the parent program
      if (!this.context || !this.context.id) {
        this.attr('context', this.program.reify().context);
      }
      return this._super.apply(this, arguments);
    }
  });

})(window.can);


text:
package me.imid.swipebacklayout.lib.app;

import android.app.Activity;
import android.support.annotation.NonNull;

import java.lang.ref.WeakReference;

import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.Utils;

/**
 * Created by laysionqet on 2018/4/24.
 */
public class SwipeBackListenerActivityAdapter implements SwipeBackLayout.SwipeListenerEx {
    private final WeakReference<Activity> mActivity;

    public SwipeBackListenerActivityAdapter(@NonNull Activity activity) {
        mActivity = new WeakReference<>(activity);
    }

    @Override
    public void onScrollStateChange(int state, float scrollPercent) {

    }

    @Override
    public void onEdgeTouch(int edgeFlag) {
        Activity activity = mActivity.get();
        if (null != activity) {
            Utils.convertActivityToTranslucent(activity);
        }
    }

    @Override
    public void onScrollOverThreshold() {

    }

    @Override
    public void onContentViewSwipedBack() {
        Activity activity = mActivity.get();
        if (null != activity && !activity.isFinishing()) {
            activity.finish();
            activity.overridePendingTransition(0, 0);
        }
    }
}


text:
**************************************************
Creating 3D presentations with Blend4Web templates
**************************************************

Intro
=====

We all have to create presentations at times. In these cases, you often use specific editors such as Powerpoint. However, technology moves forward and today it's possible to create fully functional 3D web presentations. Unfortunately, this has been limited to only professional graphic artists and programmers. We decided to simplify this difficult task, and we did almost all the routine work for slide management automation in Blender, which allows you to concentrate on creativity and fresh ideas. In this lesson, we will show you how to work with the "FILM" template, designed as a filmstrip. The template can be used for creating interesting kids` stories as well as business presentations in a novel format.

.. figure:: images/Fable-pic-en.png
		:scale: 80 %
		:align: center
		:alt: Fig. 1 Fable "The Crow and the Fox"
		:target: http://triumphllc.github.io/3DSlides/B4W-template-FILM/B4W-template-FILM-example1-en.html

		Fig. 1 Fable "The Crow and the Fox"

		`Open an example <http://triumphllc.github.io/3DSlides/B4W-template-FILM/B4W-template-FILM-example1-en.html>`_

Working with the "FILM" template
================================

Proper use of the template requires the latest version of Blend4Web. Open the "FILM" template file and click the "Run scripts" button to make the add, swap, delete and upload buttons appear. You will need to do this only once; next time the file opens with buttons.

.. figure:: images/11.jpg
		:scale: 80 %
		:align: center
		:alt: Fig. 2 Location of "Run scripts" button

		Fig. 2 Location of "Run scripts" button

Next, create a new scene by clicking the "Add slide" button; an automatically generated new scene will be added to a new slide. Camera animation for moving between scenes will be automatically generated as well. The navigation buttons "play", "left" and "right" to interact with a scene in the blend4web application are also created. A logic tree will be automatically generated depending on the number of new slides added.

If you open a list of scenes in the top toolbar, then you can see new scenes. By clicking on them, you can switch from scene to scene depending on what future actions are required. For example, we have added low-poly decoration sets and two characters of the well-known fable about the crow and the fox. There is minimum camera animation in each scene. You can use our template to build a completely new story, which already includes the appropriate frame and prepared logic. In essence, our template is a quick tool for creating a beautiful and at the same time lightweight 3D presentation, which you can send to anyone. The receiver will be able to open and view it in a browser without plug-ins.

.. figure:: images/2.jpg
		:scale: 80 %
		:align: center
		:alt: Fig. 3 List of new scenes

		Fig. 3 List of new scenes

In order to add the necessary objects in the scene we use standard Blender tools. Or, we can create these objects from scratch, depending on the goals of the presentation.

.. figure:: images/3.5.jpg
		:scale: 80 %
		:align: center
		:alt: Fig. 4 Adding objects

		Fig. 4 Adding objects

.. figure:: images/3.jpg
		:scale: 80 %
		:align: center
		:alt: Fig. 5 Copying objects

		Fig. 5 Copying objects

You can quickly and easily transfer objects from one scene to another using the standard Ctrl+C / Ctrl+V methods

.. figure:: images/4.5.jpg
		:scale: 80 %
		:align: center
		:alt: Fig. 6 Adding caption to slide

		Fig. 6 Adding caption to slide

Next, click Shift+A and type a caption for every slide.

.. figure:: images/4.jpg
		:scale: 80 %
		:align: center
		:alt: Fig. 7 Automatically generated animation keys

		Fig. 7 Automatically generated animation keys

Create another slide to create animation of camera movement between slides. Fig. 7 shows automatically generated camera animation keys. You can start and stop animation with Alt+A.

.. figure:: images/5.jpg
		:scale: 80 %
		:align: center
		:alt: Fig. 8 Final results

		Fig. 8 Final results

We solve most difficult tasks in the script and leave you with space for creativity and making your own ideas a reality. Good luck with your projects!

What is in the template
=======================

The template for creating 3D presentations is designed to simplify the process of creating presentations in blender

The template is written Python and uses both the blend4web api and blender api

The template allows you to automate three processes:
	* Creating a slide and placing service objects to move the camera and create a complex scene
	* Creating a logic tree to navigate through slides
	* Creating animation keys for the autoplay mode

1) Creating a slide
-------------------

AddSlideClass is used to create slides and service objects

By default, the template already includes the initial slide

.. figure:: images/111.jpg
		:scale: 80 %
		:align: center
		:alt: Fig. 9 Template with initial slide

		Fig. 9 Template with initial slide

so we just need to duplicate the initial slide with an offset and rename it.

Copying objects with offsets is done by using the following function::

	bpy.ops.object.duplicate_move(TRANSFORM_OT_translate={"value":(0, obj.dimensions[0] * l, 0)})

"Empty" service objects are created by the following function::

	bpy.ops.object.empty_add(type='PLAIN_AXES', radius=2, view_align=False, location=(obj.location[0],obj.location[1],obj.location[2] ))

We need two "Empty" objects, the first in the center of the slide object, the second is placed at a distance of 3.2 on the X-axis from the center of the slide object.

Creating a sub-scene can be carried out using the following function::

	bpy.ops.scene.new()

Notice that each slide should show its own sub-scene, so each slide should have a unique material with reference to a sub-scene

We can do this by copying the texture and material of the original slide (to inherit their properties) and assign the resulting material and texture to the new object::

	new_material = bpy.data.materials['material name'].copy()

	cTex = bpy.data.textures['texture name'].copy()

2) Creating logic trees
-----------------------

.. figure:: images/22.jpg
		:scale: 80 %
		:align: center
		:alt: Fig. 10 Logic tree for initial slide

		Fig. 10 Logic tree for initial slide

The logical tree to control the scene consists of three branches, which are already in the template.

The first two are responsible for the switching between autoplay and manual mode.

The third is designed to navigate by slide to the right and to the left.

It is already built correctly and running, but for only one slide.

If you add a new slide, then two new nodes will be automatically added to logic tree, after which integrity and operability of the logic tree are restored.

The add_logic_nodes function from AddSlideClass is responsible for these operations.

3) Creating animations
----------------------

Autoplay mode needs camera animation, which at certain intervals of time will move between slides.

Animation is created with the AddAnimation class.

After creating each slide, the "execute" class is called and with the function::

	bpy.context.scene.frame_set(frame_num)
           camera.location[0] = position[0] + 2
           camera.location[1] = position[1]
           camera.location[2] = position[2]
           camera.keyframe_insert(data_path="location", index=-1)

animation keys, three on each slide, will be added to the camera.

.. figure:: images/4.jpg
		:scale: 80 %
		:align: center
		:alt: Fig. 11 Automatically generated animation keys

		Fig. 11 Automatically generated animation keys

In conclusion
=============

In the end, we get a complete 3D web application with our presentation. Based on executed work we can conclude that the creation of a complete 3D presentation – is not such a complicated process and is available to wide range of passionate enthusiasts.

A video lesson is available on youtube.com https://www.youtube.com/watch?v=70xg-u-wYIo

Download the template and a prepared example of the presentation from GitHub at https://github.com/TriumphLLC/3DSlides/archive/gh-pages.zip (distributed under the MIT open source license). A set of templates will be expanded over time, allowing you to create not only a "film" presentation, but also magazines, art expositions and galleries.


text:
goog.provide('gpub.spec.SpecVersion');
goog.provide('gpub.spec.Spec');
goog.provide('gpub.spec.SpecDef');

/**
 * @typedef {{
 *  version: (gpub.spec.SpecVersion|undefined),
 *  grouping: (!gpub.spec.Grouping|undefined),
 *  gameMapping: (!Object<string, string>|undefined),
 *  specOptions: (!gpub.opts.SpecOptions|undefined),
 *  diagramOptions: (!gpub.opts.DiagramOptions|undefined),
 *  templateOptions: (!gpub.opts.TemplateOptions|undefined),
 * }}
 */
gpub.spec.SpecDef;

/**
 * The version of the spec. Necessary for storage-compatibility.
 * @enum {string}
 */
gpub.spec.SpecVersion = {
  V1: 'V1'
};

/**
 * A book spec represents a serialized Book specification or Spec. Re-running
 * Gpub on the same spec should generate the same output, modulo some details
 * like dates and debug information
 *
 * The Book Spec is descendent from the Glift Spec, but has orthogonal concerns
 * and so is separate.
 *
 * @param {(!gpub.spec.Spec|gpub.spec.SpecDef)=} opt_spec
 *
 * @constructor @struct @final
 */
gpub.spec.Spec = function(opt_spec) {
  var o = opt_spec || {};

  /**
   * The version of this spec. Required so that parsing of old specs can still
   * happen.
   *
   * @const {!gpub.spec.SpecVersion}
   */
  this.version = o.version || gpub.spec.SpecVersion.V1;

  /**
   * Top-level Position grouping.
   *
   * @const {!gpub.spec.Grouping}
   */
  this.rootGrouping = new gpub.spec.Grouping(o.rootGrouping);

  /**
   * Mapping from game id to raw game string (usu. SGF). It's not required that
   * this be a bijection, but it doesn't really make sense to duplicate games
   * in the mapping.
   *
   * @const {!Object<string, string>}
   */
  this.gameMapping =  {};
  if (o.gameMapping) {
    for (var key in o.gameMapping) {
      this.gameMapping[key] = o.gameMapping[key];
    }
  }

  /**
   * Options specific to spec creation (Phases 1 and 2)
   * @const {!gpub.opts.SpecOptions}
   */
  this.specOptions = new gpub.opts.SpecOptions(o.specOptions);

  /**
   * Options specific to Diagrams (Phase 3)
   * @const {!gpub.opts.DiagramOptions}
   */
  this.diagramOptions = new gpub.opts.DiagramOptions(o.diagramOptions);

  /**
   * Options specific to book processing (Phase 4)
   * @const {!gpub.opts.TemplateOptions}
   */
  this.templateOptions = new gpub.opts.TemplateOptions(o.templateOptions);
};

/**
 * Deserialize a spec from JSON
 * @param {string} str
 */
gpub.spec.Spec.deserializeJson = function(str) {
  var obj = /** @type {!gpub.spec.Spec} */ (JSON.parse(str));
  return new gpub.spec.Spec(obj);
};

/**
 * Overwrite the top-level entries of the first param with properties/values of
 * the second.
 *
 * @param {!Object} oldobj
 * @param {!gpub.spec.SpecDef} newobj
 * @return {!gpub.spec.Spec} a new option sobject.
 */
gpub.spec.Spec.overwrite = function(oldobj, newobj) {
  var out = {};
  for (var key in oldobj) {
    out[key] = oldobj[key];
  }
  for (var key in newobj) {
    out[key] = newobj[key];
  }
  return new gpub.spec.Spec(/** @type {!gpub.spec.SpecDef} */ (out));
};

gpub.spec.Spec.prototype = {
  /**
   * Transform a this spec into a JSON represontation.
   * @return {string}
   */
  serializeJson: function() {
    return JSON.stringify(this);
  },

  /**
   * Serialize, but remove the any value that's equal to a default value
   * @return {string}
   */
  serializeRemovingDefaults: function() {
    var baseSpec = new gpub.spec.Spec();
    // compare vs baseSpec.
    return '';
  },
};


text:
<!doctype html>
<html>

<head>
  <title>hipaa-dea-number-input test</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1, user-scalable=yes">
  <script src="../../webcomponentsjs/webcomponents-lite.js"></script>
  <script src="../../web-component-tester/browser.js"></script>
  <link rel="import" href="../hipaa-dea-number-input.html">
</head>

<body>
  <test-fixture id="basic">
    <template>
      <hipaa-dea-number-input></hipaa-dea-number-input>
    </template>
  </test-fixture>
  <test-fixture id="validator">
    <template>
      <hipaa-dea-number-input value="" auto-validate></hipaa-dea-number-input>
    </template>
  </test-fixture>
  <test-fixture id="validDeaNumber">
    <template>
      <hipaa-dea-number-input value="BJ6125341" auto-validate></hipaa-dea-number-input>
    </template>
  </test-fixture>
  <script>
    suite('hipaa-dea-number-input', function() { // jshint ignore:line
      let element, deainput;
      setup(function() { // jshint ignore:line
        element = fixture('basic'); // jshint ignore:line
      });
      test('instantiating the deanumber element works', function() { // jshint ignore:line
        assert.equal(element.is, 'hipaa-dea-number-input'); // jshint ignore:line
      });
      test('setting some value for deanumber and checking the value sets properly', function() { // jshint ignore:line
        deainput = Polymer.dom(element.root).querySelector('#input'); // jshint ignore:line
        deainput.value = '123456789';
        assert.equal(deainput.value, '123456789'); // jshint ignore:line
      });
      test('setting invalid value for deanumber and validating the deanumber', function() { // jshint ignore:line
        deainput = Polymer.dom(element.root).querySelector('#input'); // jshint ignore:line
        deainput.value = '123456789';
        deainput.validate();
        assert.isTrue(deainput.invalid, 'DEA Number is invalid'); // jshint ignore:line
      });
      test('setting first character with I and rest of the characters to valid values should throw an error', function() { // jshint ignore:line
        deainput = Polymer.dom(element.root).querySelector('#input'); // jshint ignore:line
        deainput.value = 'IJ6125341';
        deainput.validate();
        assert.isTrue(deainput.invalid, 'DEA Number is invalid'); // jshint ignore:line
      });
      test('setting first character to Q and rest of the characters to valid values should throw an error', function() { // jshint ignore:line
        deainput = Polymer.dom(element.root).querySelector('#input'); // jshint ignore:line
        deainput.value = 'QJ6125341';
        deainput.validate();
        assert.isTrue(deainput.invalid, 'DEA Number is invalid'); // jshint ignore:line
      });
      test('setting value for deanumber and validating the deanumber', function() { // jshint ignore:line
        deainput = Polymer.dom(element.root).querySelector('#input'); // jshint ignore:line
        deainput.value = 'AS5623740';
        deainput.validate();
        assert.isFalse(deainput.invalid, 'DEA Number is valid'); // jshint ignore:line
      });
    });
    suite('validating hippa-dea-number-input value', function() { // jshint ignore:line
      test('deanumber value is not set throw errorMessage', function() { // jshint ignore:line
        let input = fixture('validator'); // jshint ignore:line
        assert.equal(input.errorMessage, 'DEA Number is invalid'); // jshint ignore:line
      });
      test('valid deanumber is set invalid false', function() { // jshint ignore:line
        let input = fixture('validDeaNumber'); // jshint ignore:line
        assert.isFalse(input.invalid, 'DEA Number is valid'); // jshint ignore:line
      });
    });
  </script>
</body>

</html>


text:
.class Lcom/android/gallery3d/app/PhotoDataAdapter$UpdateInfo;
.super Ljava/lang/Object;
.source "PhotoDataAdapter.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/gallery3d/app/PhotoDataAdapter;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "UpdateInfo"
.end annotation

# instance fields
.field public contentEnd:I

.field public contentStart:I

.field public indexHint:I

.field public items:Ljava/util/ArrayList;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/ArrayList",
            "<",
            "Lcom/android/gallery3d/data/MediaItem;",
            ">;"
        }
    .end annotation
.end field

.field public reloadContent:Z

.field public size:I

.field public target:Lcom/android/gallery3d/data/Path;

.field public version:J

# direct methods
.method private constructor <init>()V
    .locals 0

    .prologue
    .line 1253
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method synthetic constructor <init>(Lcom/android/gallery3d/app/PhotoDataAdapter$1;)V
    .locals 0
    .parameter "x0"

    .prologue
    .line 1253
    invoke-direct {p0}, Lcom/android/gallery3d/app/PhotoDataAdapter$UpdateInfo;-><init>()V

    return-void
.end method


text:
using System;
using System.Threading;

namespace RioSharp
{
    public unsafe class RioSocket : IDisposable
    {
        IntPtr _requestQueue;
        internal IntPtr Socket;
        internal RioFixedBufferPool SendBufferPool, ReceiveBufferPool;
        internal Action<RioSocket, RioBufferSegment> onIncommingSegment = (socket, segment) => { };
        internal Action<RioSocket, RioBufferSegment> onIncommingSegmentWrapper;
        internal Action<RioBufferSegment> onIncommingSegmentSafe = s => { };

        internal RioSocket(RioFixedBufferPool sendBufferPool, RioFixedBufferPool receiveBufferPool,
            uint maxOutstandingReceive, uint maxOutstandingSend, IntPtr SendCompletionQueue, IntPtr ReceiveCompletionQueue,
            ADDRESS_FAMILIES adressFam, SOCKET_TYPE sockType, PROTOCOL protocol)
        {
            if ((Socket = WinSock.WSASocket(adressFam, sockType, protocol, IntPtr.Zero, 0, SOCKET_FLAGS.REGISTERED_IO | SOCKET_FLAGS.WSA_FLAG_OVERLAPPED)) == IntPtr.Zero)
                WinSock.ThrowLastWSAError();

            SendBufferPool = sendBufferPool;
            ReceiveBufferPool = receiveBufferPool;

            _requestQueue = RioStatic.CreateRequestQueue(Socket, maxOutstandingReceive, 1, maxOutstandingSend, 1, ReceiveCompletionQueue, SendCompletionQueue, GetHashCode());
            WinSock.ThrowLastWSAError();

            onIncommingSegmentWrapper = (socket, segment) =>
            {
                onIncommingSegmentSafe(segment);
                if (segment.CurrentContentLength > 0)
                    socket.BeginReceive();
                else
                    socket.Dispose();
                segment.Dispose();
            };
        }

        public Action<RioSocket, RioBufferSegment> OnIncommingSegmentUnsafe
        {
            get
            {
                return onIncommingSegment;
            }
            set
            {
                onIncommingSegment = value ?? ((socket, segment) => { });
            }
        }

        public Action<RioBufferSegment> OnIncommingSegment
        {
            get
            {
                return onIncommingSegmentSafe;
            }
            set
            {
                onIncommingSegment = onIncommingSegmentWrapper;
                onIncommingSegmentSafe = value ?? (segment => { });
            }
        }

        public void WritePreAllocated(RioBufferSegment Segment)
        {
            unsafe
            {
                if (!RioStatic.Send(_requestQueue, Segment.SegmentPointer, 1, RIO_SEND_FLAGS.DEFER, Segment.Index))
                    WinSock.ThrowLastWSAError();
            }
        }

        internal unsafe void CommitSend()
        {
            if (!RioStatic.Send(_requestQueue, RIO_BUFSEGMENT.NullSegment, 0, RIO_SEND_FLAGS.COMMIT_ONLY, 0))
                WinSock.ThrowLastWSAError();
        }

        internal unsafe void SendInternal(RioBufferSegment segment, RIO_SEND_FLAGS flags)
        {
            if (!RioStatic.Send(_requestQueue, segment.SegmentPointer, 1, flags, segment.Index))
                WinSock.ThrowLastWSAError();
        }

        public unsafe void BeginReceive()
        {
            RioBufferSegment buf;
            if (ReceiveBufferPool.TryGetBuffer(out buf))
            {
                if (!RioStatic.Receive(_requestQueue, buf.SegmentPointer, 1, RIO_RECEIVE_FLAGS.NONE, buf.Index))
                    WinSock.ThrowLastWSAError();
            }
            else
                ThreadPool.QueueUserWorkItem(o =>
                {
                    var b = ReceiveBufferPool.GetBuffer();
                    if (!RioStatic.Receive(_requestQueue, ReceiveBufferPool.GetBuffer().SegmentPointer, 1, RIO_RECEIVE_FLAGS.NONE, b.Index))
                        WinSock.ThrowLastWSAError();
                }, null);
        }

        public unsafe void WriteFixed(byte[] buffer)
        {
            var currentSegment = SendBufferPool.GetBuffer();
            fixed (byte* p = &buffer[0])
            {
                Buffer.MemoryCopy(p, currentSegment.RawPointer, currentSegment.TotalLength, buffer.Length);
            }
            currentSegment.SegmentPointer->Length = buffer.Length;
            SendInternal(currentSegment, RIO_SEND_FLAGS.NONE);
        }

        public virtual void Dispose()
        {
            WinSock.closesocket(Socket);
        }

        public int SetSocketOption(IPPROTO_IP_SocketOptions option, IntPtr value, int valueLength)
        {
            return WinSock.setsockopt(Socket, WinSock.IPPROTO_IP, (int)option, (char*)value.ToPointer(), valueLength);
        }

        public int SetSocketOption(IPPROTO_IPV6_SocketOptions option, IntPtr value, int valueLength)
        {
            return WinSock.setsockopt(Socket, WinSock.IPPROTO_IPV6, (int)option, (char*)value.ToPointer(), valueLength);
        }

        public int SetSocketOption(IPPROTO_TCP_SocketOptions option, IntPtr value, int valueLength)
        {
            return WinSock.setsockopt(Socket, WinSock.IPPROTO_TCP, (int)option, (char*)value.ToPointer(), valueLength);
        }

        public int SetSocketOption(IPPROTO_UDP_SocketOptions option, IntPtr value, int valueLength)
        {
            return WinSock.setsockopt(Socket, WinSock.IPPROTO_UDP, (int)option, (char*)value.ToPointer(), valueLength);
        }

        public int SetSocketOption(SOL_SOCKET_SocketOptions option, IntPtr value, int valueLength)
        {
            return WinSock.setsockopt(Socket, WinSock.SOL_SOCKET, (int)option, (char*)value.ToPointer(), valueLength);
        }

        public int GetSocketOption(IPPROTO_IP_SocketOptions option, IntPtr value, int valueLength)
        {
            return WinSock.getsockopt(Socket, WinSock.IPPROTO_IP, (int)option, (char*)value.ToPointer(), &valueLength);
        }

        public int GetSocketOption(IPPROTO_IPV6_SocketOptions option, IntPtr value, int valueLength)
        {
            return WinSock.getsockopt(Socket, WinSock.IPPROTO_IPV6, (int)option, (char*)value.ToPointer(), &valueLength);
        }

        public int GetSocketOption(IPPROTO_TCP_SocketOptions option, IntPtr value, int valueLength)
        {
            return WinSock.getsockopt(Socket, WinSock.IPPROTO_TCP, (int)option, (char*)value.ToPointer(), &valueLength);
        }

        public int GetSocketOption(IPPROTO_UDP_SocketOptions option, IntPtr value, int valueLength)
        {
            return WinSock.getsockopt(Socket, WinSock.IPPROTO_UDP, (int)option, (char*)value.ToPointer(), &valueLength);
        }

        public int GetSocketOption(SOL_SOCKET_SocketOptions option, IntPtr value, int valueLength)
        {
            return WinSock.getsockopt(Socket, WinSock.SOL_SOCKET, (int)option, (char*)value.ToPointer(), &valueLength);
        }
    }
}


text:
[![Build Status](https://travis-ci.org/jorisroovers/memclient.svg?branch=master)]
(https://travis-ci.org/jorisroovers/memclient)
[![GoDoc](https://godoc.org/github.com/jorisroovers/memclient?status.svg)]
(https://godoc.org/github.com/jorisroovers/memclient)

Memclient is a simple memcached commandline client written in Go.

**Memclient is very much under development and still missing some fundamental features**

Installation:
```
# Linux
wget https://raw.githubusercontent.com/jorisroovers/memclient/bin/linux/memclient
# Mac OS X
wget https://raw.githubusercontent.com/jorisroovers/memclient/bin/osx/memclient
```
For the latest functionality, build memclient from source:
```
go build memclient.go
```

Example usage:
```bash
# To set a key:
memclient set mykey myvalue
# To retrieve a key:
memclient get mykey
# To delete a key
memclient delete mykey
# To list all available keys
memclient list
# Flush all keys (they will still show in 'list', but will return 'NOT FOUND' when fetched using 'memclient get')
memclient flush
# Print the server version
memclient version

```

Other commands:
```bash
Usage: memclient [OPTIONS] COMMAND [arg...]

Simple command-line client for Memcached

Options:
  -v, --version=false      Show the version and exit
  --host, -h="localhost"   Memcached host (or IP)
  --port, -p="11211"       Memcached port

Commands:
  set          Sets a key value pair
  get          Retrieves a key
  delete       Deletes a key
  flush        Flush all cache keys (they will still show in 'list', but will return 'NOT FOUND')
  version      Show server version
  list         Lists all keys
  stats        Print server statistics
  stat         Print a specific server statistic

Run 'memclient COMMAND --help' for more information on a command.
```

# Why memclient? #
1. I couldn't find a simple commandline tool for easily inspecting the data stored by a memcached server
2. I was looking for a good opportunity to get some more experience with Go :-)

# Contributing #
I'd love for you to contribute to memclient. Just open a pull request and I'll get right on it!
You can find a wishlist below, but I'm obviously open to any suggestions you might have!

# Development #
There is a Vagrantfile in this repository that can be used for development.

```bash
vagrant up
vagrant ssh
```

To run/build memclient:

```bash
go get github.com/jawher/mow.cli
go run memclient.go set foo bar
go run memclient.go get foo
go build memclient.go
```

To run the unit tests:
```
go test -v
```
To run the integration tests (against the memcached server in vagrant):
```
vagrant up
vagrant ssh
# reset memcached server and run tests
sudo systemctl restart memcached && go test -v -tags=integration
```

Memclient uses the [Memcached protocol](https://github.com/memcached/memcached/blob/master/doc/protocol.txt) to
talk to a memcached server.

# Wishlist #
- Pretty command output, use tables
- List: only show keys that are still active (add option to also show expired keys)
- Better error handling
- Support for other memcached commands
- Support for additional command options
- Use GoDep for dependency management
- Have a look at [GoDownDoc](https://github.com/robertkrimen/godocdown) for README generation from ```doc.go```
- ...