text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace Ceen.Database
{
    /// <summary>
    /// Class for accessing a database, with simple table create/delete commands.
    /// Approaching a mini ORM, but omits the query parts
    /// </summary>
    public static class DatabaseHelper
    {
        /// <summary>
        /// Attempts to get a working database connection
        /// </summary>
        public static IDbConnection CreateConnection(string connectionstring, string connectionclass = "sqlite")
        {
            var classname = connectionclass;
            var connstr = connectionstring;
            if (string.Equals(classname, "sqlite", StringComparison.OrdinalIgnoreCase) || string.Equals(classname, "sqlite3", StringComparison.OrdinalIgnoreCase))
            {
                classname = "Mono.Data.Sqlite.SqliteConnection, Mono.Data.Sqlite, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";
                if (Type.GetType(classname) == null)
                    classname = "System.Data.SQLite.SQLiteConnection, System.Data.SQLite, Version=1.0.104.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139";

                if (!string.IsNullOrWhiteSpace(connstr) && !connstr.StartsWith("Data Source=", StringComparison.OrdinalIgnoreCase))
                    connstr = "Data Source=" + connstr;
            }
            else if (string.Equals(classname, "odbc", StringComparison.OrdinalIgnoreCase))
                classname = "System.Data.Odbc.OdbcConnection, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

            var contype = Type.GetType(classname);
            if (contype == null)
                throw new Exception($"Failed to locate the requested database type: {classname}");
            var e = Activator.CreateInstance(contype);
            if (!(e is IDbConnection))
                throw new Exception($"The requested type {contype.FullName} is not implementing {typeof(IDbConnection).FullName}");

            var connection = e as IDbConnection;

            connection.ConnectionString = connstr;
            connection.Open();

            return connection;
        }

        /// <summary>
        /// A function that returns the default dialect for a given connection
        /// </summary>
        public static Func<IDbConnection, IDatabaseDialect> DefaultDialect
        {
            get;
            set;
        } = _ => new DatabaseDialectSQLite();

        /// <summary>
        /// Gets the dialect assigned to a connection
        /// </summary>
        private static readonly Dictionary<IDbConnection, IDatabaseDialect> _dialect = new Dictionary<IDbConnection, IDatabaseDialect>();

        /// <summary>
        /// The lock used to guard the dialect table
        /// </summary>
        private static readonly object _dialectLock = new object();

        /// <summary>
        /// Gets the database dialect for a connection
        /// </summary>
        /// <returns>The dialect for the connection.</returns>
        /// <param name="connection">The connection to get the dialect for.</param>
        /// <param name="defaultOverride">A dialect that is selected instead of the default.</param>
        public static IDatabaseDialect GetDialect(this IDbConnection connection, IDatabaseDialect defaultOverride = null)
        {
            lock (_dialectLock)
            {
                if (connection is TransactionConnection trc)
                    connection = trc.Connection;

                if (!_dialect.TryGetValue(connection, out var res))
                    _dialect.Add(connection, res = defaultOverride ?? DefaultDialect(connection));

                return res;
            }
        }

        /// <summary>
        /// Removes the dialect associated with a connection, if any
        /// </summary>
        /// <param name="connection">The connection to de-associate with a dialect</param>
        /// <returns><c>true</c> if a dialect was removed; <c>false</c> otherwise</returns>
        public static bool ReleaseDialect(this IDbConnection connection)
        {
            lock (_dialectLock)
                return _dialect.Remove(connection);
        }

        /// <summary>
        /// Parses a filterstring
        /// </summary>
        /// <param name="connection">The connection to get the dialect from</param>
        /// <param name="filter">The filter to parse</param>
        /// <typeparam name="T">The type the query is for</typeparam>
        /// <returns>The filter query</returns>
        public static QueryElement ParseFilter<T>(this IDbConnection connection, string filter)
        {
            return GetDialect(connection).ParseFilter<T>(filter);
        }

        /// <summary>
        /// Renders query using the current dialect
        /// </summary>
        /// <param name="connection">The connection to get the dialect from</param>
        /// <param name="query">The query to render</param>
        /// <typeparam name="T">The type the query is for</typeparam>
        /// <returns>The query and arguments</returns>
        public static KeyValuePair<string, object[]> RenderWhereClause<T>(this IDbConnection connection, QueryElement query)
        {
            return GetDialect(connection).RenderWhereClause(typeof(T), query);
        }

        /// <summary>
        /// Renders query using the current dialect
        /// </summary>
        /// <param name="connection">The connection to get the dialect from</param>
        /// <param name="query">The query to render</param>
        /// <typeparam name="T">The type the query is for</typeparam>
        /// <returns>The query and arguments</returns>
        public static KeyValuePair<string, object[]> RenderWhereClause<T>(this IDbConnection connection, Expression<Func<T, bool>> query)
        {
            return GetDialect(connection).RenderWhereClause(typeof(T), QueryUtil.FromLambda(query));
        }

        /// <summary>
        /// Renders query using the current dialect
        /// </summary>
        /// <param name="connection">The dialect to use</param>
        /// <param name="query">The query to render</param>
        /// <typeparam name="T">The type the query is for</typeparam>
        /// <returns>The query and arguments</returns>
        public static KeyValuePair<string, object[]> RenderWhereClause<T>(this IDatabaseDialect dialect, Expression<Func<T, bool>> query)
        {
            return dialect.RenderWhereClause(typeof(T), QueryUtil.FromLambda(query));
        }

        /// <summary>
        /// Creates a table for the given type
        /// </summary>
        /// <typeparam name="T">The type of the table to create.</typeparam>
        /// <param name="connection">The connection to use</param>
        /// <param name="ifNotExists">Only create the table if it does not exist</param>
        /// <param name="autoAddColumns">Automatically add new columns to the database if they are not present</param>
        public static void CreateTable<T>(this IDbConnection connection, bool ifNotExists = true, bool autoAddColumns = true)
        {
            CreateTable(connection, typeof(T), ifNotExists, autoAddColumns);
        }

        /// <summary>
        /// Creates a table for the given type
        /// </summary>
        /// <param name="type">The type of the table to create.</param>
        /// <param name="connection">The connection to use</param>
        /// <param name="ifNotExists">Only create the table if it does not exist</param>
        /// <param name="autoAddColumns">Automatically add new columns to the database if they are not present</param>
        public static void CreateTable(this IDbConnection connection, Type type, bool ifNotExists = true, bool autoAddColumns = true)
        {
            var dialect = GetDialect(connection);
            var mapping = dialect.GetTypeMap(type);

            var sql = dialect.CreateTableSql(type, ifNotExists);
            using (var cmd = connection.CreateCommand(sql))
                cmd.ExecuteNonQuery();

            sql = dialect.CreateSelectTableColumnsSql(type);
            var columns = new List<string>();
            using (var cmd = connection.CreateCommand(sql))
            using(var rd = cmd.ExecuteReader())
                while(rd.Read())
                    columns.Add(rd.GetAsString(0));

            var missingcolumns = mapping.AllColumns.Where(x => !columns.Contains(x.ColumnName)).ToArray();
            if (missingcolumns.Length != 0)
            {
                if (!autoAddColumns)
                    throw new DataException($"The table {mapping.Name} is missing the column(s): {string.Join(", ", missingcolumns.Select(x => x.ColumnName))}");

                sql = dialect.CreateAddColumnSql(type, missingcolumns);
                using (var cmd = connection.CreateCommand(sql))
                    cmd.ExecuteNonQuery();
            }
        }

        /// <summary>
        /// Deletes the table for the given type
        /// </summary>
        /// <typeparam name="T">The type of the table to delete.</typeparam>
        /// <param name="connection">The connection to use</param>
        public static void DeleteTable<T>(this IDbConnection connection)
        {
            DeleteTable(connection, typeof(T));
        }

        /// <summary>
        /// Deletes a table for the given type
        /// </summary>
        /// <param name="type">The type of the table to delete.</param>
        /// <param name="connection">The connection to use</param>
        /// <param name="ifExists">Only delete table if it exists</param>
        public static void DeleteTable(this IDbConnection connection, Type type, bool ifExists = true)
        {
            var dialect = GetDialect(connection);
            var mapping = dialect.GetTypeMap(type);

            var sql = dialect.DeleteTableSql(type);
            using (var cmd = connection.CreateCommand(sql))
                cmd.ExecuteNonQuery();
        }

        /// <summary>
        /// Checks if the table for the given type exists
        /// </summary>
        /// <param name="connection">The connection to use</param>
        /// <typeparam name="T">The table type parameter.</typeparam>
        public static bool TableExists<T>(this IDbConnection connection)
        {
            return TableExists(connection, typeof(T));
        }

        /// <summary>
        /// Checks if the table for the given type exists
        /// </summary>
        /// <param name="connection">The connection to use</param>
        /// <param name="type">The table type parameter</param>
        public static bool TableExists(this IDbConnection connection, Type type)
        {
            var dialect = GetDialect(connection);
            using (var cmd = connection.CreateCommand())
            {
                cmd.CommandText = dialect.CreateTableExistsCommand(type);
                var res = cmd.ExecuteScalar();
                return res != null && res != DBNull.Value;
            }
        }

        /// <summary>
        /// Selects the item with the give ID. The type should have exactly one primary key when using this method
        /// </summary>
        /// <returns>The item by identifier.</returns>
        /// <param name="ids">The primary keys.</param>
        /// <param name="connection">The connection to use</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        public static T SelectItemById<T>(this IDbConnection connection, params object[] ids)
            where T : new()
        {
            return SelectSingle<T>(connection,
                GetDialect(connection)
                    .Query<T>()
                    .Select()
                    .MatchPrimaryKeys(ids)
                    .Limit(1)
            );
        }

        /// <summary>
        /// Selects a single item
        /// </summary>
        /// <returns>The first item matching the query.</returns>
        /// <param name="query">The query to use.</param>
        /// <param name="connection">The connection to use</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        public static T SelectSingle<T>(this IDbConnection connection, Query query)
            where T : new()
        {
            return SelectSingle<T>(connection, query, () => new T());
        }
        /// <summary>
        /// Selects a single item
        /// </summary>
        /// <returns>The first item matching the query.</returns>
        /// <param name="query">The query to use.</param>
        /// <param name="connection">The connection to use</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        public static T SelectSingle<T>(this IDbConnection connection, Query<T> query)
            where T : new()
        {
            return SelectSingle<T>(connection, query, () => new T());
        }

        /// <summary>
        /// Selects a single item
        /// </summary>
        /// <returns>The first item matching the query.</returns>
        /// <param name="query">The query to use.</param>
        /// <param name="connection">The connection to use</param>
        /// <param name="create">The method creating the instance of <typeref name="T" /> to update</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        public static T SelectSingle<T>(this IDbConnection connection, Query query, Func<T> create)
        {
            var dialect = GetDialect(connection);
            var mapping = dialect.GetTypeMap<T>();

            if (query.Parsed.Type != QueryType.Select)
                throw new ArgumentException($"Cannot select with a query of type {query.Parsed.Type}");

            // Force a limit of one result
            if (query.Parsed.LimitParams == null || query.Parsed.LimitParams.Item1 < 0)
                query.Parsed.Limit(1);
            else if (query.Parsed.LimitParams.Item1 != 1)
                throw new ArgumentException("The limit cannot be set when selecting a single item");

            var q = dialect.RenderStatement(query);
            using (var cmd = connection.CreateCommandWithParameters(q.Key))
            using(var rd = cmd.ExecuteReader(q.Value))
            {
                return rd.Read()
                    ? FillItem(rd, mapping, create())
                    : default(T);
            }
        }

        /// <summary>
        /// Gets all items for a given type
        /// </summary>
        /// <returns>All items of the given type.</returns>
        /// <param name="connection">The connection to use</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        public static IEnumerable<T> SelectAll<T>(this IDbConnection connection)
            where T : new()
        {
            return Select(connection,
                GetDialect(connection)
                    .Query<T>()
                    .Select()
            );
        }

        /// <summary>
        /// Adds a space in from of the query string
        /// </summary>
        /// <param name="query">The query string</param>
        /// <returns>A space prefixed query string</returns>
        private static string SpacePrefixQuery(string query)
        {
            if (string.IsNullOrWhiteSpace(query))
                return string.Empty;
            return " " + query.Trim();
        }

        /// <summary>
        /// Gets some items for a given type
        /// </summary>
        /// <returns>The items that match.</returns>
        /// <param name="connection">The connection to use</param>
        /// <param name="query">The query to use</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        public static IEnumerable<T> Select<T>(this IDbConnection connection, Expression<Func<T, bool>> query)
            where T : new()
        {
            return Select(connection,
                GetDialect(connection)
                    .Query<T>()
                    .Select()
                    .Where(query)
            );
        }

        /// <summary>
        /// Gets some items for a given type
        /// </summary>
        /// <returns>The items that match.</returns>
        /// <param name="connection">The connection to use</param>
        /// <param name="query">The query to use</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        public static IEnumerable<T> Select<T>(this IDbConnection connection, QueryElement query)
            where T : new()
        {
            return Select(connection,
                GetDialect(connection)
                    .Query<T>()
                    .Select()
                    .Where(query)
            );
        }

        /// <summary>
        /// Gets some items for a given type
        /// </summary>
        /// <returns>The items that match.</returns>
        /// <param name="connection">The connection to use</param>
        /// <param name="query">The where part of the query to use</param>
        /// <param name="arguments">The query arguments</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        public static IEnumerable<T> Select<T>(this IDbConnection connection, string query, params object[] arguments)
            where T : new()
        {
            return Select(connection,
                GetDialect(connection)
                    .Query<T>()
                    .Select()
                    .Where(new CustomQuery(query, arguments))
            );
        }

        /// <summary>
        /// Gets some items for a given type
        /// </summary>
        /// <returns>The items that match.</returns>
        /// <param name="query">The query to use</param>
        /// <param name="arguments">The query arguments</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        public static IEnumerable<T> Select<T>(this IDbConnection connection, Query<T> query)
            where T : new()
        {
            return Select<T>(connection, (Query)query);
        }

        /// <summary>
        /// Gets some items for a given type
        /// </summary>
        /// <returns>The items that match.</returns>
        /// <param name="connection">The connection to use</param>
        /// <param name="query">The where part of the query to use</param>
        /// <param name="arguments">The query arguments</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        public static IEnumerable<T> Select<T>(this IDbConnection connection, Query query)
            where T : new()
        {
            var dialect = GetDialect(connection);
            var q = dialect.RenderStatement(query);

            using (var cmd = connection.CreateCommandWithParameters(q.Key))
            {
                cmd.SetParameterValues(q.Value);
                foreach (var n in FillItems<T>(cmd))
                    yield return n;
            }
        }

        /// <summary>
        /// Gets a single item of a given type
        /// </summary>
        /// <returns>The items that match.</returns>
        /// <param name="connection">The connection to use</param>
        /// <param name="query">The query to use</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        public static T SelectSingle<T>(this IDbConnection connection, Expression<Func<T, bool>> query)
            where T : new()
        {
            return SelectSingle<T>(
                connection,
                GetDialect(connection)
                    .Query<T>()
                    .Select()
                    .Where(query)
            );
        }

        /// <summary>
        /// Gets a single item of a given type
        /// </summary>
        /// <returns>The items that match.</returns>
        /// <param name="connection">The connection to use</param>
        /// <param name="query">The query to use</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        public static T SelectSingle<T>(this IDbConnection connection, QueryElement query)
            where T : new()
        {
            return SelectSingle<T>(
                connection,
                GetDialect(connection)
                    .Query<T>()
                    .Select()
                    .Where(query)
            );
        }

        /// <summary>
        /// Gets a single item of a given type
        /// </summary>
        /// <returns>The items that match.</returns>
        /// <param name="connection">The connection to use</param>
        /// <param name="query">The where part of the query to use</param>
        /// <param name="arguments">The query arguments</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        public static T SelectSingle<T>(this IDbConnection connection, string query, params object[] arguments)
            where T : new()
        {
            return SelectSingle<T>(
                connection,
                GetDialect(connection)
                    .Query<T>()
                    .Select()
                    .Where(new CustomQuery(query, arguments))
            );
        }

        /// <summary>
        /// Handles a number of issues with a database reader, such as DBNull values and broken int64 support
        /// </summary>
        /// <param name="reader">The reader to read from</param>
        /// <param name="index">The value to read</param>
        /// <returns>The normalized value</returns>
        public static object GetNormalizedValue(this IDataReader reader, int index)
        {
            var res = reader.GetValue(index);
            // Convert DBNull to null
            if (res == DBNull.Value)
                return null;

            // Otherwise, just return it
            return res;
        }

        /// <summary>
        /// Executes a non-query
        /// </summary>
        /// <returns>The number of records affected.</returns>
        /// <param name="connection">The connection to use</param>
        /// <param name="query">The SQL statement to execute</param>
        /// <param name="arguments">The arguments to the command</param>
        public static int ExecuteNonQuery(this IDbConnection connection, string query, params object[] arguments)
        {
            var dialect = GetDialect(connection);
            using (var cmd = connection.CreateCommandWithParameters(query))
                return cmd.ExecuteNonQuery(arguments);
        }

        /// <summary>
        /// Returns the number of records that match the query
        /// </summary>
        /// <param name="connection">The connection to use</param>
        /// <param name="query">The where clause to use</param>
        /// <typeparam name="T">The table type</typeparam>
        /// <returns>The count</returns>
        public static long SelectCount<T>(this IDbConnection connection, Expression<Func<T, bool>> query)
        {
            return SelectCount<T>(connection, QueryUtil.FromLambda(query));
        }

        /// <summary>
        /// Returns the number of records that match the query.
        /// Note that this method works on all query types (select, insert, update, delete)
        /// and ignores any limits set on the query
        /// </summary>
        /// <param name="connection">The connection to use</param>
        /// <param name="query">The query to extract the where clause from</param>
        /// <typeparam name="T">The table type</typeparam>
        /// <returns>The count</returns>
        public static long SelectCount<T>(this IDbConnection connection, Query<T> query)
        {
            return SelectCount<T>(connection, query.Parsed.WhereQuery);
        }

        /// <summary>
        /// Returns the number of records that match the query
        /// </summary>
        /// <param name="connection">The connection to use</param>
        /// <param name="query">The where clause to use</param>
        /// <typeparam name="T">The table type</typeparam>
        /// <returns>The count</returns>
        public static long SelectCount<T>(this IDbConnection connection, QueryElement query)
        {
            var q = connection.GetDialect().RenderWhereClause(typeof(T), query);
            return SelectCount<T>(connection, q.Key, q.Value);
        }

        /// <summary>
        /// Returns the number of records for the table
        /// </summary>
        /// <param name="connection">The connection to use</param>
        /// <typeparam name="T">The table type</typeparam>
        /// <returns>The count</returns>
        public static long SelectCount<T>(this IDbConnection connection)
            => SelectCount<T>(connection, new Empty());

        /// <summary>
        /// Returns the number of records that match the query
        /// </summary>
        /// <param name="connection">The connection to use</param>
        /// <param name="query">The where clause to use</param>
        /// <param name="arguments">The arguments to the command</param>
        /// <typeparam name="T">The table type</typeparam>
        /// <returns>The count</returns>
        public static long SelectCount<T>(this IDbConnection connection, string query, params object[] arguments)
        {
            return (long)Convert.ChangeType(ExecuteScalar(connection, $"SELECT COUNT(*) FROM {connection.QuotedTableName<T>()}" + SpacePrefixQuery(query), arguments), typeof(long));
        }

        /// <summary>
        /// Executes a query and returns the scalar value
        /// </summary>
        /// <param name="connection">The connection to use</param>
        /// <param name="query">The SQL statement to execute</param>
        /// <param name="arguments">The arguments to the command</param>
        /// <typeparam name="T">The data type to return as the scalar</typeparam>
        /// <returns>The scalar item</returns>
        public static T ExecuteScalar<T>(this IDbConnection connection, string query, params object[] arguments)
        {
            return (T)Convert.ChangeType(ExecuteScalar(connection, query, arguments), typeof(T));
        }

        /// <summary>
        /// Executes a query and returns the scalar value
        /// </summary>
        /// <param name="connection">The connection to use</param>
        /// <param name="query">The SQL statement to execute</param>
        /// <param name="arguments">The arguments to the command</param>
        /// <returns>The scalar item</returns>
        public static object ExecuteScalar(this IDbConnection connection, string query, params object[] arguments)
        {
            var dialect = GetDialect(connection);
            using (var cmd = connection.CreateCommandWithParameters(query))
            {
                cmd.SetParameterValues(arguments);
                using(var rd = cmd.ExecuteReader())
                {
                    if (!rd.Read())
                        return null;
                    return rd.GetNormalizedValue(0);
                }
            }
        }

        /// <summary>
        /// Performs a database query and returns the results.
        /// Note this function requires the entire SQL command to be given as the query
        /// </summary>
        /// <param name="connection">The connection to use</param>
        /// <returns>A blank new query.</returns>
        /// <typeparam name="T">The data type parameter.</typeparam>
        public static Query<T> Query<T>(this IDbConnection connection)
        {
            return GetDialect(connection).Query<T>();
        }

        /// <summary>
        /// Performs a database query and returns the results.
        /// Note this function requires the entire SQL command to be given as the query
        /// </summary>
        /// <param name="connection">The connection to use</param>
        /// <param name="query">The SQL statement to execute</param>
        /// <param name="arguments">The arguments to the command</param>
        /// <returns>The items that match.</returns>
        /// <typeparam name="T">The data type parameter.</typeparam>
        public static IEnumerable<T> CustomQuery<T>(this IDbConnection connection, string query, params object[] arguments)
            where T : new()
        {
            using (var cmd = connection.CreateCommandWithParameters(query))
            {
                cmd.SetParameterValues(arguments);
                foreach (var n in FillItems<T>(cmd))
                    yield return n;
            }
        }

        /// <summary>
        /// Performs a database query and returns the first result.
        /// Note this function requires the entire SQL command to be given and should have "LIMIT 1" at the end.
        /// </summary>
        /// <param name="connection">The connection to use</param>
        /// <param name="query">The SQL statement to execute</param>
        /// <param name="arguments">The arguments to the command</param>
        /// <returns>The items that match.</returns>
        /// <typeparam name="T">The data type parameter.</typeparam>
        public static T CustomQuerySingle<T>(this IDbConnection connection, string query, params object[] arguments)
            where T : new()
        {
            using (var cmd = connection.CreateCommandWithParameters(query))
            using (var rd = cmd.ExecuteReader(arguments))
                if (rd.Read())
                    return FillItem(rd, GetDialect(connection).GetTypeMap(typeof(T)), new T());

            return default(T);
        }

        /// <summary>
        /// Fills the given item with properties from the query
        /// </summary>
        /// <returns>The items.</returns>
        /// <param name="command">The command to use</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        public static IEnumerable<T> FillItems<T>(this IDbCommand command)
            where T : new()
        {
            var dialect = GetDialect(command.Connection);
            var mapping = dialect.GetTypeMap(typeof(T));

            using(var reader = command.ExecuteReader())
                while (reader.Read())
                    yield return FillItem(reader, mapping, new T());
        }

        /// <summary>
        /// Fills the given item with properties from the query
        /// </summary>
        /// <returns>The item.</returns>
        /// <param name="reader">The reader to use</param>
        /// <param name="item">The item to fill.</param>
        /// <param name="map">The table mapping to use</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        public static T FillItem<T>(this IDataReader reader, TableMapping map, T item)
        {
            var props = map.AllColumnsBySqlName;
            for (var i = 0; i < reader.FieldCount; i++)
            {
                if (props.TryGetValue(reader.GetName(i), out var prop))
                {
                    var value = reader.GetNormalizedValue(i);
                    if (value == null && prop.MemberType.IsValueType)
                        value = Activator.CreateInstance(prop.MemberType);

                    prop.SetValueFromDb(item, value);
                }
            }

            return item;
        }

        /// <summary>
        /// Updates one or more items with the given values.
        /// </summary>
        /// <returns>The number of rows updated.</returns>
        /// <param name="connection">The connection to use</param>
        /// <param name="item">The item with values to update.</param>
        /// <param name="query">The where clause to use</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        public static int Update<T>(this IDbConnection connection, object item, Expression<Func<T, bool>> query)
        {
            return Update(connection,
                GetDialect(connection).
                    Query<T>()
                    .Update(item)
                    .Where(query)
            );
        }

        /// <summary>
        /// Updates one or more items with the given values.
        /// </summary>
        /// <returns>The number of rows updated.</returns>
        /// <param name="connection">The connection to use</param>
        /// <param name="item">The item with values to update.</param>
        /// <param name="query">The where clause to use</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        public static int Update<T>(this IDbConnection connection, object item, QueryElement query)
        {
            return Update(connection,
                GetDialect(connection).
                    Query<T>()
                    .Update(item)
                    .Where(query)
            );
        }

        /// <summary>
        /// Updates one or more items with the given values.
        /// </summary>
        /// <returns>The number of rows updated.</returns>
        /// <param name="connection">The connection to use</param>
        /// <param name="item">The item with values to update.</param>
        /// <param name="query">The SQL where clause to execute</param>
        /// <param name="arguments">The arguments to the command</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        public static int Update<T>(this IDbConnection connection, object item, string query, params object[] arguments)
        {
            return Update(connection,
                GetDialect(connection).
                    Query<T>()
                    .Update(item)
                    .Where(new CustomQuery(query, arguments))
            );
        }

        /// <summary>
        /// Updates one or more items with the given values.
        /// </summary>
        /// <returns>The number of rows updated.</returns>
        /// <param name="connection">The connection to use</param>
        /// <param name="values">Thev values to update.</param>
        /// <param name="query">The SQL where clause to execute</param>
        /// <param name="arguments">The arguments to the command</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        public static int Update<T>(this IDbConnection connection, Dictionary<string, object> values, string query, params object[] arguments)
        {
            return Update(connection,
                GetDialect(connection).
                    Query<T>()
                    .Update(values)
                    .Where(new CustomQuery(query, arguments))
            );
        }

        /// <summary>
        /// Performs an update using the query
        /// </summary>
        /// <param name="connection">The connection to use</param>
        /// <param name="query">The update query</param>
        /// <returns>The number of rows updated.</returns>
        public static int Update(this IDbConnection connection, Query query)
        {
            if (query.Parsed.Type != QueryType.Update)
                throw new InvalidOperationException($"Cannot use a query of type {query.Parsed.Type} for UPDATE");

            var dialect = GetDialect(connection);
            var mapping = dialect.GetTypeMap(query.Parsed.DataType);
            mapping.Validate(query.Parsed.UpdateValues);

            var q = connection.GetDialect().RenderStatement(query);
            using (var cmd = connection.CreateCommandWithParameters(q.Key))
                return cmd.ExecuteNonQuery(q.Value);
        }

        /// <summary>
        /// Updates the item, using the primary key to locate it.
        /// </summary>
        /// <returns><c>true</c>, if item was updated, <c>false</c> otherwise.</returns>
        /// <param name="connection">The connection to use</param>
        /// <param name="item">The item to update.</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        public static bool UpdateItem<T>(this IDbConnection connection, T item)
        {
            return Update(connection,
                GetDialect(connection).
                    Query<T>()
                    .Update(item)
                    .MatchPrimaryKeys(item)
            ) > 0;
        }

        /// <summary>
        /// Deletes items by using the primary key of the given item
        /// </summary>
        /// <returns><c>true</c>, if item was deleted, <c>false</c> otherwise.</returns>
        /// <param name="connection">The connection to use</param>
        /// <param name="item">The item to get the primary key from.</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        public static bool DeleteItem<T>(this IDbConnection connection, T item)
        {
            var dialect = GetDialect(connection);
            var mapping = dialect.GetTypeMap(typeof(T));
            return DeleteItemById<T>(connection, mapping.PrimaryKeys.Select(x => x.GetValueForDb(item)).ToArray());
        }

        /// <summary>
        /// Deletes items matching the where clause
        /// </summary>
        /// <param name="connection">The connection to use</param>
        /// <param name="tdata">The data type to use</param>
        /// <param name="query">The query to use</param>
        /// <returns>The number of items</returns>
        public static int Delete<T>(this IDbConnection connection, Expression<Func<T, bool>> query)
        {
            return Delete(connection,
                GetDialect(connection)
                    .Query<T>()
                    .Delete()
                    .Where(query)
                );
        }

        /// <summary>
        /// Deletes items matching the where clause
        /// </summary>
        /// <param name="connection">The connection to use</param>
        /// <param name="query">The query to use</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        /// <returns>The number of items</returns>
        public static int Delete<T>(this IDbConnection connection, QueryElement query)
        {
            return Delete(connection,
                GetDialect(connection)
                    .Query<T>()
                    .Delete()
                    .Where(query)
            );
        }

        /// <summary>
        /// Deletes items matching the where clause
        /// </summary>
        /// <param name="connection">The connection to use</param>
        /// <param name="whereclause">The where clause</param>
        /// <param name="arguments">The arguments for the where clause</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        /// <returns>The number of items</returns>
        public static int Delete<T>(this IDbConnection connection, string whereclause, params object[] arguments)
        {
            return Delete(connection,
                GetDialect(connection)
                    .Query<T>()
                    .Delete()
                    .Where(new CustomQuery(whereclause, arguments)
                )
            );
        }

        /// <summary>
        /// Deletes the item with the given ID
        /// </summary>
        /// <returns><c>true</c>, if item was deleted, <c>false</c> otherwise.</returns>
        /// <param name="connection">The connection to use</param>
        /// <param name="ids">The primary key.</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        public static bool DeleteItemById<T>(this IDbConnection connection, params object[] ids)
        {
            var map = GetDialect(connection).GetTypeMap<T>();
            return Delete(connection,
                GetDialect(connection)
                    .Query<T>()
                    .Delete()
                    .Limit(1)
                    .MatchPrimaryKeys(ids)
            ) > 0;
        }

        /// <summary>
        /// Deletes items matching the where clause
        /// </summary>
        /// <param name="connection">The connection to use</param>
        /// <param name="query">The query to use</param>
        /// <returns>The number of items deleted</returns>
        public static int Delete<T>(this IDbConnection connection, Query<T> query)
        {
            if (query.Parsed.Type != QueryType.Delete)
                throw new InvalidOperationException($"Cannot use a query of type {query.Parsed.Type} for DELETE");
            var q = connection.GetDialect().RenderStatement(query);
            using (var cmd = connection.CreateCommandWithParameters(q.Key))
                return cmd.ExecuteNonQuery(q.Value);
        }

        /// <summary>
        /// Deletes items matching the where clause
        /// </summary>
        /// <param name="connection">The connection to use</param>
        /// <param name="query">The query to use</param>
        /// <returns>The number of items deleted</returns>
        public static int Delete(this IDbConnection connection, Query query)
        {
            if (query.Parsed.Type != QueryType.Delete)
                throw new InvalidOperationException($"Cannot use a query of type {query.Parsed.Type} for DELETE");
            var q = connection.GetDialect().RenderStatement(query);
            using (var cmd = connection.CreateCommandWithParameters(q.Key))
                return cmd.ExecuteNonQuery(q.Value);
        }

        /// <summary>
        /// Inserts the given item into the database
        /// </summary>
        /// <param name="connection">The connection to use</param>
        /// <param name="item">The item to insert.</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        /// <returns>The inserted item</returns>
        public static T InsertOrIgnoreItem<T>(this IDbConnection connection, T item)
        {
            return Insert<T>(
                connection,
                GetDialect(connection)
                    .Query<T>()
                    .Insert(item)
                    .IgnoreInsertFailure()
            );
        }

        /// <summary>
        /// Inserts the given item into the database
        /// </summary>
        /// <param name="connection">The connection to use</param>
        /// <param name="item">The item to insert.</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        /// <returns>The inserted item</returns>
        public static T InsertItem<T>(this IDbConnection connection, T item)
        {
            // Catch bad mappings from the user
            if (item is Query)
                return Insert<T>(connection, (Query)(object)item);

            return Insert<T>(
                connection,
                GetDialect(connection)
                    .Query<T>()
                    .Insert(item)
            );
        }

        /// <summary>
        /// Inserts the given item into the database
        /// </summary>
        /// <param name="connection">The connection to use</param>
        /// <param name="query">The query to use.</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        /// <returns>The inserted item</returns>
        public static T Insert<T>(this IDbConnection connection, Query<T> query)
        {
            return Insert<T>(connection, (Query)query);
        }

        /// <summary>
        /// Inserts the given item into the database
        /// </summary>
        /// <param name="connection">The connection to use</param>
        /// <param name="query">The query to use.</param>
        /// <typeparam name="T">The data type parameter.</typeparam>
        /// <returns>The inserted item</returns>
        public static T Insert<T>(this IDbConnection connection, Query query)
        {
            var dialect = GetDialect(connection);
            var mapping = dialect.GetTypeMap(typeof(T));

            var item = (T)query.Parsed.InsertItem;
            mapping.Validate(item);

            var q = dialect.RenderStatement(query);

            using (var cmd = connection.CreateCommandWithParameters(q.Key))
            {
                if (!mapping.IsPrimaryKeyAutogenerated)
                {
                    var res = cmd.ExecuteNonQuery(q.Value) > 0;
                    foreach (var n in mapping.PrimaryKeys)
                        n.SetValueFromDb(item, query.Parsed.UpdateValues[n.MemberName]);
                }
                else
                {
                    var id = cmd.ExecuteScalar(q.Value);
                    var pk = mapping.PrimaryKeys.First();
                    pk.SetValueFromDb(item, id);
                }
            }

            // TODO: We could also read back the client generated to ensure that the values do not
            // have small precision differences
            foreach (var x in mapping.ClientGenerated)
                if (query.Parsed.UpdateValues.TryGetValue(x.MemberName, out var v))
                    x.SetValue(item, v);

            if (mapping.DatabaseGenerated.Count > (mapping.IsPrimaryKeyAutogenerated ? 1 : 0))
            {
                // Read back the client and database generated values
                var cols = mapping.DatabaseGenerated.Concat(mapping.ClientGenerated);
                SelectSingle(
                    connection,
                    connection.Query<T>()
                        .Select(cols.Select(x => x.MemberName).ToArray())
                        .MatchPrimaryKeys(item),
                    () => item
                );
            }

            return item;
        }

        /// <summary>
        /// Gets the quoted tablename for the table
        /// </summary>
        /// <param name="connection">The connection to get the dialect from</param>
        /// <typeparam name="T">The type to get the tablename from</typeparam>
        /// <returns>The quoted table name</returns>
        public static string QuotedTableName<T>(this IDbConnection connection)
        {
            return GetDialect(connection).GetTypeMap<T>().QuotedTableName;
        }

        /// <summary>
        /// Gets the quoted name for a column given the property name
        /// </summary>
        /// <param name="connection">The connection to get the dialect from</param>
        /// <param name="propertyname">The name of the property to get the column name for</param>
        /// <typeparam name="T">The type to get the column name from</typeparam>
        /// <returns>The quoted column name</returns>
        public static string QuotedColumnName<T>(this IDbConnection connection, string propertyname)
        {
            return GetDialect(connection).GetTypeMap<T>().QuotedColumnName(propertyname);
        }

        /// <summary>
        /// Gets the type map for a given type
        /// </summary>
        /// <param name="connection">The connection to get the dialect from</param>
        /// <typeparam name="T">The type to get the map from</typeparam>
        /// <returns>The table mapping for the type</returns>
        public static TableMapping GetTypeMap<T>(this IDbConnection connection)
        {
            return GetDialect(connection).GetTypeMap<T>();
        }

        /// <summary>
        /// Gets the type map for a given type
        /// </summary>
        /// <param name="connection">The connection to get the dialect from</param>
        /// <param name="type">The type to get the map from</param>
        /// <returns>The table mapping for the type</returns>
        public static TableMapping GetTypeMap(this IDbConnection connection, Type type)
        {
            return GetDialect(connection).GetTypeMap(type);
        }

    }
}


text:
public class SortAndStar {
  public static String twoSort(String[] s) {
    java.util.Arrays.sort(s);

    return String.join("***",s[0].split(""));
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace WordCamp\RemoteCSS;

defined( 'WPINC' ) or die();

add_action( 'wp_ajax_'        . AJAX_ACTION, __NAMESPACE__ . '\webhook_handler'        ); // This is useless in production, but useful for manual testing
add_action( 'wp_ajax_nopriv_' . AJAX_ACTION, __NAMESPACE__ . '\webhook_handler'        );
add_action( SYNCHRONIZE_ACTION,              __NAMESPACE__ . '\synchronize_remote_css' );

/**
 * Trigger a synchronization when a push notification is received
 *
 * Because the client can't modify the remote URL that's being used, it's safe to allow anonymous access to this,
 * provided that requests are rate-limited to prevent a malicious party from making us flood remote servers, which
 * would result in them blocking us. The worst they could do would be to force us to unnecessarily refresh the cache.
 *
 * Avoiding authentication makes the process simpler because there's less to do, and also more flexible, because
 * we don't have to handle notification formats from various platforms.
 */
function webhook_handler() {
	$time_since_last_sync = time() - get_option( OPTION_LAST_UPDATE, 0 );

	if ( $time_since_last_sync < WEBHOOK_RATE_LIMIT ) {
		$time_limit_remaining = WEBHOOK_RATE_LIMIT - $time_since_last_sync;

		/*
		 * We only want one event scheduled to prevent abuse and unnecessary requests, but
		 * wp_schedule_single_event() does that for us if the period is under 10 minutes.
		 */
		wp_schedule_single_event(
			time() + $time_limit_remaining,
			SYNCHRONIZE_ACTION,
			array( get_option( OPTION_REMOTE_CSS_URL ) )
		);

		wp_send_json_error( sprintf(
			__( 'The request could not be executed immediately because of the rate limit. Instead, it has been queued and will run in %d seconds.',
			'wordcamporg' ),
			$time_limit_remaining
		) );
	} else {
		try {
			do_action( SYNCHRONIZE_ACTION, get_option( OPTION_REMOTE_CSS_URL ) );
			wp_send_json_success( __( 'The remote CSS file was successfully synchronized.', 'wordcamporg' ) );
		} catch ( \Exception $exception ) {
			wp_send_json_error( strip_tags( $exception->getMessage() ) );   // strip_tags() instead of wp_strip_tags() because we want to preserve the inner content
		}
	}
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Agric. Mag. , Formosa 38(3): 174 (1942)

#### Original name
Phytophthora ricini Sawada, 1942

### Remarks
null


text:
define(function(){
    // This object partially parses the data contained in a pack-*.idx file, and provides
    // access to the offsets of the objects the packfile and the crc checksums of the objects.
    PackIndex = function(buf) {
    	var data = new DataView(buf);
    	this.data = data;
    	// load the index into memory
    	var magicNum = data.getUint32(0, false);
    	var versionNum = data.getUint32(4, false);

    	if (magicNum != 0xff744f63 || versionNum != 2){
    		throw(Error("Bad pack index header. Only version 2 is supported"))
    	}

    	var byteOffset = 8
    	//this.fanOffset = byteOffset;

    	var numObjects = data.getUint32(byteOffset + (255 * 4), false);

    	// skip past fanout table
    	var fanTableLen = 256 * 4;
    	byteOffset += fanTableLen;
    	var shaTableLen = numObjects * 20;
    	this.shaList = new Uint8Array(buf, byteOffset, shaTableLen);

    	// skip past shas and the CRC vals
    	byteOffset += shaTableLen + (numObjects * 4);

    	this.offsetsOffset = byteOffset;
    	this.numObjects = numObjects;
    }

    PackIndex.prototype = {
    	_compareShas : function(sha1, sha2){
    		 // assume the first byte has been matched in the fan out table
    		for (var i = 1; i < 20; i++){
    			if (sha1[i] != sha2[i]){
    				return sha1[i] - sha2[i];
    			}
    		}
    		return 0;
    	},
    	_getShaAtIndex : function(index){
    	    var byteOffset = index * 20;
    	    return this.shaList.subarray(byteOffset, byteOffset + 20);
    	},
    	getObjectOffset : function(sha){
    		var fanIndex = sha[0];

    		var sliceStart = fanIndex > 0 ? (this.data.getUint32(8 + ((fanIndex - 1) * 4), false)) : 0;
    		var sliceEnd = this.data.getUint32(8 + (fanIndex * 4), false);

    		if (sliceEnd - sliceStart == 0){
    			return -1;
    		}

    		var index;
    		while (sliceEnd - sliceStart  > 1){
    			var split = sliceStart + Math.floor(((sliceEnd - sliceStart)/2));

    			var mid = this._getShaAtIndex(split);

    			var compare = this._compareShas(sha, mid);
    			if (compare == 0){
    				index = split;
    				break;
    			}
    			else if (compare < 0){
    				sliceEnd = split;
    			}
    			else{
    				sliceStart = split + 1;
    			}
    		}
    		// if we've exited the loop without a match, sliceStart should hold the index or it's not here.
    		if (!index){
    			if (sliceStart < this.numObjects && this._compareShas(sha, this._getShaAtIndex(sliceStart)) == 0){
    				index = sliceStart;
    			}
    			else{
    				return -1;
    			}
    		}

    		var objOffset = this.data.getUint32(this.offsetsOffset + (index * 4), false);
    		return objOffset;

    	}
    }
    /*
    * = Version 2 pack-*.idx files support packs larger than 4 GiB, and
    *  have some other reorganizations.  They have the format:
    *
    *  - A 4-byte magic number '\377tOc' which is an unreasonable
    *    fanout[0] value.
    *
    *  - A 4-byte version number (= 2)
    *
    *  - A 256-entry fan-out table just like v1.
    *
    *  - A table of sorted 20-byte SHA1 object names.  These are
    *    packed together without offset values to reduce the cache
    *    footprint of the binary search for a specific object name.
    *
    *  - A table of 4-byte CRC32 values of the packed object data.
    *    This is new in v2 so compressed data can be copied directly
    *    from pack to pack during repacking without undetected
    *    data corruption.
    *
    *  - A table of 4-byte offset values (in network byte order).
    *    These are usually 31-bit pack file offsets, but large
    *    offsets are encoded as an index into the next table with
    *    the msbit set.
    *
    *  - A table of 8-byte offset entries (empty for pack files less
    *    than 2 GiB).  Pack files are organized with heavily used
    *    objects toward the front, so most object references should
    *    not need to refer to this table.
    *
    *  - The same trailer as a v1 pack file:
    *
    *    A copy of the 20-byte SHA1 checksum at the end of
    *    corresponding packfile.
    *
    *    20-byte SHA1-checksum of all of the above.
    */
    PackIndex.writePackIdx = function(objects, packSha){
    	var size = 4 + 4 + (256 * 4) + (objects.length * 20) + (objects.length * 4)  + (objects.length * 4) + (20 * 2);
    	var buf = new ArrayBuffer(size);

    	objects.sort(function(obj1, obj2){
    		for (var i = 0; i < 20; i++){
    			if (obj1.sha[i] != obj2.sha[i]){
    				return obj1.sha[i] - obj2.sha[i];
    			}
    		}
    		return 0; // shouldn't happen but just in case
    	});

        var data = new DataView(buf);

        // magic number
        data.setUint32(0, 0xff744f63, false);

        //version number
        data.setUint32(4, 2, false);

        // fan table
        var byteOffset = 8, current = 0;

        for (var i = 0; i < objects.length; i++){
        	var next = objects[i].sha[0];
        	if (next != current){

        		for (var j = current; j < next; j++){
        			data.setUint32(byteOffset + (j * 4), i, false);
        		}
        	}
        	current = next;
        }
        for (var j = current; j < 256; j++){
    		data.setUint32(byteOffset + (j * 4), objects.length, false);
    	}

        // list of shas
        byteOffset += (256 * 4);

        for (var i = 0; i < objects.length; i++){
        	for (var j = 0; j < 20; j++){
        		data.setUint8(byteOffset++, objects[i].sha[j]);
        	}
        }

        // list of crcs
        for (var i = 0; i < objects.length; i++){
        	data.setUint32(byteOffset, objects[i].crc, false);
        	byteOffset += 4;
        }

        // list of offsets. Note that I'm not going to bother with large offsets. You shouldn't be loading a packfile >2GB inside a web browser anyway.
        for (var i = 0; i < objects.length; i++){
        	data.setUint32(byteOffset, objects[i].offset, false);
        	byteOffset += 4;
        }

        // the pack file sha
        for (var i = 0; i < 20; i++){
        	data.setUint8(byteOffset++, packSha[i]);
        }

        // sha for all of the above
        var indexSha = Crypto.SHA1(new Uint8Array(buf, 0, byteOffset), {asBytes:true});
        for (var i = 0; i < 20; i++){
        	data.setUint8(byteOffset++, indexSha[i]);
        }
        return buf;
    }

    return PackIndex;
});


text: import R from 'ramda'


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class com.hazelcast.cache.impl.AbstractCacheService (Hazelcast Root 3.4.2 API)
</TITLE>

<META NAME="date" CONTENT="2015-03-26">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
com.hazelcast.cache.impl.AbstractCacheService

Packages that use AbstractCacheService

com.hazelcast.cache.impl

     Hazelcast JSR-107 aka JCache implementation

Uses of AbstractCacheService in com.hazelcast.cache.impl

Subclasses of AbstractCacheService in com.hazelcast.cache.impl

 class
CacheService

          Cache Service is the main access point of JCache implementation.

Fields in com.hazelcast.cache.impl declared as AbstractCacheService

protected  AbstractCacheService
AbstractCacheRecordStore.cacheService

Constructors in com.hazelcast.cache.impl with parameters of type AbstractCacheService

AbstractCacheRecordStore(String name,
                         int partitionId,
                         NodeEngine nodeEngine,
                         AbstractCacheService cacheService)

CacheRecordStore(String name,
                 int partitionId,
                 NodeEngine nodeEngine,
                 AbstractCacheService cacheService)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2015 Hazelcast, Inc.. All Rights Reserved.


text:
define(
	[
		'jquery',
	],
	function ($) {
		var $sticky = $('.sticky-header');

		$(document).on('scroll', function(event) {
			var scrollTop = $(window).scrollTop();
			console.log('scroll', scrollTop);
			if (scrollTop > 50) {
				$sticky.css('position', 'fixed');
			} else if (scrollTop <= 50) {
				$sticky.css('position', 'static');
			}
		});
	}
);


text:
package com.google.javascript.jscomp;

import com.google.javascript.rhino.Node;

import java.util.regex.Pattern;

/**
 * This describes the Google-specific JavaScript coding conventions.
 * Within Google, variable names are semantically significant.
 *
 */
public class GoogleCodingConvention extends CodingConventions.Proxy {

  private static final long serialVersionUID = 1L;

  private static final String OPTIONAL_ARG_PREFIX = "opt_";

  private static final String VAR_ARGS_NAME = "var_args";

  private static final Pattern ENUM_KEY_PATTERN =
    Pattern.compile("[A-Z0-9][A-Z0-9_]*");

  /** By default, decorate the ClosureCodingConvention. */
  public GoogleCodingConvention() {
    this(new ClosureCodingConvention());
  }

  /** Decorates a wrapped CodingConvention. */
  public GoogleCodingConvention(CodingConvention convention) {
    super(convention);
  }

  /**
   * {@inheritDoc}
   *
   *
This enforces the Google const name convention, that the first character
   * after the last $ must be an upper-case letter and all subsequent letters
   * must be upper case. The name must be at least 2 characters long.
   *
   *
Examples:
   *

   *      aaa          Not constant - lower-case letters in the name
   *      A            Not constant - too short
   *      goog$A       Constant - letters after the $ are upper-case.
   *      AA17         Constant - digits can appear after the first letter
   *      goog$7A      Not constant - first character after the $ must be
   *                   upper case.
   *      $A           Constant - doesn't have to be anything in front of the $
   *

   */
  @Override
  public boolean isConstant(String name) {
    if (name.length() <= 1) {
      return false;
    }

    // In compiled code, '$' is often a namespace delimiter. To allow inlining
    // of namespaced constants, we strip off any namespaces here.
    int pos = name.lastIndexOf('$');
    if (pos >= 0) {
      name = name.substring(pos + 1);
      if (name.isEmpty()) {
        return false;
      }
    }

    return isConstantKey(name);
  }

  @Override
  public boolean isConstantKey(String name) {
    if (name.isEmpty() || !Character.isUpperCase(name.charAt(0))) {
      return false;
    }

    // hack way of checking that there aren't any lower-case letters
    return name.toUpperCase().equals(name);
  }

  /**
   * {@inheritDoc}
   *
   *
This enforces Google's convention about enum key names. They must match
   * the regular expression {@code [A-Z0-9][A-Z0-9_]*}.
   *
   *
Examples:
   *

   *
A

   *
213

   *
FOO_BAR

   *

   */
  @Override
  public boolean isValidEnumKey(String key) {
    return ENUM_KEY_PATTERN.matcher(key).matches();
  }

  /**
   * {@inheritDoc}
   *
   *
In Google code, parameter names beginning with {@code opt_} are
   * treated as optional arguments.
   */
  @Override
  public boolean isOptionalParameter(Node parameter) {
    return parameter.getString().startsWith(OPTIONAL_ARG_PREFIX);
  }

  @Override
  public boolean isVarArgsParameter(Node parameter) {
    return VAR_ARGS_NAME.equals(parameter.getString());
  }

  /**
   * {@inheritDoc}
   *
   *
In Google code, any global name starting with an underscore is
   * considered exported.
   */
  @Override
  public boolean isExported(String name, boolean local) {
    return super.isExported(name, local) ||
        (!local && name.startsWith("_"));
  }

  /**
   * {@inheritDoc}
   *
   *
In Google code, private names end with an underscore, and exported
   * names are never considered private (see {@link #isExported}).
   */
  @Override
  public boolean isPrivate(String name) {
    return name.endsWith("_") && !isExported(name);
  }
}


text:
namespace peloton {
namespace networking {
class Connection;
class Listener {
 public:
  // This is the server port
  Listener(int port);
  ~Listener();

  // Get the server port
  int GetPort() const { return port_; }

  // The listenner event is in the listen_base_
  struct event_base* GetEventBase() const {
    return listen_base_;
  }

  // listener is a evconnlistener type which is a libevent type
  struct evconnlistener* GetListener() const {
    return listener_;
  }

  // Begin listening
  void Run(void* arg);

 private:
  // AcceptConnCb is a callback invoked when a new connection is accepted
  static void AcceptConnCb(struct evconnlistener* listener, evutil_socket_t fd,
                           struct sockaddr* address, int socklen, void* ctx);

  // AcceptErrorCb is invoked when error occurs
  static void AcceptErrorCb(struct evconnlistener* listener, void* ctx);

  // server listenning port
  int port_;

  // The listenner event is in the listen_base_
  struct event_base* listen_base_;

  // listener is a evconnlistener type which is a libevent type
  struct evconnlistener* listener_;
};

}  // namespace networking
}  // namespace peloton


text:
using System;
using System.Collections.Generic;

namespace Jurassic.Compiler
{
    /// <summary>
    /// Represents the base class of expressions and statements.
    /// </summary>
    internal abstract class AstNode
    {
        private static AstNode[] emptyNodeList = new AstNode[0];

        /// <summary>
        /// Gets an enumerable list of child nodes in the abstract syntax tree.
        /// </summary>
        public virtual IEnumerable<AstNode> ChildNodes
        {
            get { return emptyNodeList; }
        }

        /// <summary>
        /// Determines if this node or any of this node's children are of the given type.
        /// </summary>
        /// <typeparam name="T"> The type of AstNode to search for. </typeparam>
        /// <returns> <c>true</c> if this node or any of this node's children are of the given
        /// type; <c>false</c> otherwise. </returns>
        public bool ContainsNodeOfType<T>() where T : AstNode
        {
            if (this is T)
                return true;
            foreach (var child in this.ChildNodes)
                if (child.ContainsNodeOfType<T>())
                    return true;
            return false;
        }

        /// <summary>
        /// Generates CIL for the expression.
        /// </summary>
        /// <param name="generator"> The generator to output the CIL to. </param>
        /// <param name="optimizationInfo"> Information about any optimizations that should be performed. </param>
        public abstract void GenerateCode(ILGenerator generator, OptimizationInfo optimizationInfo);
    }
}


text:
<?php

namespace Hal\Application\Score;

use Hal\Application\Score\Factor\ReadabilityFactor;
use Hal\Application\Score\Factor\BugPreventingFactor;
use Hal\Application\Score\Factor\ComplexityFactor;
use Hal\Application\Score\Factor\MaintainabilityFactor;
use Hal\Application\Score\Factor\VolumeFactor;
use Hal\Component\Bounds\BoundsInterface;
use Hal\Component\Result\ResultCollection;
use Hal\Component\Score\ScoringInterface;

/**
 * Calculate score
 *
 * @author Jean-François Lépine <https://twitter.com/Halleck45>
 */
class Scoring implements ScoringInterface{

    /**
     * Maximal score
     */
    const MAX = 100;

    /**
     * Bounds
     *
     * @var BoundsInterface
     */
    private $bound;

    /**
     * Constructor
     *
     * @param BoundsInterface $bound
     */
    public function __construct(BoundsInterface $bound)
    {
        $this->bound = $bound;
    }

    /**
     * @inheritdoc
     */
    public function calculate(ResultCollection $collection, ResultCollection $groupedResults) {

        $calculator = new Calculator();
        $bound = $this->bound->calculate($collection);

        // list of factors of quality
        $factors = array(
            new MaintainabilityFactor($calculator)
            , new ReadabilityFactor($calculator)
            , new ComplexityFactor($calculator)
            , new VolumeFactor($calculator)
            , new BugPreventingFactor($calculator)
        );

        // score
        $result = new Result;
        foreach($factors as $qualityFactor) {
            $score = $qualityFactor->calculate($collection, $groupedResults, $bound);
            $result->push($qualityFactor->getName(), $score);
        }

        return $result;
    }
}


text:
// Copyright 2015 The MemDB Authors.
//
// 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. See the AUTHORS file
// for names of contributors.

/* jshint ignore:start */

/*!
 * Module dependencies.
 */

var Binary = require('mongodb').Binary;

module.exports = exports = Binary;


text:
'use strict';

var React = require('react');
var PureRenderMixin = require('react-addons-pure-render-mixin');
var SvgIcon = require('../../svg-icon');

var ActionReportProblem = React.createClass({
  displayName: 'ActionReportProblem',

  mixins: [PureRenderMixin],

  render: function render() {
    return React.createElement(
      SvgIcon,
      this.props,
      React.createElement('path', { d: 'M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z' })
    );
  }

});

module.exports = ActionReportProblem;


text:
/*
  In App.xaml:
  <Application.Resources>
      <vm:ViewModelLocator xmlns:vm="clr-namespace:DansLEnsemble"
                           x:Key="Locator" />
  </Application.Resources>

  In the View:
  DataContext="{Binding Source={StaticResource Locator}, Path=ViewModelName}"

  You can also use Blend to do all this with the tool's support.
  See http://www.galasoft.ch/mvvm
*/

using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Ioc;
using Microsoft.Practices.ServiceLocation;
using System.Collections.Generic;

namespace DansLEnsemble.ViewModel
{
    public class ViewModelLocator
    {
        public ViewModelLocator()
        {
            #region Initialisation IOC
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
            SimpleIoc.Default.Register<MainViewModel>();
            #endregion

            Roles = new List<string>() { "Administrateur" };
        }

        #region Autres propriétés

        public MainViewModel Main
        {
            get
            {
                return ServiceLocator.Current.GetInstance<MainViewModel>();
            }
        }

        #endregion

        public List<string> Roles { get; set; }
    }
}


text:
Here is how you can get help from the community and contribute:

### Forum / Mailing list
Join the Google Group http://groups.google.com/group/osgjs

### IRC
Join us on the #osgjs channel on Freenode

### E-mail
Reach us by sending an e-mail to contact@osgjs.org

### Twitter
Follow [@osgjs](http://twitter.com/osgjs) on Twitter.

### Blog
Follow our [Blog](http://osgjs.tumblr.com) to get news and updates.

### Google+
Follow [Community news](https://plus.google.com/u/0/communities/105204964607979327212) on G+.


text:
/******************************************************************************
* File       : Task_PT_Demo2.h
* Function   : Another demo task for PT application
* Description: To be done.
* Version    : V1.00
* Author     : Ian
* Date       : 8th Jul 2016
* History    :  No.  When           Who           What
*               1    08/Jul/2016    Ian           Create
******************************************************************************/

#ifndef _TASK_PT_DEMO2_H_
#define _TASK_PT_DEMO2_H_

#ifdef __cplusplus
extern "C" {
#endif

/* Check if specified option is set for debugging */
#ifndef __DEBUG_MODE_PT_DEMO2
#define __DEBUG_MODE      __DEBUG_NONE                /* Default: None debugging info            */
#else
#ifdef __DEBUG_MODE
#undef __DEBUG_MODE
#endif
#define __DEBUG_MODE      __DEBUG_MODE_PT_DEMO2       /* According the set from project_config.h */
#endif

/******************************************************************************
* Name       : uint8 Task_PT_Demo2_Process(uint8 u8Evt, void *pPara)
* Function   : A demo task for PT application
* Input      : uint8  u8Evt  1~254     Event for the task
*              void  *pPara            Pointer of parameter
* Output:    : None
* Return     : SW_OK   Successful operation
*            : SW_ERR  Failed operation
*              1~254   Event which is not processed.
* Description: To be done
* Version    : V1.00
* Author     : Ian
* Date       : 8th Jul 2016
******************************************************************************/
uint8 Task_PT_Demo2_Process(uint8 u8Evt, void *pPara);

#ifdef __cplusplus
}
#endif

#endif /* _TASK_PT_DEMO2_H */

/* End of file */


text:
package nl.hugojanssen.sqlgraph.model;

import static org.fest.assertions.Assertions.assertThat;

import java.util.Date;

import nl.hugojanssen.sqlgraph.model.sql.EClauseType;

import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class ParseResultTest
{
	private String name = "table1", schema = "schema1";

	private ParseResult table1, table2;

	@BeforeTest
	public void setup()
	{
		this.table1 = new ParseResult( this, this.schema, this.name, EClauseType.SOURCE, -1, -1 );
		this.table2 = new ParseResult( this, "", "table2", null, -1, -1 );
	}

	@Test( description = "Test getColNo" )
	public void testGetColNo()
	{
		assertThat( this.table1.getColNo() ).isEqualTo( -1 );
	}

	@Test( description = "Test getId" )
	public void testGetId()
	{
		assertThat( this.table1.getId() ).isEqualTo( this.schema + "." + this.name );
	}

	@Test( description = "Test getLineNo" )
	public void testGetLineNo()
	{
		assertThat( this.table1.getLineNo() ).isEqualTo( -1 );
	}

	@Test( description = "Test getName" )
	public void testGetName()
	{
		assertThat( this.table1.getName() ).isEqualTo( this.name );
	}

	@Test( description = "Test getRole" )
	public void testGetRole()
	{
		assertThat( this.table1.getRole() ).isEqualTo( EClauseType.SOURCE );
	}

	@Test( description = "Test getSchema" )
	public void testGetSchema()
	{
		assertThat( this.table1.getSchema() ).isEqualTo( this.schema );
	}

	@Test( description = "Test hashCode" )
	public void testHashCode()
	{
		assertThat( this.table1.hashCode() ).isEqualTo( 364251310 );
	}

	@Test( description = "Test getToString" )
	public void testToString()
	{
		assertThat( this.table1.toString() ).isNotNull();
	}

	@Test( description = "Test validateState" )
	public void testValidateState()
	{
		assertThat( this.table1.equals( null ) ).isFalse();
		assertThat( this.table1.equals( this.table2 ) ).isFalse();
		assertThat( this.table1.equals( Boolean.TRUE ) ).isFalse();
		assertThat( this.table1.equals( 1L ) ).isFalse();
		assertThat( this.table1.equals( new Date() ) ).isFalse();

		assertThat( this.table2.equals( this.table1 ) ).isFalse();

		assertThat( this.table1.equals( this.table1 ) ).isTrue();

		try
		{
			new ParseResult( this, "test", "", null, -1, -1 );
		}
		catch ( IllegalArgumentException e )
		{
			assertThat( e.getMessage() ).isEqualTo( "Name must be non-null and non-empty." );
		}
	}
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
#pragma warning disable 1591

namespace TWCore.Serialization.PWSerializer.Types
{
    /// <inheritdoc cref="ITypeSerializer" />
    /// <summary>
    /// Byte array optimized serializer
    /// </summary>
    public class ByteArraySerializer : ITypeSerializer<byte[]>
    {
        public static readonly HashSet<byte> ReadTypes = new HashSet<byte>(new []
        {
            DataType.ByteArrayNull, DataType.ByteArrayEmpty, DataType.ByteArrayLengthByte, DataType.ByteArrayLengthUShort, DataType.ByteArrayLengthInt,
        });

        /// <inheritdoc />
        /// <summary>
        /// Type serializer initialization
        /// </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Init()
        {
        }
        /// <inheritdoc />
        /// <summary>
        /// Clear serializer cache
        /// </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Clear()
        {
        }
        /// <inheritdoc />
        /// <summary>
        /// Gets if the type serializer can write the type
        /// </summary>
        /// <param name="type">Type of the value to write</param>
        /// <returns>true if the type serializer can write the type; otherwise, false.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool CanWrite(Type type)
            => type == typeof(byte[]);
        /// <inheritdoc />
        /// <summary>
        /// Gets if the type serializer can read the data type
        /// </summary>
        /// <param name="type">DataType value</param>
        /// <returns>true if the type serializer can read the type; otherwise, false.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool CanRead(byte type)
            => ReadTypes.Contains(type);
        /// <inheritdoc />
        /// <summary>
        /// Writes the serialized value to the binary stream.
        /// </summary>
        /// <param name="writer">Binary writer of the stream</param>
        /// <param name="value">Object value to be written</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Write(BinaryWriter writer, object value)
            => WriteValue(writer, (byte[])value);
        /// <inheritdoc />
        /// <summary>
        /// Reads a value from the serialized stream.
        /// </summary>
        /// <param name="reader">Binary reader of the stream</param>
        /// <param name="type">DataType</param>
        /// <returns>Object instance of the value deserialized</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public object Read(BinaryReader reader, byte type)
            => ReadValue(reader, type);

        /// <inheritdoc />
        /// <summary>
        /// Writes the serialized value to the binary stream.
        /// </summary>
        /// <param name="writer">Binary writer of the stream</param>
        /// <param name="value">Object value to be written</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void WriteValue(BinaryWriter writer, byte[] value)
        {
			if (value is null)
			{
				writer.Write(DataType.ByteArrayNull);
				return;
			}
            if (value.Length == 0)
            {
                writer.Write(DataType.ByteArrayEmpty);
                return;
            }
            #region Write Array
            var length = value.Length;
            if (length <= byte.MaxValue)
                WriteHelper.WriteByte(writer, DataType.ByteArrayLengthByte, (byte)length);
            else if (length <= ushort.MaxValue)
                WriteHelper.WriteUshort(writer, DataType.ByteArrayLengthUShort, (ushort)length);
            else
                WriteHelper.WriteInt(writer, DataType.ByteArrayLengthInt, length);
            writer.Write(value);
            #endregion
        }
        /// <inheritdoc />
        /// <summary>
        /// Reads a value from the serialized stream.
        /// </summary>
        /// <param name="reader">Binary reader of the stream</param>
        /// <param name="type">DataType</param>
        /// <returns>Object instance of the value deserialized</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public byte[] ReadValue(BinaryReader reader, byte type)
        {
            var length = 0;
            switch (type)
            {
                case DataType.ByteArrayNull:
                    return null;
                case DataType.ByteArrayEmpty:
                    return Array.Empty<byte>();
                case DataType.ByteArrayLengthByte:
                    length = reader.ReadByte();
                    break;
                case DataType.ByteArrayLengthUShort:
                    length = reader.ReadUInt16();
                    break;
                case DataType.ByteArrayLengthInt:
                    length = reader.ReadInt32();
                    break;
            }
            var cValue = reader.ReadBytes(length);
            return cValue;
        }
        /// <inheritdoc />
        /// <summary>
        /// Reads a value from the serialized stream.
        /// </summary>
        /// <param name="reader">Binary reader of the stream</param>
        /// <returns>Object instance of the value deserialized</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public byte[] ReadValue(BinaryReader reader)
            => ReadValue(reader, reader.ReadByte());
    }
}


text:
from scaleiopy.scaleio import ScaleIO
from pprint import pprint
import sys

# How to run:
# python create_mapall-volume.py ip-to-mdm user pass volume_name size_mb protection_domain_name storage_pool_name

# Whats this code doing:
# Create a volume of x MB [min 8192MB] inside specified protectiondomain and storagepool, then map it to all registered SDCs

sio = ScaleIO("https://" + sys.argv[1] + "/api",sys.argv[2],sys.argv[3],False,"ERROR") # HTTPS must be used as there seem to be an issue with 302 responses in Requests when using POST

sio.create_volume(sys.argv[4], sys.argv[5], sio.get_pd_by_name(sys.argv[6]), sio.get_storage_pool_by_name(sys.argv[7]), enableMapAllSdcs=True)

pprint(sio.volumes)


text:
name = "postgresql"
pg = Formula[name]
bin = pg.bin
var = pg.var
version = pg.version
pg_version_file = var/"postgres/PG_VERSION"

pg_version_installed = version.to_s[/^\d+/]
pg_version_data = pg_version_file.read.chomp
if pg_version_installed == pg_version_data
  odie <<~EOS
    #{name} data already upgraded!
  EOS
end

datadir = var/"postgres"
old_datadir = var/"postgres.old"
if old_datadir.exist?
  odie <<~EOS
    #{old_datadir} already exists!
    Remove it if you want to upgrade data automatically.
  EOS
end

old_pg_name = "#{name}@#{pg_version_data}"
old_pg_glob = "#{HOMEBREW_PREFIX}/Cellar/#{old_pg_name}/#{pg_version_data}.*/bin"
old_bin = Pathname.glob(old_pg_glob).first
old_bin ||= begin
  Formula[old_pg_name]
  ohai "brew install #{old_pg_name}"
  system "brew", "install", old_pg_name
  Pathname.glob(old_pg_glob).first
rescue FormulaUnavailableError
  nil
end

odie "No #{name} #{pg_version_data}.* version installed!" unless old_bin

server_stopped = false
moved_data = false
initdb_run = false
upgraded = false

begin
  # Following instructions from:
  # https://www.postgresql.org/docs/10/static/pgupgrade.html
  ohai "Upgrading #{name} data from #{pg_version_data} to #{pg_version_installed}..."

  if /#{name}\s+started/.match?(Utils.popen_read("brew", "services", "list"))
    system "brew", "services", "stop", name
    service_stopped = true
  elsif quiet_system "#{bin}/pg_ctl", "-D", datadir, "status"
    system "#{bin}/pg_ctl", "-D", datadir, "stop"
    server_stopped = true
  end

  # Shut down old server if it is up via brew services
  if /#{old_pg_name}\s+started/.match?(Utils.popen_read("brew", "services", "list"))
    system "brew", "services", "stop", old_pg_name
  end

  # get 'lc_collate' from old DB"
  unless quiet_system "#{old_bin}/pg_ctl", "-w", "-D", datadir, "status"
    system "#{old_bin}/pg_ctl", "-w", "-D", datadir, "start"
  end

  initdb_args = []
  locale_settings = %w[
    lc_collate
    lc_ctype
    lc_messages
    lc_monetary
    lc_numeric
    lc_time
    server_encoding
  ]
  locale_settings.each do |setting|
    sql = "SELECT setting FROM pg_settings WHERE name LIKE '#{setting}';"
    value = Utils.popen_read("#{old_bin}/psql", "postgres", "-qtAX", "-U", ENV["USER"], "-c", sql).strip

    next if value.empty?

    if setting == "server_encoding"
      initdb_args += ["-E #{value}"]
    else
      initdb_args += ["--#{setting.tr!("_", "-")}=#{value}"]
    end
  end

  if quiet_system "#{old_bin}/pg_ctl", "-w", "-D", datadir, "status"
    system "#{old_bin}/pg_ctl", "-w", "-D", datadir, "stop"
  end

  ohai "Moving #{name} data from #{datadir} to #{old_datadir}..."
  FileUtils.mv datadir, old_datadir
  moved_data = true

  (var/"postgres").mkpath
  ohai "Creating database..."
  safe_system "#{bin}/initdb", *initdb_args, "#{var}/postgres"
  initdb_run = true

  ohai "Migrating and upgrading data..."
  (var/"log").cd do
    safe_system "#{bin}/pg_upgrade",
      "-r",
      "-b", old_bin,
      "-B", bin,
      "-d", old_datadir,
      "-D", datadir,
      "-j", Hardware::CPU.cores.to_s
  end
  upgraded = true

  ohai "Upgraded #{name} data from #{pg_version_data} to #{pg_version_installed}!"
  ohai "Your #{name} #{pg_version_data} data remains at #{old_datadir}"
ensure
  if upgraded
    if server_stopped
      safe_system "#{bin}/pg_ctl", "-D", datadir, "start"
    elsif service_stopped
      safe_system "brew", "services", "start", name
    end
  else
    onoe "Upgrading #{name} data from #{pg_version_data} to #{pg_version_installed} failed!"
    if initdb_run
      ohai "Removing empty #{name} initdb database..."
      FileUtils.rm_r datadir
    end
    if moved_data
      ohai "Moving #{name} data back from #{old_datadir} to #{datadir}..."
      FileUtils.mv old_datadir, datadir
    end
    if server_stopped
      system "#{bin}/pg_ctl", "-D", datadir, "start"
    elsif service_stopped
      system "brew", "services", "start", name
    end
  end
end


text:
package com.powerknights.dashboard.gui;

import javafx.beans.property.*;
import javafx.scene.AccessibleAttribute;
import javafx.scene.control.ProgressBar;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;

/**
 * <p>
 * Info about this class goes HERE!
 * </p>
 *
 * @author Bret 'Horfius' Dusseault
 * @version ${VERSION}
 */
public class TimelineProgressBar extends ProgressBar {
    private static final double DEFAULT_MIN = 0, DEFAULT_MAX = 1;

    public TimelineProgressBar(double minimum, double maximum) {
        super();
        minimumProperty().setValue(minimum);
        maximumProperty().setValue(maximum);
    }

    public TimelineProgressBar(double minimum, double maximum, double progress) {
        super(progress);
        minimumProperty().setValue(minimum);
        maximumProperty().setValue(maximum);
        setCurrent((getMaximum() - getMinimum()) * progress + getMinimum());

        this.addEventHandler(MouseEvent.ANY, event -> {
            if(event.getButton() == MouseButton.PRIMARY) {
                if (event.getEventType() == MouseEvent.MOUSE_CLICKED || event.getEventType() == MouseEvent.MOUSE_DRAGGED
                        || event.getEventType() == MouseEvent.MOUSE_RELEASED) {
                    System.out.println(event.getSceneX() + "\t" + TimelineProgressBar.this.getWidth());
                    setCurrent(event.getSceneX() / TimelineProgressBar.this.getWidth());
                }
            }
        });
    }

    /**
     *
     * Value properties and methods
     *
     */

    /**
     * Minimum value of progress
     */
    private DoubleProperty minimum;

    /**
     * Maximum value of progress
     */
    private DoubleProperty maximum;

    /**
     * Current value in between minimum and maximum
     */
    private DoubleProperty current;

    public final DoubleProperty minimumProperty(){
        if(minimum == null){
            minimum = new DoublePropertyBase(DEFAULT_MIN) {
                @Override
                public Object getBean() {
                    return TimelineProgressBar.this;
                }

                @Override
                public String getName() {
                    return "minimum";
                }

                @Override
                protected void invalidated() {
                    if(getValue() > getMaximum()) setMinimum(getMaximum());
                    if(getCurrent() < getValue()) setCurrent(getValue());
                }
            };
        }

        return minimum;
    }

    public final DoubleProperty maximumProperty(){
        if(maximum == null){
            maximum = new DoublePropertyBase(DEFAULT_MAX) {
                @Override
                public Object getBean() {
                    return TimelineProgressBar.this;
                }

                @Override
                public String getName() {
                    return "maximum";
                }

                @Override
                protected void invalidated() {
                    if(getValue() < getMinimum()) setMaximum(getMinimum());
                    if(getCurrent() > getValue()) setCurrent(getValue());
                }
            };
        }

        return maximum;
    }

    public final DoubleProperty currentProperty(){
        if(current == null){
            current = new DoublePropertyBase() {
                @Override
                public Object getBean() {
                    return TimelineProgressBar.this;
                }

                @Override
                public String getName() {
                    return "current";
                }

                @Override
                protected void invalidated() {
                    if(getValue() < getMinimum()) setCurrent(getMinimum());
                    else if(getValue() > getMaximum()) setCurrent(getMaximum());

                    calculateCurrent();
                }
            };
        }

        return current;
    }

    public final double getCurrent(){
        return current == null ? getMinimum() : current.getValue();
    }

    public final double getMinimum(){
        return minimum == null ? DEFAULT_MIN : minimum.getValue();
    }

    public final double getMaximum(){
        return maximum == null ? DEFAULT_MAX : maximum.getValue();
    }

    public final void setCurrent(double value){
        current.setValue(value);
    }

    public final void setMinimum(double value){
        minimum.setValue(value);
    }

    public final void setMaximum(double value){
        maximum.setValue(value);
    }

    private final void calculateCurrent(){
        setProgress((getCurrent() - getMinimum()) / (getMaximum() - getMinimum()));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters) {
        switch (attribute){
            case MAX_VALUE:
                return getMaximum();
            case MIN_VALUE:
                return getMinimum();
            case VALUE:
                return getCurrent();
            default:
                return super.queryAccessibleAttribute(attribute, parameters);
        }
    }

}


text:
use libc::{c_int, c_char};
use nodes::AtNode;
use imath::bbox::Box3f;

pub enum AtNodeIterator {}

#[link(name="ai")]
extern {
    pub fn AiUniverseGetOptions() -> *mut AtNode;
    pub fn AiUniverseGetCamera() -> *mut AtNode;
    pub fn AiUniverseGetSceneBounds() -> Box3f;

    pub fn AiUniverseGetNodeIterator(mask: c_int) -> *mut AtNodeIterator;
    pub fn AiNodeIteratorDestroy(it: *mut AtNodeIterator);
    pub fn AiNodeIteratorGetNext(it: *mut AtNodeIterator) -> *mut AtNode;
    pub fn AiNodeIteratorFinished(it: *mut AtNodeIterator) -> c_int;

}


text:
FactoryGirl.define do
  factory :criminal_history do

  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#00000000"/>
<stroke android:width="0.5dp" android:color="#000000" />
<corners android:radius="200dp"/>
</shape>


text:
using System;
using System.ComponentModel.Composition;
using System.Threading.Tasks;
using OpenWeatherMap;
using Xunit;

namespace OpenWeatherMapSpecs.Specs
{
    [Export]
    public sealed class TheWeatherByCityIDActions
    {
        [Import]
        public OpenWeatherMapService OpenWeatherMapService { get; set; }

        public string CityID { get; set; }

        public OpenWeatherMapForecast Forecast { get; private set; }

        public void Set(string cityId)
        {
            if (cityId == null)
            {
                throw new ArgumentNullException(nameof(cityId));
            }

            CityID = cityId;
        }

        public async Task I_have_asked_the_forecast()
        {
            Forecast = await OpenWeatherMapService.GetWeatherForecastAsync(CityID).ConfigureAwait(false);
            Assert.NotNull(Forecast);
        }

        public void It_should_contain_the_city_id()
        {
            Assert.Equal(CityID, Forecast.Id);
        }
    }
}