text:
'use strict';

angular.module('copayApp.controllers').controller('backupController',
  function($rootScope, $scope, $timeout, $log, lodash, profileService, gettext, bwcService, bwsError, walletService) {

    var self = this;
    var fc = profileService.focusedClient;
    self.customWords = [];
    self.walletName = fc.credentials.walletName;

    var handleEncryptedWallet = function(client, cb) {
      if (!walletService.isEncrypted(client)) return cb();
      $rootScope.$emit('Local/NeedsPassword', false, function(err, password) {
        if (err) return cb(err);
        return cb(walletService.unlock(client, password));
      });
    };

    if (fc.credentials && !fc.credentials.mnemonicEncrypted && !fc.credentials.mnemonic)
      self.deleted = true;

    if (fc.isPrivKeyEncrypted() && !self.deleted) {
      self.credentialsEncrypted = true;
      passwordRequest();
    } else {
      if (!self.deleted)
        initWords();
    }

    init();

    function init() {
      $scope.passphrase = '';
      self.shuffledMnemonicWords = shuffledWords(self.mnemonicWords);
      self.customWords = [];
      self.step = 1;
      self.deleted = false;
      self.credentialsEncrypted = false;
      self.selectComplete = false;
      self.backupError = false;
    };

    self.goToStep = function(n) {
      self.step = n;
      if (self.step == 1)
        init();
      if (self.step == 3 && !self.mnemonicHasPassphrase)
        self.step++;
      if (self.step == 4) {
        confirm();
      }
    };

    function initWords() {
      var words = fc.getMnemonic();
      self.xPrivKey = fc.credentials.xPrivKey;
      walletService.lock(fc);
      self.mnemonicWords = words.split(/[\u3000\s]+/);
      self.shuffledMnemonicWords = shuffledWords(self.mnemonicWords);
      self.mnemonicHasPassphrase = fc.mnemonicHasPassphrase();
      self.useIdeograms = words.indexOf("\u3000") >= 0;
    };

    function shuffledWords(words) {
      var sort = lodash.sortBy(words);

      return lodash.map(sort, function(w) {
        return {
          word: w,
          selected: false
        };
      });
    };

    self.toggle = function() {
      self.error = "";

      if (self.credentialsEncrypted)
        passwordRequest();

      $timeout(function() {
        $scope.$apply();
      }, 1);
    };

    function passwordRequest() {
      try {
        initWords();
      } catch (e) {
        if (e.message && e.message.match(/encrypted/) && fc.isPrivKeyEncrypted()) {

          $timeout(function() {
            $scope.$apply();
          }, 1);

          handleEncryptedWallet(fc, function(err) {
            if (err) {
              self.error = bwsError.msg(err, gettext('Could not decrypt'));
              $log.warn('Error decrypting credentials:', self.error); //TODO
              return;
            }

            self.credentialsEncrypted = false;
            initWords();

            $timeout(function() {
              $scope.$apply();
            }, 1);
          });
        }
      }
    };

    $scope.addButton = function(index, item) {
      var newWord = {
        word: item.word,
        prevIndex: index
      };
      self.customWords.push(newWord);
      self.shuffledMnemonicWords[index].selected = true;
      self.shouldContinue();
    };

    $scope.removeButton = function(index, item) {
      self.customWords.splice(index, 1);
      self.shuffledMnemonicWords[item.prevIndex].selected = false;
      self.shouldContinue();
    };

    self.shouldContinue = function() {
      if (self.customWords.length == 12)
        self.selectComplete = true;
      else
        self.selectComplete = false;
    };

    function confirm() {
      self.backupError = false;

      var walletClient = bwcService.getClient();
      var separator = self.useIdeograms ? '\u3000' : ' ';
      var customSentence = lodash.pluck(self.customWords, 'word').join(separator);
      var passphrase = $scope.passphrase || '';

      try {
        walletClient.seedFromMnemonic(customSentence, {
          network: fc.credentials.network,
          passphrase: passphrase,
          account: fc.credentials.account
        })
      } catch (err) {
        return backupError(err);
      }

      if (walletClient.credentials.xPrivKey != self.xPrivKey) {
        return backupError('Private key mismatch');
      }

      $rootScope.$emit('Local/BackupDone');
    };

    function backupError(err) {
      $log.debug('Failed to verify backup: ', err);
      self.backupError = true;

      $timeout(function() {
        $scope.$apply();
      }, 1);
    };
  });


text:
Roogoo::Engine.routes.draw do
end

redpajama_set_name: RedPajamaGithub


text:
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="nav_header_vertical_spacing">16dp</dimen>
    <dimen name="nav_header_height">160dp</dimen>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="fab_margin">16dp</dimen>
    <dimen name="margin_1">8dp</dimen>
    <dimen name="margin_2">16dp</dimen>
    <dimen name="mergin_3">24dp</dimen>
</resources>


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>openaq.utils — py-openaq 1.1.0 documentation</title>
    <link rel="stylesheet" href="../../_static/bootstrap-sphinx.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/style.css" type="text/css" />

    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">

        </button>

          py-openaq
        1.1.0

API

Tutorial

Gallery

  Site

Getting Started and Installation

API Reference

py-openaq Tutorial

Example gallery

  Page

<form class="navbar-form navbar-right" action="../../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

Source code for openaq.utils

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import dateutil

def to_naive_timestamp(timestamp):
    """
        Convert a timezone aware timestamp (as a string) and return the
        python datetime in the local timezone, but without the tzinfo attribute
    """
    return dateutil.parser.parse(timestamp).replace(tzinfo=None).isoformat()

def clean_encodings(unit):
    if unit not in ('ppm', 'ppb', 'ppt', 'ugm3'):
        unit = unit.encode('utf-8')

        if unit == '\xc2\xb5g/m\xc2\xb3':
            unit = 'ugm3'

    return unit

[docs]def mass_to_mix(value, param, unit='ppb', **kwargs):
    """Convert units from ug/m3 to ppb or ppm. The conversion assumes an ambient
    pressure of 1 atmosphere and ambient temperature of 25 degC.

    :param value: the concentration in ug/m3
    :param param: the parameter to convert {'co', 'no', 'no2', 'so2', 'o3'}
    :param unit: the desired output unit {'ppb', 'ppm'}

    :type value: float
    :type param: string
    :type unit: string

    :returns: value

    :Example:

    >>> import openaq
    >>> conc_ugm3 = 100
    >>> conc_ppb = openaq.utils.mass_to_mix(conc_ugm3, param='co', unit='ppb')
    >>> conc_ppb
    114.5

    """
    lookup = {
        'co': 1.145,
        'no': 1.25,
        'no2': 1.88,
        'so2': 2.62,
        'o3': 2.0
    }

    param = param.lower()

    if param not in lookup.keys():
        return value

    value = value / lookup[param]

    if unit.lower() == 'ppm':
        value *= 1e-3

    return value

      Back to top

        © Copyright 2018, David H Hagan.

      Created using Sphinx 1.6.6.


text:
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;

/**
 * Auto-generated code below aims at helping you parse
 * the standard input according to the problem statement.
 **/
class Solution
{
	static void Main(string[] args)
	{
		int n = int.Parse(Console.ReadLine()); // the number of temperatures to analyse
		string temps = Console.ReadLine(); // the n temperatures expressed as integers ranging from -273 to 5526

		if (n == 0)
		{
			Console.WriteLine("0");
		}
		else
		{
			var temperatures = temps.Split(' ').Select(x => int.Parse(x));

			var closestT = temperatures
				.Select(x => new { t = x, absT = Math.Abs(x) })
				.OrderBy(x => x.absT)
				.ThenByDescending(x => x.t)
				.First()
				.t;

			Console.WriteLine(closestT.ToString());
		}
	}
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Xml;
using System.Xml.Linq;
using NUnit.Framework;
using SIL.Xml;

namespace SIL.Tests.Xml
{
	[TestFixture]
	[SuppressMessage("ReSharper", "PossibleNullReferenceException")]
	public class XmlUtilsTests
	{
		[Test]
		public void GetAttributes_DoubleQuotedAttribute_HasValue()
		{
			const string data = @"<element attr='data' />";
			var tmp = data.Replace("'", "\"");
			var attrValues = XmlUtils.GetAttributes(Encoding.UTF8.GetBytes(tmp), new HashSet<string> { "attr" });
			Assert.IsTrue(attrValues["attr"] == "data");

			attrValues = XmlUtils.GetAttributes(tmp, new HashSet<string> { "attr" });
			Assert.IsTrue(attrValues["attr"] == "data");
		}

		[Test]
		public void GetAttributes_SingleQuotedAttribute_HasValue()
		{
			const string data = @"<element attr='data' />";
			var attrValues = XmlUtils.GetAttributes(Encoding.UTF8.GetBytes(data), new HashSet<string> { "attr" });
			Assert.IsTrue(attrValues["attr"] == "data");

			attrValues = XmlUtils.GetAttributes(data, new HashSet<string> { "attr" });
			Assert.IsTrue(attrValues["attr"] == "data");
		}

		[Test]
		public void GetAttributes_NonExistentAttribute_IsNull()
		{
			const string data = @"<element />";
			var attrValues = XmlUtils.GetAttributes(Encoding.UTF8.GetBytes(data), new HashSet<string> { "attr" });
			Assert.IsNull(attrValues["attr"]);

			attrValues = XmlUtils.GetAttributes(data, new HashSet<string> { "attr" });
			Assert.IsNull(attrValues["attr"]);
		}

		[Test]
		public void SanitizeString_NullString_ReturnsNull()
		{
			Assert.IsNull(XmlUtils.SanitizeString(null));
		}

		[Test]
		public void SanitizeString_EmptyString_ReturnsEmptyString()
		{
			Assert.AreEqual(string.Empty, XmlUtils.SanitizeString(string.Empty));
		}

		[Test]
		public void SanitizeString_ValidString_ReturnsSameString()
		{
			string s = "Abc\u0009 \u000A\u000D\uD7FF\uE000\uFFFD";
			s += char.ConvertFromUtf32(0x10000);
			s += char.ConvertFromUtf32(0x10FFFF);
			Assert.AreEqual(s, XmlUtils.SanitizeString(s));
		}

		[Test]
		public void SanitizeString_CompletelyInvalidString_ReturnsEmptyString()
		{
			string s = "\u0000\u0008\u000B\u000C\u000E\u001F\uD800\uD999\uFFFE\uFFFF";
			int utf32 = 0x20ffff - 0x10000;
			char[] surrogate = new char[2];
			surrogate[0] = (char)((utf32 / 0x400) + '\ud800');
			surrogate[1] = (char)((utf32 % 0x400) + '\udc00');
			s += new string(surrogate);
			Assert.AreEqual(string.Empty, XmlUtils.SanitizeString(s));
		}

		[Test]
		public void SanitizeString_StringWithInvalidChars_ReturnsStringWithInvalidCharsRemoved()
		{
			string s = "A\u0008B\u000B\u000C\u000E\u001F\uD800\uD999\uFFFE\uFFFFC";
			int utf32 = 0x20ffff - 0x10000;
			char[] surrogate = new char[2];
			surrogate[0] = (char)((utf32 / 0x400) + '\ud800');
			surrogate[1] = (char)((utf32 % 0x400) + '\udc00');
			s += new string(surrogate);
			Assert.AreEqual("ABC", XmlUtils.SanitizeString(s));
		}

		[Test]
		public void RemoveNamespaces_FromElements()
		{
			var element = XElement.Parse("<Element xmlns='http://sil.org/xml' att='tribute'><Inner should='be preserved' me='2'></Inner></Element>");
			element.RemoveNamespaces();
			foreach (var elt in element.DescendantsAndSelf())
			{
				Assert.That(elt.Name.NamespaceName, Is.Null.Or.Empty);
			}
			Assert.That(element.Attributes().Count(), Is.EqualTo(1));
			Assert.That(element.Attribute("att").Value, Is.EqualTo("tribute"));
			var inner = element.Element("Inner");
			Assert.That(inner.Attributes().Count(), Is.EqualTo(2));
			Assert.That(inner.Attribute("should").Value, Is.EqualTo("be preserved"));
			Assert.That(inner.Attribute("me").Value, Is.EqualTo("2"));
		}

		[Test]
		public void RemoveNamespaces_FromSubElements()
		{
			var element = XElement.Parse("<Element></Element>");
			element.RemoveNamespaces();
			foreach (var elt in element.DescendantsAndSelf())
			{
				Assert.That(elt.Name.NamespaceName, Is.Null.Or.Empty);
				Assert.That(elt.Attributes(), Is.Empty);
			}
		}

		///
		/// This is a regression test for (FLEx) LT-13962, a problem caused by importing white space introduced by pretty-printing.
		///
		[Test]
		public void WriteNode_DoesNotIndentFirstChildOfMixedNode()
		{
			string input = @"<text>bt more text</text>";
			string expectedOutput =
				"<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n"
				+ "<root>\r\n"
				+ "	<text>bt more text</text>\r\n"
				+ "</root>";
			var output = new StringBuilder();
			using (var writer = XmlWriter.Create(output, CanonicalXmlSettings.CreateXmlWriterSettings()))
			{
				writer.WriteStartDocument();
				writer.WriteStartElement("root");
				XmlUtils.WriteNode(writer, input, new HashSet<string>());
				writer.WriteEndElement();
				writer.WriteEndDocument();
			}
			Assert.That(output.ToString(), Is.EqualTo(expectedOutput));
		}

		///
		/// This verifies the special case of (FLEx) LT-13962 where the ONLY child of an element that can contain significant text
		/// is an element.
		///
		[Test]
		public void WriteNode_DoesNotIndentChildWhenSuppressed()
		{
			string input = @"<text>bt</text>";
			string expectedOutput =
				"<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n"
				+ "<root>\r\n"
				+ "	<text>bt</text>\r\n"
				+ "</root>";
			var output = new StringBuilder();
			var suppressIndentingChildren = new HashSet<string>();
			suppressIndentingChildren.Add("text");
			using (var writer = XmlWriter.Create(output, CanonicalXmlSettings.CreateXmlWriterSettings()))
			{
				writer.WriteStartDocument();
				writer.WriteStartElement("root");
				XmlUtils.WriteNode(writer, input, suppressIndentingChildren);
				writer.WriteEndElement();
				writer.WriteEndDocument();
			}
			Assert.That(output.ToString(), Is.EqualTo(expectedOutput));
		}
		///
		/// This verifies that suppressing pretty-printing of children works for spans nested in spans nested in text.
		///
		[Test]
		public void WriteNode_DoesNotIndentChildWhenTwoLevelsSuppressed()
		{
			string input = @"<text>bitbt</text>";
			string expectedOutput =
				"<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n"
				+ "<root>\r\n"
				+ "	<text>bitbt</text>\r\n"
				+ "</root>";
			var output = new StringBuilder();
			var suppressIndentingChildren = new HashSet<string>();
			suppressIndentingChildren.Add("text");
			using (var writer = XmlWriter.Create(output, CanonicalXmlSettings.CreateXmlWriterSettings()))
			{
				writer.WriteStartDocument();
				writer.WriteStartElement("root");
				XmlUtils.WriteNode(writer, input, suppressIndentingChildren);
				writer.WriteEndElement();
				writer.WriteEndDocument();
			}
			Assert.That(output.ToString(), Is.EqualTo(expectedOutput));
		}

		[Test]
		public void GetMandatoryIntegerAttributeValue_OfElement_ReturnsInteger()
		{
			var element = new XElement("element");
			var attr = new XAttribute("intAttr", 1);
			element.Add(attr);
			Assert.AreEqual(1, XmlUtils.GetMandatoryIntegerAttributeValue(element, "intAttr"));
		}

		[Test]
		public void GetMandatoryIntegerAttributeValue_OfElement_Throws_If_Attr_Not_Present()
		{
			Assert.Throws<ApplicationException>(() => XmlUtils.GetMandatoryIntegerAttributeValue(new XElement("element"), "intAttr"));
		}

		[Test]
		public void GetMandatoryIntegerAttributeValue_OfElement_Throws_If_Not_Integer()
		{
			Assert.Throws<FormatException>(() => XmlUtils.GetMandatoryIntegerAttributeValue(new XElement("element", new XAttribute("intAttr", "Not_Int")), "intAttr"));
		}

		[Test]
		public void GetOptionalIntegerValue_OfElement_Returns_Default_Value()
		{
			Assert. AreEqual(1, XmlUtils.GetOptionalIntegerValue(new XElement("element"), "intAttr", 1));
		}

		[Test]
		public void GetOptionalIntegerValue_OfElement_Ignores_Default_Value_When_Attr_Present()
		{
			Assert.AreEqual(2, XmlUtils.GetOptionalIntegerValue(new XElement("element", new XAttribute("intAttr", "2")), "intAttr", 1));
		}

		[Test]
		public void GetOptionalIntegerValue_OfElement_Throws_If_Not_Integer()
		{
			Assert.Throws<FormatException>(() => XmlUtils.GetOptionalIntegerValue(new XElement("element", new XAttribute("intAttr", "Not_Int")), "intAttr", 1));
		}

		[TestCase(null, ExpectedResult = false, Description = "Null should return false")]
		[TestCase("", ExpectedResult = false, Description = "Empty string should return false")]
		[TestCase(" ", ExpectedResult = false, Description = "Whitespace only string should return false")]
		[TestCase("FALSE", ExpectedResult = false, Description = "'FALSE' should return false")]
		[TestCase("False", ExpectedResult = false, Description = "'False' should return false")]
		[TestCase("false", ExpectedResult = false, Description = "'false' should return false")]
		[TestCase("NO", ExpectedResult = false, Description = "'NO' should return false")]
		[TestCase("No", ExpectedResult = false, Description = "'No' should return false")]
		[TestCase("no", ExpectedResult = false, Description = "'no' should return false")]
		[TestCase("TRUE", ExpectedResult = true, Description = "'TRUE' should return true")]
		[TestCase("True", ExpectedResult = true, Description = "'True' should return true")]
		[TestCase("true", ExpectedResult = true, Description = "'true' should return true")]
		[TestCase("YES", ExpectedResult = true, Description = "'YES' should return true")]
		[TestCase("Yes", ExpectedResult = true, Description = "'Yes' should return true")]
		[TestCase("yes", ExpectedResult = true, Description = "'yes' should return true")]
		public bool GetBooleanAttributeValue_Returns_True(string input)
		{
			// Test overload that takes just the attribute's value
			return XmlUtils.GetBooleanAttributeValue(input);
		}

		[TestCase("", ExpectedResult = false, Description = "Empty string should return false")]
		[TestCase(" ", ExpectedResult = false, Description = "Whitespace only string should return false")]
		[TestCase("FALSE", ExpectedResult = false, Description = "'FALSE' should return false")]
		[TestCase("False", ExpectedResult = false, Description = "'False' should return false")]
		[TestCase("false", ExpectedResult = false, Description = "'false' should return false")]
		[TestCase("NO", ExpectedResult = false, Description = "'NO' should return false")]
		[TestCase("No", ExpectedResult = false, Description = "'No' should return false")]
		[TestCase("no", ExpectedResult = false, Description = "'no' should return false")]
		[TestCase("TRUE", ExpectedResult = true, Description = "'TRUE' should return true")]
		[TestCase("True", ExpectedResult = true, Description = "'True' should return true")]
		[TestCase("true", ExpectedResult = true, Description = "'true' should return true")]
		[TestCase("YES", ExpectedResult = true, Description = "'YES' should return true")]
		[TestCase("Yes", ExpectedResult = true, Description = "'Yes' should return true")]
		[TestCase("yes", ExpectedResult = true, Description = "'yes' should return true")]
		public bool GetBooleanAttributeValueAttrName_Returns_True(string input)
		{
			// Test overload that takes the element and attr name.
			var element = new XElement("element", new XAttribute("boolAttr", input));
			return XmlUtils.GetBooleanAttributeValue(element, "boolAttr");
		}

		[TestCase(null, true, ExpectedResult = true, Description = "No attr should return default of true")]
		[TestCase(null, false, ExpectedResult = false, Description = "No attr should return default of false")]
		[TestCase(true, false, ExpectedResult = true, Description = "Has attr should not return default of false")]
		[TestCase(false, true, ExpectedResult = false, Description = "Has attr should not return default of true")]
		public bool GetOptionalBooleanAttributeValue(bool? actualValue, bool defaultValue)
		{
			var element = new XElement("element");

			if (actualValue.HasValue)
				element.Add(new XAttribute("boolAttr", actualValue.Value));

			return XmlUtils.GetOptionalBooleanAttributeValue(element, "boolAttr", defaultValue);
		}

		[TestCase(null, "DefaultValue", ExpectedResult = "DefaultValue", Description = "No attr should return default of 'DefaultValue'")]
		[TestCase("RealValue", "DefaultValue", ExpectedResult = "RealValue", Description = "Has attr should not return default of 'DefaultValue'")]
		public string GetOptionalAttributeValue_Using_Default(string actualValue, string defaultValue)
		{
			var element = new XElement("element");

			if (actualValue != null)
				element.Add(new XAttribute("attr", actualValue));

			return XmlUtils.GetOptionalAttributeValue(element, "attr", defaultValue);
		}

		[TestCase(null, ExpectedResult = null, Description = "No attr should return default of 'DefaultValue'")]
		[TestCase("RealValue", ExpectedResult = "RealValue", Description = "Has attr should not return default of 'DefaultValue'")]
		public string GetOptionalAttributeValue_Without_Using_Default(string actualValue)
		{
			var element = new XElement("element");

			if (actualValue != null)
				element.Add(new XAttribute("attr", actualValue));

			return XmlUtils.GetOptionalAttributeValue(element, "attr");
		}

		[TestCase("-1,1,2", "'-1,1,2' should return three integers in the array", "Expected order in array is: '-1,1,2'")]
		[TestCase("1,2", "'1,2' should return two integers in the array", "Expected order in array is: '1,2'")]
		[TestCase("2,1", "'2,1' should return two integers in the array", "Expected order in array is: '2,1'")]
		public void GetMandatoryIntegerListAttributeValue_Has_Correct_List(string sourceAttrData, string errorMessageCount, string errorMessageOrder)
		{
			var element = new XElement("element", new XAttribute("intArray", sourceAttrData));
			var resultArray = XmlUtils.GetMandatoryIntegerListAttributeValue(element, "intArray");
			var sourceArray = sourceAttrData.Split(',');
			Assert.AreEqual(sourceArray.Length, resultArray.Length, errorMessageCount);

			for (var idx = 0; idx < sourceArray.Length; idx++)
			{
				Assert.AreEqual(int.Parse(sourceArray[idx], CultureInfo.InvariantCulture), resultArray[idx], errorMessageOrder);
			}
		}

		[TestCase("1,2", "'1,2' should return two integers in the array", "Expected order in array is: '1,2'")]
		[TestCase("2,1", "'2,1' should return two integers in the array", "Expected order in array is: '2,1'")]
		public void GetMandatoryUIntegerListAttributeValue_Has_Correct_List(string sourceAttrData, string errorMessageCount, string errorMessageOrder)
		{
			var element = new XElement("element", new XAttribute("intArray", sourceAttrData));
			var resultArray = XmlUtils.GetMandatoryUIntegerListAttributeValue(element, "intArray");
			var sourceArray = sourceAttrData.Split(',');
			Assert.AreEqual(sourceArray.Length, resultArray.Length, errorMessageCount);

			for (var idx = 0; idx < sourceArray.Length; idx++)
			{
				Assert.AreEqual(uint.Parse(sourceArray[idx], CultureInfo.InvariantCulture), resultArray[idx], errorMessageOrder);
			}
		}

		[Test]
		[SetCulture("")]
		public void MakeStringFromList_Int()
		{
			var ci = Thread.CurrentThread.CurrentCulture;
			ci.NumberFormat.NegativeSign = "*";
			Assert.AreEqual("-1,-2,-3", XmlUtils.MakeStringFromList(new List<int> { -1, -2, -3 }));
		}

		[Test]
		public void MakeStringFromList_Uint()
		{
			Assert.AreEqual("1,2,3", XmlUtils.MakeStringFromList(new List<uint> { 1, 2, 3 }));
		}

		[Test]
		public void DecodeXmlAttributeTest()
		{
			string sFixed = XmlUtils.DecodeXmlAttribute("abc&def<ghi>jkl"mno'pqr&stu");
			Assert.AreEqual("abc&def<ghi>jkl\"mno'pqr&stu", sFixed, "First Test of DecodeXmlAttribute");

			sFixed = XmlUtils.DecodeXmlAttribute("abc&def
ghijklŸmno");
			Assert.AreEqual("abc&def\r\nghi\u001Fjkl\u007F\u009Fmno", sFixed, "Second Test of DecodeXmlAttribute");
		}

		[Test]
		public void FindElement_For_XElements()
		{
			var grandfather = new XElement("grandfather");
			var father = new XElement("father");
			grandfather.Add(father);
			var me = new XElement("me");
			father.Add(me);

			Assert.AreSame(grandfather, XmlUtils.FindElement(grandfather, "grandfather"));
			Assert.AreSame(father, XmlUtils.FindElement(grandfather, "father"));
			Assert.AreSame(me, XmlUtils.FindElement(grandfather, "me"));
		}

		[Test]
		public void FindNode_For_XmlNodes()
		{
			var dom = new XmlDocument();
			var root = dom.CreateElement("familyTree");
			dom.AppendChild(root);
			var grandfather = dom.CreateElement("grandfather");
			root.AppendChild(grandfather);
			var father = dom.CreateElement("father");
			grandfather.AppendChild(father);
			var me = dom.CreateElement("me");
			father.AppendChild(me);

			Assert.AreSame(grandfather, XmlUtils.FindNode(grandfather, "grandfather"));
			Assert.AreSame(father, XmlUtils.FindNode(grandfather, "father"));
			Assert.AreSame(me, XmlUtils.FindNode(grandfather, "me"));
		}

		[Test]
		public void FindIndexOfMatchingNode()
		{
			var threeStooges = new List<XElement>
			{
				new XElement("Larry"),
				new XElement("Moe"),
				new XElement("Curly")
			};
			var target = new XElement("Moe");
			// Moe is in the list.
			Assert.AreEqual(1, XmlUtils.FindIndexOfMatchingNode(threeStooges, target));

			// This one is not in the list.
			Assert.AreEqual(-1, XmlUtils.FindIndexOfMatchingNode(threeStooges, new XElement("Flopsie")));
		}

		[Test]
		public void SetAttribute_AddNewAttr()
		{
			var element = new XElement("element");
			XmlUtils.SetAttribute(element, "newAttr", "newAttrValue");
			Assert.IsNotNull(element.Attribute("newAttr"));
			Assert.AreEqual("newAttrValue", element.Attribute("newAttr").Value);
		}

		[Test]
		public void SetAttribute_ChangeAttrValue()
		{
			var element = new XElement("element", new XAttribute("oldAttr", "oldAttrValue"));
			XmlUtils.SetAttribute(element, "oldAttr", "newAttrValue");
			Assert.AreEqual("newAttrValue", element.Attribute("oldAttr").Value);
		}

		[Test]
		public void SetAttribute_SameAttrValue()
		{
			var element = new XElement("element", new XAttribute("oldAttr", "oldAttrValue"));
			XmlUtils.SetAttribute(element, "oldAttr", "oldAttrValue");
			Assert.AreEqual("oldAttrValue", element.Attribute("oldAttr").Value);
		}
	}
}


text:
module Mongoid #:nodoc:

  # Defines behaviour for the identity map in Mongoid.
  class IdentityMap < Hash

    # Get a document from the identity map by its id.
    #
    # @example Get the document from the map.
    #   map.get(Person, id)
    #
    # @param [ Class ] klass The class of the document.
    # @param [ Object ] id The document id.
    #
    # @return [ Document ] The matching document.
    #
    # @since 2.1.0
    def get(klass, id)
      return nil unless Mongoid.identity_map_enabled?
      documents_for(klass)[id]
    end

    # Get a single document that matches the provided criteria.
    #
    # @example Get the document for the criteria.
    #   map.match(Person.where(:_id => id))
    #
    # @param [ Criteria ] criteria The criteria to match.
    #
    # @return [ Document ] The first matching document.
    #
    # @since 2.1.0
    def match(criteria)
      return nil unless Mongoid.identity_map_enabled?
      documents_for(criteria.klass).values.detect do |doc|
        doc.matches?(criteria.selector)
      end
    end

    # Remove the document from the identity map.
    #
    # @example Remove the document.
    #   map.removed(person)
    #
    # @param [ Document ] document The document to remove.
    #
    # @return [ Document, nil ] The removed document.
    #
    # @since 2.1.0
    def remove(document)
      return nil unless Mongoid.identity_map_enabled? && document && document.id
      documents_for(document.class).delete(document.id)
    end

    # Puts a document in the identity map, accessed by it's id.
    #
    # @example Put the document in the map.
    #   identity_map.set(document)
    #
    # @param [ Document ] document The document to place in the map.
    #
    # @return [ Document ] The provided document.
    #
    # @since 2.1.0
    def set(document)
      return nil unless Mongoid.identity_map_enabled? && document && document.id
      documents_for(document.class)[document.id] = document
    end

    private

    # Get the documents in the identity map for a specific class.
    #
    # @example Get the documents for the class.
    #   map.documents_for(Person)
    #
    # @param [ Class ] klass The class to retrieve.
    #
    # @return [ Hash ] The documents.
    #
    # @since 2.1.0
    def documents_for(klass)
      self[klass] ||= {}
    end

    class << self

      # For ease of access we provide the same API to the identity map on the
      # class level, which in turn just gets the identity map that is on the
      # current thread.
      #
      # @example Get a document from the current identity map by id.
      #   IdentityMap.get(id)
      #
      # @example Set a document in the current identity map.
      #   IdentityMap.set(document)
      #
      # @since 2.1.0
      delegate *(
        Hash.public_instance_methods(false) +
        IdentityMap.public_instance_methods(false) <<
        { :to => :"Mongoid::Threaded.identity_map" }
      )
    end
  end
end


text:
using System;

namespace HandyQuery.Language
{
    /// <summary>
    /// Allows to initialize value only when needed. Initializes only once and then is reused.
    /// <para> WARNING: NOT THREAD SAFE! </para>
    /// </summary>
    internal struct ValueLazy<TValue>
    {
        private readonly Func<TValue> _create;

        private TValue _value;

        private bool _hasValue;

        public TValue Value
        {
            get
            {
                if (_hasValue) return _value;

                _value = _create();
                _hasValue = true; // order could be changed thus this code is not thread safe.
                return _value;
            }
        }

        public ValueLazy(Func<TValue> create)
        {
            _create = create;
            _value = default;
            _hasValue = false;
        }
    }
}


text:
<?php

/**
 * MovieEarning
 *
 * @property integer        $id
 * @property integer        $movie_id
 * @property \Carbon\Carbon $date
 * @property integer        $domestic
 * @property integer        $worldwide
 * @property \Carbon\Carbon $created_at
 * @property \Carbon\Carbon $updated_at
 * @property-read \Movie    $movie
 * @method static \Illuminate\Database\Query\Builder|\MovieEarning whereId($value)
 * @method static \Illuminate\Database\Query\Builder|\MovieEarning whereMovieId($value)
 * @method static \Illuminate\Database\Query\Builder|\MovieEarning whereDate($value)
 * @method static \Illuminate\Database\Query\Builder|\MovieEarning whereDomestic($value)
 * @method static \Illuminate\Database\Query\Builder|\MovieEarning whereWorldwide($value)
 * @method static \Illuminate\Database\Query\Builder|\MovieEarning whereCreatedAt($value)
 * @method static \Illuminate\Database\Query\Builder|\MovieEarning whereUpdatedAt($value)
 */
class MovieEarning extends Eloquent {

	/**
	 * Fields to format as dates
	 * @var array
	 */
	protected $dates = ['date'];

	/**
	 * Allow filling of these fields
	 * @var array
	 */
	protected $fillable = ['movie_id', 'date', 'domestic', 'worldwide'];

	/**
	 * Get the movie of the earning
	 *
	 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
	 */
	public function movie() {
		return $this->belongsTo('Movie');
	}

}


text:
package org.apache.flink.metrics;

import org.apache.flink.annotation.Internal;

/** A simple low-overhead {@link org.apache.flink.metrics.Counter} that is not thread-safe. */
@Internal
public class SimpleCounter implements Counter {

    /** the current count. */
    private long count;

    /** Increment the current count by 1. */
    @Override
    public void inc() {
        count++;
    }

    /**
     * Increment the current count by the given value.
     *
     * @param n value to increment the current count by
     */
    @Override
    public void inc(long n) {
        count += n;
    }

    /** Decrement the current count by 1. */
    @Override
    public void dec() {
        count--;
    }

    /**
     * Decrement the current count by the given value.
     *
     * @param n value to decrement the current count by
     */
    @Override
    public void dec(long n) {
        count -= n;
    }

    /**
     * Returns the current count.
     *
     * @return current count
     */
    @Override
    public long getCount() {
        return count;
    }
}


text:
FROM scratch

LABEL maintainer="darryl.west@raincitysoftware.com"

COPY ./geozipdb /geozipdb

EXPOSE 4539

# uses the default port 5000 and route /v1/zipdb
CMD ["/geozipdb"]


text:
package dev

import (
	"gogs.io/gogs/internal/conf"
	"gogs.io/gogs/internal/context"
	"gogs.io/gogs/internal/db"
)

func TemplatePreview(c *context.Context) {
	c.Data["User"] = db.User{Name: "Unknown"}
	c.Data["AppName"] = conf.App.BrandName
	c.Data["AppVersion"] = conf.App.Version
	c.Data["AppURL"] = conf.Server.ExternalURL
	c.Data["Code"] = "2014031910370000009fff6782aadb2162b4a997acb69d4400888e0b9274657374"
	c.Data["ActiveCodeLives"] = conf.Auth.ActivateCodeLives / 60
	c.Data["ResetPwdCodeLives"] = conf.Auth.ResetPasswordCodeLives / 60
	c.Data["CurDbValue"] = ""

	c.Success(c.Params("*"))
}


text:
using System.Linq;
using FluentAssertions;
using Highway.Data.EntityFramework.Security;
using Highway.Data.Security.DataEntitlements;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Rhino.Mocks;

namespace Highway.Data.Tests.Security
{
    [TestClass]
    public class SecuredInMemoryTests
    {
        [TestMethod]
        public void ShouldReturnCorrectIntersationOfMatchingAndNonMatchingRecordsForNullPermissiveMappings()
        {
            // Arrange
            IEntitlementProvider sessionGovernor = MockRepository.GenerateMock<IEntitlementProvider>();
            sessionGovernor.Expect(x => x.IsEntitledToAll(typeof(ExampleRoot))).Return(false);
            sessionGovernor.Expect(x => x.GetEntitledIds(typeof(ExampleRoot))).Return(new long[] { 1, 2, 3 });

            var securedMappingsCache = new MappingsCache(new ISecuredRelationshipBuilder[] { new NullPermissiveExampleSecuredRelationshipBuilder() });
            var context = new InMemoryDomainContext<ExampleDomain>(sessionGovernor, securedMappingsCache);
            var singleNonMatchingLeaf = new ExampleLeaf
                                            {
                                                SecuredRoot = new ExampleRoot { Id = 4 },
                                                SecuredRoots = new[]
                                                                   {
                                                                       new ExampleRoot { Id = 6 },
                                                                       new ExampleRoot { Id = 7 }
                                                                   }
                                            };
            var pluralNonMatchingLeaf = new ExampleLeaf
                                            {
                                                SecuredRoot = new ExampleRoot { Id = 4 },
                                                SecuredRoots = new[]
                                                                   {
                                                                       new ExampleRoot { Id = 5 }
                                                                   }
                                            };
            var combinedNonMatchingLeaf = new ExampleLeaf
                                              {
                                                  SecuredRoot = new ExampleRoot
                                                                    {
                                                                        Id = 5
                                                                    },
                                                  SecuredRoots = new[]
                                                                     {
                                                                         new ExampleRoot { Id = 6 },
                                                                         new ExampleRoot { Id = 7 }
                                                                     }
                                              };
            var combinedMatchingLeaf = new ExampleLeaf
                                           {
                                               SecuredRoot = new ExampleRoot
                                                                 {
                                                                     Id = 1
                                                                 },
                                               SecuredRoots = new[]
                                                                  {
                                                                      new ExampleRoot { Id = 2 },
                                                                      new ExampleRoot { Id = 3 }
                                                                  }
                                           };

            context.Add(singleNonMatchingLeaf);
            context.Add(pluralNonMatchingLeaf);
            context.Add(combinedNonMatchingLeaf);
            context.Add(combinedMatchingLeaf);
            context.Commit();

            // Act
            var exampleLeaves = context.AsQueryable<ExampleLeaf>();
            var results = exampleLeaves.ToList();

            //Assert
            results.Should().HaveCount(1);
        }

        [TestMethod]
        public void ShouldReturnCorrectIntersationOfMatchingAndNonMatchingRecordsForNullPropertiesOnNullPermissiveMappings()
        {
            // Arrange
            IEntitlementProvider sessionGovernor = MockRepository.GenerateMock<IEntitlementProvider>();
            sessionGovernor.Expect(x => x.IsEntitledToAll(typeof(ExampleRoot))).Return(false);
            sessionGovernor.Expect(x => x.GetEntitledIds(typeof(ExampleRoot))).Return(new long[] { 1, 2, 3 });

            var securedMappingsCache = new MappingsCache(new ISecuredRelationshipBuilder[] { new NullPermissiveExampleSecuredRelationshipBuilder() });
            var context = new InMemoryDomainContext<ExampleDomain>(sessionGovernor, securedMappingsCache);
            var singleNonMatchingLeaf = new ExampleLeaf
                                            {
                                                SecuredRoot = new ExampleRoot { Id = 4 },
                                                SecuredRoots = new[]
                                                                   {
                                                                       new ExampleRoot { Id = 5 }
                                                                   }
                                            };
            var pluralNonMatchingLeaf = new ExampleLeaf
                                            {
                                                SecuredRoot = new ExampleRoot { Id = 4 },
                                                SecuredRoots = new[]
                                                                   {
                                                                       new ExampleRoot { Id = 5 }
                                                                   }
                                            };
            var combinedNonMatchingLeaf = new ExampleLeaf
                                              {
                                                  SecuredRoot = new ExampleRoot
                                                                    {
                                                                        Id = 5
                                                                    },
                                                  SecuredRoots = new[]
                                                                     {
                                                                         new ExampleRoot { Id = 6 },
                                                                         new ExampleRoot { Id = 7 }
                                                                     }
                                              };
            var combinedMatchingLeaf = new ExampleLeaf
                                           {
                                               SecuredRoot = new ExampleRoot
                                                                 {
                                                                     Id = 1
                                                                 },
                                               SecuredRoots = new[]
                                                                  {
                                                                      new ExampleRoot { Id = 2 },
                                                                      new ExampleRoot { Id = 3 }
                                                                  }
                                           };
            var combinedNullMatchingLeaf = new ExampleLeaf();
            var singleNullMatchingLeaf = new ExampleLeaf
                                             {
                                                 SecuredRoots = new[]
                                                                    {
                                                                        new ExampleRoot { Id = 1 }
                                                                    }
                                             };
            var pluralNullMatchingLeaf = new ExampleLeaf
                                             {
                                                 SecuredRoot = new ExampleRoot { Id = 1 },
                                             };

            context.Add(singleNonMatchingLeaf);
            context.Add(pluralNonMatchingLeaf);
            context.Add(combinedNonMatchingLeaf);
            context.Add(combinedMatchingLeaf);
            context.Add(combinedNullMatchingLeaf);
            context.Add(singleNullMatchingLeaf);
            context.Add(pluralNullMatchingLeaf);
            context.Commit();

            // Act
            var exampleLeaves = context.AsQueryable<ExampleLeaf>();
            var results = exampleLeaves.ToList();

            //Assert
            results.Should().HaveCount(4);
        }

        [TestMethod]
        public void ShouldReturnLimitedResults()
        {
            IEntitlementProvider sessionGovernor = MockRepository.GenerateMock<IEntitlementProvider>();
            sessionGovernor.Expect(x => x.IsEntitledToAll(typeof(ExampleRoot))).Return(false);
            sessionGovernor.Expect(x => x.GetEntitledIds(typeof(ExampleRoot))).Return(new long[] { 1, 2, 3 });

            var securedMappingsCache = new MappingsCache(new ISecuredRelationshipBuilder[] { new NullPermissiveExampleSecuredRelationshipBuilder() });
            var context = new InMemoryDomainContext<ExampleDomain>(sessionGovernor, securedMappingsCache);
            var nonMatchingLeaf = new ExampleLeaf
                                      {
                                          SecuredRoot = new ExampleRoot { Id = 4 }
                                      };
            var matchingLeaf = new ExampleLeaf
                                   {
                                       SecuredRoot = new ExampleRoot { Id = 3 }
                                   };

            context.Add(nonMatchingLeaf);
            context.Add(matchingLeaf);
            context.Commit();

            var exampleLeaves = context.AsQueryable<ExampleLeaf>();
            var results = exampleLeaves.ToList();

            results.Should().HaveCount(1);
        }

        [TestMethod]
        public void ShouldReturnLimitedResultsFromCollection()
        {
            // Arrange
            IEntitlementProvider sessionGovernor = MockRepository.GenerateMock<IEntitlementProvider>();
            sessionGovernor.Expect(x => x.IsEntitledToAll(typeof(ExampleRoot))).Return(false);
            sessionGovernor.Expect(x => x.GetEntitledIds(typeof(ExampleRoot))).Return(new long[] { 1, 2, 3 });

            var securedMappingsCache = new MappingsCache(new ISecuredRelationshipBuilder[] { new NullPermissiveExampleSecuredRelationshipBuilder() });
            var context = new InMemoryDomainContext<ExampleDomain>(sessionGovernor, securedMappingsCache);
            var nonMatchingLeaf = new ExampleLeaf
                                      {
                                          SecuredRoots = new[] { new ExampleRoot { Id = 4 } }
                                      };
            var matchingLeaf = new ExampleLeaf
                                   {
                                       SecuredRoots = new[] { new ExampleRoot { Id = 3 } }
                                   };

            context.Add(nonMatchingLeaf);
            context.Add(matchingLeaf);
            context.Commit();

            // Act
            var exampleLeaves = context.AsQueryable<ExampleLeaf>();
            var results = exampleLeaves.ToList();

            //Assert
            results.Should().HaveCount(1);
        }

        [TestMethod]
        public void IsEntitledToAllWorks()
        {
            // Arrange

            // Act

            // Assert
            Assert.Inconclusive("We haven't written the test yet.");
        }
    }
}


text:
"""Generación fácil de widgets.

Con esta clase se pretende generar los componentes que se pueden ver dentro de,
una ventana de manera sencilla.
"""
try:
    from Tkinter import ttk
except ImportError:
    from tkinter import ttk

class Widgets:
    """Clase Widgets."""

    __button = None
    __checkbutton = None
    __frame = None
    # entry, Frame, Label, LabelFrame, Menubutton, PanedWindow, Radiobutton,
    # scale, Scrollbar, Combobox, Notebook, Progressbar, Separator, Sizegrip,
    # treeview

    def __init__(self):
        """Constructor por defecto."""
        self.__checkbutton = None

    def create_button(self, parent, text, callback):
        """Añade un bóton a la ventana.

        Con esto añadimos un bóton en la ventana en la posición que se,
        indique por el numero que hay en el segundo párametro.
        """
        button = ttk.Button(parent, text=text, command=callback)
        button.grid(row=6, column=6)

    def Frame(self, parent):
        """Modificación de frame."""
        self.__frame = ttk.Frame(parent, padding="3 3 12 12")


text:
<?php
/**
 * Created by PhpStorm.
 * User: Paulius
 * Date: 2016-10-09
 * Time: 22:56
 */

namespace DownloadCore;

use Symfony\Component\DomCrawler\Crawler;

class Job
{

    public function __construct(
        \Symfony\Component\DomCrawler\Crawler $Content,
        array $filesRequiredToOutput,
        $url,
        array $projectSettings,
        $uniqueBrowserId
    )
    {

        if (empty($filesRequiredToOutput)) {
            return $this;
        }

        foreach ($filesRequiredToOutput as $fileName => $fileData) {
            //$setMethodName = 'set' . ucfirst(strtolower($fileName));

            if (method_exists($this, $fileName)) {
                $this->$fileName($fileName, $Content, $url, $projectSettings, $uniqueBrowserId);
            } else {
                $this->{$fileName} = null;
            }

        }

        return $this;

    }

    /**
     * Gets property value.
     *  Property name is the same as file name from
     *  settings.js ["files-to-output"]
     *
     * @param $name
     * @return mixed
     */
    public function __get($name)
    {
        switch ($name) {
            default:
                return $this->$name;
        }
    }

    /**
     * This method is used as default method to set default values
     *  for properties that have no individual set{FileName} method.
     * Simply saying, this is the method we use for:
     *  "The feature of extracting content for $name file does not exist."
     *
     * For example, if the new file requirement is being added globally then such
     *  file will be created immediately by using this method. However,
     *  no content will be passed to the file, because
     *  the content extraction logic is not ready while not added by a developer.
     *
     *
     * @param $name
     * @param $value
     */
    public function __set($name, $value)
    {
        $this->$name = isset($value) ? $value : null;
    }

    /*********************************************
     *
     * METHODS TO GET DATA FOR SAVING TO FILES
     *
     * *******************************************
     */

    /**
     * Gets unique id to identify the process of download.
     * All items downloaded at the same try
     *  will have the same unique id associated with.
     *
     * @param $fileAndPropertyName
     * @param \Symfony\Component\DomCrawler\Crawler $Content
     * @param $url
     * @param array $projectSettings
     * @param string $uniqueBrowserId
     */
    protected function browser_id(
        $fileAndPropertyName,
        \Symfony\Component\DomCrawler\Crawler $Content,
        $url,
        array $projectSettings,
        $uniqueBrowserId
    )
    {
        $this->$fileAndPropertyName = $uniqueBrowserId;
    }

    /**
     * Gets datetime value. When the job posting was downloaded?
     *
     * @param $fileAndPropertyName
     * @param \Symfony\Component\DomCrawler\Crawler $Content
     * @param $url
     * @param array $projectSettings
     * @param string $uniqueBrowserId
     */
    protected function datetime(
        $fileAndPropertyName,
        \Symfony\Component\DomCrawler\Crawler $Content,
        $url,
        array $projectSettings,
        $uniqueBrowserId
    )
    {

        $value = new \DateTime('now', new \DateTimeZone('UTC'));
        $value = $value->format('Y-m-d H:i:s');

        $this->$fileAndPropertyName = $value;

    }

    /**
     * Gets project's name
     *
     * @param $fileAndPropertyName
     * @param \Symfony\Component\DomCrawler\Crawler $Content
     * @param $url
     * @param array $projectSettings
     * @param string $uniqueBrowserId
     */
    protected function project(
        $fileAndPropertyName,
        \Symfony\Component\DomCrawler\Crawler $Content,
        $url,
        array $projectSettings,
        $uniqueBrowserId
    )
    {

        $value = isset($projectSettings['project_name']) ? $projectSettings['project_name'] : null;

        $this->$fileAndPropertyName = $value;

    }

    /**
     * Gets URL or the job add
     *
     * @param $fileAndPropertyName
     * @param \Symfony\Component\DomCrawler\Crawler $Content
     * @param $url
     * @param array $projectSettings
     * @param string $uniqueBrowserId
     */
    protected function url(
        $fileAndPropertyName,
        \Symfony\Component\DomCrawler\Crawler $Content,
        $url,
        array $projectSettings,
        $uniqueBrowserId
    )
    {

        $this->$fileAndPropertyName = $url;

    }

    /**
     * Unique identifier identifying job posting in the source system
     * Defaults to URL
     *
     * @param $fileAndPropertyName
     * @param \Symfony\Component\DomCrawler\Crawler $Content
     * @param $url
     * @param array $projectSettings
     * @param string $uniqueBrowserId
     */
    protected function id(
        $fileAndPropertyName,
        \Symfony\Component\DomCrawler\Crawler $Content,
        $url,
        array $projectSettings,
        $uniqueBrowserId
    )
    {
        $this->$fileAndPropertyName = $url;
    }

    /**
     * Gets content_static value. This value is saved to file later.
     * This is the place for job content that DOES change.
     * For example, statistics of page views, unique visitors, applicants, etc.
     *
     * @param $fileAndPropertyName
     * @param \Symfony\Component\DomCrawler\Crawler $Content
     * @param $url
     * @param array $projectSettings
     * @param string $uniqueBrowserId
     */
    protected function content_dynamic(
        $fileAndPropertyName,
        \Symfony\Component\DomCrawler\Crawler $Content,
        $url,
        array $projectSettings,
        $uniqueBrowserId
    )
    {

        // Empty value by default
        $this->$fileAndPropertyName = '';

    }

    /**
     * Removes part of the content ($Crawler) matching css selector ($cssSelector)
     *
     * @param Crawler $Crawler
     * @param $cssSelector
     * @return Crawler
     */
    protected function _removeContentDynamic(\Symfony\Component\DomCrawler\Crawler $Crawler, $cssSelector)
    {
        $Crawler->filter($cssSelector)->each(function (Crawler $Crawler) {
            foreach ($Crawler as $node) {
                $node->parentNode->removeChild($node);
            }
        });

        return $Crawler;
    }

    /**
     * Removes inner part of the content ($Crawler) matching css selector ($cssSelector)
     *
     * @param \Symfony\Component\DomCrawler\Crawler $Content
     * @param $cssSelector
     * @return false|string
     */
    private function _removeInnerContentDynamic(\Symfony\Component\DomCrawler\Crawler $Content, $cssSelector)
    {
        $ContentFull = $Content->html();

        $ContentToRemove = $Content->filter($cssSelector);
        $ContentToRemove = $ContentToRemove->html();

        return mb_ereg_replace(preg_quote($ContentToRemove), '', $ContentFull);

    }

}


text:
<!DOCTYPE html>

		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

		<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.0/css/bootstrap-slider.min.css">

        {% load staticfiles %}
		<link rel="stylesheet" href="{% static 'style.css' %}" type="text/css">
        <link rel="stylesheet" href="static/codemirror-5.23.0/lib/codemirror.css">

		<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
		<link rel="stylesheet" href="{% static 'angular-input-stars.css' %}">

        <base href="/" />

                 Codereco

Test

Logout

			{% block content %}
        	{% endblock %}


text:
package com.aspose.pdf.cloud.examples.properties;

import com.aspose.pdf.api.PdfApi; import com.aspose.pdf.cloud.Utils;
import com.aspose.pdf.cloud.examples.Configuration;
import com.aspose.pdf.cloud.examples.pages.MovePDFToNewLocation;
import com.aspose.pdf.model.SaaSposeResponse;
import com.aspose.storage.api.StorageApi; import android.content.Context; import com.aspose.pdf.cloud.R; import java.io.File;

public class RemoveAllDocumentProperties {

	public static void execute(Context context) throws Exception {
//ExStart: 1
		String fileName = "Sample-Annotation.pdf";
		String storage = "";
		String folder = "";
		File input = Utils.stream2file("input","pdf", context.getResources().openRawResource(R.raw.Sample_Annotation));

		try
		{
			StorageApi storageApi = new StorageApi(Configuration.apiKey, Configuration.appSID, true);
			// Instantiate Aspose Words API SDK
			PdfApi pdfApi = new PdfApi(Configuration.apiKey, Configuration.appSID, true);
		    // Upload source file to aspose cloud storage
		    storageApi.PutCreate(fileName, "", "", input);

		    // Invoke Aspose.PDF Cloud SDK API to remove all document properties
		    SaaSposeResponse apiResponse = pdfApi.DeleteProperties(fileName, storage, folder);

		    if (apiResponse != null && apiResponse.getStatus().equals("OK"))
		    {
		    	System.out.println("Remove All Document Properties from a PDF, Done!");
		    }
		}
		catch (Exception ex)
		{
		    ex.printStackTrace();
		}
//ExEnd:  1

	}

}


text:
Adds an AWS::EKS::Cluster.ResourcesVpcConfig resource property to the template.
An object representing the VPC configuration to use for an Amazon EKS cluster.

## SYNTAX

```
Add-VSEKSClusterResourcesVpcConfig [[-SecurityGroupIds] <Object>] [-SubnetIds] <Object> [<CommonParameters>]
```

## DESCRIPTION
Adds an AWS::EKS::Cluster.ResourcesVpcConfig resource property to the template.
An object representing the VPC configuration to use for an Amazon EKS cluster.

## PARAMETERS

### -SecurityGroupIds
Specify one or more security groups for the cross-account elastic network interfaces that Amazon EKS creates to use to allow communication between your worker nodes and the Kubernetes control plane.
If you don't specify a security group, the default security group for your VPC is used.

PrimitiveItemType: String
Type: List
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-eks-cluster-resourcesvpcconfig.html#cfn-eks-cluster-resourcesvpcconfig-securitygroupids
UpdateType: Mutable

```yaml
Type: Object
Parameter Sets: (All)
Aliases:

Required: False
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -SubnetIds
Specify subnets for your Amazon EKS worker nodes.
Amazon EKS creates cross-account elastic network interfaces in these subnets to allow communication between your worker nodes and the Kubernetes control plane.

PrimitiveItemType: String
Type: List
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-eks-cluster-resourcesvpcconfig.html#cfn-eks-cluster-resourcesvpcconfig-subnetids
UpdateType: Mutable

```yaml
Type: Object
Parameter Sets: (All)
Aliases:

Required: True
Position: 2
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

## OUTPUTS

### Vaporshell.Resource.EKS.Cluster.ResourcesVpcConfig
## NOTES

## RELATED LINKS

[http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-eks-cluster-resourcesvpcconfig.html](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-eks-cluster-resourcesvpcconfig.html)


text:
require 'synapse/log'
require 'synapse/statsd'
require 'synapse/retry_policy'
require 'synapse/atomic'
require 'set'
require 'hashdiff'

class Synapse::ServiceWatcher
  class BaseWatcher
    include Synapse::Logging
    include Synapse::StatsD
    include Synapse::RetryPolicy

    LEADER_WARN_INTERVAL = 30

    attr_reader :name, :revision

    def initialize(opts={}, synapse, reconfigure_callback)
      super()

      @synapse = synapse
      @revision = 0

      raise ArgumentError, "reconfigure callback is nil" if reconfigure_callback.nil?
      @reconfigure_callback = reconfigure_callback

      # set required service parameters
      %w{name discovery}.each do |req|
        raise ArgumentError, "missing required option #{req}" unless opts[req]
      end

      @name = opts['name']
      @discovery = opts['discovery']

      # deprecated singular filter
      @singular_label_filter = @discovery['label_filter']
      unless @singular_label_filter.nil?
        log.warn "synapse: `label_filter` parameter is deprecated; use `label_filters` -- an array"
      end

      @label_filters = [@singular_label_filter, @discovery['label_filters']].flatten.compact

      @leader_election = opts['leader_election'] || false
      @leader_last_warn = Time.now - LEADER_WARN_INTERVAL

      @available_generators = @synapse.available_generators
      config_for_generator = Hash[
        @available_generators.collect do |generator_name, generator|
          watcher_provided_config = opts[generator_name] || {}
          normalized_generator_opts = generator.normalize_watcher_provided_config(
            @name, watcher_provided_config
          )
          [generator_name, normalized_generator_opts]
        end
      ]
      @config_for_generator = Synapse::AtomicValue.new(config_for_generator)

      # set initial backends to default servers, if any
      @default_servers = opts['default_servers'] || []
      @backends = Synapse::AtomicValue.new(@default_servers)

      @keep_default_servers = opts['keep_default_servers'] || false

      # If there are no default servers and a watcher reports no backends, then
      # use the previous backends that we already know about.
      @use_previous_backends = opts.fetch('use_previous_backends', true)

      # If backends discovered with this watcher lack ports or discovered
      # ports should be ignored, this option indicates that
      @backend_port_override = opts['backend_port_override'] || nil

      # For backwards compatability we support server_port_override
      # This will be removed in future versions
      if @backend_port_override.nil? && config_for_generator['haproxy']
        @backend_port_override = config_for_generator['haproxy']['server_port_override']
      end

      unless @backend_port_override.nil?
        unless @backend_port_override.to_s.match(/^\d+$/)
          raise ArgumentError, "Invalid backend_port_override value"
        end
      end

      # set a flag used to tell the watchers to exit
      # this is not used in every watcher
      @should_exit = false

      validate_discovery_opts
    end

    def haproxy
      log.warn "synapse: service watcher #{@name} accessing watcher.haproxy. This is DEPRECATED and will be removed in future iterations, use watcher.config_for_generator['haproxy'] instead."
      config_for_generator['haproxy']
    end

    # this should be overridden to actually start your watcher
    def start
      log.info "synapse: starting stub watcher; this means doing nothing at all!"
    end

    # this should be overridden to actually stop your watcher if necessary
    # if you are running a thread, your loop should run `until @should_exit`
    def stop
      log.info "synapse: stopping watcher #{self.name} using default stop handler"
      @should_exit = true
    end

    # this should be overridden to do a health check of the watcher
    def ping?
      true
    end

    # this can be overridden in child classes, if different from ping?
    def watching?
      ping?
    end

    # deep clone the hash to protect its readonly property
    def config_for_generator
      Marshal.load(Marshal.dump(@config_for_generator.get))
    end

    def backends
      filtered = backends_filtered_by_labels

      if @leader_election
        failure_warning = nil
        if filtered.empty?
          failure_warning = "synapse: service #{@name}: leader election failed: no backends to choose from"
        end

        all_backends_have_ids = filtered.all?{|b| b.key?('id') && b['id']}
        unless all_backends_have_ids
          failure_warning = "synapse: service #{@name}: leader election failed; not all backends include an id"
        end

        # no problems encountered, lets do the leader election
        if failure_warning.nil?
          smallest = filtered.sort_by{ |b| b['id']}.first
          log.debug "synapse: leader election chose one of #{filtered.count} backends " \
            "(#{smallest['host']}:#{smallest['port']} with id #{smallest['id']})"

          return [smallest]

        # we had some sort of problem, lets log about it
        elsif (Time.now - @leader_last_warn) > LEADER_WARN_INTERVAL
          @leader_last_warn = Time.now
          log.warn failure_warning
          return []
        end
      end

      return filtered
    end

    private
    def validate_discovery_opts
      raise ArgumentError, "invalid discovery method '#{@discovery['method']}' for base watcher" \
        unless @discovery['method'] == 'base'

      log.warn "synapse: warning: a stub watcher with no default servers is pretty useless" if @default_servers.empty?
    end

    def backends_filtered_by_labels
      filtered_backends = @backends.get.select do |backend|
        backend_labels = backend['labels'] || {}
        @label_filters.all? do |label_filter|
          (label_filter['condition'] == 'equals' &&
            backend_labels[label_filter['label']] == label_filter['value']) ||
          (label_filter['condition'] == 'not-equals' &&
            backend_labels[label_filter['label']] != label_filter['value'])
        end
      end
    end

    def set_backends(new_backends, new_config_for_generator = {})
      # Aggregate and deduplicate all potential backend service instances.
      new_backends = (new_backends + @default_servers) if @keep_default_servers
      # Substitute backend_port_override for the provided port
      new_backends = new_backends.collect do |b|
        port = @backend_port_override ? @backend_port_override : b['port']
        b.merge({'port' => port})
      end

      new_backends = new_backends.uniq {|b|
        [b['host'], b['port'], b.fetch('name', '')]
      }

      backends_updated = update_backends(new_backends)
      config_updated = update_config_for_generator(new_config_for_generator)

      if backends_updated || config_updated
        reconfigure!
        return true
      else
        return false
      end
    end

    def update_backends(new_backends)
      current_backends = @backends.get
      if new_backends.to_set == current_backends.to_set
        log.info "synapse: backends for service #{@name} do not change."
        return false
      end

      if new_backends.empty?
        if @default_servers.empty?
          if @use_previous_backends
            # Discard this update
            log.warn "synapse: no backends for service #{@name} and no default" \
              " servers for service #{@name}; using previous backends: #{current_backends.inspect}"
            return false
          else
            log.warn "synapse: no backends for service #{@name}, no default" \
              " servers for service #{@name} and 'use_previous_backends' is disabled;" \
              " dropping all backends"

            @backends.set([])
          end
        else
          log.warn "synapse: no backends for service #{@name};" \
            " using default servers: #{@default_servers.inspect}"
          @backends.set(@default_servers)
        end
      else
        log.info "synapse: discovered #{new_backends.length} backends for service #{@name}"
        @backends.set(new_backends)
      end

      return true
    end

    def update_config_for_generator(new_config_for_generator, do_reconfigure=false)
      if new_config_for_generator.nil? || new_config_for_generator.empty?
        log.info "synapse: no config_for_generator data from #{name} for" \
              " service #{@name}; keep existing config_for_generator"
        return false
      else
        log.info "synapse: discovered config_for_generator for service #{@name}"
        diff = HashDiff.diff(new_config_for_generator, config_for_generator)

        if diff.empty?
          log.info "synapse: config_for_generator for service #{@name} does not change."
          return false
        else
          @config_for_generator.set(new_config_for_generator)
          if do_reconfigure
            reconfigure!
          end
          return true
        end
      end
    end

    # Subclasses should not invoke this directly; it's only exposed so that it
    # can be overridden in subclasses.
    def reconfigure!
      @revision += 1
      @reconfigure_callback.call(backends, config_for_generator, @revision)
    end
  end
end


text:
#import <AppKit/NSTextStorage.h>
#import "../../Foundation/NSAttributedString/NSRangeEntries.h"

@interface NSTextStorage_concrete : NSTextStorage {
    NSMutableString *_string;
    NSRangeEntries *_rangeToAttributes;
}

@end


text:
/*
 * Spring ESPN
 */
package com.infinitemule.espn.api.athletes;

/**
 *
 */
public class AthleteLinks {

  private AthleteApiLinks api;
  private AthleteApiLinks web;
  private AthleteApiLinks mobile;

  public AthleteApiLinks getApi() {
    return api;
  }

  public void setApi(AthleteApiLinks api) {
    this.api = api;
  }

  public AthleteApiLinks getWeb() {
    return web;
  }

  public void setWeb(AthleteApiLinks web) {
    this.web = web;
  }

  public AthleteApiLinks getMobile() {
    return mobile;
  }

  public void setMobile(AthleteApiLinks mobile) {
    this.mobile = mobile;
  }

}


text:
<?php

namespace DIISH\SComDisBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Syndrome for syndrome surveillance.
 *
 * @author Natsuki Hara <toconuts@gmail.com>
 *
 * @ORM\Table(name="syndrome_surveillance")
 * @ORM\Entity(repositoryClass="DIISH\SComDisBundle\Entity\Syndrome4SurveillanceRepository")
 */
class Syndrome4Surveillance
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     */
    private $id;

    /**
     * @var string $name
     *
     * @ORM\Column(name="name", type="string", length=100, unique=true)
     * @Assert\Length(max = 100)
     */
    private $name;

    /**
     * @var integer $display_id
     *
     * @ORM\Column(name="display_id", type="integer", unique=true)
     */
    private $display_id;

    /**
     * __toString().
     *
     * @return string
     */
    public function __toString()
    {
        return $this->name;
    }

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

    /**
     * Set name
     *
     * @param string $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set display_id
     *
     * @param integer $displayId
     */
    public function setDisplayId($displayId)
    {
        $this->display_id = $displayId;
    }

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

    /**
     * Set id
     *
     * @param integer $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }
}


text:
FactoryGirl.define do
  factory :invitation do
    association :lesson
    association :user
  end
end


text:
import { expect } from 'chai';
import isValidString from '../../src/easy/isValidString';

describe('isValidString', () => {
  it('should return true if all alpha characters are surrounded by a "+"', () => {
    expect(isValidString('+d+=3=+s+')).to.be.ok;
  });

  it('should return false if any alpha characters is not surrounded by a "+"', () => {
    expect(isValidString('f++d+')).to.be.not.ok;
    expect(isValidString('++d+===+c++==a')).to.be.not.ok;
  });
});


text:
using System.Collections.Generic;

namespace Roulette.Tests
{
	public class Table_Tests
	{
		IOutputService console;

		public Table_Tests(IOutputService console)
		{
			this.console = console;
		}

		public bool Tests()
		{
			bool pass = true;

			Table table = new Table(1000, 2);
			Outcome outcome = new Outcome("a", 1);

			Bet tooLow = new Bet(1, outcome);
			table.PlaceBet(tooLow);
			table.PlaceBet(tooLow);

			// Test invalid minimums.
			bool exc = false;
			try
			{
				table.ValidateBets();
			}
			catch (System.Exception)
			{
				exc = true;
			}

			if (!exc)
			{
				pass = false;
				console.WriteLine("Failed to throw exception on bet below the minimum.");
			}

			// Test over the table limit.
			table = new Table(10, 1);
			Bet bet = new Bet(5, outcome);
			table.PlaceBet(bet);
			table.PlaceBet(bet);
			table.PlaceBet(bet);

			exc = false;
			try
			{
				table.ValidateBets();
			}
			catch (System.Exception)
			{
				exc = true;
			}

			if (!exc)
			{
				pass = false;
				console.WriteLine("Failed to throw exception on total bets above the table limit.");
			}

			// Test bets list.
			Bet unexpectedBet = new Bet(5000, outcome);

			foreach (var item in table.Bets)
			{
				if (item == unexpectedBet)
				{
					pass = false;
					console.WriteLine("Failure! Found unexpected bet in bet list.");
				}

				if (item != bet)
				{
					pass = false;
					console.WriteLine("Failure! Did not find bet: '" + bet.ToString() + "' in bet list.");
				}
			}

			// Test to string methods
			if (string.IsNullOrEmpty(table.ToString()))
			{
				pass = false;
				console.WriteLine("Failure! ToString is null or empty");
			}

			if (string.IsNullOrEmpty(table.ToStringFriendly()))
			{
				pass = false;
				console.WriteLine("Failure! ToStringFriendly is null or empty");
			}

			return pass;
		}

		public void DisplayToStringMethods()
		{
			Table table = new Table(1000, 2);
			Outcome outcome = new Outcome("a", 1);

			for (int i = 1; i <= 10; i++)
			{
				Bet bet = new Bet((ushort)(i * 10), outcome);
				table.PlaceBet(bet);
			}

			console.WriteFormat("Table.ToString: \n{0}\n", table.ToString());
			console.WriteFormat("Table.ToStringFriendly: \n{0}\n", table.ToStringFriendly());
		}
	}
}


text:
title: "Play Lab: For Loops"
view: page_curriculum
theme: none
---

<%= partial('curriculum_header', :unittitle=>'Course 4', :lesson=>11, :title=> 'Play Lab: For Loops', :unplugged=>false, :time=>30) %>

[content]

[together]

## Lesson Overview

Building on the previous Play Lab activity, students will add deeper interactivity as they build their own video games.

[summary]

## Teaching Summary
### **Getting Started**

[Introduction](#GetStarted)

### **Activity: Play Lab For Loops**

[Play Lab: For Loops](#Activity)

### **Extended Learning**

[Extension Activities](#Extended)

[/summary]

## Lesson Objectives
### Students will:

- Utilize for loops to count from 1 to 100
- Count by tens repeatedly using the for loop structure
- Employ skills from previous lessons to create more difficult looping algorithms

[/together]

[together]

## Getting Started

###  Introduction

## Activity
###  [Play Lab: For Loops](http://learn.code.org/s/course4/stage/11/puzzle/1)

Play Lab allows students to combine their new for loop skills with skills from past lessons to create fun games that are relevant to their life. The last puzzle of this stage is fairly unstructured, so a watchful eye may be helpful to encourage the class to integrate for loops into their final game.

[/together]

[together]

## Extended Learning
Use these activities to enhance student learning. They can be used as outside of class activities or other enrichment.

[/together]

[standards]

## Connections and Background Information

### PARCC / Smarter Balanced Assessment Skills

- Click / tap
- Drag and drop
- Scroll
- Select and drag / slide
- Select object

### ISTE Standards (formerly NETS)

- 1.a - Apply existing knowledge to generate new ideas, products, or processes.
- 1.b - Create original works as a means of personal or group expression.
- 1.c - Use models and simulation to explore complex systems and issues.
- 2.a - Interact, collaborate, and publish with peers, experts, or others employing a variety of digital environments and media.
- 2.b - Communicate information and ideas effectively to multiple audiences using a variety of media and formats.
- 4.b - Plan and manage activities to develop a solution or complete a project.
- 4.d - Use multiple processes and diverse perspectives to explore alternative solutions.
- 6.a - Understand and use technology systems.
- 6.c - Troubleshoot systems and applications.
- 6.d - Transfer current knowledge to learning of new technologies.

### CSTA K-12 Computer Science Standards

- CT.L1:3-01. Use technology resources (e.g., puzzles, logical thinking programs) to solve age appropriate problems.
- CT.L1:3-02. Use writing tools, digital cameras and drawing tools to illustrate thoughts, ideas, and stories in a step by step manner.
- CL.L1:3-02. Work cooperatively and collaboratively with peers teachers, and others using technology.
- CL.L1:6-01. Use productivity technology tools for individual and collaborative writing, communication, and publishing activities.
- CPP.L1:3-03. Create developmentally appropriate multimedia products with support from teachers, family, or student partners.
- CPP.L1:6-03. Use technology tools for individual and collaborative writing, communication and publishing activities.
- CPP.L1:6-05. Construct a program as a set of step-by-step instructions to be acted out.
- CPP.L1:6-06. Implement problem solutions using a block-based visual programming language.
- CT.L2-01. Use the basic steps in algorithmic problem solving to design solutions.
- CT.L2-06. Describe and analyze a sequence of instructions being followed.
- CT.L2-07. Represent data in a variety of ways: text, sounds, pictures, numbers.
- CT.L2-08. Use visual representations of problem states, structures, and data.
- CT.L2-12. Use abstraction to decompose a problem into sub-problems.
- CT.L2-14. Examine connections between elements of mathematics and computer science including binary numbers, logic, sets, and functions.
- CPP.L2-08. Demonstrate dispositions amenable to open-ended problem solving and programming.
- CT.L3A.03. Explain how sequence, selection, iteration, and recursion are building blocks of algorithms.

### Next-Gen Science Standards

- 3-5-ETS1-2. Generate and compare multiple possible solutions to a problem based on how well each is likely to meet the criteria and constraints of the problem.

### Common Core Mathematical Practices

- 1. Make sense of problems and persevere in solving them.
- 2. Reason abstractly and quantitatively.
- 4. Model with mathematics
- 5. Use appropriate tools strategically.
- 6. Attend to precision.
- 7. Look for and make use of structure.
- 8. Look for and express regularity in repeated reasoning.

### Common Core Math Standards

- 3.OA.3 - Use multiplication and division within 100 to solve word problems in situations involving equal groups, arrays, and measurement quantities.
- 4.NBT.B.4 - Fluently add and subtract multi-digit whole numbers using the standard algorithm.
- 5.NBT.B.5 - Fluently multiply multi-digit whole numbers using the standard algorithm.

### Common Core Language Arts Standards

- L.3.6 - Acquire and use accurately grade-appropriate conversational, general academic, and domain-specific words and phrases, including those that signal spatial and temporal relationships.
- W.3.3 - Write narratives to develop real or imagined experiences or events using effective technique, descriptive details, and clear event sequences.
- W.3.6 - With guidance and support from adults, use technology to produce and publish writing (using keyboarding skills) as well as to interact and collaborate with others.
- L.4.6 - Acquire and use accurately grade-appropriate general academic and domain-specific words and phrases, including those that signal precise actions, emotions, or states of being and that are basic to a particular topic.
- W.4.3 - Write narratives to develop real or imagined experiences or events using effective technique, descriptive details, and clear event sequences.
- W.4.6 - With some guidance and support from adults, use technology, including the Internet, to produce and publish writing as well as to interact and collaborate with others.
- L.5.6 - Acquire and use accurately grade-appropriate general academic and domain-specific words and phrases, including those that signal contrast, addition, and other logical relationships.
- W.5.3 - Write narratives to develop real or imagined experiences or events using effective technique, descriptive details, and clear event sequences.
- W.5.6 - With some guidance and support from adults, use technology, including the Internet, to produce and publish writing as well as to interact and collaborate with others.

[/standards]

[/content]

<link rel="stylesheet" type="text/css" href="../docs/morestyle.css"/>


text:
Vendor and product management
=============================

RefStack has implemented a vendor and product registration process so that test
results can be associated to products of vendors. The creation and management
of vendor and product entities can be done using the RefStack Server UI or
RefStack APIs. The following is a quick guide outlining the information related
to the creation and management of those entities.

Vendor entity
^^^^^^^^^^^^^

Any user who has successfully authenticated to the RefStack server can create
vendor entities. The minimum required information to create a vendor is the
vendor name. Users can update the rest of the vendor related information at a
later time.

Vendor admin
~~~~~~~~~~~~~

Whenever a user creates a vendor, this user will be added as the vendor's first
vendor admin. Subsequently, any admin of the vendor can add additional users to
the vendor. In RefStack, the "OpenStack User ID" of users are used as the
identities for adding users to vendors. At the time this document is written,
RefStack has not implemented user roles, and as such, all users of a vendor are
admin users.

Vendor types
~~~~~~~~~~~~~

There are four types of vendor entities in RefStack:

- Foundation:

  This is a special entity representing the OpenStack Foundation. Users belong
  to this entity are the Foundation admins. Foundation admins have visibility
  to all vendors and products.

- Private:

  A vendor will always be created with type "private". Vendors of this type
  are only visible to their own users and Foundation admins. Vendor users can
  initiate a registration request to the Foundation to change its type from
  "private" to "official".

- Pending

  Once a registration request is submitted, the vendor type will be changed
  automatically from type "private" to "pending". Vendors of this type are
  still only visible to their own users and Foundation admins.

- Official

  Once a vendor registration request is approved by the Foundation. The vendor
  type will be changed from "pending" to "official". Official vendors are
  visible to all RefStack users.

Product entity
^^^^^^^^^^^^^^

Any user who has successfully authenticated to the RefStack server can create
product entities. The minimum information needed to create a product entity is
as follows:

- Name

  This is the name of the product entity being created.

- Product type:

  Product types are defined by OpenStack as shown on the OpenStack Marketplace
  ( https://www.openstack.org/marketplace/ ). Currently, there are three types
  of products, namely: Distro & Appliances, Hosted Private Clouds and Public
  Clouds.

- Vendor

  This is the vendor which owns the product. A default vendor will be created
  for the user if no vendor entity exists for this user.

Whenever a product is created, by default, it is a private product and is only
visible to its vendor users. Vendor users can make a product publicly visible
as needed later. However, only products that are owned by official vendors can
be made publicly visible.

Product version
~~~~~~~~~~~~~~~

A default version is created whenever a product is created. The name of the
default version is blank. The default version is used for products that have
no version.  Users can add new product versions to the product as needed.


text:
using NDatabase.Exceptions;

namespace NDatabase.Core.Query.Execution
{
    ///
    ///
A class to execute a query on more than one class and then merges the result.

    ///
    /// <remarks>
    ///
A class to execute a query on more than one class and then merges the result. It is used when polymophic is set to true because
    ///     in this case, we must execute query on the main class and all its persistent subclasses

    /// </remarks>
    internal sealed class MultiClassGenericQueryExecutor : IQueryExecutor
    {
        private readonly IMultiClassQueryExecutor _executor;

        public MultiClassGenericQueryExecutor(IMultiClassQueryExecutor executor)
        {
            _executor = executor;

            // To avoid reseting the result for each query
            _executor.SetExecuteStartAndEndOfQueryAction(false);
        }

        #region IQueryExecutor Members

        ///
        ///   The main query execution method
        ///
        /// <param name="inMemory"> </param>
        /// <param name="startIndex"> </param>
        /// <param name="endIndex"> </param>
        /// <param name="returnObjects"> </param>
        /// <param name="queryResultAction"> </param>
        public IInternalObjectSet<T> Execute<T>(bool inMemory, int startIndex, int endIndex, bool returnObjects,
                                              IMatchingObjectAction queryResultAction)
        {
            if (_executor.GetStorageEngine().IsClosed())
            {
                throw new OdbRuntimeException(
                    NDatabaseError.OdbIsClosed.AddParameter(
                        _executor.GetStorageEngine().GetBaseIdentification().Id));
            }

            if (_executor.GetStorageEngine().GetSession().IsRollbacked())
                throw new OdbRuntimeException(NDatabaseError.OdbHasBeenRollbacked);

            // Get the main class
            var underlyingType = _executor.GetQuery().UnderlyingType;

            // this is done once.
            queryResultAction.Start();
            var allClassInfos =
                _executor.GetStorageEngine().GetSession().GetMetaModel().GetPersistentSubclassesOf(underlyingType);

            var nbClasses = allClassInfos.Count;
            for (var i = 0; i < nbClasses; i++)
            {
                var classInfo = allClassInfos[i];
                // Sets the class info to the current
                _executor.SetClassInfo(classInfo);
                // Then execute query
                _executor.Execute<T>(inMemory, startIndex, endIndex, returnObjects, queryResultAction);
            }

            queryResultAction.End();
            return queryResultAction.GetObjects<T>();
        }

        #endregion
    }
}