text:
import PropTypes from 'prop-types';
import { Formik } from 'formik';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Spin } from 'antd';
import FormContent from './FormContent';

@inject('resource')
@observer
class CreateOrUpdate extends React.Component {
  constructor(props) {
    super(props);
    const {
      match: { params },
    } = props;
    const update = !!_.get(params, 'resourceTypeName');
    this.state = {
      update,
    };
    if (update) {
      props.resource.getResourceType(params.resourceTypeName);
    }
  }

  getInitialValues = () => {
    const { update } = this.state;
    const { resource } = this.props;
    if (update) {
      const resourceTypeDetail = toJS(
        _.get(resource, 'resourceTypeDetail'),
        {}
      );
      if (resourceTypeDetail) {
        const paramBindings = _.get(
          resourceTypeDetail,
          'spec.bind.paramBindings',
          {}
        );
        const parameters = _.get(resourceTypeDetail, 'spec.parameters', []);
        parameters.forEach(v => {
          if (paramBindings[`${v.name}`]) {
            v.binding = paramBindings[`${v.name}`];
          }
        });
      }
      return resourceTypeDetail;
    }

    return { spec: { parameters: [] } };
  };

  validate = values => {
    const errors = {};
    if (!values.spec.type) {
      errors.spec = _.merge(errors.spec, {
        type: intl.get('resource.messages.typeRequired'),
      });
    }

    if (!values.spec.resolver) {
      errors.spec = _.merge(errors.spec, {
        resolver: intl.get('resource.messages.resolverRequired'),
      });
    }

    if (values.spec.parameters) {
      _.forEach(values.spec.parameters, value => {
        if (!value.name) {
          errors.spec = _.merge(errors.spec, {
            parameters: intl.get('resource.messages.parameterNameRequired'),
          });
        }
      });
    }

    return errors;
  };

  submit = values => {
    values.metadata = {
      name: `resource-type-${_.toLower(values.spec.type)}`,
      labels: {
        'resource.cyclone.dev/template': 'true',
      },
    };

    const bindType = _.get(values, 'spec.bind.integrationType');
    const parameters = _.get(values, 'spec.parameters');

    if (bindType && parameters) {
      const paramBindings = {};
      parameters.forEach(v => {
        if (v.binding) {
          paramBindings[`${v.name}`] = v.binding;
        }
      });
      values.spec.bind = _.assign(values.spec.bind, paramBindings);
    }

    const { update } = this.state;
    const { resource, history } = this.props;
    if (update) {
      resource.updateResourceType(values.spec.type, values, () => {
        history.replace(`/resource/${values.spec.type}`);
      });
    } else {
      resource.createResourceType(values, () => {
        history.replace('/resource');
      });
    }
  };

  render() {
    const { history, resource } = this.props;
    if (resource.resourceTypeLoading) {
      return <Spin />;
    }
    const initValue = this.getInitialValues();

    return (
      <Formik
        initialValues={initValue}
        validate={this.validate}
        onSubmit={this.submit}
        render={props => (
          <FormContent
            {...props}
            history={history}
            update={this.state.update}
          />
        )}
      />
    );
  }
}

CreateOrUpdate.propTypes = {
  resource: PropTypes.object,
  history: PropTypes.object,
  match: PropTypes.object,
  setFieldValue: PropTypes.func,
};

export default CreateOrUpdate;


text:
package com.faceunity.gles.core;

import android.content.Context;
import android.opengl.GLES20;

/**
 * Created by tujh on 2018/1/24.
 */

public abstract class Program {
    private static final String TAG = GlUtil.TAG;

    // Handles to the GL program and various components of it.
    protected int mProgramHandle;

    protected Drawable2d mDrawable2d;

    /**
     * Prepares the program in the current EGL context.
     */
    public Program(String VERTEX_SHADER, String FRAGMENT_SHADER_2D) {
        mProgramHandle = GlUtil.createProgram(VERTEX_SHADER, FRAGMENT_SHADER_2D);
        mDrawable2d = getDrawable2d();
        getLocations();
    }

    public Program(Context context, int vertexShaderResourceId, int fragmentShaderResourceId) {
        this(Extensions.readTextFileFromResource(context, vertexShaderResourceId), Extensions.readTextFileFromResource(context, fragmentShaderResourceId));
    }

    public void updateVertexArray(float[] FULL_RECTANGLE_COORDS) {
        mDrawable2d.updateVertexArray(FULL_RECTANGLE_COORDS);
    }

    public void updateTexCoordArray(float[] FULL_RECTANGLE_TEX_COORDS) {
        mDrawable2d.updateTexCoordArray(FULL_RECTANGLE_TEX_COORDS);
    }

    protected abstract Drawable2d getDrawable2d();

    /**
     * get locations of attributes and uniforms
     */
    protected abstract void getLocations();

    /**
     * Issues the draw call.  Does the full setup on every call.
     */
    public abstract void drawFrame(int textureId, float[] texMatrix, float[] mvpMatrix);

    public void drawFrame(int textureId, float[] texMatrix) {
        drawFrame(textureId, texMatrix, GlUtil.IDENTITY_MATRIX);
    }

    public void drawFrame(int textureId, float[] texMatrix, float[] mvpMatrix, int x, int y, int width, int height) {
        int[] originalViewport = new int[4];
        GLES20.glGetIntegerv(GLES20.GL_VIEWPORT, originalViewport, 0);
        GLES20.glViewport(x, y, width, height);
        drawFrame(textureId, texMatrix, mvpMatrix);
        GLES20.glViewport(originalViewport[0], originalViewport[1], originalViewport[2], originalViewport[3]);
    }

    /**
     * Releases the program.
     * <p>
     * The appropriate EGL context must be current (i.e. the one that was used to create
     * the program).
     */
    public void release() {
        GLES20.glDeleteProgram(mProgramHandle);
        mProgramHandle = -1;
    }
}

redpajama_set_name: RedPajamaGithub


text:
const path = require('path')
const webpack = require('webpack')
const UnminifiedWebpackPlugin = require('unminified-webpack-plugin')
const isProduction = process.env.NODE_ENV === 'production'

const plugins = []
const externals = []
if (isProduction) {
  plugins.push(
    new webpack.optimize.UglifyJsPlugin({minimize: true}),
    new UnminifiedWebpackPlugin()
  )
  externals.push('jquery')
}

module.exports = {
  devtool: 'source-map',
  entry: ['./src/vtree'],
  output: {
    path: path.resolve('./build'),
    filename: 'vtree.min.js',
    library: 'Vtree',
    libraryTarget: 'umd'
  },
  resolve: {
    root: process.cwd(),
    modulesDirectories: ['node_modules'],
    extensions: ['', '.js', '.coffee', '.ejs']
  },
  module: {
    loaders: [
      {
        test: /\.coffee$/,
        loaders: ['coffee']
      },
      {
        test: /\.ejs$/,
        loaders: ['ejs']
      }
    ]
  },
  plugins: plugins,
  externals: externals,
  devServer: {
    stats: 'errors-only'
  }
}


text:
TODO
====

* Add support for multiple image-diff applications
    * resemble.js
    * image-diff
    * perceptual-diff
* Improve key-value storage
* Add Kobold Server to approve and view screens


text:
class Profile;

namespace base {
class FilePath;
class SequencedTaskRunner;
}

namespace drive {

class DebugInfoCollector;
class DownloadHandler;
class DriveAppRegistry;
class DriveServiceInterface;
class EventLogger;
class FileSystemInterface;
class JobListInterface;

namespace internal {
class FileCache;
class ResourceMetadata;
class ResourceMetadataStorage;
}  // namespace internal

// Interface for classes that need to observe events from
// DriveIntegrationService.  All events are notified on UI thread.
class DriveIntegrationServiceObserver {
 public:
  // Triggered when the file system is mounted.
  virtual void OnFileSystemMounted() {
  }

  // Triggered when the file system is being unmounted.
  virtual void OnFileSystemBeingUnmounted() {
  }

 protected:
  virtual ~DriveIntegrationServiceObserver() {}
};

// DriveIntegrationService is used to integrate Drive to Chrome. This class
// exposes the file system representation built on top of Drive and some
// other Drive related objects to the file manager, and some other sub
// systems.
//
// The class is essentially a container that manages lifetime of the objects
// that are used to integrate Drive to Chrome. The object of this class is
// created per-profile.
class DriveIntegrationService : public KeyedService,
                                public DriveNotificationObserver,
                                public content::NotificationObserver {
 public:
  class PreferenceWatcher;

  // test_drive_service, test_mount_point_name, test_cache_root and
  // test_file_system are used by tests to inject customized instances.
  // Pass NULL or the empty value when not interested.
  // |preference_watcher| observes the drive enable preference, and sets the
  // enable state when changed. It can be NULL. The ownership is taken by
  // the DriveIntegrationService.
  DriveIntegrationService(
      Profile* profile,
      PreferenceWatcher* preference_watcher,
      DriveServiceInterface* test_drive_service,
      const std::string& test_mount_point_name,
      const base::FilePath& test_cache_root,
      FileSystemInterface* test_file_system);
  ~DriveIntegrationService() override;

  // KeyedService override:
  void Shutdown() override;

  void SetEnabled(bool enabled);
  bool is_enabled() const { return enabled_; }

  bool IsMounted() const;

  // Adds and removes the observer.
  void AddObserver(DriveIntegrationServiceObserver* observer);
  void RemoveObserver(DriveIntegrationServiceObserver* observer);

  // DriveNotificationObserver implementation.
  void OnNotificationReceived() override;
  void OnPushNotificationEnabled(bool enabled) override;

  EventLogger* event_logger() { return logger_.get(); }
  DriveServiceInterface* drive_service() { return drive_service_.get(); }
  DebugInfoCollector* debug_info_collector() {
    return debug_info_collector_.get();
  }
  FileSystemInterface* file_system() { return file_system_.get(); }
  DownloadHandler* download_handler() { return download_handler_.get(); }
  DriveAppRegistry* drive_app_registry() { return drive_app_registry_.get(); }
  JobListInterface* job_list() { return scheduler_.get(); }

  // Clears all the local cache file, the local resource metadata, and
  // in-memory Drive app registry, and remounts the file system. |callback|
  // is called with true when this operation is done successfully. Otherwise,
  // |callback| is called with false. |callback| must not be null.
  void ClearCacheAndRemountFileSystem(
      const base::Callback<void(bool)>& callback);

 private:
  enum State {
    NOT_INITIALIZED,
    INITIALIZING,
    INITIALIZED,
    REMOUNTING,
  };

  // Returns true if Drive is enabled.
  // Must be called on UI thread.
  bool IsDriveEnabled();

  // Registers remote file system for drive mount point.
  void AddDriveMountPoint();
  // Unregisters drive mount point from File API.
  void RemoveDriveMountPoint();

  // Adds back the drive mount point.
  // Used to implement ClearCacheAndRemountFileSystem().
  void AddBackDriveMountPoint(const base::Callback<void(bool)>& callback,
                              FileError error);

  // Initializes the object. This function should be called before any
  // other functions.
  void Initialize();

  // Called when metadata initialization is done. Continues initialization if
  // the metadata initialization is successful.
  void InitializeAfterMetadataInitialized(FileError error);

  // Change the download directory to the local "Downloads" if the download
  // destination is set under Drive. This must be called when disabling Drive.
  void AvoidDriveAsDownloadDirecotryPreference();

  // content::NotificationObserver overrides.
  void Observe(int type,
               const content::NotificationSource& source,
               const content::NotificationDetails& details) override;

  friend class DriveIntegrationServiceFactory;

  Profile* profile_;
  State state_;
  bool enabled_;
  // Custom mount point name that can be injected for testing in constructor.
  std::string mount_point_name_;

  base::FilePath cache_root_directory_;
  scoped_ptr<EventLogger> logger_;
  scoped_refptr<base::SequencedTaskRunner> blocking_task_runner_;
  scoped_refptr<base::SingleThreadTaskRunner> file_task_runner_;
  scoped_ptr<internal::ResourceMetadataStorage,
             util::DestroyHelper> metadata_storage_;
  scoped_ptr<internal::FileCache, util::DestroyHelper> cache_;
  scoped_ptr<DriveServiceInterface> drive_service_;
  scoped_ptr<JobScheduler> scheduler_;
  scoped_ptr<DriveAppRegistry> drive_app_registry_;
  scoped_ptr<internal::ResourceMetadata,
             util::DestroyHelper> resource_metadata_;
  scoped_ptr<FileSystemInterface> file_system_;
  scoped_ptr<DownloadHandler> download_handler_;
  scoped_ptr<DebugInfoCollector> debug_info_collector_;

  base::ObserverList<DriveIntegrationServiceObserver> observers_;
  scoped_ptr<PreferenceWatcher> preference_watcher_;
  scoped_ptr<content::NotificationRegistrar> profile_notification_registrar_;

  // Note: This should remain the last member so it'll be destroyed and
  // invalidate its weak pointers before any other members are destroyed.
  base::WeakPtrFactory<DriveIntegrationService> weak_ptr_factory_;
  DISALLOW_COPY_AND_ASSIGN(DriveIntegrationService);
};

// Singleton that owns all instances of DriveIntegrationService and
// associates them with Profiles.
class DriveIntegrationServiceFactory
    : public BrowserContextKeyedServiceFactory {
 public:
  // Factory function used by tests.
  typedef base::Callback<DriveIntegrationService*(Profile* profile)>
      FactoryCallback;

  // Sets and resets a factory function for tests. See below for why we can't
  // use BrowserContextKeyedServiceFactory::SetTestingFactory().
  class ScopedFactoryForTest {
   public:
    explicit ScopedFactoryForTest(FactoryCallback* factory_for_test);
    ~ScopedFactoryForTest();
  };

  // Returns the DriveIntegrationService for |profile|, creating it if it is
  // not yet created.
  static DriveIntegrationService* GetForProfile(Profile* profile);

  // Returns the DriveIntegrationService that is already associated with
  // |profile|, if it is not yet created it will return NULL.
  static DriveIntegrationService* FindForProfile(Profile* profile);

  // Returns the DriveIntegrationServiceFactory instance.
  static DriveIntegrationServiceFactory* GetInstance();

 private:
  friend struct DefaultSingletonTraits<DriveIntegrationServiceFactory>;

  DriveIntegrationServiceFactory();
  ~DriveIntegrationServiceFactory() override;

  // BrowserContextKeyedServiceFactory overrides.
  content::BrowserContext* GetBrowserContextToUse(
      content::BrowserContext* context) const override;
  KeyedService* BuildServiceInstanceFor(
      content::BrowserContext* context) const override;

  // This is static so it can be set without instantiating the factory. This
  // allows factory creation to be delayed until it normally happens (on profile
  // creation) rather than when tests are set up. DriveIntegrationServiceFactory
  // transitively depends on ExtensionSystemFactory which crashes if created too
  // soon (i.e. before the BrowserProcess exists).
  static FactoryCallback* factory_for_test_;
};

}  // namespace drive

#endif  // CHROME_BROWSER_CHROMEOS_DRIVE_DRIVE_INTEGRATION_SERVICE_H_


text:
package cn.easyproject.easyee.ssh.sys.service.impl;

import javax.annotation.Resource;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import cn.easyproject.easyee.sh.base.util.SpringUtil;
import cn.easyproject.easyee.sh.sys.service.SysOperationPermissionService;
import ognl.OgnlException;
@RunWith(SpringJUnit4ClassRunner.class) //测试运行器
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class SysOperationPermissionServiceTest {
	@Resource(name="sysOperationPermissionService")
	SysOperationPermissionService sysOperationPermissionService;
//	SysOperationPermissionService sysOperationPermissionService=SpringUtil.getBean("sysOperationPermissionService");

	@org.junit.Test
	public void testList() throws OgnlException {
		// 查询所有操作权限
		System.out.println(sysOperationPermissionService);
//		System.out.println(sysOperationPermissionService.list(3));
		System.out.println(sysOperationPermissionService.getAllOpreationNames());

	}

}


text:
using namespace dbc;

#if _DEBUG || DEBUG
#define NewToken(Type) new dbc::Token(Type, LineCount);
#define DeleteToken(T)
#else
#define NewToken(Type) std::make_shared<dbc::Token>(Type, LineCount);
#define DeleteToken(T) T.reset<dbc::Token>(nullptr);
#endif

#define LexerError(Message, ...) \
		fprintf(stderr, "\n%s ", SourcePath); \
		fprintf(stderr, "Line %zu Lexing Error: ", LineCount); \
		fprintf(stderr, Message, ##__VA_ARGS__); \
		fprintf(stderr, "\n"); \
		PAUSE; \
		exit(-1);

dbc::LexicalAnalyzer::LexicalAnalyzer(const char * File) :
	Index(0),
	Length(0),
	LineCount(1),
	LastChar(-1),
	SourcePath(File)
{}

dbc::LexicalAnalyzer::~LexicalAnalyzer()
{
	ResetTokenStream();
}

std::deque<TokenPtr>& dbc::LexicalAnalyzer::Analyze(const std::string & _Source)
{
	ResetTokenStream();
	Source = _Source;
	Length = Source.length();
	while (!Eof())
	{
		TokenPtr Token = nullptr;
		LastChar = GetNextChar();
		if (LastChar == -1) break;
		else if (ScanEmptySpace()) continue;
		else if (ScanLinefeed(Token));
		else if (ScanSymbols(Token));
		else if (ScanKeywords(Token));
		else if (ScanTerminalSymbols(Token));
		else
		{
			LexerError("Invalid symbol \"%c\" [ASCII=%d]", LastChar, LastChar);
			break;
		}
		if (Token != nullptr)
		{
			TokenStream.push_back(std::move(Token));
		}
	}
	return TokenStream;
}

void dbc::LexicalAnalyzer::ResetTokenStream()
{
	while (TokenStream.size() > 0)
	{
		DeleteToken(TokenStream.front());
		TokenStream.pop_front();
	}
}

bool dbc::LexicalAnalyzer::CheckPair(char value)
{
	return CheckPair(value, value);;
}

bool dbc::LexicalAnalyzer::CheckPair(char value0, char value1)
{
	return (LastChar == value0 && PeekChar() == value1);
}

char dbc::LexicalAnalyzer::PeekChar(size_t Step)
{
	if (!Eof(Step)) return Source[Step + Index];
	return -1;
}

char dbc::LexicalAnalyzer::GetNextChar()
{
	if (!Eof()) return LastChar = Source[Index++];
	return -1;
}

void dbc::LexicalAnalyzer::SubOneIndex()
{
	--Index;
}

bool dbc::LexicalAnalyzer::Eof(size_t Step)
{
	return (Index + Step >= Length);
}

bool dbc::LexicalAnalyzer::ScanKeywordName(const char * Keyword)
{
	if (LastChar == Keyword[0])
	{
		int64 Index;
		int64 Length = strlen(Keyword);
		for (Index = 0; Index < Length; ++Index)
		{
			if (PeekChar(Index - 1) != Keyword[Index])
			{
				return false;
			}
		}
		for (Index = 0; Index < Length; ++Index)
		{
			GetNextChar();
		}
		SubOneIndex();
		return true;
	}
	return false;
}

bool dbc::LexicalAnalyzer::ScanCharInString(char Value, const char * Test)
{
	int64 Length = strlen(Test);
	for (int64 Index = 0; Index < Length; ++Index)
	{
		if (Test[Index] == Value)
		{
			return true;
		}
	}
	return false;
}

bool dbc::LexicalAnalyzer::ScanEmptySpace()
{
	return (ScanWhitespace() || ScanComment());
}

bool dbc::LexicalAnalyzer::ScanSymbols(TokenPtr & Token)
{
	if (ScanNotEqu(Token)) return true;
	if (ScanLTEQU(Token)) return true;
	if (ScanGTEQU(Token)) return true;
	if (ScanEqu(Token)) return true;
	if (ScanLT(Token)) return true;
	if (ScanGT(Token)) return true;
	if (ScanPlus(Token)) return true;
	if (ScanMinus(Token)) return true;
	if (ScanSlash(Token)) return true;
	if (ScanAsterisk(Token)) return true;
	if (ScanComma(Token)) return true;
	if (ScanLParen(Token)) return true;
	if (ScanRParen(Token)) return true;
	if (ScanLSQBrack(Token)) return true;
	if (ScanRSQBrack(Token)) return true;
	return false;
}

bool dbc::LexicalAnalyzer::ScanKeywords(TokenPtr & Token)
{
	if (ScanWordNative(Token)) return true;
	if (ScanWordFunc(Token)) return true;
	if (ScanWordIf(Token)) return true;
	if (ScanWordElseIf(Token)) return true;
	if (ScanWordElse(Token)) return true;
	if (ScanWordLet(Token)) return true;
	if (ScanWordEnd(Token)) return true;
	if (ScanWordRet(Token)) return true;
	if (ScanWordAnd(Token)) return true;
	if (ScanWordOr(Token)) return true;
	if (ScanWordBand(Token)) return true;
	if (ScanWordXor(Token)) return true;
	if (ScanWordBor(Token)) return true;
	if (ScanWordShl(Token)) return true;
	if (ScanWordShr(Token)) return true;
	if (ScanWordMod(Token)) return true;
	if (ScanWordWhile(Token)) return true;
	if (ScanWordNot(Token)) return true;
	return false;
}

bool dbc::LexicalAnalyzer::ScanTerminalSymbols(TokenPtr & Token)
{
	if (ScanBoolean(Token)) return true;
	if (ScanNumber(Token)) return true;
	if (ScanIdentifier(Token)) return true;
	return false;
}

#pragma region Whitespace
bool dbc::LexicalAnalyzer::ScanLinefeed(TokenPtr& Token)
{
	return false;
}
bool dbc::LexicalAnalyzer::ScanWhitespace()
{
	if (LastChar == LF)
	{
		++LineCount;
		return true;
	}
	return LastChar == 32 || LastChar == ' ' || LastChar == '\r' || LastChar == '\t';
}

bool dbc::LexicalAnalyzer::ScanComment()
{
	if (LastChar == '#')
	{
		while (LastChar != LF)
		{
			GetNextChar();
		}
		++LineCount;
		return true;
	}
	return false;
}
#pragma endregion
#pragma region Symbols
bool dbc::LexicalAnalyzer::ScanNotEqu(TokenPtr & Token)
{
	if (CheckPair('<', '>'))
	{
		Token = NewToken(TokenType::SYM_NOTEQU);
		GetNextChar();
		return true;
	}
	return false;
}

bool dbc::LexicalAnalyzer::ScanEqu(TokenPtr & Token)
{
	if (LastChar == '=')
	{
		Token = NewToken(TokenType::SYM_EQU);
		return true;
	}
	return false;
}

bool dbc::LexicalAnalyzer::ScanLT(TokenPtr & Token)
{
	if (LastChar == '<')
	{
		Token = NewToken(TokenType::SYM_LT);
		return true;
	}
	return false;
}

bool dbc::LexicalAnalyzer::ScanGT(TokenPtr & Token)
{
	if (LastChar == '>')
	{
		Token = NewToken(TokenType::SYM_GT);
		return true;
	}
	return false;
}

bool dbc::LexicalAnalyzer::ScanLTEQU(TokenPtr & Token)
{
	if (CheckPair('<', '='))
	{
		Token = NewToken(TokenType::SYM_LTEQU);
		GetNextChar();
		return true;
	}
	return false;
}

bool dbc::LexicalAnalyzer::ScanGTEQU(TokenPtr & Token)
{
	if (CheckPair('>', '='))
	{
		Token = NewToken(TokenType::SYM_GTEQU);
		GetNextChar();
		return true;
	}
	return false;
}

bool dbc::LexicalAnalyzer::ScanPlus(TokenPtr & Token)
{
	if (LastChar == '+')
	{
		Token = NewToken(TokenType::SYM_PLUS);
		return true;
	}
	return false;
}

bool dbc::LexicalAnalyzer::ScanMinus(TokenPtr & Token)
{
	if (LastChar == '-')
	{
		Token = NewToken(TokenType::SYM_MINUS);
		return true;
	}
	return false;
}

bool dbc::LexicalAnalyzer::ScanSlash(TokenPtr & Token)
{
	if (LastChar == '/')
	{
		Token = NewToken(TokenType::SYM_SLASH);
		return true;
	}
	return false;
}

bool dbc::LexicalAnalyzer::ScanAsterisk(TokenPtr & Token)
{
	if (LastChar == '*')
	{
		Token = NewToken(TokenType::SYM_ASTERISK);
		return true;
	}
	return false;
}

bool dbc::LexicalAnalyzer::ScanComma(TokenPtr & Token)
{
	if (LastChar == ',')
	{
		Token = NewToken(TokenType::SYM_COMMA);
		return true;
	}
	return false;
}

bool dbc::LexicalAnalyzer::ScanLParen(TokenPtr & Token)
{
	if (LastChar == '(')
	{
		Token = NewToken(TokenType::SYM_LPAREN);
		return true;
	}
	return false;
}

bool dbc::LexicalAnalyzer::ScanRParen(TokenPtr & Token)
{
	if (LastChar == ')')
	{
		Token = NewToken(TokenType::SYM_RPAREN);
		return true;
	}
	return false;
}
bool dbc::LexicalAnalyzer::ScanLSQBrack(TokenPtr & Token)
{
	if (LastChar == '[')
	{
		Token = NewToken(TokenType::SYM_LSQBRACK);
		return true;
	}
	return false;
}
bool dbc::LexicalAnalyzer::ScanRSQBrack(TokenPtr & Token)
{
	if (LastChar == ']')
	{
		Token = NewToken(TokenType::SYM_RSQBRACK);
		return true;
	}
	return false;
}
#pragma endregion
#pragma region Keywords
bool dbc::LexicalAnalyzer::ScanWordNot(TokenPtr & Token)
{
	if (ScanKeywordName(KEYWORD_NOT))
	{
		Token = NewToken(TokenType::WORD_NOT);
		return true;
	}
	return false;
}

bool dbc::LexicalAnalyzer::ScanWordFunc(TokenPtr & Token)
{
	if (ScanKeywordName(KEYWORD_FUNC))
	{
		Token = NewToken(TokenType::WORD_FUNC);
		return true;
	}
	return false;
}

bool dbc::LexicalAnalyzer::ScanWordIf(TokenPtr & Token)
{
	if (ScanKeywordName(KEYWORD_IF))
	{
		Token = NewToken(TokenType::WORD_IF);
		return true;
	}
	return false;
}

bool dbc::LexicalAnalyzer::ScanWordElseIf(TokenPtr & Token)
{
	if (ScanKeywordName(KEYWORD_ELSEIF))
	{
		Token = NewToken(TokenType::WORD_ELSEIF);
		return true;
	}
	return false;
}

bool dbc::LexicalAnalyzer::ScanWordElse(TokenPtr & Token)
{
	if (ScanKeywordName(KEYWORD_ELSE))
	{
		Token = NewToken(TokenType::WORD_ELSE);
		return true;
	}
	return false;
}

bool dbc::LexicalAnalyzer::ScanWordLet(TokenPtr & Token)
{
	if (ScanKeywordName(KEYWORD_LET))
	{
		Token = NewToken(TokenType::WORD_LET);
		return true;
	}
	return false;
}

bool dbc::LexicalAnalyzer::ScanWordEnd(TokenPtr & Token)
{
	if (ScanKeywordName(KEYWORD_END))
	{
		Token = NewToken(TokenType::WORD_END);
		return true;
	}
	return false;
}

bool dbc::LexicalAnalyzer::ScanWordRet(TokenPtr & Token)
{
	if (ScanKeywordName(KEYWORD_RET))
	{
		Token = NewToken(TokenType::WORD_RET);
		return true;
	}
	return false;
}
bool dbc::LexicalAnalyzer::ScanWordAnd(TokenPtr & Token)
{
	if (ScanKeywordName(KEYWORD_AND))
	{
		Token = NewToken(TokenType::WORD_AND);
		return true;
	}
	return false;
}
bool dbc::LexicalAnalyzer::ScanWordOr(TokenPtr & Token)
{
	if (ScanKeywordName(KEYWORD_OR))
	{
		Token = NewToken(TokenType::WORD_OR);
		return true;
	}
	return false;
}
bool dbc::LexicalAnalyzer::ScanWordWhile(TokenPtr & Token)
{
	if (ScanKeywordName(KEYWORD_WHILE))
	{
		Token = NewToken(TokenType::WORD_WHILE);
		return true;
	}
	return false;
}
bool dbc::LexicalAnalyzer::ScanWordBand(TokenPtr & Token)
{
	if (ScanKeywordName(KEYWORD_BAND))
	{
		Token = NewToken(TokenType::WORD_BAND);
		return true;
	}
	return false;
}
bool dbc::LexicalAnalyzer::ScanWordMod(TokenPtr & Token)
{
	if (ScanKeywordName(KEYWORD_MOD))
	{
		Token = NewToken(TokenType::WORD_MOD);
		return true;
	}
	return false;
}
bool dbc::LexicalAnalyzer::ScanWordXor(TokenPtr & Token)
{
	if (ScanKeywordName(KEYWORD_XOR))
	{
		Token = NewToken(TokenType::WORD_XOR);
		return true;
	}
	return false;
}
bool dbc::LexicalAnalyzer::ScanWordBor(TokenPtr & Token)
{
	if (ScanKeywordName(KEYWORD_BOR))
	{
		Token = NewToken(TokenType::WORD_BOR);
		return true;
	}
	return false;
}
bool dbc::LexicalAnalyzer::ScanWordShl(TokenPtr & Token)
{
	if (ScanKeywordName(KEYWORD_SHL))
	{
		Token = NewToken(TokenType::WORD_SHL);
		return true;
	}
	return false;
}
bool dbc::LexicalAnalyzer::ScanWordShr(TokenPtr & Token)
{
	if (ScanKeywordName(KEYWORD_SHR))
	{
		Token = NewToken(TokenType::WORD_SHR);
		return true;
	}
	return false;
}
bool dbc::LexicalAnalyzer::ScanWordNative(TokenPtr & Token)
{
	if (ScanKeywordName(KEYWORD_NATIVE))
	{
		Token = NewToken(TokenType::WORD_NATIVE);
		GetNextChar();
		Token->RawValue += LastChar;
		GetNextChar();
		while (!ScanKeywordName(KEYWORD_END))
		{
			if (LastChar == '\n')
				++LineCount;
			Token->RawValue += LastChar;
			GetNextChar();
		}
		return true;
	}
	return false;
}
#pragma endregion
#pragma region Terminals
bool dbc::LexicalAnalyzer::ScanNumber(TokenPtr & Token)
{
	if (ScanCharInString(LastChar, WORD_DIGIT))
	{
		Token = NewToken(TokenType::NUMBER);
		Token->RawValue += LastChar;
		GetNextChar();
		while (ScanCharInString(LastChar, WORD_DIGIT))
		{
			Token->RawValue += LastChar;
			GetNextChar();
		}
		SubOneIndex();
		return true;
	}
	return false;
}
bool dbc::LexicalAnalyzer::ScanBoolean(TokenPtr & Token)
{
	if (ScanKeywordName(KEYWORD_TRUE))
	{
		Token = NewToken(TokenType::BOOLEAN);
		Token->RawValue = "1";
		return true;
	}
	else if (ScanKeywordName(KEYWORD_FALSE))
	{
		Token = NewToken(TokenType::BOOLEAN);
		Token->RawValue = "0";
		return true;
	}
	return false;
}
bool dbc::LexicalAnalyzer::ScanIdentifier(TokenPtr & Token)
{
	if (ScanCharInString(LastChar, WORD_ALPHA))
	{
		Token = NewToken(TokenType::IDENTIFIER);
		Token->RawValue += LastChar;
		GetNextChar();
		while (ScanCharInString(LastChar, WORD_ALPHA) ||
			   ScanCharInString(LastChar, WORD_DIGIT))
		{
			Token->RawValue += LastChar;
			GetNextChar();
		}
		SubOneIndex();
		return true;
	}
	return false;
}
#pragma endregion


text:
@implementation MOMABaseModel

@end


text:
<?php

namespace KoolKode\Async\Channel;

use KoolKode\Async\CancellationException;
use KoolKode\Async\Context;
use KoolKode\Async\Failure;
use KoolKode\Async\Success;
use KoolKode\Async\Test\AsyncTestCase;

/**
 * @covers \KoolKode\Async\Channel\IterableChannel
 */
class IterableChannelTest extends AsyncTestCase
{
    public function provideItems()
    {
        yield [
            range(1, 5)
        ];

        yield [
            new \ArrayObject(range(1, 5))
        ];

        yield [
            call_user_func(function () {
                foreach (range(1, 5) as $i) {
                    yield $i;
                }
            })
        ];

        yield [
            (object) range(1, 5)
        ];
    }

    /**
     * @dataProvider provideItems
     */
    public function testConvertToIterator(Context $context, $items)
    {
        $input = new IterableChannel($items);
        $result = [];

        while (null !== ($value = yield $input->receive($context))) {
            $result[] = $value;
        }

        $this->assertEquals(range(1, 5), $result);
    }

    public function testDetectsInvalidIterable()
    {
        $this->expectException(\InvalidArgumentException::class);

        new IterableChannel(123);
    }

    public function testCanCloseChannel(Context $context)
    {
        $channel = new IterableChannel(range(1, 5));
        $this->assertEquals(1, yield $channel->receive($context));

        $channel->close();
        $this->assertNull(yield $channel->receive($context));

        $channel->close();
        $this->assertSame($this, yield $channel->receive($context, $this));
    }

    public function testCanCloseChannelWithError(Context $context)
    {
        $channel = new IterableChannel(range(1, 5));
        $this->assertEquals(1, yield $channel->receive($context));

        $channel->close(new \LogicException('Fail!'));

        $this->expectException(\LogicException::class);

        yield $channel->receive($context);
    }

    public function testWillForwardPromises(Context $context)
    {
        $channel = new IterableChannel([
            $context->delay(10, 1),
            new Success($context, 2),
            3
        ]);

        $result = [];

        while (null !== ($i = yield $channel->receive($context))) {
            $result[] = $i;
        }

        $this->assertEquals(range(1, 3), $result);
    }

    public function testFailedPromiseFailsReceive(Context $context)
    {
        $channel = new IterableChannel([
            123,
            new Failure($context, new \LogicException('Fail'))
        ]);

        $this->assertEquals(123, yield $channel->receive($context));

        $this->expectException(\LogicException::class);

        yield $channel->receive($context);
    }

    public function testFailedPromiseClosesChannelWithError(Context $context)
    {
        $channel = new IterableChannel([
            123,
            new Failure($context, new \LogicException('Fail'))
        ]);

        $this->assertEquals(123, yield $channel->receive($context));

        $channel->receive($context);

        $this->expectException(\LogicException::class);

        yield $channel->receive($context);
    }

    public function testCanCancelReceive(Context $context)
    {
        $channel = new IterableChannel([
            $context->delay(10, 123)
        ]);

        $context = $context->cancellable($cancel = $context->cancellationHandler());

        $receive = $channel->receive($context);

        $cancel->cancel('FAIL');

        $this->expectException(CancellationException::class);

        yield $receive;
    }
}


text:
package com.home.rxtwitch.profile.following;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.MenuItem;

import com.android.debug.hv.ViewServer;
import com.home.rxtwitch.BaseActivity;
import com.home.rxtwitch.R;
import com.home.rxtwitch.profile.following.channelfollowed.ChannelFollowedFragment;
import com.home.rxtwitch.profile.following.gamefollowed.GameFollowedFragment;
import com.home.rxtwitch.profile.following.streamfollowed.StreamFollowedFragment;
import com.home.rxtwitch.ui.adapter.FragmentPagerAdapter;
import com.home.rxtwitch.ui.widget.RxToolbar;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by xmax on 2/23/16.
 */
public class FollowingActivity extends BaseActivity {

    @Bind(R.id.following_top_tab) TabLayout mFollowingTabL;
    @Bind(R.id.following_view_pager) ViewPager mViewPager;
    @Bind(R.id.general_toolbar) RxToolbar mToolbar;
    private FragmentPagerAdapter mPagerAdapter;

    public static void lunch(Activity activity) {
        Intent intent = new Intent(activity, FollowingActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_following);
        ViewServer.get(this).addWindow(this);
        ButterKnife.bind(this);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        mToolbar.setTitle(R.string.following);
        mToolbar.setToOneItem();
        setupViewPager();
        setupTabLayout();
    }

    private void setupViewPager() {
        mPagerAdapter = new FragmentPagerAdapter(this, getSupportFragmentManager());
        mPagerAdapter.addFragment(new StreamFollowedFragment(), R.drawable.selector_stream_following);
        mPagerAdapter.addFragment(new ChannelFollowedFragment(), R.drawable.selector_channel_following);
        mPagerAdapter.addFragment(new GameFollowedFragment(), R.drawable.selector_game_following);
        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.setOffscreenPageLimit(2);
    }

    private void setupTabLayout() {
        mFollowingTabL.setupWithViewPager(mViewPager);
        for (int i = 0; i < mFollowingTabL.getTabCount(); i++) {
            TabLayout.Tab tab = mFollowingTabL.getTabAt(i);
            if (tab != null) {
                tab.setCustomView(mPagerAdapter.getTabView(i, R.layout.tabbar_view));
            }
        }
        mFollowingTabL.requestFocus();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
        ViewServer.get(this).setFocusedWindow(this);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ViewServer.get(this).removeWindow(this);
        ButterKnife.unbind(this);
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
N. Amer. Fl. (New York) 10: 153 (1917)

#### Original name
Crepidotus flammeus Murrill

### Remarks
null


text:
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Web;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration;

namespace EnterpriseLibraryExample.MvcApplication
{
    /// <summary>
    /// Custom exception handler that redirects the user to a fixed URL.
    /// </summary>
    [ConfigurationElementType(typeof(CustomHandlerData))]
    public class UrlRedirectHandler : IExceptionHandler
    {
        private string _url = null;

        public UrlRedirectHandler(NameValueCollection configuration)
        {
            if (configuration != null)
            {
                this.ProcessConfiguration(configuration);
            }
        }

        public Exception HandleException(Exception exception, Guid handlingInstanceId)
        {
            if (exception == null)
            {
                return null;
            }
            var context = HttpContext.Current;
            if (context == null)
            {
                return exception;
            }
            context.ClearError();
            context.Response.Redirect(this._url, true);
            return exception;
        }

        private void ProcessConfiguration(NameValueCollection configuration)
        {
            this._url = configuration["url"];
            if (String.IsNullOrEmpty(this._url))
            {
                throw new ConfigurationErrorsException("You must provide a URL to the URL redirect handler.");
            }
        }
    }
}


text:
;( function( window ) {

	'use strict';

	var support = { animations : Modernizr.cssanimations },
		animEndEventNames = { 'WebkitAnimation' : 'webkitAnimationEnd', 'OAnimation' : 'oAnimationEnd', 'msAnimation' : 'MSAnimationEnd', 'animation' : 'animationend' },
		// animation end event name
		animEndEventName = animEndEventNames[ Modernizr.prefixed( 'animation' ) ];

	/**
	 * extend obj function
	 */
	function extend( a, b ) {
		for( var key in b ) {
			if( b.hasOwnProperty( key ) ) {
				a[key] = b[key];
			}
		}
		return a;
	}

	/**
	 * createElement function
	 * creates an element with tag = tag, className = opt.cName, innerHTML = opt.inner and appends it to opt.appendTo
	 */
	function createElement( tag, opt ) {
		var el = document.createElement( tag )
		if( opt ) {
			if( opt.cName ) {
				el.className = opt.cName;
			}
			if( opt.inner ) {
				el.innerHTML = opt.inner;
			}
			if( opt.appendTo ) {
				opt.appendTo.appendChild( el );
			}
		}
		return el;
	}

	/**
	 * FForm function
	 */
	function FForm( el, options ) {
		this.el = el;
		this.options = extend( {}, this.options );
  		extend( this.options, options );
  		this._init();
	}

	/**
	 * FForm options
	 */
	FForm.prototype.options = {
		// show progress bar
		ctrlProgress : true,
		// show navigation dots
		ctrlNavDots : true,
		// show [current field]/[total fields] status
		ctrlNavPosition : true,
		// reached the review and submit step
		onReview : function() { return false; }
	};

	/**
	 * init function
	 * initialize and cache some vars
	 */
	FForm.prototype._init = function() {
		// the form element
		this.formEl = this.el.querySelector( 'form' );

		// list of fields
		this.fieldsList = this.formEl.querySelector( 'ol.fs-fields' );

		// current field position
		this.current = 0;

		// all fields
		this.fields = [].slice.call( this.fieldsList.children );

		// total fields
		this.fieldsCount = this.fields.length;

		// show first field
		$(this.fields[ this.current ]).addClass( 'fs-current' );

		// create/add controls
		this._addControls();

		// create/add messages
		this._addErrorMsg();

		// init events
		this._initEvents();
	};

	/**
	 * addControls function
	 * create and insert the structure for the controls
	 */
	FForm.prototype._addControls = function() {
		// main controls wrapper
		this.ctrls = createElement( 'div', { cName : 'fs-controls', appendTo : this.el } );

		// continue button (jump to next field)
		this.ctrlContinue = createElement( 'button', { cName : 'fs-continue', inner : 'Continuar', appendTo : this.ctrls } );
		this._showCtrl( this.ctrlContinue );

		// navigation dots
		if( this.options.ctrlNavDots ) {
			this.ctrlNav = createElement( 'nav', { cName : 'fs-nav-dots', appendTo : this.ctrls } );
			var dots = '';
			for( var i = 0; i < this.fieldsCount; ++i ) {
				dots += i === this.current ? '<button class="fs-dot-current"></button>' : '<button disabled></button>';
			}
			this.ctrlNav.innerHTML = dots;
			this._showCtrl( this.ctrlNav );
			this.ctrlNavDots = [].slice.call( this.ctrlNav.children );
		}

		// field number status
		if( this.options.ctrlNavPosition ) {
			this.ctrlFldStatus = createElement( 'span', { cName : 'fs-numbers', appendTo : this.ctrls } );

			// current field placeholder
			this.ctrlFldStatusCurr = createElement( 'span', { cName : 'fs-number-current', inner : Number( this.current + 1 ) } );
			this.ctrlFldStatus.appendChild( this.ctrlFldStatusCurr );

			// total fields placeholder
			this.ctrlFldStatusTotal = createElement( 'span', { cName : 'fs-number-total', inner : this.fieldsCount } );
			this.ctrlFldStatus.appendChild( this.ctrlFldStatusTotal );
			this._showCtrl( this.ctrlFldStatus );
		}

		// progress bar
		if( this.options.ctrlProgress ) {
			this.ctrlProgress = createElement( 'div', { cName : 'fs-progress', appendTo : this.ctrls } );
			this._showCtrl( this.ctrlProgress );
		}
	}

	/**
	 * addErrorMsg function
	 * create and insert the structure for the error message
	 */
	FForm.prototype._addErrorMsg = function() {
		// error message
		this.msgError = createElement( 'span', { cName : 'fs-message-error', appendTo : this.el } );
	}

	/**
	 * init events
	 */
	FForm.prototype._initEvents = function() {
		var self = this;

		// show next field
		this.ctrlContinue.addEventListener( 'click', function() {
			self._nextField();
		} );

		// navigation dots
		if( this.options.ctrlNavDots ) {
			this.ctrlNavDots.forEach( function( dot, pos ) {
				dot.addEventListener( 'click', function() {
					self._showField( pos );
				} );
			} );
		}

		// jump to next field without clicking the continue button (for fields/list items with the attribute "data-input-trigger")
		this.fields.forEach( function( fld ) {
			if( fld.hasAttribute( 'data-input-trigger' ) ) {
				var input = fld.querySelector( 'input[type="radio"]' ) || /*fld.querySelector( '.cs-select' ) ||*/ fld.querySelector( 'select' ); // assuming only radio and select elements (TODO: exclude multiple selects)
				if( !input ) return;

				switch( input.tagName.toLowerCase() ) {
					case 'select' :
						input.addEventListener( 'change', function() { self._nextField(); } );
						break;

					case 'input' :
						[].slice.call( fld.querySelectorAll( 'input[type="radio"]' ) ).forEach( function( inp ) {
							inp.addEventListener( 'change', function(ev) { self._nextField(); } );
						} );
						break;

					/*
					// for our custom select we would do something like:
					case 'div' :
						[].slice.call( fld.querySelectorAll( 'ul > li' ) ).forEach( function( inp ) {
							inp.addEventListener( 'click', function(ev) { self._nextField(); } );
						} );
						break;
					*/
				}
			}
		} );

		// keyboard navigation events - jump to next field when pressing enter
		document.addEventListener( 'keydown', function( ev ) {
			if( !self.isLastStep && ev.target.tagName.toLowerCase() !== 'textarea' ) {
				var keyCode = ev.keyCode || ev.which;
				if( keyCode === 13 ) {
					ev.preventDefault();
					self._nextField();
				}
			}
		} );
	};

	/**
	 * nextField function
	 * jumps to the next field
	 */
	FForm.prototype._nextField = function( backto ) {
		if( this.isLastStep || !this._validade() || this.isAnimating ) {
			return false;
		}
		this.isAnimating = true;

		// check if on last step
		this.isLastStep = this.current === this.fieldsCount - 1 && backto === undefined ? true : false;

		// clear any previous error messages
		this._clearError();

		// current field
		var currentFld = this.fields[ this.current ];

		// save the navigation direction
		this.navdir = backto !== undefined ? backto < this.current ? 'prev' : 'next' : 'next';

		// update current field
		this.current = backto !== undefined ? backto : this.current + 1;

		if( backto === undefined ) {
			// update progress bar (unless we navigate backwards)
			this._progress();

			// save farthest position so far
			this.farthest = this.current;
		}

		// add class "fs-display-next" or "fs-display-prev" to the list of fields
		$(this.fieldsList).addClass( 'fs-display-' + this.navdir );

		// remove class "fs-current" from current field and add it to the next one
		// also add class "fs-show" to the next field and the class "fs-hide" to the current one
		$(currentFld).removeClass( 'fs-current' );
		$(currentFld).addClass( 'fs-hide' );

		if( !this.isLastStep ) {
			// update nav
			this._updateNav();

			// change the current field number/status
			this._updateFieldNumber();

			var nextField = this.fields[ this.current ];
			$(nextField).addClass( 'fs-current' );
			$(nextField).addClass( 'fs-show' );
		}

		// after animation ends remove added classes from fields
		var self = this,
			onEndAnimationFn = function( ev ) {
				if( support.animations ) {
					this.removeEventListener( animEndEventName, onEndAnimationFn );
				}

				$(self.fieldsList).removeClass( 'fs-display-' + self.navdir );
				$(currentFld).removeClass( 'fs-hide' );

				if( self.isLastStep ) {
					// show the complete form and hide the controls
					self._hideCtrl( self.ctrlNav );
					self._hideCtrl( self.ctrlProgress );
					self._hideCtrl( self.ctrlContinue );
					self._hideCtrl( self.ctrlFldStatus );
					// replace class fs-form-full with fs-form-overview
					$(self.formEl).removeClass( 'fs-form-full' );
					$(self.formEl).addClass( 'fs-form-overview' );
					$(self.formEl).addClass( 'fs-show' );
					// callback
					self.options.onReview();
				}
				else {
					$(nextField).removeClass( 'fs-show' );

					if( self.options.ctrlNavPosition ) {
						self.ctrlFldStatusCurr.innerHTML = self.ctrlFldStatusNew.innerHTML;
						self.ctrlFldStatus.removeChild( self.ctrlFldStatusNew );
						$(self.ctrlFldStatus).removeClass( 'fs-show-' + self.navdir );
					}
				}
				self.isAnimating = false;
			};

		if( support.animations ) {
			if( this.navdir === 'next' ) {
				if( this.isLastStep ) {
					currentFld.querySelector( '.fs-anim-upper' ).addEventListener( animEndEventName, onEndAnimationFn );
				}
				else {
					nextField.querySelector( '.fs-anim-lower' ).addEventListener( animEndEventName, onEndAnimationFn );
				}
			}
			else {
				nextField.querySelector( '.fs-anim-upper' ).addEventListener( animEndEventName, onEndAnimationFn );
			}
		}
		else {
			onEndAnimationFn();
		}
	}

	/**
	 * showField function
	 * jumps to the field at position pos
	 */
	FForm.prototype._showField = function( pos ) {
		if( pos === this.current || pos < 0 || pos > this.fieldsCount - 1 ) {
			return false;
		}
		this._nextField( pos );
	}

	/**
	 * updateFieldNumber function
	 * changes the current field number
	 */
	FForm.prototype._updateFieldNumber = function() {
		if( this.options.ctrlNavPosition ) {
			// first, create next field number placeholder
			this.ctrlFldStatusNew = document.createElement( 'span' );
			this.ctrlFldStatusNew.className = 'fs-number-new';
			this.ctrlFldStatusNew.innerHTML = Number( this.current + 1 );

			// insert it in the DOM
			this.ctrlFldStatus.appendChild( this.ctrlFldStatusNew );

			// add class "fs-show-next" or "fs-show-prev" depending on the navigation direction
			var self = this;
			setTimeout( function() {
				$(self.ctrlFldStatus).addClass( self.navdir === 'next' ? 'fs-show-next' : 'fs-show-prev' );
			}, 25 );
		}
	}

	/**
	 * progress function
	 * updates the progress bar by setting its width
	 */
	FForm.prototype._progress = function() {
		if( this.options.ctrlProgress ) {
			this.ctrlProgress.style.width = this.current * ( 100 / this.fieldsCount ) + '%';
		}
	}

	/**
	 * updateNav function
	 * updates the navigation dots
	 */
	FForm.prototype._updateNav = function() {
		if( this.options.ctrlNavDots ) {
			$(this.ctrlNav.querySelector( 'button.fs-dot-current' )).removeClass( 'fs-dot-current' );
			$(this.ctrlNavDots[ this.current ]).addClass( 'fs-dot-current' );
			this.ctrlNavDots[ this.current ].disabled = false;
		}
	}

	/**
	 * showCtrl function
	 * shows a control
	 */
	FForm.prototype._showCtrl = function( ctrl ) {
		$(ctrl).addClass( 'fs-show' );
	}

	/**
	 * hideCtrl function
	 * hides a control
	 */
	FForm.prototype._hideCtrl = function( ctrl ) {
		$(ctrl).removeClass( 'fs-show' );
	}

	// TODO: this is a very basic validation function. Only checks for required fields..
	FForm.prototype._validade = function() {
		var fld = this.fields[ this.current ],
			input = fld.querySelector( 'input[required]' ) || fld.querySelector( 'textarea[required]' ) || fld.querySelector( 'select[required]' ),
			error;

		if( !input ) return true;

		switch( input.tagName.toLowerCase() ) {
			case 'input' :
				if( input.type === 'radio' || input.type === 'checkbox' ) {
					var checked = 0;
					[].slice.call( fld.querySelectorAll( 'input[type="' + input.type + '"]' ) ).forEach( function( inp ) {
						if( inp.checked ) {
							++checked;
						}
					} );
					if( !checked ) {
						error = 'NOVAL';
					}
				}
				else if( input.value === '' ) {
					error = 'NOVAL';
				}
				break;

			case 'select' :
				// assuming here '' or '-1' only
				if( input.value === '' || input.value === '-1' ) {
					error = 'NOVAL';
				}
				break;

			case 'textarea' :
				if( input.value === '' ) {
					error = 'NOVAL';
				}
				break;
		}

		if( error != undefined ) {
			this._showError( error );
			return false;
		}

		return true;
	}

	// TODO
	FForm.prototype._showError = function( err ) {
		var message = '';
		switch( err ) {
			case 'NOVAL' :
				message = 'Por favor rellena el campo antes de continuar';
				break;
			case 'INVALIDEMAIL' :
				message = 'Por favor ingresa un correo electrónico válido';
				break;
			// ...
		};
		this.msgError.innerHTML = message;
		this._showCtrl( this.msgError );
	}

	// clears/hides the current error message
	FForm.prototype._clearError = function() {
		this._hideCtrl( this.msgError );
	}

	// add to global namespace
	window.FForm = FForm;

})( window );


text:
import React from 'react';
import PropTypes from 'prop-types';
import Helmet from 'react-helmet';
import _ from 'lodash';
import { connect } from 'react-redux';
import { injectIntl, FormattedMessage } from 'react-intl';
import { Form, Input } from 'antd';
import SteemConnect from '../steemConnectAPI';
import { getIsReloading, getAuthenticatedUser } from '../reducers';
import socialProfiles from '../helpers/socialProfiles';
import withEditor from '../components/Editor/withEditor';
import EditorInput from '../components/Editor/EditorInput';
import { remarkable } from '../components/Story/Body';
import BodyContainer from '../containers/Story/BodyContainer';
import Action from '../components/Button/Action';
import Affix from '../components/Utils/Affix';
import LeftSidebar from '../app/Sidebar/LeftSidebar';
import requiresLogin from '../auth/requiresLogin';
import './Settings.less';

const FormItem = Form.Item;

function mapPropsToFields(props) {
  let metadata = _.attempt(JSON.parse, props.user.json_metadata);
  if (_.isError(metadata)) metadata = {};

  const profile = metadata.profile || {};

  return Object.keys(profile).reduce(
    (a, b) => ({
      ...a,
      [b]: Form.createFormField({
        value: profile[b],
      }),
    }),
    {},
  );
}

@requiresLogin
@injectIntl
@connect(state => ({
  user: getAuthenticatedUser(state),
  reloading: getIsReloading(state),
}))
@Form.create({
  mapPropsToFields,
})
@withEditor
export default class ProfileSettings extends React.Component {
  static propTypes = {
    intl: PropTypes.shape().isRequired,
    form: PropTypes.shape().isRequired,
    onImageUpload: PropTypes.func,
    onImageInvalid: PropTypes.func,
  };

  static defaultProps = {
    onImageUpload: () => {},
    onImageInvalid: () => {},
  };

  constructor(props) {
    super(props);

    this.state = {
      bodyHTML: '',
    };

    this.handleSignatureChange = this.handleSignatureChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.renderBody = this.renderBody.bind(this);
  }

  handleSignatureChange(body) {
    _.throttle(this.renderBody, 200, { leading: false, trailing: true })(body);
  }

  handleSubmit(e) {
    e.preventDefault();
    const { form } = this.props;

    if (!form.isFieldsTouched()) return;

    form.validateFields((err, values) => {
      if (!err) {
        const cleanValues = Object.keys(values)
          .filter(field => form.isFieldTouched(field))
          .reduce(
            (a, b) => ({
              ...a,
              [b]: values[b] || '',
            }),
            {},
          );
        const win = window.open(SteemConnect.sign('profile-update', cleanValues), '_blank');
        win.focus();
      }
    });
  }

  renderBody(body) {
    this.setState({
      bodyHTML: remarkable.render(body),
    });
  }

  render() {
    const { intl, form } = this.props;
    const { bodyHTML } = this.state;
    const { getFieldDecorator } = form;

    const socialInputs = socialProfiles.map(profile => (
      <FormItem key={profile.id}>
        {getFieldDecorator(profile.id, {
          rules: [
            {
              message: intl.formatMessage({
                id: 'profile_social_profile_incorrect',
                defaultMessage:
                  "This doesn't seem to be valid username. Only alphanumeric characters, hyphens, underscores and dots are allowed.",
              }),
              pattern: /^[0-9A-Za-z-_.]+$/,
            },
          ],
        })(
          <Input
            size="large"
            prefix={
              <i
                className={`Settings__prefix-icon iconfont icon-${profile.icon}`}
                style={{
                  color: profile.color,
                }}
              />
            }
            placeholder={profile.name}
          />,
        )}
      </FormItem>
    ));

    return (

        <Helmet>
          <title>
            {intl.formatMessage({ id: 'edit_profile', defaultMessage: 'Edit profile' })} - Busy
          </title>
        </Helmet>

          <Affix className="leftContainer" stickPosition={77}>

              <LeftSidebar />

          </Affix>

              <FormattedMessage id="edit_profile" defaultMessage="Edit Profile" />

            <Form onSubmit={this.handleSubmit}>

                    <FormattedMessage id="profile_name" defaultMessage="Name" />

                    <FormItem>
                      {getFieldDecorator('name')(
                        <Input
                          size="large"
                          placeholder={intl.formatMessage({
                            id: 'profile_name_placeholder',
                            defaultMessage: 'Name to display on your profile',
                          })}
                        />,
                      )}
                    </FormItem>

                    <FormattedMessage id="profile_about" defaultMessage="About me" />

                    <FormItem>
                      {getFieldDecorator('about')(
                        <Input.TextArea
                          autosize={{ minRows: 2, maxRows: 6 }}
                          placeholder={intl.formatMessage({
                            id: 'profile_about_placeholder',
                            defaultMessage: 'Few words about you',
                          })}
                        />,
                      )}
                    </FormItem>

                    <FormattedMessage id="profile_location" defaultMessage="Location" />

                    <FormItem>
                      {getFieldDecorator('location')(
                        <Input
                          size="large"
                          placeholder={intl.formatMessage({
                            id: 'profile_location_placeholder',
                            defaultMessage: 'Your location',
                          })}
                        />,
                      )}
                    </FormItem>

                    <FormattedMessage id="profile_website" defaultMessage="Website" />

                    <FormItem>
                      {getFieldDecorator('website')(
                        <Input
                          size="large"
                          placeholder={intl.formatMessage({
                            id: 'profile_website_placeholder',
                            defaultMessage: 'Your website URL',
                          })}
                        />,
                      )}
                    </FormItem>

                    <FormattedMessage id="profile_picture" defaultMessage="Profile picture" />

                    <FormItem>
                      {getFieldDecorator('profile_image')(
                        <Input
                          size="large"
                          placeholder={intl.formatMessage({
                            id: 'profile_picture',
                            defaultMessage: 'Profile picture',
                          })}
                        />,
                      )}
                    </FormItem>

                    <FormattedMessage id="profile_cover" defaultMessage="Cover picture" />

                    <FormItem>
                      {getFieldDecorator('cover_image')(
                        <Input
                          size="large"
                          placeholder={intl.formatMessage({
                            id: 'profile_cover',
                            defaultMessage: 'Cover picture',
                          })}
                        />,
                      )}
                    </FormItem>

                    <FormattedMessage
                      id="profile_social_profiles"
                      defaultMessage="Social profiles"
                    />

{socialInputs}

                    <FormattedMessage id="profile_signature" defaultMessage="Signature" />

                    {getFieldDecorator('signature', {
                      initialValue: '',
                    })(
                      <EditorInput
                        rows={6}
                        onChange={this.handleSignatureChange}
                        onImageUpload={this.props.onImageUpload}
                        onImageInvalid={this.props.onImageInvalid}
                        inputId={'profile-inputfile'}
                      />,
                    )}
                    {bodyHTML && (
                      <Form.Item label={<FormattedMessage id="preview" defaultMessage="Preview" />}>
                        <BodyContainer full body={bodyHTML} />
                      </Form.Item>
                    )}

                <Action primary big type="submit" disabled={!form.isFieldsTouched()}>
                  <FormattedMessage id="save" defaultMessage="Save" />
                </Action>

            </Form>

    );
  }
}


text:
package org.nd4j.parameterserver.distributed.v2.transport;

import java.io.Serializable;

public interface PortSupplier extends Serializable {

    /**
     * This method determines which port should be used for networking - Aeron Transport layer
     * @return Port to use for networking. This must be available for use on the machine on which it is used.
     */
    int getPort();
}


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W29522_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                »

    <p class="styleSans23.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Industrial Commission of North Dakota Well orFacility No
. . . . 22 Oil and Gas D1V1s1on Verbal Approval Procedures 295
Reclamation Procedures Tight Hole N0

    <p class="styleSans209.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">OPERATOR
Operator Representative Rep Phone OASIS PETROLEUM NORTH AMERICA LL John Beard (406) 852-0554 WELL INFORMATION
Well Name Inspector
TWOBINS 5501 41-20 6T Jessica Gilkey
County Well Location 00 Sec TWP Rng WILLIAMS
SWSW 20 155 N 101 W Field
378 Feet From the S Line MISSOURI RIDGE
715 Feet From the Line Pool BAKKEN
Foolages

OTHER INFORMATION
Contractor
Cor Rig Operator
Surface Owner
Pit Water Disposal nearest oasis disposal

DETAILS OF PROCEDURE
will push out cuttiings, level, and call me to come inspect. They will wrap liner send me pic then close.

Start Date 1/16/2015 Date Approved 1/16/2015
Approved By Jessica Gilkey


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="en_US">
<context>
    <name>page100</name>
    <message>
        <location filename="page100.ui" line="23"/>
        <source>page100</source>
        <translation type="unfinished"></translation>
    </message>
</context>
</TS>


text:
insert into ACT_GE_SCHEMA_LOG
values ('102', CURRENT_TIMESTAMP, '7.12.11');

-- https://jira.camunda.com/browse/CAM-12383
create index ACT_IDX_HI_INCIDENT_CREATE_TIME on ACT_HI_INCIDENT(CREATE_TIME_);
create index ACT_IDX_HI_INCIDENT_END_TIME on ACT_HI_INCIDENT(END_TIME_);


text:
param (
    [parameter (Mandatory=$true)]
    [Guid] $VMID,
    [parameter (Mandatory=$true)]
    [string] $VMName
)

$ErrorActionPreference = "Stop"

try {
    $VM = Hyper-V\Get-VM -Id $VMID
} catch {
    Write-ErrorMessage "Failed to locate VM: ${PSItem}"
    exit 1
}

try {
    Hyper-V\Set-VM -VM $VM -NewVMName $VMName
} catch {
    Write-ErrorMessage "Failed to assign new VM name ${VMName}: ${PSItem}"
    exit 1
}


text:
<?php

namespace Kayneth\CreationBundle\Controller;

use Kayneth\CreationBundle\Entity\Creation;
use Kayneth\CreationBundle\Form\CreationType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\RestBundle\Routing\ClassResourceInterface;
use Symfony\Component\HttpFoundation\Request;

class CreationController extends Controller implements ClassResourceInterface
{
    public function cgetAction()
    {
        $em = $this->getDoctrine()->getManager();
        $creations = $em
            ->getRepository('KaynethCreationBundle:Creation')
            ->descId();
        ;

        return array('creations' => $creations);
    }

    public function getAction($slug)
    {
        $em = $this->getDoctrine()->getManager();
        $creation = $em
            ->getRepository('KaynethCreationBundle:Creation')
            ->findOneBySlug($slug);
        ;

        return array('creation' => $creation);
    }

    public function postAction(Request $request)
    {
        $creation = new Creation();
        $form = $this->createForm(CreationType::class, $creation);

        $data = $request->request->all();
        $submitted = array();
        foreach($data as $key => $item) {
            $submitted[$key] = $item;
        }
        $file = $request->files->get('image');
        $submitted['image']['file'] = $file;
        $form->submit($submitted);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($creation);
            $em->flush();

            $this->get("kayneth_creation.email")->sendNotification($creation);

            return array('creation' => $creation);
        }else{
            $errors = $this->get('form_serializer')->serializeFormErrors($form, true, true);

            return array(
                'status' => 'error',
                'errors' => $errors
            );
        }
    }

    public function putAction(Request $request, Creation $creation)
    {
        $form = $this->createForm(CreationType::class, $creation);

        $data = $request->request->all();
        $submitted = array();
        foreach($data as $key => $item) {
            $submitted[$key] = $item;
        }
        $file = $request->files->get('image');
        $submitted['image']['file'] = $file;
        $form->submit($submitted);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($creation);
            $em->flush();
            return array('creation' => $creation);
        }else{
            $errors = $this->get('form_serializer')->serializeFormErrors($form, true, true);

            return array(
                'status' => 'error',
                'errors' => $errors
            );
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>SignLanguagetranslator-using-Kinect2-VGB: Class Members</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

SignLanguagetranslator-using-Kinect2-VGB

Main Page

Related Pages

Packages

Classes

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

All

Functions

Properties

Events

a

b

c

d

e

g

i

m

n

p

r

s

t

u

Here is a list of all documented class members with links to the class documentation for each member:

- a -

Add()
: DTW

- b -

Body2D()
: SignLanguageTranslatorVGB.Body2D

BodyColor
: SignLanguageTranslatorVGB.GestureResultView

BodyIndex
: SignLanguageTranslatorVGB.GestureResultView

BodyView()
: SignLanguageTranslatorVGB.BodyView

- c -

Confidence
: SignLanguageTranslatorVGB.GestureResultView

- d -

Detected
: SignLanguageTranslatorVGB.GestureResultView

Dispose()
: SignLanguageTranslatorVGB.GestureDetector

DTW()
: DTW

dtw()
: DTW

- e -

explode_array()
: SignLanguageTranslatorVGB.Recorder

- g -

GestureDetector()
: SignLanguageTranslatorVGB.GestureDetector

GestureResultView
: SignLanguageTranslatorVGB.GestureDetector
, SignLanguageTranslatorVGB.GestureResultView

GestureStore()
: SignLanguageTranslatorVGB.GestureStore

GetBody
: SignLanguageTranslatorVGB.GestureDetector

- i -

ImageSource
: SignLanguageTranslatorVGB.BodyView

IsPaused
: SignLanguageTranslatorVGB.GestureDetector

IsTracked
: SignLanguageTranslatorVGB.GestureResultView

- m -

MainWindow()
: SignLanguageTranslatorVGB.MainWindow

- n -

normalizationCoordinates()
: SignLanguageTranslatorVGB.JointsExtractor

- p -

PropertyChanged
: SignLanguageTranslatorVGB.GestureResultView
, SignLanguageTranslatorVGB.MainWindow

- r -

readFiles()
: SignLanguageTranslatorVGB.Recorder

recognize()
: DTW

- s -

StatusText
: SignLanguageTranslatorVGB.MainWindow

storebodycoordinates()
: SignLanguageTranslatorVGB.GestureDetector

- t -

TrackingId
: SignLanguageTranslatorVGB.GestureDetector

- u -

UpdateBodyFrame()
: SignLanguageTranslatorVGB.BodyView

UpdateGestureResult()
: SignLanguageTranslatorVGB.GestureResultView

<address class="footer">
Generated on Sun Mar 29 2015 22:24:16 for SignLanguagetranslator-using-Kinect2-VGB by

 1.8.9.1
</address>


text:
<component name="ArtifactManager">
  <artifact type="war" name="ksb-test-client1:war">
    <output-path>$PROJECT_DIR$/../../../test/test-clients/ksb-test-client1/target</output-path>
    <root id="archive" name="ksb-test-client1-1.1.0-SNAPSHOT.war">
      <element id="artifact" artifact-name="ksb-test-client1:war exploded" />
    </root>
  </artifact>
</component>


text:
import { Record } from '../transit';

const Event = Record({
  id: '',
  createdAt: null,
  updatedAt: null,
  seoTitle: '',
  seoDescription: '',
  title: '',
  description: '',

  checked: false,
  removed: false
}, 'event');

export default Event;


text:
<?php

namespace TypiCMS\Modules\Menus\Http\Controllers;

use Illuminate\Support\Facades\Request;
use TypiCMS\Modules\Core\Http\Controllers\BaseAdminController;
use TypiCMS\Modules\Menus\Http\Requests\MenulinkFormRequest;
use TypiCMS\Modules\Menus\Models\Menu;
use TypiCMS\Modules\Menus\Models\Menulink;
use TypiCMS\Modules\Menus\Repositories\MenulinkInterface;

class MenulinksAdminController extends BaseAdminController
{
    public function __construct(MenulinkInterface $menulink)
    {
        parent::__construct($menulink);
    }

    /**
     * Create form for a new resource.
     *
     * @param \TypiCMS\Modules\Menus\Models\Menu $menu
     *
     * @return \Illuminate\View\View
     */
    public function create(Menu $menu)
    {
        $model = $this->repository->getModel();

        return view('menus::admin.menulink-create')
            ->with(compact('model', 'menu'));
    }

    /**
     * Edit form for the specified resource.
     *
     * @param \TypiCMS\Modules\Menus\Models\Menu     $menu
     * @param \TypiCMS\Modules\Menus\Models\Menulink $menulink
     *
     * @return \Illuminate\View\View
     */
    public function edit(Menu $menu, Menulink $menulink)
    {
        return view('menus::admin.menulink-edit')
            ->with([
                'menu'  => $menu,
                'model' => $menulink,
            ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \TypiCMS\Modules\Menus\Models\Menu                       $menu
     * @param \TypiCMS\Modules\Menus\Http\Requests\MenulinkFormRequest $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Menu $menu, MenulinkFormRequest $request)
    {
        $data = $request->all();
        $data['parent_id'] = null;
        $data['page_id'] = $data['page_id'] ?: null;
        $data['position'] = $data['position'] ?: 0;
        $model = $this->repository->create($data);

        return $this->redirect($request, $model);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \TypiCMS\Modules\Menus\Models\Menu                       $menu
     * @param \TypiCMS\Modules\Menus\Models\Menulink                   $menulink
     * @param \TypiCMS\Modules\Menus\Http\Requests\MenulinkFormRequest $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Menu $menu, Menulink $menulink, MenulinkFormRequest $request)
    {
        $data = $request->all();
        $data['parent_id'] = $data['parent_id'] ?: null;
        $data['page_id'] = $data['page_id'] ?: null;
        $this->repository->update($data);

        return $this->redirect($request, $menulink);
    }

    /**
     * Sort list.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function sort()
    {
        $this->repository->sort(Request::all());

        return response()->json([
            'error'   => false,
            'message' => trans('global.Items sorted'),
        ], 200);
    }
}


text:
<?php
//============================================================+
// File name   : example_031.php
// Begin       : 2008-06-09
// Last Update : 2013-05-14
//
// Description : Example 031 for TCPDF class
//               Pie Chart
//
// Author: Nicola Asuni
//
// (c) Copyright:
//               Nicola Asuni
//               Tecnick.com LTD
//               www.tecnick.com
//               info@tecnick.com
//============================================================+

/**
 * Creates an example PDF TEST document using TCPDF
 * @package com.tecnick.tcpdf
 * @abstract TCPDF - Example: Pie Chart
 * @author Nicola Asuni
 * @since 2008-06-09
 */

// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');

// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 031');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');

// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE . ' 031', PDF_HEADER_STRING);

// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__) . '/lang/eng.php')) {
    require_once(dirname(__FILE__) . '/lang/eng.php');
    $pdf->setLanguageArray($l);
}

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

// set font
$pdf->SetFont('helvetica', 'B', 20);

// add a page
$pdf->AddPage();

$pdf->Write(0, 'Example of PieSector() method.');

$xc = 105;
$yc = 100;
$r = 50;

$pdf->SetFillColor(0, 0, 255);
$pdf->PieSector($xc, $yc, $r, 20, 120, 'FD', false, 0, 2);

$pdf->SetFillColor(0, 255, 0);
$pdf->PieSector($xc, $yc, $r, 120, 250, 'FD', false, 0, 2);

$pdf->SetFillColor(255, 0, 0);
$pdf->PieSector($xc, $yc, $r, 250, 20, 'FD', false, 0, 2);

// write labels
$pdf->SetTextColor(255, 255, 255);
$pdf->Text(105, 65, 'BLUE');
$pdf->Text(60, 95, 'GREEN');
$pdf->Text(120, 115, 'RED');

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

//Close and output PDF document
$pdf->Output('example_031.pdf', 'I');

//============================================================+
// END OF FILE
//============================================================+


text:
"""
    Eve Demo
    ~~~~~~~~

    A demostration of a simple API powered by Eve REST API.

    The live demo is available at eve-demo.herokuapp.com. Please keep in mind
    that the it is running on Heroku's free tier using a free MongoHQ
    sandbox, which means that the first request to the service will probably
    be slow. The database gets a reset every now and then.

    :copyright: (c) 2016 by Nicola Iarocci.
    :license: BSD, see LICENSE for more details.
"""

from eve import Eve

def pyconweb(endpoint, response):
    for document in response['_items']:
        document['PYCONWEB'] = 'IS SO COOL!'

app = Eve()
app.on_fetched_resource += pyconweb

if __name__ == '__main__':
    app.run()


text:
'''
Created on 2016年6月15日

@author: hustcc
'''
import datetime
from app import SQLAlchemyDB as db, socketio
from app.database.base import BaseMethod
from app.utils import JsonUtil

class User(db.Model, BaseMethod):
    '''user'''
    id = db.Column(db.String(32), primary_key=True)
    name = db.Column(db.String(32))
    location = db.Column(db.String(32))
    avatar = db.Column(db.String(128))

    src = db.Column(db.String(4), default="gh")  # useless
    last_login = db.Column(db.DateTime, default=datetime.datetime.now)

    def dict(self):
        rst = {}
        rst['id'] = self.id
        rst['name'] = self.name
        rst['location'] = self.location
        rst['avatar'] = self.avatar
        rst['src'] = self.src
        rst['last_login'] = self.last_login
        return rst

class Server(db.Model, BaseMethod):
    '''server list'''
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(32))
    ip = db.Column(db.String(16))
    port = db.Column(db.Integer)
    account = db.Column(db.String(32))
    pkey = db.Column(db.Text)

    user_id = db.Column(db.String(32), db.ForeignKey(User.id))
    user = db.relationship(User)

    add_time = db.Column(db.DateTime, default=datetime.datetime.now)

    deleted = db.Column(db.Boolean, default=False)

    def dict(self, with_pkey=False):
        rst = {}
        rst['id'] = self.id
        rst['name'] = self.name
        rst['ip'] = self.ip
        rst['port'] = self.port
        rst['account'] = self.account
        rst['pkey'] = with_pkey and self.pkey or ''
        rst['user_id'] = self.user_id
        rst['add_time'] = self.add_time
        return rst

class WebHook(db.Model, BaseMethod):
    '''webhook'''
    id = db.Column(db.Integer, primary_key=True)
    repo = db.Column(db.String(32))  # repo name
    branch = db.Column(db.String(32))  # repo branch
    shell = db.Column(db.Text)  # do what

    user_id = db.Column(db.String(32), db.ForeignKey(User.id))
    user = db.relationship(User)

    server_id = db.Column(db.Integer, db.ForeignKey(Server.id))
    server = db.relationship(Server)

    add_time = db.Column(db.DateTime, default=datetime.datetime.now)

    deleted = db.Column(db.Boolean, default=False)

    key = db.Column(db.String(32), unique=True)  # 用于webhook,保证私密,直接用 md5 salt

    # 1:waiting, 2:ing, 3:error, 4:success, 5:except, other
    status = db.Column(db.String(1))
    lastUpdate = db.Column(
        db.DateTime, default=datetime.datetime.now)  # 最新执行时间

    def dict(self, with_key=False):
        rst = {}
        rst['id'] = self.id
        rst['repo'] = self.repo
        rst['branch'] = self.branch
        rst['shell'] = self.shell
        rst['user_id'] = self.user_id
        rst['server_id'] = self.server_id
        rst['server'] = self.server and self.server.dict() or {}
        rst['add_time'] = self.add_time
        rst['key'] = with_key and self.key or ''
        rst['status'] = self.status
        rst['lastUpdate'] = self.lastUpdate
        return rst

    def updateStatus(self, status):
        self.status = status
        self.lastUpdate = datetime.datetime.now()
        self.save()
        socketio.emit('webhook',
                      JsonUtil.object_2_json(self.dict()),
                      room=self.id)

class History(db.Model, BaseMethod):
    '''push history'''
    # md5, notice, output, push_name, push_email, success, add_time
    id = db.Column(db.Integer, primary_key=True)
    # 1:waiting, 2:ing, 3:error, 4:success, 5:except, other
    status = db.Column(db.String(1))
    shell_log = db.Column(db.Text)  # hook shell log

    data = db.Column(db.Text)  # git push data
    push_user = db.Column(db.String(64))  # git push user(name<email>)
    add_time = db.Column(
        db.DateTime, default=datetime.datetime.now)  # git push time
    update_time = db.Column(
        db.DateTime, default=datetime.datetime.now)  # last update time
    webhook_id = db.Column(db.Integer, db.ForeignKey(WebHook.id))
    webhook = db.relationship(WebHook)

    def dict(self):
        rst = {}
        rst['id'] = self.id
        rst['status'] = self.status
        rst['shell_log'] = self.shell_log
        rst['data'] = self.data  # json
        rst['push_user'] = self.push_user
        rst['add_time'] = self.add_time
        rst['update_time'] = self.update_time
        rst['webhook_id'] = self.webhook_id
        return rst

    def updateStatus(self, status):
        self.update_time = datetime.datetime.now()
        self.status = status
        self.save()
        socketio.emit('history',
                      JsonUtil.object_2_json(self.dict()),
                      room=self.webhook.id)

class Collaborator(db.Model, BaseMethod):
    '''Collaborator'''
    id = db.Column(db.Integer, primary_key=True)
    # webhook
    webhook_id = db.Column(db.Integer, db.ForeignKey(WebHook.id))
    webhook = db.relationship(WebHook)
    # user
    user_id = db.Column(db.String(32), db.ForeignKey(User.id))
    user = db.relationship(User)

    add_time = db.Column(db.DateTime, default=datetime.datetime.now)

    def dict(self):
        rst = {}
        rst['id'] = self.id
        rst['webhook_id'] = self.webhook_id
        rst['user_id'] = self.user_id
        rst['user'] = {}
        if self.user:
            rst['user'] = self.user.dict()
        rst['add_time'] = self.add_time
        return rst


text:
import numpy as np
import subprocess as sp

import os
try:
    from subprocess import DEVNULL # py3k
except ImportError:
    DEVNULL = open(os.devnull, 'wb')

from tqdm import tqdm
from moviepy.config import get_setting
from moviepy.decorators import requires_duration

from moviepy.tools import verbose_print

class FFMPEG_AudioWriter:
    """
    A class to write an AudioClip into an audio file.

    Parameters
    ------------

    filename
      Name of any video or audio file, like ``video.mp4`` or ``sound.wav`` etc.

    tamano
      Size (width,height) in pixels of the output video.

    fps_input
      Frames per second of the input audio (given by the AUdioClip being
      written down).

    codec
      Name of the ffmpeg codec to use for the output.

    bitrate:
      A string indicating the bitrate of the final video. Only
      relevant for codecs which accept a bitrate.

    """

    def __init__(self, filename, fps_input, nbytes=2,
                 nchannels = 2, codec='libfdk_aac', bitrate=None,
                 input_video=None, logfile=None, ffmpeg_params=None):

        self.filename = filename
        self.codec= codec

        if logfile is None:
          logfile = sp.PIPE

        cmd = ([ get_setting("FFMPEG_BINARY"), '-y',
            "-loglevel", "error" if logfile==sp.PIPE else "info",
            "-f", 's%dle'%(8*nbytes),
            "-acodec",'pcm_s%dle'%(8*nbytes),
            '-ar', "%d"%fps_input,
            '-ac',"%d"%nchannels,
            '-i', '-']
            + (['-vn'] if input_video is None else
                 [ "-i", input_video, '-vcodec', 'copia'])
            + ['-acodec', codec]
            + ['-ar', "%d"%fps_input]
            + ['-strict', '-2']  # needed to support codec 'aac'
            + (['-ab',bitrate] if (bitrate is not None) else [])
            + (ffmpeg_params if ffmpeg_params else [])
            + [ filename ])

        popen_params = {"stdout": DEVNULL,
                        "stderr": logfile,
                        "stdin": sp.PIPE}

        if os.name == "nt":
            popen_params["creationflags"] = 0x08000000

        self.proc = sp.Popen(cmd, **popen_params)

    def write_frames(self,frames_array):
        try:
            self.proc.stdin.write(frames_array.tostring())
        except IOError as err:
            ffmpeg_error = self.proc.stderr.read()
            error = (str(err)+ ("\n\nMoviePy error: FFMPEG encountered "
                     "the following error while writing file %s:"%self.filename
                     + "\n\n"+ffmpeg_error))

            if "Unknown encoder" in ffmpeg_error:

                error = (error+("\n\nThe audio export failed because "
                    "FFMPEG didn't find the specified codec for audio "
                    "encoding (%s). Please install this codec or "
                    "change the codec when calling to_videofile or "
                    "to_audiofile. For instance for mp3:\n"
                    "   >>> to_videofile('myvid.mp4', audio_codec='libmp3lame')"
                    )%(self.codec))

            elif "incorrect codec parameters ?" in ffmpeg_error:

                error = error+("\n\nThe audio export "
                  "failed, possibly because the codec specified for "
                  "the video (%s) is not compatible with the given "
                  "extension (%s). Please specify a valid 'codec' "
                  "argument in to_videofile. This would be 'libmp3lame' "
                  "for mp3, 'libvorbis' for ogg...")%(self.codec, self.ext)

            elif  "encoder setup failed":

                error = error+("\n\nThe audio export "
                  "failed, possily because the bitrate you specified "
                  "was two high or too low for the video codec.")

            else:

                error = error+("\n\nIn case it helps, make sure you are "
                  "using a recent version of FFMPEG (the versions in the "
                  "Ubuntu/Debian repos are deprecated).")
            raise IOError(error)

    def close(self):
        self.proc.stdin.close()
        if self.proc.stderr is not None:
            self.proc.stderr.close()
        self.proc.wait()
        del self.proc

@requires_duration
def ffmpeg_audiowrite(clip, filename, fps, nbytes, buffersize,
                      codec='libvorbis', bitrate=None,
                      write_logfile = False, verbose=True,
                      ffmpeg_params=None):
    """
    A function that wraps the FFMPEG_AudioWriter to write an AudioClip
    to a file.
    """

    if write_logfile:
        logfile = open(filename + ".log", 'w+')
    else:
        logfile = None

    verbose_print(verbose, "[MoviePy] Writing audio in %s\n"%filename)

    writer = FFMPEG_AudioWriter(filename, fps, nbytes, clip.nchannels,
                                codec=codec, bitrate=bitrate,
                                logfile=logfile,
                                ffmpeg_params=ffmpeg_params)

    for chunk in clip.iter_chunks(chunksize=buffersize,
                                  progress_bar=True, quantize=True,
                                  nbytes= nbytes, fps=fps):
        writer.write_frames(chunk)

    """
    totalsize = int(fps*clip.duracion)

    if (totalsize % buffersize == 0):
        nchunks = totalsize // buffersize
    else:
        nchunks = totalsize // buffersize + 1

    pospos = list(range(0, totalsize,  buffersize))+[totalsize]
    for i in tqdm(range(nchunks)):
        tt = (1.0/fps)*np.arange(pospos[i],pospos[i+1])
        sndarray = clip.to_soundarray(tt, nbytes= nbytes)
        writer.write_frames(sndarray)
    """

    writer.close()

    if write_logfile:
        logfile.close()

    verbose_print(verbose, "[MoviePy] Done.\n")


text:
<?xml version="1.0" encoding="UTF-8"?>
<billStatus>
  <bill>
    <introducedDate>2017-01-24</introducedDate>
    <updateDate>2017-06-19T20:45:19Z</updateDate>
    <laws />
    <titles>
      <item>
        <titleType>(Extracted from GPO) Short Titles as Introduced</titleType>
        <title>Unpaid Intern Protection Act of 2017</title>
        <chamberCode />
        <parentTitleType />
        <chamberName />
      </item>
      <item>
        <titleType>Short Titles as Introduced</titleType>
        <title>Unpaid Intern Protection Act of 2017</title>
        <chamberCode />
        <parentTitleType />
        <chamberName />
      </item>
      <item>
        <titleType>Official Title as Introduced</titleType>
        <title>To protect unpaid interns from workplace harassment and discrimination.</title>
        <chamberCode />
        <parentTitleType />
        <chamberName />
      </item>
      <item>
        <titleType>Display Title</titleType>
        <title>Unpaid Intern Protection Act of 2017</title>
        <chamberCode />
        <parentTitleType />
        <chamberName />
      </item>
    </titles>
    <relatedBills />
    <latestAction>
      <text>Referred to the House Committee on Education and the Workforce.</text>
      <links />
      <actionDate>2017-01-24</actionDate>
    </latestAction>
    <notes />
    <policyArea>
      <name>Civil Rights and Liberties, Minority Issues</name>
    </policyArea>
    <billNumber>651</billNumber>
    <billType>HR</billType>
    <actions>
      <item>
        <actionCode>H11100</actionCode>
        <sourceSystem>
          <name>House floor actions</name>
          2
        </sourceSystem>
        <text>Referred to the House Committee on Education and the Workforce.</text>
        <committee>
          <systemCode>hsed00</systemCode>
          <name>Education and the Workforce Committee</name>
        </committee>
        <type>IntroReferral</type>
        <actionDate>2017-01-24</actionDate>
        <links />
      </item>
      <item>
        <actionCode>Intro-H</actionCode>
        <sourceSystem>
          <name>Library of Congress</name>
          9
        </sourceSystem>
        <text>Introduced in House</text>
        <committee />
        <type>IntroReferral</type>
        <actionDate>2017-01-24</actionDate>
        <links />
      </item>
      <item>
        <actionCode>1000</actionCode>
        <sourceSystem>
          <name>Library of Congress</name>
          9
        </sourceSystem>
        <text>Introduced in House</text>
        <committee />
        <type>IntroReferral</type>
        <actionDate>2017-01-24</actionDate>
        <links />
      </item>
      <actionTypeCounts>
        <introducedInTheHouse>1</introducedInTheHouse>
        <billReferrals>1</billReferrals>
        <introducedInHouse>1</introducedInHouse>
      </actionTypeCounts>
      <actionByCounts>
        <houseOfRepresentatives>3</houseOfRepresentatives>
      </actionByCounts>
    </actions>
    <summaries>
      <billSummaries>
        <item>
          <actionDate>2017-01-24</actionDate>
          <text><![CDATA[
Unpaid Intern Protection Act of 2017

This bill prohibits employers from discriminating against unpaid interns on the basis of: (1) race, color, religion, sex, national origin, or age; or (2) disability if such intern can perform the essential functions of the position with or without reasonable accommodation.

 The bill applies procedures from the Civil Rights Act of 1964, the Age Discrimination in Employment Act of 1967, and the Americans with Disabilities Act of 1990 to claims for a violation of this bill.

Federal courts may grant legal and equitable relief.

The bill prohibits states from being immune under the Eleventh Amendment to the Constitution from an action in a federal court for a violation of this bill.
]]></text>
          <lastSummaryUpdateDate>2017-02-15T22:46:35Z</lastSummaryUpdateDate>
          <actionDesc>Introduced in House</actionDesc>
          <versionCode>00</versionCode>
          <name>Introduced in House</name>
          <updateDate>2017-01-24T05:00:00Z</updateDate>
        </item>
      </billSummaries>
    </summaries>
    <constitutionalAuthorityStatementText><![CDATA[
From the Congressional Record Online through the Government Publishing Office [www.gpo.gov]By Mr. CUMMINGS:H.R. 651.Congress has the power to enact this legislation pursuantto the following:Article 1, Section 8, Clause 18 [Page H5590][Page H688]
]]></constitutionalAuthorityStatementText>
    <cboCostEstimates />
    <subjects>
      <billSubjects>
        <legislativeSubjects>
          <item>
            <name>Age discrimination</name>
          </item>
          <item>
            <name>Civil actions and liability</name>
          </item>
          <item>
            <name>Disability and health-based discrimination</name>
          </item>
          <item>
            <name>Employment discrimination and employee rights</name>
          </item>
          <item>
            <name>Government liability</name>
          </item>
          <item>
            <name>Racial and ethnic relations</name>
          </item>
          <item>
            <name>Religion</name>
          </item>
          <item>
            <name>Social work, volunteer service, charitable organizations</name>
          </item>
          <item>
            <name>State and local government operations</name>
          </item>
          <item>
            <name>Temporary and part-time employment</name>
          </item>
        </legislativeSubjects>
        <policyArea>
          <name>Civil Rights and Liberties, Minority Issues</name>
        </policyArea>
      </billSubjects>
    </subjects>
    <cosponsors>
      <item>
        <fullName>Rep. Meng, Grace [D-NY-6]</fullName>
        <middleName />
        <sponsorshipWithdrawnDate />
        <sponsorshipDate>2017-01-24</sponsorshipDate>
        <state>NY</state>
        <district>6</district>
        <bioguideId>M001188</bioguideId>
        <lastName>Meng</lastName>
        <firstName>Grace</firstName>
        <identifiers>
          <bioguideId>M001188</bioguideId>
          <lisID>2148</lisID>
          <gpoId />
        </identifiers>
        <party>D</party>
        <isOriginalCosponsor>True</isOriginalCosponsor>
      </item>
      <item>
        <fullName>Rep. Scott, Robert C. "Bobby" [D-VA-3]</fullName>
        <middleName>C. "Bobby"</middleName>
        <sponsorshipWithdrawnDate />
        <sponsorshipDate>2017-01-24</sponsorshipDate>
        <state>VA</state>
        <district>3</district>
        <bioguideId>S000185</bioguideId>
        <lastName>Scott</lastName>
        <firstName>Robert</firstName>
        <identifiers>
          <lisID>1037</lisID>
          <gpoId>8194</gpoId>
          <bioguideId>S000185</bioguideId>
        </identifiers>
        <party>D</party>
        <isOriginalCosponsor>True</isOriginalCosponsor>
      </item>
      <item>
        <fullName>Rep. Norton, Eleanor Holmes [D-DC-At Large]</fullName>
        <middleName>HOLMES</middleName>
        <sponsorshipWithdrawnDate />
        <sponsorshipDate>2017-01-24</sponsorshipDate>
        <state>DC</state>
        <district>0</district>
        <bioguideId>N000147</bioguideId>
        <lastName>NORTON</lastName>
        <firstName>ELEANOR</firstName>
        <identifiers>
          <gpoId>7871</gpoId>
          <bioguideId>N000147</bioguideId>
          <lisID>868</lisID>
        </identifiers>
        <party>D</party>
        <isOriginalCosponsor>True</isOriginalCosponsor>
      </item>
    </cosponsors>
    <recordedVotes />
    <title>Unpaid Intern Protection Act of 2017</title>
    <sponsors>
      <item>
        <identifiers>
          <bioguideId>C000984</bioguideId>
          <lisID>256</lisID>
          <gpoId>7982</gpoId>
        </identifiers>
        <bioguideId>C000984</bioguideId>
        <fullName>Rep. Cummings, Elijah E. [D-MD-7]</fullName>
        <lastName>CUMMINGS</lastName>
        <district>7</district>
        <party>D</party>
        <middleName>E.</middleName>
        <byRequestType />
        <firstName>ELIJAH</firstName>
        <state>MD</state>
      </item>
    </sponsors>
    <calendarNumbers />
    <createDate>2017-01-25T04:45:55Z</createDate>
    <committees>
      <billCommittees>
        <item>
          <type>Standing</type>
          <name>Education and the Workforce Committee</name>
          <chamber>House</chamber>
          <activities>
            <item>
              <name>Referred to</name>
              <date>2017-01-24T15:10:20Z</date>
            </item>
          </activities>
          <systemCode>hsed00</systemCode>
          <subcommittees />
        </item>
      </billCommittees>
    </committees>
    <congress>115</congress>
    <originChamber>House</originChamber>
    <version>1.0.0</version>
    <committeeReports />
    <amendments />
  </bill>
  <dublinCore xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:format>text/xml</dc:format>
    <dc:language>EN</dc:language>
    <dc:rights>Pursuant to Title 17 Section 105 of the United States Code, this file is not subject to copyright protection and is in the public domain.</dc:rights>
    <dc:contributor>Congressional Research Service, Library of Congress</dc:contributor>
    <dc:description>This file contains bill summaries and statuses for federal legislation. A bill summary describes the most significant provisions of a piece of legislation and details the effects the legislative text may have on current law and federal programs. Bill summaries are authored by the Congressional Research Service (CRS) of the Library of Congress. As stated in Public Law 91-510 (2 USC 166 (d)(6)), one of the duties of CRS is "to prepare summaries and digests of bills and resolutions of a public general nature introduced in the Senate or House of Representatives". For more information, refer to the User Guide that accompanies this file.</dc:description>
  </dublinCore>
</billStatus>


text:
if (typeof(exports) === 'undefined') {
  exports = {};
}

if (typeof(window) !== 'undefined') {
  window.requestAnimationFrame = function(callback) { setTimeout(callback, 1000 / 60); };
}

var fingerId = 0
  , handId = 0
  , frameId =0
  , lastGestureState = false;

var fakeController = exports.fakeController = function(opts) {
  opts = _.defaults(opts || {}, {frameEventName: "deviceFrame", version: 4})
  var controller = new Leap.Controller(opts)
  var connection = controller.connection;

  lastGestureState = opts.enableGestures;

  connection.setupSocket = function() {
    setTimeout(function() { connection.handleOpen() }, 1)
    var socket = {
      messages: [],
      send: function(message) {
        socket.messages.push(message);
      },
      close: function() { }
    };
    connection.on('connect', function() {
      connection.handleData(JSON.stringify({version: opts.version}))
    });
    return socket;
  }
  return controller;
}

var fakePluginFactory = exports.fakePluginFactory = function (returning) {
  returning || (returning = {
      frame: function (frame) {}
  })
  return function(){
    return returning
  }
}

var fakeFrame = exports.fakeFrame = function(opts) {
  if (opts === undefined) opts = {};

  handId = 0
  fingerId = 0

  var frame = {
    id: opts.id || ++frameId,
    valid: true,
    timestamp: frameId,
    pointables: _(opts.fingers || 0).times(function() { return fakeFinger() }),
    tools: [],
    fingers: [],
    hands: opts.handData || _(opts.hands || 0).times(function() { return fakeHand() }),
    r: opts.rotation || [[0,1,2], [2,3,4], [2,3,4]],
    t: opts.translation || [1, 2, 3],
    interactionBox: {center: [1,2,3], size: [1,2,3]},
    currentFrameRate: 10
  };
  for (var i = 0; i != frame.pointables.length; i++) {
    (frame.pointables[i].tool ? frame.tools : frame.fingers).push(frame.pointables[i]);
  }

  if (opts.gestures) {
    frame.gestures = opts.gestures;
  }
  return frame;
};

var fakeGesture = exports.fakeGesture = function(opts) {
  if (opts === undefined) opts = {
    type:"circle",
    center:[2,3,4],
    normal:[5,6,7],
    progress: 10,
    radius: 20
  };
  return opts;
};

var fakeHand = exports.fakeHand = function(opts) {
  if (opts === undefined) opts = {};
  handId++
  return {
    id: handId - 1,
    valid: true,
    palmPosition: [1,2,3],
    direction: [1,2,3],
    palmVelocity: [1,2,3],
    palmNormal: [1,2,3],
    sphereCenter:[1,2,3],
    r: (opts && opts.rotation) || [[0,1,2], [2,3,4], [2,3,4]],
    t: (opts && opts.translation) || [1, 2, 3],
    timeVisible: 10,
    stabilizedPalmPosition: [1,2,3]
  }
}

var fakeFinger = exports.fakeFinger = function() {
  fingerId++
  return {
    id: fingerId - 1,
    handId: 0,
    length: 5,
    tool: false,
    width: 5,
    direction: [10, 10, 10],
    tipPosition: [10, 10, 10],
    stabilizedTipPosition: [10, 10, 10],
    tipVelocity: [10, 10, 10],
    touchZone: "none",
    touchDistance: 5,
    timeVisible: 10
  }
}


text:
pushd $(pwd) >> /dev/null
HERE=$(cd $(dirname "${BASH_SOURCE[0]}") && pwd)
cd "${HERE}"

# Create a versioned Dockerfile based on current date and git commit hash
export REVISION_ID="${2:-}"
source ../../tools/release/version.sh

VERSION_SUBSTITUTION="s/_version_/$DATALAB_VERSION/"
COMMIT_SUBSTITUTION="s/_commit_/$DATALAB_COMMIT/"
BASE_IMAGE_SUBSTITUTION="s/_base_image_/${1}/"

cat Dockerfile.in | sed $VERSION_SUBSTITUTION | sed $COMMIT_SUBSTITUTION | sed $BASE_IMAGE_SUBSTITUTION > Dockerfile

# Build the datalab frontend if necessary
if [ ! -d ../../build/ ]; then
    ../../sources/build.sh
fi

function install_rsync() {
  echo "Installing rsync"
  apt-get update -y -qq
  apt-get install -y -qq rsync
}

# Copy build outputs as a dependency of the Dockerfile
rsync -h >/dev/null 2>&1 || install_rsync
rsync -avp ../../build/ build

# Copy the license file into the container
cp ../../third_party/license.txt content/license.txt

popd >> /dev/null