text:
package cn.world.liuhui.utils;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

/**
 * Created by liuhui on 2015/7/27.
 */
public class FileUtil {

    /**
     * 得到SD卡根目录.
     */
    public static File getRootPath() {
        File path = null;
        if (FileUtil.sdCardIsAvailable()) {
            path = Environment.getExternalStorageDirectory(); // 取得sdcard文件路径
        } else {
            path = Environment.getDataDirectory();
        }
        return path;
    }

    /**
     * SD卡是否可用.
     */
    public static boolean sdCardIsAvailable() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File sd = new File(Environment.getExternalStorageDirectory().getPath());
            return sd.canWrite();
        } else
            return false;
    }

    /**
     * 文件或者文件夹是否存在.
     */
    public static boolean fileExists(String filePath) {
        File file = new File(filePath);
        return file.exists();
    }

    public static void deleleFile(String path) {
        deleteFile(new File(path));
    }

    public static void deleteFile(File file) {
        if (file != null && file.exists())
            file.delete();
    }

    /**
     * 删除指定文件夹下所有文件, 保留文件夹.
     */
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (file.isFile()) {
            file.delete();
            return true;
        }
        File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++) {
            File exeFile = files[i];
            if (exeFile.isDirectory()) {
                delAllFile(exeFile.getAbsolutePath());
            } else {
                exeFile.delete();
            }
        }
        return flag;
    }

    /**
     * 文件复制.
     */
    public static boolean copy(String srcFile, String destFile) {
        try {
            FileInputStream in = new FileInputStream(srcFile);
            FileOutputStream out = new FileOutputStream(destFile);
            byte[] bytes = new byte[1024];
            int c;
            while ((c = in.read(bytes)) != -1) {
                out.write(bytes, 0, c);
            }
            in.close();
            out.flush();
            out.close();
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 复制整个文件夹内.
     *
     * @param oldPath string 原文件路径如:c:/fqf.
     * @param newPath string 复制后路径如:f:/fqf/ff.
     */
    public static void copyFolder(String oldPath, String newPath) {
        try {
            (new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
            File a = new File(oldPath);
            String[] file = a.list();
            File temp = null;
            for (int i = 0; i < file.length; i++) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + file[i]);
                } else {
                    temp = new File(oldPath + File.separator + file[i]);
                }

                if (temp.isFile()) {
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath + "/" + (temp.getName()).toString());
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ((len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if (temp.isDirectory()) {// 如果是子文件夹
                    copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
                }
            }
        } catch (NullPointerException e) {
        } catch (Exception e) {
        }
    }

    /**
     * 重命名文件.
     */
    public static boolean renameFile(String resFilePath, String newFilePath) {
        File resFile = new File(resFilePath);
        File newFile = new File(newFilePath);
        return resFile.renameTo(newFile);
    }

    /**
     * 获取磁盘可用空间.
     */
    @SuppressWarnings("deprecation")
    @SuppressLint("NewApi")
    public static long getSDCardAvailaleSize() {
        File path = getRootPath();
        StatFs stat = new StatFs(path.getPath());
        long blockSize, availableBlocks;
        if (Build.VERSION.SDK_INT >= 18) {
            blockSize = stat.getBlockSizeLong();
            availableBlocks = stat.getAvailableBlocksLong();
        } else {
            blockSize = stat.getBlockSize();
            availableBlocks = stat.getAvailableBlocks();
        }
        return availableBlocks * blockSize;
    }

    /**
     * 获取某个目录可用大小.
     */
    @SuppressLint("NewApi")
    @SuppressWarnings("deprecation")
    public static long getDirSize(String path) {
        StatFs stat = new StatFs(path);
        long blockSize, availableBlocks;
        if (Build.VERSION.SDK_INT >= 18) {
            blockSize = stat.getBlockSizeLong();
            availableBlocks = stat.getAvailableBlocksLong();
        } else {
            blockSize = stat.getBlockSize();
            availableBlocks = stat.getAvailableBlocks();
        }
        return availableBlocks * blockSize;
    }

    /**
     * 获取文件或者文件夹大小.
     */
    public static long getFileAllSize(String path) {
        File file = new File(path);
        if (file.exists()) {
            if (file.isDirectory()) {
                File[] childrens = file.listFiles();
                long size = 0;
                for (File f : childrens) {
                    size += getFileAllSize(f.getPath());
                }
                return size;
            } else {
                return file.length();
            }
        } else {
            return 0;
        }
    }

    /**
     * 创建一个文件.
     */
    public static boolean initFile(String path) {
        boolean result = false;
        try {
            File file = new File(path);
            if (!file.exists()) {
                result = file.createNewFile();
            } else if (file.isDirectory()) {
                file.delete();
                result = file.createNewFile();
            } else if (file.exists()) {
                result = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 创建一个文件夹.
     */
    public static boolean initDirectory(String path) {
        boolean result = false;
        File file = new File(path);
        if (!file.exists()) {
            result = file.mkdir();
        } else if (!file.isDirectory()) {
            file.delete();
            result = file.mkdir();
        } else if (file.exists()) {
            result = true;
        }
        return result;
    }

    /**
     * 复制文件.
     */
    public static void copyFile(File from, File to) throws IOException {
        if (!from.exists()) {
            throw new IOException("The source file not exist: " + from.getAbsolutePath());
        }
        FileInputStream fis = new FileInputStream(from);
        try {
            copyFile(fis, to);
        } finally {
            fis.close();
        }
    }

    /**
     * 复制文件.
     */
    public static long copyFile(InputStream from, File to) throws IOException {
        long totalBytes = 0;
        FileOutputStream fos = new FileOutputStream(to, false);
        try {
            byte[] data = new byte[1024];
            int len;
            while ((len = from.read(data)) > -1) {
                fos.write(data, 0, len);
                totalBytes += len;
            }
            fos.flush();
        } finally {
            fos.close();
        }
        return totalBytes;
    }

    /**
     * 保存流到文件.
     */
    public static void saveFile(InputStream inputStream, String filePath) {
        try {
            OutputStream outputStream = new FileOutputStream(new File(filePath), false);
            int len;
            byte[] buffer = new byte[1024];
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 用UTF8保存一个文件.
     */
    public static void saveFileUTF8(String path, String content, Boolean append) throws IOException {
        FileOutputStream fos = new FileOutputStream(path, append);
        Writer out = new OutputStreamWriter(fos, "UTF-8");
        out.write(content);
        out.flush();
        out.close();
        fos.flush();
        fos.close();
    }

    /**
     * 用UTF8读取一个文件.
     */
    public static String getFileUTF8(String path) {
        String result = "";
        InputStream fin = null;
        try {
            fin = new FileInputStream(path);
            int length = fin.available();
            byte[] buffer = new byte[length];
            fin.read(buffer);
            fin.close();
            result = new String(buffer, "UTF-8");
        } catch (Exception e) {
        }
        return result;
    }

    /**
     * 得到一个文件Intent.
     */
    public static Intent getFileIntent(String path, String mimeType) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(path)), mimeType);
        return intent;
    }
}


text:
package info.spielproject.spiel

import android.content.{ContentProvider, ContentValues}
import android.database.{Cursor, MatrixCursor}
import android.net.Uri;
import android.util.Log

/**
 * Indicates to other apps that a screen reader is active.
*/

class StatusProvider extends ContentProvider {

  // This code was blatantly ripped off from TalkBack, Scalafied and
  // simplified. I don't fully understand it myself and as such won't
  // document it, but it does seem to work.

  private val cursorValue = new Array[String](1)
  cursorValue(0) = ""

  private class StatusCursor(val status:Int) extends MatrixCursor(cursorValue) {

    override def getCount = 1

    override def getString(column:Int) = status.toString

    override def getInt(column:Int) = status

  }

  override def delete(uri:Uri, selection:String, selectionArgs:Array[String]) = 0

  override def getType(uri:Uri):String = null

  override def insert(uri:Uri, values:ContentValues):Uri = null

  def onCreate() = true

  override def query(uri:Uri, projection:Array[String], selection:String, selectionArgs:Array[String], sortOrder:String):Cursor = {
    val status = if(SpielService.enabled) 1 else 0
    new StatusCursor(status)
  }

  override def update(uri:Uri, values:ContentValues, selection:String, selectionArgs:Array[String]) = 0

}

redpajama_set_name: RedPajamaGithub


text:
package com.manuelpeinado.locationservice;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

/**
 * Created by manuel on 21/07/13.
 */
public class BootCompletedReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        context.startService(new Intent(context, LocationService.class));
    }
}


text:
import logging
import sys
import uuid

from django.urls import reverse

from notebook.models import make_notebook
from useradmin.models import User

from desktop.lib import django_mako
from desktop.lib.exceptions_renderable import PopupException

if sys.version_info[0] > 2:
  from urllib.parse import urlparse, unquote as urllib_unquote
  from django.utils.translation import gettext as _
else:
  from django.utils.translation import ugettext as _
  from urllib import unquote as urllib_unquote
  from urlparse import urlparse

LOG = logging.getLogger(__name__)

class FlinkIndexer():

  def __init__(self, user, fs):
    self.fs = fs
    self.user = user

  def create_table_from_kafka(self, source, destination, start_time=-1, dry_run=False):
    if '.' in destination['name']:
      database, table_name = destination['name'].split('.', 1)
    else:
      database = 'default'
      table_name = destination['name']
    final_table_name = table_name

    source_type = source['sourceType']
    editor_type = '55'  # destination['sourceType']

    columns = destination['columns']

    sql = '''CREATE TABLE %(table_name)s (
%(columns)s
) WITH (
  'connector' = 'kafka',
  'topic' = '%(topic)s',
  'scan.startup.mode' = 'earliest-offset',
  'properties.bootstrap.servers' = 'kafka:9094',
  'format' = 'json'
);''' % {
          'database': database,
          'table_name': table_name,
          'columns': ',\n'.join(['  %(name)s %(type)s' % col for col in columns]),
          'topic': source.get('kafkaSelectedTopics')
      }

    if dry_run:
      return sql
    else:
      on_success_url = reverse('metastore:describe_table', kwargs={'database': database, 'table': final_table_name}) + \
          '?source_type=' + source_type

      return make_notebook(
          name=_('Creating table %(database)s.%(table)s') % {'database': database, 'table': final_table_name},
          editor_type=editor_type,
          statement=sql.strip(),
          status='ready',
          database=database,
          on_success_url=on_success_url,
          last_executed=start_time,
          is_task=True
      )


text:
<?php

namespace common\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\UnidadMedida;

/**
 * UnidadMedidaSearch represents the model behind the search form about `app\models\UnidadMedida`.
 */
class UnidadMedidaSearch extends UnidadMedida
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id'], 'integer'],
            [['unidad_medida'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = UnidadMedida::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
        ]);

        $query->andFilterWhere(['like', 'unidad_medida', $this->unidad_medida]);

        return $dataProvider;
    }
}


text:
package org.gradle.api.plugins.quality.internal;

import org.gradle.api.Task;
import org.gradle.api.plugins.quality.CheckstyleReports;
import org.gradle.api.reporting.SingleFileReport;
import org.gradle.api.reporting.internal.CustomizableHtmlReportImpl;
import org.gradle.api.reporting.internal.TaskGeneratedSingleFileReport;
import org.gradle.api.reporting.internal.TaskReportContainer;

import javax.inject.Inject;

public class CheckstyleReportsImpl extends TaskReportContainer<SingleFileReport> implements CheckstyleReports {
    @Inject
    public CheckstyleReportsImpl(Task task) {
        super(SingleFileReport.class, task);

        add(CustomizableHtmlReportImpl.class, "html", task);
        add(TaskGeneratedSingleFileReport.class, "xml", task);
    }

    public SingleFileReport getHtml() {
        return getByName("html");
    }

    public SingleFileReport getXml() {
        return getByName("xml");
    }
}


text:
package com.dgrlucky.extend.ui.mvp.model.data;

import com.dgrlucky.extend.model.di.component.AppComponent;
import com.dgrlucky.extend.ui.mvp.model.ClientApi;
import com.google.gson.Gson;

import javax.inject.Inject;

/**
 * @author dgrlucky
 * @date 2016/4/10 12:45
 * @company dgrlucky
 * @desc
 */
public class DataManager {

    @Inject
    ClientApi api;
    @Inject
    Gson gson;

    public DataManager() {
        AppComponent.Instance.get().inject(this);
    }

    public ClientApi getApi() {
        return api;
    }

    public Gson getGson() {
        return gson;
    }
}


text:
{% extends "base.html" %}

{% block script %}

{% endblock %}

{% block nav %}

 Home

{% endblock %}
{% block content %}

Key Requests

          Serial Number
          Computer Name
          Requested By
          Reason for Request
          Date Requested

        {% for the_request in requests %}

{{ the_request.secret.computer.serial }}	{{ the_request.secret.computer.computername }}	{{ the_request.requesting_user }}	{{ the_request.reason_for_request }}	{{ the_request.date_requested }}	Manage

        {% endfor %}

{% endblock %}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">

	<context:property-placeholder location="classpath:/config/db.properties" />

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="${db.driver}" />
		<property name="url" value="${db.url}" />
		<property name="username" value="${db.username}" />
		<property name="password" value="${db.password}" />
		<property name="validationQuery"               value="select 1 from dual" />
		<property name="testWhileIdle"                 value="true" />
		<property name="timeBetweenEvictionRunsMillis" value="300000" />
		<property name="maxIdle" value="5" />
		<property name="minIdle" value="5" /><property name="maxActive"   value="5" />
	</bean>
	<!--
	<bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
		<property name="driverClass" value="${db.driver}" />
		<property name="url" value="${db.url}" />
		<property name="username" value="${db.username}" />
		<property name="password" value="${db.password}" />
	</bean>
	 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="typeAliasesPackage" value="com.sanha.app" />
		<property name="mapperLocations" value="classpath*:**/dao/*.xml" />
	</bean>

</beans>


text:
'use strict';

const common = require('x2node-common');

/**
 * Record collection range.
 *
 * @protected
 * @memberof module:x2node-dbos
 * @inner
 */
class RecordsRange {

	/**
	 * Create new range specification.
	 *
	 * @param {number} offset Zero-based range offset.
	 * @param {number} limit The range limit.
	 */
	constructor(offset, limit) {

		this._offset = offset;
		this._limit = limit;
	}

	/**
	 * Zero-based range offset.
	 *
	 * @member {number}
	 * @readonly
	 */
	get offset() { return this._offset; }

	/**
	 * The range limit.
	 *
	 * @member {number}
	 * @readonly
	 */
	get limit() { return this._limit; }
}

/**
 * Parse records collection range specification and build the range object.
 *
 * @protected
 * @param {Array.<number>} rangeSpec Two-element number array of the raw range
 * specification.
 * @returns {module:x2node-dbos~RecordsRange} Range object.
 * @throws {module:x2node-common.X2SyntaxError} If the specification is invalid.
 */
exports.buildRange = function(rangeSpec) {

	// validate range specification array
	if (!Array.isArray(rangeSpec) || (rangeSpec.length !== 2))
		throw new common.X2SyntaxError(
			'Records range specification is not a two-element array.');
	const offset = rangeSpec[0];
	const limit = rangeSpec[1];

	// validate range values
	if (((typeof offset) !== 'number') || !Number.isInteger(offset) ||
		(offset < 0) ||
		((typeof limit) !== 'number') || !Number.isInteger(limit) || (limit < 0))
		throw new common.X2SyntaxError(
			'Invalid records range specification: the offset or the limit' +
				' value is not a non-negative integer.');

	// create and return the range object
	return new RecordsRange(offset, limit);
};


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.Common.Core;
using Microsoft.Common.Core.Diagnostics;
using Microsoft.Common.Core.IO;
using Microsoft.Common.Core.Shell;
using Microsoft.R.Components.Application.Configuration;
using Microsoft.R.Host.Client.Extensions;

namespace Microsoft.VisualStudio.R.Package.ProjectSystem.PropertyPages.Settings {
    internal sealed class SettingsPageViewModel {
        private readonly Dictionary<string, string> _filesMap = new Dictionary<string, string>();
        private readonly IConfigurationSettingCollection _settings;
        private readonly IFileSystem _fileSystem;
        private readonly ICoreShell _coreShell;
        private IRProjectProperties _properties;
        private string _currentFile;
        private string _projectPath;

        public SettingsPageViewModel(IConfigurationSettingCollection settings, ICoreShell coreShell, IFileSystem fileSystem) {
            Check.ArgumentNull(nameof(settings), settings);
            Check.ArgumentNull(nameof(coreShell), coreShell);
            Check.ArgumentNull(nameof(fileSystem), fileSystem);

            _settings = settings;
            _coreShell = coreShell;
            _fileSystem = fileSystem;
        }

        public IEnumerable<string> Files => _filesMap.Keys;
        public SettingsTypeDescriptor TypeDescriptor => new SettingsTypeDescriptor(_coreShell, _settings);

        public string CurrentFile {
            get => _currentFile;
            set {
                if (value != null && !value.EqualsIgnoreCase(_currentFile)) {
                    try {
                        var fullPath = GetFullPath(value);
                        if (!string.IsNullOrEmpty(fullPath)) {
                            _settings.Load(fullPath);
                        }
                        _currentFile = value;
                    } catch (Exception ex) when (!ex.IsCriticalException()) {
                        _coreShell.ShowErrorMessage(string.Format(CultureInfo.InvariantCulture, Resources.Error_UnableToReadSettings, ex.Message));
                    }
                }
            }
        }

        public async Task SetProjectPathAsync(string projectPath, IRProjectProperties properties) {
            _projectPath = projectPath;
            _properties = properties;
            try {
                EnumerateSettingFiles(projectPath);
            } catch (COMException) { } catch (IOException) { } catch (UnauthorizedAccessException) { }

            if (_properties != null) {
                var file = await _properties.GetSettingsFileAsync();
                if (!string.IsNullOrEmpty(file) && _filesMap.ContainsKey(file)) {
                    CurrentFile = file;
                }
            }

            if (CurrentFile == null) {
                CurrentFile = _filesMap.Keys.FirstOrDefault();
            }
        }

        public void AddSetting(string name, string value, ConfigurationSettingValueType valueType) {
            _settings.Add(new ConfigurationSetting(name, value, valueType));
        }

        public void RemoveSetting(IConfigurationSetting s) {
            _settings.Remove(s);
        }

        public async Task<bool> SaveAsync() {
            var fullPath = GetFullPath(CurrentFile);
            if (!string.IsNullOrEmpty(fullPath)) {
                try {
                    _settings.Save(fullPath);
                    await SaveSelectedSettingsFileNameAsync();
                    return true;
                } catch (Exception ex) when (!ex.IsCriticalException()) {
                    _coreShell.ShowErrorMessage(string.Format(CultureInfo.InvariantCulture, Resources.Error_UnableToSaveSettings, fullPath, ex.Message));
                }
            }
            return false;
        }

        public async Task SaveSelectedSettingsFileNameAsync() {
            if (_properties != null) {
                // Remember R path like ~/... so when project moves we can still find the file
                await _properties.SetSettingsFileAsync(CurrentFile);
            }
        }

        public void CreateNewSettingsFile() {
            if (!string.IsNullOrEmpty(_projectPath)) {
                var fullPath = Path.Combine(_projectPath, "Settings.R");
                _currentFile = fullPath.MakeRRelativePath(_projectPath);
                _filesMap[_currentFile] = fullPath;
            }
        }

        private string GetFullPath(string rPath) {
            string fullPath = null;
            if (rPath != null) {
                _filesMap.TryGetValue(rPath, out fullPath);
            }
            return fullPath;
        }

        private void EnumerateSettingFiles(string directory) {
            var entries = _fileSystem.GetFileSystemEntries(directory, ProjectSettingsFiles.SettingsFilePattern, SearchOption.AllDirectories);
            foreach (var entry in entries) {
                var fileName = Path.GetFileName(entry);
                if (ProjectSettingsFiles.IsProjectSettingFile(fileName)) {
                    var relativePath = entry.MakeRRelativePath(_projectPath);
                    _filesMap[relativePath] = entry;
                }
            }
        }
    }
}


text:
using EditorObjects.EditorSettings;
using FlatRedBall;
using FlatRedBall.Content.Math.Splines;
using FlatRedBall.Content.Scene;
using FlatRedBall.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ToolTemplate;

namespace SplineEditor.Commands
{
    public class FileCommands
    {
        public void Save()
        {
            if (string.IsNullOrEmpty(EditorData.SplineList.Name))
            {
                MessageBox.Show("The Spline must first be saved using the \"Save As\" command");
            }
            else
            {

                SplineSaveList ssl = SplineSaveList.FromSplineList(EditorData.SplineList);
                string fileName = EditorData.SplineList.Name;

                ssl.Save(fileName);

                // Save the settings file
                SplineEditorSettingsSave sess = new SplineEditorSettingsSave();

                sess.BoundsCamera = CameraSave.FromCamera(EditorData.BoundsCamera, true);
                sess.ViewCamera = CameraSave.FromCamera(SpriteManager.Camera, false);

                FileManager.XmlSerialize(sess,
                    FileManager.RemoveExtension(fileName) + ".splsetx");
            }
        }

        public void SaveAs()
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Spline XML (*.splx)|*.splx";

            if (EditorData.SplineList != null && !string.IsNullOrEmpty(EditorData.SplineList.Name))
            {
                saveFileDialog.FileName = EditorData.SplineList.Name;
            }

            var dialogResult = saveFileDialog.ShowDialog();

            if (dialogResult == DialogResult.OK)
            {
                EditorData.SplineList.Name = saveFileDialog.FileName;

                Save();
            }
        }

        public void Load()
        {
            OpenFileDialog fileDialog = new OpenFileDialog();

            fileDialog.FileName = "*.splx";

            var dialogResult = fileDialog.ShowDialog();

            if (dialogResult == DialogResult.OK)
            {
                LoadSplineFromFileName(fileDialog.FileName);

            }
        }

        public void LoadSplineFromFileName(string fileName)
        {
            EditorData.LoadSplines(fileName);

            try
            {
                // See if there is a settings file
                string settingsFile = FileManager.RemoveExtension(fileName) + ".splsetx";

                if (FileManager.FileExists(settingsFile))
                {
                    SplineEditorSettingsSave sess = FileManager.XmlDeserialize<SplineEditorSettingsSave>(settingsFile);

                    sess.BoundsCamera.SetCamera(EditorData.BoundsCamera);
                    sess.ViewCamera.SetCamera(SpriteManager.Camera);

                }
            }
            catch (Exception e)
            {
                // no big deal, just a settings file

            }
        }

        internal void LoadScene()
        {
            OpenFileDialog fileDialog = new OpenFileDialog();

            fileDialog.FileName = "*.scnx";

            var dialogResult = fileDialog.ShowDialog();

            if (dialogResult == DialogResult.OK)
            {
                EditorData.LoadScene(fileDialog.FileName);
            }
        }
    }
}


text:
project_type = :stand_alone

# Publishing paths
http_path = "/"
http_images_path = "/images"
http_generated_images_path = "/images"
http_fonts_path = "/fonts"
css_path = "/Users/youtarot/Idea/grain-study/.cache/compass/stylesheets"

# Local development paths
sass_path = "/Users/youtarot/Idea/grain-study/theme/sass"
generated_images_path = "/Users/youtarot/Idea/grain-study/.cache/compass/images"
images_path = "/Users/youtarot/Idea/grain-study/theme/images"
fonts_path = "/Users/youtarot/Idea/grain-study/theme/fonts"

line_comments = false
output_style = :compressed


text:
from scrapy_djangoitem import DjangoItem

from apartments.models import Apartment

# http://www.tucasa.com/
# http://www.habitaclia.com/alquiler-pisos-barcelona.htm
# http://www.fotocasa.es/alquiler/casas/barcelona-capital/listado-por-foto?crp=1&ts=barcelona%20capital&llm=724,9,8,232,376,8019,0,0,0&minp=0&maxp=1000&opi=36&fss=true&mode=1&cu=es-es&pbti=2&nhtti=3&craap=1&fss=true&fs=true&lon=0&lat=0
# http://www.api.cat/es/alquiler/viviendas/barcelona/barcelona

class ApartmentItem(DjangoItem):
    django_model = Apartment


text:
<?php
//
// Copyright (c) 2013, Zynga Inc.
// https://github.com/zynga/saigon
// Author: Matt West (https://github.com/mhwest13)
// License: BSD 2-Clause
//

class SvcEscController extends Controller {

    private function fetchSvcEscInfo($deployment, $action, $modrevision) {
        $svcEscInfo = array();
        $svcEscInfo['name'] = $this->getParam('svcEscName');
        $svcEscInfo['service_description'] = $this->getParam('service');
        $svcEscInfo['contacts'] = $this->getParam('contacts');
        $svcEscInfo['contact_groups'] = $this->getParam('contactgrps');
        $svcEscInfo['first_notification'] = $this->getParam('firstnotif');
        $svcEscInfo['last_notification'] = $this->getParam('lastnotif');
        $svcEscInfo['notification_interval'] = $this->getParam('notifinterval');
        $svcEscInfo['escalation_period'] = $this->getParam('timeperiod');
        $svcEscInfo['escalation_options'] = $this->getParam('escopts');
        if ($svcEscInfo['name'] === false) {
            $viewData = new ViewData();
            $viewData->error = 'Unable to detect name specified for service escalation';
            $viewData->svcescinfo = $svcEscInfo;
            $viewData->svcs = RevDeploy::getCommonMergedDeploymentSvcs($deployment, $modrevision);
            $viewData->timeperiods = RevDeploy::getCommonMergedDeploymentTimeperiodsMetaInfo($deployment, $modrevision);
            $viewData->contacts = RevDeploy::getCommonMergedDeploymentContacts($deployment, $modrevision);
            $viewData->contactgrps = RevDeploy::getCommonMergedDeploymentContactGroups($deployment, $modrevision);
            $viewData->deployment = $deployment;
            $viewData->action = $action;
            $this->sendResponse('svc_esc_action_stage', $viewData);
        } else if ($svcEscInfo['service_description'] === false) {
            $viewData = new ViewData();
            $viewData->error = 'Unable to detect service specified for escalation';
            $viewData->svcescinfo = $svcEscInfo;
            $viewData->svcs = RevDeploy::getCommonMergedDeploymentSvcs($deployment, $modrevision);
            $viewData->timeperiods = RevDeploy::getCommonMergedDeploymentTimeperiodsMetaInfo($deployment, $modrevision);
            $viewData->contacts = RevDeploy::getCommonMergedDeploymentContacts($deployment, $modrevision);
            $viewData->contactgrps = RevDeploy::getCommonMergedDeploymentContactGroups($deployment, $modrevision);
            $viewData->deployment = $deployment;
            $viewData->action = $action;
            $this->sendResponse('svc_esc_action_stage', $viewData);
        } else if (($svcEscInfo['contacts'] === false) && ($svcEscInfo['contact_groups'] === false)) {
            $viewData = new ViewData();
            $viewData->error = 'Unable to detect contacts and contact groups, make sure at least a contact or contact group is specified';
            $viewData->svcescinfo = $svcEscInfo;
            $viewData->svcs = RevDeploy::getCommonMergedDeploymentSvcs($deployment, $modrevision);
            $viewData->timeperiods = RevDeploy::getCommonMergedDeploymentTimeperiodsMetaInfo($deployment, $modrevision);
            $viewData->contacts = RevDeploy::getCommonMergedDeploymentContacts($deployment, $modrevision);
            $viewData->contactgrps = RevDeploy::getCommonMergedDeploymentContactGroups($deployment, $modrevision);
            $viewData->deployment = $deployment;
            $viewData->action = $action;
            $this->sendResponse('svc_esc_action_stage', $viewData);
        } else if ($svcEscInfo['first_notification'] === false) {
            $viewData = new ViewData();
            $viewData->error = 'Unable to detect first notification threshold';
            $viewData->svcescinfo = $svcEscInfo;
            $viewData->svcs = RevDeploy::getCommonMergedDeploymentSvcs($deployment, $modrevision);
            $viewData->timeperiods = RevDeploy::getCommonMergedDeploymentTimeperiodsMetaInfo($deployment, $modrevision);
            $viewData->contacts = RevDeploy::getCommonMergedDeploymentContacts($deployment, $modrevision);
            $viewData->contactgrps = RevDeploy::getCommonMergedDeploymentContactGroups($deployment, $modrevision);
            $viewData->deployment = $deployment;
            $viewData->action = $action;
            $this->sendResponse('svc_esc_action_stage', $viewData);
        } else if ($svcEscInfo['last_notification'] === false) {
            $viewData = new ViewData();
            $viewData->error = 'Unable to detect last notification threshold';
            $viewData->svcescinfo = $svcEscInfo;
            $viewData->svcs = RevDeploy::getCommonMergedDeploymentSvcs($deployment, $modrevision);
            $viewData->timeperiods = RevDeploy::getCommonMergedDeploymentTimeperiodsMetaInfo($deployment, $modrevision);
            $viewData->contacts = RevDeploy::getCommonMergedDeploymentContacts($deployment, $modrevision);
            $viewData->contactgrps = RevDeploy::getCommonMergedDeploymentContactGroups($deployment, $modrevision);
            $viewData->deployment = $deployment;
            $viewData->action = $action;
            $this->sendResponse('svc_esc_action_stage', $viewData);
        } else if ($svcEscInfo['notification_interval'] === false) {
            $viewData = new ViewData();
            $viewData->error = 'Unable to detect notification interval';
            $viewData->svcescinfo = $svcEscInfo;
            $viewData->svcs = RevDeploy::getCommonMergedDeploymentSvcs($deployment, $modrevision);
            $viewData->timeperiods = RevDeploy::getCommonMergedDeploymentTimeperiodsMetaInfo($deployment, $modrevision);
            $viewData->contacts = RevDeploy::getCommonMergedDeploymentContacts($deployment, $modrevision);
            $viewData->contactgrps = RevDeploy::getCommonMergedDeploymentContactGroups($deployment, $modrevision);
            $viewData->deployment = $deployment;
            $viewData->action = $action;
            $this->sendResponse('svc_esc_action_stage', $viewData);
        }
        return $svcEscInfo;
    }

    public function stage() {
        $viewData = new ViewData();
        $deployment = $this->getDeployment('svc_esc_error');
        $modrevision = RevDeploy::getDeploymentNextRev($deployment);
        $viewData->svcescs = RevDeploy::getCommonMergedDeploymentSvcEscalationswInfo($deployment, $modrevision);
        $viewData->deployment = $deployment;
        $this->sendResponse('svc_esc_stage', $viewData);
    }

    public function add_stage() {
        $viewData = new ViewData();
        $deployment = $this->getDeployment('svc_esc_error');
        $modrevision = RevDeploy::getDeploymentNextRev($deployment);
        $viewData->svcs = RevDeploy::getCommonMergedDeploymentSvcs($deployment, $modrevision);
        $viewData->timeperiods = RevDeploy::getCommonMergedDeploymentTimeperiodsMetaInfo($deployment, $modrevision);
        $viewData->contacts = RevDeploy::getCommonMergedDeploymentContacts($deployment, $modrevision);
        $viewData->contactgrps = RevDeploy::getCommonMergedDeploymentContactGroups($deployment, $modrevision);
        $viewData->deployment = $deployment;
        $viewData->action = 'add_write';
        $this->sendResponse('svc_esc_action_stage', $viewData);
    }

    public function add_write() {
        $viewData = new ViewData();
        $deployment = $this->getDeployment('svc_esc_error');
        $this->checkGroupAuthByDeployment($deployment);
        $this->checkDeploymentRevStatus($deployment);
        $modrevision = RevDeploy::getDeploymentNextRev($deployment);
        $viewData->deployment = $deployment;
        $svcEscInfo = $this->fetchSvcEscInfo($deployment,'add_write', $modrevision);
        $svcEscName = $svcEscInfo['name'];
        if (RevDeploy::existsDeploymentSvcEscalation($deployment, $svcEscName, $modrevision) === true) {
            $viewData->error = 'Service Escalation information exists for '.$svcEscName.' in '.$deployment.' Deployment';
            $viewData->svcescinfo = $svcEscInfo;
            $viewData->svcs = RevDeploy::getCommonMergedDeploymentSvcs($deployment, $modrevision);
            $viewData->timeperiods = RevDeploy::getCommonMergedDeploymentTimeperiodsMetaInfo($deployment, $modrevision);
            $viewData->contacts = RevDeploy::getCommonMergedDeploymentContacts($deployment, $modrevision);
            $viewData->contactgrps = RevDeploy::getCommonMergedDeploymentContactGroups($deployment, $modrevision);
            $viewData->action = 'add_write';
            $this->sendResponse('svc_esc_action_stage', $viewData);
        }
        if (RevDeploy::createDeploymentSvcEscalation($deployment, $svcEscName, $svcEscInfo, $modrevision) === false) {
            $viewData->header = $this->getErrorHeader('svc_esc_error');
            $viewData->error = 'Unable to write service esclation information for '.$svcEscName.' into '.$deployment.' Deployment';
            $this->sendError('generic_error', $viewData);
        }
        $viewData->deployment = $deployment;
        $viewData->svcesc = $svcEscName;
        $this->sendResponse('svc_esc_write', $viewData);
    }

    public function modify_stage() {
        $viewData = new ViewData();
        $deployment = $this->getDeployment('svc_esc_error');
        $svcEscName = $this->getParam('svcEsc');
        if ($svcEscName === false) {
            $viewData->header = $this->getErrorHeader('svc_esc_error');
            $viewData->error = 'Unable to detect service escalation specified in post params';
            $this->sendError('generic_error', $viewData);
        }
        $modrevision = RevDeploy::getDeploymentNextRev($deployment);
        $viewData->svcescinfo = RevDeploy::getDeploymentSvcEscalation($deployment, $svcEscName, $modrevision);
        $viewData->svcs = RevDeploy::getCommonMergedDeploymentSvcs($deployment, $modrevision);
        $viewData->timeperiods = RevDeploy::getCommonMergedDeploymentTimeperiodsMetaInfo($deployment, $modrevision);
        $viewData->contacts = RevDeploy::getCommonMergedDeploymentContacts($deployment, $modrevision);
        $viewData->contactgrps = RevDeploy::getCommonMergedDeploymentContactGroups($deployment, $modrevision);
        $viewData->deployment = $deployment;
        $viewData->action = 'modify_write';
        $this->sendResponse('svc_esc_action_stage', $viewData);
    }

    public function modify_write() {
        $viewData = new ViewData();
        $deployment = $this->getDeployment('svc_esc_error');
        $this->checkGroupAuthByDeployment($deployment);
        $this->checkDeploymentRevStatus($deployment);
        $modrevision = RevDeploy::getDeploymentNextRev($deployment);
        $viewData->deployment = $deployment;
        $svcEscInfo = $this->fetchSvcEscInfo($deployment, 'modify_write', $modrevision);
        $svcEscName = $svcEscInfo['name'];
        if (RevDeploy::modifyDeploymentSvcEscalation($deployment, $svcEscName, $svcEscInfo, $modrevision) === false) {
            $viewData->header = $this->getErrorHeader('svc_esc_error');
            $viewData->error = 'Unable to write service escalation information for '.$svcEscName.' into '.$deployment.' Deployment';
            $this->sendError('generic_error', $viewData);
        }
        $viewData->svcesc = $svcEscName;
        $this->sendResponse('svc_esc_write', $viewData);
    }

    public function del_stage() {
        $viewData = new ViewData();
        $deployment = $this->getDeployment('svc_esc_error');
        $svcEscName = $this->getParam('svcEsc');
        if ($svcEscName === false) {
            $viewData->header = $this->getErrorHeader('svc_esc_error');
            $viewData->error = 'Unable to detect service escalation specified in post params';
            $this->sendError('generic_error', $viewData);
        }
        $modrevision = RevDeploy::getDeploymentNextRev($deployment);
        $svcEscInfo = RevDeploy::getDeploymentSvcEscalation($deployment, $svcEscName, $modrevision);
        $viewData->svcescinfo = $svcEscInfo;
        $viewData->deployment = $deployment;
        $viewData->action = 'del_write';
        $viewData->delFlag = true;
        $this->sendResponse('svc_esc_view_stage', $viewData);
    }

    public function del_write() {
        $viewData = new ViewData();
        $deployment = $this->getDeployment('svc_esc_error');
        $this->checkGroupAuthByDeployment($deployment);
        $this->checkDeploymentRevStatus($deployment);
        $svcEscName = $this->getParam('svcEsc');
        if ($svcEscName === false) {
            $viewData->header = $this->getErrorHeader('svc_esc_error');
            $viewData->error = 'Unable to detect service escalation specified in post params';
            $this->sendError('generic_error', $viewData);
        }
        $modrevision = RevDeploy::getDeploymentNextRev($deployment);
        RevDeploy::deleteDeploymentSvcEscalation($deployment, $svcEscName, $modrevision);
        $viewData->deployment = $deployment;
        $viewData->svcesc = $svcEscName;
        $this->sendResponse('svc_esc_delete', $viewData);
    }

    public function copy_stage() {
        $viewData = new ViewData();
        $deployment = $this->getDeployment('svc_esc_error');
        $svcEscName = $this->getParam('svcEsc');
        if ($svcEscName === false) {
            $viewData->header = $this->getErrorHeader('svc_esc_error');
            $viewData->error = 'Unable to detect service specified in post params';
            $this->sendError('generic_error', $viewData);
        }
        $modrevision = RevDeploy::getDeploymentNextRev($deployment);
        $viewData->svcescinfo = RevDeploy::getDeploymentSvcEscalation($deployment, $svcEscName, $modrevision);
        $viewData->svcs = RevDeploy::getCommonMergedDeploymentSvcs($deployment, $modrevision);
        $viewData->timeperiods = RevDeploy::getCommonMergedDeploymentTimeperiodsMetaInfo($deployment, $modrevision);
        $viewData->contacts = RevDeploy::getCommonMergedDeploymentContacts($deployment, $modrevision);
        $viewData->contactgrps = RevDeploy::getCommonMergedDeploymentContactGroups($deployment, $modrevision);
        $viewData->deployment = $deployment;
        $viewData->action = 'copy_write';
        $this->sendResponse('svc_esc_action_stage', $viewData);
    }

    public function copy_common_stage() {
        $viewData = new ViewData();
        $deployment = $this->getDeployment('svc_esc_error');
        $svcEscName = $this->getParam('svcEsc');
        if ($svcEscName === false) {
            $viewData->header = $this->getErrorHeader('svc_esc_error');
            $viewData->error = 'Unable to detect service specified in post params';
            $this->sendError('generic_error', $viewData);
        }
        $modrevision = RevDeploy::getDeploymentNextRev($deployment);
        $viewData->svcescinfo = RevDeploy::getCommonMergedDeploymentSvcEscalation($deployment, $svcEscName, $modrevision);
        $viewData->svcs = RevDeploy::getCommonMergedDeploymentSvcs($deployment, $modrevision);
        $viewData->timeperiods = RevDeploy::getCommonMergedDeploymentTimeperiodsMetaInfo($deployment, $modrevision);
        $viewData->contacts = RevDeploy::getCommonMergedDeploymentContacts($deployment, $modrevision);
        $viewData->contactgrps = RevDeploy::getCommonMergedDeploymentContactGroups($deployment, $modrevision);
        $viewData->deployment = $deployment;
        $viewData->action = 'copy_write';
        $this->sendResponse('svc_esc_action_stage', $viewData);
    }

    public function copy_write() {
        $viewData = new ViewData();
        $deployment = $this->getDeployment('svc_esc_error');
        $this->checkGroupAuthByDeployment($deployment);
        $this->checkDeploymentRevStatus($deployment);
        $modrevision = RevDeploy::getDeploymentNextRev($deployment);
        $svcEscInfo = $this->fetchSvcEscInfo($deployment, 'copy_write', $modrevision);
        $svcEscName = $svcEscInfo['name'];
        if (RevDeploy::existsDeploymentSvcEscalation($deployment, $svcEscName, $modrevision) === true) {
            $viewData->error = 'Service Escalation information exists for '.$svcEscName.' in '.$deployment.' Deployment';
            $viewData->svcs = RevDeploy::getCommonMergedDeploymentSvcs($deployment, $modrevision);
            $viewData->timeperiods = RevDeploy::getCommonMergedDeploymentTimeperiodsMetaInfo($deployment, $modrevision);
            $viewData->contacts = RevDeploy::getCommonMergedDeploymentContacts($deployment, $modrevision);
            $viewData->contactgrps = RevDeploy::getCommonMergedDeploymentContactGroups($deployment, $modrevision);
            $viewData->svcescinfo = $svcEscInfo;
            $viewData->deployment = $deployment;
            $viewData->action = 'copy_write';
            $this->sendResponse('svc_esc_action_stage', $viewData);
        }
        if (RevDeploy::createDeploymentSvcEscalation($deployment, $svcEscName, $svcEscInfo, $modrevision) === false) {
            $viewData->header = $this->getErrorHeader('svc_esc_error');
            $viewData->error = 'Unable to write service escalation information for '.$svcEscName.' into '.$deployment.' Deployment';
            $this->sendError('generic_error', $viewData);
        }
        $viewData->deployment = $deployment;
        $viewData->svcesc = $svcEscName;
        $this->sendResponse('svc_esc_write', $viewData);
    }

}


text:
using System;
using Utilities;
using NUnit.Framework;

namespace UtilitiesTest
{
	[TestFixture]
	public class StringExtensionTests
	{
		#region Variables
		private string _string;
		#endregion

		#region Setup
		[SetUp]
		public void Initialize()
		{
			_string = string.Empty;
		}
		#endregion

		#region Tests
		#region IsDate Tests
		[Test]
		public void TestValidDateNoOutParam ()
		{
			_string = "January 12, 2012";
			Assert.IsTrue (_string.IsDate ());
		}

		[Test]
		public void TestInvalidDateNoOutParam ()
		{
			_string = "Not a date string.";
			Assert.IsFalse (_string.IsDate ());
		}

		[Test]
		public void TestValidDateOutParam ()
		{
			var expected = DateTime.Now;
			_string = expected.ToString ();
			DateTime actual;
			Assert.IsTrue (_string.IsDate (out actual));
			Assert.AreEqual (expected, actual);
		}

		[Test]
		public void TestInvalidDateOutParam ()
		{
			_string = "This is not a date string.";
			DateTime actual;
			Assert.IsFalse (_string.IsDate (out actual));
			Assert.AreEqual (DateTime.MinValue, actual);
		}
		#endregion

		#region IsBool Tests
		[Test]
		public void TestValidBoolNoOutParam ()
		{
			_string = "true";
			Assert.IsTrue (_string.IsBool ());
		}

		[Test]
		public void TestInvalidBoolNoOutParam ()
		{
			_string = "This is not a boolean.";
			Assert.IsFalse (_string.IsBool ());
		}

		[Test]
		public void TestValidBoolOutParam ()
		{
			_string = "TrUe";
			bool actual;
			Assert.IsTrue (_string.IsBool (out actual));
			Assert.IsTrue (actual);
		}

		[Test]
		public void TestInvalidBoolOutParam ()
		{
			_string = "This is not a boolean.";
			bool actual;
			Assert.IsFalse (_string.IsBool (out actual));
			Assert.IsFalse (actual);
		}
		#endregion

		#region IsFloat Tests
		[Test]
		public void TestValidFloatNoOutParam ()
		{
			_string = "2.34233";
			Assert.IsTrue (_string.IsFloat ());
		}

		[Test]
		public void TestInvalidFloatNoOutParam ()
		{
			_string = "This is not a float";
			Assert.IsFalse (_string.IsFloat ());
		}

		[Test]
		public void TestValidFloatOutParam ()
		{
			_string = "2.3242342";
			float actual;
			Assert.IsTrue (_string.IsFloat (out actual));
			Assert.IsTrue (2.3242342, actual);
		}

		[Test]
		public void TestInvalidFloatOutParam ()
		{
			_string = "This is not a float.";
			float actual;
			Assert.IsFalse (_string.IsFloat (out actual));
			Assert.AreSame (0, actual);
		}
		#endregion

		#region IsInt Tests
		[Test]
		public void TestValidIntNoOutParam ()
		{
			_string = "123456";
			Assert.IsTrue (_string.IsInt ());
		}

		[Test]
		public void TestInvalidIntNoOutParam ()
		{
			_string = "This is not an int.";
			Assert.IsFalse (_string.IsInt ());
		}

		[Test]
		public void TestValidIntOutParam ()
		{
			_string = "9000";
			int actual;
			Assert.IsTrue (_string.IsInt (out actual));
			Assert.AreEqual (9000, actual);
		}

		[Test]
		public void TestInvalidIntOutParam ()
		{
			_string = "This is not an int.";
			int actual;
			Assert.IsFalse (_string.IsInt (out actual));
			Assert.AreEqual (0, actual);
		}
		#endregion

		#region IsDouble Tests
		[Test]
		public void TestValidDoubleNoOutParam ()
		{
			_string = "9000.00";
			Assert.IsTrue (_string.IsDouble ());
		}

		[Test]
		public void TestInvalidDoubleNoOutParam ()
		{
			_string = "This is not a double.";
			Assert.IsFalse (_string.IsDouble ());
		}

		[Test]
		public void TestValidDoubleOutParam ()
		{
			_string = "9000.000";
			double actual;
			Assert.IsTrue (_string.IsDouble (out actual));
			Assert.AreEqual (9000.000, actual);
		}

		[Test]
		public void TestInvalidDoubleOutParam ()
		{
			_string = "This is not a double.";
			double actual;
			Assert.IsFalse (_string.IsDouble (out actual));
			Assert.AreEqual (0, actual);
		}
		#endregion

		#region IsChar Tests
		[Test]
		public void TestValidCharNoOutParam ()
		{
			_string = "C";
			Assert.IsTrue (_string.IsChar ());
		}

		[Test]
		public void TestInvalidCharNoOutParam ()
		{
			_string = "This is not a char.";
			Assert.IsFalse (_string.IsChar ());
		}

		[Test]
		public void TestValidCharOutParam ()
		{
			_string = "C";
			char actual;
			Assert.IsTrue (_string.IsChar (out actual));
			Assert.AreEqual ('C', actual);
		}

		[Test]
		public void TestInvalidCharOutParam ()
		{
			_string = "This is not a char.";
			char actual;
			Assert.IsFalse (_string.IsChar (out actual));
			Assert.AreEqual (0, actual);
		}
		#endregion

		#region IsLong Tests
		[Test]
		public void TestValidLongNoOutParam ()
		{
			_string = "9999999999999";
			Assert.IsTrue (_string.IsLong ());
		}

		[Test]
		public void TestInvalidLongNoOutParam ()
		{
			_string = "This is not a long.";
			Assert.IsFalse (_string.IsLong ());
		}

		[Test]
		public void TestValidLongOutParam ()
		{
			long expected = 9999999999999L;
			_string = "9999999999999";
			long actual;
			Assert.IsTrue (_string.IsLong (out actual));
			Assert.AreEqual (expected, actual);
		}

		[Test]
		public void TestInvalidLongTooLarge ()
		{
			_string = "99999999999999999999999999";
			Assert.IsFalse(_string.IsLong());
		}
		#endregion
		#endregion
	}
}


text:
<?php

namespace Functional\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Hostnet\Component\EntityMutation\Mutation;
use Hostnet\Component\EntityMutation\MutationAwareInterface;

/**
 * @ORM\Entity()
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn("type")
 * @ORM\DiscriminatorMap({
 *     1 = "HostingContract",
 *     2 = "DomainContract",
 *     3 = "Contract"
 * })
 * @Mutation(strategy="current")
 */
class Contract implements MutationAwareInterface
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string")
     */
    private $identifier;

    /**
     * @ORM\Column(type="integer")
     */
    private $status;

    /**
     * The history of this object.
     *
     * @ORM\OneToMany(targetEntity="ContractMutation", mappedBy="contract")
     * @ORM\OrderBy(value={"id"="DESC"})
     * @var Collection
     */
    private $mutations;

    /**
     * @param string $identifier
     * @param int    $status
     */
    public function __construct($identifier, $status)
    {
        $this->identifier = $identifier;
        $this->status     = $status;
        $this->mutations  = new ArrayCollection();
    }

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return string
     */
    public function getIdentifier()
    {
        return $this->identifier;
    }

    /**
     * @return int
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * @param DomainContractMutation $mutation
     */
    public function addMutation($mutation)
    {
        // $this->mutations is sorted by id descending, so we should add new
        // items at the start of the Collection. Doctrine collections don't
        // allow this right now, so we add it to the end. This is fixed in
        // getMutations.
        $this->mutations->add($mutation);
    }

    /**
     * @return ContractMutation[]
     */
    public function getMutations()
    {
        $mutations = $this->mutations->toArray();
        usort($mutations, function (ContractMutation $ma, ContractMutation $mb) {
            if ($ma->getId() === $mb->getId()) {
                return 0;
            }
            return ($ma->getId() > $mb->getId()) ? -1 : 1;
        });
        return $mutations;
    }

    /**
     * @return DomainContractMutation
     */
    public function getPreviousMutation()
    {
        throw new \BadMethodCallException(__METHOD__ . ' is not implemented.');
    }
}


text:
<?xml version = '1.0' encoding = 'UTF-8'?>
<Relation class="oracle.dbtools.crest.model.design.logical.Relation" name="Relation_13" directorySegmentName="seg_0" id="9FA9D6A7-7D59-5D2E-A115-98C88FFB9E35">
<createdBy>Jose</createdBy>
<createdTime>2017-03-30 14:43:54 UTC</createdTime>
<generatorID>Generado por el Usuario</generatorID>
<ownerDesignName>MER3</ownerDesignName>
<engineerTo>
<item key="4342E310-8CEF-C4C0-F36D-934105F1D010" value="true"/>
</engineerTo>
<sourcePk>D59F6378-8798-624B-5B6F-244450A24FC6</sourcePk>
<identifying>false</identifying>
<nameOnSource>GENERA</nameOnSource>
<nameOnTarget>ES_GENERADO</nameOnTarget>
<optionalSource>true</optionalSource>
<optionalTarget>false</optionalTarget>
<sourceCardinality>1</sourceCardinality>
<sourceEntity>EBC751B0-32E9-AFE1-C4A5-972CF7582B18</sourceEntity>
<targetCardinalityString>*</targetCardinalityString>
<targetEntity>2C1BB0A5-9ECF-534B-F635-B35EB4C768BC</targetEntity>
<transferable>true</transferable>
<deleteRule>NO ACTION</deleteRule>
</Relation>


text:
//
//  PADTiltCollectionViewController.h
//  PADTiltViewController
//
//  Created by Pavel Dusatko on 5/3/14.
//  Copyright (c) 2014 Pavel Dusatko. All rights reserved.
//

#import <UIKit/UIKit.h>

/**
 *  @abstract A collection view controller that adds device tilt capability to one directional collection views.
 */
@interface PADTiltCollectionViewController : UICollectionViewController

@end


text:
//
//  JSStatusOriginalView.m
//  JSWeibo
//
//  Created by JS on 14-7-14.
//  Copyright (c) 2014年 JS. All rights reserved.
//

#import "JSStatusOriginalView.h"
#import "JSStatusOriginalFrame.h"
#import "JSStatus.h"
#import "JSUser.h"
#import "UIImageView+WebCache.h"
#import "JSStatusPhotosView.h"
#import "JSStatusLabel.h"

@interface JSStatusOriginalView()
/** 昵称 */
@property (nonatomic, weak) UILabel *nameLabel;
/** 正文 */
@property (nonatomic, weak) JSStatusLabel *textLabel;
/** 来源 */
@property (nonatomic, weak) UILabel *sourceLabel;
/** 时间 */
@property (nonatomic, weak) UILabel *timeLabel;

/** 头像 */
@property (nonatomic, weak) UIImageView *iconView;
/** 会员图标 */
@property (nonatomic, weak) UIImageView *vipView;
/** 配图相册 */
@property (nonatomic, weak) JSStatusPhotosView *photosView;
@end

@implementation JSStatusOriginalView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // 1.昵称
        UILabel *nameLabel = [[UILabel alloc] init];
        nameLabel.font = JSStatusOrginalNameFont;
        [self addSubview:nameLabel];
        self.nameLabel = nameLabel;

        // 2.正文(内容)
        JSStatusLabel *textLabel = [[JSStatusLabel alloc] init];
        [self addSubview:textLabel];
        self.textLabel = textLabel;

        // 3.时间
        UILabel *timeLabel = [[UILabel alloc] init];
        timeLabel.textColor = [UIColor orangeColor];
        timeLabel.font = JSStatusOrginalTimeFont;
        [self addSubview:timeLabel];
        self.timeLabel = timeLabel;

        // 4.来源
        UILabel *sourceLabel = [[UILabel alloc] init];
        sourceLabel.textColor = [UIColor lightGrayColor];
        sourceLabel.font = JSStatusOrginalSourceFont;
        [self addSubview:sourceLabel];
        self.sourceLabel = sourceLabel;

        // 5.头像
        UIImageView *iconView = [[UIImageView alloc] init];
        [self addSubview:iconView];
        self.iconView = iconView;

        // 6.会员图标
        UIImageView *vipView = [[UIImageView alloc] init];
        vipView.contentMode = UIViewContentModeCenter;
        [self addSubview:vipView];
        self.vipView = vipView;

        // 7.配图相册
        JSStatusPhotosView *photosView = [[JSStatusPhotosView alloc] init];
        [self addSubview:photosView];
        self.photosView = photosView;
    }
    return self;
}

- (void)setOriginalFrame:(JSStatusOriginalFrame *)originalFrame {
    _originalFrame = originalFrame;
    self.frame = originalFrame.frame;
    // 取出微博数据
    JSStatus *status = originalFrame.status;
    // 取出用户数据
    JSUser *user = status.user;
    // 1.昵称
    self.nameLabel.text = user.name;
    self.nameLabel.frame = originalFrame.nameFrame;
    if (user.isVip) { // 会员
        self.nameLabel.textColor = [UIColor orangeColor];
        self.vipView.hidden = NO;
        self.vipView.frame = originalFrame.vipFrame;
        self.vipView.image = [UIImage imageWithName:[NSString stringWithFormat:@"common_icon_membership_level%d", user.mbrank]];
    } else {
        self.vipView.hidden = YES;
        self.nameLabel.textColor = [UIColor blackColor];
    }

    // 2.正文(内容)
    self.textLabel.attributedText = status.attributedText;
    self.textLabel.frame = originalFrame.textFrame;

    // 3.时间
    NSString *time = status.created_at;
    self.timeLabel.text = time; // 刚刚 --> 1分钟前 --> 10分钟前
    CGFloat timeX = CGRectGetMinX(self.nameLabel.frame);
    CGFloat timeY = CGRectGetMaxY(self.nameLabel.frame) + JSStatusCellInset * 0.5;
    CGSize timeSize = [time sizeWithAttributes:@{NSFontAttributeName:JSStatusOrginalTimeFont}];
    self.timeLabel.frame = (CGRect){{timeX, timeY}, timeSize};

    // 4.来源
    self.sourceLabel.text = status.source;
    CGFloat sourceX = CGRectGetMaxX(self.timeLabel.frame) + JSStatusCellInset;
    CGFloat sourceY = timeY;
    CGSize sourceSize = [status.source sizeWithAttributes:@{NSFontAttributeName:JSStatusOrginalSourceFont}];
    self.sourceLabel.frame = (CGRect){{sourceX, sourceY}, sourceSize};

    // 5.头像
    self.iconView.frame = originalFrame.iconFrame;
    [self.iconView sd_setImageWithURL:[NSURL URLWithString:user.profile_image_url] placeholderImage:[UIImage imageWithName:@"avatar_default_small"]];

    // 6.配图相册
    if (status.pic_urls.count) { // 有配图
        self.photosView.frame = originalFrame.photosFrame;
        self.photosView.pic_urls = status.pic_urls;
        self.photosView.hidden = NO;
    } else {
        self.photosView.hidden = YES;
    }
}

@end


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nms.football.dao.impl;

import com.nms.football.dao.LeagueDao;
import com.nms.football.model.League;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Logger;

/**
 *
 * @author Cuong
 */
public class LeagueDaoImpl extends BaseDaoImpl<League> implements LeagueDao {

    private static final Logger _logger = Logger.getLogger(LeagueDaoImpl.class.getName());

    @Override
    protected void processSaveOrUpdate(Connection conn, PreparedStatement pstm, List<League> entities) throws SQLException {
        String sql = "MERGE INTO league a USING "
                + "(SELECT ? as id, ? as name, ? as country,  ? as history_data, "
                + "? as fixture, ? as livescore, ? as number_of_match FROM DUAL) b "
                + "ON (a.id = b.id) "
                + "WHEN MATCHED THEN "
                + "UPDATE SET "
                + "a.name = b.name, "
                + "a.country = b.country, "
                + "a.history_data = b.history_data, "
                + "a.fixture = b.fixture, "
                + "a.livescore= b.livescore, "
                + "a.number_of_match = b.number_of_match "
                + "WHEN NOT MATCHED THEN "
                + "INSERT (id, name, country, history_data, fixture, livescore, number_of_match) "
                + "VALUES "
                + "(b.id,b.name,b.country,b.history_data,b.fixture,b.livescore,b.number_of_match)";
        pstm = conn.prepareStatement(sql);

        int batchSize = 100;

        for (int count = 0; count < entities.size(); count++) {
            League league = entities.get(count);

            pstm.setInt(1, league.getId());
            pstm.setString(2, league.getName());
            pstm.setString(3, league.getCoutry());
            pstm.setBoolean(4, league.isHistoryData());
            pstm.setBoolean(5, league.isFixtures());
            pstm.setBoolean(6, league.isLivescore());
            pstm.setInt(7, league.getNumberOfMatch());

            pstm.addBatch();

            if (count % batchSize == 0) {
                pstm.executeBatch();
            }
        }

        pstm.executeBatch();
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>cxf</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>cxf</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>


text:
package lee;

import org.springframework.context.*;
import org.springframework.context.support.*;

import org.crazyit.app.service.*;

public class BeanTest
{
	public static void main(String[] args)
	{
		//´´½¨SpringÈÝÆ÷
		ApplicationContext ctx = new
			ClassPathXmlApplicationContext("bean.xml");
		Person p = (Person)ctx.getBean("chinese");
		System.out.println(p.sayHello("ÕÅÈý"));
		p.eat("Î÷¹Ï" , new java.util.Date());
	}
}


text:
http://www.appinn.com/markdown/

## Tool
### xampp(Apache, MariaDB, PHP and Perl)
https://sourceforge.net/projects/xampp/files/

### Java Decompiler
http://jd.benow.ca/

### Regular Expression online
http://www.runoob.com/regexp/regexp-metachar.html
http://tool.chinaz.com/regex/

## HTTP Client Testing Service
http://httpbin.org/

https://github.com/Runscope/httpbin

## Github
https://github.com/qiyeboy/spider_smooc/

## cdn
http://www.bootcdn.cn/
http://www.bootcdn.cn/jquery/
http://www.bootcdn.cn/bootstrap/

## LaTex
Creating Flowcharts with TikZ
https://www.sharelatex.com/blog/2013/08/29/tikz-series-pt3.html
Creating Mind Maps Using TikZ
https://www.sharelatex.com/blog/2013/09/04/tikz-series-pt5.html

## Javascript
http://vuejs.org/
http://jsbin.com/

## log4j
http://logging.apache.org/log4j/

http://blog.csdn.net/anlina_1984/article/details/5313023

## Programming Learning
http://www.runoob.com/

## Web data feed
- http://www.nationalgeographic.com.cn/
- http://www.nationalgeographic.com.cn/index.php?m=content&c=feed

- http://www.dailyenglishquote.com/
- http://www.dailyenglishquote.com/feed/


text:
package com.gemstone.gemfire.cache.query.internal.cq;

import com.gemstone.gemfire.cache.query.CqServiceStatistics;

public class MissingCqServiceStatistics implements CqServiceStatistics {

  @Override
  public long numCqsActive() {
    return 0;
  }

  @Override
  public long numCqsCreated() {
    return 0;
  }

  @Override
  public long numCqsClosed() {
    return 0;
  }

  @Override
  public long numCqsStopped() {
    return 0;
  }

  @Override
  public long numCqsOnClient() {
    return 0;
  }

  @Override
  public long numCqsOnRegion(String regionFullPath) {
    return 0;
  }
}


text:
"""
Sample microservice to provide long-term slow-access storage.
Intent is that production/performance testing environments should use an existing open source database that actually has
features.
"""

from collections import defaultdict
from enum import Enum

from microservice.core.decorator import microservice

class DBSignals(Enum):
    PUT = "put"
    GET = "get"

SimpleKeyValueDatabase = defaultdict(lambda: None)

@microservice
def _db_wrapper(signal, key, value=None):
    if signal == DBSignals.PUT:
        SimpleKeyValueDatabase[key] = value
        retval = True
    elif signal == DBSignals.GET:
        retval = SimpleKeyValueDatabase[key]
    else:
        raise ValueError("Unrecognised DB signal received: %s" % signal)
    return retval

def put(key, value):
    return _db_wrapper(DBSignals.PUT, key=key, value=value)

def get(key):
    return _db_wrapper(DBSignals.GET, key=key)


text:
'use strict';

var fs = require('fs');
var path = require('path');
var assert = require('assert');
var wres = require('..');
var yaml = require('js-yaml');

describe('Examples', function() {
  fs.readdirSync(path.resolve(__dirname, '../examples')).forEach(function (e) {
    // Load each example into a YAML and JSON string, if applicable
    var r_yaml, r_json, r_file = path.resolve(__dirname, '../examples/' + e);
    if(/\.yml/.test(e)) {
      r_yaml = fs.readFileSync(r_file, 'utf8');
      r_json = JSON.stringify(yaml.safeLoad(r_yaml));
    } else if (/\.json/.test(e)) {
      r_json = fs.readFileSync(r_file, 'utf8');
      r_yaml = yaml.safeDump(r_json);
    } else {
      return; // Not a YAML or JSON string, so skip
    }

    var example = path.basename(e, path.extname(e)); // Determine name of the exmaple
    var tempDir = path.join(__dirname, 'temp');
    try {
      fs.mkdirSync(tempDir);
    } catch (err) {}

    // Test wres render with YAML and JSON formats of each example
    it(example + ' (yaml file) renders without error', function() {
      var file = path.join(tempDir, 'resume.yml');
      fs.writeFileSync(file, r_yaml);
      assert.doesNotThrow(function() {
        wres.render(file, null, null, null);
      });
    });
    it(example + ' (json file) renders without error', function() {
      var file = path.join(tempDir, 'resume.json');
      fs.writeFileSync(file, r_json);
      assert.doesNotThrow(function() {
        wres.render(file, null, null, null);
      });
    });
    it(example + ' (yaml string) renders without error', function() {
      assert.doesNotThrow(function() {
        wres.render(r_yaml, null, null, null);
      });
    });
    it(example + ' (json string) renders without error', function() {
      assert.doesNotThrow(function() {
        wres.render(r_json, null, null, null);
      });
    });
  });
});


text:
window.addEventListener('message', function(event) {
  if(event.origin != 'https://www.edu-apps.org') {
    return;
  } else if(!event.data || event.data.action != 'InstallEduApp') {
    return;
  }
  var app = event.data;
  // fill in the form using the info from the app object
  // hide the dialog
  alert("App received!");
  console.log(app);
}, false);

// if the page is an LTI config page, add link to the DOM

// when said link is clicked, load up the app installer in an iframe dialog


text:
package org.mrgeo.services.mrspyramid.rendering;

import org.mrgeo.image.MrsImagePyramid;
import org.mrgeo.utils.Bounds;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Response;
import java.awt.image.Raster;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Interface to implement for classes writing images requested by the WMS to an HTTP response;
 * Implementing class names must begin with the image format name they handle (e.g. "Png") and end
 * with "ImageResponseWriter". This class must stay in the same namespace as ImageHandlerFactory.
 */
public interface ImageResponseWriter
{
  String[] getMimeTypes();

  /**
   * Returns the mime type for the color scale applier
   *
   * @return a mime type string
   */
  String getResponseMimeType();

  String[] getWmsFormats();

  Response write(final Raster raster);
  void write(final Raster raster, final HttpServletResponse response) throws ServletException;

  Response write(final Raster raster, double[] defaults);
  void write(final Raster raster, double[] defaults, final HttpServletResponse response) throws ServletException;

  Response write(final Raster raster, final int tileColumn, final int tileRow, final double scale,
    final MrsImagePyramid pyramid) throws IOException;
  void write(final Raster raster, final int tileColumn, final int tileRow, final double scale,
    final MrsImagePyramid pyramid, final HttpServletResponse response) throws ServletException, IOException;

  /**
   *
   * @param image
   * @param imageName
   * @return
   * @throws IOException
   */
  Response write(final Raster raster, final String imageName, final Bounds bounds);

  void write(final Raster raster, final String imageName, final Bounds bounds,
    final HttpServletResponse response) throws ServletException;

  void writeToStream(final Raster raster, double[] defaults, final ByteArrayOutputStream byteStream)
      throws IOException;
}


text:
package util;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;

/**
 * Created by naga on 13/10/19.
 */
@RunWith(Suite.class)
@Suite.SuiteClasses({
        MethodInvokerTest.正常系テスト.class,
        MethodInvokerTest.異常系テスト.class
})
public class MethodInvokerTest {

    public static class 正常系テスト {

        @Test public void 引数なしメソッドの実行() {
            MethodInvoker sut = new MethodInvoker(new Hoge(), "greeting");
            String actual = sut.invokeAndReturn(String.class);
            assertThat(actual, is("Hi !!"));
        }

        @Test public void 引数なしstaticメソッドの実行() {
            MethodInvoker sut = new MethodInvoker(new Hoge(), "greeting2");
            String actual = sut.invokeAndReturn(String.class);
            assertThat(actual, is("Hello."));
        }

        @Test public void 引数ありメソッドの実行() {
            MethodInvoker sut = new MethodInvoker(new Hoge(), "greeting");
            sut.arg("Tom", String.class);
            String actual = sut.invokeAndReturn(String.class);
            assertThat(actual, is("Hi, Tom !!"));
        }

        @Test public void 複数引数ありメソッドの実行() {
            MethodInvoker sut = new MethodInvoker(new Hoge(), "greeting");
            sut.args(new Object[] {"Tom", 3}, new Class[] {String.class, int.class});
            String actual = sut.invokeAndReturn(String.class);
            assertThat(actual, is("Hi, Tom3 !!"));
        }

        @Test public void メソッドが戻り値を持たない場合はnullが返却される() {
            MethodInvoker sut = new MethodInvoker(new Hoge(), "doNothing");
            String actual = sut.invokeAndReturn(String.class);
            assertThat(actual, is(nullValue()));
        }
    }

    public static class 異常系テスト {

        @Test(expected= Exception.class)
        public void テスト対象メソッドが存在しない場合は例外を投げる() {
            MethodInvoker sut = new MethodInvoker(new Hoge(), "non Exists Methood");
            sut.invoke();
        }

        @Test(expected= Exception.class)
        public void 引数のタイプがnullの場合は例外を投げる() {
            MethodInvoker sut = new MethodInvoker(new Hoge(), "greeting");
            sut.arg("someone", null);
            sut.invoke();
        }

        @Test(expected= Exception.class)
        public void 複数引数の値配列がnullの場合は例外を投げる() {
            MethodInvoker sut = new MethodInvoker(new Hoge(), "greeting");
            sut.args(null, new Class[]{String.class});
            sut.invoke();
        }

        @Test(expected= Exception.class)
        public void 複数引数のタイプ配列がnullの場合は例外を投げる() {
            MethodInvoker sut = new MethodInvoker(new Hoge(), "greeting");
            sut.args(new Object[] {"someone"}, null);
            sut.invoke();
        }

        @Test(expected= Exception.class)
        public void 複数引数の値配列とタイプ配列の要素数が異なる場合は例外を投げる() {
            MethodInvoker sut = new MethodInvoker(new Hoge(), "greeting");
            sut.args(new Object[] {"someone"}, new Class[] {String.class, int.class});
            sut.invoke();
        }
    }
}


text:
@interface Controller (Private)
- (void)setIsLoading:(BOOL)bFlag;
@end

@implementation Controller

+ (void)initialize
{
	NSMutableDictionary *dict = [NSMutableDictionary dictionary];
	[dict setObject:@"http://www.nesium.com/amfdemo/gateway.php" forKey:@"LastGateway"];
	[dict setObject:@"ExampleService.returnArrayCollection" forKey:@"LastService"];
	[dict setObject:@"[]" forKey:@"LastParams"];
	[[NSUserDefaultsController sharedUserDefaultsController] setInitialValues:dict];
}

- (void)awakeFromNib
{
	NSObject <StubCodeGenerator> *generator = [[SCActionscriptGenerator alloc] init];
	[[SCGenerator sharedGenerator] registerGenerator:generator forLanguage:@"Actionscript"];
	[generator release];
	generator = [[SCObjCGenerator alloc] init];
	[[SCGenerator sharedGenerator] registerGenerator:generator forLanguage:@"Objective-C"];
	[generator release];

	m_isLoading = NO;
	m_fieldEditor = [[CAMFFieldEditor alloc] init];
	[m_fieldEditor setFieldEditor:YES];
	[m_gatewayTextField setDelegate:self];
	m_sentHeaders = nil;
	m_receivedHeaders = nil;
	m_outlineViewDataSource = [[OutlineViewDataSource alloc] init];
	[m_objectOutlineView setDataSource:m_outlineViewDataSource];
	[m_objectOutlineView setDelegate:self];
	[m_dataTextView setFont:[NSFont fontWithName:@"Monaco" size:10.0]];
	[m_resultTextView setFont:[NSFont fontWithName:@"Monaco" size:10.0]];
}

- (BOOL)setURLString:(NSString *)urlString
{
	NSURL *url = [NSURL URLWithString:urlString];

	if (url == nil)
	{
		return NO;
	}

	NSMutableString *gatewayURL;
	NSString *service, *args;

	NSArray *params = [[url query] componentsSeparatedByString:@"&"];
	NSMutableArray *unusedParams = [NSMutableArray array];
	for (NSString *param in params)
	{
		NSArray *kv = [param componentsSeparatedByString:@"="];
		NSString *key = [kv objectAtIndex:0];
		NSString *value = [kv objectAtIndex:1];
		if ([key isEqualToString:@"s"])
		{
			service = [value stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
		}
		else if ([key isEqualToString:@"d"])
		{
			args = [value stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
		}
		else
		{
			[unusedParams addObject:param];
		}
	}

	gatewayURL = [NSMutableString stringWithFormat:@"http://%@", [url host]];
	if ([url port] != nil) [gatewayURL appendFormat:@":%@", [url port]];
	if ([url path] != nil) [gatewayURL appendString:[url path]];
	if ([unusedParams count])
		[gatewayURL appendFormat:@"?%@", gatewayURL, [unusedParams componentsJoinedByString:@"&"]];
	[m_gatewayTextField setStringValue:gatewayURL];
	[m_serviceTextField setStringValue:service];
	[m_dataTextView setString:args];
	return YES;
}

- (IBAction)query:(id)sender
{
	if (m_isLoading)
	{
		return;
	}

	NSURL *gatewayURL = [NSURL URLWithString:[m_gatewayTextField stringValue]];
	if (gatewayURL == nil)
	{
		NSBeginAlertSheet(@"Your URL is invalid", @"OK", nil, nil, [NSApp mainWindow], self,
			NULL, NULL, nil, @"%@ is not a valid URL.", [m_gatewayTextField stringValue]);
	}
	NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:gatewayURL];
	[request setHTTPMethod:@"POST"];
	[request setValue:@"application/x-amf" forHTTPHeaderField:@"Content-Type"];
	[request setValue:@"AMFClient" forHTTPHeaderField:@"User-Agent"];

	if ([m_gzipCheckbox state] == NSOffState)
	{
		[request setValue:@"" forHTTPHeaderField:@"Accept-Encoding"];
	}

	NSError *error = nil;
	NSObject *obj;
	@try
	{
		obj = [[CJSONDeserializer deserializer]
			deserialize:[[m_dataTextView string] dataUsingEncoding:NSUTF8StringEncoding]
			error:&error];
	}
	@catch (NSException *e)
	{
		obj = nil;
	}
	if (obj == nil)
	{
		NSBeginAlertSheet(@"Your JSON is invalid", @"OK", nil, nil, [NSApp mainWindow], self,
			NULL, NULL, nil, [error localizedDescription]);
		return;
	}

	m_error = NO;
	m_errorDescription = nil;

	AMFActionMessage *message = [[AMFActionMessage alloc] init];
	AMFMessageBody *body = [[AMFMessageBody alloc] init];
	body.data = obj;
	body.responseURI = @"/1";
	body.targetURI = [m_serviceTextField stringValue];
	message.version = [m_amfTypePopUpButton selectedTag];
	message.bodies = [NSArray arrayWithObject:body];

	[request setHTTPBody:[message data]];
	m_connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
	m_receivedData = [[NSMutableData alloc] init];
	[body release];
	[message release];
	[self setIsLoading:YES];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	[m_receivedHeadersArrayController setContent:nil];
	[m_receivedHeaders release];
	m_receivedHeaders = [[NSMutableArray alloc] init];
	NSEnumerator *headerEnum = [[(NSHTTPURLResponse *)response allHeaderFields] keyEnumerator];
	NSString *headerName;
	while (headerName = [headerEnum nextObject])
	{
		[m_receivedHeaders addObject:[NSDictionary dictionaryWithObjectsAndKeys:
			headerName, @"name", [[(NSHTTPURLResponse *)response allHeaderFields]
			objectForKey:headerName], @"value", nil]];
	}
	[m_receivedHeadersArrayController setContent:m_receivedHeaders];

	if ([[[(NSHTTPURLResponse *)response allHeaderFields] objectForKey:@"Content-Type"]
		rangeOfString:@"application/x-amf"].location == NSNotFound)
	{
		m_error = YES;
		m_errorDescription = [[NSString stringWithFormat:@"The server returned no application/x-amf data at URL %@.",
			[[response URL] absoluteString]] retain];
		return;
	}

	if ([(NSHTTPURLResponse *)response statusCode] != 200)
	{
		m_error = YES;
		m_errorDescription = [[NSString stringWithFormat:@"The server returned status code %d at URL %@.",
			[(NSHTTPURLResponse *)response statusCode], [[response URL] absoluteString]] retain];
	}
}

- (IBAction)copyURL:(id)sender
{
	NSURL *gatewayURL = [NSURL URLWithString:[m_gatewayTextField stringValue]];
	if (gatewayURL == nil)
	{
		NSBeginAlertSheet(@"Your URL is invalid", @"OK", nil, nil, [NSApp mainWindow], self,
			NULL, NULL, nil, @"%@ is not a valid URL.", [m_gatewayTextField stringValue]);
	}
	NSMutableString *url = [NSMutableString stringWithString:[[gatewayURL absoluteString]
		stringByReplacingCharactersInRange:(NSRange){0, [[gatewayURL scheme] length]}
		withString:@"amfclient"]];
	[url appendFormat:@"?s=%@", [[m_serviceTextField stringValue] URLEncodedString]];
	[url appendFormat:@"&d=%@", [[m_dataTextView string] URLEncodedString]];
	[[NSPasteboard generalPasteboard] declareTypes:[NSArray arrayWithObjects:NSStringPboardType,
		nil] owner:nil];
	[[NSPasteboard generalPasteboard] setString:url forType:NSStringPboardType];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	[m_receivedData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	AMFActionMessage *debugMessage = nil;
	AMFActionMessage *message = nil;

	if (!m_error && [m_receivedData length] == 0)
	{
		m_error = YES;
		m_errorDescription = @"The server returned zero bytes of data";
	}

	if (m_error)
	{
		NSBeginAlertSheet(@"Error querying webservice", @"OK", nil, nil, [NSApp mainWindow], self,
			NULL, NULL, nil, m_errorDescription);
		goto bailout;
	}

	debugMessage = [AMFActionMessage alloc];
	message = [AMFActionMessage alloc];
	@try
	{
		debugMessage = [debugMessage initWithDataUsingDebugUnarchiver:m_receivedData];
		message = [message initWithData:m_receivedData];
	}
	@catch (NSException *e)
	{
		NSBeginAlertSheet(@"Could not deserialize response", @"OK", nil, nil, [NSApp mainWindow],
			self, NULL, NULL, nil, [e reason]);
		goto bailout;
	}

	NSObject *debugData = [[debugMessage.bodies objectAtIndex:0] data];
	NSObject *data = [[message.bodies objectAtIndex:0] data];
	m_outlineViewDataSource.rootObject = debugData;
	[m_objectOutlineView reloadData];
	[m_objectOutlineView expandItem:[m_objectOutlineView itemAtRow:0]];

	NSString *jsonString = @"";
	@try
	{
		jsonString = [[CJSONSerializer serializer] serializeObject:data];
	}
	@catch (NSException *e)
	{
		jsonString = @"Could not create JSON representation of response data";
	}
	[m_resultTextView setString:jsonString];
	[[NSApp mainWindow] makeFirstResponder:m_objectOutlineView];
	[m_objectOutlineView selectRow:0 byExtendingSelection:NO];

	bailout:
	[m_errorDescription release];
	[m_connection release];
	[message release];
	[debugMessage release];
	[self setIsLoading:NO];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	NSBeginAlertSheet(@"Error querying webservice", @"OK", nil, nil, [NSApp mainWindow], self,
		NULL, NULL, nil, [error localizedDescription]);
	[self setIsLoading:NO];
}

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request
	redirectResponse:(NSURLResponse *)redirectResponse
{
	[m_sentHeadersArrayController setContent:nil];
	[m_sentHeaders release];
	m_sentHeaders = [[NSMutableArray alloc] init];
	NSEnumerator *headerEnum = [[request allHTTPHeaderFields] keyEnumerator];
	NSString *headerName;
	while (headerName = [headerEnum nextObject])
	{
		[m_sentHeaders addObject:[NSDictionary dictionaryWithObjectsAndKeys:
			headerName, @"name", [request valueForHTTPHeaderField:headerName], @"value", nil]];
	}
	[m_sentHeadersArrayController setContent:m_sentHeaders];
	return request;
}

- (BOOL)outlineView:(NSOutlineView *)outlineView shouldTypeSelectForEvent:(NSEvent *)event
	withCurrentSearchString:(NSString *)searchString
{
	if ([[event charactersIgnoringModifiers] characterAtIndex:0] == ' ')
	{
		if ([m_objectOutlineView selectedRow] != -1)
		{
			if ([m_detailViewHUDPanel isVisible])
			{
				[m_detailViewHUDPanel orderOut:self];
			}
			else
			{
				NSString *value = [m_outlineViewDataSource
					valueForObject:[m_objectOutlineView
					itemAtRow:[m_objectOutlineView selectedRow]]];
				[m_detailTextView setString:(value == nil || [value length] == 0)
					? @"(empty)" : value];
				[m_detailViewHUDPanel orderFront:self];
			}
			return NO;
		}
	}
	return YES;
}

- (BOOL)outlineView:(NSOutlineView *)outlineView shouldSelectItem:(id)item
{
	if ([m_detailViewHUDPanel isVisible])
	{
		NSString *value = [m_outlineViewDataSource
			valueForObject:item];
		[m_detailTextView setString:(value == nil || [value length] == 0)
			? @"(empty)" : value];
	}
	return YES;
}

- (id)windowWillReturnFieldEditor:(NSWindow *)sender toObject:(id)anObject
{
	if (anObject == m_gatewayTextField)
	{
		return m_fieldEditor;
	}
	return nil;
}

- (BOOL)fieldEditor:(NSTextView *)fieldEditor willPasteText:(NSString *)text
{
	if ([[[text substringToIndex:[@"amfclient://" length]] lowercaseString]
		isEqualToString:@"amfclient://"])
	{
		return [self setURLString:text];
	}
	return NO;
}

- (IBAction)focusGatewayTextField:(id)sender
{
	[[NSApp mainWindow] makeFirstResponder:m_gatewayTextField];
}

- (IBAction)focusServiceTextField:(id)sender
{
	[[NSApp mainWindow] makeFirstResponder:m_serviceTextField];
}

- (IBAction)focusDataTextView:(id)sender
{
	[[NSApp mainWindow] makeFirstResponder:m_dataTextView];
	[m_dataTextView setSelectedRange:(NSRange){0, [[m_dataTextView string] length]}];
}

- (IBAction)selectNextTab:(id)sender
{
	NSInteger index = [m_tabView indexOfTabViewItem:[m_tabView selectedTabViewItem]] + 1;
	if (index == [m_tabView numberOfTabViewItems])
	{
		index = 0;
	}
	[m_tabView selectTabViewItemAtIndex:index];
}

- (IBAction)selectPreviousTab:(id)sender
{
	NSInteger index = [m_tabView indexOfTabViewItem:[m_tabView selectedTabViewItem]] - 1;
	if (index == -1)
	{
		index = [m_tabView numberOfTabViewItems] - 1;
	}
	[m_tabView selectTabViewItemAtIndex:index];
}

- (void)setIsLoading:(BOOL)bFlag
{
	m_isLoading = bFlag;
	[m_executeButton setEnabled:!bFlag];
	if (bFlag)
	{
		[m_progressIndicator startAnimation:self];
	}
	else
	{
		[m_progressIndicator stopAnimation:self];
	}
}

#pragma mark -
#pragma mark OutlineView Delegate methods

- (NSMenu *)outlineView:(NSOutlineView *)outlineView contextMenuForItem:(id)item
{
	NSString *objectClassName = [(AMFDebugDataNode *)item objectClassName];
	if (objectClassName == nil)
	{
		return nil;
	}
	NSMenu *menu = [[[NSMenu alloc] init] autorelease];
	NSMenuItem *subMenuItem = [[NSMenuItem alloc]
		initWithTitle:[NSString stringWithFormat:@"Copy stub code for %@ ...", objectClassName]
			action:NULL keyEquivalent:@""];
	NSMenu *subMenu = [[NSMenu alloc] init];
	[subMenuItem setSubmenu:subMenu];
	NSArray *languages = [[SCGenerator sharedGenerator] languageNames];
	int i = 0;
	for (NSString *languageName in languages)
	{
		NSMenuItem *menuItem = [[NSMenuItem alloc]
			initWithTitle:[NSString stringWithFormat:@"in %@", languageName]
			action:@selector(copyStubCode:) keyEquivalent:@""];
		[menuItem setTag:i++];
		[menuItem setTarget:self];
		[menuItem setRepresentedObject:item];
		[subMenu addItem:menuItem];
		[menuItem release];
	}
	[menu addItem:subMenuItem];
	[subMenuItem release];
	[subMenu release];
	return menu;
}

#pragma mark ContextMenu action methods

- (void)copyStubCode:(NSMenuItem *)sender
{
	AMFDebugDataNode *node = (AMFDebugDataNode *)[sender representedObject];
	NSString *languageName = [[[SCGenerator sharedGenerator] languageNames]
		objectAtIndex:[sender tag]];
	[[NSPasteboard generalPasteboard] declareTypes:[NSArray arrayWithObjects:NSStringPboardType,
		nil] owner:nil];
	[[NSPasteboard generalPasteboard]
		setString:[[SCGenerator sharedGenerator] stubCodeForDataNode:node languageName:languageName]
		forType:NSStringPboardType];
}

@end


text:
package org.dynmap.common;

import java.io.File;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;

import org.dynmap.DynmapChunk;
import org.dynmap.DynmapWorld;
import org.dynmap.common.DynmapListenerManager.EventType;
import org.dynmap.utils.MapChunkCache;

/**
 * This interface defines a server-neutral interface for the DynmapCore and other neutral components to use to access server provided
 * services.  Platform-specific plugin must supply DynmapCore with an instance of an object implementing this interface.
 */
public abstract class DynmapServerInterface {
    /**
     * Schedule task to run on server-safe thread (one suitable for other server API calls)
     * @param run - runnable method
     * @param delay - delay in server ticks (50msec)
     */
    public abstract void scheduleServerTask(Runnable run, long delay);
    /**
     * Call method on server-safe thread
     * @param task - Callable method
     * @param <T> - return value type for method called
     * @return future for completion of call
     */
    public abstract <T> Future<T> callSyncMethod(Callable<T> task);
    /**
     * Get list of online players
     * @return list of online players
     */
    public abstract DynmapPlayer[] getOnlinePlayers();
    /**
     * Request reload of plugin
     */
    public abstract void reload();
    /**
     * Get active player
     * @param name - player name
     * @return player
     */
    public abstract DynmapPlayer getPlayer(String name);
    /**
     * Get offline player
     * @param name - player name
     * @return player (offline or not)
     */
    public abstract DynmapPlayer getOfflinePlayer(String name);

    /**
     * Get banned IPs
     * @return set of banned IPs
     */
    public abstract Set<String> getIPBans();
    /**
     * Get server name
     * @return server name
     */
    public abstract String getServerName();
    /**
     * Test if player ID is banned
     * @param pid - player ID
     * @return true if banned
     */
    public abstract boolean isPlayerBanned(String pid);
    /**
     * Strip out chat color
     * @param s - string to strip
     * @return string stripped of color codes
     */
    public abstract String stripChatColor(String s);
    /**
     * Request notificiation for given events (used by DynmapListenerManager)
     * @param type - event type
     * @return true if successful
     */
    public abstract boolean requestEventNotification(EventType type);
    /**
     * Send notification of web chat message
     * @param source - source
     * @param name - name
     * @param msg - message text
     * @return true if not cancelled
     */
    public abstract boolean sendWebChatEvent(String source, String name, String msg);
    /**
     * Broadcast message to players
     * @param msg - message
     */
    public abstract void broadcastMessage(String msg);
    /**
     * Get Biome ID lis
     * @return list of biome IDs
     */
    public abstract String[] getBiomeIDs();
    /**
     * Get snapshot cache hit rate
     * @return hit rate
     */
    public abstract double getCacheHitRate();
    /**
     * Reset cache stats
     */
    public abstract void resetCacheStats();
    /**
     * Get world by name
     * @param wname - world name
     * @return world object, or null if not found
     */
    public abstract DynmapWorld getWorldByName(String wname);
    /**
     * Test which of given set of permisssions a possibly offline user has
     * @param player - player
     * @param perms - set of permission IDs
     * @return set of permission IDs allowed to player
     */
    public abstract Set<String> checkPlayerPermissions(String player, Set<String> perms);
    /**
     * Test single permission attribute
     * @param player - player
     * @param perm - permission ID
     * @return true if permitted
     */
    public abstract boolean checkPlayerPermission(String player, String perm);
    /**
     * Render processor helper - used by code running on render threads to request chunk snapshot cache
     * @param w - world
     * @param chunks - list of chunks
     * @param blockdata - include block data, if true
     * @param highesty - include highest Y, if true
     * @param biome - include biome data, if true
     * @param rawbiome - include raw biome data, if true
     * @return chunk map
     */
    public abstract MapChunkCache createMapChunkCache(DynmapWorld w, List<DynmapChunk> chunks,
        boolean blockdata, boolean highesty, boolean biome, boolean rawbiome);
    /**
     * Get maximum player count
     * @return maximum online players
     */
    public abstract int getMaxPlayers();
    /**
     * Get current player count
     * @return number of online players
     */
    public abstract int getCurrentPlayers();
    /**
     * Test if given mod is loaded (Forge)
     * @param name - mod name
     * @return true if mod loaded
     */
    public boolean isModLoaded(String name) {
        return false;
    }
    /**
     * Get version of mod with given name
     *
     * @param name - name of mod
     * @return version, or null of not found
     */
    public String getModVersion(String name) {
        return null;
    }

    /**
     * Get block ID at given coordinate in given world (if chunk is loaded)
     * @param wname - world name
     * @param x - X coordinate
     * @param y - Y coordinate
     * @param z - Z coordinate
     * @return block ID, or -1 if chunk at given coordinate isn't loaded
     */
    public abstract int getBlockIDAt(String wname, int x, int y, int z);
    /**
     * Get current TPS for server (20.0 is nominal)
     * @return ticks per second
     */
    public abstract double getServerTPS();
    /**
     * Get address configured for server
     *
     * @return "" or null if none configured
     */
    public abstract String getServerIP();
    /**
     * Get file/directory for given mod (for loading mod resources)
     * @param mod - mod name
     * @return file or directory, or null if not loaded
     */
    public File getModContainerFile(String mod) {
        return null;
    }
    /**
     * Get mod list
     * @return list of mods
     */
    public List<String> getModList() {
        return Collections.emptyList();
    }
    /**
     * Get block ID map (modID:blockname, keyed by block ID)
     * @return block ID map
     */
    public Map<Integer, String> getBlockIDMap() {
        return Collections.emptyMap();
    }
    /**
     * Open resource (check all mods)
     * @param modid - mod id
     * @param rname - resource namep
     * @return stream, or null
     */
    public InputStream openResource(String modid, String rname) {
        return null;
    }
    /**
     * Get block unique ID map (module:blockid)
     * @return block unique ID map
     */
    public Map<String, Integer> getBlockUniqueIDMap() {
        return Collections.emptyMap();
    }
    /**
     * Get item unique ID map (module:itemid)
     * @return item unique ID map
     */
    public Map<String, Integer> getItemUniqueIDMap() {
        return Collections.emptyMap();
    }
    /**
     * Test if current thread is server thread
     * @return true if server thread
     */
    public boolean isServerThread() {
        return false;
    }
}


text:
TEST(ErrorsTest, InterfaceError)
{
    turbodbc::interface_error error("message");
    EXPECT_EQ("message", std::string(error.what()));
}


text:
function calcTrendLine(xSeries, ySeries, ignoreLeadingZeros) {
  ignoreLeadingZeros = (ignoreLeadingZeros !== undefined || ignoreLeadingZeros !== null) ? ignoreLeadingZeros : true;

  if(xSeries.length < ySeries.length) {
    return [[0, 0], [0, 0]];
  }

  var n;
  var idx;
  var sumPlus = 0;
  var sumSquaredX = 0;
  var sumX = 0;
  var sumY = 0;
  var startOffset = 0;

  var adjustedXSeries = [];
  var adjustedYSeries = [];
  var foundValue = false;

  if(ySeries[0] === 0) {
    for(idx = 0; idx < xSeries.length; idx++) {
      if(ySeries[idx] !== 0 || foundValue) {
        adjustedXSeries.push(xSeries[idx]);
        if(idx < ySeries.length) {
          adjustedYSeries.push(ySeries[idx]);
        }

        if(!foundValue) {
          startOffset = idx + 1;
          foundValue = true;
        }
      }
    }
  } else {
    adjustedXSeries = xSeries;
    adjustedYSeries = ySeries;
  }

  n = adjustedYSeries.length;

  for(idx = 0; idx < adjustedYSeries.length; idx++) {
    sumPlus += adjustedXSeries[idx] * adjustedYSeries[idx];
    sumX += adjustedXSeries[idx];
    sumY += adjustedYSeries[idx];
    sumSquaredX += Math.pow(adjustedXSeries[idx], 2);
  }

  var a = n * sumPlus;
  var b = sumX * sumY;
  var c = n * sumSquaredX;
  var d = Math.pow(sumX, 2);
  var m = (a - b) / (c - d);

  var e = sumY;
  var f = m * sumX;

  var bSlope = (e - f) / n;

  return [[startOffset, _calcYForX(startOffset)], [xSeries.length, _calcYForX(xSeries.length)]];

  function _calcYForX(x) {
    return m * x + bSlope;
  }
}