text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Languages.Interfaces;
using StockExchangeGame.Database.Models;

namespace StockExchangeGame.Database.Generic
{
    // ReSharper disable once UnusedMember.Global
    public class DatabaseAdapter : IDatabaseAdapter
    {
        private const string SqlDbFileName = "StockGame.sqlite3";
        private IEntityController<Bought> _boughtController;
        private IEntityController<CompanyEndings> _companyEndingsController;
        private IEntityController<CompanyNames> _companyNamesController;
        private SQLiteConnection _connection;
        private ILanguage _currentLanguage;
        private IEntityController<DummyCompany> _dummyCompanyController;
        private IEntityController<Merchant> _merchantController;
        private IEntityController<Names> _namesController;
        private IEntityController<Sold> _soldController;
        private IEntityController<Stock> _stockController;
        private IEntityController<StockHistory> _stockHistoryController;
        private IEntityController<StockMarket> _stockMarketController;
        private IEntityController<Surnames> _surnamesController;
        private IEntityController<Taxes> _taxesController;

        public DatabaseAdapter(ILanguage language)
        {
            InitializeControllers(GetConnectionString());
            SetCurrentLanguage(language);
            CreateDatabaseFileIfNotExists();
        }

        public void SetCurrentLanguage(ILanguage language)
        {
            _currentLanguage = language;
            SetLanguages(language);
        }

        public ILanguage GetCurrentLanguage()
        {
            return _currentLanguage;
        }

        public string GetConnectionString()
        {
            return @"Data Source=" + GetDatabasePath() + "; " +
                   @"Version=3; FailIfMissing=True; Foreign Keys=True;";
        }

        public string GetDatabasePath()
        {
            var location = Assembly.GetExecutingAssembly().Location;
            return Path.Combine(Directory.GetParent(location).FullName, SqlDbFileName);
        }

        public void CreateBoughtTable()
        {
            _boughtController.CreateTable();
        }

        public void CreateCompanyEndingsTable()
        {
            _companyEndingsController.CreateTable();
        }

        public void CreateCompanyNamesTable()
        {
            _companyNamesController.CreateTable();
        }

        public void CreateDummyCompanyTable()
        {
            _dummyCompanyController.CreateTable();
        }

        public void CreateMerchantTable()
        {
            _merchantController.CreateTable();
        }

        public void CreateNamesTable()
        {
            _namesController.CreateTable();
        }

        public void CreateSoldTable()
        {
            _soldController.CreateTable();
        }

        public void CreateStockTable()
        {
            _stockController.CreateTable();
        }

        public void CreateStockHistoryTable()
        {
            _stockHistoryController.CreateTable();
        }

        public void CreateStockMarketTable()
        {
            _stockMarketController.CreateTable();
        }

        public void CreateSurnamesTable()
        {
            _surnamesController.CreateTable();
        }

        public void CreateTaxesTable()
        {
            _taxesController.CreateTable();
        }

        public void CreateAllTables()
        {
            CreateBoughtTable();
            CreateCompanyEndingsTable();
            CreateCompanyNamesTable();
            CreateDummyCompanyTable();
            CreateMerchantTable();
            CreateNamesTable();
            CreateSoldTable();
            CreateStockTable();
            CreateStockHistoryTable();
            CreateStockMarketTable();
            CreateSurnamesTable();
            CreateTaxesTable();
        }

        public List<T> Get<T>()
        {
            if (typeof(T) == typeof(Bought))
                return _boughtController.Get() as List<T>;
            if (typeof(T) == typeof(CompanyEndings))
                return _companyEndingsController.Get() as List<T>;
            if (typeof(T) == typeof(CompanyNames))
                return _companyNamesController.Get() as List<T>;
            if (typeof(T) == typeof(DummyCompany))
                return _dummyCompanyController.Get() as List<T>;
            if (typeof(T) == typeof(Merchant))
                return _merchantController.Get() as List<T>;
            if (typeof(T) == typeof(Names))
                return _namesController.Get() as List<T>;
            if (typeof(T) == typeof(Sold))
                return _soldController.Get() as List<T>;
            if (typeof(T) == typeof(Stock))
                return _stockController.Get() as List<T>;
            if (typeof(T) == typeof(StockHistory))
                return _stockHistoryController.Get() as List<T>;
            if (typeof(T) == typeof(StockMarket))
                return _stockMarketController.Get() as List<T>;
            if (typeof(T) == typeof(Surnames))
                return _surnamesController.Get() as List<T>;
            if (typeof(T) == typeof(Taxes))
                return _taxesController.Get() as List<T>;
            return null;
        }

        public T Get<T>(long id)
        {
            if (typeof(T) == typeof(Bought))
            {
                var value = _boughtController.Get(id);
                return (T) Convert.ChangeType(value, typeof(T));
            }
            if (typeof(T) == typeof(CompanyEndings))
            {
                var value = _companyEndingsController.Get(id);
                return (T) Convert.ChangeType(value, typeof(T));
            }
            if (typeof(T) == typeof(CompanyNames))
            {
                var value = _companyNamesController.Get(id);
                return (T) Convert.ChangeType(value, typeof(T));
            }
            if (typeof(T) == typeof(DummyCompany))
            {
                var value = _dummyCompanyController.Get(id);
                return (T) Convert.ChangeType(value, typeof(T));
            }
            if (typeof(T) == typeof(Merchant))
            {
                var value = _merchantController.Get(id);
                return (T) Convert.ChangeType(value, typeof(T));
            }
            if (typeof(T) == typeof(Names))
            {
                var value = _namesController.Get(id);
                return (T) Convert.ChangeType(value, typeof(T));
            }
            if (typeof(T) == typeof(Sold))
            {
                var value = _soldController.Get(id);
                return (T) Convert.ChangeType(value, typeof(T));
            }
            if (typeof(T) == typeof(Stock))
            {
                var value = _stockController.Get(id);
                return (T) Convert.ChangeType(value, typeof(T));
            }
            if (typeof(T) == typeof(StockHistory))
            {
                var value = _stockHistoryController.Get(id);
                return (T) Convert.ChangeType(value, typeof(T));
            }
            if (typeof(T) == typeof(StockMarket))
            {
                var value = _stockMarketController.Get(id);
                return (T) Convert.ChangeType(value, typeof(T));
            }
            if (typeof(T) == typeof(Surnames))
            {
                var value = _surnamesController.Get(id);
                return (T) Convert.ChangeType(value, typeof(T));
            }
            if (typeof(T) != typeof(Taxes)) return (T) Convert.ChangeType(null, typeof(T));
            {
                var value = _taxesController.Get(id);
                return (T) Convert.ChangeType(value, typeof(T));
            }
        }

        private void InitializeControllers(string connectionString)
        {
            _connection = new SQLiteConnection(connectionString);
            _boughtController = new BoughtController(_connection);
            _companyEndingsController = new CompanyEndingsController(_connection);
            _companyNamesController = new CompanyNamesController(_connection);
            _dummyCompanyController = new DummyCompanyController(_connection);
            _merchantController = new MerchantController(_connection);
            _namesController = new NamesController(_connection);
            _soldController = new SoldController(_connection);
            _stockController = new StockController(_connection);
            _stockHistoryController = new StockHistoryController(_connection);
            _stockMarketController = new StockMarketController(_connection);
            _surnamesController = new SurnamesController(_connection);
            _taxesController = new TaxesController(_connection);
        }

        private void SetLanguages(ILanguage language)
        {
            _boughtController.SetCurrentLanguage(language);
            _boughtController.SetCurrentLanguage(language);
            _companyEndingsController.SetCurrentLanguage(language);
            _companyNamesController.SetCurrentLanguage(language);
            _dummyCompanyController.SetCurrentLanguage(language);
            _merchantController.SetCurrentLanguage(language);
            _namesController.SetCurrentLanguage(language);
            _soldController.SetCurrentLanguage(language);
            _stockController.SetCurrentLanguage(language);
            _stockHistoryController.SetCurrentLanguage(language);
            _stockMarketController.SetCurrentLanguage(language);
            _surnamesController.SetCurrentLanguage(language);
            _taxesController.SetCurrentLanguage(language);
        }

        private void CreateDatabaseFileIfNotExists()
        {
            var databasePath = GetDatabasePath();
            if (File.Exists(databasePath))
            {
                CreateAllTables();
                return;
            }
            CreateDatabaseAndTables(databasePath);
        }

        private void CreateDatabaseAndTables(string databasePath)
        {
            File.Create(databasePath);
            CreateAllTables();
        }

        public ObservableCollection<T> Get<T, TValue>(Expression<Func<T, bool>> predicate = null,
            Expression<Func<T, TValue>> orderBy = null)
        {
            // ReSharper disable SuspiciousTypeConversion.Global
            // ReSharper disable ExpressionIsAlwaysNull
            if (typeof(T) == typeof(Bought))
                // ReSharper disable once SuspiciousTypeConversion.Global
                // ReSharper disable once ExpressionIsAlwaysNull
                return _boughtController.Get(predicate as Expression<Func<Bought, bool>>,
                    // ReSharper disable once SuspiciousTypeConversion.Global
                    // ReSharper disable once ExpressionIsAlwaysNull
                    orderBy as Expression<Func<Bought, TValue>>) as ObservableCollection<T>;
            if (typeof(T) == typeof(CompanyEndings))
                // ReSharper disable once SuspiciousTypeConversion.Global
                // ReSharper disable once ExpressionIsAlwaysNull
                return _companyEndingsController.Get(predicate as Expression<Func<CompanyEndings, bool>>,
                    // ReSharper disable once SuspiciousTypeConversion.Global
                    // ReSharper disable once ExpressionIsAlwaysNull
                    orderBy as Expression<Func<CompanyEndings, TValue>>) as ObservableCollection<T>;
            if (typeof(T) == typeof(CompanyNames))
                // ReSharper disable once SuspiciousTypeConversion.Global
                // ReSharper disable once ExpressionIsAlwaysNull
                return _companyNamesController.Get(predicate as Expression<Func<CompanyNames, bool>>,
                    // ReSharper disable once SuspiciousTypeConversion.Global
                    // ReSharper disable once ExpressionIsAlwaysNull
                    orderBy as Expression<Func<CompanyNames, TValue>>) as ObservableCollection<T>;
            if (typeof(T) == typeof(DummyCompany))
                // ReSharper disable once SuspiciousTypeConversion.Global
                // ReSharper disable once ExpressionIsAlwaysNull
                return _dummyCompanyController.Get(predicate as Expression<Func<DummyCompany, bool>>,
                    // ReSharper disable once SuspiciousTypeConversion.Global
                    // ReSharper disable once ExpressionIsAlwaysNull
                    orderBy as Expression<Func<DummyCompany, TValue>>) as ObservableCollection<T>;
            if (typeof(T) == typeof(Merchant))
                // ReSharper disable once SuspiciousTypeConversion.Global
                // ReSharper disable once ExpressionIsAlwaysNull
                return _merchantController.Get(predicate as Expression<Func<Merchant, bool>>,
                    // ReSharper disable once SuspiciousTypeConversion.Global
                    // ReSharper disable once ExpressionIsAlwaysNull
                    orderBy as Expression<Func<Merchant, TValue>>) as ObservableCollection<T>;
            if (typeof(T) == typeof(Names))
                // ReSharper disable once SuspiciousTypeConversion.Global
                // ReSharper disable once ExpressionIsAlwaysNull
                return _namesController.Get(predicate as Expression<Func<Names, bool>>,
                    // ReSharper disable once SuspiciousTypeConversion.Global
                    // ReSharper disable once ExpressionIsAlwaysNull
                    orderBy as Expression<Func<Names, TValue>>) as ObservableCollection<T>;
            if (typeof(T) == typeof(Sold))
                // ReSharper disable once SuspiciousTypeConversion.Global
                // ReSharper disable once ExpressionIsAlwaysNull
                return _soldController.Get(predicate as Expression<Func<Sold, bool>>,
                    // ReSharper disable once SuspiciousTypeConversion.Global
                    // ReSharper disable once ExpressionIsAlwaysNull
                    orderBy as Expression<Func<Sold, TValue>>) as ObservableCollection<T>;
            if (typeof(T) == typeof(Stock))
                // ReSharper disable once SuspiciousTypeConversion.Global
                // ReSharper disable once ExpressionIsAlwaysNull
                return _stockController.Get(predicate as Expression<Func<Stock, bool>>,
                    // ReSharper disable once SuspiciousTypeConversion.Global
                    // ReSharper disable once ExpressionIsAlwaysNull
                    orderBy as Expression<Func<Stock, TValue>>) as ObservableCollection<T>;
            if (typeof(T) == typeof(StockHistory))
                // ReSharper disable once SuspiciousTypeConversion.Global
                // ReSharper disable once ExpressionIsAlwaysNull
                return _stockHistoryController.Get(predicate as Expression<Func<StockHistory, bool>>,
                    // ReSharper disable once SuspiciousTypeConversion.Global
                    // ReSharper disable once ExpressionIsAlwaysNull
                    orderBy as Expression<Func<StockHistory, TValue>>) as ObservableCollection<T>;
            if (typeof(T) == typeof(StockMarket))
                // ReSharper disable once SuspiciousTypeConversion.Global
                // ReSharper disable once ExpressionIsAlwaysNull
                return _stockMarketController.Get(predicate as Expression<Func<StockMarket, bool>>,
                    // ReSharper disable once SuspiciousTypeConversion.Global
                    // ReSharper disable once ExpressionIsAlwaysNull
                    orderBy as Expression<Func<StockMarket, TValue>>) as ObservableCollection<T>;
            if (typeof(T) == typeof(Surnames))
                // ReSharper disable once SuspiciousTypeConversion.Global
                // ReSharper disable once ExpressionIsAlwaysNull
                return _surnamesController.Get(predicate as Expression<Func<Surnames, bool>>,
                    // ReSharper disable once SuspiciousTypeConversion.Global
                    // ReSharper disable once ExpressionIsAlwaysNull
                    orderBy as Expression<Func<Surnames, TValue>>) as ObservableCollection<T>;
            if (typeof(T) == typeof(Taxes))
                // ReSharper disable once SuspiciousTypeConversion.Global
                // ReSharper disable once ExpressionIsAlwaysNull
                return _taxesController.Get(predicate as Expression<Func<Taxes, bool>>,
                    // ReSharper disable once SuspiciousTypeConversion.Global
                    // ReSharper disable once ExpressionIsAlwaysNull
                    orderBy as Expression<Func<Taxes, TValue>>) as ObservableCollection<T>;
            return null;
        }

        public T Get<T>(Expression<Func<T, bool>> predicate)
        {
            // ReSharper disable SuspiciousTypeConversion.Global
            // ReSharper disable ExpressionIsAlwaysNull
            if (typeof(T) == typeof(Bought))
            {
                // ReSharper disable once ExpressionIsAlwaysNull
                // ReSharper disable once SuspiciousTypeConversion.Global
                var value = _boughtController.Get(predicate as Expression<Func<Bought, bool>>);
                return (T) Convert.ChangeType(value, typeof(T));
            }
            if (typeof(T) == typeof(CompanyEndings))
            {
                // ReSharper disable once ExpressionIsAlwaysNull
                // ReSharper disable once SuspiciousTypeConversion.Global
                var value = _companyEndingsController.Get(predicate as Expression<Func<CompanyEndings, bool>>);
                return (T) Convert.ChangeType(value, typeof(T));
            }
            if (typeof(T) == typeof(CompanyNames))
            {
                // ReSharper disable once ExpressionIsAlwaysNull
                // ReSharper disable once SuspiciousTypeConversion.Global
                var value = _companyNamesController.Get(predicate as Expression<Func<CompanyNames, bool>>);
                return (T) Convert.ChangeType(value, typeof(T));
            }
            if (typeof(T) == typeof(DummyCompany))
            {
                // ReSharper disable once ExpressionIsAlwaysNull
                // ReSharper disable once SuspiciousTypeConversion.Global
                var value = _dummyCompanyController.Get(predicate as Expression<Func<DummyCompany, bool>>);
                return (T) Convert.ChangeType(value, typeof(T));
            }
            if (typeof(T) == typeof(Merchant))
            {
                // ReSharper disable once ExpressionIsAlwaysNull
                // ReSharper disable once SuspiciousTypeConversion.Global
                var value = _merchantController.Get(predicate as Expression<Func<Merchant, bool>>);
                return (T) Convert.ChangeType(value, typeof(T));
            }
            if (typeof(T) == typeof(Names))
            {
                // ReSharper disable once ExpressionIsAlwaysNull
                // ReSharper disable once SuspiciousTypeConversion.Global
                var value = _namesController.Get(predicate as Expression<Func<Names, bool>>);
                return (T) Convert.ChangeType(value, typeof(T));
            }
            if (typeof(T) == typeof(Sold))
            {
                // ReSharper disable once ExpressionIsAlwaysNull
                // ReSharper disable once SuspiciousTypeConversion.Global
                var value = _soldController.Get(predicate as Expression<Func<Sold, bool>>);
                return (T) Convert.ChangeType(value, typeof(T));
            }
            if (typeof(T) == typeof(Stock))
            {
                // ReSharper disable once ExpressionIsAlwaysNull
                // ReSharper disable once SuspiciousTypeConversion.Global
                var value = _stockController.Get(predicate as Expression<Func<Stock, bool>>);
                return (T) Convert.ChangeType(value, typeof(T));
            }
            if (typeof(T) == typeof(StockHistory))
            {
                // ReSharper disable once ExpressionIsAlwaysNull
                // ReSharper disable once SuspiciousTypeConversion.Global
                var value = _stockHistoryController.Get(predicate as Expression<Func<StockHistory, bool>>);
                return (T) Convert.ChangeType(value, typeof(T));
            }
            if (typeof(T) == typeof(StockMarket))
            {
                // ReSharper disable once ExpressionIsAlwaysNull
                // ReSharper disable once SuspiciousTypeConversion.Global
                var value = _stockMarketController.Get(predicate as Expression<Func<StockMarket, bool>>);
                return (T) Convert.ChangeType(value, typeof(T));
            }
            if (typeof(T) == typeof(Surnames))
            {
                // ReSharper disable once ExpressionIsAlwaysNull
                // ReSharper disable once SuspiciousTypeConversion.Global
                var value = _surnamesController.Get(predicate as Expression<Func<Surnames, bool>>);
                return (T) Convert.ChangeType(value, typeof(T));
            }
            if (typeof(T) != typeof(Taxes)) return (T) Convert.ChangeType(null, typeof(T));
            {
                // ReSharper disable once ExpressionIsAlwaysNull
                // ReSharper disable once SuspiciousTypeConversion.Global
                var value = _taxesController.Get(predicate as Expression<Func<Taxes, bool>>);
                return (T) Convert.ChangeType(value, typeof(T));
            }
        }

        public int Insert<T>(T entity)
        {
            if (typeof(T) == typeof(Bought))
                return _boughtController.Insert(entity as Bought);
            if (typeof(T) == typeof(CompanyEndings))
                return _companyEndingsController.Insert(entity as CompanyEndings);
            if (typeof(T) == typeof(CompanyNames))
                return _companyNamesController.Insert(entity as CompanyNames);
            if (typeof(T) == typeof(DummyCompany))
                return _dummyCompanyController.Insert(entity as DummyCompany);
            if (typeof(T) == typeof(Merchant))
                return _merchantController.Insert(entity as Merchant);
            if (typeof(T) == typeof(Names))
                return _namesController.Insert(entity as Names);
            if (typeof(T) == typeof(Sold))
                return _soldController.Insert(entity as Sold);
            if (typeof(T) == typeof(Stock))
                return _stockController.Insert(entity as Stock);
            if (typeof(T) == typeof(StockHistory))
                return _stockHistoryController.Insert(entity as StockHistory);
            if (typeof(T) == typeof(StockMarket))
                return _stockMarketController.Insert(entity as StockMarket);
            if (typeof(T) == typeof(Surnames))
                return _surnamesController.Insert(entity as Surnames);
            if (typeof(T) == typeof(Taxes))
                return _taxesController.Insert(entity as Taxes);
            return -1;
        }

        public int Update<T>(T entity)
        {
            if (typeof(T) == typeof(Bought))
                return _boughtController.Update(entity as Bought);
            if (typeof(T) == typeof(CompanyEndings))
                return _companyEndingsController.Update(entity as CompanyEndings);
            if (typeof(T) == typeof(CompanyNames))
                return _companyNamesController.Update(entity as CompanyNames);
            if (typeof(T) == typeof(DummyCompany))
                return _dummyCompanyController.Update(entity as DummyCompany);
            if (typeof(T) == typeof(Merchant))
                return _merchantController.Update(entity as Merchant);
            if (typeof(T) == typeof(Names))
                return _namesController.Update(entity as Names);
            if (typeof(T) == typeof(Sold))
                return _soldController.Update(entity as Sold);
            if (typeof(T) == typeof(Stock))
                return _stockController.Update(entity as Stock);
            if (typeof(T) == typeof(StockHistory))
                return _stockHistoryController.Update(entity as StockHistory);
            if (typeof(T) == typeof(StockMarket))
                return _stockMarketController.Update(entity as StockMarket);
            if (typeof(T) == typeof(Surnames))
                return _surnamesController.Update(entity as Surnames);
            if (typeof(T) == typeof(Taxes))
                return _taxesController.Update(entity as Taxes);
            return -1;
        }

        public int Delete<T>(T entity)
        {
            if (typeof(T) == typeof(Bought))
                return _boughtController.Delete(entity as Bought);
            if (typeof(T) == typeof(CompanyEndings))
                return _companyEndingsController.Delete(entity as CompanyEndings);
            if (typeof(T) == typeof(CompanyNames))
                return _companyNamesController.Delete(entity as CompanyNames);
            if (typeof(T) == typeof(DummyCompany))
                return _dummyCompanyController.Delete(entity as DummyCompany);
            if (typeof(T) == typeof(Merchant))
                return _merchantController.Delete(entity as Merchant);
            if (typeof(T) == typeof(Names))
                return _namesController.Delete(entity as Names);
            if (typeof(T) == typeof(Sold))
                return _soldController.Delete(entity as Sold);
            if (typeof(T) == typeof(Stock))
                return _stockController.Delete(entity as Stock);
            if (typeof(T) == typeof(StockHistory))
                return _stockHistoryController.Delete(entity as StockHistory);
            if (typeof(T) == typeof(StockMarket))
                return _stockMarketController.Delete(entity as StockMarket);
            if (typeof(T) == typeof(Surnames))
                return _surnamesController.Delete(entity as Surnames);
            if (typeof(T) == typeof(Taxes))
                return _taxesController.Delete(entity as Taxes);
            return -1;
        }

        public int Insert<T>(List<T> entities)
        {
            return entities.Sum(Insert);
        }

        public int Update<T>(List<T> entities)
        {
            return entities.Sum(Update);
        }

        public int Delete<T>(List<T> entities)
        {
            return entities.Sum(Delete);
        }

        public int Count<T>(Expression<Func<T, bool>> predicate = null)
        {
            // ReSharper disable ExpressionIsAlwaysNull
            // ReSharper disable SuspiciousTypeConversion.Global
            if (typeof(T) == typeof(Bought))
                return _boughtController.Count(predicate as Expression<Func<Bought, bool>>);
            if (typeof(T) == typeof(CompanyEndings))
                return _companyEndingsController.Count(predicate as Expression<Func<CompanyEndings, bool>>);
            if (typeof(T) == typeof(CompanyNames))
                return _companyNamesController.Count(predicate as Expression<Func<CompanyNames, bool>>);
            if (typeof(T) == typeof(DummyCompany))
                return _dummyCompanyController.Count(predicate as Expression<Func<DummyCompany, bool>>);
            if (typeof(T) == typeof(Merchant))
                return _merchantController.Count(predicate as Expression<Func<Merchant, bool>>);
            if (typeof(T) == typeof(Names))
                return _namesController.Count(predicate as Expression<Func<Names, bool>>);
            if (typeof(T) == typeof(Sold))
                return _soldController.Count(predicate as Expression<Func<Sold, bool>>);
            if (typeof(T) == typeof(Stock))
                return _stockController.Count(predicate as Expression<Func<Stock, bool>>);
            if (typeof(T) == typeof(StockHistory))
                return _stockHistoryController.Count(predicate as Expression<Func<StockHistory, bool>>);
            if (typeof(T) == typeof(StockMarket))
                return _stockMarketController.Count(predicate as Expression<Func<StockMarket, bool>>);
            if (typeof(T) == typeof(Surnames))
                return _surnamesController.Count(predicate as Expression<Func<Surnames, bool>>);
            if (typeof(T) == typeof(Taxes))
                return _taxesController.Count(predicate as Expression<Func<Taxes, bool>>);
            return -1;
        }

        public void Truncate<T>()
        {
            if (typeof(T) == typeof(Bought))
            {
                _boughtController.Truncate();
                return;
            }
            if (typeof(T) == typeof(CompanyEndings))
            {
                _companyEndingsController.Truncate();
                return;
            }
            if (typeof(T) == typeof(CompanyNames))
            {
                _companyNamesController.Truncate();
                return;
            }
            if (typeof(T) == typeof(DummyCompany))
            {
                _dummyCompanyController.Truncate();
                return;
            }
            if (typeof(T) == typeof(Merchant))
            {
                _merchantController.Truncate();
                return;
            }
            if (typeof(T) == typeof(Names))
            {
                _namesController.Truncate();
                return;
            }
            if (typeof(T) == typeof(Sold))
            {
                _soldController.Truncate();
                return;
            }
            if (typeof(T) == typeof(Stock))
            {
                _stockController.Truncate();
                return;
            }
            if (typeof(T) == typeof(StockHistory))
            {
                _stockHistoryController.Truncate();
                return;
            }
            if (typeof(T) == typeof(StockMarket))
            {
                _stockMarketController.Truncate();
                return;
            }
            if (typeof(T) == typeof(Surnames))
            {
                _surnamesController.Truncate();
                return;
            }
            if (typeof(T) == typeof(Taxes))
                _taxesController.Truncate();
        }
    }
}


text:
id: 5364
title: 'The Russian Jersey Shore: No one is ready.'
date: 2011-07-27T12:11:01+00:00
author: Vicki
layout: post
guid: http://blog.vickiboykis.com/wlb/?p=5364
permalink: /2011/07/the-russian-jersey-shore-no-one-is-ready/
categories:
  - Uncategorized
tags:
  - brighton beach
  - Jersey Shore
  - Russian
  - Russian Jews
---
#### Edit: Ok, I give in.  I’m liveblogging it!  Come back here August 11 for fun. I’ll remind you, don’t worry.

Are you guys ready for this? (via everyone I know who sent me this link. )

I don’t think I’m ready.

[](https://raw.githubusercontent.com/veekaybee/wlb/gh-pages/assets/images/2011/07/Screen-shot-2011-07-26-at-11.45.53-AM.png)

Should I liveblog it?

redpajama_set_name: RedPajamaGithub


text:
define(
   ({
    _widgetLabel: "Yazdır",
    title: "Harita Başlığı",
    format: "Biçim",
    layout: "Düzen",
    settings: "Gelişmiş",
    mapScaleExtent: "Harita ölçeği/yayılımı",
    preserve: "Koru",
    mapScale: "harita ölçeği",
    mapExtent: "harita yayılımı",
    forceScale: "Ölçeği zorla",
    getCurrentScale: "mevcut",
    mapMetadata: "Düzen meta verisi",
    author: "Yazar",
    copyright: "Telif Hakkı",
    fullLayoutOptions: "Tam düzen seçenekleri",
    scaleBarUnitsMetric: "Ölçek çubuğu birimi, metrik",
    scaleBarUnitsNonMetric: "Ölçek çubuğu birimi, metrik olmayan",
    unitsMiles: "Mil",
    unitsKilometers: "Kilometre",
    unitsMeters: "Metre",
    unitsFeet: "Fit",
    unitsYards: "Yarda",
    unitsNauticalMiles: "Deniz Mili",
    lncludeLegend: "Gösterim ekle",
    printQualityOptions: "Baskı kalitesi",
    dpi: "DPI",
    mapOnlyOptions: "MAP_ONLY boyutu",
    width: "Genişlik (px)",
    height: "Yükseklik (px)",
    print: "Yazdır",
    clearList: "Baskıları Temizle",
    creatingPrint: "Baskı Oluşturuluyor",
    printError: "Hata, yeniden deneyin"
  })
);


text:
package main

import (
	"strings"

	"github.com/rs/zerolog/log"
	"github.com/spf13/cobra"
	"github.com/spf13/pflag"
	"github.com/spf13/viper"

	"github.com/capitalone/cloud-custodian/tools/omnissm/pkg/aws/ssm"
	"github.com/capitalone/cloud-custodian/tools/omnissm/pkg/omnissm"
)

var RegisterCmd = &cobra.Command{
	Use:   "register",
	Short: "",
	Run: func(cmd *cobra.Command, args []string) {
		url := viper.GetString("register_endpoint")
		if url == "" {
			log.Fatal().Msg("registration url (OMNISSM_REGISTER_ENDPOINT) cannot be blank")
		}
		c, err := omnissm.NewClient(url)
		if err != nil {
			log.Fatal().Msgf("unable to initialize node: %v", err)
		}
		if ssm.IsManagedInstance(c.ManagedId) {
			log.Info().Str("ManagedId", c.ManagedId).Msg("instance already registered")
			return
		}
		log.Info().Msg("attempting to register instance ...")
		if err := c.Register(); err != nil {
			log.Fatal().Msgf("cannot register instance: %v", err)
		}
		if err := c.Update(); err != nil {
			log.Fatal().Msgf("cannot update instance ManagedId: %v", err)
		}
		log.Info().Str("ManagedId", c.ManagedId).Msg("instance registered")
	},
}

func init() {
	RegisterCmd.Flags().String("register-endpoint", "", "")
	RegisterCmd.LocalFlags().VisitAll(func(f *pflag.Flag) {
		viper.BindPFlag(strings.Replace(f.Name, "-", "_", -1), RegisterCmd.Flags().Lookup(f.Name))
	})
}


text:
package wxalogin

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"

	"gopkg.in/goyy/goyy.v0/comm/xtype"
	"gopkg.in/goyy/goyy.v0/util/strings"
	"gopkg.in/goyy/goyy.v0/util/times"
	"gopkg.in/goyy/goyy.v0/web/controller"
	"gopkg.in/goyy/goyy.v0/web/xhttp"
)

func init() {
	xhttp.GET("/wxalogin", ctl.login)
}

func (me *Controller) login(c xhttp.Context) {
	code := c.Param("code")
	r := res{Success: true}
	if strings.IsBlank(code) || code == "null" || code == "undefined" {
		logger.Errorln("login.code err:", code)
		r.Success = false
	} else {
		r := getWxInfo(code)
		if r.Success {
			var p *xtype.Principal
			if Wx2Principal != nil {
				p = Wx2Principal(r.OpenId, r.UnionId, r.SessionKey)
			} else {
				p = getPrincipal(r)
			}
			err := c.Session().SetPrincipal(*p)
			if err != nil {
				logger.Errorln("login.SetPrincipal err:", err)
			}
		}
	}
	r.Token = c.Session().Id()
	err := c.JSON(xhttp.StatusOK, r)
	if err != nil {
		logger.Errorln("response err:", err)
	}
}

func getPrincipal(r *result) *xtype.Principal {
	id, ok := getUserId(r.UnionId)
	if !ok {
		id = createUser(r.UnionId, r.OpenId)
	}
	p := &xtype.Principal{
		Id:        id,
		Code:      r.OpenId,
		Key:       r.SessionKey,
		LoginName: r.UnionId,
		LoginTime: times.NowUnixStr(),
	}
	return p
}

func getWxInfo(code string) *result {
	// http request
	url := "https://api.weixin.qq.com/sns/jscode2session"
	query := fmt.Sprintf("?appid=%v&secret=%v&js_code=%v&grant_type=authorization_code", AppId, AppSecret, code)
	resp, err := http.Get(url + query)
	if err != nil {
		logger.Errorln("getWxInfo.Get err:", err)
		return &result{Success: false}
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		logger.Errorln("getWxInfo.ReadAll err:", err)
		return &result{Success: false}
	}
	// json unmarshal
	r := &result{Success: true}
	err = json.Unmarshal(body, r)
	if err != nil {
		logger.Errorln("getWxInfo.Unmarshal err:", err)
		return &result{Success: false}
	}
	if strings.IsBlank(r.OpenId) {
		r.Success = false
	} else {
		if strings.IsBlank(r.UnionId) {
			r.UnionId = r.OpenId
		}
	}
	return r
}

type res struct {
	Success bool   `json:"success"`
	Token   string `json:"token"`
	Message string `json:"message"`
}

type result struct {
	Success    bool   `json:"success"`
	OpenId     string `json:"openid"`
	SessionKey string `json:"session_key"`
	UnionId    string `json:"unionid"`
	ErrCode    int    `json:"errcode"`
	ErrMsg     string `json:"errmsg"`
}

type Controller struct {
	controller.JSONController
}

var ctl = &Controller{}


text:
/**
 * A mock implementation of the Windows shell execute API.
 * This is used for our tests
 */
'use strict';
require('ref');
var debug = require('debug')('windows-registry'),
    assert = require('assert'),
    struct = require('ref-struct'),
    uniontype = require('ref-union'),
    types = require('../../lib/types');

var DUMMYUNIONNAME = uniontype({
    hIcon: types.HANDLE,
    hMonitor: types.HANDLE
});

var SHELLEXECUTEINFO  = struct({
    cbSize: types.DWORD,
    fMask: types.ULONG,
    hwnd: types.HWND,
    lpVerb:  types.STRING,
    lpFile:  types.STRING,
    lpParameters: types.STRING,
    lpDirectory: types.STRING,
    nShow: types.INT,
    hInstApp: types.HINSTANCE,
    lpIDList: types.LPVOID,
    lpClass: types.STRING,
    hkeyClass: types.HKEY,
    dwHotKey: types.DWORD,
    DUMMYUNIONNAME: DUMMYUNIONNAME,
    hProcess: types.HANDLE
});

var shell32Mock = {
    ShellExecuteExA: function () {
    }
};
shell32Mock.ShellExecuteExA.async = function (type, cb) {
    debug('async');
    debug(type.deref().lpFile);
    assert.deepEqual(type.type.fields.cbSize, SHELLEXECUTEINFO.fields.cbSize);
    cb(null, true);
};

module.exports = shell32Mock;


text:
/*
 * SMagic.java
 *
 * Control statements use this class
 *
 */

package cross;

/**
 *
 * @author Dar
 */
public class SMagic extends Scalar{

    Node val;
    /** Creates a new instance of SMagic */
    public SMagic(Node n,Script s) {
        super(s);
        val = n;
    }

    public Scalar eval(){
        return (new Evaluator(val,script)).eval();
    }

    public Scalar eval(Scalar arg){
        if(!(val instanceof BranchNode)){
            System.out.println("Bad things are happening with a control statement");
            //This is a problem
            return new Scalar(script);
        } else {
            Node n = ((BranchNode)val).getBranch(arg);
            if(n==null){
                return new Scalar(script);
            }
            return new Evaluator(n,script).eval();
        }
    }

}


text:
import store from "./store"
import faviconLocked from "./favicon.png"
import faviconUnlocked from "./favicon-unlocked.png"

function render() {
  const favicon = store.loggedIn ? faviconUnlocked : faviconLocked
  document.querySelector("link[rel=icon]").setAttribute("href", favicon)
}

export function init() {
  store.register(render)
  render()
}


text: <include TaskForest::REST::Status /status2.html />


text:
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
	margin: 0;
	padding: 0;
	border: 0;
	font-size: 100%;
	font: inherit;
	vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
	display: block;
}
body {
	line-height: 1;
}
ol, ul {
	list-style: none;
}
blockquote, q {
	quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
	content: '';
	content: none;
}
table {
	border-collapse: collapse;
	border-spacing: 0;
}

.poketable{
	width: 30%
	float:left;
	height: 100%;
	overflow: scroll;
}

.pokerow{
	background-color: lightblue;
	border:1px solid black;
	width: 100%;
	height: 80px;
	line-height: 80px;
}

.avatar-container{
	width: 120px;
	display: inline-block;
	text-align: :center;

}
.avatar{
	vertical-align: :middle;
	max-width: 75px;
	max-width: 100px;
}

.pokechat{

}


text:
import pytest
from tests.lib import pyversion
from pip.vcs import VersionControl
from pip.vcs.bazaar import Bazaar
from pip.vcs.git import Git
from pip.vcs.subversion import Subversion
from mock import Mock
from pip._vendor.packaging.version import parse as parse_version

if pyversion >= '3':
    VERBOSE_FALSE = False
else:
    VERBOSE_FALSE = 0

@pytest.fixture
def git():
    git_url = 'http://github.com/pypa/pip-test-package'
    refs = {
        '0.1': 'a8992fc7ee17e5b9ece022417b64594423caca7c',
        '0.1.1': '7d654e66c8fa7149c165ddeffa5b56bc06619458',
        '0.1.2': 'f1c1020ebac81f9aeb5c766ff7a772f709e696ee',
        'foo': '5547fa909e83df8bd743d3978d6667497983a4b7',
        'bar': '5547fa909e83df8bd743d3978d6667497983a4b7',
        'master': '5547fa909e83df8bd743d3978d6667497983a4b7',
        'origin/master': '5547fa909e83df8bd743d3978d6667497983a4b7',
        'origin/HEAD': '5547fa909e83df8bd743d3978d6667497983a4b7',
    }
    sha = refs['foo']

    git = Git()
    git.get_url = Mock(return_value=git_url)
    git.get_revision = Mock(return_value=sha)
    git.get_short_refs = Mock(return_value=refs)
    return git

@pytest.fixture
def dist():
    dist = Mock()
    dist.egg_name = Mock(return_value='pip_test_package')
    return dist

def test_git_get_src_requirements(git, dist):
    ret = git.get_src_requirement(dist, location='.')

    assert ret == ''.join([
        'git+http://github.com/pypa/pip-test-package',
        '@5547fa909e83df8bd743d3978d6667497983a4b7',
        '#egg=pip_test_package'
    ])

@pytest.mark.parametrize('ref,result', (
    ('5547fa909e83df8bd743d3978d6667497983a4b7', True),
    ('5547fa909', True),
    ('abc123', False),
    ('foo', False),
))
def test_git_check_version(git, ref, result):
    assert git.check_version('foo', ref) is result

def test_translate_egg_surname():
    vc = VersionControl()
    assert vc.translate_egg_surname("foo") == "foo"
    assert vc.translate_egg_surname("foo/bar") == "foo_bar"
    assert vc.translate_egg_surname("foo/1.2.3") == "foo_1.2.3"

def test_bazaar_simple_urls():
    """
    Test bzr url support.

    SSH and launchpad have special handling.
    """
    http_bzr_repo = Bazaar(
        url='bzr+http://bzr.myproject.org/MyProject/trunk/#egg=MyProject'
    )
    https_bzr_repo = Bazaar(
        url='bzr+https://bzr.myproject.org/MyProject/trunk/#egg=MyProject'
    )
    ssh_bzr_repo = Bazaar(
        url='bzr+ssh://bzr.myproject.org/MyProject/trunk/#egg=MyProject'
    )
    ftp_bzr_repo = Bazaar(
        url='bzr+ftp://bzr.myproject.org/MyProject/trunk/#egg=MyProject'
    )
    sftp_bzr_repo = Bazaar(
        url='bzr+sftp://bzr.myproject.org/MyProject/trunk/#egg=MyProject'
    )
    launchpad_bzr_repo = Bazaar(
        url='bzr+lp:MyLaunchpadProject#egg=MyLaunchpadProject'
    )

    assert http_bzr_repo.get_url_rev() == (
        'http://bzr.myproject.org/MyProject/trunk/', None,
    )
    assert https_bzr_repo.get_url_rev() == (
        'https://bzr.myproject.org/MyProject/trunk/', None,
    )
    assert ssh_bzr_repo.get_url_rev() == (
        'bzr+ssh://bzr.myproject.org/MyProject/trunk/', None,
    )
    assert ftp_bzr_repo.get_url_rev() == (
        'ftp://bzr.myproject.org/MyProject/trunk/', None,
    )
    assert sftp_bzr_repo.get_url_rev() == (
        'sftp://bzr.myproject.org/MyProject/trunk/', None,
    )
    assert launchpad_bzr_repo.get_url_rev() == (
        'lp:MyLaunchpadProject', None,
    )

def test_subversion_remove_auth_from_url():
    # Check that the url is doctored appropriately to remove auth elements
    #    from the url
    svn_auth_url = 'https://user:pass@svnrepo.org/svn/project/tags/v0.2'
    expected_url = 'https://svnrepo.org/svn/project/tags/v0.2'
    url = Subversion.remove_auth_from_url(svn_auth_url)
    assert url == expected_url

    # Check that this doesn't impact urls without authentication'
    svn_noauth_url = 'https://svnrepo.org/svn/project/tags/v0.2'
    expected_url = svn_noauth_url
    url = Subversion.remove_auth_from_url(svn_noauth_url)
    assert url == expected_url

    # Check that links to specific revisions are handled properly
    svn_rev_url = 'https://user:pass@svnrepo.org/svn/project/trunk@8181'
    expected_url = 'https://svnrepo.org/svn/project/trunk@8181'
    url = Subversion.remove_auth_from_url(svn_rev_url)
    assert url == expected_url

    svn_rev_url = 'https://svnrepo.org/svn/project/trunk@8181'
    expected_url = 'https://svnrepo.org/svn/project/trunk@8181'
    url = Subversion.remove_auth_from_url(svn_rev_url)
    assert url == expected_url

def test_get_git_version():
    git_version = Git().get_git_version()
    assert git_version >= parse_version('1.0.0')


text:
import os
import subprocess
import sys

from workflow import Workflow3 as Workflow, MATCH_SUBSTRING
from workflow.background import run_in_background

import brew_actions
import helpers

GITHUB_SLUG = 'fniephaus/alfred-homebrew'

def execute(wf, cmd_list):
    brew_arch = helpers.get_brew_arch(wf)
    new_env = helpers.initialise_path(brew_arch)
    cmd, err = subprocess.Popen(cmd_list,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                env=new_env).communicate()
    if err:
        return err
    return cmd

def get_all_formulae():
    return execute(wf, ['brew', 'formulae']).splitlines()

def get_installed_formulae():
    return execute(wf, ['brew', 'list', '--versions']).splitlines()

def get_pinned_formulae():
    return execute(wf, ['brew', 'list', '--pinned', '--versions']).splitlines()

def get_outdated_formulae():
    return execute(wf, ['brew', 'outdated', '--formula']).splitlines()

def get_info():
    return execute(wf, ['brew', 'info'])

def get_commands(wf, query):
    result = execute(wf, ['brew', 'commands']).splitlines()
    commands = [x for x in result if ' ' not in x]
    query_filter = query.split()
    if len(query_filter) > 1:
        return wf.filter(query_filter[1], commands, match_on=MATCH_SUBSTRING)
    return commands

def get_all_services():
    services_response = execute(wf, ['brew', 'services', 'list']).splitlines()
    services_response.pop(0)
    services = []
    for serviceLine in services_response:
        services.append({'name': serviceLine.split()[0], 'status': serviceLine.split()[1]})
    return services

def filter_all_formulae(wf, query):
    formulae = wf.cached_data('brew_all_formulae',
                              get_all_formulae,
                              max_age=3600)
    query_filter = query.split()
    if len(query_filter) > 1:
        return wf.filter(query_filter[1], formulae, match_on=MATCH_SUBSTRING)
    return formulae

def filter_installed_formulae(wf, query):
    formulae = wf.cached_data('brew_installed_formulae',
                              get_installed_formulae,
                              max_age=3600)
    query_filter = query.split()
    if len(query_filter) > 1:
        return wf.filter(query_filter[1], formulae, match_on=MATCH_SUBSTRING)
    return formulae

def filter_pinned_formulae(wf, query):
    formulae = wf.cached_data('brew_pinned_formulae',
                              get_pinned_formulae,
                              max_age=3600)
    query_filter = query.split()
    if len(query_filter) > 1:
        return wf.filter(query_filter[1], formulae, match_on=MATCH_SUBSTRING)
    return formulae

def filter_outdated_formulae(wf, query):
    formulae = wf.cached_data('brew_outdated_formulae',
                              get_outdated_formulae,
                              max_age=3600)
    query_filter = query.split()
    if len(query_filter) > 1:
        return wf.filter(query_filter[1], formulae, match_on=MATCH_SUBSTRING)
    return formulae

def filter_all_services(wf, query):
    services = wf.cached_data('brew_all_services',
                              get_all_services,
                              session=True)
    query_filter = query.split()
    if len(query_filter) > 1:
        return wf.filter(query_filter[1], services, key=lambda x: x['name'], match_on=MATCH_SUBSTRING)
    return services

def add_service_actions(wf, service_name):
    wf.add_item('Run Service',
                'Run the service formula without registering to launch at login (or boot).',
                autocomplete='services %s run' % service_name,
                arg='brew services run %s' % service_name,
                valid=True,
                icon=helpers.get_icon(wf, 'chevron-right'))
    wf.add_item('Stop Service',
                'Stop the service formula immediately and unregister it from launching at login (or boot).',
                autocomplete='services %s stop' % service_name,
                arg='brew services stop %s' % service_name,
                valid=True,
                icon=helpers.get_icon(wf, 'chevron-right'))
    wf.add_item('Start Service',
                'Start the service formula immediately and register it to launch at login (or boot).',
                autocomplete='services %s start' % service_name,
                arg='brew services start %s' % service_name,
                valid=True,
                icon=helpers.get_icon(wf, 'chevron-right'))
    wf.add_item('Restart Service',
                'Stop (if necessary) and start the service formula immediately and register it to launch '
                'at login (or boot).',
                autocomplete='services %s restart' % service_name,
                arg='brew services restart %s' % service_name,
                valid=True,
                icon=helpers.get_icon(wf, 'chevron-right'))

def main(wf):
    if wf.update_available:
        wf.add_item('An update is available!',
                    autocomplete='workflow:update',
                    valid=False,
                    icon=helpers.get_icon(wf, 'cloud-download'))

    # Check for brew installation
    find_brew = helpers.brew_installed()

    if not (find_brew['INTEL'] or find_brew['ARM']):
        helpers.brew_installation_instructions(wf)
    else:
        # extract query
        query = wf.args[0] if len(wf.args) else None

        if (not query and
                len(wf.cached_data('brew_outdated_formulae',
                                   get_outdated_formulae,
                                   max_age=3600)) > 0):
            wf.add_item('Some of your formulae are outdated!',
                        autocomplete='outdated ',
                        valid=False,
                        icon=helpers.get_icon(wf, 'cloud-download'))

        if query and query.startswith('install'):
            for formula in filter_all_formulae(wf, query):
                wf.add_item(formula, 'Install formula.',
                            arg='brew install %s' % formula,
                            valid=True,
                            icon=helpers.get_icon(wf, 'package'))
        elif query and query.startswith('services'):
            query_filter = query.split()
            if len(query_filter) == 2 and query.endswith(' '):
                service_name = query_filter[1]
                add_service_actions(wf, service_name)
            else:
                services = filter_all_services(wf, query)
                for service in services:
                    wf.add_item(service['name'], 'Select for action. Status: %s' % service['status'],
                                autocomplete='services %s ' % service['name'],
                                arg='',
                                valid=False,
                                icon=helpers.get_icon(wf, 'package'))
        elif query and query.startswith('search'):
            for formula in filter_all_formulae(wf, query):
                wf.add_item(formula, 'Open formula on GitHub.',
                            arg='brew info --github %s' % formula,
                            valid=True,
                            icon=helpers.get_icon(wf, 'package'))
        elif query and query.startswith('uninstall'):
            for formula in filter_installed_formulae(wf, query):
                name = formula.rsplit()[0]
                wf.add_item(formula, 'Uninstall formula.',
                            arg='brew uninstall %s' % name,
                            valid=True,
                            icon=helpers.get_icon(wf, 'package'))
        elif query and query.startswith('list'):
            for formula in filter_installed_formulae(wf, query):
                name = formula.rsplit()[0]
                wf.add_item(formula, 'Open formula on GitHub.',
                            arg='brew info --github %s' % name,
                            valid=True,
                            icon=helpers.get_icon(wf, 'package'))
        elif query and query.startswith('pin'):
            for formula in filter_installed_formulae(wf, query):
                name = formula.rsplit()[0]
                wf.add_item(formula, 'Pin formula.',
                            arg='brew pin %s' % name,
                            valid=True,
                            icon=helpers.get_icon(wf, 'package'))
                # delete cached file
                wf.cache_data('brew_pinned_formulae', None)
        elif query and query.startswith('unpin'):
            for formula in filter_pinned_formulae(wf, query):
                name = formula.rsplit()[0]
                wf.add_item(formula, 'Unpin formula.',
                            arg='brew unpin %s' % name,
                            valid=True,
                            icon=helpers.get_icon(wf, 'package'))
                # delete cached file
                wf.cache_data('brew_pinned_formulae', None)
        elif query and query.startswith('cat'):
            for formula in filter_all_formulae(wf, query):
                name = formula.rsplit()[0]
                wf.add_item(formula, 'Display the source to this formula.',
                            arg='brew cat %s' % name,
                            valid=True,
                            icon=helpers.get_icon(wf, 'package'))
        elif query and query.startswith('outdated'):
            for formula in filter_outdated_formulae(wf, query):
                name = formula.rsplit()[0]
                wf.add_item(formula, 'Upgrade formula.',
                            arg='brew upgrade %s' % name,
                            valid=True,
                            icon=helpers.get_icon(wf, 'package'))
        elif query and query.startswith('info'):
            wf.add_item(get_info(),
                        autocomplete='',
                        icon=helpers.get_icon(wf, 'info'))
        elif query and query.startswith('commands'):
            for command in get_commands(wf, query):
                wf.add_item(command, 'Run this command.',
                            arg='brew %s' % command,
                            valid=True,
                            icon=helpers.get_icon(wf, 'chevron-right'))
        elif query and query.startswith('config'):
            helpers.edit_settings(wf)
            wf.add_item('`settings.json` has been opened.',
                        autocomplete='',
                        icon=helpers.get_icon(wf, 'info'))
        else:
            actions = brew_actions.ACTIONS
            if len(wf.cached_data('brew_pinned_formulae',
                                  get_pinned_formulae,
                                  max_age=3600)) > 0:
                actions.append({
                    'name': 'Unpin',
                    'description': 'Unpin formula.',
                    'autocomplete': 'unpin ',
                    'arg': '',
                    'valid': False,
                })
            # filter actions by query
            if query:
                actions = wf.filter(query, actions,
                                    key=helpers.search_key_for_action,
                                    match_on=MATCH_SUBSTRING)

            if len(actions) > 0:
                for action in actions:
                    wf.add_item(action['name'], action['description'],
                                uid=action['name'],
                                autocomplete=action['autocomplete'],
                                arg=action['arg'],
                                valid=action['valid'],
                                icon=helpers.get_icon(wf, 'chevron-right'))
            else:
                wf.add_item('No action found for "%s"' % query,
                            autocomplete='',
                            icon=helpers.get_icon(wf, 'info'))

        if len(wf._items) == 0:
            query_name = query[query.find(' ') + 1:]
            wf.add_item('No formula found for "%s"' % query_name,
                        autocomplete='%s ' % query[:query.find(' ')],
                        icon=helpers.get_icon(wf, 'info'))

    wf.send_feedback()

    # refresh cache
    cmd = ['/usr/bin/python', wf.workflowfile('brew_refresh.py')]
    run_in_background('brew_refresh', cmd)

if __name__ == '__main__':
    wf = Workflow(update_settings={'github_slug': GITHUB_SLUG})
    sys.exit(wf.run(main))


text:
package com.gokuai.yunku.demo.file;

import com.gokuai.base.DebugConfig;
import com.gokuai.base.ReturnResult;
import com.gokuai.yunku.demo.helper.DeserializeHelper;
import com.gokuai.yunku.demo.helper.EntFileManagerHelper;
import com.yunkuent.sdk.FilePermissions;

/**
 * Created by qp on 2017/5/17.
 * <p>
 * 修改文件夹权限
 */
public class SetPermission {

    public static void main(String[] args) {

        DebugConfig.DEBUG = true;

        ReturnResult result = EntFileManagerHelper.getInstance().setPermission("test", 4, "tom",
                FilePermissions.FILE_PREVIEW, FilePermissions.FILE_DELETE,
                FilePermissions.FILE_READ, FilePermissions.FILE_WRITE);

        DeserializeHelper.getInstance().deserializeReturn(result);
    }
}


text:
// AForge Math Library
// AForge.NET framework
// http://www.aforgenet.com/framework/
//
// Copyright © Andrew Kirillov, 2007-2010
// andrew.kirillov@aforgenet.com
//

namespace AForge.Math.Geometry
{
    using System;
    using System.Collections.Generic;
    using AForge;

    ///
    /// Shape optimizer, which removes obtuse angles (close to flat) from a shape.
    ///
    ///
    /// <remarks><para>This shape optimizing algorithm checks all adjacent edges of a shape
    /// and substitutes any 2 edges with a single edge if angle between them is greater than
    /// <see cref="MaxAngleToKeep"/>. The algorithm makes sure there are not obtuse angles in
    /// a shape, which are very close to flat line.</para>
    ///
    /// <para>The shape optimizer does not optimize shapes to less than 3 points, so optimized
    /// shape always will have at least 3 points.</para>
    ///
    /// <para>
    /// For example, the below circle shape comprised of 65 points, can be optimized to 10 points
    /// by setting <see cref="MaxAngleToKeep"/> to 160.

    ///
    /// </para>
    /// </remarks>
    ///
    public class FlatAnglesOptimizer : IShapeOptimizer
    {
        private double maxAngleToKeep = 160;

        ///
        /// Maximum angle between adjacent edges to keep in a shape, [140, 180].
        ///
        ///
        /// <remarks><para>The property sets maximum angle between adjacent edges, which is kept
        /// during optimization. All edges, which have a greater angle between them, are substituted
        /// by a single edge.</para>
        ///
        /// <para>Default value is set to 160.</para></remarks>
        ///
        public double MaxAngleToKeep
        {
            get { return maxAngleToKeep; }
            set { maxAngleToKeep = Math.Min( 180, Math.Max( 140, value ) ); }
        }

        ///
        /// Initializes a new instance of the <see cref="FlatAnglesOptimizer"/> class.
        ///
        ///
        public FlatAnglesOptimizer( ) { }

        ///
        /// Initializes a new instance of the <see cref="FlatAnglesOptimizer"/> class.
        ///
        ///
        /// <param name="maxAngleToKeep">Maximum acceptable angle between two edges of a shape (see <see cref="MaxAngleToKeep"/>).</param>
        ///
        public FlatAnglesOptimizer( double maxAngleToKeep )
        {
            this.maxAngleToKeep = maxAngleToKeep;
        }

        ///
        /// Optimize specified shape.
        ///
        ///
        /// <param name="shape">Shape to be optimized.</param>
        ///
        /// <returns>Returns final optimized shape, which may have reduced amount of points.</returns>
        ///
        public List<IntPoint> OptimizeShape( List<IntPoint> shape )
        {
            // optimized shape
            List<IntPoint> optimizedShape = new List<IntPoint>( );

            if ( shape.Count <= 3 )
            {
                // do nothing if shape has 3 points or less
                optimizedShape.AddRange( shape );
            }
            else
            {
                double angle = 0;

                // add first 2 points to the new shape
                optimizedShape.Add( shape[0] );
                optimizedShape.Add( shape[1] );
                int pointsInOptimizedHull = 2;

                for ( int i = 2, n = shape.Count; i < n; i++ )
                {
                    // add new point
                    optimizedShape.Add( shape[i] );
                    pointsInOptimizedHull++;

                    // get angle between 2 vectors, which start from the next to last point
                    angle = Tools.GetAngleBetweenVectors( optimizedShape[pointsInOptimizedHull - 2],
                        optimizedShape[pointsInOptimizedHull - 3], optimizedShape[pointsInOptimizedHull - 1] );

                    if ( ( angle > maxAngleToKeep ) &&
                         ( ( pointsInOptimizedHull > 3 ) || ( i < n - 1 ) ) )
                    {
                        // remove the next to last point
                        optimizedShape.RemoveAt( pointsInOptimizedHull - 2 );
                        pointsInOptimizedHull--;
                    }
                }

                if ( pointsInOptimizedHull > 3 )
                {
                    // check the last point
                    angle = Tools.GetAngleBetweenVectors( optimizedShape[pointsInOptimizedHull - 1],
                        optimizedShape[pointsInOptimizedHull - 2], optimizedShape[0] );

                    if ( angle > maxAngleToKeep )
                    {
                        optimizedShape.RemoveAt( pointsInOptimizedHull - 1 );
                        pointsInOptimizedHull--;
                    }

                    if ( pointsInOptimizedHull > 3 )
                    {
                        // check the first point
                        angle = Tools.GetAngleBetweenVectors( optimizedShape[0],
                            optimizedShape[pointsInOptimizedHull - 1], optimizedShape[1] );

                        if ( angle > maxAngleToKeep )
                        {
                            optimizedShape.RemoveAt( 0 );
                        }
                    }
                }
            }

            return optimizedShape;
        }
    }
}


text:
layout: postag
title: 'DET'
shortdef: 'determiner'
udver: '2'
---

This document is a placeholder for the language-specific documentation
for `DET`.


text:
package cc.suitalk.ipcinvoker;

import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.text.TextUtils;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import cc.suitalk.ipcinvoker.annotation.NonNull;
import cc.suitalk.ipcinvoker.tools.Log;

/**
 * Created by albieliang on 2018/9/21.
 */

class ServiceConnectionManager {

    private static final String TAG = "IPC.ServiceConnectionManager";

    private static final Map<String, List<ServiceConnection>> sMap = new HashMap<>();

    public static boolean registerServiceConnection(@NonNull String processName, @NonNull ServiceConnection serviceConnection) {
        if (TextUtils.isEmpty(processName) || serviceConnection == null) {
            Log.w(TAG, "registerServiceConnection failed, processName(%s), or serviceConnection(%s) is null.",
                    processName, serviceConnection);
            return false;
        }
        List<ServiceConnection> list;
        synchronized (sMap) {
            list = sMap.get(processName);
            if (list == null) {
                list = new LinkedList<>();
                sMap.put(processName, list);
            }
        }
        synchronized (list) {
            if (list.contains(serviceConnection)) {
                return false;
            }
            return list.add(serviceConnection);
        }
    }

    public static boolean unregisterServiceConnection(@NonNull String processName, @NonNull ServiceConnection serviceConnection) {
        if (TextUtils.isEmpty(processName) || serviceConnection == null) {
            Log.w(TAG, "unregisterServiceConnection failed, processName(%s), or serviceConnection(%s) is null.",
                    processName, serviceConnection);
            return false;
        }
        List<ServiceConnection> list;
        synchronized (sMap) {
            list = sMap.get(processName);
            if (list == null) {
                return false;
            }
        }
        synchronized (list) {
            return list.remove(serviceConnection);
        }
    }

    static void dispatchOnServiceConnected(String processName, ComponentName name, IBinder service) {
        Log.i(TAG, "dispatchOnServiceConnected(pn : %s)", processName);
        List<ServiceConnection> list;
        synchronized (sMap) {
            list = sMap.get(processName);
            if (list == null || list.isEmpty()) {
                return;
            }
        }
        List<ServiceConnection> tempList;
        synchronized (list) {
            tempList = new LinkedList<>(list);
        }
        for (ServiceConnection sc : tempList) {
            sc.onServiceConnected(name, service);
        }
    }

    static void dispatchOnServiceDisconnected(String processName, ComponentName name) {
        Log.i(TAG, "dispatchOnServiceDisconnected(pn : %s)", processName);
        List<ServiceConnection> list;
        synchronized (sMap) {
            list = sMap.get(processName);
            if (list == null || list.isEmpty()) {
                return;
            }
        }
        List<ServiceConnection> tempList;
        synchronized (list) {
            tempList = new LinkedList<>(list);
        }
        for (ServiceConnection sc : tempList) {
            sc.onServiceDisconnected(name);
        }
    }
}


text:
{% extends 'layouts/base.html' %}

{% block main_content %}

    Home

    Digital Assets

            Id
            Source
            Title
            Description
            Author
            Lat, Long
            Actions

        {% if digital_assets %}

            {% for digital_asset in digital_assets %}

                {{ digital_asset._id }}
                {% if digital_asset.source_organization %}
                    {{ digital_asset.source_organization }}
                {% else %}

                {% endif %}
                {{ digital_asset.title }}
                {{ digital_asset.description }}
                {{ digital_asset.author }}
                {{ digital_asset.latitude }}, {{ digital_asset.longitude}}

                    <form method="post" role="form" class="pull-left form-inline" action="{{ url_for('digital_assets.delete_digital_asset', id=digital_asset._id) }}">

                        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
                        <button class="btn btn-danger btn-sm" type="submit">
                        </button>
                    </form>

            {% endfor %}
        {% endif %}

{% endblock main_content %}


text:
package com.scenic.wechat.server.bean;

/**
 * 封装获取用户所属的标签请求参数
 * author:980463316@qq.com <br/>
 * Created on 2016-08-31 21:28.
 */
public class GetTagsOfUserParameter extends BaseBean {

    private String openid;

    public GetTagsOfUserParameter(String openId) {
        this.openid = openId;
    }

    public String getOpenid() {
        return openid;
    }

    public void setOpenid(String openid) {
        this.openid = openid;
    }
}


text:
using Modelo;
using Servico;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ClienteWeb.Controllers
{
    [Authorize]
    public class ServicoPController : Controller
    {
        private Contexto db = new Contexto();

        private ServicoService service;
        private TipoServicoService Tiposervice;

        public ServicoPController()
        {
            service = new ServicoService();
            Tiposervice = new TipoServicoService();
        }

        // GET: Serviço
        public ActionResult Index()
        {
            var result = db.Servicos.ToList();
            return View(result);
        }

        public ActionResult Delete(int id)
        {
            var item = db.Servicos.Find(id);
            var result = false;
            if (item != null)
            {
                db.Servicos.Remove(item);
                db.SaveChanges();
                result = true;
            }

            return Json(new { Resultado = result }, JsonRequestBehavior.AllowGet);
        }

        // GET: Servico/Create
        public ActionResult Create()
        {
            TipoServico tipo = new TipoServico { Id = 0, Descricao = "Selecionar Tipo" };
            var listTipo = new List<TipoServico>();
            listTipo.Add(tipo);

            var resultTipo = Tiposervice.Load().ToList();
            listTipo.AddRange(resultTipo);

            ViewBag.TipoServicoID = new SelectList(listTipo, "Id", "Descricao");
            return View();
        }

        // POST: Servico/Create
        [HttpPost]
        public ActionResult Create(ServicoP entity)
        {
            try
            {
                service.Save(entity);

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

    }
}


text:
package com.programmerdan.minecraft.devotion.dao.info;

public class PlayerEditBookInfo {
	public String trace_id;
	public int slot;
	public Boolean signing;
	public String prevTitle;
	public String newTitle;
	public Boolean titleChanged;
	public Boolean authorChanged;
	public Boolean contentChanged;
	public Boolean pageCountChanged;
	public Boolean eventCancelled;
}


text:
package org.seaborne.delta.server.local.patchstores.mem;

import java.util.Collections;
import java.util.List;

import org.seaborne.delta.DataSourceDescription;
import org.seaborne.delta.Id;
import org.seaborne.delta.server.local.LocalServerConfig;
import org.seaborne.delta.server.local.PatchLog;
import org.seaborne.delta.server.local.PatchStore;
import org.seaborne.delta.server.local.PatchStoreProvider;
import org.seaborne.delta.server.local.patchstores.PatchLogBase;
import org.seaborne.delta.server.local.patchstores.PatchLogIndex;
import org.seaborne.delta.server.local.patchstores.PatchStorage;

/**
 * In-memory, ephemeral {@link PatchStore}.
 * All the work is done in
 * {@link PatchLogIndexMem} and {@link PatchStorageMem}.
 */
public class PatchStoreMem extends PatchStore {

    public PatchStoreMem(PatchStoreProvider provider) {
        super(provider);
    }

    @Override
    public List<DataSourceDescription> initialDataSources() {
        return Collections.emptyList();
    }

    @Override
    protected void initialize(LocalServerConfig config) {}

    @Override
    protected PatchLog newPatchLog(DataSourceDescription dsd) {
        return newPatchLogFromIndexAndStorage(dsd);
    }

    @Override
    protected PatchLogIndex newPatchLogIndex(DataSourceDescription dsd, PatchStore patchStore, LocalServerConfig configuration) {
        return new PatchLogIndexMem();
    }

    @Override
    protected PatchStorage newPatchStorage(DataSourceDescription dsd, PatchStore patchStore, LocalServerConfig configuration) {
        return new PatchStorageMem();
    }

    @Override
    protected void delete(PatchLog patchLog) {}

    @Override
    protected void shutdownSub() {}

    @Override
    protected PatchLog renamePatchLog(PatchLog patchLog, String oldName, String newName) {
        DataSourceDescription dsd1 = patchLog.getDescription();
        Id dsRef2;

        if ( false )
            // No need to copy. Retain id and URI.
            dsRef2 = dsd1.getId();
        else
            // Simulate other store that do rename as copy-delete.
            dsRef2 = Id.create();

        DataSourceDescription dsd2 = new DataSourceDescription(dsRef2, newName, dsd1.getUri());
        PatchLogBase plb = (PatchLogBase)patchLog;
        return new PatchLogBase(dsd2, plb.getPatchLogIndex(), plb.getPatchLogStorage(), plb.getPatchStore());
    }
}


text:
/**
 * The try rule event
 *
 * @event module:rules/AST_Try.rule
 * @property {string} ruleName The string 'AST_Try'
 * @property {module:AST.node} ast The AST node that is an instance of this rule
 * @property {string} file The file that the rule begins on.
 * @property {number} line The line of the file where the rule begins on.
 * @property {number} column The column of the file where the rule begins on.
 * @property {boolean} processingComplete Indicates whether the rule has been processed yet or not. This can be used to
 *		determine if this is the pre-evalutation event or the post-evaluation event.
 * @property {(module:base.BaseType | undefined)} exception The exception, if one was thrown, else undefined.
 *		Only available post-evaluation.
 */

var AST = require('../AST'),
	RuleProcessor = require('../RuleProcessor'),
	Runtime = require('../Runtime'),
	Base = require('../Base'),
	AST = require('../AST');

AST.registerRuleProcessor('AST_Try', function processRule() {

	var	tryBlock = this.body,
		catchBlock = this.bcatch,
		catchArg,
		finallyBlock = this.bfinally,
		b,
		c,
		f,
		result,
		exception,
		caughtException,
		error,
		i, len;

	RuleProcessor.preProcess(this);

	RuleProcessor.fireRuleEvent(this, {}, false);

	RuleProcessor.fireRuleEvent(this, {}, false);
	RuleProcessor.logRule('AST_Try');

	catchArg = catchBlock && catchBlock.argname.name;
	if (catchBlock && (catchArg === 'eval' || catchArg === 'arguments')) {
		Base.throwNativeException('SyntaxError', '"' + catchArg + '" is not a valid identifier name in strict mode');
	}

	try {
		Base.enterTryCatch();
		b = RuleProcessor.processBlock(tryBlock);
	} catch (e) {
		if (e.isCodeProcessorException) {
			b = ['throw', Runtime._exception, undefined];
			caughtException = Runtime._exception;
			Runtime._exception = undefined;
		} else {
			throw e;
		}
	}
	Base.exitTryCatch();

	function evalCatch(param) {
		var currentContext = Base.getCurrentContext(),
			oldEnv = currentContext.lexicalEnvironment,
			catchEnv = Base.newDeclarativeEnvironment(oldEnv);
		Base.setVisited(catchBlock.argname);
		if (Base.type(param) === 'Unknown') {
			catchBlock.argname._unknown = true;
		}
		catchEnv.envRec.createMutableBinding(catchArg);
		catchEnv.envRec.setMutableBinding(catchArg, param, false);
		currentContext.lexicalEnvironment = catchEnv;
		try {
			result = RuleProcessor.processBlock(catchBlock.body);
		} finally {
			currentContext.lexicalEnvironment = oldEnv;
		}
		exception = param;
		return result;
	}

	if (catchBlock && finallyBlock) {
		Base.setVisited(catchBlock);
		Base.setVisited(finallyBlock);
		if (b[0] === 'throw') {
			caughtException = undefined;
			try {
				c = evalCatch(b[1]);
			} catch(e) {
				caughtException = Runtime._exception;
			}
		} else {
			c = b;
			Base.processInSkippedMode(function () {
				catchBlock.argname.processRule();
				for (i = 0, len = catchBlock.body.length; i < len; i++) {
					catchBlock.body[i].processRule();
				}
			});
		}
		f = RuleProcessor.processBlock(finallyBlock.body);
		if (f[0] === 'normal') {
			result = c;
		} else {
			result = f;
		}
		if (caughtException) {
			Runtime._exception = caughtException;
			error = new Error('VM exception flow controller');
			error.isCodeProcessorException = true;
			throw error;
		}
	} else if (catchBlock) {
		Base.setVisited(catchBlock);
		if (b[0] === 'throw') {
			result = evalCatch(b[1]);
		} else {
			result = b;
			Base.processInSkippedMode(function () {
				Base.setVisited(catchBlock.argname);
				for (i = 0, len = catchBlock.body.length; i < len; i++) {
					catchBlock.body[i].processRule();
				}
			});
		}
	} else if (finallyBlock) {
		Base.setVisited(finallyBlock);
		f = RuleProcessor.processBlock(finallyBlock.body);
		if (f[0] === 'normal') {
			if (caughtException) {
				Runtime._exception = caughtException;
				error = new Error('VM exception flow controller');
				error.isCodeProcessorException = true;
				throw error;
			} else {
				result = b;
			}
		} else {
			result = f;
		}
	}

	RuleProcessor.fireRuleEvent(this, {
		exception: exception,
		result: result
	}, true);

	RuleProcessor.postProcess(this);

	return result;
});


text:
using System;
using System.IO;
using Microsoft.Practices.Prism.Modularity;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Microsoft.Practices.Prism.Composition.Tests.Modularity
{
    [TestClass]
    public class AssemblyResolverFixture
    {
        private const string ModulesDirectory1 = @".\DynamicModules\MocksModulesAssemblyResolve";

        [TestInitialize]
        [TestCleanup]
        public void CleanUpDirectories()
        {
            CompilerHelper.CleanUpDirectory(ModulesDirectory1);
        }

        [TestMethod]
        public void ShouldThrowOnInvalidAssemblyFilePath()
        {
            bool exceptionThrown = false;
            using (var resolver = new AssemblyResolver())
            {
                try
                {
                    resolver.LoadAssemblyFrom(null);
                }
                catch (ArgumentException)
                {
                    exceptionThrown = true;
                }

                Assert.IsTrue(exceptionThrown);

                try
                {
                    resolver.LoadAssemblyFrom("file://InexistentFile.dll");
                    exceptionThrown = false;
                }
                catch (FileNotFoundException)
                {
                    exceptionThrown = true;
                }

                Assert.IsTrue(exceptionThrown);

                try
                {
                    resolver.LoadAssemblyFrom("InvalidUri.dll");
                    exceptionThrown = false;
                }
                catch (ArgumentException)
                {
                    exceptionThrown = true;
                }

                Assert.IsTrue(exceptionThrown);
            }
        }

        [TestMethod]
        public void ShouldResolveTypeFromAbsoluteUriToAssembly()
        {
            string assemblyPath = CompilerHelper.GenerateDynamicModule("ModuleInLoadedFromContext1", "Module", ModulesDirectory1 + @"\ModuleInLoadedFromContext1.dll");
            var uriBuilder = new UriBuilder
                                 {
                                     Host = String.Empty,
                                     Scheme = Uri.UriSchemeFile,
                                     Path = Path.GetFullPath(assemblyPath)
                                 };
            var assemblyUri = uriBuilder.Uri;
            using (var resolver = new AssemblyResolver())
            {
                Type resolvedType =
                    Type.GetType(
                        "TestModules.ModuleInLoadedFromContext1Class, ModuleInLoadedFromContext1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null");
                Assert.IsNull(resolvedType);

                resolver.LoadAssemblyFrom(assemblyUri.ToString());

                resolvedType =
                    Type.GetType(
                        "TestModules.ModuleInLoadedFromContext1Class, ModuleInLoadedFromContext1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null");
                Assert.IsNotNull(resolvedType);
            }
        }

        [TestMethod]
        public void ShouldResolvePartialAssemblyName()
        {
            string assemblyPath = CompilerHelper.GenerateDynamicModule("ModuleInLoadedFromContext2", "Module", ModulesDirectory1 + @"\ModuleInLoadedFromContext2.dll");
            var uriBuilder = new UriBuilder
                                 {
                                     Host = String.Empty,
                                     Scheme = Uri.UriSchemeFile,
                                     Path = Path.GetFullPath(assemblyPath)
                                 };
            var assemblyUri = uriBuilder.Uri;
            using (var resolver = new AssemblyResolver())
            {
                resolver.LoadAssemblyFrom(assemblyUri.ToString());

                Type resolvedType =
                    Type.GetType("TestModules.ModuleInLoadedFromContext2Class, ModuleInLoadedFromContext2");

                Assert.IsNotNull(resolvedType);

                resolvedType =
                    Type.GetType("TestModules.ModuleInLoadedFromContext2Class, ModuleInLoadedFromContext2, Version=0.0.0.0");

                Assert.IsNotNull(resolvedType);

                resolvedType =
                    Type.GetType("TestModules.ModuleInLoadedFromContext2Class, ModuleInLoadedFromContext2, Version=0.0.0.0, Culture=neutral");

                Assert.IsNotNull(resolvedType);
            }
        }
    }
}


text:
This documentation will define how to contribute `robe-react-ui`. If you believe this documentation should be developed please open an issue.

## Opening issues
Feel free to suggest new components, replacing the old ones or changing the props for easier usage or reporting bugs. You can open issue for everything but please be sure that it is not duplicated and explained well.

## Testing
The UX is important, you can always test the usage of the components and give advice according to their behaviour.

## Coding
Pick an issue and create a pull request. Every issue is available for everyone. If it is not clear, request for more information and then we can discuss the issue to explain it better.

## Clean Code & Clean Coder
Sometimes we get confused with namings of components, props or methods, please do not hesitate to review/refactor our sources and create a pull request to make them understandable.

## Documentation
It is important we know. Generally, samples and docs are enough for us but not for an outsider. We can call it project blindness, a pair of brand new eyes will be more objective about them. Feel free to request or write docs.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bolezni rastenii 17(3-4): 184 (1928)

#### Original name
Septoria triticina Lobik

### Remarks
null


text:
using System;
using Xunit;

namespace Evol.Redis.Tests
{
    public class UnitTest1
    {
        [Fact]
        public void Test1()
        {
        }
    }
}


text:
const BitcoreLibDoge = require('bitcore-lib-doge');
import { AbstractBitcoreLibDeriver } from '../btc';
export class DogeDeriver extends AbstractBitcoreLibDeriver {
  bitcoreLib = BitcoreLibDoge;
}


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

package com.google.opengse.performance;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * A servlet that echoes back whatever was sent in the body of the request.
 *
 * @author Wenbo Zhu
 */
@SuppressWarnings("serial")
public final class EchoServlet extends javax.servlet.http.HttpServlet {
  /**
   * Echoes back whatever was sent in the body of the request.
   *
   *
The response is always a document of type {@code "text/html"}, and the
   * request body is wrapped in {@code } and {@code <body_buf>} tags.
   */
  @Override
  public void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException {
    PrintWriter out = null;
    try {
      // Get the binary output stream
      out = response.getWriter();

      // Set the response type
      response.setContentType("text/html");

      // Convert the input sequence to character string
      InputStream is = request.getInputStream();
      Reader ic = new InputStreamReader(is, request.getCharacterEncoding());

      StringBuilder bodyStr = new StringBuilder();
      char[] buffer = new char[8192];
      int length;
      while ((length = ic.read(buffer)) != -1) {
        bodyStr.append(buffer, 0, length);
      }

      out.println("\n<body_buf>\n");
      out.println(bodyStr);
      out.println("\n</body_buf>\n\n");

    } catch (RuntimeException e) {
      throw new ServletException(e.getMessage());
    } catch (IOException e) {
      throw new ServletException(e.getMessage());
    } finally {
      if (out != null) {
        out.close();
      }
    }
  }
}


text:
module SimpleEmbed
  class Helpers
    AUTO_LINK_RE = /
              (?: ([\w+.:-]+:)\/\/ | www\. )
              [^\s<]+
            /x

    def self.auto_embed(text)
      text.to_str.gsub(AUTO_LINK_RE) do
        scheme, href = $1, $&
        punctuation = []
        # don't include trailing punctuation character as part of the URL
        while href.sub!(/[^\w\/-]$/, '')
          punctuation.push $&
          if opening = BRACKETS[punctuation.last] and href.scan(opening).size > href.scan(punctuation.last).size
            href << punctuation.pop
            break
          end
        end

        href = 'http://' + href unless scheme
        embed_code(href)
      end
    end

    def self.embed_code(url)
      begin
        EmbedLinkFactory.get_embed_link(url).embed_code
      rescue
        begin
          DefaultLink.new(url).embed_code
        rescue
          url
        end
      end
    end

    def self.contains_link?(text)
      AUTO_LINK_RE.match(text)
    end

  end
end


text:
using System.Collections.Generic;
using System.Runtime.InteropServices.Tests.Common;
using Xunit;

namespace System.Runtime.InteropServices.Tests
{
    public partial class IsComObjectTests
    {
        public static IEnumerable<object[]> IsComObject_Windows_TestData()
        {
            yield return new object[] { new ComImportObject(), true };
            yield return new object[] { new ComImportObject[0], false };
            yield return new object[] { new SubComImportObject(), true };
            yield return new object[] { new GenericSubComImportObject<string>(), true };
            yield return new object[] { new InterfaceAndComImportObject(), true };
            yield return new object[] { new InterfaceComImportObject(), false };
        }

        [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))]
        [MemberData(nameof(IsComObject_Windows_TestData))]
        public void IsComObject_Windows_ReturnsExpected(object value, bool expected)
        {
            Assert.Equal(expected, Marshal.IsComObject(value));
        }
    }
}


text:
    // This is a generated file created by Glue. To change this file, edit the camera settings in Glue.
    // To access the camera settings, push the camera icon.
    using Camera = FlatRedBall.Camera;
    namespace Dodgeball
    {
        public class CameraSetupData
        {
            public float Scale { get; set; }
            public bool Is2D { get; set; }
            public int ResolutionWidth { get; set; }
            public int ResolutionHeight { get; set; }
            public decimal? AspectRatio { get; set; }
            public bool AllowWidowResizing { get; set; }
            public bool IsFullScreen { get; set; }
            public ResizeBehavior ResizeBehavior { get; set; }
        }
        public enum ResizeBehavior
        {
            StretchVisibleArea,
            IncreaseVisibleArea
        }
        internal static class CameraSetup
        {
            static Microsoft.Xna.Framework.GraphicsDeviceManager graphicsDeviceManager;
            public static CameraSetupData Data = new CameraSetupData
            {
                Scale = 50f,
                ResolutionWidth = 1920,
                ResolutionHeight = 1080,
                Is2D = true,
                AspectRatio = 1.7777777777777777777777777778m,
                IsFullScreen = false,
                AllowWidowResizing = true,
                ResizeBehavior = ResizeBehavior.IncreaseVisibleArea,
            }
            ;
            internal static void ResetCamera (Camera cameraToReset = null)
            {
                if (cameraToReset == null)
                {
                    cameraToReset = FlatRedBall.Camera.Main;
                }
                cameraToReset.Orthogonal = Data.Is2D;
                if (Data.Is2D)
                {
                    cameraToReset.OrthogonalHeight = Data.ResolutionHeight;
                    cameraToReset.OrthogonalWidth = Data.ResolutionWidth;
                    cameraToReset.FixAspectRatioYConstant();
                }
                if (Data.AspectRatio != null)
                {
                    SetAspectRatioTo(Data.AspectRatio.Value);
                }
            }
            internal static void SetupCamera (Camera cameraToSetUp, Microsoft.Xna.Framework.GraphicsDeviceManager graphicsDeviceManager)
            {
                CameraSetup.graphicsDeviceManager = graphicsDeviceManager;
                ResetWindow();
                ResetCamera(cameraToSetUp);
                FlatRedBall.FlatRedBallServices.GraphicsOptions.SizeOrOrientationChanged += HandleResolutionChange;
            }
            internal static void ResetWindow ()
            {
                #if WINDOWS || DESKTOP_GL
                FlatRedBall.FlatRedBallServices.Game.Window.AllowUserResizing = Data.AllowWidowResizing;
                if (Data.IsFullScreen)
                {
                    #if DESKTOP_GL
                    graphicsDeviceManager.HardwareModeSwitch = false;
                    FlatRedBall.FlatRedBallServices.GraphicsOptions.SetResolution(Microsoft.Xna.Framework.Graphics.GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width, Microsoft.Xna.Framework.Graphics.GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height, FlatRedBall.Graphics.WindowedFullscreenMode.FullscreenBorderless);
                    #elif WINDOWS
                    System.IntPtr hWnd = FlatRedBall.FlatRedBallServices.Game.Window.Handle;
                    var control = System.Windows.Forms.Control.FromHandle(hWnd);
                    var form = control.FindForm();
                    form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
                    form.WindowState = System.Windows.Forms.FormWindowState.Maximized;
                    #endif
                }
                else
                {
                    FlatRedBall.FlatRedBallServices.GraphicsOptions.SetResolution((int)(Data.ResolutionWidth * Data.Scale/ 100.0f), (int)(Data.ResolutionHeight * Data.Scale/ 100.0f));
                }
                #elif IOS || ANDROID
                FlatRedBall.FlatRedBallServices.GraphicsOptions.SetFullScreen(FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionWidth, FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionHeight);
                #elif UWP
                if (Data.IsFullScreen)
                {
                    FlatRedBall.FlatRedBallServices.GraphicsOptions.SetFullScreen(Data.ResolutionWidth, Data.ResolutionHeight);
                }
                else
                {
                    FlatRedBall.FlatRedBallServices.GraphicsOptions.SetResolution((int)(Data.ResolutionWidth * Data.Scale/ 100.0f), (int)(Data.ResolutionHeight * Data.Scale/ 100.0f));
                }
                #endif
            }
            private static void HandleResolutionChange (object sender, System.EventArgs args)
            {
                if (Data.AspectRatio != null)
                {
                    SetAspectRatioTo(Data.AspectRatio.Value);
                }
                if (Data.Is2D && Data.ResizeBehavior == ResizeBehavior.IncreaseVisibleArea)
                {
                    FlatRedBall.Camera.Main.OrthogonalHeight = FlatRedBall.Camera.Main.DestinationRectangle.Height / (Data.Scale/ 100.0f);
                    FlatRedBall.Camera.Main.FixAspectRatioYConstant();
                }
            }
            private static void SetAspectRatioTo (decimal aspectRatio)
            {
                var resolutionAspectRatio = FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionWidth / (decimal)FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionHeight;
                int destinationRectangleWidth;
                int destinationRectangleHeight;
                int x = 0;
                int y = 0;
                if (aspectRatio > resolutionAspectRatio)
                {
                    destinationRectangleWidth = FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionWidth;
                    destinationRectangleHeight = FlatRedBall.Math.MathFunctions.RoundToInt(destinationRectangleWidth / (float)aspectRatio);
                    y = (FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionHeight - destinationRectangleHeight) / 2;
                }
                else
                {
                    destinationRectangleHeight = FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionHeight;
                    destinationRectangleWidth = FlatRedBall.Math.MathFunctions.RoundToInt(destinationRectangleHeight * (float)aspectRatio);
                    x = (FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionWidth - destinationRectangleWidth) / 2;
                }
                FlatRedBall.Camera.Main.DestinationRectangle = new Microsoft.Xna.Framework.Rectangle(x, y, destinationRectangleWidth, destinationRectangleHeight);
                FlatRedBall.Camera.Main.FixAspectRatioYConstant();
            }
        }
    }


text:
For developing the application server, check out the [App Server Guide](app_server/CONTRIBUTING.md)

For developing extension modules for Wowza streaming engine, check out the [Media Server Guide](media_server/CONTRIBUTING.md)