text:
package org.elasticsearch.client.ml.dataframe.stats.outlierdetection;

import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.test.AbstractXContentTestCase;

import java.io.IOException;

public class ParametersTests extends AbstractXContentTestCase<Parameters> {

    @Override
    protected boolean supportsUnknownFields() {
        return true;
    }

    @Override
    protected Parameters doParseInstance(XContentParser parser) throws IOException {
        return Parameters.PARSER.apply(parser, null);
    }

    @Override
    protected Parameters createTestInstance() {
        return createRandom();
    }

    public static Parameters createRandom() {
        return new Parameters(
            randomBoolean() ? null : randomIntBetween(1, Integer.MAX_VALUE),
            randomBoolean() ? null : randomAlphaOfLength(5),
            randomBoolean() ? null : randomBoolean(),
            randomBoolean() ? null : randomDouble(),
            randomBoolean() ? null : randomDouble(),
            randomBoolean() ? null : randomBoolean()
        );
    }
}


text:
using NoMoreZeroDays.HabitManager;
using NoMoreZeroDays.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;

namespace NoMoreZeroDays.Tests
{
    public class TestAddingHabits
    {
        static Random rnd = new Random();
        public TestAddingHabits()
        {
            int randomNumber = new Random().Next(5) + 3;
            for (int i = 0; i < randomNumber; i++)
                HabitList.Instance.Add(CreateRandomHabit());
        }

        public Habit CreateRandomHabit(String Name = "", String Description = "", String ImageLocation = "", int Days = 0, int CurrentDay = 0)
        {
            if (Name == String.Empty)
            {
                Name = "Habit " + rnd.Next(100);
            }
            if (Description == String.Empty)
            {
                Description = "Habit description" + rnd.Next(100);
            }
            if (Days == 0)
            {
                Days = rnd.Next(15) + 15;
            }
            if (CurrentDay == 0)
            {
                CurrentDay = rnd.Next(Days);
            }
            Habit habit = new Habit();
            habit.Name = Name;
            habit.Description = Description;
            habit.CurrentDay = CurrentDay;
            habit.Days = Days;
            //habit.LastDateDone = new DateTime(2014, 10, 11 + new Random().Next(5));
            Debug.WriteLine(habit);
            return habit;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;

public class OrderSegmentTest {

    @BeforeClass
    public static void classSetUp() {
        Planet.reset();
    }

    @Before
    public void setUp() {
        new Planet(null, 0, 5, 1.0, 7.0);
        new Planet(null, 1, 5, 4.0, 4.0);
        new Planet(null, 2, 5, 2.0, 5.0);
    }

    @Test
    public void attributes() {
        final OrderSegment segment = new OrderSegment(Planet.get(0), 20, 3, 0);
        assertEquals(Planet.get(0), segment.getSource());
        assertEquals(20, segment.getShipCount());
        assertEquals(3, segment.getDistance());
        assertEquals(0, segment.getTurnDelta());
    }

    @Test
    public void equals_and_hashCode() {
        final OrderSegment segment = new OrderSegment(Planet.get(0), 20, 3, 0);
        final OrderSegment same = new OrderSegment(Planet.get(0), 20, 3, 0);
        final OrderSegment other = new OrderSegment(Planet.get(1), 30, 3, 1);
        assertEquals(same, segment);
        assertEquals(same.hashCode(), segment.hashCode());
        assertFalse(other.equals(segment));
        assertFalse(other.hashCode() == segment.hashCode());
    }

    @Test
    public void string() {
        final OrderSegment segment = new OrderSegment(Planet.get(0), 20, 3, 0);
        assertEquals("<S " + Planet.get(0) + " #20 in (0+3)>", segment.toString());
    }

    @After
    public void tearDown() {
        Planet.reset();
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using log4net;
using Mail2Bug.Email;

namespace Mail2Bug.MessageProcessingStrategies
{
    /// <summary>
    /// This class is responsible for processing the message and extracting the list of all the fields that should be overridden
    /// and the values with which they should be overridden.
    /// These values can then be applied to the work item by the message processing strategy.
    /// </summary>
    public class OverridesExtractor
    {
        private readonly Config.InstanceConfig _config;
        private Dictionary<string, DateBasedValueResolver> _dateBasedResolvers;

        public OverridesExtractor(Config.InstanceConfig config)
        {
            _config = config;

            InitDateBasedResolvers();
        }

        private void InitDateBasedResolvers()
        {
            _dateBasedResolvers = new Dictionary<string, DateBasedValueResolver>();

            if (_config.WorkItemSettings.DateBasedOverrides == null)
            {
                return;
            }

            foreach (var overrides in _config.WorkItemSettings.DateBasedOverrides)
            {
                var entries = new SortedList<DateTime, string>();
                overrides.Entries.ForEach(x => entries.Add(x.StartDate, x.Value));

                _dateBasedResolvers.Add(overrides.FieldName, new DateBasedValueResolver(overrides.DefaultValue, entries));
            }
        }

        public Dictionary<string, string> GetOverrides(IIncomingEmailMessage message)
        {
            var result = new Dictionary<string, string>();
            AddToDictionary(GetRecipientOverrides(message), result);
            AddToDictionary(GetDatebasedOverrides(), result);
            AddToDictionary(GetMnemonicOverrides(GetMessageFullText(message)), result);
            AddToDictionary(GetExplicitOverrides(GetMessageFullText(message)), result);

            return result;
        }

        public Dictionary<string, string> GetOverrides(string text)
        {
            var result = new Dictionary<string, string>();
            AddToDictionary(GetMnemonicOverrides(text), result);
            AddToDictionary(GetExplicitOverrides(text), result);

            return result;
        }

        private IEnumerable<KeyValuePair<string, string>> GetDatebasedOverrides()
        {
            var overrides = new List<KeyValuePair<string, string>>();
            foreach (var resolver in _dateBasedResolvers)
            {
                overrides.Add(new KeyValuePair<string, string>(resolver.Key, resolver.Value.Resolve(DateTime.Now)));
            }

            return overrides;
        }

        private IEnumerable<KeyValuePair<string, string>> GetRecipientOverrides(IIncomingEmailMessage message)
        {
            var overrides = new List<KeyValuePair<string, string>>();
            overrides.AddRange(message.CcAddresses.SelectMany(ExtractRecipientOverrides));
            overrides.AddRange(message.ToAddresses.SelectMany(ExtractRecipientOverrides));

            return overrides;
        }

        private IEnumerable<KeyValuePair<string,string>> ExtractRecipientOverrides(string recipientAlias)
        {
            if (_config.WorkItemSettings.RecipientOverrides == null)
            {
                return new Dictionary<string, string>();
            }

            var overrides =
                from def in _config.WorkItemSettings.RecipientOverrides
                where def.Alias.Equals(recipientAlias, StringComparison.InvariantCultureIgnoreCase)
                select new KeyValuePair<string, string>(def.Field, def.Value);

            var overridesList = overrides as List<KeyValuePair<string, string>> ?? overrides.ToList();
            foreach (var entry in overridesList)
            {
                Logger.InfoFormat("Found override {0}={1} for alias {2}", entry.Key, entry.Value, recipientAlias);
            }

            return overridesList;
        }

        /// <summary>
        /// Adds the elements from 'elementsToAdd' to the dictionary.
        /// If an element already exists in the dictionary, its value is overwritten by the new value.
        /// </summary>
        private static void AddToDictionary(IEnumerable<KeyValuePair<string, string>> elementsToAdd, Dictionary<string, string> dictionary)
        {
            elementsToAdd.ToList().ForEach(x => dictionary[x.Key] = x.Value);
        }

        /// <summary>
        /// Gets the list of key-value pairs for fields overridden by mnemonics
        /// </summary>
        /// <returns></returns>
        private IEnumerable<KeyValuePair<string, string>> GetMnemonicOverrides(string text)
        {
            return GetMnemonics(text).SelectMany(ResolveMnemonic);
        }

        private string GetMessageFullText(IIncomingEmailMessage message)
        {
            var sb = new StringBuilder();
            sb.AppendLine(message.Subject).AppendLine(message.PlainTextBody);
            return sb.ToString();
        }

        /// <summary>
        /// Gets a list of all the mnemonics that appear in the text
        /// </summary>
        private static IEnumerable<string> GetMnemonics(string text)
        {
            var mnemonicsRegex = new Regex(@"@@@\s*(?<mnemonic>\w+)");
            var mnemonics = from Match match in mnemonicsRegex.Matches(text) select match.Groups["mnemonic"].Value;
            return mnemonics;
        }

        /// <summary>
        /// Resolves a mnemonic to the list of fields it should set and their appropriate values
        /// </summary>
        private IEnumerable<KeyValuePair<string, string>> ResolveMnemonic(string mnemonic)
        {
            var mnemonicEntries = _config.WorkItemSettings.Mnemonics.FindAll(x => x.Mnemonic.Equals(mnemonic, StringComparison.InvariantCultureIgnoreCase));

            if (!mnemonicEntries.Any())
            {
                Logger.WarnFormat("Unknown mnemonic used - '{0}'", mnemonic);
                return new List<KeyValuePair<string, string>>();
            }

            mnemonicEntries.ForEach(entry => Logger.InfoFormat("Mnemonic {0} resolved to {1}={2}", mnemonic, entry.Field, entry.Value));
            return mnemonicEntries.Select(x => new KeyValuePair<string,string>(x.Field, x.Value));
        }

        /// <summary>
        /// Gets a list of all the explicit overrides in the message
        /// </summary>
        private IEnumerable<KeyValuePair<string, string>> GetExplicitOverrides(string text)
        {
            var overridesRegex = new Regex(_config.EmailSettings.ExplicitOverridesRegex);

            var overrides =
                from Match match in overridesRegex.Matches(text)
                select ExtractOverride(match);

            return overrides;
        }

        /// <summary>
        /// Helper function to transform regex match to a friendly form for handling overrides
        /// </summary>
        private static KeyValuePair<string, string> ExtractOverride(Match match)
        {
            var key = match.Groups["fieldName"].Value.Trim();
            var value = match.Groups["value"].Value.Trim();

            Logger.InfoFormat("Found explicit override {0}={1}", key, value);
            return new KeyValuePair<string, string>(key, value);
        }

        private static readonly ILog Logger = LogManager.GetLogger(typeof(OverridesExtractor));
    }
}


text:
require 'spec_helper'

describe Voltron::Config::Flash do

  let(:flash) { Voltron::Config::Flash.new }

  it 'has a version number' do
    expect(Voltron::Flash::VERSION).to_not be(nil)
  end

  it 'should have a default header of X-Flash' do
    expect(flash.header).to eq('X-Flash')
  end

  it 'should return an instance of the flash config' do
    expect(Voltron.config.flash).to be_a(Voltron::Config::Flash)
  end

  it 'includes flash config in voltron config when generated' do
    expect(Voltron.config.to_h).to have_key(:flash)
    expect(Voltron.config.to_h[:flash]).to eq({ header: Voltron.config.flash.header, group: Voltron.config.flash.group })
  end
end


text:
"use strict";

/**
 * Resolve once all promise give in the array are complete
 * @param array
 * @returns {*}
 */
module.exports = function(array) {
    return (Promise.all(array));
};


text:
package com.faforever.client.user;

import com.faforever.client.task.CompletableTask;

import java.util.concurrent.CompletableFuture;

public interface UserService {

  CompletableFuture<Void> login(String username, String password, boolean autoLogin);

  String getUsername();

  String getPassword();

  Integer getUserId();

  void cancelLogin();

  void logOut();

  CompletableTask<Void> changePassword(String currentPassword, String newPassword);

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:padding="10dp" >

    <ImageView
        android:id="@+id/menu_pic"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_gravity="center_vertical"
        android:src="@drawable/close_pressed" />

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical" >

        <TextView
            android:id="@+id/menu_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="5dp"
            android:text="面刀大盘鸡"
            android:textColor="#666666" />

        <TextView
            android:id="@+id/price"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/menu_name"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="5dp"
            android:gravity="center_vertical"
            android:text="78.00"
            android:textColor="#ff6800" />

        <TextView
            android:id="@+id/is_sale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/price"
            android:layout_marginLeft="3dp"
            android:layout_toRightOf="@id/price"
            android:layout_centerVertical="true"
            android:background="@drawable/menu_coupon_red_bg_shape"
            android:text="惠"
            android:textColor="#FFF"
            android:textSize="10sp"
            android:visibility="gone" />

        <TextView
            android:id="@+id/coupon_price"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@id/price"
            android:layout_below="@+id/price"
            android:layout_marginLeft="2dp"
            android:gravity="center_vertical"
            android:textColor="#cccccc"
            android:textSize="10sp" />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical" >

        <ImageView
            android:id="@+id/reduce"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_centerVertical="true"
            android:layout_marginRight="5dp"
            android:layout_toLeftOf="@+id/count"
            android:src="@drawable/cart_minus" />

        <TextView
            android:id="@+id/count"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginRight="5dp"
            android:layout_toLeftOf="@+id/add"
            android:text="1"
            android:textColor="#666666" />

        <ImageView
            android:id="@+id/add"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:src="@drawable/order" />
    </RelativeLayout>

</LinearLayout>


text:
Split filter
---

Status : core plugin, unit tested and maintained.

The split filter is used to split a line of log into multiple lines, on a given delimiter.

Example 1: ``filter://split://?delimiter=|`` split all lines of logs on ``|`` char.

Config using url: ``filter://split://?delimiter=|``.
You have to url encode special chars (%0A for ``\n``).

Config using logstash format:
````
filter {
  split {
    delimiter => '|'
  }
}
````

Parameters:

* ``delimiter``: delimiter used to split.


text:
using namespace System;
using namespace System::Collections::Generic;
using namespace System::Runtime::InteropServices;

namespace zuki::tools::llvm::clang {

// FORWARD DECLARATIONS
//
ref class Diagnostic;

//---------------------------------------------------------------------------
// Class DiagnosticChildCollection
//
// Specialization of DiagnosticCollection for child diagnostics
//---------------------------------------------------------------------------

public ref class DiagnosticChildCollection : public DiagnosticCollection
{
public:

	//-----------------------------------------------------------------------
	// Properties

	// default[int]
	//
	// Gets the element at the specified index in the read-only list
	property Diagnostic^ default[int]
	{
		virtual Diagnostic^ get(int index) override;
	}

	// Count
	//
	// Gets the number of elements in the collection
	property int Count
	{
		virtual int get() override;
	}

internal:

	//-----------------------------------------------------------------------
	// Internal Member Functions

	// Create
	//
	// Creates a new DiagnosticChildCollection instance
	static DiagnosticChildCollection^ Create(SafeHandle^ owner, TranslationUnitHandle^ transunit, CXDiagnosticSet diagnostics);

private:

	// DiagnosticSetReferenceHandle
	//
	// TranslationUnitReferenceHandle specialization for CXDiagnosticSet
	using DiagnosticSetReferenceHandle = TranslationUnitReferenceHandle<CXDiagnosticSet>;

	// Instance Constructor
	//
	DiagnosticChildCollection(DiagnosticSetReferenceHandle^ handle);

	//-----------------------------------------------------------------------
	// Member Variables

	DiagnosticSetReferenceHandle^	m_handle;		// Diagnostic set handle
	array<Diagnostic^>^				m_cache;		// Collection element cache
};

//---------------------------------------------------------------------------

} // zuki::tools::llvm::clang

#pragma warning(pop)

#endif	// __DIAGNOSTICCHILDCOLLECTION_H_


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

namespace VoiceChat
{
    public class VoiceChatCircularBuffer<T>
    {
        int capacity;
        int count;
        int head;
        int tail;
        T[] buffer;

        public bool HasItems
        {
            get { return count > 0; }
        }

        public int TailIndex
        {
            get { return tail; }
        }

        public T[] Data
        {
            get { return buffer; }
        }

        public int Count
        {
            get { return count; }
        }

        public int Capacity
        {
            get { return capacity; }
        }

        public VoiceChatCircularBuffer(int maxCapacity)
        {
            capacity = maxCapacity;
            buffer = new T[capacity];
        }

        public void Add(T item)
        {
            if (count == capacity && head == tail)
            {
                if (++tail == capacity)
                {
                    tail = 0;
                }
            }

            buffer[head] = item;

            if (++head == capacity)
            {
                head = 0;
            }

            count = Math.Min(capacity, count + 1);
        }

        public T Remove()
        {
            if (count == 0)
            {
                throw new ArgumentOutOfRangeException();
            }

            T item = buffer[tail];

            if (++tail == capacity)
            {
                tail = 0;
            }

            --count;

            return item;
        }

        public bool NextIndex(ref int value)
        {
            if (++value == capacity)
            {
                value = 0;
            }

            return value != head;
        }
    }

}


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

using System.Text;

namespace DomainCQRS.Common
{
	/// <summary>
	/// For when an item is removed from a <see cref="IDicionary"/>
	/// </summary>
	/// <typeparam name="TKey">The key</typeparam>
	/// <typeparam name="TValue">The value</typeparam>
	public class KeyValueRemovedArgs<TKey, TValue> : EventArgs
	{
		public TKey Key { get; set; }
		public TValue Value { get; set; }
	}
}


text:
<?php

namespace Nimbu\NotificacionBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * UsuarioNegocio
 *
 * @ORM\Table(name="usuario_negocio", indexes={@ORM\Index(name="usuario_id", columns={"usuario_id"}), @ORM\Index(name="negocio_id", columns={"negocio_id"})})
 * @ORM\Entity
 */
class UsuarioNegocio
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var \Usuario
     *
     * @ORM\ManyToOne(targetEntity="Usuario")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="usuario_id", referencedColumnName="id")
     * })
     */
    private $usuario;

    /**
     * @var \Negocio
     *
     * @ORM\ManyToOne(targetEntity="Negocio")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="negocio_id", referencedColumnName="id")
     * })
     */
    private $negocio;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set usuario
     *
     * @param \Nimbu\NotificacionBundle\Entity\Usuario $usuario
     * @return UsuarioNegocio
     */
    public function setUsuario(\Nimbu\NotificacionBundle\Entity\Usuario $usuario = null)
    {
        $this->usuario = $usuario;

        return $this;
    }

    /**
     * Get usuario
     *
     * @return \Nimbu\NotificacionBundle\Entity\Usuario
     */
    public function getUsuario()
    {
        return $this->usuario;
    }

    /**
     * Set negocio
     *
     * @param \Nimbu\NotificacionBundle\Entity\Negocio $negocio
     * @return UsuarioNegocio
     */
    public function setNegocio(\Nimbu\NotificacionBundle\Entity\Negocio $negocio = null)
    {
        $this->negocio = $negocio;

        return $this;
    }

    /**
     * Get negocio
     *
     * @return \Nimbu\NotificacionBundle\Entity\Negocio
     */
    public function getNegocio()
    {
        return $this->negocio;
    }
}


text:
layout: post
title: A Holy Doubt
---

> Eventually my fifth-grade dream, along with many others, evaporated completely, and today I am a preacher. I have a family. I live in LA. I am a Christian. I teach the Bible at a church we started in 2006. Nothing could be more different from what I pictured for myself earlier on in life. And the truth is, I couldn't be more satisfied and more at peace. And that is because God taught me to doubt.
>
> Yes, doubt.
>
> Most people would not associate doubt with Christian faith, but there is a kind of holy doubt, a sacred skepticism that asks hard questions about life. While many people spend time questioning the Bible, it may come as a surprise that the Bible actually questions us:
>
> - What do you expect out of life?
> - What if your expectations are wrong?
> - Where did your expectations come from?
>
> —**Tim Chaddick**. *Better*.

Tim Chaddick's experience forced him to doubt himself and his expectations. This exploration led Him to discover Jesus and the fulfilling life that He has to offer. As Christians we shy away from doubt of any kind, when in actuality we should be given to this "*holy doubt*" as away to see how our false expectations and false hopes don't line up with the life that God has intended for us.

Chaddick continues with this challenging question:

> Are you willing to have your script reworked?

This simple question sets the trajectory for our entire lives and leaves us with a pressing challenge: are we going to accept and embrace the script that God has written for us? Are we willing to follow Jesus, whatever the cost?


text:
var fs = require('fs')
  , f = require('util').format;

/**
 * @ignore
 */
exports['Should correctly authenticate using x509'] = function(configuration, test) {
  var ServerManager = require('../../tools/server_manager').ServerManager
    , MongoClient = configuration.getMongoPackage().MongoClient;

  // All inserted docs
  var docs = [];
  var errs = [];
  var insertDocs = [];

  // Read the cert and key
  var cert = fs.readFileSync(__dirname + "/certificates/x509/client.pem");
  var key = fs.readFileSync(__dirname + "/certificates/x509/client.pem");

  // User name
  var userName = "CN=client,OU=kerneluser,O=10Gen,L=New York City,ST=New York,C=US";

  // Start server
  serverManager = new ServerManager({
      auth:true
    , purgedirectories:true
    , journal:true
    , ssl:true
    , ssl_ca: '../test/tests/ssl/certificates/x509/ca.pem'
    , ssl_crl: '../test/tests/ssl/certificates/x509/crl.pem'
    , ssl_server_pem: "../test/tests/ssl/certificates/x509/server.pem"
    , ssl_weak_certificate_validation: true
    // EnsureUp options
    , host: 'server'
  });

  serverManager.start(true, function() {
    // Connect and validate the server certificate
    MongoClient.connect("mongodb://server:27017/test?ssl=true&maxPoolSize=1", {
      server: {
          sslKey:key
        , sslCert:cert
      }
    }, function(err, db) {
      test.equal(null, err);
      test.ok(db != null);

      // Execute build info
      db.command({buildInfo:1}, function(err, result) {
        test.equal(null, err);
        var version = parseInt(result.versionArray.slice(0, 3).join(""), 10);
        if(version < 253) {
          db.close();
          return test.done();
        }

        // Add the X509 auth user to the $external db
        var ext = db.db('$external');
        ext.addUser(userName, {roles: [
          {'role': 'readWriteAnyDatabase', 'db': 'admin'},
          {'role': 'userAdminAnyDatabase', 'db': 'admin'}
        ]}, function(err, result) {
          test.equal(null, err);
          test.equal(userName, result[0].user);
          test.equal('', result[0].pwd);
          db.close();

          // Connect using X509 authentication
          MongoClient.connect(f('mongodb://%s@server:27017/test?authMechanism=%s&ssl=true&maxPoolSize=1'
              , encodeURIComponent(userName), 'MONGODB-X509'), {
            server: {
                sslKey:key
              , sslCert:cert
            }
          }, function(err, db) {
            test.equal(null, err);
            test.ok(db != null);

            db.close();
            serverManager.killAll();
            test.done();
          });
        });
      });
    });
  });
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<?xml-model href="http://www.stoa.org/epidoc/schema/latest/tei-epidoc.rng" schematypens="http://relaxng.org/ns/structure/1.0"?>
<?xml-model href="http://www.stoa.org/epidoc/schema/dev/ircyr-checking.sch" schematypens="http://purl.oclc.org/dsdl/schematron"?>
<?xml-model href="http://www.stoa.org/epidoc/schema/latest/tei-epidoc.rng" schematypens="http://purl.oclc.org/dsdl/schematron"?>
<TEI xmlns="http://www.tei-c.org/ns/1.0" xml:id="C49000" xml:lang="en">
   <teiHeader>
      <fileDesc>
         <titleStmt>
            <title><rs type="textType">Funerary</rs> fragment</title>
            <editor>Joyce M. Reynolds</editor>
         </titleStmt>
         <publicationStmt>
            <authority>Centre for Computing in the Humanities, King's College London</authority>
            <idno type="filename">C49000</idno>
            <idno type="JMR">1084</idno>
            <idno type="Excel">217</idno>
            <availability>

Creative Commons licence Attribution UK 2.0
                    (<ref>http://creativecommons.org/licenses/by/2.0/uk/</ref>)

All reuse or distribution of this work must contain somewhere a link back to the
                    URL <ref>http://inslib.kcl.ac.uk/</ref>

            </availability>
         </publicationStmt>
         <sourceDesc>
            <msDesc>
               <msIdentifier><msName>n/a</msName></msIdentifier>
               <physDesc>
                  <objectDesc>
                     <supportDesc>
                        <support>

Fragment from the lower part of a <material>limestone</material> <objectType>stele</objectType>
                              (<dimensions>
                                 <width>0.21</width>
                                 <height>0.19</height>
                                 <depth>0.10</depth>
                              </dimensions>).

                        </support>
                     </supportDesc>
                     <layoutDesc>
                        <layout><rs type="execution" key="scalpro">Inscribed</rs> on one face within an incised panel
                           (<dimensions>
                              <width>0.14</width>
                              <height>0.115</height>
                           </dimensions>).</layout>
                     </layoutDesc>
                  </objectDesc>
                  <handDesc>
                     <handNote><height>0.02</height>, between incised guidelines.</handNote>
                  </handDesc>
               </physDesc>
               <history>
                  <origin>
                     <origPlace>Unknown.</origPlace>
                     <origDate notBefore="0001" notAfter="0300" precision="low" evidence="lettering">First - third century A.D.</origDate>
                  </origin>

                        <provenance type="found">

                              <placeName type="ancientFindspot" ref="http://pleiades.stoa.org/places/373778" key="db909">Cyrene</placeName>:
                              findspot unrecorded; found <date type="found">before 1941</date>.

                        </provenance>
                        <provenance type="observed">

                              <rs type="monuList" key="db933">Cyrene Museum</rs>.

                        </provenance>

               </history>
            </msDesc>
         </sourceDesc>
      </fileDesc>
      <encodingDesc>

Marked-up according to the EpiDoc Guidelines version 8

      <classDecl><taxonomy><category xml:id="photograph"><catDesc>Digital or digitized photographs</catDesc></category><category xml:id="representation"><catDesc>Digitized other representations</catDesc></category></taxonomy></classDecl></encodingDesc>
      <profileDesc>
         <langUsage>
            <language ident="ar">Arabic</language>
            <language ident="en">English</language>
            <language ident="fr">French</language>
            <language ident="de">German</language>
            <language ident="grc">Ancient Greek</language>
            <language ident="grc-Latn">Transliterated Greek</language>
            <language ident="el">Modern Greek</language>
            <language ident="he">Hebrew</language>
            <language ident="it">Italian</language>
            <language ident="la">Latin</language>
         </langUsage>
         <textClass/>
         <textClass>
            <keywords scheme="IRCyr">
               <term>
                        <geogName type="ancientRegion" key="Cyrene">Cyrenaica</geogName>
                    </term>
               <term>
                        <geogName type="modernCountry" key="LY">Libya</geogName>
                    </term>
               <term>
                        <placeName type="modernFindspot" ref="http://sws.geonames.org/82972">Shahat</placeName>
                    </term>
            </keywords>
         </textClass>
      <creation>Transcription (Reynolds).</creation></profileDesc>
      <revisionDesc>
         <change when="2012-11-05" who="GB">moved text-constituted-from to profileDesc/creation</change>
         <change when="2012-10-16" who="GB">broke provenance events into multiple provenance elements</change>
         <change when="2010-08-04" who="GB">Converted from TEI P4 (EpiDoc DTD v. 6) to P5 (EpiDoc RNG schema v. 8)</change>
         <change when="2010-03-15" who="GillianB">tokenized</change>
         <change when="2009-07-10" who="Pietro">turned to XML and tidied</change>
         <change when="2009-05-11" who="GB">mailmerged: created from template</change>
      </revisionDesc>
   </teiHeader><facsimile><graphic url="JMR_1162front" decls="#photograph"><desc><ref type="inscription">C49000</ref>, <ref type="inscription">C60600</ref> and
      <ref type="inscription">CG01900</ref></desc></graphic>
      <graphic url="JMR_1084front" decls="#photograph"><desc>Face (Reynolds VI.54)</desc></graphic></facsimile>
   <text>

            Bibliography

<ab>
                    <lb n="0"/><gap reason="lost" extent="unknown" unit="line"/>
                    <lb n="1"/><persName type="attested"><name nymRef="Εὐ-"><seg part="I">Εὐ</seg></name><gap reason="lost" extent="unknown" unit="character"/>
                    <lb n="2"/><persName type="attested"><name nymRef="Ἰούλιος">Ἰουλ<supplied reason="lost" cert="low">ίου</supplied></name></persName></persName>
                    <lb n="3"/><date dur="P16Y"><num value="16">ις</num> </date>
                </ab>

Translation

            Commentary

Aged 16.

   </text>
</TEI>


text:
package net.prank.tools;

import org.junit.Test;

import java.util.HashSet;
import java.util.Set;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;

/**
 * Created by dave on 5/2/17.
 */
public class ScoringRangeTest {

    @Test
    public void test_aboveRange() {

        ScoringRange range = new ScoringRange(0.0, 5.0, 1.0);
        assertTrue(range.aboveRange(6.0));
        assertFalse(range.aboveRange(4.0));
    }

    @Test
    public void test_belowRange() {

        ScoringRange range = new ScoringRange(0.0, 5.0, 1.0);
        assertTrue(range.belowRange(-1.0));
        assertFalse(range.belowRange(4.0));
    }

    @Test
    public void test_equals() {

        ScoringRange rangeOne = new ScoringRange(0.0, 1.0, 5.0);
        ScoringRange rangeTwo = new ScoringRange(0.0, 1.0, 5.0);
        assertEquals(rangeOne, rangeTwo);
        assertEquals(rangeOne, rangeOne);
    }

    @Test
    public void test_equals_not() {

        ScoringRange rangeOne = new ScoringRange(0.0, 1.0, 5.0);
        ScoringRange rangeTwo = new ScoringRange(0.0, 2.0, 4.0);
        ScoringRange rangeThree = new ScoringRange(-1.0, 3.0, 6.0);
        ScoringRange rangeFour = new ScoringRange(1.0, 1.0, 5.0);
        assertNotEquals(rangeOne, rangeTwo);
        assertNotEquals(rangeOne, rangeThree);
        assertNotEquals(rangeOne, rangeFour);
        assertNotEquals(rangeOne, "foo");
        assertNotEquals(rangeOne, null);
    }

    @Test
    public void test_hashCode() {

        ScoringRange rangeOne = new ScoringRange(0.0, 1.0, 5.0);
        ScoringRange rangeTwo = new ScoringRange(0.0, 1.0, 4.0);
        Set<ScoringRange> ranges = new HashSet<>();
        ranges.add(rangeOne);
        ranges.add(rangeTwo);
        assertEquals(2, ranges.size());
    }

    @Test
    public void test_toString() {

        ScoringRange rangeOne = new ScoringRange(0.0, 1.0, 5.0);
        assertEquals("ScoringRange{_min=0.0, _max=1.0, _scorePoints=5.0}", rangeOne.toString());
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.resourcemanager.perf;

import com.azure.perf.test.core.PerfStressProgram;
import com.azure.resourcemanager.perf.dns.CreateDnsZonesTest;
import com.azure.resourcemanager.perf.resources.ListResourceGroupsTest;
import com.azure.resourcemanager.perf.resources.ListSubscriptionsTest;
import com.azure.resourcemanager.perf.resources.ListTenantsTest;
import com.azure.resourcemanager.perf.storage.CreateStorageAccountsTest;

/**
 * Runs the resource manager performance test.
 *
 *
To run from command line. Package the project into a jar with dependencies via mvn clean package.
 * Then run the program via java -jar 'compiled-jar-with-dependencies-path'

 *
 *
 To run from IDE, set all the required environment variables in IntelliJ via Run -> EditConfigurations section.
 * Then run the App's main method via IDE.

 */
public class App {
    public static void main(String[] args) {
        PerfStressProgram.run(new Class<?>[]{
            CreateDnsZonesTest.class,
            CreateStorageAccountsTest.class,
            ListResourceGroupsTest.class,
            ListSubscriptionsTest.class,
            ListTenantsTest.class
        }, args);
    }
}


text:
using System;
using System.Text;

using ZXing.Common;

namespace ZXing.OneD
{
   ///
   ///
Implements decoding of the UPC-E format.

   ///

   ///
Thisis a great reference for
   /// UPC-E information.

   ///   <author>Sean Owen</author>
   ///
   public sealed class UPCEReader : UPCEANReader
   {
      ///
      /// The pattern that marks the middle, and end, of a UPC-E pattern.
      /// There is no "second half" to a UPC-E barcode.
      ///
      private static readonly int[] MIDDLE_END_PATTERN = { 1, 1, 1, 1, 1, 1 };

      ///
      /// See L_AND_G_PATTERNS these values similarly represent patterns of
      /// even-odd parity encodings of digits that imply both the number system (0 or 1)
      /// used, and the check digit.
      ///
      private static readonly int[][] NUMSYS_AND_CHECK_DIGIT_PATTERNS = {
                                                                  new[] { 0x38, 0x34, 0x32, 0x31, 0x2C, 0x26, 0x23, 0x2A, 0x29, 0x25 },
                                                                  new[] { 0x07, 0x0B, 0x0D, 0x0E, 0x13, 0x19, 0x1C, 0x15, 0x16, 0x1A }
                                                               };

      private readonly int[] decodeMiddleCounters;

      ///
      /// Initializes a new instance of the <see cref="UPCEReader"/> class.
      ///
      public UPCEReader()
      {
         decodeMiddleCounters = new int[4];
      }

      ///
      /// Decodes the middle.
      ///
      /// <param name="row">The row.</param>
      /// <param name="startRange">The start range.</param>
      /// <param name="result">The result.</param>
      /// <returns></returns>
      override internal protected int decodeMiddle(BitArray row, int[] startRange, StringBuilder result)
      {
         int[] counters = decodeMiddleCounters;
         counters[0] = 0;
         counters[1] = 0;
         counters[2] = 0;
         counters[3] = 0;
         int end = row.Size;
         int rowOffset = startRange[1];

         int lgPatternFound = 0;

         for (int x = 0; x < 6 && rowOffset < end; x++)
         {
            int bestMatch;
            if (!decodeDigit(row, counters, rowOffset, L_AND_G_PATTERNS, out bestMatch))
               return -1;
            result.Append((char)('0' + bestMatch % 10));
            foreach (int counter in counters)
            {
               rowOffset += counter;
            }
            if (bestMatch >= 10)
            {
               lgPatternFound |= 1 << (5 - x);
            }
         }

         if (!determineNumSysAndCheckDigit(result, lgPatternFound))
            return -1;

         return rowOffset;
      }

      ///
      /// Decodes the end.
      ///
      /// <param name="row">The row.</param>
      /// <param name="endStart">The end start.</param>
      /// <returns></returns>
      override protected int[] decodeEnd(BitArray row, int endStart)
      {
         return findGuardPattern(row, endStart, true, MIDDLE_END_PATTERN);
      }

      ///
      ///   <returns>see checkStandardUPCEANChecksum(String)</returns>
      ///
      /// <param name="s"></param>
      /// <returns></returns>
      override protected bool checkChecksum(String s)
      {
         return base.checkChecksum(convertUPCEtoUPCA(s));
      }

      ///
      /// Determines the num sys and check digit.
      ///
      /// <param name="resultString">The result string.</param>
      /// <param name="lgPatternFound">The lg pattern found.</param>
      /// <returns></returns>
      private static bool determineNumSysAndCheckDigit(StringBuilder resultString, int lgPatternFound)
      {

         for (int numSys = 0; numSys <= 1; numSys++)
         {
            for (int d = 0; d < 10; d++)
            {
               if (lgPatternFound == NUMSYS_AND_CHECK_DIGIT_PATTERNS[numSys][d])
               {
                  resultString.Insert(0, new[] { (char)('0' + numSys) });
                  resultString.Append((char)('0' + d));
                  return true;
               }
            }
         }
         return false;
      }

      ///
      /// Get the format of this decoder.
      /// <returns>The 1D format.</returns>
      ///
      override internal BarcodeFormat BarcodeFormat
      {
         get { return BarcodeFormat.UPC_E; }
      }

      ///
      /// Expands a UPC-E value back into its full, equivalent UPC-A code value.
      ///
      /// <param name="upce">UPC-E code as string of digits</param>
      /// <returns>equivalent UPC-A code as string of digits</returns>
      ///
      public static String convertUPCEtoUPCA(String upce)
      {
         var upceChars = upce.Substring(1, 6);
         StringBuilder result = new StringBuilder(12);
         result.Append(upce[0]);
         char lastChar = upceChars[5];
         switch (lastChar)
         {
            case '0':
            case '1':
            case '2':
               result.Append(upceChars, 0, 2);
               result.Append(lastChar);
               result.Append("0000");
               result.Append(upceChars, 2, 3);
               break;
            case '3':
               result.Append(upceChars, 0, 3);
               result.Append("00000");
               result.Append(upceChars, 3, 2);
               break;
            case '4':
               result.Append(upceChars, 0, 4);
               result.Append("00000");
               result.Append(upceChars[4]);
               break;
            default:
               result.Append(upceChars, 0, 5);
               result.Append("0000");
               result.Append(lastChar);
               break;
         }
         result.Append(upce[7]);
         return result.ToString();
      }
   }
}


text:
<?php

declare(strict_types=1);

namespace App\Model;

use Nette;
use Nette\Utils\FileSystem;

/**
 * Tool for reading and writing text files.
 */
class FileManager {

	use Nette\SmartObject;

	/**
	 * @var string
	 */
	private $configDir;

	/**
	 * Constructor
	 * @param string $configDir Directory with files
	 */
	public function __construct(string $configDir) {
		$this->configDir = $configDir;
	}

	/**
	 * Read file
	 * @param string $fileName File name
	 * @return string File content
	 */
	public function read(string $fileName) {
		return FileSystem::read($this->configDir . '/' . $fileName);
	}

	/**
	 * Encode JSON from array and write JSON file
	 * @param string $fileName File name
	 * @param array $content File content
	 */
	public function write(string $fileName, $content) {
		$fileName = 'nette.safe://' . $this->configDir . '/' . $fileName;
		FileSystem::write($fileName, $content, null);
	}

}


text:
import React from 'react';
import PropTypes from 'prop-types';

import Icon from './Icon';

const Header = ({ showRefreshButton, handleRefresh }) => (
  <header
    className="header"
  >
    <div className="header__content">
      <h1
        className="header__content__title"
      >
        Lunchroulette
      </h1>

      {showRefreshButton &&
        <button
          className="header__content__reload"
          onClick={handleRefresh}
        >
          <Icon
            name="refresh"
          />
        </button>
      }
    </div>
  </header>
);

Header.propTypes = {
  showRefreshButton: PropTypes.bool.isRequired,
  handleRefresh: PropTypes.func.isRequired
};

export default Header;


text:
@protocol WaterFLayoutDelegate<NSObject>
@required
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath;
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section;
@end
@interface MyLayout : UICollectionViewLayout
{
    float x;
    float leftY;
    float rightY;
}
@property(nonatomic,assign)UIEdgeInsets sectionInset;
@property(nonatomic,weak)id<WaterFLayoutDelegate> delegate;

@end


text:
.drag-drop-cursor {
    position: absolute;
    border-left: 2px solid #696969;
}

.panel-heading.no-background {
    background: transparent;
}
.wiki-panel-header {
    height: 50px;
}
.markdown-it-view {
    padding: 10px;
    height: auto;
}
.wiki-compare-view {
    white-space: pre-wrap;
    padding: 10px;
}
.panel-collapsed {
    background: #F5F5F5;
    height: auto;
}
.wiki-sidenav h4, .wiki-sidenav li>ul>.btn,  .osf-sidenav.wiki-sidenav ul>li .row {
    padding: 8px 15px;
    margin-top: 2px;
}
.wiki-sidenav h4 {
    margin-top:20px;
    margin-bottom: 0;
    font-weigth: normal;
}
.osf-sidenav.wiki-sidenav ul>li a:hover {
    background: transparent;
}
.osf-sidenav.wiki-sidenav ul>li:hover {
    background: #f5f5f5;
}
.osf-sidenav.wiki-sidenav ul>li.active a {
    line-height: 26px;
}
.osf-sidenav.wiki-sidenav ul>li.active, .osf-sidenav.wiki-sidenav ul>li.active:hover {
    background: #f5f5f5;
    border-left: 2px solid #337AB7;
}
.osf-sidenav.wiki-sidenav ul>li.active a {
    border-right: none;
    color: #337AB7;
}
.osf-sidenav.wiki-sidenav h4 a:hover {
    text-decoration: none;
}
.osf-sidenav.wiki-sidenav ul>li a:hover {
    text-decoration: none;
}

/* Changes to default icons to be consistent with the grey look of many new ui items */
.btn-default-alt {
    background: #EFEFEF;
}
.btn-success-alt {
    background: #D9E8D9;
}
.addon-external-link:hover,
.addon-external-link:focus {
    text-decoration: none !important;
}

/*Special for wiki panel */
.osf-panel-flex {
    width: 100%;
    display: -webkit-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    height: 764px;
    -webkit-align-content: flex-start;
    -ms-align-content: flex-start;
    align-content: flex-start;
    -webkit-flex-direction: column;
    -ms-flex-direction: column;
    flex-direction: column;
    -webkit-box-align: stretch;
    -webkit-align-items: stretch;
    -ms-flex-align: stretch;
    align-items: stretch;
    -webkit-flex-wrap: wrap;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
}
.osf-panel-heading-flex {
    width: 100%;
    margin: auto;
    -webkit-box-flex: 0 0 auto;
    -webkit-flex: 0 0 auto;
    -ms-flex: 0 0 auto;
    flex: 0 0 auto;
}
.osf-panel-body-flex {
    width: 100%;
    margin: auto;
    -webkit-box-flex: 3 0 auto;
    -webkit-flex: 3 0 auto;
    -ms-flex: 3 0 auto;
    flex: 3 0 auto;
    height: 500px;
    overflow: auto;
}
.osf-panel .superlist li {
    display: block;
    font-size: 20px;
}
.superlist li {
    display: inline-block;
    float: none;
}
.superlist li a {
    padding: 15px 10px;
}

@media (max-width: 768px) {
 .superlist.navbar-nav {
    margin: 0;
 }
}

/* Style for Ace wiki editor */
.wiki-editor {
    position: relative;
    border: solid;
    border-width: 1px;
    width: 100%;
    margin: auto;
    -webkit-box-flex: 3 0 auto;
    -webkit-flex: 3 0 auto;
    -ms-flex: 3 0 auto;
    flex: 3 0 auto;
    height: 400px; /* this will get overwritten by flex box */
}

/* Make wiki images responsive */
.wiki img{
    vertical-align: middle;
    display: block;
    max-width: 100%;
    height: auto;
}
.wiki-title {
    line-height: 36px;
    border-bottom: none;
    margin-top: 0.2em;
    margin-bottom: 20px;
}

/* Extra small devices */
@media (max-width: 767px) {
    .wiki-title-xs {
        font-size: 20px;
        line-height: 20px;
    }
    .wiki-status-sm {
        float: none;
        text-align: center;
        margin-top: 20px;
    }
}
@media (min-width: 768px) {
    .wiki-status-lg {
        float: right;
        margin-left: 20px;
        display: inline-block;
    }
}

.wiki-title-container {
    display: inline-block;
    width:60%;
}
.wiki-nav-closed .icon-stack-base {
    font-size: 20px;
}
.wiki-nav-closed .icon-plus {
    margin-left: -14px;
    font-size: 12px;
}
.wiki-component {
    list-style-type: none;
    padding-right: 20px;
}
.wiki-component li {
    margin-bottom: 8px;
}

/* Markdown editing */
.wmd-panel {
    width: 100%;
    display: -webkit-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    height: 620px;
    -webkit-align-content: flex-start;
    -ms-align-content: flex-start;
    align-content: flex-start;
    -webkit-flex-direction: column;
    -ms-flex-direction: column;
    flex-direction: column;
    -webkit-box-align: stretch;
    -webkit-align-items: stretch;
    -ms-flex-align: stretch;
    align-items: stretch;
    -webkit-flex-wrap: wrap;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
}
.wmd-panel .list-inline {
    width: 100%;
    margin: auto;
    -webkit-box-flex: 0 0 auto;
    -webkit-flex: 0 0 auto;
    -ms-flex: 0 0 auto;
    flex: 0 0 auto;
}
.wiki-view-icon-container  /* this keeps the container of the view icon and dropdown responsive */
{
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    -webkit-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
}
.wmd-button-bar {
    width: 100%;
    background-color: Silver;
}
#wmd-button-bar {
    margin: auto;
    -webkit-box-flex: 0 0 auto;
    -webkit-flex: 0 0 auto;
    -ms-flex: 0 0 auto;
    flex: 0 0 auto;
}
.wmd-input {
    border: 1px solid DarkGray;
}
.wmd-button-row {
    position: relative;
    margin-left: 0;
    margin-right: 0;
    margin-bottom: 5px;
    margin-top: 0px;
    padding: 0px;
}
.wmd-spacer {
    width: 1px;
    height: 20px;
    margin-left: 14px;
    background-color: Silver;
    display: inline-block;
    list-style: none;
}
.wmd-button {
    width: 20px;
    height: 20px;
    padding-left: 2px;
    padding-right: 3px;
    display: inline-block;
    list-style: none;
    cursor: pointer;
}
.wmd-button > span {
    background-image: url(/static/public/vendor/pagedown/wmd-buttons.png);
    background-repeat: no-repeat;
    background-position: 0px 0px;
    width: 20px;
    height: 20px;
    display: inline-block;
}
.wmd-spacer1 {
    left: 50px;
}
.wmd-spacer2 {
    left: 175px;
}
.wmd-spacer3 {
    left: 300px;
}
.wmd-prompt-background {
    background-color: Black;
}
.wmd-prompt-dialog {
    border: 1px solid #999999;
    background-color: #F5F5F5;
}
#wmd-autocom-toggle {
    margin-left:5px;
    list-style: none;
    display: inline-block;

}
.wiki-single-heading {
    border: 1px solid #ddd;
}
select.form-control {
    padding:1px;
    display: inline;
    height: 24px;
    font-size: 13px;
}
.wiki-toolbar-icon {
    padding: 5px 10px;
    display: inline-block;
    box-shadow: 0 0 2px #BBB;
    background: #F8F8F8;
    margin-right: 5px;
    cursor: pointer;
    font-size: 13px;
    border-radius: 2px;
    float: left;
}
.wiki-toolbar-icon .fa {
    font-size: 15px;
}
.wiki-toolbar-icon span {
    margin-left: 5px;
}
.wiki-toolbar-icon:hover {
  background: rgba(51, 122, 183, 0.15);
}

.absolute-center{
    display: none;
    position: absolute;
    -webkit-transform:translateY(-50%);
    -webkit-transform:translateX(-50%);
    transform:translateY(-50%);
    transform:translateX(-50%);
    left: 50%;
    top:50%;
    z-index: 1;
}


text:
DEBUG = True
SECRET_KEY = 'todo-app-secret-key'

SQLALCHEMY_DATABASE_URI = 'sqlite:///appdata.db'

SECURITY_PASSWORD_HASH = 'pbkdf2_sha512'
SECURITY_PASSWORD_SALT = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

# SMTP Settings
SECURITY_EMAIL_SENDER = 'no-reply@example.com'
MAIL_SERVER = 'localhost'
MAIL_PORT = 1025
MAIL_USE_SSL = False
MAIL_USERNAME = ''
MAIL_PASSWORD = ''

# Flask-Security Settings
SECURITY_REGISTERABLE = True
SECURITY_CONFIRMABLE = True
SECURITY_RECOVERABLE = True


text:
PhotoGallery
============

"Android Programming: The Big Nerd Ranch Guide" Chapter 26-29 Example App


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Diagnostics
{
    /// <summary>
    /// Provides and caches information about diagnostic analyzers such as <see cref="AnalyzerReference"/>,
    /// <see cref="DiagnosticAnalyzer"/> instance, <see cref="DiagnosticDescriptor"/>s.
    /// Thread-safe.
    /// </summary>
    internal sealed partial class DiagnosticAnalyzerInfoCache
    {
        /// <summary>
        /// Supported descriptors of each <see cref="DiagnosticAnalyzer"/>.
        /// </summary>
        /// <remarks>
        /// Holds on <see cref="DiagnosticAnalyzer"/> instances weakly so that we don't keep analyzers coming from package references alive.
        /// They need to be released when the project stops referencing the analyzer.
        ///
        /// The purpose of this map is to avoid multiple calls to <see cref="DiagnosticAnalyzer.SupportedDiagnostics"/> that might return different values
        /// (they should not but we need a guarantee to function correctly).
        /// </remarks>
        private readonly ConditionalWeakTable<DiagnosticAnalyzer, DiagnosticDescriptorsInfo> _descriptorsInfo;

        private sealed class DiagnosticDescriptorsInfo
        {
            public readonly ImmutableArray<DiagnosticDescriptor> SupportedDescriptors;
            public readonly bool TelemetryAllowed;
            public readonly bool HasCompilationEndDescriptor;

            public DiagnosticDescriptorsInfo(ImmutableArray<DiagnosticDescriptor> supportedDescriptors, bool telemetryAllowed)
            {
                SupportedDescriptors = supportedDescriptors;
                TelemetryAllowed = telemetryAllowed;
                HasCompilationEndDescriptor = supportedDescriptors.Any(DiagnosticDescriptorExtensions.IsCompilationEnd);
            }
        }

        internal DiagnosticAnalyzerInfoCache()
        {
            _descriptorsInfo = new ConditionalWeakTable<DiagnosticAnalyzer, DiagnosticDescriptorsInfo>();
        }

        /// <summary>
        /// Returns <see cref="DiagnosticAnalyzer.SupportedDiagnostics"/> of given <paramref name="analyzer"/>.
        /// </summary>
        public ImmutableArray<DiagnosticDescriptor> GetDiagnosticDescriptors(DiagnosticAnalyzer analyzer)
            => GetOrCreateDescriptorsInfo(analyzer).SupportedDescriptors;

        /// <summary>
        /// Returns <see cref="DiagnosticAnalyzer.SupportedDiagnostics"/> of given <paramref name="analyzer"/>
        /// that are not compilation end descriptors.
        /// </summary>
        public ImmutableArray<DiagnosticDescriptor> GetNonCompilationEndDiagnosticDescriptors(DiagnosticAnalyzer analyzer)
        {
            var descriptorInfo = GetOrCreateDescriptorsInfo(analyzer);
            return !descriptorInfo.HasCompilationEndDescriptor
                ? descriptorInfo.SupportedDescriptors
                : descriptorInfo.SupportedDescriptors.WhereAsArray(d => !d.IsCompilationEnd());
        }

        /// <summary>
        /// Returns true if given <paramref name="analyzer"/> has a compilation end descriptor
        /// that is reported in the Compilation end action.
        /// </summary>
        public bool IsCompilationEndAnalyzer(DiagnosticAnalyzer analyzer)
            => GetOrCreateDescriptorsInfo(analyzer).HasCompilationEndDescriptor;

        /// <summary>
        /// Determine whether collection of telemetry is allowed for given <paramref name="analyzer"/>.
        /// </summary>
        public bool IsTelemetryCollectionAllowed(DiagnosticAnalyzer analyzer)
            => GetOrCreateDescriptorsInfo(analyzer).TelemetryAllowed;

        private DiagnosticDescriptorsInfo GetOrCreateDescriptorsInfo(DiagnosticAnalyzer analyzer)
            => _descriptorsInfo.GetValue(analyzer, CalculateDescriptorsInfo);

        private DiagnosticDescriptorsInfo CalculateDescriptorsInfo(DiagnosticAnalyzer analyzer)
        {
            ImmutableArray<DiagnosticDescriptor> descriptors;
            try
            {
                // SupportedDiagnostics is user code and can throw an exception.
                descriptors = analyzer.SupportedDiagnostics.NullToEmpty();
            }
            catch
            {
                // No need to report the exception to the user.
                // Eventually, when the analyzer runs the compiler analyzer driver will report a diagnostic.
                descriptors = ImmutableArray<DiagnosticDescriptor>.Empty;
            }

            var telemetryAllowed = IsTelemetryCollectionAllowed(analyzer, descriptors);
            return new DiagnosticDescriptorsInfo(descriptors, telemetryAllowed);
        }

        private static bool IsTelemetryCollectionAllowed(DiagnosticAnalyzer analyzer, ImmutableArray<DiagnosticDescriptor> descriptors)
            => analyzer.IsCompilerAnalyzer() ||
               analyzer is IBuiltInAnalyzer ||
               descriptors.Length > 0 && descriptors[0].ImmutableCustomTags().Any(t => t == WellKnownDiagnosticTags.Telemetry);

        /// <summary>
        /// Return true if the given <paramref name="analyzer"/> is suppressed for the given project.
        /// NOTE: This API is intended to be used only for performance optimization.
        /// </summary>
        public bool IsAnalyzerSuppressed(DiagnosticAnalyzer analyzer, Project project)
        {
            var options = project.CompilationOptions;
            if (options == null || analyzer == FileContentLoadAnalyzer.Instance || analyzer.IsCompilerAnalyzer())
            {
                return false;
            }

            // If user has disabled analyzer execution for this project, we only want to execute required analyzers
            // that report diagnostics with category "Compiler".
            if (!project.State.RunAnalyzers &&
                GetDiagnosticDescriptors(analyzer).All(d => d.Category != DiagnosticCategory.Compiler))
            {
                return true;
            }

            // NOTE: Previously we used to return "CompilationWithAnalyzers.IsDiagnosticAnalyzerSuppressed(options)"
            //       on this code path, which returns true if analyzer is suppressed through compilation options.
            //       However, this check is no longer correct as analyzers can be enabled/disabled for individual
            //       documents through .editorconfig files. So we pessimistically assume analyzer is not suppressed
            //       and let the core analyzer driver in the compiler layer handle skipping redundant analysis callbacks.
            return false;
        }
    }
}


text:
require 'spec_helper'
#
# resent-cc       =       "Resent-Cc:" address-list CRLF

describe Mail::ResentCcField do

  describe "initialization" do

    it "should initialize" do
      expect { Mail::ResentCcField.new("Resent-Cc: Mikel") }.not_to raise_error
    end

    it "should mix in the CommonAddress module" do
      expect(Mail::ResentCcField.included_modules).to include(Mail::CommonAddress)
    end

    it "should accept a string with the field name" do
      t = Mail::ResentCcField.new('Resent-Cc: Mikel Lindsaar <mikel@test.lindsaar.net>, "Bob Smith" <bob@me.com>')
      expect(t.name).to eq 'Resent-Cc'
      expect(t.value).to eq 'Mikel Lindsaar <mikel@test.lindsaar.net>, "Bob Smith" <bob@me.com>'
    end

    it "should accept a string without the field name" do
      t = Mail::ResentCcField.new('Mikel Lindsaar <mikel@test.lindsaar.net>, "Bob Smith" <bob@me.com>')
      expect(t.name).to eq 'Resent-Cc'
      expect(t.value).to eq 'Mikel Lindsaar <mikel@test.lindsaar.net>, "Bob Smith" <bob@me.com>'
    end

  end

  # Actual testing of CommonAddress methods oResentCcurs in the address field spec file

  describe "instance methods" do
    it "should return an address" do
      t = Mail::ResentCcField.new('Mikel Lindsaar <mikel@test.lindsaar.net>')
      expect(t.formatted).to eq ['Mikel Lindsaar <mikel@test.lindsaar.net>']
    end

    it "should return two addresses" do
      t = Mail::ResentCcField.new('Mikel Lindsaar <mikel@test.lindsaar.net>, Ada Lindsaar <ada@test.lindsaar.net>')
      expect(t.formatted.first).to eq 'Mikel Lindsaar <mikel@test.lindsaar.net>'
      expect(t.addresses.last).to eq 'ada@test.lindsaar.net'
    end

    it "should return one address and a group" do
      t = Mail::ResentCcField.new('sam@me.com, my_group: mikel@me.com, bob@you.com;')
      expect(t.addresses[0]).to eq 'sam@me.com'
      expect(t.addresses[1]).to eq 'mikel@me.com'
      expect(t.addresses[2]).to eq 'bob@you.com'
    end

    it "should return the formatted line on to_s" do
      t = Mail::ResentCcField.new('sam@me.com, my_group: mikel@me.com, bob@you.com;')
      expect(t.value).to eq 'sam@me.com, my_group: mikel@me.com, bob@you.com;'
    end

    it "should return the encoded line" do
      t = Mail::ResentCcField.new('sam@me.com, my_group: mikel@me.com, bob@you.com;')
      expect(t.encoded).to eq "Resent-Cc: sam@me.com, \r\n\smy_group: mikel@me.com, \r\n\sbob@you.com;\r\n"
    end

  end

end


text:
class Timer {
 public:
  Timer(Parallel* const parallel) : parallel(parallel) {}

  virtual ~Timer() = default;

  virtual void init() = 0;

  virtual void start(const std::string& event) = 0;

  virtual void checkpoint(const std::string& msg) = 0;

  virtual void end() = 0;

 protected:
  Parallel* const parallel;
};

#endif


text:
package com.yannick_cw.elastic_indexer4s.elasticsearch.index_ops

import cats.data.EitherT
import cats.implicits._
import com.sksamuel.elastic4s.http.ElasticDsl.{addAlias, removeAlias, search, _}
import com.sksamuel.elastic4s.http.settings.IndexSettingsResponse
import com.sksamuel.elastic4s.http.{ElasticClient, Response}
import com.yannick_cw.elastic_indexer4s.Index_results.IndexError

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

case class IndexWithInfo(index: String, aliases: List[String], creationTime: Long)

trait EsOpsClientApi {

  type OpsResult[A] = EitherT[Future, IndexError, A]

  def removeAliasFromIndex(index: String, alias: String): OpsResult[Boolean]
  def addAliasToIndex(index: String, alias: String): OpsResult[Boolean]
  def sizeFor(index: String): OpsResult[Long]
  def delete(index: String): OpsResult[Boolean]
  def allIndicesWithAliasInfo: OpsResult[List[IndexWithInfo]]

  def indicesByAgeFor(alias: String): OpsResult[List[String]] =
    for {
      indices <- allIndicesWithAliasInfo
    } yield indices.filter(_.aliases.contains(alias)).sortBy(_.creationTime).map(_.index)

  def latestIndexWithAliasSize(alias: String): OpsResult[Option[Long]] =
    for {
      indices <- indicesByAgeFor(alias)
      size    <- indices.lastOption.traverse(sizeFor)
    } yield size

  def removeAliasFromOldestIfExists(alias: String): OpsResult[Option[Boolean]] =
    for {
      indices    <- indicesByAgeFor(alias)
      optRemoved <- indices.headOption.traverse(removeAliasFromIndex(_, alias))
    } yield optRemoved

  def switchAliasToIndex(alias: String, index: String): OpsResult[Option[Boolean]] =
    for {
      rSuccess <- removeAliasFromOldestIfExists(alias)
      aSuccess <- addAliasToIndex(index, alias)
    } yield rSuccess.map(_ && aSuccess)
}

class EsOpsClient(client: ElasticClient) extends EsOpsClientApi {

  implicit class WithEitherTResult[A](f: Future[Response[A]]) {
    def opsResult: OpsResult[A] =
      EitherT(
        f.map(response =>
          response.fold[Either[IndexError, A]](
            Left(IndexError(s"Index creation failed with error: ${response.error}")))(Right(_))))
    def opsResult[B](to: A => B): OpsResult[B] = opsResult.map(to)
  }

  def delete(index: String): OpsResult[Boolean] =
    client.execute(deleteIndex(index)).opsResult(_.acknowledged)

  private def indexCreationDate(indexName: String, response: IndexSettingsResponse): Option[Long] =
    for {
      indexSettings <- response.settings.get(indexName)
      creationDate  <- indexSettings.get("index.creation_date")
    } yield creationDate.toLong

  def allIndicesWithAliasInfo: OpsResult[List[IndexWithInfo]] =
    for {
      aliases  <- client.execute(getAliases()).opsResult
      settings <- client.execute(getSettings(aliases.mappings.keys.map(_.name))).opsResult
    } yield
      aliases.mappings
        .map {
          case (index, aliasi) =>
            indexCreationDate(index.name, settings).map(date =>
              IndexWithInfo(index.name, aliasi.toList.map(_.name), date))
        }
        .collect { case Some(x) => x }
        .toList

  def removeAliasFromIndex(index: String, alias: String): OpsResult[Boolean] =
    client.execute(removeAlias(alias) on index).opsResult(_.acknowledged)

  def addAliasToIndex(index: String, alias: String): OpsResult[Boolean] =
    client.execute(addAlias(alias) on index).opsResult(_.acknowledged)

  def sizeFor(index: String): OpsResult[Long] =
    client.execute(search(index) size 0).opsResult(_.totalHits)
}

object EsOpsClient {
  def apply(client: ElasticClient): EsOpsClient = new EsOpsClient(client)
}


text:
#if !defined(AFX_DLGCERTTUTORIAL_H__73C6A6D9_05B6_11D6_8A83_000255320F1C__INCLUDED_)
#define AFX_DLGCERTTUTORIAL_H__73C6A6D9_05B6_11D6_8A83_000255320F1C__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// DlgCertTutorial.h : Header-Datei
//

/////////////////////////////////////////////////////////////////////////////
// Dialogfeld CDlgCertificateGeneration

#include "PSEDemo.h"

class CDlgCertificateGeneration : public CDialog
{
// Konstruktion
	void OnChangeCertData();

public:
	CDlgCertificateGeneration(CWnd* pParent = NULL);   // Standardkonstruktor
	BOOL m_PSEIsExtern;

	void InitRSA(CPSEDemo* Cert);
protected:
	CPSEDemo* m_Cert;
private:
	time_t m_lTime;

// Dialogfelddaten
	//{{AFX_DATA(CDlgCertificateGeneration)
	enum { IDD = IDD_CERTIFICATE_GENERATION };
	CEdit	m_CtrlPINv;
	CEdit	m_CtrlPIN;
	CEdit	m_CtrlFirstName;
	CEdit	m_CtrlName;
	CEdit	m_CtrlKeyID;
	CButton	m_CtrlOK;
	CString	m_sDName;
	CString	m_sFirstName;
	CString	m_sKeyID;
	CString	m_sName;
	CString	m_sUserID;
	CString	m_sBitLength;
	CString	m_sPIN;
	CString	m_sPINv;
	CString	m_sKeyPublic;
	CString	m_sModN;
	//}}AFX_DATA

// Überschreibungen
	// Vom Klassen-Assistenten generierte virtuelle Funktionsüberschreibungen
	//{{AFX_VIRTUAL(CDlgCertificateGeneration)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV-Unterstützung
	//}}AFX_VIRTUAL

// Implementierung
protected:

	// Generierte Nachrichtenzuordnungsfunktionen
	//{{AFX_MSG(CDlgCertificateGeneration)
	virtual BOOL OnInitDialog();
	afx_msg void OnPseImport();
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
public:
	afx_msg void OnChangeEdit();
	virtual void OnOK();
};

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ fügt unmittelbar vor der vorhergehenden Zeile zusätzliche Deklarationen ein.

#endif // AFX_DLGCERTTUTORIAL_H__73C6A6D9_05B6_11D6_8A83_000255320F1C__INCLUDED_


text:
{% extends "account/base.html" %}

{% block head_title %}Регистрация{% endblock %}

{% block content %}

Регистрация

            <form class="form" method="post" action="{% url 'account_signup' %}">
                {% csrf_token %}
                {% include "includes/bootstrap/bs3-form.html" %}

                {% if redirect_field_value %}
                    <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
                {% endif %}

                    <button class="btn btn-primary" type="submit">Зарегистрироваться</button>

            </form>

    Вход

{% endblock %}


text:
inherit STD_WEAPON;

void create_object(void);

void create_object(void)
{
    set_name("rod");
    add_id("iron rod");
    add_id("glowing iron rod");
    set_short("a glowing iron rod");
    set_long("A redglowing iron rod that has been heated up over a fire. " +
             "It's cooling down a bit now, but it is still hot to the " +
             "touch.\n");
    set_value(10);
    set_weight(3);
    set_type("blunt");
    set_class(17);
    set_material("iron");
    set_property("average");
}


text:
layout: post
title: "Singleton Design Pattern - C# implementation"
subtitle: "Singleton Design Pattern - C# implementation"
date: 2014-01-05 18:19
author: "Anuraj"
comments: true
categories: [.Net, .Net 3.0 / 3.5, .Net 4.0, ASP.Net, Windows Forms]
tags: [.Net, .Net 4.0, ASP.Net MVC, C#, C#.Net, Design Patterns, Singleton, Windows Forms]
header-img: "img/post-bg-01.jpg"
---
The singleton pattern is a software design pattern that is used to restrict instantiation of a class to one object. This is useful when we require exactly one object of a class to perform our operations. In this pattern we ensure that the class has only one instance and we provide a global point of access to this object. The normal implementation of singleton design pattern in C#like this.

{% highlight CSharp %}
public class Singleton
{
    private static Singleton _instance;
    private Singleton()
    {
        Console.WriteLine("Instance created");
    }

    public void Log(string message)
    {
        Console.WriteLine(message);
    }

    public static Singleton Instance
    {
        get
        {
            if (null == _instance)
            {
                _instance = new Singleton();
            }

            return _instance;
        }
    }
}
{% endhighlight %}

Here is the implementation details, by making the constructor private, ensuring no one able to create the instance of the class using the new keyword. And you can access the instance of the class using the Instance static property.(It can be static method also). The get accessor is responsible for creating and returning the instance if the instance is null, thus it making sure that singleton is returing only one instance. In this I have a log method, which will prints a message in the console. And you can consume the class like this.

{% highlight CSharp %}
var singleton = Singleton.Instance;
singleton.Log("Hello World");
{% endhighlight %}

And here is the output

![Singleton Application running in the console]({{ site.url }}{{ site.baseurl }}/assets/images/2014/01/Singleton_v1_console.png)

But this code will fail in a multi threaded environment. Like if you are running this using a Parallel For Each.

{% highlight CSharp %}
Parallel.For(1, 10, x =>
{
    var logger = Singleton.Instance;
    logger.Log(x.ToString());
});
{% endhighlight %}

And here is the output.

![Singleton running on Multithreaded environment]({{ site.url }}{{ site.baseurl }}/assets/images/2014/01/Singleton_v1_Multithreaded.png)

If you look at the screen shot, the constructor is getting invoked 4 times. That means it violates the only one instance principle of singleton. You can resolve this by adding a [lock statement](http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx) before the instantiation, like this. The following implementation allows only a single thread to enter the critical area, which the lock block identifies, when no instance of Singleton has yet been created.

{% highlight CSharp %}
public class Singleton
{
    private static Singleton _instance;
    private static object _lockObject = new object();

    private Singleton()
    {
        Console.WriteLine("Instance created");
    }

    public void Log(string message)
    {
        Console.WriteLine(message);
    }

    public static Singleton Instance
    {
        get
        {
            if (null == _instance)
            {
                lock (_lockObject)
                {
                    _instance = new Singleton();
                }
            }

            return _instance;
        }
    }
}
{% endhighlight %}

Again this will work most of the scenarios, but it will also fail in some (Because multiple threads can check for null, before one thread acquire lock and creates the instance). Here is the screenshot, the application again creates multiple instances.

![Singleton Multithreaded with lock statement]({{ site.url }}{{ site.baseurl }}/assets/images/2014/01/Singleton_v2_Multithreaded.png)

To avoid this by using a technique called [double checked locking](http://en.wikipedia.org/wiki/Double-checked_locking). In this implementation, you are verifying the instance variable again inside the lock() statement. Here is the implementation.

{% highlight CSharp %}
public class Singleton
{
    private static volatile Singleton _instance;
    private static object _lockObject = new object();

    private Singleton()
    {
        Console.WriteLine("Instance created");
    }

    public void Log(string message)
    {
        Console.WriteLine(message);
    }

    public static Singleton Instance
    {
        get
        {
            if (null == _instance)
            {
                lock (_lockObject)
                {
                    if (null == _instance)
                    {
                        _instance = new Singleton();
                    }
                }
            }

            return _instance;
        }
    }
}
{% endhighlight %}

This will resolve the problem. Here is the screenshot of application running in the console.

![Singleton Multithreaded - with Double-checked locking]({{ site.url }}{{ site.baseurl }}/assets/images/2014/01/Singleton_v3_Multithreaded.png)

Later I found an [simple and better approach](http://haacked.com/archive/2007/03/19/double-check-locking-and-other-premature-optimizations-can-shoot-you.aspx/) :) Here is the implementation.

{% highlight CSharp %}
public class Singleton
{
    private static Singleton _instance = new Singleton();

    private Singleton()
    {
        Console.WriteLine("Instance created");
    }

    public void Log(string message)
    {
        Console.WriteLine(message);
    }

    public static Singleton Instance
    {
        get
        {
            return _instance;
        }
    }
}
{% endhighlight %}

In this implementation CLR guarantees that the code in a static constructor (implicit or explicit) is only called once. You get all that thread safety for free! No need to write your own error prone locking code in this case and no need to dig through Memory Model implications. And one more approach is if you are using .Net 4.0 or more you can [System.Lazy](http://msdn.microsoft.com/en-us/library/dd642331.aspx) type for implementing singleton, and here is the implementation.

{% highlight CSharp %}
public class Singleton
{
    private static readonly Lazy<Singleton> _lazy =
        new Lazy<Singleton>(() => new Singleton());

    private Singleton()
    {
        Console.WriteLine("Instance created");
    }

    public void Log(string message)
    {
        Console.WriteLine(message);
    }

    public static Singleton Instance
    {
        get
        {
            return _lazy.Value;
        }
    }
}
{% endhighlight %}

Happy Programming :)


text:
RBTransformers

This is an Objective-C project I've done to showcase a few different programming techniques.

Objectives:
The Transformers are at war and  you  are in charge of settling the score! Here are the rules.

1. Each Transformer has the following criteria on their tech spec: Strength, Intelligence, Speed, Endurance, Rank, Courage , Firepower, Skill
2. The "overall rating" of a Transformer is the following formula: (Strength + Intelligence + Speed + Endurance + Firepower)
3. Each Transformer must either be an Autobot or a Deception.
4. The program takes input that describes a group of Transformers and based on that group displays: The number of battles, The winning team, The surviving members of the losing team
5. The teams is pre-sorted by rank and faced off one on one against each other in order to determine a victor, the loser is eliminated
6. A battle between opponents uses the following rules:
7. If any fighter is down 4 or more points of courage and 3 or more points of strength compared to their opponent, the opponent automatically wins the face-off regardless of overall rating (opponent has ran away)
8. Otherwise, if one of the fighters is 3 or more points of skill above their opponent, they win the fight regardless of overall rating
9. The winner is the Transformer with the highest overall rating
10. In the event of a tie, both Transformers are considered destroyed
11. Any Transformers who don't have a fight are skipped (i.e. if it's a team of 2 vs. a team of 1, there's only going to be one battle)
12. The team who eliminated the largest number of the opposing team is the winner
13. Any Transformer named Optimus Prime or Predaking wins his fight automatically regardless of any other criteria
14. In the event either of the above face each other (or a duplicate of each other), the game immediately ends with all competitors destroye

Project startup:
1. Checkout the develop branch
2. Open RBTransformers.xcworkspace
3. Run in a simulator
4. War starts automatically in the ViewController's startWar method
5. Observe the results in the UI or a bit more detailed results in the console log

Input:
transformers.json file in the project directory is being used as the source file for the war lineup. Feel free to modify it and re run the application again to see the new results.
Some fail safe checks are in place, but not all corner cases are covered for invalid input.

Output:
The RBWarMachine singleton delivers a RBWarResult class object to the ViewController upon conclusion of a war. It can be examined for further result details.

// war end result enum
@property (nonatomic, assign, readonly) RBBattleResult result;

// the count for how many battles took place
@property (nonatomic, assign, readonly) int battlesFought;

// an array of RBTransformer class objects of the winning team members.
@property (nonatomic, strong, readonly) NSArray <RBTransformer*> *winningTeamMembersArray;

// an array of RBTransformer class objects of the surviving losing team members.
@property (nonatomic, strong, readonly) NSArray <RBTransformer*> *survivingLosingTeamMembersArray;

// concatenated names of the winning team members
@property (nonatomic, strong, readonly) NSString *winningTeamMembersNames;

// concatenated names of the losing team members
@property (nonatomic, strong, readonly) NSString *losingTeamMembersNames;

// a concatenated full results description string
@property (nonatomic, strong, readonly) NSString *resultDescription;


text:
/* eslint-disable max-len */
/**
 * Pipe best of twits directly into your squad chat
 */

/*
 * AetheBot - A Discord Chatbot
 *
 * Created by Tyrone Trevorrow on 05/08/20.
 * Copyright (c) 2020 Tyrone Trevorrow. All rights reserved.
 *
 * This source code is licensed under the permissive MIT license.
 */

import { TweetPoolContent, TweetPool } from "./tweetpool"
import { fetchCustomToots } from "./twit_this"

const BRAIN_KEYS = {
    TOOT_LIST: "twit:toot_list",
}

const CONTENT: TweetPoolContent[] = [
    {
        content: "Yeah I'm p good with the old Microsoft Office [i accidentally click the button that makes all the paragraph symbols appear] ah she's fucked",
        retweets: 1481,
        likes: 6565,
        url: "https://twitter.com/bea_ker/status/840061788351733760",
        author: "Bea_ker (@bea_ker)",
        avatar: "https://cdn.discordapp.com/attachments/550619622450135046/740475457002012682/EONsIIb6_400x400.png",
    },
    {
        content: "The whole internet loves Milkshake Duck, a lovely duck that drinks milkshakes! \\*5 seconds later\\* We regret to inform you the duck is racist",
        retweets: 14340,
        likes: 38224,
        url: "https://twitter.com/pixelatedboat/status/741904787361300481",
        author: "pixelatedboat aka "mr tweets" (@pixelatedboat)",
        avatar: "https://cdn.discordapp.com/attachments/550619622450135046/740477065123463218/hc8K1aT0_bigger.png",
    },
    {
        content: ""Sweet dreams you piece of shit." I try to snap the prison guard's neck but just make him look to the left very quickly.",
        retweets: 15776,
        likes: 45961,
        url: "https://twitter.com/vineyille/status/822814010185842688",
        author: "vineyille (@vineyille)",
        avatar: "https://cdn.discordapp.com/attachments/550619622450135046/740480320087785472/TTZjmQNH_bigger.png",
    },
    {
        content: "Judge: Now wait a second Mike. if the other players were hacking, wouldn't that make their kills on you unfair?\nMe: That's right your honor.",
        retweets: 531,
        likes: 1820,
        url: "http://twitter.com/animaldrumss/status/491058831028678656",
        author: "Mike F (@mikefossey)",
        avatar: "https://cdn.discordapp.com/attachments/550619622450135046/740483003515666452/unknown.png",
    },
    {
        content: "Akchally it's an ancient Italian symbol dat represents da peaceful intasection of the four ingredients of a perfect Alfredo sauce",
        retweets: 1181,
        likes: 5898,
        url: "https://twitter.com/nycguidovoice/status/914531086977429504",
        author: "nYC Guido Voice (@nycguidovoice)",
        avatar: "https://cdn.discordapp.com/attachments/550619622450135046/740483433024847912/KevZFIjk_400x400.png",
        image: "https://cdn.discordapp.com/attachments/550619622450135046/740483897577439343/DLERKcrV4AAvhQ3.png",
    },
    {
        content: "My name on valorant is mywifediedin2012 and in a game a few days ago a guy said "this one goes out to this dudes wife" then got a headshot",
        retweets: 3233,
        likes: 23404,
        url: "https://twitter.com/tomwalkerisgood/status/1286188390988181504",
        author: "TOM (@tomwalkerisgood)",
        avatar: "https://cdn.discordapp.com/attachments/550619622450135046/740484282375733309/hBzLtmH_bigger.png",
    },
    {
        content: "SOCRATES: I am wiser than this man; he fancies he knows something, although he knows nothing—\nDARRYL, SOCRATES' FRIEND: fuck him up socrates",
        retweets: 40158,
        likes: 82981,
        url: "https://twitter.com/leyawn/status/585859882869469184",
        author: "leon (@leyawn)",
        avatar: "https://cdn.discordapp.com/attachments/550619622450135046/740491796223885343/70e0971b8c52faf3a44fd9a6194c54f5_bigger.gif",
    },
    {
        content: "https://t.co/8HothQooBg",
        retweets: 4263,
        likes: 32036,
        url: "https://twitter.com/nocontextboomer/status/1283366754559950852",
        author: "Cropped Boomer Images (@NoContextBoomer)",
        avatar: "https://cdn.discordapp.com/attachments/550619622450135046/740509840631398400/Clicc486_bigger.png",
        image: "https://cdn.discordapp.com/attachments/550619622450135046/740509718769827900/Ec9vQxhXYAk1Ug3.png",
    },
    {
        content: "https://t.co/kA7UMu4Mmz",
        retweets: 9858,
        likes: 50092,
        url: "https://twitter.com/mort/status/1280756378697641984",
        author: "mort (@mort)",
        avatar: "https://cdn.discordapp.com/attachments/550619622450135046/740510566451380254/unknown.png",
        image: "https://cdn.discordapp.com/attachments/550619622450135046/740510726606815312/EcYpIQKX0AAxpLU.png",
    },
    {
        content: "\\*opens briefcase\\* shall we dispense with the small talk and get down to business?",
        retweets: 538,
        likes: 2260,
        url: "https://twitter.com/robotrowboat/status/1276630335288197123",
        author: "Troutman (@robotrowboat)",
        avatar: "https://cdn.discordapp.com/attachments/550619622450135046/740511404167266414/0GEC33Y__bigger.png",
        image: "https://cdn.discordapp.com/attachments/550619622450135046/740511591081967664/EbeAdmhXYAE-FjJ.png",
    },
    {
        content: "If unemployment exceeds 30% and distrust of the political process becomes widespread, there is a danger that the United States will enter what historians call The Cool Zone.",
        retweets: 6767,
        likes: 31273,
        url: "https://twitter.com/SeanRMoorhead/status/1248065386714558465",
        author: "Ed Mubarak (@SeanRMoorhead)",
        avatar: "https://cdn.discordapp.com/attachments/550619622450135046/740512740858396672/ojhF57p__bigger.png",
    },
    {
        content: "my roommate bansky is at it again. he made coffee and said he put something inside that would \"REALLY wake me up\"",
        retweets: 23710,
        likes: 46044,
        url: "https://twitter.com/electrolemon/status/489101252844736513",
        author: "demi adejuyigbe (@electrolemon)",
        avatar: "https://cdn.discordapp.com/attachments/550619622450135046/740513457165697096/0Aa9lo1__bigger.png",
        image: "https://cdn.discordapp.com/attachments/550619622450135046/740513721050333226/Bsmi_1eCQAEBule.png",
    },
    {
        content: "https://t.co/jMZOnrjhxy",
        retweets: 2,
        likes: 11,
        url: "https://twitter.com/camtyeson/status/1257931864783765504",
        author: "Cam Tyeson (@camtyeson)",
        avatar: "https://cdn.discordapp.com/attachments/550619622450135046/740515355625259028/ZgUS5Sxt_bigger.png",
        image: "https://cdn.discordapp.com/attachments/550619622450135046/740515256006082560/EXUSXB3VcAAtqie.png",
    },
    {
        content: "oh so all of a sudden you know how to use metric measurements",
        retweets: 98,
        likes: 1440,
        url: "https://twitter.com/AaronGocs/status/1256870506227105795",
        author: "Aaron Gocs (@AaronGocs)",
        avatar: "https://cdn.discordapp.com/attachments/550619622450135046/740515973043454043/efb427f8f43ff1c7650b7a6cc2d36867_bigger.png",
        image: "https://cdn.discordapp.com/attachments/550619622450135046/740516644006395954/unknown.png",
    },
    {
        content: "[mysterious old lady flips tarot card revealing a dude who looks exactly like me flying a hot air balloon into power lines]\nMe: is that good",
        retweets: 42249,
        likes: 84781,
        url: "https://twitter.com/boring_as_heck/status/604761050857095168",
        author: "mr. peepee poopoo (@boring_as_heck)",
        avatar: "https://cdn.discordapp.com/attachments/550619622450135046/740516343648092180/n0coWjbP_bigger.png",
    },
    {
        content: "me: Welcome to Troll Academy. First order of business, you have to pick a troll name which you will use all times at the school.\n(everyones hand goes up)\nme: The name cannot be a racial slur.\n(everyones hand goes down except one)\nme: No exceptions.\n(the last hand goes down)",
        retweets: 8,
        likes: 115,
        url: "https://twitter.com/getfiscal/status/982755131325403136",
        author: "Don Hughes 🦌 (@getfiscal)",
        avatar: "https://cdn.discordapp.com/attachments/550619622450135046/740516953487048764/5nqTrvC0_bigger.png",
    },
    {
        content: "me: Alright that concludes my opening remarks on Troll Academy. Does anyone have any questions? Yes, you.\nstudent: Fuck you.\nme: Good. Anyone else? Yes.\nother student: You look like it a potato lost its job.\nme: Great. Troll Academy isn't easy, and you're stupid for signing up.",
        retweets: 4,
        likes: 35,
        url: "https://twitter.com/getfiscal/status/982766436077768704",
        author: "Don Hughes 🦌 (@getfiscal)",
        avatar: "https://cdn.discordapp.com/attachments/550619622450135046/740516953487048764/5nqTrvC0_bigger.png",
    },
    {
        content: "Just to let everyone know I work in the 5G field.  While I was working from home this weekend I just realised I had all the units set to "give corona" setting instead of the default "make everyone gay" default setting. Really sorry about that.",
        retweets: 2383,
        likes: 12069,
        url: "https://twitter.com/NZjusticeSUCKS/status/1251941154494406656",
        author: "NZ Truth Warrior (@NZjusticeSUCKS)",
        avatar: "https://cdn.discordapp.com/attachments/550619622450135046/740517353460334712/9Zmg1Bal_bigger.png",
    },
    {
        content: "i think i'd like to have one of those youtube channels where every video thumbnail is this bullshit",
        retweets: 5039,
        likes: 19544,
        url: "https://twitter.com/robwhisman/status/735281634656669696",
        author: "rob (@robwhisman)",
        avatar: "https://cdn.discordapp.com/attachments/550619622450135046/740517652434518046/pojRP1iz_bigger.png",
        image: "https://cdn.discordapp.com/attachments/550619622450135046/740517674903142460/CjQ-v9oWgAAuoiO.png",
    },
    {
        content: "i see u know ur pinot well",
        retweets: 7,
        likes: 23,
        url: "https://twitter.com/robwhisman/status/735317544156991488",
        author: "a big pretty Lizard (@birdcardigan)",
        avatar: "https://cdn.discordapp.com/attachments/550619622450135046/740517908244856903/ZKzY7QRK_bigger.png",
        image: "https://cdn.discordapp.com/attachments/550619622450135046/740518221769080912/unknown.png",
    },
    {
        content: "god: i have made Mankind\nangels: you fucked up a perfectly good monkey is what you did. look at it. it's got anxiety",
        retweets: 50220,
        likes: 89131,
        url: "https://twitter.com/jon_snow_420/status/659443020908003328",
        author: "failings spectre (@jon_snow_420)",
        avatar: "https://cdn.discordapp.com/attachments/293954139845820416/921202881347072030/zoAyRuJP_normal.jpg",
    },
    {
        content: "Sci-Fi Author: In my book I invented the Torment Nexus as a cautionary tale\n\nTech Company: At long last, we have created the Torment Nexus from classic sci-fi novel Don't Create The Torment Nexus",
        retweets: 27409,
        likes: 102134,
        url: "https://twitter.com/AlexBlechman/status/1457842724128833538",
        author: "Alex Blechman (@AlexBlechman)",
        avatar: "https://cdn.discordapp.com/attachments/293954139845820416/921995248803127306/KhbtX6JF_bigger.png",
    },
    {
        content: "\\*Cracks Diet Pepsi Ahh...Refreshing Diet Peppi \\*Slowly Sips, Then Gulps, The Diet Pappo\\*\\* Ahh, Diet Parpo. Thank's To The Papor-Colla Corp.",
        retweets: 7373,
        likes: 15369,
        url: "https://twitter.com/tree_bro/status/79444819902074880",
        author: "Jackson (@tree_bro)",
        avatar: "https://cdn.discordapp.com/attachments/767671918505099294/935753034443677786/BRO_bigger.jpg",
    },
    {
        content: "Hello sir, I-\\*briefcase full of jellybeans falls open\\*",
        retweets: 8469,
        likes: 22017,
        url: "https://twitter.com/brendlewhat/status/165631372327784448",
        author: "brendle (@brendlewhat)",
        avatar: "https://cdn.discordapp.com/attachments/767671918505099294/935753703951073290/pZ4ZTsOU_bigger.png",
    },
    {
        content: "most cutting thing you can say is \"who's this clown?\" because it implies they're a) a clown & b) not even one of the better-known clowns",
        retweets: 71480,
        likes: 126859,
        url: "https://twitter.com/skullmandible/status/411281851131523072",
        author: "Cohen is a ghost (@skullmandible)",
        avatar: "https://cdn.discordapp.com/attachments/767671918505099294/935754001981521950/Kw0VfgAV_bigger.jpg",
    },
    {
        content: "What should we call this giant advertising board?\nPHIL: A philboard\nBILL: I have a better idea",
        retweets: 11079,
        likes: 21428,
        url: "https://twitter.com/internethippo/status/585108383985836034",
        author: "The Borscht Identity (@InternetHippo)",
        avatar: "https://cdn.discordapp.com/attachments/767671918505099294/935754402629845002/mV-fry51_bigger.jpg",
    },
    {
        content: "amazon: we shipped your package! it should deliver by 8pm tomorrow!\n\nme, nose pressed against the door, fogging the glass as i breathe: **𝗽𝗮𝗸𝗶𝗱𝗴𝗲**",
        retweets: 67330,
        likes: 284318,
        url: "https://twitter.com/sexhomaru/status/1108074779121197058",
        author: "rin | check pinned (@sexhomaru)",
        avatar: "https://cdn.discordapp.com/attachments/767671918505099294/935755313628479498/KBJShADR_bigger.png",
        image: "https://cdn.discordapp.com/attachments/767671918505099294/935755614167109632/ENFoiFiXsAA_4bB.png",
    },
    {
        content: "[Dentist waiting room]\n\nMe: [chanting] teeth, teeth-\n\nOther patients: teeth, TEETH\n\nSecretary: [pounding her clipboard] TEETH, TEETH, TEETH!",
        retweets: 38270,
        likes: 121463,
        url: "https://twitter.com/lebeargirdle/status/898280833299230722",
        author: "brandAn is good (@LeBearGirdle)",
        avatar: "https://cdn.discordapp.com/attachments/767671918505099294/935755841099956224/zKYF1c45_bigger.jpg",
    },
    {
        content: "democracy is this cool system where you yell at people online for 6 months and then people in Ohio and Florida pick the president",
        retweets: 12946,
        likes: 23868,
        url: "https://twitter.com/bromanconsul/status/742627660367429632",
        author: "bog person (@bromanconsul)",
        avatar: "https://cdn.discordapp.com/attachments/767671918505099294/935756501467922492/erCOWmQt_bigger.jpg",
    },
    {
        content: "[quietly tries to open a can of beer]\ndriving instructor: what was that",
        retweets: 5797,
        likes: 14574,
        url: "https://twitter.com/cornonthegoblin/status/714202417944854528",
        author: "Cat Damon (@CornOnTheGoblin)",
        avatar: "https://cdn.discordapp.com/attachments/767671918505099294/935756754082480128/7ncWKKow_bigger.jpeg",
    },
    {
        content: "One of McDonald's mascots is a guy who steals from McDonald's.",
        retweets: 1077,
        likes: 2382,
        url: "https://twitter.com/tylerschmall/status/443190789758132224",
        author: "Tyler Schmall (@tylerschmall)",
        avatar: "https://cdn.discordapp.com/attachments/767671918505099294/935757032928182353/gCOEwKyC_bigger.jpg",
    },
    {
        content: "Day 20. Still lost at sea. Crew thinks I know how to plot a course with a protractor. I just like making it walk on the map. Pointy Leg Man.",
        retweets: 12659,
        likes: 33591,
        url: "https://twitter.com/vineyille/status/551873301963079680",
        author: "vineyille (@vineyille)",
        avatar: "https://cdn.discordapp.com/attachments/767671918505099294/935757247320051792/TTZjmQNH_bigger.jpg",
    },
    {
        content: "Its really disgusting how other white people dont even know about the plight of [quickly wikipedias \"Who is having alot of plight 2012]",
        retweets: 2296,
        likes: 7941,
        url: "https://twitter.com/kanwetwitty/status/177549627090927616",
        author: "we (@kanwetwitty)",
        avatar: "https://cdn.discordapp.com/attachments/767671918505099294/935757468527628348/NjFHHWlu_bigger.jpg",
    },
]

export const TOOTS_BY_ID = new Map(CONTENT.map(obj => {
    const url = new URL(obj.url)
    const pathComponents = url.pathname.split("/")
    if (url.host !== "twitter.com") {
        throw new Error("idiot developer error: tweet urls must be on twitter dot com")
    }
    return [pathComponents[pathComponents.length - 1], obj]
}))

export class Twit extends TweetPool {
    protected async fetchList(): Promise<Map<string, TweetPoolContent>> {
        const builtins = TOOTS_BY_ID
        const customsObj = await fetchCustomToots(this.brain)
        const customs = new Map(Object.entries(customsObj))
        for (const [key, value] of builtins) {
            customs.set(key, value)
        }
        return customs
    }

    protected get persistenceVersion(): number {
        return 2
    }

    protected brainKeyForChannel(chanId: string): string {
        return `${BRAIN_KEYS.TOOT_LIST}:${chanId}`
    }
}


text:
<!DOCTYPE html>

    <title>Sample: Local Screensharing</title>

Local Screensharing

This sample demonstrates sharing your local screen

    <form id="credentials">
      <fieldset>
        <legend>Credentials</legend>
        <input
          id="access-token"
          name="accessToken"
          placeholder="Your access token"
          type="text">
        <input id="connect" title="connect" type="submit" value="connect">

disconnected

      </fieldset>
    </form>

    <form id="dialer">
      <fieldset>
        <legend>Dialer</legend>
        <input
          id="invitee"
          name="invitee"
          placeholder="Person ID or Email Address or SIP URI or Room ID"
          size="60"
          type="text">
          <input title="dial" type="submit" value="dial">
      </fieldset>
    </form>

    <form id="call-controls">
      <fieldset>
        <legend>Call Controls</legend>
        <button id="hangup" title="hangup" type="button">cancel/hangup</button>

        <button id="share-screen" title="share screen" type="button">share screen</button>
        <button id="share-application" title="share application" type="button">share application</button>
        <button id="stop-screen-share" title="stop screen share" type="button">stop screen share</button>
      </fieldset>
    </form>

        <video style="width: 100%" id="self-view" muted autoplay></video>
        <video style="width: 100%" id="remote-view-video" autoplay></video>
        <audio id="remote-view-audio" autoplay></audio>

        <video style="width: 100%;" id="self-screen" muted autoplay></video>

Events