text:
import chai from "chai";
import sinon from "sinon";
chai.use(require("sinon-chai"));
const {expect} = chai;

import Container from "../../app/component/container";
import Injectable from "../../app/component/injectable";
import InvalidArgumentError from "../../app/util";

const INJECTABLE_NAME = "component";
const INEXISTENT_INJECTABLE_NAME = "garbage";
var containerInstance, injectableInstance;

beforeEach(() => {
    containerInstance = new Container();
    injectableInstance = new Injectable(INJECTABLE_NAME, () => {return true;});
})

describe("Container", () => {
    it("should construct without an error", () => {
        expect(containerInstance).to.be.an.instanceOf(Container);
    });

    it("should throw error when not an injectable is registered", () => {
        expect(() => containerInstance.registerInjectable({}))
            .to.throw(InvalidArgumentError);

        expect(() => containerInstance.registerInjectable(null))
            .to.throw(InvalidArgumentError);
    });

    describe("registerInjectable()", () => {
        it("should register valid injectables without error", () => {
            expect(() => containerInstance.registerInjectable(injectableInstance))
                .to.not.throw();

            expect(containerInstance.injectables.has(INJECTABLE_NAME)).to.equal(true);
            expect(containerInstance.injectables.get(INJECTABLE_NAME)).to.equal(injectableInstance);
        });
    });

    describe("create()", () => {
        it("should throw error when creating inexistent injectables", () => {
            expect(() => containerInstance.create(INEXISTENT_INJECTABLE_NAME))
                .to.throw(InvalidArgumentError);
        });

        it("should execute the loader function upon creating an injectable", () => {
            const SPY_INSTANCE_NAME = "bond";
            let spy = sinon.spy(exampleFactory);
            let spyInjectableInstance = new Injectable(SPY_INSTANCE_NAME, spy);

            var resultOfCreateCall;
            expect(() => containerInstance.registerInjectable(spyInjectableInstance)).to.not.throw();
            expect(() => resultOfCreateCall = containerInstance.create(SPY_INSTANCE_NAME)).to.not.throw();
            expect(resultOfCreateCall).to.deep.equal(factoryResult);
            expect(spy).to.have.callCount(1);
        });

        it("should create singletons only once and pass the instance", () => {
            const SPY_INSTANCE_NAME = "singleton";
            let spy = sinon.spy(exampleFactory);

            let injectables = [new Injectable(SPY_INSTANCE_NAME, spy, {singleton: true})];
            injectables.push(new Injectable("component", (singleton) => true));
            injectables.push(new Injectable("component2", (singleton) => true));
            injectables.forEach((injectable) => containerInstance.registerInjectable(injectable));

            expect(() => containerInstance.create("component")).to.not.throw();
            expect(() => containerInstance.create("component2")).to.not.throw();
            expect(spy).to.have.callCount(1);
        });
    });

    describe("getFilteredDependenciesOfInjectable()", () => {
        it("should filter out arguments nicely", () => {
            const FUNCTION_TO_BE_FILTERED = (sp, logger, dbConnector) => true;
            const FILTERED_ARGUMENTS = ["logger", "dbConnector"];
            const filterableInjectableInstance = new Injectable("a", FUNCTION_TO_BE_FILTERED);

            expect(() => containerInstance.getFilteredDependenciesOfInjectable(filterableInjectableInstance))
                .to.not.throw();

            expect(containerInstance.getFilteredDependenciesOfInjectable(filterableInjectableInstance))
                .to.be.deep.equal(FILTERED_ARGUMENTS);
        });
    });
});

const factoryResult = new Object();
function exampleFactory() {
    return factoryResult;
}


text:
layout: post
title: CentOS使用Eclipse开发Hadoop应用程序
category: Hadoop
tags: Hadoop
keywords:
description:
---

## 简介
在CentOS6.5上开发Hadoop应用程序,例子采用Hadoop提供的WordCount。

## 启动Hadoop
本机Hadoop目录:~/Hadoop/hadoop1.2.1

	$ cd ~/Hadoop/hadoop1.2.1
	$ ./bin/start-all.sh

如果NameNode没启动成功,则可能是因为${hadoop.tmp.dir}目录的内容被清除了。
hadoop.tmp.dir是hadoop文件系统依赖的基础配置,很多路径都依赖它。它默认的位置是在/tmp/{$user}下面,但是在/tmp路径下的存储是不安全的,因为linux一次重启,文件就可能被删除。

建议重新配置hadoop.tmp.dir,编辑${HADOOP_HOME}/conf/core-site.xml,目录的位置可自行定义。

	<property>
        <name>hadoop.tmp.dir</name>
        <value>/home/xandy/Hadoop/hadoop-1.2.1/tmp</value>
    </property>

则需重新格式化名字节点,然后启动:

	$ cd ~/Hadoop/hadoop1.2.1
	$./bin/hadoop namenode -format
	$ ./bin/start-all.sh

## 新建WordCount项目

Eclipse中选择`File -> New -> Other -> Map/Reduce Project`新建名为WordCount的Map/Reduce项目。

创建`net.cocloud.hadoop`包,将${HADOOP_HOME}/src/examples/org/apache/hadoop/examples/WordCount.java复制到`net.cocloud.hadoop`下面。

在Map/Reduce视图中的Map/Reduce Locations中New Hadoop Location。填写相应的参数:

* Location name:XandyHadoop
* Map/Reduce Master Host:localhost; Port:9001
* DFS Master Host:localhost; Port:9000
* User name:xandy

## 准备数据

	$ vi~/wordcount.txt

将Hadoop简介的一段文字填入其中。

	what Is Apache Hadoop?
	The Apache™ Hadoop® project develops open-source software for reliable, scalable, distributed computing.

	The Apache Hadoop software library is a framework that allows for the distributed processing of large data sets across clusters of computers using simple programming models. It is designed to scale up from single servers to thousands of machines, each offering local computation and storage. Rather than rely on hardware to deliver high-availability, the library itself is designed to detect and handle failures at the application layer, so delivering a highly-available service on top of a cluster of computers, each of which may be prone to failures.

将wordcount.txt复制到hdfs/input目录下面

	./bin/hadoop fs -mkdir input
	./bin/hadoop fs -put ~/wordcount.txt input

在DFS Locations下面可以看到/usr/xandy/input/wordcount.txt文件

## 运行程序

WordCount项目右键,`Run as -> Run Configurations`

	Main:
		Project: WordCount
		Main Class: net.cocloud.hadoop.WordCount
	Arguments:
		Program arguments: hdfs://localhost:9000/user/xandy/input/wordcount.txt hdfs://localhost:9000/user/xandy/output/

点击Run按钮,得到相应的输出:

	14/08/24 01:59:33 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
	14/08/24 01:59:33 WARN mapred.JobClient: No job jar file set.  User classes may not be found. See JobConf(Class) or JobConf#setJar(String).
	14/08/24 01:59:33 INFO input.FileInputFormat: Total input paths to process : 1
	14/08/24 01:59:33 WARN snappy.LoadSnappy: Snappy native library not loaded
	14/08/24 01:59:33 INFO mapred.JobClient: Running job: job_local1283277468_0001
	14/08/24 01:59:33 INFO mapred.LocalJobRunner: Waiting for map tasks
	14/08/24 01:59:33 INFO mapred.LocalJobRunner: Starting task: attempt_local1283277468_0001_m_000000_0
	14/08/24 01:59:33 INFO util.ProcessTree: setsid exited with exit code 0
	...
	14/08/24 01:59:34 INFO mapred.JobClient:     Map output records=103
	14/08/24 01:59:34 INFO mapred.JobClient:     Combine input records=103
	14/08/24 01:59:34 INFO mapred.JobClient:     Reduce input records=78

从DFS Locations中查看WordCount项目生成的输出文件`/user/xandy/output/part-r-00000`内容:

	Apache	2
	Apache™	1
	Hadoop	1
	Hadoop?	1
	Hadoop®	1
	...
	the	3
	thousands	1
	to	5
	top	1
	up	1
	using	1
	what	1
	which	1

## Eclipse调试

* F5-Step Into:表示进入当前方法。
* F6-Step Over:表示运行下一行代码。如果当前行有方法调用,这个方法将被执行完毕返回,然后到下一行。
* F7-Step Return:表示退出当前方法,返回到调用层。
* F8-表示当前实现继续运行直到下一个断点。

redpajama_set_name: RedPajamaGithub


text:
/*------------MD.cpp----------------------------------------------------------//
*
*             MD.cpp -- a simple event-driven MD simulation
*
* Purpose: Figure out the pressure on the interior of a box based on
*          Boltzmann's theory and stuff
*
*   Notes: This simulation will predominantly follow the logic of the link in
*          the README file
*
*-----------------------------------------------------------------------------*/

#include <algorithm>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <random>
#include <vector>

#include "math.h"

namespace sim {
    /* putting our stuff in its own namespace so we can call "time" "time"
    without colliding with names from the standard library */
    using time = double;

/*----------------------------------------------------------------------------//
* STRUCTS AND FUNCTIONS
*-----------------------------------------------------------------------------*/

// Holds our data in a central struct, to be called mainly in a vector
struct Particle {
    Point pos;
    Vector vel;
    uint64_t pid;
    time ts;
};

// holds interaction data
struct Interaction {
    time rtime;
    uint64_t first, second;

    Interaction() {}
    Interaction(time t, uint64_t p1, uint64_t p2)
        : rtime{t}, first{p1}, second{p2} {}
};

inline bool operator<(const Interaction& lhs, const Interaction& rhs) {
    return lhs.rtime < rhs.rtime;
}

// Makes starting data
std::vector<Particle> populate(uint64_t pnum, double box_length, double max_vel);

// Makes the interactions for our simulation later, required starting data
void update_interactions(const std::vector<Particle>& particles,
                         std::vector<Interaction>& interactions,
                         double box_length, double radius);

// This performs our MD simulation with a vector of interactions
// Also writes simulation to file, specified by README
void simulate(std::vector<Interaction>& interactions,
              std::vector<Particle>& particles,
              double radius, double mass, double box_length);

/*----------------------------------------------------------------------------//
* SUBROUTINES
*-----------------------------------------------------------------------------*/

// Makes starting data
std::vector<Particle> populate(uint64_t pnum, double box_length, double max_vel){
    std::vector<Particle> particles(pnum);

    uint64_t pid_counter = 0u;
    for (auto &p : particles){ //read: for all particles p in particles
        p.ts = 0;
        p.pid = pid_counter++;
        p.pos = uniform_in_bounds2d<Point>(0, box_length);
        p.vel = uniform_in_bounds2d<Vector>(0, max_vel);
    }

    return particles;
}

// Makes the interactions for our simulation later, required starting data
// Step 1: Check interactions between Particles, based on README link
// Step 2: Update interactions.
// Step 3: Sort interactions, lowest first
void update_interactions(const std::vector<Particle>& particles,
                         std::vector<Interaction>& interactions,
                         double, double radius) {
    // Step 1 -- find interactions
    for (auto i = 0u; i < particles.size() - 1; ++i) {
        for (auto j = i + 1; j < particles.size(); ++j) {
            auto& first = particles[i];
            auto& second = particles[j];

            Vector del_p = first.pos - second.pos;
            Vector del_v = first.vel - second.vel;

            double sigma = 2 * radius;

            // This is under the radical in quad eq., thus "rad_d"
            double rad_d = (square(dot(del_v, del_v))
                           - 4 * dot(del_v, del_v)
                           * (dot(del_p, del_p) - square(sigma)));

            if (dot(del_p, del_v) >= 0 || rad_d < 0){
                continue;
            }

            double check = (-dot(del_v, del_p)+ sqrt(rad_d)) / (2 * dot(del_v, del_v));

            std::cout << "found one!" << std::endl;
            interactions.emplace_back(check, i, j);
        }
    }

    // Step 3 -- sort the interactions

    // The std::sort command wants to know 3 things:
    //     1. Where to start sorting
    //     2. Where to stop sorting
    //     3. Which element value is greater
    //
    // To check #3, we use the user-defined "<" operator of Interaction.
    std::sort(std::begin(interactions), std::end(interactions));
}

// This performs our MD simulation with a vector of interactions
// Also writes simulation to file, specified by README
// Note: Time-loop here
// Step 1: loop over timesteps, defined in interactions
// Step 2: model the interaction of particles that interact
// Step 3: update interactions
// Step 4: output positions to file
// UNCHECKED
void simulate(std::vector<Interaction>& interactions,
              std::vector<Particle>& particles,
              double radius, double mass, double box_length) {

    // Note that these are all defined in the material linked in README
    // Step 1
    for (double simtime = 0; simtime < interactions.back().rtime;
         simtime += interactions[0].rtime){
        auto& first = particles[interactions[0].first];
        auto& second = particles[interactions[0].second];

        Vector del_p = first.pos + first.vel * simtime
                       - second.pos + second.vel * simtime;
        Vector del_v = first.vel - second.vel;

        double rtot = del_p.length();
        double del_vtot = del_v.length();

        // Step 2
        double J_tot = (2 * mass * mass * del_vtot * rtot) / (2 * radius * (2 * mass));

        Vector J = J_tot * del_p / (2 * radius);

        first.vel += J / mass;
        second.vel += J / mass;

        // Step 3 -- update interactions; TODO
        // UNCHECKED
        update_interactions(particles, interactions, box_length, radius);
    }
}

}

// C++ doesn't need the explicit void in main()
int main() {
    uint64_t pnum = 10000;
    double box_length = 10, max_vel = 0.01;

    std::vector<sim::Interaction> interactions;
    std::vector<sim::Particle> particles = sim::populate(pnum, box_length, max_vel);
    sim::update_interactions(particles, interactions, box_length, 0.1);

    // Iterating by const& because we do not intend to change to objects
    for (const auto &p : particles){
        std::cout << p.pos.x << std::endl;
    }

    std::cout << std::endl << std::endl;
    for (const auto &it : interactions){
        std::cout << it.rtime << std::endl;
    }

    return 0;
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:padding="10dip"
        android:text="@string/settings_title"
        android:textColor="@android:color/white"
        android:textSize="25sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dip"
        android:layout_marginRight="20dip"
        android:layout_marginTop="10dip"
        android:background="@drawable/shape"
        android:orientation="horizontal"
        android:paddingBottom="15dip"
        android:paddingTop="15dip" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:text="@string/sensitivity"
            android:textColor="@android:color/white" />

        <TextView
            android:id="@+id/sensitivity_value"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:textColor="@android:color/white"
            android:text="1" />
    </LinearLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip" >

        <TextView
            android:id="@+id/low"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:text="@string/low"
            android:textColor="@android:color/darker_gray" />

        <SeekBar
            android:id="@+id/sensitivity"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dip"
            android:layout_marginRight="10dip"
            android:layout_toLeftOf="@+id/high"
            android:layout_toRightOf="@id/low"
            android:max="10"
            android:maxHeight="5dip"
            android:minHeight="5dip"
            android:progress="3"
            android:focusable="true"/>

        <TextView
            android:id="@+id/high"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:text="@string/high"
            android:textColor="@android:color/darker_gray" />
    </RelativeLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="35dip"
        android:layout_marginRight="35dip"
        android:text="@string/sensitivity_info"
        android:textColor="@android:color/darker_gray" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dip"
        android:layout_marginRight="20dip"
        android:layout_marginTop="15dip"
        android:background="@drawable/shape" >

        <TextView
            android:id="@+id/step"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:paddingBottom="15dip"
            android:paddingTop="15dip"
            android:layout_marginLeft="10dp"
            android:text="@string/height"
            android:textColor="@android:color/white" />

        <TextView
            android:id="@+id/step_lenth_value"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignTop="@id/step"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dip"
            android:layout_toRightOf="@id/step"
            android:textColor="@android:color/white"
            android:text="2" />
    </RelativeLayout>

    <SeekBar
        android:id="@+id/step_lenth"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="35dip"
        android:layout_marginRight="35dip"
        android:max="50"
        android:maxHeight="5dip"
        android:minHeight="5dip"
        android:progress="3"
        android:focusable="true"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="35dip"
        android:layout_marginRight="35dip"
        android:text="@string/setp_length_info_1"
        android:textColor="@android:color/darker_gray" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dip"
        android:layout_marginRight="20dip"
        android:layout_marginTop="15dip"
        android:background="@drawable/shape"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:paddingBottom="15dip"
        android:paddingTop="15dip" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/weigth"
            android:textColor="@android:color/white"
            android:layout_marginLeft="10dp"/>

        <TextView
            android:id="@+id/weight_value"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:textColor="@android:color/white"
            android:text="3" />
    </LinearLayout>

    <SeekBar
        android:id="@+id/weight"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="35dip"
        android:layout_marginRight="35dip"
        android:max="50"
        android:maxHeight="5dip"
        android:minHeight="5dip"
        android:progress="3" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="35dip"
        android:layout_marginRight="35dip"
        android:text="@string/weight_info"
        android:textColor="@android:color/darker_gray" />

    <Button
        android:id="@+id/save"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="@drawable/shape"
        android:text="@string/save"
        android:textColor="@android:color/white"
        android:textStyle="bold"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:layout_gravity="center_horizontal" />

</LinearLayout>


text:
import webbrowser
import wx

class HyperLinkCtrl(wx.Panel):
    def __init__(self, parent, id, label, url, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, name="hyperlink"):
        wx.Panel.__init__(self, parent, id, pos, size, style, name)
        self.url = url
        self.normal_cursor = self.GetCursor()

        if wx.Platform == "__WXMSW__":
            self.SetCursor(wx.StockCursor(wx.CURSOR_HAND))

        self.label = wx.StaticText(self, label=label)
        self.label.SetForegroundColour(wx.BLUE)
        font = self.GetFont()
        font.SetUnderlined(True)
        self.label.SetFont(font)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.label, 1, wx.EXPAND)
        self.SetSizer(sizer)

        if wx.Platform != "__WXMSW__":
            self.Bind(wx.EVT_ENTER_WINDOW, self.__OnEnterWindow)
            self.Bind(wx.EVT_LEAVE_WINDOW, self.__OnLeaveWindow)
        else:
            self.label.Bind(wx.EVT_ENTER_WINDOW, self.__OnEnterWindow)
            self.label.Bind(wx.EVT_LEAVE_WINDOW, self.__OnLeaveWindow)

        self.label.Bind(wx.EVT_LEFT_UP, self.__OnLeftUp)

    def __OnEnterWindow(self, evt):
        self.label.SetForegroundColour(wx.RED)
        self.Refresh()
        wx.SetCursor(wx.StockCursor(wx.CURSOR_HAND))

    def __OnLeaveWindow(self, evt):
        self.label.SetForegroundColour(wx.BLUE)
        self.Refresh()
        wx.SetCursor(self.normal_cursor)

    def __OnLeftUp(self, evt):
        webbrowser.open_new_tab(self.url)


text:
function openEmailDialog(){
	var emailDialog = Titanium.UI.createEmailDialog();
	emailDialog.subject = "Secrets Unsealed App Contact";
	emailDialog.toRecipients = ['info+MobileApp@secretsunsealed.org'];
	emailDialog.messageBody = '';
	// var f = Ti.Filesystem.getFile('cricket.wav');
	// emailDialog.addAttachment(f);
	emailDialog.open();
}

function callNumber(){
	if (Ti.Platform.osname == 'ipad'){
		alert("(888) 738-1412");
	}
	else{
		Titanium.Platform.openURL("tel:8887381412");
	}

}

$.mapMailUs.selectAnnotation($.annotationAddress);
if (OS_ANDROID) {

	    $.mapMailUs.setLocation({
		    latitude:36.772384,
		    longitude:-119.684473,
		    animate:false,
		    latitudeDelta:0.04,
		    longitudeDelta:0.04
		});

	setTimeout(function() {
	    $.mapMailUs.visible = true;
	}, 200);
}
else {
	setTimeout(function() {

		$.mapMailUs.setLocation({
		    latitude:36.772384,
		    longitude:-119.684473,
		    animate:false,
		    latitudeDelta:0.04,
		    longitudeDelta:0.04
		});

	}, 200);
}

// Ti.App.addEventListener('orient', reorient);
//
// function reorient(){
	// var osname = Ti.Platform.osname, height = Ti.Platform.displayCaps.platformHeight, width = Ti.Platform.displayCaps.platformWidth;
	// var isTablet = osname === 'ipad' || (osname === 'android' && (width > 899 || height > 899));
//
	// if (isTablet){
		// if(Titanium.UI.orientation == 1 || Titanium.UI.orientation == 2){ // portrait
			// $.mapMailUs.height = "815dp";
	       	// $.lblMailUs.bottom = "820dp";
		// }
		// if(Titanium.UI.orientation == 3 || Titanium.UI.orientation == 4){ // landscape
	        // $.mapMailUs.height = "560dp";
	        // $.lblMailUs.bottom = "565dp";
		// }
	// }
// }
// if (Titanium.Platform.displayCaps.platformHeight == 568) {
   // $.mapMailUs.height = "370dp";
   // $.lblMailUs.bottom = "377dp";
// } else {
    // // code for 3.5-inch screen
// }


text:
<?php
namespace Acme\TestBundle;
class hello
{
	public function show($string){
		return "hello world ".$string;
	}
}


text:
NSString * const JTCalendarNotificationSelectedDate = @"JTCalendarNotificationSelectedDate";
NSString * const JTCalendarKeySelectedDate = @"JTCalendarKeySelectedDate";

@interface JTCalendar(){
    BOOL cacheLastWeekMode;
    NSUInteger cacheFirstWeekDay;
}

@end

@implementation JTCalendar

- (instancetype)init
{
    self = [super init];
    if(!self){
        return nil;
    }

    self->_currentDate = [NSDate date];
    self->_calendarAppearance = [JTCalendarAppearance new];
    self->_dataCache = [JTCalendarDataCache new];
    self.dataCache.calendarManager = self;

    return self;
}

// Bug in iOS
- (void)dealloc
{
    [self->_menuMonthsView setDelegate:nil];
    [self->_contentView setDelegate:nil];
}

- (void)setMenuMonthsView:(JTCalendarMenuView *)menuMonthsView
{
    [self->_menuMonthsView setDelegate:nil];
    [self->_menuMonthsView setCalendarManager:nil];

    self->_menuMonthsView = menuMonthsView;
    [self->_menuMonthsView setDelegate:self];
    [self->_menuMonthsView setCalendarManager:self];

    cacheLastWeekMode = self.calendarAppearance.isWeekMode;
    cacheFirstWeekDay = self.calendarAppearance.calendar.firstWeekday;

    [self.menuMonthsView setCurrentDate:self.currentDate];
    [self.menuMonthsView reloadAppearance];
}

- (void)setContentView:(JTCalendarContentView *)contentView
{
    [self->_contentView setDelegate:nil];
    [self->_contentView setCalendarManager:nil];

    self->_contentView = contentView;
    [self->_contentView setDelegate:self];
    [self->_contentView setCalendarManager:self];

    [self.contentView setCurrentDate:self.currentDate];
    [self.contentView reloadAppearance];
}

- (void)reloadData
{
    // Erase cache
    [self.dataCache reloadData];

    [self repositionViews];
    [self.contentView reloadData];
}

- (void)reloadAppearance
{
    [self.menuMonthsView reloadAppearance];
    [self.contentView reloadAppearance];

    if(cacheLastWeekMode != self.calendarAppearance.isWeekMode || cacheFirstWeekDay != self.calendarAppearance.calendar.firstWeekday){
        cacheLastWeekMode = self.calendarAppearance.isWeekMode;
        cacheFirstWeekDay = self.calendarAppearance.calendar.firstWeekday;

        [self setCurrentDate:self.currentDate];
    }
}

- (void)setCurrentDate:(NSDate *)currentDate
{
    NSAssert(currentDate, @"JTCalendar currentDate cannot be null");

    self->_currentDate = currentDate;

    [self.menuMonthsView setCurrentDate:currentDate];
    [self.contentView setCurrentDate:currentDate];

    [self repositionViews];
    [self.contentView reloadData];
}

#pragma mark - UIScrollView delegate

- (void)scrollViewDidScroll:(UIScrollView *)sender
{
    if(self.calendarAppearance.isWeekMode){
        return;
    }

    CGFloat ratio = CGRectGetWidth(self.contentView.frame) / CGRectGetWidth(self.menuMonthsView.frame);
    if(isnan(ratio)){
        ratio = 1.;
    }
    ratio *= self.calendarAppearance.ratioContentMenu;

    if(sender == self.menuMonthsView && self.menuMonthsView.scrollEnabled){
        self.contentView.contentOffset = CGPointMake(sender.contentOffset.x * ratio, self.contentView.contentOffset.y);
    }
    else if(sender == self.contentView && self.contentView.scrollEnabled){
        self.menuMonthsView.contentOffset = CGPointMake(sender.contentOffset.x / ratio, self.menuMonthsView.contentOffset.y);
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if(scrollView == self.contentView){
        self.menuMonthsView.scrollEnabled = NO;
    }
    else if(scrollView == self.menuMonthsView){
        self.contentView.scrollEnabled = NO;
    }

}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    scrollView.userInteractionEnabled = NO;
}

// Use for scroll with scrollRectToVisible or setContentOffset
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    [self updatePage];
    self.contentView.userInteractionEnabled = YES;

}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self updatePage];
    self.contentView.userInteractionEnabled = YES;
}

- (void)updatePage
{
    CGFloat pageWidth = CGRectGetWidth(self.contentView.frame);
    CGFloat fractionalPage = self.contentView.contentOffset.x / pageWidth;

    int currentPage = roundf(fractionalPage);
    if (currentPage == (NUMBER_PAGES_LOADED / 2)){
        self.menuMonthsView.scrollEnabled = YES;
        self.contentView.scrollEnabled = YES;
        return;
    }

    NSCalendar *calendar = self.calendarAppearance.calendar;
    NSDateComponents *dayComponent = [NSDateComponents new];

    if(!self.calendarAppearance.isWeekMode){
        dayComponent.month = currentPage - (NUMBER_PAGES_LOADED / 2);
    }
    else{
        dayComponent.day = 7 * (currentPage - (NUMBER_PAGES_LOADED / 2));
    }

    NSDate *currentDate = [calendar dateByAddingComponents:dayComponent toDate:self.currentDate options:0];

    [self setCurrentDate:currentDate];

    self.menuMonthsView.scrollEnabled = YES;
    self.contentView.scrollEnabled = YES;

    if(currentPage < (NUMBER_PAGES_LOADED / 2)){
        if([self.dataSource respondsToSelector:@selector(calendarDidLoadPreviousPage)]){
            [self.dataSource calendarDidLoadPreviousPage];
        }
    }
    else if(currentPage > (NUMBER_PAGES_LOADED / 2)){
        if([self.dataSource respondsToSelector:@selector(calendarDidLoadNextPage)]){
            [self.dataSource calendarDidLoadNextPage];
        }
    }

}

- (void)repositionViews
{
    // Position to the middle page
    CGFloat pageWidth = CGRectGetWidth(self.contentView.frame);
    self.contentView.contentOffset = CGPointMake(pageWidth * ((NUMBER_PAGES_LOADED / 2)), self.contentView.contentOffset.y);

    CGFloat menuPageWidth = CGRectGetWidth([self.menuMonthsView.subviews.firstObject frame]);
    self.menuMonthsView.contentOffset = CGPointMake(menuPageWidth * ((NUMBER_PAGES_LOADED / 2)), self.menuMonthsView.contentOffset.y);
}

- (void)loadNextMonth
{
    if(self.calendarAppearance.isWeekMode){
        NSLog(@"JTCalendar loadNextMonth ignored");
        return;
    }

    self.menuMonthsView.scrollEnabled = NO;

    CGRect frame = self.contentView.frame;
    frame.origin.x = frame.size.width * ((NUMBER_PAGES_LOADED / 2) + 1);
    frame.origin.y = 0;
    [self.contentView scrollRectToVisible:frame animated:YES];
}

- (void)loadPreviousMonth
{
    if(self.calendarAppearance.isWeekMode){
        NSLog(@"JTCalendar loadPreviousMonth ignored");
        return;
    }

    self.menuMonthsView.scrollEnabled = NO;

    CGRect frame = self.contentView.frame;
    frame.origin.x = frame.size.width * ((NUMBER_PAGES_LOADED / 2) - 1);
    frame.origin.y = 0;
    [self.contentView scrollRectToVisible:frame animated:YES];
}

- (void)selectDate:(NSDate *)date
{
    if (!date) {
        return;
    }
    self.currentDate = date;
    [[NSNotificationCenter defaultCenter] postNotificationName:JTCalendarNotificationSelectedDate object:nil userInfo:@{ JTCalendarKeySelectedDate: date }];
}

@end


text:
(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('rxjs/Subscriber'), require('rxjs/operator/pluck'), require('rxjs/operator/map'), require('rxjs/operator/distinctUntilChanged')) :
    typeof define === 'function' && define.amd ? define(['exports', 'rxjs/Subscriber', 'rxjs/operator/pluck', 'rxjs/operator/map', 'rxjs/operator/distinctUntilChanged'], factory) :
    (factory((global.ngrx = global.ngrx || {}, global.ngrx.core = global.ngrx.core || {}),global.Rx,global.Rx.Observable.prototype,global.Rx.Observable.prototype,global.Rx.Observable.prototype));
}(this, (function (exports,rxjs_Subscriber,rxjs_operator_pluck,rxjs_operator_map,rxjs_operator_distinctUntilChanged) { 'use strict';

var __extends = (undefined && undefined.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
function enterZone(zone) {
    return this.lift(new EnterZoneOperator(zone));
}
var EnterZoneOperator = (function () {
    function EnterZoneOperator(_zone) {
        this._zone = _zone;
    }
    EnterZoneOperator.prototype.call = function (subscriber, source) {
        return source._subscribe(new EnterZoneSubscriber(subscriber, this._zone));
    };
    return EnterZoneOperator;
}());
var EnterZoneSubscriber = (function (_super) {
    __extends(EnterZoneSubscriber, _super);
    function EnterZoneSubscriber(destination, _zone) {
        _super.call(this, destination);
        this._zone = _zone;
    }
    EnterZoneSubscriber.prototype._next = function (value) {
        var _this = this;
        this._zone.run(function () { return _this.destination.next(value); });
    };
    return EnterZoneSubscriber;
}(rxjs_Subscriber.Subscriber));

var __extends$1 = (undefined && undefined.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
function leaveZone(zone) {
    return this.lift(new LeaveZoneOperator(zone));
}
var LeaveZoneOperator = (function () {
    function LeaveZoneOperator(_zone) {
        this._zone = _zone;
    }
    LeaveZoneOperator.prototype.call = function (subscriber, source) {
        return source._subscribe(new LeaveZoneSubscriber(subscriber, this._zone));
    };
    return LeaveZoneOperator;
}());
var LeaveZoneSubscriber = (function (_super) {
    __extends$1(LeaveZoneSubscriber, _super);
    function LeaveZoneSubscriber(destination, _zone) {
        _super.call(this, destination);
        this._zone = _zone;
    }
    LeaveZoneSubscriber.prototype._next = function (value) {
        var _this = this;
        this._zone.runOutsideAngular(function () { return _this.destination.next(value); });
    };
    return LeaveZoneSubscriber;
}(rxjs_Subscriber.Subscriber));

function select(pathOrMapFn) {
    var paths = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        paths[_i - 1] = arguments[_i];
    }
    var mapped$;
    if (typeof pathOrMapFn === 'string') {
        mapped$ = rxjs_operator_pluck.pluck.call.apply(rxjs_operator_pluck.pluck, [this, pathOrMapFn].concat(paths));
    }
    else if (typeof pathOrMapFn === 'function') {
        mapped$ = rxjs_operator_map.map.call(this, pathOrMapFn);
    }
    else {
        throw new TypeError(("Unexpected type " + typeof pathOrMapFn + " in select operator,")
            + " expected 'string' or 'function'");
    }
    return rxjs_operator_distinctUntilChanged.distinctUntilChanged.call(mapped$);
}

var compose = function () {
    var functions = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        functions[_i - 0] = arguments[_i];
    }
    return function (arg) {
        if (functions.length === 0) {
            return arg;
        }
        var last = functions[functions.length - 1];
        var rest = functions.slice(0, -1);
        return rest.reduceRight(function (composed, fn) { return fn(composed); }, last(arg));
    };
};

exports.enterZone = enterZone;
exports.EnterZoneOperator = EnterZoneOperator;
exports.leaveZone = leaveZone;
exports.LeaveZoneOperator = LeaveZoneOperator;
exports.select = select;
exports.compose = compose;

Object.defineProperty(exports, '__esModule', { value: true });

})));


text:
package followheart.fragments;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import followheart.activities.R;
import followheart.activities.TableActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class TableListFragment extends Fragment {

	private static View mView;
	List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
	List<Map<String, Boolean>> checkboxList = new ArrayList<Map<String, Boolean>>();
	private int tableNumber;
	ListView tablelist;
	Button newtable_btn;
	SimpleAdapter adapter;

	public static final TableListFragment newInstance() {
		TableListFragment f = new TableListFragment();

		Bundle b = new Bundle();
		f.setArguments(b);

		return f;
	}

	// �Զ����õ�onCreateView
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		mView = inflater.inflate(R.layout.activity_tablelist, container, false);
		tablelist = (ListView) mView.findViewById(R.id.tablelist);
		newtable_btn = (Button) mView.findViewById(R.id.newtable_btn);

		// �����½����ť����ת�����ҳ��
		newtable_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Bundle bundle = new Bundle();
				bundle.putInt("tableNumber", tableNumber);
				// String s = "";
				// bundle.putString("tableName",);
				String s = "未命名";
				bundle.putString("tableName",s);

				Intent intent = new Intent();
				intent.setClass(getActivity(), TableActivity.class);
				intent.putExtras(bundle);
				startActivityForResult(intent, 0);
				getActivity().finish();
			}
		});
		// �������б�
		adapter = new SimpleAdapter(getActivity(), getTableListData(),
				R.layout.tablelist_listitem,
				new String[] { "tablename", "date" }, new int[] {
						R.id.tablename, R.id.date });
		tablelist.setAdapter(adapter);
		// ���tablelist��ת������ı��
		tablelist.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Bundle bundle = new Bundle();
				bundle.putInt("tableNumber", tableNumber);
				bundle.putString("tableName", getFile().get(arg2).getName());
				Intent intent = new Intent();
				intent.setClass(getActivity(), TableActivity.class);
				intent.putExtras(bundle);
				startActivityForResult(intent, 0);
				getActivity().finish();
			}
		});

		// 长按分享弹出对话框
		tablelist.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					final int arg2, long arg3) {
				// TODO Auto-generated method stub

				AlertDialog.Builder builder = new AlertDialog.Builder(
						getActivity());
				builder.setMessage("分享至")
						.setCancelable(true)
						.setPositiveButton("删除",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int id) {
										// TODO Auto-generated method stub
										File file = new File(
												"/sdcard/data/data/mesapp/"
														+ getFile().get(arg2)
																.getName());
										file.delete();
										adapter = new SimpleAdapter(
												getActivity(),
												getTableListData(),
												R.layout.tablelist_listitem,
												new String[] { "tablename",
														"date" }, new int[] {
														R.id.tablename,
														R.id.date });
										tablelist.setAdapter(adapter);
										dialog.cancel();

									}
								})
						.setNegativeButton("重命名",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int id) {
										// TODO Auto-generated method stub

										dialog.cancel();
										final EditText renameEditText = new EditText(
												getActivity());
										new AlertDialog.Builder(getActivity())
												.setTitle("请输入")
												.setIcon(
														android.R.drawable.ic_dialog_info)
												.setView(renameEditText)
												.setPositiveButton(
														"确定",
														new DialogInterface.OnClickListener() {

															@Override
															public void onClick(
																	DialogInterface dialog,
																	int id) {
																File file = new File(
																		"/sdcard/data/data/mesapp/"
																				+ getFile()
																						.get(arg2)
																						.getName());
																File file2 = new File(
																		"/sdcard/data/data/mesapp/"
																				+ renameEditText
																						.getText());
																Log.d("ccccccccc",
																		file2.getName());
																file.renameTo(file2);
																Log.d("ddddddddd",
																		file.getName());
																adapter = new SimpleAdapter(
																		getActivity(),
																		getTableListData(),
																		R.layout.tablelist_listitem,
																		new String[] {
																				"tablename",
																				"date" },
																		new int[] {
																				R.id.tablename,
																				R.id.date });
																tablelist
																		.setAdapter(adapter);
															}
														})
												.setNegativeButton("取消", null)
												.show();
									}
								})
						.setNeutralButton("分享",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int id) {
										// TODO Auto-generated method stub
										dialog.cancel();
									}
								});
				AlertDialog shareDialog = builder.create();
				shareDialog.show();
				return true;
			}

		});

		return mView;
	}

	// ��ȡ���ڱ��б���ƣ���ţ��������ڲ�����
	private List<Map<String, Object>> getTableListData() {
		List<Map<String, Object>> tablelist = new ArrayList<Map<String, Object>>();

		Map<String, Object> map = new HashMap<String, Object>();
		// Log.d("������������������������",".................");
		List<File> list = getFile();
		tableNumber = getFile().size();
		for (int i = 0; i < list.size(); i++) {
			map = new HashMap<String, Object>();
			map.put("tablename", list.get(i).getName());
			// ��ȡ�ļ�����޸�ʱ��
			Calendar cal = Calendar.getInstance();
			long time = list.get(i).lastModified();
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			cal.setTimeInMillis(time);
			map.put("date", formatter.format(cal.getTime()));
			tablelist.add(map);
		}

		return tablelist;
	}

	// ����Ŀ¼���������еı�
	public List<File> getFile() {
		File f1 = new File("/sdcard/data");

		if(!f1.exists()){
			f1.mkdir();
		}
		File f2 = new File("/sdcard/data/data");
		if(!f2.exists()){
			f2.mkdir();
		}
		File f3 = new File("/sdcard/data/data/measapp");
		if(!f3.exists()){
			try {
				f3.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		List<File> listFile = new ArrayList<File>();
		File allFiles[] = new File("/sdcard/data/data/mesapp").listFiles();
		// Log.d("������������������������",".................");
		if(allFiles != null){
			for (int i = 0; i < allFiles.length; i++) {
				File file = allFiles[i];
				// Log.d("������������������������","!!!!!!!!!");
				if (file.isFile()) {
					listFile.add(file);
				}
			}
		}

		return listFile;
	}

	public int getTableNumber() {
		return tableNumber;
	}

	public void setTableNumber(int tableNumber) {
		this.tableNumber = tableNumber;
	}

}


text:
'''
Created on Feb 4, 2016

@author: mike
'''
from __future__ import print_function, unicode_literals
import argparse
import codecs
from cslavonic import ucs_codec
import sys

def main_reencode(args):

    ucs_codec.register_UCS()

    with codecs.open(args.input or sys.stdin.fileno(), 'r', args.encoding) as src:
        with codecs.open(args.output or sys.stdout.fileno(), 'w', 'utf-8') as dest:
            dest.write(src.read())

    return 0

def main():
    parser = argparse.ArgumentParser(description='Converts file from UCS (or any other input encoding) to utf-8')
    parser.add_argument('-i', '--input', default=None, help='File to decode. If not set, reads STDIN')
    parser.add_argument('-e', '--encoding', default='UCS', help='Input file encoding. Default is UCS')
    parser.add_argument('-o', '--output', default=None, help='File to create. If not set, writes to STDOUT.')

    args = parser.parse_args()

    parser.exit(main_reencode(args))

if __name__ == '__main__':
    main()


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

using CognitiveServices.Tests.Helpers;
using Microsoft.Azure.Management.CognitiveServices;
using Microsoft.Azure.Management.CognitiveServices.Models;
using Microsoft.Azure.Management.Resources;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using ResourceGroups.Tests;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Xunit;

namespace CognitiveServices.Tests
{
    public class CognitiveServicesAccountTests
    {
        private const string c_resourceNamespace = "Microsoft.CognitiveServices";
        private const string c_resourceType = "accounts";

        [Fact]
        public void CognitiveServicesAccountCreateTest()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient = CognitiveServicesManagementTestUtilities.GetResourceManagementClient(context, handler);
                var cognitiveServicesMgmtClient = CognitiveServicesManagementTestUtilities.GetCognitiveServicesManagementClient(context, handler);

                // Create resource group
                var rgname = CognitiveServicesManagementTestUtilities.CreateResourceGroup(resourcesClient);

                // prepare account properties
                string accountName = TestUtilities.GenerateName("csa");
                var parameters = CognitiveServicesManagementTestUtilities.GetDefaultCognitiveServicesAccountParameters();

                // Create cognitive services account
                var account = cognitiveServicesMgmtClient.Accounts.Create(rgname, accountName, parameters);
                CognitiveServicesManagementTestUtilities.VerifyAccountProperties(account, true);

                // Create same account again, make sure it doesn't fail
                account = cognitiveServicesMgmtClient.Accounts.Create(rgname, accountName, parameters);
                CognitiveServicesManagementTestUtilities.VerifyAccountProperties(account, true);

                // Create account with only required params, for each sku (but free, since we can't have two free accounts in the same subscription)
                CognitiveServicesManagementTestUtilities.CreateAndValidateAccountWithOnlyRequiredParameters(cognitiveServicesMgmtClient, rgname, "S1");
                CognitiveServicesManagementTestUtilities.CreateAndValidateAccountWithOnlyRequiredParameters(cognitiveServicesMgmtClient, rgname, "S2");
                CognitiveServicesManagementTestUtilities.CreateAndValidateAccountWithOnlyRequiredParameters(cognitiveServicesMgmtClient, rgname, "S3");
                CognitiveServicesManagementTestUtilities.CreateAndValidateAccountWithOnlyRequiredParameters(cognitiveServicesMgmtClient, rgname, "S4");
            }
        }

        [Fact]
        public void CognitiveServicesAccountCreateAllApisTest()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient = CognitiveServicesManagementTestUtilities.GetResourceManagementClient(context, handler);
                var cognitiveServicesMgmtClient = CognitiveServicesManagementTestUtilities.GetCognitiveServicesManagementClient(context, handler);

                // Create resource group
                var rgname = CognitiveServicesManagementTestUtilities.CreateResourceGroup(resourcesClient);

                CognitiveServicesManagementTestUtilities.CreateAndValidateAccountWithOnlyRequiredParameters(cognitiveServicesMgmtClient, rgname, "S1", "Bing.Autosuggest.v7", "global");
                CognitiveServicesManagementTestUtilities.CreateAndValidateAccountWithOnlyRequiredParameters(cognitiveServicesMgmtClient, rgname, "S1", "Bing.CustomSearch", "global");
                CognitiveServicesManagementTestUtilities.CreateAndValidateAccountWithOnlyRequiredParameters(cognitiveServicesMgmtClient, rgname, "S1", "Bing.Search.v7", "global");
                CognitiveServicesManagementTestUtilities.CreateAndValidateAccountWithOnlyRequiredParameters(cognitiveServicesMgmtClient, rgname, "S0", "Bing.Speech", "global");
                CognitiveServicesManagementTestUtilities.CreateAndValidateAccountWithOnlyRequiredParameters(cognitiveServicesMgmtClient, rgname, "S1", "Bing.SpellCheck.v7", "global");
                CognitiveServicesManagementTestUtilities.CreateAndValidateAccountWithOnlyRequiredParameters(cognitiveServicesMgmtClient, rgname, "S1", "ComputerVision", "westus");
                CognitiveServicesManagementTestUtilities.CreateAndValidateAccountWithOnlyRequiredParameters(cognitiveServicesMgmtClient, rgname, "S0", "ContentModerator", "westus");
                CognitiveServicesManagementTestUtilities.CreateAndValidateAccountWithOnlyRequiredParameters(cognitiveServicesMgmtClient, rgname, "S0", "CustomSpeech", "westus");
                CognitiveServicesManagementTestUtilities.CreateAndValidateAccountWithOnlyRequiredParameters(cognitiveServicesMgmtClient, rgname, "S0", "CustomVision.Prediction", "southcentralus");
                CognitiveServicesManagementTestUtilities.CreateAndValidateAccountWithOnlyRequiredParameters(cognitiveServicesMgmtClient, rgname, "S0", "CustomVision.Training", "southcentralus");
                CognitiveServicesManagementTestUtilities.CreateAndValidateAccountWithOnlyRequiredParameters(cognitiveServicesMgmtClient, rgname, "S0", "Face", "westus");
                CognitiveServicesManagementTestUtilities.CreateAndValidateAccountWithOnlyRequiredParameters(cognitiveServicesMgmtClient, rgname, "S0", "LUIS", "westus");
                CognitiveServicesManagementTestUtilities.CreateAndValidateAccountWithOnlyRequiredParameters(cognitiveServicesMgmtClient, rgname, "S0", "SpeakerRecognition", "westus");
                CognitiveServicesManagementTestUtilities.CreateAndValidateAccountWithOnlyRequiredParameters(cognitiveServicesMgmtClient, rgname, "S1", "SpeechTranslation", "global");
                CognitiveServicesManagementTestUtilities.CreateAndValidateAccountWithOnlyRequiredParameters(cognitiveServicesMgmtClient, rgname, "S1", "TextAnalytics", "westus");
                CognitiveServicesManagementTestUtilities.CreateAndValidateAccountWithOnlyRequiredParameters(cognitiveServicesMgmtClient, rgname, "S1", "TextTranslation", "global");
            }
        }

        [Fact]
        public void CognitiveServicesAccountDeleteTest()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient = CognitiveServicesManagementTestUtilities.GetResourceManagementClient(context, handler);
                var cognitiveServicesMgmtClient = CognitiveServicesManagementTestUtilities.GetCognitiveServicesManagementClient(context, handler);

                // Create resource group
                var rgname = CognitiveServicesManagementTestUtilities.CreateResourceGroup(resourcesClient);

                // Delete an account which does not exist
                cognitiveServicesMgmtClient.Accounts.Delete(rgname, "missingaccount");

                // Create cognitive services account
                string accountName = CognitiveServicesManagementTestUtilities.CreateCognitiveServicesAccount(cognitiveServicesMgmtClient, rgname);

                // Delete an account
                cognitiveServicesMgmtClient.Accounts.Delete(rgname, accountName);

                // Delete an account which was just deleted
                cognitiveServicesMgmtClient.Accounts.Delete(rgname, accountName);
            }
        }

        [Fact]
        public void CognitiveServicesAccountCreateAndGetDifferentSkusTest()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient = CognitiveServicesManagementTestUtilities.GetResourceManagementClient(context, handler);
                var cognitiveServicesMgmtClient = CognitiveServicesManagementTestUtilities.GetCognitiveServicesManagementClient(context, handler);

                // Create resource group
                var rgname = CognitiveServicesManagementTestUtilities.CreateResourceGroup(resourcesClient);

                // Default parameters
                var f0Account = CognitiveServicesManagementTestUtilities.CreateAndValidateAccountWithOnlyRequiredParameters(cognitiveServicesMgmtClient, rgname, "F0", "TextAnalytics");
                var s1Account = CognitiveServicesManagementTestUtilities.CreateAndValidateAccountWithOnlyRequiredParameters(cognitiveServicesMgmtClient, rgname, "S1", "TextAnalytics");

                var f0Properties = cognitiveServicesMgmtClient.Accounts.GetProperties(rgname, f0Account.Name);
                Assert.Equal("F0", f0Properties.Sku.Name);
                Assert.Equal("TextAnalytics".ToString(), f0Properties.Kind);

                var s1Properties = cognitiveServicesMgmtClient.Accounts.GetProperties(rgname, s1Account.Name);
                Assert.Equal("S1", s1Properties.Sku.Name);
                Assert.Equal("TextAnalytics".ToString(), s1Properties.Kind);
            }
        }

        [Fact]
        public void CognitiveServicesAccountListByResourceGroupTest()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient = CognitiveServicesManagementTestUtilities.GetResourceManagementClient(context, handler);
                var cognitiveServicesMgmtClient = CognitiveServicesManagementTestUtilities.GetCognitiveServicesManagementClient(context, handler);

                // Create resource group
                var rgname = CognitiveServicesManagementTestUtilities.CreateResourceGroup(resourcesClient);

                var accounts = cognitiveServicesMgmtClient.Accounts.ListByResourceGroup(rgname);
                Assert.Empty(accounts);

                // Create cognitive services accounts
                string accountName1 = CognitiveServicesManagementTestUtilities.CreateCognitiveServicesAccount(cognitiveServicesMgmtClient, rgname);
                string accountName2 = CognitiveServicesManagementTestUtilities.CreateCognitiveServicesAccount(cognitiveServicesMgmtClient, rgname);

                accounts = cognitiveServicesMgmtClient.Accounts.ListByResourceGroup(rgname);
                Assert.Equal(2, accounts.Count());

                CognitiveServicesManagementTestUtilities.VerifyAccountProperties(accounts.First(), true);
                CognitiveServicesManagementTestUtilities.VerifyAccountProperties(accounts.Skip(1).First(), true);
            }
        }

        [Fact]
        public void CognitiveServicesAccountListBySubscriptionTest()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient = CognitiveServicesManagementTestUtilities.GetResourceManagementClient(context, handler);
                var cognitiveServicesMgmtClient = CognitiveServicesManagementTestUtilities.GetCognitiveServicesManagementClient(context, handler);

                // Create resource group and cognitive services account
                var rgname1 = CognitiveServicesManagementTestUtilities.CreateResourceGroup(resourcesClient);
                string accountName1 = CognitiveServicesManagementTestUtilities.CreateCognitiveServicesAccount(cognitiveServicesMgmtClient, rgname1);

                // Create different resource group and cognitive account
                var rgname2 = CognitiveServicesManagementTestUtilities.CreateResourceGroup(resourcesClient);
                string accountName2 = CognitiveServicesManagementTestUtilities.CreateCognitiveServicesAccount(cognitiveServicesMgmtClient, rgname2);

                var accounts = cognitiveServicesMgmtClient.Accounts.List();

                Assert.True(accounts.Count() >= 2);

                CognitiveServicesAccount account1 = accounts.First(
                    t => StringComparer.OrdinalIgnoreCase.Equals(t.Name, accountName1));
                CognitiveServicesManagementTestUtilities.VerifyAccountProperties(account1, true);

                CognitiveServicesAccount account2 = accounts.First(
                    t => StringComparer.OrdinalIgnoreCase.Equals(t.Name, accountName2));
                CognitiveServicesManagementTestUtilities.VerifyAccountProperties(account2, true);
            }
        }

        [Fact]
        public void CognitiveServicesAccountListKeysTest()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient = CognitiveServicesManagementTestUtilities.GetResourceManagementClient(context, handler);
                var cognitiveServicesMgmtClient = CognitiveServicesManagementTestUtilities.GetCognitiveServicesManagementClient(context, handler);

                // Create resource group
                string rgname = CognitiveServicesManagementTestUtilities.CreateResourceGroup(resourcesClient);

                // Create cognitive services account
                string accountName = CognitiveServicesManagementTestUtilities.CreateCognitiveServicesAccount(cognitiveServicesMgmtClient, rgname);

                // List keys
                var keys = cognitiveServicesMgmtClient.Accounts.ListKeys(rgname, accountName);
                Assert.NotNull(keys);

                // Validate Key1
                Assert.NotNull(keys.Key1);
                // Validate Key2
                Assert.NotNull(keys.Key2);
            }
        }

        [Fact]
        public void CognitiveServicesAccountGetUsagesTest()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient = CognitiveServicesManagementTestUtilities.GetResourceManagementClient(context, handler);
                var cognitiveServicesMgmtClient = CognitiveServicesManagementTestUtilities.GetCognitiveServicesManagementClient(context, handler);

                // Create resource group
                string rgname = CognitiveServicesManagementTestUtilities.CreateResourceGroup(resourcesClient);

                // Create cognitive services account
                string accountName = CognitiveServicesManagementTestUtilities.CreateCognitiveServicesAccount(cognitiveServicesMgmtClient, rgname);

                // Get usages
                var usages = cognitiveServicesMgmtClient.Accounts.GetUsages(rgname, accountName);

                // Has usage data.
                Assert.NotNull(usages.Value);

                // Has quota limit
                Assert.True(usages.Value[0].Limit > 0);

                // Current value == 0 as there is no call made for this newly created account.
                Assert.Equal(0, usages.Value[0].CurrentValue);
            }
        }

        [Fact]
        public void CognitiveServicesAccountRegenerateKeyTest()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient = CognitiveServicesManagementTestUtilities.GetResourceManagementClient(context, handler);
                var cognitiveServicesMgmtClient = CognitiveServicesManagementTestUtilities.GetCognitiveServicesManagementClient(context, handler);

                // Create resource group
                string rgname = CognitiveServicesManagementTestUtilities.CreateResourceGroup(resourcesClient);

                // Create cognitive services account
                string accountName = CognitiveServicesManagementTestUtilities.CreateCognitiveServicesAccount(cognitiveServicesMgmtClient, rgname);

                // List keys
                var keys = cognitiveServicesMgmtClient.Accounts.ListKeys(rgname, accountName);
                Assert.NotNull(keys);
                var key2 = keys.Key2;
                Assert.NotNull(key2);

                // Regenerate keys and verify that keys change
                var regenKeys = cognitiveServicesMgmtClient.Accounts.RegenerateKey(rgname, accountName, KeyName.Key2);
                var key2Regen = regenKeys.Key2;
                Assert.NotNull(key2Regen);

                // Validate key was regenerated
                Assert.NotEqual(key2, key2Regen);
            }
        }

        [Fact]
        public void CognitiveServicesAccountUpdateWithCreateTest()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient = CognitiveServicesManagementTestUtilities.GetResourceManagementClient(context, handler);
                var cognitiveServicesMgmtClient = CognitiveServicesManagementTestUtilities.GetCognitiveServicesManagementClient(context, handler);

                // Create resource group
                var rgname = CognitiveServicesManagementTestUtilities.CreateResourceGroup(resourcesClient);

                // Create cognitive services account
                var createdAccount = CognitiveServicesManagementTestUtilities.CreateAndValidateAccountWithOnlyRequiredParameters(cognitiveServicesMgmtClient, rgname, "S2", "TextAnalytics");
                var accountName = createdAccount.Name;

                // Update SKU
                var account = cognitiveServicesMgmtClient.Accounts.Update(rgname, accountName, new Sku { Name = "S1" });
                Assert.Equal("S1", account.Sku.Name);

                // Validate
                var fetchedAccount = cognitiveServicesMgmtClient.Accounts.GetProperties(rgname, accountName);
                Assert.Equal("S1", fetchedAccount.Sku.Name);

                var newTags = new Dictionary<string, string>
                {
                    {"key3","value3"},
                    {"key4","value4"},
                    {"key5","value5"}
                };

                // Update account tags
                account = cognitiveServicesMgmtClient.Accounts.Update(rgname, accountName, null, newTags);
                Assert.Equal(newTags.Count, account.Tags.Count);
                // Validate
                fetchedAccount = cognitiveServicesMgmtClient.Accounts.GetProperties(rgname, accountName);
                Assert.Equal("S1", fetchedAccount.Sku.Name);
                Assert.Equal(newTags.Count, fetchedAccount.Tags.Count());
                Assert.Collection(fetchedAccount.Tags,
                    (keyValue) => { Assert.Equal("key3", keyValue.Key); Assert.Equal("value3", keyValue.Value); },
                    (keyValue) => { Assert.Equal("key4", keyValue.Key); Assert.Equal("value4", keyValue.Value); },
                    (keyValue) => { Assert.Equal("key5", keyValue.Key); Assert.Equal("value5", keyValue.Value); }
                );
            }
        }

        [Fact]
        public void CognitiveServicesAccountEnumerateSkusTest()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient = CognitiveServicesManagementTestUtilities.GetResourceManagementClient(context, handler);
                var cognitiveServicesMgmtClient = CognitiveServicesManagementTestUtilities.GetCognitiveServicesManagementClient(context, handler);

                // Create resource group
                var rgname = CognitiveServicesManagementTestUtilities.CreateResourceGroup(resourcesClient);

                // Create cognitive services account
                var createdAccount = CognitiveServicesManagementTestUtilities.CreateAndValidateAccountWithOnlyRequiredParameters(cognitiveServicesMgmtClient, rgname, "S3", "TextAnalytics");
                var accountName = createdAccount.Name;

                // Enumerate SKUs

                var skuList = cognitiveServicesMgmtClient.Accounts.ListSkus(rgname, accountName);

                Assert.Single(skuList.Value.Select(x => x.ResourceType).Distinct());

                Assert.Equal($"{c_resourceNamespace}/{c_resourceType}", skuList.Value.Select(x => x.ResourceType).First());

                Assert.Collection(skuList.Value.Select(x => x.Sku),
                    (sku) => { Assert.Equal("F0", sku.Name); Assert.Equal(SkuTier.Free, sku.Tier); },
                    (sku) => { Assert.Equal("S0", sku.Name); Assert.Equal(SkuTier.Standard, sku.Tier); },
                    (sku) => { Assert.Equal("S1", sku.Name); Assert.Equal(SkuTier.Standard, sku.Tier); },
                    (sku) => { Assert.Equal("S2", sku.Name); Assert.Equal(SkuTier.Standard, sku.Tier); },
                    (sku) => { Assert.Equal("S3", sku.Name); Assert.Equal(SkuTier.Standard, sku.Tier); },
                    (sku) => { Assert.Equal("S4", sku.Name); Assert.Equal(SkuTier.Standard, sku.Tier); }
                );
            }
        }

        //   Negative Scenarios Tests
        [Fact]
        public void CognitiveServicesCreateAccountErrorTest()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient = CognitiveServicesManagementTestUtilities.GetResourceManagementClient(context, handler);
                var cognitiveServicesMgmtClient = CognitiveServicesManagementTestUtilities.GetCognitiveServicesManagementClient(context, handler);

                // Create resource group
                var rgname = CognitiveServicesManagementTestUtilities.CreateResourceGroup(resourcesClient);

                var accountName = TestUtilities.GenerateName("csa");
                var parameters = new CognitiveServicesAccountCreateParameters
                {
                    Sku = new Sku { Name = "F0" },
                    Kind = "ComputerVision",
                    Location = CognitiveServicesManagementTestUtilities.DefaultLocation,
                    Properties = new object(),
                };

                CognitiveServicesManagementTestUtilities.ValidateExpectedException(
                    () => cognitiveServicesMgmtClient.Accounts.Create("NotExistedRG", accountName, parameters),
                    "ResourceGroupNotFound");

                parameters.Location = "BLA";
                CognitiveServicesManagementTestUtilities.ValidateExpectedException(
                    () => cognitiveServicesMgmtClient.Accounts.Create(rgname, accountName, parameters),
                    "LocationNotAvailableForResourceType");
            }
        }

        [Fact]
        public void CognitiveServicesCreateAccountErrorTest2()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient = CognitiveServicesManagementTestUtilities.GetResourceManagementClient(context, handler);
                var cognitiveServicesMgmtClient = CognitiveServicesManagementTestUtilities.GetCognitiveServicesManagementClient(context, handler);

                // Create resource group
                var rgname = CognitiveServicesManagementTestUtilities.CreateResourceGroup(resourcesClient);

                var accountName = TestUtilities.GenerateName("csa");
                var nonExistApiPara = new CognitiveServicesAccountCreateParameters
                {
                    Sku = new Sku { Name = "F0" },
                    Kind = "NonExistAPI",
                    Location = CognitiveServicesManagementTestUtilities.DefaultLocation,
                    Properties = new object(),
                };

                var nonExistSkuPara = new CognitiveServicesAccountCreateParameters
                {
                    Sku = new Sku { Name = "N0" },
                    Kind = "Face",
                    Location = CognitiveServicesManagementTestUtilities.DefaultLocation,
                    Properties = new object(),
                };

                CognitiveServicesManagementTestUtilities.ValidateExpectedException(
                    () => cognitiveServicesMgmtClient.Accounts.Create(rgname, accountName, nonExistApiPara),
                    "InvalidApiSetId");

                CognitiveServicesManagementTestUtilities.ValidateExpectedException(
                    () => cognitiveServicesMgmtClient.Accounts.Create(rgname, accountName, nonExistSkuPara),
                    "InvalidSkuId");
            }
        }

        [Fact]
        public void CognitiveServicesGetAccountErrorTest()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient = CognitiveServicesManagementTestUtilities.GetResourceManagementClient(context, handler);
                var cognitiveServicesMgmtClient = CognitiveServicesManagementTestUtilities.GetCognitiveServicesManagementClient(context, handler);

                // Create resource group
                var rgname = CognitiveServicesManagementTestUtilities.CreateResourceGroup(resourcesClient);

                CognitiveServicesManagementTestUtilities.ValidateExpectedException(
                    () => cognitiveServicesMgmtClient.Accounts.GetProperties("NotExistedRG", "nonExistedAccountName"),
                    "ResourceGroupNotFound");

                CognitiveServicesManagementTestUtilities.ValidateExpectedException(
                    () => cognitiveServicesMgmtClient.Accounts.GetProperties(rgname, "nonExistedAccountName"),
                    "ResourceNotFound");

                CognitiveServicesManagementTestUtilities.ValidateExpectedException(
                    () => cognitiveServicesMgmtClient.Accounts.ListByResourceGroup("NotExistedRG"),
                    "ResourceGroupNotFound");
            }
        }

        [Fact]
        public void CognitiveServicesUpdateAccountErrorTest()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient = CognitiveServicesManagementTestUtilities.GetResourceManagementClient(context, handler);
                var cognitiveServicesMgmtClient = CognitiveServicesManagementTestUtilities.GetCognitiveServicesManagementClient(context, handler);

                // Create resource group
                var rgname = CognitiveServicesManagementTestUtilities.CreateResourceGroup(resourcesClient);

                // Create cognitive services account
                var createdAccount = CognitiveServicesManagementTestUtilities.CreateAndValidateAccountWithOnlyRequiredParameters(cognitiveServicesMgmtClient, rgname, "S0", "Face");
                var accountName = createdAccount.Name;

                // try to update non-existent account
                CognitiveServicesManagementTestUtilities.ValidateExpectedException(
                    () => cognitiveServicesMgmtClient.Accounts.Update("NotExistedRG", "nonExistedAccountName"),
                    "ResourceGroupNotFound");

                CognitiveServicesManagementTestUtilities.ValidateExpectedException(
                    () => cognitiveServicesMgmtClient.Accounts.Update(rgname, "nonExistedAccountName"),
                    "ResourceNotFound");

                // Update with a SKU which doesn't exist
                CognitiveServicesManagementTestUtilities.ValidateExpectedException(
                    () => cognitiveServicesMgmtClient.Accounts.Update(rgname, accountName, new Sku("P1")),
                    "InvalidSkuId");
            }
        }

        [Fact]
        public void CognitiveServicesDeleteAccountErrorTest()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient = CognitiveServicesManagementTestUtilities.GetResourceManagementClient(context, handler);
                var cognitiveServicesMgmtClient = CognitiveServicesManagementTestUtilities.GetCognitiveServicesManagementClient(context, handler);

                // Create resource group
                var rgname = CognitiveServicesManagementTestUtilities.CreateResourceGroup(resourcesClient);

                // try to delete non-existent account
                CognitiveServicesManagementTestUtilities.ValidateExpectedException(
                    () => cognitiveServicesMgmtClient.Accounts.Delete("NotExistedRG", "nonExistedAccountName"),
                    "ResourceGroupNotFound");
            }
        }

        [Fact]
        public void CognitiveServicesAccountKeysErrorTest()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient = CognitiveServicesManagementTestUtilities.GetResourceManagementClient(context, handler);
                var cognitiveServicesMgmtClient = CognitiveServicesManagementTestUtilities.GetCognitiveServicesManagementClient(context, handler);

                // Create resource group
                var rgname = CognitiveServicesManagementTestUtilities.CreateResourceGroup(resourcesClient);

                CognitiveServicesManagementTestUtilities.ValidateExpectedException(
                    () => cognitiveServicesMgmtClient.Accounts.ListKeys("NotExistedRG", "nonExistedAccountName"),
                    "ResourceGroupNotFound");

                CognitiveServicesManagementTestUtilities.ValidateExpectedException(
                    () => cognitiveServicesMgmtClient.Accounts.ListKeys(rgname, "nonExistedAccountName"),
                    "ResourceNotFound");
            }
        }

        [Fact]
        public void CognitiveServicesEnumerateSkusErrorTest()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient = CognitiveServicesManagementTestUtilities.GetResourceManagementClient(context, handler);
                var cognitiveServicesMgmtClient = CognitiveServicesManagementTestUtilities.GetCognitiveServicesManagementClient(context, handler);

                // Create resource group
                var rgname = CognitiveServicesManagementTestUtilities.CreateResourceGroup(resourcesClient);

                CognitiveServicesManagementTestUtilities.ValidateExpectedException(
                    () => cognitiveServicesMgmtClient.Accounts.ListSkus("NotExistedRG", "nonExistedAccountName"),
                    "ResourceGroupNotFound");

                CognitiveServicesManagementTestUtilities.ValidateExpectedException(
                    () => cognitiveServicesMgmtClient.Accounts.ListSkus(rgname, "nonExistedAccountName"),
                    "ResourceNotFound");
            }
        }

        [Fact]
        public void CognitiveServicesCheckSkuAvailabilityTest()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient = CognitiveServicesManagementTestUtilities.GetResourceManagementClient(context, handler);
                var cognitiveServicesMgmtClient = CognitiveServicesManagementTestUtilities.GetCognitiveServicesManagementClient(context, handler);

                var skus = cognitiveServicesMgmtClient.CheckSkuAvailability.List(
                    location: "westus",
                    skus: new List<string>() { "S0" },
                    kind: "Face",
                    type: $"{c_resourceNamespace}/{c_resourceType}");

                Assert.NotNull(skus);
                Assert.NotNull(skus.Value);
                Assert.True(skus.Value.Count > 0);
            }
        }

        [Fact]
        public void CognitiveServicesResourceSkusListTest()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient = CognitiveServicesManagementTestUtilities.GetResourceManagementClient(context, handler);
                var cognitiveServicesMgmtClient = CognitiveServicesManagementTestUtilities.GetCognitiveServicesManagementClient(context, handler);

                var skus = cognitiveServicesMgmtClient.ResourceSkus.List();

                Assert.True(skus.Any(), "Assert that the array of skus has at least 1 member.");
                Assert.True(skus.Any(sku => sku.Kind == "Face"), "Assert that the sku list at least contains one Face sku.");
                Assert.True(skus.Any(sku => sku.Name == "F0"), "Assert that the sku list at least contains one F0 sku.");
                Assert.True(skus.Any(sku => sku.Locations != null), "Assert that the sku list has non null location info in it.");
                Assert.True(skus.All(sku => sku.Locations.Count == 1), "There should be exactly one location info per entry.");
            }
        }

        [Fact]
        public void CognitiveServicesAccountMinMaxNameLengthTest()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient = CognitiveServicesManagementTestUtilities.GetResourceManagementClient(context, handler);
                var cognitiveServicesMgmtClient = CognitiveServicesManagementTestUtilities.GetCognitiveServicesManagementClient(context, handler);

                // Create resource group
                var rgname = CognitiveServicesManagementTestUtilities.CreateResourceGroup(resourcesClient);

                var parameters = new CognitiveServicesAccountCreateParameters
                {
                    Sku = new Sku { Name = "S0" },
                    Kind = "Face",
                    Location = CognitiveServicesManagementTestUtilities.DefaultLocation,
                    Properties = new object(),
                };

                var minName = "zz";
                var maxName = "AcadAcadAcadAcadAcadAcadAcadAcadAcadAcadAcadAcadAcadAcadAcadAcad";

                var minAccount = cognitiveServicesMgmtClient.Accounts.Create(rgname, minName, parameters);
                var maxAccount = cognitiveServicesMgmtClient.Accounts.Create(rgname, maxName, parameters);

                Assert.Equal(minName, minAccount.Name);
                Assert.Equal(maxName, maxAccount.Name);
            }
        }
    }
}


text:
const
    pug = require('pug'),
    TransformStream = require('stream').Transform,
    util = require('../util')

class Stream extends TransformStream {
    constructor(opts) {
        super(opts)
        this.opts = opts || {}
    }

    _transform(chunk, enc, cb) {

        if (!chunk.length) return cb()

        try {

            let opts = this.opts,
                nameFn

            if (this.curFilePath) {
                if (opts.name && util.isFunction(opts.name)) {
                    nameFn = opts.name
                    opts.name = nameFn(this.curFilePath)
                }
            }

            this.push(pug.compileClient(chunk.toString(), opts))

            nameFn && (opts.name = nameFn)

            cb()

        } catch (ex) {
            cb(ex)
        }
    }
}

module.exports = opts => new Stream(opts)


text:
package org.artifactory.io;

import org.apache.commons.io.input.ProxyInputStream;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author Yoav Landman
 */
public class NonClosingInputStream extends ProxyInputStream {

    public NonClosingInputStream(InputStream proxy) {
        super(proxy);
    }

    /**
     * Does nothing!
     *
     * @throws IOException
     */
    @Override
    public void close() throws IOException {
        //Do not close the stream, since we need to continue processing it -
        //it will be close by the caller
    }

    /**
     * Forces the stream to be closed
     *
     * @throws IOException
     */
    public void forceClose() throws IOException {
        super.close();
    }
}


text:
'use strict';

describe('nosql', function () {

  require('./common');
  require('./adapters');

});


text:
/*	$NetBSD: util.h,v 1.3 2012/06/05 00:39:57 christos Exp $	*/

/* Id: util.h,v 1.1 2003/06/04 00:27:09 marka Exp  */
/*
 * Copyright (c) 2000,2001 Japan Network Information Center.
 * All rights reserved.
 *
 * By using this file, you agree to the terms and conditions set forth bellow.
 *
 * 			LICENSE TERMS AND CONDITIONS
 *
 * The following License Terms and Conditions apply, unless a different
 * license is obtained from Japan Network Information Center ("JPNIC"),
 * a Japanese association, Kokusai-Kougyou-Kanda Bldg 6F, 2-3-4 Uchi-Kanda,
 * Chiyoda-ku, Tokyo 101-0047, Japan.
 *
 * 1. Use, Modification and Redistribution (including distribution of any
 *    modified or derived work) in source and/or binary forms is permitted
 *    under this License Terms and Conditions.
 *
 * 2. Redistribution of source code must retain the copyright notices as they
 *    appear in each source code file, this License Terms and Conditions.
 *
 * 3. Redistribution in binary form must reproduce the Copyright Notice,
 *    this License Terms and Conditions, in the documentation and/or other
 *    materials provided with the distribution.  For the purposes of binary
 *    distribution the "Copyright Notice" refers to the following language:
 *    "Copyright (c) 2000-2002 Japan Network Information Center.  All rights reserved."
 *
 * 4. The name of JPNIC may not be used to endorse or promote products
 *    derived from this Software without specific prior written approval of
 *    JPNIC.
 *
 * 5. Disclaimer/Limitation of Liability: THIS SOFTWARE IS PROVIDED BY JPNIC
 *    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 *    PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL JPNIC BE LIABLE
 *    FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 *    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 *    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 *    BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 *    WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 *    OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 *    ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 */

#ifndef IDN_IDNCONV_UTIL_H
#define IDN_IDNCONV_UTIL_H 1

#include <idn/res.h>

#define IDNCONV_LOCALBUF_SIZE	512

typedef struct {
	char	*str;
	size_t	size;
	char	local_buf[IDNCONV_LOCALBUF_SIZE];
} idnconv_strbuf_t;

extern idn_result_t	selective_encode(idn_resconf_t conf,
					 idn_action_t actions, char *from,
					 char *to, int tolen);
extern idn_result_t	selective_decode(idn_resconf_t conf,
					 idn_action_t actions, char *from,
					 char *to, int tolen);
extern void		set_defaults(idn_resconf_t conf);
extern void		load_conf_file(idn_resconf_t conf, const char *file);
extern void		set_encoding_alias(const char *encoding_alias);
extern void		set_localcode(idn_resconf_t conf, const char *code);
extern void		set_idncode(idn_resconf_t conf, const char *code);
extern void		set_delimitermapper(idn_resconf_t conf,
					    unsigned long *delimiters,
					    int ndelimiters);
extern void		set_localmapper(idn_resconf_t conf,
					char **mappers, int nmappers);
extern void		set_nameprep(idn_resconf_t conf, char *version);
extern void		set_mapper(idn_resconf_t conf,
				   char **mappers, int nmappers);
extern void		set_normalizer(idn_resconf_t conf,
				       char **normalizer, int nnormalizer);
extern void		set_prohibit_checkers(idn_resconf_t conf,
					      char **prohibits,
					      int nprohibits);
extern void		set_unassigned_checkers(idn_resconf_t conf,
						char **unassigns,
						int nunassigns);
extern void		errormsg(const char *fmt, ...);
extern void		strbuf_init(idnconv_strbuf_t *buf);
extern void		strbuf_reset(idnconv_strbuf_t *buf);
extern char		*strbuf_get(idnconv_strbuf_t *buf);
extern size_t		strbuf_size(idnconv_strbuf_t *buf);
extern char		*strbuf_copy(idnconv_strbuf_t *buf, const char *str);
extern char		*strbuf_append(idnconv_strbuf_t *buf, const char *str);
extern char		*strbuf_alloc(idnconv_strbuf_t *buf, size_t size);
extern char		*strbuf_double(idnconv_strbuf_t *buf);
extern char		*strbuf_getline(idnconv_strbuf_t *buf, FILE *fp);

#endif /* IDN_IDNCONV_UTIL_H */


text:
/*
 * Decompiled with CFR 0_79.
 *
 * Could not load the following classes:
 *  android.app.Activity
 *  android.bluetooth.BluetoothAdapter
 *  android.bluetooth.BluetoothDevice
 *  android.content.BroadcastReceiver
 *  android.content.Context
 *  android.content.Intent
 *  android.content.IntentFilter
 *  android.content.res.Resources
 *  android.os.Bundle
 *  android.os.Parcelable
 *  android.util.Log
 *  android.view.View
 *  android.view.View$OnClickListener
 *  android.widget.AdapterView
 *  android.widget.AdapterView$OnItemClickListener
 *  android.widget.ArrayAdapter
 *  android.widget.Button
 *  android.widget.ListAdapter
 *  android.widget.ListView
 *  android.widget.TextView
 */
package com.SixClawWorm.application;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.SixClawWorm.utils.ExitApplication;
import com.SixClawWorm.utils.Param;
import java.util.Iterator;
import java.util.Set;

public class DeviceListActivity
extends Activity {
    private static final boolean D = 1;
    public static String EXTRA_DEVICE_ADDRESS = "device_address";
    private static final String TAG = "DeviceListActivity";
    private BluetoothAdapter mBtAdapter;
    private AdapterView.OnItemClickListener mDeviceClickListener;
    private ArrayAdapter<String> mNewDevicesArrayAdapter;
    private ArrayAdapter<String> mPairedDevicesArrayAdapter;
    private final BroadcastReceiver mReceiver;

    public DeviceListActivity() {
        this.mDeviceClickListener = new AdapterView.OnItemClickListener(){

            public void onItemClick(AdapterView<?> adapterView22, View view, int adapterView22, long adapterView22) {
                DeviceListActivity.this.mBtAdapter.cancelDiscovery();
                String string = ((TextView)view).getText().toString();
                try {
                    String string2;
                    Param.address = string2 = string.substring(-17 + string.length());
                    Intent intent = new Intent();
                    intent.putExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS, string2);
                    DeviceListActivity.this.setResult(-1, intent);
                    DeviceListActivity.this.finish();
                    return;
                }
                catch (Exception var8_5) {
                    var8_5.fillInStackTrace();
                    return;
                }
            }
        };
        this.mReceiver = new BroadcastReceiver(){

            /*
             * Enabled aggressive block sorting
             */
            public void onReceive(Context context, Intent intent) {
                String string = intent.getAction();
                if ("android.bluetooth.device.action.FOUND".equals(string)) {
                    BluetoothDevice bluetoothDevice = (BluetoothDevice)intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
                    if (bluetoothDevice.getBondState() == 12) return;
                    DeviceListActivity.this.mNewDevicesArrayAdapter.add((Object)(String.valueOf(bluetoothDevice.getName()) + "\n" + bluetoothDevice.getAddress()));
                    return;
                }
                if (!"android.bluetooth.adapter.action.DISCOVERY_FINISHED".equals(string)) return;
                DeviceListActivity.this.setProgressBarIndeterminateVisibility(false);
                DeviceListActivity.this.setTitle(2130968584);
                if (DeviceListActivity.this.mNewDevicesArrayAdapter.getCount() != 0) return;
                String string2 = DeviceListActivity.this.getResources().getText(2130968586).toString();
                DeviceListActivity.this.mNewDevicesArrayAdapter.add((Object)string2);
            }
        };
    }

    private void doDiscovery() {
        Log.d((String)"DeviceListActivity", (String)"doDiscovery()");
        this.setProgressBarIndeterminateVisibility(true);
        this.setTitle(2130968583);
        this.findViewById(2131099660).setVisibility(0);
        if (this.mBtAdapter.isDiscovering()) {
            this.mBtAdapter.cancelDiscovery();
        }
        this.mBtAdapter.startDiscovery();
    }

    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        this.requestWindowFeature(5);
        this.setContentView(2130903043);
        this.setResult(0);
        ExitApplication.getInstance().addActivity((Activity)this);
        ((Button)this.findViewById(2131099662)).setOnClickListener((View.OnClickListener)new View.OnClickListener(){

            public void onClick(View view) {
                DeviceListActivity.this.doDiscovery();
                view.setVisibility(8);
            }
        });
        this.mPairedDevicesArrayAdapter = new ArrayAdapter((Context)this, 2130903044);
        this.mNewDevicesArrayAdapter = new ArrayAdapter((Context)this, 2130903044);
        ListView listView = (ListView)this.findViewById(2131099659);
        listView.setAdapter(this.mPairedDevicesArrayAdapter);
        listView.setOnItemClickListener(this.mDeviceClickListener);
        ListView listView2 = (ListView)this.findViewById(2131099661);
        listView2.setAdapter(this.mNewDevicesArrayAdapter);
        listView2.setOnItemClickListener(this.mDeviceClickListener);
        IntentFilter intentFilter = new IntentFilter("android.bluetooth.device.action.FOUND");
        this.registerReceiver(this.mReceiver, intentFilter);
        IntentFilter intentFilter2 = new IntentFilter("android.bluetooth.adapter.action.DISCOVERY_FINISHED");
        this.registerReceiver(this.mReceiver, intentFilter2);
        this.mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        Set set = this.mBtAdapter.getBondedDevices();
        if (set.size() > 0) {
            this.findViewById(2131099658).setVisibility(0);
            Iterator iterator = set.iterator();
            do {
                if (!iterator.hasNext()) {
                    return;
                }
                BluetoothDevice bluetoothDevice = (BluetoothDevice)iterator.next();
                this.mPairedDevicesArrayAdapter.add((Object)(String.valueOf(bluetoothDevice.getName()) + "\n" + bluetoothDevice.getAddress()));
            } while (true);
        }
        String string = this.getResources().getText(2130968585).toString();
        this.mPairedDevicesArrayAdapter.add((Object)string);
    }

    protected void onDestroy() {
        super.onDestroy();
        if (this.mBtAdapter != null) {
            this.mBtAdapter.cancelDiscovery();
        }
        this.unregisterReceiver(this.mReceiver);
    }

}


text:
#pragma once
#include <aws/macie2/Macie2_EXPORTS.h>
#include <aws/macie2/model/SearchResourcesComparator.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/macie2/model/SearchResourcesTagCriterionPair.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace Macie2
{
namespace Model
{

  /**
   *
Specifies a tag-based filter condition that determines which Amazon Web
   * Services resources are included or excluded from the query
   * results.

See Also:
   AWS
   * API Reference

   */
  class AWS_MACIE2_API SearchResourcesTagCriterion
  {
  public:
    SearchResourcesTagCriterion();
    SearchResourcesTagCriterion(Aws::Utils::Json::JsonView jsonValue);
    SearchResourcesTagCriterion& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The operator to use in the condition. Valid values are EQ (equals) and NE
     * (not equals).

     */
    inline const SearchResourcesComparator& GetComparator() const{ return m_comparator; }

    /**
     *
The operator to use in the condition. Valid values are EQ (equals) and NE
     * (not equals).

     */
    inline bool ComparatorHasBeenSet() const { return m_comparatorHasBeenSet; }

    /**
     *
The operator to use in the condition. Valid values are EQ (equals) and NE
     * (not equals).

     */
    inline void SetComparator(const SearchResourcesComparator& value) { m_comparatorHasBeenSet = true; m_comparator = value; }

    /**
     *
The operator to use in the condition. Valid values are EQ (equals) and NE
     * (not equals).

     */
    inline void SetComparator(SearchResourcesComparator&& value) { m_comparatorHasBeenSet = true; m_comparator = std::move(value); }

    /**
     *
The operator to use in the condition. Valid values are EQ (equals) and NE
     * (not equals).

     */
    inline SearchResourcesTagCriterion& WithComparator(const SearchResourcesComparator& value) { SetComparator(value); return *this;}

    /**
     *
The operator to use in the condition. Valid values are EQ (equals) and NE
     * (not equals).

     */
    inline SearchResourcesTagCriterion& WithComparator(SearchResourcesComparator&& value) { SetComparator(std::move(value)); return *this;}

    /**
     *
The tag keys, tag values, or tag key and value pairs to use in the
     * condition.

     */
    inline const Aws::Vector<SearchResourcesTagCriterionPair>& GetTagValues() const{ return m_tagValues; }

    /**
     *
The tag keys, tag values, or tag key and value pairs to use in the
     * condition.

     */
    inline bool TagValuesHasBeenSet() const { return m_tagValuesHasBeenSet; }

    /**
     *
The tag keys, tag values, or tag key and value pairs to use in the
     * condition.

     */
    inline void SetTagValues(const Aws::Vector<SearchResourcesTagCriterionPair>& value) { m_tagValuesHasBeenSet = true; m_tagValues = value; }

    /**
     *
The tag keys, tag values, or tag key and value pairs to use in the
     * condition.

     */
    inline void SetTagValues(Aws::Vector<SearchResourcesTagCriterionPair>&& value) { m_tagValuesHasBeenSet = true; m_tagValues = std::move(value); }

    /**
     *
The tag keys, tag values, or tag key and value pairs to use in the
     * condition.

     */
    inline SearchResourcesTagCriterion& WithTagValues(const Aws::Vector<SearchResourcesTagCriterionPair>& value) { SetTagValues(value); return *this;}

    /**
     *
The tag keys, tag values, or tag key and value pairs to use in the
     * condition.

     */
    inline SearchResourcesTagCriterion& WithTagValues(Aws::Vector<SearchResourcesTagCriterionPair>&& value) { SetTagValues(std::move(value)); return *this;}

    /**
     *
The tag keys, tag values, or tag key and value pairs to use in the
     * condition.

     */
    inline SearchResourcesTagCriterion& AddTagValues(const SearchResourcesTagCriterionPair& value) { m_tagValuesHasBeenSet = true; m_tagValues.push_back(value); return *this; }

    /**
     *
The tag keys, tag values, or tag key and value pairs to use in the
     * condition.

     */
    inline SearchResourcesTagCriterion& AddTagValues(SearchResourcesTagCriterionPair&& value) { m_tagValuesHasBeenSet = true; m_tagValues.push_back(std::move(value)); return *this; }

  private:

    SearchResourcesComparator m_comparator;
    bool m_comparatorHasBeenSet;

    Aws::Vector<SearchResourcesTagCriterionPair> m_tagValues;
    bool m_tagValuesHasBeenSet;
  };

} // namespace Model
} // namespace Macie2
} // namespace Aws