text stringlengths 10 2.61M |
|---|
require_relative "session_controller"
module Session
def login
login_data = login_form
@user = SessionController.login(login_data)
rescue Net::HTTPError => e
puts e.response.parsed_response["errors"][0]
puts
end
end
|
### Easy 4 Start ####
###############################################################################
=begin
"Short Long Short"
Write a method that takes two strings as arguments, determines the longest of
the two strings, and then returns the result of concatenating the shorter
string, the longer string, and the shorter string once again.
You may assume that the strings are of different lengths.
def short_long_short(str1,str2)
if str1.length >= str2.length
return str2 + str1 + str2
elsif str1.length <= str2.length
return str1 + str2 + str1
else
puts "Invalid Input"
end
end
=end
###############################################################################
###############################################################################
=begin
"What Century is That?"
Write a method that takes a year as input and returns the century.
The return value should be a string that begins with the century number,
and ends with st, nd, rd, or th as appropriate for that number.
New centuries begin in years that end with 01. So, the years 1901-2000 comprise
the 20th century.
def century(num)
num = num.to_f
if num <= 100
cen_num = 1
elsif num < 1000
cen_num = num / 100 + 1
cen_num = cen_num.to_i
elsif num > 1000
n = num.to_s[0..1]
n1 = num/n.to_f/100*n.to_f
if n1 > n1.floor
cen_num = n1.floor + 1
cen_num = cen_num.to_i
else
cen_num = n1.to_i
end
else
puts "Invalid input"
end
if (10..19).include?(cen_num % 100) || (4..9).include?(cen_num % 10)
return cen_num.to_s + "th"
elsif cen_num % 10 == 3
return cen_num.to_s + "rd"
elsif cen_num % 10 == 2
return cen_num.to_s + "nd"
elsif cen_num % 10 == 1
return cen_num.to_s + "st"
elsif cen_num % 10 == 0
return cen_num.to_s + "th"
else
puts "Invalid Input"
end
end
=end
###############################################################################
###############################################################################
=begin
"Leap Years (Part 1)"
In the modern era under the Gregorian Calendar, leap years occur in every year
that is evenly divisible by 4, unless the year is also divisible by 100. If the
year is evenly divisible by 100, then it is not a leap year unless the year is
evenly divisible by 400.
Assume this rule is good for any year greater than year 0. Write a method that
takes any year greater than 0 as input, and returns true if the year is a leap
year, or false if it is not a leap year.
def leap_year?(year)
if year % 100 != 0 && year % 4 == 0 || year % 400 == 0
true
else
false
end
end
=end
###############################################################################
###############################################################################
=begin
"Leap Years (Part 2)"
A continuation of the previous exercise.
The British Empire adopted the Gregorian Calendar in 1752, which was a leap year.
Prior to 1752, the Julian Calendar was used. Under the Julian Calendar, leap
years occur in any year that is evenly divisible by 4.
Using this information, update the method from the previous exercise to
determine leap years both before and after 1752.
def leap_year?(year)
if year >= 1752
if year % 100 != 0 && year % 4 == 0 || year % 400 == 0
return true
else
return false
end
else
(year < 1752 && year % 4 == 0) ? true : false
end
end
=end
###############################################################################
###############################################################################
=begin
"Multiples of 3 and 5"
Write a method that searches for all multiples of 3 or 5 that lie between 1 and
some other number, and then computes the sum of those multiples. For instance,
if the supplied number is 20, the result should be 98
(3 + 5 + 6 + 9 + 10 + 12 + 15 + 18 + 20).
You may assume that the number passed in is an integer greater than 1.
def multisum(n)
Array(0..n).select{|i| i % 3 == 0 || i % 5 == 0}.sum
end
=end
###############################################################################
###############################################################################
=begin
"Running Totals"
Write a method that takes an Array of numbers, and returns an Array with the
same number of elements, and each element has the running total from the original Array.
def running_total(arr)
r_total = arr[0]
arr1 = [arr[0]]
for i in 1...arr.size
r_total += arr[i]
arr1 << r_total
end
if arr == []
return []
else
return arr1
end
end
=end
###############################################################################
###############################################################################
=begin
"Convet a String to a Number!"
The String#to_i method converts a string of numeric characters (including an
optional plus or minus sign) to an Integer. String#to_i and the Integer constructor
(Integer()) behave similarly. In this exercise, you will create a method that
does the same thing.
Write a method that takes a String of digits, and returns the appropriate number
as an integer. You may not use any of the methods mentioned above.
For now, do not worry about leading + or - signs, nor should you worry about
invalid characters; assume all characters will be numeric.
You may not use any of the standard conversion methods available in Ruby, such
as String#to_i, Integer(), etc. Your method should do this the old-fashioned
way and calculate the result by analyzing the characters in the string.
def string_to_integer(s)
result = 0
digit_place = 1
i = s.size
num_hash = {"0" => 0, "1" => 1, "2"=> 2, "3" => 3, "4" => 4, "5"=> 5,
"6" => 6, "7" => 7, "8" => 8, "9" => 9}
while i > 0
result += num_hash[s[i-1]] * digit_place
digit_place *= 10
i -= 1
end
result
end
=end
###############################################################################
###############################################################################
=begin
"Convert a String to a Signed Number!
In the previous exercise, you developed a method that converts simple numeric
strings to Integers. In this exercise, you're going to extend that method to
work with signed numbers.
Write a method that takes a String of digits, and returns the appropriate number
as an integer. The String may have a leading + or - sign; if the first character
is a +, your method should return a positive number; if it is a -, your method
should return a negative number. If no sign is given, you should return a
positive number.
You may assume the string will always contain a valid number.
You may not use any of the standard conversion methods available in Ruby, such
as String#to_i, Integer(), etc. You may, however, use the string_to_integer
method from the previous lesson.
def string_to_signed_integer(s)
result = 0
digit_place = 1
i = s.size
num_hash = {"0" => 0, "1" => 1, "2"=> 2, "3" => 3, "4" => 4, "5"=> 5,
"6" => 6, "7" => 7, "8" => 8, "9" => 9}
if s.include?('+')
s.delete!("+")
i = s.size
while i > 0
result += num_hash[s[i-1]] * digit_place
digit_place *= 10
i -= 1
end
return result
elsif s.include?('-')
s.delete!("-")
i = s.size
while i > 0
result += num_hash[s[i-1]] * digit_place
digit_place *= 10
i -= 1
end
return result * -1
else
while i > 0
result += num_hash[s[i-1]] * digit_place
digit_place *= 10
i -= 1
end
return result
end
end
Better Solution:
def string_to_signed_integer(string)
case string[0]
when '-' then -string_to_integer(string[1..-1])
when '+' then string_to_integer(string[1..-1])
else string_to_integer(string)
end
end
=end
###############################################################################
###############################################################################
=begin
"Convert a Number to a String!"
In the previous two exercises, you developed methods that convert simple numeric
strings to signed Integers. In this exercise and the next, you're going to reverse
those methods.
Write a method that takes a positive integer or zero, and converts it to a string
representation.
You may not use any of the standard conversion methods available in Ruby, such
as Integer#to_s, String(), Kernel#format, etc. Your method should do this the
old-fashioned way and construct the string by analyzing and manipulating the number.
def integer_to_string(n)
result = ""
num_hash = {0 => "0", 1 => "1", 2 => "2", 3 => "3", 4 => "4", 5=> "5",
6 => "6", 7 => "7", 8 => "8", 9 => "9"}
if n == 0
return result + num_hash[n]
end
while n > 0
result << num_hash[n%10]
n /= 10
end
result.reverse
end
=end
###############################################################################
###############################################################################
=begin
"Convert a Signed Number to a String!"
In the previous exercise, you developed a method that converts non-negative
numbers to strings. In this exercise, you're going to extend that method by
adding the ability to represent negative numbers as well.
Write a method that takes an integer, and converts it to a string representation.
You may not use any of the standard conversion methods available in Ruby, such
as Integer#to_s, String(), Kernel#format, etc. You may, however, use integer_to_string
from the previous exercise.
def integer_to_string(n)
result = ""
num_hash = {0 => "0", 1 => "1", 2 => "2", 3 => "3", 4 => "4", 5=> "5",
6 => "6", 7 => "7", 8 => "8", 9 => "9"}
if n == 0
return result + num_hash[n]
end
while n > 0
result << num_hash[n%10]
n /= 10
end
result.reverse
end
def signed_integer_to_string(num)
if num > 0
return "+" + integer_to_string(num)
elsif num < 0
num1 = num* -1
return "-" + integer_to_string(num1)
else
return integer_to_string(num)
end
end
=end
###############################################################################
### Easy 4 End ####
### Easy 5 Start ####
###############################################################################
=begin
"ASCII String Value"
Write a method that determines and returns the ASCII string value of a string
that is passed in as an argument. The ASCII string value is the sum of the ASCII
values of every character in the string. (You may use String#ord to determine
the ASCII value of a character.)
def ascii_value(s)
char_arr = s.chars
result = 0
char_arr.each {|e| result += e.ord}
result
end
=end
###############################################################################
###############################################################################
=begin
"After Midnight (Part 1)"
The time of day can be represented as the number of minutes before or after
midnight. If the number of minutes is positive, the time is after midnight. If
the number of minutes is negative, the time is before midnight.
Write a method that takes a time using this minute-based format and returns the
time of day in 24 hour format (hh:mm). Your method should work with any integer input.
You may not use ruby's Date and Time classes.
=end
###############################################################################
def time_of_day(n)
if n < 60 && n > -60
mins = n
elsif n > 60 || n < -60
hours, mins = n.divmod(60)
end
time = "#{}:#{mins}"
###############################################################################
=begin
"Letter Swap"
Given a string of words separated by spaces, write a method that takes this
string of words and returns a string in which the first and last letters of
every word are swapped.
You may assume that every word contains at least one letter, and that the string
will always contain at least one word. You may also assume that each string
contains nothing but words and spaces
def letter_swap(words)
swap = words.split.each {|word| word[0], word[-1] = word[-1], word[0]}
swap.join(" ")
end
=end
###############################################################################
###############################################################################
=begin
"Clean up the words"
Given a string that consists of some words and an assortment of non-alphabetic
characters, write a method that returns that string with all of the non-alphabetic
characters replaced by spaces. If one or more non-alphabetic characters occur in
a row, you should only have one space in the result (the result should never have
consecutive spaces).
def cleanup(str)
uniq_str = str.split("").uniq.join
uniq_str.gsub(/[^0-9a-z ]/i, ' ')
end
=end
###############################################################################
###############################################################################
=begin
"Letter Counter (Part 1)"
Write a method that takes a string with one or more space separated words and
returns a hash that shows the number of words of different sizes.
Words consist of any string of characters that do not include a space.
def word_sizes(words)
letters_hash = Hash.new
word_arr = words.split(" ")
sizes = word_arr.map{|i| i.length}
hash_keys = sizes.uniq
for i in hash_keys
letters_hash[i] = 0
end
for i in sizes
letters_hash[i] += 1
end
letters_hash
end
=end
###############################################################################
###############################################################################
=begin
"Letter Counter (Part 2)"
Modify the word_sizes method from the previous exercise to exclude non-letters
when determining word size. For instance, the length of "it's" is 3, not 4.
def word_sizes2(words)
words.gsub!(/[^0-9a-z ]/i, '')
letters_hash = Hash.new
word_arr = words.split(" ")
sizes = word_arr.map{|i| i.length}
hash_keys = sizes.uniq
for i in hash_keys
letters_hash[i] = 0
end
for i in sizes
letters_hash[i] += 1
end
letters_hash
end
=end
###############################################################################
###############################################################################
=begin
"Alphabetical Numbers"
Write a method that takes an Array of Integers between 0 and 19, and returns
an Array of those Integers sorted based on the English words for each number:
zero, one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve,
thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen
Example:
alphabetic_number_sort((0..19).to_a) == [
8, 18, 11, 15, 5, 4, 14, 9, 19, 1, 7, 17,
6, 16, 10, 13, 3, 12, 2, 0]
NUM_WORDS = %w(zero one two three four five six seven eight nine ten eleven twelve
thirteen fourteen fifteen sixteen seventeen eighteen nineteen)
def alphabetic_number_sort(range_0_to_19)
answer = []
range_0_to_19 = (0..19).to_a
num_hash = Hash.new()
for i in (range_0_to_19)
num_hash[i] = NUM_WORDS[i]
end
rev_num_hash = num_hash.invert
sorted_hash = rev_num_hash.keys.sort
for i in sorted_hash
answer << rev_num_hash[i]
end
answer
end
=end
###############################################################################
###############################################################################
=begin
"ddaaiillyy ddoouubbllee"
Write a method that takes a string argument and returns a new string that
contains the value of the original string with all consecutive duplicate
characters collapsed into a single character. You may not use String#squeeze or
String#squeeze!.
def crunch(str)
letters = str.split("")
i = letters.size - 1
while i > 0
if letters[i] == letters[i-1]
letters.delete_at(i)
end
i -= 1
end
letters.join
end
=end
###############################################################################
###############################################################################
=begin
"Bannerizer"
Write a method that will take a short line of text, and print it within a box.
You may assume that the input will always fit in your terminal window.
def print_in_box(str)
in_box_str = "| " + str + " |"
top_and_bottom = "+" + ("-"*(in_box_str.size - 2)) + "+"
sides = "|" + (" "*(in_box_str.size - 2)) + "|"
puts top_and_bottom, sides, in_box_str, sides, top_and_bottom
end
Modify this method so it will truncate the message if it will be too wide to fit
inside a standard terminal window (80 columns, including the sides of the box).
For a real challenge, try word wrapping very long messages so they appear on
multiple lines, but still within a box.
(Still in progress)
def print_in_box(str)
if str.size <= 76
in_box_str = "| " + str.slice!(0..76) + " |"
top_and_bottom = "+" + ("-"*(in_box_str.size - 2)) + "+"
sides = "|" + (" "*(in_box_str.size - 2)) + "|"
puts top_and_bottom, sides, in_box_str, sides, top_and_bottom
elsif str.size > 76
in_box_str = "| " + str.slice!(0..76) + " |"
top_and_bottom = "+" + ("-"*(in_box_str.size - 2)) + "+"
sides = "|" + (" "*(in_box_str.size - 2)) + "|"
puts top_and_bottom, sides, in_box_str
i = (str.size/76.to_f).ceil
for i in 0...i
next_slice = str.slice!(0..76)
in_box_next_slice = "| " + next_slice + (" " *(78 - (next_slice.size- 1))) + " |"
puts in_box_next_slice
end
puts sides, top_and_bottom
end
end
=end
###############################################################################
###############################################################################
=begin
"Spin Me Around In Circles"
You are given a method named spin_me that takes a string as an argument and
returns a string that contains the same words, but with each word's characters
reversed. Given the method's implementation, will the returned string be the
same object as the one passed in as an argument or a different object?
def spin_me(str)
str.split.each do |word|
word.reverse!
end.join(" ")
end
spin_me("hello world") # "olleh dlrow"
The original string will not be permenently affected. The string is passed
and then split into an array which is a seperate object. That array object
is the one that is being permenently mutated because of .reverse!
=end
###############################################################################
### Easy 5 End ####################################
### Easy 6 Start ####################################
###############################################################################
=begin
"Cute angles"
Write a method that takes a floating point number that represents an angle
between 0 and 360 degrees and returns a String that represents that angle in
degrees, minutes and seconds. You should use a degree symbol (°) to represent
degrees, a single quote (') to represent minutes, and a double quote (") to
represent seconds. A degree has 60 minutes, while a minute has 60 seconds.
Note: your results may differ slightly depending on how you round values, but
should be within a second or two of the results shown.
You should use two digit numbers with leading zeros when formatting the minutes
and seconds, e.g., 321°03'07".
You may use this constant to represent the degree symbol: DEGREE = "\xC2\xB0"
Since degrees are normally restricted to the range 0-360, can you modify the
code so it returns a value in the appropriate range when the input is less
than 0 or greater than 360?
DEGREE = "\xC2\xB0"
def dms(num)
if num > 360 || num < 0
num = num % 360
end
degree = "#{num.floor}" + DEGREE
min = (num-num.floor)*60
minutes = "#{min.floor}" + "'"
sec = (min - min.floor)*60
seconds = "#{sec.floor}" + '"'
puts degree + minutes.rjust(3,"0") + seconds.rjust(3,"0")
end
=end
###############################################################################
###############################################################################
=begin
"Delete vowels"
Write a method that takes an array of strings, and returns an array of the
same string values, except with the vowels (a, e, i, o, u) removed.
def remove_vowels(arr)
arr.map{|str| str.gsub(/[aeiouAEIOU]/,"")}
end
=end
###############################################################################
###############################################################################
=begin
"Fibonacci Number Location By Lenght"
The Fibonacci series is a series of numbers (1, 1, 2, 3, 5, 8, 13, 21, ...) such
that the first 2 numbers are 1 by definition, and each subsequent number is the
sum of the two previous numbers. This series appears throughout the natural world.
Computationally, the Fibonacci series is a very simple series, but the results
grow at an incredibly rapid rate. For example, the 100th Fibonacci number is
354,224,848,179,261,915,075 -- that's enormous, especially considering that it
takes 6 iterations before it generates the first 2 digit number.
Write a method that calculates and returns the index of the first Fibonacci
number that has the number of digits specified as an argument.
(The first Fibonacci number has index 1.)
def create_fibonacci(limit)
fib_arr = [1,1]
for n in 1..limit
fib_arr << fib_arr[n] + fib_arr[n-1]
end
fib_arr
end
def fib_limit_creator(num)
n = 1
for i in 0..num
n *= 10
end
n
end
def find_fibonacci_index_by_length(num_digits)
limit = fib_limit_creator(num_digits)
fib_arr = create_fibonacci(limit)
index = 2
digit_counter = 0
for ind in 2...fib_arr.size
for i in 1..num_digits
fib_arr[ind] /= 10
digit_counter += 1
break if fib_arr[ind] == 0
end
if digit_counter == num_digits
break
else
digit_counter = 0
end
index += 1
end
index + 1
end
=end
###############################################################################
###############################################################################
=begin
"Reversed Arrays (Part 1)"
Write a method that takes an Array as an argument, and reverses its elements in
place; that is, mutate the Array passed into this method. The return value
should be the same Array object.
You may not use Array#reverse or Array#reverse!.
def reverse_arr(arr)
transition_arr = []
counter = arr.size-1
while counter >= 0
transition_arr << arr[counter]
counter -= 1
end
for i in 0...transition_arr.size
arr[i] = transition_arr[i]
end
arr
end
=end
###############################################################################
###############################################################################
=begin
"Reversed Arrays (Part 2)"
Write a method that takes an Array, and returns a new Array with the elements
of the original list in reverse order. Do not modify the original list.
You may not use Array#reverse or Array#reverse!, nor may you use the method you
wrote in the previous exercise.
def reverse_arr2(arr)
transition_arr1 = []
counter = arr.size-1
while counter >= 0
transition_arr1 << arr[counter]
counter -= 1
end
transition_arr2 = []
for i in 0...transition_arr1.size
transition_arr2[i] = transition_arr1[i]
end
transition_arr2
end
Even shorter Solution
def reverse_arr3(arr)
arr.reverse_each.each_with_object([]){|x, arr| arr << x}
end
=end
###############################################################################
###############################################################################
=begin
"Combining Arrays"
Write a method that takes two Arrays as arguments, and returns an Array that
contains all of the values from the argument Arrays. There should be no
duplication of values in the returned Array, even if there are duplicates in the
original Arrays.
def merge_arr(arr1, arr2)
arr3 = []
for i in 0...arr1.size
arr3 << arr1[i]
end
for i in 0...arr2.size
arr3 << arr2[i]
end
arr3.uniq!
end
=end
###############################################################################
###############################################################################
=begin
"Halvsies"
Write a method that takes an Array as an argument, and returns two Arrays
(as a pair of nested Arrays) that contain the first half and second half of the
original Array, respectively. If the original array contains an odd number of
elements, the middle element should be placed in the first half Array.
def halvsies(arr)
arr1 = []
first_half = arr[0, (arr.size.to_f/2).round]
last_half = arr[(arr.size.to_f/2).round, arr.size]
arr1[0], arr1[1] = first_half, last_half
end
=end
###############################################################################
###############################################################################
=begin
"Find the Duplicate"
Given an unordered array and the information that exactly one value in the array
occurs twice (every other value occurs exactly once), how would you determine
which value occurs twice? Write a method that will find and return the duplicate
value that is known to be in the array.
def find_dup(arr)
arr1 = arr.sort
duplicate = 0
for i in 1...arr.size
if arr1[i] == arr1[i-1]
duplicate = arr1.delete_at(i)
end
end
duplicate
end
=end
###############################################################################
###############################################################################
=begin
"Does My List Include This?"
Write a method named include? that takes an Array and a search value as
arguments. This method should return true if the search value is in the array,
false if it is not. You may not use the Array#include? method in your solution.
def include?(arr, val)
for i in arr
if i == val
return true
end
end
false
end
=end
###############################################################################
###############################################################################
=begin
"Right Triangles"
Write a method that takes a positive integer, n, as an argument, and displays a
right triangle whose sides each have n stars. The hypotenuse of the triangle
(the diagonal side in the images below) should have one end at the lower-left of
the triangle, and the other end at the upper-right.
def triangle(n)
spaces = n - 1
stars = 1
for i in 0...n
puts (" "*spaces) + ("*"*stars)
spaces -= 1
stars += 1
end
end
=end
###############################################################################
### Easy 6 End ######################################
### Easy 7 Start ####################################
###############################################################################
=begin
"Combine Two Lists"
Write a method that combines two Arrays passed in as arguments, and returns a
new Array that contains all elements from both Array arguments, with the elements
taken in alternation.
You may assume that both input Arrays are non-empty, and that they have the same
number of elements.
def interleave(arr1,arr2)
arr3 = []
for i in 0...(arr1.size)
arr3 << arr1[i] << arr2[i]
end
arr3
end
=end
###############################################################################
###############################################################################
=begin
"Lettercase Counter"
Write a method that takes a string, and then returns a hash that contains 3
entries: one represents the number of characters in the string that are lowercase
letters, one the number of characters that are uppercase letters, and one the
number of characters that are neither.
def letter_case_count(str)
str_arr = str.chars
count_hash = {lowercase: 0, uppercase: 0, neither: 0}
for i in str_arr
if ('a'..'z').to_a.include?(i)
count_hash[:lowercase] += 1
elsif ('A'..'Z').to_a.include?(i)
count_hash[:uppercase] += 1
elsif !('a'..'z').to_a.include?(i) && !('A'..'Z').to_a.include?(i)
count_hash[:neither] += 1
else
puts 'Invalid input. Please put a string'
end
end
count_hash
end
=end
###############################################################################
###############################################################################
=begin
"Capitalize Words"
Write a method that takes a single String argument and returns a new string that
contains the original value of the argument with the first character of every
word capitalized and all other letters lowercase.
You may assume that words are any sequence of non-blank characters.
def word_cap(str)
str.split(" ").map!{|word| word.capitalize}.join(" ")
end
=end
###############################################################################
###############################################################################
=begin
"Swap Case"
Write a method that takes a string as an argument and returns a new string in
which every uppercase letter is replaced by its lowercase version, and every
lowercase letter by its uppercase version. All other characters should be
unchanged.
You may not use String#swapcase; write your own version of this method.
def swapcase(str)
str_arr = str.chars
str_arr.map! do |letter|
if ('a'..'z').include?(letter)
letter.upcase
elsif ('A'..'Z').include?(letter)
letter.downcase
else
letter
end
end
str_arr.join
end
=end
###############################################################################
###############################################################################
=begin
"Staggered Caps (Part 1)"
Write a method that takes a String as an argument, and returns a new String that
contains the original value using a staggered capitalization scheme in which
every other character is capitalized, and the remaining characters are lowercase.
Characters that are not letters should not be changed, but count as characters
when switching between upper and lowercase.
def staggered_case(str)
str_arr = str.chars
str_arr.each_with_index do |l,i|
if i.even?
l.upcase!
elsif i.odd?
l.downcase!
end
end
str_arr.join
end
=end
###############################################################################
###############################################################################
=begin
"Staggered Caps (Part 2)"
Modify the method from the previous exercise so it ignores non-alphabetic
characters when determining whether it should uppercase or lowercase each letter.
The non-alphabetic characters should still be included in the return value; they
just don't count when toggling the desired case.
LETTERS = [('a'..'z').to_a,('A'..'Z').to_a].flatten
def staggered_case(str)
str_arr = str.chars
bool = true
str_arr.map! do |element|
if bool && LETTERS.include?(element)
bool = !bool
element.upcase
elsif bool == false && LETTERS.include?(element)
bool = !bool
element.downcase
else
element
end
end
str_arr.join
end
=end
###############################################################################
###############################################################################
=begin
"Multiplicative Average"
Write a method that takes an Array of integers as input, multiplies all the
numbers together, divides the result by the number of entries in the Array,
and then prints the result rounded to 3 decimal places. Assume the array is
non-empty.
def show_multiplicative_average(arr)
result = 1.0
arr.each{|x| result *= x }
puts "The result is #{format('%.3f',(result/arr.size))}"
end
=end
###############################################################################
###############################################################################
=begin
"Multiply Lists"
Write a method that takes two Array arguments in which each Array contains a
list of numbers, and returns a new Array that contains the product of each pair
of numbers from the arguments that have the same index. You may assume that the
arguments contain the same number of elements.
def multiply_list(arr1,arr2)
arr3 = []
arr1.size.times{|i| arr3 << (arr1[i]*arr2[i])}
arr3
end
=end
###############################################################################
###############################################################################
=begin
"Multiply All Pairs"
Write a method that takes two Array arguments in which each Array contains a
list of numbers, and returns a new Array that contains the product of every pair
of numbers that can be formed between the elements of the two Arrays. The
results should be sorted by increasing value.
You may assume that neither argument is an empty Array.
Nested loop way:
def multiply_all_pairs(arr1, arr2)
result = []
for i in arr1
for j in arr2
result << i*j
end
end
result.sort
end
=end
###############################################################################
###############################################################################
=begin
"The End Is Near But Not Here"
Write a method that returns the next to last word in the String passed to it as
an argument.
Words are any sequence of non-blank characters.
You may assume that the input String will always contain at least two words.
def penultimate(str)
str.split(" ")[-2]
end
=end
###############################################################################
### Easy 7 End ######################################
### Easy 8 Start ######################################
###############################################################################
=begin
"Sum of Sums"
Write a method that takes an Array of numbers and then returns the sum of the
sums of each leading subsequence for that Array. You may assume that the Array
always contains at least one number.
def sum_of_sums(arr)
sum = 0
arr_clone = arr.clone
for i in 0...arr_clone.size
sum += arr_clone.sum
arr_clone.pop
end
sum
end
=end
###############################################################################
###############################################################################
=begin
"Madlibs"
Mad libs are a simple game where you create a story template with blanks for words.
You, or another player, then construct a list of words and place them into the story,
creating an often silly or funny story as a result.
Create a simple mad-lib program that prompts for a noun, a verb, an adverb, and an
adjective and injects those into a story that you create.
puts "Enter a noun:"
noun = gets.chomp
puts "Enter a verb:"
verb = gets.chomp
puts "Enter an adjective:"
adj = gets.chomp
puts "Enter an adverb:"
adverb = gets.chomp
"Do you like the #{adj} #{noun}? I know the #{noun} can be very #{adj}. Just #{verb} and everything will be alright"
=end
###############################################################################
###############################################################################
=begin
"Leading Substrings"
Write a method that returns a list of all substrings of a string that start at
the beginning of the original string. The return value should be arranged in order
from shortest to longest substring.
def substrings_at_start(str)
arr = []
for i in 1..str.size
arr << str[0,i]
end
arr
end
=end
###############################################################################
###############################################################################
=begin
"All Substrings"
Write a method that returns a list of all substrings of a string. The returned
list should be ordered by where in the string the substring begins. This means
that all substrings that start at position 0 should come first, then all substrings
that start at position 1, and so on. Since multiple substrings will occur at each
position, the substrings at a given position should be returned in order from shortest to longest.
You may (and should) use the substrings_at_start method you wrote in the previous exercise:
def substrings_at_start(str)
arr = []
for i in 1..str.size
arr << str[0,i]
end
arr
end
def substrings(str)
arr = []
for i in 0...str.size
arr << substrings_at_start(str[i..-1])
end
arr.flatten
end
=end
###############################################################################
###############################################################################
=begin
"Palindromic Substrings"
Write a method that returns a list of all substrings of a string that are palindromic.
That is, each substring must consist of the same sequence of characters forwards
as it does backwards. The return value should be arranged in the same sequence as
the substrings appear in the string. Duplicate palindromes should be included multiple times.
You may (and should) use the substrings method you wrote in the previous exercise.
For the purposes of this exercise, you should consider all characters and pay
attention to case; that is, "AbcbA" is a palindrome, but neither "Abcba" nor "Abc-bA" are.
In addition, assume that single characters are not palindromes.
def substrings_at_start(str)
arr = []
for i in 1..str.size
arr << str[0,i]
end
arr
end
def substrings(str)
arr = []
for i in 0...str.size
arr << substrings_at_start(str[i..-1])
end
arr.flatten
end
def palindromes(str)
arr = substrings(str)
arr1 = arr.select {|word| word.size > 1}
arr1.select{|word| word == word.reverse}
end
=end
###############################################################################
###############################################################################
=begin
"fizzbuzz"
Write a method that takes two arguments: the first is the starting number, and
the second is the ending number. Print out all numbers between the two numbers,
except if a number is divisible by 3, print "Fizz", if a number is divisible by 5,
print "Buzz", and finally if a number is divisible by 3 and 5, print "FizzBuzz".
def fizzbuzz(s,e)
arr = []
(s..e).each do |num|
arr << if num % 3 == 0 && num % 5 == 0
a = "FizzBuzz"
elsif num % 3 == 0
a = "Fizz"
elsif num % 5 == 0
a = "Buzz"
else
a = num
end
end
arr.join(", ")
end
=end
###############################################################################
###############################################################################
=begin
"Double Char (Part 1)"
Write a method that takes a string, and returns a new string in which every character is doubled.
def repeater(str)
str.split("").map{|letter| letter*2}.join
end
=end
###############################################################################
###############################################################################
=begin
"Double Char (Part 2)"
Write a method that takes a string, and returns a new string in which every consonant
character is doubled. Vowels (a,e,i,o,u), digits, punctuation, and whitespace should
not be doubled.
def repeater(str)
str.split("").map{|letter| letter*2}.join
end
def double_consonants(str)
result = str.split("").map do |letter|
if letter.downcase.match(/\A(?=[^aeiou])(?=[a-z])/i) != nil
repeater(letter)
else
letter
end
end
result.join
end
=end
###############################################################################
###############################################################################
=begin
"Convert number to reversed array of digits"
Write a method that takes a positive integer as an argument and returns that
number with its digits reversed.
def reversed_number(num)
num.to_s.reverse.to_i
end
=end
###############################################################################
###############################################################################
=begin
"Get The Middle Character"
Write a method that takes a non-empty string argument, and returns the middle
character or characters of the argument. If the argument has an odd length, you
should return exactly one character. If the argument has an even length, you
should return exactly two characters.
def center_of(str)
if str.size.odd?
str[str.size/2]
else
str[(str.size/2)-1,2]
end
end
=end
###############################################################################
### Easy 8 End #######################################
### Easy 9 Start #######################################
###############################################################################
=begin
"Welcome Stranger"
Create a method that takes 2 arguments, an array and a hash. The array will
contain 2 or more elements that, when combined with adjoining spaces, will produce
a person's name. The hash will contain two keys, :title and :occupation, and the
appropriate values. Your method should return a greeting that uses the person's
full name, and mentions the person's title.
def greetings(arr,hash)
puts "Hello #{arr.join(" ")}! Must be cool to be a #{hash[:title]} #{hash[:occupation]}!"
end
=end
###############################################################################
###############################################################################
=begin
"Double Doubles"
A double number is a number with an even number of digits whose left-side digits
are exactly the same as its right-side digits. For example, 44, 3333, 103103, 7676
are all double numbers. 444, 334433, and 107 are not.
Write a method that returns 2 times the number provided as an argument, unless
the argument is a double number; double numbers should be returned as-is.
def double_num?(num)
if num.to_s.size.even?
num.to_s[0..((num.to_s.size/2)-1)] == num.to_s[(num.to_s.size/2)..-1]
end
end
def twice(num)
if double_num?(num)
return num
else
return num*2
end
end
=end
###############################################################################
###############################################################################
=begin
"Always Return Negative"
Write a method that takes a number as an argument. If the argument is a positive
number, return the negative of that number. If the number is 0 or negative, return
the original number.
def negative(num)
if num <= 0
return num
else
return -num
end
end
=end
###############################################################################
###############################################################################
=begin
"Counting Up"
Write a method that takes an integer argument, and returns an Array of all integers,
in sequence, between 1 and the argument.
You may assume that the argument will always be a valid integer that is greater than 0.
def sequence(num)
arr = []
if num > 0
(1..num).each {|x| arr << x}
elsif num < 0
(num..-1).each {|x| arr << x}
arr.reverse!
end
arr
end
=end
###############################################################################
###############################################################################
=begin
"Uppercase Check"
Write a method that takes a string argument, and returns true if all of the
alphabetic characters inside the string are uppercase, false otherwise. Characters
that are not alphabetic should be ignored.
def uppercase?(str)
uppers = ("A".."Z").to_a
lowers = ("a".."z").to_a
just_letters = str.chars.select{|char| uppers.include?(char) || lowers.include?(char)}
just_letters.all?{|letter| uppers.include?(letter)}
end
=end
###############################################################################
###############################################################################
=begin
"How long are you?"
Write a method that takes a string as an argument, and returns an Array that
contains every word from the string, to which you have appended a space and the word length.
You may assume that words in the string are separated by exactly one space, and
that any substring of non-space characters is a word.
def word_lengths(str)
str.split(" ").each_with_object([]){|w,arr| arr << (w + " #{w.size}")}
end
=end
###############################################################################
###############################################################################
=begin
"Name Swapping"
Write a method that takes a first name, a space, and a last name passed as a
single String argument, and returns a string that contains the last name, a
comma, a space, and the first name.
def swap_name(name)
n = name.split(" ")
return "#{n[1]}, #{n[0]}"
end
=end
###############################################################################
###############################################################################
=begin
"Sequence Count"
Create a method that takes two integers as arguments. The first argument is a
count, and the second is the first number of a sequence that your method will
create. The method should return an Array that contains the same number of elements
as the count argument, while the values of each element will be multiples of the starting number.
You may assume that the count argument will always have a value of 0 or greater,
while the starting number can be any integer value. If the count is 0, an empty list
should be returned.
def sequence(count,num)
n = 0
(1..count).to_a.each_with_object([]) do |_,arr|
n+= num
arr << n
end
end
=end
###############################################################################
###############################################################################
=begin
"Grade Book"
Write a method that determines the mean of the three scores passed to it, and
returns the letter value associated with that grade. Tested values are all between
0 and 100. There is no need to check for negative values or values greater than 100.
def get_grade(num1,num2,num3)
avg = (num1 + num2 + num3)/3
result = case avg
when 90..100
"A"
when 80..89
"B"
when 70..79
"C"
when 60..69
"D"
when 0..59
"F"
else
"Invalid Input"
end
result
end
=end
###############################################################################
###############################################################################
=begin
"Grocery List"
Write a method which takes a grocery list (array) of fruits with quantities and
converts it into an array of the correct number of each fruit.
def buy_fruit(arr)
arr.each_with_object([]) do |sub_array, result|
sub_array[1].times{result << sub_array[0]}
end
end
=end
###############################################################################
### Easy 9 End #######################################
|
FactoryGirl.define do
factory :account do
company_id 1
name 'Cash'
description 'Money for immediate use'
category :assets
subcategory :current
end
end
|
require 'CSV'
class PhobiaApp < Sinatra::Base
set :haml, :format => :html5
configure do
set :daily_phobia, { phobia: nil, phobia_descr: nil, crt: nil }
set :phobia_list, CSV.open('phobia_list.txt', 'r', col_sep: "\t").to_a.drop(1)
end
def load_phobias
print "\nLoading phobia file...\n"
csv = CSV.open('phobia_list.txt', 'r', col_sep: "\t")
return csv.to_a.drop(1)
end
def new_daily_phobia
rand_phobia = settings.phobia_list.sample;
phobia_name = rand_phobia[0].split
phobia_name[0].sub(/-/, "")
settings.daily_phobia["phobia"] = phobia_name.first
settings.daily_phobia["phobia_descr"] = rand_phobia[1]
settings.daily_phobia["crt"] = Time.now
print "NEW PHOBIA!!\n"
end
before do
headers "Content-Type" => "text/html; charset=uft-8"
end
get '/' do
haml :home
end
get '/daily' do
curr_time = Time.now
beginning_day = Time.utc(curr_time.year, curr_time.month, curr_time.day, 0, 0)
ending_day = Time.utc(curr_time.year, curr_time.month, curr_time.day, 23, 59)
time_range = beginning_day..ending_day
#check for first run
if(settings.daily_phobia["phobia"] == nil)
print "first run\n"
new_daily_phobia()
end
#get new phobia if the last phobia's timestamp is outside today's range
print
if (time_range.cover?(settings.daily_phobia["crt"]) == false)
print "change date....\n"
new_daily_phobia()
end
haml :daily_phobia, :locals => {:daily_phobia => settings.daily_phobia}
end
end
|
# == Schema Information
#
# Table name: branches
#
# id :integer not null, primary key
# name :string
# address :string
# shop_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# latitude :float
# longitude :float
# prefecture_id :integer
#
class Branch < ActiveRecord::Base
belongs_to :shop, counter_cache: true
belongs_to :prefecture
validates :name, presence: true, uniqueness: true
geocoded_by :address
after_validation :geocode
scope :with_shop, -> { includes(:shop) }
scope :with_prefecture, -> { includes(:prefecture) }
scope :of_shops, -> ids { where("shop_id IN (?)", ids) }
scope :in_prefecutres, -> ids { where("prefecture_id IN (?)", ids) }
def self.search(sid, pid)
Branch.where(shop_id: sid, prefecture_id: pid)
end
def self.make_latlng_uniq(branches)
increment_num = 0.0001
# frequency = {}
branches.each_with_index do |a, i|
# frequency["#{a.latitude}, #{a.longitude}"] = [a.address]
branches[i..-1].each do |b|
if b.shop_id == a.shop_id
next
end
if equal_latlng(a, b)
b.longitude += increment_num
# frequency["#{a.latitude}, #{a.longitude}"].push(b.name+":"+b.address)
end
end
end
# puts "RESULT"
# puts frequency.sort_by{|k, v| v.length}.reverse
return branches
end
private
# latitude, longitudeが同じかどうかを判断する
def self.equal_latlng(a, b)
if a.latitude.nil? || b.latitude.nil? || a.longitude.nil? || b.longitude.nil?
return false
end
return a.latitude == b.latitude && a.longitude == b.longitude
end
end
|
##
# TileRack is the child class of the TileGroup class
# via inheritance
require_relative "tile_group.rb"
require_relative "tile_bag.rb"
require_relative "Word.rb"
class TileRack < TileGroup
## subclass constructor
def initialize
super
end
##
# this method returns the number of tiles needed to fill the
# rack to upto 7 tiles
def number_of_tiles_needed
return 7-self.tiles.length
end
##
# this method returns true if rack has enough
#letters to make the input text parameter
# since only 7 letters are stored at a time this may be acceptable
# if -loop provides speed improvement for rogue(long) inputs
def has_tiles_for?(text)
array = text.upcase.split("")
if(array.length<=self.hand.length)
self.hand.split("").each{|x| i =array.index(x); array.delete_at(i) if i}
array.empty?
else
return false
end
end
##
# method to remove text from tile rack and making a Word
# Word is returned
def remove_word(text)
wordObject = Word.new
if(self.has_tiles_for?(text))
text.upcase.split("").each{|x| i =@arrayOfTiles.index(x.to_sym);
@arrayOfTiles.delete_at(i);wordObject.append(x.to_sym) }
end
wordObject
end
end
|
require 'filequeue'
require_relative 'proxy'
class ProxyStore < FileQueue
def initialize(filename)
File.write(filename, '') unless File.file? filename
super
end
def pop
item = super
item ? Proxy.from_s(item) : nil
end
alias next pop
def push(proxy)
super proxy.to_s if proxy
end
alias << push
end
class AutoProxyStore < ProxyStore
require_relative 'proxy_finder'
def pop
super || ProxyFinder.next_valid_proxy
end
alias next pop
end
|
# encoding: UTF-8
require 'yaml'
require './minefield.rb'
class Game
BITS = %w(HEAD ARM BUTT LEGS FACE PET-TURTLE)
attr_reader :map
def initialize(matrix_side_length, number_of_bombs)
@minefield = MineField.new(matrix_side_length, number_of_bombs)
end
def play
begin
display
move(*get_input)
end until win?
display
win_message
end
def save
File.open('saved_game.txt', 'w') do |f|
f.print @minefield.to_yaml
end
end
def load
field = YAML.load(File.read('saved_game.txt'))
if field.is_a?(MineField)
@minefield = field
else
puts "-----NO SAVED GAME-----"
end
end
def display
@minefield.display
end
def win_message
puts "YOU HAVE WON!!!"
puts "YOU DID NOT LOSE YOUR #{BITS.sample}!!!"
puts "I LIKE YOU!!!!"
end
def move(y, x = nil, flagging = false)
unless x
if y == 's'
save
return
else
load
return
end
end
if flagging
@minefield[[x.to_i, y.to_i]].flag
else
@minefield[[x.to_i, y.to_i]].sweep
lose if @minefield[[x.to_i, y.to_i]].bomb?
end
end
def get_input
valid = false
until valid
prompt
choice = gets.split
valid = check_valid(choice)
end
choice
end
# refactor with Error stuff.
def check_valid(choice)
return false unless choice.length.between?(1,3)
if choice.length.between?(2, 3)
return false unless choice[0].between?("0", (@minefield.matrix_side_length - 1).to_s)
return false unless choice[1].between?("0", (@minefield.matrix_side_length - 1).to_s)
return true if choice.length == 3 && choice[2].downcase == "f"
return true
end
return true if choice[0].downcase == "s" || choice[0].downcase == "l"
puts
puts "---WARNING---"
puts "Never operate a minesweeper device without RTFM!"
puts "---WARNING---"
puts
false
end
def prompt
puts "enter s to save or l to load a game"
puts "to sweep, enter x and y index seperated by a space. (0 0)"
puts "follow indices with 'f' if you want to flag (0 0 f)"
end
def win?
@minefield.win?
end
def lose
display
puts "BOOOOM!"
puts "YOU HAVE LOST YOUR #{BITS.sample}!!!"
exit
end
end
Game.new(9, 11).play
|
# == Schema Information
#
# Table name: platform_phone_numbers
#
# id :bigint(8) not null, primary key
# phone_number :string
# provider :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class PlatformPhoneNumber < ApplicationRecord
has_many :blocked_numbers, :dependent => :destroy
validates :phone_number, :provider, presence: true
enum provider: {twilio: 0, nexmo: 1}
end
|
require 'spec_helper'
require 'app/presenters/social_media_account_presenter'
describe SocialMediaAccountPresenter do
let(:social_media_accounts) do
[Factory(:social_media_account), Factory(:social_media_account)]
end
it 'presents a social_media_account with a root key' do
social_media_account = social_media_accounts.first
expected = {
'social_media_account' => {
'website' => social_media_account.website,
'handle' => social_media_account.handle,
'_links' => {
'external' => {
'href' => social_media_account.url
}
}
}
}
hash = SocialMediaAccountPresenter.present(social_media_accounts.first, context: self)
expect(hash).to eq(expected)
end
end
describe SocialMediaAccountsPresenter do
let(:context) do
double.tap do |d|
allow(d).to receive(:params).and_return({})
end
end
before { 2.times { Factory(:social_media_account) } }
it 'presents a collection of social_media_accounts' do
social_media_accounts = SocialMediaAccount.all
expected = {
'count' => 2,
'social_media_accounts' => [
SocialMediaAccountPresenter.new(social_media_accounts.first, context: context, root: nil).present,
SocialMediaAccountPresenter.new(social_media_accounts.last, context: context, root: nil).present
]
}
presented = SocialMediaAccountsPresenter.new(social_media_accounts, context: context, root: nil).present
expect(presented['count']).to eq(expected['count'])
expect(presented['social_media_accounts']).to match_array(expected['social_media_accounts'])
end
end
|
class News < Article
set_table_name "news"
validates_presence_of :synopsis, :if => Proc.new {|c| c.published?}
end
|
class Admin::TweetsController < Admin::ApplicationController
include LaughTrack::CouchDb
def unclassified
@total = db.function('_design/laughtrack/_view/unclassified').length
@docs = unclassified_ids.collect { |hash| db.get hash.id }
end
def unconfirmed
@docs = unconfirmed_ids.collect { |hash| db.get hash.id }
end
def confirmed
@docs = confirmed_ids.collect { |hash| db.get hash.id }
end
def positive
doc = db.get params[:id]
doc.classification = 'positive'
doc.confirmed = true
db.save doc
redirect_to :back
end
def negative
doc = db.get params[:id]
doc.classification = 'negative'
doc.confirmed = true
db.save doc
redirect_to :back
end
def ignore
doc = db.get params[:id]
doc.ignore = true
db.save doc
redirect_to :back
end
def confirm
doc = db.get params[:id]
doc.confirmed = true
db.save doc
redirect_to :back
end
private
def unclassified_ids
@unclassified_ids ||= db.function('_design/laughtrack/_view/unclassified',
:limit => 20)
end
def unconfirmed_ids
@unconfirmed_ids ||= db.function('_design/laughtrack/_view/unconfirmed',
:limit => 20)
end
def confirmed_ids
@confirmed_ids ||= db.function('_design/laughtrack/_view/confirmed')
end
end
|
Pod::Spec.new do |s|
s.name = "AGURLSessionStubs"
s.version = "0.2"
s.summary = "A small library inspired by OHHTTPStubs to stub your network requests written in Swift"
s.homepage = "https://github.com/aerogear/aerogear-ios-httpstub"
s.license = "Apache License, Version 2.0"
s.author = "Red Hat, Inc."
s.platform = :ios, "8.0"
s.source = { :git => "https://github.com/aerogear/aerogear-ios-httpstub.git", :branch => "master" }
s.source_files = 'AGURLSessionStubs/*.{swift}'
s.framework = "Foundation"
end
|
# encoding: UTF-8
#
# Author:: Xabier de Zuazo (<xabier@zuazo.org>)
# Copyright:: Copyright (c) 2014-2015 Onddo Labs, SL.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require_relative '../spec_helper'
describe 'postfixadmin::apache', order: :random do
let(:chef_run) do
ChefSpec::SoloRunner.new do |node|
node.set['postfixadmin']['ssl'] = true
end.converge(described_recipe)
end
before { stub_command('/usr/sbin/apache2 -t').and_return(true) }
it 'includes apache2::default recipe' do
expect(chef_run).to include_recipe('apache2::default')
end
it 'includes php recipe' do
expect(chef_run).to include_recipe('php')
end
it 'includes apache2::mod_php5 recipe' do
expect(chef_run).to include_recipe('apache2::mod_php5')
end
it 'creates ssl_certificate' do
expect(chef_run).to create_ssl_certificate('postfixadmin')
end
it 'ssl_certificate resource notifies apache' do
resource = chef_run.ssl_certificate('postfixadmin')
expect(resource).to notify('service[apache2]').to(:restart).delayed
end
context 'web_app postfixadmin definition' do
it 'creates apache2 site' do
expect(chef_run)
.to create_template(%r{/sites-available/postfixadmin\.conf$})
end
end
context 'ruby_block[web_app-postfixadmin-reload]' do
let(:resource) do
chef_run.find_resource(:ruby_block, 'web_app-postfixadmin-reload')
end
it 'notifies apache restart' do
expect(resource).to notify('service[apache2]').to(:restart).immediately
end
it 'subscribes to a2ensite postfixadmin' do
expect(resource).to subscribe_to('execute[a2ensite postfixadmin.conf]')
.on(:create).immediately
end
end
end
|
module Slideshare
module Configuration
VALID_OPTIONS_KEYS = [
:api_version,
:api_key,
:api_shared_secret,
:api_http_endpoint,
:api_https_endpoint,
:api_response_format
].freeze
VALID_FROMATS = [:xml].freeze
DEFAULT_API_VERSION = "2".freeze
DEFAULT_API_KEY = nil
DEFAULT_API_SHARED_SECRET = nil
DEFAULT_API_HTTP_ENDPOINT = "http://www.slideshare.net/api/2/".freeze
DEFAULT_API_HTTPS_ENDPOINT = "https://www.slideshare.net/api/2/".freeze
DEFAULT_API_RESPONSE_FORMAT = :xml
# @private
attr_accessor *VALID_OPTIONS_KEYS
# When this module is extended, set all configuration options to their default values
def self.extended(base)
base.reset
end
# Convenience method to allow configuration options to be set in a block
def configure
yield self
end
# Create a hash of options and their values
def options
Hash[VALID_OPTIONS_KEYS.map {|key| [key, send(key)] }]
end
# Reset all configuration options to defaults
def reset
self.api_version = DEFAULT_API_VERSION
self.api_key = DEFAULT_API_KEY
self.api_shared_secret = DEFAULT_API_SHARED_SECRET
self.api_http_endpoint = DEFAULT_API_HTTP_ENDPOINT
self.api_https_endpoint = DEFAULT_API_HTTPS_ENDPOINT
self.api_response_format = DEFAULT_API_RESPONSE_FORMAT
self
end
end
end
|
require 'spec_helper'
module Alf
module Operator::Relational
describe Summarize::SortBased do
let(:input) {[
{:a => "via_method", :time => 1},
{:a => "via_method", :time => 1},
{:a => "via_method", :time => 2},
{:a => "via_reader", :time => 4},
{:a => "via_reader", :time => 2},
]}
let(:expected) {[
{:a => "via_method", :time_sum => 4, :time_max => 2},
{:a => "via_reader", :time_sum => 6, :time_max => 4},
]}
let(:aggs){Summarization.new(
:time_sum => Aggregator.sum{ time },
:time_max => Aggregator.max{ time }
)}
let(:operator){ Summarize::SortBased.new(by_key, allbut, aggs) }
before{ operator.pipe(input) }
subject{ operator.to_a.sort{|t1,t2| t1[:a] <=> t2[:a]} }
describe "when allbut is not set" do
let(:by_key){ AttrList.new([:a]) }
let(:allbut){ false }
it { should == expected }
end
describe "when allbut is set" do
let(:by_key){ AttrList.new([:time]) }
let(:allbut){ true }
it { should == expected }
end
end
end
end
|
# encoding: binary
# frozen_string_literal: true
RSpec.shared_examples "HMAC" do
context ".new" do
it "raises EncodingError on a key with wrong encoding" do
expect { described_class.new(wrong_key) }.to raise_error(EncodingError)
end
it "raises LengthError when key is zero bytes" do
expect { described_class.new("") }.to raise_error(::RbNaCl::LengthError)
end
end
context ".auth" do
it "raises EncodingError on a key with wrong encoding " do
expect { described_class.auth(wrong_key, message) }.to raise_error(EncodingError)
end
end
context ".verify" do
it "raises EncodingError on a key with wrong encoding" do
expect { described_class.verify(wrong_key, tag, message) }.to raise_error(EncodingError)
end
end
context "Instance methods" do
let(:authenticator) { described_class.new(key) }
before(:each) { authenticator.update(message) }
context "#update" do
it "returns hexdigest when produces an authenticator" do
expect(authenticator.update(message)).to eq mult_tag.unpack1("H*")
end
end
context "#digest" do
it "returns an authenticator" do
expect(authenticator.digest).to eq tag
end
end
context "#hexdigest" do
it "returns hex authenticator" do
expect(authenticator.hexdigest).to eq tag.unpack1("H*")
end
end
end
end
|
class TagsController < ApplicationController
def create
@image = Image.find params[:image_id]
@tag = @image.tags.new(params.require(:tag).permit(:str))
if @tag.save
redirect_to image_url(@image), notice: "Tag saved"
else
redirect_to image_url(@image), notice: "Tag not saved"
end
end
def edit
@tag = Tag.find(params[:id])
end
def update
@tag = Tag.find(params[:id])
if @tag.update(params.require(:tag).permit(:str))
redirect_to image_url(@tag.image)
else
redirect_to image_url(@tag.image), notice: "Tag update failed"
end
end
def destroy
@tag = Tag.find(params[:id])
@tag.destroy
redirect_to image_url(@tag.image)
end
end
|
class Post < ActiveRecord::Base
# hooks
# relations
belongs_to :sub
belongs_to :user
has_many :comments
has_one :popmeter, as: :votable
# validations
validates :title, presence: true, length: { maximum: 130 }
validates :link, presence: true
validates :text, length: { maximum: 1200 }
self.per_page = 30
def total
self.popmeter.total
end
def upvotes
self.popmeter.upvotes
end
def downvotes
self.popmeter.downvotes
end
end
|
module ChartsHelper
def self.l(s)
s
end
# Shows chart plugin menu.
def show_charts_menu
res = ""
RedmineCharts::Utils.controllers_for_routing do |name, controller_name|
link_name = l("charts_link_#{name}".to_sym)
if controller.controller_name == controller_name
res << link_name << "<br /> "
else
res << link_to(link_name, :controller => controller_name, :project_id => @project) << "<br /> "
end
end
res
end
# Shows chart flash setting path to data.
def show_graph(data)
div_name = 'flash_content_leRRmNzK'
relative_url_path = ActionController::Base.respond_to?(:relative_url_root) ? ActionController::Base.relative_url_root : ActionController::AbstractRequest.relative_url_root
html = "<div id=\"#{div_name}\"></div>"
html << '<script type="text/javascript">' << "\n"
html << "function open_flash_chart_inline_data() {\n"
html << "return '#{data.gsub("'","\\\\'")}';\n"
html << "};\n"
html << "swfobject.embedSWF('#{relative_url_path}/plugin_assets/open_flash_chart/open-flash-chart.swf', '#{div_name}', '100%', '400', '9.0.0', 'expressInstall.swf', {'get-data':'open_flash_chart_inline_data'});"
html << "\nvar charts_to_image_title = '#{h(controller.controller_name)}';\n"
html << "var charts_to_image_id = '#{div_name}';\n"
html << '</script>'
html
end
# Shows date condition.
def show_date_condition(limit, range, offset)
res = ""
res << l(:charts_show_last) << " "
res << text_field_tag(:limit, limit, :size => 4)
res << hidden_field_tag(:offset, offset) << " "
res << select_tag(:range, options_for_select(RedmineCharts::RangeUtils.options, range.to_sym))
res << ' '
# Pagination.
res << link_to_function(l(:charts_earlier), :onclick => 'charts_earlier();') << " - "
if offset.to_i == 1
res << l(:charts_later)
else
res << link_to_function(l(:charts_later), :onclick => 'charts_later();')
end
res
end
# Shows pages.
def show_pages(page, pages)
res = ""
if pages > 1
if page == 1
res << l(:charts_previous)
else
res << link_to_function(l(:charts_previous), :onclick => 'charts_previous();')
end
res << ' - '
if page == pages
res << l(:charts_next)
else
res << link_to_function(l(:charts_next), :onclick => 'charts_next();')
end
end
res
end
end
|
class Item < ActiveRecord::Base
belongs_to :list
def days_left
# Get todays date using DateTime object then strip off hrs, mins, secs using `.to_date` method.
todays_date = DateTime.now.to_date
# Get the created_at date for that item and strip hrs, mins and secs.
item_created_at = self.created_at.to_date
# Note how long an item has before auto delete.
item_duration = 7.days
# Figure out the due date, takes the created_at and adds 7 days to it.
due_date = item_created_at + item_duration
# Take the due_date and subtract todays date, et voila!
(due_date - todays_date).to_i
end
end
|
class UserProfileBorder < Netzke::Base
# Remember regions collapse state and size
include Netzke::Basepack::ItemPersistence
component :user_logs
component :user_stats
component :user_profiles
def configure(c)
super
c.header = false
c.items = [
{ netzke_component: :user_logs, region: :center, split: true},
{ netzke_component: :user_stats, region: :east, width: 350, split: true},
{ netzke_component: :user_profiles, region: :south, height: 150, split: true }
]
end
js_configure do |c|
c.layout = :border
c.border = false
c.mixin :init_component
end
end
|
Rails.application.routes.draw do
# The priority is based upon order of creation:
# first created -> highest priority.
resources:photos
# Sample of regular route:
# match 'products/:id' => 'catalog#view'
# Keep in mind you can assign values other than :controller and :action
root "photos#index"
end |
class Dashboard::OrdersController < Dashboard::BaseController
def index
@orders = current_user.orders.page(params[:page] || 1).per(params[:per_page] || 12).order(id: "desc").includes(:address)
end
end
|
class MainController < ApplicationController
before_action :authenticate_admin!, only: [:admin]
def index
#access main dashboard
@game = update()
unless @game.paused
@next_round = @game.next_round.getlocal.strftime("%l:%M:%S %p")
else
@next_round = (@game.next_round + (Time.now - @game.pause_time)).getlocal.strftime("%l:%M:%S %p")
end
@terror = TerrorTracker.sum(:amount)
@time_til_next_round = (@game.next_round - Time.now)*6
p "Next round time is : #{@time_til_next_round}"
t = Launchstart.first
data = {}
data[:game] = @game
data[:nuclear_launch] = t.value
data[:next_round] = @next_round
data[:time_til_next_round] = (@game.next_round - Time.now)
data[:terror] = @terror
respond_to do |format|
format.html
format.json {render json: data}
end
end
def reset_game
Game.reset
redirect_to root_path
end
def admin
@game = Game.first
end
def update_control_message
@game = Game.first
@game.control_message = params[:game][:control_message]
@game.save
redirect_to admin_controls_path
end
def toggle_game_status
@game = Game.first
#Game was paused
unless @game.paused
@game.next_round = @game.next_round + (Time.now - @game.pause_time)
else
@game.pause_time = Time.now
end
@game.paused = !@game.paused
@game.save
redirect_to admin_controls_path
end
private
def update
game = Game.first
# Can't have more than 12 rounds.
if game.current_round > 13
game.paused = True
game.saved
end
unless game.paused
if game.next_round < Time.now
game.current_round +=1
game.next_round = game.next_round + (30*60)
game.save()
end
end
return game
end
end
|
class Festival < ActiveRecord::Base
include Skyscanner
SEARCH_RADIUS = 500
has_many :performances, dependent: :destroy
has_many :artists, through: :performances
has_many :festival_genres, dependent: :destroy
has_many :genres, through: :festival_genres
validates :name, presence: true
def search_flights(params)
key = "flights/#{params["festival_id"]}/#{params["departure_airport"]}/#{params["arrival_airport"]}"
Rails.cache.fetch(key, expires_in: 30.minutes) do
session_id = create_skyscanner_session(params)
if session_id
data = get_itineraries(session_id)
@results = get_first_five_results(data)
else
@results = []
end
end
end
def self.different_airport?(departure, arrival)
departure != arrival
end
def self.upcoming
Rails.cache.fetch("upcoming_festivals", expires_in: 1.hours) do
Festival.includes(:genres).where('start_date > ?', Date.today).order(:start_date).limit(20)
end
end
def self.search(params, date, session_id)
@festivals = self.joins("INNER JOIN performances AS p ON p.festival_id = festivals.id INNER JOIN artists AS a ON p.artist_id = a.id INNER JOIN festival_genres AS fg ON fg.festival_id = festivals.id INNER JOIN genres AS g ON fg.genre_id = g.id").where('start_date >= ? AND LOWER(camping) LIKE ? AND g.name LIKE ? AND a.name LIKE ?', date, "%#{params[:camping]}%", "%#{params[:genre]}%", "%#{params[:artist]}%").distinct
d = DistanceService.new
@festivals = @festivals.select do |f|
dist_km = d.calc_distance(params["search_lat"], params["search_long"], f)
dist_km <= SEARCH_RADIUS
end
end
def self.set_background(num_of_festivals)
img_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
@img_classes = []
num_of_festivals.times do
i = rand(img_array.length)
@img_classes << img_array[i]
end
@img_classes
end
def validate_bus_search(festival, usr_location)
depart_from = { city: usr_location["city"], state: usr_location["state"]}
return_from = { city: festival.city, state: festival.state }
if festival.country != "CA" && festival.country != "US"
return "Sorry, bus schedules are currently only available for Canada and US"
elsif depart_from == return_from
return "Festival is located in your home city. You're already there!"
elsif Date.today > festival.end_date
return "Festival has already ended."
elsif Date.today >= festival.start_date
return "Festival already in progress."
else
return nil
end
end
def validate_flight_search(festival, usr_location, session_id)
departure_airport = $redis.hget(session_id, 'departure_airport_iata')
arrival_airport = DistanceService.new.get_nearest_airport(festival.latitude, festival.longitude, festival.country).iata_code.downcase
if departure_airport == arrival_airport
return "Festival is located in your home city. Try the driving directions!"
elsif Date.today > festival.end_date
return "Festival has already ended."
elsif Date.today >= festival.start_date
return "Festival already in progress."
else
return nil
end
end
def save_bus_data(greyhound_data, festival_id, session_id)
puts greyhound_data
if greyhound_data.is_a? Hash
greyhound_data[:depart].each do |key, schedule|
@lowest_cost = []
@lowest_cost << schedule[:cost].to_f
@lowest_cost = @lowest_cost.min
end
bus_time = greyhound_data[:depart][0][:travel_time]
redis_key = "#{session_id}_#{festival_id}_bus"
$redis.hmset("#{redis_key}", 'searched?', 'true', 'cost', @lowest_cost, 'time', bus_time)
else
$redis.hmset("#{redis_key}", 'searched?', 'true')
end
$redis.expire("#{redis_key}", 1800)
end
def self.get_flickr_images(festival)
url = "https://api.flickr.com/services/rest/?api_key=#{ENV['FLICKR_KEY']}&method=flickr.photos.search&tags=festival&text=#{festival}&sort=relevance&per_page=10&page=1&content_type=1&format=json&nojsoncallback=1"
encode_url = URI.encode(url)
img_src = URI.parse(encode_url)
response = HTTParty.get(img_src).body
@image = JSON.parse(response)
end
def get_festival_travel_data(session_id, festival, user_location, params)
festival_json = festival.as_json
@fg = FestivalGridService.new
bus = $redis.hgetall("#{session_id}_#{festival.id}_bus")
# byebug
if bus['searched?'] == 'true'
festival_json['price_bus'] = bus["cost"]
festival_json['time_bus'] = bus["time"]
else
bus = @fg.get_first_bus(festival, session_id, user_location)
if bus && bus.is_a?(Hash)
festival_json['price_bus'] = bus[:cost]
festival_json['time_bus'] = bus[:travel_time]
end
end
arrival_airport = DistanceService.new.get_nearest_airport(festival.latitude, festival.longitude, festival.country)
arrival_airport = arrival_airport.iata_code.downcase
flight = $redis.hgetall("#{session_id}_#{festival.id}_flight_#{user_location["departure_airport_iata"]}_#{arrival_airport}")
if flight['searched?'] == 'true'
festival_json['price_flight'] = flight['cost']
festival_json['time_flight_in'] = flight['outbound_time']
festival_json['time_flight_out'] = flight['inbound_time']
else
result = @fg.get_cheapest_flight(festival, user_location)
if result
festival_json['price_flight'] = flight['PricingOptions'][0]['Price']
festival_json['time_flight_in'] = flight[:inbound_leg]['Duration']
festival_json['time_flight_out'] = flight[:outbound_leg]['Duration']
end
end
festival_json['price_car'] = params["drivingPrice"]
festival_json['time_car'] = params["drivingTime"]
festival_json
end
end
|
json.array!(@venta_diaria) do |venta_diarium|
json.extract! venta_diarium, :id, :fecha, :monto, :monto_notas_credito, :monto_bruto, :monto_bruto_usd, :monto_costo_venta, :monto_neto, :monto_neto_usd, :editable
json.url venta_diarium_url(venta_diarium, format: :json)
end
|
# frozen_string_literal: true
module SecurityApp
class SecurityPermissionInteractor < BaseInteractor
def repo
@repo ||= SecurityGroupRepo.new
end
def security_permission(cached = true)
if cached
@security_permission ||= repo.find_security_permission(@id)
else
@security_permission = repo.find_security_permission(@id)
end
end
def validate_security_permission_params(params)
SecurityPermissionSchema.call(params)
end
def create_security_permission(params)
res = validate_security_permission_params(params)
return validation_failed_response(res) unless res.messages.empty?
@id = repo.create_security_permission(res)
success_response("Created security permission #{security_permission.security_permission}",
security_permission)
rescue Sequel::UniqueConstraintViolation
validation_failed_response(OpenStruct.new(messages: { security_permission: ['This security permission already exists'] }))
end
def update_security_permission(id, params)
@id = id
res = validate_security_permission_params(params)
return validation_failed_response(res) unless res.messages.empty?
repo.update_security_permission(id, res)
success_response("Updated security permission #{security_permission.security_permission}",
security_permission(false))
end
def delete_security_permission(id)
@id = id
name = security_permission.security_permission
repo.delete_security_permission(id)
success_response("Deleted security permission #{name}")
end
end
end
|
class UniversityChoicesController < ApplicationController
before_action :authenticate_user!
authorize_resource
before_action :set_university_choice, only: [:show, :edit, :update, :destroy]
# GET /university_choices
# GET /university_choices.json
def index
@university_choices = UniversityChoice.all
end
# GET /university_choices/1
# GET /university_choices/1.json
def show
end
# GET /university_choices/new
def new
@applicant = params[:applicant] ? Applicant.find(params[:applicant]) : current_user.applicant
@applicant.complete_program_choices.each do |pc|
uc_count = pc.university_choices.count
((uc_count + 1)..pc.program.universities.count).each do |order|
UniversityChoice.create(choice_order: order, program_choice_id: pc.id)
end
end
end
# GET /university_choices/1/edit
def edit
end
# POST /university_choices
# POST /university_choices.json
def create
@applicant = Applicant.find(params[:applicant])
uc_params = params["university_choices"]
uc_params.each do |university_choice|
uc = UniversityChoice.find(uc_params[university_choice]["id"])
uc.update(university_id: nil)
end
uc_params.each do |university_choice|
uc = UniversityChoice.find(uc_params[university_choice]["id"])
uc.update(university_choice_params(uc_params[university_choice]))
end
unless @applicant.complete_university_choices.blank?
flash[:notice] = 'University choices saved successfully'
if @applicant.applicant_exam_hub.blank?
redirect_to new_applicant_exam_hub_path(applicant: @applicant.id)
else
redirect_to edit_applicant_exam_hub_path(@applicant.applicant_exam_hub)
end
else
flash[:alert] = 'Please select at least one university to proceed'
render 'new'
end
end
# PATCH/PUT /university_choices/1
# PATCH/PUT /university_choices/1.json
def update
end
# DELETE /university_choices/1
# DELETE /university_choices/1.json
def destroy
@university_choice.destroy
respond_to do |format|
format.html { redirect_to university_choices_url, notice: 'University choice was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_university_choice
@university_choice = UniversityChoice.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def university_choice_params(my_params)
my_params.permit(:id, :program_choice_id, :choice_order, :university_id)
end
end
|
class AddConfirmableAttributesToUser < ActiveRecord::Migration
change_table :users do |t|
t.column :confirmation_token, :string
t.column :confirmed_at, :datetime
t.column :confirmation_sent_at, :datetime
t.column :unconfirmed_email, :string
t.index :confirmation_token
end
end
|
class Product < ApplicationRecord
has_many :order_items, dependent: :destroy
has_many :reviews, dependent: :destroy
belongs_to :user, optional: true
has_and_belongs_to_many :categories
validates :name, presence: true, uniqueness: true
validates :price, presence: true, numericality: {only_integer: true, greater_than: 0}
validates :stock, presence: true, numericality: {only_integer: true, greater_than_or_equal_to: 0}
def show_rating
@reviews = Review.all
total = 0
reviews = @reviews.where(product_id: self.id)
return "No reviews" if reviews.count == 0
reviews.each do |review|
total += review.rating
end
average = total/reviews.count
return average
end
def self.by_pet_type
# {"cat"=>[product1]}
products_by_pets = {}
Product.all.each do |product|
unless products_by_pets.key? product.pet_type
# that pet type is not already there
products_by_pets[product.pet_type] = []
end
products_by_pets[product.pet_type] << product
end
return products_by_pets
end
def self.pet_type(type)
where(pet_type: type).limit(4)
end
def self.cat
pet_type("cat")
end
def self.dog
pet_type("dog")
end
def self.reptile
pet_type("reptile")
end
def stock_reduction(quantity)
stock = self.stock - quantity
self.update(stock: stock)
end
end
|
FactoryGirl.define do
factory :team do
token 'RyPgoRCq4HvWQX1b37l6ivRQ'
slack_team_id 'T0001'
domain 'example'
trait :with_user do
after :create do |object, evaluator|
create(:user, team: object)
end
end
trait :with_channel do
after :create do |object, evaluator|
create(:channel, team: object)
end
end
end
end
|
class DayAheadEnergyVolume < ActiveRecord::Base
belongs_to :region, class_name: "EnergyRegion"
end
|
class PalletLabel < Prawn::Document
def initialize(pallet)
super(top_margin: 80)
@i = 0
@pallet = pallet
while @i < @pallet.number_of_pallets
@pallet_number = @pallet.id + @i
pallet_number
origin_cc
destination_cc
vendor
pallet_date
barcode
@i += 1
if @i < @pallet.number_of_pallets
start_new_page
end
end
p = Pallet.find(@pallet.id)
p.number_of_pallets = 1
p.save
end
def pallet_number
move_down 20
text "Pallet: "+@pallet_number.to_s, size: 30, style: :bold
end
def origin_cc
move_down 20
text "Origin: "+@pallet.origin_cc, size: 30, style: :bold
end
def destination_cc
move_down 20
text "Destination: "+@pallet.destination_cc, size: 30, style: :bold
end
def vendor
move_down 20
text "Vendor: "+@pallet.vendor_code, size: 30, style: :bold
end
def pallet_date
move_down 20
text "Date Created: "+@pallet.created_at.strftime("%e %b %Y"), size: 30, style: :bold
end
def barcode
move_down 20
barcode = Barby::Code39.new @pallet_number.to_s
barcode.annotate_pdf(self)
end
end
|
require_relative 'code'
class Parser
def initialize(assembly_instructions)
@assembly_instructions = assembly_instructions
@machine_instructions = []
@code_instructions = Code.new()
end
def parse
@assembly_instructions.each do |instruction|
if command_type(instruction) == :a_command
@machine_instructions << assemble_a_command(instruction)
elsif command_type(instruction) == :c_command
@machine_instructions << assemble_c_command(instruction)
end
end
@machine_instructions
end
def assemble_a_command(instruction)
command = "0"
command << constant(instruction[1..-1])
end
def constant(value)
"%015b" % value
end
def assemble_c_command(instruction)
command = "111"
if instruction.include? '='
@c_instruction = instruction.split('=')
command << @code_instructions.comp(@c_instruction[1])
command << @code_instructions.dest(@c_instruction[0])
command << '000'
else instruction.include? ';'
@c_instruction = instruction.split(';')
command << @code_instruction.comp(@c_instruction[0])
command << '000'
command << @code_instruction.jump(@c_instruction[1])
end
end
def command_type(instruction)
if instruction.start_with?("@")
:a_command
else
:c_command
end
end
end |
#!/usr/bin/env ruby
require 'rpc_bench'
optobj = RPCBench::ClientOptions.new
begin
options = optobj.parse
rescue OptionParser::MissingArgument, OptionParser::InvalidOption => e
puts "[warning] failed to parse command line option (#{e})"
puts optobj.usage
exit 1
end
server = fork do
begin
RPCBench::Server.new(options).run
rescue Interrupt => e
# pass
end
end
# delay to setup server
sleep(0.5)
RPCBench::Client.new(options).run
Process.detach(server)
Process.kill(:INT, server)
|
require 'rails/generators'
module KepplerGaDashboard
module Tasks
class Install
class << self
def run
copy_initializer_file
puts "Done!"
end
def copy_initializer_file
print "Agregado archivo de configuración...\n"
app_path = Rails.root.join("config/initializers")
copier.copy_file File.join(gem_path, 'lib/templates/dashboard.rb'), File.join(app_path, 'dashboard.rb')
end
def copy_view
print "Vistas agregadas al proyecto...\n"
origin = File.join(gem_path, 'app/views')
destination = Rails.root.join('app/views')
copy_files(['.'], origin, destination)
end
private
def copy_files(directories, origin, destination)
directories.each do |directory|
Dir[File.join(origin, directory, 'keppler_ga_dashboard', '**/*')].each do |file|
relative = file.gsub(/^#{origin}\//, '')
dest_file = File.join(destination, relative)
dest_dir = File.dirname(dest_file)
if !File.exist?(dest_dir)
FileUtils.mkdir_p(dest_dir)
end
copier.copy_file(file, dest_file) unless File.directory?(file)
end
end
end
def gem_path
File.expand_path('../../..', File.dirname(__FILE__))
end
def copier
unless @copier
Rails::Generators::Base.source_root(gem_path)
@copier = Rails::Generators::Base.new
end
@copier
end
end
end
end
end |
# -*- encoding : utf-8 -*-
# Kontroler zdjęć
#
# Umożliwia pobieranie zdjęć zdekodowanych z formatu Base64.
#
class PhotosController < ApplicationController
skip_before_filter :require_login
layout false
# GET /photos/1
def show
photo = Photo.find(params[:id])
if !photo.nil? && !photo.photo.nil?
send_data Base64.decode64(photo.photo), :type => photo.mime_type, :disposition => 'inline'
end
end
end
|
# === COPYRIGHT:
# Copyright (c) Jason Adam Young
# === LICENSE:
# see LICENSE file
class DraftPlayer < ApplicationRecord
include CleanupTools
belongs_to :team, optional: true
belongs_to :original_team, :class_name => 'Team', optional: true
has_many :rosters
has_many :draft_rankings
has_one :draft_pick
has_many :draft_wanteds
has_many :wantedowners, :through => :draft_wanteds, :source => :owner
has_many :draft_owner_ranks
has_many :rankingowners, :through => :draft_owner_ranks, :source => :owner
# player types
PITCHER = 1
BATTER = 2
# positions
PITCHING_POSITIONS = ['sp','rp']
BATTING_POSITIONS = ['c','1b','2b','3b','ss','lf','cf','rf','dh']
# list filters
ALL_PLAYERS = 'all'
DRAFTED_PLAYERS = 'drafted'
NOTDRAFTED_PLAYERS = 'notdrafted'
ME_ME_ME = 'notdrafted+mine'
# new draftstatus
DRAFT_STATUS_NOTDRAFTED = 2
DRAFT_STATUS_DRAFTED = 3
DRAFT_STATUS_TEAMED = 4
paginates_per 50
scope :teamed, lambda { where(:draftstatus => DRAFT_STATUS_TEAMED) }
scope :notdrafted, lambda { where(:draftstatus => DRAFT_STATUS_NOTDRAFTED) }
scope :drafted, lambda { where(:draftstatus => DRAFT_STATUS_DRAFTED) }
scope :draft_eligible, lambda { where(["draftstatus IN (#{DRAFT_STATUS_DRAFTED}, #{DRAFT_STATUS_NOTDRAFTED})"]) }
scope :rostered, lambda { where(["draftstatus IN (#{DRAFT_STATUS_DRAFTED}, #{DRAFT_STATUS_TEAMED})"]) }
scope :not_injured, lambda { where("position != 'INJ'") }
scope :byteam, lambda {|team| where(team_id: team.id)}
scope :byposition, lambda {|position| where(position: position.downcase)}
def self.rebuild_from_statlines
self.dump_data
# Pitchers
DraftPitchingStatline.order('last_name,first_name asc').each do |pitcherstat|
pitcher = DraftPitcher.create(:first_name => pitcherstat.first_name,
:last_name => pitcherstat.last_name,
:position => pitcherstat.position,
:age => pitcherstat.age,
:statline_id => pitcherstat.id,
:team_id => pitcherstat.team_id,
:draftstatus => (pitcherstat.team_id == Team::NO_TEAM) ? DraftPlayer::DRAFT_STATUS_NOTDRAFTED : DraftPlayer::DRAFT_STATUS_TEAMED)
end
# Batters
DraftBattingStatline.order('last_name,first_name asc').each do |batterstat|
batter = DraftBatter.create(:first_name => batterstat.first_name,
:last_name => batterstat.last_name,
:position => batterstat.position,
:age => batterstat.age,
:statline_id => batterstat.id,
:team_id => batterstat.team_id,
:draftstatus => (batterstat.team_id == Team::NO_TEAM) ? DraftPlayer::DRAFT_STATUS_NOTDRAFTED : DraftPlayer::DRAFT_STATUS_TEAMED)
end
# rebuild rankings
DraftRankingValue.rebuild
end
def self.playerlist(owner:, draftstatus:, position:, owner_rank: false, ranking_values: [])
# sorting
if(ranking_values.length > 0)
if(owner_rank)
case position.downcase
when 'all'
query_column = 'overall'
when 'default'
query_column = 'overall'
when 'allbatters'
query_column = 'overall'
when 'allpitchers'
query_column = 'overall'
when 'of'
query_column = 'overall'
else
query_column = "pos_#{position.downcase}"
end
buildscope = self.select("#{self.table_name}.*, draft_rankings.value as rankvalue, draft_owner_ranks.#{query_column} as draft_owner_rankvalue")
buildscope = buildscope.includes(:team)
buildscope = buildscope.joins(:draft_rankings)
buildscope = buildscope.joins(:draft_owner_ranks)
buildscope = buildscope.where("draft_rankings.draft_ranking_value_id IN (#{ranking_values.map(&:id).join(',')})")
buildscope = buildscope.where("draft_owner_ranks.owner_id = #{owner.id}")
buildscope = buildscope.where("draft_owner_ranks.#{query_column} IS NOT NULL")
buildscope = buildscope.order("draft_owner_rankvalue ASC")
buildscope = buildscope.order("rankvalue DESC")
buildscope = buildscope.order("#{self.table_name}.id ASC")
else
buildscope = self.select("#{self.table_name}.*, draft_rankings.value as rankvalue")
buildscope = buildscope.includes(:team)
buildscope = buildscope.joins(:draft_rankings)
buildscope = buildscope.where("draft_rankings.draft_ranking_value_id IN (#{ranking_values.map(&:id).join(',')})")
buildscope = buildscope.order("rankvalue DESC")
buildscope = buildscope.order("#{self.table_name}.id ASC")
end
else
buildscope = self.includes(:team)
buildscope = buildscope.order("last_name ASC")
end
pitching_positions = PITCHING_POSITIONS
batting_positions = BATTING_POSITIONS
case position.downcase
when *pitching_positions
buildscope = buildscope.where("(#{self.table_name}.position = '#{position}')")
buildscope = buildscope.includes(:statline)
when *batting_positions
if(position.downcase == 'dh')
buildscope = buildscope.where("(#{self.table_name}.position = '#{position}')")
buildscope = buildscope.includes(:statline)
else
ratingfield = DraftBattingStatline::RATINGFIELDS[position.downcase]
buildscope = buildscope.joins(:statline)
buildscope = buildscope.where("(draft_players.position = '#{position}' or draft_batting_statlines.#{ratingfield} != '')")
end
when 'of'
buildscope = buildscope.joins(:statline)
buildscope = buildscope.where("(draft_players.position IN ('cf','lf','rf') or draft_batting_statlines.pos_cf != '' or draft_batting_statlines.pos_lf != '' or draft_batting_statlines.pos_rf != '')")
else
buildscope = buildscope.includes(:statline)
end
case draftstatus
when DRAFTED_PLAYERS
buildscope = buildscope.where("#{self.table_name}.team_id != 0")
when NOTDRAFTED_PLAYERS
buildscope = buildscope.where("#{self.table_name}.team_id = 0")
when ME_ME_ME
filter_team = owner.team
buildscope = buildscope.where("#{self.table_name}.team_id = 0 or #{self.table_name}.team_id = #{filter_team.id}")
end
buildscope
end
def self.positionlabel(position)
downcased = position.downcase
case downcased
when 'all'
'All Players'
when 'allbatters'
'All Batters'
when 'allpitchers'
'All Pitchers'
when 'of'
'All Outfielders'
else
if(DraftPitcher::POSITIONS[downcased])
DraftPitcher::POSITIONS[downcased]
elsif(DraftBatter::POSITIONS[downcased])
DraftBatter::POSITIONS[downcased]
else
'Unknown'
end
end
end
def fullname
"#{self.first_name} #{self.last_name}"
end
def initials
"#{self.first_name.first}#{self.last_name.first}"
end
def teamed?
return (self.team_id != Team::NO_TEAM)
end
def drafted?
return (!self.draft_pick.nil?)
end
def releaseplayer
current_team_id = self.team_id
self.update({:team_id => Team::NO_TEAM, :draftstatus => DRAFT_STATUS_NOTDRAFTED, :original_team_id => current_team_id})
end
def returntodraft
return if(self.draftstatus != DRAFT_STATUS_DRAFTED)
if(!self.draft_pick.nil?)
dp = DraftPick.where(draft_player_id: self.id).first
dp.update({:draft_player_id => DraftPick::NOPICK})
end
current_team = self.team
self.update({:team_id => Team::NO_TEAM, :draftstatus => DRAFT_STATUS_NOTDRAFTED})
end
def draftplayer(options = {})
pick = options[:draftpick] || DraftPick::CURRENTPICK
team = options[:team] || nil
return if(self.draftstatus != DRAFT_STATUS_NOTDRAFTED)
pick = pick.to_i
if(pick == DraftPick::CURRENTPICK)
pick = DraftPick.current_pick
end
if(team.nil?)
team = Team.find_by_draftpick(pick)
end
if(team)
self.update({:team_id => team.id, :draftstatus => DRAFT_STATUS_DRAFTED})
pick.update({:draft_player_id => self.id, :team_id => team.id})
end
end
def positions
if(self.class.name == 'Pitcher')
return [self.position.downcase]
else
mystatline = self.statline
returnpositions = []
DraftBattingStatline::RATINGFIELDS.each do |pos,field|
if(!mystatline.send(field).blank?)
returnpositions << pos
end
end
return returnpositions
end
end
def self.searchplayers(searchterm)
if searchterm.nil?
return nil
end
# remove any leading * to avoid borking mysql
# remove any '\' characters because it's WAAAAY too close to the return key
searchterm = searchterm.gsub(/\\/,'').gsub(/^\*/,'$').strip
# in the format wordone wordtwo?
words = searchterm.split(%r{\s*,\s*|\s+})
if(words.length > 1)
findvalues = {
:firstword => words[0],
:secondword => words[1]
}
conditions = ["((first_name ~* :firstword AND last_name ~* :secondword) OR (first_name ~* :secondword AND last_name ~* :firstword))",findvalues]
else
findvalues = {
:findfirst => searchterm,
:findlast => searchterm
}
conditions = ["(first_name ~* :findfirst OR last_name ~* :findlast)",findvalues]
end
where(conditions)
end
def self.rankingvalues(ranking_value)
self.byrankingvalue(ranking_value).map(&:rankvalue).map{|rv|rv*100}
end
def scaled_stats_by_rankingvalue(ranking_value)
stats = {}
playertype = (self.class == DraftPitcher) ? Stat::PITCHER : Stat::BATTER
ranking_value.formula.each do |factor|
column = factor[:column]
stat = DraftStatDistribution.find_or_create(playertype,column)
stats[column] = {}
stats[column][:mine] = stat.scaled_distribution[:players][self.id] ? stat.scaled_distribution[:players][self.id] : 0
stats[column][:max] = stat.scaled_distribution[:values].max
stats[column][:min] = stat.scaled_distribution[:values].min
end
stats
end
def owner_rank_or_blank(owner)
if(!@dor or (@dor.owner != owner))
if(!(@dor = self.draft_owner_ranks.where(owner: owner).first))
@dor = self.draft_owner_ranks.new(owner: owner)
end
end
@dor
end
def owner_rankvalue_for_position(owner,position)
dor = owner_rank_or_blank(owner)
if(position == 'overall')
dor.overall || 0
else
position_attribute = "pos_#{position}"
dor.send(position_attribute) || 0
end
end
def wanted_by_owner(owner)
draft_wanteds.where(owner: owner).first
end
end
|
module Karafka
# Namespace for all elements related to requests routing
module Routing
# Karafka framework Router for routing incoming messages to proper controllers
class Router
# @param message [Karafka::Connection::Message] single incoming message
# @return [Karafka::Router] router instance
def initialize(message)
@message = message
end
# @raise [Karafka::Topic::NonMatchingTopicError] raised if topic name is not match any
# topic of descendants of Karafka::BaseController
# Forwards message to controller inherited from Karafka::BaseController based on it's topic
# and run it
def build
descendant = Karafka::Routing::Mapper.by_topics[@message.topic.to_sym]
fail Errors::NonMatchingTopicError, @message.topic unless descendant
controller = descendant.new
controller.params = @message
controller
end
end
end
end
|
module XcodeInstall
class Command
class Installed < Command
self.command = 'installed'
self.summary = 'List installed Xcodes.'
def run
installer = XcodeInstall::Installer.new
installer.installed_versions.each do |xcode|
puts "#{xcode.version}\t(#{xcode.path})"
end
end
end
end
end
|
Capistrano::Configuration.instance(true).load do
namespace :nginx do
desc 'Uploads main nginx config for use within cdb-context'
task :config, :roles => :app do
file_path = File.expand_path('../configs/nginx.conf.erb', File.dirname(__FILE__))
template = File.read(file_path)
erb = ERB.new( template, 0, '-' )
put( erb.result( binding ), "#{release_path}/config/nginx.conf" )
end
desc 'Uploads nginx location/upstream configs if exist for inclusion in main nginx config'
task :includes, :roles => :app do
Dir["config/nginx/**/*.erb"].each do |config|
template = File.read(config)
erb = ERB.new( template, 0, '-' )
result_path = config.chomp(".erb")
put( erb.result( binding ), "#{release_path}/#{result_path}")
end
end
end
after 'deploy:update', 'nginx:config'
after 'deploy:update', 'nginx:includes'
end
|
require 'rails_helper'
RSpec.describe Cart, type: :model do
it 'can be created' do
user = User.create(
username: 'testtest',
email: 'test@example.com',
password: 'password123',
password_confirmation: 'password123'
)
cart = Cart.new(
user: user,
).save
expect(cart).to eq(true)
end
it 'cannot be without user' do
cart = Cart.new(
).save
expect(cart).to eq(false)
end
end
|
require 'test_helper'
class ProblemTypes::SearchControllerTest < AuthenticatingControllerTestCase
# Replace this with your real tests.
setup do
@problem_type = Factory.build(:problem_type)
@valid_search_hash = {'search' => {'query' => "for something"}}
end
test "index without current_lesson set in session returns simple problem type search" do
get :new
assert_response :success
assert assigns(:subjects)
assert assigns(:tags)
assert_problem_type_search_displayed_in_view
assert_current_asset_display_in_view false
end
test "new search displays current lesson when valid current_lesson_id is set in session" do
lesson = Factory.build(:lesson, :id => 234234)
Lesson.expects(:find).with(anything).returns(lesson)
session['current_lesson_id'] = lesson.id
get :new
assert_response :success
assert_equal lesson, assigns(:current_asset), "Current lesson not found as expected"
assert_current_asset_display_in_view
assert_problem_type_search_displayed_in_view
end
test "new search displays simple problem type search when invalid current_lesson_id is set in session" do
get_new_search_with_invalid_current_lesson_id_in_session!
assert_response :success
assert_problem_type_search_displayed_in_view
assert_current_asset_display_in_view false
end
test "no errors in new search when current_lesson_id is invalid" do
assert_nothing_raised do
get_new_search_with_invalid_current_lesson_id_in_session!
end
end
test "new search clears current_lesson_id in session when the id is invalid" do
get_new_search_with_invalid_current_lesson_id_in_session!
assert_nil session[:current_lesson_id]
end
test "show search results" do
get :show, :search => {:query => "Monomial Fraction"}
assert_response :success
assert assigns(:problem_types).include?(problem_types(:dividing_monomials_problem_type))
end
test "show search results displays current lesson when valid current_lesson_id is set in session" do
lesson = Factory.build(:lesson, :id => 234234)
Lesson.expects(:find).with(anything).returns(lesson)
ProblemType.expects(:search).with(anything).returns([@problem_type])
session['current_lesson_id'] = lesson.id
get :show, {:search => "Monomial Fraction"}
assert_response :success
assert_equal lesson, assigns(:current_asset), "Current lesson not found as expected"
assert_current_asset_display_in_view
assert assigns(:problem_types).include?(@problem_type)
end
test "show search results displays simple problem type search when invalid current_lesson_id is set in session" do
ProblemType.expects(:search).with(anything).returns([@problem_type])
get_search_results_with_invalid_current_lesson_id_in_session!
assert_response :success
assert_current_asset_display_in_view false
assert assigns(:problem_types).include?(@problem_type)
end
test "no errors in show search results when current_lesson_id is invalid" do
assert_nothing_raised do
get_search_results_with_invalid_current_lesson_id_in_session!
end
end
test "show search results clears current_lesson_id in session when said id is invalid" do
get_new_search_with_invalid_current_lesson_id_in_session!
assert_nil session[:current_lesson_id]
end
test "show search results clears lesson and worksheet asset ids if both are specified in incoming session" do
session['current_lesson_id'] = 234234
session['current_worksheet_id'] = 453453
get :new, @valid_search_hash
assert_response :success
assert_nil session[:current_lesson_id], "Expected current_lesson_id to be nil in session"
assert_nil session[:current_worksheet_id], "Expected current_worksheet_id to be nil in session"
end
test "show search results displays error message when two current assets set in session" do
session['current_lesson_id'] = 234234
session['current_worksheet_id'] = 453453
get :new, @valid_search_hash
assert_error_message RightRabbitErrors::DEFAULT
end
test "search with no quotes triggers title search" do
query = " this is a tittle"
ProblemType.expects(:title_search).with(query).returns(types_from_search)
get :show, {'search' => {'query' => query}}
end
test "search with quotes triggers tag search" do
query = "\"tag 1\", \"tag 2\""
ProblemType.expects(:tagged_with).with(['tag 1', 'tag 2']).returns(types_from_search)
get :show, {'search' => {'query' => query}}
end
private
def types_from_search
types = []
2.times { types << Factory.build(:problem_type) }
types
end
def get_new_search_with_invalid_current_lesson_id_in_session!
invalid_id = 234234
Lesson.expects(:find).with(invalid_id).raises(ActiveRecord::RecordNotFound)
session['current_lesson_id'] = invalid_id
get :new, @valid_search_hash
end
def get_search_results_with_invalid_current_lesson_id_in_session!
invalid_id = 234234
Lesson.expects(:find).with(invalid_id).raises(ActiveRecord::RecordNotFound)
session['current_lesson_id'] = invalid_id
get :show, @valid_search_hash
end
end
|
require 'line/bot'
class LineBotClient
def self.generate
Line::Bot::Client.new do |config|
config.channel_secret = ENV["LINE_CHANNEL_SECRET"]
config.channel_token = ENV["LINE_CHANNEL_TOKEN"]
end
end
end
|
require 'bigdecimal'
class BigDecimal
# Floating-point numbers that go through the 'json' Logstash filter get automatically converted into BigDecimals.
# Example of such a filter:
#
# filter {
# json {
# source => "message"
# }
# }
#
# The problem is that { "value" => BigDecimal('0.12345') } gets serialized into { "value": "0.12345e0"}. We do
# want to keep floating point numbers serialized as floating point numbers, even at the expense of loosing a little
# bit of precision during the conversion. So, in the above example, the correct serialization would be:
# { "value": 0.12345}
def to_json(options = nil) #:nodoc:
if finite?
self.to_f.to_s
else
'null'
end
end
end |
require_dependency "administration/application_controller"
module Administration
class BlogCommentsController < ApplicationController
skip_before_filter :authenticate_admin!, only: [:create]
def create
@blog = Blog.find(params[:blog_id])
if admin_signed_in? && !user_signed_in?
params[:blog_comment][:author] = current_admin.id
params[:blog_comment][:admin] = true
else
params[:blog_comment][:author] = current_user.id
params[:blog_comment][:admin] = false
end
comment = @blog.blog_comments.create!(comment_params)
redirect_to @blog
end
def destroy
end
private
def comment_params
allow = [:content, :admin, :author]
params.require(:blog_comment).permit(allow)
end
end
end
|
module Tarot
module UseCases
class UseCase
include Support::ValidationHelpers
def card_factory
@card_factory ||= Services::CardFactory.new
end
end
end
end
|
module EventAgent
attr_accessor :event_inbox
def new_event_inbox
@event_inbox = []
end
def init_event_agent
new_event_inbox
end
module Publisher
def notify(payload)
EventBus.receive(
Event.new(message = payload, publisher = self)
)
true
end
def make_subscribable
publisher_exists = EventBus.subscriptions.find{ |subscription| subscription[:publisher] == self}
if publisher_exists
puts "You're already listed as a publisher"
nil
else
EventBus.subscriptions.push( {publisher: self, subscribers: []} )
true
end
end
end
module Subscriber
def subscribe(publisher)
publisher = EventBus.subscriptions.find { |subscription| subscription[:publisher] == publisher}
if !publisher
puts "Not listed for subscription."
false
elsif publisher == self
puts "Cannot subscribe to yourself"
false
elsif publisher[:subscribers].include?(self)
puts "Already subcribed to this publisher"
elsif publisher != self
publisher[:subscribers].push(self)
puts "Now subcribed to Event Agent ##{publisher}"
true
end
end
def unsubscribe(publisher)
publisher = EventBus.subscriptions.find { |subscriptions| subscriptions[:id] == publisher}
publisher[:subscribers].delete(self)
puts "Unsubscribed"
true
end
end
include Publisher
include Subscriber
end
|
INITIAL_MARKER = ' '
PLAYER_MARKER = 'X'
COMPUTER_MARKER = 'O'
def prompt(msg)
puts "=> #{msg}"
end
def display_board(brd)
system 'clear'
puts "You are #{PLAYER_MARKER}. Computer is #{COMPUTER_MARKER}"
puts "|-----+-----+-----|"
puts "| | | |"
puts "| #{brd[1]} | #{brd[2]} | #{brd[3]} |"
puts "| | | |"
puts "|-----+-----+-----|"
puts "| | | |"
puts "| #{brd[4]} | #{brd[5]} | #{brd[6]} |"
puts "| | | |"
puts "|-----+-----+-----|"
puts "| | | |"
puts "| #{brd[7]} | #{brd[8]} | #{brd[9]} |"
puts "| | | |"
puts "|-----+-----+-----|"
end
# you can choose what data structure to use, but hash is good as the key represents the square in the box, and value represents
# the symbol (X or O)
def initialize_board
new_board = {}
(1..9).each { |num| new_board[num] = INITIAL_MARKER }
new_board # so this contains a hash like {1 => ' ', 2 => ' ', 3 => ' ', etc.}
end
def empty_squares(brd) # this will only inspect not mutate, unlike the method 'player_places_piece!'
# this will simply return an array of integers that have empty value.
brd.keys.select { |num| brd[num] == INITIAL_MARKER }
end
def player_places_piece!(brd) # this will mutate, so notice the !. this is pass by reference
square = ''
loop do
prompt "Choose a square #{empty_squares(brd).join(' ')}:"
square = gets.chomp.to_i
break if empty_squares(brd).include?(square)
prompt("Invalid choice")
end
brd[square] = PLAYER_MARKER # this sets the square in the box to be X. Remember its a hash. this mutates line 40 argument
end
def computer_places_piece!(brd)
square = empty_squares(brd).sample
brd[square] = COMPUTER_MARKER
end
def board_full?(brd)
empty_squares(brd).empty?
end
def someone_won?(brd)
!!detect_winner(brd)
end
def detect_winner(brd)
winning_lines = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + # rows
[[2, 5, 8], [1, 4, 7], [3, 6, 9]] + # columns
[[1, 5, 9], [3, 5, 7]] # diagonals
winning_lines.each do |line|
if brd[line[0]] == PLAYER_MARKER &&
brd[line[1]] == PLAYER_MARKER &&
brd[line[2]] == PLAYER_MARKER
return 'Player'
elsif brd[line[0]] == COMPUTER_MARKER &&
brd[line[1]] == COMPUTER_MARKER &&
brd[line[2]] == COMPUTER_MARKER
return 'Computer'
end
end
nil
end
loop do
# now board has the return value of the method 'initialize_board'
board = initialize_board
loop do
# then you can pass board into the method 'display board'
display_board(board)
player_places_piece!(board)
break if someone_won?(board) || board_full?(board)
computer_places_piece!(board)
break if someone_won?(board) || board_full?(board)
end
display_board(board)
if someone_won?(board)
prompt("#{detect_winner(board)} won!")
else
prompt("Its a tie")
end
prompt("Play again? Y or N")
answer = gets.chomp.downcase
break if answer == "n"
end
prompt("Thanks for playing")
|
class CreateMaterials < ActiveRecord::Migration
def change
create_table :materials do |t|
t.string :name
t.string :type
t.string :model
t.decimal :count
t.decimal :price
t.date :stockdate
t.string :recorder
t.string :remark
t.timestamps
end
end
end
|
require 'ffwd/plugin/kairosdb/utils'
describe FFWD::Plugin::KairosDB::Utils do
describe "#safe_string" do
it "should escape unsafe characters" do
expect(described_class.safe_string("foo bar")).to eq("foo/bar")
expect(described_class.safe_string("foo:bar")).to eq("foo_bar")
end
end
describe "#make_tags" do
it "should build safe tags" do
tags = {:foo => "bar/baz"}
ref = {"host"=>"host", "foo"=>"bar/baz"}
expect(described_class.safe_tags(:host, tags)).to eq(ref)
end
end
describe "#safe_entry" do
it "should escape parts of entries" do
entry = {:name => :name, :host => :host, :attributes => {:foo => "bar/baz"}}
ref = {:name=>"name", :tags=>{"host"=>"host", "foo"=>"bar/baz"}}
expect(described_class.safe_entry(entry)).to eq(ref)
end
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Specify Vagrant version and Vagrant API version
Vagrant.require_version ">= 1.6.0"
VAGRANTFILE_API_VERSION = "2"
# Specify default provider (uncomment the provider you want to use)
#ENV['VAGRANT_DEFAULT_PROVIDER'] = 'virtualbox'
ENV['VAGRANT_DEFAULT_PROVIDER'] = 'vmware_fusion'
#ENV['VAGRANT_DEFAULT_PROVIDER'] = 'vmware_workstation'
# Specify clone directory for VMware provider (to enable exclusion
# from Time Machine backups)
# Comment this out if not using the VMware provider
# Set the desired location if using the VMware provider
ENV['VAGRANT_VMWARE_CLONE_DIRECTORY'] = '~/.vagrant'
# Require 'yaml' module
require 'yaml'
# Read YAML file with VM details (box, CPU, RAM, IP addresses)
# Be sure to edit servers.yml to provide correct IP addresses
servers = YAML.load_file(File.join(File.dirname(__FILE__), 'servers.yml'))
# Create and configure the VMs
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
# Always use Vagrant's default insecure key
config.ssh.insert_key = false
# Iterate through entries in YAML file to create VMs
servers.each do |servers|
config.vm.define servers["name"] do |srv|
# Don't check for box updates
srv.vm.box_check_update = false
# Set VM hostname
srv.vm.hostname = servers["name"]
# Set box to be used by this VM
srv.vm.box = servers["box"]
# Configure VM networking
# Assign an additional static private network for management
srv.vm.network "private_network", ip: servers["mgmt"]
# Add additional interfaces if IP addresses are provided in servers.yml
if servers["tunnel"] != "0.0.0.0"
srv.vm.network "private_network", ip: servers["tunnel"]
end # test for tunnel interface
if servers["storage"] != "0.0.0.0"
srv.vm.network "private_network", ip: servers["storage"]
end # test for storage interface
if servers["external"] != "0.0.0.0"
srv.vm.network "private_network", ip: servers["external"]
end # test for external interface
# Disable default synced folder
srv.vm.synced_folder ".", "/vagrant", disabled: true
# Configure VMs with RAM and CPUs per settings in servers.yml
# First for Fusion-based VMs
srv.vm.provider :vmware_fusion do |vmw|
vmw.vmx["memsize"] = servers["ram"]
end # srv.vm.provider vmware_fusion
# Next for Workstation-based VMs
srv.vm.provider :vmware_workstation do |vmw|
vmw.vmx["memsize"] = servers["ram"]
end # srv.vm.provider vmware_workstation
# Finally for VirtualBox-based VMs
srv.vm.provider :virtualbox do |vb|
vb.customize ["modifyvm", :id, "--memory", servers["ram"]]
end # srv.vm.provider virtualbox
# If this is the compute node and you are using the VMware provider,
# enable nested virtualization
if servers["name"] == "compute-01"
srv.vm.provider :vmware_fusion do |vmw|
vmw.vmx["vhv.enable"] = "TRUE"
end # srv.vm.provider vmware_fusion
srv.vm.provider :vmware_workstation do |vmw|
vmw.vmx["vhv.enable"] = "TRUE"
end # srv.vm.provider vmware_workstation
end # test for compute node
end # config.vm.define
end # servers.each
end # vagrant.configure |
def bubble_sort(array)
n = array.length
loop do
swapped = false
(n - 1).times do |i|
if array[i] > array[i + 1]
array[i], array[i + 1] = array[i + 1], array[i]
swapped = true
end
end
break unless swapped
end
array
end
if $0 == __FILE__
puts 'Enter a list of numbers separated by space'
list = gets
bubble_sort(list)
print list
end
|
class SearchesController < ApplicationController
# GET /searches
# GET /searches.json
def index
@twitter_users = Array.new
@facebook_pages = Array.new
if !params[:keyword].blank?
Twitter.configure do |config|
config.consumer_key = ENV['TWITTER_CONSUMER_KEY']
config.consumer_secret = ENV['TWITTER_CONSUMER_SECRET']
config.oauth_token = ENV['TWITTER_OAUTH_TOKEN']
config.oauth_token_secret = ENV['TWITTER_OAUTH_TOKEN_SECRET']
end
@twitter_users = Twitter.user_search params[:keyword]
graph = Koala::Facebook::GraphAPI.new(ENV['FACEBOOK_OAUTH_TOKEN'])
graph.get_connections("search", '', :type => 'page', :q => params[:keyword] ).each do |page|
@facebook_pages.push page
end
end
respond_to do |format|
format.html # index.html.erb
end
end
end
|
json.array!(@nuclear_codes) do |nuclear_code|
json.extract! nuclear_code, :id
json.url nuclear_code_url(nuclear_code, format: :json)
end
|
module MongoDoc
module Index
DIRECTION = { :asc => Mongo::ASCENDING,
:desc => Mongo::DESCENDING,
:geo2d => Mongo::GEO2D }
OPTIONS = [:min, :max, :background, :unique, :dropDups]
# Create an index on a collection.
#
# For compound indexes, pass pairs of fields and
# directions (+:asc+, +:desc+) as a hash.
#
# For a unique index, pass the option +:unique => true+.
# To create the index in the background, pass the options +:background => true+.
# If you want to remove duplicates from existing records when creating the
# unique index, pass the option +:dropDups => true+
#
# For GeoIndexing, specify the minimum and maximum longitude and latitude
# values with the +:min+ and +:max+ options.
#
# <tt>Person.index(:last_name)</tt>
# <tt>Person.index(:ssn, :unique => true)</tt>
# <tt>Person.index(:first_name => :asc, :last_name => :asc)</tt>
# <tt>Person.index(:first_name => :asc, :last_name => :asc, :unique => true)</tt>
def index(*args)
options_and_fields = args.extract_options!
if args.any?
collection.create_index(args.first, options_and_fields)
else
fields = options_and_fields.except(*OPTIONS)
options = options_and_fields.slice(*OPTIONS)
collection.create_index(to_mongo_direction(fields), options)
end
end
protected
def to_mongo_direction(fields_hash)
fields_hash.to_a.map {|field| [field.first, direction(field.last)]}
end
def direction(dir)
DIRECTION[dir] || Mongo::ASCENDING
end
end
end
|
class RegistrationsController < Devise::RegistrationsController
def change_password
@user = current_user
if @user
render :change_password
else
render file: 'public/404', status: 404
end
end
def cancel_account
end
def update
self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key)
prev_unconfirmed_email = resource.unconfirmed_email if resource.respond_to?(:unconfirmed_email)
resource_updated = update_resource(resource, account_update_params)
yield resource if block_given?
if resource_updated
set_flash_message_for_update(resource, prev_unconfirmed_email)
bypass_sign_in resource, scope: resource_name if sign_in_after_change_password?
respond_with resource, location: after_update_path_for(resource)
else
clean_up_passwords resource
set_minimum_password_length
unless request.referer.include? user_change_password_path
respond_with resource
else
flash[:errors] = resource.errors
redirect_to user_change_password_path
end
end
end
private
def sign_up_params
params.require(:user).permit( :name,
:phone,
:email,
:password,
:password_confirmation)
end
def account_update_params
params.require(:user).permit( :name,
:phone,
:avatar,
:email,
:password,
:password_confirmation,
:current_password)
end
end |
line1=Настраиваемые параметры,11
default_mode=Способ вывода списка процессов по умолчанию,4,last-Последний выбранный,tree-Дерево процессов,user-Упорядочивать по именам пользователей,size-Упорядочивать по размеру,cpu-Упорядочивать по CPU,search-Страница поиска,run-Страница выполнения
cut_length=Максимальная длина команд,3,Не ограничена
trace_java=Показывать трассировку системных вызовов используя,1,1-Java-апплет,0-Текст
line2=Системные параметры,11
ps_style=Стиль вывода команды PS,1,sysv-SYSV,linux-Linux,hpux-HPUX,freebsd-FreeBSD,macos-MacOS,openbsd-OpenBSD
|
require 'spec_helper'
feature 'Signup' do
let!(:host) { FactoryGirl.create :host }
context 'on landing page' do
it "can create account with valid input" do
visit root_path
expect {
fill_in 'host_email', with: "blank@blank.com"
fill_in 'host_password', with: "password123"
click_button "Create Account"
}.to change(Host, :count).by(1)
end
it "redirects to root page if incorrect sign up email info is passed" do
visit root_path
fill_in 'host_email', with: ""
fill_in 'host_password', with: "testing"
click_button "Create Account"
expect(page).to have_content("Email is invalid")
end
it "redirects to root page if incorrect sign up email info is passed" do
visit root_path
fill_in 'host_email', with: "logan@gmail.com"
fill_in 'host_password', with: "test"
click_button "Create Account"
expect(page).to have_content("Password is too short")
end
end
describe 'Sign out' do
before(:each) do
web_login host
end
context 'events page' do
it "can log user out" do
click_link "Logout"
uri = URI.parse(current_url)
"#{uri.path}#{uri.query}".should == root_path
end
end
end
describe 'log in' do
context 'on landing page' do
it "can log in with valid input (testing url)" do
current_host = Host.create name: 'guy', password: "password123", email: "a@b.com"
web_login current_host
uri = URI.parse(current_url)
"#{uri.path}#{uri.query}".should == host_events_path(current_host)
end
it "can't log in with invalid input (testing url)" do
current_host = Host.create name: 'guy', password: "password123", email: "a@b.com"
visit root_path
fill_in 'login_email', with: "a@b.com"
fill_in 'login_password', with: "wefwefwefwef"
click_button "Log in"
uri = URI.parse(current_url)
"#{uri.path}#{uri.query}".should == root_path
end
end
end
end |
module Annotable
Fabricator(:user, from: User) do
name { user_attributes[:name] }
email { user_attributes[:email] }
organization
end
end
|
require File.dirname(__FILE__) + '/../test_helper'
class TestLineStyle < Test::Unit::TestCase
def setup
@klass = Class.new(MockChart).class_eval { include GoogleChart::LineStyle }
end
should 'not include line styles by default' do
assert_no_match(/\bchls=/, @klass.new.to_url)
end
should 'support solid lines' do
assert_match(/\bchls=1,1,0\b/, @klass.new(:style => :solid).to_url)
end
should 'support dashed lines' do
assert_match(/\bchls=1,3,2\b/, @klass.new(:style => :dash).to_url)
end
should 'support dotted lines' do
assert_match(/\bchls=1,1,2\b/, @klass.new(:style => :dot).to_url)
end
should 'support multiple line styles' do
assert_match(/\bchls=1,3,2\|1,1,2\|1,1,0\b/, @klass.new(:style => [:dash, :dot, :solid]).to_url)
end
should 'support custom line width' do
assert_match(/\bchls=2,2,0\b/, @klass.new(:width => 2).to_url)
end
should 'support named line style with custom width' do
assert_match(/\bchls=2,6,4\b/, @klass.new(:style => :dash, :width => 2).to_url)
end
should 'support multiple line styles and multiple custom widths' do
assert_match(/\bchls=2,2,4\|3,9,6\b/, @klass.new(:style => [:dot, :dash], :width => [2, 3]).to_url)
end
should 'use default line width if there are more styles than widths' do
assert_match(/\bchls=2,2,4\|1,3,2\|1,1,0\b/, @klass.new(:style => [:dot, :dash, :solid], :width => 2).to_url)
end
should 'use default line style if there are more widths than styles' do
assert_match(/\bchls=2,2,4\|3,3,0\|2,2,0\b/, @klass.new(:style => :dot, :width => [2, 3, 2]).to_url)
end
end
|
require File.expand_path(File.join(File.dirname(__FILE__), *%w[.. .. spec_helper]))
describe '/instances/summary' do
before :each do
@instance = Instance.generate!(:description => 'Test Instance')
end
def do_render
render :partial => '/instances/summary', :locals => { :instance => @instance }
end
it 'should display the name of the instance' do
do_render
response.should have_text(Regexp.new(@instance.name))
end
it 'should link the instance name to the instance show page' do
do_render
response.should have_tag('a[href=?]', instance_path(@instance), :text => @instance.name)
end
it 'should display the description of the instance' do
do_render
response.should have_text(Regexp.new(@instance.description))
end
it 'should show deployment hosts' do
deployable = Deployable.generate!(:instance => @instance)
deployment = Deployment.generate!(:deployable => deployable)
deployed_service = DeployedService.generate!(:deployment => deployment)
do_render
response.should have_text(Regexp.new(deployed_service.host.name))
end
end
|
class UpdateBookedItemSerialType < ActiveRecord::Migration
def change
change_column :booked_items, :serial_number, :text
end
end
|
require 'test_helper'
class StripeCacheTest < ActiveSupport::TestCase
setup do
Rails.cache.clear
@stripe_helper = StripeMock.create_test_helper
StripeMock.start
@stripe_helper.create_plan(id: 'basic', amount: 100)
customer = Stripe::Customer.create(source: @stripe_helper.generate_card_token)
subscription = Stripe::Subscription.create(customer: customer, plan: 'basic')
@user = users(:garrett)
@user.update(stripe_customer_id: customer.id, stripe_subscription_id: subscription.id)
@stripe_cache = StripeCache.new(@user)
end
test '#refresh' do
assert_nil(Rails.cache.fetch(@stripe_cache.send(:cache_key, 'customer')))
assert_nil(Rails.cache.fetch(@stripe_cache.send(:cache_key, 'subscription')))
@stripe_cache.refresh
cached_customer = Rails.cache.fetch(@stripe_cache.send(:cache_key, 'customer'))
cached_subscription = Rails.cache.fetch(@stripe_cache.send(:cache_key, 'subscription'))
refute_nil(cached_subscription)
refute_nil(cached_customer)
end
test '#customer' do
assert_nil(Rails.cache.fetch(@stripe_cache.send(:cache_key, 'customer')))
customer = @stripe_cache.customer
assert_equal(customer, Rails.cache.fetch(@stripe_cache.send(:cache_key, 'customer')))
end
test '#subscription' do
assert_nil(Rails.cache.fetch(@stripe_cache.send(:cache_key, 'subscription')))
subscription = @stripe_cache.subscription
cached_subscription = Rails.cache.fetch(@stripe_cache.send(:cache_key, 'subscription'))
refute_nil(cached_subscription)
assert_equal(subscription, cached_subscription)
end
end
|
class WelcomeController < ApplicationController
def index
if user_signed_in?
if current_user.orders.count > 0
redirect_to controller: 'profiles', action: 'orders'
else
redirect_to controller: 'profiles', action: 'edit'
end
else
render layout: false
end
end
end
|
Rails.application.routes.draw do
root('orders#index')
resources(:orders)
end
|
require_relative 'user'
STATUS_OPTIONS = [:AVAILABLE, :UNAVAILABLE]
DRIVERS_CUT = 0.8
FEE = 1.65
module RideShare
class Driver < RideShare::User
attr_reader :vehicle_id, :driven_trips, :status
def initialize(input)
super(input)
@vehicle_id = input[:vin]
@driven_trips = input[:driven_trips].nil? ? [] : input[:driven_trips]
@status = input[:status].nil? ? :AVAILABLE : input[:status]
raise ArgumentError.new("That is an invalid status") unless STATUS_OPTIONS.include?(@status)
raise ArgumentError.new("That is an invalid VIN") unless @vehicle_id.length == 17
end
def add_driven_trip(trip)
raise ArgumentError unless trip.is_a? Trip
@driven_trips << trip
end
def average_rating
trip_ratings = []
@driven_trips.each do |trip|
trip_ratings << trip.rating
end
trip_ratings.length == 0 ? 0 : (trip_ratings.sum / trip_ratings.length).to_f
end
def total_revenue
total_revenue = 0
@driven_trips.each do |trip|
total_revenue += (DRIVERS_CUT * (trip.cost - FEE))
end
return total_revenue.round(2)
end
def net_expenditures
return (super - total_revenue).round(2)
end
def becomes_unavailable
@status = :UNAVAILABLE
end
end
end
|
class ChangeLocationDataType < ActiveRecord::Migration
def change
change_column :lsspdfassets, :u_location_desc, :text
end
end
|
require 'angularize_rails_validations/ng_validator'
module Ng
class MaxLengthValidator < Validator
attr_reader :maximum
def initialize(am_validator)
raise StandardError.new 'am_validator must be an ActiveModel::Validations::LengthValidator' unless am_validator.is_a? ActiveModel::Validations::LengthValidator
raise StandardError.new 'am_validator must have a maximum length option' unless am_validator.options[:maximum]
@maximum = am_validator.options[:maximum]
super
@input_attribute = "ng-maxlength=\"#{@maximum}\""
@ng_show_attribute = "maxlength"
end
private
def default_message
"may contain at most #{@maximum} characters"
end
end
end
|
class CharityController < ApplicationController
get '/charities' do
@charities = Charity.all
erb :'/charity/charities'
end
get '/charities/new' do
authenticator
erb :'/charity/new'
end
get '/charities/:id' do
@charity = Charity.find_by_id(params[:id])
erb :'charity/show'
end
get '/charities/:id/edit' do
authenticator
@charity = Charity.find_by_id(params[:id])
authorize(@charity)
erb :'charity/edit'
end
get '/charities/:id/delete' do
@charity = Charity.find_by_id(params[:id])
authenticator
authorize(@charity)
erb :'/charity/delete'
end
post '/charities' do
if logged_in?
if params[:name] != "" && params[:description] != ""
@charity = Charity.create(params)
@charity.user_id = current_user.id
current_user.charities << @charity
current_user.save
redirect to '/charities'
else
redirect to '/charities/new'
end
else
redirect to '/login'
end
end
patch '/charities/:id' do
@charity = Charity.find_by_id(params[:id])
if logged_in? && @charity.user_id == current_user.id
if params[:name] != nil && params[:description] != nil
@charity.update(name: params[:name], description: params[:description])
@charity.save
redirect to '/charities'
else
redirect to '/charities/:id/edit'
end
else
redirect to '/login'
end
end
delete '/charities/:id/delete' do
@charity = Charity.find_by_id(params[:id])
@charity.destroy
redirect to '/charities'
end
end |
class Post < ActiveRecord::Base
validates :image, presence: true
# Post processing
has_attached_file :image, styles: { :square=> "500x500!" }
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
end |
guard 'livereload' do
watch %r{^.*\.(html|css|js|png|jpg)$}
end
|
module CourseApi
class Purchase < Grape::API
helpers AuthenticationHelper
before { authenticate! }
rescue_from ActiveRecord::RecordNotFound do |e|
error!('404 RecordNotFound', 404)
end
resources :courses do
desc 'User can buy the course'
params do
requires :id, type: Integer, desc: 'Course ID which wanna buy.'
end
route_param :id do
post :purchase do
course = Course.find params[:id]
order = current_user.orders.new(course: course)
if order.save
# TODO: 導至付款頁面
present order, with: Entities::OrderEntity
else
error!(order.errors.full_messages.join(''), 400)
end
end
end
end
end
end |
Rails.application.routes.draw do
devise_for :users
root 'welcom#index'
get '/search', to: 'search#index'
resources :users do
resources :characters
resources :guilds
resources :invites do
patch 'reject', on: :member
end
end
namespace :guild_panel do
resource :administration, only: :show
resource :guild
resources :news
resources :characters, only: [:index] do
patch 'grant_privilege', on: :member
patch 'remove_privilege', on: :member
delete 'kick', on: :member
patch 'up_rank', on: :member
patch 'down_rank', on: :member
end
resources :invites, only: [:index] do
patch 'approval', on: :member
patch 'reject', on: :member
patch 'accepted', on: :member
end
end
end
|
class AddCurrentPriceToAuctions < ActiveRecord::Migration[5.0]
def change
add_column :auctions, :current_price, :float, default: 1.0
end
end
|
$: << File.expand_path(File.dirname(__FILE__))
require 'test_helper'
require 'adcenter_client'
require 'date'
class ReportingServiceTest < Test::Unit::TestCase
def setup
# $DEBUG = true
# assert_sandboxed(TEST_CREDENTIALS)
@acc = AdCenterClient.new(TEST_CREDENTIALS, nil, false)
@svc = @acc.reporting_service
@entities = @acc.entities
@report_request_id = nil
end
def test_get_keyword_performance_report
report_date = Date.today - 1
report_format = "Xml"
report_language = 'English'
report_name = sprintf("Keyword Performance Report - %s", report_date.strftime("%Y-%m-%d"))
report_complete_data_only_flag = false
report_aggregation = 'Summary'
report_columns = %w[ AccountName Keyword KeywordId CurrentMaxCpc Impressions Clicks Spend AveragePosition AverageCpm ]
report_filter = nil
report_scope = @entities::AccountReportScope.new
report_time = @entities::ReportTime.new(report_date, report_date)
kprr = @entities::KeywordPerformanceReportRequest.new(report_format, report_language,
report_name, report_complete_data_only_flag, report_aggregation,
report_columns, report_filter, report_scope, report_time)
report_request = @entities::SubmitGenerateReportRequest.new(kprr)
res = @svc.submitGenerateReport(report_request)
assert_equal @entities::SubmitGenerateReportResponse, res.class
assert res.reportRequestId
@@report_request_id = res.reportRequestId
end
def test_poll_generate_report_request()
res = @svc.pollGenerateReport(@entities::PollGenerateReportRequest.new(@@report_request_id))
assert_equal @entities::PollGenerateReportResponse, res.class
assert res.reportRequestStatus.status
assert res.reportRequestStatus.reportDownloadUrl
end
end
|
class CreateCharacters < ActiveRecord::Migration
def change
create_table :characters do |t|
t.references :account
t.references :current_room
t.references :current_morph
t.string :name, :unique => true
t.string :dc_name, :unique => true
t.timestamps
end
add_index :characters, :name, :unique => true
add_index :characters, :dc_name, :unique => true
add_index :characters, :current_room_id
end
end
|
# frozen_string_literal: true
class Ability
include CanCan::Ability
attr_reader :user
def initialize(user)
@user = user
if user
user.admin? ? admin_abilities : user_abilities
else
guest_abilities
end
end
def guest_abilities
can :read, :all
can :search, :all
end
def admin_abilities
can :manage, :all
end
def user_abilities
guest_abilities
can :create, [Question, Answer, Subscription]
can :create_comment, Comment
can :update, [Question, Answer], user_id: user.id
can :destroy, [Question, Answer, Subscription], user_id: user.id
can :destroy, Link, linkable: { user_id: user.id }
can :destroy, ActiveStorage::Attachment, record: { user_id: user.id }
can :best, Answer, question: { user_id: user.id }
can :create_vote, Vote
cannot :create_vote, Vote, votable: { user_id: user.id }
can [:like, :dislike, :unvote], Vote, user_id: user.id
cannot [:like, :dislike, :unvote], Vote, votable: { user_id: user.id }
end
end
|
require 'spec_helper'
describe "Customer" do
before(:each) do
MovieLibrary.class_variable_set(:@@main_instance, nil)
@main_library = MovieLibrary.create_main_instance
@customer = Customer.new("test","pass")
end
let(:valid_movie) {Movie.new("Blade Runner", "Do androids dream of electric sheep", "1982", "Sci Fi") }
describe "add_to_queue(movie_name)" do
it "should allow user to add movie to their queue" do
@main_library << valid_movie
@customer.add_to_queue(valid_movie.title)
@customer.movie_queue.find(valid_movie.title).should == valid_movie
@main_library.size.should == 0
end
end
describe "remove_from_queue(movie_name)" do
it "should allow user to remove movie from their queue" do
@main_library << valid_movie
@customer.add_to_queue(valid_movie.title)
@customer.movie_queue.find(valid_movie.title).should == valid_movie
@main_library.size.should == 0
@customer.remove_from_queue(valid_movie.title)
@main_library.size.should == 1
@customer.movie_queue.size.should == 0
end
end
describe "rent_movie(movie_name)" do
it "should allow user to rent a movie that's in their queue" do
@main_library << valid_movie
@customer.add_to_queue(valid_movie.title)
rented_movie = @customer.rent_movie(valid_movie.title)
rented_movie.should be_rented
end
end
describe "return_movie(movie_name)" do
it "should allow user to return a movie that they have rented" do
@main_library << valid_movie
@customer.add_to_queue(valid_movie.title)
rented_movie = @customer.rent_movie(valid_movie.title)
@customer.return_movie(rented_movie.title)
@customer.movie_queue.size.should == 0
end
end
describe "main_library" do
it "should return the single instance of main library" do
customer2 = Customer.new("test2","pass2")
@customer.main_library.should == customer2.main_library
end
end
describe "can_rent?" do
it "should return true if the customer does not have any rentals" do
@main_library << valid_movie
@customer.add_to_queue(valid_movie.title)
@customer.rent_movie(valid_movie.title)
@customer.can_rent?.should == false
end
end
end |
class Category < ApplicationRecord
has_many :videos
has_and_belongs_to_many :users
end
|
#
# Cookbook Name:: spinen-grails
# Attribute file:: default
#
# Copyright (C) 2015 SPINEN
#
# Licensed under the MIT license.
# A copy of this license is provided at the root of this cookbook.
#
default['grails']['version'] = '2.3.11'
default['grails']['home'] = '/usr/local/grails'
default['grails']['url'] = "http://dist.springframework.org.s3.amazonaws.com/release/GRAILS/grails-#{node['grails']['version']}.zip"
default['grails']['checksum'] = 'c53e01a9d98c499f91d7c7d54312dbdfd33f99ffcdec8bc4946036e4bea2c8e1' |
describe :enumeratorize, :shared => true do
ruby_version_is '' ... '1.8.7' do
it "raises a LocalJumpError if no block given", ->
lambda{ [1,2].send(@method) ).toThrow(LocalJumpError)
ruby_version_is '1.8.7' do
it "returns an Enumerator if no block given", ->
[1,2].send(@method).should be_an_instance_of(enumerator_class)
|
class User < ApplicationRecord
has_many :event_listings, :foreign_key => :attendee_id
has_many :attended_events, :through => :event_listings
has_many :created_events, :foreign_key => :creator_id, :class_name => 'Event'
end
|
class RestaurantMenuList < ApplicationRecord
belongs_to :restaurant
belongs_to :menu_category
has_many :menu_items
end
|
Spree::Image.class_eval do
attr_accessible :color
class Uploader < CarrierWave::Uploader::Base
include CarrierWave::Compatibility::Paperclip
include Cloudinary::CarrierWave
process :convert => 'png'
# Spree looks in attachment#errors, so just delegate to model#errors
delegate :errors, :to => :model
# Match the path defined in Spree::Image
def paperclip_path
"dev/assets/products/:id/:style/:basename.:extension"
end
# These are the versions defined in Spree::Image
version :mini do
process :resize_to_fit => [125, 125]
end
version :small do
process :resize_to_fit => [300, 300]
end
version :product do
process :resize_to_fit => [510, 510]
end
version :large do
process :resize_to_fit => [1000, 1000]
end
version :feature do
process :resize_to_fit => [460, 460]
end
end
mount_uploader :attachment, Uploader, :mount_on => :attachment_file_name
# Get rid of the paperclip callbacks
def save_attached_files; end
def prepare_for_destroy; end
def destroy_attached_files; end
private
def attachment_file_name
'not_blank'
end
end
|
class Fish < ApplicationRecord
belongs_to :fish_type
belongs_to :user
has_many :bookings, dependent: :destroy
has_one_attached :photo, dependent: :destroy
geocoded_by :address
validates :name, presence: true
after_validation :add_city
after_validation :geocode, if: :will_save_change_to_address?
# validates :price_per_week, numericality: { only_integer: true }
end
def unavailable_dates
bookings.pluck(:start_at, :end_at).map do |range|
{ from: range[0], to: range[1] }
end
end
private
def add_city
self.city = Geocoder.search(self.address)&.first&.municipality
end
|
class AirportsController < ApplicationController
# 'typeahead' action is required for home airports survey and travel plan
# to load airport data for the typeahead
def typeahead
@airports = Airport.includes(:parent).order(code: :asc)
respond_to do |format|
format.json do
fresh_when last_modified: @airports.maximum(:updated_at),
etag: @airports.cache_key
end
end
end
end
|
class CreatePayments < ActiveRecord::Migration
def change
create_table :payments do |t|
t.string :stripe_customer_id, :null => false
t.integer :subscription_id, :null => false
t.timestamps
end
add_index :payments, :stripe_customer_id
add_index :payments, :subscription_id
end
end
|
Pod::Spec.new do |s|
s.name = "AheadTLV"
s.version = "0.1.0"
s.summary = "TLV parser library"
s.description = "TLV parser library - handle BER TLV"
s.homepage = "https://github.com/monetplus/EOP_iOS_AheadTLV"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "Ivan Gürtler" => "ivan.gurtler@ahead-itec.com" }
s.ios.deployment_target = "8.0"
s.ios.vendored_frameworks = 'AheadTLV.framework'
s.source = { :http => "https://github.com/monetplus/EOP_iOS_AheadTLV/raw/master/0.1.0/AheadTLV.zip" }
s.exclude_files = "Classes/Exclude"
s.swift_version = '4.1'
end
|
class QuestionGroup < ApplicationRecord
validates :topic, presence: true, uniqueness: true
validates :order, presence: true, uniqueness: true
has_many :answers, primary_key: :id, foreign_key: :question_group_id
end
|
require './Manejador'
require './Generales'
require './Cesar'
require './Vigenere'
class Principal
MENU = "[0] Salir \n"+
"[1] Frecuencias \n"+
"[2] N-Gramas \n"+
"[3] Cifrar Cesar \n"+
"[4] Descifrar Cesar \n"+
"[5] Cifrar Vigenere \n"+
"[6] Descifrar Vigenere \n"
def initialize
puts "Hello!"
STDOUT.flush
end
## Metodo que se invoca para que el programa se ejecute
def correr
puts MENU
print "Que Deseas Hacer? \n>> "
opcion = gets.chomp.to_i
if opcion == 0
puts "GOD BYE...."
return opcion
elsif opcion > 6
puts "Opcion no registrada."
return 0
end
salida = 0
puts "Indicar ruta del archivo"
ruta = gets.chomp
#puts ruta
managment = Manejador.new(ruta)
if opcion == 1
grals = Generales.new(managment)
grals.frecuencias(true)
salida = 1
elsif opcion == 2
puts "Pendiente......"
salida = 2
elsif opcion == 3
cesar = Cesar.new(managment, true)
puts "Dame el desplazamiento. "
desplazamiento = gets.chomp.to_i
cesar.cifrar_Cesar(desplazamiento)
system("rm texto_limpio.txt")
salida = 3
elsif opcion == 4
cesar = Cesar.new(managment, false)
puts "Dame el desplazamiento. "
desplazamiento = gets.chomp.to_i
cesar.des_encriptar_cesar(desplazamiento)
salida = 4
elsif opcion == 5
vigen = Vigenere.new(managment, true)
puts "Dame la llave del cifrado."
_key = gets.chomp.upcase
vigen.cifra_vigenere(_key)
system("rm texto_limpio.txt")
salida = 5
elsif opcion == 6
vigen = Vigenere.new(managment, false)
puts "Dame la llave del cifrado."
_key = gets.chomp.upcase
vigen.des_cifra_vigenere(_key)
salida = 6
end
return salida
end
end
## Se ejecuta el main
if __FILE__ == $0
_main = Principal.new
status = -1
while status != 0
status = _main.correr
end
end
|
require 'tb'
require 'test/unit'
require 'tmpdir'
class TestTbEnum < Test::Unit::TestCase
def test_cat_without_block
t1 = Tb::Enumerator.from_header_and_values(%w[a b], [1, 2], [3, 4])
t2 = Tb::Enumerator.from_header_and_values(%w[c d], [5, 6], [7, 8])
e = t1.cat(t2)
result = []
e.with_header {|header|
result << [:header, header]
}.each {|x|
assert_kind_of(Hash, x)
result << [x.to_a]
}
assert_equal(
[[:header, %w[a b c d]],
[[['a', 1], ['b', 2]]],
[[['a', 3], ['b', 4]]],
[[['c', 5], ['d', 6]]],
[[['c', 7], ['d', 8]]]],
result)
end
def test_cat_with_block
t1 = Tb::Enumerator.from_header_and_values(%w[a b], [1, 2], [3, 4])
t2 = Tb::Enumerator.from_header_and_values(%w[c d], [5, 6], [7, 8])
result = []
t1.cat(t2) {|x|
assert_kind_of(Hash, x)
result << x.to_a
}
assert_equal(
[[['a', 1], ['b', 2]],
[['a', 3], ['b', 4]],
[['c', 5], ['d', 6]],
[['c', 7], ['d', 8]]],
result)
end
def test_write_to_csv_basic
obj = [
{'a' => 0, 'b' => 1, 'c' => 2},
{'a' => 3, 'b' => 4, 'c' => 5},
{'a' => 6, 'b' => 7, 'c' => 8},
]
def obj.header_and_each(header_proc, &block)
header_proc.call(nil) if header_proc
self.each(&block)
end
obj.extend Tb::Enumerable
Dir.mktmpdir {|d|
open("#{d}/foo.csv", 'w') {|f|
obj.write_to_csv(f)
}
assert_equal(<<-'End'.gsub(/^\s*/, ''), File.read("#{d}/foo.csv"))
a,b,c
0,1,2
3,4,5
6,7,8
End
}
end
def test_write_to_csv_header_extension
obj = [
{'a' => 0},
{'b' => 1},
{'c' => 2},
]
def obj.header_and_each(header_proc, &block)
header_proc.call(nil) if header_proc
self.each(&block)
end
obj.extend Tb::Enumerable
Dir.mktmpdir {|d|
open("#{d}/foo.csv", 'w') {|f|
obj.write_to_csv(f)
}
assert_equal(<<-'End'.gsub(/^\s*/, ''), File.read("#{d}/foo.csv"))
a,b,c
0
,1
,,2
End
}
end
def test_write_to_csv_without_header
obj = [
{'1' => "x"},
{'2' => "y"},
{'3' => "z"},
]
def obj.header_and_each(header_proc, &block)
header_proc.call(nil) if header_proc
self.each(&block)
end
obj.extend Tb::Enumerable
Dir.mktmpdir {|d|
open("#{d}/foo.csv", 'w') {|f|
obj.write_to_csv(f, false)
}
assert_equal(<<-'End'.gsub(/^\s*/, ''), File.read("#{d}/foo.csv"))
x
,y
,,z
End
}
end
def test_extsort_by
er = Tb::Enumerator.new {|y|
y.yield("a" => 1, "b" => 2)
y.yield("b" => 3, "c" => 4)
}
er2 = er.extsort_by {|pairs| -pairs["b"] }
result = []
er2.with_header {|h|
result << h
}.each {|pairs|
result << pairs
}
assert_equal([%w[a b c], {"b" => 3, "c" => 4}, {"a" => 1, "b" => 2}], result)
end
def test_with_cumulative_header
er = Tb::Enumerator.new {|y|
y.set_header %w[a c]
y.yield("c" => 1, "d" => 2)
y.yield("b" => 1, "c" => 2)
y.yield("a" => 3, "b" => 4)
}
result = []
er.with_cumulative_header {|header|
result << header
}.each {|pairs, cheader|
result << pairs << cheader
}
assert_equal(
[%w[a c],
{ "c" => 1, "d" => 2 },
%w[a c d],
{ "b" => 1, "c" => 2 },
%w[a c d b],
{ "a" => 3, "b" => 4 },
%w[a c d b]],
result)
end
def test_with_cumulative_header_no_header_proc
er = Tb::Enumerator.new {|y|
y.set_header %w[a c]
y.yield("c" => 1, "d" => 2)
y.yield("b" => 1, "c" => 2)
y.yield("a" => 3, "b" => 4)
}
result = []
er.with_cumulative_header.each {|pairs, cheader|
result << pairs << cheader
}
assert_equal(
[{ "c" => 1, "d" => 2 },
%w[a c d],
{ "b" => 1, "c" => 2 },
%w[a c d b],
{ "a" => 3, "b" => 4 },
%w[a c d b]],
result)
end
end
|
def source
'1&-3.14&-0x4ad.fp2'
end
def expected_tokens
[
{
type: 'T_LITERAL_INTEGER_DECIMAL',
value: '1'
},
{
type: 'T_OPERATOR',
value: '&-'
},
{
type: 'T_LITERAL_FLOATING_POINT_DECIMAL',
value: '3.14'
},
{
type: 'T_OPERATOR',
value: '&-'
},
{
type: 'T_LITERAL_FLOATING_POINT_HEXADECIMAL',
value: '0x4ad.fp2'
}
]
end
def expected_ast
{
__type: 'program',
body: [
{
__type: 'binary-expression',
operator: '&-',
left: {
__type: 'binary-expression',
operator: '&-',
left: {
__type: 'literal-integer',
value: 1
},
right: {
__type: 'literal-double',
value: 3.140000000000000E+00
}
},
right: {
__type: 'literal-double',
value: 4.791750000000000E+03
}
}
]
}
end
load 'spec_builder.rb'
|
$:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "date-parser/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "date-parser"
s.version = DateParser::VERSION
s.authors = ["Robert Voß", "Niels Bennke"]
s.email = ["voss@bfpi.de", "bennke@bfpi.de"]
s.homepage = "http://www.bfpi.de"
s.summary = "Simple parser for dates and times from strings"
s.description = "Simple parser for dates and times from strings"
s.license = "MIT"
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
s.require_path = 'lib'
s.add_dependency "rails"
end
|
require 'sinatra/base'
require 'json'
module Sinatra
module Companies
def self.registered(app)
#Create a new company
app.post '/company' do
if params.empty?
params_json = JSON.parse(request.body.read)
company = Company.new(params_json)
else
company = Company.new(params['company'])
end
if company.save
company.to_json
else
halt 500
end
end
#List all companies
app.get '/company' do
Company.all.to_json
end
#Get the details about one company
app.get '/company/:id' do
company = Company.find(params[:id])
return status 404 if company.nil?
company.to_json
end
#Update a company
app.put '/company/:id' do
company = Company.find(params[:id])
return status 404 if company.nil?
company.update(params[:company])
company.save
status 202
end
#Delete a company
app.delete '/company/:id' do
company = Company.find(params[:id])
return status 404 if company.nil?
company.delete
status 202
end
end
end
register Companies
end
|
class GnipImporter < CsvImporter
def self.import_to_table(table_name, gnip_instance_id, workspace_id, user_id, event_id)
event = Events::Base.find(event_id)
gnip_instance = GnipInstance.find(gnip_instance_id)
c = ChorusGnip.from_stream(gnip_instance.stream_url, gnip_instance.username, gnip_instance.password)
result = c.to_result
workspace = Workspace.find(workspace_id)
csv_file = workspace.csv_files.new(
:contents => StringIO.new(result.contents),
:column_names => result.column_names,
:types => result.types,
:delimiter => ',',
:to_table => table_name,
:new_table => true,
:file_contains_header => false
)
csv_file.user_uploaded = false
csv_file.user = User.find(user_id)
csv_file.save!
GnipImporter.import_file(csv_file, event)
rescue Exception => e
GnipImporter.create_failure_event(e.message, event, table_name)
end
def create_success_event
gnip_event = Events::GnipStreamImportCreated.find(import_created_event_id).tap do |event|
event.dataset = destination_dataset
event.save!
end
event = Events::GnipStreamImportSuccess.by(gnip_event.actor).add(
:workspace => gnip_event.workspace,
:dataset => gnip_event.dataset,
:gnip_instance => gnip_event.gnip_instance
)
Notification.create!(:recipient_id => gnip_event.actor.id, :event_id => event.id)
end
def create_failure_event(error_message)
gnip_event = Events::GnipStreamImportCreated.find(import_created_event_id)
GnipImporter.create_failure_event(error_message, gnip_event, csv_file.to_table)
end
def self.create_failure_event(error_message, gnip_event, table_name)
event = Events::GnipStreamImportFailed.by(gnip_event.actor).add(
:workspace => gnip_event.workspace,
:destination_table => table_name,
:gnip_instance => gnip_event.gnip_instance,
:error_message => error_message
)
Notification.create!(:recipient_id => gnip_event.actor.id, :event_id => event.id)
end
end |
module Contentr
class LinkedPage < Page
# Includes
include Rails.application.routes.url_helpers
# Protect attributes from mass assignment
# Validations
# Public: find a LinkedPage by specific parameters
#
# params - A hash containing the following keys:
# controller
# action
# id (optional)
#
# Returns the found LinkedPage
def self.find_by_request_params(params)
controller = params[:controller]
action = params[:action]
id = params[:id]
return if controller.blank?
return if action.blank?
wildcard_pattern = "#{controller}#*"
default_pattern = "#{controller}##{action}"
full_pattern = "#{default_pattern}:#{id}" if id.present?
if full_pattern.present?
page = LinkedPage.where(linked_to: full_pattern).try(:first)
return page if page.present?
end
page = LinkedPage.where(linked_to: default_pattern).try(:first)
return page if page.present?
page = LinkedPage.where(linked_to: wildcard_pattern).try(:first)
return page if page.present?
end
end
end
|
require 'spec_helper'
describe "Static pages" do
subject { page }
let(:base_title) { "Bulletin Board" }
describe "about page" do
before { visit about_path }
it { should have_title "#{base_title} | About" }
it { should have_content "About application" }
end
describe "contact page" do
before { visit contact_path }
it { should have_title "#{base_title} | Contact" }
it { should have_content "Contact author" }
end
end
|
class AssignmentReward < ActiveRecord::Base
belongs_to :assignment
belongs_to :reward
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.