text:
DROP INDEX IF EXISTS IDX_KNOWLEDGE_ID_VARCHAR;
CREATE INDEX IDX_KNOWLEDGE_ID_VARCHAR ON KNOWLEDGES(CAST(KNOWLEDGE_ID AS VARCHAR(20)));


text:
<!DOCTYPE html>

		<meta content="IE=edge" http-equiv="x-ua-compatible"></meta>
		<link href="./css/graph.css" rel="stylesheet"></link>
		<link href="./css/bootstrap.min.css" rel="stylesheet"></link>
		<link href="./css/theme.default.css" rel="stylesheet"></link>
		<link href="./css/datepicker.css" rel="stylesheet"></link>

        <title>Common Reporting Summary</title>

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

					</button>
					Max Hour BreakDown

							2015

Select API:
										<select id="selectDropdown" class="select" onchange="selectChanged()"  style="font-weight: normal;"></select>

redpajama_set_name: RedPajamaGithub


text:
//
//  ViewController.m
//  1-CoreData
//
//  Created by qianfeng on 16/1/27.
//  Copyright © 2016年 Jane. All rights reserved.
//

#import "ViewController.h"
//导入头文件
#import <CoreData/CoreData.h>
#import "Person+CoreDataProperties.h"
@interface ViewController ()
//声明属性 数据库 coredata 上下文 方便使用
@property (nonatomic,strong) NSManagedObjectContext *context;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self createContext];
    [self insertData];
    [self selectData];
//    [self deleteDate];
}

/**
 *  创建CoreData 上下文Context
 */
-(void)createContext{

    //1.找到模型url (NSbundle 找)
    //2.初始化模型 NSManagedObjectModel *model=....
    //3.添加数据库支持  NSPersistentStoreCoordinator
    //4.找个路径存放他
    //5.拼接全路径
    //6.找到该路径 NSURL fileUrlWith。。。。
    //7.家协调器 NSPersistentStore
    //8.创建上下文

    //1.先从bundle中加载模型文件 (可以再创建项目是自动生成 也可以自动创建)
    //找到模型的url
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"];
    //初始化模型文件
    NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:url];

    NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];

    NSString *docs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

    docs = [docs stringByAppendingPathComponent:@"coredata.sqlite"];

    NSURL *sqlUrl = [NSURL fileURLWithPath:docs];

    NSError *error = nil;
    //添加协调器
    //1.类型 NSSQLiteStoreType
    //2.config nil
    //3.url  路径
    //4.options nil
    //5.错误信息 用error存储
    NSPersistentStore *store = [psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:sqlUrl options:nil error:&error];
    if (error) {
        NSLog(@"创建数据库失败了");
        //oc抛出异常

        [NSException raise:@"添加失败" format:@"%@",[error localizedDescription]];
    }else{
        NSLog(@"创建数据库成功了");
           NSLog(@"%@",NSHomeDirectory());
    }

    //创建COredata的上下文
    NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
    context.persistentStoreCoordinator = psc;
    self.context = context;
}

/**
 *  怎加数据
 */
- (void)insertData {

    //数据模型 NSManagedObject
    //用来描述模型 NSEntityDescription
    //第一个参数是实体名称
    //第二个是上下文
    Person *obj = [NSEntityDescription  insertNewObjectForEntityForName:@"Person" inManagedObjectContext:_context];
    //给插入得数据赋值 KVC 键值编码
//    [obj setValue:@"猪猪" forKey:@"name"];
//    [obj setValue:@11 forKey:@"age"];

    obj.name = @"猪猪";
    obj.age = @18;
    NSError *error = nil;
    //context save 必须保存下
    if([_context save:&error]){
        NSLog(@"插入成功");
    }else{
        NSLog(@"%@",error);
    }
}

/**
 *  查询数据
 */
-(void)selectData{

    //1.FatchRequest
    //2.设置实体
    //3.设置条件

    NSFetchRequest *request = [[NSFetchRequest alloc] init];

    //查询的条件 和要查询的实体

    //1.查询实体
    request.entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:_context];

    //查询条件 谓词
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@",@"猪猪"];

    request.predicate = predicate;

    //获取结果
    NSError *error = nil;
    NSArray *resl = [_context executeFetchRequest:request error:&error];
    if (error) {
        NSLog(@"%@",error);
    }else{

//        NSLog(@"%@",resl);
        //类似forin 枚举器
        [resl enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSLog(@"name=%@  age=%@",[obj valueForKey:@"name"],[obj valueForKey:@"age"]);
        }];
    }

}

/**
 *  删除数据
 */
-(void)deleteDate{

    //先查询
    NSFetchRequest *request = [[NSFetchRequest alloc]init];

    request.entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:_context];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K = %@",@"name",@"小明"];
    request.predicate = predicate;
    NSArray *result = [_context executeFetchRequest:request error:nil];
    //删除
    for (Person *item in result) {
        [_context deleteObject:item];
    }
    //删除完后要保存
    if([_context save:nil]){
        NSLog(@"删除成功");
    }else{
        NSLog(@"删除失败");
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
// Copyright (c) 2000 Matthias Clasen
// See the file COPYING for copying permission.

#ifndef UTF16CodingSystem_INCLUDED
#define UTF16CodingSystem_INCLUDED 1

#include "CodingSystem.h"

#ifdef SP_NAMESPACE
namespace SP_NAMESPACE {
#endif

class SP_API UTF16CodingSystem : public CodingSystem {
public:
  Decoder *makeDecoder(Boolean) const;
  Encoder *makeEncoder() const;
};

#ifdef SP_NAMESPACE
}
#endif

#endif /* not UTF16CodingSystem_INCLUDED */


text:
"""
Utility to upload folders to swift using the form post middleware
credentials provided by zuul
"""

import argparse
import magic
import os
import requests
import sys
import tempfile
import time

def generate_log_index(file_list, logserver_prefix, swift_destination_prefix):
    """Create an index of logfiles and links to them"""

    output = '<title>Index of results</title>'
    output += '
'
    for f in file_list:
        file_url = os.path.join(logserver_prefix, swift_destination_prefix, f)
        # Because file_list is simply a list to create an index for and it
        # isn't necessarily on disk we can't check if a  file is a folder or
        # not. As such we normalise the name to get the folder/filename but
        # then need to check if the last character was a trailing slash so to
        # re-append it to make it obvious that it links to a folder
        filename_postfix = '/' if f[-1] == '/' else ''
        filename = os.path.basename(os.path.normpath(f)) + filename_postfix
        output += '
'
        output += '%s' % (file_url, filename)
        output += '
'

    output += '
'
    output += ''
    return output

def make_index_file(file_list, logserver_prefix, swift_destination_prefix,
                    index_filename='index.html'):
    """Writes an index into a file for pushing"""

    index_content = generate_log_index(file_list, logserver_prefix,
                                       swift_destination_prefix)
    tempdir = tempfile.mkdtemp()
    fd = open(os.path.join(tempdir, index_filename), 'w')
    fd.write(index_content)
    return os.path.join(tempdir, index_filename)

def get_file_mime(file_path):
    """Get the file mime using libmagic"""

    if not os.path.isfile(file_path):
        return None

    if hasattr(magic, 'from_file'):
        return magic.from_file(file_path, mime=True)
    else:
        # no magic.from_file, we might be using the libmagic bindings
        m = magic.open(magic.MAGIC_MIME)
        m.load()
        return m.file(file_path).split(';')[0]

def swift_form_post_submit(file_list, url, hmac_body, signature):
    """Send the files to swift via the FormPost middleware"""

    # We are uploading the file_list as an HTTP POST multipart encoded.
    # First grab out the information we need to send back from the hmac_body
    payload = {}

    (object_prefix,
     payload['redirect'],
     payload['max_file_size'],
     payload['max_file_count'],
     payload['expires']) = hmac_body.split('\n')
    payload['signature'] = signature

    # Loop over the file list in chunks of max_file_count
    for sub_file_list in (file_list[pos:pos + int(payload['max_file_count'])]
                          for pos in xrange(0, len(file_list),
                                            int(payload['max_file_count']))):
        if payload['expires'] < time.time():
            raise Exception("Ran out of time uploading files!")
        files = {}
        # Zuul's log path is generated without a tailing slash. As such the
        # object prefix does not contain a slash and the files would be
        # uploaded as 'prefix' + 'filename'. Assume we want the destination
        # url to look like a folder and make sure there's a slash between.
        filename_prefix = '/' if url[-1] != '/' else ''
        for i, f in enumerate(sub_file_list):
            if os.path.getsize(f['path']) > int(payload['max_file_size']):
                sys.stderr.write('Warning: %s exceeds %d bytes. Skipping...\n'
                                 % (f['path'], int(payload['max_file_size'])))
                continue
            files['file%d' % (i + 1)] = (filename_prefix + f['filename'],
                                         open(f['path'], 'rb'),
                                         get_file_mime(f['path']))
        requests.post(url, data=payload, files=files)

def build_file_list(file_path, logserver_prefix, swift_destination_prefix,
                    create_dir_indexes=True):
    """Generate a list of files to upload to zuul. Recurses through directories
       and generates index.html files if requested."""

    # file_list: a list of dicts with {path=..., filename=...} where filename
    #            is appended to the end of the object (paths can be used)
    file_list = []
    if os.path.isfile(file_path):
        file_list.append({'filename': os.path.basename(file_path),
                          'path': file_path})
    elif os.path.isdir(file_path):
        if file_path[-1] == os.sep:
            file_path = file_path[:-1]
        parent_dir = os.path.dirname(file_path)
        for path, folders, files in os.walk(file_path):
            folder_contents = []
            for f in files:
                full_path = os.path.join(path, f)
                relative_name = os.path.relpath(full_path, parent_dir)
                push_file = {'filename': relative_name,
                             'path': full_path}
                file_list.append(push_file)
                folder_contents.append(relative_name)

            for f in folders:
                full_path = os.path.join(path, f)
                relative_name = os.path.relpath(full_path, parent_dir)
                folder_contents.append(relative_name + '/')

            if create_dir_indexes:
                index_file = make_index_file(folder_contents, logserver_prefix,
                                             swift_destination_prefix)
                relative_name = os.path.relpath(path, parent_dir)
                file_list.append({
                    'filename': os.path.join(relative_name,
                                             os.path.basename(index_file)),
                    'path': index_file})

    return file_list

def grab_args():
    """Grab and return arguments"""
    parser = argparse.ArgumentParser(
        description="Upload results to swift using instructions from zuul"
    )
    parser.add_argument('--no-indexes', action='store_true',
                        help='do not generate any indexes at all')
    parser.add_argument('--no-root-index', action='store_true',
                        help='do not generate a root index')
    parser.add_argument('--no-dir-indexes', action='store_true',
                        help='do not generate a indexes inside dirs')
    parser.add_argument('-n', '--name', default="logs",
                        help='The instruction-set to use')
    parser.add_argument('files', nargs='+', help='the file(s) to upload')

    return parser.parse_args()

if __name__ == '__main__':
    args = grab_args()
    file_list = []
    root_list = []

    try:
        logserver_prefix = os.environ['SWIFT_%s_LOGSERVER_PREFIX' % args.name]
        swift_destination_prefix = os.environ['LOG_PATH']
        swift_url = os.environ['SWIFT_%s_URL' % args.name]
        swift_hmac_body = os.environ['SWIFT_%s_HMAC_BODY' % args.name]
        swift_signature = os.environ['SWIFT_%s_SIGNATURE' % args.name]
    except KeyError as e:
        print 'Environment variable %s not found' % e
        quit()

    for file_path in args.files:
        file_path = os.path.normpath(file_path)
        if os.path.isfile(file_path):
            root_list.append(os.path.basename(file_path))
        else:
            root_list.append(os.path.basename(file_path) + '/')

        file_list += build_file_list(
            file_path, logserver_prefix, swift_destination_prefix,
            (not (args.no_indexes or args.no_dir_indexes))
        )

    index_file = ''
    if not (args.no_indexes or args.no_root_index):
        index_file = make_index_file(root_list, logserver_prefix,
                                     swift_destination_prefix)
        file_list.append({
            'filename': os.path.basename(index_file),
            'path': index_file})

    swift_form_post_submit(file_list, swift_url, swift_hmac_body,
                           swift_signature)

    print os.path.join(logserver_prefix, swift_destination_prefix,
                       os.path.basename(index_file))


text:
package com.quantarray.skylark.measure

import scala.language.higherKinds

/**
  * Can exponentiate quantity type class.
  *
  * @author Araik Grigoryan
  */
trait CanExponentiateQuantity[N, M, Q[_, _], RM] extends CanExponentiateMeasure[M, RM]
{
  type QR

  def powQuantity(base: Q[N, M], exponent: Double): QR
}


text:
// Copyright 2015 - present The Direct Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import {app} from './app.js';

/*
 * initializes wrapperElem for specTabCtrl scope
 * element is a jqLite wrapper around an element with class=spec-tab-ctrl-wrap
 */
app.directive('specTabCtrlWrap', function () {
  return {
    restrict: 'C',
    link: function ($scope, element, attrs) {
      $scope.wrapperElem = element;
    },
  };
});

/*
 * enables drag-to-reorder rows,
 * and clicking outside of containment to close drawer
 */
app.directive('specGridContainment', function () {
  return {
    restrict: 'C',
    link: function ($scope, element, attrs) {
      // options for drag-to-reorder rows
      $scope.sortableOptions = {
        axis: 'y',
        handle: '.item-canvas',
        tolerance: 'pointer',
        disabled: !$scope.editing,
        containment: element,
      };

      $scope.$watch('editing', function () {
        $scope.sortableOptions.disabled = !$scope.editing;
      });
    },
  };
});

/*
 * sizes the spec property tags on the timeline view
 */
app.directive('specPropertyTagSizer', function ($timeout) {
  return {
    restrict: 'A',
    link: function ($scope, element, attrs) {
      var updateSize = function () {
        var itemCanvasWrap = element.parent('.item-canvas-wrap');
        if (itemCanvasWrap.width() > 200) {
          element.css('max-width', '100%');
        } else {
          element.css('max-width', 200);

          var canvasMargin =
            itemCanvasWrap.outerWidth(true) - itemCanvasWrap.outerWidth();
          var specItem = element.closest('.spec-item');
          if (canvasMargin + element.outerWidth() > specItem.width()) {
            var offset =
              specItem.width() - (canvasMargin + element.outerWidth());
            if (Math.abs(offset) < canvasMargin) {
              element.css('margin-left', offset);
            } else {
              element.css('margin-left', 0);
            }
          }
        }
      };
      $(window).resize(updateSize);
      $(document).ready(updateSize);
    },
  };
});

/**
 * Allow stepping through video with arrow keys
 */
app.directive('scrubbable', function () {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      var video = element[0];

      /* timeline video scrubbing */
      var gridContainment = $(element[0])
        .parents('.spec-content')
        .find('.spec-grid-containment');

      // convert between timestamp in seconds to pixels from left edge of spec
      var secondsToX = function (videoSeconds) {
        var videoMs = videoSeconds * 1000;
        var numMinorDivisions = videoMs / scope.spec.divisions.minor;
        var coordinateX = numMinorDivisions * scope.spec.divisions.minorGap;
        return coordinateX;
      };

      var xToSeconds = function (coordinateX) {
        var ms = scope.spec.divisions.minor;
        var mGap = scope.spec.divisions.minorGap;
        var timestampMs = (coordinateX / mGap) * ms;
        var timestampSeconds = timestampMs * 0.001;
        return timestampSeconds;
      };

      var onTimeUpdate = function () {
        var x = secondsToX(video.currentTime);
        moveScrubber(x);
        updateTimestamp();
        if (!video.paused || video.seeking) {
          window.requestAnimationFrame(onTimeUpdate);
        }
      };

      var updateTimestamp = function () {
        // request angular to update value for video.currentTime in UI
        scope.$apply();
      }
        // @ts-ignore
        .throttle(); // rate limit this event to one / 100ms (to prevent ui lag)

      video.addEventListener('seeking', function () {
        window.requestAnimationFrame(onTimeUpdate);
      });

      video.addEventListener('play', function () {
        window.requestAnimationFrame(onTimeUpdate);
      });

      var constrainScrubberX = function (x) {
        var gridWidth = $(gridContainment).find('.spec-grid').width();
        var durationX = secondsToX(video.duration);
        // @ts-ignore
        var maxAllowedX = Math.min(durationX, gridWidth);
        x = Math.min(x, maxAllowedX);
        x = Math.max(x, 0);
        return x;
      };

      var scrubber = $(gridContainment).find('.spec-grid-scrubber');
      var moveScrubber = function (x) {
        if (!scrubber.length) {
          scrubber = $(gridContainment).find('.spec-grid-scrubber');
        }
        scope.refreshCanvas();
        scrubber.css('left', constrainScrubberX(x));
      };

      var scrubVideoX = function (x) {
        var timestampSeconds = xToSeconds(x);

        if (timestampSeconds < video.duration) {
          if (!video.paused) {
            video.pause();
          }
          video.currentTime = timestampSeconds;
          window.requestAnimationFrame(onTimeUpdate);
        }
      }
        // @ts-ignore
        .throttle(); // rate limit this event to one / 100ms (to prevent ui lag)

      // listen to mouse events on the scrub handle
      $(gridContainment).one('mouseover', '.spec-grid-scrubber', function () {
        var scrubber = $(this);
        // @ts-ignore
        scrubber.draggable({
          axis: 'x',
          cursorAt: {left: 0},
          drag: function (evt, ui) {
            ui.position.left = constrainScrubberX(ui.position.left);
            scrubVideoX(ui.position.left);
          },
        });
      });

      // show warning message if durations don't match
      var checkDurationMatch = function () {
        if (video.duration && scope.spec.duration) {
          var warn =
            Math.abs(video.duration * 1000 - scope.spec.duration) > 100;
          scope.toggleVideoWarning(warn);
          scope.setCanScrubVideo(!warn);
        }
      };

      scope.$watch('spec.duration', checkDurationMatch);
      video.addEventListener('durationchange', checkDurationMatch);
    },
  };
});

app.directive('loadedData', function () {
  return function ($scope, $element) {
    var parentScope = $scope.$parent;
    parentScope.video = $element[0];

    parentScope.video.addEventListener('loadeddata', function () {
      console.log('Video loaded');
      $scope.$parent.$broadcast('refreshCanvas');

      // attach functions to video play controls
      parentScope.toggleVideoLooping = function () {
        parentScope.video.loop = !parentScope.video.loop;
      };

      parentScope.toggleVideoPaused = function () {
        if (parentScope.video.paused) {
          parentScope.video.play();
        } else {
          parentScope.video.pause();
        }
      };
    });
  };
});


text:
import json
import unittest

try:
    from .testfiles.test_components import test_components
except (ImportError, SystemError):
    from .testfiles.test_components import test_components

class TestLoadComponents(unittest.TestCase):
    def test_load_assertion_from_test_components(self):
        assertion = test_components['2_0_basic_assertion']
        assertion_value = json.loads(assertion)
        self.assertEqual(assertion_value['issuedOn'], "2016-12-31T23:59:59Z")


text:
<component name="libraryTable">
  <library name="com.mortennobel:java-image-scaling:0.8.6" type="repository">
    <properties maven-id="com.mortennobel:java-image-scaling:0.8.6" />
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/lib/java-image-scaling-0.8.6.jar!/" />
      <root url="jar://$PROJECT_DIR$/lib/filters-2.0.235.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand

required_packages = ['pyparsing==2.0.3']
if sys.version_info[:2] == (2, 6):
    required_packages.append('ordereddict')

class PyTestCommand(TestCommand):
    user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]

    def initialize_options(self):
        TestCommand.initialize_options(self)
        self.pytest_args = []

    def finalize_options(self):
        TestCommand.finalize_options(self)
        self.test_args = []
        self.test_suite = True

    def run_tests(self):
        import pytest
        errno = pytest.main(self.pytest_args)
        sys.exit(errno)

setup(
    name='pyhocon',
    version='0.3.5',
    description='HOCON parser for Python',
    long_description='pyhocon is a HOCON parser for Python. Additionally we provide a tool (pyhocon) to convert any HOCON content into json, yaml and properties format.',
    keywords='hocon parser',
    license='Apache License 2.0',
    author='Francois Dang Ngoc',
    author_email='francois.dangngoc@gmail.com',
    url='http://github.com/chimpler/pyhocon/',
    classifiers=[
        'License :: OSI Approved :: Apache Software License',
        'Topic :: Software Development :: Libraries :: Python Modules',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
    ],
    packages=[
        'pyhocon',
    ],
    install_requires=required_packages,
    tests_require=['pytest'],
    entry_points={
        'console_scripts': [
            'pyhocon=pyhocon.tool:main'
        ]
    },
    test_suite='tests',
    cmdclass={
        'test': PyTestCommand
    }
)


text:
<?php

namespace Maybe\Tests;

use Maybe\Maybe;

use Maybe\Util\Reflection as TestClass;

class MaybeTest extends \PHPUnit_Framework_TestCase {

	public function testMaybeCanWrapAnObjectWithoutAlteringIt () {

		$maybe = new Maybe('Maybe\Tests\Simple');
		$simple = new Simple();

		$wrapped = $maybe->wrap($simple);

		$this->assertEquals($simple->doSomething(), $wrapped->doSomething());
		$this->assertEquals($simple->doSomethingElse(), $wrapped->doSomethingElse());
	}

	public function testMaybeCanWrapNullAndProvideAFakeInstanceOfAClass () {

		$maybe = new Maybe('Maybe\Tests\Simple');

		$wrapped = $maybe->wrap(null);

		$this->assertTrue(method_exists($wrapped,'doSomething'));
		$this->assertTrue(method_exists($wrapped,'doSomethingElse'));
		$this->assertInstanceOf('Maybe\Tests\Simple',$wrapped);
		$this->assertInstanceOf('Maybe\Tests\SimpleInterface',$wrapped);
	}

	public function testMaybeCanWrapNullAndProvideAFakeImplementationOfAnInterface () {

		$maybe = new Maybe('Maybe\Tests\SimpleInterface');

		$wrapped = $maybe->wrap(null);

		$this->assertTrue(method_exists($wrapped,'doSomething'));
		$this->assertTrue(method_exists($wrapped,'doSomethingElse'));
		$this->assertInstanceOf('Maybe\Tests\SimpleInterface',$wrapped);
	}

	public function testFakeInstancesShouldReturnTheRightTypeAccordingToAnnotations () {

		$maybe = new Maybe('Maybe\Tests\Simple');

		$wrapped = $maybe->wrap(null);

		$this->assertInternalType('int', $wrapped->doSomething());
		$this->assertInternalType('string', $wrapped->doSomethingElse());
		$this->assertInternalType('bool', $wrapped->returnSomeBoolean());
		$this->assertInternalType('float', $wrapped->returnSomeFloatNumber());
		$this->assertInternalType('array', $wrapped->returnSomeArray());
		$this->assertNull($wrapped->uncommented());
		$this->assertNull($wrapped->commentedButUnknown());

	}

	public function testMaybeCanProvideAFakeInstanceDirectly () {

		$maybe = new Maybe('Maybe\Tests\Simple');

		$wrapped = $maybe->wrap(null);

		$this->assertEquals($wrapped, $maybe->buildFakeObject());
	}

	public function testFakeInstancesShouldWrapReturnedObjectsWithMaybe () {

		$maybe = new Maybe('Maybe\Tests\Simple');
		$fake = $maybe->buildFakeObject();

		$this->assertInstanceOf('\Maybe\Util\Reflection', $fake->getReflection());
		$this->assertInstanceOf('Maybe\Tests\AnotherEmptyClass', $fake->getAnotherEmptyClass());
		$this->assertInternalType('int', $fake->getAnotherEmptyClass()->getThree());
		$this->assertNotEquals(3, $fake->getAnotherEmptyClass()->getThree());

		//NOT IMPLEMENTED YET
		//$this->assertInstanceOf('Maybe\Util\Reflection', $fake->getTestClass());

	}

	public function testFakeInstancesShouldAcceptAnyNumberOfArgument () {
		$maybe = new Maybe('Maybe\Tests\Simple');
		$fake = $maybe->buildFakeObject();

		$this->assertInternalType('int', $fake->getAnotherEmptyClass()->getThree(1,2,3,'foo'));
	}
}

interface SimpleInterface {
	/**
	 * @return int
	 */
	public function doSomething ();

	/**
	 * @return string
	 */
	public function doSomethingElse ();
}

class Simple implements SimpleInterface {
	/**
	 * @return int
	 */
	public function doSomething () {
		return 3;
	}

	/**
	 * @return string
	 */
	public function doSomethingElse () {
		return 'foobar';
	}

	/** @return bool a boolean value */
	public function returnSomeBoolean () {}

	/** @return float a float value */
	public function returnSomeFloatNumber () {}

	/** @return array an array */
	public function returnSomeArray () {}

	public function uncommented () {}

	/** @return zertyui dzffdfzfonz */
	public function commentedButUnknown () {}

	/**
	 * @return AnotherEmptyClass some random object
	 */
	public function getAnotherEmptyClass () {
		return null;
	}

	/**
	 * @return \Maybe\Util\Reflection
	 */
	public function getReflection () {
		return null;
	}

	/**
	 * @return TestClass an object using an alias in "use"
	 */
	public function getTestClass () {
		return null;
	}

}

class AnotherEmptyClass {

	/**
	 * @return int 3
	 */
	public function getThree () {
		return 3;
	}

}


text:
package io.sommers.packmode.proxy;

import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraftforge.fml.common.FMLCommonHandler;

import java.util.List;

public class ServerProxy extends CommonProxy<EntityPlayerMP> {
    @Override
    public List<EntityPlayerMP> getPlayers() {
        return FMLCommonHandler.instance().getMinecraftServerInstance().getPlayerList().getPlayers();
    }
}


text:
all :
	@echo "The default build process has changed, and this Makefile is just for useful hints in unusual cases."
	@echo ""
	@echo "You probably want to run the following to build and install the code:"
	@echo "  python setup.py install --user"

# Mike likes to use python's virtual environments to build with
# various versions and arrangements of python.  As such, he finds that
# the following is, unfortunately, necessary for him.  This makes him
# happy.  It is probably not necessary for most users, however.
MikeHappy :
	$(VIRTUAL_ENV)/bin/python setup.py install --prefix=$(VIRTUAL_ENV)

#	cd Quaternions && $(VIRTUAL_ENV)/bin/python setup.py install --prefix=$(VIRTUAL_ENV)

############################################
## Flags for building only the c++ files: ##
############################################
# The compiler needs to be able to find the GSL (GNU Scientific
# Library) headers and libraries.  The following paths are the most
# common places for these to be installed.  If compilation doesn't
# work, correct these paths.
INCFLAGS = -IQuaternions -I/opt/local/include -I/usr/local/include
LIBFLAGS = -L/opt/local/lib -L/usr/local/lib
ifdef GSL_HOME
	INCFLAGS = -I${GSL_HOME}/include ${INCFLAGS}
	LIBFLAGS = -L${GSL_HOME}/lib ${LIBFLAGS}
endif
# Set compiler name and optimization flags here, if desired
C++ = g++
OPT = -O3 -Wall -Wno-deprecated
## DON'T USE -ffast-math in OPT

#############################################################################
## The following are pretty standard and probably won't need to be changed ##
#############################################################################

# Tell 'make' not to look for files with the following names
.PHONY : all cpp clean allclean realclean swig Quaternions doc

# This rebuilds the documentation, assuming doxygen is working
doc :
	make -C docs

# If needed, we can also make object files to use in other C++ programs
cpp : Quaternions/Quaternions.o Combinatorics.o WignerDMatrices.o SWSHs.o

# This is how to build those object files
%.o : %.cpp %.hpp Errors.hpp
	$(C++) $(OPT) -c $(INCFLAGS) $< -o $@

# The following are just handy targets for removing compiled stuff
clean :
	-/bin/rm -f *.o
allclean : clean
	-/bin/rm -rf build
realclean : allclean

# This just runs SWIG, which can be handy for committing pre-swigged files
swig :
	swig -python -globals constants -c++ -o SphericalFunctions_wrap.cpp SphericalFunctions.i


text:
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { HotKeys } from 'react-hotkeys';
import DocumentTitle from 'react-document-title';

import { fetchConfig } from '../actions/config';
import keyboardShortcuts from '../constants/keyboardShortcuts';

// Components
import Sidebar from './Sidebar';
import Header from './Header';
import Notifications from './Notifications';

class App extends Component {

  componentDidMount() {
    const { fetchConfig } = this.props;
    fetchConfig();
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.updated !== nextProps.updated) {
      const { fetchConfig } = this.props;
      fetchConfig();
    }
  }

  render() {
    const { config, isFetching } = this.props;

    if (isFetching) {
      return null;
    }

    return (
      <DocumentTitle title="Bunto Admin">
        <HotKeys
          keyMap={keyboardShortcuts}
          className="wrapper">
          {
            config.content &&

              <Sidebar config={config.content} />

                  {this.props.children}

              <Notifications />

          }
        </HotKeys>
      </DocumentTitle>
    );
  }
}

App.propTypes = {
  children: PropTypes.element,
  fetchConfig: PropTypes.func.isRequired,
  config: PropTypes.object.isRequired,
  isFetching: PropTypes.bool.isRequired,
  updated: PropTypes.bool
};

const mapStateToProps = (state) => ({
  config: state.config.config,
  updated: state.config.updated,
  isFetching: state.config.isFetching,
});

const mapDispatchToProps = (dispatch) => bindActionCreators({
  fetchConfig
}, dispatch);

export default connect(mapStateToProps, mapDispatchToProps)(App);


text:
export {default as bisect, bisectRight, bisectLeft} from "./bisect.js";
export {default as ascending} from "./ascending.js";
export {default as bisector} from "./bisector.js";
export {default as count} from "./count.js";
export {default as cross} from "./cross.js";
export {default as descending} from "./descending.js";
export {default as deviation} from "./deviation.js";
export {default as extent} from "./extent.js";
export {default as group} from "./group.js";
export {default as bin, default as histogram} from "./bin.js"; // Deprecated; use bin.
export {default as thresholdFreedmanDiaconis} from "./threshold/freedmanDiaconis.js";
export {default as thresholdScott} from "./threshold/scott.js";
export {default as thresholdSturges} from "./threshold/sturges.js";
export {default as max} from "./max.js";
export {default as maxIndex} from "./maxIndex.js";
export {default as mean} from "./mean.js";
export {default as median} from "./median.js";
export {default as merge} from "./merge.js";
export {default as min} from "./min.js";
export {default as minIndex} from "./minIndex.js";
export {default as pairs} from "./pairs.js";
export {default as permute} from "./permute.js";
export {default as quantile} from "./quantile.js";
export {default as quickselect} from "./quickselect.js";
export {default as range} from "./range.js";
export {default as rollup} from "./rollup.js";
export {default as least} from "./least.js";
export {default as leastIndex} from "./leastIndex.js";
export {default as scan} from "./scan.js"; // Deprecated; use leastIndex.
export {default as shuffle} from "./shuffle.js";
export {default as sum} from "./sum.js";
export {default as ticks, tickIncrement, tickStep} from "./ticks.js";
export {default as transpose} from "./transpose.js";
export {default as variance} from "./variance.js";
export {default as zip} from "./zip.js";


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Sitecore.Shell.Client.Bootstrap3.Layouts.Renderings.Common.InlineStyles
{
  public partial class InlineStyleRenderingModel : Sitecore.Mvc.Presentation.SpeakRenderingModel
  {
    [System.CodeDom.Compiler.GeneratedCodeAttribute("SitecoreRocks", "1.0.0.0")]
    public string Style { get { return this.GetString("Style"); } }
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<catalog prefer="public" xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog">
    <group id="Folder Repository, directory=, recursive=true, Auto-Update=true, version=2" prefer="public" xml:base="">
        <uri id="Automatically generated entry, Timestamp=1337197063543" name="http://purl.obolibrary.org/obo/obi.owl" uri="obi.b4.owl"/>
        <uri id="Automatically generated entry, Timestamp=1337197063543" name="duplicate:http://purl.obolibrary.org/obo/webService.owl" uri="obi.owl"/>
        <uri id="Automatically generated entry, Timestamp=1337197063543" name="duplicate:http://purl.obolibrary.org/obo/webService.owl" uri="webService.owl"/>
        <uri id="Automatically generated entry, Timestamp=1337197063543" name="http://purl.org/obo/all" uri="edam.owl"/>
    </group>
</catalog>


text:
<?php
include("conectare_db.php");

$sql = 'begin :rezultat :=  admin_pachet.insert_joc(:v_nume,:v_dif,:v_descr,:v_instr,:v_domeniu,:i_link,:g_link); END;';
$stid = oci_parse($connection, $sql);
if (preg_match('/\W /', $_POST["nume"]) && $_POST["nume"] != null) {
    session_start();
    $_SESSION["mesaj_err"] = "Textul contine caractere invalide!";
    header('Location: ../FRONT/HTML/pagina_eroare_admin.html');
    exit;
}
oci_bind_by_name($stid, ":v_nume", $_POST["nume"]);
oci_bind_by_name($stid, ":v_dif", $_POST["dificultate"]);
if (preg_match('/\W /', $_POST["descr"]) && $_POST["descr"] != null) {
    session_start();
    $_SESSION["mesaj_err"] = "Textul contine caractere invalide!";
    header('Location: ../FRONT/HTML/pagina_eroare_admin.html');
    exit;
}
oci_bind_by_name($stid, ":v_descr", $_POST["descr"]);
if (preg_match('/\W /', $_POST["instr"]) && $_POST["instr"] != null) {
    session_start();
    $_SESSION["mesaj_err"] = "Textul contine caractere invalide!";
    header('Location: ../FRONT/HTML/pagina_eroare_admin.html');
    exit;
}
oci_bind_by_name($stid, ":v_instr", $_POST["instr"]);
oci_bind_by_name($stid, ":v_domeniu", $_POST["domeniu"]);
$target_dir = "../../../IMG/JOCURI/";
$info = pathinfo($_FILES['fileToUpload']['name']);
$ext = $info['extension']; // get the extension of the file
$newname = $_POST["nume"] . "." . $ext;
$target_file = $target_dir . $newname;
$uploadOk = 1;
if (isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if ($check !== false) {
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Allow certain file formats
if ($ext != "jpg" && $ext != "png" && $ext != "jpeg") {
    echo "Sorry, only JPG, and PNG files are allowed.";
    $uploadOk = 0;
}
if ($uploadOk == 0) {
    echo "Sorry, your picture was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        oci_bind_by_name($stid, ":i_link", $target_file);
        oci_bind_by_name($stid, ":g_link", $_POST["game_path"]);
        oci_bind_by_name($stid, ':rezultat', $rezultat, 100);
        if (!oci_execute($stid)) {
            $e = oci_error($stid);
            echo "Something went wrong :( <br/>";
            echo "Error: " . $e['message'];
        }
        oci_free_statement($stid);
        oci_close($connection);
        echo $rezultat;
    } else {
        echo "Sorry, there was an error uploading your picture.";
    }
}
?>


text:
package com.fizzbuzz.vroom.core.api.filter;

import com.fizzbuzz.vroom.core.api.service.CorsService;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.restlet.Context;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.data.Method;
import org.restlet.engine.header.Header;
import org.restlet.engine.header.HeaderConstants;
import org.restlet.engine.header.MethodWriter;
import org.restlet.routing.Filter;
import org.restlet.util.Series;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class CorsFilter extends Filter {
    public enum CorsResponseHeader {
        ALLOW_ORIGIN("Access-Control-Allow-Origin"),
        ALLOW_CREDENTIALS("Access-Control-Allow-Credentials"),
        EXPOSE_HEADERS("Access-Control-Expose-Headers"),
        MAX_AGE("Access-Control-Max-Age"),
        ALLOW_METHODS("Access-Control-Allow-Methods"),
        ALLOW_HEADERS("Access-Control-Allow-Headers");
        private final String name;

        CorsResponseHeader(final String name) {
            this.name = name;
        }
    }

    private final Logger mLogger = LoggerFactory.getLogger(PackageLogger.TAG);
    private CorsService corsService;

    /**
     * Constructor.
     *
     * @param context The parent context.
     */
    public CorsFilter(Context context) {
        super(context);
    }

    @Override
    protected void afterHandle(final Request request, final Response response) {
        super.afterHandle(request, response);

        Series<Header> requestHeaders = (Series<Header>)
                request.getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS);

        String origin = requestHeaders.getFirstValue("Origin", true);

        if (origin != null) {
            // handle pre-flight OPTIONS requests
            Method requestedMethod = getRequestedMethod(requestHeaders);
            List<String> requestedHeaders = getRequestedHeaders(requestHeaders);

            if (request.getMethod() == Method.OPTIONS && requestedMethod != null) {
                handlePreflightRequest(request, response, origin, requestedMethod, requestedHeaders);
            } else
                handleNormalRequest(request, response, origin);
        }
    }

    protected boolean supportsCredentials(final Request request, final Response response) {
        // this default implementation uses the CorsService's configuration to determine whether credentials
        // are supported.  Override this method to implement more specific logic, such as determining this on a
        // per-resource basis.
        return getCorsService().getAllowCredentials();
    }

    protected long getMaxAge(final Request request, final Response response) {
        // this default implementation uses the CorsService's configuration for the max age.  Override this
        // method to implement more specific logic, such as determining this on a per-resource basis
        return getCorsService().getMaxAge();
    }

    protected Set<Method> getAllowedMethods(final Request request, final Response response) {
        // this implementation returns the set of methods implemented on the resource.  Override this method
        // to implement more specific logic.
        Set<Method> result = response.getAllowedMethods();
        return result;
    }

    protected CorsService getCorsService() {
        if (corsService == null)
            corsService = getApplication().getServices().get(CorsService.class);
        return corsService;
    }

    protected boolean allowAllOrigins(final Request request, final Response response) {
        return getAllowedOrigins(request, response).contains("*");
    }

    protected List<String> getAllowedOrigins(final Request request, final Response response) {
        return getCorsService().getAllowedOrigins();
    }

    protected void handlePreflightRequest(final Request request, final Response response,
                                          final String origin, final Method requestedMethod,
                                          final List<String> requestedHeaders) {
        // We already now that the origin header was provided; that was checked in afterHandle
        // See http://www.w3.org/TR/cors section 6.2, step 1

        // Check whether the origin is in the allowed list of origins (this is a case-sensitive compare,
        // See http://www.w3.org/TR/cors section 6.2, step 2
        if (originIsAllowed(request, response, origin)) {

            // We already know that the requested method is non-null; that was already checked in afterHandle
            // See http://www.w3.org/TR/cors section 6.2, step 3

            // We have the list of requested headers.  See http://www.w3.org/TR/cors section 6.2, step 4

            // Check that the requested method is allowed
            // See http://www.w3.org/TR/cors section 6.2, step 5
            if (methodIsAllowed(request, response, requestedMethod)) {

                // Check that all of the requested headers are allowed. Note: this is a case-insensitive compare
                // See http://www.w3.org/TR/cors section 6.2, step 6
                if (allRequestedHeadersAreAllowed(request, response, requestedHeaders)) {

                    // If the resource supports credentials, add an Access-Control-Allow-Origin header for the origin,
                    // and a Access-Control-Allow-Credentials header.  Otherwise, add an Access-Control-Allow-Origin
                    // header, with either the value of the Origin header or the string "*" as value.
                    // see http://www.w3.org/TR/cors section 6.2, step 7
                    if (supportsCredentials(request, response)) {
                        addResponseHeader(response, CorsResponseHeader.ALLOW_ORIGIN, origin);
                        addResponseHeader(response, CorsResponseHeader.ALLOW_CREDENTIALS, "true");
                    } else {
                        addResponseHeader(response, CorsResponseHeader.ALLOW_ORIGIN,
                                allowAllOrigins(request, response) ? "*" : origin);
                    }

                    // Optionally add a single Access-Control-Max-Age header with as value the amount of seconds the
                    // user agent is allowed to cache the result of the request.
                    // See http://www.w3.org/TR/cors section 6.2, step 8
                    if (getMaxAge(request, response) > 0) {
                        addResponseHeader(response, CorsResponseHeader.MAX_AGE,
                                Long.toString(getCorsService().getMaxAge()));
                    }

                    // Set the Access-Control-Allow-Methods header to reflect the methods allowed.
                    // See http://www.w3.org/TR/cors section 6.2, step 9
                    addResponseHeader(response, CorsResponseHeader.ALLOW_METHODS,
                            MethodWriter.write(getAllowedMethods(request, response)));

                    // Add Access-Control-Allow-Headers headers for each requested header
                    // See http://www.w3.org/TR/cors section 6.2, step 10
                    for (String allowedHeader : getAllowedHeaders(request, response))
                        addResponseHeader(response, CorsResponseHeader.ALLOW_HEADERS, allowedHeader);
                }
            }
        }
    }

    protected List<String> getAllowedHeaders(final Request request, final Response response) {
        // This default implementation uses the allowed headers configured on the CorsService.  Override this
        //  method to implement more specific logic, such as determining the allowed headers on a per-resource basis.
        List<String> result = getCorsService().getAllowedHeaders();
        return result;
    }

    protected void handleNormalRequest(final Request request, final Response response, final String origin) {
        // We already now that the origin header was provided; that was checked in afterHandle.
        // See http://www.w3.org/TR/cors section 6.1, step 1

        // Check that the origin is allowed.
        // See http://www.w3.org/TR/cors section 6.1, step 2
        if (originIsAllowed(request, response, origin)) {
            // If the resource supports credentials, add an Access-Control-Allow-Origin header for the origin,
            // and a Access-Control-Allow-Credentials header.  Otherwise, add an Access-Control-Allow-Origin
            // header, with either the value of the Origin header or the string "*" as value.
            // see http://www.w3.org/TR/cors section 6.1, step 3
            if (supportsCredentials(request, response)) {
                addResponseHeader(response, CorsResponseHeader.ALLOW_ORIGIN, origin);
                addResponseHeader(response, CorsResponseHeader.ALLOW_CREDENTIALS, "true");
            } else {
                addResponseHeader(response, CorsResponseHeader.ALLOW_ORIGIN,
                        allowAllOrigins(request, response) ? "*" : origin);
            }

            // Indicate which response headers should be exposed
            // See http://www.w3.org/TR/cors section 6.1, step 4
            List<String> exposedHeaders = getExposedHeaders(request, response);
            if (!exposedHeaders.isEmpty()) {
                addResponseHeader(response, CorsResponseHeader.EXPOSE_HEADERS, Joiner.on(",").join(exposedHeaders));
            }

        }
    }

    protected List<String> getExposedHeaders(final Request request, final Response response) {
        // This default implementation uses the exposed headers configured on the CorsService.  Override this
        // method to implement more specific logic, such as determining the exposed headers on a per-resource basis.
        return getCorsService().getExposedHeaders();
    }

    protected void addResponseHeader(final Response response, final CorsResponseHeader corsHeader, final String value) {
        addCustomResponseHeader(response, corsHeader.name, value);
    }

    private Method getRequestedMethod(final Series<Header> requestHeaders) {
        String requestedMethod = requestHeaders.getFirstValue("Access-Control-Request-Method", true);
        return requestedMethod == null ? null : new Method(requestedMethod);
    }

    private List<String> getRequestedHeaders(final Series<Header> requestHeaders) {
        // Get the list of requested headers
        List<String> requestedHeaders = new ArrayList<>();
        String accessControlRequestHeaders = requestHeaders.getFirstValue("Access-Control-Request-Headers", true);
        if (accessControlRequestHeaders != null)
            requestedHeaders.addAll(Lists.newArrayList(Splitter.on(",").trimResults().split
                    (accessControlRequestHeaders)));
        return requestedHeaders;
    }

    private boolean originIsAllowed(final Request request, final Response response, final String origin) {
        List<String> allowedOrigins = getAllowedOrigins(request, response);
        boolean result = allowAllOrigins(request, response) || allowedOrigins.contains(origin);
        if (!result)
            mLogger.debug("origin not allowed: {}.  Allowed origins: {}", origin, allowedOrigins);
        return result;
    }

    private boolean methodIsAllowed(final Request request, final Response response, final Method requestedMethod) {
        Set<Method> allowedMethods = getAllowedMethods(request, response);
        boolean result = allowedMethods.contains(requestedMethod);
        if (!result)
            mLogger.debug("method not allowed: {}.  Allowed methods: {}", requestedMethod, allowedMethods);
        return result;
    }

    private boolean allRequestedHeadersAreAllowed(final Request request, final Response response,
                                                  final List<String> requestedHeaders) {
        List<String> allowedHeaders = getAllowedHeaders(request, response);
        boolean allAreAllowed = true;
        for (String header : requestedHeaders) {
            boolean thisOneIsAllowed = false;
            for (String allowedHeader : allowedHeaders) {
                if (header.equalsIgnoreCase(allowedHeader)) {
                    thisOneIsAllowed = true;
                    break;
                }
            }
            if (!thisOneIsAllowed) {
                mLogger.debug("header not allowed: {}.  Allowed headers: {}", header, allowedHeaders);
                allAreAllowed = false;
                break;
            }
        }
        return allAreAllowed;
    }

    private void addCustomResponseHeader(final Response response, final String header, final String value) {
        Series<Header> responseHeaders = (Series<Header>)
                response.getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS);
        if (responseHeaders == null) {
            responseHeaders = new Series(Header.class);
            response.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS,
                    responseHeaders);
        }
        responseHeaders.add(new Header(header, value));
    }
}


text:
Move-Item `
    -Path        (join-path $_.Package.Directory.FullName "project.csproj") `
    -Destination (join-path $_.Package.Directory.FullName "$($_.Metadata.getProperty("name")).csproj")

$projectProperties = New-PropertyContainer (Join-Path $_.Package.Directory.FullName "package.json")
$projectProperties.setProperty("pacman", @{
    "build" = @{
        "projects" = "*.csproj"
        "target" = "Restore,Pack"
        "parameters" = @{
            "configuration" = "Release"
            "platform" = "Any CPU"
        }
    }
})


text:
@implementation MailAccountInfo

-(NSArray<Ignore,MailFolderInfo> *)folders{
    if (_folders) return _folders;

    NSError *error;
    if (_serverType == TBMailServerTypePOP){
        _folders = (NSMutableArray<Ignore,MailFolderInfo>*)[MailFolderInfo arrayOfModelsFromJsonString:@"[{\"title\": \"Inbox\",\"path\": \"INBOX\",\"flags\": 16},{\"title\": \"Sent\",\"path\": \"Sent Messages\",\"flags\": 32},{\"title\": \"Deleted\",\"path\": \"Deleted Messages\",\"flags\": 256}]" withKeyMapper:NO error:&error];

        for (MailFolderInfo *folder in _folders) {
            folder.ownerAccount = self;
        }
    }else if (_serverType == TBMailServerTypeiTurbo){
        _folders = (NSMutableArray<Ignore,MailFolderInfo>*)[MailFolderInfo arrayOfModelsFromJsonString:@"[{\"title\": \"Inbox\",\"path\": \"INBOX\",\"flags\": 16},{\"title\": \"Sent\",\"path\": \"Sent Messages\",\"flags\": 32},{\"title\": \"Archive\",\"path\": \"Archive\",\"flags\": 4096}]" withKeyMapper:NO error:&error];

        for (MailFolderInfo *folder in _folders) {
            folder.ownerAccount = self;
        }
    }else{
        _folders = (NSMutableArray<Ignore,MailFolderInfo>*)[NSMutableArray arrayWithArray:(NSArray*)[[ApplicationDirector sharedInstance].mailCacheFolders objectForKey:self.identifier]];

        if (!_folders.count) {
            [_folders addObjectsFromArray:[MailFolderInfo arrayOfModelsFromJsonString:@"[{\"title\": \"Inbox\",\"path\": \"INBOX\",\"flags\": 16},{\"title\": \"Sent\",\"path\": \"Sent Messages\",\"flags\": 32}]" withKeyMapper:NO error:&error]];
        }

        for (MailFolderInfo *folder in _folders) {
            folder.ownerAccount = self;
        }
    }

    if (error) NSLog(@"%@",error);

    return _folders;
}

-(MailFolderInfo *)trashFolder{
    if (_trashFolder) {
        return _trashFolder;
    }

    for (MailFolderInfo *folder in _folders) {
        if ([folder isTrash]) {
            _trashFolder = folder;
            break;
        }
    }

    if (!_trashFolder) {
        for (MailFolderInfo *folder in _folders) {
            if ([folder isArchive]) {
                _trashFolder = folder;
                break;
            }
        }
    }
    return _trashFolder;
}

-(NSString<Optional> *)smtpHostname{
    if (_smtpHostname.length)
        return _smtpHostname;

    if ([_hostname hasPrefix:@"mail"]) {
        _smtpHostname = _hostname;
    }else if ([_hostname hasPrefix:@"imap"]){
        _smtpHostname = [_hostname stringByReplacingOccurrencesOfString:@"imap" withString:@"smtp"];
    }else if ([_hostname hasPrefix:@"pop"]){
        _smtpHostname = [_hostname stringByReplacingOccurrencesOfString:@"pop" withString:@"smtp"];
    }else
    {
        _smtpHostname = nil;
    }
    return _smtpHostname;
}

-(NSString<Index,Optional> *)identifier{
    return [NSString stringWithFormat:@"@%@@%ld@%ld",_address,_port,_serverType];
}

-(BOOL) complete{
    if (_serverType == TBMailServerTypeIMAP || _serverType == TBMailServerTypePOP) {
        if (_hostname.length==0 || _port == 0 || _address.length==0 || _password.length==0) {
            return NO;
        }
    }else{
        if (_address.length==0) {
            return NO;
        }
    }

    return YES;
}

-(MCOSMTPSession<Ignore> *)smtpSession{
    if (_smtpSession)
        return _smtpSession;

    if (_serverType == TBMailServerTypeIMAP || _serverType == TBMailServerTypePOP) {
        MCOSMTPSession *session = [[MCOSMTPSession alloc] init];
        [session setHostname:self.smtpHostname];
        [session setUsername:_address];
        [session setPassword:_password];
        [session setConnectionType:_connectionType];
        if (_smtpPort == 0) {
            if (session.connectionType == MCOConnectionTypeStartTLS) {
                [session setPort:587];
            }else if (session.connectionType == MCOConnectionTypeTLS) {
                [session setPort:465];
            }else{
                [session setPort:25];
            }
        }else{
            [session setPort:(int)_smtpPort];
        }
        [session setAuthType:MCOAuthTypeSASLNone];
        [session setTimeout:30];
        [session setUseHeloIPEnabled:YES];
        [session setConnectionLogger:^(void * connectionID, MCOConnectionLogType type, NSData * data) {
            if (data) {
                NSLog(@"SMTP: %ld %@",type, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
            }

            if ((type == MCOConnectionLogTypeErrorParse) || (type == MCOConnectionLogTypeErrorReceived) || (type == MCOConnectionLogTypeErrorSent)) {
                NSLog(@"SMTP ERROR: %ld %@",type, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
            }
        }];
        _smtpSession = session;
    }else{
        _smtpSession = nil;
    }

    return _smtpSession;
}

-(NSObject<Ignore>*)session{

    if (_session)
        return _session;

    if (_serverType == TBMailServerTypeIMAP) {
        MCOIMAPSession *session = [[MCOIMAPSession alloc] init];
        [session setHostname:_hostname];
        [session setPort:(int)_port];
        [session setUsername:_username?:_address];
        [session setPassword:_password];
        [session setConnectionType:_connectionType];
        [session setAuthType:MCOAuthTypeSASLNone];
        [session setTimeout:30];
        [session setConnectionLogger:^(void * connectionID, MCOConnectionLogType type, NSData * data) {
//            if (data) {
//                NSLog(@"IMAP: %ld %@",type, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
//            }

            if ((type == MCOConnectionLogTypeErrorParse) || (type == MCOConnectionLogTypeErrorReceived) || (type == MCOConnectionLogTypeErrorSent)) {
                NSLog(@"IMAP ERROR: %ld %@",type, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
            }
        }];
        _session = session;
    }else if (_serverType == TBMailServerTypePOP){
        __block MCOPOPSession *session = [[MCOPOPSession alloc] init];
        [session setHostname:_hostname];
        [session setPort:(int)_port];
        [session setUsername:_username?:_address];
        [session setPassword:_password];
        [session setConnectionType:_connectionType];
        [session setAuthType:MCOAuthTypeSASLNone];
        [session setTimeout:30];
        [session setCheckCertificateEnabled:YES];
        [session setConnectionLogger:^(void * connectionID, MCOConnectionLogType type, NSData * data) {
            if (data) {
                NSLog(@"POP3: %ld %@",type, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
            }

            if ((type == MCOConnectionLogTypeErrorParse) || (type == MCOConnectionLogTypeErrorReceived) || (type == MCOConnectionLogTypeErrorSent)) {
                NSLog(@"POP3 ERROR: %ld %@",type, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
            }
        }];
        _session = session;
    }else{
        _session = @"iTurbo";
    }

    return _session;
}

-(void)setUsername:(NSString<Optional> *)username{
    _username = username;
    if (_session) {
        [(MCOPOPSession *)_session setUsername:_username];
    }
}

-(NSString *)summaryTitle{
    return _title?_title:(NSString<Optional> *)_address;
}

-(NSString *)summaryDetailTitle{
    if (_serverType == TBMailServerTypeiTurbo) {
        return nil;
    }
    return _address;
}
@end

@implementation MailFolderInfo

-(NSString<Index,Optional> *)identifier{
    return [NSString stringWithFormat:@"%@@%@",_path,_ownerAccount.identifier];
}

-(BOOL)invalid{
    if ([_path hasPrefix:@"Public"]) {
        return YES;
    }else if ([_path isEqualToString:@"Notes"]) {
        return YES;
    }
    return NO;
}

-(BOOL)isTrash{
    if (_flags&MCOIMAPFolderFlagTrash || [self.title hasPrefix:@"Deleted"]) {
        return YES;
    }
    return NO;
}

-(BOOL)isArchive{
    if (_flags&MCOIMAPFolderFlagArchive || [self.title hasPrefix:@"Archive"]) {
        return YES;
    }
    return NO;
}

-(NSMutableArray<Optional> *)messages{
    if (_messages) return _messages;

    NSArray *cached = (NSArray*)[[ApplicationDirector sharedInstance].mailCacheMessages objectForKey:self.identifier];
    _messages = [NSMutableArray arrayWithArray:cached];

    // 初始化originalFlags,該參數未序列化
    if (_ownerAccount.serverType == TBMailServerTypeIMAP) {
        for (MCOIMAPMessage *msg in _messages) {
            if (!msg.originalFlags)
                msg.originalFlags = msg.flags;
        }
    }

    NSLog(@"Load %ld for %@",_messages.count,self.identifier);
    return _messages;
}

-(void)saveMessages{
    if (_messages) {
        [[ApplicationDirector sharedInstance].mailCacheMessages setObject:_messages forKey:self.identifier block:^(TMDiskCache *cache, NSString *key, id<NSCoding> object, NSURL *fileURL) {
            NSLog(@"%ld messages cached to %@",[(NSArray*)object count],fileURL);
        }];
    }
}

-(void)setPath:(NSString<Index> *)path{
    _path = path;
    [self setTitle:(NSString<Optional> *)_path];
}

-(void)setTitle:(NSString<Optional> *)title{
    // UTF7_IMAP decode
    unsigned long encode = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF7_IMAP);
    NSData *responseData =[title dataUsingEncoding:NSUTF8StringEncoding];
    _title = [[NSString alloc] initWithData:responseData encoding:encode];
}

-(NSInteger)order{
    if (_order > 0) return _order;

    if (_flags & MCOIMAPFolderFlagInbox || [self.title isEqualToString:@"INBOX"]) {
        _order = 1;
    }else if (_flags & MCOIMAPFolderFlagSentMail || [self.title isEqualToString:@"Sent Messages"]) {
        _order = 5;
    }else if (_flags & MCOIMAPFolderFlagStarred) {
        _order = 15;
    }else if (_flags & MCOIMAPFolderFlagTrash || [self.title isEqualToString:@"Deleted Messages"]) {
        _order = 20;
    }else if (_flags & MCOIMAPFolderFlagDrafts || [self.title isEqualToString:@"Drafts"]) {
        _order = 10;
    }else if (_flags & MCOIMAPFolderFlagSpam || [self.title isEqualToString:@"Junk"]) {
        _order = 30;
    }else if (_flags & MCOIMAPFolderFlagImportant) {
        _order = 3;
    }else if (_flags & MCOIMAPFolderFlagArchive || [self.title isEqualToString:@"Archive"]) {
        _order = 35;
    }else if ([self.title isEqualToString:@"Deleted Items"]) {
        _order = 21;
    }else if ([self.title isEqualToString:@"Sent Items"]) {
        _order = 6;
    }else{
        _order = 100;
    }

    return _order;
}

-(void)setFlags:(MCOIMAPFolderFlag)flags{
    if ([_title isEqualToString:@"INBOX"]) {
        _flags = flags|MCOIMAPFolderFlagInbox;
    }else if ([_title isEqualToString:@"Sent Messages"]) {
        _flags = flags|MCOIMAPFolderFlagSentMail;
    }else if ([_title isEqualToString:@"Deleted Messages"]) {
        _flags = flags|MCOIMAPFolderFlagTrash;
    }else if ([_title isEqualToString:@"Drafts"]) {
        _flags = flags|MCOIMAPFolderFlagDrafts;
    }else if ([_title isEqualToString:@"Junk"]) {
        _flags = flags|MCOIMAPFolderFlagSpam;
    }else if ([_title isEqualToString:@"Archive"]) {
        _flags = flags|MCOIMAPFolderFlagArchive;
    }else if ([_title isEqualToString:@"Deleted Items"]) {
        _flags = flags|MCOIMAPFolderFlagTrash;
    }else if ([_title isEqualToString:@"Sent Items"]) {
        _flags = flags|MCOIMAPFolderFlagSentMail;
    }else{
        _flags = flags;
    }
}

-(NSString *)summaryTitle{
    if (_flags & MCOIMAPFolderFlagInbox || [_title isEqualToString:@"INBOX"]) {
        return NSLocalizedString(@"收件箱", nil);
    }else if (_flags & MCOIMAPFolderFlagSentMail || [_title isEqualToString:@"Sent Messages"]) {
        return NSLocalizedString(@"已發郵件", nil);
    }else if (_flags & MCOIMAPFolderFlagStarred) {
        return NSLocalizedString(@"已加星标", nil);
    }else if (_flags & MCOIMAPFolderFlagTrash || [_title isEqualToString:@"Deleted Messages"]) {
        return NSLocalizedString(@"已刪除郵件", nil);
    }else if (_flags & MCOIMAPFolderFlagDrafts || [_title isEqualToString:@"Drafts"]) {
        return NSLocalizedString(@"草稿", nil);
    }else if (_flags & MCOIMAPFolderFlagSpam || [_title isEqualToString:@"Junk"]) {
        return NSLocalizedString(@"垃圾郵件", nil);
    }else if (_flags & MCOIMAPFolderFlagImportant) {
        return NSLocalizedString(@"重要郵件", nil);
    }else if (_flags & MCOIMAPFolderFlagArchive || [_title isEqualToString:@"Archive"]) {
        return NSLocalizedString(@"存檔", nil);
    }else if ([_title isEqualToString:@"Notes"]) {
        return NSLocalizedString(@"便簽夾", nil);
    }else if ([_title isEqualToString:@"Deleted Items"]) {
        return NSLocalizedString(@"已刪除項", nil);
    }else if ([_title isEqualToString:@"Sent Items"]) {
        return NSLocalizedString(@"已發送項", nil);
    }

    return _title;
}

-(NSString *)summaryDetailTitle{
    if (_status) {
        return _status.messageCount?[NSString stringWithFormat:@"%d/%d",_status.unseenCount,_status.messageCount]:@"0";
    }else if (_info){
        return [NSString stringWithFormat:@"%d",_info.messageCount];
    }else{
        return nil;
    }
}

-(NSInteger)summaryBadage{
    return _status.unseenCount;
}

-(void)summaryImageToCellImageView:(UIImageView *)imageView completed:(SDWebImageCompletionBlock)completed{

    if (_flags & MCOIMAPFolderFlagInbox){
        imageView.image = [UIImage imageNamed:@"Folder"];
    }else if (_flags & MCOIMAPFolderFlagNoSelect){
        imageView.image = [UIImage imageNamed:@"Folders"];
    }else if (_flags & MCOIMAPFolderFlagSentMail){
        imageView.image = [UIImage imageNamed:@"Folder"];
    }else if (_flags & MCOIMAPFolderFlagStarred){
        imageView.image = [UIImage imageNamed:@"Folder"];
    }else if (_flags & MCOIMAPFolderFlagAllMail){
        imageView.image = [UIImage imageNamed:@"Folder"];
    }else if (_flags & MCOIMAPFolderFlagTrash){
        imageView.image = [UIImage imageNamed:@"Folder"];
    }else if (_flags & MCOIMAPFolderFlagDrafts){
        imageView.image = [UIImage imageNamed:@"Folder"];
    }else if (_flags & MCOIMAPFolderFlagSpam){
        imageView.image = [UIImage imageNamed:@"Folder"];
    }else if (_flags & MCOIMAPFolderFlagImportant){
        imageView.image = [UIImage imageNamed:@"Folder"];
    }else if (_flags & MCOIMAPFolderFlagArchive){
        imageView.image = [UIImage imageNamed:@"Folder"];
    }else{
        imageView.image = [UIImage imageNamed:@"Folder"];
    }
}
@end

@implementation SmartFolder
-(instancetype)init{
    self = [super init];
    if (self) {
        messageCollection = [NSMutableArray array];
    }
    return self;
}

- (instancetype) initWithFolder:(MailFolderInfo*)folder{
    self = [self init];
    if (self) {
        self.title = folder.title;
        self.folders = (NSArray<Optional,MailFolderInfo>*)[NSArray arrayWithObject:folder];
    }

    return self;
}

- (void)didReceiveMemoryWarning {
    // Dispose of any resources that can be recreated.
}

- (void)saveMessages{
    for (MailFolderInfo *folder in _folders) {
        [folder saveMessages];
    }
}

-(void)setFolders:(NSArray<Optional,MailFolderInfo> *)folders{
    _folders = folders;
    for (MailFolderInfo *folder in _folders) {
        // Insert cached messages
        for (MCOAbstractMessage *msg in folder.messages) {
            [self insertMessage:msg inArray:messageCollection];
        }
    }
}

-(NSIndexSet*)insertMessages:(NSArray *)messages inFolder:(MailFolderInfo*)folder{
    NSMutableIndexSet *indexes = [NSMutableIndexSet indexSet];
    NSArray *sorted = [messages sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"header.date" ascending:NO]]];

    for (MCOAbstractMessage *insertMsg in sorted) {
        NSUInteger atIndex = [self insertMessage:insertMsg inFolder:folder];
        if (atIndex != NSNotFound) {
            [indexes addIndex:atIndex];
        }
    }

    if (indexes.count) {

        if (![folder isTrash]) {
            AudioServicesPlaySystemSound(1000);
        }

        return [indexes copy];
    }
    return nil;
}

-(NSUInteger)insertMessage:(MCOAbstractMessage *)message inFolder:(MailFolderInfo*)folder{
    // 先插入 Folder
    NSUInteger index = [self insertMessage:message inArray:folder.messages];

    if (index == NSNotFound) {
        return index;
    }

    // 再插入集合,並且返回集合的index
    return [self insertMessage:message inArray:messageCollection];
}

-(NSUInteger)insertMessage:(MCOAbstractMessage *)message inArray:(NSMutableArray*)array{

    // 不重複插入Message
    if ([array containsObject:message]) {
        return NSNotFound;
    }

    __block NSUInteger index = array.count;
    [array enumerateObjectsUsingBlock:^(MCOAbstractMessage *cmsg, NSUInteger idx, BOOL *stop) {
        if ([message.header.date compare:cmsg.header.date] == NSOrderedDescending){
            index = idx;
            *stop = YES;
        }
    }];
    [array insertObject:message atIndex:index];

    return index;
}

-(NSIndexSet*)updateMessages:(NSArray *)messages{
    return [self updateMessages:messages isDelete:NO];
}

-(NSIndexSet*)updateMessages:(NSArray *)messages isDelete:(BOOL)deleted{
    for (MailFolderInfo *folder in _folders) {

        NSMutableArray *processMessages = [NSMutableArray array];
        for (MCOAbstractMessage *message in messages) {

            NSUInteger idx = [folder.messages indexOfObject:message];
            if (idx != NSNotFound) {
                if (deleted && [folder isTrash]) {
                    [folder.messages[idx] updateFlags:MCOMessageFlagDeleted];
                    if (folder.ownerAccount.serverType == TBMailServerTypeIMAP)
                        [processMessages addObject:folder.messages[idx]];
                    [folder.messages removeObjectAtIndex:idx];
                    if (folder.status) folder.status.messageCount --;
                }else if (deleted) {
                    // move to trash
                    [folder.messages[idx] updateFlags:MCOMessageFlagDeleted];

                    MailFolderInfo *trashFolder = folder.ownerAccount.trashFolder;
                    [trashFolder.messages addObject:folder.messages[idx]];
                    if (trashFolder.status) trashFolder.status.messageCount ++;

                    [processMessages addObject:folder.messages[idx]];
                    [folder.messages removeObjectAtIndex:idx];
                    if (folder.status) folder.status.messageCount --;
                }else{
                    [folder.messages[idx] updateFlags:[message TBFlags]];
                    if (folder.status) folder.status.unseenCount --;

                    if (folder.ownerAccount.serverType!=TBMailServerTypePOP){
                        // POP不需要更新服務器處理
                        [processMessages addObject:folder.messages[idx]];
                    }
                }
            }
        }

        if (processMessages.count) {
            // change flags to server
            if (folder.ownerAccount.serverType == TBMailServerTypeIMAP){
                __block BOOL containsDelete = NO;
                [processMessages enumerateObjectsUsingBlock:^(MCOIMAPMessage *msg, NSUInteger pidx, BOOL *stop) {
                    if (msg.originalFlags != msg.flags) {
                        if (deleted && ![folder isTrash]){
                            // move to trash
                            MailFolderInfo *trashFolder = folder.ownerAccount.trashFolder;
                            MCOIMAPCopyMessagesOperation *cop = [(MCOIMAPSession *)folder.ownerAccount.session copyMessagesOperationWithFolder:folder.path uids:[MCOIndexSet indexSetWithIndex:msg.uid] destFolder:trashFolder.path];
                            [cop start:^(NSError *error, NSDictionary *uidMapping) {
                                if(!error) {
                                    [uidMapping enumerateKeysAndObjectsUsingBlock:^(NSNumber *key, NSNumber *obj, BOOL *stop) {
                                        for (MCOIMAPMessage *trashmsg in trashFolder.messages) {
                                            if (trashmsg.uid == [key unsignedIntValue]) {
                                                trashmsg.uid = [obj unsignedIntValue];
                                                break;
                                            }
                                        }
                                    }];
                                    NSLog(@"Copy message:%@", uidMapping);
                                }else{
                                    NSLog(@"Error copy message:%@", error);
                                }
                            }];
                        }

                        NSLog(@"storeFlags %d:%ld,%ld",msg.uid,msg.originalFlags,msg.flags);

                        MCOIMAPOperation *op = [(MCOIMAPSession *)folder.ownerAccount.session storeFlagsOperationWithFolder:folder.path uids:[MCOIndexSet indexSetWithIndex:msg.uid] kind:MCOIMAPStoreFlagsRequestKindSet flags:msg.flags];

                        containsDelete = msg.flags&MCOMessageFlagDeleted;

                        [op start:^(NSError * error) {
                            if(error) {
                                NSLog(@"Error updating flags:%@", error);
                            }else{
                                msg.originalFlags = msg.flags;
                            }
                            if (pidx == processMessages.count - 1) {
                                if(containsDelete)
                                {
                                    //Must also expunge for the archive to happen
                                    MCOIMAPOperation *exOp = [(MCOIMAPSession *)folder.ownerAccount.session expungeOperation:folder.path];
                                    [exOp start:^(NSError *error) {
                                        if(error) {
                                            //TODO: should undo if it fails.
                                            NSLog(@"Error expungeOperation:%@", error);
                                        }
                                        [folder saveMessages];
                                    }];
                                }else{
                                    [folder saveMessages];
                                }
                            }
                        }];
                    }
                }];

            }else if (folder.ownerAccount.serverType == TBMailServerTypePOP){
                MCOPOPMessage *msg = [messages firstObject];
                if (msg.flags&MCOMessageFlagDeleted){
                    MCOIndexSet *messageIds = [MCOIndexSet indexSet];
                    for (MCOPOPMessage *message in processMessages) {
                        [messageIds addIndex:message.index];
                    }

                    MCOPOPOperation *op = [(MCOPOPSession *)folder.ownerAccount.session deleteMessagesOperationWithIndexes:messageIds];
                    [op start:^(NSError *error) {
                        if(error)
                            NSLog(@"%@", error);
                        else
                            [folder saveMessages];
                    }];
                }
            }
        }

    }

    // 處理messageCollection
    NSMutableIndexSet *indexes = [NSMutableIndexSet indexSet];
    for (MCOAbstractMessage *message in messages) {
        NSUInteger idx = [messageCollection indexOfObject:message];
        if (idx != NSNotFound) {
            [indexes addIndex:idx];
        }
    }

    if (deleted){
        [messageCollection removeObjectsAtIndexes:indexes];
    }
    return [indexes copy];
}

-(NSIndexSet*)removeMessages:(NSArray *)messages{
    return [self updateMessages:messages isDelete:YES];
}

- (MailFolderInfo*)ownerFolder:(MCOAbstractMessage*)message{

    for (MailFolderInfo *folder in self.folders) {
        for (MCOAbstractMessage *msg in folder.messages) {
            if ([message isEqual:msg]) {
                return folder;
            }
        }
    }
    return nil;
}
- (NSUInteger)indexOfMessage:(MCOAbstractMessage*) message{
    return [messageCollection indexOfObject:message];
}

- (MCOAbstractMessage*) messageAtIndex:(NSUInteger)index{
    return messageCollection[index];
}
- (NSUInteger) countOfMessages{
    return messageCollection.count;
}

-(NSString *)summaryTitle{
    return _title;
}

-(NSString *)summaryDetailTitle{
    if (_folders.count <= 1) {
        return nil;
    }else{
        MailFolderInfo *info = [_folders firstObject];
        if (info.ownerAccount.serverType == TBMailServerTypeiTurbo) {
            return [NSString stringWithFormat:NSLocalizedString(@"%@及%ld帳戶", nil),[info.ownerAccount summaryTitle],_folders.count-1];
        }else{
            return [NSString stringWithFormat:NSLocalizedString(@"%ld帳戶", nil),_folders.count];
        }
    }
}

-(NSInteger)summaryBadage{
    NSUInteger count = 0;
    for (MailFolderInfo *folder in _folders) {
        count += folder.messages.count;
    }
    return count;
}
@end

@implementation AttachmentsFolder
+ (AttachmentsFolder*)sharedInstance{
    static AttachmentsFolder *sharedInstance;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[AttachmentsFolder alloc] init];
    });

    return sharedInstance;
}

- (void)refresh{
    _attachmentCollection = nil;
}

-(NSString *)summaryTitle{
    return NSLocalizedString(@"已下載附件", nil);
}

-(NSString *)summaryDetailTitle{
    return [NSString stringWithFormat:@"%ld",(long)self.attachmentCollection.count];
}

-(void)summaryImageToCellImageView:(UIImageView *)imageView completed:(SDWebImageCompletionBlock)completed{
    [imageView setImage:[UIImage imageNamed:@"Attachment"]];

    if (completed) {
        completed(imageView.image,nil,SDImageCacheTypeDisk,nil);
    }
}

-(void)removeAttachmentCollectionAtIndexes:(NSIndexSet *)indexes{

    NSArray *removed = [_attachmentCollection objectsAtIndexes:indexes];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    for (NSURL *url in removed) {
        [fileManager removeItemAtURL:url error:nil];
    }
    _attachmentCollection = nil;
}

-(NSArray<Optional> *)attachmentCollection{
    if (_attachmentCollection) {
        return _attachmentCollection;
    }

    NSString *attachmentDir = [[[ApplicationDirector sharedInstance] documentDirectory] stringByAppendingPathComponent:@"MailAttachments"];
    _attachmentCollection = [ApplicationDirector folderFilesAtPath:attachmentDir withDir:NO];
    return _attachmentCollection;
}
@end


text:
"""Test the module Tomek's links."""
from __future__ import print_function

import os

import numpy as np
from numpy.testing import assert_raises
from numpy.testing import assert_equal
from numpy.testing import assert_array_equal
from numpy.testing import assert_warns

from sklearn.datasets import make_classification
from sklearn.utils.estimator_checks import check_estimator

from imblearn.under_sampling import TomekLinks

# Generate a global dataset to use
RND_SEED = 0
X, Y = make_classification(n_classes=2, class_sep=2, weights=[0.1, 0.9],
                           n_informative=3, n_redundant=1, flip_y=0,
                           n_features=20, n_clusters_per_class=1,
                           n_samples=5000, random_state=RND_SEED)

def test_tl_sk_estimator():
    """Test the sklearn estimator compatibility"""
    check_estimator(TomekLinks)

def test_tl_init():
    """Test the initialisation of the object"""

    # Define a ratio
    tl = TomekLinks(random_state=RND_SEED)

    assert_equal(tl.n_jobs, -1)
    assert_equal(tl.random_state, RND_SEED)

def test_tl_fit_single_class():
    """Test either if an error when there is a single class"""

    # Create the object
    tl = TomekLinks(random_state=RND_SEED)
    # Resample the data
    # Create a wrong y
    y_single_class = np.zeros((X.shape[0], ))
    assert_warns(RuntimeWarning, tl.fit, X, y_single_class)

def test_tl_fit():
    """Test the fitting method"""

    # Create the object
    tl = TomekLinks(random_state=RND_SEED)
    # Fit the data
    tl.fit(X, Y)

    # Check if the data information have been computed
    assert_equal(tl.min_c_, 0)
    assert_equal(tl.maj_c_, 1)
    assert_equal(tl.stats_c_[0], 500)
    assert_equal(tl.stats_c_[1], 4500)

def test_tl_sample_wt_fit():
    """Test either if an error is raised when sample is called before
    fitting"""

    # Create the object
    tl = TomekLinks(random_state=RND_SEED)
    assert_raises(RuntimeError, tl.sample, X, Y)

def test_tl_fit_sample():
    """Test the fit sample routine"""

    # Resample the data
    tl = TomekLinks(random_state=RND_SEED)
    X_resampled, y_resampled = tl.fit_sample(X, Y)

    currdir = os.path.dirname(os.path.abspath(__file__))
    X_gt = np.load(os.path.join(currdir, 'data', 'tl_x.npy'))
    y_gt = np.load(os.path.join(currdir, 'data', 'tl_y.npy'))
    assert_array_equal(X_resampled, X_gt)
    assert_array_equal(y_resampled, y_gt)

def test_tl_fit_sample_with_indices():
    """Test the fit sample routine with indices support"""

    # Resample the data
    tl = TomekLinks(return_indices=True, random_state=RND_SEED)
    X_resampled, y_resampled, idx_under = tl.fit_sample(X, Y)

    currdir = os.path.dirname(os.path.abspath(__file__))
    X_gt = np.load(os.path.join(currdir, 'data', 'tl_x.npy'))
    y_gt = np.load(os.path.join(currdir, 'data', 'tl_y.npy'))
    idx_gt = np.load(os.path.join(currdir, 'data', 'tl_idx.npy'))
    assert_array_equal(X_resampled, X_gt)
    assert_array_equal(y_resampled, y_gt)
    assert_array_equal(idx_under, idx_gt)

def test_tl_sample_wrong_X():
    """Test either if an error is raised when X is different at fitting
    and sampling"""

    # Create the object
    tl = TomekLinks(random_state=RND_SEED)
    tl.fit(X, Y)
    assert_raises(RuntimeError, tl.sample, np.random.random((100, 40)),
                  np.array([0] * 50 + [1] * 50))


text:
'use strict';

var PathfinderManager = angular.module('PathfinderManager');
PathfinderManager.controller("AddGroupStatus",function($scope, $uibModalInstance, items){
    $scope.items = items;

    $scope.ok = function () {
        $uibModalInstance.close();
    };

    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };

    $scope.addGroupStatus = function(newGroupStatusName, newGroupStatusDuration){
        if(newGroupStatusName!=""){
            var statusName = newGroupStatusName.charAt(0).toUpperCase() + newGroupStatusName.slice(1);
            var statusDuration = parseInt(newGroupStatusDuration, 10)
            var status = {name: statusName, duration: statusDuration};
            angular.forEach($scope.charactersToAddStatuses, function(character){
                character.statuses.push(status);
            });
        };
        $scope.charactersToAddStatuses = [];
        $uibModalInstance.close();
    };

});


text:
describe("coreHelpers", () => {

  it("should escape MBean names", () => {
    // given
    let mbeans = ['aaa/bbb/ccc', 'aaa!bbb!ccc', 'aaa"bbb"ccc', 'a/b!c"d'];
    let escaped = ['aaa!/bbb!/ccc', 'aaa!!bbb!!ccc', 'aaa!%22bbb!%22ccc', 'a!/b!!c!%22d'];
    // when
    let results = mbeans.map(mbean => Core.escapeMBean(mbean));
    // then
    _.zip(results, escaped).forEach(
      ([result, expected]) => expect(result).toBe(expected));
  });

  it("should escape MBean paths", () => {
    // given
    let mbeans = ['java.lang:type=Memory'];
    let escaped = ['java.lang/type=Memory'];
    // when
    let results = mbeans.map(mbean => Core.escapeMBeanPath(mbean));
    // then
    _.zip(results, escaped).forEach(
      ([result, expected]) => expect(result).toBe(expected));
  });

});


text:
package org.optaplanner.quarkus.drl.it;

import java.util.Arrays;
import java.util.concurrent.ExecutionException;

import javax.inject.Inject;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.optaplanner.core.api.solver.SolverJob;
import org.optaplanner.core.api.solver.SolverManager;
import org.optaplanner.quarkus.drl.it.domain.TestdataQuarkusEntity;
import org.optaplanner.quarkus.drl.it.domain.TestdataQuarkusSolution;

@Path("/optaplanner/test")
public class OptaPlannerTestResource {

    @Inject
    SolverManager<TestdataQuarkusSolution, Long> solverManager;

    @POST
    @Path("/solver-factory")
    @Produces(MediaType.TEXT_PLAIN)
    public String solveWithSolverFactory() throws InterruptedException {
        TestdataQuarkusSolution planningProblem = new TestdataQuarkusSolution();
        planningProblem.setEntityList(Arrays.asList(
                new TestdataQuarkusEntity(),
                new TestdataQuarkusEntity()));
        planningProblem.setLeftValueList(Arrays.asList("a", "b", "c"));
        planningProblem.setRightValueList(Arrays.asList("1", "2", "3"));
        SolverJob<TestdataQuarkusSolution, Long> solverJob = solverManager.solve(1L, planningProblem);
        try {
            TestdataQuarkusSolution sol = solverJob.getFinalBestSolution();
            StringBuilder out = new StringBuilder();
            out.append("score=").append(sol.getScore()).append('\n');
            for (int i = 0; i < sol.getEntityList().size(); i++) {
                out.append("entity." + i + ".fullValue=").append(sol.getEntityList().get(i).getFullValue()).append('\n');
            }
            return out.toString();
        } catch (ExecutionException e) {
            throw new IllegalStateException("Solving failed.", e);
        }
    }

}


text:
package net.jxta.impl.util;

import junit.framework.*;

import java.io.*;
import java.net.*;
import java.util.*;

/**
 *
 * @author mike
 */
public class SeedingManagerTest extends TestCase {

    public SeedingManagerTest(java.lang.String testName) {
        super(testName);
    }

    public static void main(java.lang.String[] args) {
        junit.textui.TestRunner.run(suite());

        System.err.flush();
        System.out.flush();
    }

    public static Test suite() {
        TestSuite suite = new TestSuite(SeedingManagerTest.class);

        return suite;
    }

    public void testPermanentSeeds() {
        URI seeduris[] = {
            URI.create("tcp://1.2.3.4:1234"),
            URI.create("tcp://4.3.2.1:4321"),
            URI.create("http://1.2.3.4:1234"),
            URI.create("http://4.3.2.1:1234")
        };

        URISeedingManager seeder = new URISeedingManager(null, true, null, null );

        seeder.addSeed(seeduris[0]);

        URI seeds[] = seeder.getActiveSeedURIs();

        assertTrue("Incorrect number of seeds returned.", seeds.length == 1);
        assertTrue("Seed not as expected.", seeds[0].equals(seeduris[0]));

        for (URI aSeed : Arrays.asList(seeduris)) {
            seeder.addSeed(aSeed);
        }

        seeds = seeder.getActiveSeedURIs();

        assertTrue("Incorrect number of seeds returned.", seeds.length == seeduris.length);
        for (URI aSeed : Arrays.asList(seeduris)) {
            if (!Arrays.asList(seeduris).contains(aSeed)) {
                fail("Missing permanent seed");
            }
        }
    }

    public void testSeeding() {
        URI seedinguris[] = {
            URI.create("file:///home/mike/rendezvous.xml"),
            URI.create("ftp://ftp.duigou.org/jxta/rendezvous.txt")
        };

        URISeedingManager seeder = new URISeedingManager(null, true, null, null);

        seeder.addSeedingURI(seedinguris[0]);

        URI seeds[] = seeder.getActiveSeedURIs();

        seeder.addSeedingURI(seedinguris[1]);

        seeds = seeder.getActiveSeedURIs();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<com.mogoo.market.viewpager.extensions.ViewPagerTabButton
	xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:viewpagerextensions="http://schemas.android.com/apk/res/com.mogoo.market"
    android:layout_width="0dip"
    android:layout_height="0dip"
    android:layout_weight="1"
    android:background="@drawable/tab_holo"
    android:gravity="center"
    style="@style/tab_button_text"/>


text:
The purpose of this repository is to provide some data structures and algorithms in various languages.
All the code in this repository is commented and thoroughly tested.
If you find any mistake, please let me know.

You can reuse it without constraint, but do not forget to credit me as the author.
You can also find some of the Java classes in the algs4 library maintained by Robert Sedgewick and Kevin Wayne, both teachers and researchers at Princeton University, available [here](http://algs4.cs.princeton.edu/code/)

There will be no regular update of this repository, I may not write anything for months or I may as well push hundreds of lines during a week.

I sincerely hope this will be helpful.

If you have any particular wish or suggestion, feel free to contact me.

Tristan 'ElyKar' Claverie


text:
class ProjectCollaborator < ActiveRecord::Base
  PROJECT_ROLES = ['owner', 'participant', 'observer', 'design consultant']

  belongs_to :project
  belongs_to :user

  validates_presence_of :user, :project_role
  validates_inclusion_of :project_role, :in => PROJECT_ROLES, :allow_blank => true

  delegate :name, :to => :user, :prefix => :user, :allow_nil => true

  PROJECT_ROLES.each do |role|
    scope role.pluralize.underscore.to_sym, where(:project_role => role)
  end

  def initialize(*params)
    super
    self.project_role ||= 'participant'
  end
end


text:
/**
 * Created by alex on 10.04.17.
 */

"use strict";
var _noble = require('noble');

var  buntfalke_address = "cc:20:e8:2a:5b:a0";

class BLEGateway {

    constructor(ble_lib){
        if(ble_lib){
            this.ble_lib= ble_lib;
        } else {
            this.ble_lib = _noble;// require('noble'); //Default;
        }
        //this.enableBLECommunication();
    }

    set device(ble_device){
        if(ble_device){
            this.ble_device = ble_device;
            this.enableBLECommunication();
        }
    }

    enableBLECommunication(){
        this.ble_lib.on('stateChange', (state) => {
            if (state === 'poweredOn') {
                // serviceUUIDs = ["180f"]; // default: [] => all
                var serviceUUIDs = []; // default: [] => all
                // // var serviceUUIDs = []; // default: [] => all
                this.ble_lib.startScanning(serviceUUIDs);
            } else {
                this.ble_lib.stopScanning(serviceUUIDs);
            }
        });

        this.ble_lib.on('discover', (peripheral) => {
            console.log('discovered -> ' + peripheral.address  + ' name:' + peripheral.advertisement.localName);
            console.log('this.ble_device.address -> ' + this.ble_device.address);
            if (peripheral.address.toUpperCase() === this.ble_device.address.toUpperCase()) {
                console.log('target device found, establish connection');
                this.ble_lib.stopScanning();
                peripheral.connect();

            }

            peripheral.on('connect', () => {
                console.log('on -> connect, to ' +peripheral.advertisement.localName);
                peripheral.discoverServices(['180f'], function(error, services) {
                    var deviceInformationService = services[0];
                    console.log('discovered device information service');

                    deviceInformationService.discoverCharacteristics(['2a19'], function(error, characteristics) {
                        var batteryLevelCharacteristic = characteristics[0];
                        console.log('discovered manufacturer '+characteristics);
                        console.log('discovered manufacturer name characteristic');
                        batteryLevelCharacteristic.read(function () {

                        });
                        batteryLevelCharacteristic.on('read', function(data, isNotification) {
                            console.log('battery level is now: ', data.readUInt8(0) + '%');
                            peripheral.disconnect();
                        });
                    });
                });

            });

            peripheral.on('disconnect', ()  => {
                console.log('on -> disconnect, bye bye');
                peripheral.disconnect();
                process.exit();
            });

        });

    }

    powerOn(){
     this.ble_lib.state = 'poweredOn';//Switching on the gateway.
    }

    powerOff(){
        this.ble_lib.state = 'poweredOff';//Switching on the gateway.
    }

}

module.exports = BLEGateway;


text:
layout:     post
title:      'Introduction to data.table'
subtitle:   "Applied R April Edition"
date:       2016-04-11 15:20:00
author:     "Philipp"
header-img: "img/home-bg.jpg"
---

Applied R April Edition:

## Introduction to data.table

Speaker:

Janek Thomas (PhD student, Institute for Statistics, LMU Munich)

Find all information under [<u>meetup</u>](http://www.meetup.com/Applied-R-Munich)!


text:
package org.jasig.portlet.emailpreview.caching;

/**
 *
 * @author James Wennmacher, jwennmacher@unicon.net
 */
public interface IMailAccountCacheKeyGenerator {

	/**
	 * Returns a cache key for the user and email system hostname for selected prefix
	 *
	 *
     *
     * @param loginId username
     * @param hostSystem mail system fully-qualified hostname
     * @param prefix prefix
     * @return cache key for the user
	 */
	String getKey(String loginId, String hostSystem, String prefix);

}