text:
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Linq;
//using mattmc3.dotmore.Text;
using mattmc3.dotmore.Diagnostics;
using mattmc3.dotmore.Extensions;

namespace mattmc3.dotmore.Collections.Generic {

	/// <summary>
	/// A dictionary object that allows rapid hash lookups using keys, but also
	/// maintains the key insertion order so that values can be retrieved by
	/// key index.
	/// </summary>
	/// <remarks>
	/// Similar to the way a DataColumn is indexed by column position and by column name, this
	/// advanced dictionary construct allows for a very natural and robust handling of indexed
	/// structured data.
	/// </remarks>
	[DebuggerDisplay("Count = {Count}"), DebuggerTypeProxy(typeof(OrderedDictionaryDebugView))]
	public class OrderedDictionary<TKey, TValue> : IOrderedDictionary<TKey, TValue> {

		#region Fields/Properties

		private KeyedCollection2<TKey, KeyValuePair<TKey, TValue>> _keyedCollection;

		/// <summary>
		/// Gets or sets the value associated with the specified key.
		/// </summary>
		/// <param name="key">The key associated with the value to get or set.</param>
		public TValue this[TKey key] {
			get {
				return GetValue(key);
			}
			set {
				SetValue(key, value);
			}
		}

		/// <summary>
		/// Gets or sets the value at the specified index.
		/// </summary>
		/// <param name="index">The index of the value to get or set.</param>
		public TValue this[int index] {
			get {
				return GetItem(index).Value;
			}
			set {
				SetItem(index, value);
			}
		}

		/// <summary>
		/// Gets the number of items in the dictionary
		/// </summary>
		public int Count {
			get { return _keyedCollection.Count; }
		}

		/// <summary>
		/// Gets all the keys in the ordered dictionary in their proper order.
		/// </summary>
		public ICollection<TKey> Keys {
			get {
				return _keyedCollection.Select(x => x.Key).ToList();
			}
		}

		/// <summary>
		/// Gets all the values in the ordered dictionary in their proper order.
		/// </summary>
		public ICollection<TValue> Values {
			get {
				return _keyedCollection.Select(x => x.Value).ToList();
			}
		}

		/// <summary>
		/// Gets the key comparer for this dictionary
		/// </summary>
		public IEqualityComparer<TKey> Comparer {
			get;
			private set;
		}

		#endregion

		#region Constructors

		public OrderedDictionary() {
			Initialize();
		}

		public OrderedDictionary(IEqualityComparer<TKey> comparer) {
			Initialize(comparer);
		}

		public OrderedDictionary(IOrderedDictionary<TKey, TValue> dictionary) {
			Initialize();
			foreach (KeyValuePair<TKey, TValue> pair in dictionary) {
				_keyedCollection.Add(pair);
			}
		}

		public OrderedDictionary(IOrderedDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) {
			Initialize(comparer);
			foreach (KeyValuePair<TKey, TValue> pair in dictionary) {
				_keyedCollection.Add(pair);
			}
		}

		public OrderedDictionary(IEnumerable<KeyValuePair<TKey, TValue>> items) {
			Initialize();
			foreach (KeyValuePair<TKey, TValue> pair in items) {
				_keyedCollection.Add(pair);
			}
		}

		public OrderedDictionary(IEnumerable<KeyValuePair<TKey, TValue>> items, IEqualityComparer<TKey> comparer) {
			Initialize(comparer);
			foreach (KeyValuePair<TKey, TValue> pair in items) {
				_keyedCollection.Add(pair);
			}
		}

		#endregion

		#region Methods

		private void Initialize(IEqualityComparer<TKey> comparer = null) {
			this.Comparer = comparer;
			if (comparer != null) {
				_keyedCollection = new KeyedCollection2<TKey, KeyValuePair<TKey, TValue>>(x => x.Key, comparer);
			}
			else {
				_keyedCollection = new KeyedCollection2<TKey, KeyValuePair<TKey, TValue>>(x => x.Key);
			}
		}

		/// <summary>
		/// Adds the specified key and value to the dictionary.
		/// </summary>
		/// <param name="key">The key of the element to add.</param>
		/// <param name="value">The value of the element to add.  The value can be null for reference types.</param>
		public void Add(TKey key, TValue value) {
			_keyedCollection.Add(new KeyValuePair<TKey, TValue>(key, value));
		}

		/// <summary>
		/// Removes all keys and values from this object.
		/// </summary>
		public void Clear() {
			_keyedCollection.Clear();
		}

		/// <summary>
		/// Inserts a new key-value pair at the index specified.
		/// </summary>
		/// <param name="index">The insertion index.  This value must be between 0 and the count of items in this object.</param>
		/// <param name="key">A unique key for the element to add</param>
		/// <param name="value">The value of the element to add.  Can be null for reference types.</param>
		public void Insert(int index, TKey key, TValue value) {
			_keyedCollection.Insert(index, new KeyValuePair<TKey, TValue>(key, value));
		}

		/// <summary>
		/// Gets the index of the key specified.
		/// </summary>
		/// <param name="key">The key whose index will be located</param>
		/// <returns>Returns the index of the key specified if found.  Returns -1 if the key could not be located.</returns>
		public int IndexOf(TKey key) {
			if (_keyedCollection.Contains(key)) {
				return _keyedCollection.IndexOf(_keyedCollection[key]);
			}
			else {
				return -1;
			}
		}

		/// <summary>
		/// Determines whether this object contains the specified value.
		/// </summary>
		/// <param name="value">The value to locate in this object.</param>
		/// <returns>True if the value is found.  False otherwise.</returns>
		public bool ContainsValue(TValue value) {
			return this.Values.Contains(value);
		}

		/// <summary>
		/// Determines whether this object contains the specified value.
		/// </summary>
		/// <param name="value">The value to locate in this object.</param>
		/// <param name="comparer">The equality comparer used to locate the specified value in this object.</param>
		/// <returns>True if the value is found.  False otherwise.</returns>
		public bool ContainsValue(TValue value, IEqualityComparer<TValue> comparer) {
			return this.Values.Contains(value, comparer);
		}

		/// <summary>
		/// Determines whether this object contains the specified key.
		/// </summary>
		/// <param name="key">The key to locate in this object.</param>
		/// <returns>True if the key is found.  False otherwise.</returns>
		public bool ContainsKey(TKey key) {
			return _keyedCollection.Contains(key);
		}

		/// <summary>
		/// Returns the KeyValuePair at the index specified.
		/// </summary>
		/// <param name="index">The index of the KeyValuePair desired</param>
		/// <exception cref="ArgumentOutOfRangeException">
		/// Thrown when the index specified does not refer to a KeyValuePair in this object
		/// </exception>
		public KeyValuePair<TKey, TValue> GetItem(int index) {
			if (index < 0 || index >= _keyedCollection.Count) {
				throw new ArgumentException("The index was outside the bounds of the dictionary: {0}".FormatWith(index));
			}
			return _keyedCollection[index];
		}

		/// <summary>
		/// Sets the value at the index specified.
		/// </summary>
		/// <param name="index">The index of the value desired</param>
		/// <param name="value">The value to set</param>
		/// <exception cref="ArgumentOutOfRangeException">
		/// Thrown when the index specified does not refer to a KeyValuePair in this object
		/// </exception>
		public void SetItem(int index, TValue value) {
			if (index < 0 || index >= _keyedCollection.Count) {
				throw new ArgumentException("The index is outside the bounds of the dictionary: {0}".FormatWith(index));
			}
			var kvp = new KeyValuePair<TKey, TValue>(_keyedCollection[index].Key, value);
			_keyedCollection[index] = kvp;
		}

		/// <summary>
		/// Returns an enumerator that iterates through all the KeyValuePairs in this object.
		/// </summary>
		public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() {
			return _keyedCollection.GetEnumerator();
		}

		/// <summary>
		/// Removes the key-value pair for the specified key.
		/// </summary>
		/// <param name="key">The key to remove from the dictionary.</param>
		/// <returns>True if the item specified existed and the removal was successful.  False otherwise.</returns>
		public bool Remove(TKey key) {
			return _keyedCollection.Remove(key);
		}

		/// <summary>
		/// Removes the key-value pair at the specified index.
		/// </summary>
		/// <param name="index">The index of the key-value pair to remove from the dictionary.</param>
		public void RemoveAt(int index) {
			if (index < 0 || index >= _keyedCollection.Count) {
				throw new ArgumentException("The index was outside the bounds of the dictionary: {0}".FormatWith(index));
			}
			_keyedCollection.RemoveAt(index);
		}

		/// <summary>
		/// Gets the value associated with the specified key.
		/// </summary>
		/// <param name="key">The key associated with the value to get.</param>
		public TValue GetValue(TKey key) {
			if (_keyedCollection.Contains(key) == false) {
				throw new ArgumentException("The given key is not present in the dictionary: {0}".FormatWith(key));
			}
			var kvp = _keyedCollection[key];
			return kvp.Value;
		}

		/// <summary>
		/// Sets the value associated with the specified key.
		/// </summary>
		/// <param name="key">The key associated with the value to set.</param>
		/// <param name="value">The the value to set.</param>
		public void SetValue(TKey key, TValue value) {
			var kvp = new KeyValuePair<TKey, TValue>(key, value);
			var idx = IndexOf(key);
			if (idx > -1) {
				_keyedCollection[idx] = kvp;
			}
			else {
				_keyedCollection.Add(kvp);
			}
		}

		/// <summary>
		/// Tries to get the value associated with the specified key.
		/// </summary>
		/// <param name="key">The key of the desired element.</param>
		/// <param name="value">
		/// When this method returns, contains the value associated with the specified key if
		/// that key was found.  Otherwise it will contain the default value for parameter's type.
		/// This parameter should be provided uninitialized.
		/// </param>
		/// <returns>True if the value was found.  False otherwise.</returns>
		/// <remarks></remarks>
		public bool TryGetValue(TKey key, out TValue value) {
			if (_keyedCollection.Contains(key)) {
				value = _keyedCollection[key].Value;
				return true;
			}
			else {
				value = default(TValue);
				return false;
			}
		}

		#endregion

		#region Sorting
		public void SortKeys() {
			_keyedCollection.SortByKeys();
		}

		public void SortKeys(IComparer<TKey> comparer) {
			_keyedCollection.SortByKeys(comparer);
		}

		public void SortKeys(Comparison<TKey> comparison) {
			_keyedCollection.SortByKeys(comparison);
		}

		public void SortValues() {
			var comparer = Comparer<TValue>.Default;
			SortValues(comparer);
		}

		public void SortValues(IComparer<TValue> comparer) {
			_keyedCollection.Sort((x,y) => comparer.Compare(x.Value, y.Value));
		}

		public void SortValues(Comparison<TValue> comparison) {
			_keyedCollection.Sort((x, y) => comparison(x.Value, y.Value));
		}
		#endregion

		#region IDictionary<TKey, TValue>

		void IDictionary<TKey, TValue>.Add(TKey key, TValue value) {
			Add(key, value);
		}

		bool IDictionary<TKey, TValue>.ContainsKey(TKey key) {
			return ContainsKey(key);
		}

		ICollection<TKey> IDictionary<TKey, TValue>.Keys {
			get { return Keys; }
		}

		bool IDictionary<TKey, TValue>.Remove(TKey key) {
			return Remove(key);
		}

		bool IDictionary<TKey, TValue>.TryGetValue(TKey key, out TValue value) {
			return TryGetValue(key, out value);
		}

		ICollection<TValue> IDictionary<TKey, TValue>.Values {
			get { return Values; }
		}

		TValue IDictionary<TKey, TValue>.this[TKey key] {
			get {
				return this[key];
			}
			set {
				this[key] = value;
			}
		}

		#endregion

		#region ICollection<KeyValuePair<TKey, TValue>>

		void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) {
			_keyedCollection.Add(item);
		}

		void ICollection<KeyValuePair<TKey, TValue>>.Clear() {
			_keyedCollection.Clear();
		}

		bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) {
			return _keyedCollection.Contains(item);
		}

		void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) {
			_keyedCollection.CopyTo(array, arrayIndex);
		}

		int ICollection<KeyValuePair<TKey, TValue>>.Count {
			get { return _keyedCollection.Count; }
		}

		bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly {
			get { return false; }
		}

		bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) {
			return _keyedCollection.Remove(item);
		}

		#endregion

		#region IEnumerable<KeyValuePair<TKey, TValue>>

		IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() {
			return GetEnumerator();
		}

		#endregion

		#region IEnumerable

		IEnumerator IEnumerable.GetEnumerator() {
			return GetEnumerator();
		}

		#endregion

		#region IOrderedDictionary

		IDictionaryEnumerator IOrderedDictionary.GetEnumerator() {
			return new DictionaryEnumerator<TKey, TValue>(this);
		}

		void IOrderedDictionary.Insert(int index, object key, object value) {
			Insert(index, (TKey)key, (TValue)value);
		}

		void IOrderedDictionary.RemoveAt(int index) {
			RemoveAt(index);
		}

		object IOrderedDictionary.this[int index] {
			get {
				return this[index];
			}
			set {
				this[index] = (TValue)value;
			}
		}

		#endregion

		#region IDictionary

		void IDictionary.Add(object key, object value) {
			Add((TKey)key, (TValue)value);
		}

		void IDictionary.Clear() {
			Clear();
		}

		bool IDictionary.Contains(object key) {
			return _keyedCollection.Contains((TKey)key);
		}

		IDictionaryEnumerator IDictionary.GetEnumerator() {
			return new DictionaryEnumerator<TKey, TValue>(this);
		}

		bool IDictionary.IsFixedSize {
			get { return false; }
		}

		bool IDictionary.IsReadOnly {
			get { return false; }
		}

		ICollection IDictionary.Keys {
			get { return (ICollection)this.Keys; }
		}

		void IDictionary.Remove(object key) {
			Remove((TKey)key);
		}

		ICollection IDictionary.Values {
			get { return (ICollection)this.Values; }
		}

		object IDictionary.this[object key] {
			get {
				return this[(TKey)key];
			}
			set {
				this[(TKey)key] = (TValue)value;
			}
		}

		#endregion

		#region ICollection

		void ICollection.CopyTo(Array array, int index) {
			((ICollection)_keyedCollection).CopyTo(array, index);
		}

		int ICollection.Count {
			get { return ((ICollection)_keyedCollection).Count; }
		}

		bool ICollection.IsSynchronized {
			get { return ((ICollection)_keyedCollection).IsSynchronized; }
		}

		object ICollection.SyncRoot {
			get { return ((ICollection)_keyedCollection).SyncRoot; }
		}

		#endregion
	}
}


text:
@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [NSThread sleepForTimeInterval:2.0];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
}

- (void)applicationWillTerminate:(UIApplication *)application {
}

@end

redpajama_set_name: RedPajamaGithub


text:
import { PrismaClient } from '@prisma/client'

// This file will not be executed, just compiled to check if the typings are valid
async function main() {
  const prisma = new PrismaClient({
    datasources: {
      db: {
        url: 'file:dev.db',
      },
    },
  })

  await prisma.user.findMany({
    distinct: ['id', 'email', 'age', 'followerCount', 'name'],
  })
}

main().catch((e) => {
  console.error(e)
})


text:
using Machine.Specifications;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MFlow.Core.Tests.for_FluentValidation
{
    public class when_calling_is_alpha_with_a_value_that_does_not_satisfy_a_custom_alpha_validator : given.a_fluent_user_validator_with_custom_implementation_set_to_replace
    {

        Because of = () =>
        {
            user.Password = "doesnotmatchcustomalphavalidator";
            validator.Check(u => u.Password).IsAlpha();
        };

        It should_not_be_satisfied = () => { validator.Satisfied().ShouldBeFalse(); };
        It should_return_the_correct_validation_message = () => { validator.Validate().First().Condition.Message.ShouldEqual("Password should only contain letters"); };

    }
}


text:
namespace BusTicketsSystem.Services.Contracts
{
    using Models;

    public interface ITicketService
    {
        Ticket Create(int customerId, int tripId, decimal price, string seat);
    }
}


text:
/***************************************************************************
 *  DatabaseConfigurationClient.cs
 *
 *  Written by Scott Peterson <lunchtimemama@gmail.com>
 ****************************************************************************/

/*  THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 *  DEALINGS IN THE SOFTWARE.
 */

using System;
using System.Data;

using Hyena.Data.Sqlite;

using Banshee.Database;
using Banshee.ServiceStack;

namespace Banshee.Configuration
{
    public class DatabaseConfigurationClient : IConfigurationClient
    {
        public static DatabaseConfigurationClient Client {
            get { return ServiceManager.DbConnection.Configuration; }
        }

        private readonly BansheeDbConnection connection;
        private readonly HyenaSqliteCommand select_value_command;
        private readonly HyenaSqliteCommand select_id_command;
        private readonly HyenaSqliteCommand insert_command;
        private readonly HyenaSqliteCommand update_command;

        public DatabaseConfigurationClient(BansheeDbConnection connection)
        {
            this.connection = connection;

            select_value_command = new HyenaSqliteCommand (String.Format (
                "SELECT Value FROM {0} WHERE Key=?", TableName));

            select_id_command = new HyenaSqliteCommand (String.Format (
                "SELECT EntryID FROM {0} WHERE Key=?", TableName));

            insert_command = new HyenaSqliteCommand (String.Format (
                "INSERT INTO {0} (EntryID, Key, Value) VALUES (NULL, ?, ?)", TableName));

            update_command = new HyenaSqliteCommand (String.Format (
                "UPDATE {0} SET Value=? WHERE Key=?", TableName));
        }

        public T Get <T> (SchemaEntry<T> entry)
        {
            return Get (entry.Namespace, entry.Key, entry.DefaultValue);
        }

        public T Get <T> (SchemaEntry<T> entry, T fallback)
        {
            return Get (entry.Namespace, entry.Key, fallback);
        }

        public T Get <T> (string key, T fallback)
        {
            return Get (null, key, fallback);
        }

        public T Get <T> (string namespce, string key, T fallback)
        {
            using (IDataReader reader = Get (namespce, key)) {
                if (reader.Read ()) {
                    return (T) Convert.ChangeType (reader.GetString (0), typeof (T));
                } else {
                    return fallback;
                }
            }
        }

        private IDataReader Get (string namespce, string key)
        {
            return connection.Query (select_value_command,
                Banshee.Configuration.MemoryConfigurationClient.MakeKey (namespce, key));
        }

        public void Set <T> (SchemaEntry<T> entry, T value)
        {
            Set (entry.Namespace, entry.Key, value);
        }

        public void Set <T> (string key, T value)
        {
            Set (null, key, value);
        }

        public void Set <T> (string namespce, string key, T value)
        {
            string fq_key = Banshee.Configuration.MemoryConfigurationClient.MakeKey (namespce, key);
            if (connection.Query<int> (select_id_command, fq_key) > 0) {
                connection.Execute (update_command, value.ToString (), fq_key);
            } else {
                connection.Execute (insert_command, fq_key, value.ToString ());
            }
        }

        protected virtual string TableName {
            get { return "CoreConfiguration"; }
        }
    }
}


text:
class FullscreenRenderTargetPool {
  constructor() {
    this.renderTargets = [];
    this.used = 0;
  }

  _createFullscreenRenderTarget() {
    const [x, y] = PROJECT.aspectRatio.split(':').map(n => +n);
    const renderTarget = new THREE.WebGLRenderTarget(x * GU, y * GU, {
      minFilter: THREE.LinearFilter,
      magFilter: THREE.LinearFilter,
      format: THREE.RGBAFormat,
    });
    return renderTarget;
  }

  getFullscreenRenderTarget() {
    let renderTarget = this.renderTargets[this.used];
    if(!renderTarget) {
      renderTarget = this._createFullscreenRenderTarget();
      this.renderTargets[this.used] = renderTarget;
    }
    this.used++;
    renderTarget.texture.repeat.set(1, 1);
    renderTarget.texture.offset.set(0, 0);
    return renderTarget;
  }

  withdrawFullscreenRenderTargets() {
    this.used = 0;
  }

  resize() {
    const [x, y] = PROJECT.aspectRatio.split(':').map(n => +n);
    for(let i = 0; i < this.renderTargets.length; i++) {
      this.renderTargets[i].setSize(x * GU, y * GU);
    }
  }
}

module.exports = FullscreenRenderTargetPool;


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

namespace Azure.ResourceManager.DnsResolver.Models
{
    /// <summary> Describes an inbound endpoint for a DNS resolver for PATCH operation. </summary>
    public partial class DnsResolverInboundEndpointPatch
    {
        /// <summary> Initializes a new instance of DnsResolverInboundEndpointPatch. </summary>
        public DnsResolverInboundEndpointPatch()
        {
            Tags = new ChangeTrackingDictionary<string, string>();
        }

        /// <summary> Tags for inbound endpoint. </summary>
        public IDictionary<string, string> Tags { get; }
    }
}


text:
Set-StrictMode -Version latest
$ErrorAction = "Stop"

Uninstall-ChocolateyEnvironmentVariable `
    -VariableName 'GIT_SSH' -VariableType 'Machine'


text:
#ifndef _RendererDispatcherTest_H
#define _RendererDispatcherTest_H

#include "TestCase.h"

class RendererDispatcherTest : public testframework::TestCase
{
public:
	//--- constructors

	//!TestCase constructor
	//! \param name name of the test
	RendererDispatcherTest(TString tstrName);

	//!destroys the test case
	~RendererDispatcherTest();

	//--- public api

	//!builds up a suite of testcases for this test
	static Test *suite ();

	//!test the find of rendered service names
	void FindServiceNameTest();
};

#endif


text:
<?php

namespace Redsys\Api;

final class Terminal implements ApiInterface
{
    const MAX_LENGTH = 3;

    private $value;

    public function __construct($value)
    {
        $value = str_replace(" ", "", trim($value));
        $length = strlen($value);
        if (self::MAX_LENGTH < $length) {
            throw new \LengthException(
                sprintf('Max terminal value length is %d, but "%s" code is %d', self::MAX_LENGTH, $value, $length)
            );
        }
        $this->value = (string)$value;
    }

    public function getValue()
    {
        return $this->value;
    }

    /**
     * @inheritdoc
     */
    public function __toString()
    {
        return $this->getValue();
    }
}


text:
import * as React from 'react';
import Box from '@mui/joy/Box';
import Modal from '@mui/joy/Modal';
import ModalDialog from '@mui/joy/ModalDialog';
import Typography from '@mui/joy/Typography';

export default function ServerModal() {
  const rootRef = React.useRef(null);

  return (
    <Box
      sx={{
        height: 240,
        flexGrow: 1,
        minWidth: 300,
        transform: 'translateZ(0)',
        // The position fixed scoping doesn't work in IE11.
        // Disable this demo to preserve the others.
        '@media all and (-ms-high-contrast: none)': {
          display: 'none',
        },
      }}
      ref={rootRef}
    >
      <Modal
        disablePortal
        disableEnforceFocus
        disableAutoFocus
        open
        container={() => rootRef.current}
      >
        <ModalDialog
          aria-labelledby="server-modal-title"
          aria-describedby="server-modal-description"
          layout="center"
        >
          <Typography
            id="server-modal-title"
            component="h2"
            level="inherit"
            fontSize="1.25em"
            mb="0.25em"
          >
            Server-side modal
          </Typography>
          <Typography id="server-modal-description" textColor="text.tertiary">
            If you disable JavaScript, you will still see me.
          </Typography>
        </ModalDialog>
      </Modal>
    </Box>
  );
}


text:
<?php
/**
 * Sastrawi (https://github.com/sastrawi/sastrawi)
 *
 * @link      http://github.com/sastrawi/sastrawi for the canonical source repository
 * @license   https://github.com/sastrawi/sastrawi/blob/master/LICENSE The MIT License (MIT)
 */

namespace Sastrawi\Morphology\Disambiguator;

/**
 * Disambiguate Prefix Rule 40b (CC infix rules)
 * Rule 40b : CinV -> CV
 */
class DisambiguatorPrefixRule40b implements DisambiguatorInterface
{
    /**
     * Disambiguate Prefix Rule 40b (CC infix rules)
     * Rule 40b : CinV -> CV
     */
    public function disambiguate($word)
    {
        $contains = preg_match('/^([bcdfghjklmnpqrstvwxyz])in([aiueo])(.*)$/', $word, $matches);

        if ($contains === 1) {
            return $matches[1] . $matches[2] . $matches[3];
        }
    }
}


text:
package org.opencb.opencga.analysis.variant.stats;

import org.opencb.biodata.models.variant.Variant;
import org.opencb.biodata.models.variant.metadata.SampleVariantStats;
import org.opencb.biodata.models.variant.metadata.VariantMetadata;
import org.opencb.biodata.tools.variant.stats.SampleVariantStatsCalculator;
import org.opencb.commons.ProgressLogger;
import org.opencb.commons.datastore.core.DataResult;
import org.opencb.commons.datastore.core.Query;
import org.opencb.commons.datastore.core.QueryOptions;
import org.opencb.commons.run.ParallelTaskRunner;
import org.opencb.opencga.analysis.StorageToolExecutor;
import org.opencb.opencga.analysis.variant.manager.VariantStorageManager;
import org.opencb.opencga.core.exceptions.ToolException;
import org.opencb.opencga.core.exceptions.ToolExecutorException;
import org.opencb.opencga.core.tools.annotations.ToolExecutor;
import org.opencb.opencga.core.tools.variant.SampleVariantStatsAnalysisExecutor;
import org.opencb.opencga.storage.core.variant.adaptors.VariantQueryParam;
import org.opencb.opencga.storage.core.variant.adaptors.iterators.VariantDBIterator;
import org.opencb.opencga.storage.core.variant.io.db.VariantDBReader;

import java.util.List;

@ToolExecutor(id="opencga-local", tool = SampleVariantStatsAnalysis.ID,
        framework = ToolExecutor.Framework.LOCAL,
        source = ToolExecutor.Source.STORAGE)
public class SampleVariantStatsLocalAnalysisExecutor extends SampleVariantStatsAnalysisExecutor implements StorageToolExecutor {

    @Override
    public int getDefaultBatchSize() {
        return 5000;
    }
    @Override
    public int getMaxBatchSize() {
        return 10000;
    }

    @Override
    public void run() throws ToolException {

        VariantStorageManager variantStorageManager = getVariantStorageManager();

        List<String> sampleNames = getSampleNames();

        Query query = new Query(getVariantQuery())
                .append(VariantQueryParam.STUDY.key(), getStudy())
                .append(VariantQueryParam.INCLUDE_SAMPLE.key(), sampleNames);

        List<SampleVariantStats> stats;
        try {
            DataResult<VariantMetadata> metadata = variantStorageManager.getMetadata(query, new QueryOptions(), getToken());
            SampleVariantStatsCalculator calculator = new SampleVariantStatsCalculator(metadata.first().getStudies().get(0));

            ProgressLogger progressLogger = new ProgressLogger("Variants processed:");
            VariantDBIterator iterator = variantStorageManager.iterator(query, new QueryOptions(), getToken());

            ParallelTaskRunner.Config config = ParallelTaskRunner.Config.builder().setNumTasks(1).setBatchSize(10).build();

            ParallelTaskRunner<Variant, Variant> ptr = new ParallelTaskRunner<>(
                    new VariantDBReader(iterator),
                    calculator.then((List<Variant> b) -> {
                        progressLogger.increment(b.size());
                        return b;
                    }),
                    null,
                    config);

            ptr.run();

            stats = calculator.getSampleVariantStats();
        } catch (Exception e) {
            throw new ToolExecutorException(e);
        }

        writeStatsToFile(stats);
    }
}


text:
package util
package security

import play.api._
import play.api.Configuration
import models.User
import org.specs2.mutable._
import java.io.File

object AuthenticationProviderSpec extends Specification with _root_.test.ResourceFinder {

  "Authentication Providers" should {
    "work with default authentication" >> {
      val provider = AuthenticationProvider.Default
      provider.authenticate("blake", "admin:first") must beSome[User]
      provider.authenticate("no", "suchuser") must beNone
    }
    /*
    "work with file based auth" >> {
      val authFile = findResource("htpasswd_users")
      val configData = Map(
        "authentication.type" -> "file",
        "authentication.permissionsFile" -> "conf/permissions.yaml",
        "authentication.basic.userfile" -> authFile.getAbsolutePath
      )
      val config = Configuration.from(configData)
      _root_.util.config.AppConfig.globalConfig = Some(config)
      val provider = AuthenticationProvider.get("basic")

      val users = Seq(
        ("blake", "password123", "engineering"),
        ("testuser", "FizzBuzzAbc", "ny,also")
      )

      users.foreach { case(username,password,roles) =>
        val user = provider.authenticate(username, password)
        user must beSome[User]
        user.get.username mustEqual username
        user.get.password mustNotEqual password
        user.get.roles mustEqual roles
      }
      provider.authenticate("blake", "abbazabba") must beNone
    }
    "work with IPA authentication" >> {
      val configData = Map(
        "authentication.type" -> "ipa",
        "authentication.host" -> "192.168.130.53",
        "authentication.searchbase" -> "cn=accounts,dc=example,dc=com",
        "authentication.usersub" -> "cn=users",
        "authentication.groupsub" -> "cn=groups"
      )
      val config = Configuration.from(configData)
      val authConfig = config.getConfig("authentication")
      authConfig must beSome
      val provider = AuthenticationProvider.get("ipa", authConfig.get)
      provider must haveClass[IpaAuthenticationProvider]
      val ups = Seq(
        ("test_eng", "test_eng-franklin595%", 654800006, Seq("infra","ipausers")),
        ("test_noeng", "test_noeng-franklin595%", 654800007, Seq("ipausers")))
      ups.foreach { case(username,password,id,roles) =>
        val user = provider.authenticate(username, password)
        user must beSome[User]
        user.get.username mustEqual username
        user.get.password mustNotEqual password
        user.get.id mustEqual id
        user.get.roles must containAllOf(roles)
      }
      provider.authenticate("fizz", "buzz") must beNone
    } // with IPA authentication
    "work with LDAP authentication" >> {
      val configData = Map(
        "authentication.type" -> "ldap",
        "authentication.host" -> "192.168.130.7",
        "authentication.searchbase" -> "dc=corp,dc=tumblr,dc=net",
        "authentication.usersub" -> "cn=users",
        "authentication.groupsub" -> "cn=groups"
      )
      val config = Configuration.from(configData)
      val authConfig = config.getConfig("authentication")
      authConfig must beSome
      val provider = AuthenticationProvider.get("ldap", authConfig.get)
      provider must haveClass[LdapAuthenticationProvider]
      val ups = Seq(
        ("test_eng", "test_eng-franklin595%", 1093, Seq("engineering")),
        ("test_noeng", "test_noeng-franklin595%", 1094, Seq("ny")))
      ups.foreach { case(username,password,id,roles) =>
        val user = provider.authenticate(username, password)
        user must beSome[User]
        user.get.username mustEqual username
        user.get.password mustNotEqual password
        user.get.id mustEqual id
        user.get.roles must containAllOf(roles)
      }
      provider.authenticate("fizz", "buzz") must beNone
    } // with LDAP authentication
    */
  }
}


text:
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using System.CodeDom.Compiler;

namespace AppCampus.Infrastructure.Models.Mapping
{
	[GeneratedCode("EntityFrameworkCodeGeneration", "6.1.1")]
    public class AnnouncementTableMap : EntityTypeConfiguration<AnnouncementTable>
    {
        public AnnouncementTableMap()
        {
            // Primary Key
            this.HasKey(t => t.Id);

            // Properties
            this.Property(t => t.Message)
                .IsRequired()
                .HasMaxLength(256);

            this.Property(t => t.Severity)
                .IsRequired()
                .HasMaxLength(16);

            this.Property(t => t.Name)
                .IsRequired()
                .HasMaxLength(64);

            // Relationships
            this.HasRequired(t => t.Company)
                .WithMany(t => t.Announcements)
                .HasForeignKey(d => d.CompanyId);

        }
    }
}


text:
package com.feedly.cassandra.dao;

import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;

import me.prettyprint.cassandra.model.IndexedSlicesQuery;
import me.prettyprint.hector.api.beans.AbstractComposite.ComponentEquality;
import me.prettyprint.hector.api.beans.OrderedRows;
import me.prettyprint.hector.api.beans.Row;
import me.prettyprint.hector.api.factory.HFactory;

import com.feedly.cassandra.EConsistencyLevel;
import com.feedly.cassandra.IKeyspaceFactory;
import com.feedly.cassandra.entity.EntityMetadata;
import com.feedly.cassandra.entity.IndexMetadata;
import com.feedly.cassandra.entity.SimplePropertyMetadata;

/*
 * used to fetch data using native cassandra indexes. Lazy loading is supported.
 */
class HashIndexFindHelper<K, V> extends LoadHelper<K, V>
{
    private OperationStatistics _indexStats;

    HashIndexFindHelper(EntityMetadata<V> meta, IKeyspaceFactory factory, int statsSize)
    {
        super(meta, factory, statsSize);
        _indexStats = new OperationStatistics(statsSize);
    }

    private V uniqueValue(Collection<V> values)
    {
        if(values == null || values.isEmpty())
            return null;

        if(values.size() > 1)
            throw new IllegalStateException("non-unique value");

        return values.iterator().next();
    }

    public OperationStatistics indexStats()
    {
        return _indexStats;
    }

    public V find(V template, FindOptions options, IndexMetadata index)
    {
        return uniqueValue(mfind(template, options, index));
    }

    public Collection<V> mfind(V template, FindOptions options, IndexMetadata index)
    {
        Collection<V> values = null;
        switch(options.getColumnFilterStrategy())
        {
            case UNFILTERED:
                values = bulkFindByIndexPartial(template, null, null, null, null, null, options.getMaxRows(), index, options.getConsistencyLevel());
                break;

            case RANGE:
                byte[] startCol = propertyName(options.getStartColumn(), ComponentEquality.EQUAL);
                byte[] endCol = propertyName(options.getEndColumn(), ComponentEquality.GREATER_THAN_EQUAL);
                values =  bulkFindByIndexPartial(template, startCol, endCol, null, null, null, options.getMaxRows(), index, options.getConsistencyLevel());
                break;

            case INCLUDES:
                values = mfind(template, options.getIncludes(), options.getExcludes(), options.getMaxRows(), index, options.getConsistencyLevel());
                break;
        }

        _stats.incrNumOps(1);
        _indexStats.incrNumOps(1);
        return values;
    }

    private Collection<V> mfind(V template, Set<? extends Object> includes, Set<String> excludes, int maxRows, IndexMetadata index, EConsistencyLevel level)
    {
        if(includes != null && excludes != null)
            throw new IllegalArgumentException("either includes or excludes should be specified, not both");

        if(includes != null && excludes != null)
            throw new IllegalArgumentException("either includes or excludes should be specified, not both");

        List<byte[]> colNames = new ArrayList<byte[]>();
        List<byte[]> counterColNames = new ArrayList<byte[]>();
        List<CollectionRange> ranges = derivePartialColumns(colNames, counterColNames, includes, excludes);

        return bulkFindByIndexPartial(template, null, null, colNames, counterColNames, ranges, maxRows, index, level);

    }

    private Collection<V> bulkFindByIndexPartial(V template,
                                                 byte[] startBytes,
                                                 byte[] endBytes,
                                                 List<byte[]> colNames,
                                                 List<byte[]> counterColNames,
                                                 List<CollectionRange> ranges,
                                                 int maxRows,
                                                 IndexMetadata index,
                                                 EConsistencyLevel level)
    {
        SimplePropertyMetadata pm = index.getIndexedProperties().get(0); //must be exactly 1

        Object propVal = invokeGetter(pm, template);
        if(propVal == null)
            throw new IllegalArgumentException("null values not supported for hash indexes");

        IndexedSlicesQuery<byte[], byte[], byte[]> query = HFactory.createIndexedSlicesQuery(_keyspaceFactory.createKeyspace(level), SER_BYTES, SER_BYTES, SER_BYTES);
        query.setColumnFamily(_entityMeta.getFamilyName());
        query.setRowCount(CassandraDaoBase.ROW_RANGE_SIZE);
        query.addEqualsExpression(pm.getPhysicalNameBytes(), serialize(propVal, false, pm.getSerializer()));

        if(colNames != null)
            query.setColumnNames(colNames);
        else
            query.setRange(startBytes, endBytes, false, CassandraDaoBase.COL_RANGE_SIZE);

        return new LazyLoadedCollection(query,
                                        startBytes,
                                        endBytes,
                                        ranges,
                                        new EqualityValueFilter<V>(_entityMeta, template, index),
                                        counterColNames,
                                        maxRows,
                                        index,
                                        level);
    }

    @SuppressWarnings("unchecked")
    private byte[] fetchBatch(IndexedSlicesQuery<byte[],byte[],byte[]> query,
                              byte[] startRowKey,
                              byte[] startColBytes,
                              byte[] endColBytes,
                              K lastKey,
                              int maxRows,
                              List<V> values,
                              List<byte[]> counterColNames,
                              List<CollectionRange> ranges,
                              EConsistencyLevel level)
    {
        long indexStartTime = System.nanoTime();

        SimplePropertyMetadata keyMeta = _entityMeta.getKeyMetadata();
        int fetchRowCount = Math.min(maxRows, CassandraDaoBase.ROW_RANGE_SIZE);
        query.setRowCount(fetchRowCount);

        if(startRowKey != null)
            query.setStartKey(startRowKey);

        OrderedRows<byte[],byte[],byte[]> rows = query.execute().get();
        long indexEndTime = System.nanoTime();
        long startTime = indexEndTime;
        List<K> keys = new ArrayList<K>();

        K first = null, last = null;
        /*
         * the last key of the previous range and the first key of the current range may overlap
         */
        for(Row<byte[], byte[], byte[]> row : rows)
        {
            K key = (K) keyMeta.getSerializer().fromBytes(row.getKey());

            if(lastKey != null)
            {
                if(key.equals(lastKey))
                {
                    lastKey = null;
                    continue;
                }

                lastKey = null;
            }

            V value = fromColumnSlice(key, null, keyMeta, row.getKey(), null, row.getColumnSlice(), endColBytes, level);

            keys.add(key);
            values.add(value);

            if(first == null)
                first = key;

            last = key;
        }

        _logger.debug("range {} - {}", first, last);

        if(ranges != null && !values.isEmpty())
        {
            _logger.debug("adding full collections to {} values: ({})", values.size(), ranges);
            addCollectionRanges(keys, values, ranges, level);
        }

        int cnt = rows.getCount();

        byte[] lastKeyBytes = cnt == 0 ? null : rows.getList().get(cnt - 1).getKey();

        //if counters exist and must be fetched
        if(_entityMeta.hasCounterColumns() && (counterColNames == null || !counterColNames.isEmpty()))
            bulkLoadFromMultiCounterGet(keys, values, counterColNames, startColBytes, endColBytes, true, level);

        int nonNull = 0;
        for(int i = values.size() - 1; i >= 0; i--)
        {
            if(values.get(i) == null)
                values.remove(i);
            else
                nonNull++;
        }

        int size = values.size();

        _stats.addRecentTiming(System.nanoTime() - startTime);
        _indexStats.addRecentTiming(indexEndTime - indexStartTime);
        _stats.incrNumRows(size);
        _indexStats.incrNumRows(size);
        _indexStats.incrNumCassandraOps(1);

        _logger.debug("{} rows, {} values, ({} non null) fetched", new Object[] {cnt, size, nonNull});

        return lastKeyBytes;
    }

    private class LazyLoadedIterator implements Iterator<V>
    {
        private final LazyLoadedCollection _parent;
        private final IndexedSlicesQuery<byte[],byte[],byte[]> _query;
        private final IValueFilter<V> _filter;
        private final IndexMetadata _index;
        private byte[] _nextStartKey;
        private final byte[] _startCol, _endCol;
        private int _remRows; //remaining rows left to fetch, based on max set by user and if the last batch fetched was maximal
        private List<V> _current;
        private Iterator<V> _currentIter;
        private V _next;
        private final List<byte[]> _counterColNames;
        private List<CollectionRange> _ranges;
        private int _iteratedCount = 0;
        private final EConsistencyLevel _level;

        public LazyLoadedIterator(LazyLoadedCollection parent,
                                  List<V> first,
                                  IndexedSlicesQuery<byte[],byte[],byte[]> query,
                                  byte[] nextStartKey,
                                  byte[] startCol,
                                  byte[] endCol,
                                  List<byte[]> counterColNames,
                                  List<CollectionRange> ranges,
                                  IValueFilter<V> filter,
                                  int maxRows,
                                  IndexMetadata index,
                                  EConsistencyLevel level)
        {
            _parent = parent;
            _filter = filter;
            _index = index;

            _current = new ArrayList<V>(first);
            _currentIter = _current.iterator();
            _next = _currentIter.next();
            _query = query;
            _nextStartKey = nextStartKey;
            _ranges = ranges;
            _counterColNames = counterColNames;
            _level = level;

            if(first.size() < CassandraDaoBase.ROW_RANGE_SIZE)
                _remRows = 0;
            else
                _remRows = maxRows - first.size();

            _startCol = startCol;
            _endCol = endCol;
        }

        @Override
        public boolean hasNext()
        {
            return _next != null;
        }

        @SuppressWarnings("unchecked")
        @Override
        public V next()
        {
            if(_next == null)
                throw new NoSuchElementException();

            _iteratedCount++;
            V rv = _next;

            V next = null;

            while(next == null)
            {
                while(_currentIter.hasNext())
                {
                    next = _currentIter.next();
                    if(_filter.isFiltered(indexedValue(next, _index)) == EFilterResult.PASS)
                        break;
                    else
                        _logger.debug("filtered {}", next);
                }

                if(next == null)
                {
                    if(_remRows > 0) //fetch next batch
                    {
                        SimplePropertyMetadata keyMeta = _entityMeta.getKeyMetadata();
                        V last = _current.get(_current.size() - 1);
                        K lastKey = (K) invokeGetter(keyMeta, last);
                        _current.clear();
                        _nextStartKey = fetchBatch(_query, _nextStartKey, _startCol, _endCol, lastKey, _remRows, _current, _counterColNames, _ranges, _level);

                        int cnt = _current.size();
                        if(cnt == 0) //get yielded no rows
                        {
                            next = null;
                            _remRows = 0;
                            _logger.debug("empty fetch, no more values");
                            break;
                        }
                        else
                        {
                            if(cnt < CassandraDaoBase.ROW_RANGE_SIZE - 1) //allow for query range boundary duplications
                                _remRows = 0;
                            else
                                _remRows -= cnt;

                            _currentIter = _current.iterator();
                        }
                    }
                    else //no more rows
                    {
                        _logger.debug("remaining rows zero");
                        break;
                    }
                }
            }

            if(next == null) //have iterated through all results, cache size
                _parent.setSize(_iteratedCount);

            _next = next;

            return rv;
        }

        @Override
        public void remove()
        {
            throw new UnsupportedOperationException();
        }
    }

    private IndexedValue<V> indexedValue(V value, IndexMetadata index)
    {
        SimplePropertyMetadata pm = index.getIndexedProperties().get(0);
        return new IndexedValue<V>(Collections.singletonList(invokeGetter(pm, value)), value);
    }

    private class LazyLoadedCollection extends AbstractCollection<V>
    {
        private byte[] _nextRowKeyBytes;
        private byte[] _startColBytes;
        private byte[] _endColBytes;
        private int _maxRows;
        private IndexedSlicesQuery<byte[], byte[], byte[]> _query;
        private final IValueFilter<V> _filter;
        private final IndexMetadata _index;
        private Integer _size;
        private List<V> _all = null; //if it is known all rows have been fetched, this field is set
        private List<V> _first = new ArrayList<V>();
        private final List<CollectionRange> _ranges;
        private final EConsistencyLevel _level;
        private final List<byte[]> _counterColNames;

        @SuppressWarnings("unchecked")
        public LazyLoadedCollection(IndexedSlicesQuery<byte[], byte[], byte[]> query,
                                    byte[] startColBytes,
                                    byte[] endColBytes,
                                    List<CollectionRange> ranges,
                                    IValueFilter<V> filter,
                                    List<byte[]> counterColNames,
                                    int maxRows,
                                    IndexMetadata index,
                                    EConsistencyLevel level)
        {
            _query = query;
            _startColBytes = startColBytes;
            _endColBytes = endColBytes;
            _maxRows = maxRows;
            _filter = filter;
            _counterColNames = counterColNames;
            _index = index;
            _ranges = ranges;
            _level = level;

            K lastKey = null;
            while(true) //loop until unfiltered rows are found
            {
                _nextRowKeyBytes = fetchBatch(query, _nextRowKeyBytes,
                                              startColBytes, endColBytes,
                                              lastKey, maxRows, _first,
                                              _counterColNames, _ranges,
                                              _level);
                if(_first.isEmpty())
                    break;

                Iterator<V> iter = _first.iterator();
                if(!_first.isEmpty())
                    lastKey = (K) invokeGetter(_entityMeta.getKeyMetadata(), _first.get(_first.size() - 1));
                while(iter.hasNext())
                {
                    V next = iter.next();
                    if(filter.isFiltered(indexedValue(next, index)) != EFilterResult.PASS)
                        iter.remove();
                }

                if(!_first.isEmpty())
                    break;
            }

            if(_first.size() == maxRows || _first.isEmpty()) //loaded all rows or none exist
            {
                _all = _first;
            }
        }

        //override, don't want to invoke size, just to check if empty
        @Override
        public boolean isEmpty()
        {
            return _first.isEmpty();
        }

        void setSize(int size)
        {
            _size = size;
        }

        //may aggressively fetch and retain all values, use with caution
        @Override
        public int size()
        {
            if(_size != null)
                return _size;
            if(_all == null)
            {
                Iterator<V> iter = iterator();
                _all = new ArrayList<V>();
                while(iter.hasNext())
                    _all.add(iter.next());
            }

            return _all.size();
        }

        @Override
        public java.util.Iterator<V> iterator()
        {
            if(_all != null)
                return _all.iterator();

            return new LazyLoadedIterator(this, _first, _query, _nextRowKeyBytes, _startColBytes, _endColBytes, _counterColNames, _ranges, _filter, _maxRows, _index, _level);
        }
    }
}


text:
package org.apache.isis.core.metamodel.facets.value.date;

import java.util.Date;

import org.apache.isis.applib.adapters.EncoderDecoder;
import org.apache.isis.applib.adapters.Parser;
import org.apache.isis.core.metamodel.facetapi.FacetHolder;
import org.apache.isis.core.metamodel.services.ServicesInjector;

public class DateValueSemanticsProvider extends DateValueSemanticsProviderAbstract<org.apache.isis.applib.value.Date> {

    // no default
    private static final org.apache.isis.applib.value.Date DEFAULT_VALUE = null;

    /**
     * Required because implementation of {@link Parser} and
     * {@link EncoderDecoder}.
     */
    public DateValueSemanticsProvider() {
        this(null, null);
    }

    public DateValueSemanticsProvider(final FacetHolder holder, final ServicesInjector context) {
        super(holder, org.apache.isis.applib.value.Date.class, Immutability.NOT_IMMUTABLE, EqualByContent.NOT_HONOURED, DEFAULT_VALUE, context);
    }

    @Override
    protected org.apache.isis.applib.value.Date add(final org.apache.isis.applib.value.Date original, final int years, final int months, final int days, final int hours, final int minutes) {
        final org.apache.isis.applib.value.Date date = original;
        return date.add(years, months, days);
    }

    @Override
    protected org.apache.isis.applib.value.Date now() {
        return new org.apache.isis.applib.value.Date();
    }

    @Override
    protected Date dateValue(final Object value) {
        return ((org.apache.isis.applib.value.Date) value).dateValue();
    }

    @Override
    protected org.apache.isis.applib.value.Date setDate(final Date date) {
        return new org.apache.isis.applib.value.Date(date);
    }
}


text:
<?php

namespace PersonneBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;

class MemoType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('contenu' , TextType::class)
        ->add('fait' , CheckBoxType::class , array( 'label' => 'Action effectuée', 'required' => false ,))
        ->add('enregistrer' , SubmitType::class);

    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'PersonneBundle\Entity\Memo'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'personnebundle_memo';
    }

}


text:
HC_SR04::HC_SR04(int trigPin, int echoPin){
  _minCM = 10.0;
  _maxCM = 250.0;
  _trigPin = trigPin;
  _echoPin = echoPin;
  pinMode(_trigPin, OUTPUT);
  pinMode(_echoPin, INPUT);
}

HC_SR04::HC_SR04(int trigPin, int echoPin, double minCM, double maxCM){
  _minCM = minCM;
  _maxCM = maxCM;
  _trigPin = trigPin;
  _echoPin = echoPin;
  pinMode(_trigPin, OUTPUT);
  pinMode(_echoPin, INPUT);
}

double HC_SR04::getDistanceCM(){
  sendTriggerPulse(_trigPin);
  waitForEcho(_echoPin, HIGH, 100);
  long startTime = micros();
  waitForEcho(_echoPin, LOW, 100);
  long endTime = micros();
  long duration = endTime - startTime;
  double distance = duration / 29.0 / 2.0;
  if (distance < _minCM || distance > _maxCM){
   return -1;
  }
  return distance;
}

double HC_SR04::getDistanceInch(){
  double distCM = getDistanceCM();
  if (distCM == -1){
     return -1;
  }
  return (distCM / 2.5);
}

void HC_SR04::sendTriggerPulse(int pin){
    digitalWrite(pin, HIGH);
    delayMicroseconds(10);
    digitalWrite(pin, LOW);
}

void HC_SR04::waitForEcho(int pin, int value, long timeout){
    long giveupTime = millis() + timeout;
    while (digitalRead(pin) != value && millis() < giveupTime) {}
}


text:
package org.zstack.test.core.cloudbus;

import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.zstack.core.cloudbus.CloudBusIN;
import org.zstack.core.componentloader.ComponentLoader;
import org.zstack.header.AbstractService;
import org.zstack.header.Service;
import org.zstack.header.message.Message;
import org.zstack.test.BeanConstructor;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class TestCloudBusSend {
    ComponentLoader loader;
    CloudBusIN bus;
    CountDownLatch latch = new CountDownLatch(1);
    boolean isSuccess = false;
    Service serv;

    public static class HelloWorldMsg extends Message {
    }

    class FakeService extends AbstractService {
        @Override
        public boolean start() {
            bus.registerService(this);
            bus.activeService(this);
            return true;
        }

        @Override
        public boolean stop() {
            bus.deActiveService(this);
            bus.unregisterService(this);
            return true;
        }

        @Override
        public void handleMessage(Message msg) {
            if (msg.getClass() == HelloWorldMsg.class) {
                isSuccess = true;
            }
            latch.countDown();
        }

        @Override
        public String getId() {
            return this.getClass().getCanonicalName();
        }

    }

    @Before
    public void setUp() throws Exception {
        BeanConstructor con = new BeanConstructor();
        loader = con.build();
        bus = loader.getComponent(CloudBusIN.class);
        serv = new FakeService();
        serv.start();
    }

    @Test
    public void test() throws InterruptedException, ClassNotFoundException {
        HelloWorldMsg msg = new HelloWorldMsg();
        msg.setServiceId(FakeService.class.getCanonicalName());
        bus.send(msg);
        latch.await(10, TimeUnit.SECONDS);
        serv.stop();
        Assert.assertEquals(true, isSuccess);
    }
}


text:
package com.triangleleft.flashcards.ui.main;

import com.android.debug.hv.ViewServer;
import com.annimon.stream.Optional;
import com.triangleleft.flashcards.R;
import com.triangleleft.flashcards.di.main.DaggerMainPageComponent;
import com.triangleleft.flashcards.di.main.MainPageComponent;
import com.triangleleft.flashcards.service.vocabular.VocabularyWord;
import com.triangleleft.flashcards.ui.cards.FlashcardsActivity;
import com.triangleleft.flashcards.ui.common.BaseActivity;
import com.triangleleft.flashcards.ui.main.drawer.NavigationView;
import com.triangleleft.flashcards.util.FunctionsAreNonnullByDefault;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.View;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

@FunctionsAreNonnullByDefault
public class MainActivity extends BaseActivity<MainPageComponent, IMainView, MainPresenter> implements IMainView {

    private static final Logger logger = LoggerFactory.getLogger(MainActivity.class);
    private static final String FRAGMENTS_TAG = "android:support:fragments";

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.navigation_view)
    NavigationView navigationView;
    @Bind(R.id.main_container)
    View mainContainer;

    private IMainActivityDelegate delegate;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            // We don't want fragments to be recreated automatically
            savedInstanceState.putParcelable(FRAGMENTS_TAG, null);
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        setSupportActionBar(toolbar);

        boolean fixedDrawer = getResources().getBoolean(R.bool.fixed_drawer);
        boolean twoPanes = getResources().getBoolean(R.bool.two_panes);

        Configuration configuration = getResources().getConfiguration();
        int screenWidthDp = configuration.screenWidthDp;
        int screenHeightDp = configuration.screenHeightDp;
        logger.debug("onCreate() width: {}, height: {}", screenWidthDp, screenHeightDp);

        // TODO: Factory.buildViewDelegate(fixedDrawer, twoPanes);
        if (fixedDrawer && twoPanes) {
            delegate = new TabletWideDelegate(this);
        } else if (fixedDrawer) {
            delegate = new PhoneDelegate(this);
        } else {
            delegate = new PhoneDelegate(this);
        }

        navigationView.init(getComponent());
        ViewServer.get(this).addWindow(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ViewServer.get(this).removeWindow(this);
    }

    @Override
    protected void inject() {
        getComponent().inject(this);
    }

    @NonNull
    @Override
    protected MainPageComponent buildComponent() {
        return DaggerMainPageComponent.builder()
                .applicationComponent(getApplicationComponent())
                .mainPageModule(new MainPageModule())
                .build();
    }

    @NonNull
    @Override
    protected IMainView getMvpView() {
        return this;
    }

    @Override
    public void setTitle(String title) {
        toolbar.setTitle(title);
    }

    @Override
    public void showList() {
        logger.debug("showList() called");
        delegate.showList();
    }

    @Override
    public void reloadList() {
        logger.debug("reloadList()");
        delegate.reloadList();
    }

    @Override
    public void showWord(@NonNull Optional<VocabularyWord> word) {
        logger.debug("showWord() called with: word = [{}]", word);
        delegate.showWord(word);
    }

    @Override
    public void onBackPressed() {
        if (delegate.isDrawerOpen()) {
            delegate.closeDrawer();
        } else {
            getPresenter().onBackPressed();
        }
    }

    @OnClick(R.id.button_flashcards)
    public void onFlashcardsClick(View view) {

        Intent intent = new Intent(this, FlashcardsActivity.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            int[] location = new int[2];
            view.getLocationOnScreen(location);
            int cx = location[0] + view.getWidth() / 2;
            int cy = location[1] + view.getHeight() / 2;
            intent.putExtra(FlashcardsActivity.REVEAL_X, cx);
            intent.putExtra(FlashcardsActivity.REVEAL_Y, cy);
            startActivity(intent);
            overridePendingTransition(-1, -1);
        } else {
            startActivity(intent);
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace Apfelfrisch\Edifact\Exceptions;

class BuildException extends EdifactException
{
    public static function finalizedBuildNotModifiable(): self
    {
        return new self("Cannot add Segments to finalized Builder.");
    }
}


text:
package ch.usi.dag.dislreserver.msg.classinfo;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import ch.usi.dag.dislreserver.exception.DiSLREServerException;
import ch.usi.dag.dislreserver.reqdispatch.RequestHandler;
import ch.usi.dag.dislreserver.shadow.ShadowClass;
import ch.usi.dag.dislreserver.shadow.ShadowClassTable;
import ch.usi.dag.dislreserver.shadow.ShadowObject;
import ch.usi.dag.dislreserver.shadow.ShadowObjectTable;

public class ClassInfoHandler implements RequestHandler {

	public void handle(DataInputStream is, DataOutputStream os, boolean debug)
			throws DiSLREServerException {

		try {

			long net_ref = is.readLong();
			String classSignature = is.readUTF();
			String classGenericStr = is.readUTF();
			ShadowObject classLoader = ShadowObjectTable.get(is.readLong());

			ShadowClass superClass = (ShadowClass) ShadowObjectTable.get(is
					.readLong());
			ShadowClassTable.newInstance(net_ref, superClass, classLoader,
					classSignature, classGenericStr, debug);
		} catch (IOException e) {
			throw new DiSLREServerException(e);
		}
	}

	public void exit() {

	}
}


text:
class CreatePages < ActiveRecord::Migration[4.2]
  def change
    create_table :pages do |t|
      t.belongs_to :catalog, index: true, foreign_key: true
      t.integer :creator_id, :index => true
      t.integer :reviewer_id, :index => true
      t.string :slug
      t.text :title
      t.text :content
      t.string :locale
      t.string :status

      t.timestamps null: false
    end

    add_foreign_key "pages", "users", :column => "creator_id"
    add_foreign_key "pages", "users", :column => "reviewer_id"
  end
end


text:
require "test_helper"

class KeysTest < Minitest::Spec
  def setup
    @camelcase_strings = { "aA" => 1, "bB" => 2 }
    @camelcase_symbols = { aA: 1, bB: 2 }
    @camelcase_mixed = { :aA => 1, "bB" => 2 }
    @underscore_strings = { "a_a" => 1, "b_b" => 2 }
    @underscore_symbols = { a_a: 1, b_b: 2 }
    @underscore_mixed = { :a_a => 1, "b_b" => 2 }

    @nested_camel_case_strings = { "aA" => { "bB" => { "cC" => 3 } } }
    @nested_camel_case_symbols = { aA: { bB: { cC: 3 } } }
    @nested_camel_case_mixed = { "aA" => { bB: { "cC" => 3 } } }
    @nested_underscore_strings = { "a_a" => { "b_b" => { "c_c" => 3 } } }
    @nested_underscore_symbols = { a_a: { b_b: { c_c: 3 } } }
    @nested_underscore_mixed = { "a_a" => { b_b: { "c_c" => 3 } } }

    @camelcase_string_array_of_hashes = { "aA" => [{ "bB" => 2 }, { "cC" => 3 }, 4] }
    @camelcase_symbol_array_of_hashes = { aA: [{ bB: 2 }, { cC: 3 }, 4] }
    @camelcase_mixed_array_of_hashes = { aA: [{ bB: 2 }, { "cC" => 3 }, 4] }
    @underscore_string_array_of_hashes = { "a_a" => [{ "b_b" => 2 }, { "c_c" => 3 }, 4] }
    @underscore_symbol_array_of_hashes = { a_a: [{ b_b: 2 }, { c_c: 3 }, 4] }
    @underscore_mixed_array_of_hashes = { a_a: [{ b_b: 2 }, { "c_c" => 3 }, 4] }
  end

  it "underscore_keys" do
    @camelcase_strings.underscore_keys.must_equal @underscore_strings
    @camelcase_symbols.underscore_keys.must_equal @underscore_symbols
    @camelcase_mixed.underscore_keys.must_equal @underscore_mixed
  end

  it "camelize_keys" do
    @underscore_strings.camelize_keys.must_equal @camelcase_strings
    @underscore_symbols.camelize_keys.must_equal @camelcase_symbols
    @underscore_mixed.camelize_keys.must_equal @camelcase_mixed
  end

  it "deep_underscore_keys" do
    @nested_camel_case_strings.deep_underscore_keys.must_equal @nested_underscore_strings
    @nested_camel_case_symbols.deep_underscore_keys.must_equal @nested_underscore_symbols
    @nested_camel_case_mixed.deep_underscore_keys.must_equal @nested_underscore_mixed
    @camelcase_string_array_of_hashes.deep_underscore_keys.must_equal @underscore_string_array_of_hashes
    @camelcase_symbol_array_of_hashes.deep_underscore_keys.must_equal @underscore_symbol_array_of_hashes
    @camelcase_mixed_array_of_hashes.deep_underscore_keys.must_equal @underscore_mixed_array_of_hashes
  end

  it "deep_camelize_keys" do
    @nested_underscore_strings.deep_camelize_keys.must_equal @nested_camel_case_strings
    @nested_underscore_symbols.deep_camelize_keys.must_equal @nested_camel_case_symbols
    @nested_underscore_mixed.deep_camelize_keys.must_equal @nested_camel_case_mixed
    @underscore_string_array_of_hashes.deep_camelize_keys.must_equal @camelcase_string_array_of_hashes
    @underscore_symbol_array_of_hashes.deep_camelize_keys.must_equal @camelcase_symbol_array_of_hashes
    @underscore_mixed_array_of_hashes.deep_camelize_keys.must_equal @camelcase_mixed_array_of_hashes
  end
end


text:
#ifndef DISPLAYLIST_H_
#define DISPLAYLIST_H_

#include "Bounds.h"

#include <vector>

class DisplayList
{
public:
    DisplayList() : margins{0, 0, 0, 0} {}

    void set_margins(std::tuple<int, int, int, int> margins);

    void add_display(Bounds display);

    // find display based on most overlap
    // return display (+ idx_offset) after margins applied
    Bounds target_display(Bounds window, std::ptrdiff_t idx_offset = 0);

    const std::vector<Bounds>& get_vec();

private:
    //          l    r    t    b
    std::tuple<int, int, int, int> margins;
    std::vector<Bounds> displays; // before margins applied
    std::vector<int>    overlaps;
};

#endif /* DISPLAYLIST_H_ */


text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>WebMovie - Dashboard</title>

<link href="{{ url('public/assets/bootstrap.min.css') }}" rel="stylesheet">
<link href="{{ url('public/assets/styles.css') }}" rel="stylesheet">
<link href="{{ url('public/css/customs.css') }}" rel="stylesheet">
<link href="{{ url('public/assets/bootstrap-select.min.css') }}" rel="stylesheet">
<link href="{{ url('public/assets/tokenfield-typeahead.min.css') }}" rel="stylesheet">
<link href="{{ url('public/assets/bootstrap-tokenfield.min.css') }}" rel="stylesheet">

404 Page not found

                        Go Home
                        @if($currentUser['role'] == 'admin')
                            Go Admin
                        @else
                            Go My Account
                        @endif


text:
package it.unitn.ing.esqui.client;

/** Quantitative.java
 *

 * Title:			ESQUI Client Quantitative Analysis
 *

 * Description:		Methods to set up a quantitative analysis
 for the ESQUI client
 * @author:			Leonardo Cont, December 2000
 * @revision:		February 2001
 * @comment:		none
 */

public class Quantitative extends ClientAnalysis {

  final float[] zDEFAULT_StdText = {noMove, noMove, noMove};
  final float[] yDEFAULT_StdText = {noMove, noMove, noMove};
  final float[] xDEFAULT_StdText = {noMove, noMove, noMove};
  final float[] phiDEFAULT_StdText = {noMove, noMove, noMove};
  final float[] chiDEFAULT_StdText = {noMove, noMove, noMove};
  final float[] omegaDEFAULT_StdText = {10, 20, 10};
  final float[] twothetaDEFAULT_StdText = {10, 30, 20};
  final int ctDEFAULT_StdText = 10;
  final float kVDEFAULT_StdText = 40;
  final float mADEFAULT_StdText = 30;
  final int channelsDEFAULT_StdText = 4096;
  final int movefilterDEFAULT_StdText = 0;
  final String measuretypeDEFAULT_StdText = "Step_Scan";

  public Quantitative(String title) {
    super(title);
    setDefaultParameters();
  }

  public void setDefaultParameters() {
    setParameters(z, zDEFAULT_StdText);
    setParameters(y, yDEFAULT_StdText);
    setParameters(x, xDEFAULT_StdText);
    setParameters(phi, phiDEFAULT_StdText);
    setParameters(chi, chiDEFAULT_StdText);
    setParameters(omega, omegaDEFAULT_StdText);
    setParameters(twotheta, twothetaDEFAULT_StdText);
    ct = ctDEFAULT_StdText;
    kV = kVDEFAULT_StdText;
    mA = mADEFAULT_StdText;
    channels = channelsDEFAULT_StdText;
    movefilter = movefilterDEFAULT_StdText;
    measuretype = measuretypeDEFAULT_StdText;
  }

  public String getAnalysisFile() {
    StringBuffer tmpBuffer = new StringBuffer("US " + Client.getUser());
    setNewLine(tmpBuffer);
    for (int i = 0; i < separator; i++) {
      tmpBuffer.append(esquigoCommands[i]);
      setBlankSpace(tmpBuffer);
      tmpBuffer.append(allOptionsVector.elementAt(i));
      setNewLine(tmpBuffer);
    }

    int j = 0;
    while (j < 3) {
      tmpBuffer.append(esquigoCommands[separator]);
      for (int i = j++; i < allMovementsVector.size(); i = i + 3) {
        setBlankSpace(tmpBuffer);
        if (((Float) allMovementsVector.elementAt(i)).intValue() == noMove) {
          tmpBuffer.append("-" + ",");
        } else {
          tmpBuffer.append(allMovementsVector.elementAt(i) + ",");
        }
      }
      setNewLine(tmpBuffer);
      separator++;
    }

    for (int i = separator; i < esquigoCommands.length; i++) {
      tmpBuffer.append(esquigoCommands[i]);
      setNewLine(tmpBuffer);
    }

    return tmpBuffer.toString();
  }
}


text:
This inspection reports any instances of for loops which iterate
over collections or arrays, and can be replaced with the JDK 5.0 "for each" iteration syntax.

The setting Report java.util.List indexed loops is responsible for finding loops involving list.get(index) calls.
These loops generally can be replaced with the foreach loops, unless they modify underlying list in the process, e.g. by calling list.remove(index).
If latter is the case, foreach form of loop may throw ConcurrentModificationException.

For safety, this inspection is disabled unless the project uses JDK 5.0.

  Powered by InspectionGadgets


text:
from swgpy.object import *

def create(kernel):
	result = Tangible()

	result.template = "object/tangible/wearables/armor/ithorian_defender/shared_ith_armor_s01_bracer_r.iff"
	result.attribute_template_id = 0
	result.stfName("wearables_name","ith_armor_s01_bracer_r")

	#### BEGIN MODIFICATIONS ####
	####  END MODIFICATIONS  ####

	return result


text:
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup

d = generate_distutils_setup(
    packages = ['behavior_simplemissiondriveto'],
    package_dir = {'': 'src'}
)

setup(**d)


text:
from flask_app.flask_app import db

class WeaponMode(db.Model):
    __tablename__ = 'weaponmode'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(100))

    def __init__(self, name=None):
        self.name = name

    def __repr__(self):
        pass


text:
package sh.isaac.solor.model.fields;

/**
 * 2019-03-07
 * aks8m - https://github.com/aks8m
 */
public interface ConceptFields {

    int getDefinitionStatus();
    void setDefinitionStatus(int definitionStatus);
}


text:
#include <aws/lightsail/model/DeleteDomainEntryRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Lightsail::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

DeleteDomainEntryRequest::DeleteDomainEntryRequest() :
    m_domainNameHasBeenSet(false),
    m_domainEntryHasBeenSet(false)
{
}

Aws::String DeleteDomainEntryRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_domainNameHasBeenSet)
  {
   payload.WithString("domainName", m_domainName);

  }

  if(m_domainEntryHasBeenSet)
  {
   payload.WithObject("domainEntry", m_domainEntry.Jsonize());

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection DeleteDomainEntryRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "Lightsail_20161128.DeleteDomainEntry"));
  return headers;

}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

       <item android:id="@+id/frag1"
           android:orderInCategory="1"
           android:title="Show Fragment 1"/>
       <item android:id="@+id/frag2"
           android:orderInCategory="2"
           android:title="Show Fragment 2"/>

</menu>


text:
'use strict';

// Declare app level module which depends on views, and components
var serket = angular.module('serket', ['ngRoute'])

serket.config(['$routeProvider', function($routeProvider) {

  $routeProvider.otherwise({redirectTo: '/home'});

  $routeProvider.when('/home', {
    templateUrl: 'home/home.html',
    controller: 'homeController'
  });
}]);


text:
require 'test_helper'

class TmpuserTest < ActiveSupport::TestCase
   test "the truth" do
     assert true
   end
end


text:
var fs = require('fs');
var argv = require('minimist')(process.argv.slice(2));
var SocketCluster = require('socketcluster').SocketCluster;
var scHotReboot = require('sc-hot-reboot');

var workerControllerPath = argv.wc || process.env.SOCKETCLUSTER_WORKER_CONTROLLER;
var brokerControllerPath = argv.bc || process.env.SOCKETCLUSTER_BROKER_CONTROLLER;
var initControllerPath = argv.ic || process.env.SOCKETCLUSTER_INIT_CONTROLLER;
var environment = process.env.ENV || 'dev';

var options = {
    workers: Number(argv.w) || Number(process.env.SOCKETCLUSTER_WORKERS) || 1,
    brokers: Number(argv.b) || Number(process.env.SOCKETCLUSTER_BROKERS) || 1,
    port: Number(argv.p) || Number(process.env.SOCKETCLUSTER_PORT) || Number(process.env.PORT) || 8000,
    // If your system doesn't support 'uws', you can switch to 'ws' (which is slower but works on older systems).
    wsEngine: process.env.SOCKETCLUSTER_WS_ENGINE || 'uws',
    appName: argv.n || process.env.SOCKETCLUSTER_APP_NAME || null,
    workerController: workerControllerPath || __dirname + '/worker.js',
    brokerController: brokerControllerPath || __dirname + '/broker.js',
    initController: initControllerPath || null,
    socketChannelLimit: Number(process.env.SOCKETCLUSTER_SOCKET_CHANNEL_LIMIT) || 1000,
    clusterStateServerHost: argv.cssh || process.env.SCC_STATE_SERVER_HOST || null,
    clusterStateServerPort: process.env.SCC_STATE_SERVER_PORT || null,
    clusterAuthKey: process.env.SCC_AUTH_KEY || null,
    clusterStateServerConnectTimeout: Number(process.env.SCC_STATE_SERVER_CONNECT_TIMEOUT) || null,
    clusterStateServerAckTimeout: Number(process.env.SCC_STATE_SERVER_ACK_TIMEOUT) || null,
    clusterStateServerReconnectRandomness: Number(process.env.SCC_STATE_SERVER_RECONNECT_RANDOMNESS) || null,
    crashWorkerOnError: argv['auto-reboot'] != false,
    // If using nodemon, set this to true, and make sure that environment is 'dev'.
    killMasterOnSignal: false,
    instanceId: 'realm-1',
    pubSubBatchDuration: null,
    environment: environment
};

var SOCKETCLUSTER_OPTIONS;

if (process.env.SOCKETCLUSTER_OPTIONS) {
    SOCKETCLUSTER_OPTIONS = JSON.parse(process.env.SOCKETCLUSTER_OPTIONS);
}

for (var i in SOCKETCLUSTER_OPTIONS) {
    if (SOCKETCLUSTER_OPTIONS.hasOwnProperty(i)) {
        options[i] = SOCKETCLUSTER_OPTIONS[i];
    }
}

var masterControllerPath = argv.mc || process.env.SOCKETCLUSTER_MASTER_CONTROLLER;

var start = function () {
    var socketCluster = new SocketCluster(options);

    if (masterControllerPath) {
        var masterController = require(masterControllerPath);
        masterController.run(socketCluster);
    }

    if (environment == 'dev') {
        // This will cause SC workers to reboot when code changes anywhere in the app directory.
        // The second options argument here is passed directly to chokidar.
        // See https://github.com/paulmillr/chokidar#api for details.
        console.log(`   !! The sc-hot-reboot plugin is watching for code changes in the ${__dirname} directory`);
        scHotReboot.attach(socketCluster, {
            cwd: __dirname,
            ignored: ['public', 'node_modules', 'README.md', 'Dockerfile', 'server.js', 'broker.js', /[\/\\]\./]
        });
    }
};

var bootCheckInterval = Number(process.env.SOCKETCLUSTER_BOOT_CHECK_INTERVAL) || 200;

if (workerControllerPath) {
    // Detect when Docker volumes are ready.
    var startWhenFileIsReady = (filePath) => {
        return new Promise((resolve) => {
            if (!filePath) {
                resolve();
                return;
            }
            var checkIsReady = () => {
                fs.exists(filePath, (exists) => {
                    if (exists) {
                        resolve();
                    } else {
                        setTimeout(checkIsReady, bootCheckInterval);
                    }
                });
            };
            checkIsReady();
        });
    };
    var filesReadyPromises = [
        startWhenFileIsReady(masterControllerPath),
        startWhenFileIsReady(workerControllerPath),
        startWhenFileIsReady(brokerControllerPath),
        startWhenFileIsReady(initControllerPath)
    ];
    Promise.all(filesReadyPromises).then(() => {
        start();
    });
} else {
    start();
}


text:
- [Coffeescript](http://coffeescript.org/)
- [Jade](http://jade-lang.com/)
- [Less](http://www.lesscss.org/)

## Framework|Tools
- [AngularJS](http://angularjs.org/)
- [Bootstrap3](http://getbootstrap.com/)
- [Gulp](http://gulpjs.com/)
- Livereload

## Installation
[Install npm](https://nodejs.org/download/)
Install bower by running this command
  `npm install -g bower`

Run these two commands in the command line.
  `npm install`
  `bower install`

## Development server
Run this command to host a development server

  `npm run-script watch`

Access to the application at this address: http://127.0.0.1:8008
The livereload update your browser each time you change source files.

## Your Function
Go to src-public/controllers/member.coffee, and scroll down until you see
	```
	$scope.matchAll = () ->
		...
		...
	```
This is the function for you to edit. I've already queried the database, and iteratively updated the database at the end of the function.

## Testing
Add /conortest to the end of your development server URL. There's a button that you can hit that will run your function. Use the console to check what's happening (I've demonstrated how to print to the console at the end of your function. To see the Javascript console on your browser, hit Command+Option+J). One catch; it sometimes takes a little while for the front end to connect to the backend, and if you hit the test button before this connection has been made, nothing will happen. If you open up the console, a bunch of info will be printed to it once the front end connects to the back end, so just make sure that happens before you hit test.


text:
/* fileLseek.h - This file may be generated by a program or script
 */

#ifndef DATA_OBJ_LSEEK_H
#define DATA_OBJ_LSEEK_H

/* This is a low level file type API call */

#include "rods.h"
#include "rcMisc.h"
#include "procApiRequest.h"
#include "apiNumber.h"
#include "initServer.h"

#include "fileDriver.h"
#include "fileLseek.h"

/* This is a high level type API call */

#if defined(RODS_SERVER)
#define RS_DATA_OBJ_LSEEK rsDataObjLseek
/* prototype for the server handler */
int
rsDataObjLseek (rsComm_t *rsComm, openedDataObjInp_t *dataObjLseekInp,
fileLseekOut_t **dataObjLseekOut);
rodsLong_t
_l3Lseek (rsComm_t *rsComm, int rescTypeInx, int l3descInx,
rodsLong_t offset, int whence);
#else
#define RS_DATA_OBJ_LSEEK NULL
#endif

#ifdef COMPAT_201
#if defined(RODS_SERVER)
#define RS_DATA_OBJ_LSEEK201 rsDataObjLseek201
/* prototype for the server handler */
int
rsDataObjLseek201 (rsComm_t *rsComm, fileLseekInp_t *dataObjLseekInp,
fileLseekOut_t **dataObjLseekOut);
#else
#define RS_DATA_OBJ_LSEEK201 NULL
#endif
#endif

#ifdef  __cplusplus
extern "C" {
#endif

/* prototype for the client call */
/* rcDataObjLseek - Lseek an opened iRODS data object descriptor.
 * Input -
 *   rcComm_t *conn - The client connection handle.
 *   fileLseekInp_t *dataObjLseekInp - Relevant items are:
 *      l1descInx - the iRODS data object descriptor to lseek.
 *	offset - the offset
 *	whence - SEEK_SET, SEEK_CUR and SEEK_END
 *
 * OutPut -
 *   int status of the operation - >= 0 ==> success, < 0 ==> failure.
 *   fileLseekOut_t **dataObjLseekOut. Relevant items are:
 *	offset - the new offset
 */

int
rcDataObjLseek (rcComm_t *conn, openedDataObjInp_t *dataObjLseekInp,
fileLseekOut_t **dataObjLseekOut);

#ifdef  __cplusplus
}
#endif

#endif	/* DATA_OBJ_LSEEK_H */


text:
package io.netty.resolver.dns;

import java.net.InetSocketAddress;

abstract class DefaultDnsServerAddresses extends DnsServerAddresses {

    protected final InetSocketAddress[] addresses;
    private final String strVal;

    DefaultDnsServerAddresses(String type, InetSocketAddress[] addresses) {
        this.addresses = addresses;

        final StringBuilder buf = new StringBuilder(type.length() + 2 + addresses.length * 16);
        buf.append(type).append('(');

        for (InetSocketAddress a: addresses) {
            buf.append(a).append(", ");
        }

        buf.setLength(buf.length() - 2);
        buf.append(')');

        strVal = buf.toString();
    }

    @Override
    public String toString() {
        return strVal;
    }
}


text:
FROM ubuntu:xenial

#######################################################################
#                           Basic platform                            #
#######################################################################

RUN apt-get -y update

# Install the base dependencies
RUN apt-get install -y \
    build-essential \
    curl \
    git \
    graphicsmagick \
    libcurl4-openssl-dev \
    libcairo2 \
    nginx \
    python-pip \
    unzip \
    lsof \
    wget \
    tmux

#######################################################################
#                   Essential Selenium dependencies                   #
#######################################################################

#############################################
#  X virtual Frame buffer, Chrome, Firefox  #
#############################################

RUN sh -c 'curl -sL https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -'
RUN sh -c 'echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list'
RUN apt-get update
RUN apt-get install -y xvfb google-chrome-stable
RUN apt-get clean
# Version 35 is all that works with Selenium!
# See https://github.com/SeleniumHQ/selenium/issues/1915
RUN wget sourceforge.net/projects/ubuntuzilla/files/mozilla/apt/pool/main/f/firefox-mozilla-build/firefox-mozilla-build_35.0.1-0ubuntu1_amd64.deb
RUN dpkg -i firefox-mozilla-build_35.0.1-0ubuntu1_amd64.deb

COPY xvfb.service /etc/init.d/xvfb
RUN chmod +x /etc/init.d/xvfb

##########
#  Java  #
##########

ENV JAVA_URL=http://download.oracle.com/otn-pub/java/jdk/8u65-b17/jdk-8u65-linux-x64.tar.gz
RUN mkdir -p /usr/lib/jvm
RUN wget --no-check-certificate --quiet --no-cookies --header "Cookie: oraclelicense=accept-securebackup-cookie" $JAVA_URL
RUN tar -zxf jdk-8u65-linux-x64.tar.gz -C /usr/lib/jvm
RUN rm jdk-8u65-linux-x64.tar.gz
RUN update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.8.0_65/bin/java" 1
RUN update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.8.0_65/bin/javac" 1
RUN update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/lib/jvm/jdk1.8.0_65/bin/javaws" 1
RUN chmod a+x /usr/bin/java /usr/bin/javac /usr/bin/javaws

#######################################################################
#                            Install Node                             #
#######################################################################

ENV NODE_VERSION=6.9.2 \
 NENV=nenv \
 DISPLAY=:0

RUN mkdir /opt/node-envs
RUN pip install nodeenv
RUN nodeenv -n $NODE_VERSION /opt/node-envs/$NODE_VERSION

COPY $NENV /usr/local/bin/$NENV
RUN chmod +x /usr/local/bin/$NENV

RUN $NENV npm install webdriver-manager -g

########################################
#  install or copy webdriverio-server  #
########################################

# This installs selenium

RUN $NENV webdriver-manager update

RUN apt-get install -y fonts-roboto

EXPOSE 4444

CMD ["sh", "-c", "service xvfb start; $NENV webdriver-manager start"]
#CMD bash