text:
using DigitalPlatform.IO;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace dp2Command.Service
{
    /// <summary>
    /// 用户数据库
    /// </summary>
    public sealed class WxUserDatabase
    {
        private static readonly WxUserDatabase _db = new WxUserDatabase();
        public static WxUserDatabase Current
        {
            get
            {
                return _db;
            }
        }

        MongoClient _mongoClient = null;
        IMongoDatabase _database = null;
        string _wxUserDbName = "";

        IMongoCollection<WxUserItem> _wxUserCollection = null;
        public IMongoCollection<WxUserItem> wxUserCollection
        {
            get
            {
                return this._wxUserCollection;
            }
        }

        // 初始化
        public void Open(
            string strMongoDbConnStr,
            string strInstancePrefix)
        {
            if (string.IsNullOrEmpty(strMongoDbConnStr) == true)
                throw new ArgumentException("strMongoDbConnStr 参数值不应为空");

            if (string.IsNullOrEmpty(strInstancePrefix) == false)
                strInstancePrefix = strInstancePrefix + "_";
            _wxUserDbName = strInstancePrefix + "user";

            this._mongoClient = new MongoClient(strMongoDbConnStr);
            this._database = this._mongoClient.GetDatabase(this._wxUserDbName);

            //图书馆点对点账号
            _wxUserCollection = this._database.GetCollection<WxUserItem>("item");

            // todo 创建索引
            bool bExist = false;
            var indexes = _wxUserCollection.Indexes.ListAsync().Result.ToListAsync().Result;
            foreach (BsonDocument doc in indexes)
            {
            }
            // _logCollection.DropAllIndexes();
            if (bExist == false)
            {
                CreateIndex();
            }

        }

        // 创建索引
        public void CreateIndex()
        {
            var options = new CreateIndexOptions() { Unique = false };  //不唯一,一个微信用户可能对应多个读者
            _wxUserCollection.Indexes.CreateOne(
                Builders<WxUserItem>.IndexKeys.Ascending("weixinId"),
                options);

        }

        // 清除集合内的全部内容
        public async Task Clear()
        {
            if (_wxUserCollection == null)
            {
                throw new Exception("访问日志 mongodb 集合尚未初始化");
            }

            // https://docs.mongodb.org/getting-started/csharp/remove/
            var filter = new BsonDocument();
            await _wxUserCollection.DeleteManyAsync(filter);
            CreateIndex();
        }

        /*
        /// <summary>
        /// 根据微信号与图书馆代码查
        /// </summary>
        /// <param name="weixinId"></param>
        /// <param name="libCode"></param>
        /// <returns></returns>
        public WxUserItem GetActive(string weixinId,string libCode)
        {
            var filter = Builders<WxUserItem>.Filter.Eq("weixinId", weixinId)
                & Builders<WxUserItem>.Filter.Eq("libCode", libCode)
                & Builders<WxUserItem>.Filter.Eq("isActive", 1);

            List<WxUserItem> list = this.wxUserCollection .Find(filter).ToList();
            if (list.Count > 0)
                return list[0];

            return null;
        }
        */
        public WxUserItem GetActiveOrFirst(string weixinId, string libCode)
        {
            // 先查active的
            var filter = Builders<WxUserItem>.Filter.Eq("weixinId", weixinId)
                & Builders<WxUserItem>.Filter.Eq("libCode", libCode)
                & Builders<WxUserItem>.Filter.Eq("isActive", 1);

            List<WxUserItem> list = this.wxUserCollection.Find(filter).ToList();
            if (list.Count > 0)
                return list[0];

            // 没有查first
            filter = Builders<WxUserItem>.Filter.Eq("weixinId", weixinId)
                     & Builders<WxUserItem>.Filter.Eq("libCode", libCode);

            list = this.wxUserCollection.Find(filter).ToList();
            if (list.Count > 0)
                return list[0];

            return null;
        }

        public WxUserItem GetOneOrEmptyPatron(string weixinId, string libCode,string readerBarcode)
        {
            // 先查到weixinId+libCode+readerBarcode唯一的记录
            var filter = Builders<WxUserItem>.Filter.Eq("weixinId", weixinId)
                & Builders<WxUserItem>.Filter.Eq("libCode", libCode)
                & Builders<WxUserItem>.Filter.Eq("readerBarcode", readerBarcode);
            List<WxUserItem> list = this.wxUserCollection.Find(filter).ToList();
            if (list.Count >= 1)
                return list[0];

            // 未找到查weixinId+libCode,readerBarcoe为空的记录
            filter = Builders<WxUserItem>.Filter.Eq("weixinId", weixinId)
                & Builders<WxUserItem>.Filter.Eq("libCode", libCode)
                & Builders<WxUserItem>.Filter.Eq("readerBarcode", "");
            list = this.wxUserCollection.Find(filter).ToList();
            if (list.Count >= 1)
                return list[0];

            return null;
        }

        public WxUserItem GetActive(string weixinId)
        {
            var filter = Builders<WxUserItem>.Filter.Eq("weixinId", weixinId)
                & Builders<WxUserItem>.Filter.Eq("isActive", 1);

            List<WxUserItem> list= this.wxUserCollection.Find(filter).ToList();//.ToListAsync().Result;
            if (list.Count > 1)
                throw new Exception("程序异常:微信号活动读者数量有" +list.Count+"个");

            if (list.Count == 1)
                return list[0];

            return null;
        }

        public List<WxUserItem> GetByWeixinId(string weixinId)
        {
            var filter = Builders<WxUserItem>.Filter.Eq("weixinId", weixinId);

            return this.wxUserCollection.Find(filter).ToList();//.ToListAsync().Result;
        }

        public WxUserItem GetOneByWeixinId(string weixinId)
        {
            var filter = Builders<WxUserItem>.Filter.Eq("weixinId", weixinId);

            List<WxUserItem>list= this.wxUserCollection.Find(filter).ToList();//.ToListAsync().Result;
            if (list.Count > 0)
                return list[0];

            return null;
        }

        /// <summary>
        /// 查找所有用户
        /// </summary>
        /// <returns></returns>
        public List<WxUserItem> GetUsers()
        {
            IFindFluent<WxUserItem, WxUserItem> f = this.wxUserCollection.Find(new BsonDocument());
            if (f != null)
                return f.ToList();

            return null;
        }

        public WxUserItem Add(WxUserItem item)
        {
            //item.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");

            this.wxUserCollection.InsertOne(item);

            return item;
        }

        // 更新
        public long Update(WxUserItem item)
        {
            IMongoCollection<WxUserItem> collection = this.wxUserCollection;

            var filter = Builders<WxUserItem>.Filter.Eq("id", item.id);
            var update = Builders<WxUserItem>.Update
                .Set("weixinId", item.weixinId)
                .Set("readerBarcode", item.readerBarcode)
                .Set("readerName", item.readerName)
                .Set("libCode", item.libCode)
                .Set("libUserName", item.libUserName)
                .Set("libName", item.libName)
                .Set("createTime", item.createTime)
                .Set("updateTime", item.updateTime)
                .Set("xml", item.xml)
                .Set("refID", item.refID)
                .Set("isActive", item.isActive);

            UpdateResult ret = collection.UpdateOne(filter, update);
            return ret.ModifiedCount;
        }

        public WxUserItem GetById(String id)
        {
            if (string.IsNullOrEmpty(id) == true || id == "null")
                return null;
            IMongoCollection<WxUserItem> collection = this.wxUserCollection;
            var filter = Builders<WxUserItem>.Filter.Eq("id", id);
            List<WxUserItem> list = this.wxUserCollection.Find(filter).ToList();
            if (list.Count > 0)
            {
                return list[0];
            }
            return null;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="item"></param>
        public void Delete(String id)
        {
            if (string.IsNullOrEmpty(id) == true || id=="null")
                return;

            IMongoCollection<WxUserItem> collection = this.wxUserCollection;
            var filter = Builders<WxUserItem>.Filter.Eq("id", id);

            // 检查一下是否被删除读者是否为默认读者,如果是,把自动将默认值设了第一个读者上。
            List<WxUserItem> list = this.wxUserCollection.Find(filter).ToList();
            string weixinId = "";
            if (list.Count > 0)
            {
                weixinId = list[0].weixinId;
            }

            // 先删除
            collection.DeleteOne(filter);

            // 自动将第一个设为默认的
            WxUserItem newUserItem = this.GetOneByWeixinId(weixinId);
            if (newUserItem != null)
                this.SetActive(newUserItem);
        }

        public void SetActive(WxUserItem item)
        {
            this.SetActive(item.weixinId, item.id);
        }

        public void SetActive(string weixinId,string id)
        {
            if (string.IsNullOrEmpty(weixinId) == true || weixinId=="null")
                return;

            if (string.IsNullOrEmpty(weixinId) == true || id=="null")
                return;

            IMongoCollection<WxUserItem> collection = this.wxUserCollection;

            // 先将该微信用户的所有绑定读者都设为非活动
            var filter = Builders<WxUserItem>.Filter.Eq("weixinId", weixinId);
            var update = Builders<WxUserItem>.Update
                .Set("isActive", 0)
                .Set("updateTime", DateTimeUtil.DateTimeToString(DateTime.Now));
            UpdateResult ret = collection.UpdateMany(filter, update);

            // 再将参数传入的记录设为活动状态
            filter = Builders<WxUserItem>.Filter.Eq("id",id);
            update = Builders<WxUserItem>.Update
                .Set("isActive", 1)
                .Set("updateTime", DateTimeUtil.DateTimeToString(DateTime.Now));
            ret = collection.UpdateMany(filter, update);
        }

    }
    public class WxUserItem
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string id { get; private set; }

        public string weixinId { get; set; } // 绑定必备
        public string readerBarcode { get; set; }
        public string readerName { get; set; }

        public string libCode { get; set; } // 绑定必备
        public string libUserName { get; set; }// 绑定必备
        public string libName { get; set; }// 绑定必备

        public string createTime { get; set; } // 创建时间
        public string updateTime { get; set; } // 更校报时间

        public string xml { get; set; }
        public string refID { get; set; }

        public int isActive = 0;

        // 绑定必备
        public string prefix { get; set; }  //必须设为属性,才能在前端传值。
        public string word  { get; set; }
        public string password  { get; set; }

        public string fullWord { get; set; } // 服务器用fullWord将strPrefix:strWord存在一起
    }

}


text:
SharpCompress
=============

Github mirror of http://sharpcompress.codeplex.com

SharpCompress is a compression library for .NET/Mono/Silverlight/WP7 that can unrar, un7zip, unzip, untar unbzip2 and ungzip with forward-only reading and file random access APIs. Write support for zip/tar/bzip2/gzip are implemented.

The major feature is support for non-seekable streams so large files can be processed on the fly (i.e. download stream).

A Simple Request

Hi everyone. I hope you're using SharpCompress and finding it useful. Please give me feedback on what you'd like to see changed especially as far as usability goes. New feature suggestions are always welcome as well. I would also like to know what projects SharpCompress is being used in. I like seeing how it is used to give me ideas for future versions. Thanks!

Want to contribute?

I'm always looking for help or ideas. Please submit code or email with ideas. Unfortunately, just letting me know you'd like to help is not enough because I really have no overall plan of what needs to be done. I'll definitely accept code submissions and add you as a member of the project!

TODOs (always lots):
* RAR 5 support
* 7Zip writing
* Zip64
* Multi-volume Zip support.

Version 0.11:
==============
- Been over a year, contains mainly fixes from contributors!
- Possible breaking change: ArchiveEncoding is UTF8 by default now.
- TAR supports writing long names using longlink
- RAR Protect Header added

Version 0.10.3:
==============
- Finally fixed Disposal issue when creating a new archive with the Archive API

Version 0.10.2:
==============
- Fixed Rar Header reading for invalid extended time headers.
- Windows Store assembly is now strong named
- Known issues with Long Tar names being worked on
- Updated to VS2013
	- Portable targets SL5 and Windows Phone 8 (up from SL4 and WP7)

Version 0.10.1:
==============
- Fixed 7Zip extraction performance problem

Version 0.10:
==============
- Added support for RAR Decryption (thanks to https://github.com/hrasyid)
- Embedded some BouncyCastle crypto classes to allow RAR Decryption and Winzip AES Decryption in Portable and Windows Store DLLs
- Built in Release (I think)

Some Help/Discussion:
https://sharpcompress.codeplex.com/discussions

7Zip implementation based on: https://code.google.com/p/managed-lzma/

LICENSE
Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

redpajama_set_name: RedPajamaGithub


text:
package digitalocean

import (
	"fmt"
	"log"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/JamesClonk/easy-vpn/config"
	"github.com/stretchr/testify/assert"
)

var testConfig *config.Config

func init() {
	var err error
	testConfig, err = config.LoadConfiguration("../../fixtures/config_test.toml")
	if err != nil {
		log.Println(err)
	}
}

func getTestServer(code int, body string) *httptest.Server {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(code)
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprint(w, body)
	}))
	baseUrl = ts.URL
	return ts
}

func Test_Provider_Digitalocean_GetProviderName(t *testing.T) {
	d := DO{Config: testConfig}
	if assert.NotNil(t, d) {
		assert.Equal(t, "digitalocean", d.GetProviderName())
	}
}

func Test_Provider_Digitalocean_GetConfig(t *testing.T) {
	d := DO{Config: testConfig}
	cfg := d.GetConfig()
	if assert.NotNil(t, cfg) {
		assert.Equal(t, testConfig, cfg)
	}
}

func Test_Provider_Digitalocean_GetInstalledSshKeys_Error(t *testing.T) {
	server := getTestServer(http.StatusNotAcceptable, `{error-message}`)
	defer server.Close()

	d := DO{Config: testConfig}

	keys, err := d.GetInstalledSshKeys()
	assert.Nil(t, keys)
	if assert.NotNil(t, err) {
		assert.Equal(t, `{error-message}`, err.Error())
	}
}

func Test_Provider_Digitalocean_GetInstalledSshKeys_NoKeys(t *testing.T) {
	server := getTestServer(http.StatusOK,
		`{"ssh_keys": [], "links": {}, "meta": {"total": 0}}`)
	defer server.Close()

	d := DO{Config: testConfig}

	keys, err := d.GetInstalledSshKeys()
	if err != nil {
		t.Error(err)
	}
	assert.Nil(t, keys)
}

func Test_Provider_Digitalocean_GetInstalledSshKeys_Keys(t *testing.T) {
	server := getTestServer(http.StatusOK,
		`{"ssh_keys": [
			{"id": 1, "fingerprint": "who cares", "public_key": "aaaa", "name": "alpha"},
			{"id": 2, "fingerprint": "who cares", "public_key": "bbbb", "name": "beta"},
			{"id": 3, "fingerprint": "who cares", "public_key": "cccc", "name": "charlie"}
			], "links": {}, "meta": {"total": 3}
		}`)
	defer server.Close()

	d := DO{Config: testConfig}

	keys, err := d.GetInstalledSshKeys()
	if err != nil {
		t.Error(err)
	}
	if assert.NotNil(t, keys) {
		assert.Equal(t, 3, len(keys))
		// keys can be in random order
		for _, key := range keys {
			switch key.Id {
			case "1":
				assert.Equal(t, "aaaa", key.Key)
			case "2":
				assert.Equal(t, "bbbb", key.Key)
			case "3":
				assert.Equal(t, "charlie", key.Name)
			default:
				t.Error("Unknown Key Id")
			}
		}
	}
}

func Test_Provider_Digitalocean_InstallNewSshKey_Error(t *testing.T) {
	server := getTestServer(http.StatusNotAcceptable, `{error-message}`)
	defer server.Close()

	d := DO{Config: testConfig}

	keyId, err := d.InstallNewSshKey("delta", "ddddd")
	assert.Equal(t, "", keyId)
	if assert.NotNil(t, err) {
		assert.Equal(t, `{error-message}`, err.Error())
	}
}

func Test_Provider_Digitalocean_InstallNewSshKey_NoKeyId(t *testing.T) {
	server := getTestServer(http.StatusCreated, `{error-message}`)
	defer server.Close()

	d := DO{Config: testConfig}

	keyId, err := d.InstallNewSshKey("delta", "ddddd")
	assert.Equal(t, "", keyId)
	if assert.NotNil(t, err) {
		assert.Equal(t, `{error-message}`, err.Error())
	}
}

func Test_Provider_Digitalocean_InstallNewSshKey_KeyId(t *testing.T) {
	server := getTestServer(http.StatusCreated,
		`{"ssh_key":{"id":4,"public_key":"ddddd","name":"My SSH Public Key"}}`)
	defer server.Close()

	d := DO{Config: testConfig}

	keyId, err := d.InstallNewSshKey("delta", "ddddd")
	if err != nil {
		t.Error(err)
	}
	if assert.NotNil(t, keyId) {
		assert.Equal(t, "4", keyId)
	}
}

func Test_Provider_Digitalocean_DeleteSshKey_Error(t *testing.T) {
	server := getTestServer(http.StatusNotAcceptable, `{error-message}`)
	defer server.Close()

	d := DO{Config: testConfig}

	err := d.deleteSshKey("123")
	if assert.NotNil(t, err) {
		assert.Equal(t, `{error-message}`, err.Error())
	}
}

func Test_Provider_Digitalocean_DeleteSshKey_Deleted(t *testing.T) {
	server := getTestServer(http.StatusNoContent, `{no-response?!}`)
	defer server.Close()

	d := DO{Config: testConfig}

	err := d.deleteSshKey("123")
	if err != nil {
		t.Error(err)
	}
}

func Test_Provider_Digitalocean_GetAllVMs_Error(t *testing.T) {
	server := getTestServer(http.StatusNotAcceptable, `{error-message}`)
	defer server.Close()

	d := DO{Config: testConfig}

	machines, err := d.GetAllVMs()
	assert.Nil(t, machines)
	if assert.NotNil(t, err) {
		assert.Equal(t, `{error-message}`, err.Error())
	}
}

func Test_Provider_Digitalocean_GetAllVMs_NoVMs(t *testing.T) {
	server := getTestServer(http.StatusOK, `{"droplets": [],"links": {},"meta": {"total": 0}}`)
	defer server.Close()

	d := DO{Config: testConfig}

	machines, err := d.GetAllVMs()
	if err != nil {
		t.Error(err)
	}
	assert.Nil(t, machines)
}

func Test_Provider_Digitalocean_GetAllVMs_VMs(t *testing.T) {
	server := getTestServer(http.StatusOK, `{"droplets": [{
    "id": 1111,
    "name": "example.com",
    "memory": 512,
    "disk": 20,
    "status": "active",
    "image": {
        "id": 6918990,
        "name": "14.04 x64",
        "distribution": "Ubuntu",
        "slug": "ubuntu-14-04-x64"
    },
    "size_slug": "512mb",
    "networks": {
        "v4": [{
            "ip_address": "104.236.32.111",
            "netmask": "255.255.192.0",
            "gateway": "104.236.0.1",
            "type": "public"
        }],
        "v6": [{}]
    },
    "region": {
        "name": "New York 3",
        "slug": "nyc3"
    }
},{
    "id": 7777,
    "name": "example.com",
    "memory": 512,
    "status": "active",
    "image": {
        "id": 123,
        "distribution": "CentOS",
        "slug": "centos-x64"
    },
    "size_slug": "512mb",
    "networks": {
        "v4": [{
            "ip_address": "104.236.32.999",
            "netmask": "255.255.192.0",
            "gateway": "104.236.0.1",
            "type": "public"
        }]
    },
    "region": {
        "name": "New York 2",
        "slug": "nyc2"
    }
},{
    "id": 9999,
    "name": "test.com",
    "memory": 1024,
    "status": "stopped",
    "image": {
        "slug": "ubuntu-14-10-x64"
    },
    "networks": {"v4": [{"ip_address": "104.236.32.777"}]},
    "region": {
        "name": "New York 1",
        "slug": "nyc1"
    }
}],"links": {},"meta": {"total": 3}}`)
	defer server.Close()

	d := DO{Config: testConfig}

	machines, err := d.GetAllVMs()
	if err != nil {
		t.Error(err)
	}
	if assert.NotNil(t, machines) {
		assert.Equal(t, 3, len(machines))
		// machines can be in random order
		for _, vm := range machines {
			switch vm.Id {
			case "1111":
				assert.Equal(t, "example.com", vm.Name)
				assert.Equal(t, "ubuntu-14-04-x64", vm.OS)
				assert.Equal(t, "nyc3", vm.Region)
				assert.Equal(t, "active", vm.Status)
			case "7777":
				assert.Equal(t, "nyc2", vm.Region)
				assert.Equal(t, "104.236.32.999", vm.IP)
				assert.Equal(t, "centos-x64", vm.OS)
			case "9999":
				assert.Equal(t, "test.com", vm.Name)
				assert.Equal(t, "stopped", vm.Status)
				assert.Equal(t, "104.236.32.777", vm.IP)
			default:
				t.Error("Unknown VM Id")
			}
		}
	}
}

func Test_Provider_Digitalocean_CreateVM_Error(t *testing.T) {
	server := getTestServer(http.StatusNotAcceptable, `{error-message}`)
	defer server.Close()

	d := DO{Config: testConfig}

	vmId, err := d.CreateVM("test-vm", "test-os", "test-size", "test-region", "test-key-id")
	assert.Equal(t, "", vmId)
	if assert.NotNil(t, err) {
		assert.Equal(t, `{error-message}`, err.Error())
	}
}

func Test_Provider_Digitalocean_CreateVM_NoVMId(t *testing.T) {
	server := getTestServer(http.StatusAccepted, `{error-message}`)
	defer server.Close()

	d := DO{Config: testConfig}

	vmId, err := d.CreateVM("test-vm", "test-os", "test-size", "test-region", "test-key-id")
	assert.Equal(t, "", vmId)
	if assert.NotNil(t, err) {
		assert.Equal(t, `{error-message}`, err.Error())
	}
}

func Test_Provider_Digitalocean_CreateVM_VMId(t *testing.T) {
	server := getTestServer(http.StatusAccepted, `{"droplet":{"id":3333,"name":"example.com","status":"new"}}`)
	defer server.Close()

	d := DO{Config: testConfig}

	vmId, err := d.CreateVM("test-vm", "test-os", "test-size", "test-region", "test-key-id")
	if err != nil {
		t.Error(err)
	}
	if assert.NotNil(t, vmId) {
		assert.Equal(t, "3333", vmId)
	}
}

func Test_Provider_Digitalocean_StartVM_Error(t *testing.T) {
	server := getTestServer(http.StatusNotAcceptable, `{error-message}`)
	defer server.Close()

	d := DO{Config: testConfig}

	err := d.StartVM("1111")
	if assert.NotNil(t, err) {
		assert.Equal(t, `{error-message}`, err.Error())
	}
}

func Test_Provider_Digitalocean_StartVM_StatusMissing(t *testing.T) {
	server := getTestServer(http.StatusCreated, `{"action":{"id":123,"???":"???"}}`)
	defer server.Close()

	d := DO{Config: testConfig}

	err := d.StartVM("1111")
	if assert.NotNil(t, err) {
		assert.Equal(t, `{"action":{"id":123,"???":"???"}}`, err.Error())
	}
}

func Test_Provider_Digitalocean_StartVM_StatusErrored(t *testing.T) {
	server := getTestServer(http.StatusCreated, `{"action":{"id":123,"status":"errored"}}`)
	defer server.Close()

	d := DO{Config: testConfig}

	err := d.StartVM("1111")
	if assert.NotNil(t, err) {
		assert.Equal(t, `{"action":{"id":123,"status":"errored"}}`, err.Error())
	}
}

func Test_Provider_Digitalocean_StartVM_VMId(t *testing.T) {
	server := getTestServer(http.StatusCreated, `{"action":{"id":456,"status":"in-progress","type":"power_on"}}`)
	defer server.Close()

	d := DO{Config: testConfig}

	err := d.StartVM("1111")
	if err != nil {
		t.Error(err)
	}
}

func Test_Provider_Digitalocean_DestroyVM_Error(t *testing.T) {
	server := getTestServer(http.StatusNotAcceptable, `{error-message}`)
	defer server.Close()

	d := DO{Config: testConfig}

	err := d.DestroyVM("1111")
	if assert.NotNil(t, err) {
		assert.Equal(t, `{error-message}`, err.Error())
	}
}

func Test_Provider_Digitalocean_DestroyVM_VMId(t *testing.T) {
	server := getTestServer(http.StatusNoContent, `{no-response?!}`)
	defer server.Close()

	d := DO{Config: testConfig}

	err := d.DestroyVM("1111")
	if err != nil {
		t.Error(err)
	}
}


text:
from django.conf import settings

def global_settings(request):
    """Setting for templates"""
    return {
        'DEBUG': settings.DEBUG,
        'BURST_CALL_ACOM': settings.BURST_CALL_ACOM,
        'ABOUT_LINK': settings.ABOUT_LINK,
        'LOGO_NAME': settings.LOGO_NAME,
        'THEME': settings.THEME,
        'NEWBC_LINK': settings.NEWBC_LINK,
        'NEWBC_IMG': settings.NEWBC_IMG,
        'NEWBC_IMG_SMALL': settings.NEWBC_IMG_SMALL,
        'FOOTER_TAGS': settings.FOOTER_TAGS,
    }


text:
package mobilita.poteri;

public interface PuoFunzionareAutomaticamente {

	void avvia();

	void spegni();
}


text:
<?php

namespace HkApps\Tests\Http\Controllers\Api;

use HkApps\App\Models\Memo;
use mpyw\Cowitter\Client as CowitterClient;

/**
 * Class MemosControllerTest.
 *
 * @package HkApps\Tests\Http\Controllers\Api
 */
class MemosControllerTest extends TestCase
{
    /**
     * Memo instance.
     *
     * @var Memo
     */
    protected $memo;

    /**
     * Set up.
     */
    public function setUp()
    {
        parent::setUp();
        $this->memo = new Memo();
    }

    /**
     * All memo data provider.
     *
     * @return array
     */
    public function allMemoDataProvider()
    {
        $data = [];
        foreach ((new Memo())->all() as $memo) {
            $data[] = [$memo];
        }

        return $data;
    }

    public function testAll()
    {
        $this
            ->get('/api/memo/all')
            ->assertResponseOk();
        $this->seeJsonEquals($this->memo->all()->toArray());
    }

    public function testAllOnBadMethod()
    {
        $this
            ->post('/api/memo/all')
            ->onBadMethodCall();
    }

    /**
     * @dataProvider allMemoDataProvider
     *
     * @param Memo $memo
     */
    public function testShow(Memo $memo)
    {
        $this->call('GET', '/api/memo/show', ['id' => $memo->id]);
        $this
            ->seeJsonEquals($memo->toArray())
            ->assertResponseOk();
    }

    public function testShowOnIdEmpty()
    {
        $this
            ->get('/api/memo/show', [])
            ->seeJsonEquals(['error' => ['message' => 'id is empty.', 'code' => 500]])
            ->assertResponseStatus(500);
    }

    public function testShowOnNotFound()
    {
        $this->call('GET', '/api/memo/show', ['id' => '1000']);
        $this
            ->seeJsonEquals(['error' => ['message' => 'Memo not found.', 'code' => 500]])
            ->assertResponseStatus(500);
    }

    public function testShowOnBadMethod()
    {
        $this
            ->post('/api/memo/show', [])
            ->onBadMethodCall();
    }

    /**
     * @dataProvider createDataProvider
     *
     * @param string $id
     * @param string $user_sn
     * @param string $user_id
     */
    public function testCreate($id, $user_sn, $user_id)
    {
        $this
            ->post('/api/memo/create', compact('id'))
            ->seeJson(compact('user_sn', 'user_id'))
            ->assertResponseOk();
    }

    /**
     * testCreate data provider.
     *
     * @return array
     */
    public function createDataProvider()
    {
        $data           = [];
        $cowitterClient = new CowitterClient(config('twitter.cowitter'));
        for ($i = 0; $i < 2; ++$i) {
            $status = 'HkApps Test at '.time().' / '.md5(uniqid(mt_rand(), true));
            /** @var \stdClass $r */
            $r      = $cowitterClient->post('statuses/update', compact('status'));
            $data[] = [
                $r->id_str,
                $r->user->screen_name,
                $r->user->id_str,
            ];
        }

        return $data;
    }

    public function testCreateOnBadMethod()
    {
        $this
            ->get('/api/memo/create')
            ->onBadMethodCall();
    }

    public function testCreateOnIdEmpty()
    {
        $this
            ->post('/api/memo/create', [])
            ->seeJsonEquals(['error' => ['message' => 'id is empty.', 'code' => 500]]);
        $this->assertResponseStatus(500);
    }

    public function testMissingMethod()
    {
        $this->callMissingMethod('/memo/test-missing-method');
    }
}


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

import com.facebook.presto.kafka.util.EmbeddedKafka;
import com.facebook.presto.tests.AbstractTestDistributedQueries;
import io.airlift.tpch.TpchTable;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;

import java.io.IOException;

import static com.facebook.presto.kafka.KafkaQueryRunner.createKafkaQueryRunner;
import static com.facebook.presto.kafka.util.EmbeddedKafka.createEmbeddedKafka;
import static io.airlift.testing.Closeables.closeAllRuntimeException;

@Test
public class TestKafkaDistributed
        extends AbstractTestDistributedQueries
{
    private final EmbeddedKafka embeddedKafka;

    public TestKafkaDistributed()
            throws Exception
    {
        this(createEmbeddedKafka());
    }

    public TestKafkaDistributed(EmbeddedKafka embeddedKafka)
            throws Exception
    {
        super(createKafkaQueryRunner(embeddedKafka, TpchTable.getTables()));
        this.embeddedKafka = embeddedKafka;
    }

    @AfterClass(alwaysRun = true)
    public void destroy()
            throws IOException
    {
        closeAllRuntimeException(queryRunner, embeddedKafka);
    }

    //
    // Kafka connector does not support table creation.
    //

    @Override
    public void testCreateTable()
            throws Exception
    {
    }

    @Override
    public void testCreateTableAsSelect()
            throws Exception
    {
    }

    @Override
    public void testCreateTableAsSelectSampled()
            throws Exception
    {
    }

    @Override
    public void testSymbolAliasing()
            throws Exception
    {
    }

    //
    // Kafka connector does not support views.
    //

    @Override
    public void testView()
            throws Exception
    {
    }

    @Override
    public void testViewMetadata()
            throws Exception
    {
    }

    //
    // Kafka connector does not insert.
    //

    @Override
    public void testInsert()
            throws Exception
    {
    }

    //
    // Kafka connector does not delete.
    //

    @Override
    public void testDelete()
            throws Exception
    {
    }

    //
    // Kafka connector does not table rename.
    //

    @Override
    public void testRenameTable()
            throws Exception
    {
    }

    //
    // Kafka connector does not table column.
    //

    @Override
    public void testRenameColumn()
            throws Exception
    {
    }
}


text:
usage="Usage: hadoop-daemon.sh [--config <conf-dir>] [--hosts hostlistfile] (start|stop) <hadoop-command> <args...>"

# if no args specified, show usage
if [ $# -le 1 ]; then
  echo $usage
  exit 1
fi

bin=`dirname "$0"`
bin=`cd "$bin"; pwd`

. "$bin"/hadoop-config.sh

# get arguments
startStop=$1
shift
command=$1
shift

hadoop_rotate_log ()
{
    log=$1;
    num=5;
    if [ -n "$2" ]; then
	num=$2
    fi
    if [ -f "$_HADOOP_DAEMON_OUT" ]; then # rotate logs
	while [ $num -gt 1 ]; do
	    prev=`expr $num - 1`
	    [ -f "$_HADOOP_DAEMON_OUT.$prev" ] && mv "$_HADOOP_DAEMON_OUT.$prev" "$_HADOOP_DAEMON_OUT.$num"
	    num=$prev
	done
	mv "$_HADOOP_DAEMON_OUT" "$_HADOOP_DAEMON_OUT.$num";
    fi
}

if [ -f "${HADOOP_CONF_DIR}/hadoop-env.sh" ]; then
  . "${HADOOP_CONF_DIR}/hadoop-env.sh"
fi

if [ "$HADOOP_IDENT_STRING" = "" ]; then
  export HADOOP_IDENT_STRING="$USER"
fi

# get log directory
if [ "$HADOOP_LOG_DIR" = "" ]; then
  export HADOOP_LOG_DIR="$HADOOP_HOME/logs"
fi
mkdir -p "$HADOOP_LOG_DIR"

if [ "$HADOOP_PID_DIR" = "" ]; then
  HADOOP_PID_DIR=/tmp
fi

# some variables
export HADOOP_LOGFILE=hadoop-$HADOOP_IDENT_STRING-$command-$HOSTNAME.log
export HADOOP_ROOT_LOGGER="INFO,DRFA"
export HADOOP_SECURITY_LOGGER="INFO,DRFAS"
export _HADOOP_DAEMON_OUT=$HADOOP_LOG_DIR/hadoop-$HADOOP_IDENT_STRING-$command-$HOSTNAME.out
export _HADOOP_DAEMON_PIDFILE=$HADOOP_PID_DIR/hadoop-$HADOOP_IDENT_STRING-$command.pid
export _HADOOP_DAEMON_DETACHED="true"
export DN_LOG_SCRIPT="$HADOOP_CONF_DIR/../hadoop_mgmt/dn_log.py"

# Set default scheduling priority
if [ "$HADOOP_NICENESS" = "" ]; then
    export HADOOP_NICENESS=0
fi

case $startStop in

  (start)

    mkdir -p "$HADOOP_PID_DIR"

    if [ -f $_HADOOP_DAEMON_PIDFILE ]; then
      if kill -0 `cat $_HADOOP_DAEMON_PIDFILE` > /dev/null 2>&1; then
        echo $command running as process `cat $_HADOOP_DAEMON_PIDFILE`.  Stop it first.
        exit 1
      fi
    fi

    if [ "$HADOOP_MASTER" != "" ]; then
      echo rsync from $HADOOP_MASTER
      rsync -a -e ssh --delete --exclude=.svn --exclude='logs/*' --exclude='contrib/hod/logs/*' $HADOOP_MASTER/ "$HADOOP_HOME"
    fi

    hadoop_rotate_log $_HADOOP_DAEMON_OUT
    echo starting $command, logging to $_HADOOP_DAEMON_OUT
    cd "$HADOOP_HOME"

    if [ $command == "tasktracker" && x$HADOOP_TASKTRACKER_CPU_CORES -ne x ]; then
        export CPU_CORES=$HADOOP_TASKTRACKER_CPU_CORES
    fi

    nice -n $HADOOP_NICENESS "$HADOOP_HOME"/bin/hadoop --config $HADOOP_CONF_DIR $command "$@" < /dev/null

    # datanode needs additional log processig daemon
    if [ $command == "datanode" ]; then
       if [ -f $DN_LOG_SCRIPT ]; then
            python $DN_LOG_SCRIPT start
       fi
    fi
    ;;

  (stop)
    # datanode needs additional log processig daemon
    if [ $command == "datanode" ]; then
       if [ -f $DN_LOG_SCRIPT ]; then
            python $DN_LOG_SCRIPT stop
       fi
    fi

    if [ -f $_HADOOP_DAEMON_PIDFILE ]; then
      if kill -0 `cat $_HADOOP_DAEMON_PIDFILE` > /dev/null 2>&1; then
        echo stopping $command
        kill `cat $_HADOOP_DAEMON_PIDFILE`
      else
        echo no $command to stop
      fi
    else
      echo no $command to stop
    fi
    ;;

  (*)
    echo $usage
    exit 1
    ;;

esac


text:
namespace pw::software_update {

class BlobStoreOpenableReader final : public OpenableReader {
 public:
  explicit constexpr BlobStoreOpenableReader(blob_store::BlobStore& blob_store)
      : blob_store_(blob_store), blob_reader_(blob_store_) {}

  Status Open() override { return blob_reader_.Open(); }
  Status Close() override { return blob_reader_.Close(); }
  bool IsOpen() override { return blob_reader_.IsOpen(); }
  stream::SeekableReader& reader() override { return blob_reader_; }

 private:
  blob_store::BlobStore& blob_store_;
  blob_store::BlobStore::BlobReader blob_reader_;
};

}  // namespace pw::software_update


text:
package org.apereo.cas.ticket;

import org.apereo.cas.authentication.principal.Service;

import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * This is {@link TransientSessionTicketFactory}.
 *
 * @author Misagh Moayyed
 * @since 5.3.0
 */
public interface TransientSessionTicketFactory extends TicketFactory {
    /**
     * Create delegated authentication request ticket.
     *
     * @param service    the service
     * @param properties the properties
     * @return the delegated authentication request ticket
     */
    TransientSessionTicket create(Service service, Map<String, Serializable> properties);

    /**
     * Create transient session ticket.
     *
     * @param id         the id
     * @param properties the properties
     * @return the transient session ticket
     */
    TransientSessionTicket create(String id, Map<String, Serializable> properties);

    /**
     * Create delegated authentication request ticket.
     *
     * @param service the service
     * @return the delegated authentication request ticket
     */
    default TransientSessionTicket create(final Service service) {
        return create(service, new LinkedHashMap<>());
    }

    /**
     * Normalize ticket id string.
     *
     * @param id the id
     * @return the string
     */
    static String normalizeTicketId(final String id) {
        return TransientSessionTicket.PREFIX + '-' + id;
    }
}


text:
#ifndef LM_MODEL__
#define LM_MODEL__

#include "lm/bhiksha.hh"
#include "lm/binary_format.hh"
#include "lm/config.hh"
#include "lm/facade.hh"
#include "lm/quantize.hh"
#include "lm/search_hashed.hh"
#include "lm/search_trie.hh"
#include "lm/state.hh"
#include "lm/value.hh"
#include "lm/vocab.hh"
#include "lm/weights.hh"

#include "util/murmur_hash.hh"

#include <algorithm>
#include <vector>

#include <string.h>

namespace util { class FilePiece; }

namespace lm {
namespace ngram {
namespace detail {

// Should return the same results as SRI.
// ModelFacade typedefs Vocabulary so we use VocabularyT to avoid naming conflicts.
template <class Search, class VocabularyT> class GenericModel : public base::ModelFacade<GenericModel<Search, VocabularyT>, State, VocabularyT> {
  private:
    typedef base::ModelFacade<GenericModel<Search, VocabularyT>, State, VocabularyT> P;
  public:
    // This is the model type returned by RecognizeBinary.
    static const ModelType kModelType;

    static const unsigned int kVersion = Search::kVersion;

    /* Get the size of memory that will be mapped given ngram counts.  This
     * does not include small non-mapped control structures, such as this class
     * itself.
     */
    static uint64_t Size(const std::vector<uint64_t> &counts, const Config &config = Config());

    /* Load the model from a file.  It may be an ARPA or binary file.  Binary
     * files must have the format expected by this class or you'll get an
     * exception.  So TrieModel can only load ARPA or binary created by
     * TrieModel.  To classify binary files, call RecognizeBinary in
     * lm/binary_format.hh.
     */
    explicit GenericModel(const char *file, const Config &config = Config());

    /* Score p(new_word | in_state) and incorporate new_word into out_state.
     * Note that in_state and out_state must be different references:
     * &in_state != &out_state.
     */
    FullScoreReturn FullScore(const State &in_state, const WordIndex new_word, State &out_state) const;

    /* Slower call without in_state.  Try to remember state, but sometimes it
     * would cost too much memory or your decoder isn't setup properly.
     * To use this function, make an array of WordIndex containing the context
     * vocabulary ids in reverse order.  Then, pass the bounds of the array:
     * [context_rbegin, context_rend).  The new_word is not part of the context
     * array unless you intend to repeat words.
     */
    FullScoreReturn FullScoreForgotState(const WordIndex *context_rbegin, const WordIndex *context_rend, const WordIndex new_word, State &out_state) const;

    /* Get the state for a context.  Don't use this if you can avoid it.  Use
     * BeginSentenceState or EmptyContextState and extend from those.  If
     * you're only going to use this state to call FullScore once, use
     * FullScoreForgotState.
     * To use this function, make an array of WordIndex containing the context
     * vocabulary ids in reverse order.  Then, pass the bounds of the array:
     * [context_rbegin, context_rend).
     */
    void GetState(const WordIndex *context_rbegin, const WordIndex *context_rend, State &out_state) const;

    /* More efficient version of FullScore where a partial n-gram has already
     * been scored.
     * NOTE: THE RETURNED .rest AND .prob ARE RELATIVE TO THE .rest RETURNED BEFORE.
     */
    FullScoreReturn ExtendLeft(
        // Additional context in reverse order.  This will update add_rend to
        const WordIndex *add_rbegin, const WordIndex *add_rend,
        // Backoff weights to use.
        const float *backoff_in,
        // extend_left returned by a previous query.
        uint64_t extend_pointer,
        // Length of n-gram that the pointer corresponds to.
        unsigned char extend_length,
        // Where to write additional backoffs for [extend_length + 1, min(Order() - 1, return.ngram_length)]
        float *backoff_out,
        // Amount of additional content that should be considered by the next call.
        unsigned char &next_use) const;

    /* Return probabilities minus rest costs for an array of pointers.  The
     * first length should be the length of the n-gram to which pointers_begin
     * points.
     */
    float UnRest(const uint64_t *pointers_begin, const uint64_t *pointers_end, unsigned char first_length) const {
      // Compiler should optimize this if away.
      return Search::kDifferentRest ? InternalUnRest(pointers_begin, pointers_end, first_length) : 0.0;
    }

  private:
    friend void lm::ngram::LoadLM<>(const char *file, const Config &config, GenericModel<Search, VocabularyT> &to);

    static void UpdateConfigFromBinary(int fd, const std::vector<uint64_t> &counts, Config &config);

    FullScoreReturn ScoreExceptBackoff(const WordIndex *const context_rbegin, const WordIndex *const context_rend, const WordIndex new_word, State &out_state) const;

    // Score bigrams and above.  Do not include backoff.
    void ResumeScore(const WordIndex *context_rbegin, const WordIndex *const context_rend, unsigned char starting_order_minus_2, typename Search::Node &node, float *backoff_out, unsigned char &next_use, FullScoreReturn &ret) const;

    // Appears after Size in the cc file.
    void SetupMemory(void *start, const std::vector<uint64_t> &counts, const Config &config);

    void InitializeFromBinary(void *start, const Parameters &params, const Config &config, int fd);

    void InitializeFromARPA(const char *file, const Config &config);

    float InternalUnRest(const uint64_t *pointers_begin, const uint64_t *pointers_end, unsigned char first_length) const;

    Backing &MutableBacking() { return backing_; }

    Backing backing_;

    VocabularyT vocab_;

    Search search_;
};

} // namespace detail

// Instead of typedef, inherit.  This allows the Model etc to be forward declared.
// Oh the joys of C and C++.
#define LM_COMMA() ,
#define LM_NAME_MODEL(name, from)\
class name : public from {\
  public:\
    name(const char *file, const Config &config = Config()) : from(file, config) {}\
};

LM_NAME_MODEL(ProbingModel, detail::GenericModel<detail::HashedSearch<BackoffValue> LM_COMMA() ProbingVocabulary>);
LM_NAME_MODEL(RestProbingModel, detail::GenericModel<detail::HashedSearch<RestValue> LM_COMMA() ProbingVocabulary>);
LM_NAME_MODEL(TrieModel, detail::GenericModel<trie::TrieSearch<DontQuantize LM_COMMA() trie::DontBhiksha> LM_COMMA() SortedVocabulary>);
LM_NAME_MODEL(ArrayTrieModel, detail::GenericModel<trie::TrieSearch<DontQuantize LM_COMMA() trie::ArrayBhiksha> LM_COMMA() SortedVocabulary>);
LM_NAME_MODEL(QuantTrieModel, detail::GenericModel<trie::TrieSearch<SeparatelyQuantize LM_COMMA() trie::DontBhiksha> LM_COMMA() SortedVocabulary>);
LM_NAME_MODEL(QuantArrayTrieModel, detail::GenericModel<trie::TrieSearch<SeparatelyQuantize LM_COMMA() trie::ArrayBhiksha> LM_COMMA() SortedVocabulary>);

// Default implementation.  No real reason for it to be the default.
typedef ::lm::ngram::ProbingVocabulary Vocabulary;
typedef ProbingModel Model;

} // namespace ngram
} // namespace lm

#endif // LM_MODEL__


text:
package com.cardpay.pccredit.jnpad.dao;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.cardpay.pccredit.intopieces.model.IntoPieces;
import com.cardpay.pccredit.jnpad.model.CustomerInfo;
import com.wicresoft.util.annotation.Mapper;

@Mapper
public interface JnpadZongBaoCustomerInsertDao {

	//查看抢单列表
	List<CustomerInfo> selectCustomerInfo(@Param (value ="userId") String userId);
	//抢单
	Object updateCustomerInfo(@Param (value ="customerId")String customerId,@Param (value ="userId")String userId);
	List<IntoPieces> selectAllMyZb(@Param (value ="userId") String userId);
	int selectCustomerInfoCount(@Param (value ="cardId") String cardId);
}


text:
module.exports = function(grunt) {

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    jshint: {
      files: ['*.js', 'test/**/*.js'],
        options: {
          globals: {
            jQuery: true,
            console: true,
            module: true
          }
        }
    },
    shell: {
      mocha: {
        options: {
          stdout: true
        },
        command: 'mocha'
      }
    },
    release: {
      options: {
        // Don't release to NPM since travis does this
        npm: false,
        npmtag: false,
        // default: 'release <%= version %>'
        commitMessage: 'Release <%= version %>'
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-shell');
  grunt.loadNpmTasks('grunt-release');

  grunt.registerTask('test', ['jshint', 'shell:mocha']);
};


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Saltarelle.Compiler.JSModel.Statements;
using Saltarelle.Compiler.JSModel.ExtensionMethods;

namespace Saltarelle.Compiler.JSModel.Expressions {
	public enum ExpressionNodeType {
		ArrayLiteral,

		// Binary
		LogicalAnd,
		LogicalOr,
		NotEqual,
		LesserOrEqual,
		GreaterOrEqual,
		Lesser,
		Greater,
		Equal,
		Subtract,
		Add,
		Modulo,
		Divide,
		Multiply,
		BitwiseAnd,
		BitwiseOr,
		BitwiseXor,
		Same,
		NotSame,
		LeftShift,
		RightShiftSigned,
		RightShiftUnsigned,
		InstanceOf,
		In,
		Index,

		Assign,
		MultiplyAssign,
		DivideAssign,
		ModuloAssign,
		AddAssign,
		SubtractAssign,
		LeftShiftAssign,
		RightShiftSignedAssign,
		RightShiftUnsignedAssign,
		BitwiseAndAssign,
		BitwiseOrAssign,
		BitwiseXorAssign,
		// /Binary

		Comma,
		Conditional,

		// Constants
		Number,
		String,
		Boolean,
		Regexp,
		Null,
		// /Constants

		FunctionDefinition,
		Identifier,
		Invocation,
		MemberAccess,
		New,
		ObjectLiteral,

		// Unary
		TypeOf,
		LogicalNot,
		Negate,
		Positive,
		PrefixPlusPlus,
		PrefixMinusMinus,
		PostfixPlusPlus,
		PostfixMinusMinus,
		Delete,
		Void,
		BitwiseNot,
		// /Unary

		This,

		// Fake
		TypeReference,
		Literal,

		AssignFirst = Assign,
		AssignLast = BitwiseXorAssign,
		BinaryFirst = LogicalAnd,
		BinaryLast = BitwiseXorAssign,
		ConstantFirst = Number,
		ConstantLast = Null,
		UnaryFirst = TypeOf,
		UnaryLast = BitwiseNot
	}

	[Serializable, DebuggerDisplay("{DebugToString()}")]
	public abstract class JsExpression {
		[System.Diagnostics.DebuggerStepThrough]
		public abstract TReturn Accept<TReturn, TData>(IExpressionVisitor<TReturn, TData> visitor, TData data);

		public ExpressionNodeType NodeType { get; private set; }

		private string DebugToString() {
			return OutputFormatter.Format(this, allowIntermediates: true);
		}

		public static implicit operator JsStatement(JsExpression expr) {
			return JsStatement.Expression(expr);
		}

		public static implicit operator JsExpressionStatement(JsExpression expr) {
			return JsStatement.Expression(expr);
		}

		protected JsExpression(ExpressionNodeType nodeType) {
			NodeType = nodeType;
		}

		public static JsArrayLiteralExpression ArrayLiteral(IEnumerable<JsExpression> elements) {
			return new JsArrayLiteralExpression(elements);
		}

		public static JsArrayLiteralExpression ArrayLiteral(params JsExpression[] elements) {
			return ArrayLiteral((IEnumerable<JsExpression>)elements);
		}

		public static JsBinaryExpression Binary(ExpressionNodeType nodeType, JsExpression left, JsExpression right) {
			return new JsBinaryExpression(nodeType, left, right);
		}

		public static JsBinaryExpression LogicalAnd(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.LogicalAnd, left, right);
		}

		public static JsBinaryExpression LogicalOr(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.LogicalOr, left, right);
		}

		public static JsBinaryExpression NotEqual(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.NotEqual, left, right);
		}

		public static JsBinaryExpression LesserOrEqual(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.LesserOrEqual, left, right);
		}

		public static JsBinaryExpression GreaterOrEqual(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.GreaterOrEqual, left, right);
		}

		public static JsBinaryExpression Lesser(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.Lesser, left, right);
		}

		public static JsBinaryExpression Greater(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.Greater, left, right);
		}

		public static JsBinaryExpression Equal(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.Equal, left, right);
		}

		public static JsBinaryExpression Subtract(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.Subtract, left, right);
		}

		public static JsBinaryExpression Add(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.Add, left, right);
		}

		public static JsBinaryExpression Modulo(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.Modulo, left, right);
		}

		public static JsBinaryExpression Divide(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.Divide, left, right);
		}

		public static JsBinaryExpression Multiply(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.Multiply, left, right);
		}

		public static JsBinaryExpression BitwiseAnd(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.BitwiseAnd, left, right);
		}

		public static JsBinaryExpression BitwiseOr(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.BitwiseOr, left, right);
		}

		public static JsBinaryExpression BitwiseXor(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.BitwiseXor, left, right);
		}

		public static JsBinaryExpression Same(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.Same, left, right);
		}

		public static JsBinaryExpression NotSame(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.NotSame, left, right);
		}

		public static JsBinaryExpression LeftShift(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.LeftShift, left, right);
		}

		public static JsBinaryExpression RightShiftSigned(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.RightShiftSigned, left, right);
		}

		public static JsBinaryExpression RightShiftUnsigned(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.RightShiftUnsigned, left, right);
		}

		public static JsBinaryExpression InstanceOf(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.InstanceOf, left, right);
		}

		public static JsBinaryExpression In(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.In, left, right);
		}

		public static JsBinaryExpression Index(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.Index, left, right);
		}

		public static JsBinaryExpression Assign(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.Assign, left, right);
		}

		public static JsBinaryExpression MultiplyAssign(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.MultiplyAssign, left, right);
		}

		public static JsBinaryExpression DivideAssign(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.DivideAssign, left, right);
		}

		public static JsBinaryExpression ModuloAssign(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.ModuloAssign, left, right);
		}

		public static JsBinaryExpression AddAssign(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.AddAssign, left, right);
		}

		public static JsBinaryExpression SubtractAssign(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.SubtractAssign, left, right);
		}

		public static JsBinaryExpression LeftShiftAssign(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.LeftShiftAssign, left, right);
		}

		public static JsBinaryExpression RightShiftSignedAssign(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.RightShiftSignedAssign, left, right);
		}

		public static JsBinaryExpression RightShiftUnsignedAssign(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.RightShiftUnsignedAssign, left, right);
		}

		public static JsBinaryExpression BitwiseAndAssign(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.BitwiseAndAssign, left, right);
		}

		public static JsBinaryExpression BitwiseOrAssign(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.BitwiseOrAssign, left, right);
		}

		public static JsBinaryExpression BitwiseXorAssign(JsExpression left, JsExpression right) {
			return Binary(ExpressionNodeType.BitwiseXorAssign, left, right);
		}

		public static JsCommaExpression Comma(IEnumerable<JsExpression> expressions) {
			return new JsCommaExpression(expressions);
		}

		public static JsCommaExpression Comma(params JsExpression[] expressions) {
			return Comma((IEnumerable<JsExpression>)expressions);
		}

		public static JsConditionalExpression Conditional(JsExpression test, JsExpression truePart, JsExpression falsePart) {
			return new JsConditionalExpression(test, truePart, falsePart);
		}

		public static JsConstantExpression Regexp(string pattern, string options = null) {
			return new JsConstantExpression(new JsConstantExpression.RegexpData(pattern, options ?? ""));
		}

		public static JsConstantExpression Number(double value) {
			return new JsConstantExpression(value);
		}

		public static JsConstantExpression String(string value) {
			return new JsConstantExpression(value);
		}

		public static JsConstantExpression Boolean(bool value) {
			return value ? True : False;
		}

		public static JsConstantExpression Null { get { return JsConstantExpression.Null; } }
		public static JsConstantExpression True { get { return JsConstantExpression.True; } }
		public static JsConstantExpression False { get { return JsConstantExpression.False; } }

		public static JsFunctionDefinitionExpression FunctionDefinition(IEnumerable<string> parameterNames, JsStatement body, string name = null) {
			return new JsFunctionDefinitionExpression(parameterNames, body, name);
		}

		public static JsIdentifierExpression Identifier(string name) {
			return new JsIdentifierExpression(name);
		}

		public static JsInvocationExpression Invocation(JsExpression method, IEnumerable<JsExpression> arguments) {
			return new JsInvocationExpression(method, arguments);
		}

		public static JsInvocationExpression Invocation(JsExpression method, params JsExpression[] arguments) {
			return Invocation(method, (IEnumerable<JsExpression>)arguments);
		}

		public static JsMemberAccessExpression MemberAccess(JsExpression target, string member) {
			return new JsMemberAccessExpression(target, member);
		}

		/// <summary>
		/// Creates an expression to access a member. If the member is a valid JS identifier, will return target.member, otherwise returns traget["member"].
		/// </summary>
		public static JsExpression Member(JsExpression target, string member) {
			return member.IsValidJavaScriptIdentifier() ? (JsExpression)MemberAccess(target, member) : Index(target, JsExpression.String(member));
		}

		public static JsNewExpression New(JsExpression constructor, IEnumerable<JsExpression> arguments) {
			return new JsNewExpression(constructor, arguments);
		}

		public static JsNewExpression New(JsExpression constructor, params JsExpression[] arguments) {
			return New(constructor, (IEnumerable<JsExpression>)arguments);
		}

		public static JsObjectLiteralExpression ObjectLiteral(IEnumerable<JsObjectLiteralProperty> values) {
			return new JsObjectLiteralExpression(values);
		}

		public static JsObjectLiteralExpression ObjectLiteral(params JsObjectLiteralProperty[] values) {
			return ObjectLiteral((IEnumerable<JsObjectLiteralProperty>)values);
		}

		public static JsUnaryExpression Unary(ExpressionNodeType nodeType, JsExpression operand) {
			return new JsUnaryExpression(nodeType, operand);
		}

		public static JsUnaryExpression TypeOf(JsExpression operand) {
			return Unary(ExpressionNodeType.TypeOf, operand);
		}

		public static JsUnaryExpression LogicalNot(JsExpression operand) {
			return Unary(ExpressionNodeType.LogicalNot, operand);
		}

		public static JsUnaryExpression Negate(JsExpression operand) {
			return Unary(ExpressionNodeType.Negate, operand);
		}

		public static JsUnaryExpression Positive(JsExpression operand) {
			return Unary(ExpressionNodeType.Positive, operand);
		}

		public static JsUnaryExpression PrefixPlusPlus(JsExpression operand) {
			return Unary(ExpressionNodeType.PrefixPlusPlus, operand);
		}

		public static JsUnaryExpression PrefixMinusMinus(JsExpression operand) {
			return Unary(ExpressionNodeType.PrefixMinusMinus, operand);
		}

		public static JsUnaryExpression PostfixPlusPlus(JsExpression operand) {
			return Unary(ExpressionNodeType.PostfixPlusPlus, operand);
		}

		public static JsUnaryExpression PostfixMinusMinus(JsExpression operand) {
			return Unary(ExpressionNodeType.PostfixMinusMinus, operand);
		}

		public static JsUnaryExpression Delete(JsExpression operand) {
			return Unary(ExpressionNodeType.Delete, operand);
		}

		public static JsUnaryExpression Void(JsExpression operand) {
			return Unary(ExpressionNodeType.Void, operand);
		}

		public static JsUnaryExpression BitwiseNot(JsExpression operand) {
			return Unary(ExpressionNodeType.BitwiseNot, operand);
		}

		public static JsThisExpression This { get { return JsThisExpression.This; } }
	}
}


text:
GT_Matrix::GT_Matrix(): GT_Matrix(2) {}

GT_Matrix::GT_Matrix(int ploidy): ploidy(ploidy), gts(Genotype::enumerate_gts(ploidy)), data(Genotype::alleles.size(),std::vector<double>(gts.size(),0.0)) {
}

GT_Matrix::GT_Matrix(std::string filename, int ploidy):
ploidy(ploidy), gts(Genotype::enumerate_gts(ploidy)), data(Genotype::alleles.size(),std::vector<double>(gts.size())){
	std::ifstream f;
	f.exceptions ( std::ifstream::failbit | std::ifstream::badbit );
	f.open(filename);
	int i = 0;
	for(std::string line; std::getline(f,line);){
		std::istringstream row(line);
		int j = 0;
		for(std::string val; std::getline(row,val,'\t');){
			data[i][j] = std::stod(val);
		}
	}
	f.close();
}

// GT_Matrix::GT_Matrix(Pileupdata plpdata, int ploidy, theta_t theta):
// ploidy(ploidy), gts(Genotype::enumerate_gts(ploidy)), data(std::vector<double>(gts.size()),Genotype::alleles.size()){
// 	for (pileupdata_t::iterator tid = plpdata.begin(); tid != plpdata.end(); ++tid){
// 		for(std::vector<pileuptuple_t>::iterator pos = tid->begin(); pos != tid->end(); ++pos){
// 			const std::vector<char> &x = std::get<0>(*pos);
// 			const char &ref = std::get<3>(*pos);
// 			for (std::vector<Genotype>::iterator g = gts.begin(); g != gts.end(); ++g){
// 				double pg_x = Popstatem::pg_x_given_theta(*g,x,theta);
// 				double pdata = Popstatem::pdata_given_theta(x,theta,gts);
// 				this(ref,*g) += pg_x / pdata;
// 			}
// 		}
// 	}
// }

const std::vector<double>& GT_Matrix::operator[](char allele) const{
	return data[std::distance(Genotype::alleles.begin(),std::find(Genotype::alleles.begin(), Genotype::alleles.end(), allele))];
}

double GT_Matrix::operator()(char allele, Genotype gt) const{
	std::vector<double> row = data[std::distance(Genotype::alleles.begin(),std::find(Genotype::alleles.begin(), Genotype::alleles.end(), allele))];
	ptrdiff_t idx = std::distance(gts.begin(),std::find(gts.begin(), gts.end(), gt));
	return row[idx];
}

double& GT_Matrix::operator()(char allele, Genotype gt){
	std::vector<double>& row = data[std::distance(Genotype::alleles.begin(),std::find(Genotype::alleles.begin(), Genotype::alleles.end(), allele))];
	ptrdiff_t idx = std::distance(gts.begin(),std::find(gts.begin(), gts.end(), gt));
	return row[idx];
}

std::ostream& operator<<(std::ostream& os, const GT_Matrix m){
	os << "- gt_matrix - " << std::endl;
	os << "GTs : " << m.gts << std::endl;
	for(int i = 0; i < Genotype::alleles.size(); ++i){
		os << Genotype::alleles[i] << " : ";
		os << m[i] << std::endl;
	}
	return os << "----------" << std::endl;
}


text:
package sg.atom2d.swing;

import com.jme3.effect.ParticleEmitter;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.shape.Sphere;
import java.util.logging.Level;
import java.util.logging.Logger;
import sg.atom.swing.SwingSimple3DApp;
import sg.atom.world.WorldTestHelper;

public class SwingSimple2DApp extends SwingSimple3DApp {

    private ParticleEmitter currentParticle;
    /**
     * Singleton reference of Object.
     */
    private static SwingSimple2DApp selfRef;

    /**
     * Constructs singleton instance of Object.
     */
    protected SwingSimple2DApp() {
        selfRef = this;
    }

    /**
     * Provides reference to singleton object of Object.
     *
     * @return Singleton instance of Object.
     */
    public static final SwingSimple2DApp getInstance() {
        if (selfRef == null) {
            selfRef = new SwingSimple2DApp();
        }
        return selfRef;
    }

    public static void main(String[] args) {
        SwingSimple2DApp app = new SwingSimple2DApp();
        app.setShowSettings(false);
        app.start();

        Logger.getLogger("com.jme3").setLevel(Level.WARNING);
    }

    protected void createMark(Vector3f loc) {
        Sphere sphere = new Sphere(8, 8, 0.2f);
        Geometry mark = new Geometry("BOOM!", sphere);
        Material mark_mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        mark_mat.setColor("Color", ColorRGBA.Red);
        mark.setMaterial(mark_mat);
        mark.setLocalTranslation(loc.clone());
        rootNode.attachChild(mark);
    }

    @Override
    public void simpleInitApp() {
        flyCam.setMoveSpeed(40f);
        //Create tesint enviroment
        WorldTestHelper worldHelper = new WorldTestHelper(rootNode, assetManager);
        worldHelper.createGrid(40, 40);
        //worldHelper.createLight();
        //worldHelper.createFlatGround();
        //worldHelper.createSkyBox();
        //createParticle();
        initInput();
    }

    public void initInput() {
        flyCam.setDragToRotate(true);
        inputManager.setCursorVisible(true);

        //inputManager.addListener(actionListener, "changeTexture");
        cam.setLocation(new Vector3f(-10, 10, -10));
        cam.lookAt(Vector3f.ZERO.clone(), Vector3f.UNIT_Y.clone());

        viewPort.setBackgroundColor(ColorRGBA.DarkGray);
    }
/*
    public void createParticle() {
        ParticleFactory pf = new ParticleFactory(assetManager);
        currentParticle = pf.createFlame();
        rootNode.attachChild(currentParticle);
    }

    public ParticleEmitter getCurrentParticle() {
        return currentParticle;
    }

    public Texture changeTexture(File file) {
        try {

            //String filePath = file.getParent().replaceAll("\\", "/");
            //System.out.println("" + filePath + "/");
            String filePath = file.getParent();
            assetManager.registerLocator(filePath, FileLocator.class);
            Texture newTex = assetManager.loadTexture(file.getName());

            currentParticle.getMaterial().setTexture("Texture", newTex);
            return newTex;
        } catch (Exception e) {
            return null;

        }
    }
    */
}


text:
run_as_root = true
prosody_user = "root"


text:
module Puppet::Scheduler
  class Job
    attr_reader :run_interval
    attr_accessor :last_run
    attr_accessor :start_time

    def initialize(run_interval, &block)
      self.run_interval = run_interval
      @last_run = nil
      @run_proc = block
      @enabled = true
    end

    def run_interval=(interval)
      @run_interval = [interval, 0].max
    end

    def ready?(time)
      if @last_run
        @last_run + @run_interval <= time
      else
        true
      end
    end

    def enabled?
      @enabled
    end

    def enable
      @enabled = true
    end

    def disable
      @enabled = false
    end

    def interval_to_next_from(time)
      if ready?(time)
        0
      else
        @run_interval - (time - @last_run)
      end
    end

    def run(now)
      @last_run = now
      if @run_proc
        @run_proc.call(self)
      end
    end
  end
end


text:
package opentools.ILib;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;

import android.os.Handler;
import android.os.Looper;

public class AsyncInputOutputReaderWriter
{
	public interface AsyncInputOutputReaderWriterHandler
	{
		public void OnRead(AsyncInputOutputReaderWriter sender, InputStream iStream, byte[] buffer, int length);
		public void OnEndOfStream(AsyncInputOutputReaderWriter sender);
	}

	private Thread readerThread,writerThread;
	private InputStream mReadStream;
	private OutputStream mWriteStream;

	private Handler writerHandle = null;
	private AsyncInputOutputReaderWriterHandler mUser = null;

	public AsyncInputOutputReaderWriter(InputStream iStream, OutputStream wStream, AsyncInputOutputReaderWriterHandler callback)
	{
		mReadStream = iStream;
		mWriteStream = wStream;
		mUser = callback;
	}
	public void Stop()
	{
		if(writerHandle!=null)
		{
			writerHandle.getLooper().quit();
		}
		readerThread.interrupt();
	}
	public void Start(int bufferSize, boolean useCircularBuffer)
	{
		readerThread = new Thread(new RunnableEx<Object[]>(new Object[]{Integer.valueOf(bufferSize), Boolean.valueOf(useCircularBuffer)})
				{
					@Override
					public void run(Object[] param)
					{
						int bufferSize = ((Integer)param[0]).intValue();
						boolean useCircularBuffer = ((Boolean)param[1]).booleanValue();
						int bytesRead;
						byte[] readBuffer = new byte[bufferSize];

						try
						{
							ILibCircularBuffer circleBuffer=null;
							if(useCircularBuffer)
							{
								circleBuffer = new ILibCircularBuffer(bufferSize);
							}

							while(true)
							{
								bytesRead = mReadStream.read(readBuffer);
								if(bytesRead>0)
								{
									if(useCircularBuffer)
									{
										circleBuffer.getOutputStream().write(readBuffer, 0, bytesRead);
										if(mUser!=null)
										{
											mUser.OnRead(AsyncInputOutputReaderWriter.this, circleBuffer.getInputStream(), null, bytesRead);
										}
									}
									else
									{
										if(mUser!=null)
										{
											mUser.OnRead(AsyncInputOutputReaderWriter.this, null, readBuffer, bytesRead);
										}
									}
								}
								else
								{
									if(mUser!=null)
									{
										mUser.OnEndOfStream(AsyncInputOutputReaderWriter.this);
									}
									if(useCircularBuffer)
									{
										circleBuffer.close();
									}
									mReadStream.close();
									mWriteStream.close();
								}
							}
						} catch (IOException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
							if(mUser!=null)
							{
								mUser.OnEndOfStream(AsyncInputOutputReaderWriter.this);
							}
						}
					}
				});
		readerThread.start();

		writerThread = new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				Looper.prepare();
				writerHandle = new Handler();
				Looper.loop();
			}
		});
		writerThread.start();
	}
	public void Write(byte[] buffer, int offset, int length)
	{
		ByteBuffer b = ByteBuffer.allocate(length);
		b.put(buffer, offset, length);

		writerHandle.post(new RunnableEx<ByteBuffer>(b)
				{
					@Override
					public void run(ByteBuffer param)
					{
						try
						{
							mWriteStream.write(param.array());
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});
	}
	public void WriteEx(byte[] buffer, int offset, int length) throws IOException
	{
		mWriteStream.write(buffer, offset, length);
	}
}


text:
<gd-appbar>
    <app-title>Google·Design¬</app-title>
    <app-logo gd-href="https://docs.angularjs.org/img/angularjs-for-header-only.svg"></app-logo>
    <app-nav>
        <app-link gd-href="/" gd-label="home"></app-link>
        <app-link gd-href="/about" gd-label="about"></app-link>
        <app-link gd-href="/contact" gd-label="contact"></app-link>
    </app-nav>
</gd-appbar>


text:
use super::abi::tls::{Key as AbiKey, Tls};

pub type Key = usize;

#[inline]
pub unsafe fn create(dtor: Option<unsafe extern "C" fn(*mut u8)>) -> Key {
    Tls::create(dtor).as_usize()
}

#[inline]
pub unsafe fn set(key: Key, value: *mut u8) {
    Tls::set(AbiKey::from_usize(key), value)
}

#[inline]
pub unsafe fn get(key: Key) -> *mut u8 {
    Tls::get(AbiKey::from_usize(key))
}

#[inline]
pub unsafe fn destroy(key: Key) {
    Tls::destroy(AbiKey::from_usize(key))
}

#[inline]
pub fn requires_synchronized_create() -> bool {
    false
}


text:
require 'coveralls'
Coveralls.wear!
require 'spec_helper'
module Hangman
  describe Choice do
    choice = Choice.new
    picked_word = choice.pick_word

    context '#initialize' do
      it 'be an instance of Hangman::Choice' do
        expect(choice.class).to eq(Hangman::Choice)
      end

      it 'has a file_path attribute ' do
        expect(choice.file_path).to eq('5desk.txt')
      end
    end

    context '#pick_word' do
      it 'returns a string in downcase' do
        expect(picked_word.class).to eql String
      end
      it 'cannot be an empty string' do
        expect(picked_word.length).not_to eql 0
      end

      it 'cannot be a sring with length < 5' do
        expect(picked_word.length).not_to eql 4
      end

      it 'cannot be a sring with length < 5' do
        expect(picked_word.length).not_to eql 3
      end

      it 'cannot be a sring with length < 5' do
        expect(picked_word.length).not_to eql 2
      end

      it 'cannot be a sring with length < 5' do
        expect(picked_word.length).not_to eql 1
      end
    end
  end
end


text:
apetools.parsers.sumparser.HumanExpressionSum
=============================================

.. currentmodule:: apetools.parsers.sumparser

.. autoclass:: HumanExpressionSum

   .. automethod:: __init__

   .. rubric:: Methods

   .. autosummary::

      ~HumanExpressionSum.__init__

   .. rubric:: Attributes

   .. autosummary::

      ~HumanExpressionSum.expression
      ~HumanExpressionSum.logger
      ~HumanExpressionSum.regex
      ~HumanExpressionSum.thread_column


text:
package com.github.pwittchen.gesture.app;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.TextView;
import com.github.pwittchen.gesture.library.Gesture;
import com.github.pwittchen.gesture.library.GestureEvent;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import java.util.Locale;

public class GestureRxActivity extends AppCompatActivity {
  private Gesture gesture;
  private TextView textView;
  private Disposable subscription;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    textView = (TextView) findViewById(R.id.textView);
    gesture = new Gesture();
    subscription = gesture.observe()
        .subscribeOn(Schedulers.computation())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(event -> {
          final String msg = event.toString();
          if (event.equals(GestureEvent.ON_MULTI_TAP)) {
            textView.setText(
                msg.concat(String.format(Locale.getDefault(), " [%d]", event.getClicks())));
          } else {
            textView.setText(msg);
          }
        });
  }

  @Override public boolean dispatchTouchEvent(MotionEvent event) {
    gesture.dispatchTouchEvent(event);
    return super.dispatchTouchEvent(event);
  }

  @Override protected void onPause() {
    super.onPause();
    safelyDispose(subscription);
  }

  private void safelyDispose(Disposable disposable) {
    if (disposable != null && !disposable.isDisposed()) {
      disposable.dispose();
    }
  }

  @Override public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main_menu, menu);
    return true;
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.listener:
        onBackPressed();
        break;
      case R.id.rx:
        break;
    }
    return true;
  }
}


text:
from importlib import import_module
import os

import numpy as np

import pandas as pd

# Compatibility import for lib
for imp in ["pandas._libs.lib", "pandas.lib"]:
    try:
        lib = import_module(imp)
        break
    except (ImportError, TypeError, ValueError):
        pass

# Compatibility import for the testing module
try:
    import pandas._testing as tm
except ImportError:
    import pandas.util.testing as tm  # noqa

numeric_dtypes = [
    np.int64,
    np.int32,
    np.uint32,
    np.uint64,
    np.float32,
    np.float64,
    np.int16,
    np.int8,
    np.uint16,
    np.uint8,
]
datetime_dtypes = [np.datetime64, np.timedelta64]
string_dtypes = [object]
try:
    extension_dtypes = [
        pd.Int8Dtype,
        pd.Int16Dtype,
        pd.Int32Dtype,
        pd.Int64Dtype,
        pd.UInt8Dtype,
        pd.UInt16Dtype,
        pd.UInt32Dtype,
        pd.UInt64Dtype,
        pd.CategoricalDtype,
        pd.IntervalDtype,
        pd.DatetimeTZDtype("ns", "UTC"),
        pd.PeriodDtype("D"),
    ]
except AttributeError:
    extension_dtypes = []

def setup(*args, **kwargs):
    # This function just needs to be imported into each benchmark file to
    # set up the random seed before each function.
    # https://asv.readthedocs.io/en/latest/writing_benchmarks.html
    np.random.seed(1234)

class BaseIO:
    """
    Base class for IO benchmarks
    """

    fname = None

    def remove(self, f):
        """Remove created files"""
        try:
            os.remove(f)  # noqa: PDF008
        except OSError:
            # On Windows, attempting to remove a file that is in use
            # causes an exception to be raised
            pass

    def teardown(self, *args, **kwargs):
        self.remove(self.fname)


text:
<?php
class Encuesta extends AppModel {
	var $name  = 'Encuesta';
	var $order = 'Encuesta.id DESC';
	var $useTable = 'fr_encuestas';
	var $displayField = 'nombre';
	var $hasMany = array(
		'Pregunta' => array(
			'className' => 'Frage.Pregunta',
			'dependent' => true
		)
	);
}
?>


text:
require 'spec_helper'

describe AttachmentDecorator do
end


text:
import app from '../../app';
import moment from 'moment';

describe('Calendar App', () => {

  describe('CalendarCtrl', () => {
    let CalendarCtrl, CalendarService;

    beforeEach(() => {
      angular.mock.module(app);

      CalendarService = {
        generateDates: () => {},
        loadMoreDates: () => {},
        getDayNames: () => {},
        setDates: () => {},
        setDefault: () => {}
      };

      spyOn(CalendarService, 'getDayNames').and.returnValue([]);
      spyOn(CalendarService, 'setDates');
      spyOn(CalendarService, 'loadMoreDates').and.returnValue([]);
      spyOn(CalendarService, 'generateDates').and.returnValue([]);

      angular.mock.inject(($controller) => {
        CalendarCtrl = $controller('CalendarCtrl', {CalendarService: CalendarService});
      });
    });

    describe('contructor', () => {
      it('days should be an array', () => {
        expect(CalendarCtrl.days).toEqual([]);
      });

      it('dates should be an array', () => {
        expect(CalendarCtrl.dates).toEqual([]);
      });

      it('selectedDates should be an array', () => {
        expect(CalendarCtrl.selectedDates).toEqual([]);
      });
    });

    describe('methods', () => {
      it('should return day of week for passed moment', () => {
        expect(moment().date()).toEqual(CalendarCtrl.getDate(moment()));
      });

      it('should return full month name for passed moment', () => {
        expect('October').toEqual(CalendarCtrl.getMonth(moment().month(9)));
      });

      it('should return object with keys-classes for styling secific price', () => {
        let dateObject = {
          specificPrice: {
            'price': 14.9,
            'unbroken': false,
            '_first': true,
            '_last': false
          }
        };

        let classes = CalendarCtrl.specificPriceClasses(dateObject);

        expect(true).toEqual(classes.first);
        expect(false).toEqual(classes.last);
        expect(false).toEqual(classes.unbroken);
      });
    });

    describe('cell style filling', () => {
      it('shuold return width and left position of element according daily time', () => {
        let cell = {
          'date': moment('2016-09-12T21:00:00.000Z'),
          'weekend': false,
          'current': false,
          'opened': {
            'first': false,
            'last': false
          },
          'availability': [],
          'price': 149,
          'specificPrice': null,
          'selected': true,
          'unbroken': false,
          '_first': moment('2016-09-13T03:00:00.000Z'),
          '_last': moment('2016-09-13T17:59:59.999Z')
        };
        expect({width: '62.4306%', left: '25.0000%'}).toEqual(CalendarCtrl.cellStyle(cell));
      });

      it('shuold return width (50%) and right (0) position of element according daily time', () => {
        let cell = {
          'date': moment('2016-08-21T21:00:00.000Z'),
          'weekend': false,
          'current': false,
          'opened': {
            'first': true,
            'last': false
          },
          'availability': [],
          'price': null,
          'specificPrice': null,
          'selected': true,
          'unbroken': false,
          '_first': moment('2016-08-22T09:00:00.000Z'),
          '_last': false
        };

        expect({width: '50%', right: '0'}).toEqual(CalendarCtrl.cellStyle(cell));
      });

      it('shuold return width (100%) of element according daily time', () => {
        expect({width: '100%'}).toEqual(CalendarCtrl.cellStyle({}));
      });
    });
  });
});


text:
<component name="ProjectDictionaryState">
  <dictionary name="Alberto" />
</component>


text:
package ru.job4j.boardGame;

/**
 * Created by pacman on 10.07.17.
 * The stage of the game.
 */
public interface Stage {

    /**
     * Shows info about the current status of the game.
     */
    void showInfo();

    /**
     * The response on player's enter.
     */
    void action();
}


text:
<?php

namespace Test\TopicBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Test\TopicBundle\Entity\User;
use Test\TopicBundle\Entity\Role;
use Test\TopicBundle\Form\UserType;
use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;

class UserController extends Controller
{
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $users = $em->getRepository('TestTopicBundle:User')->findAll();

        return $this->render('TestTopicBundle:User:index.html.twig', array(
            'users' => $users,
        ));
    }

    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $user = $em->getRepository('TestTopicBundle:User')->find($id);

        if (!$user) {
            throw $this->createNotFoundException('Unable to find User user.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('TestTopicBundle:User:show.html.twig', array(
            'user'      => $user,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    public function newAction()
    {
        $user = new User();
        $form   = $this->createForm(new UserType(), $user);

        return $this->render('TestTopicBundle:User:new.html.twig', array(
            'user' => $user,
            'form'   => $form->createView(),
        ));
    }

    public function createAction(Request $request)
    {
        $user  = new User();
        $form = $this->createForm(new UserType(), $user);
        $form->bind($request);

        // шифрует и устанавливает пароль для пользователя,
        // эти настройки совпадают с конфигурационными файлами
        $encoder = new MessageDigestPasswordEncoder('sha1', false, 1);
        $password = $encoder->encodePassword($user->getPassword(), $user->getSalt());
        $user->setPassword($password);

//        $user->getUserRoles()->add($role);

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

            return $this->redirect($this->generateUrl('user_show', array('id' => $user->getId())));
        }

        return $this->render('TestTopicBundle:User:show.html.twig', array(
            'user' => $user,
            'form'   => $form->createView(),
        ));
    }

    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $user = $em->getRepository('TestTopicBundle:User')->find($id);

        if (!$user) {
            throw $this->createNotFoundException('Unable to find User user.');
        }

        $editForm = $this->createForm(new UserType(), $user);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('TestTopicBundle:User:edit.html.twig', array(
            'user'      => $user,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $user = $em->getRepository('TestTopicBundle:User')->find($id);

        if (!$user) {
            throw $this->createNotFoundException('Unable to find User user.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new UserType(), $user);
        $editForm->bind($request);

        if ($editForm->isValid()) {
            $em->persist($user);
            $em->flush();

            return $this->redirect($this->generateUrl('user_edit', array('id' => $id)));
        }

        return $this->render('TestTopicBundle:User:edit.html.twig', array(
            'user'      => $user,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $user = $em->getRepository('TestTopicBundle:User')->find($id);

            if (!$user) {
                throw $this->createNotFoundException('Unable to find User user.');
            }

            $em->remove($user);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('user'));
    }

    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
}


text:
using namespace std;

class Point {
public:
	float x;
	float y;
	float z;
};

class Color {
public:
	float r;
	float g;
	float b;
};

class Model {
public:
	GLuint points;
	GLuint normals;
	GLuint textures;
	int nPoints;
	bool hasTexture;
	GLuint texID;
	Color diffusion;
};

class Group {
public:
	vector<Model> models;
	float translateTime;
	Point translation;
	vector<Point> controlPoints;
	Point rotation;
	Point scale;
	float rotateTime;
	vector<Group>childs;
	float deltaT;
};

class Light {
public:
	int type;
	Point position;
};


text:
var squares = ['We\'re taking it to the next level',
                'Siri kicks off the event',
                'Jonny Ive describes something as magical',
                'Jonny Ive is actually on stage',
                'One more thing...',
                'Apple TV SDK',
                'Awkward presentation from non-Apple exec',
                'Siri SDK',
                'Revolutionary',
                'Hairforce one',
                'Video of Apple products changing people\'s lives',
                'Eddy Cue\'s shirt is not camera friendly',
                'Android mentioned',
                'Infinity Blade',
                'Eddy Cue\'s shirt not tucked in',
                'It\'s our best X yet',
                'Only Apple could do this',
                '...and we\'d love to show it to you now',
                'Angela Ahrendts on stage',
                'Chamfered',
                'Solid piece of aluminium',
                'We\'ve shot a video of the store opening and we\'d love to show it to you now',
                '...and it\'s available today',
                'Video of the Spaceship Campus',
                'Video of the manufacturing process',
                'It\'s that easy',
                'It just works',
                'Phil Schiller reads off a list of specifications',
                'iOS adoption chart',
                'Painfully unfunny "comedy" segment',
                'Isn\'t it just gorgeous?',
                'iPad Pro',
                'Apple Watch Sales Update',
                'Apple Exec \'Amazed\' at customer response to product',
                'Home automation',
                'Finely tuned',
		'China highlighted',
		'Force Touch on iOS',
		'Kevin Lynch on stage',
		'A woman on stage who is not Angela Ahrendts',
		'iPhone 6s',
		'Rose gold (definitely NOT pink)',
		'7000 series aluminum',
		'More ApplePay countries announced',
		'A9 Processor',
		'1080p Front Facing Camera',
		'Stylus for iPad',
		'iOS 9.1',
		'New Apple Watch Bands',
		'12 Megapixel Rear Camera',
		'iPad Mini 4',
		'Amount given to developers mentioned from sales on App Store',
		'3D Touch Display'i,
		'The customer SATs are off the charts',
		'Apple Watch available in more countries'];


text:
typedef struct node {
    char data;
    struct node *next;
} node;

node *makeList();
void printList(node *head);
bool isPalindrome(node *head, node *end, int *length, int *offset);

void printList(node *head) {
    while (head != LIST_END) {
        printf("%c ", head->data);
        head = head->next;
    }

    printf("\n");
}

node *makeList() {
    int nodes = 0;
    node *head = LIST_END, *previous = LIST_END;

    printf("Please enter number of nodes: ");
    scanf("%d", &nodes);

    while ((nodes--) > 0) {
        char value;

        node *item = (node *) malloc(sizeof(node));
        if (item == NULL) {
            printf("Memory allocation error\n");
            exit(EXIT_FAILURE);
        }

        printf("Enter value: ");
        scanf(" %c", &value);

        item->data = value;
        item->next = LIST_END;

        if (head == LIST_END) {
            head = item;
        } else {
            previous->next = item;
        }

        previous = item;
    }

    return head;
}

// comparing elements pairs that have the same distance to the middle of the list
// the list is a palindrome if all the pairs comparisons return true
bool isPalindrome(node *head, node *runner, int *length, int *offset) {
    // we will move the runner till it reaches the end
    runner = runner->next;

    if (runner == LIST_END) { // the end of the list, it doesn't have a pair and we don't need to check it
        return true;
    }

    *length += 1;

    // using recursion for getting to the list end and start checking elements from there
    bool isValid = isPalindrome(head, runner, length, offset);

    if (isValid == false) { // if any of the pairis returns false, the list is not a palindrome
        return false;
    }

    *offset += 1;
    // we need to check only the half of the list
    if (*offset > *length/2) {
        return true;
    }

    // check the pair of elements that have the same distance from/to the middle
    if (head->data != runner->data) {
        return false;
    }

    // move to the next element
    head = head->next;

    return true;
}

int main(void) {
    node *list = makeList();
    printf("Your list: ");
    printList(list);

    int length = 0, offset = 0;
    printf("This is %s\n", isPalindrome(list, list, &length, &offset) ? "a palindrome" : "not a palindrome");
    return 0;
}


text:
  <title>Mocha spec runner</title>
  <link rel="stylesheet" href="mocha.css">


text:
<?php

/**
 * @namespace
 */
namespace Zend\Tool\Project\Context\Zf;

use Zend\Code\Generator\FileGeneratorRegistry,
    Zend\Code\Generator\MethodGenerator,
    Zend\Code\Generator\ClassGenerator,
    Zend\Code\Generator\FileGenerator;

/**
 * This class is the front most class for utilizing Zend\Tool\Project
 *
 * A profile is a hierarchical set of resources that keep track of
 * items within a specific project.
 *
 * @uses       \Zend\Code\Generator\ClassGenerator
 * @uses       \Zend\Code\Generator\FileGenerator
 * @uses       \Zend\Code\Generator\MethodGenerator
 * @category   Zend
 * @package    Zend_Tool
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class ControllerFile extends \Zend\Tool\Project\Context\Filesystem\File
{

    /**
     * @var string
     */
    protected $_controllerName = 'index';

    /**
     * @var string
     */
    protected $_moduleName = null;

    /**
     * @var string
     */
    protected $_filesystemName = 'controllerName';

    /**
     * init()
     *
     */
    public function init()
    {
        $this->_controllerName = $this->_resource->getAttribute('controllerName');
        $this->_moduleName = $this->_resource->getAttribute('moduleName');
        $this->_filesystemName = ucfirst($this->_controllerName) . 'Controller.php';
        parent::init();
    }

    /**
     * getPersistentAttributes
     *
     * @return array
     */
    public function getPersistentAttributes()
    {
        return array(
            'controllerName' => $this->getControllerName()
            );
    }

    /**
     * getName()
     *
     * @return string
     */
    public function getName()
    {
        return 'ControllerFile';
    }

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

    /**
     * getContents()
     *
     * @return string
     */
    public function getContents()
    {
        $className = ($this->_moduleName) ? ucfirst($this->_moduleName) . '\\' : '';
        $className .= ucfirst($this->_controllerName) . 'Controller';

        $codeGenFile = new FileGenerator();
        $codeGenFile->setFilename($this->getPath());
        $cg = new ClassGenerator($className);
        $cg->setMethod(new MethodGenerator('init', array(), null, '/* Initialize action controller here */'));
        $codeGenFile->setClass($cg);

        if ($className == 'ErrorController') {

        	$codeGenFile = new FileGenerator();
            $codeGenFile->setFilename($this->getPath());
            $cg = new ClassGenerator($className);

            $cg->setMethods(array(new MethodGenerator('errorAction', array(), null, <<<'EOS'
$errors = $this->_getParam('error_handler');

if (!$errors || !$errors instanceof \ArrayObject) {
    $this->view->vars()->message = 'You have reached the error page';
    return;
}

switch ($errors->type) {
    case \Zend\Controller\Plugin\ErrorHandler::EXCEPTION_NO_ROUTE:
    case \Zend\Controller\Plugin\ErrorHandler::EXCEPTION_NO_CONTROLLER:
    case \Zend\Controller\Plugin\ErrorHandler::EXCEPTION_NO_ACTION:
        // 404 error -- controller or action not found
        $this->getResponse()->setHttpResponseCode(404);
        $priority = \Zend\Log\Logger::NOTICE;
        $this->view->vars()->message = 'Page not found';
        break;
    default:
        // application error
        $this->getResponse()->setHttpResponseCode(500);
        $priority = \Zend\Log\Logger::CRIT;
        $this->view->vars()->message = 'Application error';
        break;
}

// Log exception, if logger available
if (($log = $this->getLog())) {
    $log->log($this->view->vars()->message, $priority, $errors->exception);
    $log->log('Request Parameters', $priority, $errors->request->getParams());
}

// conditionally display exceptions
if ($this->getInvokeArg('displayExceptions') == true) {
    $this->view->vars()->exception = $errors->exception;
}

$this->view->vars()->request = $errors->request;
EOS
                    ), new MethodGenerator('getLog', array(), null, <<<'EOS'
/* @var $bootstrap Zend\Application\Bootstrap */
$bootstrap = $this->getInvokeArg('bootstrap');
if (!$bootstrap->getBroker()->hasPlugin('Log')) {
    return false;
}
$log = $bootstrap->getResource('Log');
return $log;
EOS
                    )
                )
            );
        }

        // store the generator into the registry so that the addAction command can use the same object later
        FileGeneratorRegistry::registerFileCodeGenerator($codeGenFile); // REQUIRES filename to be set
        return $codeGenFile->generate();
    }

    /**
     * addAction()
     *
     * @param string $actionName
     */
    public function addAction($actionName)
    {
        $classCodeGen = $this->getCodeGenerator();
        $classCodeGen->setMethod(new MethodGenerator($actionName . 'Action', array(), null, '        // action body here'));
        file_put_contents($this->getPath(), $classCodeGen->generate());
    }

    /**
     * getCodeGenerator()
     *
     * @return \Zend\Code\Generator\FileGenerator
     */
    public function getCodeGenerator()
    {
        $codeGenFile = FileGenerator::fromReflectedFileName($this->getPath());
        $codeGenFileClasses = $codeGenFile->getClasses();
        $class = array_shift($codeGenFileClasses);
        return $class;
    }

}


text:
from ctypes import *
import os
import subprocess
import unittest
import sys

import gdb_rsp
import test_files.test_basic as test_basic

# These are set up by Main().
COMMAND = None

class Tests(unittest.TestCase):

  def test_disconnect(self):
    process = gdb_rsp.PopenDebugStub(COMMAND)
    try:
      # Connect.
      connection = gdb_rsp.GdbRspConnection()
      connection.Close()
      # Reconnect 3 times.
      for _ in range(3):
        connection = gdb_rsp.GdbRspConnection()
        connection.Close()
    finally:
      gdb_rsp.KillProcess(process)

  def test_kill(self):
    process = gdb_rsp.PopenDebugStub(COMMAND)
    try:
      connection = gdb_rsp.GdbRspConnection()
      # Request killing the target.
      reply = connection.RspRequest('k')
      self.assertEqual(reply, 'OK')
      signal = c_byte(process.wait()).value
      self.assertEqual(signal, gdb_rsp.RETURNCODE_KILL)
    finally:
      gdb_rsp.KillProcess(process)

  def test_detach(self):
    process = gdb_rsp.PopenDebugStub(COMMAND)
    try:
      connection = gdb_rsp.GdbRspConnection()
      # Request detaching from the target.
      # This resumes execution, so we get the normal exit() status.
      reply = connection.RspRequest('D')
      self.assertEqual(reply, 'OK')
    finally:
      gdb_rsp.KillProcess(process)

def Main():
  index = sys.argv.index('--')
  args = sys.argv[index + 1:]
  # The remaining arguments go to unittest.main().
  global COMMAND
  COMMAND = args
  unittest.main(argv=sys.argv[:index])

if __name__ == '__main__':
  Main()


text:
$(function() {
    $container = $('.js-trick-container');

    $container.masonry({
        gutter: 0,
        itemSelector: '.trick-card',
        columnWidth: '.trick-card'//,
        //transitionDuration: 0
    });
    $('.js-goto-trick a').click(function(e) { e.stopPropagation() });

    $('.js-goto-trick').click(function(e)
    {
        e.preventDefault();
        var url = "{{ route('tricks.show') }}";
        var slug = $(this).data('slug');
        window.location = url + '/' + slug;
    });
});


text:
import { assert } from 'chai';

import { isPromise } from '../jsutils/isPromise.js';
import type { PromiseOrValue } from '../jsutils/PromiseOrValue.js';

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

export function expectEqualPromisesOrValues<T>(
  items: ReadonlyArray<PromiseOrValue<T>>,
): PromiseOrValue<T> {
  const [firstItem, ...remainingItems] = items;
  if (isPromise(firstItem)) {
    if (remainingItems.every(isPromise)) {
      return Promise.all(items).then(expectMatchingValues);
    }
  } else if (remainingItems.every((item) => !isPromise(item))) {
    return expectMatchingValues(items);
  }

  assert(false, 'Received an invalid mixture of promises and values.');
}


text:
title: get_masterTableViewHeader()
page_title: get_masterTableViewHeader() | RadGrid for ASP.NET AJAX Documentation
description: get_masterTableViewHeader()
slug: grid/client-side-programming/radgrid-object/properties/get_mastertableviewheader()
tags: get_mastertableviewheader()
published: True
position: 10
---

# get_masterTableViewHeader()

##

This property returns the MasterTableView header instance for the respective grid client object.

|  **get_masterTableViewHeader()**  |
| ------ |
||

Example:

````JavaScript
function getMasterTableViewHeader() {
    var grid = $find("<%=RadGrid1.ClientID %>");
    var masterTableViewHeader = grid.get_masterTableViewHeader();
}
````

>note Please, keep in mind that this property would only return a non-null value when scrolling with static headers is enabled:
>

````ASP.NET
<clientsettings>
        <Scrolling AllowScroll="true" UseStaticHeaders="true" />
</clientsettings>
````

In all other cases, this property will return a null value.