text:
// The following code was written in JavaScript by Gabriel de Diego

// FreeCodeCamp: BONFIRE (ALGORITHM CHALLENGES)

// NOTE: Algorithms are in order from beginner to advanced.
// Each algorithm will display given instructions along with my personal code to solve the problem.

/*
	Bonfire: Reverse a String
	--------------------------
	Reverse the provided string.

You may need to turn the string into an array before you can reverse it.

Your result must be a string.
*/

function reverseString(str) {
  str = str.split("").reverse().toString().replace(/,/g, "");
  return str;
}

reverseString('hello');

/*
	Bonfire: Factorialize a Number
	-------------------------------

	Return the factorial of the provided integer.

If the integer is represented with the letter n, a factorial is the product of all positive integers less than or equal to n.

Factorials are often represented with the shorthand notation n!

For example: 5! = 1 * 2 * 3 * 4 * 5 = 120f
*/

function factorialize(num)
{
  var oneLess = num - 1;

  while (oneLess > 0) {
    num = num * oneLess;
    oneLess--;
  }

  return  num;
}

factorialize(5);

/*
	Bonfire: Check for Palindromes
	-------------------------------

	Return true if the given string is a palindrome. Otherwise, return false.

A palindrome is a word or sentence that's spelled the same way both forward and backward, ignoring punctuation, case, and spacing.

You'll need to remove punctuation and turn everything lower case in order to check for palindromes.

We'll pass strings with varying formats, such as "racecar", "RaceCar", and "race CAR" among others.
*/

function palindrome(str) {
 var oldString = str.toLowerCase();
 var punctuation = /[!.?, ]\w+/g;

  for (var i = 0; i<oldString.length; i++) {
      if (oldString.charAt(i).match(/[!.?, ]\w+/g)) {
        oldString = oldString.replace(oldString.charAt(i), ' ');
      }
    }

    oldString = oldString.replace(/ /g, '');

    if (oldString == oldString.split('').reverse().join('')) {
        return true;
      }else{
          return false;
      }
}

palindrome("eye");

/*
	Bonfire: Find the Longest Word in a String
	------------------------------------------

	Return the length of the longest word in the provided sentence.

Your response should be a number.
*/

function findLongestWord(str)
{
  str = str.split(' '); //turns the string into an array.
  var max = 0;

  for (var i = 0; i < str.length; i++)
  {
    if (str[i].length > max)
    {
      max = str[i].length;
    }

  }
  return max;
}

findLongestWord('The quick brown fox jumped over the lazy dog');

/*
	Bonfire: Title Case a Sentence
	------------------------------

	Return the provided string with the first letter of each word capitalized.

For the purpose of this exercise, you should also capitalize connecting words like 'the' and 'of'.
*/

function titleCase(str) {
  return str.replace(/\w\S*/g, function(text) {
    return text.charAt(0).toUpperCase() + text.substr(1).toLowerCase();

  });
}

titleCase("I'm a little tea pot");

/*
	Bonfire: Return Largest Numbers in Arrays
	------------------------------------------

	Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.

Remember, you can iterate through an array with a simple for loop, and access each member with array syntax arr[i] .

If you are writing your own Chai.js tests, be sure to use a deep equal statement instead of an equal statement when comparing arrays.
*/

function largestOfFour(arr) {
  var largest = [];

  for(var innerIndex = 0; innerIndex < arr.length; innerIndex++) {
     largest.push(Math.max.apply(Math, arr[innerIndex]));
  }

  return largest;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

/*
	Bonfire: Confirm the Ending
	----------------------------

	Check if a string (first argument) ends with the given target string (second argument).
*/

function end(str, target) {

  //use regex to find the last word of every string
  var lastWordFinder = /\w+$/m;

  //use lastWordFinder to find the last word of the str and convert it to a String
  var extractedWord = str.match(lastWordFinder).toString();

  if (extractedWord === target) {
    return true;
  } else if (extractedWord.charAt(extractedWord.length - 1) === target){
    return true;
  } else {
    return false;
  }

  //return str;
}

end('If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing', 'mountain');

/*
	Bonfire: Repeat a string repeat a string
	-----------------------------------------

	Repeat a given string (first argument) n times (second argument). Return an empty string if n is a negative number.
*/

function repeat(str, num) {
  var holder = [];
  // repeat after me
  for(var i = 0; i < num; i++){
    holder.push(str);
  }
  return holder.join("");
}

repeat('abc', 3);

/*
	Bonfire: Truncate a string
	--------------------------

	Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a '...' ending.

Note that the three dots at the end add to the string length.
*/

function truncate(str, num) {
  // Clear out that junk in your trunk

if (str.length == num || str.length < num)
  {
    return str;
  }
  else
  {
    return str.substring(0,num).slice(0, str.search(" ")) + "...";
  }

}

truncate('A-tisket a-tasket A green and yellow basket', 11);

/*
	Bonfire: Chunky Monkey
	-----------------------

	Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a multidimensional array.
*/

function chunk(arr, size) {
 var finalArray = [];
  var secondArray = [];

  for (var i = 0; i < size; i++) {
    //for each instance shift the first element and place it into holder
    var holder = arr.shift();
    //once holder has a value, we push it, adding it to the the once empty array
    secondArray.push(holder);
  }

  finalArray.push(secondArray);
  finalArray.push(arr);
  return finalArray;
  //console.log(finalArray);
}

chunk(['a', 'b', 'c', 'd'], 2);

/*
	Bonfire: Slasher Flick
	-----------------------

	Return the remaining elements of an array after chopping off n elements from the head.
*/

function slasher(arr, howMany) {
  // it doesn't always pay to be first
  for(var i = 1; i <= howMany; i++) {
    arr.shift();
  }

  return arr;
}

slasher([1, 2, 3], 2);

/*
	Bonfire: Mutations
	-------------------

	Return true if the string in the first element of the array contains all of the letters of the string in the second element of the array.

For example, ['hello', 'Hello'], should return true because all of the letters in the second string are present in the first, ignoring case.

The arguments ['hello', 'hey'] should return false because the string 'hello' does not contain a 'y'.

Lastly, ['Alien', 'line'], should return true because all of the letters in 'line' are present in 'Alien'.
*/

function mutation(arr)
{
  //first element in the array
  var firstElement = arr[0].toString().toLowerCase();
  //second element that will now be considered the comparer
  var comparer = arr[1].toString().toLowerCase().split("");
  //the global variable used to hold
  var index;

  for(var i = 0; i < arr[1].length; i++)
  {
    index = firstElement.search(comparer[i]);

    if(index !== -1)
    {
      firstElement = firstElement.replace(firstElement.charAt(index), "");
      comparer.shift();
    }

  }

  //Final test after all comparisons
  if(comparer.length === 0){
    return true;
  } else {
    return false;
  }

}

mutation(['hello', 'hey']);

/*
	Bonfire: Falsey Bouncer
	------------------------

	Remove all falsey values from an array.

Falsey values in javascript are false, null, 0, "", undefined, and NaN.

*/

function bouncer(arr) {
  // Don't show a false ID to this bouncer.
  return arr.filter(Boolean);
}

bouncer([7, 'ate', '', false, 9]);

/*
	Bonfire: Where art thou
	------------------------

	Make a function that looks through a list (first argument) and returns an array of all objects that have equivalent property values (second argument).
*/

function where(collection, source)
{
  var arr = [];

  for(var i = 0; i < collection.length; i++)
  {
    if(collection[i].last === source.last)
    {
      arr.push(collection[i]);
    }
  }
  return arr;
}

where([{ first: 'Romeo', last: 'Montague' }, { first: 'Mercutio', last: null }, { first: 'Tybalt', last: 'Capulet' }], { last: 'Capulet' });

/*
	Bonfire: Seek and Destroy
	--------------------------

	You will be provided with an initial array (the first argument in the destroyer function), followed by one or more arguments. Remove all elements from the initial array that are of the same value as these arguments.
*/

function destroyer(arr) {
  var holder = [];

  for (var i = 1; i < arguments.length; i++)
    {
      holder.push(arr[i]);
    }

   function remove(value)
  {
    for (var index = 0; index < holder.length; index++)
      {
        return value != holder[0] && value != holder[1];
      }
  }

  return arr.filter(remove);
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

/*
	Bonfire: Where do I belong
	---------------------------

	Return the lowest index at which a value (second argument) should be inserted into a sorted array (first argument).

For example, where([1,2,3,4], 1.5) should return 1 because it is greater than 1 (0th index), but less than 2 (1st index).
*/

function where(arr, num) {
  // Find my place in this sorted array.
  arr.push(num);

  arr.sort(function(a, b){
    return a-b;
  });

  return arr.indexOf(num);
}

where([40, 60, 90, 10000, 20], 7111110);

/*
	Bonfire: Sum All Numbers in a Range
	------------------------------------

	We'll pass you an array of two numbers. Return the sum of those two numbers and all numbers between them.

The lowest number will not always come first.
*/

function sumAll(arr)
{
  // Find the max value
  var max = Math.max(arr[0], arr[1]);
  // Find the min value
  var min = Math.min(arr[0], arr[1]);

  var total = max + min;

  while (max > min)
    {
       max--;
       total += max;
    }

  // The final total will always be ahead by the min due to the way the while loop is set up, the last decrement will not take effect until it loops through the last time, thus making the total a constant overlap of the min.

  return total - min;
}

sumAll([1, 4]);

/*
	Bonfire: Search and Replace
	----------------------------

	Perform a search and replace on the sentence using the arguments provided and return the new sentence.

First argument is the sentence to perform the search and replace on.

Second argument is the word that you will be replacing (before).

Third argument is what you will be replacing the second argument with (after).

NOTE: Preserve the case of the original word when you are replacing it. For example if you mean to replace the word 'Book' with the word 'dog', it should be replaced as 'Dog'
*/

function replace(str, before, after) {

  if(before.charAt(0).toUpperCase() === before.charAt(0)){
    after = after.charAt(0).toUpperCase() + after.slice(1);
  }
 return str.replace(before, after);
}

replace("A quick brown fox mumped over the lazy dog", "mumped", "leaped");

/*
	Bonfire: Pig Latin
	-------------------

	Translate the provided string to pig latin.

Pig Latin takes the first consonant (or consonant cluster) of an English word, moves it to the end of the word and suffixes an "ay".

If a word begins with a vowel you just add "way" to the end.
*/

function translate(str) {
  var holder;
  var regex = /[aeiou]/;
  var first;

   holder = str.search(regex);

   if(holder > 0){
    first = str.substr(0, holder);
    str = str.substr(holder, str.length);
    return str + first + "ay";
  } else {
    return str + "way";
  }
}

translate("consonant");

/*
	Bonfire: DNA Pairing
	---------------------

	The DNA strand is missing the pairing element. Match each character with the missing element and return the results as a 2d array.

Base pairs are a pair of AT and CG. Match the missing element to the provided character.

Return the provided character as the first element in each array.
*/

function pair(str) {
  var newArray = [];
  str = str.split("");

  for (var i = 0; i < str.length; i++){
    // if the letter is A
    if (str[i] === 'A'){
      newArray.push([str[i], 'T']);

      // if the letter is T
    } else if (str[i] === 'T'){
      newArray.push([str[i], 'A']);

      // if the letter is C
    } else if (str[i] === 'C'){
      newArray.push([str[i], 'G']);

    } else {
      newArray.push([str[i], 'C']);
    }
  }

  return newArray;
}

// A pairs with T, C pairs with G

pair("GCG");

/*
	Bonfire: Boo who
	-----------------

	Check if a value is classified as a boolean primitive. Return true or false.

Boolean primitives are true and false.
*/

function boo(bool) {
  // What is the new fad diet for ghost developers? The Boolean.
  if(bool === true || bool === false){
    return true;
  } else {
    return false;
  }

  //return bool;
}

boo(null);

/*
	Bonfire: Sum All Odd Fibonacci Numbers
	--------------------------------------

	Return the sum of all odd Fibonacci numbers up to and including the passed number if it is a Fibonacci number.

The first few numbers of the Fibonacci sequence are 1, 1, 2, 3, 5 and 8, and each subsequent number is the sum of the previous two numbers.

As an example, passing 4 to the function should return 5 because all the odd Fibonacci numbers under 4 are 1, 1, and 3.
*/

function sumFibs(num) {

  var fibseq = [1,1]; // Create starting point for required Fibonacci Sequence
  var nextNum = 0; // Used to calcuate the next number needed in Fibonacci Sequence
  var sum = 0; // Sum all odd fibonacci numbers
  var brickWall; // Used to find the last number in sequence where num won't bounce over
 // var odds = []; USED TO DEBUG

  // Add next number to Fibonacci sequence as long as number arguement has not been met
  while (fibseq[fibseq.length-1] < num)
    {
      // Next Fibonacci sequence is always current number plus the prior
      nextNum = fibseq[fibseq.length-1] + fibseq[fibseq.length-2];

      // Add new number to the Fibonacci sequence
      fibseq.push(nextNum);

      //count++; USED TO DEBUG
    }

  // Figure out where the final iteration for the sum will stop
  if (fibseq[fibseq.length-1] > num)
    {
      brickWall = fibseq[fibseq.length-2];
    }
  else
    {
      brickWall = fibseq[fibseq.length-1];
    }

  // console.log("The brickwall is: " + brickWall + "\nFib indexOf brickWall is: " + fibseq.indexOf(brickWall)); USED TO DEBUG

  // iterate up until we reach the brick wall
  for (var x = 0; x <= fibseq.indexOf(brickWall); x++)
    {
      // is the number odd? If so, add it to the sum
      if (fibseq[x] % 2)
        {
          // odds.push(fibseq[x]); USED TO DEBUG
          sum += fibseq[x];
        }
    }

  // console.log("Odds are: " + odds); USED TO DEBUG

  return sum;

}

sumFibs(4);

/*
	Bonfire: Finders Keepers
	------------------------

	Create a function that looks through an array (first argument) and returns the first element in the array that passes a truth test (second argument).
*/

function find(arr, func)
{
  var finalArr = [];

  for (var i = 0; i < arr.length; i++)
  {
    if (func(arr[i]))
      {
        finalArr.push(arr[i]);
      }
  }

  return finalArr[0];
}

find([1, 2, 3, 4], function(num){ return num % 2 === 0; });

/*
	Bonfire: Drop it
	-----------------

	Drop the elements of an array (first argument), starting from the front, until the predicate (second argument) returns true.
*/

function drop(arr, func) {

  var newArray = [];

  for(var i = 0; i< arr.length; i++) {

    if(func(arr[i]) === true) {

      console.log(func(arr[i]) + " : " + arr[i]);
      newArray.push(arr[i]);
    }
  }
  return newArray;
}

drop([1, 2, 3], function(n) {return n < 3; });

/*
	Bonfire: Binary Agents
	------------------------

	Return an English translated sentence of the passed binary string.

The binary string will be space separated.

*/

function binaryAgent(str)
{
  var answerArray = [];
  var finalAnswer = [];

  // Holds the binary placement values and fixed octet length.
  var binaryVal = [128, 64, 32, 16, 8, 4, 2, 1];

  //split the str for easy array manipulation
  str = str.split(" ");

  for (var segment = 0; segment < str.length; segment++)
    {
      var sum = 0;

      for (var internal = binaryVal.length; internal >= 0; internal--)
        {
          console.log(str[segment].charAt(internal));
          if (str[segment].charAt(internal) === '1')
            {
              sum += binaryVal[internal];
            }

        }

      answerArray.push(sum);
    }

  for (var i = 0; i < answerArray.length; i++)
    {
      finalAnswer.push(String.fromCharCode(answerArray[i]));
    }

  return finalAnswer.join().replace(/,/g,"");
}

binaryAgent('01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111');

/*
	Bonfire: Everything Be True
	----------------------------

	Check if the predicate (second argument) returns truthy (defined) for all elements of a collection (first argument).

For this, check to see if the property defined in the second argument is present on every element of the collection.

Remember, you can access object properties through either dot notation or [] notation.
*/

function every(collection, pre) {
  for (var i = 0; i < collection.length; i++)
    {
        if (Boolean(collection[i][pre]))
          {
            if (i === collection.length-1)
              {
                return true;
              }
          }
        else
          {
            return false;
          }
    }
}

every([{'user': 'Tinky-Winky', 'sex': 'male'}, {'user': 'Dipsy', 'sex': 'male'}, {'user': 'Laa-Laa', 'sex': 'female'}, {'user': 'Po', 'sex': 'female'}], 'sex');

/*
	Bonfire: Make a Person
	-----------------------

	Fill in the object constructor with the methods specified in the tests.

Those methods are getFirstName(), getLastName(), getFullName(), setFirstName(first), setLastName(last), and setFullName(firstAndLast).

All functions that take an argument have an arity of 1, and the argument will be a string.

These methods must be the only available means for interacting with the object.
*/

var Person = function(firstAndLast) {

    var fullName = firstAndLast;

    this.getFirstName = function(){
      return fullName.substring(0, fullName.indexOf(" "));
    };

    this.getLastName = function(){
      return fullName.substring(fullName.indexOf(" ") + 1, fullName.length);
    };

    this.getFullName = function(){
      return fullName;
    };

    this.setFirstName = function(newFirst){
       fullName = newFirst + " " + this.getLastName();
    };

    this.setLastName = function(newLast){
        fullName = this.getFirstName() + " " + newLast;
    };

    this.setFullName = function(newName){
        fullName = newName;
    };
};

var bob = new Person('Bob Ross');

// This can be done more efficiently by incorporating prototypal inheritance and putting each function into the Person prototype (less code generated for each new instance of Person).

/*
	Bonfire: Map the Debris
	------------------------

	Return a new array that transforms the element's average altitude into their orbital periods.

The array will contain objects in the format {name: 'name', avgAlt: avgAlt}.

You can read about orbital periods on wikipedia.

The values should be rounded to the nearest whole number. The body being orbited is Earth.

The radius of the earth is 6367.4447 kilometers, and the GM value of earth is 398600.4418

*/

function orbitalPeriod(arr) {

  var arrFinal = [];

  // lowercase mu (greek symbol) used in formala is GM
  var GM = 398600.4418;
  var earthRadius = 6367.4447;

  for (var i = 0; i < arr.length; i++)
    {
      // (a) symbol in orbital period formula is earthRadius + avgAlt
      var a = earthRadius + arr[i].avgAlt;

      // Must round the final orbital period as per requirements
      var orbitalP = Math.round(2*Math.PI*Math.sqrt(Math.pow(a,3)/GM));

      arrFinal.push({name : arr[i].name, orbitalPeriod : orbitalP});
    }

  return arrFinal;
}

orbitalPeriod([{name : "sputkin", avgAlt : 35873.5553}]);

/*
Bonfire: Diff Two Arrays
-------------------------

Compare two arrays and return a new array with any items not found in both of the original arrays.
*/

function diff(arr1, arr2) {
  var newArr = [];

  var filterArr1 = arr1.filter(function(value){
    return arr2.indexOf(value) === -1;
  });

  var filterArr2 = arr2.filter(function(value){
    return arr1.indexOf(value) === -1;
  });

  return filterArr1.concat(filterArr2);
}

diff([1, 2, 3, 5], [1, 2, 3, 4, 5]);

/*
Bonfire: Missing letters
--------------------------

Find the missing letter in the passed letter range and return it.

If all letters are present in the range, return undefined.
*/

function fearNotLetter(str)
{
  var missing;
  // Create alphabet for algorithm
  var alphabet = 'abcdefghijklmnopqrstuvwxyz';

  // Obtain first element of argument
  var firstIndx = str.charAt(0);
  // Obtain second element of argument
  var lastIndx = str.charAt(str.length-1);

  // Obtain the section of the alphabet based on the first and last index of the argument. + 1 must be included as part of the second argument of the slice function due to the nature of the function
  var selected = alphabet.slice(alphabet.indexOf(firstIndx), alphabet.indexOf(lastIndx) + 1);

  console.log("First index of str contains: " + firstIndx + "\nLast index of str contains: " + lastIndx + "\nThe selected string from alphabet is: " + selected);

  for (var i = 0; i < selected.length; i++)
    {
      if (selected.charAt(i) !== str.charAt(i))
        {
          console.log(selected.charAt(i) + " Does NOT equal " + str.charAt(i));
          missing = selected.charAt(i);
          // Exit the for-loop entirely
          break;
        }
    }

  return missing;
}

fearNotLetter('abce');

/*
  Bonfire: Spinal Tap Case
  ------------------------
Convert a string to spinal case. Spinal case is all-lowercase-words-joined-by-dashes.

*/

function spinalCase(str)
{
  var res = str.replace(/[" _"]+/g, "-").split("");
  res[0] = res[0].toLowerCase(); // Die, you damn you bug.

  for (var x = 0; x < res.length; x++)
    {
      if (res[x] === res[x].toUpperCase() && res[x] !== "-" && res[x-1] !== "-")
        {
          res.splice(x, 0, " ");
          x++;
        }
    }
  for (var i = 0; i < res.length; i++)
    {
      if (res[i] === " " || res[i] === "_")
        {
          res[i] = "-";
        }
    }

  return res.join("").toLowerCase();

}

spinalCase('This Is Spinal Tap');

/*
Bonfire: Steamroller
-----------------------

Flatten a nested array. You must account for varying levels of nesting.

*/

function steamroller(arr)
{
  var newArr = [];
  console.log("The arrays length is: " + arr.length);
  // Convert array to string and remove all nests. Replace ALL commas(,) with empty space.
  arr = arr.join().replace(/,+/g,"");

  console.log(arr);

  for (var i = 0; i < arr.length; i++)
    {
      console.log(arr.charAt(i));
      // Use parseInt function to convert each string into a number
      if (!isNaN(arr.charAt(i)))
        {
          newArr.push(parseInt(arr.charAt(i)));
        }
      else
        {
          newArr.push(arr.charAt(i));
        }
    }

  return newArr;
}

steamroller([1, [2], [3, [[4]]]]);

/*
Bonfire: Smallest Common Multiple
------------------------------------
Find the smallest common multiple of the provided parameters that can be evenly divided by both, as well as by all sequential numbers in the range between these parameters.

The range will be an array of two numbers that will not necessarily be in numerical order.

e.g. for 1 and 3 - find the smallest common multiple of both 1 and 3 that is evenly divisible by all numbers between 1 and 3.

*/

function smallestCommons(arr)
{
  var dock = []; // this will contain the range with respect to the provided array arguement.
  var largest;
  var smallest;

  // find the largest and smallest number respectively
  if (arr[0] > arr[1])
    {
      largest = arr[0];
      smallest = arr[1];
      dock.push(largest);
    }
  else
    {
      largest = arr[1];
      smallest = arr[0];
      dock.push(largest);
    }

  // populate the dock
  for (var i = largest-1; i >= smallest; i--)
    {
      dock.push(i);
    }

  dock.sort(); // Once populated, sort the dock for easy iteration in the for-loop seen below.

  console.log(dock);

  /* All heavy lifting for algorithm begins here */

  var count = 1; // create count variable for loop
  var exit = 0;

  while (exit !== 1) // Create infinite loop due to the fact that for each run of the program the arguements may be different. This is countered by (return) statement within the nested if conditional
    {
      var top = largest * count;
      console.log(top);

      for (var x = 0; x < dock.length; x++)
        {
          if (top % dock[x] === 0)
            {
              console.log(top + " % " + dock[x] + " is equal to 0."); // Used to debug, view in console to see how the program works

              if (x === dock.length-1 && top % dock[x] === 0)
                {
                  exit = 1;
                  return top;
                }
            }
          else
            {
              console.log(top + " % " + dock[x] + " NOT EQUAL TO 0."); // Same as above
              break; // break out into the while loop if the condition has not been met.
            }
        }

      count++; // gradually increment count due to the nature of the top variable.
    }

}

smallestCommons([1,5]);

/*

Bonfire: Pairwise
--------------------
Return the sum of all indices of elements of 'arr' that can be paired with one other element to form a sum that equals the value in the second argument 'arg'. If multiple sums are possible, return the smallest sum. Once an element has been used, it cannot be reused to pair with another.

For example, pairwise([1, 4, 2, 3, 0, 5], 7) should return 11 because 4, 2, 3 and 5 can be paired with each other to equal 7.

pairwise([1, 3, 2, 4], 4) would only equal 1, because only the first two elements can be paired to equal 4, and the first element has an index of 0!

*/

function pairwise(arr, arg) {
  var answers = 0;
  var used = [];

  for (var i = 0; i < arr.length; i++) {
    for (var x = i+1; x < arr.length; x++) {

      if (((arr[i] + arr[x]) === arg) && (!used.includes(i) && !used.includes(x))) {
          answers += i + x;
          used.push(i);
          used.push(x);
          break;
       }
    }
  }

  return answers;
}

pairwise([1,4,2,3,0,5], 7);

/*
Bonfire: Sorted Union
----------------------
Write a function that takes two or more arrays and returns a new array of unique values in the order of the original provided arrays.

In other words, all values present from all arrays should be included in their original order, but with no duplicates in the final array.

The unique numbers should be sorted by their original order, but the final array should not be sorted in numerical order.
*/

function unite(arr1, arr2, arr3) {

  // NOTE: Brackets are not needed if one line of code is used after conditional

  for (var i = 1; i < arguments.length; i++)
    for (var x = 0; x< arguments[i].length; x++)
      if (arr1.indexOf(arguments[i][x]) == -1)
        arr1.push(arguments[i][x]);

  return arr1;
}

unite([1, 3, 2], [5, 2, 1, 4], [2, 1]);

/*
Bonfire: Arguments Optional
-----------------------------
Create a function that sums two arguments together. If only one argument is provided, then return a function that expects one argument and returns the sum.

For example, add(2, 3) should return 5, and add(2) should return a function.

Calling this returned function with a single argument will then return the sum:

var sumTwoAnd = add(2);

sumTwoAnd(3) returns 5.

If either argument isn't a valid number, return undefined.
*/

function add() {

  var holder = arguments[0];

    for (var i = 0; i < arguments.length; i++) {
      if (typeof(arguments[i]) !== 'number') {
        return undefined;
      } else if (i === 1) {
        return holder + arguments[1];
      }
    }

  // return anon function as closure
    return function(arg) {
      if (typeof(arg) === 'number') {
        return holder + arg;
      } else {
        return undefined;
      }
   };
 }

add(2)(3);

/*
  Inventory Update

Compare and update the inventory stored in a 2D array against a second 2D array of a fresh delivery.
Update the current existing inventory item quantities (in arr1).
If an item cannot be found, add the new item and quantity into the inventory array.
The returned inventory array should be in alphabetical order by item.

*/
function updateInventory(curInv, newInv) {
    var updated = curInv;
    var amount = 0;
    var itemName = 1;

    for (var i = 0; i < newInv.length; i++){
        for (var x = 0; x < curInv.length; x++){
            // check if the new item exists in current inv
            if (newInv[i][itemName] === curInv[x][itemName]) {
                console.log(curInv[x] + " | " + newInv[i])
                // update our current inventory with new incoming amount
                curInv[x][amount] += newInv[i][amount];
                break;
            }
            // if unable to match items push this item onto updated
            if (x === curInv.length-1) {
                updated.push(newInv[i]);
                break;
            }
        }

        // if the store is empty, push all new items into inventory
        if (curInv.length === 0) {
            updated.push(newInv[i]);
        }
    }

    // sort the list in alphabetical order
    updated.sort(function(a, b){
        if(a[1] < b[1]) return -1;
        if(a[1] > b[1]) return 1;
        return 0;
    });

    return updated;

}

// Example inventory lists
var curInv = [
    [21, "Bowling Ball"],
    [2, "Dirty Sock"],
    [1, "Hair Pin"],
    [5, "Microphone"]
];

var newInv = [
    [2, "Hair Pin"],
    [3, "Half-Eaten Apple"],
    [67, "Bowling Ball"],
    [7, "Toothpaste"]
];

updateInventory(curInv, newInv);

/* MORE ALGORITHMS COMING SOON! */


text:
package io.tromba.testdriver.core;

import io.tromba.testdriver.core.logging.TestdriverLogger;
import org.openqa.selenium.WebDriver;

import java.util.UUID;

/**
 * Data class for the essential components of a Testdriver test.
 */
public class TestEssential {

    private WebDriver driver;
    private TestdriverLogger logger;
    private UUID uuid;

    public TestEssential(WebDriver driver, TestdriverLogger logger) {
        this.uuid = UUID.randomUUID();
        this.driver = driver;
        this.logger = logger;
    }

    /**
     * Return the driver.
     * @return the correct WebDriver.
     */
    public WebDriver getDriver() {
        return driver;
    }

    /**
     * Get the logger.
     * @return the TestdriverLogger.
     */
    public TestdriverLogger getLogger() {
        return logger;
    }

    /**
     * Get the UUID
     * @return a String with the UUID.
     */
    public String getUuid() {
        return uuid.toString();
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Magento\Framework\Code\Reader;

require_once __DIR__ . '/_files/SourceArgumentsReaderTest.php.sample';

class SourceArgumentsReaderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Magento\Framework\Code\Reader\SourceArgumentsReader
     */
    protected $sourceArgumentsReader;

    protected function setUp()
    {
        $this->sourceArgumentsReader = new \Magento\Framework\Code\Reader\SourceArgumentsReader();
    }

    /**
     * @param string $class
     * @param array $expectedResult
     * @dataProvider getConstructorArgumentTypesDataProvider
     */
    public function testGetConstructorArgumentTypes($class, $expectedResult)
    {
        $class = new \ReflectionClass($class);
        $actualResult = $this->sourceArgumentsReader->getConstructorArgumentTypes($class);
        $this->assertEquals($expectedResult, $actualResult);
    }

    public function getConstructorArgumentTypesDataProvider()
    {
        return [
            [
                'Some\Testing\Name\Space\AnotherSimpleClass',
                [
                    '\Some\Testing\Name\Space\Item',
                    '\Imported\Name\Space\One',
                    '\Imported\Name\Space\AnotherTest\Extended',
                    '\Imported\Name\Space\Test',
                    '\Imported\Name\Space\Object\Under\Test',
                    '\Imported\Name\Space\Object',
                    '\Some\Testing\Name\Space\Test',
                    'array',
                    ''
                ],
            ],
            [
                '\stdClass',
                [null]
            ]
        ];
    }
}


text:
' Copyright (c) 2015 ZZZ Projects. All rights reserved
' Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods)
' Website: http://www.zzzprojects.com/
' Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927
' All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library

Public Module Extensions_486

	''' <summary>
	'''     A string extension method that query if this object contains the given value.
	''' </summary>
	''' <param name="this">The @this to act on.</param>
	''' <param name="value">The value.</param>
	''' <returns>true if the value is in the string, false if not.</returns>
	<System.Runtime.CompilerServices.Extension> _
	Public Function Contains(this As String, value As String) As Boolean
		Return this.IndexOf(value) <> -1
	End Function

	''' <summary>
	'''     A string extension method that query if this object contains the given value.
	''' </summary>
	''' <param name="this">The @this to act on.</param>
	''' <param name="value">The value.</param>
	''' <param name="comparisonType">Type of the comparison.</param>
	''' <returns>true if the value is in the string, false if not.</returns>
	<System.Runtime.CompilerServices.Extension> _
	Public Function Contains(this As String, value As String, comparisonType As StringComparison) As Boolean
		Return this.IndexOf(value, comparisonType) <> -1
	End Function
End Module


text:
package org.springframework.web.reactive.function.server;

import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;

import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RequestPredicates.accept;
import static org.springframework.web.reactive.function.server.RequestPredicates.contentType;
import static org.springframework.web.reactive.function.server.RequestPredicates.method;
import static org.springframework.web.reactive.function.server.RequestPredicates.methods;
import static org.springframework.web.reactive.function.server.RequestPredicates.path;
import static org.springframework.web.reactive.function.server.RequestPredicates.pathExtension;
import static org.springframework.web.reactive.function.server.RequestPredicates.queryParam;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;

/**
 * @author Arjen Poutsma
 */
public class ToStringVisitorTests {

	@Test
	public void nested() {
		HandlerFunction<ServerResponse> handler = new SimpleHandlerFunction();
		RouterFunction<ServerResponse> routerFunction = route()
				.path("/foo", builder ->
					builder.path("/bar", () -> route()
							.GET("/baz", handler)
							.build())
				)
				.build();

		ToStringVisitor visitor = new ToStringVisitor();
		routerFunction.accept(visitor);
		String result = visitor.toString();

		String expected = "/foo => {\n" +
				" /bar => {\n" +
				"  (GET && /baz) -> \n" +
				" }\n" +
				"}";
		assertThat(result).isEqualTo(expected);
	}

	@Test
	public void predicates() {
		testPredicate(methods(HttpMethod.GET), "GET");
		testPredicate(methods(HttpMethod.GET, HttpMethod.POST), "[GET, POST]");

		testPredicate(path("/foo"), "/foo");

		testPredicate(pathExtension("foo"), "*.foo");

		testPredicate(contentType(MediaType.APPLICATION_JSON), "Content-Type: application/json");

		ToStringVisitor visitor = new ToStringVisitor();
		contentType(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN).accept(visitor);
		assertThat(visitor.toString()).matches("Content-Type: \\[.+, .+\\]").contains("application/json", "text/plain");

		testPredicate(accept(MediaType.APPLICATION_JSON), "Accept: application/json");

		testPredicate(queryParam("foo", "bar"), "?foo == bar");

		testPredicate(method(HttpMethod.GET).and(path("/foo")), "(GET && /foo)");

		testPredicate(method(HttpMethod.GET).or(path("/foo")), "(GET || /foo)");

		testPredicate(method(HttpMethod.GET).negate(), "!(GET)");

		testPredicate(GET("/foo")
				.or(contentType(MediaType.TEXT_PLAIN))
				.and(accept(MediaType.APPLICATION_JSON).negate()),
				"(((GET && /foo) || Content-Type: text/plain) && !(Accept: application/json))");
	}

	private void testPredicate(RequestPredicate predicate, String expected) {
		ToStringVisitor visitor = new ToStringVisitor();
		predicate.accept(visitor);
		String result = visitor.toString();

		assertThat(result).isEqualTo(expected);
	}

	private static class SimpleHandlerFunction implements HandlerFunction<ServerResponse> {

		@Override
		public Mono<ServerResponse> handle(ServerRequest request) {
			return ServerResponse.ok().build();
		}

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

}


text:
    <kc-tabs-realm></kc-tabs-realm>

    <form class="form-horizontal" name="realmForm" novalidate kc-read-only="!access.manageRealm">
        <input type="text" readonly value="this is not a login form" style="display: none;">
        <input type="password" readonly value="this is not a login form" style="display: none;">

            * {{:: 'host' | translate}}

                <input class="form-control" id="smtpHost" type="text" ng-model="realm.smtpServer.host" placeholder="{{:: 'smtp-host' | translate}}" required>

            {{:: 'port' | translate}}

                <input class="form-control" id="smtpPort" type="number" ng-model="realm.smtpServer.port" placeholder="{{:: 'smtp-port' | translate}}">

            {{:: 'fromDisplayName' | translate}}

                <input class="form-control" id="smtpFromDisplayName" type="text" ng-model="realm.smtpServer.fromDisplayName" placeholder="{{:: 'sender-email-addr-display' | translate}}">

            <kc-tooltip>{{:: 'fromDisplayName.tooltip' | translate}}</kc-tooltip>

            * {{:: 'from' | translate}}

                <input class="form-control" id="smtpFrom" type="email" ng-model="realm.smtpServer.from" placeholder="{{:: 'sender-email-addr' | translate}}" required>

            {{:: 'replyToDisplayName' | translate}}

                <input class="form-control" id="smtpReplyToDisplayName" type="text" ng-model="realm.smtpServer.replyToDisplayName" placeholder="{{:: 'reply-to-email-addr-display' | translate}}">

            <kc-tooltip>{{:: 'replyToDisplayName.tooltip' | translate}}</kc-tooltip>

            {{:: 'replyTo' | translate}}

                <input class="form-control" id="smtpReplyTo" type="email" ng-model="realm.smtpServer.replyTo" placeholder="{{:: 'reply-to-email-addr' | translate}}">

            {{:: 'envelopeFrom' | translate}}

                <input class="form-control" id="smtpEnvelopeFrom" type="email" ng-model="realm.smtpServer.envelopeFrom" placeholder="{{:: 'sender-envelope-email-addr' | translate}}">

            <kc-tooltip>{{:: 'envelopeFrom.tooltip' | translate}}</kc-tooltip>

            {{:: 'enable-ssl' | translate}}

                <input ng-model="realm.smtpServer.ssl" name="smtpSSL" id="smtpSSL" onoffswitch on-text="{{:: 'onText' | translate}}" off-text="{{:: 'offText' | translate}}"/>

            {{:: 'enable-start-tls' | translate}}

                <input ng-model="realm.smtpServer.starttls" name="smtpStartTLS" id="smtpStartTLS" onoffswitch on-text="{{:: 'onText' | translate}}" off-text="{{:: 'offText' | translate}}"/>

            {{:: 'enable-auth' | translate}}

                <input ng-model="realm.smtpServer.auth" name="smtpAuth" id="smtpAuth" onoffswitch on-text="{{:: 'onText' | translate}}" off-text="{{:: 'offText' | translate}}"/>

            * {{:: 'username' | translate}}

                <input class="form-control" id="smtpUsername" type="text" ng-model="realm.smtpServer.user" placeholder="{{:: 'login-username' | translate}}" ng-disabled="!realm.smtpServer.auth" ng-required="realm.smtpServer.auth">

            * {{:: 'password' | translate}}

                <input class="form-control" id="smtpPassword" type="password" ng-model="realm.smtpServer.password" placeholder="{{:: 'login-password' | translate}}" ng-disabled="!realm.smtpServer.auth" ng-required="realm.smtpServer.auth">

                <button data-kc-save data-ng-disabled="!changed">{{:: 'save' | translate}}</button>
                <button data-kc-reset data-ng-disabled="!changed">{{:: 'cancel' | translate}}</button>

    </form>

<kc-menu></kc-menu>


text:
import threading
from changeover.common import syncutils
from changeover.common.settings import Settings
from common import saxslog

class ChangeoverThread(threading.Thread):
    """
    Thread class that performs the changeover
    """
    def __init__(self, folder_create=False, folder_folders={},
                       rsync_enabled=False, rsync_checksum=True,
                       rsync_compress=True, rsync_exclude=[],
                       post_checksum=True, post_delete=False):
        """
        Constructor of the changeover thread class
        """
        super(ChangeoverThread, self).__init__()
        conf = Settings()
        self._logger, self._raven_client = saxslog.setup(__name__,
                                                         conf['logging']['debug'],
                                                         conf['logging']['sentry'])
        self._stop = threading.Event()

    def run(self):
        """
        The main run method of the thread.
        """
        self._stop.wait(10)
        if self.stopped():
            return

    def stop(self):
        """
        Stops the thread.
        """
        self._stop.set()

    def stopped(self):
        """
        Returns the stop flag of the thread
        """
        return self._stop.is_set()


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.security.fluent;

import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;
import com.azure.resourcemanager.security.fluent.models.IoTSecurityAggregatedRecommendationInner;

/**
 * An instance of this class provides access to all the operations defined in
 * IotSecuritySolutionsAnalyticsRecommendationsClient.
 */
public interface IotSecuritySolutionsAnalyticsRecommendationsClient {
    /**
     * Use this method to get the aggregated security analytics recommendation of yours IoT Security solution. This
     * aggregation is performed by recommendation name.
     *
     * @param resourceGroupName The name of the resource group within the user's subscription. The name is case
     *     insensitive.
     * @param solutionName The name of the IoT Security solution.
     * @param aggregatedRecommendationName Name of the recommendation aggregated for this query.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return ioT Security solution recommendation information along with {@link Response}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    Response<IoTSecurityAggregatedRecommendationInner> getWithResponse(
        String resourceGroupName, String solutionName, String aggregatedRecommendationName, Context context);

    /**
     * Use this method to get the aggregated security analytics recommendation of yours IoT Security solution. This
     * aggregation is performed by recommendation name.
     *
     * @param resourceGroupName The name of the resource group within the user's subscription. The name is case
     *     insensitive.
     * @param solutionName The name of the IoT Security solution.
     * @param aggregatedRecommendationName Name of the recommendation aggregated for this query.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return ioT Security solution recommendation information.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    IoTSecurityAggregatedRecommendationInner get(
        String resourceGroupName, String solutionName, String aggregatedRecommendationName);

    /**
     * Use this method to get the list of aggregated security analytics recommendations of yours IoT Security solution.
     *
     * @param resourceGroupName The name of the resource group within the user's subscription. The name is case
     *     insensitive.
     * @param solutionName The name of the IoT Security solution.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of IoT Security solution aggregated recommendations as paginated response with {@link
     *     PagedIterable}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    PagedIterable<IoTSecurityAggregatedRecommendationInner> list(String resourceGroupName, String solutionName);

    /**
     * Use this method to get the list of aggregated security analytics recommendations of yours IoT Security solution.
     *
     * @param resourceGroupName The name of the resource group within the user's subscription. The name is case
     *     insensitive.
     * @param solutionName The name of the IoT Security solution.
     * @param top Number of results to retrieve.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of IoT Security solution aggregated recommendations as paginated response with {@link
     *     PagedIterable}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    PagedIterable<IoTSecurityAggregatedRecommendationInner> list(
        String resourceGroupName, String solutionName, Integer top, Context context);
}


text:
package com.labstack;

import static com.labstack.ClientTest.WEBPAGE_SERVICE;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import org.junit.jupiter.api.Test;
import com.labstack.webpage.ImageRequest;
import com.labstack.webpage.ImageResponse;
import com.labstack.webpage.PDFRequest;
import com.labstack.webpage.PDFResponse;

class WebpageServiceTest {

    @Test
    void lookup() {
        assertDoesNotThrow(() -> {
            ImageRequest request = ImageRequest.builder().url("http://amazon.com").build();
            ImageResponse response = WEBPAGE_SERVICE.image(request);
            assertNotEquals("", response.getImage());
        });
    }

    @Test
    void pdf() {
        assertDoesNotThrow(() -> {
            PDFRequest request = PDFRequest.builder().url("http://amazon.com").build();
            PDFResponse response = WEBPAGE_SERVICE.pdf(request);
            assertNotEquals("", response.getPdf());
        });
    }
}


text:
{-# LANGUAGE LambdaCase, QuasiQuotes, OverloadedStrings #-}
module PrettySpec where

import qualified Data.Text as Text
import Test.Hspec
import Test.QuickCheck

import Grin.Pretty
import Grin.Grin
import Grin.TH
import Grin.Parse
import Test.Test
import Test.Assertions

runTests :: IO ()
runTests = hspec spec

spec :: Spec
spec = do

  describe "external defintions" $ do
    it "primop + ffi" $ do
      let sample = [prog|
        primop effectful
          _prim_string_print  :: T_String -> T_Unit
          _prim_read_string   :: T_String

          "newArrayArray#" :: {"Int#"} -> {"State#" %s} -> {"GHC.Prim.Unit#" {"MutableArrayArray#" %s}}

        primop pure
          _prim_string_concat   :: T_String -> T_String -> T_String

        ffi pure
          newArrayArray :: {Int} -> {State %s} -> {GHC.Prim.Unit {MutableArrayArray %s}}

        grinMain = pure ()
        |]
      let before = parseGrin "" (Text.pack . show $ (PP $ prettyProgram WithExternals sample))
          after = Program

            [ External
                { eName = "_prim_string_print"
                , eRetType = TySimple T_Unit
                , eArgsType = [ TySimple T_String ]
                , eEffectful = True
                , eKind = PrimOp
                }
            , External
                { eName = "_prim_read_string"
                , eRetType = TySimple T_String
                , eArgsType = []
                , eEffectful = True
                , eKind = PrimOp
                }
            , External
                { eName = "newArrayArray#"
                , eRetType = TyCon "GHC.Prim.Unit#"
                    [ TyCon "MutableArrayArray#" [ TyVar "s" ] ]
                , eArgsType =
                    [ TyCon "Int#" []
                    , TyCon "State#" [ TyVar "s" ]
                    ]
                , eEffectful = True
                , eKind = PrimOp
                }
            , External
                { eName = "_prim_string_concat"
                , eRetType = TySimple T_String
                , eArgsType =
                    [ TySimple T_String
                    , TySimple T_String
                    ]
                , eEffectful = False
                , eKind = PrimOp
                }
            , External
                { eName = "newArrayArray"
                , eRetType = TyCon "GHC.Prim.Unit"
                    [ TyCon "MutableArrayArray" [ TyVar "s" ] ]
                , eArgsType =
                    [ TyCon "Int" []
                    , TyCon "State" [ TyVar "s" ]
                    ]
                , eEffectful = False
                , eKind = FFI
                }
            ]
            [ Def "grinMain" [] ( SReturn Unit ) ]
      (fmap PP before) `shouldBe` (Right $ PP after)


text:
$.fn.postalCode = function(url, target) {
    var input = $(this);
    input.autocomplete({
        source : function(requete, response){
            var motcle = input.val();
            var data = 'motcle='+ motcle;
            $.ajax({
                type:"POST",
                url: url,
                datatype: 'json',
                data: data,
                success: function(donnee){
                    response($.map(donnee, function(objet){
                        return objet;
                    }));
                }
            });
        },
        minLength: 3,
        appendTo: input.parent('.col-sm-7'.$this),
        select: function(event, ui){
            target.val(ui.item.name);
        }
    });
};


text:
package org.trustedanalytics.services.downloader.store;

import org.trustedanalytics.services.downloader.core.DownloadRequest;
import org.trustedanalytics.services.downloader.utils.MemoryUniqGeneratedKeysStore;

import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

@Component
@Profile("default")
public class MemoryDownloadRequestStore implements DownloadRequestsStore {

    private MemoryUniqGeneratedKeysStore<DownloadRequest> store =
            new MemoryUniqGeneratedKeysStore<>();

    @Override
    public DownloadRequest add(DownloadRequest downloadRequest) {
        String id = store.put(downloadRequest);
        downloadRequest.setId(id);
        return downloadRequest;
    }

    @Override
    public DownloadRequest get(String id) {
        return store.get(id);
    }

    @Override
    public boolean has(String id) {
        return store.has(id);
    }
}


text:
ARG1=$1

PROJ=Sensorama
TOOL=xcodebuild
if [ "x$BUILDTOOL" != "x" ]; then
	TOOL="$BUILDTOOL"
fi

OPTS=""
if [ "x${TRAVIS}" != "x" ]; then
	OPTS='CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY='
fi

if [ "$BUILD_JOBS" != "" ]; then
	OPTS="$OPTS -IDEBuildOperationMaxNumberOfConcurrentCompileTasks=${BUILD_JOBS}"
fi

function build_normal() {
	(
		cd ${PROJ}

		pod install

		$TOOL $OPTS archive \
			-workspace ${PROJ}.xcworkspace \
			-scheme ${PROJ}
	)
}

function test_normal() {
	(
		cd ${PROJ}

		xcodebuild -workspace ${PROJ}.xcworkspace \
			-scheme "${PROJ}Tests" \
			-sdk iphonesimulator \
			-destination 'platform=iOS Simulator,name=iPhone 6' \
			test | xcpretty
	)
}

function test_fastlane() {
	(
		cd ${PROJ}

		scan --workspace ${PROJ}.xcworkspace --scheme ${PROJ}Tests
	)
}

function build_fastlane() {
	export PATH=`pwd`/scripts/git-hack:$PATH
	(cd Sensorama && fastlane beta)
}

function build_fastlane_release() {
	export PATH=`pwd`/scripts/git-hack:$PATH
	(cd Sensorama && FASTLANE_ITUNES_TRANSPORTER_USE_SHELL_SCRIPT=1 fastlane release)
}

function ci_env_init() {
	openssl aes-256-cbc -K $encrypted_c972abe91c70_key -iv $encrypted_c972abe91c70_iv -in scripts/travis.enc -out scripts/travis -d
	eval "$(ssh-agent -s)"
	chmod 600 scripts/travis
	ssh-add scripts/travis
	pod repo update
}

function tools_bootstrap () {
	scripts/bootstrap.sh
	exit 0
}

if [ ! -z "$TRAVIS" ]; then
	echo "# will init CI environment"
	ci_env_init
	echo "# CI environment initialized"
fi

if   [ "$ARG1" = "bootstrap" ]; then
	tools_bootstrap
elif [ "$ARG1" = "fastlane" ]; then
	build_fastlane
elif [ "$ARG1" = "fastlane_release" ]; then
	build_fastlane_release
elif [ "$ARG1" = "normal" ]; then
	build_normal
elif [ "$ARG1" = "test_normal" ]; then
	test_normal
elif [ "$ARG1" = "test_fastlane" ]; then
	test_fastlane
else
	echo "build.sh [bootstrap|fastlane|normal|fastlane_release|test_normal|test_fastlane]"
fi


text:
Fable plugin for NUnit tests

## Installation

```sh
$ npm install --save-dev fable-plugins-nunit
```

## Usage

```sh
$ fable MyScript.fsx --plugins node_modules/fable-plugins-nunit/Fable.Plugins.NUnit.dll
```

Check [the tutorial](http://fsprojects.github.io/Fable/samples/nunit/) for more info.


text:
module Pageflow
  # A registry of additional rows to display in attribute tables on
  # admin pages.
  #
  # @since 12.2
  module Admin
    class AttributesTableRows
      # @api private
      def initialize
        @rows = {}
      end

      # Insert an additional row into an attribute table.
      #
      # @param resource_name [Symbol] Either :entry, :account or :theming.
      #
      # @param name [Symbol] Name of the attribute to display.
      #
      # @param options [Hash] Supports same options as
      #   ActiveAdmin::Views::AttributesTable#row, in addition to:
      #
      # @option options [Symbol] :before Insert row before row with
      #   given name. Append to table if not found.
      #
      # @option options [Symbol] :after Insert row after row with
      #   given name. Append to table if not found.
      #
      # @yieldparam resource [ActiveRecord::Base] A block which is
      #   evaluated in the context of the Arbre template to render the
      #   contents of the cell.
      def register(resource_name, name, options = {}, &block)
        @rows[resource_name] ||= []
        @rows[resource_name] << {
          name: name,
          block: block,
          options: options.except(:before, :after),
          **options.slice(:before, :after)
        }
      end

      # @api private
      def for(resource_name)
        @rows.fetch(resource_name, [])
      end
    end
  end
end


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

namespace InstallationSampleConsoleApp
{
    public class SetDatabaseSettingsVersion : DatabaseVersion
    {
        public SetDatabaseSettingsVersion()
            : base(1)
        {
        }

        public override void AddDbChanges(List<IDbChange> dbChangeList)
        {

            var databaseSettings = dbChangeList.AddNewDatabaseSettings(); ;
            databaseSettings.CreateLogin("MyLogin2")
                .WithUser("MyUser2")
                .AddRoleMembershipDataReader()
                .AddRoleMembershipDataWriter();
        }
    }
}


text:
import nose
from os import path

from pyffi.utils.withref import ref
from pyffi.formats.nif import NifFormat

from pyffi.utils.withref import ref
from pyffi.formats.nif import NifFormat

def n_create_normal_map(n_nitexturingproperty):
    """Adds a diffuse texture to a NiTexturingProperty"""

    n_nitexturingproperty.has_normal_texture = True

    n_nisourcetexture = NifFormat.NiSourceTexture()

    file_path = 'textures' + path.sep + 'normal' + path.sep + 'normal.dds'
    n_nisourcetexture.file_name = file_path.encode()
    n_nisourcetexture.pixel_layout = NifFormat.PixelLayout.PIX_LAY_DEFAULT # 6
    n_nisourcetexture.use_mipmaps = 1

    with ref(n_nitexturingproperty.normal_texture) as n_texdesc:
        n_texdesc.source = n_nisourcetexture

def n_check_normal_property(n_tex_prop):

    nose.tools.assert_is_instance(n_tex_prop, NifFormat.NiTexturingProperty)
    nose.tools.assert_equal(n_tex_prop.has_normal_texture, True)

def n_check_normal_source_texture(n_nisourcetexture, n_texture_path):

    nose.tools.assert_is_instance(n_nisourcetexture, NifFormat.NiSourceTexture)

    n_split_path = n_texture_path.split(path.sep)
    n_rel_path = n_split_path[len(n_split_path)-3:] #get a path relative to \\textures folder

    n_src_path = n_nisourcetexture.file_name.decode()
    n_src_path = n_src_path.split(path.sep)

    nose.tools.assert_equal(n_src_path, n_rel_path)
    nose.tools.assert_equal(n_nisourcetexture.pixel_layout, NifFormat.PixelLayout.PIX_LAY_DEFAULT) # 6
    nose.tools.assert_equal(n_nisourcetexture.use_mipmaps, NifFormat.MipMapFormat.MIP_FMT_YES) # 1
    nose.tools.assert_equal(n_nisourcetexture.use_external, 1)


text:
ACCEPTED

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

#### Published in
Nachr. Königl. Ges. Wiss. Georg-Augusts-Univ. 1868:72. 1868

#### Original name
null

### Remarks
null


text:
package fake

import (
	api "github.com/openshift/origin/pkg/project/api"
	pkg_api "k8s.io/kubernetes/pkg/api"
	unversioned "k8s.io/kubernetes/pkg/api/unversioned"
	core "k8s.io/kubernetes/pkg/client/testing/core"
	labels "k8s.io/kubernetes/pkg/labels"
	watch "k8s.io/kubernetes/pkg/watch"
)

// FakeProjects implements ProjectResourceInterface
type FakeProjects struct {
	Fake *FakeProject
}

var projectsResource = unversioned.GroupVersionResource{Group: "project.openshift.io", Version: "", Resource: "projects"}

func (c *FakeProjects) Create(project *api.Project) (result *api.Project, err error) {
	obj, err := c.Fake.
		Invokes(core.NewRootCreateAction(projectsResource, project), &api.Project{})
	if obj == nil {
		return nil, err
	}
	return obj.(*api.Project), err
}

func (c *FakeProjects) Update(project *api.Project) (result *api.Project, err error) {
	obj, err := c.Fake.
		Invokes(core.NewRootUpdateAction(projectsResource, project), &api.Project{})
	if obj == nil {
		return nil, err
	}
	return obj.(*api.Project), err
}

func (c *FakeProjects) Delete(name string, options *pkg_api.DeleteOptions) error {
	_, err := c.Fake.
		Invokes(core.NewRootDeleteAction(projectsResource, name), &api.Project{})
	return err
}

func (c *FakeProjects) DeleteCollection(options *pkg_api.DeleteOptions, listOptions pkg_api.ListOptions) error {
	action := core.NewRootDeleteCollectionAction(projectsResource, listOptions)

	_, err := c.Fake.Invokes(action, &api.ProjectList{})
	return err
}

func (c *FakeProjects) Get(name string) (result *api.Project, err error) {
	obj, err := c.Fake.
		Invokes(core.NewRootGetAction(projectsResource, name), &api.Project{})
	if obj == nil {
		return nil, err
	}
	return obj.(*api.Project), err
}

func (c *FakeProjects) List(opts pkg_api.ListOptions) (result *api.ProjectList, err error) {
	obj, err := c.Fake.
		Invokes(core.NewRootListAction(projectsResource, opts), &api.ProjectList{})
	if obj == nil {
		return nil, err
	}

	label, _, _ := core.ExtractFromListOptions(opts)
	if label == nil {
		label = labels.Everything()
	}
	list := &api.ProjectList{}
	for _, item := range obj.(*api.ProjectList).Items {
		if label.Matches(labels.Set(item.Labels)) {
			list.Items = append(list.Items, item)
		}
	}
	return list, err
}

// Watch returns a watch.Interface that watches the requested projects.
func (c *FakeProjects) Watch(opts pkg_api.ListOptions) (watch.Interface, error) {
	return c.Fake.
		InvokesWatch(core.NewRootWatchAction(projectsResource, opts))
}

// Patch applies the patch and returns the patched project.
func (c *FakeProjects) Patch(name string, pt pkg_api.PatchType, data []byte, subresources ...string) (result *api.Project, err error) {
	obj, err := c.Fake.
		Invokes(core.NewRootPatchSubresourceAction(projectsResource, name, data, subresources...), &api.Project{})
	if obj == nil {
		return nil, err
	}
	return obj.(*api.Project), err
}


text:
package webbrowser

import (
	"errors"
	"fmt"
	"net/url"
	"os"
	"os/exec"
	"runtime"
	"strings"
)

var (
	ErrCantOpenBrowser = errors.New("webbrowser: can't open browser")
	ErrNoCandidates    = errors.New("webbrowser: no browser candidate found for your OS")
)

// Candidates contains a list of registered `Browser`s that will be tried with Open.
var Candidates []Browser

type Browser interface {
	// Command returns a ready to be used Cmd that will open an URL.
	Command(string) (*exec.Cmd, error)
	// Open tries to open a URL in your default browser. NOTE: This may cause
	// your program to hang until the browser process is closed in some OSes,
	// see https://github.com/toqueteos/webbrowser/issues/4.
	Open(string) error
}

// Open tries to open a URL in your default browser ensuring you have a display
// set up and not running this from SSH. NOTE: This may cause your program to
// hang until the browser process is closed in some OSes, see
// https://github.com/toqueteos/webbrowser/issues/4.
func Open(s string) (err error) {
	if len(Candidates) == 0 {
		return ErrNoCandidates
	}

	// Try to determine if there's a display available (only linux) and we
	// aren't on a terminal (all but windows).
	switch runtime.GOOS {
	case "linux":
		// No display, no need to open a browser. Lynx users **MAY** have
		// something to say about this.
		if os.Getenv("DISPLAY") == "" {
			return fmt.Errorf("webbrowser: tried to open %q, no screen found", s)
		}
		fallthrough
	case "darwin":
		// Check SSH env vars.
		if os.Getenv("SSH_CLIENT") != "" || os.Getenv("SSH_TTY") != "" {
			return fmt.Errorf("webbrowser: tried to open %q, but you are running a shell session", s)
		}
	}

	// Try all candidates
	for _, candidate := range Candidates {
		err := candidate.Open(s)
		if err == nil {
			return nil
		}
	}

	return ErrCantOpenBrowser
}

func init() {
	// Register the default Browser for current OS, if it exists.
	if os, ok := osCommand[runtime.GOOS]; ok {
		Candidates = append(Candidates, browserCommand{os.cmd, os.args})
	}
}

var (
	osCommand = map[string]*browserCommand{
		"darwin":  &browserCommand{"open", nil},
		"freebsd": &browserCommand{"xdg-open", nil},
		"linux":   &browserCommand{"xdg-open", nil},
		"netbsd":  &browserCommand{"xdg-open", nil},
		"openbsd": &browserCommand{"xdg-open", nil}, // It may be open instead
		"windows": &browserCommand{"cmd", []string{"/c", "start"}},
	}
)

type browserCommand struct {
	cmd  string
	args []string
}

func (b browserCommand) Command(s string) (*exec.Cmd, error) {
	u, err := url.Parse(s)
	if err != nil {
		return nil, err
	}

	validUrl := ensureValidURL(u)

	b.args = append(b.args, validUrl)

	return exec.Command(b.cmd, b.args...), nil
}

func (b browserCommand) Open(s string) error {
	cmd, err := b.Command(s)
	if err != nil {
		return err
	}

	return cmd.Run()
}

func ensureValidURL(u *url.URL) string {
	// Enforce a scheme (windows requires scheme to be set to work properly).
	if u.Scheme != "https" {
		u.Scheme = "http"
	}
	s := u.String()

	// Escape characters not allowed by cmd/bash
	switch runtime.GOOS {
	case "windows":
		s = strings.Replace(s, "&", `^&`, -1)
	}

	return s
}


text:
package org.radargun.stages.cache;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.IntStream;

import org.radargun.DistStageAck;
import org.radargun.StageResult;
import org.radargun.stages.cache.generators.ByteArrayValueGenerator;
import org.radargun.stages.cache.generators.KeyGenerator;
import org.radargun.stages.cache.generators.StringKeyGenerator;
import org.radargun.stages.cache.generators.ValueGenerator;
import org.radargun.stages.helpers.CacheSelector;
import org.radargun.state.WorkerState;
import org.radargun.traits.BasicOperations;
import org.radargun.traits.CacheInformation;
import org.radargun.traits.Lifecycle;
import org.radargun.util.CacheStageRunner;
import org.radargun.util.CacheTraitRepository;
import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * @author Matej Cimbora
 */
@Test(timeOut = 30000)
public class XSReplCheckStageTest {

   public void smokeTest() throws Exception {
      CacheStageRunner stageRunner = new CacheStageRunner(2);

      StringKeyGenerator keyGenerator = new StringKeyGenerator();
      ByteArrayValueGenerator valueGenerator = new ByteArrayValueGenerator();

      WorkerState workerState = stageRunner.getWorkerState(0);
      workerState.put(KeyGenerator.KEY_GENERATOR, keyGenerator);
      workerState.put(ValueGenerator.VALUE_GENERATOR, valueGenerator);
      workerState.put(CacheSelector.CACHE_SELECTOR, new CacheSelector.Default());

      workerState = stageRunner.getWorkerState(1);
      workerState.put(KeyGenerator.KEY_GENERATOR, keyGenerator);
      workerState.put(ValueGenerator.VALUE_GENERATOR, valueGenerator);
      workerState.put(CacheSelector.CACHE_SELECTOR, new CacheSelector.Default());

      Lifecycle lifecycle1 = stageRunner.getTraitImpl(Lifecycle.class, 0);
      lifecycle1.start();
      Lifecycle lifecycle2 = stageRunner.getTraitImpl(Lifecycle.class, 0);
      lifecycle2.start();

      XSReplCheckStage xsReplCheckStage1 = new XSReplCheckStage();
      xsReplCheckStage1.backupValueGenerator = valueGenerator;
      xsReplCheckStage1.backupCaches = Arrays.asList("test");
      xsReplCheckStage1.numEntries = 100;
      xsReplCheckStage1.entrySize = 1024;

      XSReplCheckStage xsReplCheckStage2 = new XSReplCheckStage();
      xsReplCheckStage2.backupValueGenerator = valueGenerator;
      xsReplCheckStage2.backupCaches = Arrays.asList("test");
      xsReplCheckStage2.numEntries = 100;
      xsReplCheckStage2.entrySize = 1024;

      BasicOperations basicOperations = stageRunner.getTraitImpl(BasicOperations.class);
      stageRunner.replaceTraitImpl(BasicOperations.class, basicOperations, 1);
      CacheInformation cacheInformation = stageRunner.getTraitImpl(CacheInformation.class);
      stageRunner.replaceTraitImpl(CacheInformation.class, cacheInformation, 1);

      CacheTraitRepository.BasicOperationsCache cache = (CacheTraitRepository.BasicOperationsCache) basicOperations.getCache(null);
      Random random = new Random(123);

      IntStream.range(0, 100).forEach(i -> {
         Object key = keyGenerator.generateKey(i);
         Object value = valueGenerator.generateValue(key, 1024, random);
         cache.put(key, value);
      });

      Assert.assertEquals(cache.size(), 100);

      List<DistStageAck> acks = stageRunner.executeOnWorker(new XSReplCheckStage[] {xsReplCheckStage1, xsReplCheckStage2}, new int[] {0, 1});

      Assert.assertEquals(stageRunner.processAckOnMain(xsReplCheckStage1, acks), StageResult.SUCCESS);
   }
}


text:
namespace android.text
{
	[global::MonoJavaBridge.JavaClass(typeof(global::android.text.Layout_))]
	public abstract partial class Layout : java.lang.Object
	{
		internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
		protected Layout(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
		{
		}
		[global::MonoJavaBridge.JavaClass()]
		public sealed partial class Alignment : java.lang.Enum
		{
			internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
			internal Alignment(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
			{
			}
			private static global::MonoJavaBridge.MethodId _m0;
			public static global::android.text.Layout.Alignment[] values()
			{
				global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
				if (global::android.text.Layout.Alignment._m0.native == global::System.IntPtr.Zero)
					global::android.text.Layout.Alignment._m0 = @__env.GetStaticMethodIDNoThrow(global::android.text.Layout.Alignment.staticClass, "values", "()[Landroid/text/Layout/Alignment;");
				return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.text.Layout.Alignment>(@__env.CallStaticObjectMethod(android.text.Layout.Alignment.staticClass, global::android.text.Layout.Alignment._m0)) as android.text.Layout.Alignment[];
			}
			private static global::MonoJavaBridge.MethodId _m1;
			public static global::android.text.Layout.Alignment valueOf(java.lang.String arg0)
			{
				global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
				if (global::android.text.Layout.Alignment._m1.native == global::System.IntPtr.Zero)
					global::android.text.Layout.Alignment._m1 = @__env.GetStaticMethodIDNoThrow(global::android.text.Layout.Alignment.staticClass, "valueOf", "(Ljava/lang/String;)Landroid/text/Layout$Alignment;");
				return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.text.Layout.Alignment>(@__env.CallStaticObjectMethod(android.text.Layout.Alignment.staticClass, global::android.text.Layout.Alignment._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.text.Layout.Alignment;
			}
			internal static global::MonoJavaBridge.FieldId _ALIGN_CENTER5223;
			public static global::android.text.Layout.Alignment ALIGN_CENTER
			{
				get
				{
					global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
					return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.text.Layout.Alignment>(@__env.GetStaticObjectField(global::android.text.Layout.Alignment.staticClass, _ALIGN_CENTER5223)) as android.text.Layout.Alignment;
				}
			}
			internal static global::MonoJavaBridge.FieldId _ALIGN_NORMAL5224;
			public static global::android.text.Layout.Alignment ALIGN_NORMAL
			{
				get
				{
					global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
					return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.text.Layout.Alignment>(@__env.GetStaticObjectField(global::android.text.Layout.Alignment.staticClass, _ALIGN_NORMAL5224)) as android.text.Layout.Alignment;
				}
			}
			internal static global::MonoJavaBridge.FieldId _ALIGN_OPPOSITE5225;
			public static global::android.text.Layout.Alignment ALIGN_OPPOSITE
			{
				get
				{
					global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
					return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.text.Layout.Alignment>(@__env.GetStaticObjectField(global::android.text.Layout.Alignment.staticClass, _ALIGN_OPPOSITE5225)) as android.text.Layout.Alignment;
				}
			}
			static Alignment()
			{
				global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
				global::android.text.Layout.Alignment.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/text/Layout$Alignment"));
				global::android.text.Layout.Alignment._ALIGN_CENTER5223 = @__env.GetStaticFieldIDNoThrow(global::android.text.Layout.Alignment.staticClass, "ALIGN_CENTER", "Landroid/text/Layout$Alignment;");
				global::android.text.Layout.Alignment._ALIGN_NORMAL5224 = @__env.GetStaticFieldIDNoThrow(global::android.text.Layout.Alignment.staticClass, "ALIGN_NORMAL", "Landroid/text/Layout$Alignment;");
				global::android.text.Layout.Alignment._ALIGN_OPPOSITE5225 = @__env.GetStaticFieldIDNoThrow(global::android.text.Layout.Alignment.staticClass, "ALIGN_OPPOSITE", "Landroid/text/Layout$Alignment;");
			}
		}
		[global::MonoJavaBridge.JavaClass()]
		public partial class Directions : java.lang.Object
		{
			internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
			protected Directions(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
			{
			}
			static Directions()
			{
				global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
				global::android.text.Layout.Directions.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/text/Layout$Directions"));
			}
		}
		private static global::MonoJavaBridge.MethodId _m0;
		public virtual float getLineWidth(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.text.Layout.staticClass, "getLineWidth", "(I)F", ref global::android.text.Layout._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static global::MonoJavaBridge.MethodId _m1;
		public virtual global::java.lang.CharSequence getText()
		{
			return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.lang.CharSequence>(this, global::android.text.Layout.staticClass, "getText", "()Ljava/lang/CharSequence;", ref global::android.text.Layout._m1) as java.lang.CharSequence;
		}
		private static global::MonoJavaBridge.MethodId _m2;
		public virtual void draw(android.graphics.Canvas arg0)
		{
			global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.text.Layout.staticClass, "draw", "(Landroid/graphics/Canvas;)V", ref global::android.text.Layout._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static global::MonoJavaBridge.MethodId _m3;
		public virtual void draw(android.graphics.Canvas arg0, android.graphics.Path arg1, android.graphics.Paint arg2, int arg3)
		{
			global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.text.Layout.staticClass, "draw", "(Landroid/graphics/Canvas;Landroid/graphics/Path;Landroid/graphics/Paint;I)V", ref global::android.text.Layout._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
		}
		private static global::MonoJavaBridge.MethodId _m4;
		public virtual int getWidth()
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getWidth", "()I", ref global::android.text.Layout._m4);
		}
		private static global::MonoJavaBridge.MethodId _m5;
		public virtual int getHeight()
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getHeight", "()I", ref global::android.text.Layout._m5);
		}
		private static global::MonoJavaBridge.MethodId _m6;
		public virtual global::android.text.TextPaint getPaint()
		{
			return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.text.Layout.staticClass, "getPaint", "()Landroid/text/TextPaint;", ref global::android.text.Layout._m6) as android.text.TextPaint;
		}
		private static global::MonoJavaBridge.MethodId _m7;
		public abstract int getLineCount();
		private static global::MonoJavaBridge.MethodId _m8;
		public virtual int getLineBounds(int arg0, android.graphics.Rect arg1)
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getLineBounds", "(ILandroid/graphics/Rect;)I", ref global::android.text.Layout._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
		}
		private static global::MonoJavaBridge.MethodId _m9;
		public static float getDesiredWidth(java.lang.CharSequence arg0, int arg1, int arg2, android.text.TextPaint arg3)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (global::android.text.Layout._m9.native == global::System.IntPtr.Zero)
				global::android.text.Layout._m9 = @__env.GetStaticMethodIDNoThrow(global::android.text.Layout.staticClass, "getDesiredWidth", "(Ljava/lang/CharSequence;IILandroid/text/TextPaint;)F");
			return @__env.CallStaticFloatMethod(android.text.Layout.staticClass, global::android.text.Layout._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
		}
		public static float getDesiredWidth(string arg0, int arg1, int arg2, android.text.TextPaint arg3)
		{
			return getDesiredWidth((global::java.lang.CharSequence)(global::java.lang.String)arg0, arg1, arg2, arg3);
		}
		private static global::MonoJavaBridge.MethodId _m10;
		public static float getDesiredWidth(java.lang.CharSequence arg0, android.text.TextPaint arg1)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (global::android.text.Layout._m10.native == global::System.IntPtr.Zero)
				global::android.text.Layout._m10 = @__env.GetStaticMethodIDNoThrow(global::android.text.Layout.staticClass, "getDesiredWidth", "(Ljava/lang/CharSequence;Landroid/text/TextPaint;)F");
			return @__env.CallStaticFloatMethod(android.text.Layout.staticClass, global::android.text.Layout._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
		}
		public static float getDesiredWidth(string arg0, android.text.TextPaint arg1)
		{
			return getDesiredWidth((global::java.lang.CharSequence)(global::java.lang.String)arg0, arg1);
		}
		private static global::MonoJavaBridge.MethodId _m11;
		public virtual int getEllipsizedWidth()
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getEllipsizedWidth", "()I", ref global::android.text.Layout._m11);
		}
		private static global::MonoJavaBridge.MethodId _m12;
		public virtual void increaseWidthTo(int arg0)
		{
			global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.text.Layout.staticClass, "increaseWidthTo", "(I)V", ref global::android.text.Layout._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static global::MonoJavaBridge.MethodId _m13;
		public virtual global::android.text.Layout.Alignment getAlignment()
		{
			return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<android.text.Layout.Alignment>(this, global::android.text.Layout.staticClass, "getAlignment", "()Landroid/text/Layout$Alignment;", ref global::android.text.Layout._m13) as android.text.Layout.Alignment;
		}
		private static global::MonoJavaBridge.MethodId _m14;
		public virtual float getSpacingMultiplier()
		{
			return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.text.Layout.staticClass, "getSpacingMultiplier", "()F", ref global::android.text.Layout._m14);
		}
		private static global::MonoJavaBridge.MethodId _m15;
		public virtual float getSpacingAdd()
		{
			return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.text.Layout.staticClass, "getSpacingAdd", "()F", ref global::android.text.Layout._m15);
		}
		private static global::MonoJavaBridge.MethodId _m16;
		public abstract int getLineTop(int arg0);
		private static global::MonoJavaBridge.MethodId _m17;
		public abstract int getLineDescent(int arg0);
		private static global::MonoJavaBridge.MethodId _m18;
		public abstract int getLineStart(int arg0);
		private static global::MonoJavaBridge.MethodId _m19;
		public abstract int getParagraphDirection(int arg0);
		private static global::MonoJavaBridge.MethodId _m20;
		public abstract bool getLineContainsTab(int arg0);
		private static global::MonoJavaBridge.MethodId _m21;
		public abstract global::android.text.Layout.Directions getLineDirections(int arg0);
		private static global::MonoJavaBridge.MethodId _m22;
		public abstract int getTopPadding();
		private static global::MonoJavaBridge.MethodId _m23;
		public abstract int getBottomPadding();
		private static global::MonoJavaBridge.MethodId _m24;
		public virtual float getPrimaryHorizontal(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.text.Layout.staticClass, "getPrimaryHorizontal", "(I)F", ref global::android.text.Layout._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static global::MonoJavaBridge.MethodId _m25;
		public virtual float getSecondaryHorizontal(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.text.Layout.staticClass, "getSecondaryHorizontal", "(I)F", ref global::android.text.Layout._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static global::MonoJavaBridge.MethodId _m26;
		public virtual float getLineLeft(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.text.Layout.staticClass, "getLineLeft", "(I)F", ref global::android.text.Layout._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static global::MonoJavaBridge.MethodId _m27;
		public virtual float getLineRight(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.text.Layout.staticClass, "getLineRight", "(I)F", ref global::android.text.Layout._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static global::MonoJavaBridge.MethodId _m28;
		public virtual float getLineMax(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.text.Layout.staticClass, "getLineMax", "(I)F", ref global::android.text.Layout._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static global::MonoJavaBridge.MethodId _m29;
		public virtual int getLineForVertical(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getLineForVertical", "(I)I", ref global::android.text.Layout._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static global::MonoJavaBridge.MethodId _m30;
		public virtual int getLineForOffset(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getLineForOffset", "(I)I", ref global::android.text.Layout._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static global::MonoJavaBridge.MethodId _m31;
		public virtual int getOffsetForHorizontal(int arg0, float arg1)
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getOffsetForHorizontal", "(IF)I", ref global::android.text.Layout._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
		}
		private static global::MonoJavaBridge.MethodId _m32;
		public virtual int getLineEnd(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getLineEnd", "(I)I", ref global::android.text.Layout._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static global::MonoJavaBridge.MethodId _m33;
		public virtual int getLineVisibleEnd(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getLineVisibleEnd", "(I)I", ref global::android.text.Layout._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static global::MonoJavaBridge.MethodId _m34;
		public virtual int getLineBottom(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getLineBottom", "(I)I", ref global::android.text.Layout._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static global::MonoJavaBridge.MethodId _m35;
		public virtual int getLineBaseline(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getLineBaseline", "(I)I", ref global::android.text.Layout._m35, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static global::MonoJavaBridge.MethodId _m36;
		public virtual int getLineAscent(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getLineAscent", "(I)I", ref global::android.text.Layout._m36, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static global::MonoJavaBridge.MethodId _m37;
		public virtual int getOffsetToLeftOf(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getOffsetToLeftOf", "(I)I", ref global::android.text.Layout._m37, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static global::MonoJavaBridge.MethodId _m38;
		public virtual int getOffsetToRightOf(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getOffsetToRightOf", "(I)I", ref global::android.text.Layout._m38, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static global::MonoJavaBridge.MethodId _m39;
		public virtual void getCursorPath(int arg0, android.graphics.Path arg1, java.lang.CharSequence arg2)
		{
			global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.text.Layout.staticClass, "getCursorPath", "(ILandroid/graphics/Path;Ljava/lang/CharSequence;)V", ref global::android.text.Layout._m39, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
		}
		public void getCursorPath(int arg0, android.graphics.Path arg1, string arg2)
		{
			getCursorPath(arg0, arg1, (global::java.lang.CharSequence)(global::java.lang.String)arg2);
		}
		private static global::MonoJavaBridge.MethodId _m40;
		public virtual void getSelectionPath(int arg0, int arg1, android.graphics.Path arg2)
		{
			global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.text.Layout.staticClass, "getSelectionPath", "(IILandroid/graphics/Path;)V", ref global::android.text.Layout._m40, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
		}
		private static global::MonoJavaBridge.MethodId _m41;
		public virtual global::android.text.Layout.Alignment getParagraphAlignment(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<android.text.Layout.Alignment>(this, global::android.text.Layout.staticClass, "getParagraphAlignment", "(I)Landroid/text/Layout$Alignment;", ref global::android.text.Layout._m41, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.text.Layout.Alignment;
		}
		private static global::MonoJavaBridge.MethodId _m42;
		public virtual int getParagraphLeft(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getParagraphLeft", "(I)I", ref global::android.text.Layout._m42, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static global::MonoJavaBridge.MethodId _m43;
		public virtual int getParagraphRight(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getParagraphRight", "(I)I", ref global::android.text.Layout._m43, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static global::MonoJavaBridge.MethodId _m44;
		protected virtual bool isSpanned()
		{
			return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.text.Layout.staticClass, "isSpanned", "()Z", ref global::android.text.Layout._m44);
		}
		private static global::MonoJavaBridge.MethodId _m45;
		public abstract int getEllipsisStart(int arg0);
		private static global::MonoJavaBridge.MethodId _m46;
		public abstract int getEllipsisCount(int arg0);
		private static global::MonoJavaBridge.MethodId _m47;
		protected Layout(java.lang.CharSequence arg0, android.text.TextPaint arg1, int arg2, android.text.Layout.Alignment arg3, float arg4, float arg5) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (global::android.text.Layout._m47.native == global::System.IntPtr.Zero)
				global::android.text.Layout._m47 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "<init>", "(Ljava/lang/CharSequence;Landroid/text/TextPaint;ILandroid/text/Layout$Alignment;FF)V");
			global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.text.Layout.staticClass, global::android.text.Layout._m47, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5));
			Init(@__env, handle);
		}
		public static int DIR_LEFT_TO_RIGHT
		{
			get
			{
				return 1;
			}
		}
		public static int DIR_RIGHT_TO_LEFT
		{
			get
			{
				return -1;
			}
		}
		static Layout()
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			global::android.text.Layout.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/text/Layout"));
		}
	}

	[global::MonoJavaBridge.JavaProxy(typeof(global::android.text.Layout))]
	internal sealed partial class Layout_ : android.text.Layout
	{
		internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
		internal Layout_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
		{
		}
		private static global::MonoJavaBridge.MethodId _m0;
		public override int getLineCount()
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout_.staticClass, "getLineCount", "()I", ref global::android.text.Layout_._m0);
		}
		private static global::MonoJavaBridge.MethodId _m1;
		public override int getLineTop(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout_.staticClass, "getLineTop", "(I)I", ref global::android.text.Layout_._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static global::MonoJavaBridge.MethodId _m2;
		public override int getLineDescent(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout_.staticClass, "getLineDescent", "(I)I", ref global::android.text.Layout_._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static global::MonoJavaBridge.MethodId _m3;
		public override int getLineStart(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout_.staticClass, "getLineStart", "(I)I", ref global::android.text.Layout_._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static global::MonoJavaBridge.MethodId _m4;
		public override int getParagraphDirection(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout_.staticClass, "getParagraphDirection", "(I)I", ref global::android.text.Layout_._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static global::MonoJavaBridge.MethodId _m5;
		public override bool getLineContainsTab(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.text.Layout_.staticClass, "getLineContainsTab", "(I)Z", ref global::android.text.Layout_._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static global::MonoJavaBridge.MethodId _m6;
		public override global::android.text.Layout.Directions getLineDirections(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.text.Layout_.staticClass, "getLineDirections", "(I)Landroid/text/Layout$Directions;", ref global::android.text.Layout_._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.text.Layout.Directions;
		}
		private static global::MonoJavaBridge.MethodId _m7;
		public override int getTopPadding()
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout_.staticClass, "getTopPadding", "()I", ref global::android.text.Layout_._m7);
		}
		private static global::MonoJavaBridge.MethodId _m8;
		public override int getBottomPadding()
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout_.staticClass, "getBottomPadding", "()I", ref global::android.text.Layout_._m8);
		}
		private static global::MonoJavaBridge.MethodId _m9;
		public override int getEllipsisStart(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout_.staticClass, "getEllipsisStart", "(I)I", ref global::android.text.Layout_._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static global::MonoJavaBridge.MethodId _m10;
		public override int getEllipsisCount(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout_.staticClass, "getEllipsisCount", "(I)I", ref global::android.text.Layout_._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		static Layout_()
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			global::android.text.Layout_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/text/Layout"));
		}
	}
}


text:
describe RequestTypeVisibilityService do
  let(:subject) { described_class.new }

  describe "#determine_visibility" do
    context "when the request type is 'clone_to_template'" do
      let(:request_type) { :clone_to_template }

      it "returns the values to be hidden" do
        expect(subject.determine_visibility(request_type)).to eq(:hide => %i(vm_filter vm_auto_start))
      end
    end

    context "when the request type is 'clone_to_vm'" do
      let(:request_type) { :clone_to_vm }

      it "returns the values to be hidden" do
        expect(subject.determine_visibility(request_type)).to eq(:hide => [:vm_filter])
      end
    end

    context "when the request type is anything else" do
      let(:request_type) { :potato }

      it "returns an empty list of values to be hidden" do
        expect(subject.determine_visibility(request_type)).to eq(:hide => [])
      end
    end
  end
end


text:
namespace BulletML.Equationator
{
    /// <summary>
    /// All the different types of values that might be stored in a Token object
    /// </summary>
    public enum TokenType
    {
        Number,
        Operator,
        OpenParen,
        CloseParen,
        Function,
        Param,
        Tier,
        Rand,
        Invalid
    }
}


text:
use ruma_api::ruma_api;
use ruma_events::presence::PresenceState;
use ruma_identifiers::UserId;

ruma_api! {
    metadata {
        description: "Set presence status for this user.",
        method: PUT,
        name: "set_presence",
        path: "/_matrix/client/r0/presence/:user_id/status",
        rate_limited: true,
        requires_authentication: true,
    }

    request {
        /// The user whose presence state will be updated.
        #[ruma_api(path)]
        pub user_id: UserId,

        /// The new presence state.
        pub presence: PresenceState,

        /// The status message to attach to this state.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub status_msg: Option<String>,
    }

    response {}

    error: crate::Error
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Demo DOM 015</title>
  <link href="css/normalize.css" rel="stylesheet" />
  <link href="css/tests.css" rel="stylesheet" />

Scrawl-canvas v8 - DOM test 015

Use stacked DOM artefact corners as pivot points

    <canvas
      id="mycanvas"
      data-scrawl-canvas
      data-is-responsive="true"
      data-base-background-color="gray"
    ></canvas>

This DOM element can be dragged around the Scrawl-canvas stack using the mouse.

Width

<input class="controlItem" id="width" type="range" value="0" min="0" max="600" step="10" />

Height

<input class="controlItem" id="height" type="range" value="0" min="0" max="600" step="10" />

Handles

X: <input class="controlItem" id="handle_xAbsolute" type="range" value="0" min="-200" max="200" step="1" />

Y: <input class="controlItem" id="handle_yAbsolute" type="range" value="0" min="-200" max="200" step="1" />

Offset

X: <input class="controlItem" id="offset_xAbsolute" type="range" value="0" min="-200" max="200" step="1" />

Y: <input class="controlItem" id="offset_yAbsolute" type="range" value="0" min="-200" max="200" step="1" />

Roll

<input class="controlItem" id="roll" type="range" value="10" min="0" max="360" step="1" />

Pitch

<input class="controlItem" id="pitch" type="range" value="20" min="0" max="360" step="1" />

Yaw

<input class="controlItem" id="yaw" type="range" value="30" min="0" max="360" step="1" />

Scale

<input class="controlItem" id="scale" type="range" value="1" min="0.5" max="2" step="0.02" />

Test purpose

Drag and drop the element to test its sensors correctly collide with underlying canvas entitys

Create a set of blocks to act as the grid over which the test element will be dragged

Perform artefact collision checks between the element and the grid group, updating colliding grid entitys to show that they are in collision

Drag and drop the element across the stack canvas, to check that element's sensors are correctly positioned and the artefact collision detection works as expected

Vary the element's attributes (handle, offset, 3d-rotation, scale) to make sure its sensors correctly account for these changes

Touch test: should work as expected

Annotated code