query
stringlengths 7
9.55k
| document
stringlengths 10
363k
| metadata
dict | negatives
listlengths 0
101
| negative_scores
listlengths 0
101
| document_score
stringlengths 3
10
| document_rank
stringclasses 102
values |
|---|---|---|---|---|---|---|
sums the series: basem, base(m+1)...base(n1), base(n) Assumes exponents are positive integers, and first_exp 2^0 + 2^1 + 2^2 + 2^3 Returns base^exp, if first_exp = second_exp (trivial case) Returns 'nil' if first_exp > second_exp, or exponents not positivbe integers
|
def sum_base_to_exponent_series(base, first_exp, second_exp)
sum = 0
if (first_exp.is_a?(Integer) &&
second_exp.is_a?(Integer) &&
first_exp <= second_exp &&
first_exp >= 0 &&
second_exp >= 0)
if first_exp == second_exp
sum = base**first_exp
else
exp = first_exp
until exp > second_exp
sum += base**exp
exp += 1
end
end
else
# parameter conditions not met
sum = nil
end
return sum
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def sum_base_2_number(pow = 1)\n (2**pow).to_s.split('').map(&:to_i).inject(:+)\nend",
"def rec_exp_1(base, power)\nend",
"def rec_exp_2(base, power)\nend",
"def power_digit_sum(base, exponent)\n\t(2 ** 1000).to_s.split(\"\").inject(0) {|sum, n| sum + n.to_i}\nend",
"def exp1(base, n)\n return 1 if n == 0 \n\n base * exp1(base, n-1)\nend",
"def exp1(base, power)\n return 1 if power <= 0\n exp1(base, power - 1) * base\nend",
"def exp1(base, power)\n return 1 if power == 0\n base * exp1(base, power - 1)\nend",
"def exp1(base, num)\n return 1 if num == 0\n return base if num == 1\n expo = base * exp1(base, num-1)\nend",
"def exponentiation_one(base, exp)\n return nil if exp < 0\n return 1 if exp == 0\n return base if exp == 1\n\n base * exponentiation_one(base, exp - 1)\nend",
"def exp1(base, power)\n return 1 if power == 0\n base * exp1(base, power - 1)\nend",
"def exp_r1 (base, exponent)\n if exponent == 0\n return 1\n else\n base * exp_r1(base, exponent - 1)\n end\nend",
"def exp_1(base, exp)\n return 1 if exp == 0\n\n base * exp_1(base, exp-1)\nend",
"def power(base, exponent)\n return (0...exponent).inject(1) { |memo| memo * base } if exponent >= 0\n (exponent...0).inject(1.0) { |memo| memo * 1/base }\nend",
"def power_digit_sum(base, exponent)\n # 1) calculate the power\n power = base ** exponent\n sum = 0\n\n # 2) convert to string to iterate each digit\n len = power.to_s.length\n for index in (0...len)\n # 3) convert back to number to calculate sum\n sum += power.to_s[index].to_i\n end\n\n # 4) return sum\n return sum\nend",
"def exponent1(base, num)\n return 1 if num == 0\n return base if num == 1\n x = base * exponent1(base, num-1)\n\nend",
"def convert_base(number, base)\n \n exponents = []\n n = 0 # Exponent / number position\n\n # Find the appropriate exponent size larger than the number \n while number != 0\n # puts \"Current top number: #{number}\"\n # puts \"Current exponent value: #{n}\"\n running_total = 0\n if number < base ** n\n # puts \"Base ** n: #{base ** n}\" \n # puts \"If loop current number: #{number}\"\n running_total += base ** (n-1)\n # puts \"If loop running_total: #{running_total}\"\n number = number - running_total\n # puts \"If loop number after subtraction: #{number}\"\n if exponents[n-1].nil? then exponents[n-1] = 1 else exponents[n-1] += 1 end\n n = 0\n else\n n += 1\n end\n end\n\n exponents.inspect\n\nend",
"def exp(base, power)\n return 1 if power == 0\n return base if power == 1\n base * exp(base, (power-1))\nend",
"def power(base, exponent)\n if !base.is_a?(Integer) || !exponent.is_a?(Integer)\n return nil\n else \n product = 1\n (1..exponent).each do\n product *= base\n end\n return product\n end\nend",
"def exp2(base, num)\n return 1 if num == 0\n return base if num == 1\n if num % 2 == 0\n expo = exp(base, num/2)\n else\n expo = exp(base, (num-1)/2)\n end\nend",
"def exp(base, exponent)\n return base if exponent == 1\n base * exp(base, exponent-1)\nend",
"def to_base(a, b)\n return [a] if a == 1 or a == 2\n maxlen = Math.log(a + 1, b).ceil\n base_nums = Array.new maxlen, 0\n while a > 0\n c = Math.log(a, b).floor\n rm = b ** c\n a -= rm\n i = maxlen - c - 1\n base_nums[i] += 1\n end\n base_nums\nend",
"def exponent1(base, power)\n # if power equals zero , then 1 else (base * method(base,power - 1))\n if power == 0\n return 1\n else\n (base * exponent1(base, power - 1))\n end\nend",
"def exp2(base, power)\n return 1 if power == 0\n half = exp2(base, power / 2)\n\n if power.even?\n half * half\n else\n # note that (power / 2) == ((power - 1) / 2) if power.odd?\n base * half * half\n end\nend",
"def exponentiation(base, exp)\n return nil if exp < 0\n return 1 if exp == 0\n return base if exp == 1\n\n if exp.even?\n (exponentiation(base, exp / 2)**2)\n else\n base * (exponentiation(base, (exp - 1) / 2)**2)\n end\nend",
"def exp1(base, power)\n puts \"exp1\"\n return 1 if power == 0\n base * exp1(base, power - 1)\nend",
"def exponent1(base, power)\n\treturn 1 if power == 0\n\tbase * exponent1(base, power - 1)\nend",
"def pow(base, exponent) #(3, 4) ==> 3 * 3 * 3 * 3 = \n return 1 if exponent == 0 \n #return base if exponent == 1\n base * pow(base, exponent - 1)\nend",
"def exp_2(base, exp)\n return 1 if exp == 0\n return base if exp == 1\n\n if exp % 2 == 0\n even = exp_2(base, exp / 2)\n even * even\n else\n odd = exp_2(base, (exp - 1) / 2)\n base * odd * odd\n end\nend",
"def power(base, exponent)\n total = 1\n\n # we don't actually need this\n # if exponent == 1\n # total = base\n # elsif exponent == 0\n # total = 1\n # end\n # But what if the exponent were negative?\n\n (exponent.abs).times do\n total = multiply(total, base)\n end\n\n if exponent < 0\n total = (1.0 / total).to_r\n end\n\n total\nend",
"def exp2(base, power)\n return 1 if power == 0\n\n half = exp2(base, power / 2)\n\n if power.even?\n half * half\n else\n # note that (power / 2) == ((power - 1) / 2) if power.odd?\n base * half * half\n end\nend",
"def exp(base, exponent)\n return 1 if exponent.zero?\n\n base * exp(base, exponent - 1)\nend",
"def exponent_v1(base, power)\n return 1 if power <= 0\n base * exponent_v1(base, power-1)\nend",
"def exponent_1(base, power)\n\treturn 1 if power == 0\n\tlesser_power = power - 1\n\tbase_to_the_lesser_power = exponent_1(base, lesser_power)\n\tbase * base_to_the_lesser_power\nend",
"def power(base, exp)\n i = 0\n output = 1\n\n while i < exp\n output *= base\n i += 1\n end\n return output\nend",
"def power(base, exponent)\n return nil if exponent < 0\n\n return 1 if exponent == 0\n\n value = base\n\n (exponent - 1).times do value *= base end\n\n value\nend",
"def exp(base,exponent)\n p exponent\n return 1 if exponent == 0\n return base if exponent == 1\n if exponent.even?\n result = exp(base,exponent/2)\n result * result\n else\n result = exp(base,(exponent-1)/2)\n base * (result * result)\n end\n\n\nend",
"def exp2(base, power)\n puts \"exp2\"\n return 1 if power == 0\n return base if power == 1 #\n\n if power.even?\n exp2(base, power / 2) ** 2\n else\n base * ( exp2(base, (power - 1) / 2) ** 2 )\n end\nend",
"def ui_pow(base, exp)\n result = 1;\n while (exp)\n if (exp & 1)\n result *= base\n end\n exp >>= 1;\n base *= base\n end\n if(exp==0)\n result=base\n end\n return result\nend",
"def power(base, exponent)\n total = 1\n\n exponent.times do\n total *= base\n end\n\n return total\nend",
"def exp(b,n) #First method\n return 1 if n == 0\n if n > 0\n b * exp(b,n - 1)\n else\n (1.0/b) * exp(b,n + 1) \n end\nend",
"def power(base, exp)\n return base ** exp\nend",
"def exponentiation(base, power)\n return 1 if power == 0\n base * exponentiation(base, power - 1)\nend",
"def sum_dig_pow(a, b)\n (a..b).select do |num| \n num == num.to_s\n .chars\n .map\n .with_index(1) { |dig, idx| dig.to_i**idx }\n .inject(:+)\n end\nend",
"def exp(a, b)\n if b == 0\n 1\n else\n a * exp(a, b - 1)\n end\nend",
"def power(base, exponent)\n exponent <= 1 ? base : base * (power base, (exponent - 1))\nend",
"def exp1(b, n)\n n == 0 ? 1 : b * exp1(b, n - 1)\nend",
"def exp1(b, n)\n return 1 if n == 0\n b * exp1(b, n - 1)\nend",
"def sum_of_power(p)\n result = []\n powers = 0.upto(10).map {|n| n**p}\n 2.upto(p.get_max_num) do |i|\n num = i.get_base_array(10).map {|n| powers[n]}\n if i == num.inject(0) {|t,n| t + n}\n result << i\n end\n end\n return result\nend",
"def exp_1(b, n)\n return 1 if n == 0\n b * exp_1(b, n - 1)\nend",
"def pow(base, exponent)\n\n result = 1\n\n exponent.times do\n result = result * base\n end\n\n return result\n \n end",
"def decimal_base(n)\n 10**(n-1)\nend",
"def recursive_exponent_1(base, exponent)\n puts \"#{__method__} called\"\n return 1 if exponent.zero?\n base * recursive_exponent_1(base, exponent - 1)\nend",
"def pow(base, exponent)\n\n result = 1\n exponent.times do \n result = base.to_i * result\n end\n result\nend",
"def geometricSeriesSum(x, n)\n return (power(x, n + 1) - 1) / (x - 1)\nend",
"def power_sumDigTerm(n)\n (2..200).each_with_object([]) do |base, sequence_array|\n 2.upto(30) do |power|\n sequence_array << base ** power if (base ** power).digits.sum == base\n end\n end.sort[n - 1]\nend",
"def exp1(b, n)\n return 1 if n == 0\n p b * exp1(b, n - 1)\nend",
"def last_digit(n1, n2)\n return 1 if n2 == 0\n return 0 if n1 == 0\n\n exp = n2 % 4 == 0 ? 4 : n2 % 4\n (n1**exp) % 10\nend",
"def exponent_plus(num1, num2)\n total = (num1 ** 2) + num2\n return total\nend",
"def sum_dig_pow(a,b)\n eureka_numbers = [] # Where we store the array\n a.upto(b) do |number|\n number_length = number.to_s.length\n digits = number.to_s.split(\"\") # This will return an array of the numbers\n index = 0\n sum = 0\n while index < number_length\n sum += digits[index].to_i ** (index + 1) # Multiplying by the power\n index += 1\n end\n if number == sum\n eureka_numbers << number\n end\n end\n eureka_numbers # Our implicit return\nend",
"def exp_1(b, num)\n return 1 if num == 0\n b * exp_1(b, num - 1)\nend",
"def power(base,exponent)\n i = 0\n output = 1\n while i < exponent\n output = output * base\n i += 1\n end\n return output\nend",
"def power(base, exponent)\n result = 1\n exponent.times { result *= base }\n result\nend",
"def digit_sum(a,b)\n\tsums = []\n\tnum = a**b\n\tarr = num.to_s.split('')\n\tnum_arr = arr.map{|n| n.to_i}\n\tsums << num_arr.reduce(:+)\n\tp sums.max\nend",
"def power(base,exponent)\n\n return base ** exponent\nend",
"def exponent(b, n)\n return 1 if n == 0\n if n > 0\n b * exponent(b, n - 1)\n else\n 1.0/b * exponent(b, n + 1)\n end\nend",
"def exponent(b, n)\n return 1 if n == 0\n if n > 0\n b * exponent(b, n - 1)\n else\n 1.0/b * exponent(b, n + 1)\n end\nend",
"def power_digit_sum(power)\n result = 2 ** power\n result.to_s.chars.map(&:to_i).inject(&:+)\nend",
"def exp_ver_two(base, exponent)\n return 1 if exponent.zero?\n\n if exponent.even?\n n = exp_ver_two(base, exponent / 2)\n n * n\n else\n n = exp_ver_two(base, (exponent - 1) / 2)\n base * (n * n)\n end\nend",
"def exponent(b, n)\n return 1 if n == 0\n\n if n > 0\n b * exponent(b, n - 1)\n else\n 1.0/b * exponent(b, n + 1)\n end\nend",
"def power(base, power)\r\n base ** multiply(power, 1)\r\nend",
"def exponent_v1(b, n)\n puts s += 1\n if n == 0\n return 1\n end\n b * exponent_v1(b, n-1)\nend",
"def exp(b,n)\n return 1 if n == 0\n b * exp(b,n-1)\nend",
"def mr_expmod(base, exp, m)\n if (exp % 2 == 0) && exp != 0\n x = mr_expmod(base, (exp/2), m)\n square = (x**2) % m\n (square == 1) && (x != 1) && (x != (m-1)) ? (return 0) : (return square)\n elsif exp != 0\n x = mr_expmod(base, (exp-1), m)\n return ((base * x) % m)\n else\n return 1\n end\nend",
"def mr_expmod(base, exp, m)\n if (exp % 2 == 0) && exp != 0\n x = mr_expmod(base, (exp/2), m)\n square = (x**2) % m\n (square == 1) && (x != 1) && (x != (m-1)) ? (return 0) : (return square)\n elsif exp != 0\n x = mr_expmod(base, (exp-1), m)\n return ((base * x) % m)\n else\n return 1\n end\nend",
"def exp1(num, exponent)\n return 1 if exponent == 0\n # return ( 1 / exp1(num, exponent - 1) )\n\n num * exp1(num, exponent - 1)\nend",
"def power(base,exponent)\n i=1\n output = base\n while i<exponent\n output = output*base\n i += 1\n end\n return output\nend",
"def factorial (base)\r\n\tcount = 1\r\n\tfor i in 2..base do\r\n\t\tcount = count * i\r\n\tend\r\n\treturn count\r\nend",
"def digit_powers(power)\n sums = []\n # First I was wrong because I assumed they all had to be five digits; then I\n # was wrong becaus the assumption is that 1 doesn't count, maybe because\n # valid sums are two digits.\n (10...10**7).each do |candidate|\n digits = candidate.to_s.split(\"\").map(&:to_i)\n sum = digits.map {|digit| digit**power}.inject(:+)\n sums << candidate if candidate == sum\n end\n sums\nend",
"def base10_to_base2(num)\n base2_ary = []\n\n MAX_POWER_OF_TWO.downto(0).each do |pow|\n if 2 ** pow <= num\n base2_ary << num / 2 ** pow\n num = num % 2 ** pow\n else\n base2_ary << 0\n end\n end\n\n base2_ary.join('').to_i\nend",
"def powerI(power, base)\n acc = 1\n power.times { acc *= base }\n return acc\nend",
"def power(base, exponent)\n i = \n output = 1\n while i <= exponent\n output = output * base\n i += 1\n end \n return output\nend",
"def exp(b, n) # option 2\n return 1 if n == 0\n result = nil\n\n if n.even?\n result = exp(b, n / 2) ** 2\n else\n result = b * (exp(b, (n - 1) / 2) ** 2)\n end\n\n result\nend",
"def pwr_sum(pwr)\n (2**pwr).to_s.split('').map(&:to_i).sum\nend",
"def exp(b, n)\n return b if n == 0 || n == 1\n \n return b * exp(b, n - 1)\nend",
"def exp(b,n)\n return 1 if n == 0\n return b if n == 1\n case \n when n > 0 && n.even?\n exp(b,n/2) ** 2\n when n > 0 && n.odd?\n b * exp(b,(n-1)/2)**2\n when n < 0 && n.even?\n exp(1.0/b,n/2) ** 2\n when n < 0 && n.odd?\n 1.0/b * exp(b,(n+1)/2) **2\n end\nend",
"def pow(base,exponent)\n base**exponent\n end",
"def power_of_n(number, power)\n array = [number] * power\n base_number = 1\n array.each do |num|\n base_number = multiply(base_number, num)\n end\n base_number\nend",
"def exponent(a, b)\n return 1 if b.zero?\n\n array_of_values = []\n\n b.abs.times do\n array_of_values.push(a)\n end\n\n calculated_multiplier = array_of_values.reduce(:*)\n\n b > 0 ? calculated_multiplier : \"1/#{calculated_multiplier}\"\nend",
"def exp(b, n)\n return b if n <= 1\n b * exp(b, n-1)\nend",
"def exponentiation_1(b, n)\n return 1 if n == 0\n return b if n == 1\n b * exponentiation_1(b, n - 1)\nend",
"def power (*base_and_power)\n base_and_power.inject(:**)\nend",
"def exponentiation_1(b, n)\n return 1 if n == 0\n return b if n == 1\n b*exponentiation_1(b, n-1)\nend",
"def power_sig_exp(b, x)\n l10 = x / Math.log(10, b)\n log10_sig_exp(l10)\nend",
"def powers(base, limit)\n 0.upto(Math.log(limit)/Math.log(base)) {|x| yield base ** x}\nend",
"def exp1(b, e)\n return 1 if e == 0\n exp1(b, e - 1) * b\nend",
"def exponent(b, n)\n return b if n == 1\n return 1 if n == 0\n if n >= 0\n exponent(b, n-1) * b\n else\n (1.0/b) * exponent(b, n+1)\n end\n end",
"def from_base(base=10)\n n = 0\n chars.reverse_each.with_index do |c, power|\n value = BASE_DIGITS[c]\n n += (base**power) * value\n end\n n\n end",
"def exp(b,n)\n return 1 if n == 0\n return b if n == 1\n\n if n.even?\n num = exp(b, n / 2)\n num * num\n else\n num = exp(b, (n - 1) / 2)\n b * num * num\n end\nend",
"def power(n, exp)\n total = 1\n 1.upto(exp) do |num|\n total = multiply(n, total)\n end\n total\nend",
"def exponent_v2(b, n)\n puts s += 1\n if n == 0 \n return 1\n elsif n == 1 \n return b\n elsif n.even?\n rec = exponent_v2(b, n / 2)\n rec * rec\n else \n rec = exponent_v2(b, (n - 1) / 2)\n b * rec * rec\n end\nend"
] |
[
"0.6745065",
"0.6632199",
"0.66135454",
"0.6524792",
"0.6473241",
"0.64234036",
"0.63033384",
"0.62924904",
"0.6276634",
"0.62561995",
"0.6239749",
"0.6203269",
"0.6167198",
"0.6165442",
"0.6144075",
"0.61336285",
"0.61278594",
"0.6127639",
"0.61219263",
"0.6108432",
"0.6102343",
"0.6086666",
"0.60841984",
"0.60774094",
"0.6048055",
"0.6040694",
"0.6039299",
"0.60365486",
"0.6035361",
"0.6029962",
"0.6025948",
"0.59833425",
"0.5980672",
"0.5937053",
"0.59215546",
"0.5904428",
"0.58703196",
"0.5870271",
"0.58559734",
"0.5835067",
"0.58211994",
"0.581296",
"0.57995033",
"0.5797934",
"0.57618433",
"0.57295245",
"0.5718805",
"0.57155156",
"0.57014835",
"0.56955576",
"0.56655",
"0.5660097",
"0.5643997",
"0.56437665",
"0.563975",
"0.5627693",
"0.5626326",
"0.56253886",
"0.56220967",
"0.56217945",
"0.5614257",
"0.55651504",
"0.55399835",
"0.5538473",
"0.5531168",
"0.5531168",
"0.55216444",
"0.552027",
"0.55061674",
"0.5499099",
"0.54927176",
"0.5465218",
"0.5461046",
"0.5461046",
"0.54434574",
"0.5440064",
"0.5435965",
"0.5435678",
"0.54351443",
"0.5433753",
"0.54238605",
"0.5414872",
"0.541257",
"0.5411294",
"0.540953",
"0.53998697",
"0.5387096",
"0.5383747",
"0.5383326",
"0.53798914",
"0.5377665",
"0.5373735",
"0.5372104",
"0.5369718",
"0.53685606",
"0.536788",
"0.5359297",
"0.5359205",
"0.5347016",
"0.5345562"
] |
0.8149083
|
0
|
p "Hello World" end say_hello def sayHello(greeting) p greeting end sayHello("Good evening") def add(num01, num02) p num01 + num02 end add(6, 2) def add(num01, num02) return num01 + num02 end add_result = add(6, 2) p add_result
|
def average(num01, num02, num03)
return (num01 + num02 + num03) / 3
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def add (a, b)\n puts \"Adding #{a} + #{b}\"\n return a+b\nend",
"def add(a, b)\n puts \"Add #{a} + #{b}\"\n return a + b\nend",
"def add(a, b)\n puts \"addng #{a} + #{b}\"\n return a + b\nend",
"def add(a, b)\n\tputs \"Adding #{a} + #{b}\\n\"\n\treturn a + b\n\nend",
"def add(a,b)\n puts \"Adding #{a} and #{b}:\"\n return a + b\nend",
"def add(a, b)\n puts \"adding #{a} and #{b}:\"\n return a + b\nend",
"def add(a, b)\n\t# a method that adds two numbers together\n\tputs \"ADDING #{a} + #{b}\"\n\treturn a + b\nend",
"def add(a, b)\n puts \"ADDING #{a} + #{b}\"\n return a + b\nend",
"def add(a, b)\n puts \"ADDING #{a} + #{b}\"\n return a + b\nend",
"def add(a, b)\n p \"ADDING #{a} + #{b}\"\n return a + b\nend",
"def add(a, b)\n puts \"#{a} + #{b}\"\n return a + b\nend",
"def add(a, b)\n puts \"#{a} + #{b}\"\n return a + b\nend",
"def add(a, b)\n puts \"#{a} + #{b}\"\n return a + b\nend",
"def add(a, b)\n puts \"ADDING: #{a} + #{b}\"\n return a + b\nend",
"def add(a,b)\n p (a + b)\nend",
"def add (a, b)\n puts 1\n puts 2 \n (a+b)\n return result\n \nend",
"def add(a, b)\n puts \"SUM #{a} + #{b}\"\n return a + b\nend",
"def add(x, y)\n puts \"Adding #{x}, #{y}\"\n return x + y\nend",
"def add(a,b)\n puts \"Adding #{a} + #{b}\"\n a + b\nend",
"def add(num_1, num_2)\n p num_1 + num_2\nend",
"def add(a, b)\n #puts a + b\n return a + b\nend",
"def add(num_1, num_2)\n num_1 = 2\n num_2 = 3\n p num_1 + num_2\nend",
"def add(x, y)\n puts \"The sum of x & y is: #{x} + #{y}\"\n return x + y\nend",
"def say_addition\n\tnum1 = 1\n\tnum2 = 2\n\tputs num1 + num2\nend",
"def add(a, b)\n puts \"ADDING #{a} + #{b}\"\n a + b\nend",
"def add(number_1, number_2)\n p number_1 + number_2\nend",
"def addition(x, y)\n puts \"Addition: #{x} + #{y}\"\n return x + y\nend",
"def addition(a, b)\n puts a + b\nend",
"def add(x, y)\n p x+y\nend",
"def addition(a,b)\n puts a + b\nend",
"def add(a, b)\n puts a + b\nend",
"def add(a, b)\n puts a + b\nend",
"def add(a, b)\n puts a + b\nend",
"def add(a, b)\n puts a + b\nend",
"def add\n puts 2+2\nend",
"def add(a,b)\n return (a + b);\nend",
"def addition(num1, num2)\n p num1 + num2\nend",
"def add (a, b)\n answ = a + b\n puts \"Adding #{a} and #{b}...\"\n puts \"Answer is: #{answ}.\"\n return answ\nend",
"def add (a, b) \n return a + b; \nend",
"def add(num_one,num_two)\n puts \"#{num_one} + #{num_two} = #{num_one + num_two}\"\nend",
"def add(num_1, num_2)\n sum = num_1 + num_2\n puts sum\n return sum\nend",
"def add_sum(a, b)\n puts \"ADDING #{a} + #{b}\"\n return a + b\nend",
"def say_hello thing_to_say\n puts \"Hello \"+thing_to_say\nend",
"def addition num1,num2 #num1 and num2 are known as parameters\nputs num1 + num2 \nend",
"def add(a,b)\n puts \"Adding these numbers #{a}, #{b}\"\n a + b\n end",
"def sum(a, b)\n puts \"The sum of #{a} + #{b} = \" + \"#{(a + b)}\"\n #return a + b not needed for this\nend",
"def add(a,b)\n return a+b\nend",
"def add(num1, num2)\n puts num1 + num2\nend",
"def add(a,b)\n return a + b\nend",
"def add_num(a, b)\n puts a + b\nend",
"def add_two num\n p num + 2\nend",
"def add(one,two)\n\treturn one+two\nend",
"def add(num1,num2)\n\tputs \"num1 has the value : #{ num1 }\"\n\tputs \"num2 has the value : #{ num2 }\"\n\tresults = num1 + num2\n\tputs \"results is then: #{ results}\"\nend",
"def addition(value1, value2)\n result = value1 + value2\n puts \"The sum of #{ value1 } + #{ value2 } = #{ result }\"\nend",
"def add(a,b)\n return a + b\nend",
"def add(a,b)\n return a + b\nend",
"def add(num_1, num_2)\n puts num_1 + num_2\nend",
"def addition1(num1, num2)\n\tprint \"addition1 gets call: \"\n\treturn num1 + num2\nend",
"def add(num_1, num_2)\n #your code here\n \treturn (num_1 + num_2)\nend",
"def add(x, y)\n return(x + y)\nend",
"def add(a, b)\n return a + b\nend",
"def numbers(a, b)\n p \"#{a} + #{b}\"\n return a + b\nend",
"def add(a, b) #a and b are the value of two number for addition\nreturn a+b\nend",
"def sum(a, b)\n puts \"Sum total: #{a} + #{b} = #{10 + 20}\"\n\nend",
"def add(first, second)\n puts '[DEBUG]: adding two numbers'\n puts \"[DEBUG]: first: #{first}\"\n return first + second\nend",
"def sum_method(a, b)\n puts \"Adding #{a} + #{b}\"\n puts a + b\nend",
"def add(a, b)\n return a + b\nend",
"def add(a, b)\n return a + b\nend",
"def add(a, b)\n return a + b\nend",
"def add_numbers(num1, num2)\n p num1 + num2\nend",
"def addition(a, b) \n return a + b\nend",
"def add(num_1, num_2)\n #your code here\n \treturn num_1 + num_2\nend",
"def addition(num_1, num_2)\n num_1 + num_2\n return num_1 + num_2\nend",
"def addition_method(num1, num2)\n\tputs num1 + num2\nend",
"def add_nums(num1, num2)\n p \"Addition of #{num1} + #{num2} = #{num1 + num2}\"\nend",
"def another_greeting()\n return greet() + \" there!\"\nend",
"def addition(a, b)\n\treturn a + b\nend",
"def add(number1, number2)\n number1+number2\nend",
"def add(a, b)\n\ta + b \nend",
"def greet(name)\n return puts \"Hello, #{name} how are you doing today?\"\nend",
"def do_addition(number_1, number_2)\n\tfinal_number = number_1 + number_2\n\tputs \"Your first number, #{$first_number}, plus your second number, #{$second_number}, equals #{final_number}.\"\nend",
"def multiply(num1, num2)\n puts \"hey you!\"\n return 'I am cool'\n num1 * num2\nend",
"def add(a,b)\n a+b\nend",
"def add(a,b)\n a+b\nend",
"def numbers(a, b)\n puts \"First number is #{a}\"\n puts \"Second number is #{b}\"\n return a + b\nend",
"def add(x,y)\n return x+y\nend",
"def addition(a,b)\n\ta + b\nend",
"def sum(a, b)\n p a + b\nend",
"def sum(a, b)\n p a + b\nend",
"def add(num1, num2)\n return num1 + num2\nend",
"def add(num1, num2)\n return num1 + num2\nend",
"def add(num1, num2)\n return num1 + num2\nend",
"def add(num1, num2)\n total = num1 + num2\n puts \"The sum of #{num1} + #{num2} = \" + total.to_s\nend",
"def add(a, b)\n sum = a + b\n return sum\nend",
"def add(a, b)\n a+b\nend",
"def add(a, b)\n a+b\nend",
"def add(number_1, number_2)\n return number_1 + number_2\nend",
"def add(num1,num2)\n\treturn num1 + num2\nend",
"def sum(a,b)\n p a + b\nend",
"def add(a, b)\n\ta + b\nend",
"def add(a, b)\n\ta + b\nend"
] |
[
"0.8245984",
"0.81725264",
"0.8168753",
"0.81513226",
"0.8099404",
"0.8098024",
"0.8079049",
"0.80449384",
"0.80449384",
"0.8017992",
"0.800409",
"0.800409",
"0.800409",
"0.7993886",
"0.79398483",
"0.793644",
"0.7926613",
"0.79179037",
"0.79147065",
"0.7898445",
"0.78460443",
"0.78391474",
"0.7808224",
"0.77789164",
"0.77708143",
"0.7769815",
"0.7720189",
"0.77199924",
"0.77149683",
"0.7710835",
"0.76805115",
"0.76805115",
"0.76805115",
"0.76805115",
"0.7674752",
"0.7632126",
"0.7630401",
"0.76072",
"0.76066494",
"0.7596679",
"0.7582303",
"0.75725484",
"0.75349975",
"0.7512659",
"0.75092673",
"0.7506039",
"0.7502764",
"0.7480507",
"0.7478724",
"0.7472857",
"0.74626267",
"0.74580705",
"0.74495816",
"0.7438852",
"0.74378145",
"0.74378145",
"0.74315965",
"0.7418527",
"0.7410032",
"0.7409525",
"0.7409266",
"0.7408596",
"0.74047005",
"0.73964036",
"0.73899144",
"0.73694503",
"0.7367799",
"0.7367799",
"0.7367799",
"0.7365757",
"0.7362185",
"0.73615265",
"0.73414683",
"0.733445",
"0.7328512",
"0.7327553",
"0.73251855",
"0.7317828",
"0.73098207",
"0.7301913",
"0.72906",
"0.7288076",
"0.7288049",
"0.7288049",
"0.7281546",
"0.72763413",
"0.7269104",
"0.72674495",
"0.72674495",
"0.7261518",
"0.7261518",
"0.7261518",
"0.7259558",
"0.72595555",
"0.72591496",
"0.72591496",
"0.7258114",
"0.72578",
"0.72552",
"0.7251026",
"0.7251026"
] |
0.0
|
-1
|
Available metadata are : url, label, nbhomograph, score, nature
|
def metadatas(response:)
if response_ok?(response: response)
parse_result(body: response.body)
else
Rails.logger.warn 'Dictionnaire-Academie failed in ' \
"its seach for #{word}"
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def metadata; end",
"def metadata; end",
"def metadata; end",
"def metadata; end",
"def metadata; end",
"def metadata; end",
"def metadata; end",
"def metadata\n {\n title: flickr_title,\n description: description\n }\n end",
"def metadata\n @meta_data\n end",
"def meta\n {\n source: @host,\n favicon: @favicon,\n url: @url,\n title: title,\n description: @description,\n keywords: keywords,\n image_url: @main_image,\n extractable: extractable?\n }\n end",
"def store_metadata\n html = HTMLParse.new(url)\n self.meta_title = html.title\n self.meta_desc = html.desc\n end",
"def metadata=(_); end",
"def metadata\n @metadata ||= {}\n end",
"def metadata\n @metadata ||= {}\n end",
"def metadata\n @data[:metadata]\n end",
"def metadata\n return @metadata if defined? @metadata\n\n @metadata = Henkei.read :metadata, data\n end",
"def metadata\n return @metadata if defined? @metadata\n\n @metadata = Henkei.read :metadata, data\n end",
"def metadata\n attributes['metadata'] ||= {}\n attributes['metadata']\n end",
"def extract_meta\n end",
"def metadata\n {\n version: 0,\n prefill: true,\n returnUrl: '/veteran-information'\n }\n end",
"def metadata\n {\n version: 0,\n prefill: true,\n returnUrl: '/veteran-information'\n }\n end",
"def print_meta_head\n puts \"\\nDataset: #{@meta_data.name}\"\n end",
"def metadata\n @metadata\n end",
"def metadata\n hash.inject([]){ |list, data| list << MetaData.new(data[0], data[1][0]) }\n end",
"def fetch_metadata\n self.title ||= biblio_commons.title\n self.thumbnail ||= RemoteImage.new(:url => biblio_commons.thumbnail_url)\n self.format ||= biblio_commons.format\n end",
"def metadata\n self[:metadata] || {}\n end",
"def metadata\n @metadata ||= Mash.new\n end",
"def meta\n @d[:meta]\n end",
"def extract_metadata; end",
"def metadata=(value)\n @metadata = value\n end",
"def metadata=(value)\n @metadata = value\n end",
"def metadata\n metadata = {}\n @file.data.each { |key, value| metadata[key.to_sym] = value }\n\n metadata[:type] = @file.class.name.split('::')[1].downcase\n metadata[:url] = @file.url\n\n metadata[:slug] = slug\n\n metadata[:posted_at] = @file.date.to_time.to_i if @file.respond_to? :date\n metadata[:tags] = tags\n\n metadata\n end",
"def get_meta_data\r\n MetaData.new(:':curr-id' => Node.current_id,\r\n :':curr-quest-flag' => QuestMaker.current_quest_flag)\r\n end",
"def descMetadata_display_fields\n [:identifier, :title, :alternative, :creator, :contributor, :description, :abstract,\n :toc, :publisher, :source, :date, :date_created, :date_copyrighted,\n :date_submitted, :date_accepted, :date_issued, :date_available,\n :date_modified, :language, :type, :format, :extent, :medium, :persname,\n :corpname, :geogname, :subject, :genre, :provenance, :rights,\n :access_rights, :rights_holder, :license, :replaces, :isReplacedBy,\n :hasFormat, :isFormatOf, :hasPart, :isPartOf, :accrualPolicy, :audience,\n :references, :spatial, :bibliographic_citation, :temporal, :funder,\n :resolution, :bitdepth, :colorspace, :filesize]\n end",
"def metadata_options\n data[:metadata_options]\n end",
"def metadata\n @metadata ||= Metadata.new(self)\n end",
"def read_metadata; end",
"def metadata\n {\n :name => \"QRCode Raplet\",\n :description => \"Shows a QRCode under phone numbers in the HUD\",\n :welcome_text => %q{\n <p>In order to see this raplet in action, connect your Google Contacts\n to Rapportive and then click on a phone number.</p>\n <p>You'll then be able to take a photo of the QRCode instead of having\n to type the number into your phone.</p>\n },\n :provider_name => \"Conrad Irwin\",\n :provider_url => \"http://github.com/ConradIrwin/qrcode-raplet\",\n :type => 'telephony'\n }\n end",
"def description\n metadata[:description]\n end",
"def fetch_metadata\n self.user_id ||= biblio_commons.user_id\n self.title ||= biblio_commons.name\n self.thumbnail ||= RemoteImage.new(:url => biblio_commons.thumbnail_url)\n end",
"def metadata_file; end",
"def metadata_file; end",
"def info\n MiGA::Dataset.INFO_FIELDS.map do |k|\n (k==\"name\") ? self.name : metadata[k.to_sym]\n end\n end",
"def metadata=(_arg0); end",
"def metadata\n return unless self[:metadata]\n\n self[:metadata].deep_symbolize_keys\n end",
"def meta\n {}\n end",
"def meta_data\n #object = instance_variable_get('@'+controller_name.singularize)\n object = instance_variable_get('@resource')\n meta = {}\n\n if object.kind_of? ActiveRecord::Base\n meta[:keywords] = object.meta_keywords if object[:meta_keywords].present?\n meta[:description] = object.meta_description if object[:meta_description].present?\n end\n\n #if meta[:description].blank? && object.kind_of?(Spree::Product)\n # meta[:description] = strip_tags(truncate(object.description, length: 160, separator: ' '))\n #end\n\n meta.reverse_merge!({\n keywords: current_store.meta_keywords,\n description: current_store.meta_description,\n }) if meta[:keywords].blank? or meta[:description].blank?\n meta\n end",
"def update_metadata\n response = Net::HTTP.post(URI('https://api.linkpreview.net'),\n { 'key' => ENV['LINKPREVIEW_API_KEY'],\n 'q' => self.url }.to_json)\n\n body = JSON.parse(response.body)\n self.title = body['title']\n self.image = body['image']\n self.description = body['description']\n save\n end",
"def metadata\n data = oembed || {}\n attributes.each do |attribute|\n if attribute_value = self.send(attribute)\n data[attribute] ||= attribute_value\n end\n end\n data\n end",
"def rdf_metadata\n @rdf_metadata ||= Valkyrie::Persistence::Shared::JSONValueMapper.new(object[:metadata]).result\n end",
"def custom_meta_data\n end",
"def build_content_metadata record, tags\n # TODO: Further enrich the structured data by marking up FAQ accordions, Video Carousels, Image Galleries, etc.\n # Also ItemList metadata for the meditations archive\n # See here: https://developers.google.com/search/docs/data-types/article\n []\n end",
"def meta_information\n @meta_hash ||= {}\n end",
"def metadata\n value_of(:metadata, JSON.method(:pretty_generate), '{}')\n end",
"def meta_data\n @meta_data ||= params['metaData']\n end",
"def site_meta\n end",
"def site_meta\n end",
"def metadata\n return \"\"\n end",
"def metadata(filepath)\n metadata = {}\n metadata.merge!(author(filepath))\n metadata.merge!(title(filepath))\n metadata.merge!(serie(filepath))\n metadata\n end",
"def metadata\n { \"name\" => name,\n \"description\" => description,\n \"license\" => license,\n \"source\" => datasource.title,\n \"url\" => datasource.url,\n \"publish_date\" => published_at,\n \"default\" => default_dim,\n \"units\" => {}, \n \"indvars\" => datacolumns.independent.map(&:name),\n \"depvars\" => datacolumns.dependent.map(&:name)\n }\n end",
"def page_meta_description\n \"To encourage an atmosphere of responsibility and transparency, while creating the most positive social network experience, Ello has created this bill of rights for all social network users.\"\n end",
"def parse_metadata(metadata)\n\t{\n :name => metadata[:name],\n :url => metadata[:href],\n :catalog_name => \"utah.gov\",\n :catalog_url => @base_uri,\n :org_type => \"governmental\",\n :organization => { :name => \"Utah\" },\n\n\t}\n end",
"def meta_description\n read_attribute(:meta_description).blank? ? self.intro[0, 255] : read_attribute(:meta_description)\n end",
"def metadata\n out_hash = {}.with_indifferent_access\n %i[doi upload_type publication_date title creators description access_right license\n keywords notes related_identifiers method locations communities].each do |meth|\n next if meth == 'doi' && @dataset_type != :data\n\n result = send(meth)\n out_hash[meth] = result unless result.blank?\n end\n out_hash\n end",
"def metadata\n case object.package_type\n when 'composer'\n object.composer_metadatum\n when 'conan'\n object.conan_metadatum\n when 'maven'\n object.maven_metadatum\n when 'nuget'\n object.nuget_metadatum\n when 'pypi'\n object.pypi_metadatum\n else\n nil\n end\n end",
"def metadata\n # TODO Move into {NRSER::Props::Metadata}?\n # \n unless NRSER::Props::Metadata.has_metadata? self\n instance_variable_set \\\n NRSER::Props::Metadata::VARIABLE_NAME,\n NRSER::Props::Metadata.new( self )\n end\n \n NRSER::Props::Metadata.metadata_for self\n end",
"def metadata\n Hash.from_xml(self[:metadata])['hash']\n end",
"def metadata?\n true\n end",
"def meta_data\n @meta_data ||= @internal_struct[:meta_data]\n end",
"def metadata\n api_get(\"$metadata\").body\n end",
"def metadata\n Metadata.new(self)\n end",
"def meta\n json_body.fetch('meta', {})\n end",
"def set_individual_action_meta_information(args={})\n\t\t\t@title = args[:title]\n\t\t\t@meta_description = args[:description]\n\t\tend",
"def meta_data\n return nil unless success?\n\n @meta_data\n end",
"def metadata=(metadata)\n @metadata = metadata\n end",
"def metadata=(metadata)\n @metadata = metadata\n end",
"def metadata=(metadata)\n @metadata = metadata\n end",
"def metadata=(metadata)\n @metadata = metadata\n end",
"def type ; metadata[:type] ; end",
"def klass_attribute_to_metadata_attribute_map\n {\n :avalon_uploader => :creator,\n :avalon_publisher => :publisher,\n :title => :main_title,\n :alternative_title => :alternative_title,\n :translated_title => :translated_title,\n :uniform_title => :uniform_title,\n :statement_of_responsibility => :statement_of_responsibility,\n :creator => :creator,\n :date_created => :date_created,\n :date_issued => :date_issued,\n :copyright_date => :copyright_date,\n :abstract => :abstract,\n :note => :note,\n :format => :media_type,\n :contributor => :contributor,\n :publisher => :publisher,\n :genre => :genre,\n :subject => :topical_subject,\n :related_item => :related_item_id,\n :collection => :collection,\n :geographic_subject => :geographic_subject,\n :temporal_subject => :temporal_subject,\n :topical_subject => :topical_subject,\n :collection => :collection\n }\n end",
"def apply_extracted_metadata\n\n return if content_blob.nil? or content_type.nil?\n\n metadata = Workflow.extract_metadata(:type => content_type.title, :data => content_blob.data)\n\n self.title = metadata[\"title\"] if metadata[\"title\"] and title.nil?\n self.body = metadata[\"description\"] if metadata[\"description\"] and body.nil?\n self.image = metadata[\"image\"] if metadata[\"image\"] and image.nil?\n self.svg = metadata[\"svg\"] if metadata[\"svg\"] and svg.nil?\n end",
"def apply_extracted_metadata\n\n return if content_blob.nil? or content_type.nil?\n\n metadata = Workflow.extract_metadata(:type => content_type.title, :data => content_blob.data)\n\n self.title = metadata[\"title\"] if metadata[\"title\"] and title.nil?\n self.body = metadata[\"description\"] if metadata[\"description\"] and body.nil?\n self.image = metadata[\"image\"] if metadata[\"image\"] and image.nil?\n self.svg = metadata[\"svg\"] if metadata[\"svg\"] and svg.nil?\n end",
"def meta_data\n data = []\n data << \"@#{@mention}\" unless @mention.empty?\n data << Array.new(@priority + 1).join('!') if @priority > 0\n data\n end",
"def meta\n options[:meta]\n end",
"def metadata\n @metadata ||= lambda { read_metadata }.call\n end",
"def metadata\n @metadata ||= lambda { read_metadata }.call\n end",
"def doi_metadata\n # This must be mock_doi rather than any identifier defined in the object.\n # Otherwise users could manually specify a different identifier and\n # change records they're not supposed to.\n data = {:identifier => mock_doi}\n \n data[:alternate_identifier] = identifier.map do |identifier|\n next if identifier == full_mock_doi\n guess_identifier_type(identifier)\n end .compact\n\n if respond_to? :doi_published and doi_published\n data[:publication_year] = \"#{doi_published.year}\"\n else\n data[:publication_year] = \"#{Time.new.year}\"\n end\n\n data[:subject] =\n (subject.to_a.map do |e|\n { scheme:'FAST', schemeURI: 'http://fast.oclc.org/', label: e }\n end) +\n (tag.to_a.map do |e|\n { scheme: nil, schemeURI: nil, label: e}\n end)\n\n creator_role=Sufia.config.contributor_roles['Creator']\n data[:creator] = ((contributors_sorted.select do |c|\n c.role.include? creator_role\n end).select do |c|\n !c.marked_for_destruction?\n end).map do |c|\n { name: c.contributor_name.first,\n affiliation: c.affiliation\n }\n end\n\n data[:abstract] = abstract.to_a\n data[:research_methods] = research_methods.to_a\n data[:description] = description.to_a\n data[:funder] = funder.to_a\n data[:contributor] = contributors_sorted.reduce([]) do |a,c|\n # Creator role is converted to nil in contributor_role_to_datacite and then removed with compact\n next a if c.marked_for_destruction?\n roles=c.role.map do |r| contributor_role_to_datacite r end\n roles.compact!\n next a if roles.empty?\n roles.sort! # Roles must be sorted, otherwise authors might change arbitrarily\n roles.each do |r|\n a << {\n name: c.contributor_name.first,\n affiliation: c.affiliation,\n contributor_type: r\n }\n end\n a\n end\n\n\n data[:relatedIdentifier] = related_url.map do |url|\n # related field is now titled cited by, so use that as the relation type\n (guess_identifier_type url).tap do |ident| ident[:relation_type]='IsCitedBy' end\n end\n\n if self.class == GenericFile\n data[:title] = title\n data[:resource_type] = Sufia.config.resource_types_to_datacite[resource_type.first] # Only maping first choice from the list\n data[:size] = [content.size]\n data[:format] = [content.mime_type]\n data[:date_uploaded] = date_uploaded.strftime('%Y-%m-%d')\n data[:rights] = rights.map do |frights|\n {rights: Sufia.config.cc_licenses_reverse[frights], rightsURI: frights}\n end\n else #Add Collection metadata\n data[:title] = [title] # Collection returns string, XML builder expects array\n # FixMe: construct << {contributor, email}\n if not date_created.empty?\n data[:date_created] = Date.parse(date_created.first.to_s).strftime('%Y-%m-%d') unless date_created.empty?\n end\n data[:resource_type] = Sufia.config.resource_types_to_datacite['Collection']\n\n #Add members metadata\n# \t\t\tdata[:rights] = rights.map do |crights|\n# \t\t\t\t{rights: \"Collection rights - \" + Sufia.config.cc_licenses_reverse[crights], rightsURI: crights }\n# \t\t\tend\n# members.reduce(data[:rights]) do |a,mobj|\n data[:rights] = members.reduce([]) do |a,mobj|\n if member_visible? mobj\n if mobj.content.original_name.nil? then filename = mobj.id else filename = mobj.content.original_name end\n if mobj.rights.any?\n a << { # Do we allow for multiple licensing?\n rights: filename + \" - \" + Sufia.config.cc_licenses_reverse[mobj.rights[0]],\n rightsURI: mobj.rights[0]\n }\n else\n a\n end\n else\n a\n end\n end\n\n data[:format] = members.reduce([]) do |a,mobj|\n if member_visible? mobj\n if mobj.content.original_name.nil? then filename = mobj.id else filename = mobj.content.original_name end\n if mobj.content.mime_type.nil? then a end\n a << (filename + \" - \" + mobj.content.mime_type)\n else\n a\n end\n end\n\n data[:size] = members.reduce([]) do |a,mobj|\n if member_visible? mobj\n if mobj.content.original_name.nil? then filename = mobj.id else filename = mobj.content.original_name end\n if mobj.content.size then a end\n a << \"#{filename} - #{mobj.content.size}\"# Should we preatyfier file size in bytes?\n else\n a\n end\n end\n\n\n members.reduce(data[:relatedIdentifier]) do |a,mobj|\n if member_visible? mobj and mobj.respond_to? :doi_landing_page #FixMe: only public objects\n a << { id: mobj.doi_landing_page, id_type: 'URL', relation_type: 'HasPart' }\n else\n a\n end\n end\n end\n return data\n end",
"def metadata\n {:definitions => representer_attrs.grep(Definition).map {|definition| definition.name},\n :links => representer_attrs.grep(Link).map {|link| link.options[:as] ? {link.rel => {'as' => link.options[:as]}} : link.rel}\n }\n end",
"def include_meta_info\n true\n end",
"def metadata\n @page.metadata\n end",
"def meta\n @meta ||= decoded_body[:meta]\n end",
"def metadata\n\t\tif @meta.nil?\n\t\t\t@meta = @store.metadata @metric_id\n\t\t\t@meta = @source.metaadd @meta\n\t\tend\n\t\treturn @meta\n\tend",
"def generate_metadata\n data = Hash.new\n data['id'] = self.id\n data['title'] = self.title\n data['author'] = self.author\n data['updated_at'] = self.updated_at\n return data\n end",
"def search_attributes\n {:title => self.name, :description => self.bio.present? ? self.bio[0..100] : \"\", :image => self.portrait(:thumb)}\n end",
"def set_record_metatags! tags, record\n tags['title'] = record.name\n tags['description'] = record.excerpt if record.respond_to?(:excerpt)\n tags['og:url'] = wm_url_for(record)\n tags['og:type'] = 'article'\n tags['og:image'] = record.thumbnail.url if record.try(:thumbnail).present?\n tags['og:article:published_time'] = record.created_at.to_s(:db)\n tags['og:article:modified_time'] = record.updated_at.to_s(:db)\n tags['og:article:section'] = record.category&.name if record.is_a?(Article)\n tags['twitter:card'] = 'summary'\n\n set_locale_metatags!(tags, record) if record.try(:translatable?)\n set_static_page_metatags!(tags, record) if record.is_a?(StaticPage)\n set_video_metatags!(tags, record) if record.try(:vimeo_metadata).present?\n end",
"def metadata\n if any? && metadata_schema\n response = api('request',\n :uri => \"hm://metadata/#{resource_name}s\",\n :batch => true,\n :payload => map {|resource| {:uri => resource.metadata_uri}},\n :response_schema => metadata_schema\n )\n response['result']\n else\n []\n end\n end",
"def attributes\n @metadata\n end",
"def metadata\n {\n district_council: response[\"consellBarri\"]&.strip,\n district: response[\"barri\"]&.strip,\n document_number: document_number,\n }\n end",
"def artist_social(artist)\n\t #-----------For Artist Meta Tags----------------\n\n\t #Page Title, Facebook Title and Twitter Title\n\t @social_title = artist.name+\" on Three Repeater\"\n\t #Meta description (google), Facebook Description, and Twitter Card Description\n\t @social_descrip = artist.bio\n\n\t #logic around figuring out which facebook url is used\n\t facebook_url(artist)\n\n\t #Twitter ID\n\t @social_twitter_name = artist.twitter_name\n\n\t #Image for twitter and FB\n\t @social_image = artist.logo.to_s\n\n\t #------------------------------------------------\n\n end",
"def get_metadata(metadata_def = {})\n metadata_def.each { |k, v| @metadata[k] = v }\n\n case universe\n when :ebi, :ncbi, :web\n # Get taxonomy\n @metadata[:tax] = get_ncbi_taxonomy\n when :gtdb\n # Get taxonomy\n @metadata[:tax] = get_gtdb_taxonomy\n when :seqcode\n # Taxonomy already defined\n # Copy IDs over to allow additional metadata linked\n @metadata[:ncbi_asm] = @metadata[:seqcode_asm]\n @metadata[:ncbi_nuccore] = @metadata[:seqcode_nuccore]\n end\n\n if metadata[:get_ncbi_taxonomy]\n tax = get_ncbi_taxonomy\n tax&.add_alternative(@metadata[:tax].dup, false) if @metadata[:tax]\n @metadata[:tax] = tax\n end\n @metadata[:get_ncbi_taxonomy] = nil\n @metadata = get_type_status(metadata)\n end",
"def read_metadata\n raise NotImplementedError.new 'This is only a function body for documentation'\n end"
] |
[
"0.71635",
"0.71635",
"0.71635",
"0.71635",
"0.71635",
"0.71635",
"0.71635",
"0.7005023",
"0.67693895",
"0.6684788",
"0.6489462",
"0.64442337",
"0.64356923",
"0.63780254",
"0.6355773",
"0.6252556",
"0.6252556",
"0.6245898",
"0.62441194",
"0.6228329",
"0.6228329",
"0.62274486",
"0.6221595",
"0.6214384",
"0.6171194",
"0.6168139",
"0.61616325",
"0.6161086",
"0.61284596",
"0.6120847",
"0.6120847",
"0.6117914",
"0.6088001",
"0.60819286",
"0.6081785",
"0.6076271",
"0.60387444",
"0.6036575",
"0.603225",
"0.601859",
"0.60149384",
"0.60149384",
"0.60072166",
"0.60022026",
"0.6000024",
"0.59995013",
"0.5994492",
"0.5991916",
"0.5976839",
"0.5974096",
"0.597093",
"0.59695894",
"0.59631974",
"0.59336925",
"0.5930519",
"0.5921377",
"0.5921377",
"0.5905185",
"0.59027857",
"0.58993393",
"0.5880985",
"0.5878534",
"0.58783406",
"0.58627874",
"0.5859716",
"0.5850648",
"0.58445424",
"0.5841747",
"0.5831927",
"0.5829251",
"0.58286244",
"0.5826771",
"0.58020854",
"0.5794667",
"0.5793166",
"0.5793166",
"0.5793166",
"0.5793166",
"0.5792896",
"0.5786884",
"0.5783327",
"0.5783327",
"0.5774896",
"0.5774239",
"0.57731944",
"0.57731944",
"0.5769174",
"0.57606703",
"0.575911",
"0.5757032",
"0.5729635",
"0.57061535",
"0.5701697",
"0.5700164",
"0.56928414",
"0.5689589",
"0.56834984",
"0.56739455",
"0.56732965",
"0.5666539",
"0.5665917"
] |
0.0
|
-1
|
Example: Input: [2, 1, 3, 4, 1, 2, 1, 5, 4] Output: 6 Explanation: [4,1,2,1] has the largest sum = 6. Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
|
def max_sub_array(numbers)
max = numbers[0]
(1...numbers.size).each do |idx|
current_sum = numbers[idx] + numbers[idx - 1]
numbers[idx] = current_sum if current_sum > numbers[idx]
max = numbers[idx] if numbers[idx] > max
end
max
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def optimized_largest_subsum(arr)\n max = arr.first\n sum = arr.first \n arr.shift\n arr.each do |el|\n sum += el\n if el > max && el > sum \n max = el \n sum = el \n elsif sum > max\n max = sum\n end \n end \n max\nend",
"def largest_sum_arr_n2(arr)\n list = []\n i = 0\n while i < arr.length\n j = i\n while j < arr.length\n list.push arr[i..j]\n j += 1\n end\n i += 1\n end\n\n result = nil\n max = nil\n list.each do |a|\n current_sum = a.inject(:+)\n if max.nil? || current_sum > max\n result = a\n max = current_sum\n end\n end\n result\nend",
"def largest_subsum(list)\n max = list[0] # O(1)\n current_sum = list[0] # O(1)\n\n (1...list.length).each do |i| # O(n)\n # debugger\n if current_sum < 0 # O(1)\n current_sum = 0 # O(1)\n end \n current_sum += list[i] # O(1)\n if current_sum > max # O(1)\n max = current_sum # O(1)\n end\n end\n\n max # O(1)\n\nend",
"def largest_cont_subsum_slow(list) # n = list.length\n subarrs = find_subarrays(list) # n^2 runtime\n largest = subarrs[0].sum\n \n subarrs.each do |subarr| # n^2 length subarrs\n largest = [largest, subarr.sum].max # constant\n end\n\n return largest\n # n^2 overall\nend",
"def solve(array)\n largest_sum = 0\n\n array.each_with_index do |element, index|\n current_largest_sum = 0\n if element > 0\n current_largest_sum += element\n\n array[index..(-1)].each do |el|\n current_largest_sum += el if el > element\n end\n current_largest_sum -= element\n largest_sum = current_largest_sum if current_largest_sum > largest_sum\n end\n end\n largest_sum\nend",
"def max_sub_array(nums)\n current_sum = nil\n max_sum = nil\n \n nums.each do |n|\n if current_sum.nil?\n current_sum = n\n elsif current_sum + n < n\n current_sum = n\n else\n current_sum = current_sum + n\n end\n max_sum = current_sum if max_sum.nil? || current_sum > max_sum\n end\n max_sum\nend",
"def largest_contiguous_sub_sum1(list)\n max = list[0]\n (0...list.length).each do |i|\n (i...list.length).each do |j| \n sub_sum = list[i..j].sum \n max = sub if sub >= max \n end\n end\n max\nend",
"def largest_continous_subsum\n largest = 0\n subsets = []\n\n i = 0\n while i < self.length\n j = i\n while j < self.length\n subsets << self[i..j]\n j += 1\n end\n i += 1\n end\n\n subsets.each do |pair|\n if largest < pair.reduce(:+)\n largest = pair.reduce(:+)\n end\n end\n largest\n\n end",
"def largest2(list)\n time = Time.now\n largest_sum = list.max\n sum = 0\n list.each do |el|\n sum += el\n if sum < 0\n sum = 0\n end\n if largest_sum < sum\n largest_sum = sum\n end\n end\n p Time.now - time\n return list.max if sum <= 0\n return largest_sum\nend",
"def better_largest_contiguous_subsum(list)\n current_largest_sum = 0\n current_sum = 0\n return list.max if list.all? {|ele| ele < 0}\n\n (0...list.length).each do |i |\n # debugger\n #add current element to current sum\n current_sum += list[i]\n\n #if current sum is less than 0 ignore it and reset to move on to next number\n if ( current_sum < 0 ) \n current_sum = 0\n end \n # if current sum is greater than our current largest sum, we want to keep it\n if current_sum > current_largest_sum\n current_largest_sum = current_sum\n end\n end\n current_largest_sum\nend",
"def sub_sum_better(list)\n largest_sum = list.first\n\n #iterate over once.\n # as you iterate keep a tally of the sum.\n # indexing into an array is O(1)\n # [2, 3, -6, 7, -6, 7]\n\n sub_sum = 0\n list.each do |el|\n sub_sum += el\n largest_sum = sub_sum if sub_sum > largest_sum\n\n sub_sum = 0 if sub_sum < 0\n end\n\n largest_sum\nend",
"def opt_max_sum(arr)\n result = -1000\n (0...arr.length).each do |start|\n sum = 0\n (1..arr.length).each do |size|\n if start + size > arr.length\n break\n end\n sum += arr[start + size - 1]\n if sum > result\n result = sum\n end\n end\n end\n return result\nend",
"def better_largest_sub_sum(array)\n largest_sum = 0\n current_sum = 0\n array.each_with_index do |el, idx|\n current_sum += el\n current_sum = 0 if current_sum < 0\n largest_sum = current_sum if current_sum > largest_sum\n end\n largest_sum\nend",
"def largest_sum_better(arr)\n largest_sum = arr.first\n current = arr.first\n\n (1...arr.length).each do |idx|\n if current < 0\n current = 0\n end\n\n current += arr[idx]\n \n if current > largest_sum\n largest_sum = current\n end\n end\n\n largest_sum\nend",
"def largest_contiguous_subsum(list)\n max_sum = list[0]\n\ttemp_sum = list[0]\n\tdebugger\n #0(n) #note: only n^2 if nested\n \n return list.max if list.all? { |ele| ele < 0 } \n #need to add O(1) return case\n # Write a new function using O(n) time with O(1) memory. Keep a running tally of the largest sum.\n\n list_2 = list.drop(1)\n list_2.each do |ele|\n\t\ttemp_sum = [ele, temp_sum + ele].max #O(1) operation, should refactor \n #temp_sum = ele = 4, temp_sum = 1+3, [4, 8].max\n # [3, -7]\n #[3, 5 + 3] = > 3, 8 = > 8 max = 5\n #[-7, 8 - 7] => 1, 1 = > 1 max = 8\n max_sum = temp_sum if temp_sum > max_sum\n\tend\n\t\n\tmax_sum\nend",
"def largest_contiguous_subsum(list) # O(n^2)\n array = []\n list.each_with_index do |ele1, i1| # O(n^2)\n (i1...list.length).each do |i2|\n array << list[i1..i2]\n end\n end\n\n max_sum = array.first.sum\n array[1..-1].each do |subarr| # O(n^2)\n sum = subarr.sum\n if sum > max_sum\n max_sum = sum\n end\n end\n\n max_sum\n\nend",
"def largest_continuous_subsum(list)\n curr_sum = 0\n max_sum = list.first\n list.each do |el|\n curr_sum += el\n if curr_sum > max_sum\n max_sum = curr_sum\n end\n\n if curr_sum < 0\n curr_sum = 0\n end\n end\n max_sum\nend",
"def largest_cont_subsum_fast(list)\n # for constant size to be true, you cant create any variables\n # whose memory size depends on the size of the input\n curr_sum = list[0]\n largest_sum = list[0]\n\n # we know there are n^2 potential, so if we ever check all of them\n # it must be n^2\n\n # there must be a way to find the max without checking every subarray\n list[1..-1].each do |ele|\n # debugger\n if curr_sum > largest_sum\n largest_sum = curr_sum\n end\n\n if curr_sum < 0\n curr_sum = 0\n end\n\n curr_sum += ele\n\n end\n\n # debugger\n return [largest_sum, curr_sum].max\n\nend",
"def solve(nums)\n sorted = nums.sort\n largest = 0\n (0...sorted.length - 1).each do |i|\n if (sorted[i+1] - sorted[i]) > largest\n largest = (sorted[i+1] - sorted[i])\n end\n end\n return largest\n\nend",
"def largest_contiguous_subsum_1(list)\n subs = []\n (0...list.length).each do |idx| #O(n)\n (idx...list.length).each do |idx_2| #O(n)\n subs << list[idx..idx_2] #O(n)\n end\n end\n max = list.first\n subs.each do |subarr|\n if subarr.sum > max\n max = subarr.sum\n end\n end\n max\nend",
"def largest_contiguous_subsum(list)\n current_max = list[0]\n current_sum = list[0]\n\n (1...list.size).each do |i|\n current_sum += list[i]\n if current_sum > current_max\n current_max = current_sum\n end\n\n if current_sum < 0 \n current_sum = 0\n end\n \n end\n\n current_max\nend",
"def largest_contiguous_subsum(arr) #BigO of O(n)\n max = 0 \n current_sum = 0\n arr.each_with_index do |el,idx|\n if current_sum + el >= el \n current_sum += el \n else \n current_sum = el \n end \n max = current_sum if current_sum > max \n end \n max\nend",
"def largest_contiguous_subsum(list)\r\n max_val = 0 #8\r\n current_sum = 0 #8\r\n list.each do |num|\r\n current_sum = [0, current_sum + num].max\r\n max_val = [max_val, current_sum].max\r\n end\r\n return max_val\r\nend",
"def largest_cont_sum(array)\n return nil if array.empty?\n \n max_sum = 0\n current_max_sum = 0\n\n array.each do |number|\n current_max_sum = [current_max_sum + number, number].max\n max_sum = [current_max_sum, max_sum].max\n end\n\n max_sum\nend",
"def largest_contiguous_subsum_2(list)# [2, 3, -6, 7, -6, 7]\n largest_num = list[0]#2 O(1)\n running_sum = list[0]#2 - 5 after entering loop. O(1)\n\n (1...list.length).each do |i| #O(n) \n running_sum = 0 if running_sum < 0 #O(1)\n running_sum += list[i] #O(1)\n largest_num = running_sum if running_sum > largest_num #O(1)\n end\n return largest_num #O(1)\nend",
"def largest_sub_sum_linear(arr)\n largest = arr.first\n current = arr.first\n\n return arr.max if arr.all? { |num| num < 0 }\n i = 1\n\n while i < arr.length\n current = 0 if current < 0\n current += arr[i]\n largest = current if current > largest\n i+=1\n end\n\n largest\n end",
"def largest_contigous_subsum_ii(list)\n current_sum = list.first\n max = list.first\n (1..-1).each do |i|\n current_sum += list[i]\n current_sum = 0 if current_sum < 0\n max = current_sum if max < current_sum\n end\n current_sum\nend",
"def largest_contiguous_subsum(list) \n subs = []\n\n (0...list.length).each do |i|\n (i...list.length).each do |j|\n sub = list[i..j]\n subs << sub\n end\n end\n \n max = nil\n\n subs.each do |sub|\n sum = sub.sum \n if max == nil || sum > max\n max = sum\n end\n end\n max\nend",
"def largest_sub_sum1 #0(n^2)\n result = []\n (0...self.length).each do |idx1|\n (idx1...self.length).each do |idx2|\n subarray_result = self[idx1..idx2]\n result << subarray_result\n end\n end\n\n largest_sum = result[0][0]\n result.each do |arr|\n largest_sum = arr.sum if arr.sum > largest_sum\n end\n largest_sum\n end",
"def largest_contiguous_subsum1(list)\n greatest_sum = -1.0/0.0\n (0...list.length).each do |i|\n (i...list.length).each do |j|\n greatest_sum = list[i..j].sum if greatest_sum < list[i..j].sum\n end\n end\n greatest_sum\nend",
"def largest_contiguous_subsum_2(list)\n current_sum = 0\n largest_sum = 0\n (0...list.length).each do |idx|\n current_sum += list[idx]\n largest_sum = current_sum if current_sum > largest_sum\n current_sum = 0 if current_sum < 0\n end\n largest_sum\nend",
"def largest_contiguous_subsum(nums)\n running_sum = 0\n max = nums.first || 0\n\n nums.each do |n|\n running_sum += n\n max = running_sum if max < running_sum\n running_sum = 0 if running_sum < 0\n end\n max\nend",
"def largest_contiguous_subsum_2(list)\n largest_sum = 0\n current_sum = 0\n\n list.each do |el|\n largest_sum = current_sum \n current_sum += el \n if current_sum < el \n current_sum = el \n end \n largest_sum = current_sum if largest_sum < current_sum\n end\n\n largest_sum\nend",
"def largest(list)\n time = Time.now\n arr = []\n list.each_with_index do |el, i|\n list.each_with_index do |el2, i2|\n arr << list[i..i + i2]\n end\n end\n max = arr[0].sum\n arr.each do |el|\n max = el.sum if el.sum > max\n end\n puts Time.now - time\n max\nend",
"def max_2_sum(a)\n a.length > 0 ? a.sort.pop(2).inject(:+) : 0\nend",
"def largest_contiguous_subsum_two(list)\n largest_sum = list[0]\n current_sum = 0\n # list.inject {|acc, ele| acc + ele}\n list.each do |ele|\n current_sum = [ele, current_sum + ele].max\n largest_sum = [largest_sum, current_sum].max\n end\n largest_sum\nend",
"def max_2_sum arr\n return 0 if arr.empty?\n return arr.first if arr.size == 1\n arr.sort.pop(2).inject(:+)\nend",
"def largest_contiguous_subsum_v2(arr) # O(n)\n\n largest_sum = arr[0]\n current_sum = arr[0]\n \n (1...arr.length).each do |i|\n if current_sum < 0\n if current_sum < arr[i]\n current_sum = arr[i]\n end\n else\n current_sum += arr[i]\n end\n if current_sum > largest_sum\n largest_sum = current_sum\n end\n end\n largest_sum\nend",
"def largest_contiguous_subsum1(list)\n arr = []\n (0...list.length).each do |i|\n (i...list.length).each { |j| arr << list[i..j] }\n end\n largest_sum = arr.first.sum\n arr.each do |sub_arr|\n largest_sum = sub_arr.sum if sub_arr.sum > largest_sum\n end\n largest_sum\nend",
"def largest_contiguous_subsum_good(arr) \n last_max = arr.first\n current_max = 0\n arr.each do |num|\n temp_sum = current_max + num\n if temp_sum < 0\n last_max = current_max if temp_sum > last_max\n else\n if temp_sum > last_max\n last_max = temp_sum\n end\n end\n if num > temp_sum\n current_max = num\n else\n current_max = temp_sum\n end\n end\n last_max\nend",
"def find_sum(array)\n max = 0\n temp_array = array.clone\n (1...array.length).each do |i|\n (0...i).each do |j|\n if (array[i] > array[j] && temp_array[i] < temp_array[j] + array[i])\n temp_array[i] = temp_array[j] + array[i]\n end\n end\n end\n (0...array.length).each do |k|\n max = temp_array[k] if temp_array[k] > max\n end\n return max\nend",
"def largest_contiguous_sub_sum3(arr)\n\n largest_sum = arr.first\n current_sum = arr.first\n\n (1...arr.length).each do |index|\n current_num = arr[index]\n prev_num = arr[index-1]\n\n if largest_sum < current_num\n largest_sum = current_num\n end\n\n current_sum = current_sum + current_num\n prev_sum = prev_num + current_num\n\n if prev_sum > current_sum\n current_sum = prev_sum\n end\n\n if largest_sum < current_sum\n largest_sum = current_sum\n end\n end\n largest_sum\nend",
"def largest_contiguous_subsum(list)\n prev_max = -9999999999999\n new_max = 0\n list.each do |ele|\n new_max += ele\n prev_max = new_max if prev_max <= new_max\n new_max = 0 if new_max < 0 # Reset\n end\n prev_max\nend",
"def largest_contiguous_subsum(list)\n max_sum = list.first\n current_sum = list.first\n \n (1...list.length).each do |i| \n current_sum = 0 if current_sum < 0 \n current_sum += list[i]\n max_sum = current_sum if current_sum > max_sum\n end\n max_sum\nend",
"def largest_contiguous_subsum(list)\r\n \r\n largest = -1*Float::INFINITY\r\n current_sum = 0\r\n\r\n list.each do |num|\r\n if (current_sum += num ) < 0\r\n current_sum = 0\r\n if largest < num\r\n largest = num\r\n end\r\n else\r\n largest = current_sum if largest < current_sum\r\n end\r\n end\r\n largest\r\n # last_idx = 0\r\n # list.each_with_index do |e, i|\r\n # if current_sum < 0 || (current_sum += e) > largest\r\n # last_idx = i \r\n # largest = current_sum > 0 ? current_sum : e\r\n # end\r\n # end\r\n # p largest\r\n # p last_idx\r\n # largest = -1*Float::INFINITY\r\n # current_sum = 0\r\n\r\n # last_idx.downto(0).each do |i|\r\n # if current_sum < 0 || (current_sum += list[i]) > largest\r\n # largest = current_sum > 0 ? current_sum : list[i]\r\n # end\r\n # end\r\n\r\n # largest\r\nend",
"def best_largest_contiguous_subsum(arr)\n return arr.max if arr.max < 0\n largest = 0\n current = 0\n\n\n (0..(arr.length-1)).each do |idx1|\n if current + arr[idx1] < 0\n current = arr[idx1]\n else\n current += arr[idx1]\n end\n\n largest = current if current > largest\n end\n largest\nend",
"def largest_cont_subsum(list)\n biggest = list[0]\n current = 0\n\n (0...list.length).each do |i|\n current += list[i]\n biggest = current if current > biggest\n end\n biggest\nend",
"def largest_contiguous_subsum(list)\n largest_sum = 0\n current_sum = list[0]\n (1...list.length).each do |i|\n current_sum = 0 if current_sum < 0 #we need to reset current sum if we hit a negative number\n current_sum += list[i]\n largest_sum = current_sum if current_sum > largest_sum\n end\n largest_sum\nend",
"def max_sub(a)\na[(0...(n=a.size)).inject([]){|r,i|(i...n).inject(r){|r,j|r<<(i..j)}}.sort_by{|r|a[r].inject{|i,j|i+j}}[-1]]\nend",
"def max_sub_array(arr)\n current_sum = arr[0]\n max_sum = current_sum\n\n arr[1..-1].each do |num|\n current_sum = [num, current_sum + num].max\n max_sum = [max_sum, current_sum].max\n end\n\n return max_sum\nend",
"def max_2_sum(array)\n sum array.sort.last(2)\nend",
"def largest_contiguous_subsum2(list)\n largest_sum = list[0]\n current_sum = 0\n# list = [2, 3, -6, 7, -6, 7]\n list.each do |number|\n current_sum += number\n if current_sum > largest_sum\n largest_sum = current_sum\n elsif current_sum < 0\n current_sum = 0\n end\n end\n largest_sum\nend",
"def max_2_sum(array)\n sum(array.sort.last(2))\nend",
"def largest_contiguous_subsum_2(list)\n largest_sum = list.first\n current_sum = 0\n list.each do |ele| \n current_sum += ele\n if current_sum > largest_sum\n largest_sum = current_sum\n end\n current_sum = 0 if current_sum < 0 \n end\n largest_sum\nend",
"def maxSubArray(a)\n return nil if a.empty?\n curr_sum = a[0]\n max_sum = a[0]\n (1...a.length).each do |i| \n if curr_sum <= 0\n curr_sum = a[i]\n else\n curr_sum += a[i]\n end\n max_sum = curr_sum if max_sum < curr_sum\n end\n max_sum\nend",
"def largest_continguous_subsum(arr)\n largest_sum = arr.first\n current_sum = arr.first\n \n (1...arr.length).each do |i|\n current_sum += arr[i]\n if current_sum > largest_sum\n largest_sum = current_sum\n elsif current_sum < 0\n current_sum = 0\n end\n end\n largest_sum\nend",
"def largest_con_subsum_2(list)\n largest = list.first\n contiguous_sum = list.first\n\n i = 1\n \n while i < list.length\n current = list[i]\n contiguous_sum += current\n if contiguous_sum > largest\n largest = contiguous_sum \n elsif current > largest\n largest = current\n \n end\n contiguous_sum = 0 if contiguous_sum < 0\n i += 1 \n \n end\n return largest\nend",
"def sum_of_two_largest_numbers(arr)\n arr.max(2).reduce(:+)\nend",
"def largest_contiguous_subsum_2(arr)\n sum = 0\n max = 0\n arr.each do |num|\n sum += num\n if sum > 0\n max = sum if sum > max\n else\n sum = 0\n end\n end\n max\nend",
"def largest_contiguous_subsum(list) # O(n^2)\n subs_sums = []\n\n list.each_index do |i|\n list.each_index do |j|\n next if j < i\n subs_sums << list[i..j]\n end\n end\n\n highest_array_sum = nil\n subs_sums.each do |array|\n array_sum = array.reduce(:+)\n if highest_array_sum == nil || array_sum > highest_array_sum\n highest_array_sum = array_sum\n end\n end\n\n highest_array_sum\nend",
"def largest_sub_sum(array)\n subsets = []\n i = 0\n while i < array.length\n j = i\n while j < array.length\n subsets << array[i..j]\n j += 1\n end\n i += 1\n end\n result = nil\n subsets.map {|subset| subset.inject(:+)}.each do |sum|\n result = sum if result.nil? || result < sum\n end\n result\nend",
"def largest_contiguous_subsum2(list)\n sum = 0 # keeps track of current sum\n largest_sum = list.first # evaluates to the largest sum\n list.each do |ele|\n sum += ele \n largest_sum = sum if sum > largest_sum\n sum = 0 if sum < 0\n end\n largest_sum\nend",
"def max_sum_of_subarray(arr)\n current_max = global_max = arr.first\n array_size = arr.size\n\n (1..(array_size-1)).each do |i|\n current_max = [arr[i], current_max + arr[i]].max\n\n if current_max > global_max\n global_max = current_max\n end\n end\n\n global_max\nend",
"def better_largest_contiguous_subsum(list)\n total_sum = list.first\n current_sum = list.first\n\n list.each_index do |idx| \n current_sum = [list[idx], current_sum + list[idx]].max\n total_sum = [total_sum, current_sum].max\n end\n\n return total_sum\nend",
"def largest_contiguous_sub_sum2(arr)\n #one varable tracks largest sum\n #one variable tracks current sum\n #O(n) + O(1)\n # list = [2, 3, -6, 7, -6, 7]\n\n # largest_sum= arr.first\n\n # i = 0\n # arr_end = true\n\n # while arr_end\n # current_sum = arr[i]\n # if arr[i+1] == nil\n # arr_end = false\n # puts \"This is current sum: #{current_sum}\"\n # else\n # if current_sum > largest_sum\n # current_sum += arr[i+1]\n # largest_sum = current_sum\n # end\n # end\n # if i < arr.length\n # arr_end = true\n # i += 1\n # end\n # end\n # largest_sum\n \n\n\n # arr.each_with_index do |ele, idx|\n # if ele > largest_sum\n # largest_sum = ele\n # end\n\n # i = idx\n # sum = ele\n # while i < arr.length - 1\n # if sum <= sum + arr[i+1]\n # largest_sum = sum + arr[i+1]\n # end\n # sum = sum + arr[i+1]\n # i+=1\n # end\n # end\n # largest_sum\n\nend",
"def largest_contiguous_subsum(arr)\n max = 0\n\n (0...arr.count).each do |i|\n sum = arr[i]\n (i + 1...arr.count).each do |j|\n sum += arr[j]\n max = sum if max < sum \n end \n end \n\n max\nend",
"def max_sub_array(array)\n max_sum = current_val = array[0]\n array.each_with_index do |num, i|\n if (i > 0)\n sum = current_val + num\n if (sum > num)\n current_val = sum\n else\n current_val = num\n end\n if current_val > max_sum\n max_sum = current_val\n end\n end\n end\n max_sum\nend",
"def largest_contiguous_subsum_fast(list)\n start = Time.now\n max_sum = list[0]\n cur_sum = list[0]\n list[1..-1].each do |el|\n if el >= cur_sum && cur_sum < 0\n cur_sum = el\n else\n cur_sum += el\n end\n max_sum = cur_sum if cur_sum > max_sum\n end\n finish = Time.now\n puts \"Runtime: #{finish - start}\"\n return max_sum\nend",
"def better_subsum(arr)\n largest_sum = arr.first\n current_sum = arr.first\n\n \n # return arr[0] if arr.length == 1\n \n # current_sum = better_subsum(arr[1..-1])+ arr[0]\n\n # if current_sum > largest_sum\n # largest_sum = current_sum\n # end\n\n # largest_sum\n\n # i = 0\n # j = arr.length\n # while i < arr.length\n\n # arr[i..j].sum\n # j-=1\n # i+=1\n # end\n \n (1...arr.length).each do |idx|\n if arr[idx] + current_sum > 0\n current_sum += arr[idx]\n largest_sum = current_sum if current_sum > largest_sum\n else\n current_sum = 0\n end\n end\n\n largest_sum\nend",
"def phase_2_largest_contiguous_sum(arr)\n\n return [[]] if arr.empty?\n subs = arr.take(arr.count-1).phase_2_largest_contiguous_sum\n subs.concat(subs.map {|sub| sub + [last]})\n\n largest_sum = subs.first.sum \n\n subs.each do |sub|\n current_sum = sub.sum \n if current_sum > largest_sum\n largest_sum = current_sum\n end\n end\n\n largest_sum\n\nend",
"def max_2_sum arr\n sum(arr.sort.last(2))\nend",
"def largest_contig_subsum(nums)\n max = nil\n nums.each_with_index do |num, i|\n j = i\n while j < nums.length\n if !max || nums[i..j].sum > max\n max = nums[i..j].sum\n end\n j += 1\n end\n end\n max\nend",
"def subsum_fast(arr)\n max_subsum = arr.first\n last = nil\n\n arr.all? { |n| return arr.max if n < 1 }\n arr[1..-1].each do |n|\n if last\n if last < 0\n last = n\n elsif last > 0\n last = last + n\n end\n\n if last > max_subsum\n max_subsum = last\n last = nil\n end\n\n else\n checking = max_subsum + n\n if checking >= max_subsum\n max_subsum = checking\n elsif checking != 0\n last = checking\n end\n end\n end\n\n max_subsum\nend",
"def max_2_sum arr\n if arr.count > 1 \n arr_ord = arr.sort \n return arr_ord[-1] + arr_ord[-2]\n elsif arr.count == 1\n return arr[0]\n else\n return 0\n end\nend",
"def largest_contiguous_subsum2(list)\n result = list.first\n sum = list.first\n\n list.each_with_index do |n, i|\n next if i == 0\n\n sum = 0 if sum < 0\n\n sum += n\n\n result = sum if sum > result\n end\n\n result\nend",
"def largest_subsum_p2(arr)\n max_sum = 0\n arr.each do |el|\n temp = max_sum + el\n temp = 0 if temp < 0\n max_sum = temp if temp > max_sum\n end\n\n if max_sum == 0\n # all the nums are negative\n max_sum = arr[0]\n arr.each do |el|\n max_sum = el if el > max_sum\n end\n end\n\n max_sum\nend",
"def sub_array_sum(nums)\n greatest_sum = nums.first\n current_sum = 0\n nums.each do |num|\n current_sum += num\n greatest_sum = current_sum if current_sum > greatest_sum\n current_sum = 0 if current_sum < 0\n end\n greatest_sum\nend",
"def largest_contiguous_subsum2(array)\n # return [list[0]] if list.count == 1\n #\n # start_num = list.shift\n # large_sum = start_num\n #\n # other_list = list.dup\n #\n # idx = 0\n # while idx < list.count\n # sum = list[0..idx].inject(:+)\n # if large_sum < start_num + sum\n # large_sum = start_num + sum\n # end\n # idx += 1\n # end\n #\n # [large_sum] + largest_contiguous_subsum2(other_list)\n\n largest = nil\n current = 0\n\n array.each do |el|\n current += el\n if largest.nil? || current > largest\n largest = current\n end\n current = 0 if current < 0\n end\n\n largest\n\nend",
"def largest_contiguous_subsum_n(list2)\n large = 0\n \n list2.inject do |sum, n|\n if (sum + n) > sum\n sum += n \n large = sum if sum > large\n sum\n else\n sum = 0\n end\n end\n\n large\nend",
"def largest_contiguous_subsum(arr)\n current_sum = arr.first \n max_sum = arr.first \n (0...arr.length-1).each do |i|\n if current_sum < 0 \n current_sum = [current_sum, arr[i+1]].max\n max_sum = current_sum\n else \n current_sum += arr[i+1]\n max_sum = [current_sum, max_sum].max\n end \n end \n max_sum\nend",
"def max_2_sum array\n # return 0 if array.empty?\n # return array[0] if array.length == 1\n # array.sort![-1] + array[-2]\n array.length > 0 ? array.sort.pop(2).inject(:+) : 0\nend",
"def largest_contiguous_subsum(array)\r\n max = array.first \r\n current_sum = 0\r\n array.each do |ele|\r\n current_sum += ele\r\n max = current_sum if current_sum > max\r\n current_sum = 0 if current_sum < 0\r\n end\r\n max\r\nend",
"def max_2_sum arr\n if arr.empty?\n return 0\n elsif arr.size==1\n return arr[arr.size-1]\n else\n arr=arr.sort\n return arr[arr.size-1]+arr[arr.size-2]\n end\nend",
"def largest_contiguous_subsum2(list)\n # O(N) ==> Time\n # O(1) ==> Space\n largest = list.first\n curr = list.first\n\n len = list.length\n (1...len).each do |i|\n curr = 0 if curr < 0 \n curr += list[i]\n largest = curr if curr > largest\n end\n largest\nend",
"def sub_sum(list)\n array = []\n (0...list.length).each do |idx1|\n (idx1...list.length).each do |idx2|\n array << list[idx1..idx2] #O(n)\n end\n end \n array.map {|sub| sub.length > 1 ? sub.sum : sub.first}.max\nend",
"def largest_contiguous_subsum(array)\n current_sum = array.first\n largest_sum = array.first\n array.each do |num|\n current_sum += num\n if largest_sum < current_sum\n largest_sum = current_sum\n end\n end\n largest_sum\nend",
"def max_2_sum arr\n # arr.max(2).sum()\n return arr.sort.reverse[0,2].sum() # 내림차순 sort하고 2개 합\nend",
"def max_2_sum arr\n sum(arr.sort.last(2)) \nend",
"def largest_contiguous_subsum_v2(list)\n largest_sum = list.first\n sum = list.first # but the first element can be a negative number\n\n (1...list.length).each do |i|\n # a negative number + a postive number always less than pos number on its own\n sum = 0 if sum < 0 # if we add to a negative sum, then result is less than pos number on its own\n sum += list[i]\n largest_sum = sum if largest_sum < sum\n end\n\n largest_sum\nend",
"def max_slice_sum(a)\n n = a.length - 1\n result = nil\n\n (0..n).each do |p|\n sum = 0\n\n (p..n).each do |q|\n sum += a[q]\n result = result.nil? ? sum : [result, sum].max\n end\n end\n result\nend",
"def largest_contiguous_subsum(arr)\n max = arr.first\n arr.each_index do |idx1|\n (idx1+1..arr.length).each do |idx2|\n sub_arr = arr[idx1...idx2]\n sum = sub_arr.reduce(:+)\n max = sum if max < sum \n end\n\n end\n max\nend",
"def largest_contiguous_subsum(list)\n max_sum = 0\n i = 0\n while i < list.size\n curr_sum = list[0..i].take(i).sum #take from front\n max_sum = curr_sum if curr_sum > max_sum\n\n curr_sum = list[i..-1].take(i).sum #take from front\n max_sum = curr_sum if curr_sum > max_sum\n\n curr_sum = list[0..i].drop(i).sum #drop from back\n max_sum = curr_sum if curr_sum > max_sum\n\n curr_sum = list[i..-1].drop(i).sum #drop from back\n max_sum = curr_sum if curr_sum > max_sum\n\n curr_sum = list[i..-i].take(i).sum #take from front\n max_sum = curr_sum if curr_sum > max_sum\n\n curr_sum = list[i..-i].drop(i).sum #drop from back\n max_sum = curr_sum if curr_sum > max_sum\n\n i += 1\n end\n max_sum\nend",
"def largest_contiguous_subsum2(int_list)\n largest_sum = int_list.first\n curr_sum = int_list.first\n\n (1...int_list.length).each do |idx|\n curr_sum = (int_list[idx] > curr_sum + int_list[idx]) ? int_list[idx] : curr_sum + int_list[idx]\n largest_sum = curr_sum if curr_sum > largest_sum\n end\n\n largest_sum\nend",
"def largest_contiguous_subsum(arr)\n max = arr[0]\n current = 0\n (0...arr.length).each do |i|\n current += arr[i]\n max = current if current > max\n current = 0 if current < 0\n end\n max\nend",
"def largest_contiguous_subsum(list)\n rolling_sum = 0\n largest_sum = list[0]\n # reset the index if rolling sum to 0\n list.each_with_index do |el, idx| # Go through the array once\n rolling_sum += el # Keep a rolling sum and add current element to it\n largest_sum = rolling_sum if rolling_sum > largest_sum # Update the largest sum if your current rolling sum is greater (new largest rolling_sum)\n rolling_sum = 0 if rolling_sum < 0 # Reset your rolling sum back to 0 if your rolling_sum is negative (negative means you won't be able to cancel out, so you need to reset it)\n end\n return largest_sum\n\nend",
"def miniMaxSum(arr)\n arr.sort!\n sum = 0\n arr.each {|item| sum+=item}\n puts \"#{sum-arr[-1]} #{sum-arr[0]}\"\nend",
"def largest_contiguous_sum(arr)\n largest_sum = nil\n p_tations = subsets(arr)\n\n p_tations.each do |tation|\n if largest_sum == nil\n largest_sum = tation.sum \n elsif tation.sum > largest_sum\n largest_sum = tation.sum \n end\n end \n\n largest_sum\nend",
"def largest_contiguous_subsum(arr)\n max_sum = arr.first\n\n (0...arr.length).each do |start|\n (start...arr.length).each do |ending|\n sum = arr[start..ending].sum\n max_sum = sum if sum > max_sum\n end\n end\n\n max_sum\nend",
"def largest_contiguous_subsum(list)\n helper_arr = [list.first]\n (1...list.length).each do |idx|\n if helper_arr[-1] + list[idx] > list[idx]\n helper_arr << helper_arr[-1] + list[idx]\n else\n helper_arr << list[idx]\n end\n end\n helper_arr.max\nend",
"def max_sub_array3(nums)\n max_sum = nums[0]\n\n (1...nums.size).each do |i|\n # nums[i] 记录到该位置时,可能获得的最大和\n # 如果前面的一个是正的,那么就加上\n # 如果前面的是付的,那么就保留当前值\n nums[i] += nums[i - 1] if nums[i - 1] > 0\n max_sum = [nums[i], max_sum].max\n end\n p nums\n p nums.max\n max_sum\nend",
"def largest_contiguous_subsum(list)\n # O(N*M) ==> Time\n # O(N*M) ==> Space\n sub_arrs = sub_arrays_of(list) # O(N^3)\n sums = []\n sub_arrs.each do |sub_arr| ## O(N*M)\n sums << sub_arr.sum\n end\n # Get the max of the sums array\n sums.max # O(N)\nend"
] |
[
"0.77887315",
"0.7764424",
"0.769981",
"0.763341",
"0.7622439",
"0.7581459",
"0.7525786",
"0.7488166",
"0.7477562",
"0.7471363",
"0.7465058",
"0.7457307",
"0.7452194",
"0.74472725",
"0.7442229",
"0.74417573",
"0.7439776",
"0.7425036",
"0.742079",
"0.7418939",
"0.7398655",
"0.7398243",
"0.7392028",
"0.73883265",
"0.7377143",
"0.7373835",
"0.7370591",
"0.73692185",
"0.73557574",
"0.73549676",
"0.7343877",
"0.73343855",
"0.731541",
"0.73131067",
"0.73127335",
"0.73113835",
"0.7299981",
"0.7296902",
"0.72890365",
"0.7282635",
"0.72812617",
"0.7275066",
"0.72726357",
"0.7272418",
"0.7266663",
"0.7253501",
"0.725339",
"0.7252602",
"0.7251448",
"0.72501945",
"0.7247739",
"0.7246044",
"0.7244036",
"0.7243665",
"0.724315",
"0.7230602",
"0.7224507",
"0.7218242",
"0.72161806",
"0.7209302",
"0.72070116",
"0.720225",
"0.72004443",
"0.7191539",
"0.7191141",
"0.7188253",
"0.71815246",
"0.717862",
"0.717172",
"0.71678776",
"0.71615505",
"0.7160626",
"0.71504194",
"0.71442723",
"0.71420145",
"0.7140045",
"0.7136868",
"0.7133901",
"0.7133897",
"0.71313435",
"0.71294874",
"0.71260196",
"0.71233076",
"0.7120083",
"0.71155643",
"0.7111014",
"0.7108431",
"0.71065265",
"0.7101843",
"0.70993745",
"0.7093699",
"0.70921034",
"0.7090611",
"0.7087579",
"0.70838475",
"0.7080763",
"0.70804065",
"0.7077814",
"0.7073668",
"0.70690477",
"0.70662737"
] |
0.0
|
-1
|
call from unauthenticated actions that want current_user if available
|
def set_current_user
# for access to authenticate method
t = ActionController::HttpAuthentication::Token
@current_user = t.authenticate(self, &AUTH_PROC)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def set_current_user\n current_user\n authorize\n end",
"def current_user\n\t\t@current_user ||= authorize_request\n\tend",
"def current_user\n @current_user ||= authorize_request\n end",
"def current_user\n @current_user ||= authorize_request\n end",
"def current_user\n nil\n end",
"def current_user\n @current_user ||= authorize_request\n end",
"def current_user\n nil\n end",
"def ensure_user\n current_user? || deny_access('You must be logged in to perform this action.')\n end",
"def current_user\n raise NotImplementedError\n end",
"def current_user\n raise NotImplementedError\n end",
"def current_user\n super\n if @current_user\n return @current_user\n end\n\n authenticate_user!\n @current_user\n end",
"def ensure_current_user\n unless current_user\n redirect_to root_path\n # otherwise redirect somewhere root_path\n end\n end",
"def current_user\n @usys_logged_in_user ||= lookup_user\n end",
"def current_user()\n nil\n end",
"def current_user\n # authorization initialization if not run yet\n # (in the case of paper_trial it might not have run)\n authorization_init\n @logged_in_user\n end",
"def ensure_no_user\n !current_user? || redirect_back_or_default\n end",
"def current_user\n @current_user ||= find_logged_in_user\n end",
"def get_current_user\n @current_user = current_or_guest_user\n end",
"def current_user\n @current_user ||= auth_user\n end",
"def authenticate_request\n @current_user = nil\n end",
"def check_user\n if current_user.nil?\n render status: :forbidden, json: false\n return\n end\n end",
"def logged_in_user\n unless current_user \n redirect_to root_path\n end\n end",
"def current_user\n @current_user ||= nil\n end",
"def no_current_user\n if @user = current_user\n logger.warn \"Restricting user #{@user.id} from calling create!\"\n head :method_not_allowed\n end\n end",
"def current_user\n login_from_session || login_from_basic_auth \n end",
"def current_user\n logger.debug 'ApplicationController:current_user'\n @current_user ||= super\n @current_user && @current_user.is_guest? ? nil : @current_user\n end",
"def current_user\n @current_user ||= context[:current_user]\n end",
"def auth_user\n if !current_user\n redirect_to root_url\n end\n end",
"def auth_user\n if !current_user\n redirect_to root_url\n end\n end",
"def auth_user\n if !current_user\n redirect_to root_url\n end\n end",
"def context; { user: current_user } end",
"def current_user\n import_user\n end",
"def require_current_user\n if !current_user?(@user)\n redirect_to root_path\n end\n end",
"def current_user\n@current_user ||= (login_from_session || login_from_basic_auth || login_from_cookie) unless @current_user == false\nend",
"def current_user\n\t\tauthenticated(User)\n\tend",
"def authenticate_current_user\n render json: {}, status: :unauthorized if get_current_user.nil?\n end",
"def current_user\n\t\tview_context.current_user\n\tend",
"def current_user # Check the current user\n @current_user ||= User.find(session[:user_id]) if session[:user_id]\n end",
"def check_current_user\n @user = User.find(params[:id])\n redirect_to(root_url) unless current_user?(@user) || is_manager_or_admin?\n end",
"def require_current_user\n \tunless User.find(params[:id]) == current_user\n \t\tflash[:error] = \"Sorry! Viewing not authorized.\"\n \tend\n end",
"def user_is_current\n fetch_user\n\n unless current_user?(@user)\n flash[:error] = t(:not_authorized)\n redirect_to root_path\n end\n end",
"def authenticate_user\n\t\trender_unauthorized unless current_user\n\tend",
"def get_user\n @current_user = current_user\n end",
"def get_user\n @current_user = current_user\n end",
"def get_user\n @current_user = current_user\n end",
"def get_user\n @current_user = current_user\n end",
"def get_user\n @current_user = current_user\n end",
"def get_user\n @current_user = current_user\n end",
"def get_user\n @current_user = current_user\n end",
"def get_user\n @current_user = current_user\n end",
"def current_user\n @authenticated_user\n end",
"def current_user\n @authenticated_user\n end",
"def authenticate_current_user\n raise_not_authorized_error unless current_user\n end",
"def current_user\n# if there is a current user rtn that if not then rtn nil\n@current_user ||= User.find(session[:user_id]) if session[:user_id]\n end",
"def unauthorized_user!\n if @user != current_user\n redirect_to root_path, status: :unauthorized, alert: 'You can only perform this action on your own user!'\n end\n end",
"def current_user\n # super: don't change anything, i just want the exact same behavior \n # as in the method that we are overriding\n\n # what this line means is that if the user is logged in, super is true,\n # then call super treat everything normal, and ignore right hand side\n # if super == false, call right hand side\n\n # super comes from devise class\n # meanwhile the r.h.s comes from open struct class\n super || guest_user\n end",
"def authenticated_user\n\t \tauthenticated\n\t \terror!('401 Unauthorized', 401) unless current_user\n\t end",
"def current_user\n @current_user ||= get(User)\n end",
"def authenticate_user\n unauthorized unless current_user\n end",
"def current_user\n super\n end",
"def current_user\n super\n end",
"def block_unauthenticated_user!\n unless current_user\n return render_unauthorized\n end\n end",
"def check_current_user\n if !current_user.nil?\n Thread.current[:user] = current_user\n end\n end",
"def current_user\n # if a user is logged in we just use devise's implementation.\n super || guest_user\n end",
"def current_user\n login_from_session || login_from_basic_auth\n end",
"def current\n respond_with current_user\n end",
"def current_user\r\n super || guest_user\r\n end",
"def get_user\n @current_user = current_admin || current_user\n end",
"def current_user\n @current_user if logged_in?\n end",
"def current_user\n @current_user if logged_in?\n end",
"def set_current_user\n AuthorizationData.current_user = current_user\n yield\n ensure\n AuthorizationData.current_user = nil\n end",
"def current_user\n @current_user ||= User.find(session[:user_id]) if session[:user_id] # ||= means if not, here means if there is no current user logged in, do the following\n end",
"def current_user\n !session[:uid].nil?\n end",
"def authorize\n redirect_to('/login') unless @current_user\n end",
"def current_user\n get_from_options_or_controller(:current_user)\n end",
"def current_user\n @_current_user ||= authenticate_token\n end",
"def current_user\n @_current_user ||= authenticate_token\n end",
"def authenticated_user\n authenticated\n error!('401 Unauthorized', 401) unless current_user\n end",
"def call(current_user:)\n _ = current_user # presently ignored\n Success()\n end",
"def set_current_user\n if params[:user].blank?\n self.my_current_user = nil\n else\n self.my_current_user = User.find params[:user]\n end\n end",
"def current_user\n @current_user ||= User.find_by(id: authenticate_user)\n end",
"def current_user\r\n super || guest_user\r\n end",
"def ensure_authenticated_user\r\n head :unauthorized unless current_user\r\n end",
"def current_user\n ActiveRecord::Base.current_user_proc.call if ActiveRecord::Base.current_user_proc\n end",
"def before_filter\n if current_user\n true\n end\n end",
"def current_user\n User.find_by_id(session[:user_id]) if session[:user_id] \n end",
"def current_user(user)\n @current_user = user\n end",
"def current_user\n @current_user ||= TwitterUser.where(twitter_id: session[:current_user]).first\n rescue\n ensure_logout\n end",
"def begin_of_association_chain\n self.action_name != 'index' ? current_user : super\n end",
"def current_user\n @current_user ||= User.authenticatable.find_by_id(session[:user_id]) if session[:user_id]\n #unauthenticate unless @current_user\n @current_user\n end",
"def current_user\n @current_user ||= login_from_session\n end",
"def get_user\n @current_user = current_user\n end",
"def show\n self.current_user\n \n if not @current_user\n redirect_to login_path\n else\n render :action => 'edit'\n end\n end",
"def current_user\n if session[:user_id]\n @current_user=session[:user_id]\n end\nend",
"def current_user\n @current_user ||= fetch_user_from_request\n end",
"def current_user\n # if current_user is et use it otherwise ask the data store\n @current_user ||= User.find_by(id: session[:user_id])\n end",
"def check_current_user_owns\n head :not_found unless @user == current_user\n end",
"def only_current_user\n @user=User.find(params[:user_id])\n redirect_to(root_url) unless @user == current_user #current user is from devise\n end",
"def current_user\n if session[:user_id]\n User.find(session[:user_id])\n end\nend",
"def user_authenticated\n redirect_to root_url, alert: 'You must be logged in to go here' unless current_user\n end",
"def current_user\n cu = super\n return cu unless cu.blank?\n return nil unless doorkeeper_token && doorkeeper_token.accessible?\n @current_user ||= User.find_by_id(doorkeeper_token.resource_owner_id)\n end"
] |
[
"0.7672984",
"0.76452863",
"0.7631483",
"0.7631483",
"0.7595083",
"0.75813127",
"0.74963737",
"0.7456062",
"0.74307525",
"0.74307525",
"0.739522",
"0.7351485",
"0.73496693",
"0.7346652",
"0.7345665",
"0.73454344",
"0.7335022",
"0.73241764",
"0.732219",
"0.7305931",
"0.73044974",
"0.7302391",
"0.7301395",
"0.7300711",
"0.7291976",
"0.72888124",
"0.7259452",
"0.72429055",
"0.72429055",
"0.72429055",
"0.72427565",
"0.72253406",
"0.7211926",
"0.7209938",
"0.7206736",
"0.7205428",
"0.7189069",
"0.71826804",
"0.71796525",
"0.7169256",
"0.71666616",
"0.7164749",
"0.7164346",
"0.7164346",
"0.7164346",
"0.7164346",
"0.7164346",
"0.7164346",
"0.7164346",
"0.7164346",
"0.71617424",
"0.71617424",
"0.7155802",
"0.7153342",
"0.7151033",
"0.71380216",
"0.7126891",
"0.71218854",
"0.71112776",
"0.70980597",
"0.70980597",
"0.70975906",
"0.70911634",
"0.7082955",
"0.70819086",
"0.70727503",
"0.70719385",
"0.7071938",
"0.70693415",
"0.70693415",
"0.7062057",
"0.70615435",
"0.70558196",
"0.7051558",
"0.70467913",
"0.7040573",
"0.7040573",
"0.7038757",
"0.70382875",
"0.7037507",
"0.70369554",
"0.70345634",
"0.7033402",
"0.70322025",
"0.70257705",
"0.7025405",
"0.70183265",
"0.70122206",
"0.7010414",
"0.7003517",
"0.7002447",
"0.70002115",
"0.6994935",
"0.69923246",
"0.6992096",
"0.69920677",
"0.69919896",
"0.6985475",
"0.698345",
"0.6983437",
"0.6978927"
] |
0.0
|
-1
|
This method is based on the implementation in twitterbootstraprails. It has been slightly edited. See
|
def bootstrap_flash
messages = flash.flat_map do |type, message|
next if message.blank?
type = type.to_sym
type = :success if type == :notice
type = :danger if type == :alert
type = :danger if type == :error
next unless ALERT_TYPES.include?(type)
options = {
class: "alert fade in alert-#{type}"
}
close_button =
content_tag(:button, "×", type: "button", class: "close", "data-dismiss" => "alert")
Array(message).flat_map do |msg|
if msg
content_tag(:div, close_button + msg, options)
end
end
end
messages.compact.join("\n").html_safe
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def before_bootstrap; end",
"def before_bootstrap\n end",
"def private; end",
"def after_bootstrap\n end",
"def html_classes; end",
"def bootstrap_init\n end",
"def after_view_setup\n end",
"def input_html_classes; end",
"def initialize_html_tags; end",
"def pagination_links(obj)\n paginator = Paginator.new(obj)\n paginator.current_page = params[:page]\n\n # PAGE BUTTON LINKS (w/Bootstap styling)\n def previous_page_link(paginator)\n content_tag :li do\n link_to({ controller: \"#{controller_name}\", action: \"#{action_name}\", page: paginator.previous_page }, { remote: true, :'aria-label' => 'Previous Page', title: 'Previous Page', data: { toggle: 'tooltip', placement: 'top' } }) do\n raw '<span aria-hidden=\"true\">«</span>'\n end\n end\n end\n\n def previous_group_link(paginator)\n content_tag :li do\n link_to({ controller: \"#{controller_name}\", action: \"#{action_name}\", page: paginator.previous_range_first_page }, { remote: true, :'aria-label' => 'Previous Page Group', title: 'Previous Page Group', data: { toggle: 'tooltip', placement: 'top' } }) do\n raw '<span aria-hidden=\"true\">...</span>'\n end\n end\n end\n\n def page_link(page_num, current_page)\n status = 'active' if page_num == current_page\n\n content_tag :li, class: \"#{status}\" do\n link_to(\"#{page_num}\", controller: \"#{controller_name}\", action: \"#{action_name}\", page: \"#{page_num}\", remote: true)\n end\n end\n\n def next_group_link(paginator)\n content_tag :li do\n link_to({ controller: \"#{controller_name}\", action: \"#{action_name}\", page: paginator.next_range_first_page }, { remote: true, :'aria-label' => 'Next Page Group', title: 'Next Page Group', data: { toggle: 'tooltip', placement: 'top' } }) do\n raw '<span aria-hidden=\"true\">...</span>'\n end\n end\n end\n\n def next_page_link(paginator)\n content_tag :li do\n link_to({ controller: \"#{controller_name}\", action: \"#{action_name}\", page: paginator.next_page }, { remote: true, :'aria-label' => 'Next Page', title: 'Next Page', data: { toggle: 'tooltip', placement: 'top' } }) do\n raw '<span aria-hidden=\"true\">»</span>'\n end\n end\n end\n\n # BUILD PAGINATION LINKS\n # Start Bootstap pagination style\n output = '<nav class=\"text-center\"><ul class=\"pagination\">'\n\n # Show the '<<' aka previous page button\n unless paginator.first_page? || paginator.current_page < 1\n output += previous_page_link(paginator)\n end\n\n # Show the '...' aka previous page group button\n unless paginator.first_page? || paginator.current_page <= paginator.links_per_page\n output += previous_group_link(paginator)\n end\n\n # Show individual page links, stopping at the limit of links per page set by the user\n paginator.current_range_first_page.upto(paginator.last_page_in_current_range) do |page_num|\n output += page_link(page_num, paginator.current_page) unless page_num > paginator.total_pages\n end\n\n # Show the '...' aka next page group button\n unless paginator.next_range_first_page > paginator.total_pages || paginator.last_page?\n output += next_group_link(paginator)\n end\n\n # Show the '>>' aka next page button\n unless paginator.last_page? || paginator.current_page > paginator.total_pages\n output += next_page_link(paginator)\n end\n\n # Append page numbering and end Bootstap pagination style\n output += \"</ul><p><strong>Page:</strong> #{paginator.current_page} / #{paginator.total_pages}</p></nav>\"\n\n # Output the string to the view\n raw output unless paginator.total_pages <= 1\n end",
"def on_pre_request( request ); end",
"def helpers; end",
"def helpers; end",
"def helpers; end",
"def input_html_options; end",
"def after_generate_callbacks; end",
"def on_before_load\n end",
"def html_head\n \"<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>\n <html xmlns='http://www.w3.org/1999/xhtml'>\n <head>\n <meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1' />\n <title>#enforcers @ Slashnet stats by Asmer</title>\n <link href='css/bootstrap.min.css' rel='stylesheet' media='screen'>\n <link rel='stylesheet' type='text/css' title='estats' href='/css/estats.css' />\n <script src='http://code.jquery.com/jquery.js'></script>\n <script src='js/bootstrap.min.js'></script>\n </head>\n <body>\n <div align='center'>\n <div class='navbar navbar-fixed-top navbar-inverse'>\n <div class='navbar-inner'>\n <div class='container'>\n <a class='brand' href='#'>#enforcers @ Slashnet stats by Asmer</a>\n <ul class='nav'>\n <li><a href='/'>Channel Stats</a></li>\n <li><a class='active'}' href='dickbag.html'>Dickbag</a></li>\n <li><a class='active'}' href='karma.html'>Karma</a></li>\n <li><a class='active'}' href='hangouts.html'>Hangouts</a></li>\n <li><a href='http://shitenforcerslink.tumblr.com/'>Link Logger</a></li>\n </ul>\n </div>\n </div>\n </div>\n <div class='container'>\n <div class='row'>\n <div class='content span10 offset1'>\"\nend",
"def myletter\n \n end",
"def after_partial_setup(view)\n end",
"def on_pre_request( request )\n end",
"def apply\n\t\t\t\t\n\t\t\tend",
"def custom; end",
"def custom; end",
"def kopal_layout_after_page_header\n\n end",
"def bootstrap\n check_config\n\n Patches::RoutesPatch::prepend\n\n # Rails classes patches\n ActionDispatch::Callbacks.to_prepare do\n unless Redmine::MenuManager::MenuHelper.included_modules.include? RedmineWikipub::Patches::MenuHelperPatch\n Redmine::MenuManager::MenuHelper.send(:include, Patches::MenuHelperPatch)\n end\n unless ApplicationHelper.included_modules.include? RedmineWikipub::Patches::ThemesPatch\n ApplicationHelper.send(:include, Patches::ThemesPatch)\n end\n unless ApplicationHelper.included_modules.include? RedmineWikipub::Patches::ViewHelperPatch\n ApplicationHelper.send(:include, Patches::ViewHelperPatch)\n end\n unless Mailer.included_modules.include? RedmineWikipub::Patches::MailerPatch\n Mailer.send(:include, Patches::MailerPatch)\n end\n unless AccountController.included_modules.include? RedmineWikipub::Patches::AccountControllerPatch\n AccountController.send(:include, Patches::AccountControllerPatch)\n end\n end\n end",
"def to_html; end",
"def weber; end",
"def to_html\n\n bootstrap_wrapping do\n content_tag(:div, class: 'input-group bs_label_with_content') do\n content_tag(:div, class: 'row') do\n tmp = ActiveSupport::SafeBuffer.new\n\n tmp << content_tag(:div, class: \"col-md-6 col-lg-6\") do\n builder.input method, :label => false\n end\n\n if object.send(method).exists?\n tmp << content_tag(:div, class: \"col-md-6 col-lg-6\") do\n image_tag object.send(method).url,class:'img-responsive img-thumbnail',style:'max-height:200px;'\n end\n end\n\n tmp\n end\n end\n end\n end",
"def markup_context; end",
"def escaper; end",
"def originalsourceform; end",
"def schubert; end",
"def initialize\n super\n end",
"def initialize\n super\n end",
"def dom_class; end",
"def dom_class; end",
"def dom_class; end",
"def dom_class; end",
"def active_element; end",
"def initialize\n super\n end",
"def initialize\n super\n end",
"def initialize\n super\n end",
"def apply_template_before?; end",
"def page_header(site_config, page_count)\n # start common page region\n page = %(<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <!-- The above 3 meta tags *must* come first in the head;\n any other head content must come *after* these tags -->\n <title>#{site_config['title']}</title>)\n page += add_icons\n page += %(\n <meta name=\"description\" content=\"#{site_config['description']}\">\n <meta name=\"theme-color\" content=\"##{site_config['theme_color']}\">\n <link rel=\"stylesheet\" href=\"assets/bootstrap/css/bootstrap.min.css\">\n <link rel=\"stylesheet\" href=\"assets/bootstrap/css/bootstrap-theme.min.css\">\n <style>\n .container-fluid { padding: 0px; }\n .navbar, .navbar-default { margin-bottom: 0; padding: 5pt; background-color: ##{site_config['theme_color']}; font-size: 12pt; }\n .navbar, .navbar-default li a { color: ##{site_config['text_color']} !important; }\n .navbar-default .navbar-brand { margin-left: 20px !important; color: ##{site_config['logo_text_color']}; font-size: 18pt; font-weight: bold; }\n .navbar-brand:hover { background-color: #{site_config['nav_hover_color']} !important; }\n div[id^=\"d3pie_chart_div_\"], canvas { margin-bottom: 100px; }\n footer { background-color: ##{site_config['theme_color']}; min-height: 200px;}\n footer ul a { color: ##{site_config['text_color']} !important; font-size: 13pt; }\n footer .container { margin-left: 15px; }\n .built { text-decoration: none !important; }\n .selected { background-color: #{site_config['nav_selected_color']}; font-weight: bold; }\n .navbar-default li:hover a { background-color: #{site_config['nav_hover_color']} !important; }\n h1 { text-align: center; background-color: ##{site_config['theme_color']}; padding: 14px; color: ##{site_config['text_color']}; }\n pre { white-space: pre-wrap; word-wrap: break-word; }\n .homepage { padding: 5px 30px 5px 30px; }\n .logo { float: left; }\n .oll { padding-left: 1em; }\n h2#other { text-align: center; }\n .plotlypie { height: 625px; }\n </style>\n </head>\n <body>\n <!-- Static navbar -->\n <nav class=\"navbar navbar-default\" id=\"head1\">\n <div class=\"container-fluid\">\n <div class=\"navbar-header\">\n <a href=\"index.html\"><img src=\"assets/images/logo.png\" alt=\"Ruby Powered\" class=\"logo\"></a>\n <button type=\"button\" class=\"navbar-toggle collapsed\" data-toggle=\"collapse\" data-target=\"#navbar\" aria-expanded=\"false\" aria-controls=\"navbar\">\n <span class=\"sr-only\">Toggle navigation</span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n </button>\n <a class=\"navbar-brand\" href=\"index.html\">#{site_config['nav_heading']}</a>\n </div>\n <div id=\"navbar\" class=\"navbar-collapse collapse\">\n <ul class=\"nav navbar-nav\">)\n page += add_links(page_count)\n page += %(\n </ul>\n </div>\n </div>\n </nav>\n <div class=\"container-fluid\">)\n (0..page_count).map do |i|\n instance_variable_set(\"@page#{ii(i)}\", page)\n end\nend",
"def set_bootstrap_file_name\n @bootstrap_file_name = 'replr-bootstrap.js'\n end",
"def probers; end",
"def sitemaps; end",
"def styles; end",
"def styles; end",
"def styles; end",
"def view_renderer; end",
"def view_renderer; end",
"def around_hooks; end",
"def before_setup; end",
"def page_load; end",
"def kopal_layout_before_page_header\n\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end",
"def initialize()\n super\n end"
] |
[
"0.59120595",
"0.57880944",
"0.55023664",
"0.5421375",
"0.52382725",
"0.5178643",
"0.5030141",
"0.49202925",
"0.48784065",
"0.48398462",
"0.4801357",
"0.47817773",
"0.47817773",
"0.47817773",
"0.4726089",
"0.47239262",
"0.47233304",
"0.47056603",
"0.4699905",
"0.46969587",
"0.46930456",
"0.46922606",
"0.4687338",
"0.4687338",
"0.4677194",
"0.46747866",
"0.46680722",
"0.4663441",
"0.4650724",
"0.46368203",
"0.4622905",
"0.4611645",
"0.45998177",
"0.4599777",
"0.4599777",
"0.45927733",
"0.45927733",
"0.45927733",
"0.45927733",
"0.45817676",
"0.45800877",
"0.45800877",
"0.45800877",
"0.45707375",
"0.45695612",
"0.45584574",
"0.45550412",
"0.4551177",
"0.45504677",
"0.45504677",
"0.45504677",
"0.4544335",
"0.4544335",
"0.4541474",
"0.45267817",
"0.45254406",
"0.45253286",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777",
"0.45152777"
] |
0.0
|
-1
|
Plus initializer... this will likely be fixed later ... DEFINITELY gonna be fixed soon, this is so ugly
|
def initialize network:
super network[:type], network[:struct], act_fn: network[:act_fn]
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def initialize(*) end",
"def initialize(*) end",
"def initialize(*) end",
"def initialize(*) end",
"def initialize(*) end",
"def initialize() end",
"def initialize; end",
"def initialize; end",
"def initialize; end",
"def initialize; end",
"def initialize; end",
"def initialize; end",
"def initialize; end",
"def initialize; end",
"def initialize; end",
"def initialize; end",
"def initialize; end",
"def init; end",
"def init; end",
"def init; end",
"def init; end",
"def initialize\n\t\t\n\tend",
"def initialize\n \n end",
"def initialize(*) \n end",
"def initialize\n \n end",
"def initialize\n\n\tend",
"def initialize\n\n\tend",
"def initialize\n super(true)\n end",
"def private; end",
"def initialize(*)\n end",
"def initialize(*)\n end",
"def constructor; end",
"def initialize(*rest) end",
"def pre_initialize; end",
"def initialize(*_)\n super\n end",
"def initialize\r\n\r\n end",
"def init\n end",
"def init\n end",
"def init\n end",
"def initialize\n\t\nend",
"def initialize\n super\n end",
"def initialize\n super\n end",
"def initialize\n super\n end",
"def initialize\n # nothing here for now\n end",
"def initialize()\n\t\tend",
"def init\n\n end",
"def initialize\n super \n end",
"def initialize\n super()\n end",
"def initialize\n super()\n end",
"def initialize\n super()\n end",
"def initialize\n super()\n end",
"def initialize\n super()\n end",
"def initialize\n super()\n end",
"def initialize\n super()\n end",
"def initialize\n initialize!\n end",
"def initialize\n initialize!\n end",
"def initialize(*); end",
"def initialize()\r\n\r\n end",
"def initialize\n\n\n\n end",
"def initialize(*a); super; end",
"def initialize(*a); super; end",
"def initialize()\n\tend",
"def initialize()\n\tend",
"def initialize\n super\n end",
"def initialize\n super\n end",
"def initialize\n super\n end",
"def initialize\n\tinit\n\tsuper\nend",
"def initialize\n super()\n end",
"def initialize(*)\n super\n apply_defaults\n end",
"def initialize\n end",
"def initialize *args\n super\n end",
"def init; end",
"def initialize(*args); end",
"def initialize\n \n end",
"def initialize\n \n end",
"def initialize\n super\n end",
"def initialize\n super\n end",
"def initialize\n\n end",
"def initialize\n\n end",
"def initialize( * )\n super\n end",
"def initialize()\n end",
"def initialize()\n end",
"def initialize()\n end",
"def initialize()\n end",
"def initialize()\n end",
"def initialize()\n end",
"def initialize()\n end",
"def initialize()\n end",
"def initialize(*args)\n #This is a stub, used for indexing\n end",
"def initialize()\n end",
"def initialize\n end",
"def initialize\n end",
"def initialize\n end",
"def initialize\n end",
"def initialize\n end",
"def initialize\n end",
"def initialize\n end",
"def initialize\n end",
"def initialize\n end",
"def initialize()\n # override parent\n end",
"def initialize\nend"
] |
[
"0.7433664",
"0.7433664",
"0.7433664",
"0.7433664",
"0.7433664",
"0.7410543",
"0.7281168",
"0.7281168",
"0.7281168",
"0.7281168",
"0.7281168",
"0.7281168",
"0.7281168",
"0.7281168",
"0.7281168",
"0.7281168",
"0.7281168",
"0.7270239",
"0.7270239",
"0.7270239",
"0.7270239",
"0.6962764",
"0.69347036",
"0.6888439",
"0.6886729",
"0.68487227",
"0.68487227",
"0.68428236",
"0.68053555",
"0.67629594",
"0.67629594",
"0.67589206",
"0.67544335",
"0.67411506",
"0.6706592",
"0.67046636",
"0.6703296",
"0.6703296",
"0.6703296",
"0.6689074",
"0.6687417",
"0.6687417",
"0.6687417",
"0.668599",
"0.66724515",
"0.66589177",
"0.6648875",
"0.6646468",
"0.6646468",
"0.6646468",
"0.6646468",
"0.6646468",
"0.6646468",
"0.6646468",
"0.6638704",
"0.6638704",
"0.6629887",
"0.6627843",
"0.6625044",
"0.6620639",
"0.6620639",
"0.6605629",
"0.6605629",
"0.65965694",
"0.65965694",
"0.65965694",
"0.65943223",
"0.6588212",
"0.6587664",
"0.6586912",
"0.6585981",
"0.6584561",
"0.6560088",
"0.65528727",
"0.65528727",
"0.65458864",
"0.65458864",
"0.6543838",
"0.6543838",
"0.65432674",
"0.6531772",
"0.6531772",
"0.6531772",
"0.6531772",
"0.6531772",
"0.6531772",
"0.6531772",
"0.6531772",
"0.65307933",
"0.6525809",
"0.6518542",
"0.6518542",
"0.6518542",
"0.6518542",
"0.6518542",
"0.6518542",
"0.6518542",
"0.6518542",
"0.6518542",
"0.64924437",
"0.6485228"
] |
0.0
|
-1
|
We reimplement created_at but leave updated_at unimplemented so that we can set it ourselves.
|
def set_timestamps
self.created_at = Time.now
#Set updated_at initially before manually setting because column cannot be null.
self.updated_at = Time.now
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def created_at; super; end",
"def created_at; end",
"def created_at=(_arg0); end",
"def set_created_at\n if !timeless? && !created_at\n time = Time.configured.now\n self.updated_at = time if is_a?(Updated) && !updated_at_changed?\n self.created_at = time\n end\n clear_timeless_option\n end",
"def created_at\n with_type!(Fixnum) { attribute_from_model(:created_at) || attribute_from_model(:created) }\n end",
"def updated_at\n created_at\n end",
"def set_created_at\n self.created_at ||= Date.today if new_record?\n end",
"def real_created_at\n self[:remote_created_at] || self[:created_at]\n end",
"def generate_default_values\n self.created_at = DateTime.now unless self.created_at\n end",
"def created_at\n nil\n end",
"def create_timestamp\n self.created_at = Time.now\n end",
"def create_timestamp\n self.created_at = Time.now\n end",
"def initialize\n @created_at = Time.now\n end",
"def created_at # overwriting what this method returns\n object.created_at.strftime('%B %d, %Y') # Object represents the instance\n end",
"def created_at\n @created_at ||= Time.now\n end",
"def created_at\n @created_at ||= Time.now\n end",
"def created_at\n @created_at ||= Time.now\n end",
"def created_at(key)\n raise \"Method not implemented. Called abstract class.\"\n end",
"def created_at\n object.created_at.in_time_zone.iso8601 if object.created_at\n end",
"def created_at\n @created_at ||= self[:created_at] ? Time.parse(self[:created_at]) : nil\n end",
"def before_create\n temp_time = Time.sl_local\n self.created_at = temp_time\n self.modified_at = temp_time\n end",
"def created_at\n super.in_time_zone if super\n end",
"def created_at\n @attributes[:created_at]\n end",
"def created_at\n @attributes[:created_at]\n end",
"def created_at\n @attributes[:created_at]\n end",
"def created_at\n @attributes[:created_at]\n end",
"def created_at\n @attributes[:created_at]\n end",
"def created_at\n @attributes[:created_at]\n end",
"def created_at\n @attributes[:created_at]\n end",
"def created_at\n @attributes[:created_at]\n end",
"def created_at\n @attributes[:created_at]\n end",
"def touch\n now = Time.current.utc\n self.updated_at = now\n self.created_at = now if new_record?\n end",
"def before_create; self.created_on = Time.now.utc; end",
"def before_create\n self.created_at = Time.now\n self.updated_at = Time.now\n end",
"def created_at\n attributes.send(:ts_created) rescue nil\n end",
"def set_record_created_at\n self.record_created_at = Time.current.utc.iso8601(3)\n end",
"def created_at\n object.created_at.iso8601\n end",
"def timestamps!\n before(:create) do\n self['updated_at'] = self['created_at'] = Time.now\n end \n before(:update) do \n self['updated_at'] = Time.now\n end\n end",
"def createdAt\n self.created_at.to_s(:db)\n end",
"def created_at\n @created_at ||= Time.zone.now.utc.to_i\n end",
"def created_at\n Time.at(created)\n end",
"def created_at\n Time.at(created)\n end",
"def bump_timestamps\n self.updated_at = Time.now.utc\n end",
"def creation_date\n self.created_at.iso8601\n end",
"def created_at\n object.created_at.to_time.to_i\n end",
"def published_at\n self[:published_at] ||= if created_at?\n created_at\n else\n Time.now.utc\n end\n end",
"def created_at=(value)\n @created_at = DateTime.parse(value)\n end",
"def _update_timestamps\n if self.respond_to?('updated_at')\n self.updated_at = Time.now\n end\n end",
"def created_at\n Time.at(response[\"createdAt\"]) if response[\"createdAt\"]\n end",
"def created_at\n formatted_time(object.created_at)\n end",
"def created_at\n formatted_time(object.created_at)\n end",
"def created_at\n formatted_time(object.created_at)\n end",
"def created_at\n formatted_time(object.created_at)\n end",
"def created_at\n data['creationDate'].to_date\n end",
"def before_create\n self.created_at ||= Time.now\n super # ($)\n end",
"def created_at; @doc['created_at']; end",
"def creation_date=(_); end",
"def created_at_datetime\n @created_at_datetime ||= DateTime.parse(@created_at)\n end",
"def created_at\n content_key.created_at\n end",
"def created_at=(val)\n if val.is_a?(String)\n @created_at = Time.parse(val)\n else\n @created_at = val\n end\n end",
"def created_at\n begin\n Time.parse(self.create_date)\n rescue\n nil\n end\n end",
"def created_at\n ensure_full_data!\n Time.at(@gapi[\"creationTime\"] / 1000.0)\n end",
"def created_at\n @record.created_at\n end",
"def canonical_date\n self.created_at\n end",
"def audit_update\n self.modified_date = DateTime.now\n if self.created_date.blank?\n self.created_date = DateTime.now\n end\n end",
"def started_at\n created_at\n end",
"def before_validation\n if values[:created_at].nil?\n values[:created_at] = DateTime.now\n end\n end",
"def created_at\n Time.at(created.to_i)\n end",
"def created_at\n Time.at(created.to_i)\n end",
"def created_at\n Time.parse(attributes['created_at'])\n end",
"def created_at\n Time.parse(@created_at).utc unless @created_at.nil?\n end",
"def created_at\n valid? ? Time.at(value[1]) : nil\n end",
"def updated_at\n dateChanged\n end",
"def created_at\n\t\tobject.created_at.strftime(\"%A, %B %e\")\n\tend",
"def created_at\n return DateTime.parse(@created_at) if @created_at\n\n @created_at\n end",
"def created_at\n object.created_at.strftime(\"%B %d, %Y\")\n end",
"def creation_date\n raise NotImplementedError\n end",
"def created_at\n @created_at ||= changelogs.first&.[](\"time\")\n end",
"def timestamps!\n property :created_at\n property :updated_at\n \n before_create :touch_created_at\n before_create :touch_updated_at\n before_save :touch_updated_at\n end",
"def created_at\n Time.parse @gapi.creation_time\n rescue StandardError\n nil\n end",
"def check_for_timestamp name\n @created_at = true if name == CREATED_AT_FIELD\n @updated_at = true if name == UPDATED_AT_FIELD\n nil\n end",
"def created_at\n id.generation_time\n end",
"def decorated_created_at\n created_at.to_date.to_s(:long) \n end",
"def method_missing_with_timestamp_aliases(method,*args,&block)\n if method == :created_on && respond_to?(:created_at)\n self.class.send(:alias_method,:created_on,:created_at)\n created_at\n elsif method == :created_on= && respond_to?(:created_at=)\n self.class.send(:alias_method,:created_on=,:created_at=)\n self.created_at = args.first\n elsif method == :created_at && respond_to?(:created_on)\n self.class.send(:alias_method,:created_at,:created_on)\n created_on\n elsif method == :created_at= && respond_to?(:created_on=)\n self.class.send(:alias_method,:created_at=,:created_on=)\n self.created_on = args.first\n elsif method == :updated_at && respond_to?(:updated_on)\n self.class.send(:alias_method,:updated_at,:updated_on)\n updated_on\n elsif method == :updated_at= && respond_to?(:updated_on=)\n self.class.send(:alias_method,:updated_at=,:updated_on=)\n self.updated_on = args.first\n elsif method == :updated_on && respond_to?(:updated_at)\n self.class.send(:alias_method,:updated_on,:updated_at)\n updated_at\n elsif method == :updated_on= && respond_to?(:updated_at=)\n self.class.send(:alias_method,:updated_on=,:updated_at=)\n self.updated_at = args.first\n else\n method_missing_without_timestamp_aliases(method,*args,&block)\n end\n end",
"def updated_at\n Time.at @updated rescue nil\n end",
"def set_updated!\n @updated_at = Time.now\n end",
"def unchanged?\n created_at == updated_at\n end",
"def created_at(format = nil)\n if new?\n format ? Time.now.strftime(format) : Time.now\n else\n format ? self[:created_at].strftime(format) : self[:created_at]\n end\n end",
"def date\n Time.at(self.created_utc)\n end",
"def date\n Time.at(self.created_utc)\n end",
"def date\n Time.at(self.created_utc)\n end",
"def created_at\n @gapi[\"timeCreated\"]\n end",
"def updated_at\n @updated_at ||= Time.parse(@attributes['updated_at'])\n end",
"def decorated_updated_at\n updated_at.to_date.to_s(:long)\n # created_at.strftime \"%d/%m/%Y %H:%M\"\n end",
"def creation_date\n raise NotImplemented\n end",
"def creation_date\n raise NotImplemented\n end",
"def has_enabled_but_unset_created_at?\n able_to_store_created_at? && !instance_read(:created_at)\n end",
"def fresh?\n created_at == updated_at\n end",
"def created_at\n # parse date from utc_random generated id\n Time.at(id[0, 14].to_i(16) / 1000 / 1000).utc\n end",
"def updated_on\n updated_at\n end"
] |
[
"0.82227004",
"0.7883998",
"0.788314",
"0.7670101",
"0.76289743",
"0.7537689",
"0.75163126",
"0.74530387",
"0.72943956",
"0.7282098",
"0.72775656",
"0.72767836",
"0.7252003",
"0.72140354",
"0.716192",
"0.716192",
"0.716192",
"0.71449715",
"0.7098751",
"0.7077208",
"0.7074179",
"0.70282644",
"0.701516",
"0.701516",
"0.701516",
"0.701516",
"0.701516",
"0.701516",
"0.701516",
"0.701516",
"0.701516",
"0.6988386",
"0.69871134",
"0.6962568",
"0.6952969",
"0.69504064",
"0.692576",
"0.69067323",
"0.68994194",
"0.6890449",
"0.6889601",
"0.6889601",
"0.68719375",
"0.6790765",
"0.6776884",
"0.6730237",
"0.6724613",
"0.6707066",
"0.6702894",
"0.6692237",
"0.6692237",
"0.6692237",
"0.6692237",
"0.6688794",
"0.668874",
"0.668277",
"0.66796017",
"0.66662604",
"0.6663929",
"0.66582143",
"0.66530603",
"0.66487664",
"0.6642368",
"0.6608671",
"0.65923977",
"0.6585272",
"0.6571282",
"0.65677553",
"0.65677553",
"0.65654594",
"0.6559452",
"0.655503",
"0.6535039",
"0.65141964",
"0.6483223",
"0.64779836",
"0.6462073",
"0.6454473",
"0.64543813",
"0.64361894",
"0.6429299",
"0.6428726",
"0.64099324",
"0.640402",
"0.6366165",
"0.63642824",
"0.63517296",
"0.6347372",
"0.6341346",
"0.6341346",
"0.6341346",
"0.63392025",
"0.6318035",
"0.6313894",
"0.6309253",
"0.6309253",
"0.63049835",
"0.6302977",
"0.6295371",
"0.6279507"
] |
0.7057025
|
21
|
iterate over and find ... if found... select and put into an array counting how many items in the array
|
def get_occupation(data, hometown)
# code here
occupation = nil
data.each do |key1, value1|
value1.each do |key_value_pair|
if key_value_pair["hometown"] == hometown
occupation = key_value_pair["occupation"]
break
end
end
end
occupation
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def my_count\n array = self.my_select {|item| yield item}\n array.length\n end",
"def count_elements(array)\n new_array = []\n\n array.each do |original_array_element|\n\n #now inside the array looking at each indv hash\n \tif new_array.empty?\n\n \t\tfirst_new_element = {name: original_array_element[:name], count: 1}\n \t\tnew_array.push(first_new_element)\n\n \telse\n name_found = false\n \t\tnew_array.each do |new_hash_item|\n \t\t\t#binding.pry\n \t\t\tif new_hash_item.has_value?(original_array_element[:name])\n \t\t\t\tnew_hash_item[:count] += 1\n name_found = true\n \t\t\tend\n end\n if name_found == false\n new_element = {name: original_array_element[:name], count: 1}\n new_array.push(new_element)\n end\n \tend\n end\n return new_array\nend",
"def count_elements(array)\n newArray = []\n array.each do |obj|\n newArray.push(obj)\n obj[:count] = 0\n #if newArray.length > 0\n newArray.each do |obj|\n if obj.include?(:count)\n obj[:count] += 1\n else\n obj[:count] = 1\n end\n #binding.pry\n end\n #end\n end\n newArray.shift\n return newArray\nend",
"def count_elements(array)\n\t# My attempt:\n\t# hash = {}\n\t# array.each do |e|\n\t# \thash[e] = 1\n\t# end\n\t# new_array = []\n\t# hash.each do |animal, count|\n\t# \tnew_array = hash.select{|animal2, count2| animal2 == animal}\n\t# end\n\t# new_array\n\n\t# Stack Overflow:\n\tcounts = Hash.new(0) # sets default value (the value that is returned when trying to access key that does not exist) to 0 instead of nil\n\tarray.each { |e| counts[e] += 1 }\n\tcounts\nend",
"def count_elements (array)\n result_array = []\n\n array.each do |data|\n flag =0\n result_array.each do |k|\n if k[:name] == data[:name]\n k[:count] +=1\n flag =1\n end\n end\n if(flag == 0)\n data[:count] = 1\n result_array << data\n end\n end\n result_array\nend",
"def count(arr)\n arr.select { |el| yield(el) }.size\nend",
"def count_elements(arr)\n counter = Array.new\n counter_helper = Array.new\n arr.each do |element|\n if counter_helper.include?(element)\n counter[counter_helper.find_index(element)][:count] += 1\n else\n counter_helper.push(element.clone)\n element[:count] = 1\n counter.push(element)\n end\n end\n counter\nend",
"def count_elements(collection)\n count_array = []\n hash_array = []\n\n collection.each do |hash|\n\n if count_array.include?(hash[:name])\n hash_array.each do |value|\n if value[:name] == hash[:name]\n value[:count] = value[:count] + 1\n end\n end\n else\n new_hash = {}\n new_hash[:name] = hash[:name]\n new_hash[:count] = 1\n\n count_array << hash[:name]\n hash_array << new_hash\n end\n\n\n end\n\n return hash_array\nend",
"def count(collection)\n collection.select { |el| yield(el) }.size\nend",
"def count(array, item)\n i = 0\n output = []\n count = 0\n while i <= array.length-1\n if array[i] == item\n count += 1\n end\n i += 1\n end\n return count\nend",
"def query_7\n document_ids = Perpetuity[Document].select {|document| document.id}.to_a\n return document_ids.size\nend",
"def cnts a\n r = []\n found = false\n a.each do |x|\n r.each do |y|\n if y[0] === x\n y[1] += 1\n found = true\n break\n end\n end\n if !found\n r.push([x, 1])\n else\n found = false\n end\n end\n r\nend",
"def count\n size = 0\n core_search.group(\"name.id, #{main_group_by_columns}\").each do |_x|\n size += 1\n end\n size\n end",
"def find_counts()\n # Search through given fields for given text\n counts = Array.new\n find_text = @replace['replace']['find']\n @replace['replace']['tables'].each do |table, fields|\n query = find_query(find_text, table, fields.clone)\n @dbconn.query(query).each do |row|\n count_hash = {table: table, fields: fields, count: row['total']}\n counts.push count_hash\n end\n end\n counts\n end",
"def solution(a)\r\n # write your code in Ruby 2.2\r\n \r\n arr =[]\r\n a.each_with_index{|el,i|\r\n \r\n if !arr.index(el) \r\n arr << el\r\n end\r\n \r\n }\r\n arr.count\r\nend",
"def count_eggs(chicken_array)\n total_eggs = 0\n for chicken in chicken_array\n total_eggs += chicken[:eggs]\n end\n return total_eggs\nend",
"def birthdayCakeCandles(ar)\n height = 0\n count = 0\n ar.collect do |number|\n if number > height\n count = 1\n height = number\n elsif number == height\n count += 1\n else\n end\n end\n return count\nend",
"def my_count(val)\n counter = 0\n self.each do |ele|\n if ele == val\n counter += 1\n end\n end\n counter\n end",
"def count\n @count || first[N]\n end",
"def count(item)\n item.select { |*args| yield(*args) }.size\nend",
"def number_of(val)\n res = 0\n @array.each { |row| row.each { |v| res +=1 if v == val } }\n res\n end",
"def count_elements(array)\n array.uniq.collect do |word|\n word[:count] = array.count(word)\n word\n end\nend",
"def find(n)\r\n result = []\r\n n = group(n)\r\n\r\n n.each { |element| result << [element, element.length]}\r\n\r\n result\r\nend",
"def count_elements(arr)\n count = 0\n\n arr.each do |x|\n if arr.include?(x+1)\n count += 1\n end\n end\n \n count\nend",
"def count_items(elective_array)\n return elective_array.length\nend",
"def search_array (arr, number)\n\n count=0\n arr.each do |integer|\n if integer == number\n return count\n break\n end\n count += 1\n\n end\n return nil\nend",
"def find_elements(arr)\n elements = Hash.new(0)\n\n arr.each { |ele| elements[ele] += 1 }\n\n elements\nend",
"def count_contestants_by_hometown(data, hometown)\n counter = 0 # COUNTER VALUE HAS TO BE HERE\n data.each do |season, season_array|\n season_array.each do |into_array|\n if into_array[\"hometown\"] == hometown\n counter += 1\n # binding.pry\n end \n end \n end\n counter\nend",
"def custom_count(array)\n counter = 0\n array.each do |elem|\n if elem != nil\n counter += 1\n end\n end\n counter\nend",
"def count_items(electives)\n electives.length #counts number of items in the array\nend",
"def element_count(array)\n\nend",
"def my_count(arg = nil)\n result = []\n if block_given?\n my_each do |elem|\n result << elem if yield(elem) == true\n end\n end\n\n unless block_given?\n if arg.nil? arg.nil?\n result = self\n else\n my_each do |elem|\n result << elem if elem == arg\n end\n end\n end\n result.size\n end",
"def find!\n @total_found = 0\n @results = nil\n return results\n end",
"def counts\n count = Hash.new(0)\n self.each{|ele| count[ele] += 1}\n count\n end",
"def num_occur(array, target)\n return 0 if array.empty?\n count = 0\n count += 1 if array.first == target \n count + num_occur(array.drop(1), target)\nend",
"def count_elements(array)\n array.group_by(&:itself).map { |key, value| key.merge(count: value.length)} # counts number of times occur\nend",
"def occurences_count\n\t\t\t\t\t\tHash.new(0).tap do |result|\n\t\t\t\t\t\t each { |item| result[item] += 1 }\n\t\t\t\t\t\tend\n\t\t\t\tend",
"def count(arr, item)\n\tarr.count { |x| x == item }\nend",
"def repeats(arr)\nsum = 0\narr.find_all { |x| sum+=x if arr.count(x) == 1 }\nsum\nend",
"def count_elements(array)\n new_array = []\n for person in array.uniq\n new_array.push{:name => person[:name], :count => array.count(name)}\n end\nend",
"def my_select(collection)\n holder = [] #for collection at the end\n counter = 0 #start at beginning of array\n\n while counter < collection.length # condition to be met\n if yield(collection[counter]) == true #if the mumbojumbo results in true *which select gives\n holder.push(collection[counter]) #then push that element into the new array\n end\n counter += 1 #iterate throughout the array incremently\n end\n holder #show everyone your new array\nend",
"def find_matches(*arrays)\n hash = Hash.new(0)\n arrays.flatten.each do |num|\n hash[num] += 1\n end\n hash.keys.find_all do |num|\n\t\thash[num] == 3\n\tend\nend",
"def num_matches\n count = 0\n other_answers.each do |a|\n count += 1 if base_answer.food_groups == a.food_groups\n end\n count\n end",
"def count_elements(array)\n counted = []\n array.each do |item|\n item[:count] = array.count(item)\n counted << item\n end\n return counted.uniq{ |item|\n item[:name]\n }\nend",
"def element_count(arr)\n fre = {}\n fre.default = 0\n arr.each { |el| fre[el] += 1 }\n return fre\nend",
"def count_elements(array)\n\nend",
"def count_occurrences(array)\n result = {}\n array.each do |x|\n result[x] = if !result.key?(x)\n 1\n else\n result.fetch(x) + 1\n end\n end\n result.each do |k, count|\n p \"#{k} => #{count}\"\n end\nend",
"def pets_by_breed(pet_shop_hash, pet_breed)\n breed_count = []\n pet_shop_hash[:pets].select { | pet | breed_count << pet if pet[:breed] == pet_breed}\n return breed_count\nend",
"def stock_count(stock_count_array)\n stock_count_array[:pets].count\nend",
"def count_primes(array)\n select_primes(array).count\nend",
"def num_occur(array, target)\n return 0 if array.empty?\n count = array.first == target ? 1 : 0\n count += num_occur(array.drop(1), target)\nend",
"def solution0(a)\n\n total_count = 0\n elem_counts = Hash.new(0)\n\n a.each do |elem|\n elem_counts[elem] += 1\n total_count += 1 if elem_counts[elem] == 2\n end\n\n return total_count\n\nend",
"def count_occurrences(array)\n return puts('Invalid Array') unless array.is_a?(Array)\n return puts('There is nothing to count') if array.empty?\n\n counts = array.each_with_object(Hash.new(0)) do |word, hash|\n hash[word] += 1\n end\n\n counts.each do |word, count|\n puts \"#{word} => #{count}\"\n end\nend",
"def simple_search (search_array, search_number)\n counter = 0\n search_array.each do |number|\n if number == search_number \n return counter \n else \n counter +=1 \n end \nend\n nil \nend",
"def count_occurence(array)\n counts = Hash.new(0)\n array.each { |name| counts[name] += 1 }\n puts counts\n\n price_calculator=PriceCalculator.new\n price_calculator.sepitem_quantity(counts)\n\n end",
"def find_counts(code)\n find_by_code(code).map { |row| row[1] }.sort.reverse\n end",
"def one_rv\n count = 0\n for x in 1...@elements.length\n if @elements[x].remaining_vals.length == 1\n count+=1\n end\n end\n count\n end",
"def num_occur(array, target)\n return 0 if array.empty?\n occurrence = array.first == target ? 1 : 0\n occurrence + num_occur(array.drop(1))\nend",
"def gem_element arr\n freq = Hash.new(0)\n count = 0\n\n combo = arr.map(&:chars).map(&:uniq).flatten\n combo.each{ |key| freq[key]+=1 }\n freq.each{ |k,v| count +=1 if v == arr.size }\n count\n \nend",
"def query_1\n document_ids = Perpetuity[Document].all.to_a.map(&:id)\n index_num = [ 42, 76, 44, 90, 8, 12, 4, 77, 43, 99]\n all_ids = []\n index_num.each do |num|\n all_ids << document_ids[num]\n end\n\n processed_number = 0\n all_ids.each do |id|\n Perpetuity[Document].find(id)\n processed_number+=1\n end\n return processed_number\nend",
"def count_array(array, val)\n i = 0\n output = 0\n while i < array.length\n if array[i] == val\n output += 1\n end\n i += 1\n end\n return output\nend",
"def count_occurences(array)\n\n # interate over array and add unique values as keys to a new hash\n unique_values = {}\n\n array.each do |item|\n if unique_values.keys.include?(item) == false\n unique_values[item] = 0\n end\n end\n # ------------\n\n\n # interate over hash and array, +1 the value of key for every match in array\n unique_values.each_key do |key|\n array.each do |item|\n if key == item\n unique_values[key] += 1\n end\n end\n end\n\n unique_values\nend",
"def count(arr)\n counter = 0\n arr.each { |el| counter += 1 if yield(el) }\n counter\nend",
"def num_occur(array, target)\n count = 0\n if array.empty?\n 0\n else\n count = 1 if array.first == target\n count += num_occur(array.drop(1), target)\n count\n end\nend",
"def search_array (array, number)\n counter = 0\n index = []\n array.each do |value|\n index << counter if value == number\n counter += 1\n end\n index.empty? ? nil : index\n end",
"def actor_list(array)\n #the variable actors is equal to a new array that only has the key actors in each of the movies\n actor_in_bond = array.map {|movie| movie[:actor]}\n #list variable gives me the array of unique people out of the list of array\n list = actor_in_bond.uniq\n #variable movies per actor is equal to a iterator that will give me a new array of the movie actor from the list and\n #check the number of times the actor's name shows up in the array actor in bond then it will\n #give me an array of the actors name with the number of movie it is in\n movies_per_actor = list.map {|movie| \"#{movie} => #{actor_in_bond.count(movie)}\"}\n #outputs the list of actors with number of movies they are in\n puts movies_per_actor\nend",
"def count_results(result_array)\n results = empty_counter\n result_array.each do |topic|\n topic.keys.each {|key| results[key] += topic[key]}\n end\n results\n end",
"def count(array)\n count = 0\n array.each do |x|\n count += 1\n end\n\n return count\nend",
"def count_occurrences(array)\n\toccurences = {}\n\n\tarray.each do |element|\n\t\toccurences[element] = array.count(element)\n\tend\n\n\toccurences.each do |element, count|\n\t\tputs \"#{element} => #{count}\"\n\tend\t\nend",
"def element_count(arr)\n # Write your code here\n array = arr.uniq\n result = {}\n i = 0\n x = array.length\n loop do\n result.store(array[i],arr.count(array[i]))\n i += 1\n break if i == x\n end \nreturn result\nend",
"def customer_pet_count(customer_array)\n customer_array[:pets].count\nend",
"def count\n all.size\n end",
"def count_elements(array)\n new_array = array.uniq\n new_array.each do |hash|\n hash[:count] = array.count(hash)\n end\n new_array\nend",
"def tester_device_in_bugs_count(testerId, deviceId, bugs_array)\n\tcount = bugs_array.select {|bug| bug['deviceId'] == deviceId && bug['testerId'] == testerId}.count\n\t{\"testerId\" => testerId, \"deviceId\" => deviceId, \"count\" => count}\n\nend",
"def slow_dance(target, tiles_array)\r\n count = 0 \r\n tiles_array.each do |ele|\r\n if ele == target\r\n return count\r\n else\r\n count +=1\r\n end\r\n end\r\nend",
"def survey_count\n @pub_surveys = Survey.select('id').where(status: 'published')\n @pub_survey_ids = Array.new\n\n @pub_surveys.each do |u|\n @pub_survey_ids.push (u.id)\n end\n \n @user_taken_surveys = UserSurvey.where(user_id: current_login)\n @user_taken_survey_ids = Array.new\n\n @user_taken_surveys.each do |u|\n @user_taken_survey_ids.push (u.survey_id)\n end\n\n @untaken_pub_surveys_ids = Array.new\n\n @pub_survey_ids.each do |u|\n if @user_taken_survey_ids.index(u)\n puts \"it exists\"\n else\n @untaken_pub_surveys_ids.push (u)\n end\n end\n\n if @untaken_pub_surveys_ids.empty?\n count = 0\n else\n count = @untaken_pub_surveys_ids.count\n end\n return count\n end",
"def count\n each.size\n end",
"def element_frequency_count\n collection.each_with_object(Hash.new(0)) {|element, occurrence| occurrence[element] += 1}\n end",
"def frequency(word)\n arr = $words.select do |sample|\n word == sample\n end\n arr.size\nend",
"def count_filter_email\n email_filter.reduce(0) do |sum, element| ##???\n sum += 1\n end\nend",
"def part1()\n @seats = @input.map(&:dup)\n until rules_part1() == 0\n end\n count = 0\n @seats.each { |row| count += row.count('#') }\n count\nend",
"def count(*array)\n total = 0\n array.each { |element| total += 1 if yield(element) }\n total\nend",
"def search_array(array, number)\n search_result = Array.new # Defining a search result array\n count = 0 # count to loop through array\n\n # The following logic goes into the array using the counter\n while count < array.length\n \t# If the search number matches a value in the array return that index \n \t# Pushing it to the search_result array\n if number == array[count]\n return search_result.push(count)\n count += 1\n else\n count += 1\n end\n end\nend",
"def available_spots(arr, num)\n count = 0\n arr.each_with_index do |item, index|\n next if index == arr.count - 1\n if item.odd? == arr[index + 1].odd? \n if item.odd? != num.odd?\n next\n else\n count += 1\n end\n else\n count += 1\n end\n end\n count\nend",
"def traversal_9\n num_occurances = 0\n Perpetuity[Address].all.to_a.each do |address|\n num_occurances += 1 if address.city.downcase.split('').first == address.city.downcase.split('').last\n end\n return num_occurances\nend",
"def count\n elements.count\n end",
"def test_array_select2\n a = [2, 5, 2, 2, 3]\n num = a.select {|n| n == 2}\n assert_equal([2, 2, 2], num)\n end",
"def run\n # Digits 1,4,7,8 have 2,4,3,7 segments respectively\n @list.map{|line| line[1]}.flatten.map(&:length).filter{|len| [2, 4, 3, 7].include?(len)}.count\n end",
"def count1(collection)\n true_counter = 0\n collection.each { |element| true_counter += 1 if yield(element) }\n true_counter\nend",
"def count_elements(array)\n array.each_with_object(Hash.new(0)){|arr, hash| hash[arr[:name]] += 1}.map{|key, value|{:name=>key, :count=>value}}\nend",
"def num_occur(array, target)\n return 0 if array == []\n #every element appears zero times\n dup_array = array.dup\n value = dup_array.shift\n #previous\n if value == target\n count = num_occur(dup_array, target) + 1 #return previous, add one\n else\n count = num_occur(dup_array, target) #return previous value\n end\n count #ensures count is used for prior calls\n\nend",
"def count(array)\n hash = {}\n array.each do |item|\n hash[item] = array.count(item)\n end\n hash\nend",
"def count\n to_a.size\n end",
"def count\n to_a.size\n end",
"def perform_global_search(pattern, arr, dir)\n traverse(pattern, arr, dir)\n output_count(arr)\n end",
"def nitems\n count = 0\n i = 0\n lim = self.__size\n while i < lim\n count += 1 unless self.__at(i)._equal?(nil)\n i += 1\n end\n count\n end",
"def unknown_count\n (select &:unknown?).count\n end",
"def count(collection)\n counter = 0\n collection.each { |element| counter += 1 if yield(element) }\n counter\nend",
"def count_elements(array)\n #Build hash where key = name and val = count\n counts = Hash.new(0)\n array.each do |element|\n counts[element[:name]] += 1\n end\n\n #Turn this into array of hashes\n ret = []\n counts.map do |key, val|\n h = {}\n h[:name] = key\n h[:count] = val\n ret << h\n end\n ret\nend",
"def get_count_of_eobs_containing_image_numbers_that_of_job(eobs)\r\n eobs = eobs.select do |eob|\r\n (pages_from..pages_to).include?(eob.image_page_no)\r\n end\r\n eobs.length\r\n end",
"def driver_ride_count(driver_id, rides)\n driver_rides = rides.select { |ride| ride [:driver_id] == driver_id }\n total_num_rides_for_driver = driver_rides.length\n puts \"Problem 1: #{driver_id}: #{total_num_rides_for_driver} rides\"\nend"
] |
[
"0.66130316",
"0.6239821",
"0.6126654",
"0.61057043",
"0.60812604",
"0.60614747",
"0.6009859",
"0.5978063",
"0.5955366",
"0.59545875",
"0.5944068",
"0.5937777",
"0.5913292",
"0.58522654",
"0.58372915",
"0.581719",
"0.5797452",
"0.57965857",
"0.57927793",
"0.57775444",
"0.57757753",
"0.5763916",
"0.57489955",
"0.57430774",
"0.5741987",
"0.57249063",
"0.5715353",
"0.57031703",
"0.57028586",
"0.56984913",
"0.56980616",
"0.56933236",
"0.56919056",
"0.5684789",
"0.56810135",
"0.56509066",
"0.5631677",
"0.56315917",
"0.5624015",
"0.5619356",
"0.5607643",
"0.560586",
"0.560224",
"0.5598777",
"0.5582176",
"0.5578037",
"0.55721444",
"0.55719066",
"0.5570936",
"0.55636686",
"0.555677",
"0.5553241",
"0.55471104",
"0.55460995",
"0.55448854",
"0.5542345",
"0.5540478",
"0.55315346",
"0.5530951",
"0.5529787",
"0.55222666",
"0.55146",
"0.5510208",
"0.5509531",
"0.550612",
"0.5500845",
"0.549704",
"0.54941416",
"0.54925245",
"0.5490202",
"0.5487369",
"0.5486107",
"0.54853153",
"0.5481886",
"0.5476986",
"0.54689664",
"0.54663426",
"0.5457007",
"0.54501957",
"0.54492575",
"0.54462886",
"0.5444869",
"0.54428214",
"0.54416114",
"0.54359645",
"0.543503",
"0.5433216",
"0.54264414",
"0.5423056",
"0.5422473",
"0.54215664",
"0.54213893",
"0.54199696",
"0.54199696",
"0.5412631",
"0.5406106",
"0.5401754",
"0.53998196",
"0.5398665",
"0.53986144",
"0.5397095"
] |
0.0
|
-1
|
GET /projects GET /projects.json
|
def index
@projects = Project.all
if params[:filtered]
@custom_search = true
end
if params[:search]
@projects = Project.search(params[:search]).order("created_at DESC")
else
@projects = Project.all.order("created_at DESC")
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def listprojects\n get('listprojects.json')['projects']\n end",
"def list\n get 'projects'\n end",
"def projects\n request(method: 'getAllProjects')\n end",
"def projects\n resource 'projects'\n end",
"def projects(params = {})\n make_get_request('/account/projects', params)\n end",
"def projects\n Sifter.\n get(\"/api/projects\").\n parsed_response[\"projects\"].\n map { |p| Sifter::Project.new(p) }\n end",
"def index\n @projects = Project.all\n render json: @projects\n end",
"def index\n # @projects = @current_user.projects\n @projects = Project.all\n json_response(@projects)\n end",
"def index\n @projects = Project.all\n render json: @projects, status: :ok\n end",
"def get_projects\n me = request('/services/v5/me')\n me['projects']\n end",
"def index\n @projects = current_user.projects\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def get\n CircleCi.request(conf, '/projects').get\n end",
"def projects\n return forbidden unless current_account # already returns a 401 if credentials aren't supplied\n opts = { :include_document_ids => params[:include_document_ids] != 'false' }\n @response = {'projects' => Project.accessible(current_account).map {|p| p.canonical(opts) } }\n render_cross_origin_json\n end",
"def projects\n records \"project\", \"/project/list\"\n end",
"def index\n @projects = current_user.projects.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def index\n @projects = Project.all\n render json: @projects, layout: false\n end",
"def projects(params = {})\n fetch_all('projects', 'projects', params)\n end",
"def index\n @projects = Project.all_for_user(current_user.id)\n render json: @projects.to_json(include: :project_detail), status: 200\n end",
"def index\n @projects = Project.visible\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def index\n @user = User.find_by(id: params[:user_id])\n @project = @user.projects\n if @project \n render :json => @project\n else\n render :json => 422\n end\n end",
"def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @projects }\n end\n end",
"def all_projects()\n @endpoint = \"/projects.json?limit=100\"\n setup_get\n res = @http.request(@req)\n return JSON.load(res.body)[\"projects\"].sort_by { |proj| proj[\"name\"] }\n end",
"def index\n \n @workspaces = current_user.workspaces\n # debugger\n @projects = Project.where(:workspace_id => @workspace)\n\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def projects(options = {})\n get(\"projects\", options).projects\n end",
"def list_projects\n handle_action_exceptions(__method__) do\n cmd_line = ['listprojects']\n cmd_line << 'json' if @json\n\n handle_return(@toolshck_ether.cmd(cmd_line.join(' ')))\n end\n end",
"def index\n @projects = Project.includes(:user).all\n respond_with(@projects) do |format|\n format.json { render :json => {:list => @projects.as_json, :current_user => current_user.as_json} }\n format.html\n end\n end",
"def projects(req_params = {})\n name = 'Projects'\n params = { req: req_params }\n\n data = endpoint(name: name, params: params).do_get\n\n collection name, data\n end",
"def index \n\n @projects = Project.all\n respond_to do |format|\n format.html {render :template => \"projects/index\"}\n format.json { render json: @projects }\n end\n end",
"def index\n @projects = Project.with_permissions_to(:read)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def projects\n @projects ||= Harvest::API::Projects.new(credentials)\n end",
"def show\n @project = @client.projects.find(params[:id])\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end",
"def index\n @projects = Project.where user: current_user\n render json: @projects, each_serializer: Projects::IndexSerializer\n end",
"def index\n @projects = Project.order_by_company_and_project.paginate(page: params[:page] || 1, per_page: helpers.pager_per_page)\n respond_to do |format|\n message = @projects.present? ? \"\" : \"There are no projects available at this time\"\n format.json do\n status = @projects.present? ? :ok : :not_found\n render json: { response: @projects, status: status, message: message }\n end\n format.html do\n # Only authorize html format, json is okay because we use it as\n # an api.\n authorize(:project)\n flash[:alert] = message unless message.blank?\n @projects\n end\n end\n end",
"def index\n if signed_in?\n @projects = current_user.projects\n respond_to do |format|\n format.html { render 'projects/index' }\n format.json { render template: 'projects/index.json.jbuilder' }\n end\n else\n redirect_to :projects\n end\n end",
"def get_projects_of_user\n respond_to do |format|\n format.json {\n #param = params[:payload]\n #@user = User.find_by_id(param[:id])\n @projects = Project.where(:user_id => @current_user.id)\n if @projects\n render :json => @projects\n else\n render :nothing => true, :status => 200, :content_type => 'text/html'\n end\n }\n end\n end",
"def get_projects_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ProjectsApi.get_projects ...'\n end\n # resource path\n local_var_path = '/projects'\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['Token']\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'Projects')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ProjectsApi#get_projects\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def show_all_projects\r\n json = GoodData.get GoodData.profile.projects\r\n puts \"You have this project available:\"\r\n json[\"projects\"].map do |project|\r\n pid = project[\"project\"][\"links\"][\"roles\"].to_s\r\n puts \"Project name: #{project[\"project\"][\"meta\"][\"title\"].bright} Project PID: #{pid.match(\"[^\\/]{32}\").to_s.bright}\"\r\n end\r\n end",
"def init_projects\n @projects = []\n\n response = @conn.get do |req|\n req.url \"/api/v1/projects\"\n req.headers = rest_headers\n end\n\n @projects = json(response.body)[:projects]\n end",
"def projects\n @projects ||= begin\n http = Net::HTTP.new(API_HOST, API_PORT)\n http.use_ssl = true\n http.ca_file = (Twigg.root + 'files' + 'github.pem').to_s\n http.verify_mode = OpenSSL::SSL::VERIFY_PEER\n uri = ORG_REPOS_ENDPOINT % Config.github.organization\n headers = { 'Authorization' => \"token #{Config.github.token}\" }\n\n [].tap do |names|\n begin # loop: page through project list\n request = Net::HTTP::Get.new(uri, headers)\n response = http.request(request)\n raise \"Bad response #{response.inspect}\" unless response.is_a?(Net::HTTPOK)\n names.concat JSON[response.body].map { |repo| repo['name'] }\n uri = parse_link(response['Link'])\n end until uri.nil?\n end\n end\n end",
"def projects\n @projects = Project.order(created_at: :desc).page(@page).per(10)\n respond_to do |format|\n format.html\n format.js { render :projects}\n end\n end",
"def list_project(optional={})\n\t\targs = self.class.new_params\n\t\targs[:method] = 'GET'\n\t\targs[:pattern] = '/projects'\n\t\targs[:query]['Action'] = 'ListProject'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\targs[:scheme] = 'http'\n\t\tif optional.key? :page\n\t\t\targs[:query]['Page'] = optional[:page]\n\t\tend\n\t\tif optional.key? :page_size\n\t\t\targs[:query]['PageSize'] = optional[:page_size]\n\t\tend\n\t\tif optional.key? :project_owner\n\t\t\targs[:query]['ProjectOwner'] = optional[:project_owner]\n\t\tend\n\t\tself.run(args)\n\tend",
"def project(project_id, options={})\n response_body = nil\n begin\n response = connection.get do |req|\n req.url \"/api/v1/projects/#{project_id}\", options\n end\n response_body = response.body\n rescue MultiJson::DecodeError => e\n #p 'Unable to parse JSON.'\n end\n \n response_body\n end",
"def index\n\t\tif present_user.role? 'admin'\n\t\t\t@projects = Project.all\n\t\telse\n\t\t\t@projects = present_user.projects\n\t\tend\n\t\tmake_breadcrumbs\n\n\t\trespond_to do |format|\n\t\t\tformat.html # index.html.erb\n\t\t\tformat.json { render json: @projects }\n\t\tend\n\tend",
"def show\n @projects = find_projects\n end",
"def index\n projects = current_user.admin_projects.paginate(:page => params[:page])\n render json: projects\n end",
"def list\r\n @projects = Project.where(user:current_user).order(created_at: :desc).page(params[:page])\r\n respond_with(@projects)\r\n end",
"def index\n @user = User.find_by_id(session[:userid])\n @projects = current_user_projects\n respond_to do |format|\n format.html # index.html.erb\n format.json\n end\n end",
"def index\n @user = get_user\n @projects = Project.all\n # render :inline => @projects.to_json\n end",
"def project\n request :project\n end",
"def show\n\n render json: Project.all\n\n end",
"def listProjects \n uri = URI(RUNDECKSERVER + ':' + RUNDECKPORT + '/api/1/projects')\n http = Net::HTTP.new(uri.host, uri.port)\n headers = {\n 'Content-Type'=> 'application/json',\n 'X-RunDeck-Auth-Token'=> API_KEY \n}\n r = http.get(uri.path, headers)\n return r.body.force_encoding(\"UTF-8\")\n\nend",
"def available_projects_list\n uri = \"#{@api_url}?access_token=#{@access_token}\"\n get uri\n end",
"def index\n @projects = current_user.active_projects.includes(:project_errors)\n @project_invitations = current_user.user_projects.pending\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def project(project_id, params = {})\n make_get_request(\"/projects/#{project_id}\", params)\n end",
"def list_projects # :nologin:\n query = create_query(:Project, :all, :by => :title)\n show_selected_projects(query)\n end",
"def index\n @projects = Project.includes(:participants).all\n\n render json: @projects, include: :participants, status: 200\n end",
"def show\n render json: @project\n end",
"def projects\n @projects\n end",
"def index\n @projects = @projects.includes(:latest_iteration).where(:tenant_id => current_user.tenant).order(\"name\").page(params[:page]).per(DEFAULT_ROWS_PER_PAGE)\n\n respond_with @projects\n end",
"def index\n @projects = Service::JIRA.projects\n respond_with(@projects) do |format|\n format.json { render json: @projects.to_a.sort_by(&:name).map(&:attrs).to_json }\n end\n end",
"def projects\n Harvest::Resources::Project\n end",
"def project(project_id, query_params = nil)\n get(\"/projects/#{project_id}\", query_params)\n end",
"def get_projects_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: ProjectsApi#get_projects ...\"\n end\n \n # resource path\n path = \"/Projects\".sub('{format}','json')\n\n # query parameters\n query_params = {}\n query_params[:'brief'] = opts[:'brief'] if opts[:'brief']\n query_params[:'skip'] = opts[:'skip'] if opts[:'skip']\n query_params[:'top'] = opts[:'top'] if opts[:'top']\n query_params[:'count_total'] = opts[:'count_total'] if opts[:'count_total']\n\n # header parameters\n header_params = {}\n\n # HTTP header 'Accept' (if needed)\n _header_accept = ['application/json']\n _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result\n\n # HTTP header 'Content-Type'\n _header_content_type = ['application/json']\n header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n \n\n auth_names = []\n data, status_code, headers = @api_client.call_api(:GET, path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'Array<APIProject>')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ProjectsApi#get_projects\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def index\n @projects = @namespace.projects.all\n end",
"def projects\n tmp = client.get @json['user']['links']['projects']\n tmp['projects'].map do |project_meta|\n project_uri = project_meta['project']['links']['self']\n project = client.get project_uri\n client.factory.create(GoodData::Project, project)\n end\n end",
"def get_projects_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ProjectApi.get_projects ...'\n end\n # resource path\n local_var_path = '/v1/project'\n\n # query parameters\n query_params = opts[:query_params] || {}\n query_params[:'name'] = opts[:'name'] if !opts[:'name'].nil?\n query_params[:'excludeInactive'] = opts[:'exclude_inactive'] if !opts[:'exclude_inactive'].nil?\n\n # header parameters\n header_params = opts[:header_params] || {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:body] \n\n # return_type\n return_type = opts[:return_type] || 'Array<Project>' \n\n # auth_names\n auth_names = opts[:auth_names] || ['X-Api-Key']\n\n new_options = opts.merge(\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ProjectApi#get_projects\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def index\n\t\t@projects = Project.all\n\tend",
"def index\n #@projects = []\n if current_user\n #@projects = current_user.projects.where(\"memberships.status >= ?\", 1)\n end\n\n if params[:id]\n @project = Project.find(params[:id])\n authorize! :read, @project\n else\n @project = @projects.first\n end\n\n respond_to do |format|\n format.html # index.html.erb\n format.js { render :action => 'show'}\n format.json { render json: @projects }\n end\n end",
"def index_participating\n projects = current_user.projects.paginate(:page => params[:page])\n render json: projects\n end",
"def list_project(optional={})\n\t\targs = self.class.new_params\n\t\targs[:method] = 'GET'\n\t\targs[:query]['Action'] = 'ListProject'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\targs[:scheme] = 'http'\n\t\tif optional.key? :page\n\t\t\targs[:query]['Page'] = optional[:page]\n\t\tend\n\t\tif optional.key? :page_size\n\t\t\targs[:query]['PageSize'] = optional[:page_size]\n\t\tend\n\t\tif optional.key? :project_owner\n\t\t\targs[:query]['ProjectOwner'] = optional[:project_owner]\n\t\tend\n\t\tself.run(args)\n\tend",
"def project\n return forbidden unless current_account and params[:id] and (request.format.json? || request.format.js? || request.format.text?)\n project = Project.accessible(current_account).find(params[:id].to_i)\n return not_found unless project\n opts = { :include_document_ids => params[:include_document_ids] != 'false' }\n @response = {'project' => project.canonical(opts)}\n render_cross_origin_json\n end",
"def show \n project= Project.find(params[:id])\n\n render json: project\n end",
"def list_projects(company_id: )\n url = \"#{@base_url}/vapid/projects?company_id=#{company_id}\"\n HTTParty.get(url, headers: procore_headers(token: @customer_info[:token], company_id: @customer_info[:company_id] )).parsed_response\n end",
"def index\n @projects = current_user.projects\n end",
"def index\n @projects = current_user.projects\n end",
"def index\n @projects = current_user.projects\n end",
"def index\n @projects = current_user.projects\n end",
"def index\n @projects = current_user.projects\n end",
"def index\n @projects = current_user.projects\n end",
"def index\n @projects = current_user.projects\n end",
"def index\n @projects = current_user.projects\n end",
"def index\n @projects_people = ProjectsPerson.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects_people }\n end\n end",
"def index\r\n @projects = current_user.projects\r\n end",
"def projects\n PivotalTracker::Project.all\n end",
"def show\n render json: Project.where(id: params.fetch(:id))\n end",
"def get_projects\n @params=task_params\n @client=current_user.clients.find(@params[:client_id])\n counter=0\n @res=[]\n @client.projects.each do |c|\n if c.users.include? current_user\n @res[counter]={\n project_id: c.id, \n name: c.name\n }\n counter+=1\n end\n end\n respond_to do |format|\n format.json {render json: @res.uniq}\n end\n end",
"def show\n @projects = Project.all\n end",
"def projects\n @projects ||= begin\n user = api('user')\n api(\"users/#{user['id']}/projects\").sort_by { |p| p['id'] }\n end\nend",
"def list_projects_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: QcApi.list_projects ...\"\n end\n # resource path\n local_var_path = \"/projects.json\"\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['api_key']\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'Array<Project>')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: QcApi#list_projects\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def getProjectID()\n result = RestClient.get GITHUB_API + PROJECTS_PATH, :accept => 'application/vnd.github.inertia-preview+json', :'Authorization' => 'token ' + CONFIG['OAUTH']\n result = JSON.parse(result) \n end",
"def index\n @projects = Project.all\n end",
"def index\n @projects = Project.all\n end",
"def index\n @projects = Project.all\n end"
] |
[
"0.8574897",
"0.8386689",
"0.8355737",
"0.8062607",
"0.80368364",
"0.8002139",
"0.78593457",
"0.7834634",
"0.78324",
"0.7799698",
"0.77792805",
"0.7748103",
"0.77139485",
"0.7700251",
"0.7696023",
"0.7695487",
"0.7695487",
"0.7695487",
"0.7695487",
"0.7695487",
"0.7695487",
"0.7695487",
"0.7695384",
"0.7677249",
"0.7659848",
"0.76413786",
"0.7627596",
"0.76157665",
"0.76007134",
"0.75998086",
"0.7599048",
"0.755127",
"0.75476474",
"0.7504184",
"0.7464399",
"0.7463047",
"0.74520797",
"0.7440121",
"0.74273944",
"0.74115896",
"0.74086154",
"0.7406792",
"0.73953074",
"0.73152006",
"0.72899425",
"0.7288984",
"0.727693",
"0.72592014",
"0.725888",
"0.72443324",
"0.72430474",
"0.7232267",
"0.7224122",
"0.7218089",
"0.7194763",
"0.7187098",
"0.71705997",
"0.7170378",
"0.7167435",
"0.7164896",
"0.71607876",
"0.7140332",
"0.7130536",
"0.7128779",
"0.7127035",
"0.7124004",
"0.7118136",
"0.711526",
"0.7114364",
"0.71083033",
"0.71005213",
"0.7098299",
"0.70919305",
"0.70723647",
"0.70523155",
"0.70496404",
"0.70492387",
"0.7042553",
"0.70393467",
"0.7036608",
"0.7033363",
"0.7031996",
"0.7031996",
"0.7031996",
"0.7031996",
"0.7031996",
"0.7031996",
"0.7031996",
"0.7031996",
"0.70277584",
"0.7026879",
"0.7022911",
"0.70143616",
"0.70081574",
"0.70047146",
"0.70036596",
"0.7003546",
"0.7002825",
"0.69961166",
"0.69961166",
"0.69961166"
] |
0.0
|
-1
|
GET /projects/1 GET /projects/1.json
|
def show
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def list\n get 'projects'\n end",
"def listprojects\n get('listprojects.json')['projects']\n end",
"def show\n @project = @client.projects.find(params[:id])\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end",
"def projects\n resource 'projects'\n end",
"def index\n @projects = Project.all\n render json: @projects, status: :ok\n end",
"def index\n @projects = Project.all\n render json: @projects\n end",
"def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def index\n @user = User.find_by(id: params[:user_id])\n @project = @user.projects\n if @project \n render :json => @project\n else\n render :json => 422\n end\n end",
"def projects\n request(method: 'getAllProjects')\n end",
"def project(project_id, params = {})\n make_get_request(\"/projects/#{project_id}\", params)\n end",
"def index\n @projects = Project.visible\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @projects }\n end\n end",
"def show\n render json: Project.where(id: params.fetch(:id))\n end",
"def show \n project= Project.find(params[:id])\n\n render json: project\n end",
"def index\n @projects = Project.all_for_user(current_user.id)\n render json: @projects.to_json(include: :project_detail), status: 200\n end",
"def project(project_id, options={})\n response_body = nil\n begin\n response = connection.get do |req|\n req.url \"/api/v1/projects/#{project_id}\", options\n end\n response_body = response.body\n rescue MultiJson::DecodeError => e\n #p 'Unable to parse JSON.'\n end\n \n response_body\n end",
"def index\n @projects = current_user.projects\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end",
"def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end",
"def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end",
"def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end",
"def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end",
"def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end",
"def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end",
"def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end",
"def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end",
"def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end",
"def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end",
"def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end",
"def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end",
"def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end",
"def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end",
"def project(project_id, query_params = nil)\n get(\"/projects/#{project_id}\", query_params)\n end",
"def project(project_id)\n resource \"projects/#{project_id}\"\n end",
"def index\n @projects = Project.all\n render json: @projects, layout: false\n end",
"def getProjectID()\n result = RestClient.get GITHUB_API + PROJECTS_PATH, :accept => 'application/vnd.github.inertia-preview+json', :'Authorization' => 'token ' + CONFIG['OAUTH']\n result = JSON.parse(result) \n end",
"def show\n @project = Project.find(params[:id])\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end",
"def get\n CircleCi.request(conf, '/projects').get\n end",
"def index\n # @projects = @current_user.projects\n @projects = Project.all\n json_response(@projects)\n end",
"def projects\n records \"project\", \"/project/list\"\n end",
"def projects\n Sifter.\n get(\"/api/projects\").\n parsed_response[\"projects\"].\n map { |p| Sifter::Project.new(p) }\n end",
"def index \n\n @projects = Project.all\n respond_to do |format|\n format.html {render :template => \"projects/index\"}\n format.json { render json: @projects }\n end\n end",
"def index\n @projects = current_user.projects.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def index\n \n @workspaces = current_user.workspaces\n # debugger\n @projects = Project.where(:workspace_id => @workspace)\n\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def show\n @project = Project.find(params[:id])\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @project }\n end\n end",
"def show\n render json: @project\n end",
"def show\n repo = ProjectRepo.new current_user\n @v_project = repo.get(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @v_project }\n end\n end",
"def find_project(name)\n get(\"/projects/#{name}\")\n end",
"def find_project(name)\n get(\"/projects/#{name}\")\n end",
"def show\n @project = Project.find_by(id: params[:id])\n if @project\n render :json => @project\n else\n render :json => 422\n end\n end",
"def projects(params = {})\n make_get_request('/account/projects', params)\n end",
"def project\n request :project\n end",
"def project\n return forbidden unless current_account and params[:id] and (request.format.json? || request.format.js? || request.format.text?)\n project = Project.accessible(current_account).find(params[:id].to_i)\n return not_found unless project\n opts = { :include_document_ids => params[:include_document_ids] != 'false' }\n @response = {'project' => project.canonical(opts)}\n render_cross_origin_json\n end",
"def show \n render :json => Project.find_by_id(params[:id])\n end",
"def show\n @ourproject = Ourproject.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @ourproject }\n end\n end",
"def get_project(project_id)\n http = Net::HTTP.new(@city_db_url, @port)\n http.read_timeout = 1000\n if @city_db_is_https\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n end\n\n request = Net::HTTP::Get.new(\"/projects/#{project_id}.json\")\n request.add_field('Content-Type', 'application/json')\n request.add_field('Accept', 'application/json')\n request.basic_auth(ENV['URBANOPT_USERNAME'], ENV['URBANOPT_PASSWORD'])\n\n response = http.request(request)\n if response.code != '200' # success\n @runner.registerError(\"Bad response #{response.code}\")\n @runner.registerError(response.body)\n @result = false\n return {}\n end\n\n result = JSON.parse(response.body, symbolize_names: true)\n return result\n end",
"def index\n @projects = Project.with_permissions_to(:read)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def show\n @projectresource = Projectresource.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @projectresource }\n end\n end",
"def index\n @projects = Project.where user: current_user\n render json: @projects, each_serializer: Projects::IndexSerializer\n end",
"def show \n respond_to do |format|\n format.json {\n\n @project = Project.find_by_id(params[:id])\n\n if @project\n render :json => @project\n else\n render :nothing => true, :status => 200, :content_type => 'text/html'\n end\n }\n end\n end",
"def show\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end",
"def show\n @current_project = CurrentProject.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @current_project }\n end\n end",
"def show\n respond_with(@project) do |format|\n format.json { render json: @project.as_json }\n format.html\n end\n end",
"def show\n @show_project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @show_project }\n end\n end",
"def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end",
"def show\n respond_with @project do |format|\n format.json do\n render json: @project.as_json.merge(\n commits_url: project_commits_url(@project, format: 'json'),\n commits: @project.commits.order('committed_at DESC').limit(10).map { |commit|\n commit.as_json.merge(\n percent_done: commit.fraction_done.nan? ? 0.0 : commit.fraction_done*100,\n translations_done: commit.translations_done,\n translations_total: commit.translations_total,\n strings_total: commit.strings_total,\n import_url: import_project_commit_url(@project, commit, format: 'json'),\n sync_url: sync_project_commit_url(@project, commit, format: 'json'),\n url: project_commit_url(@project, commit),\n status_url: project_commit_url(@project, commit),\n )\n }\n )\n end\n end\n end",
"def show\n # turn ruby database into json\n # route to the project 3 page with this json\n # id = 1\n end",
"def show\n\n render json: Project.all\n\n end",
"def projects(params = {})\n fetch_all('projects', 'projects', params)\n end",
"def index\n @about_projects = AboutProject.last(1)\n\n respond_to do |format|\n format.json {render json: @about_projects[0], :only => [:description]}\n end\n end",
"def show\n set_surrogate_key_header \"api/platforms/#{@platform.id}/projects\"\n set_cache_control_headers 3600\n end",
"def show\n @projects = find_projects\n end",
"def get_project(optional={})\n\t\targs = self.class.new_params\n\t\targs[:method] = 'GET'\n\t\targs[:pattern] = '/projects/[ProjectName]'\n\t\targs[:query]['Action'] = 'GetProject'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\targs[:scheme] = 'http'\n\t\tif optional.key? :project_name\n\t\t\targs[:path]['ProjectName'] = optional[:project_name]\n\t\tend\n\t\tself.run(args)\n\tend",
"def show_by_gitpath\n @project = Project.includes(:users).includes(:technos).find_by_gitpath(params[:gitpath])\n\n respond_to do |format|\n format.json { render json: @project, status: 200 }\n end\n end",
"def project\n @client.project(:id => project_id)\n end",
"def list_projects\n handle_action_exceptions(__method__) do\n cmd_line = ['listprojects']\n cmd_line << 'json' if @json\n\n handle_return(@toolshck_ether.cmd(cmd_line.join(' ')))\n end\n end",
"def index\n #@projects = []\n if current_user\n #@projects = current_user.projects.where(\"memberships.status >= ?\", 1)\n end\n\n if params[:id]\n @project = Project.find(params[:id])\n authorize! :read, @project\n else\n @project = @projects.first\n end\n\n respond_to do |format|\n format.html # index.html.erb\n format.js { render :action => 'show'}\n format.json { render json: @projects }\n end\n end",
"def projects\n return forbidden unless current_account # already returns a 401 if credentials aren't supplied\n opts = { :include_document_ids => params[:include_document_ids] != 'false' }\n @response = {'projects' => Project.accessible(current_account).map {|p| p.canonical(opts) } }\n render_cross_origin_json\n end",
"def get_projects_of_user\n respond_to do |format|\n format.json {\n #param = params[:payload]\n #@user = User.find_by_id(param[:id])\n @projects = Project.where(:user_id => @current_user.id)\n if @projects\n render :json => @projects\n else\n render :nothing => true, :status => 200, :content_type => 'text/html'\n end\n }\n end\n end",
"def get\n render json: Project.select(:id, \"name as label\")\n end",
"def index\n @projects = Project.includes(:user).all\n respond_with(@projects) do |format|\n format.json { render :json => {:list => @projects.as_json, :current_user => current_user.as_json} }\n format.html\n end\n end",
"def details\n get(\"project/details\")[\"project\"]\n end",
"def show\n @unfinished_project = UnfinishedProject.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @unfinished_project }\n end\n end",
"def show\n @workspaces = current_user.workspaces\n @project = Project.find(params[:id])\n @workspace = Workspace.find(params[:workspace_id])\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end",
"def index\n @user = User.find_by_id(session[:userid])\n @projects = current_user_projects\n respond_to do |format|\n format.html # index.html.erb\n format.json\n end\n end",
"def get(project_name)\n response = get_request(\"/projects/#{project_name}/\")\n TheShiningSource::Project.new(response)\n end",
"def show_project\r\n @project = Project.find(params[:id])\r\n @id = @project.id\r\n respond_to do |format|\r\n format.html { render 'project_control/view' }\r\n format.json { render json: @project }\r\n end\r\n end",
"def getProject(project)\r\n\t\t\t\tproject_json = JSON.parse project\r\n\t\t\t\tproject_array = project_json[\"projects\"]\r\n\t\t\t\treturn jsonToProject(project_array[0])\r\n\t\t\tend",
"def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @projects }\n #format.json { render json: @project.as_json(:include => [:client, :project_participants] ) }\n end\n end",
"def index\n if signed_in?\n @projects = current_user.projects\n respond_to do |format|\n format.html { render 'projects/index' }\n format.json { render template: 'projects/index.json.jbuilder' }\n end\n else\n redirect_to :projects\n end\n end",
"def index\n @projects = @projects.includes(:latest_iteration).where(:tenant_id => current_user.tenant).order(\"name\").page(params[:page]).per(DEFAULT_ROWS_PER_PAGE)\n\n respond_with @projects\n end",
"def show\n respond_to do |format|\n format.html {render :show}\n format.json {render json: @project}\n end\n end",
"def show\n @project = Project.find(params[:id])\n\t@user = User.find(@project.user_id)\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end",
"def find(project_id)\n raw_response = get_request(\"projects/#{project_id}\")\n parse_response(raw_response, :project)\n end"
] |
[
"0.7868971",
"0.76979554",
"0.7680216",
"0.7611453",
"0.75334454",
"0.75258976",
"0.74926496",
"0.74926496",
"0.74926496",
"0.74926496",
"0.74926496",
"0.74926496",
"0.74926496",
"0.74924207",
"0.7484109",
"0.7479275",
"0.7444873",
"0.74294627",
"0.74224764",
"0.7414947",
"0.7385035",
"0.7380203",
"0.7379937",
"0.7375317",
"0.7361155",
"0.7361155",
"0.7361155",
"0.7361155",
"0.7361155",
"0.7361155",
"0.7361155",
"0.7361155",
"0.7361155",
"0.7361155",
"0.7361155",
"0.7361155",
"0.7361155",
"0.7361155",
"0.7361155",
"0.73572785",
"0.7352506",
"0.73521084",
"0.73436445",
"0.73410857",
"0.73250616",
"0.7303016",
"0.72884965",
"0.72734356",
"0.72727096",
"0.72536707",
"0.7251402",
"0.72502863",
"0.72433484",
"0.7241812",
"0.7228012",
"0.7228012",
"0.7213682",
"0.7210143",
"0.72031206",
"0.71956533",
"0.7184686",
"0.71557546",
"0.71509594",
"0.71480834",
"0.7120158",
"0.71123755",
"0.7106823",
"0.70865124",
"0.7084294",
"0.7079523",
"0.705198",
"0.70506",
"0.7044681",
"0.70423746",
"0.70259416",
"0.70248544",
"0.70047486",
"0.70040953",
"0.70025414",
"0.7000689",
"0.6987457",
"0.6984701",
"0.69802356",
"0.6979858",
"0.69780463",
"0.69780076",
"0.6970507",
"0.6966368",
"0.69646454",
"0.69622666",
"0.6961776",
"0.6961545",
"0.69614834",
"0.69565344",
"0.6943089",
"0.6936655",
"0.69335127",
"0.69173217",
"0.69125015",
"0.6909762",
"0.69050795"
] |
0.0
|
-1
|
POST /projects POST /projects.json
|
def create
@project = Project.new(project_params)
@project.user_id = current_user.id
respond_to do |format|
if @project.save
format.html { redirect_to @project, success: 'Project was successfully created.' }
format.json { render :show, status: :created, location: @project }
else
format.html { render :new }
format.json { render json: @project.errors, status: :unprocessable_entity }
end
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.json { render :json => @project, :status => :created, :location => @project }\n format.html { redirect_to(projects_path) }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @project.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create_project(name)\n post('projects', {:name => name})[\"project\"]\n end",
"def create\n @project = Project.new(project_params)\n\n if @project.save\n render json: @project, status: 200\n else\n render json: { errors: @project.errors.messages }, status: 200\n end\n end",
"def create\n @project = Project.new(project_params)\n\n if @project.save\n render json: @project, status: :created\n else\n render json: @project.errors, status: :unprocessable_entity\n end\n end",
"def create\n @urlroot = Designax::Application.config.urlroot\n if params[:pk] == \"new\" and params[:name] == \"project_name\"\n project_name = params[:value]\n @project = Project.new()\n @project.project_name = project_name\n else\n @project = Project.new(params[:project])\n end\n\n respond_to do |format|\n if @project.save\n redirect_url = @urlroot + \"/projects\"\n response_url = { \"url\" => redirect_url }\n format.json { render json: response_url, status: 200 }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(params[:project] || JSON.parse(request.body.read))\n\n if (params[:id])\n @project.id = params[:id]\n end\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to(@project, :notice => 'Project was successfully created.') }\n format.xml { render :xml => @project, :status => :created, :location => @project }\n format.json { render :json => @project }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @project.errors, :status => :unprocessable_entity }\n format.json { render :text => \"error creating project via http/json\" }\n end\n end\n end",
"def test_should_create_project_via_API_JSON\r\n get \"/logout\"\r\n post \"/projects.json\", :api_key => 'testapikey',\r\n :project => {:user_id => 1,\r\n :url => 'http://www.apiproject.com',\r\n :name => 'API Project',\r\n :description => 'API Project Desc' }\r\n assert_response :created\r\n project = JSON.parse(response.body)\r\n check_new_project(project) \r\n end",
"def create\n\t\t@project = current_user.projects.new(project_params)\n\n\t\trespond_to do |format|\n\t\t\tif @project.save\n\t\t\t\tformat.json { render :show, status: :created }\n\t\t\telse\n\t\t\t\tformat.json { render json: @project.errors, status: :unprocessable_entity }\n\t\t\tend\n\t\tend\n\tend",
"def create\n @projects = current_user.projects\n @project = current_user.projects.new(project_params)\n\n respond_to do |format|\n if @projects << @project\n format.html { redirect_to user_projects_path(current_user), notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.json { render json: @project, status: :created, location: @project }\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n else\n format.json { render json: @project.errors, status: :unprocessable_entity }\n format.html { render action: \"new\" }\n end\n end\n end",
"def create\n @project = current_user.projects.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create(attributes={})\n raw_response = post_request('projects', project: attributes)\n parse_response(raw_response, :project)\n end",
"def create\n #byebug\n @project = Project.new(create_params)\n @project.user_id = @current_user.id\n @project.save\n #@project = Project.create(name_project: \"prueba\", subsidy: true, parking: true, user_id: @current_user.id)\n #byebug\n render json: @project, status: :created\n end",
"def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to(@project, :notice => 'Project was successfully created.') }\n format.json { render :json => @project, :status => :created, :location => @project }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @project.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to projects_path, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n if @project.save\n render json: @project, status: :ok\n else\n render json: {error: @project.errors.full_messages.to_sentence } , status: :unprocessable_entity\n end\n end",
"def create\n @user = current_user\n @project = @user.projects.build(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = current_user.projects.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html {redirect_to \"/projects\", notice: \"Project was successfully created.\"}\n format.json {render :show, status: :created, location: @project}\n else\n format.html {render :new, status: :unprocessable_entity}\n format.json {render json: @project.errors, status: :unprocessable_entity}\n end\n end\n end",
"def create\n @project = current_user.projects.build(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: \"Project was successfully created.\" }\n User.find(current_user.id).projects << Project.find(@project.id)\n @projects_user = ProjectsUser.find_by(user_id: current_user.id, project_id: @project.id)\n format.json { render :show, status: :created, location: @project }\n\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: t('models.project.create') }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @api_project = Project.new(api_project_params)\n\n respond_to do |format|\n if @api_project.save\n format.html { redirect_to @api_project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @api_project }\n else\n format.html { render :new }\n format.json { render json: @api_project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to projects_path, notice: \"Project was successfully created.\" }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to projects_path, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = @client.projects.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @client, notice: 'Project was successfully created.' }\n else\n format.html { render action: \"new\" }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.json { render json: @project, status: 200 }\n else\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = current_user.projects.build(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to projects_path, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n @project.user_id = @user.id\n if @project.save\n render json: {status: :success, project: @project}\n else\n render json: {status: :failed, project: @project}\n end\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to projects_path, notice: 'Project was successfully created.' }\n format.json { render action: 'show', status: :created, location: @project }\n else\n format.html { render action: 'new' }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n respond_to do |format|\n if project.save\n format.html { redirect_to project, notice: 'Project was successfully created.' }\n format.json { render json: project, status: ':created', location: project }\n else\n format.html { render action: 'new' }\n format.json { render json: project.errors, status: ':unprocessable_entity' }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: 'new' }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to admin_projects_url, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = current_user.projects.new(project_params)\n if @project.save\n render :show\n else\n render json: { errors: @project.errors }\n end\n end",
"def create\n @project = Project.new(project_params)\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, flash: {success: 'Project was successfully created.'} }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n # authenticate_user!\n @project = Project.new\n @project[:category] = params[:category]\n @project[:title] = params[:title]\n @project[:body] = params[:body]\n @project[:location] = params[:location]\n @project[:image_link] = params[:image_link]\n @project[:project_url] = params[:project_url]\n @project[:year] = params[:year]\n @project[:likes] = params[:likes]\n @project.save\n\n render json: @project\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params.merge(user_id: current_user.id))\n\n respond_to do |format|\n if @project.save\n format.json { render :show, status: :created, location: @project }\n else\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n \n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @client = Client.find(params[:client_id])\n @project = @client.projects.build(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to client_projects_path(@client), notice: 'Project was successfully created.' }\n format.json { render json: client_projects_path(@client), status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: client_projects_path(@client).errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = current_user.projects.build(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to root_path, notice: 'Enhorabuena! Tienes un nuevo proyecto. A trabajar!' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.create project_params\n current_user.memberships.create(\n project_id: @project.id,\n owner_at: Time.now\n )\n\n if @project.save\n render 'projects/create', status: 201\n else\n render 'projects/error', status: 422\n end\n end",
"def create\n @project = @client.projects.build(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to(client_projects_url(@client), notice: 'Project was successfully created.') }\n format.xml { render xml: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.xml { render xml: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @create_project = current_user.projects.build(params[:project])\n flash[:notice] = \"Project #{@create_project.description} successfully created\" if @create_project.save\n respond_with(@create_project, layout: !request.xhr?)\n end",
"def new_project\n @request = Request.new(data_type: :project)\n @request.build_contact\n @request.build_project\n @request.build_general_information\n\n render 'new'\n end",
"def create\t\t\t\t\t\t\t\t\t# Creates record in db and redirects (porbably to index)\n\t\t@project = Project.new(projects_params)\t# Passes only title and desc.\n\n \trespond_to do |format|\t\t\t\t\t# All this is doing is rendering stuff in case of json\n \t\tif @project.save\n \t\tformat.html { redirect_to @project, notice: 'Created a new project!' }\n \t\tformat.json { render :show, status: :created, location: @project }\n \t\telse\n \t\tformat.html { render :new }\n \t\t\tformat.json { render json: @project.errors, status: :unprocessable_entity }\n \t\tend\n \tend\n\tend",
"def create\n if params[:project_id]\n cloned_from = Project.find(params[:project_id])\n @project = cloned_from.clone(params, @cur_user.id)\n else\n @cloned_project = nil\n @project = Project.new project_params\n @project.user_id = @cur_user.id\n end\n\n respond_to do |format|\n if @project.save\n format.html do\n redirect_to @project, notice: 'Project was successfully created.'\n end\n format.json do\n render json: @project.to_hash(false),\n status: :created, location: @project\n end\n else\n flash[:error] = @project.errors.full_messages\n format.html { redirect_to projects_path }\n format.json do\n render json: @project.errors, status: :unprocessable_entity\n end\n end\n end\n end",
"def create_project(key, name, params = {})\n params[:key] = key\n params[:name] = name\n post('projects', params)\n end",
"def create\n @project = Project.new(project_params)\n @project.owner = current_user unless @project.owner\n if @project.save\n render :show, status: :created, location: @project\n else\n render json: @project.errors, status: :unprocessable_entity\n end\n end",
"def create_project(optional={})\n\t\targs = self.class.new_params\n\t\targs[:method] = 'POST'\n\t\targs[:pattern] = '/projects'\n\t\targs[:query]['Action'] = 'CreateProject'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\targs[:scheme] = 'http'\n\t\tif optional.key? :project\n\t\t\targs[:body]['Project'] = optional[:project]\n\t\tend\n\t\tself.run(args)\n\tend",
"def projects\n resource 'projects'\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n build_projects_user\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n project_attrs = params[:project].merge(validate_repo_connectivity: true)\n @project = current_user.owned_projects.create(project_attrs, as: :owner)\n respond_with @project do |format|\n format.json do\n if @project.valid?\n render json: decorate(@project).to_json, status: :created\n else\n render json: {project: @project.errors.as_json}.to_json, status: :unprocessable_entity\n end\n end\n end\n end",
"def create\n @project = Project.new(params[:project])\n\t\t@project.user_id =current_user.id\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(params[:project])\n @project.skills = params[:skills]\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.create(project_params)\n if @project.errors.blank?\n flash[:success] = t('controllers.projects.create.success', project: @project.name)\n else\n flash.now[:alert] = @project.errors.full_messages.unshift(t('controllers.projects.create.failure'))\n end\n respond_with @project, location: projects_url\n end",
"def create\n @new_nav = true;\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n if params[:project_attachments]\n create_attachments\n end\n\n if params[:project_fields]\n create_fields\n end\n\n if params[:slider_objects]\n create_slider_objects\n end\n\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n @project.user = current_user\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n begin\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors.full_messages, status: :unprocessable_entity }\n end\n end\n rescue Exception => e\n @project.destroy\n respond_to do |format|\n format.html { render :new }\n format.json { render json: e.as_json, status: :service_unavailable }\n end\n end\n end",
"def project_create(global_options, options)\n result = Excon.post(\n \"#{global_options[:fenton_server_url]}/projects.json\",\n body: project_json(options),\n headers: { 'Content-Type' => 'application/json' }\n )\n\n [result.status, JSON.parse(result.body)]\n end",
"def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n @project.user_projects.create(:user_id => current_user.id, :status => true, :role => 1)\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n respond_to do |format|\n if @project.save\n flash[:alert] = \"Project created successfully.\"\n format.html { redirect_back(fallback_location: root_path) }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n if is_organization_admin? and @project.save\n @project.team_members.create(user_id: @project.organization.owner_id)\n render json: {\n name: @project.name,\n organization: @project.organization.name,\n url: project_dashboard_path(@project.id)\n }\n else\n render json: @project.errors, status: :unprocessable_entity\n end\n end",
"def create\n @project = Project.new(project_params)\n\n if params[\"project\"][\"client_id\"] != \"\"\n @project.client = Client.find params[\"project\"][\"client_id\"]\n end\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Novo projeto cadastrado com sucesso.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = current_user.projects.create(params[:project])\n \n if @project.save\n record_activity(\"created new project: \" + @project.id.to_s)\n redirect_to root_path, :notice => \"Project created successfully\"\n else\n render 'new'\n end\n end",
"def create\n find_projects(params[:api_key])\n end",
"def create\n @project = Project.new(:project_title => params[:project_title], :start_date => params[:startDate], :end_date => params[:endDate],\n :status => params[:project_status])\n\n @project.user_id = current_user.id\n\n\n respond_to do |format|\n if @project.save\n p \"pass on projects controller\"\n format.html { redirect_to @project}\n format.json { render json: \"ok\" }\n else\n p \"fail on projects controller\"\n end\n end\n\n\n end",
"def create_project_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ProjectApi.create_project ...'\n end\n # resource path\n local_var_path = '/projects'\n\n # query parameters\n query_params = opts[:query_params] || {}\n\n # header parameters\n header_params = opts[:header_params] || {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n content_type = @api_client.select_header_content_type(['application/json'])\n if !content_type.nil?\n header_params['Content-Type'] = content_type\n end\n\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:debug_body] || @api_client.object_to_http_body(opts[:'create_project_body'])\n\n # return_type\n return_type = opts[:debug_return_type] || 'Project'\n\n # auth_names\n auth_names = opts[:debug_auth_names] || ['oryAccessToken']\n\n new_options = opts.merge(\n :operation => :\"ProjectApi.create_project\",\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ProjectApi#create_project\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to :projects, notice: \"Project was successfully created.\" }\n format.json { render :show, status: :created, location: @project }\n else\n format.html do\n @teams = Team.order(:name)\n render :new\n end\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n @project.team.touch\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n render_errors(format, @project.errors, :new)\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to [:user, @project], notice: 'Project temp was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n\n render text: params[:project].inspect\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to projects_path, notice: 'Proyecto creado sastifactoriamente' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(params[:project])\n @project.status = \"Etat zero\"\n creator = current_user\n ProjectUser.create(:project => @project, :user => creator, :admin => true)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.new(project_params)\n @project.user_id = current_user.id\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n\n #Acá se retorna de la vista New (o de cualquier lugar que llame a create con POST). Le llega el hash project_params con \n # los datos que retornó la vista.\n\n #Crea el nuevo usuario.\n @project = Project.new(project_params)\n\n respond_to do |format| #Esta linea es curiosa. Si el request le llegó por HTML, entonces fue un navegador. Si le llego\n #por JSON, entonces probablemente fue otra cosa, un app movil por ejemplo.\n if @project.save #Esto guarda el proyecto nuevo en la base de datos y retorna True si no hubo problema, y False si hubo un error.\n # Es importante notar que al llamar .save, primero pasa por el modelo, el cual revisa que no falte ningún dato.\n # Por ejemplo, si el modelo necesita que se incluya el nombre del proyecto, si o si, y no se le pasó el nombre,\n # Entonces el modelo va a guardar ese error en un hash llamado errors, dentro de el mismo (@projects.errors)\n # y va a hacer que .save retorne False.\n\n\n format.html { redirect_to :controller => \"misc\", :action =>\"about\", notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = @projectable.projects.new(params[:project])\n\n respond_to do |format|\n if @project.save\n track_activity @project\n format.html { redirect_to [@projectable, @project], notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render layout: 'form', action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end"
] |
[
"0.7338293",
"0.73130125",
"0.7307476",
"0.7298852",
"0.7226645",
"0.7225086",
"0.71968895",
"0.7115993",
"0.7104099",
"0.70948637",
"0.7070004",
"0.7039725",
"0.7034717",
"0.70244694",
"0.7018911",
"0.7008889",
"0.6983907",
"0.6974434",
"0.6963028",
"0.69624406",
"0.6948445",
"0.6948445",
"0.6948445",
"0.6948445",
"0.6948445",
"0.6948445",
"0.6948445",
"0.6948445",
"0.6948445",
"0.69433033",
"0.6939295",
"0.6937509",
"0.692051",
"0.6910932",
"0.6907946",
"0.6906763",
"0.6893684",
"0.68899953",
"0.68843",
"0.68792963",
"0.68788743",
"0.6878588",
"0.68779224",
"0.6868213",
"0.6865548",
"0.6865263",
"0.6865263",
"0.6865263",
"0.6865263",
"0.6865263",
"0.6865263",
"0.6865263",
"0.6865263",
"0.6865263",
"0.6865263",
"0.6865263",
"0.6865263",
"0.6865263",
"0.6865263",
"0.6865263",
"0.68651164",
"0.68650335",
"0.6859234",
"0.68578434",
"0.6845717",
"0.6828112",
"0.68190205",
"0.6805993",
"0.6785467",
"0.6784394",
"0.6772122",
"0.67537344",
"0.6748771",
"0.67365366",
"0.6717932",
"0.6715843",
"0.66995734",
"0.6686984",
"0.6686144",
"0.6685788",
"0.66839826",
"0.668309",
"0.66800094",
"0.667597",
"0.66702014",
"0.6667841",
"0.66565335",
"0.66517794",
"0.6651524",
"0.66484773",
"0.66480523",
"0.6640583",
"0.66379994",
"0.6633938",
"0.6632241",
"0.6629466",
"0.6627336",
"0.6625422",
"0.6625179",
"0.66251725"
] |
0.6648931
|
89
|
PATCH/PUT /projects/1 PATCH/PUT /projects/1.json
|
def update
respond_to do |format|
if @project.update(project_params)
format.html { redirect_to @project, info: 'Project was successfully updated.' }
format.json { render :show, status: :ok, location: @project }
else
format.html { render :edit }
format.json { render json: @project.errors, status: :unprocessable_entity }
end
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def update\n if @project.update(project_params)\n render json: @project, status: 200\n else\n render json: { errors: @project.errors.messages }, status: 200\n end\n end",
"def update\n authorize! :update, @project\n\n if @project.update(project_params)\n head :no_content\n else\n render 'projects/error', status: 422\n end\n end",
"def update\n @project = Project.find(params[:id])\n\n if params[:name] == \"project_name\"\n project_name = params[:value]\n @project.project_name = project_name\n end\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n\n @projects = Project.all\n format.html {\n render :action => \"index\"\n }\n format.json { render json: @project }\n else\n logMessage = self.class.to_s + \"#\" + __method__.to_s + \" \" + current_user.username + \" errors:\" + @project.errors.full_messages.to_s\n logger.info logMessage\n\n format.html {\n flash[:error] = 'Project was not successfully updated.'\n redirect_to action: \"index\"\n }\n errorMsg = @project.errors.full_messages.to_s.split(\"\\\"\")\n format.json { render json: errorMsg[1], status: 500 }\n end\n end\n end",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, :notice => 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @project.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to projects_path, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to(@project, :notice => 'Project was successfully updated.') }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @project.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update_project\n\t\t@project = Project.find(params[:id])\n\n\t \trespond_to do |format|\n\t\t if @project.update_attributes(project_update_params)\n\t\t format.html { redirect_to(@project, :notice => 'Entry was successfully updated.') }\n\t\t format.json { respond_with_bip(@project) }\n\t\t else\n\t\t format.html { render :action => \"edit\" }\n\t\t format.json { respond_with_bip(@project) }\n\t\t end\n\n \t end\n\tend",
"def update\t\t\t\t\t\t\t\t\t# Actually modifies the data and redirects (probably to index or show? depends)\n\t\t#@project = Project.find(params[:id])\t# Taken out because of the before action GENIUS!\n\n\t\trespond_to do |format|\n \t\t if @project.update(projects_params)\n \t\tformat.html { redirect_to @project, notice: 'Project was successfully updated.' }\n \t\tformat.json { render :show, status: :ok, location: @project }\n \t\telse\n \t\tformat.html { render :edit }\n \t\tformat.json { render json: @project.errors, status: :unprocessable_entity }\n \t\tend\n \tend\n\tend",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @project = current_user.projects.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @project = @client.projects.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(project_params)\n format.html { redirect_to([@client, @project], notice: 'Project was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render action: \"edit\" }\n format.xml { render xml: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.json { render :show, status: :ok, location: @project }\n else\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.json { render json: @project, status: 200 }\n else\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n\t\trespond_to do |format|\n\t\t\tif @project.update(project_params)\n\t\t\t\tformat.json { render :show, status: :ok }\n\t\t\telse\n\t\t\t\tformat.json { render json: @project.errors, status: :unprocessable_entity }\n\t\t\tend\n\t\tend\n\tend",
"def update\n @client = Client.find(params[:client_id])\n @project = Project.find(params[:id])\n \n respond_to do |format|\n if @project.update_attributes(project_params)\n format.html { redirect_to client_projects_path(@client), notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: client_projects_path(@client).errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render json: @project.as_json(:include => [:client, :project_participants ] ) }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if project.update(project_params)\n format.html { redirect_to project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: project.errors, status: ':unprocessable_entity' }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to projects_path, notice: 'project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :ok }\n else\n @main_projects = Project.roots.where(creator_id: @project.creator_id)\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n if @project.update(project_params)\n render json: {status: :success, project: @project}\n else\n render json: {status: :failed, project: @project}\n end\n end",
"def update\n @edit_project = Project.find(params[:id])\n\n respond_to do |format|\n if @edit_project.update_attributes(params[:project])\n format.html { redirect_to @edit_project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @edit_project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @api_project.update(api_project_params)\n format.html { redirect_to @api_project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @api_project }\n else\n format.html { render :edit }\n format.json { render json: @api_project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def project_update(project)\n raise Client::FileboundClientException.new('Id is required', 0) unless project[:projectId].greater_than_zero?\n put('/projects', nil, project)\n end",
"def update\n\t\t@project = Project.find(params[:id])\n\t\tmake_breadcrumbs\n\t\t\n\t\trespond_to do |format|\n\t\t\tif @project.update_attributes(params[:project])\n\t\t\t\tformat.html { redirect_to @project, notice: t('app.projects.updated') }\n\t\t\t\tformat.json { head :ok }\n\t\t\telse\n\t\t\t\tformat.html { render action: \"edit\" }\n\t\t\t\tformat.json { render json: @project.errors, status: :unprocessable_entity }\n\t\t\tend\n\t\tend\n\tend",
"def update\n if @project.update(project_params)\n render :show, status: :ok, location: api_v1_project_url(@project)\n else\n render json: @project.errors, status: :unprocessable_entity\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n \t\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to add_path(@project), notice: 'Project was successfully updated.' }\n format.json { render :add, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @project = Project.find(params[:id])\n params[:project][:problem_ids] ||= []\n params[:project][:target_ids] ||= []\n params[:project][:factor_ids] ||= []\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to(projects_path, :notice => 'Project was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @project.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to projects_path, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: projects_path }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\r\n respond_to do |format|\r\n if @project.update(project_params)\r\n format.html { redirect_to @project }\r\n format.json { respond_with_bip(@project) }\r\n else\r\n format.html { render action: 'edit' }\r\n format.json { respond_with_bip(@project) }\r\n end\r\n end\r\n end",
"def update\n authenticate_user!\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to(@project, :notice => 'Project was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @project.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update_project(optional={})\n\t\targs = self.class.new_params\n\t\targs[:method] = 'PUT'\n\t\targs[:pattern] = '/projects/[ProjectName]'\n\t\targs[:query]['Action'] = 'UpdateProject'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\targs[:scheme] = 'http'\n\t\tif optional.key? :project\n\t\t\targs[:body]['Project'] = optional[:project]\n\t\tend\n\t\tif optional.key? :project_name\n\t\t\targs[:path]['ProjectName'] = optional[:project_name]\n\t\tend\n\t\tself.run(args)\n\tend",
"def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to projects_path() }\n format.xml { head :ok }\n else\n @edit_mode = true\n @tasks = Task.find_all_by_project_id(@project.id)\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @project.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def project_updates\n @project = Project.find(params[:id])\n end",
"def update\n if @project.update(project_params)\n render :show, status: :ok\n else\n render json: @project.errors, status: :unprocessable_entity\n end\n end",
"def update\n if @project.update(project_params)\n render :show, status: :ok\n else\n render json: @project.errors, status: :unprocessable_entity\n end\n end",
"def update\n @project = Project.find(params[:id])\n<<<<<<< HEAD:app/controllers/projects_controller.rb\n handle_disciplines_projects\n \n=======\n\n>>>>>>> 336471e6be257cf55c9afa2a65f928fde34e41fe:app/controllers/projects_controller.rb\n respond_to do |format|\n if @project.update_attributes(params[:project])\n flash[:notice] = 'Project was successfully updated.'\n format.html { redirect_to(@project) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @project.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to projects_path, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to projects_path, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch_project_with_http_info(project_id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ProjectApi.patch_project ...'\n end\n # verify the required parameter 'project_id' is set\n if @api_client.config.client_side_validation && project_id.nil?\n fail ArgumentError, \"Missing the required parameter 'project_id' when calling ProjectApi.patch_project\"\n end\n # resource path\n local_var_path = '/projects/{project_id}'.sub('{' + 'project_id' + '}', CGI.escape(project_id.to_s))\n\n # query parameters\n query_params = opts[:query_params] || {}\n\n # header parameters\n header_params = opts[:header_params] || {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n content_type = @api_client.select_header_content_type(['application/json'])\n if !content_type.nil?\n header_params['Content-Type'] = content_type\n end\n\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:debug_body] || @api_client.object_to_http_body(opts[:'json_patch'])\n\n # return_type\n return_type = opts[:debug_return_type] || 'SuccessfulProjectUpdate'\n\n # auth_names\n auth_names = opts[:debug_auth_names] || ['oryAccessToken']\n\n new_options = opts.merge(\n :operation => :\"ProjectApi.patch_project\",\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:PATCH, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ProjectApi#patch_project\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to projects_path, notice: \"Project was successfully updated.\" }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors.full_messages, status: :unprocessable_entity }\n end\n end\n end",
"def update\n if @project\n if @project.update(project_params)\n render json: @project, status: :ok\n else\n render json: {error: @project.errors.full_messages.to_sentence } , status: :unprocessable_entity\n end\n else\n render json: {error: \"Project does not exist\"} , status: :unprocessable_entity\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end"
] |
[
"0.70004326",
"0.69119745",
"0.6911138",
"0.6889052",
"0.6888448",
"0.6878091",
"0.68675476",
"0.6857582",
"0.685334",
"0.685334",
"0.68503886",
"0.68503886",
"0.68503886",
"0.68503886",
"0.68503886",
"0.68503886",
"0.68503886",
"0.68503886",
"0.68503886",
"0.68503886",
"0.68503886",
"0.68503886",
"0.68503886",
"0.68503886",
"0.6850255",
"0.6842495",
"0.684057",
"0.684057",
"0.684057",
"0.684057",
"0.68398464",
"0.68397754",
"0.6839175",
"0.6829714",
"0.6829413",
"0.68209535",
"0.68173355",
"0.6808719",
"0.68025875",
"0.68025875",
"0.6780633",
"0.6771888",
"0.67589355",
"0.67586994",
"0.67586994",
"0.67561215",
"0.6746647",
"0.6735708",
"0.67201793",
"0.6706241",
"0.6702684",
"0.66779363",
"0.66752994",
"0.66677266",
"0.6659675",
"0.66557306",
"0.66467226",
"0.6633223",
"0.6633223",
"0.66229934",
"0.66225135",
"0.66225135",
"0.6615703",
"0.661438",
"0.66133374",
"0.66015583",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113",
"0.6600113"
] |
0.0
|
-1
|
DELETE /projects/1 DELETE /projects/1.json
|
def destroy
if @project.user_id != current_user.id and current_user.admin == false
return redirect_to root_path, danger: "Only admin user can delete this project"
end
@project.destroy
respond_to do |format|
format.html { redirect_to projects_url, success: 'Project was successfully destroyed.' }
format.json { head :no_content }
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def destroy\n @project.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end",
"def destroy\n project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n \n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n # @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to(projects_url) }\n format.json { head :ok }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.delete\n\n respond_to do |format|\n format.html { redirect_to request.referer }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.status = 'deleted'\n @project.save!\n\n respond_to do |format|\n format.json { render :json => \"success\" }\n end\n end",
"def delete\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_path }\n format.json { head :no_content }\n end\n end",
"def destroy\n project = Project.find(params[:id])\n project.destroy\n\n respond_to do |format|\n format.html { redirect_to root_path }\n format.json { head :no_content }\n end\n end",
"def destroy\n name = @project.name\n @project.destroy\n render json: [\"You have successfullly deleted '#{name}''\"], status: 200\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to admin_projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\r\n @project.destroy\r\n respond_to do |format|\r\n format.html { redirect_to projects_url }\r\n format.json { head :no_content }\r\n end\r\n end",
"def delete(projects)\n project_ids = projects.collect { |project| project.id } \n args = {ids: project_ids.to_json}\n return @client.api_helper.command(args, \"project_delete\")\n end",
"def delete\r\n\t\t\trender json: Project.delete_by_id(params[:id])\r\n\t\tend",
"def destroy\n\t\t@project.destroy\n\t\trespond_to do |format|\n\t\t\tformat.json { head :no_content }\n\t\tend\n\tend",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to administration_projects_path }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = current_user.projects.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { render :json => {:message=>\"OK\",:id=>@project.id}, :staus=>:ok}\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n head :no_content\n end",
"def destroy\t\t\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Successfully deleted project.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: t('models.project.destroy') }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = @client.projects.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to @client }\n end\n end",
"def destroy\n @project.destroy\n\n head :no_content\n end",
"def destroy\n @ourproject = Ourproject.find(params[:id])\n @ourproject.destroy\n\n respond_to do |format|\n format.html { redirect_to ourprojects_url }\n format.json { head :ok }\n end\n end",
"def destroy\n authorize @project\n @project.destroy\n render json: [\"Deleted successfully.\"], status: :ok\n end",
"def destroy\n @project.destroy_all\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'The project was successfully removed.' }\n format.json { head :no_content }\n end\n end",
"def delete_project(project)\n handle_action_exceptions(__method__) do\n cmd_line = [\"deleteproject '#{project}'\"]\n cmd_line << 'json' if @json\n\n handle_return(@toolshck_ether.cmd(cmd_line.join(' ')))\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { render :json => {:valid => true} }\n end\n end",
"def destroy\n @api_project.destroy\n respond_to do |format|\n format.html { redirect_to api_projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_path, notice: 'Project was successfully deleted.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully deleted.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully deleted.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find_by_permalink(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def delproject(project)\n post('delproject.json', project: project)\n end",
"def destroy\n authorize! :destroy, @project\n @project.destroy\n\n head :no_content\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_back(fallback_location: root_path) }\n format.json { head :no_content }\n end\n end",
"def destroy\n Rails.logger.info \"We are deleting project\"\n @todo_project.destroy\n respond_to do |format|\n format.html { redirect_to todo_projects_url, notice: 'Project was successfully deleted.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = @projectable.projects.find(params[:id])\n @project.destroy\n track_activity @project\n\n respond_to do |format|\n format.html { redirect_to [@projectable, :projects] }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find(params[:id])\n @project.destroy\n @project.users.delete_all\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n \t@project = Project.find(params[:id])\n \t#ap @project\n \t#abort\n \n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to :back }\n format.json { head :no_content }\n end\n end",
"def destroy\n authenticate_user!\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to(projects_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @project.destroy\n render json: {message: 'Projeto Excluido'}, status: :ok\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to root_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to root_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Project.find_by_slug(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :ok }\n end\n end",
"def destroy\n\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: \"Project was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: \"#{I18n.t 'project.project_destoy'}\"}\n format.json { head :no_content }\n end\n end",
"def destroy\n @project = Admin::Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_projects_url) }\n format.xml { head :ok }\n end\n end",
"def delete_project(optional={})\n\t\targs = self.class.new_params\n\t\targs[:method] = 'DELETE'\n\t\targs[:pattern] = '/projects/[ProjectName]'\n\t\targs[:query]['Action'] = 'DeleteProject'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\targs[:scheme] = 'http'\n\t\tif optional.key? :project_name\n\t\t\targs[:path]['ProjectName'] = optional[:project_name]\n\t\tend\n\t\tself.run(args)\n\tend",
"def destroy\n @project = current_user.active_projects.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n standard_destroy(Project, params[:id])\n end",
"def destroy\n authorize! :delete, @project\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: \"Project was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: \"Project was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: \"Project was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end"
] |
[
"0.78951",
"0.78593713",
"0.7778056",
"0.7771693",
"0.77585995",
"0.7730887",
"0.77305084",
"0.77305084",
"0.77305084",
"0.77305084",
"0.77305084",
"0.77244985",
"0.7718401",
"0.7718401",
"0.7718401",
"0.7718401",
"0.7704753",
"0.7704753",
"0.7704753",
"0.7704753",
"0.7704753",
"0.7704753",
"0.7704753",
"0.7704753",
"0.7704753",
"0.7704753",
"0.7704753",
"0.7704753",
"0.7704753",
"0.7704753",
"0.7704753",
"0.7704753",
"0.7704753",
"0.7704753",
"0.7704753",
"0.7704753",
"0.7704753",
"0.7704753",
"0.7700103",
"0.76993084",
"0.7682566",
"0.7669082",
"0.7659675",
"0.764973",
"0.76495475",
"0.7641442",
"0.763269",
"0.761519",
"0.76147044",
"0.7611191",
"0.76066136",
"0.7605034",
"0.7598783",
"0.75986093",
"0.7593673",
"0.7591231",
"0.75896156",
"0.7571706",
"0.7571697",
"0.7561333",
"0.7543007",
"0.7537952",
"0.75324875",
"0.75302756",
"0.75237787",
"0.75237787",
"0.75189",
"0.75063527",
"0.7504202",
"0.7499374",
"0.7494583",
"0.7487019",
"0.74810386",
"0.74776345",
"0.7469382",
"0.74652857",
"0.7460907",
"0.7460907",
"0.74520767",
"0.7448516",
"0.744649",
"0.74448746",
"0.74421936",
"0.7441719",
"0.74374086",
"0.7437005",
"0.74365294",
"0.74365294",
"0.74365294",
"0.7436244",
"0.7436244",
"0.7436244",
"0.7436244",
"0.7436244",
"0.7436244",
"0.7436244",
"0.7436244",
"0.7436244",
"0.7436244",
"0.7436244",
"0.7436244"
] |
0.0
|
-1
|
Use callbacks to share common setup or constraints between actions.
|
def set_project
@project = Project.find(params[:id])
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def set_required_actions\n # TODO: check what fields change to asign required fields\n end",
"def action_hook; end",
"def run_actions; end",
"def define_action_hook; end",
"def actions; end",
"def define_action_helpers\n if super && action == :save\n @instance_helper_module.class_eval do\n define_method(:valid?) do |*args|\n self.class.state_machines.fire_event_attributes(self, :save, false) { super(*args) }\n end\n end\n end\n end",
"def add_actions; end",
"def callbacks; end",
"def callbacks; end",
"def setup *actions, &proc\n (@setup_procs ||= []) << [proc, actions.size > 0 ? actions : [:*]]\n end",
"def define_action_helpers; end",
"def post_setup\n end",
"def action_methods; end",
"def action_methods; end",
"def action_methods; end",
"def before_setup; end",
"def action_run\n end",
"def execute(setup)\n @action.call(setup)\n end",
"def define_action_helpers?; end",
"def set_actions\n actions :all\n end",
"def action_done(action)\n dispatch = { :migrate => :done_migrating, :map => :done_mapping, :reduce =>\n :done_reducing, :finalize => :done_finalizing } \n self.send dispatch[action[:action]], action\n end",
"def dependencies action, &block\n @actions.each do |other|\n if action[:requires].include? other[:provide]\n block.call other\n end\n end\n end",
"def setup!\n return unless @setup_procs\n http_actions = actions\n @setup_procs.each do |setup_proc|\n proc, actions = setup_proc\n @setup__actions = actions.map do |action|\n\n action.is_a?(Regexp) ?\n http_actions.select { |a| a.to_s =~ action } :\n action.is_a?(String) && action =~ /\\A\\./ ?\n http_actions.map { |a| a.to_s << action if format?(a).include?(action) }.compact :\n action\n\n end.flatten\n self.class_exec &proc\n @setup__actions = nil\n end\n @setup_procs = nil\n end",
"def before_actions(*logic)\n self.before_actions = logic\n end",
"def setup_handler\n end",
"def set_action(opts)\n opts = check_params(opts,[:actions])\n super(opts)\n end",
"def setup(action)\n @targets.clear\n unless action.item.target_filters.empty?\n @targets = SES::TargetManager.make_targets(action)\n else\n item = action.item\n if item.for_opponent?\n @targets = $game_troop.alive_members\n elsif item.for_dead_friend?\n @targets = $game_party.battle_members.select { |actor| actor.dead? }\n else\n $game_party.battle_members.select { |actor| actor.alive? }\n end\n end\n @item_max = @targets.size\n create_contents\n refresh\n show\n activate\n end",
"def action; end",
"def action; end",
"def action; end",
"def action; end",
"def action; end",
"def workflow\n end",
"def revisable_shared_setup(args, block)\n class << self\n attr_accessor :revisable_options\n end\n options = args.extract_options!\n self.revisable_options = Options.new(options, &block)\n \n self.send(:include, Common)\n self.send(:extend, Validations) unless self.revisable_options.no_validation_scoping?\n self.send(:include, WithoutScope::QuotedColumnConditions)\n end",
"def setup\n @action = SampleActionAndroid.new(os_name: 'android',\n app_name: APP_PATH)\n end",
"def before(action)\n invoke_callbacks *self.class.send(action).before\n end",
"def process_action(...)\n send_action(...)\n end",
"def before_dispatch(env); end",
"def after_actions(*logic)\n self.after_actions = logic\n end",
"def setup\n # override and do something appropriate\n end",
"def setup(client)\n return unless @setup\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n actions.each do |action|\n action.execute(client)\n end\n self\n end",
"def setup(_context)\n end",
"def setup(resources) ; end",
"def validate_actions\n errors.add(:base, :should_give_at_least_one_action) if !manage? && !forecasting? && !read? && !api?\n end",
"def setup\n @resource_config = {\n :callbacks => {\n :before_create => nil,\n :after_create => nil,\n :before_update => nil,\n :after_update => nil,\n :before_destroy => nil,\n :after_destroy => nil,\n },\n :child_assoc => nil,\n :model => nil,\n :parent => nil,\n :path => nil,\n :permission => {},\n :properties => {},\n :relation => {\n :create => nil,\n :delete => nil,\n },\n :roles => nil,\n }\n end",
"def determine_valid_action\n\n end",
"def process_shared\n handle_taxes\n handle_shippings\n create_adjustments_from_params\n handle_status\n handle_inventory_refunds\n handle_payment_transactions\n order.updater.update\n end",
"def startcompany(action)\n @done = true\n action.setup\n end",
"def init_actions\n am = action_manager()\n am.add_action(Action.new(\"&Disable selection\") { @selection_mode = :none; unbind_key(32); bind_key(32, :scroll_forward); } )\n am.add_action(Action.new(\"&Edit Toggle\") { @edit_toggle = !@edit_toggle; $status_message.value = \"Edit toggle is #{@edit_toggle}\" })\n end",
"def event_callbacks(event, metadata={})\n case event\n when :reset, :review\n if confirmed\n update_attributes(confirmed: false)\n end\n when :confirm\n confirm\n # trigger :order for all applicable items\n # NOTE: :order event is common to both physical and digital items\n items.each do |i|\n if i.event_permitted(:order)\n user_id = last_transition.user_id\n i.trigger!(:order, { order_id: id, user_id: user_id })\n end\n end\n when :complete_work\n request = metadata[:request]\n work_complete_notification(request)\n when :close\n close\n end\n if event != :close && !open\n reopen\n end\n end",
"def setup_action\n return unless PONY::ERRNO::check_sequence(current_act)\n new_sequence = @action_sequence[@sequence_index+1...@action_sequence.size]\n @sequence_index = 0\n new_sequence = DND::SkillSequence::ACTS[@acts[1]] + new_sequence\n execute_sequence\n end",
"def define_tasks\n define_weave_task\n connect_common_tasks\n end",
"def setup(&block)\n define_method(:setup, &block)\n end",
"def setup\n transition_to(:setup)\n end",
"def setup\n transition_to(:setup)\n end",
"def action\n end",
"def setup( *args )\n\t\t\tself.class.setupBlocks.each {|sblock|\n\t\t\t\tdebugMsg \"Calling setup block method #{sblock}\"\n\t\t\t\tself.send( sblock )\n\t\t\t}\n\t\t\tsuper( *args )\n\t\tend",
"def config(action, *args); end",
"def setup\n @setup_proc.call(self) if @setup_proc\n end",
"def before_action \n end",
"def setup_callbacks\n defined_callbacks.each do |meth|\n unless respond_to?(\"call_#{meth}_callbacks\".to_sym)\n self.class.module_eval <<-EOE\n def call_#{meth}_callbacks(*args)\n plugin_store.each {|a| a.call_#{meth}_callbacks(*args) } if respond_to?(:plugin_store) && plugin_store\n self.send :#{meth}, *args if respond_to?(:#{meth})\n end\n EOE\n end\n end\n end",
"def action\n end",
"def matt_custom_action_begin(label); end",
"def setup\n # override this if needed\n end",
"def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend",
"def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend",
"def action(options,&callback)\n new_action = Action===options ? options : Action.new(options,&callback)\n # replace any with (shared name/alias or both default) + same arity\n @actions.delete_if do |existing_action|\n ((existing_action.names & new_action.names).size > 0 ||\n existing_action.default? && new_action.default?) &&\n existing_action.required.size == new_action.required.size &&\n existing_action.optional.size <= new_action.optional.size\n end\n @actions = (@actions + [new_action]).sort\n new_action\n end",
"def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action\n end",
"def after(action)\n invoke_callbacks *options_for(action).after\n end",
"def pre_task\n end",
"def setup(server)\n server.on('beforeMethod', method(:before_method), 10)\n end",
"def add_actions\n attribute = machine.attribute\n name = self.name\n \n owner_class.class_eval do\n define_method(name) {self.class.state_machines[attribute].events[name].fire(self)}\n define_method(\"#{name}!\") {self.class.state_machines[attribute].events[name].fire!(self)}\n define_method(\"can_#{name}?\") {self.class.state_machines[attribute].events[name].can_fire?(self)}\n end\n end",
"def init_actions\n @select_action = SelectAction.new\n @endpoint_mouse_action = EndpointMouseAction.new\n @move_action = MoveAction.new\n end",
"def setup_signals; end",
"def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend",
"def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend",
"def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action.respond_to?('weak!') ? action.weak! : action\n end",
"def initialize(*args)\n super\n @action = :set\nend",
"def after_set_callback; end",
"def setup\n #implement in subclass;\n end",
"def lookup_action; end",
"def setup &block\n if block_given?\n @setup = block\n else\n @setup.call\n end\n end",
"def setup_action\n return TSBS.error(@acts[0], 1, @used_sequence) if @acts.size < 2\n actions = TSBS::AnimLoop[@acts[1]]\n if actions.nil?\n show_action_error(@acts[1])\n end\n @sequence_stack.push(@acts[1])\n @used_sequence = @acts[1]\n actions.each do |acts|\n @acts = acts\n execute_sequence\n break if @break_action\n end\n @sequence_stack.pop\n @used_sequence = @sequence_stack[-1]\n end",
"def release_actions; end",
"def around_hooks; end",
"def save_action; end",
"def setup(easy)\n super\n easy.customrequest = @verb\n end",
"def action_target()\n \n end",
"def setup\n callback(:setup) do\n notify(:setup)\n migration_check.last_deployed_commit\n end\n end",
"def setup\n return unless @setup\n\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n run_actions_and_retry(actions)\n self\n end",
"def before_setup\n # do nothing by default\n end",
"def my_actions(options)\n @setup = false\n get_template_part(\"custom_used\",\"action_users\",true)\n end",
"def default_action; end",
"def setup(&blk)\n @setup_block = blk\n end",
"def callback_phase\n super\n end",
"def advice\n end",
"def _handle_action_missing(*args); end",
"def duas1(action)\n action.call\n action.call\nend",
"def shared_action(name, &block)\n @controller.shared_actions[name] = block\n end",
"def before_action action, &block\n @audience[:before][action] ||= Set.new\n @audience[:before][action] << block\n end",
"def setup_initial_state\n\n state_a = State.new(\"a\", 0)\n state_b = State.new(\"b\", 0)\n state_c = State.new(\"c\", 10)\n\n move_to_b = Action.new(\"move_to_b\", 1, state_b)\n\n move_to_c = Action.new(\"move_to_c\", 1, state_c)\n\n state_a.actions = [move_to_b, move_to_c]\n\n return state_a\n \nend"
] |
[
"0.6163163",
"0.6045976",
"0.5946146",
"0.591683",
"0.5890051",
"0.58349305",
"0.5776858",
"0.5703237",
"0.5703237",
"0.5652805",
"0.5621621",
"0.54210985",
"0.5411113",
"0.5411113",
"0.5411113",
"0.5391541",
"0.53794575",
"0.5357573",
"0.53402257",
"0.53394014",
"0.53321576",
"0.53124547",
"0.529654",
"0.5296262",
"0.52952296",
"0.52600986",
"0.52442724",
"0.52385926",
"0.52385926",
"0.52385926",
"0.52385926",
"0.52385926",
"0.5232394",
"0.523231",
"0.5227454",
"0.52226824",
"0.52201617",
"0.5212327",
"0.52079266",
"0.52050185",
"0.51754695",
"0.51726824",
"0.51710224",
"0.5166172",
"0.5159343",
"0.51578903",
"0.51522785",
"0.5152022",
"0.51518047",
"0.51456624",
"0.51398855",
"0.5133759",
"0.5112076",
"0.5111866",
"0.5111866",
"0.5110294",
"0.5106169",
"0.509231",
"0.50873137",
"0.5081088",
"0.508059",
"0.50677156",
"0.50562143",
"0.5050554",
"0.50474834",
"0.50474834",
"0.5036181",
"0.5026331",
"0.5022976",
"0.5015441",
"0.50121695",
"0.5000944",
"0.5000019",
"0.4996878",
"0.4989888",
"0.4989888",
"0.49864885",
"0.49797225",
"0.49785787",
"0.4976161",
"0.49683493",
"0.4965126",
"0.4958034",
"0.49559742",
"0.4954353",
"0.49535993",
"0.4952725",
"0.49467874",
"0.49423352",
"0.49325448",
"0.49282882",
"0.49269363",
"0.49269104",
"0.49252945",
"0.4923091",
"0.49194667",
"0.49174926",
"0.49173003",
"0.49171105",
"0.4915879",
"0.49155936"
] |
0.0
|
-1
|
Never trust parameters from the scary internet, only allow the white list through.
|
def project_params
params.require(:project).permit(:title, :description, :goal, :duration, :markdown, :outstanding, :main_image, category_ids: [])
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def strong_params\n params.require(:user).permit(param_whitelist)\n end",
"def strong_params\n params.require(:listing_member).permit(param_whitelist)\n end",
"def allow_params_authentication!; end",
"def allowed_params\n ALLOWED_PARAMS\n end",
"def default_param_whitelist\n [\"mode\"]\n end",
"def param_whitelist\n [:role, :title]\n end",
"def expected_permitted_parameter_names; end",
"def safe_params\n params.except(:host, :port, :protocol).permit!\n end",
"def strong_params\n params.require(:team_member).permit(param_whitelist)\n end",
"def permitir_parametros\n \t\tparams.permit!\n \tend",
"def strong_params\n params.require(:community).permit(param_whitelist)\n end",
"def permitted_strong_parameters\n :all #or an array of parameters, example: [:name, :email]\n end",
"def strong_params\n params.require(:education).permit(param_whitelist)\n end",
"def restricted_params\n #params.require(self.controller_name.classify.underscore.to_sym).permit([])\n raise(\"No strong params set, override restricted_params method in your controller. E.g. params.require(:model).permit(:attribute1, :attribute2)\")\n end",
"def allowed_params\n params.require(:user).permit(:username, :email, :password, :password_confirmation)\n end",
"def param_whitelist\n [:rating, :review]\n end",
"def param_whitelist\n whitelist = [\n :username, :name,\n :parent_id,\n :headline, :description, :video,\n :policy, :signup_mode, :category,\n :website, :facebook, :twitter, :linkedin,\n :founded_at,\n privacy: [\n :events,\n :resources\n ],\n permission: [\n :profile,\n :members,\n :children,\n :statistics,\n :posts,\n :listings,\n :resources,\n :events\n ],\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:parent_id)\n unless current_user.role_in(@community) === 'owner'\n whitelist.delete(:privacy)\n whitelist.delete(:permission)\n end\n end\n \n whitelist\n end",
"def param_whitelist\n if @user.present? && current_user != @user\n return [:followed]\n end\n \n whitelist = [\n :username, :email, :password,\n :first_name, :last_name,\n :birthday, :gender,\n :headline, :biography, :ask_about, :focus,\n :website, :facebook, :linkedin, :twitter, :github,\n roles: [],\n skills: [],\n interests: [],\n privacy: { contact: [] },\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:email)\n whitelist.delete(:password)\n end\n \n whitelist\n end",
"def user_params \n \tparams.require(:user).permit(:name, :email, :password, :password_confirmation)# preventing CSTR\n end",
"def valid_params_request?; end",
"def user_params\n params.permit(:name, :phoneNumber, :address, :postalCode, :local, :link, :counter, :latitude, :longitude) \n end",
"def strong_params\n params.require(:experience).permit(param_whitelist)\n end",
"def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end",
"def whitelist_url_params\n params.require(:whitelist_url).permit(:domain)\n end",
"def allowed_params\n params.require(:allowed).permit(:email)\n end",
"def permitted_params\n []\n end",
"def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end",
"def safe_params\n params.permit(:id, :name, :origin, :emails => []); #emails is an array\n end",
"def query_param\n\t\tparams.permit(:first_name, :last_name, :phone)\n\tend",
"def strong_params\n params.require(:success_metric).permit(param_whitelist)\n end",
"def devise_filter\r\n logger.debug(\"In devise_filter =>PARAMS: #{params.inspect}\")\r\n\r\n # White list for sign_up\r\n devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(user_whitelist) }\r\n\r\n # White list for account update\r\n devise_parameter_sanitizer.for(:account_update) { |u| u.permit(user_whitelist, :current_password) }\r\n\r\n # White list for Invitation creation\r\n devise_parameter_sanitizer.for(:invite) { |u| u.permit(:account_type, :email, :invitation_token)}\r\n\r\n # White list for accept invitation\r\n devise_parameter_sanitizer.for(:accept_invitation) { |u| u.permit(user_whitelist, :invitation_token)}\r\n\r\n end",
"def whitelisted_user_params\n params.require(:user).\n permit( :first_name, :last_name, :email,:password,:password_confirmation,:birthday,:gender)\n end",
"def user_params\n ActionController::Parameters.permit_all_parameters = true\n params.require(:user) #.permit(:name, :surname, :phone, :password, :email, :time_zone)\n end",
"def safe_params\n params.require(:user).permit(:name)\n end",
"def strong_params\n params.require(:metric_change).permit(param_whitelist)\n end",
"def get_params\n\t\treturn ActionController::Parameters.new(self.attributes).permit(\"account_id\", \"title\", \"category\", \"introduction\", \"tags\", \"segment_type\", \"visible\", \"status\", \"main_image\")\n\tend",
"def grant_params\n @whitelisted = params.require(:grant).permit(:name, :description, :agency_id, :acronym)\n end",
"def check_params; true; end",
"def param_whitelist\n whitelist = [\n :description,\n :progress,\n :kpi_id\n ]\n \n unless action_name === 'create'\n whitelist.delete(:kpi_id)\n end\n \n whitelist\n end",
"def quote_params\n params.permit!\n end",
"def valid_params?; end",
"def paramunold_params\n params.require(:paramunold).permit!\n end",
"def user_params\n\t\tparams.permit(:nickname, :avatar, :description, :password, :gender, :birthday, :email, :phone, :qq_id, :wechat_id)\n\tend",
"def filtered_parameters; end",
"def user_params\n params.permit(\n \t:id,\n \t:email, \n \t:first_name, \n \t:last_name, \n \t:password, \n \t:confirm_token, \n \t:phone_number,\n \t:facebook_link,\n \t:car_model,\n \t:license_plate)\n end",
"def filtering_params\n params.permit(:email, :name)\n end",
"def check_params\n true\n end",
"def wx_public_params\n params.require(:wx_public).permit(:nickname, :manager, :alias)\n end",
"def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end",
"def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end",
"def listing_params\n\t\tparams.permit(:address, :transit_info, :rules, :other_info, :lat, :lng)\n\tend",
"def social_account_params\n\t\t\tparams.require(:social_account).permit!\n\t\tend",
"def safe_params\n resurce_name = self.class.resource_name\n params_method_name = \"#{resurce_name}_params\".to_sym\n if params[resurce_name]\n if respond_to?(params_method_name) || private_methods.include?(params_method_name)\n send(params_method_name)\n else\n raise ActiveModel::ForbiddenAttributesError, \"Please, define the '#{params_method_name}' method in #{self.class.name}\"\n end\n end\n end",
"def user_params\n params.require(:user).permit(:uri, :username, :password, :realname, :email, :publicvisible)\n end",
"def model_params\n\t\tparams.require(:manager).permit(\n\t :user_name,\n :password,\n :email,\n \t\t\t)\n\tend",
"def url_params\n params.require(:url).permit(:short_url, :original_url, :clicks, :ip_addresses)\n end",
"def article_params_whitelist\n params.require(:article).permit(:title, :description, category_ids: [])\n end",
"def college_whitelist_params\n params.require(:college_whitelist).permit(:status)\n end",
"def filtering_params\n params.permit(:email)\n end",
"def valid_params(params)\n params.permit(:user_id, :photo_id, :originX, :originY, :width, :height)\n end",
"def active_code_params\n params[:active_code].permit\n end",
"def ip_address_params\n\t\t\tparams.require(:ip_address).permit!\n end",
"def reserved_params\n params.require(:reserved).permit(:name, :email, :pax, :address, :KTP, :title)\n end",
"def pull_request_params\n whitelist = [\n :url,\n :id,\n :html_url,\n :diff_url,\n :patch_url,\n :issue_url,\n :number,\n :state,\n :locked,\n :title\n ]\n params.require(:pull_request).permit(whitelist)\n end",
"def post_params\n if current_user.admin? \n params.permit(:title, :body, :city, :country, :gps_location, :privacy, :visible, :latitude, :longitude, images: [], files: [])\n else \n params.permit(:title, :body, :city, :country, :gps_location, :privacy,:latitude, :longitude, images: [], files: [])\n end \n end",
"def filter_parameters; end",
"def filter_parameters; end",
"def list_params\n params.permit(:name)\n end",
"def vineyard_params\n params.permit(:vineyard_name, :email, :website_url, :phone, :address, :city, :region, :postcode, :country, :specialty, :description, :pet_friendly, :holiday, :tours, :events, :family_friendly, :cover_image, :image_one, :image_two, :image_three, :image_four, :user_id, :base64)\n end",
"def available_activity_params\n # params.require(:available_activity).permit(:type,:geometry,:properties)\n whitelisted = ActionController::Parameters.new({\n type: params.require(:available_activity)[:type],\n geometry: params.require(:available_activity)[:geometry].try(:permit!).to_h,\n properties: params.require(:available_activity)[:properties].try(:permit!).to_h\n }).try(:permit!)\n end",
"def user_params\n params.permit(:name, :username, :email, :password, :img_url, :bg_url, :coinbank)\n end",
"def user_params_pub\n\t \tparams[:user].permit(:hruid)\n\t end",
"def user_params\n params.permit(:id, :email, :password, :nickname, :status, :avatar, :flat_picture, :flatsharing_id, :member,\n :user, :color, :solde)\n end",
"def validate_search_inputs\n @whitelisted = params.fetch(:user, nil)\n if @whitelisted.blank?\n render_error(400, \"#{I18n.t('general_error.params_missing_key')}\": [I18n.t('general_error.params_missing_value', model: \"review\")])\n return\n else\n @whitelisted = @whitelisted.permit(:name, :uen, :description)\n end\n end",
"def param_whitelist\n [\n :title,\n :description,\n :organization,\n :team_id,\n :started_at,\n :finished_at,\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n end",
"def admin_social_network_params\n params.require(:social_network).permit!\n end",
"def url_whitelist; end",
"def valid_params(params)\n params.permit(:login, :first_name, :last_name, \n :password, :password_confirmation)\n end",
"def origin_params\n params.permit(:country, :state, :city, :postal_code, :address, :description)\n end",
"def filter_params\n params.require(:filters).permit(:letters)\n end",
"def permit_request_params\n params.permit(:address)\n end",
"def sensitive_params=(params)\n @sensitive_params = params\n end",
"def user_params\n # Ensure a user can't give themselves admin priveleges\n params.delete(:admin) if current_user.admin?\n params.require(:user).permit(:name, :email, :admin, :image)\n end",
"def secure_params\n params.require(:location).permit(:name)\n end",
"def strong_params\n params.require( :setting ).\n permit( :global_scan_limit, :per_user_scan_limit,\n :target_whitelist_patterns, :target_blacklist_patterns )\n end",
"def question_params\n params.require(:survey_question).permit(question_whitelist)\n end",
"def case_insensitive_params\n params.require(:case_insensitive).permit(:name)\n end",
"def empire_master_no_match_params\n params.require(:empire_master_no_match).permit(:uid, :last_name, :list, :search_date, :double, :source)\n end",
"def maintenance_request_params\n params[:maintenance_request].permit! #allow all parameters for now\n end",
"def unwanted_params\n params.require(:unwanted).permit(:title, :description, :image)\n end",
"def url_params\n params[:url].permit(:full)\n end",
"def backend_user_params\n params.permit!\n end",
"def user_params\n params.permit(:name, :age, :username, :display_photo, :password)\n end",
"def filter_params\n\t\treturn params[:candidate].permit(:name_for_filter)\n\tend",
"def speed_measurement_params\n\n #fuckit, to lazy to deal with permit crap right now\n ActionController::Parameters.permit_all_parameters = true\n\n params[:speed_measurement]\n end",
"def get_params\r\n #params.require(:article).permit(:title, :permalink, :content, :source_site, :introtext, :type_id, :order_by, :searchable, :created_by, :edited_by, :published_by, :published_on, :user_id)\r\n params.require(:article).permit!\r\n\r\n end",
"def pub_params\n params.require(:pub).permit(:name, :description, :phone, :email, :hidden, :city_id, :address)\n end",
"def pass_params\n params[:pass].permit(:name, :price, :description, :colour, :events)\n end",
"def droptraining_params\n params.permit(:training_id,:user_id, :utf8, :authenticity_token, :commit)\n end",
"def person_params\n # params whitelist does *not* include admin, sub, remember_token\n # TBD: share this whitelist with the list used by configuration_permitted_parameters\n # TBD: should current_password be on this list? -- for now, leaving off, since it seems to work without\n # NOTE: do not include 'admin' in this list!\n params.require(:person).permit(\n :name, \n :email, \n :description,\n :password, \n :password_confirmation\n )\n end",
"def parameter_params\n params.require(:parameter).permit(:name, :description, :param_code, :param_value, :active_from, :active_to)\n end"
] |
[
"0.69802505",
"0.6781974",
"0.67470175",
"0.67430073",
"0.67350477",
"0.6593221",
"0.6504263",
"0.64988977",
"0.6481794",
"0.64800006",
"0.64568025",
"0.64411247",
"0.6379476",
"0.63765615",
"0.6368045",
"0.6320141",
"0.6300363",
"0.6300057",
"0.62952244",
"0.6294712",
"0.6293856",
"0.6290323",
"0.62816143",
"0.6241851",
"0.6241208",
"0.622036",
"0.62128764",
"0.62110275",
"0.61966056",
"0.61776453",
"0.617547",
"0.6174961",
"0.61654735",
"0.6153256",
"0.61516005",
"0.6149498",
"0.6123234",
"0.6118653",
"0.61077267",
"0.61061186",
"0.6093616",
"0.608318",
"0.6074428",
"0.60650206",
"0.60244286",
"0.6020295",
"0.60155797",
"0.6012826",
"0.6010141",
"0.6010141",
"0.60037106",
"0.600298",
"0.59979576",
"0.5994806",
"0.5994283",
"0.5993927",
"0.5980616",
"0.59667075",
"0.59614897",
"0.59610957",
"0.596071",
"0.5959614",
"0.59554",
"0.59542966",
"0.5946781",
"0.5940262",
"0.5940262",
"0.59401053",
"0.5937168",
"0.5932135",
"0.59293395",
"0.592659",
"0.59202623",
"0.59112674",
"0.59088206",
"0.590716",
"0.59056735",
"0.589997",
"0.5899655",
"0.5898926",
"0.5896042",
"0.589589",
"0.5895867",
"0.58894163",
"0.5884936",
"0.5879227",
"0.58740723",
"0.5871364",
"0.5870148",
"0.5869228",
"0.5868196",
"0.5867967",
"0.5865532",
"0.58653617",
"0.58644646",
"0.58631665",
"0.5862611",
"0.5857609",
"0.58558804",
"0.5853729",
"0.5853025"
] |
0.0
|
-1
|
string.split(" ") = ["Hello", "there,", "and", "how", "are", "you?"] array = ["Hello", "there,", "and", "how", "are", "you?"] array.reverse_each = ["olleH", "ereht,", "dna", "woh", "era", "?uoy"
|
def reverse_each_word(string)
array = string.split
new_array = []
array.collect do |string|
new_array.push(string.reverse)
end
new_array.join(' ')
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def reverse_each_word_with_each(string)\n original_array = string.split(\" \")\n return_array = []\n original_array.each do |string|\n return_array << string.reverse\n end\n return_array.join(\" \")\n\nend",
"def reverse_each_word(string)\n split_array = string.split(' ')\n reversed = []\n split_array.each do |word|\n reversed << word.reverse\n end\nreturn reversed.join(' ')\nend",
"def reverse_each_word(array)\n array.split(\" \").collect {|x| x.reverse!}.join(\" \")\nend",
"def reverse_each_word(array)\n reverse_sentence = []\n reverse_sentence = array.split.collect {|x| x.reverse}\n reverse_sentence.join(\" \")\nend",
"def reverse_each_word(string)\n splitted_array = string.split(\" \")\n new_array = splitted_array.collect do |word|\n word.reverse\n end\n\n new_array.join(\" \")\nend",
"def reverse_each_word(array)\n new_array = array.split(\" \") \n reversed_array = new_array.each {|x| x.reverse!} \n return reversed_array.join(\" \") \n end",
"def reverse_each_word(x) \n #Create a new array to store the split string\n array = []\n #Use .split to split the string into an array of strings\n array = x.split \n #Use collect enumerable to iterate over the elements of array and .reverse! to reverse each element\n array.collect{|n| n.reverse!}\n #Use .join on the array with ' ' to join the elements together with a space into a string\n array.join(' ')\nend",
"def reverse_each_word(string)\n original_array = string.split(\" \")\n new_array = []\n original_array.each do|string|\n new_array << string.reverse\n end\n new_array.join(\" \")\nend",
"def reverse_each_word(string) #collect returns new arr \n string.split(' ').collect {|i| i.reverse!}.join(' ')\nend",
"def reverse_each_word(string)\n array = []\n array = string.split(\" \")\n array.collect do |word| \n word.reverse!\n end\n final_array = array.join(\" \")\n final_array\nend",
"def reverse_each_word(string)\n new_arr = string.split\n new_arr.collect do |word|\n word.reverse\n end.join(' ')\n \nend",
"def reverse_each_word(string)\n array = string.split(\" \")\n def reversed_array(array)\n array.collect do |string| \n string.reverse\n end\n end\n reversed_array(array).join(\" \")\nend",
"def reverse_each_word(string)\n string_array = string.split(' ')\n reversed_array = []\n string_array.collect do |words|\n reversed_array << words.reverse\n end\n reversed_array.join(' ')\nend",
"def reverse_each_word(sentence)\n words_array = sentence.split(\" \") \n new_array = []\n new_array = words_array.collect {|word| word.reverse}\n new_array.join(\" \")\nend",
"def reverse_each_word(string)\n sentence_array = string.split(\" \")\n reversed_array = []\n sentence_array.collect do |string|\n reversed_array << string.reverse\n end\n reversed_array.join(\" \")\nend",
"def reverse_each_word(string)\n array = string.split(\" \")\n new_array = []\n array.collect do |word|\n new_array.push(word.reverse)\n end\n new_array.join(\" \")\nend",
"def reverse_each_word(string)\n array = string.split\n array.collect {|words| words.reverse}.join(\" \")\nend",
"def reverse_each_word(sentence)\narrayed = sentence.split (\" \")\nreversed = arrayed.collect {|i| i.reverse}\nreversed.join (\" \")\nend",
"def split_reverse(string)\n\tnew_strings = string.split(' ')\n\treturn new_strings.reverse\nend",
"def reverse_words(string)\n array = string.split(\" \")\n reversed_array = array.each{|element| element.reverse!()}\n final = reversed_array.join(\" \")\n p final\nend",
"def reverse_each_word(string)\n string_to_array = string.split\n reverse_array = []\n string_to_array.collect do |word|\n reverse_array << word.reverse\n end #each\n reverse_array.join(' ')\nend",
"def reverse_each_word(input_string)\n input_array = input_string.split(\" \")\n \n reverse_array = input_array.collect{ |each_word| each_word.reverse}\n reverse_array.join(\" \")\nend",
"def reverse_words(string)\n # reversed_string = string.reverse!\n # reversed_array = reversed_string.split(\" \")\n # p reversed_array\n # reversed_array.sort! {|x, y| y<=>x}\n # p reversed_array\n\n split_string = string.split(\" \")\n split_string.each do |word|\n word.reverse!\n end\n reversed_string = split_string.join(\" \")\n puts reversed_string\nend",
"def reverse_each_word(string)\n new_array = []\n string = string.split(\" \")\n string = string.collect{|x| x.reverse}\n new_array = string.join(\" \")\n new_array\nend",
"def reverse_each_word(string)\n new_array = string.split(\" \").collect do |word|\n word.reverse\n end\n new_array.join(\" \")\nend",
"def reverse_each_word(string)\r\n array = string.split(\" \")\r\n reverse_array = []\r\n array.collect do|string|\r\n reverse_array << string.reverse\r\n end\r\n reverse_array.join(\" \")\r\nend",
"def reverse_each_word(sentence1)\n sentence1.split.collect {|word| word.reverse}.join(\" \")\n# new_array = []\n# reversed_words = []\n# new_array << sentence1.split.collect(&:reverse!).join(\" \")\n #reversed_words << new_array.collect(&:reverse!)\n #new_array.collect {|word| reversed_words << word.reverse}\n# sentence1.split('').reverse.join('').reverse\n #binding.pry\n #new_array\nend",
"def reverse_each_word(string_of_words)\n storage_array1 = string_of_words.split(\" \")\n final_message = \"\"\n storage_array1.collect do |word|\n final_message += \"#{word.reverse!} \"\n end\n final_message.strip\nend",
"def reverse_each_word(string)\n array = string.split(\" \")\n new_array = []\n array.collect do |reverse|\n new_array << reverse.reverse\n end\n new_array.join(\" \")\nend",
"def reverse_each_word(string)\n new_array = string.split\n reversed = new_array.collect do |word|\n word.reverse\n end\n reversed.join(' ')\nend",
"def reverse_each_word(sentence)\n array = sentence.split(\" \")\n array_new = []\n array_new = array.collect do |element| \n element.reverse \n end\n array_new.join(\" \")\nend",
"def reverse_each_word(string)\n array = string.split(\" \") #can't enumerate on string, so must turn into an array.\n test_array = [] #creating a new array.\n array.collect do |string| #iterate over the string.\n test_array << string.reverse #adding the reverse string into the new empty array.\n end\n test_array.join(\" \") #making the array a string again. \nend",
"def reverse_each_word(sentence1)\n \n reverse_array=[]\n split_sentence_array=sentence1.split(\" \")\n reversed=split_sentence_array.collect {|word| word.reverse}\n reversed.join(\" \")\n \nend",
"def reverse_each_word(sentence)\n array = sentence.split\n new_arr = []\n array.collect do |word| \n new_arr << word.reverse\n end\n p new_arr.join(' ')\nend",
"def reverse_each_word(string)\nstring = string.split(\" \")\nsentence1 = string.each {|a| a.reverse}\nsentence1.join(\" \")\nsentence2 = string.collect {|a| a.reverse}\nsentence2.join(\" \")\nend",
"def reverse_every_element_in_array(array)\n array.map{ | word | word.reverse }\nend",
"def reverse_words(string)\n split_array = string.split(' ')\n results_array = split_array.map! do |word|\n word.reverse\n end\n results_array.join(' ')\nend",
"def reverse_each_word(string)\n array = string.split(\" \")\n new_array = []\n array.collect do |string|\n new_array << string.reverse\n end\n new_array.join(\" \")\nend",
"def reverse_each_word(string)\n array = string.split(\" \")\n new_array = []\n array.collect do |string|\n new_array << string.reverse \n end\n return new_array.join(\" \")\nend",
"def reverse(array)\n array.collect do |word|\n word.reverse\n end\nend",
"def reverse_each_word(string)\n new_string = string.split(\" \")\n new_array = new_string.collect do |item|\n item.reverse\n end\n\tnew_array.join(\" \")\nend",
"def reverse_each_word(string)\n words_arr = string.split\n reverse = words_arr.collect {|word| word.reverse}\n reverse.join(\" \")\nend",
"def reverse_each_word(sentence)\r\n array1 = sentence.split(\" \")\r\n array1.collect do |x|\r\n x.reverse!\r\n end\r\n array1.join(\" \")\r\nend",
"def reverse_words(string)\n words=string.split(\" \")\n array=[]\n words.each do |word|\n array.push(word.reverse!)\n end\n p array.join(\" \")\nend",
"def reverse_each_word(string)\n array = string.split(\" \")\n reverse_array = array.collect {|word| word.reverse}\n reverse_string = reverse_array.join(\" \")\n return reverse_string\nend",
"def reverse_each_word(sentence)\n array_of_split_string = []\n reversed_words = []\n array_of_split_string = sentence.split\n array_of_split_string.collect {|words| reversed_words << words.reverse!}\n reversed_words.join(\" \")\nend",
"def reverse_each_word (sentence)\n array_sentence = sentence.split()\n array_reversed = array_sentence.collect do |word|\n word.reverse\n end\n array_reversed.join(\" \")\nend",
"def reverse_each_word(string)\n strarray = string.split(\" \")\n new_string = strarray.collect {|word|\n word.reverse }\n new_string.join(\" \")\nend",
"def reverse_each_word(string)\n array = string.split(\" \")\n reversed_array = array.collect do |element| \n element.reverse\n end\n result = reversed_array.join(\" \")\n return result\nend",
"def reverse_each_word(sentence1)\n ## sentence1.split turns the string into an array, where each word is an element of the array. No spaces.\n sentence_array = sentence1.split\n sentence_array.collect { |word|\n \n ## .reverse! reverses each word \"in place\", not creating new\n word.reverse!\n }\n ## .join(\" \") takes the elements of the array, joins them as a string with a space between each \n sentence_array.join(\" \")\nend",
"def reverse_each_word(string)\n sentence_array = string.split(\" \")\n reversed_sentence = []\n sentence_array.collect do |word|\n reversed_sentence << word.reverse\n end\n reversed_sentence.join(\" \")\nend",
"def reverse_each_word(string)\n array = string.split \" \"\n array.collect { |word| word.reverse! }\n array.join(\" \")\nend",
"def reverse_each_word(string)\n array = string.split\n array.each do |word|\n word.reverse!\n end\n array.join(\" \")\nend",
"def reverse_each_word(string)\n array_frm_string = string.split(\" \")\n rev_string = \"\"\n array_frm_string.collect do |word|\n rev_string << word.reverse + \" \"\n end\n rev_string.chop\nend",
"def reverse_each_word(words)\n words.split(\" \").collect{ |x| x.reverse}.join(\" \")\nend",
"def reverse_each_word(sentence)\n new_array = sentence.split(\" \").collect do |word|\n word.reverse!\n end\n new_array.join(\" \")\nend",
"def reverse_each_word(sentence)\n array=sentence.split(\" \")\n new_arr=[]\n array.collect do |word|\n new_arr<< word.reverse\n end\n new_arr.join(\" \")\n end",
"def reverse_words(string)\n words = string.split(\" \")\n words.map! {|element| element.reverse}\n words.join(\" \")\n\nend",
"def reverse_each_word(sentance)\n reversed_sentance = []\n sentance = sentance.split(\" \")\n sentance.collect do |word|\n reversed_sentance << word.reverse\n end\n reversed_sentance.join(\" \")\nend",
"def reverse_each_word(string)\n string_array = string.split(\" \");\n reverse_string_array = string_array.collect { |string| string.reverse};\n return reverse_string_array.join(\" \");\nend",
"def reverse_each_word(string)\n array = string.split(' ')\n array.collect do |word|\n word.reverse!\n end\n array.join(' ')\nend",
"def reverse_each_word(string)\n arrayOfReversedWords = string.split.collect do |letter|\n letter.reverse\n end\n arrayOfReversedWords.join(\" \")\nend",
"def reverse_each_word(sentence)\n new_array = sentence.split(\" \")\n \n new_sentence = new_array.collect do |word| \n word.reverse \n end\n \n new_sentence.join(\" \")\nend",
"def reverse_each_word(string)\n array = string.split\n rev_array = array.collect do |i|\n i.reverse\n end\n rev_array.join(\" \")\nend",
"def reverse_each_word(string)\n array = string.split\n \n array.collect do |element| \n element.reverse\n end.join(\" \")\nend",
"def reverse_each_word(sentence1)\n array=sentence1.split(\" \")\n new_array=array.collect do |word|\n word.reverse\n end\n new_array.join(\" \")\nend",
"def reverse_each_word(string)\n arr = string.split\n reversed = arr.collect do |n| n.reverse\n end\n p reversed.join(\" \")\nend",
"def reverse_each_word(string)\n s = string.split(\" \")\n backward_sentence = s.collect do |word|\n word.reverse\n end\n backward_sentence.join(\" \")\nend",
"def reverse_each_word(string)\n string_array = string.split(' ')\n string_array.collect do |word|\n word.reverse!\n end\n string_array.join(\" \")\nend",
"def reverse_each_word (sentence)\r\n arr = sentence.split\r\n new_sentence = []\r\n arr.collect do |word|\r\n new_sentence << word.reverse\r\n end\r\n new_sentence.join(\" \")\r\nend",
"def reverse_words(words)\n reversed = words.split(' ') # split each sentence into array after each space\n reversed.map {|element| element.reverse!} # loop through and\n reversed.join(' ') # join the array elements with a space between each element\nend",
"def reverse_each_word(sentence)\n sentence_array = []\n split_sentence = sentence.split\n \n split_sentence.collect do |element|\n reverse = element.reverse\n sentence_array << reverse\n \n end\nreverse_sentence = sentence_array.join(\" \")\nreverse_sentence\nend",
"def reverse_each_word(string)\n words = string.split(\" \")\n \n words.collect do |word|\n word.reverse!\n end\n \n words.join(\" \")\nend",
"def reverseString(string)\n splitString = string.split(' ')\n splitString.each do |word|\n word.reverse!\n end\n puts splitString.join(' ')\nend",
"def reverse_each_word(string)\n array = string.split\n array = array.collect do |word|\n word.reverse\n end\n string = array.join(\" \")\n string\nend",
"def reverse_each_word(str)\n str_arr = str.split\n new_str_arr = str_arr.collect do |word|\n word.reverse\n end\n new_str_arr.join(' ')\nend",
"def reverse_each_word(sentence)\n array =[ ]\n new_sentence = \" \"\n(sentence.split).collect do |word|\n word.reverse\n array << (word.reverse)\nend\narray.join(\" \")\nend",
"def reverse_each_word(string)\n sentence = string.split(\" \")\n sentence.collect do |word|\nword.reverse\nend.join(\" \")\nend",
"def reverse_each_word(sentence)\n array = sentence.split\n array = array.collect {|word| word.reverse}\n array.join(\" \")\nend",
"def reverse_each_word(str)\n arr = str.split\n revArr = arr.collect do |word|\n word.reverse\n end\n revArr.join(\" \")\nend",
"def reverse_each_word(sentence)\n\n sentence_array = sentence.split\n \n joined_sentence = sentence_array.collect do |something|\n something.reverse\n\n end\n joined_sentence.join(\" \")\nend",
"def reverse_each_word(sentence)\n backwards = []\n sentence_array = sentence.split(/ /)\n sentence_array.collect do |word|\n backwards << word.reverse\n end\n backwards.join(\" \")\nend",
"def reverse_each_word(string)\n reversed = string.split(\" \").collect do |word|\n word.reverse\nend\n reversed.join(\" \")\nend",
"def reverse_each_word(sentence)\n word_array = []\n rev_array = []\n word_array = sentence.split\n word_array.collect {|word| rev_array << word.reverse}\n return rev_array.join(\" \")\nend",
"def reverse_each_word(sentence)\n sentence.split.collect {|word| word.reverse}.join(' ')\n # new_sentence = []\n # new_sentence = sentence.split(' ')\n # new_sentence.collect {|word| word.reverse}\n # new_sentence.join(' ')\n end",
"def reverse_each_word(sentence1)\r\nnew_array = []\r\nsentence1.split.collect do |words| new_array << \"#{words}\".reverse\r\n end\r\nnew_array.join(\" \")\r\nend",
"def reverse_each_word(string)\n p string.split.collect {|word| word.reverse}.join(\" \")\nend",
"def reverse_each_word(string)\n array = string.split\n array.collect do |element|\n element.reverse!\n end\n array.join(\" \")\nend",
"def reverse_each_word(astring)\n astring.split(\" \").collect {|word| word.reverse}.join(\" \")\nend",
"def reverse_each_word(string)\n split = string.split\n split = split.collect do |word|\n word.reverse\n end\n return split.join(\" \")\nend",
"def reverse_words(string)\n word_array = string.split\n reversed_sentence = [ ]\n \n word_array.each do |word|\n reversed_sentence.push(word.reverse)\n end\n\n p reversed_sentence.join(\" \")\nend",
"def reverse_words(words)\n separate_words = words.split\n new_ary = separate_words.map do |word|\n word.reverse\n end\n new_ary.join(' ')\nend",
"def reverse_each_word(phrase)\n phrase.split.collect {|word| word.reverse}.join(\" \")\n \n end",
"def reverse(string)\ns = string.split.reverse.join(\" \")\n #your code here\nend",
"def reverse_each_word(string)\n step_one = string.split(\" \")\n step_one.collect do |word| word.reverse\n \"#{word.reverse}\"\n end\n .join(\" \")\nend",
"def reverse_each_word(sentence) # will use #collect\n sentence.split(\" \").collect {|word| word.reverse}.join(\" \")\nend",
"def reverse(string)\n array = string.split(\" \")\n reversed_array = array.reverse\n reversed_string = reversed_array.join(\" \")\nend",
"def reverse_words(string)\n words = string.split(\" \")\n words.map! {|element| element.reverse}\n words.join(\" \")\nend",
"def reverse_each_word(sentence)\n sentence_array = sentence.split(/ /) \n final_sentence = sentence_array.collect {|word| word.reverse}\n final_sentence.join(\" \")\nend",
"def reverse_each_word(sentence)\n reversed = []\n array = sentence.split(/ /)\n array.collect do |word|\n reversed << word.reverse\n end\n reversed.join(\" \")\nend"
] |
[
"0.80633825",
"0.78274935",
"0.7817646",
"0.781217",
"0.7809727",
"0.77886355",
"0.7777532",
"0.77596",
"0.7757672",
"0.77559143",
"0.77505636",
"0.77380085",
"0.7734981",
"0.7732814",
"0.7699341",
"0.76940763",
"0.7664423",
"0.7663534",
"0.7662147",
"0.7662048",
"0.765288",
"0.7650998",
"0.76508605",
"0.7648447",
"0.76338404",
"0.76319784",
"0.76226795",
"0.76216733",
"0.76197517",
"0.7615009",
"0.7609032",
"0.76067454",
"0.7600395",
"0.75900644",
"0.75885046",
"0.7583135",
"0.7576318",
"0.75758016",
"0.7575619",
"0.75750804",
"0.75749165",
"0.75701463",
"0.756732",
"0.7561734",
"0.75562763",
"0.75545925",
"0.7553303",
"0.7553235",
"0.7551667",
"0.7543921",
"0.75371134",
"0.75255686",
"0.7519878",
"0.7519104",
"0.7494038",
"0.7492959",
"0.7491092",
"0.7489414",
"0.7480114",
"0.7478501",
"0.74756616",
"0.74649596",
"0.7463553",
"0.74590975",
"0.7456509",
"0.74559814",
"0.7444679",
"0.7440895",
"0.7439612",
"0.7430119",
"0.7421556",
"0.7419091",
"0.7418345",
"0.74178725",
"0.74151725",
"0.74143535",
"0.74137425",
"0.74082273",
"0.74023914",
"0.74004406",
"0.73949134",
"0.7390657",
"0.7384549",
"0.73814577",
"0.7374443",
"0.73728406",
"0.7362907",
"0.73587084",
"0.7355467",
"0.735098",
"0.7347866",
"0.7327379",
"0.73204595",
"0.73080885",
"0.7306621",
"0.73063457",
"0.7297942",
"0.729737",
"0.72854656",
"0.7283391"
] |
0.74773896
|
60
|
NO VIEW TEMPLATE Linked from account/preferences/_privacy bulk_filename_purge
|
def update
Image.where(user_id: User.current_id).update_all(original_name: "")
flash_notice(:prefs_bulk_filename_purge_success.t)
redirect_to(edit_account_preferences_path)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def file_name\n 'unused'\n end",
"def delete_fragments\n glob_cache_expire( 'C:/tmp/cache/views/user_type_id/*/browse/category_id/' + self.id.to_s )\n\n glob_cache_expire( 'C:/tmp/cache/views/user_type_id/*/shared_symbiont/symbiote_wrapper_container/symbiote_item_category_id/' + self.id.to_s )\n\n glob_cache_expire( 'C:/tmp/cache/views/user_type_id/*/shared_menu/menu_organized_category/category_id/' + self.id.to_s )\nend",
"def remove_unimported_pages\n end",
"def info_file_empty\n File.join(Rails.root, 'app', 'views', 'layers', 'custom', topic_name.downcase, \"_#{name}_info_leer.html.erb\")\n end",
"def obsolete_files; end",
"def no_supplemental_files\n model.persisted? && supplemental_files.blank?\n end",
"def croucher_index_file\n nil\n end",
"def prune_index\n# missing_files=index_time_dbm_file.reject{|filename,itime| File.exists?(filename) && Picolena::IndexedDirectories.any?{|dir,alias_path| filename.starts_with?(dir)}}\n# missing_files.each{|filename, itime|\n# index.writer.delete(:complete_path, filename)\n# index_time_dbm_file.delete(filename)\n# logger.debug \"Removed : #{filename}\"\n# }\n# index.optimize\n end",
"def confirmation_instructions(record, token, opts={})\n if record.respond_to?(:coupon_id) && !record.coupon_id.nil? && Dir.exists?(\"#{Rails.root}/app/views/users/mailer/#{Coupon.find(record.coupon_id).shareable_tag}\")\n opts[:template_path]=\"users/mailer/#{Coupon.find(record.coupon_id).shareable_tag}\"\n end\n super\n end",
"def delete_service_files(resource)\n file get_service_script_name(resource) do\n action :delete\n only_if { get_service_script_name != nil }\n end\nend",
"def remove_files_we_dont_need\n say 'Remove files we don\\'t need'\n build :remove_public_index\n build :remove_readme_rdoc\n end",
"def empty_storage!\n if storage_exists?\n empty_storage\n else\n raise IOError, \"No banned words file!\"\n end\n end",
"def before_filter_check_on_hash(hsh, nm)\n if hsh.has_key?(:content)\n cont = hsh.delete(:content)\n temp_file = \"#{base_dir}/templates/default/#{nm}.erb\"\n ::FileUtils.mkdir_p(::File.dirname(temp_file)) unless ::File.directory? temp_file\n ::File.open(temp_file, \"w+\") {|f| f.print cont }\n hsh.merge!({:source => \"#{nm}.erb\"})\n end\n # \n hsh.delete(:require) if hsh.has_key?(:require)\n hsh\n end",
"def sweep_partial_cache\n cache_dir = RAILS_ROOT+\"/tmp/cache/views/*\"\n FileUtils.rm_r(Dir.glob(cache_dir)) rescue Errno::ENOENT\n logger.debug(\"Cache '#{cache_dir}' delete.\")\n end",
"def delete\n super \"/templates/#{template_id}.json\", {}\n end",
"def remove_attachment\n @user.assegnazione.purge if @user.assegnazione.attached?\n render :show\n end",
"def basename\n 'unused'\n end",
"def clean_environment\n `rm -rf /tmp/#{@upload_id}` # all sliced pages of the source file\n end",
"def purge\n ::FileUtils.rm(@fname)\n end",
"def purge\n end",
"def destroy_manuscript\n requires_user_can :edit, task\n paper.file.destroy!\n\n head :no_content\n end",
"def prune_index\n missing_files=index_time_dbm_file.reject{|filename,itime| File.exists?(filename) && Picolena::IndexedDirectories.any?{|dir,alias_path| filename.starts_with?(dir)}}\n missing_files.each{|filename, itime|\n index.writer.delete(:complete_path, filename)\n index_time_dbm_file.delete(filename)\n logger.debug \"Removed : #{filename}\"\n }\n index.optimize\n end",
"def index\n assets = current_user.assets.all\n \n assets.each do |asset|\n if asset.tempfile == true\n asset.destroy\n end\n end\n \n @assets = current_user.assets.all\n end",
"def remove_views\n FileUtils.rm_rf(File.dirname(__FILE__) + \"/views\")\n end",
"def empty\n files.each { |filename, data| open(filename) if data[:safe] }\n end",
"def template_name; end",
"def template_name; end",
"def remove_file\n @assignment = Assignment.find(params[:id])\n if ((@assignment.facebook_user.id == @fb_user.id) or (@assignment.is_author? @fb_user))\n @assignment.remove_file(params[:path])\n ZipWorker.asynch_zip_assignment(:id => @assignment.id)\n render :partial => \"file_removed\", :layout => false\n end\n end",
"def delete_all_files\n @import.delete_all_files\n head :no_content\n end",
"def purge_unused_page_index(index)\n purge_page_index(index)\n end",
"def delete_content(title)\n File.delete(\"pages/#{title}.txt\")\nend",
"def keep_files; end",
"def delete_cache_files; end",
"def delete_cache_files; end",
"def del_copy_views_dir(template_dir,the_dir)\n\n real_template_dir = Rails.root.join('app/assets/templates/'+template_dir).to_s # /app/assets/templates/ror_cms\n real_view_dir = Rails.root.join('app/views/'+the_dir).to_s # /app/views/[landing,devise,article_single,...]\n\n #view directory\n if Dir.exists?(real_view_dir)\n FileUtils.rm_rf(Dir.glob(real_view_dir+'/*'))\n end\n\n #template directory\n if Dir.exists?(real_template_dir+'/views/'+the_dir)\n FileUtils.cp_r real_template_dir+'/views/'+the_dir+'/.', real_view_dir\n end\n\n end",
"def public_txt_files\n template 'humans.txt.tt', 'public/humans.txt'\n template 'robots.txt.tt', 'public/robots.txt', force: true\n end",
"def template() false end",
"def unshare_file_in_db(file_id, user_id)\n $db.execute(\"DELETE FROM shared_files WHERE file_id = ? AND user_id = ?\", file_id, user_id)\nend",
"def delete_index_file\n $log.info(\"Deleting old index.html file...\")\n File.delete(\"/home/matt/Documents/programming/ruby/dmsw/index.html\")\nend",
"def del_weblog_explain; \"Remove weblog from your list.\"; end",
"def purgeFiles\n Dir[\"#{@pagespath}/*\"].reject{ |f| f[\"#{@pagespath}/.keep\"] }.each do |filename|\n File.delete filename\n end\n\n Dir[\"#{@assetpath}/*\"].reject{ |f| f[\"#{@pagespath}/.keep\"] }.each do |filename|\n File.delete filename\n end\n end",
"def remove_content\n File.unlink(filename) if File.exist?(filename)\n end",
"def cleanup\n begin\n File.delete(full_filename, full_filename + \".meta\")\n rescue\n logger.warn \"Unable to delete recordings files: #{full_filename}*\"\n end\n end",
"def unpublish\n template = Template.find(params[:id])\n authorize template\n Template.transaction do\n # expected: template is latest\n template.generate_version! if template.published? && template.plans.any?\n Template.where(family_id: template.family_id)\n .update_all(published: false)\n end\n flash.now[:notice] = _(\"Successfully unpublished your #{template_type(template)}\") if flash[:alert].blank?\n redirect_to(request.referer.presence || org_admin_templates_path)\n end",
"def delete_opml_file\n if self.filename.present?\n Feedbunch::Application.config.uploads_manager.delete self.user_id, OpmlExporter::FOLDER, self.filename\n end\n end",
"def clean_filename\n doc_file_name.gsub!(' ', '_')\n end",
"def remove_file(file)\n file = File.expand_path(file, @app.root)\n \n if @local_data.has_key?(file)\n @app.cache.remove(:raw_template, file)\n @local_data.delete(file) \n end\n end",
"def delete(filename); end",
"def remove_section_markdown_file(file_name)\n if File.exists? \"./web/source/markdown/#{file_name}.md.erb\"\n `rm ./web/source/markdown/#{file_name}.md.erb`\n end\n end",
"def remove_virus_affected_file()\n @import.destroy\n end",
"def delete_blocked\n end",
"def remove_pdf\n begin\n File.delete \"public/pdfs/legal_briefs/\" + self.id.to_s + \".pdf\" \n rescue Errno::ENOENT\n # if file is not there, just ignore\n end\n end",
"def template!(path, full_paths = T.unsafe(nil)); end",
"def purge\n\n\t\tend",
"def filename_completion\n#p @tmpl_doc.basename_orig\n#p @cfg[:append_doc]\n#p Dyndoc.docExt(@cfg[:format_doc])\n ext_mode=nil\n if @tmpl_doc.basename_orig =~ /\\_(html|tex|c|rb|txtl|md|txt|raw)$/\n @cfg[:cmd] += [:make_content,:save]\n ext_mode=$1.to_sym\n @cfg[:format_doc]=@cfg[:mode_doc]=@cfg[:format_output]=(ext_mode == :raw ? :txt : ext_mode )\n last=-(2 + $1.length)\n else\n last=-1\n end\n ##DEBUG:\n p [@tmpl_doc.basename_orig[0..last],@tmpl_doc.cfg[:append],@cfg[:append_doc],@cfg[:format_doc],Dyndoc.docExt(ext_mode || @cfg[:format_doc])]\n @cfg[:filename_doc]=@tmpl_doc.basename_orig[0..last]+@tmpl_doc.cfg[:append]+@cfg[:append_doc]+Dyndoc.docExt(ext_mode || @cfg[:format_doc]) if @cfg[:filename_doc].empty?\n ##p [:filename_completion,@filename,@cfg[:filename_doc] ]\n end",
"def clean_local_file\n File.delete(@file_path) if File.exist? @file_path\n end",
"def delete_expired_tempfiles\n return if !self.config.clean_up? || !self.config.enabled?\n log \"CloudTempfile.delete_expired_tempfiles is running...\"\n # Delete expired temp files\n fog_files = (self.config.local?)? local_root.files : get_remote_files\n fog_files.each do |file|\n if file.last_modified <= Time.now.utc.ago(self.config.clean_up_older_than)\n delete_file(file)\n end\n end\n log \"CloudTempfile.delete_expired_tempfiles is complete!\"\n end",
"def index\n @title = @view_title = t(\"contact.title\") \n #@ft = \"removed\"\n # this is also done inline in toolbar\n end",
"def remove_storage_use_nfs(opts)\n opts = check_params(opts,[:usage])\n super(opts)\n end",
"def remove_unwanted_views\n blacklight_config.view.delete(:gallery)\n blacklight_config.view.delete(:masonry)\n blacklight_config.view.delete(:slideshow)\n end",
"def delete_extra_files( filelist )\n\tdescription = humanize_file_list( filelist, ' ' )\n\tlog \"Files to delete:\\n \", description\n\task_for_confirmation( \"Really delete them?\", false ) do\n\t\tfilelist.each do |f|\n\t\t\trm_rf( f, :verbose => true )\n\t\tend\n\tend\nend",
"def delete_extra_files( filelist )\n\t\t\tdescription = humanize_file_list( filelist, '\t ' )\n\t\t\tlog \"Files to delete:\\n \", description\n\t\t\task_for_confirmation( \"Really delete them?\", false ) do\n\t\t\t\tfilelist.each do |f|\n\t\t\t\t\trm_rf( f, :verbose => true )\n\t\t\t\tend\n\t\t\tend\n\t\tend",
"def delete_file_parts\n #TODO implementation\n end",
"def delete_file \n #pp \"deleting file_asset: path is\" + full_filepath\n File.delete(full_filepath) if File.exists?(full_filepath)\n end",
"def purge_files(to_purge)\n to_purge.each do |p|\n begin\n Puppet.debug(\"Attempting to purge #{p.to_s}\")\n p.delete\n rescue\n Puppet.err(\"File #{p.to_s} could not be deleted\")\n else\n Puppet.debug(\"File #{p.to_s} has been deleted\")\n end\n end\n end",
"def deletable?\n is_regular_page?\n end",
"def non_autograded_template_files=(template_files)\n self.template_files.clear\n self.template_files = template_files\n test_cases.clear\n end",
"def cleanTmp\n ts_str = \"/tmp/d\" + Date.today.strftime(\"%Y%m%d\") + \"-*\"\n Gitchefsync.logger.info \"clean up of #{ts_str}\"\n FS.cmdNoError \"sudo rm -fr #{ts_str}\"\n end",
"def photo__after_destroy_trigger\r\n\r\nDir[File.join(FILES_DEST_PHOTO, \"#{self.id}_*\")].each{|f| File.delete(f)}\r\nDir[File.join(FILES_DEST_PHOTO__THUMBS, \"#{self.id}_*\")].each{|f| File.delete(f)}\r\nend",
"def safe_delete_contents\n SafeDeletable.path_for(self).children.each {|entry| FileUtils.remove_entry_secure(entry) }\n end",
"def delete_local\n super\n end",
"def delete_files\n #TODO delete original file\n unless filename.blank?\n File.delete(splash_file(:full_path => true)) if File.exists?(splash_file(:full_path => true))\n File.delete(flv_file(:full_path => true)) if File.exists?(flv_file(:full_path => true))\n File.delete(original_file) if File.exists?(original_file)\n end\n end",
"def delete_tags(filename=@filename)\n Mutagen::AIFF::delete_chunk filename\n clear\n end",
"def purge_type!(type)\n # puts \"*** before purge type #{type},Document.count:#{Document.count}\"\n Document.delete_all(:typ => type)\n # puts \"*** after purge type #{type},Document.count:#{Document.count}\"\n end",
"def delete_view\n super\n end",
"def file_delete(file)\n\t\tputs \"Delete entries to the local site store from file: #{file}\" if @verbose\n\t\traise \"File non-exist. Please check your file path and name again: #{file}\" unless File.exist?(file)\n\t\tsites=file_2_list(file)\n\t\tchanges=Array.new\n\t\tchanges=bulk_delete(sites) unless sites.nil? or sites.empty?\n\trescue => ee\n\t\tputs \"Exception on method file_delete: #{ee} for file: #{file}\" if @verbose\n\tend",
"def remove_temp_files(xfrm)\n xfrm.destroy!\n end",
"def remove_index\n remove_file \"public/index.html\"\n end",
"def remove_index\n remove_file \"public/index.html\"\n end",
"def generate_html_views\n selective_copy 'app/views/kublog/posts/*.html.erb'\n end",
"def notemplate\n \"there is no 'notemplate.xhtml' associated with this action\"\n end",
"def notemplate\n \"there is no 'notemplate.xhtml' associated with this action\"\n end",
"def notemplate\n \"there is no 'notemplate.xhtml' associated with this action\"\n end",
"def notemplate\n \"there is no 'notemplate.xhtml' associated with this action\"\n end",
"def notemplate\n \"there is no 'notemplate.xhtml' associated with this action\"\n end",
"def notemplate\n \"there is no 'notemplate.xhtml' associated with this action\"\n end",
"def active_template?\n stored_files.template.count > 0\n end",
"def unfiltered_content; end",
"def unfiltered_content; end",
"def unfiltered_content; end",
"def confirm_filename(filename)\n filename.gsub!(/[<>:\"\\/\\\\|?*]/) { \"\" }\n end",
"def purge!\n\n fetch_all({}).each { |hwi| @context.storage.delete(hwi) }\n end",
"def ftpCleanUp(conf,ftp)\n limit=conf[:generations]\n puts \"Remote backup files:\"\n #must match generated archive names\n a=ftp.nlst(conf[:backupFile]+'????????-??????.tgz').sort\t\n a.each do |e| puts e end\n return if a.size<= limit\n while (a.size> limit)\n ftp.delete(a[0])\n puts 'Deleted old archive: '+a[0]\n a.delete_at(0)\n end\nend",
"def no_content_for(name)\n @view_flow.append!(name, DryViews::EMPTY_CONTENT)\n end",
"def reset\n\t\t\t#@index = 0\n\t\t\tload_template @filename\n\t\tend",
"def destroy\n mytemplate = Mytemplate.get(params[:id])\n close_document(mytemplate)\n \n begin\n if mytemplate != nil\n if File.exist?(mytemplate.path) \n FileUtils.rm_rf mytemplate.path\n end\n \n if File.exist?(mytemplate.file_path+mytemplate.id.to_s) \n FileUtils.rm_rf mytemplate.file_path+mytemplate.id.to_s\n end\n\n end\n rescue\n puts_message \"Error! in progress of mytemplate file deletion.\"\n end\n\n mytemplate.destroy\n \n respond_to do |format|\n format.html { redirect_to(mytemplates_url) }\n format.xml { head :ok }\n end\n end",
"def importable_wilds\n wilds.select {|w| Hash === w && w['IMPORT_TEMPLATE'] }\n end",
"def use_template_filename\n return nil unless @args[:___use_template___]\n ConfigData.real_type_filename 'templates', @args[:___use_template___]\n end",
"def index\n @bulk_mails = policy_scope(BulkMail).includes(:user, :template).order(updated_at: :desc).page(params[:page])\n end",
"def keep_files=(_arg0); end"
] |
[
"0.5718153",
"0.55457807",
"0.5495424",
"0.540882",
"0.53963405",
"0.52423024",
"0.5186017",
"0.51778716",
"0.51776326",
"0.51735777",
"0.5148203",
"0.51074004",
"0.5094198",
"0.5092664",
"0.5091207",
"0.5089462",
"0.5087719",
"0.5080943",
"0.5072686",
"0.50652784",
"0.50605226",
"0.5059106",
"0.5046954",
"0.5038575",
"0.50373554",
"0.5031597",
"0.5031597",
"0.50162655",
"0.5011431",
"0.49971226",
"0.4986055",
"0.49632967",
"0.4953464",
"0.4953464",
"0.49474367",
"0.49372685",
"0.49343938",
"0.49320728",
"0.49256742",
"0.4906128",
"0.4899853",
"0.4892526",
"0.4888102",
"0.48858517",
"0.48704135",
"0.4865894",
"0.48608312",
"0.4838592",
"0.48358396",
"0.48253968",
"0.48237786",
"0.4821217",
"0.48201308",
"0.48170283",
"0.48062614",
"0.48004723",
"0.4798979",
"0.47980034",
"0.4793228",
"0.47921833",
"0.47902775",
"0.47683287",
"0.47641143",
"0.47637066",
"0.4763607",
"0.4750993",
"0.47509748",
"0.47474784",
"0.47468624",
"0.47446418",
"0.47425637",
"0.47365192",
"0.47311777",
"0.47299644",
"0.47247878",
"0.4716184",
"0.4709498",
"0.4707361",
"0.4707361",
"0.47037908",
"0.47026238",
"0.47026238",
"0.47026238",
"0.47026238",
"0.47026238",
"0.47026238",
"0.46967387",
"0.46959934",
"0.46959934",
"0.46959934",
"0.469361",
"0.46921846",
"0.46893373",
"0.46852824",
"0.4667622",
"0.4664925",
"0.46599588",
"0.46588773",
"0.4654367",
"0.46541327"
] |
0.49025226
|
40
|
returns the array with error letters
|
def errors
@user_guesses - normalized_letters
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def error(name)\n array name, required: false do |s|\n s.string\n end\n end",
"def error\n []\n end",
"def loose_errors\n err = []\n err << title\n err << authors\n err << s3_error_uploads\n err << url_error_validating\n\n err.flatten\n end",
"def errors\n result = []\n result.push(:title) unless valid_string? @title\n result.push(:author) unless valid_string? @author\n result.push(:release_date) unless valid_date? @release_date\n result.push(:publisher) unless valid_string? @publisher\n result.push(:isbn) unless valid_integer? @isbn\n result\n end",
"def get_error_codes\n return [] unless has_errors\n\n @errors.keys\n end",
"def error(ex) [:error, ex]; end",
"def errors\n @test_results.map { |tuple| (tuple[2] - tuple[3]).abs }\n end",
"def missing_letters\n missing = Array.new\n ('a'..'z').each {|l| missing << l if @hist[l] == 0}\n missing\n end",
"def get_all_errors\n\t\t@category.errors.full_messages.compact.join(',')\n\tend",
"def errors\n\t\t@errors.join(', ')\n end",
"def errors\n @errors.values.flatten\n end",
"def errors_array(record)\n record.errors.to_a\n end",
"def errors_array(record)\n record.errors.to_a\n end",
"def array\n ErrorArray.new(self)\n end",
"def show_wrong_letters\n\t\t@wrong_letters.sort.join(\", \")\n\tend",
"def errors\n @errors ||= []\n end",
"def errors\n @errors ||= []\n end",
"def errors\n @errors ||= []\n end",
"def show_wrong_letters\n puts \"These letters are not in the word: #{@wrong_letters.join(\", \")}\"\n puts \"\\n\"\n end",
"def getErrors() \n\t\t\t$errors = @errors\n\t\t\t#@errors = []\n\t\t\treturn $errors;\n\t\tend",
"def print_invalids\n\t\t@invalids.each do |invalids|\n\t\t\tprint \"Error: Unexpected character: \\\"#{invalids.get_value}\\\" \"\n\t\t\tputs \"at line: #{invalids.get_nline}, column: #{invalids.get_ncolumn}\" \n\t\tend\n\tend",
"def errors\n @errors ||= []\n end",
"def errors\n @errors ||= []\n end",
"def printer_error(s)\n # your code\n errs = 0\n possibles = s.length\n arr = s.split('')\n\n arr.each do |i|\n if i.ord > 109\n errs += 1\n end\n end\n\n \"#{errs}/#{possibles}\"\nend",
"def errors\n @errors || []\n end",
"def errors_string\n getErrors.map { |e| \"(#{e.object || ''}): #{e.error}\" }.join(', ').strip\n end",
"def errors\n @errors ||= []\n end",
"def errors\n @errors.values\n end",
"def errors\n if missing.empty?\n return RipperErrors.new(@code_lines.map(&:original).join).call.errors\n end\n\n missing.map { |miss| why(miss) }\n end",
"def errors\n @diagnostics.select {|d| d.severity == :error }\n end",
"def error_rows\n Array(@gapi.insert_errors).map { |ie| @rows[ie.index] }\n end",
"def error_messages\n errors ? errors.map { |prop, msg| \"#{prop} : #{msg}\" } : []\n end",
"def errors\n @error.fetch('errors', [])\n end",
"def get_all_errors\n\t\t@user.errors.full_messages.compact.join(',')\n\tend",
"def inspect\n errors = 0\n chars_array.each_with_index do |chars, index|\n chars_index = index + 1\n\n errors += 1 unless space_before_semicolon?(chars, chars_index)\n errors += 1 unless indentation?(chars, chars_index)\n errors += 1 unless trailing_white_space?(chars, chars_index)\n errors += 1 unless ending_semicolon?(chars, chars_index)\n errors += 1 unless space_before_colon?(chars, chars_index)\n errors += 1 unless space_after_colon?(chars, chars_index)\n end\n puts 'No Errors Found'.green if errors.zero?\n puts\n puts 'Fix Errors!'.red unless errors.zero?\n end",
"def errors_for row\n ie = insert_error_for row\n return ie.errors if ie\n []\n end",
"def error_response\n [\"I'm Sorry, I don't understand. Please try again\",\n \"Oh oh! Something went wrong. Please try again\",\n \"Um... Sorry, I don't understand. Did you input correct words?\"].sample\n end",
"def step_errors\n each_step_error.to_a\n end",
"def error_response\n [\"I'm Sorry, I don't understand. Please try again\",\n \"Oh oh! Something went wrong. Please try again\", \n \"Um... Sorry, I don't understand. Did you input correct words?\"].sample\n end",
"def errors\n errors_list.map(&:error)\n end",
"def errors\n err = []\n err << article_id\n err << title\n err << authors\n err << research_domain\n err << funder\n err << abstract\n err << subjects\n\n err << s3_error_uploads\n err << url_error_validating\n err << over_file_count\n err << over_files_size\n err << data_required\n\n err.flatten\n end",
"def error_message (errors)\n\tmessage = \"\"\n\terror_array = errors.split\n\n\terror_array.each do |error|\n\t\tcase error\n\t\twhen \"name\"\n\t\t\tmessage += \"Invalid Name \\n\"\n\t\twhen \"email\"\n\t\t\tmessage += \"Invalid Email \\n\"\n\t\twhen \"dup\"\n\t\t\tmessage += \"Duplicate Name \\n\"\n\t\twhen \"bName\"\n\t\t\tmessage += \"Invalid Business Name \\n\"\n\t\tend\n\tend\n\t\n\treturn message\nend",
"def contact_errors\n error \"name\"\n error \"age\"\n error \"homepage\"\n end",
"def full_error_messages_array(record, field, errors)\n if errors.is_a? Array\n errors.map { |attribute, message| record.errors.full_message(attribute, message) }\n else\n [record.errors.full_message(field, errors)]\n end\n end",
"def letter_array (name)\n\tname.chars\nend",
"def messages_from_errors(errors)\n buffer = []\n\n errors.each do |attribute, messages|\n buffer |= messages\n end\n\n buffer.join \"\\n\"\n end",
"def errors\n @errors ||= Hash.new { |hash, key| hash[key] = [] }\n end",
"def errors\n @errors ||= Hash.new { |hash, key| hash[key] = [] }\n end",
"def seriously_all_of_the_errors\n messages = errors.full_messages.reject { |e| e == \"#{I18n.t('nouns.extension').capitalize} version is invalid\" }\n\n extension_versions.each do |version|\n almost_everything = version.errors.full_messages.reject { |x| x =~ /Tarball can not be/ }\n messages += almost_everything\n end\n\n messages\n end",
"def error_message\n if @errors\n @errors.map { |(k,v)|\n \"#{k} #{v.join(',')}\"\n }.join(\"; \")\n end\n end",
"def get_error_response()\n error_message = \"\"\n @errors.each do |k,v|\n error_message << v + \",\"\n end\n error_message\n end",
"def error_messages\n return error_message_generator(@error_message)\n end",
"def api_result_errors(result)\n return result.to_h['errors'].map { |item| item['message'] }\n end",
"def errors\n return fetch('errors') || []\n end",
"def add_error mess_err\n @errors ||= Array::new\n @errors << mess_err\n end",
"def find_fail_keys(contents)\n keys = []\n contents.map do |line|\n line.scan(/(fail|raise)\\s+([A-Z]\\w+)\\,\\s+\\:(\\w+)/).each do |m|\n keys << m[1..2].map(&:underscore).join('.')\n end\n end\n keys.uniq\n end",
"def test_12_add_wrong_letter_to_wrong_count_array\r\n $wrong_count = [\"z\", \"x\", \"w\", \"q\", \"d\", \"f\", \"k\", \"m\"]\r\n letter = \"u\"\r\n results = wrong_letter(letter)\r\n assert_equal([\"z\", \"x\", \"w\", \"q\", \"d\", \"f\", \"k\", \"m\", \"u\"], $wrong_count)\r\n end",
"def input_error_messages(input_ary)\n if correct_color_input?(input_ary, COLORS) == false\n error_wrong_input_values\n elsif correct_input_size?(input_ary, 4) == false\n error_wrong_input_size\n end\n end",
"def failed_attemps\n\t\tselected_letters.select {|letter| !word.include?(letter)}.size\n\tend",
"def get_error_codes\n assert_not_nil @rdigg.info.get_error_codes\n end",
"def generate_failure_lines(array_file_content)\n array_details = Array.new\n array_get = false\n index = 0\n array_file_content.each do |line|\n index += 1 if array_get and line.match(Regexp.new(\"#{index + 2}\\\\)\"))\n array_get = true if line.match(Regexp.new(\"#{index + 1}\\\\)\"))\n if array_get and line.match(/assertions/).nil?\n array_details[index] = Array.new if array_details[index].nil?\n next if array_details[index].length == 0 and line.match(/[0-9]\\)/).nil?\n array_details[index] << line\n end\n end\n (0..index).to_a.each do |arr_index|\n html_details, array_details = generate_failure_or_error_line(array_details, arr_index)\n end\n html_details\n end",
"def _err_text(ary)\n ary[0] = __make_head + ary[0] unless $stderr.tty?\n ary.join(\"\\n \")\n end",
"def errors\n @fields.flat_map(&:errors)\n end",
"def error\n return {error: \"\"}\n end",
"def validation_errors\n errors = []\n ErrorCompiler.with_errors(errors) do |e|\n check_schools_consistency_in_each_round(e)\n check_legitimate_progress_through_rounds(e)\n check_wildcards(e)\n end\n errors\n end",
"def errors\n @errors ||= failed.select { |rule| rule.severity == \"Severe\" }\n end",
"def format_dv_errors(model)\n errors = []\n model.errors.each_pair do |key, value|\n errors.push({ key => value })\n end\n return errors\n end",
"def full_messages\n inject([]) do |m, kv| \n att, errors = *kv\n errors.each {|e| m << (e.is_a?(LiteralString) ? e : \"#{Array(att).join(' and ')} #{e}\")}\n m\n end\n end",
"def key_errors\n key(\"errors\")\n end",
"def error_chunks(text) \n text.split(/^$/).select(){ |block| block =~ /^(\\d+)\\t([^\\t]+)\\t([^\\t]+)\\t(.+)$/ }\nend",
"def error_fields\n\t\treturn self.missing | self.invalid.keys\n\tend",
"def error_fields\n\t\treturn self.missing | self.invalid.keys\n\tend",
"def error_list\n res = []\n t = @data_object\n res << \"Missing team name\" if t.team_name.empty?\n\n check_length(res, t.team_name, 100, \"Team Name\")\n\n cha = Challenge.with_id(t.team_challenge)\n if cha\n msg = cha.check_ok_for_level(t.team_level)\n res << msg if msg\n else\n res << \"Unknown challenge\"\n end\n\n @members.each do |m|\n unless m.tm_name.empty?\n res.concat m.error_list\n end\n end\n\n if res.empty?\n err = check_team_level\n res << err if err\n end\n res\n end",
"def make_error_list\n\t\terror_list = []\n\t\t@predictions.each do |arr|\n\t\t\terror_list <<(arr[2] - arr[3]).abs\n\t\tend\n\t\terror_list\n\tend",
"def find_dataset_errors(dataset:)\n errs = []\n return errs unless dataset.present? && !dataset.valid?\n\n errs << dataset.errors.full_messages\n errs = errs.flatten.uniq\n errs.any? ? [\"Dataset : #{errs}\"] : []\n end",
"def get_errors\n return nil unless has_errors?\n return filter_low_priority_errors(@stderr)\n end",
"def message_error errors\n errors.full_messages.find{|object| /en.errors.messages.extension_whitelist_error/ =~ object }.nil? ?\n errors.full_messages.first.capitalize.to_s.gsub('_',' ') + \".\" :\n 'Only jpeg,jpg and png allowed!'\n\tend",
"def errors\n self.__source.errors.messages.to_hash.stringify_keys\n end",
"def errors(text)\n res = @driver.checkSyntax([text])\n return res.first.errors\n end",
"def getErrorRecepientEmailList()\n return @errorRecepients\n end",
"def presentar_errores\n return unless self.errores.is_a? Hash\n return unless self.errores.any?\n self.errores.keys.map do |k|\n if self.errores[k].is_a? Array\n self.errores[k].map { |v| \"#{k.to_s.humanize}: #{v}\" }\n else\n \"#{k.to_s.humanize}: #{self.errores[k]}\"\n end\n end.join(\"<br/>\")\n end",
"def error_msg\n return nil if result\n\n bad_emails = email_addresses.reject { |email| regex.match(email) }\n\n \"#{bad_emails.count == 1 ? 'Email does' : 'Emails do'} not meet criteria: #{bad_emails.join(', ')}\"\n end",
"def error_message(flag, value, valid)\n classes = valid.compact.map do\n s = _1.to_s\n s = s.downcase if s =~ /\\b(Array|Float|Hash|Integer|String|Symbol)\\b/\n s\n end.join('/')\n \"expected :#{flag} to be #{classes}, not #{value.inspect}\"\n end",
"def compare_error_arrays(file_name, array_a, array_b)\n err_strs = []\n array_a.each do |a|\n found = false\n array_b.each do |b|\n found = true if a[0].to_i == b[0].to_i && a[1] == b[1]\n err_strs << \"errorcode match, but not error name: #{estr(a)} (b is #{estr(b)})\" if !found and a[0].to_i == b[0].to_i\n err_strs << \"error name match, but not errorcode: #{estr(a)} (b is #{estr(b)})\" if !found and a[1] == b[1]\n end\n err_strs << \"unmatched: #{estr(a)}\" unless found\n end\n puts \"#{err_strs.size} errorcode match errors/warnings in #{file_name}\" if err_strs.size != 0\n err_strs.each do |str|\n puts \" #{str}\"\n end\nend",
"def exception\n case word\n when 'y' then ['ˈə'] * 2\n when 'yr' then ['ˈər'] * 2\n when 'til' then ['ˈtɪl'] * 2\n else nil\n end\n end",
"def errors_for_params\n errors.collect{ |error| \"{code:#{error.code}, message:'#{CGI.escape error.message}'}\" }.join(\", \")\n end",
"def extract_uni_err(mis)\n run_cmd(\n \"samtools view -H #{@names.get('mapped_uniqsort')}\" \\\n \"> #{@names.get('mapped_uni', mis)}\"\n )\n run_cmd(\n \"samtools view -h #{@names.get('mapped_uniqsort')} \" \\\n \"| grep -E '([nN]M:i:#{mis})|(^@)' \" \\\n '| samtools view -S - ' \\\n \">> #{@names.get('mapped_uni', mis)}\"\n )\n end",
"def field_validation_errors\n errors = field_validation_error_elements.map { |e| e.text.downcase }.reject { |e| e.empty? }\n exclude = \"Please fill the required fields.\"\n\n if errors.include?(exclude)\n errors.delete(exclude)\n end\n\n errors\n end",
"def errmsg(str, prefix='** ')\n if str.is_a?(Array)\n str.each{|s| errmsg(s)}\n else\n str.split(\"\\n\").each do |s|\n msg(\"%s%s\" % [prefix, s])\n end\n end\n end",
"def errors\n @raw_response.parsed_response&.dig(\"errorList\", \"error\") || []\n end",
"def find_missing_letter(arr)\n alphabets = (arr[0]..arr[-1]).to_a # [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\n \n (alphabets - arr)[0] # \"e\"\nend",
"def test()\n # All errors\n errors = []\n # Return all the errors\n return errors\n end",
"def get_invalids\n\t\treturn @invalids\n\tend",
"def error\n %i[error fatal]\n end",
"def get_exceptions\n\t\tif @exceptions1 == nil\n\t\t\tfilename = \"../../../tex/generic/hyph-utf8/patterns/tex/hyph-#{@code}.tex\";\n\t\t\tlines = IO.readlines(filename, '.').join(\"\")\n\t\t\texceptions = lines.gsub(/%.*/,'');\n\t\t\tif (exceptions.index('\\hyphenation') != nil)\n\t\t\t\t@exceptions1 = exceptions.gsub(/.*\\\\hyphenation\\s*\\{(.*?)\\}.*/m,'\\1').\n\t\t\t\t\tgsub(/\\s+/m,\"\\n\").\n\t\t\t\t\tgsub(/^\\s*/m,'').\n\t\t\t\t\tgsub(/\\s*$/m,'').\n\t\t\t\t\tsplit(\"\\n\")\n\t\t\telse\n\t\t\t\t@exceptions1 = \"\"\n\t\t\tend\n\t\tend\n\n\t\treturn @exceptions1\n\tend",
"def lookup_all_error\n\n#print \"lae(): \"; Raabro.pp(self, colors: true)\n @children.each { |c| return [ c, nil ] if c.result == 0 }\n @children.reverse.each { |c| es = c.lookup_all_error; return es if es }\n nil\n end",
"def error_messages\n @error_messages ||= begin\n data[:errors] ? data[:errors] : [data]\n end\n end",
"def print_failures(arr)\n if arr.length > 0\n puts \"Failures:\"\n end\n\n arr.each do |bad|\n puts \"\\t#{bad}\"\n end\n end",
"def list_errors\n error_messages = []\n @models.each do |m|\n if !m[:model].valid?\n m[:model].errors.each do |e|\n error_messages << \"#{e.to_s.titlecase} #{m[:model].errors[e][0]} - #{m[:meta][:sheet]}, row #{m[:meta][:row] or 'N/A'}\"\n end\n end\n end\n error_messages\n end",
"def errors\n e = []\n e << 'EndSeqNo must either be 0 (inifinity) or be >= BeginSeqNo' unless end_seq_no_valid?\n [super, e].flatten\n end"
] |
[
"0.6885124",
"0.68481314",
"0.65918285",
"0.6453857",
"0.639925",
"0.6332116",
"0.6296849",
"0.629186",
"0.6241251",
"0.6221037",
"0.61755127",
"0.6170697",
"0.6170697",
"0.6121758",
"0.6120652",
"0.61092466",
"0.60883766",
"0.60883766",
"0.60802764",
"0.6075781",
"0.6071082",
"0.6070128",
"0.6070128",
"0.60527915",
"0.60490817",
"0.600934",
"0.5994514",
"0.5984307",
"0.5979314",
"0.597331",
"0.59460825",
"0.5938539",
"0.59307003",
"0.5929637",
"0.5928731",
"0.59077793",
"0.589828",
"0.589638",
"0.58888125",
"0.5883254",
"0.58818674",
"0.5877034",
"0.5870181",
"0.58684784",
"0.5867136",
"0.5867033",
"0.58614683",
"0.58614683",
"0.58408916",
"0.5836857",
"0.5829184",
"0.5817996",
"0.58092993",
"0.5781957",
"0.57802415",
"0.57731736",
"0.5767832",
"0.5767587",
"0.57616025",
"0.5756855",
"0.5746391",
"0.57423496",
"0.5726064",
"0.5718219",
"0.5716005",
"0.57097155",
"0.57023805",
"0.5697501",
"0.56909287",
"0.5689481",
"0.56766087",
"0.56766087",
"0.5671872",
"0.5667714",
"0.56548786",
"0.5645515",
"0.5643922",
"0.5641902",
"0.56414056",
"0.56239974",
"0.5619279",
"0.5615103",
"0.5610345",
"0.5605224",
"0.55983883",
"0.55921066",
"0.55871147",
"0.55862665",
"0.5580234",
"0.5578564",
"0.55699706",
"0.55657876",
"0.5553101",
"0.5548016",
"0.55419004",
"0.5540513",
"0.5539673",
"0.5538836",
"0.5534574",
"0.5530141"
] |
0.66634756
|
2
|
returns number of errors
|
def errors_made
errors.length
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def error_count\n return @error_count\n end",
"def count\n errors.count\n end",
"def NumErrors\n Builtins.size(@errors)\n end",
"def errors_count\n @error_rows_codes.count\n end",
"def errors_count\n @error_rows_codes.count\n end",
"def errors_count\n @error_rows_codes.count\n end",
"def error_count\n Array(@gapi.insert_errors).count\n end",
"def error_count\n peek(\"#{testbench_top}.debug.errors\").to_i\n end",
"def error_count\n peek('origen.debug.errors').to_i\n end",
"def error_count\n @@state[@server] ? @@state[@server][:count] : 0\n end",
"def errored\n @errored ||= count('errored')\n end",
"def errorcount\r\n\t\t\t`#{BITS::BITSADMIN} /geterrorcount {#{@id}}`\r\n\t\tend",
"def size\n @errors.size\n end",
"def error_device_count\n return @error_device_count\n end",
"def error_number; end",
"def failure_count\n @failures.size\n end",
"def count_failing\n return self.failing_tests.size\n end",
"def size\n @errors.values.inject(0) { |error_count, attribute| error_count + attribute.size }\n end",
"def size\n @errors.values.inject(0) { |error_count, attribute| error_count + attribute.size }\n end",
"def size\n @errors.values.inject(0) { |error_count, attribute| error_count + attribute.size }\n end",
"def count_errors(exec_obj)\n num_errors = 0\n re = Regexp.new '^ERROR.*'\n exec_obj.stdout.split(\"\\n\").each do |line|\n $log.debug line\n\n next unless line.match(re)\n\n $log.debug \"Matching error output: #{line}\"\n\n num_errors += 1\n end\n num_errors\n end",
"def error_count=(value)\n @error_count = value\n end",
"def errors_allowed\n TOTAL_ERRORS_ALLOWED - errors_made\n end",
"def failed_count\n return @failed_count\n end",
"def errnum\r\n self.class.errnum\r\n end",
"def errors?\n @error_count > 0\n end",
"def error\n 1/0\n end",
"def insert_count\n @rows.count - error_count\n end",
"def errors?\n @statistics[:error] != 0\n end",
"def percent_errors_failures; end",
"def percent_errors_failures; end",
"def failed\n total - successful\n end",
"def failed?\n errors.count > 0\n end",
"def error_count(queue)\n collection.find(conditions(queue).merge({ :error => { '$ne' => nil } })).count\n end",
"def results_errno()\n r = attr_get(\"status\")\n if(r.eql?(\"passed\"))\n 0\n end\n r = attr_get(\"errno\")\n unless r\n r = -1\n end\n r\n end",
"def count_errors files\n ActiveRecord::Base.connection_pool.with_connection do \n @repo.code_reviews.each do |review|\n if files.has_key?(review.file_path)\n files[review.file_path]['total_errors'] += 1\n error_lines = (review.line_end - review.line_begin) + 1\n files[review.file_path]['lines_with_error'] += error_lines\n review.code_category.each do |category|\n files[review.file_path]['categories'][category.name]['total_errors'] += 1\n files[review.file_path]['categories'][category.name]['lines_with_error'] += error_lines\n end\n end\n end\n end\n return files\n end",
"def failed_users_count\n return @failed_users_count\n end",
"def error_count(queue)\n conditions = {:error.not => nil}\n conditions[:record_class_name] = queue.class_names unless queue.class_names.empty?\n count(conditions)\n end",
"def errors\n @runner.errors\n end",
"def number_returned; 0; end",
"def get_error_count(user_id)\n error_counts_lock.synchronize do\n self.error_counts[user_id] ||= 0\n end\n end",
"def send_errors(m, errors, cmd)\n # ignore warnings and rake output lines\n errors.reject!{|e| non_error_line?(e) }\n size = errors.size\n\n if size > 0\n gist_url = paste_text(errors.join, cmd)\n m.reply \"Got #{size} errors during '#{cmd}'. See: #{gist_url}\"\n end\n\n return size\n end",
"def fail\n @counts.fails += 1\n puts_failure_data(header: FAIL_HEADER)\n end",
"def errors_found?\n errors.size > 0\n end",
"def errors\n @error.fetch('errors', [])\n end",
"def failure!\n @count += 1\n end",
"def error_threshold; end",
"def errors\n @errors\n end",
"def errors\n @errors\n end",
"def errors\n @errors\n end",
"def code\n @errorcode\n end",
"def count_failing\n return self.failing_products.size\n end",
"def errors; end",
"def errors; end",
"def errors; end",
"def errors; end",
"def errors; end",
"def errors; end",
"def errors; end",
"def errors; end",
"def errors; end",
"def number_of_success\n\t\treturn number_of_attempts_with_status(success: true)\n\tend",
"def check_count\n if FantasyPoint.count > 0\n errors[:base] << 'there are too many FantasyPoint records'\n end\n end",
"def errors\n @test_results.map { |tuple| (tuple[2] - tuple[3]).abs }\n end",
"def percent_errors_failures\n ((errors + failures) / count.to_f * 100).to_i\n end",
"def error_device_count=(value)\n @error_device_count = value\n end",
"def success_count\n examples_total - examples_pending - examples_failed\n end",
"def error_count(queue)\n conditions = [\"#{connection.quote_column_name('error')} IS NOT NULL\"]\n unless queue.class_names.empty?\n conditions.first << \" AND #{connection.quote_column_name('record_class_name')} IN (?)\"\n conditions << queue.class_names\n end\n count(:conditions => conditions)\n end",
"def errors\n validate_or_get_results :errors\n end",
"def check_for_errors\n if !valid\n errors = {}\n\n DIGIT_DATA.each do |valid_digit_index,valid_digit_data|\n errors[valid_digit_index] = count_comparison_errors(valid_digit_data['string'])\n end\n\n # no single char error can result in two possible digits so we either find\n # one match with a single error or no matches\n errors.each do |valid_integer,error_count|\n set_salvagable(valid_integer) if error_count === 1\n end\n end\n end",
"def errors\n @errors ||= failed.select { |rule| rule.severity == \"Severe\" }\n end",
"def errors\n run_validation\n @errors\n end",
"def has_errors?\n return @exitcode == 2 || @exitcode == 1\n end",
"def calculate_iteration_error\n (@sum_error / @patterns.count) * 0.5\n end",
"def tasks_failed_count\n count do |task|\n task.failed?\n end\n end",
"def errno\n @last_error ? @last_error.errno : 0\n end",
"def error?(name = nil, type = nil)\n return 0 < errors(name, type).size\n end",
"def errors?\n @errors.size > 0\n end",
"def checkError(n)\n\t\tif n > @error\n\t\t\treturn true\n\t\telse\n\t\t\treturn false\n\t\tend\n\tend",
"def get_error_codes\n assert_not_nil @rdigg.info.get_error_codes\n end",
"def get_rerun_count(test_objects)\n count = 0\n test_objects.each do |test|\n if test.status == 'failed'\n count +=1\n end\n end\n count\n end",
"def errors\n @errors ||= []\n end",
"def errors\n @errors ||= []\n end",
"def check_for_errors\n return unless @chunks.any? { |chunk| chunk.first[0] == :error }\n errors = @chunks.find_all { |chunk| chunk[0] == :error }\n $stderr.puts \"WARNING: found the following errors: #{errors.map(&last).inspect}\"\n end",
"def errors?\n @errors.size > 0\n end",
"def error_check\n if @number_of_players.to_i * @number_of_cards.to_i > Deck::CARD_COUNT\n error_message\n input_players\n else\n get_player_names\n end\nend",
"def errors\n @errors ||= []\n end",
"def failure_count(headers)\n if headers.nil? || headers['count'].nil?\n 0\n else\n headers['count']\n end\n end",
"def errors\n @errors\n end",
"def errors\n @errors\n end",
"def errors\n @errors\n end",
"def max_failed_count\n MAX_FAILED_COUNT\n end",
"def errors\n raise \"This audio file has not been checked for errors yet.\" unless checked_for_errors?\n\n @errors\n end",
"def errors\n @errors ||= []\n end",
"def errors\n @errors ||= []\n end",
"def error?\n resources.error.count > 0\n end",
"def error?\n resources.error.count > 0\n end",
"def geterrorcode()\r\n return getvalue(@@ERROR_CODE)\r\n end",
"def count_comparison_errors(valid_to_compare_to)\n errors = 0\n\n valid_to_compare_to.split('').each_with_index do |char,index|\n errors += 1 unless char == string.split('')[index]\n end\n\n errors\n end",
"def successful\n count(&:ok?)\n end"
] |
[
"0.8684961",
"0.836196",
"0.83341783",
"0.82288563",
"0.82288563",
"0.82288563",
"0.80139995",
"0.8004782",
"0.79705036",
"0.7631777",
"0.7490927",
"0.74772096",
"0.74536073",
"0.74502033",
"0.74251884",
"0.7306997",
"0.7266018",
"0.724427",
"0.724427",
"0.7221631",
"0.7195949",
"0.71709204",
"0.71589416",
"0.7136133",
"0.7020169",
"0.70070875",
"0.68867576",
"0.68174374",
"0.68160903",
"0.6788672",
"0.6788672",
"0.66908836",
"0.6676602",
"0.6636885",
"0.66080445",
"0.65891075",
"0.6538641",
"0.65247554",
"0.6476668",
"0.645412",
"0.6451189",
"0.64467114",
"0.64182603",
"0.63875735",
"0.63804877",
"0.63720536",
"0.63610154",
"0.63562953",
"0.63562953",
"0.63562953",
"0.6348911",
"0.6344134",
"0.632927",
"0.632927",
"0.632927",
"0.632927",
"0.632927",
"0.632927",
"0.632927",
"0.632927",
"0.632927",
"0.63242954",
"0.631827",
"0.63025963",
"0.62815124",
"0.6271314",
"0.62702936",
"0.6268704",
"0.6254435",
"0.6252958",
"0.62520814",
"0.6248284",
"0.62474364",
"0.62376696",
"0.6235747",
"0.6211298",
"0.62076753",
"0.6202622",
"0.6195631",
"0.6182781",
"0.6180855",
"0.6167439",
"0.6167439",
"0.615655",
"0.61550456",
"0.614073",
"0.6138093",
"0.6132876",
"0.6128074",
"0.6128074",
"0.6128074",
"0.6126238",
"0.6124497",
"0.61188024",
"0.61188024",
"0.6115504",
"0.6115504",
"0.61098385",
"0.61039215",
"0.61032873"
] |
0.8205057
|
6
|
returns the number of errors lest
|
def errors_allowed
TOTAL_ERRORS_ALLOWED - errors_made
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def error_count\n return @error_count\n end",
"def error_count\n peek(\"#{testbench_top}.debug.errors\").to_i\n end",
"def NumErrors\n Builtins.size(@errors)\n end",
"def errors_made\n errors.length\n end",
"def error_count\n peek('origen.debug.errors').to_i\n end",
"def errored\n @errored ||= count('errored')\n end",
"def errors_count\n @error_rows_codes.count\n end",
"def errors_count\n @error_rows_codes.count\n end",
"def errors_count\n @error_rows_codes.count\n end",
"def percent_errors_failures; end",
"def percent_errors_failures; end",
"def count\n errors.count\n end",
"def count_failing\n return self.failing_tests.size\n end",
"def error_count\n @@state[@server] ? @@state[@server][:count] : 0\n end",
"def error_count\n Array(@gapi.insert_errors).count\n end",
"def failure_count\n @failures.size\n end",
"def error_device_count\n return @error_device_count\n end",
"def error_threshold; end",
"def error_number; end",
"def failed_count\n return @failed_count\n end",
"def error\n 1/0\n end",
"def failed\n total - successful\n end",
"def size\n @errors.values.inject(0) { |error_count, attribute| error_count + attribute.size }\n end",
"def size\n @errors.values.inject(0) { |error_count, attribute| error_count + attribute.size }\n end",
"def size\n @errors.values.inject(0) { |error_count, attribute| error_count + attribute.size }\n end",
"def errorcount\r\n\t\t\t`#{BITS::BITSADMIN} /geterrorcount {#{@id}}`\r\n\t\tend",
"def errors?\n @statistics[:error] != 0\n end",
"def size\n @errors.size\n end",
"def percent_errors_failures\n ((errors + failures) / count.to_f * 100).to_i\n end",
"def calculate_iteration_error\n (@sum_error / @patterns.count) * 0.5\n end",
"def success_count\n examples_total - examples_pending - examples_failed\n end",
"def invalid_max_staleness?\n @test['error']\n end",
"def scanning_error_rate()\n\t\t@nbval.flatten.select do |v| \n\t\t\tnot is_value_compatible_with_at_least_one_rule?(v)\n\t\tend.reduce(:+) || 0\n\tend",
"def errors\n @test_results.map { |tuple| (tuple[2] - tuple[3]).abs }\n end",
"def error_count=(value)\n @error_count = value\n end",
"def errnum\r\n self.class.errnum\r\n end",
"def count_errors(exec_obj)\n num_errors = 0\n re = Regexp.new '^ERROR.*'\n exec_obj.stdout.split(\"\\n\").each do |line|\n $log.debug line\n\n next unless line.match(re)\n\n $log.debug \"Matching error output: #{line}\"\n\n num_errors += 1\n end\n num_errors\n end",
"def results_errno()\n r = attr_get(\"status\")\n if(r.eql?(\"passed\"))\n 0\n end\n r = attr_get(\"errno\")\n unless r\n r = -1\n end\n r\n end",
"def errors?\n @error_count > 0\n end",
"def error_threshold\n @error_threshold ||= 100\n end",
"def error\n 1.0 - accuracy()\n end",
"def max_failed_count\n MAX_FAILED_COUNT\n end",
"def failure_index\n max_terminal_failure_index\n end",
"def count_comparison_errors(valid_to_compare_to)\n errors = 0\n\n valid_to_compare_to.split('').each_with_index do |char,index|\n errors += 1 unless char == string.split('')[index]\n end\n\n errors\n end",
"def insert_count\n @rows.count - error_count\n end",
"def number_returned; 0; end",
"def percent_passes\n 100 - percent_skips - percent_errors_failures\n end",
"def errors\n @errors ||= failed.select { |rule| rule.severity == \"Severe\" }\n end",
"def failed_users_count\n return @failed_users_count\n end",
"def get_error_count(user_id)\n error_counts_lock.synchronize do\n self.error_counts[user_id] ||= 0\n end\n end",
"def checkError(n)\n\t\tif n > @error\n\t\t\treturn true\n\t\telse\n\t\t\treturn false\n\t\tend\n\tend",
"def num_successful_attacks\n return @num_success_attacks\n end",
"def error_check(resolved_facts)\n status = 0\n if Options[:strict]\n missing_names = resolved_facts.select { |fact| fact.type == :nil }.map(&:user_query)\n\n if missing_names.count.positive?\n status = 1\n log_errors(missing_names)\n end\n end\n\n status\n end",
"def processor_core_count_check_failed_percentage\n return @processor_core_count_check_failed_percentage\n end",
"def success_threshold; end",
"def number_of_success\n\t\treturn number_of_attempts_with_status(success: true)\n\tend",
"def tasks_failed_count\n inject(0) do |sum, node|\n sum + node.graph.tasks_failed_count\n end\n end",
"def tasks_failed_count\n inject(0) do |sum, node|\n sum + node.graph.tasks_failed_count\n end\n end",
"def max_errors\n OrigenSim.max_errors || config[:max_errors] || 100\n end",
"def passes\n count - failures - errors - skips\n end",
"def stddev\n return 0.0 if errors.size < 2\n errors.stdev.to_f.round(1)\n end",
"def check_for_errors\n if !valid\n errors = {}\n\n DIGIT_DATA.each do |valid_digit_index,valid_digit_data|\n errors[valid_digit_index] = count_comparison_errors(valid_digit_data['string'])\n end\n\n # no single char error can result in two possible digits so we either find\n # one match with a single error or no matches\n errors.each do |valid_integer,error_count|\n set_salvagable(valid_integer) if error_count === 1\n end\n end\n end",
"def percent_failed\n if recent_calls.count == 0\n 0\n else\n (recent_calls.select(&:failed?).count / recent_calls.count.to_f)\n end\n end",
"def NumWarnings\n Builtins.size(@warnings)\n end",
"def rms\n return 0.0 if errors.size < 2\n Math.sqrt(errors.inject(0) { |sum, error| sum + error * error }.to_f / errors.size.to_f ).round(1)\n end",
"def count_failing\n return self.failing_products.size\n end",
"def num_successful_attacks\n return @successful_attacks\n end",
"def check_for_errors\n return unless @chunks.any? { |chunk| chunk.first[0] == :error }\n errors = @chunks.find_all { |chunk| chunk[0] == :error }\n $stderr.puts \"WARNING: found the following errors: #{errors.map(&last).inspect}\"\n end",
"def failed?\n errors.count > 0\n end",
"def rms()\n r = error_list.inject{|s,n| s + n ** 2}/error_list.size\n return Math.sqrt(r)\n end",
"def size\n @errors.size + @children.each_value.reduce(0) do |total, child|\n total + child.size\n end\n end",
"def count_passing\n return self.passing_tests.size\n end",
"def processor_family_check_failed_percentage\n return @processor_family_check_failed_percentage\n end",
"def fail\n @counts.fails += 1\n puts_failure_data(header: FAIL_HEADER)\n end",
"def check_count\n if FantasyPoint.count > 0\n errors[:base] << 'there are too many FantasyPoint records'\n end\n end",
"def ram_check_failed_percentage\n return @ram_check_failed_percentage\n end",
"def os_check_failed_percentage\n return @os_check_failed_percentage\n end",
"def ballot_failed\n incr_stat :failed_analysis\n end",
"def error_check\n if @number_of_players.to_i * @number_of_cards.to_i > Deck::CARD_COUNT\n error_message\n input_players\n else\n get_player_names\n end\nend",
"def tasks_failed_count\n count do |task|\n task.failed?\n end\n end",
"def get_errors\n return nil unless has_errors?\n return filter_low_priority_errors(@stderr)\n end",
"def errors\n @runner.errors\n end",
"def error_count(queue)\n collection.find(conditions(queue).merge({ :error => { '$ne' => nil } })).count\n end",
"def nb_problems\n return @pb_list.length\n end",
"def failed_runs\n return @failed_runs\n end",
"def losses()\n\t\tself.as_regular_contestants.select{|c| c.loss()}.size()\n\tend",
"def failure!\n @count += 1\n end",
"def check_error_no\n @error_no = 0\n if @err_bit\n if @data != nil && @data.size > 0\n @error_no = (0x0 - 0xFFFFFFFF + (BioPacket.swap_dword(@data.first) - 1)).to_i\n @error_desc = BioPacket.format_err_desc(@error_no)\n $test_logger.log(\"Error#{(\" in ACK\" if @ack_bit)}: #{@error_no} #{@error_desc}\")\n else \n $test_logger.log(\"Error bit is set but error code not found!!\")\n end\n end\n end",
"def count_incomplete\n return self.incomplete_tests.size\n end",
"def missingmodulecount\n $number_of_missing_modules = @missingmodules.count().to_s\nend",
"def get_rerun_count(test_objects)\n count = 0\n test_objects.each do |test|\n if test.status == 'failed'\n count +=1\n end\n end\n count\n end",
"def errors\n @error.fetch('errors', [])\n end",
"def check_summary_for_errors(summary)\n if summary.has_key?(\"resources\")\n resources = summary[\"resources\"]\n\n failed_to_restart = resources[\"failed_to_restart\"]\n if failed_to_restart.nil?\n @errors << \"failed to restart count not in summary.\"\n elsif failed_to_restart > 0\n @errors << \"#{failed_to_restart} resources failed to restart.\"\n end\n\n failed = resources[\"failed\"]\n if failed.nil?\n @errors << \"failed resources count not in summary.\"\n elsif failed > 0\n @errors << \"#{failed} failed resources.\"\n end\n\n total = resources[\"total\"]\n # this happens when execution expired sometimes. \n if total.nil?\n @errors << \"total resources count not in summary.\"\n elsif total == 0\n @errors << \"there were zero total resources in the run summary, which suggests something went wrong.\"\n end \n else\n @errors << \"no resources information.\"\n end\n\n # failure events are usually failed resourced, but sometimes aren't.\n # we record these if there aren't already failed resources.\n if summary.has_key?(\"events\")\n failure = summary[\"events\"][\"failure\"]\n if failure.nil?\n @errors << \"no failure count in summary events.\"\n elsif failure > 0 and failed == 0\n @errors << \"#{failure} failure events.\"\n end\n else\n @errors << \"no events in summary.\"\n end\n\n @errors.length\n end",
"def rms\n\t\tsum = 0\n\t\tpred_list.each do |pred|\n\t\t\tsum += pred[:error] ** 2\n\t\tend\n\t\treturn Math.sqrt(sum / size)\n\tend",
"def error_level\n @error_level\n end",
"def count_errors files\n ActiveRecord::Base.connection_pool.with_connection do \n @repo.code_reviews.each do |review|\n if files.has_key?(review.file_path)\n files[review.file_path]['total_errors'] += 1\n error_lines = (review.line_end - review.line_begin) + 1\n files[review.file_path]['lines_with_error'] += error_lines\n review.code_category.each do |category|\n files[review.file_path]['categories'][category.name]['total_errors'] += 1\n files[review.file_path]['categories'][category.name]['lines_with_error'] += error_lines\n end\n end\n end\n end\n return files\n end",
"def total_throws\n puts \"Total throws:: #{@counter}\"\n end",
"def errno\n @last_error ? @last_error.errno : 0\n end",
"def display_error\n counter = 0\n file_data_arr.each_with_index do |file_data, index|\n data_index = index + 1\n counter += 1 unless missing_ending_semicolon?(file_data, data_index)\n counter += 1 unless space_before_semicolon?(file_data, data_index)\n counter += 1 unless indentation_error?(file_data, data_index)\n counter += 1 unless space_after_colon?(file_data, data_index)\n counter += 1 unless space_before_colon?(file_data, data_index)\n counter += 1 unless trailing_white_space?(file_data, data_index)\n end\n puts 'No Errors Found'.green if counter.zero?\n end",
"def rms\n\t\tsum = (@error_list.inject { |sum, x| sum + x } ** 2) / @error_list.size\n\t\tMath.sqrt(sum)\n\tend"
] |
[
"0.8013918",
"0.7972357",
"0.77702326",
"0.76749706",
"0.7481861",
"0.7373196",
"0.7317007",
"0.7317007",
"0.7317007",
"0.7215685",
"0.7215685",
"0.7204756",
"0.71702707",
"0.7082253",
"0.7001549",
"0.69353104",
"0.6934013",
"0.69311494",
"0.68705237",
"0.6817181",
"0.6742872",
"0.6704815",
"0.6676417",
"0.6676417",
"0.66660285",
"0.66452545",
"0.6644137",
"0.6631766",
"0.6561778",
"0.6502184",
"0.6494399",
"0.64863837",
"0.6485543",
"0.6482191",
"0.6472679",
"0.6437932",
"0.6422574",
"0.63880366",
"0.6379311",
"0.6324442",
"0.63073367",
"0.6292737",
"0.6272501",
"0.6256237",
"0.62489915",
"0.62318903",
"0.6229039",
"0.62194556",
"0.6204971",
"0.61814237",
"0.6170839",
"0.6159819",
"0.61305535",
"0.61174536",
"0.6087823",
"0.60868245",
"0.6068889",
"0.6068889",
"0.6064462",
"0.60630375",
"0.6047771",
"0.6044746",
"0.6036536",
"0.6032258",
"0.6019721",
"0.60102683",
"0.6008913",
"0.5986489",
"0.5974019",
"0.593794",
"0.59347725",
"0.591026",
"0.58973914",
"0.5877898",
"0.5877374",
"0.58721924",
"0.58708906",
"0.5857982",
"0.5856636",
"0.5849032",
"0.5846134",
"0.5845115",
"0.58442974",
"0.58429563",
"0.5842472",
"0.58396286",
"0.5835575",
"0.58225846",
"0.582245",
"0.58189887",
"0.58152544",
"0.58150196",
"0.5807159",
"0.58023536",
"0.57941675",
"0.5778449",
"0.5777819",
"0.5768368",
"0.576651",
"0.57641417"
] |
0.7257373
|
9
|
returns the array of letters, which are left to guess
|
def letters_to_guess
@letters.map do |letter|
if @user_guesses.include?(normalize_letter(letter))
letter
else
nil
end
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def guess_letters\n guess_array = []\n @current_word.each do\n guess_array << \"_\"\n end\n return guess_array\n end",
"def guessed_letters()\n guessed = $bucket.join(\" \") # return a string of guessed letters\nend",
"def check_guess(letter)\n\t\tret = []\n\t\tif(@secret_word.include?(letter))\n\t\t\t@secret_word.split(\"\").each_with_index do |let, i|\n\t\t\t\tif(let == letter)\n\t\t\t\t\tret << i\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\tret\n\tend",
"def guess\n\t\tcollect_words_of_length\n\t\tputs \"Already guessed letters by computer: #{@guessed_letters}\"\n\t\t@guessing_letter = nil\n\t\twhile @guessing_letter == nil || invalid?(@guessing_letter)\n\t\t\t@guessing_letter = guessing_letter\n\t\tend\n\t\t@guessed_letters << @guessing_letter\n\t\t@guessing_letter\n\tend",
"def respond_to_letter_guess(letter)\n indices_matching_letter = []\n i = 0\n while i < @secret_word.length\n if @secret_word[i] == letter\n indices_matching_letter << i\n end\n\n i += 1\n end\n\n indices_matching_letter\n end",
"def guess_letter\n @unused_letters.pop\n end",
"def guessed_wrong_letter()\n if $hidden_word_arr.exclude?($input)\n $guessed.append($input)\n end\n end",
"def missing_letters\n missing = Array.new\n ('a'..'z').each {|l| missing << l if @hist[l] == 0}\n missing\n end",
"def check_letters(letter)\n progress(letter)\n count = 0\n @word_to_guess.each do |char|\n if char == letter\n @hidden_word[count] = letter\n else\n @hidden_word \n end\n count +=1 \n end\n puts @hidden_word\n @hidden_word\n end",
"def make_guess\n\t\tbegin\n\t\t\thighest_letter_left = freq_hash\n\t\t\t\t.sort_by{|k, v| v}\n\t\t\t\t.reverse\n\t\t\t\t.map{|char, freq| char}\n\t\t\t\t.detect{|char| !@guessed_letters.include?(char)}\n\n\t\t\traise \"Aw, damn! Got nothin' left. Let's start a new game.\" unless highest_letter_left\n\t\trescue Exception => e\n\t\t\tputs e.message\n\t\t\texit\n\t\telse\n\t\t\t@guessed_letters << highest_letter_left\n\t\t\thighest_letter_left\n\t\tend\n\tend",
"def available_letters\n ltrs = []\n letter_set.letter_amount_points.each do |k, v|\n ltrs << k.to_s unless k == '?'\n end\n return ltrs.sort\n end",
"def letters\n the_letters = []\n letter_regex = /[a-z]/i\n chars.each do |character|\n the_letters << character if character.match(letter_regex)\n end\n the_letters.join\n end",
"def guess_letters(letter)\n @guesses << letter\n @guesses\nend",
"def wordArray(guessword)\n word_array = []\n\n guessword.length.times do |letter|\n word_array << guessword[letter]\n end\n return word_array\nend",
"def check_for_correct_letters(user_guess)\n @correct_letters << user_guess.count do |guess_char|\n @solution.include?(guess_char)\n end\n end",
"def alphabet_array\n ('A'..'Z').to_a\n end",
"def initialize\n @wrong_letters = []\n @wrong_guesses = 0\n end",
"def get_letters(game)\n game.letters.split(\"\").reject{|letter| game.word.upcase.include?(letter)}.join(\" \")\nend",
"def match_letters #handle_guess\n\t\tindexes_matched = @word_array.each_index.select { |i| @word_array[i] == @guess}\n\n\t\tfor x in indexes_matched do\n\t\t\t@result_array[x] = guess\n\t\tend\n\n\t\tputs @result_array\n\tend",
"def match_letters #handle_guess\n\t\tindexes_matched = @word_array.each_index.select { |i| @word_array[i] == @guess}\n\n\t\tfor x in indexes_matched do\n\t\t\t@result_array[x] = guess\n\t\tend\n\n\t\tputs @result_array\n\tend",
"def guess(letters)\n raise ArgumentError if letters == \"\"\n raise ArgumentError if letters !~ %r{\\w}\n letters.downcase!\n if @word.include?(letters) \n !@guesses.include?(letters) ? @guesses << letters : false\n\n else\n @wrong_guesses.include?(letters) ? false : wrong_guesses << letters \n end\n end",
"def match_letters \n\t\tindexes_matched = @word_array.each_index.select { |i| @word_array[i] == @guess}\n\n\t\tfor x in indexes_matched do\n\t\t\t@result_array[x] = @guess\n\t\tend\n\tend",
"def letters\n @letters.join(\"\")\n end",
"def evaluate_players_letter()\n letter= @player1.give_letter()\n if @hiddenword1.determine_if_correct_letter_given(letter)\n p @hiddenword1.obscured_word\n @guessed_letters.push(letter)\n else\n @player1.lives-=1\n p \"Please try again\"\n p @guessed_letters\n p @hiddenword1.obscured_word\n end\n end",
"def guess(letter)\r\n\t\t@guessed << letter.downcase\r\n\t\t@word[0].each_index do |i| #Iterate through indexes instead of values\r\n\t\t\tif @word.dig(0,i) == letter #since @word is an array inside an array, dig helps us look in word ([0]) each index for the letter.\r\n\t\t\t\t@hidden_word[i] = letter #if found, substitute \"_\" for the letter guessed in the same index for @hidden_word\r\n\t\t\tend\r\n\t\tend\r\n\t\tp @hidden_word #give feedback of results\r\n\tend",
"def letter_list(equation)\n equation.gsub(/[^A-Z]/, '').chars.uniq\n end",
"def guessed?\n \t(word.split('') - selected_letters).empty?\n\tend",
"def check_guess(letter)\n @indices = gameboard[0].each_index.select { |i| gameboard[0][i].downcase == letter }\n if @indices.empty?\n incorrect_guesses << letter\n puts 'Sorry, the secret word does not contain that letter'\n else\n @indices.each do |index|\n gameboard[1][index] = gameboard[0][index] # letter\n end\n puts 'Good guess!'\n end\n end",
"def guessable_letters(animal)\n alphabet = *('a'..'z')\n letter_array = animal.name.downcase.split('')\n\n while letter_array.length < 12\n letter_array.push(alphabet.sample)\n end\n return letter_array.shuffle\n end",
"def check_letter(guess)\n if @word.include? guess\n puts \"You chose wisely!\"\n #find which position(s) the guess is in the word array\n correct_index_arr = @word.each_index.select { |i| @word[i] == guess }\n # rebuild @game_status with the correct letter guessed into that position of the word\n correct_index_arr.each do |index|\n @game_status[index] = guess\n end\n # if they don't make guess and put an empty response\n elsif guess.empty?\n puts \"You didn't make a guess. Try again.\"\n # if the user guesses the same wrong letter again\n elsif @wrong_guesses.include? guess\n puts \"You guessed that before! Try again.\"\n else\n @guesses_remaining -= 1\n puts \"wrong guess, the guesses remaining: #{@guesses_remaining}\"\n @wrong_guesses.push(guess)\n end\n end",
"def getletters(string)\n arr = []\n pos = 0\n i = 0\n x = string.length\n while i < x\n if arr.include?(string[i])\n i += 1\n elsif !arr.include?(string[i])\n arr[pos] = string[i]\n i += 1\n pos += 1\n end\n end\n return arr\nend",
"def check_guess(input)\n @guessed_letters.push(input)\n if @secret_word.match?(input)\n @secret_word.split(//).each_with_index { |char, index| @guessed_word[index] = char if char == input }\n else\n puts 'Incorrect'\n @guesses_left -= 1\n @wrong_letters.push(input)\n end\n end",
"def guess!(letter)\n end",
"def check_guess(guess)\n\t\thits_arr = []\n\t\t@secret.chars.each_index do |idx|\n\t\t\thits_arr << idx if guess == @secret[idx]\n\t\tend\n\t\t\n\t\thits_arr\n\tend",
"def letters\n # the_letters = []\n letter_regex = /[a-z]/i\n # for i in 0..self.length - 1\n # character = self[i]\n # if (character.match(letter_regex))\n # the_letters << character\n # end\n # end\n\n # self.chars.each do |character|\n # if character.match(letter_regex)\n # the_letters << character\n # end\n # end\n # the_letters.join\n\n # self.chars.select { |c| c.match letter_regex }.join\n\n # self.chars.map{ |c| c.match /[a-zA-Z]/ }.join\n\n self.scan(letter_regex).join\n end",
"def letters_before(char)\n (\"a\"...char).to_a\nend",
"def letters\n @letters ||= {\n \"2\" => ['a','b','c'],\n \"3\" => ['d','e','f'],\n \"4\" => ['g','h','i'],\n \"5\" => ['j','k','l'],\n \"6\" => ['m','n','o'],\n \"7\" => ['p','q','r','s'],\n \"8\" => ['t','u','v'],\n \"9\" => ['w','x','y','z']\n }\n end",
"def check_letters(letters)\n @user_guesses = []\n letters.split(/,\\s||,||\"\"/).each do |letter|\n @user_guesses << (['R', 'G', 'B', 'Y', 'O', 'P'].include? (letter))\n end\n !@user_guesses.include? (false)\n end",
"def match_letters(player_guess) \n indexes_matched = @word_array.each_index.select { |i| @word_array[i] == player_guess}\n for x in indexes_matched do\n @results[x] = player_guess\n end\n end",
"def missing_letters(string)\n a_to_z_array = (\"a\"..\"z\").to_a\n a_to_z_array - string.chars\n\nend",
"def letter_index(user_letter)\n letter_indeces =[]\n if user_letter.length > 1\n if user_letter == @word.gsub(/[^0-9A-Za-z]/, '')\n you_win\n letter_indeces = (0...@letters.length).to_a\n end\n else\n @letters.length.times do |i|\n if @letters[i] == user_letter\n letter_indeces << i\n end\n end\n end\n return letter_indeces\n end",
"def guess_letter(a_letter)\n p a_letter.downcase\n @word.split(\"\").each_with_index do |another_letter, index|\n if a_letter == another_letter\n @input_word[index] = a_letter\n puts \"Correct! Here are your guesses so far\"\n p @input_word\n end\n if !@word.include? (a_letter)\n end\n end\n end",
"def good_letter(letter)\n if $bucket.include? letter # check to see if letter has already been guessed and reprompt if so\n $prompt = \"You already guessed that one - TRY AGAIN!\"\n elsif letter[/[a-zA-Z]+/] and letter.length == 1 # check is a single -letter- has been entered\n $bucket.push(letter) # if so, add it to the bucket array\n letter_test(letter) # then pass it to letter_test()\n else # if multiple letters, non-alpha characters or nothing has been entered\n $prompt = \"Enter a single letter - TRY AGAIN!\" # reprompt user to try again\n end\nend",
"def guess\n letters = @possible_letters.collect {|letter| [ score_for(letter),letter ]}\n letter = letters.min {|letter1,letter2| letter1 <=> letter2 }\n letter[1]\n end",
"def player_guess_split\n @player_guess.chars\n end",
"def guess_letters_check\n @user_guess.length != 4 || !check_letters(@user_guess)\n end",
"def find_letters(alphabet)\n selected_letters = ''\n counter = 0\n\n loop do \n break if counter == alphabet.size\n \n current_letter = alphabet[counter]\n selected_letters << current_letter if current_letter == 'g'\n \n counter += 1\n end\n \n selected_letters\nend",
"def check_guess(letter)\n\t\tputs \"Please enter the correct positions where the guess occurs\"\n\t\tmatches = gets.chomp.split(\" \")\n\t\tmatches.map { |match| match.to_i }\n\tend",
"def check_letter(guess_letter)\n @word_array.each_with_index { |letter, index|\n if letter == guess_letter\n @correct_index_list.append(index)\n end\n }\n if @word_array.include? guess_letter\n puts \"Congratulations you guess a letter correctly!\"\n else\n puts \"Sorry! You did not guess a correct letter.\"\n @number_incorrect += 1\n end\n return @correct_index_list\n end",
"def letter_array (name)\n\tname.chars\nend",
"def reveal_matches(letter)\n hits = []\n i = 0\n @secret.split(\"\").each do |c|\n hits << i if c == letter\n i += 1\n end\n hits.each do |i|\n @solution[i] = letter\n end\n return @solution\n end",
"def check_guess(guess)\n # checks human guess, displays discovered, and return if letter found\n letter_found = false\n self.secret_word.split('').each_with_index do |chr, ind|\n if chr == guess\n self.currently_discovered[ind] = chr\n letter_found = true\n end\n end\n p self.currently_discovered\n letter_found\n end",
"def wrong_letter(letter)\r\n \t@chances -= 1\r\n @guesses << letter\r\n end",
"def letters_before(character)\n\t\n\t alphabet_storage = []\n results = []\n \n (\"a\"..\"z\").each do |i|\n \t alphabet_storage << i\n end\n \n starting_position = alphabet_storage.index(character) \n i = 0\n \n until i == starting_position\n results << alphabet_storage[i]\n i += 1\n end\n \n puts \"#{results}\"\nend",
"def guess_array\n @guess_array\n end",
"def determine_missing_letter(arr)\n alpha = ('A'..'z').to_a\n current_index = alpha.index(arr.first)\n arr.each_with_index do |char, index|\n next if index == 0\n if alpha.index(char) != current_index + 1\n return alpha[current_index + 1]\n end\n current_index += 1\n end\nend",
"def failed_attemps\n\t\tselected_letters.select {|letter| !word.include?(letter)}.size\n\tend",
"def check_guessed_letter(word,letter,available_letters)\n\n\tif word.include?(letter)\n\t\treturn 0\n\telsif !available_letters.include?(letter)\n\t\treturn 0\n\telse\n\t\t$missed_letters.push(letter)\n\t\treturn -1\n\tend\nend",
"def get_poss_characters()\n alpha = \"abcdefghijklmnopqrstuvwxyz0123456789\"\n poss = []\n for i in (0..alpha.length-1)\n poss.push(alpha[i])\n end\n return poss\nend",
"def get_letter() \n loop do\n puts \"Please enter a letter.\"\n $input = gets.chomp\n $input = $input.downcase\n if $input.count(\"a-z\") == 0\n puts \"\"\n puts \"Sorry, that isn't a letter!\"\n elsif $input.size > 1\n puts \"\"\n puts \"You entered too many letters!\"\n elsif $guessed.exclude?($input) && $hidden_word_arr.exclude?($input)\n break\n else\n puts \"\"\n puts \"You already guessed that one!\"\n end\n end \n end",
"def game_board(guess_letter)\r\n\t puts \"\"\t \r\n\t result_index_array = (0 ... @secret_word.length).find_all { |i| @secret_word[i,1] == guess_letter }\r\n\t \r\n\t # Change the output to show a successful guess\r\n\t if result_index_array.size == 0\r\n\t @incorrect_letters += guess_letter\r\n\t\t@incorrect_letters += \", \"\r\n\t else \r\n\t result_index_array.each { |index| @correct_letters[2*index] = guess_letter }\r\n end\r\n\t \r\n\t # Update variables and check if the game has been won\r\n\t @turn_count -= 1\r\n\t puts @correct_letters\r\n\t #@incorrect_letters.each {|letter| print \"#{letter}, \"}\r\n\t puts \"\\nIncorrect Guesses: #{@incorrect_letters}\"\r\n\t win_game if @correct_letters.count('_') == 0\r\n\t end_turn\r\n\tend",
"def checkLetter(letter)\n @word.split(\"\").each_with_index do |item, index|\n if item == letter\n @guess[index] = letter\n end\n end\n puts @guess\nend",
"def wrong_letter(letter)\n @chances -= 1\n @guesses << letter\n end",
"def letter_guessed(user_guess)\n\t\tif @guessed_letters.length == 0\n\t\t\t@guessed_letters << user_guess\n\t\telse \n\t\t\tif @guessed_letters.include?(user_guess)\n\t\t\t\tputs \"--You already guessed that letter! Try again!--\"\n\t\t\t\t@guess_count -= 1\n\t\t\telse\n\t\t\t\t@guessed_letters << user_guess\n\t\t\tend\n\t\tend\n\tend",
"def compare_letters\n @secret_array.each do |letter|\n if @guesses[-1] == letter\n return true\n # else\n # return false\n # Again, I could not figure out why this method did not return false if the letter did not match any letter in the secret word array.\n end\n end\nend",
"def find_missing_letter(range)\n missing_letters = []\n user_input = range.split('')\n alphabet = user_input[0].upto(user_input.last).to_a\n\n alphabet.each do |letter|\n missing_letters << letter unless user_input.include? letter\n # missing_letters << letter\n # end\n end\n\n # if missing_letters.empty?\n # return nil\n # else\n # missing_letters.join\n # end\n\n missing_letters.join if missing_letters.empty?\nend",
"def createGuess\n\t\tprint \"Please use lowercase letters a - f: \\n\" \n\t\tprint \"first spot: \" \n\t\tfirst = gets\n\t\tprint \"second spot: \" \n\t\tsecond = gets\n\t\tprint \"third spot: \" \n\t\tthird = gets\n\t\tprint \"fourth spot: \" \n\t\tfourth = gets\n\t\tguessBoard = [first.ord, second.ord, third.ord, fourth.ord]\n\t\tstore(guessBoard)\n\t\treturn [first.ord, second.ord, third.ord, fourth.ord]\n\tend",
"def letter_guess(input,dead_man)\n if @letters_guessed_array.include?(input) || dead_man.wrong_letters.include?(input)\n puts \"You have already guessed this letter!\"\n display(dead_man)\n elsif @correct_word_array.include?(input)\n @letters_guessed_array.each_with_index do |letter, index|\n @letters_guessed_array[index] = input if @correct_word_array[index] == input\n end\n puts \"The letter #{input} is in the word.\"\n if @letters_guessed_array.include?(\"__\")\n display(dead_man)\n else\n win\n end\n else\n puts \"The letter #{input} is not in the word.\"\n dead_man.wrong_letters.push(input)\n dead_man.wrong_guesses += 1\n display(dead_man)\n end\n end",
"def uses_available_letters?(input, letters_in_hand)\n\n input_array = input.upcase.chars\n\n letters_in_hand.each do |letter|\n\n if input_array.include? letter\n index = input_array.index(letter)\n input_array.delete_at(index)\n end\n end\n\n return input_array.length == 0\n\nend",
"def missing_letters(string)\n missing_letters = []\n str = string.downcase\n ('a'..'z').each do |c|\n missing_letters << c if !str.include?(c)\n end\n missing_letters\nend",
"def find_missing_letter(arr)\n alphabets = (arr[0]..arr[-1]).to_a # [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\n \n (alphabets - arr)[0] # \"e\"\nend",
"def check_guess\n @already_guessed.push(@guess)\n if @secret_word.include?(@guess)\n @secret_word.split(\"\").each_with_index do |letter, index|\n if letter == @guess\n @blanks[index] = letter\n end\n end\n else\n @guesses_left -= 1\n @missed_letters.push(@guess)\n end\n @blanks\n end",
"def guess?(letter)\n if @guessed_letter.include?(letter)\n puts \"You already guessed that letter!\"\n return\n end\n @guessed_letter << letter\n \n found = false\n if @characters.include?(letter)\n found = true \n puts \"Yes that letter is in the word!\"\n else\n puts \"Wrong answer!\"\n end \n \n @characters.each_with_index do |char, index|\n if char == letter\n @displayed_character[index] = letter\n end\n end\n found\n end",
"def show_wrong_letters\n\t\t@wrong_letters.sort.join(\", \")\n\tend",
"def missing_letters(string)\n\n result = []\n\n (\"a\"..\"z\").each do |ch|\n result << ch if string.downcase.include?(ch) == false\n\n end\n result\nend",
"def letters\n self.chars.select { |c| c.match(/[a-z]/i) }.join\nend",
"def user_input\n\t\tputs \"Please pick a letter to guess the word.\"\n\t\t@letter = gets.chomp.downcase\n\t\t@letters_array = [*?a..?z] #creates an array of the alphabet from a to z lowercase\n\t\tuser_input_check\n\tend",
"def guess_letter(letter)\n won = false\n failed_guess = feedback(letter)\n if failed_guess\n @tries_left -= 1\n else\n won = won?(@display_word.split(\" \").join(\"\"))\n end\n won\n end",
"def missing_letters(phrase)\n counts = Hash.new(0)\n phrase.chars.each do |character|\n counts[character] += 1\n end\n missing = []\n ('a'..'z').each do |letter|\n missing << letter if counts[letter] == 0\n end\n missing\nend",
"def letter_guess\n letter = get_letter_player()\n check_letter_in_random_word(@guess_letter)\n if @correct_guess == false\n @failed_attempts += 1\n if @failed_attempts == 10\n @lose = true\n end\n end\n guess_word_status_string = @guess_word_status.join()\n if guess_word_status_string == @random_word\n @win = true\n end\n end",
"def add_to_guess\n @guess = @guess.map!.with_index do |character, index|\n @word.downcase[index] == @letter ? @word[index] : character\n end\n end",
"def include_letter(word, letter)\n index = 0 \n if @letter_bank.include?(letter) \n puts \"You already tried this letter\"\n else \n word.each_char do |l|\n if l == letter\n @blanks[index] = letter\n end \n index += 1\n end \n @guess_count -= 1 \n @letter_bank << letter\n end \n puts \"You have #{guess_count} guesses left\"\n p @blanks\n end",
"def show_letter\n split_blanks = hidden_word.split(\" \")\n occurences = []\n occurences = (0 ... @secret_word.length).find_all { |i| @secret_word[i,1] == @current_guess}\n occurences.each { |i| split_blanks[i] = @current_guess}\n @hidden_word = split_blanks.join(\" \")\n hidden_word\n end",
"def getAlphabet\n alphabet = \"A\"..\"Z\"\n $alphabet_array = alphabet.to_a\nend",
"def check_guess(player_guess, display)\n letter_found = false\n @secret_word.chars.each_with_index do |char, index|\n if char.downcase == player_guess\n display[index] = char\n letter_found = true\n end\n end\n letter_found\n end",
"def letter_choices(game_data)\n \"USED LETTERS: #{game_data.chosen_letters}\"\n end",
"def test_12_add_wrong_letter_to_wrong_count_array\r\n $wrong_count = [\"z\", \"x\", \"w\", \"q\", \"d\", \"f\", \"k\", \"m\"]\r\n letter = \"u\"\r\n results = wrong_letter(letter)\r\n assert_equal([\"z\", \"x\", \"w\", \"q\", \"d\", \"f\", \"k\", \"m\", \"u\"], $wrong_count)\r\n end",
"def guess(letter, secret_word)\r\n \t\t\r\n \t\t\r\n \t\tright = false\r\n \t\r\n \t\tsecret_word.each do|char| \r\n\r\n \t\t\tif char == letter\r\n \t\t\t\tright = true\r\n \t\t\tend\r\n \t\tend\r\n \t\t\r\n \t\tif right == true\r\n \t\t\tputs \"correct!\"\r\n \t\t\t\r\n \t\telse\r\n \t\t\tputs \"wrong!\"\r\n \t\tend\r\n \t\t@guess_count -= 1\r\n\r\n \t\tputs \"Guesses remaining #{guess_count}\"\r\n \t\t\r\n\r\n\r\n \tend",
"def wrong_letter(letter)\n if $wrong_count.length < 9 # if the wrong_count array has less than 9 letters\n $wrong_count.push(letter) # then add the letter to the array\n $prompt = \"Sorry - that letter was not in the word. Please try again!\"\n else # if this is the tenth wrong letter, it's game over\n $wrong_count.push(letter) # then add the letter to the array\n $game_over = true # set the flag to indicate that the game is over\n $games_lost += 1 # increase the games_lost score by 1\n end\nend",
"def love_letter string\n\n count = 0\n\n arr = string.chars\n\n alpha = ('a'..'z').to_a\n\n arr.each_with_index do |x,xi|\n while arr[xi] != arr[-(xi+1)]\n opposite = arr[-(xi+1)]\n cur_letter = [arr[xi], opposite].max\n\n alpha_index = alpha.index(cur_letter)\n\n if opposite > arr[xi]\n arr[-(xi+1)] = alpha[alpha_index - 1]\n count += 1\n end\n\n if arr[xi] > opposite\n arr[xi] = alpha[alpha_index-1]\n count +=1\n end\n\n end\n end\n\n count\n\nend",
"def show_letter\n split_blanks = hidden_word.split(\"\")\n occurences = []\n occurences = (0 ... secret_word.length).find_all { |i| secret_word[i,1] == current_guess}\n occurences.each { |i| split_blanks[i] = current_guess}\n @hidden_word = split_blanks.join(\"\")\n puts hidden_word\n end",
"def check_letter(input_letter)\n # Each time we check, the number of guesses is increased \n @guess_count += 1\n \n # Transform the words into arrays for convenience\n arr_word_to_guess = @word_to_guess.split('') \n arr_guessed_word = @guessed_word.split('') \n \n # Search for the input_letter in arr_word_to_guess\n index_found = arr_word_to_guess.each_index.select{|i| arr_word_to_guess[i] == input_letter}\n \n if (index_found == []) then\n return false \n else \n # if the letter is found, update the guessed word\n n_found = index_found.size\n i = 0 \n n_found.times do \n arr_guessed_word[index_found[i]] = input_letter\n i += 1\n end\n @guessed_word = arr_guessed_word.join('')\n return true\n end \n end",
"def show_wrong_letters\n puts \"These letters are not in the word: #{@wrong_letters.join(\", \")}\"\n puts \"\\n\"\n end",
"def all_letters_guessed?\n @word_to_guess.each do |letter_in_word_to_guess|\n if !has_been_guessed_correctly?(letter_in_word_to_guess)\n return false\n end\n end\n return true\n end",
"def guess(letter_guessed)\r\n# \ti. Run loop to see if the letter has been guessed yet.\r\n\tif word_split.include? (letter_guessed)\r\n\t\t# a. Iterate through the word characters to see if it includes the letter guessed\r\n\t\t@word_split.each_with_index do |char, index|\r\n\t\t\tif word_split[index] == letter_guessed\r\n\t\t\t\t@guessed[index] = letter_guessed\r\n\t\t\tend #if\r\n\t\tend #do\r\n\t\t# b. If it is right then put you have guessed a letter and then ask for another guess repeat method\r\n\t\tputs \"You guessed correctly. Enter another guess\"\r\n# \t\tc. If it is wrong then put you have guessed wrong and ask for another guess. Maybe return how many guesses you have left?\r\n\telse\r\n\t\t@guess_count +=1\r\n\t\tputs \"You guessed incorrectly. Enter another guess\"\r\n\tend#if\r\nend",
"def wrong_guess(letter)\n\t\tif !@attempted_letters.include?(letter)\n\t\t\tputs \"WRONG....\"\n\t\t\t@attempted_letters << letter\n\t\t\t@number_of_guesses -= 1 \n\t\t\tp @number_of_guesses\n\t\t\tp @display\n\t\t\tp \"you have #{@number_of_guesses} guesses left...\"\n\t\t\treturn true\n\t\tend\n\tend",
"def love_letter string\n arr = string.chars\n alpha = ('a'..'z').to_a\n count = 0\n\n arr.each_with_index do |x,xi|\n while arr[xi] != arr[-(xi+1)]\n opposite = arr[-(xi+1)]\n cur_letter = [opposite, arr[xi]].max\n a_index = alpha.index(cur_letter) - 1\n new_char = alpha[a_index]\n\n if opposite > arr[xi]\n arr[-(xi+1)] = new_char\n count +=1\n else\n arr[xi] = new_char\n count +=1\n end\n end\n end\n count\nend",
"def check_letter(user_guess)\n @letter = user_guess.length == 1\n end",
"def guess(letter)\r\n letter = letter.downcase\r\n #find the guess\r\n returnValue = @word.count(letter) \r\n case returnValue\r\n when 0\r\n #Meaning this was an invalid guess\r\n @count-=1\r\n #maybe for debugging purposes\r\n @guessedFalse << letter\r\n else\r\n #maybe for debugging purposes\r\n @guessedTrue << letter\r\n #get all index of a matching letter\r\n arryOfMatchesIndexs = (0 ... @word.length).find_all { |i| @word[i,1] == letter }\r\n #iterate through the matches and replace the shadow word\r\n arryOfMatchesIndexs.each { |x| \r\n @shadowWord[x] = letter \r\n }\r\n \r\n #if the shadowWord array does not have any underscroes then we win \r\n if (@shadowWord.index(\"_\")).nil? \r\n @win = true\r\n end\r\n end\r\n #return the value of found\r\n returnValue\r\n end",
"def getguess guess\r\n\t\t\t\t\t@spin_flag = false\r\n\t\t\t\t if guess.length == 1\r\n\t\t\t\t if check_repeated_choice guess\r\n\t\t\t\t @message = \"Already guessed this letter!\"\r\n\t\t\t\t if @console\r\n\t\t\t\t\t\t\t\t@output.puts \"#{@message}\"\r\n\t\t\t\t\t\t\t\tword_input = take_user_word_input\r\n\t\t\t\t\t\t\t\tvalid = false\r\n\t\t\t\t\t\t\t while !valid do\r\n\t\t if validate_input word_input\r\n\t\t valid = true\r\n\t\t else\r\n\t\t @output.puts \"Invalid input\"\r\n\t\t word_input = take_user_word_input\r\n\t\t end\r\n\t\t\t\t\t\t\t end\r\n\t\t\t\t\t\t\t\tif check_enter word_input\r\n\t\t\t\t\t\t\t\t\t\t@break_flag = true\r\n\t\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t\t getguess word_input\r\n\t\t\t\t\t\t\t\tend\r\n\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t@spin_flag = true\r\n\t\t\t\t end\r\n\t\t\t\t else\r\n\t\t\t\t \t@message=\"Guess a letter from the word/phrase.\"\r\n\t\t\t\t @guess_counter+=1\r\n\t\t\t\t check_guess guess\r\n\t\t\t\t set_guess_analysis guess\r\n\t\t\t\t end\r\n\t\t\t\t success = check_phrase @resulta.join(',').gsub(\",\",\"\")\r\n\t\t\t\t return success ? true : false\r\n\t\t\t\telse\r\n\t\t\t\t\t if check_phrase guess\r\n\t\t\t\t\t\t phrase = @secretword.chars\r\n\t\t\t\t\t\t i = 0\r\n\t\t\t\t\t\t while i < phrase.length do\r\n\t\t\t\t\t\t\t\t\t\t@resulta[i] = phrase[i]\r\n\t\t\t\t\t\t\t\t\t\ti += 1\r\n\t\t\t\t\t\t end\r\n\t\t\t\t\t\t return true\r\n\t\t\t\t\t else\r\n\t\t\t\t\t\t @num_guessed = 0\r\n\t\t\t\t\t\t incrementturn\r\n\t\t\t\t\t\t @guess_counter+=1\r\n\t\t\t\t\t\t set_guess_analysis guess\r\n\t\t\t\t\t\t return false\r\n\t\t\t\t\t end\r\n\t\t\t\tend\r\n\t\t\t\tend"
] |
[
"0.83717734",
"0.76092356",
"0.7403644",
"0.73906",
"0.7341107",
"0.7259141",
"0.7250252",
"0.71186",
"0.7107187",
"0.69222337",
"0.6911611",
"0.6904964",
"0.6879654",
"0.68753994",
"0.6873055",
"0.68552655",
"0.6841495",
"0.6822786",
"0.68145984",
"0.68145984",
"0.67986995",
"0.6793718",
"0.67438984",
"0.6735218",
"0.67158014",
"0.67155504",
"0.67102414",
"0.668606",
"0.66691124",
"0.6666417",
"0.664855",
"0.6633082",
"0.6631306",
"0.662871",
"0.66276455",
"0.6625177",
"0.66180915",
"0.661433",
"0.6609061",
"0.65979904",
"0.65926963",
"0.6583749",
"0.6580094",
"0.6558355",
"0.6555686",
"0.6524532",
"0.6521014",
"0.6519171",
"0.6516764",
"0.650322",
"0.65025437",
"0.64899474",
"0.64870316",
"0.64610255",
"0.6459986",
"0.64560604",
"0.6444816",
"0.6444101",
"0.6435374",
"0.6433094",
"0.64274013",
"0.64262843",
"0.64232767",
"0.6412391",
"0.64086074",
"0.6403613",
"0.63965625",
"0.6390919",
"0.6379443",
"0.63691807",
"0.63652587",
"0.63643014",
"0.6361252",
"0.6358969",
"0.63583064",
"0.6356779",
"0.63547456",
"0.63531226",
"0.6344991",
"0.6341343",
"0.6332455",
"0.63296676",
"0.6318133",
"0.6311609",
"0.63063633",
"0.63054985",
"0.6304235",
"0.6290713",
"0.62827814",
"0.6275303",
"0.6273329",
"0.6267301",
"0.6260077",
"0.6254994",
"0.6233685",
"0.6228936",
"0.6226321",
"0.6225916",
"0.6224318",
"0.62214524"
] |
0.79954636
|
1
|
the next three methods check whether the game is won, lost or is already over the game is lost if there are no errors left
|
def lost?
errors_allowed == 0
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def check_if_lost\n\t\tif @guess_count == @number_guess + 1\n\t\t\t@game_over = 2\n\t\tend\n\t\t@game_over\n\tend",
"def check_win\n if @game_board.return_count == 5 and @timer.return_time >= 0\n @win = true\n end\n if @game_board.return_count < 5 and @timer.return_time == 0\n @lose = true\n end\n end",
"def game_over?\n self.lost? || self.won?\n end",
"def game_over?\n if victory?\n puts \"The code has been broken!\"\n true\n elsif (@turns == 12)\n puts \"The codebreaker failed.\"\n true\n else\n false\n end\n end",
"def game_system_win_fail\n case @board.win_or_fail\n when 'win' then end_game(win: true)\n when 'fail' then end_game(fail: true)\n end\n end",
"def check_lost\n if @guess_count == MAX_GUESS\n puts \"\\tYou lost! You've used up all your guesses!\"\n self.new_round\n end\n end",
"def game_over(won)\n if won\n puts 'The code has been broken! Game over'\n else\n puts 'The code could not be broken! Game over'\n end\n end",
"def game_over?\n true\n end",
"def check_win\r\n\t\tif @guess_word == @secret_word \r\n\t\t\t@is_over = true \r\n\t\t\tputs \"Congrats! You won!\"\r\n\t\telse\r\n\t\t\tfalse \r\n\t\tend \r\n\r\n\t\tif @num_guess == 0 \r\n\t\t\t@is_over = true\r\n\t\t\tputs \"No more tries! You have lost.\"\r\n\t\telse \r\n\t\t\tfalse\r\n\t\tend \r\n\tend",
"def win_or_lose\n if game_data.guesses_remaining.zero?\n puts File.read('./views/you_dead')\n puts File.read('./views/dead')\n elsif game_data.letters_left_to_guess == []\n puts File.read('./views/winscreen')\n else\n # allows us to break recursion if we are testing\n @test_cond == false ? Turn.new(game_data) : true\n end\n end",
"def game_over?\n @board.pieces['black'].empty? || @board.pieces['white'].empty? || (@board.moves(HUMAN_PLAYER).empty? && @board.moves(CPU_PLAYER).empty?)\n end",
"def check_for_loss\n if @number_incorrect.to_i == 6\n puts \"Unfortuntately you are out of guesses. Please play again!\"\n exit\n end\n end",
"def game_over?\n @players.all? {|p| p.last_turn == \"skipped turn\"} || (@letter_bank.empty? && current_player.rack_empty?)\n end",
"def lost?()\r\n\t\tlose_game = false\r\n\t\t\r\n\t\tif (bad_guess_count() == MAX_GUESSES)\r\n\t\t\tlose_game = true\r\n\t\tend\r\n\t\t\r\n\t\treturn lose_game\r\n\tend",
"def game_over?\n if $board.has_value?(\"none\") == false then\n puts \"No more turns available\"\n return true\n else\n return false\n end\n end",
"def judge_win_loss\n return if update_processes or @spriteset.effect?\n #-------------------------------------------------------------\n # Check Victory Conditions\n check_victory_conditions\n\n #-------------------------------------------------------------\n # Check Failure conditions\n check_failure_conditions\n \n #If all Actors dead\n if (friends_of(Battler_Actor).select {|mem| !mem.death_state?}).empty?\n add_fail_com\n end\n update_event_queue\n end",
"def game_over\n remaining_player.count == 1\n end",
"def check_win\n\t\t\tif win\n\t\t\t\tputs \"\\n You win!\" \n\t\t\telse\n\t\t\t\t# shows how many turns remain\n\t\t\t\tputs \"\\n You have #{TURNS - @turns} turns left\"\n\t\t\tend\n\t\tend",
"def game_over?\n remaining_players == 1\n end",
"def game_over?\n possible_moves(:white).empty? && possible_moves(:black).empty? \n end",
"def lose?\n\t\t@wrong_guesses.length == 6\n\tend",
"def game_is_over?\n (won? || draw? || full?) ? true : false\n end",
"def check_winner\n if win_state == CHECK\n if players[0].get_hand_score >= players[1].get_hand_score\n self.win_state = LOSS\n else\n self.win_state = WIN\n end\n end\n\n if win_state == WIN\n self.wins = wins + 1 \n puts \"Good win! You're now at #{wins} wins and #{losses}.\"\n else\n self.losses = losses + 1\n puts \"Better luck next time. You're now at #{wins} wins and #{losses} losses.\"\n end\n end",
"def game_over?\n return true if victory? || (@turns == 12)\n false\n end",
"def is_game_over?\n @guesses_left == 0 ? true : false\n end",
"def check_game_over (guess, code)\n red_orb = give_hint(guess,code)[0]\n white_orb = give_hint(guess,code)[1]\n puts \"Red Orb: #{red_orb}, White Orb: #{white_orb}\"\n (give_hint(guess, code)[0] == 4) ? true : false\n end",
"def over?\n \t@game_over = true\n end",
"def gameover?\n full? or not check_winner.nil?\n end",
"def game_over?\n shots_remaining <= 0 || board.boats.all?(&:sunk?)\n end",
"def lost?\n @current_wrong_guesses == @max_wrong_guesses\n end",
"def remaining_guesses()\n if $turns > 1\n puts \"You have #{$turns} incorrect guesses left!\"\n elsif $turns == 1\n puts \"You have 1 incorrect guess left!\"\n else\n puts \"GAME OVER\"\n end\n end",
"def end_game?\n self.message = []\n if winner?(self.player)\n self.message[2] = \"#{self.player.name} wins!\"\n self.player.score += 1\n result = true\n elsif winner?(self.computer)\n self.message[2] = \"#{self.computer.name} wins!\"\n self.computer.score += 1\n result = true\n elsif self.board.all_squares_occupied?\n self.message[2] = \"Tie game!\"\n result = true\n end\n draw\n return result\n end",
"def lost_game?\n\n return true if self.score == 0\n\n false\n end",
"def over?(board)\n if won?(board) || draw?(board) #BE CAREFUL! If you flipped this, the test wouldn't have passed because it wouldn't stopped after the fail\n true\n end\nend",
"def game_over?\nwin_formations = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 4, 8],\n[2, 4, 6], [0, 3, 6], [1, 4, 7], [2, 5, 7] ]\nwin_formations.each do |win_formation|\nif formation_met?(win_formation)\nend_game_message \"Player #{ @player } Won.\"\nreturn true\nend\nend\ndraw?\nend",
"def game_over?\n\t\t(@board.guesses.key?(12) || @board.guesses.value?(@code)) ? true : false\n\tend",
"def gameIsOver\n\t\treturn frameNumber() > @lastFrameNumber\n\tend",
"def game_over\n #some end game conditions\nend",
"def is_game_over?\n players.count < 2 ||\n @state == 'stop' ||\n @cards_on_table.count >= Deck.num_cards ||\n (players.map{|p| p.num_cards_remaining == Deck.num_cards}.include? true)\n end",
"def gameover(game)\n if game.full_board?() #Si el tablero se lleno primero es que hubo un empate\n puts \"GAME OVER\"\n return \"draw\"\n end\n if game.match() #Si se tiene match de fichas\n puts \"TIC TAC TOE\"\n return \"win\"\n end\nend",
"def game_over?\n losing_players != nil ? true: false\n end",
"def check_if_won\n\t\tif @word_hidden == @answer_word\n\t\t\t@game_over = 1\n\t\tend\n\t\t@game_over\n\tend",
"def out_of_tries?\n if @tries_left < 1\n puts \"Player lost!\"\n File.delete(\"saves/#{@user}.yml\") if File.exist?(\"saves/#{@user}.yml\")\n true\n else \n false\n end\n end",
"def lost?(state)\n done?(state) && !won?(state)\n end",
"def game_over?\n return false unless @previous_piece\n\n previous_color = @previous_piece.color == :white ? :black : :white\n no_legal_moves_captures?(previous_color)\n end",
"def check_for_game_over\n if @proposed_code == @secret_code && @player_role_selection == 'breaker'\n puts 'YOU WIN!'\n true\n elsif @proposed_code == @secret_code && @player_role_selection == 'maker'\n puts 'COMPUTER WINS!'\n true\n else\n false\n end\n end",
"def game_over\n [:winner, :tie].include?(board.status)\n end",
"def check_win_or_lose\n # returns one of the symbols :win, :lose, or :play depending on the current game state\n \n end",
"def game_over\n if @counter == 0 && !(@puzzle_array.join == user.word_to_guess)\n puts \"You didn't get it! The word was #{user.word_to_guess}.\"\n return true\n elsif @counter == 0 && @puzzle_array.join == user.word_to_guess\n puts \"Congrats! You won!\"\n graphic\n return true\n elsif @puzzle_array.join == user.word_to_guess\n puts \"Congrats! You won!\"\n return true\n else\n return false\n end\n end",
"def end_conditions?\n #checks winner\n if @board.win_conditions?\n if @current_player\n puts \"Congratulations! Player 1 wins!!\"\n else\n puts \"Congratulations! Player 2 wins!!\"\n end\n @board.render\n return true\n end\n #return true if game over\n if @board.grid_full?\n puts \"It's a draw! GAME OVER.\"\n @board.render\n return true\n end\n false\n end",
"def game_over?\n players_found_phrase = @states.select { |s| s.found_phrase }\n if players_found_phrase.size == 1\n @renderer.output \"We have a winner! #{players_found_phrase.first.player.name} found the phrase!\"\n return true \n elsif players_found_phrase.size > 1\n drawn_player_names = players_found_phrase.map { |s| s.player.name }\n @renderer.output \"We have a draw between #{drawn_player_names.join(' and ')}\"\n return true\n else\n dead_players = @states.select { |s| s.incorrect_guesses.count >= Gallows.stages.count - 1 }\n if dead_players.count > 0\n dead_player_names = dead_players.map { |s| s.player.name }\n @renderer.output \"#{dead_player_names.join(' and ')} is dead.\"\n if dead_players.count == @states.count\n @renderer.output \"It's a draw, all players are dead.\"\n else\n surviving_players = @states.select { |s| dead_players.index(s).nil? }\n surviving_player_names = surviving_players.map { |s| s.player.name }\n @renderer.output \"We have a winner! #{surviving_player_names.join(' and ')} survived longer!\"\n end\n return true\n end\n end\n return false\n end",
"def game_over\n end",
"def isGameOver()\n return isBoardFull() ||\n (!isValidMoveAvailableForDisc(WHITE) &&\n !isValidMoveAvailableForDisc(BLACK))\n end",
"def checkWin()\n # bool vars to check valid moves \n player1Valid = false\n player2Valid = false\n\n if @player1.numPlayedPieces <=2 && @player1.numUnplayedPieces == 0 \n puts \"Player 2 has won the game!\"\n return true\n elsif @player2.numPlayedPieces <=2 && @player2.numUnplayedPieces == 0 \n puts \"Player 1 has won the game!\"\n return true\n else\n # both players have more then 2 pieces on the bord.\n # check if players have valid moves left.\n if @player1.numUnplayedPieces > 0 \n # No winner there is a valid move for player1.\n puts \"Player 1 has valid moves\"\n return false\n elsif @player2.numUnplayedPieces > 0 \n puts \"Player 2 has valid moves\"\n return false\n else\n # check if any moves are possible.\n\n # player 1\n # until true, loop through played pieces, for each location call validMove(). there is no (get adjacent function so this is clunky sorry)\n for piece in @player1.playedPieces\n \n @board.locations.each do |row|\n row.each do |location|\n \n # validMove will return true if it is valid. \n if validMove(piece, location)\n player1Valid = true\n end \n break if player1Valid \n end\n break if player1Valid \n end\n break if player1Valid \n end\n\n #player2\n for piece in @player2.playedPieces\n \n @board.locations.each do |row|\n row.each do |location|\n \n # validMove will return true if it is valid. \n if validMove(piece, location)\n player2Valid = true\n end \n break if player2Valid \n end\n break if player2Valid \n end\n break if player2Valid \n end\n \n\n if !player1Valid && !player2Valid \n puts \"Both Player's have no moves. The game is a draw\"\n return true\n \n elsif !player1Valid\n # player1 has no remaining moves\n puts @player1.name +\" has no valid moves,\" + @player2.name + \" wins!\"\n return true\n\n \n elsif !player2Valid\n # player1 has no rem\n puts @player2.name +\" has no valid moves,\" + @player1.name + \" wins!\"\n return true\n \n else\n puts \" both players have valid moves left. The game is not over.\"\n return false\n end\n end\n end\n\n end",
"def game_over\n return :winner if winner?\n return :draw if draw?\n false\n end",
"def isGameOver()\n\t\treturn isBoardFull() ||\n\t\t\t\t\t(!isValidMoveAvailableForDisc(WHITE) &&\n\t\t\t\t\t\t\t\t!isValidMoveAvailableForDisc(BLACK))\n\tend",
"def isGameOver()\n\t\treturn isBoardFull() ||\n\t\t\t\t\t(!isValidMoveAvailableForDisc(WHITE) &&\n\t\t\t\t\t\t\t\t!isValidMoveAvailableForDisc(BLACK))\n\tend",
"def over?\n for i in 1..4\n if @figures[0].position == @figures[i].position\n log \"**GAME OVER:** Mr. X was caught - The agents win.\"\n @logger.save\n puts \"Game Over: The agents win\"\n return true\n end\n end\n if @turns > 19\n log \"**GAME OVER:** 20 turns have passed - Mr. X wins.\"\n @logger.save\n puts \"Game Over: Mr. X wins\"\n return true\n end\n return false\n end",
"def actions_when_game_is_lost\n puts \"\"\n puts \"GAME OVER\".red\n self.quit_game = true\n end",
"def over?\n draw? || won?\n end",
"def game_over?\n return @gamestate.checkmate?(@current_player.team)\n end",
"def check_game_status\n # create all winning combinations in a variable using an array\n winning_combos = [[@board[0],@board[1],@board[2]], [@board[3],@board[4],@board[5]], [@board[6],@board[7],@board[8]], [@board[0],@board[3],@board[6]], [@board[1],@board[4],@board[7]], [@board[2],@board[5],@board[8]], [@board[0],@board[4],@board[8]], [@board[2],@board[4],@board[6]] ]\n # if the winning combinations include all \"X\"'s then you won\n if winning_combos.include? ([@symbol, @symbol, @symbol])\n display_board\n puts \"Winner!\"\n exit\n # if the winning combinations include all \"O\"'s the computer won.\n elsif winning_combos.include? ([@computer_symbol, @computer_symbol, @computer_symbol])\n display_board\n puts \"You lose. Better luck next time!\"\n exit\n # check if the game is a tie/draw\n elsif @board.all? {|i| i == \"X\" || i == \"O\"}\n display_board\n puts \"It's a draw. Try again.\"\n exit\n else\n # if none of these then continue playing the game\n play_game\n end\n end",
"def over?\n won? || full? || draw?\n end",
"def game_over?\n x_array = []\n o_array = []\n @taken.each do |key, value|\n if value == \"X\"\n x_array << key\n else\n o_array << key\n end\n end\n # The x and o arrays are compared to 3 because 3 moves is the minimum number of moves needed to win\n if x_array.length >= 3 || o_array.length >= 3\n if three_in_a_row?(x_array) == true || three_in_a_row?(o_array) == true\n return true\n end\n else\n return false\n end\n end",
"def over?\r\n won? || draw?\r\n end",
"def end_of_game_logic\n check_and_manage_winner\n show_winner_and_scores\n new_round?\n end",
"def over?\n won? || draw? || full?\n end",
"def over?\n won? || draw? || full?\n end",
"def over?\n won? || draw? || full?\n end",
"def game_over?\n @board.game_over?\n end",
"def over?\n won? || full? || draw?\n end",
"def won?\n won_checker\n end",
"def game_over?\n @game_over\n end",
"def lose?\n end",
"def lives_checker\n if (player_1.lives == 0 || player_2.lives == 0)\n self.game_over\n else\n puts \"------NEW ROUND------\"\n self.start_game\n end\n end",
"def is_game_over?; won_by?(:hunter) || won_by?(:prey) end",
"def over?\n draw? || won?\n end",
"def over?\n draw? || won?\n end",
"def over?\n draw? || won?\n end",
"def check_win_or_lose\n if !@word_with_guesses.include?(\"-\")\n return :win\n elsif @word_with_guesses.include?(\"-\") && @attempts >= 8\n return :lose\n else \n return :play \n end\n end",
"def over?\n won? || draw? || full?\n end",
"def check_end_of_game\n return has_this_player_won?(COMPUTER) ? COMPUTER : (has_this_player_won?(HUMAN) ? HUMAN : false)\n end",
"def outOfGame\n @inGame = false\n end",
"def over?\n if won? || draw? || full?\n true\n end\n end",
"def end_game\n if @guess_count == 0 && @blanks != @new_word\n puts \"The game is over, Better luck next time :(\"\n @is_over = true\n elsif @blanks == @new_word\n puts \"Congrats you guessed the secret word! :)\"\n @is_over = true\n end \n end",
"def over?\n won? || board.full? || draw?\n end",
"def over?\n return draw? || won?\n end",
"def check_win_or_lose\n # if guessed letters are 7 then lose\n if self.wrong_guesses.length >= 7\n :lose\n elsif all_letters_in_word_in_guesses?\n :win\n else\n :play\n end\n end",
"def over?\n won? || draw?\n end",
"def game_is_over(board)\n someone_wins(board) || tie(board)\n end",
"def new_game?\n moves.empty?\n end",
"def over?\n draw? || won? || full?\nend",
"def over?\n if won? != false && won? != nil || draw? == true\n return true\n else\n return false\n end\n end",
"def is_win\n\t\tgame_win = false # on cree une variable Game_win qui vaux false par default\n\t\t# si une des 8 condition de victoire est bonne alor on la variable game_win devien egale a true\n\t\tif (@board_case[\"A1\"] == @board_case[\"A2\"] && @board_case[\"A2\"] == @board_case[\"A3\"] && @board_case[\"A1\"] != \" \") ||\n\t\t\t(@board_case[\"B1\"] == @board_case[\"B2\"] && @board_case[\"B2\"] == @board_case[\"B3\"] && @board_case[\"B1\"] != \" \") ||\n\t\t\t(@board_case[\"C1\"] == @board_case[\"C2\"] && @board_case[\"C2\"] == @board_case[\"C3\"] && @board_case[\"C1\"] != \" \") ||\n\t\t\t(@board_case[\"A1\"] == @board_case[\"B1\"] && @board_case[\"B1\"] == @board_case[\"C1\"] && @board_case[\"A1\"] != \" \") ||\n\t\t\t(@board_case[\"A2\"] == @board_case[\"B2\"] && @board_case[\"B2\"] == @board_case[\"C2\"] && @board_case[\"A2\"] != \" \") ||\n\t\t\t(@board_case[\"A3\"] == @board_case[\"B3\"] && @board_case[\"B3\"] == @board_case[\"C3\"] && @board_case[\"A3\"] != \" \") ||\n\t\t\t(@board_case[\"A1\"] == @board_case[\"B2\"] && @board_case[\"B2\"] == @board_case[\"C3\"] && @board_case[\"A1\"] != \" \") ||\n\t\t\t(@board_case[\"A3\"] == @board_case[\"B2\"] && @board_case[\"B2\"] == @board_case[\"C1\"] && @board_case[\"A3\"] != \" \")\n\t\t\tgame_win = true\n\t\tend\n\t\tgame_win # on renvoi la valeur de la variable qui indique si il y a un cas de victoire sur le plateau ou pas\n\tend",
"def game_over_lose\n flash[:error] = 'Game Over: Better Luck Next Time!'\n end",
"def check_and_manage_winner\n if codebreaker_wins?\n manage_codebreaker_winning_guess\n else manage_codemaker_wins\n end\n end",
"def over?\n won? || draw?\n end",
"def over?\n won? || draw?\n end",
"def check_win_or_lose\n return @check_win_or_lose\n end",
"def game_finished?\n finished = true\n # Check for any display placeholders, if they exit the game is not finished.\n @@word_display.each do |c|\n if (c == \"_\")\n finished = false\n break\n end\n end\n\n # If there are no placeholder marks and guesses remaining, then the player has won and the game is finished.\n if (finished)\n if (@@guesses_remaining > 0)\n @@game_status = \"win\"\n end\n # There are still placeholders, so if we have no more guesses then the player has lost and the game is finished.\n else\n if (@@guesses_remaining == 0)\n @@game_status = \"lose\"\n finished = true\n end\n end\n finished\nend"
] |
[
"0.80396205",
"0.76528126",
"0.7486093",
"0.7463803",
"0.73961127",
"0.7348537",
"0.73139834",
"0.72851336",
"0.7265934",
"0.72365624",
"0.7236358",
"0.71909916",
"0.7185107",
"0.7182554",
"0.7171043",
"0.7162245",
"0.7141368",
"0.7125404",
"0.71241695",
"0.71201646",
"0.7101498",
"0.70999324",
"0.7095319",
"0.70587456",
"0.7057187",
"0.70500964",
"0.70431995",
"0.7038517",
"0.7035744",
"0.70273316",
"0.7025034",
"0.70216984",
"0.7012052",
"0.7008789",
"0.70087004",
"0.69899136",
"0.6984122",
"0.6975385",
"0.6973948",
"0.6960484",
"0.6950084",
"0.6947921",
"0.69455355",
"0.69383425",
"0.6935953",
"0.6933712",
"0.69333947",
"0.6910648",
"0.690351",
"0.69006264",
"0.6898855",
"0.6896478",
"0.6880243",
"0.6878727",
"0.68727964",
"0.6863111",
"0.6863111",
"0.6860813",
"0.68397313",
"0.68394136",
"0.6836844",
"0.6826467",
"0.6824327",
"0.6818309",
"0.6814",
"0.68130225",
"0.68055624",
"0.68055624",
"0.68055624",
"0.6803868",
"0.6795739",
"0.67916155",
"0.6788526",
"0.67881286",
"0.6784865",
"0.6773615",
"0.6771665",
"0.67707956",
"0.67707956",
"0.67701876",
"0.6761095",
"0.6760178",
"0.6759869",
"0.67543596",
"0.6746484",
"0.67377746",
"0.6737725",
"0.67337966",
"0.6726546",
"0.67259",
"0.6725848",
"0.6723404",
"0.6718819",
"0.670708",
"0.6706",
"0.6703801",
"0.6699787",
"0.6699787",
"0.6695784",
"0.669032"
] |
0.7018597
|
32
|
method plays the letter, chosen by user it puts the letter into the array of user guesses
|
def play!(letter)
if !over? && !@user_guesses.include?(letter)
@user_guesses << normalize_letter(letter)
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def evaluate_players_letter()\n letter= @player1.give_letter()\n if @hiddenword1.determine_if_correct_letter_given(letter)\n p @hiddenword1.obscured_word\n @guessed_letters.push(letter)\n else\n @player1.lives-=1\n p \"Please try again\"\n p @guessed_letters\n p @hiddenword1.obscured_word\n end\n end",
"def guess_letter\n guess = \"\"\n if @letters_guessed.size > 0\n puts \"\\nSo far, you have already guessed the following letters:\"\n puts \"(\" + @letters_guessed.join(\", \") + \")\"\n end\n begin\n puts \"\\n\\nPlease enter a letter for your guess: \"\n puts \"(or type the entire keyword: 'SAVE' or 'EXIT')\"\n guess = gets.chomp.strip.upcase\n if guess == \"SAVE\"\n save_game\n elsif guess == \"EXIT\"\n puts \"\\nExiting the current round...\"\n puts \"\\n=================================================\"\n else\n error_msg1 = \"Selected letter was not of the correct format.\"\n raise ArgumentError.new(error_msg1) unless guess =~ /^[A-Z]$/\n error_msg2 = \"Selected letter has already been guessed.\"\n raise ArgumentError.new(error_msg2) if @letters_guessed.include?(guess)\n end\n rescue ArgumentError=>e\n puts \"Error: #{e.message}\"\n retry\n end\n return guess\n end",
"def respond_to_guess(letter)\n letter = letter.clone.downcase\n\n if @incorrect_letters.include?(letter) || @progress.include?(letter) || @progress.include?(letter.upcase)\n puts \"You already guessed that letter!\"\n puts \"\"\n elsif @word.include?(letter) || @word.include?(letter.upcase)\n update_progress(letter)\n unless @progress.include?(\"_\")\n @round_finished = true\n @guessed = true\n end\n else\n @incorrect_letters << letter\n @round_finished = true if @incorrect_letters.size == 6\n end\n print_hangman\n end",
"def user_input\n\t\tputs \"Please pick a letter to guess the word.\"\n\t\t@letter = gets.chomp.downcase\n\t\t@letters_array = [*?a..?z] #creates an array of the alphabet from a to z lowercase\n\t\tuser_input_check\n\tend",
"def guess_letters(letter)\n @guesses << letter\n @guesses\nend",
"def letter_guess\n letter = get_letter_player()\n check_letter_in_random_word(@guess_letter)\n if @correct_guess == false\n @failed_attempts += 1\n if @failed_attempts == 10\n @lose = true\n end\n end\n guess_word_status_string = @guess_word_status.join()\n if guess_word_status_string == @random_word\n @win = true\n end\n end",
"def guess(letter)\r\n\t\t\r\n\t\tif(@word.include?(letter))\r\n\t\t @good_guesses.add(letter)\r\n\t end\r\n\t\r\n\tend",
"def guess(letter)\n # STEP 1: check to make sure the letter is not any non-letter character and\n # raises an error if it is\n if /^[a-zA-Z]+$/.match(letter)\n letter.downcase!\n else raise_error(\"Invalid letter\")\n end\n\n # STEP 2: check to make sure the user does not guess the same letter more\n # than once\n if @guesses.include? letter; return false; end\n if @wrong_guesses.include? letter; return false; end\n\n # STEP 3: check to see if the guessed letter matches any letters in the \n # word\n if @word.include? letter\n @guesses += letter\n # if there is a match, update the word_with_guesses to show where\n # in the string the letter was matched\n @word.each_char.with_index do |c, i|\n if c == letter\n @word_with_guesses[i] = c\n end\n end \n else \n @wrong_guesses += letter\n @attempts += 1\n end\n # update the number of attempts and call the function to check if\n # the user won, lost, or continues playing\n check_win_or_lose\n end",
"def guess?(letter)\n if @guessed_letter.include?(letter)\n puts \"You already guessed that letter!\"\n return\n end\n @guessed_letter << letter\n \n found = false\n if @characters.include?(letter)\n found = true \n puts \"Yes that letter is in the word!\"\n else\n puts \"Wrong answer!\"\n end \n \n @characters.each_with_index do |char, index|\n if char == letter\n @displayed_character[index] = letter\n end\n end\n found\n end",
"def get_letter_player\n print \"Please give a letter: \"\n @guess_letter = gets.chomp.upcase\n puts \"\\nYou chose #{@guess_letter}\"\n end",
"def guess\n puts \"Enter a letter\"\n puts\n letter = gets.chomp\n if @word_array.include?(letter)\n @word_array.each_with_index do |char, index|\n if char == letter\n @puzzle_array[index] = letter\n end\n end\n puts \"Correct!\"\n else\n puts \"Try again!\"\n end\n @counter -= 1\n end",
"def guess(letter)\r\n if word_has?(letter)\r\n \tput_letter_on_board(letter)\r\n else\r\n wrong_letter(letter) if !@guesses.include? letter\r\n end\r\n end",
"def guess_letter\n\t\tprint \"Your guess: \"\n\t\tguess = gets.chomp.downcase\n\t\treturn guess if guess == \"save\"\n\t\tif (guess.between?('a','z') && !(@guessed_letters.include? guess)\\\n\t\t\t&& guess.length == 1)\n\t\t\tprocess_guess(guess)\n\t\t\t@guessed_letters << guess\n\t\t\t@turns += 1\n\t\telse\n\t\t\tif guess.between?('a','z')\n\t\t\t\tputs \"\\nYour guess must be ONE letter\" unless guess.length == 1\n\t\t\t\tputs \"\\nYou've already guessed that!\" if @guessed_letters.include? guess\n\t\t\telse\n\t\t\t\tputs \"\\nYour guess must be a letter!\" unless guess.between?('a','z')\n\t\t\tend\n\t\t\tputs \"Try again!\\n\\n\"\n\t\t\tguess = guess_letter\n\t\tend\n\t\tguess\n\tend",
"def letters_to_guess\n @letters.map do |letter|\n if @user_guesses.include?(normalize_letter(letter))\n letter\n else\n nil\n end\n end\n end",
"def check_letter(guess)\n if @word.include? guess\n puts \"You chose wisely!\"\n #find which position(s) the guess is in the word array\n correct_index_arr = @word.each_index.select { |i| @word[i] == guess }\n # rebuild @game_status with the correct letter guessed into that position of the word\n correct_index_arr.each do |index|\n @game_status[index] = guess\n end\n # if they don't make guess and put an empty response\n elsif guess.empty?\n puts \"You didn't make a guess. Try again.\"\n # if the user guesses the same wrong letter again\n elsif @wrong_guesses.include? guess\n puts \"You guessed that before! Try again.\"\n else\n @guesses_remaining -= 1\n puts \"wrong guess, the guesses remaining: #{@guesses_remaining}\"\n @wrong_guesses.push(guess)\n end\n end",
"def guess!(letter)\n end",
"def letter_guessed(user_guess)\n\t\tif @guessed_letters.length == 0\n\t\t\t@guessed_letters << user_guess\n\t\telse \n\t\t\tif @guessed_letters.include?(user_guess)\n\t\t\t\tputs \"--You already guessed that letter! Try again!--\"\n\t\t\t\t@guess_count -= 1\n\t\t\telse\n\t\t\t\t@guessed_letters << user_guess\n\t\t\tend\n\t\tend\n\tend",
"def start_guess\r\n\t\tuntil @is_over == true\r\n\t#player enters 1 letter string\r\n\r\n\t\t\tputs \"guess a letter you've already guessed #{@used}. #{@tries-@guess_count} attempts remain\"\r\n\t\t\tputs @blanks.join\r\n\t\t\tletter = gets.chomp\r\n\t#if letter is not in guessed box take a turn away\r\n\t\t\tif @used.include?(letter) == false\r\n\t\t\t\t@guess_count += 1\r\n\t\t\t\tif @tries == @guess_count \r\n\t\t\t\t\t@is_over = true\r\n\t\t\t\tend\r\n\t\t#if letter is in the world replace the blank\r\n\t\t\t\tif @word.include?(letter)\r\n\t\t\t\t\twordindex = @word.index(letter)\r\n\t\t\t\t\t@blanks[wordindex] = letter\r\n\t\t\t\t\tif @blanks.include?(\"_ \") == false\r\n\t\t\t\t\t\t@is_over = true\r\n\t\t\t\t\tend\r\n\t\t#if letter is not in the world add to guessed box\r\n\t\t\t\telse\r\n\t\t\t\t\t@used << letter\r\n\t\t\t\tend\r\n\t#if letter is in guessed box don't consume a turn\r\n\t\t\telse\r\n\t\t\t\tputs \"you already tried that letter\"\r\n\t\t\tend\r\n\t\tend\r\n\r\n\t#end:\r\n\t#if word is guessed correctly print congrants\r\n\t\tif @blanks.include?(\"_ \")\r\n\t\t\tputs \"haha try harder next time\"\r\n\t#if word is guessed wrong print taunt\r\n\t\telse\r\n\t\t\tputs \"well done! you guessed the word\"\r\n\t\tend\r\n\tend",
"def letter_guess(input,dead_man)\n if @letters_guessed_array.include?(input) || dead_man.wrong_letters.include?(input)\n puts \"You have already guessed this letter!\"\n display(dead_man)\n elsif @correct_word_array.include?(input)\n @letters_guessed_array.each_with_index do |letter, index|\n @letters_guessed_array[index] = input if @correct_word_array[index] == input\n end\n puts \"The letter #{input} is in the word.\"\n if @letters_guessed_array.include?(\"__\")\n display(dead_man)\n else\n win\n end\n else\n puts \"The letter #{input} is not in the word.\"\n dead_man.wrong_letters.push(input)\n dead_man.wrong_guesses += 1\n display(dead_man)\n end\n end",
"def guess\n\t\tcollect_words_of_length\n\t\tputs \"Already guessed letters by computer: #{@guessed_letters}\"\n\t\t@guessing_letter = nil\n\t\twhile @guessing_letter == nil || invalid?(@guessing_letter)\n\t\t\t@guessing_letter = guessing_letter\n\t\tend\n\t\t@guessed_letters << @guessing_letter\n\t\t@guessing_letter\n\tend",
"def guess letter\n raise InvalidGuessError if letter.strip.empty? || letter.length > 1\n letter = letter[0].upcase\n if @guesses.include?(letter)\n return {advance: false, message: \"#{letter} has already been played, silly!\"}\n else\n @guesses << letter\n end\n @guessed.each_with_index do |guessed_pos, index|\n if guessed_pos\n if letter == secret[index]\n return {advance: false, message: \"#{letter} has already been played, silly!\"}\n end\n else\n if letter == secret[index]\n reveal_all(letter)\n return {advance: true, message: \"We found #{letter}!\"}\n end\n end\n end\n {advance: true, message: \"Sorry, we did not find #{letter}!\"}\n end",
"def guess!(letter)\n self.word.include? letter\n self.letter = letter\n end",
"def guess(letter)\r\n\t\t@guessed << letter.downcase\r\n\t\t@word[0].each_index do |i| #Iterate through indexes instead of values\r\n\t\t\tif @word.dig(0,i) == letter #since @word is an array inside an array, dig helps us look in word ([0]) each index for the letter.\r\n\t\t\t\t@hidden_word[i] = letter #if found, substitute \"_\" for the letter guessed in the same index for @hidden_word\r\n\t\t\tend\r\n\t\tend\r\n\t\tp @hidden_word #give feedback of results\r\n\tend",
"def wrong_letter(letter)\r\n \t@chances -= 1\r\n @guesses << letter\r\n end",
"def add_to_guess\n @guess = @guess.map!.with_index do |character, index|\n @word.downcase[index] == @letter ? @word[index] : character\n end\n end",
"def play_game\n turn = 1\n while turn < @turns\n puts \"Please guess a letter in the word.\"\n puts \"\"\n user_choice = gets.chomp.to_s\n until @alphabet.include? user_choice and user_choice.length == 1 do\n puts \"Please choose a single letter in the alphabet to guess the content of the word.\"\n user_choice = gets.chomp.to_s\n end\n puts \"Evaluating user choice\"\n is_secret_word_letter(user_choice)\n self.show_game_progress\n turn +=1\n puts \"Turn #{turn} complete!\"\n self.game_over_check\n end\n end",
"def guess\n # takes human input and stores guess\n puts 'Pick a letter'\n self.human_guess = gets.chomp\n end",
"def guess(letter_guessed)\r\n# \ti. Run loop to see if the letter has been guessed yet.\r\n\tif word_split.include? (letter_guessed)\r\n\t\t# a. Iterate through the word characters to see if it includes the letter guessed\r\n\t\t@word_split.each_with_index do |char, index|\r\n\t\t\tif word_split[index] == letter_guessed\r\n\t\t\t\t@guessed[index] = letter_guessed\r\n\t\t\tend #if\r\n\t\tend #do\r\n\t\t# b. If it is right then put you have guessed a letter and then ask for another guess repeat method\r\n\t\tputs \"You guessed correctly. Enter another guess\"\r\n# \t\tc. If it is wrong then put you have guessed wrong and ask for another guess. Maybe return how many guesses you have left?\r\n\telse\r\n\t\t@guess_count +=1\r\n\t\tputs \"You guessed incorrectly. Enter another guess\"\r\n\tend#if\r\nend",
"def wrong_letter(letter)\n @chances -= 1\n @guesses << letter\n end",
"def guess_letter(a_letter)\n p a_letter.downcase\n @word.split(\"\").each_with_index do |another_letter, index|\n if a_letter == another_letter\n @input_word[index] = a_letter\n puts \"Correct! Here are your guesses so far\"\n p @input_word\n end\n if !@word.include? (a_letter)\n end\n end\n end",
"def get_new_letter\n loop do\n puts \"What letter would you like to guess?\"\n @guess = gets.chomp.downcase\n break if valid_letter?(@guess)\n end\n end",
"def good_letter(letter)\n if $bucket.include? letter # check to see if letter has already been guessed and reprompt if so\n $prompt = \"You already guessed that one - TRY AGAIN!\"\n elsif letter[/[a-zA-Z]+/] and letter.length == 1 # check is a single -letter- has been entered\n $bucket.push(letter) # if so, add it to the bucket array\n letter_test(letter) # then pass it to letter_test()\n else # if multiple letters, non-alpha characters or nothing has been entered\n $prompt = \"Enter a single letter - TRY AGAIN!\" # reprompt user to try again\n end\nend",
"def guess(letters)\n raise ArgumentError if letters == \"\"\n raise ArgumentError if letters !~ %r{\\w}\n letters.downcase!\n if @word.include?(letters) \n !@guesses.include?(letters) ? @guesses << letters : false\n\n else\n @wrong_guesses.include?(letters) ? false : wrong_guesses << letters \n end\n end",
"def check_letters(letter)\n progress(letter)\n count = 0\n @word_to_guess.each do |char|\n if char == letter\n @hidden_word[count] = letter\n else\n @hidden_word \n end\n count +=1 \n end\n puts @hidden_word\n @hidden_word\n end",
"def play\n welcome()\n while @current_turn <= @max_turn && @display_word.include?(\"_\")\n puts \"Turn #{@current_turn} out of #{@max_turn}\"\n puts \"Word: #{@display_word}\"\n puts \"Enter a letter for a guess (will only count first letter):\"\n @current_guess = parse_letter(gets.chomp)\n if @current_guess == \"+\"\n save_game()\n else\n @current_turn +=1\n end\n update_display_word()\n end\n end_message()\n end",
"def play_game\r\n\r\n word = select_word #Call on the method that retrieves a random word\r\n\r\n Console_Screen.cls #Clear the display area\r\n\r\n consonants = get_consonants #Call on the method that prompts the player\r\n #to enter a list of consonants\r\n\r\n Console_Screen.cls #Clear the display area\r\n\r\n #Call on the method that prompts the player to enter a vowel\r\n vowel = get_vowel\r\n\r\n #Remove blank spaces from the word to create a short version of the word\r\n shortWord = word.gsub(\" \", \"\")\r\n\r\n #Call the method that processes player guesses\r\n prompt_for_guess(shortWord, word, consonants, vowel)\r\n\r\n Console_Screen.cls #Clear the display area\r\n\r\n end",
"def guess_letter(letter)\n won = false\n failed_guess = feedback(letter)\n if failed_guess\n @tries_left -= 1\n else\n won = won?(@display_word.split(\" \").join(\"\"))\n end\n won\n end",
"def game_loop\n while self.game_word.guessed_all_correct? == false\n puts \"P2, guess a letter\"\n letter = gets.chomp\n game_word.guess!(letter)\n puts game_word.output_word\n end\nend",
"def check_guess(letter)\n @indices = gameboard[0].each_index.select { |i| gameboard[0][i].downcase == letter }\n if @indices.empty?\n incorrect_guesses << letter\n puts 'Sorry, the secret word does not contain that letter'\n else\n @indices.each do |index|\n gameboard[1][index] = gameboard[0][index] # letter\n end\n puts 'Good guess!'\n end\n end",
"def guess_letter(letter)\n\t\tif @ans_word.include?(letter)\n\t\t\ti = @ans_word.index(letter)\n\t\t\t@guess.insert(i, letter)\n\t\t\t@guess.pop\n\t\t\tputs \"Good! You are getting closer: #{@guess*\"\"}\"\n\t\telse\n\t\t\tputs \"sorry, guess again\"\n\t\tend\n\tend",
"def get_guess\n\t\t# There are turns left...\n\t\tif @turn < 9\n\t\t\tshow_board\n\t\t\tputs \"Enter your letter guess...\"\n\t\t\tletter = gets.chomp.downcase\n\t\t\tvalidate_letter(letter)\n\t\t# No turns left, show losing message and delete game if it was previously saved\n\t\telse\n\t\t\tputs\n\t\t\tshow_board\n\t\t\tputs \"Dangit, you ran out of turns!\"\n\t\t\tputs \"The word was #{@word.join}...\"\n\t\t\tif @running_saved_game != nil\n\t\t\t\tover_write_data\n\t\t\tend\n\t\t\tgo_again\n\t\tend\n\tend",
"def guess_letters\n while @guess_count > 0 && @word_guessed.include?('_')\n print 'Guess a letter to play or type save to save game: '\n letter_guessed = gets.chomp.downcase\n if letter_guessed == 'save'\n save_game\n return\n else\n check_letters letter_guessed\n end\n end\n puts \"The secret word was #{@secret_word}\"\n end",
"def get_guess\n @guess = \"\"\n until @guess.match(/^[a-z]$/) && !@already_guessed.include?(@guess)\n print \"Please enter a letter. \"\n @guess = gets.chomp.downcase\n if @guess == 'save'\n save_game\n elsif @already_guessed.include?(@guess)\n puts \"You have already guessed that letter. Please try again.\"\n elsif !@guess.match(/^[a-z]$/)\n puts \"That is not a valid guess. Please enter a single letter.\"\n end\n end\n @guess\n end",
"def play_game\n # play the game until the board is the same as the word and no letters are left to guess\n until (@board == @word)\n puts \"\\nThe points for each correct guess this turn is #{@random_points}\\n\\n\"\n\n if (@turn == 1)\n puts \"Player one's turn: Player one currently has #{@player_one_points} points.\\n\"\n else\n puts \"Player two's turn: Player two currently has #{@player_two_points} points.\\n\"\n end\n\n puts \"Please enter a letter or number player #{@turn}\"\n letter = gets.chomp.to_s.downcase\n positions = @word.enum_for(:scan, /#{letter}/).map { Regexp.last_match.begin(0) }\n\n if (positions.length != 0)\n puts \"\\nCorrect! There is #{positions.length} of the letter #{letter}!\\n\"\n if (@turn == 1)\n @player_one_points = @player_one_points + @random_points * positions.length\n else\n @player_two_points = @player_two_points + @random_points * positions.length\n end\n else\n puts \"\\nIncorrect! There is not a(n) #{letter}!\\n\\n\"\n change_turn\n end\n\n # turn the board into the correct letter that was guessed at the correct index\n positions.map { |e| @board[e] = letter }\n puts @board\n\n # change the point value if both players have played their turns\n random_point_change\n end\n end",
"def game()\n $match_index_arr = []\n $guessed = []\n $turns = 10\n $index = 0\n $end_game = false\n\n get_word()\n puts $hangman[$index]\n show_word()\n loop do \n get_letter()\n letter_match()\n no_match()\n puts $hangman[$index]\n remaining_guesses()\n dash_to_letter()\n puts \"\"\n show_word()\n puts \"\"\n guessed_wrong_letter()\n game_over()\n if $end_game\n break\n end\n check_guess_count()\n end\n return\n end",
"def guess(letter)\n # raise an execption\n # raise will 'break' the method if valid_guess? == false\n raise InvalidGuessException.new(\"Invalid guess!\") unless valid_guess?(letter)\n if word_has?(letter)\n \tput_letter_on_board(letter)\n else\n wrong_letter(letter) if !@guesses.include? letter\n end\n end",
"def beginGame()\n puts \"Let's Play HangMan!\"\n puts \"The word is #{@randomWord.size - 1} characters long.\"\n \n \n while(@numOfGuesses < 10 && @foundWord == false)\n displayLettersFound()\n puts \"Please enter in a character:\"\n\n @userInput = $stdin.gets.chomp\n @userInput.downcase\n\n #verify the character hasn't already been used \n if @lettersUsed.include?(@userInput) == true\n puts \"You've used #{@userInput} already!\"\n @numOfGuesses = @numOfGuesses + 1\n drawHangMan()\n\n #the letter hasn't already been used and\n #is apart of the word\n elsif @randomWord.include?(@userInput) == true \n puts \"You've gussed a letter!\"\n updateLettersFound()\n drawHangMan()\n\n #the letter isn't apart of the word\n else\n @numOfGuesses = @numOfGuesses + 1\n @lettersUsed.push(@userInput)\n drawHangMan()\n end\n\n puts \"You've made #{@numOfGuesses} out of 10 guesses\"\n winOrLose()\n @userInput = nil\n \n end \n \n end",
"def guess(letter)\n raise InvalidGuessException.new(\"Invalid Guess!\") unless valid_guess?(letter)\n \n if word_has?(letter)\n \tput_letter_on_board(letter)\n else\n wrong_letter(letter) if !@guesses.include? letter\n end\n end",
"def guess(letter)\r\n letter = letter.downcase\r\n num = 0\r\n #iterate through word comparing guessed letter to letter's in the word\r\n @word_arr.each_index do |i| \r\n if @word_arr[i] == letter\r\n #if the letter matches update the game board in the equivalent spot\r\n @gameboard[i] = letter\r\n num += 1\r\n end\r\n end\r\n #add letter to guessed database, and lower amount of guesses by one\r\n @guessed_letters << letter\r\n @guesses -= 1\r\n return num\r\n end",
"def guessing_for_the_win(letter)\n\t\tif repeat_guess(letter)\n\t\telsif guess_correct(letter)\n\t\telse wrong_guess(letter)\n\t\tend \n\n\t\tif @secret_word == @display\n\t\t\tcongrats\n\t\telsif @number_of_guesses > 0 \n\n\t\t\tp \"Keep guessing\"\n\t\telse\n\t\t\tfailure\n\t\tend\n\tend",
"def guess_letters\n guess_array = []\n @current_word.each do\n guess_array << \"_\"\n end\n return guess_array\n end",
"def setguessmatch(letter)\n\t\t@guess_count +=1\t\n\t\t@guessed_letters << letter\n\n\t\t@starting_word.each_with_index do |char,index|\n\t\t\tif char == letter\n\t\t\t\t@guessing_word[index] = char\n\t\t\t\tif starting_word == guessing_word\n\t\t\t\t\t@game_status = true\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend",
"def turn\n\t\t\t@turns += 1\n\t\t\t@guess_letter = gets[0].downcase\n\t\t\tshow_matches\n\t\t\tcheck_win\n\t\tend",
"def getguess guess\r\n\t\t\t\t\t@spin_flag = false\r\n\t\t\t\t if guess.length == 1\r\n\t\t\t\t if check_repeated_choice guess\r\n\t\t\t\t @message = \"Already guessed this letter!\"\r\n\t\t\t\t if @console\r\n\t\t\t\t\t\t\t\t@output.puts \"#{@message}\"\r\n\t\t\t\t\t\t\t\tword_input = take_user_word_input\r\n\t\t\t\t\t\t\t\tvalid = false\r\n\t\t\t\t\t\t\t while !valid do\r\n\t\t if validate_input word_input\r\n\t\t valid = true\r\n\t\t else\r\n\t\t @output.puts \"Invalid input\"\r\n\t\t word_input = take_user_word_input\r\n\t\t end\r\n\t\t\t\t\t\t\t end\r\n\t\t\t\t\t\t\t\tif check_enter word_input\r\n\t\t\t\t\t\t\t\t\t\t@break_flag = true\r\n\t\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t\t getguess word_input\r\n\t\t\t\t\t\t\t\tend\r\n\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t@spin_flag = true\r\n\t\t\t\t end\r\n\t\t\t\t else\r\n\t\t\t\t \t@message=\"Guess a letter from the word/phrase.\"\r\n\t\t\t\t @guess_counter+=1\r\n\t\t\t\t check_guess guess\r\n\t\t\t\t set_guess_analysis guess\r\n\t\t\t\t end\r\n\t\t\t\t success = check_phrase @resulta.join(',').gsub(\",\",\"\")\r\n\t\t\t\t return success ? true : false\r\n\t\t\t\telse\r\n\t\t\t\t\t if check_phrase guess\r\n\t\t\t\t\t\t phrase = @secretword.chars\r\n\t\t\t\t\t\t i = 0\r\n\t\t\t\t\t\t while i < phrase.length do\r\n\t\t\t\t\t\t\t\t\t\t@resulta[i] = phrase[i]\r\n\t\t\t\t\t\t\t\t\t\ti += 1\r\n\t\t\t\t\t\t end\r\n\t\t\t\t\t\t return true\r\n\t\t\t\t\t else\r\n\t\t\t\t\t\t @num_guessed = 0\r\n\t\t\t\t\t\t incrementturn\r\n\t\t\t\t\t\t @guess_counter+=1\r\n\t\t\t\t\t\t set_guess_analysis guess\r\n\t\t\t\t\t\t return false\r\n\t\t\t\t\t end\r\n\t\t\t\tend\r\n\t\t\t\tend",
"def correct_guess?(letter)\n if @word_selected.include?(letter)\n if @correct_guesses.empty?\n @correct_guesses << letter\n elsif @correct_guesses.include?(letter)\n puts 'Letter already guessed! try another one!'\n else\n @correct_guesses << letter\n end\n return true\n end\n false\n end",
"def guessed_letters()\n guessed = $bucket.join(\" \") # return a string of guessed letters\nend",
"def check_guess(player_guess, display)\n letter_found = false\n @secret_word.chars.each_with_index do |char, index|\n if char.downcase == player_guess\n display[index] = char\n letter_found = true\n end\n end\n letter_found\n end",
"def start_game\r\n\t puts \"Welcome to Hangman! A secret word has been chosen. You have #{turn_count} guesses to get the word correct. Good luck!\"\r\n\t (@secret_word.size).times { @correct_letters += \"_ \" }\r\n\t puts @correct_letters\r\n\t begin_guessing\r\n\tend",
"def game_board(guess_letter)\r\n\t puts \"\"\t \r\n\t result_index_array = (0 ... @secret_word.length).find_all { |i| @secret_word[i,1] == guess_letter }\r\n\t \r\n\t # Change the output to show a successful guess\r\n\t if result_index_array.size == 0\r\n\t @incorrect_letters += guess_letter\r\n\t\t@incorrect_letters += \", \"\r\n\t else \r\n\t result_index_array.each { |index| @correct_letters[2*index] = guess_letter }\r\n end\r\n\t \r\n\t # Update variables and check if the game has been won\r\n\t @turn_count -= 1\r\n\t puts @correct_letters\r\n\t #@incorrect_letters.each {|letter| print \"#{letter}, \"}\r\n\t puts \"\\nIncorrect Guesses: #{@incorrect_letters}\"\r\n\t win_game if @correct_letters.count('_') == 0\r\n\t end_turn\r\n\tend",
"def turn\n\t\toutputStatus\n\t\tif @guesses_left < 10\n\t\t\tsaveGame if save?\n\t\tend\n\t\tletter = getLetter\n\t\tif checkLetter(letter)\n\t\t\treplaceLetter(letter)\n\t\telse\n\t\t\twrongGuess(letter)\n\t\tend\n\tend",
"def guess(rand_word)\n puts \"enter a letter\"\n letter = gets.chomp.downcase\n display_word(rand_word,letter)\nend",
"def ask_letter\n letter = Display.ask\n if letter == 'save'\n save_game\n ask_letter\n end\n word_check = @word.map(&:clone)\n check_if_correct(word_check, letter)\n end",
"def play_game\n\n\tword = select_word #call on the method that retrievess a random word\n\n\tConsole_Screen.cls #clear the display area\n\n\tconsonants = get_consonants #call on the method that prompts the player\n\t#to enter a list of consonatns\n\n\tConsole_Screen.cls #clear the display area\n\n\t#call on the method that prompts the player to enter a vowel\n\tvowel = get_vowel\n\n\t#remove blank spaces from the word to create a short version of the word\n\tshortWord = word.gsub(\" \", \"\")\n\n\t#call the method that processes palyer guesses\n\tprompt_for_guess(shortWord, word, consonants, vowel)\n\n\tConsole_Screen.cls #clear the display area\n\nend",
"def match_letters(player_guess) \n indexes_matched = @word_array.each_index.select { |i| @word_array[i] == player_guess}\n for x in indexes_matched do\n @results[x] = player_guess\n end\n end",
"def guess(letter)\n is_letter = /^[a-zA-Z]$/\n if letter.nil? or letter.empty? or not letter.match(is_letter)\n throw ArgumentError \n end\n letter.downcase!\n if self.guesses.include? letter or self.wrong_guesses.include? letter\n return false\n end\n if self.word.include? letter\n self.guesses = self.guesses + letter\n else\n self.wrong_guesses = self.wrong_guesses + letter\n end\n return true\n end",
"def play_new_game\n #get new code word\n @word_master.choose_code_word\n @code_word = @word_master.code_word\n @good_guesses = Array.new(@code_word.length, '_ ')\n #tells you rules\n puts \"Try to figure out the word. If you guess 6 wrong letters, you lose!\"\n #starts playing\n game_loop\n end",
"def check_letters(letter_guessed)\n if @secret_word.include?(letter_guessed)\n @characters_guessed_correctly << letter_guessed\n puts 'you guessed correctly'\n puts replace_correct_letters\n else\n puts 'you guessed wrong'\n @guess_count -= 1\n end\n end",
"def play_letter(letter, y = @cursor.y, x = @cursor.x)\n @moves.add(current_player, modify_letter_input(letter), y, x)\n end",
"def hangman()\n puts \"Let's play a game of hangman!\"\n puts \"To play, you have the guess the word that I am thinking of letter by letter.\"\n puts \"You have to guess the game in less than 20 turns, or you lose!\"\n def game()\n words = [\"chance\",\"gemini\",\"brooklyn\",\"love\",\"family\",\"friend\",\"robot\",\"computer\",\"ruby\",\"javascript\",\"peach\",\"winter\"]\n i = rand(0..words.length).to_i\n random_word = words[i]\n hangman_word = random_word.split(//).to_a\n hidden_word = (hangman_word.map { |letter| letter = \"#\"}).join(\" \")\n puts hidden_word\n guesses_allowed = 12\n player_guesses = []\n while guesses_allowed > player_guesses.length.to_i && guesses_allowed <= 20 || hangman_word.length.to_i >= 0\n puts \"Guess a letter:\"\n player_input=gets.chomp.to_s\n if (hangman_word.include? player_input) == true\n puts \"Woohoo! There is a '#{player_input}' in the word!\"\n hangman_word.delete(player_input.to_s)\n # puts new_hidden_word = (hangman_word.map |letter| letter == \"#{player_input}\" ? letter : \"#{player_input}\").join(\" \")\n elsif (player_guesses.include? player_input) == true\n puts \"You already guessed #{player_input} before.\"\n elsif (hangman_word.include? player_input) == false\n puts \"Sorry! There is no '#{player_input}' in the word!\"\n end\n player_guesses.push(player_input)\n puts \"You have guessed the following letters: #{player_guesses}\"\n puts \"You have #{guesses_allowed} guesses left.\"\n guesses_allowed -= 1\n if hangman_word.length.to_i == 0\n puts \"Congratulations! You have won!\"\n break\n elsif player_input == \"exit\" \n puts \"You've quit the game...\"\n break\n elsif guesses_allowed == 0 \n puts \"GAME OVER. You've run out of chances!\"\n break\n end\n end\n end\n game()\nend",
"def guess?(letter)\n if !self_is_letter?(letter)\n puts \"Not a letter!\"\n return false\n end\n if @word.include? letter\n if(@word.count(letter) > 1)\n while(@word.include? letter)\n puts \"Hit this while loop\"\n index = @word.index(letter)\n @word.slice!(index,0)\n @word[index] = '_'\n\n puts \"Word\" + @word\n @guessedWord.slice!(index,0)\n @guessedWord[index] = letter\n\n end\n else\n index = @word.index(letter)\n\n @guessedWord.slice!(index,0)\n @guessedWord[index] = letter\n\n\n\n end\n\n\n output_word()\n return true\n end\n p \"Word does not contain #{letter}\"\n @health -= 1\n p \"you have #{@health} tries left\"\n return false\n end",
"def check_guess(letter)\n\t\t# If the guessed letter is in the word, replace \"_\" in the guess variable with the letter in the right spot\n\t\t@word.each_with_index do |l, i|\n\t\t\tif l == letter\n\t\t\t\t@guess[i] = letter\n\t\t\tend\n\t\tend\n\t\t# If the guessed word and the answer are the same, the user won!\n\t\t# Show message and if the game was previously saved, delete it\n\t\tif @word.join == @guess\n\t\t\tputs \n\t\t\tshow_board\n\t\t\tputs \"You won!!\"\n\t\t\tif @running_saved_game != nil\n\t\t\t\tover_write_data\n\t\t\tend\n\t\t\tgo_again\n\t\t# Got a letter but didn't win. Get another guess\n\t\telsif @word.include?(letter)\n\t\t\tputs\n\t\t\tputs \"You got a letter!\"\n\t\t\tget_guess\n\t\t# Letter wasn't in word, put letter in missed letter variable and guess again\n\t\telse\n\t\t\tputs \n\t\t\tputs \"No #{letter}'s.\"\n\t\t\t@wrong_letters.sub!(\"_\", letter)\n\t\t\t@turn += 1\n\t\t\tget_guess\n\t\tend\n\tend",
"def play\n puts \"I have generated a beginner sequence with four elements made up of: (r)ed,\n (g)reen, (b)lue, and (y)ellow. Use (q)uit at any time to end the game.\n What's your guess?\"\n mastermind = Game.new\n mastermind.game_solution\n amount_of_guesses = 0\n guess = gets.chomp\n user_guess = []\n user_guess << guess.chars\n amount_of_guesses += 1\n mastermind.check_for_correct_letters(user_guess)\n mastermind.check_for_correct_indexes(user_guess, mastermind.solution)\n until guess == \"q\"\n if guess == \"c\"\n puts \"The solution is #{mastermind.solution}\"\n break\n elsif guess.length > 4\n puts \"Your guess was too long.\"\n elsif guess.length < 4\n puts \"Your guess was too short.\"\n elsif guess != mastermind.solution\n puts \"You had #{mastermind.correct_letters} correct colors with #{mastermind.correct_indexes}\n in the correct position.\"\n break\n elsif guess == mastermind.solution.to_s\n \"You won! You guessed #{guess}. You had #{mastermind.correct_letters} correct\n colors in #{mastermind.correct_indexes} correct positions.\n You guessed #{amount_of_guesses.to_s} times.\"\n break\n else\n puts \"Goodbye, quitter.\"\n end\n end\nend",
"def process_guess(letter)\n\n\t\tletter = letter.downcase\n\n\t\tif @prev_guesses.include? letter\n\t\t\tputs \"\\\"#{letter}\\\" has already been guessed\"\n\t\t\tprint_status\n\t\t\treturn false \n\t\telse\n\t\t\t@prev_guesses << letter\n\t\t\tdecrement_guesses\n\t\tend\n\n\t\tif @original_word.include? letter\n\t\t\tupdate_gameboard(letter)\n\t\t\tprint_status\n\t\t\ttrue\n\t\telse\n\t\t\tprint_status\n\t\t\tfalse\n\t\tend\n\tend",
"def failed_guess(letter)\r\n @failed_guesses << letter\r\n @attempts_left -= 1\r\n end",
"def playerguess\n @guess = []\n puts \"What do you think the first colour is?\"\n @guess[0] = gets.chomp.downcase\n #input_validator(@guess[0])\n puts \"What do you think the second colour is?\"\n @guess[1] = gets.chomp.downcase\n #input_validator(@guess[1])\n puts \"What do you think the third colour is?\"\n @guess[2] = gets.chomp.downcase\n #input_validator(@guess[2])\n puts \"What do you think the fourth colour is?\"\n @guess[3] = gets.chomp.downcase\n #input_validator(@guess[3])\n end",
"def wrong_guess(letter)\n\t\tif !@attempted_letters.include?(letter)\n\t\t\tputs \"WRONG....\"\n\t\t\t@attempted_letters << letter\n\t\t\t@number_of_guesses -= 1 \n\t\t\tp @number_of_guesses\n\t\t\tp @display\n\t\t\tp \"you have #{@number_of_guesses} guesses left...\"\n\t\t\treturn true\n\t\tend\n\tend",
"def win\n puts \"\\n\"\n @letters_guessed_array = @correct_word_array\n puts @letters_guessed_array.join(\" \")\n puts \"\\n\"\n puts \"You have guess the whole word correctly! You have saved\"\n puts \"this man from a hanging!\"\n end",
"def guess?(letter)\n correct = false\n @@secret.length.times do |i|\n if (@@secret[i] == letter && @@progress[i] == '_')\n @@progress[i] = letter\n correct = true\n end\n end\n @@incorrect << letter if !correct\n @@guesses += 1\n puts(\"secret: #{@@secret}\")\n correct\n end",
"def respond_to_guess(guess)\n\t\t@guessed_letters << guess\n\t\t@secret_word.split(\"\").include?(guess)\t\n\tend",
"def begin_guessing\r\n\t while @turn_count > 0 do\r\n\t puts \"\\nPlease enter 'guess' if you would like to guess the word. Otherwise, please enter a single letter guess.\"\r\n\t guess_input = gets.chomp\r\n\t\t\r\n\t\t# Handles the case if the user wants to guess the word\r\n\t\tif guess_input.downcase == \"guess\"\r\n\t\t puts \"\\nPlease enter your guess.\"\r\n\t\t full_guess = gets.chomp\r\n\t\t full_guess.downcase!\r\n\t\t if full_guess == @secret_word \r\n\t\t win_game \r\n\t\t else \r\n\t\t @turn_count -= 1\r\n\t\t puts \"\\nIncorrect guess.\"\r\n\t\t\tend_turn\r\n\t\t end\r\n\t\t \r\n\t\t# Handles the case if the user wants to guess a letter\r\n\t\telse\r\n\t guess_letter = guess_input[0].downcase\r\n\t game_board(guess_letter)\r\n\t\tend\r\n\t end\r\n\t lose_game if @turn_count == 0\r\n\tend",
"def match_letters #handle_guess\n\t\tindexes_matched = @word_array.each_index.select { |i| @word_array[i] == @guess}\n\n\t\tfor x in indexes_matched do\n\t\t\t@result_array[x] = guess\n\t\tend\n\n\t\tputs @result_array\n\tend",
"def match_letters #handle_guess\n\t\tindexes_matched = @word_array.each_index.select { |i| @word_array[i] == @guess}\n\n\t\tfor x in indexes_matched do\n\t\t\t@result_array[x] = guess\n\t\tend\n\n\t\tputs @result_array\n\tend",
"def check_guess(input)\n @guessed_letters.push(input)\n if @secret_word.match?(input)\n @secret_word.split(//).each_with_index { |char, index| @guessed_word[index] = char if char == input }\n else\n puts 'Incorrect'\n @guesses_left -= 1\n @wrong_letters.push(input)\n end\n end",
"def guess(guess)\r\n\t\t# Make sure the guess is either a letter or the whole word\r\n\t\tif guess.length != 1 && guess.length != @win_word.length\r\n\t\t\tp @remaining_guesses.to_s + \" guesses left\"\r\n\t\t\tp \"Guess a letter, or the complete word!\"\r\n\t\t# check for repeated guesses\r\n\t\telsif @past_guesses.include? guess\r\n\t\t\tp @remaining_guesses.to_s + \" guesses left\"\r\n\t\t\tp @hint\r\n\t\t\tp \"You guessed that already!\"\r\n\t\t# check if they guessed the entire word correctly\r\n\t\telsif guess == @win_word\r\n\t\t\twin\r\n\t\t# if the letter is not in the word\r\n\t\telsif !@win_word.include? guess\r\n\t\t\t# Add guess to arrayof past guesses\r\n\t\t\t@past_guesses << guess\r\n\t\t\tif @remaining_guesses == 1\r\n\t\t\t\tlose\r\n\t\t\telse\r\n\t\t\tguesses_remaining\r\n\t\t\tp @remaining_guesses.to_s + \" guesses left\"\r\n\t\t\tp @hint\r\n\t\t\tp \"Sorry, try again!\"\r\n\t\t\tend\r\n\t\t# if the letter is in the word\r\n\t\telsif @win_word.include? guess\r\n\t\t\t# Add guess to arrayof past guesses\r\n\t\t\t@past_guesses << guess\r\n\t\t\tguesses_remaining\r\n\t\t\tp @remaining_guesses.to_s + \" guesses left\"\r\n\t\t\tupdate_hint(guess)\r\n\t\t\tif @hint_str == @win_word\r\n\t\t\t\twin\r\n\t\t\telse\r\n\t\t\t\tp \"Nice guess!\"\r\n\t\t\tend\r\n\t\telse\r\n\t\t\tp \"Error\"\r\n\t\tend\r\n\r\n\tend",
"def respond_to_letter_guess(letter)\n indices_matching_letter = []\n i = 0\n while i < @secret_word.length\n if @secret_word[i] == letter\n indices_matching_letter << i\n end\n\n i += 1\n end\n\n indices_matching_letter\n end",
"def prompt(output_array, unmatch_array, word)\n puts \"\\nGuess a letter.\"\n letter = gets.chomp.downcase\n\n if letter =~ /[A-Za-z]/ || letter == \" \" || letter == \"-\"\n else\n puts \"Incorrect input. Try again.\"\n prompt(output_array, unmatch_array, word)\n end\n\n#verify if a string entered by the user is equal to the word\n if letter == word\n puts \"You have won the game!\" \n exit\n end\n\n#verify if user's guess has already been entered.\n output_array.each do |e|\n if letter == e\n puts \"This character has been entered.\"\n prompt(output_array, unmatch_array, word)\n end\n end\n\n#verify if the user's guess has already been entered (in the unmatch_array)\n unmatch_array.each do |ea|\n if letter == ea\n puts \"This character has already been entered.\"\n prompt(output_array, unmatch_array, word)\n end\n end\n return letter\nend",
"def guess char\n #get 1st char\n \n if char.nil?\n raise ArgumentError, 'Argument is not string' \n return false\n end\n if char.length != 1\n raise ArgumentError, 'Argument is not string'\n return false\n end \n if char.match(/[a-zA-Z]/) == nil\n raise ArgumentError, 'Argument is not string' \n return false\n end\n \n pick = char.chr.downcase\n\n #catch replicant entries\n if @guesses.match(\"#{pick}\") != nil\n # @word_with_guesses << \"You have already used that letter\"\n return false\n end \n \n if @wrong_guesses.match(\"#{pick}\") != nil\n# @word_with_guesses << \"You have already used that letter\"\n return false\n end \n \n #actual match\n if @word.match(\"#{pick}\") != nil\n guesses << pick # 1st char\n else\n wrong_guesses << pick # \n @attempt += 1\n end\n \n # build up guess string i.e. \"----a-e\"\n @word_with_guesses = '';\n @check_win_or_lose = :win\n word.each_char { |a|\n if @guesses.match(\"#{a}\") != nil \n @word_with_guesses << a\n else\n @word_with_guesses << '-'\n @check_win_or_lose = :play\n end\n }\n \n #check game status\n if @attempt > 6\n @check_win_or_lose = :lose\n end\n \n return true\n end",
"def play\n\t\tprocessed = process_guesses(@user_guesses, @word)\n\t\tboard = draw(processed)\n\t\tinput = get_input\n\t\t@user_guesses << input\n\t\t@num_guesses -= 1\n\t\tresult = game_over?\n\t\tif result[:over]\n\t\t\tputs \"Game Over!\\n#{result[:message]}\"\n\t\t\tputs \"Word was #{@word}\"\n\t\t\treturn @controller.play_again\n\t\telse\n\t\t\treturn play\n\t\tend\n\n\tend",
"def guess_progress(user_guess)\n @letter_found = false\n check_letter(user_guess)\n\n @secret_array.each_index do |i|\n if !@letter\n puts \"Invalid input. Please input a letter\"\n @letter_found = true\n break\n elsif @secret_array[i] == user_guess \n @display_array[i] = \" #{user_guess} \"\n @letter_found = true\n end\n end\n\n puts \"Sorry. '#{user_guess}' is not in the secret word\" if !@letter_found\n\n if !check_finish\n increment_guess(user_guess)\n end \n\n @display_array\n @is_over\n end",
"def include_letter(word, letter)\n index = 0 \n if @letter_bank.include?(letter) \n puts \"You already tried this letter\"\n else \n word.each_char do |l|\n if l == letter\n @blanks[index] = letter\n end \n index += 1\n end \n @guess_count -= 1 \n @letter_bank << letter\n end \n puts \"You have #{guess_count} guesses left\"\n p @blanks\n end",
"def guess(letter)\n \n raise ArgumentError if letter.nil? ## Raise an error if the letter is null.\n raise ArgumentError if letter == '' ## Raise an error if the user entered an empty string. \n raise ArgumentError if !letter.match(/[a-zA-Z]/) ## Raise an error is the user entered a letter that is not in the alphabet.\n\n \n letter.downcase!\n \n # If word includes letter\n if(word.include? letter)\n # And the letter isnt already in guess\n unless (guesses.include? letter)\n # Add guessed word to guesses\n guesses.concat(letter)\n \n # For test case 14\n for i in 0..word.length do\n # If the guessedLetter is in the string, replace it with the guessed letter\n if(letter == word[i])\n word_with_guesses[i] = letter\n end\n \n end\n \n # If guessed letters match word set to win\n if(word_with_guesses == word)\n @check_win_or_lose = :win\n end\n \n return true # return true valid guess\n end #end unless\n return false # invalid guess false\n else\n unless (wrong_guesses.include? letter)\n # Add the guessed letter to the list of incorrected guesses\n wrong_guesses.concat(letter)\n \n # Wrong guesses greater than 7 set win or loose to loose\n if(@wrong_guesses.length>=7)\n @check_win_or_lose = :lose\n end\n \n return true\n end # end unless\n return false # invalid guess\n end # end for \n end",
"def play\n while @tries.positive?\n print_guesses_remaining\n print_used_letters\n print_word\n\n input = scan_letter\n\n result = process_letter(input)\n\n if %w[save exit].include? result\n process_forced_exit(result)\n return\n end\n\n next unless win?\n\n print_word\n puts 'You won!'.green\n return\n end\n\n puts \"You lost! The word was #{@key}\".red\n end",
"def checkLetter(letter)\n @word.split(\"\").each_with_index do |item, index|\n if item == letter\n @guess[index] = letter\n end\n end\n puts @guess\nend",
"def guess_letter?(letter)\r\n\r\n\t\t#Add 1 to the total number of guesses in game IF not already guessed (in the guesses array)\r\n\t\tif @guesses.index(letter) == nil\r\n\t\t\t@guesses << letter\r\n\t\t\t@num_of_guesses += 1\r\n\t\tend\r\n\r\n\t\t#If the letter exists (aka returns valid index)\r\n\t\t# 1. Loop through letters in word and compare to the guessed letter\r\n\t\t# 2. If guessed letter = original letter in word, set board = to letter in that index\r\n\t\t# 3. Return True\r\n\t\t#Else if the letter does not exist in word array\r\n\t\t# 1. Return False\r\n\t\tif @word_array.index(letter)\r\n\t\t\tindex = 0\r\n\t\t\t@word_array.each do|i|\r\n\t\t\t\tif letter == i\r\n\t\t\t\t\t@board_array[index] = letter\r\n\t\t\t\tend\r\n\t\t\t\tindex+=1\r\n\t\t\tend\r\n\t\t\ttrue\r\n\t\telse\r\n\t\t\tfalse\r\n\t\tend\r\n\tend",
"def prompt_for_guess(shortWord, word, consonants, vowel)\r\n\r\n Console_Screen.cls #Clear the display area\r\n\r\n consonants.push(vowel) #To make things easy, add the vowel to the\r\n #list of consonants\r\n\r\n wordArray = word.split(\" \") #Split the secret word into an array\r\n\r\n i = 0 #Initialize index variable to zero\r\n\r\n #Loop once for each letter in the word (stored in an array)\r\n wordArray.each do |letter|\r\n\r\n match = false #Initialize the variable with a starting value of false\r\n\r\n #Loop once for each consonant stored in the consonants array\r\n consonants.each do |character|\r\n\r\n #Compare the current character from the consonants array to the\r\n #current letter in the wordArray array\r\n if character == letter then\r\n match = true #Set variable value to indicate a match\r\n break #Terminate loop execution when a match occurs\r\n end\r\n\r\n end\r\n\r\n #If there is no matching character in the consonants array for the\r\n #current letter in the wordArray array, replace that letter in the\r\n #wordArray with an underscore character\r\n if match == false then\r\n wordArray[i] = \"_\" #Replace the current character with an\r\n end #underscore\r\n\r\n i = i + 1 #Increment the variable's value by 1\r\n\r\n end\r\n\r\n #Once the contents of the array have been formatted with underscores,\r\n #convert the contents of the array back into a word\r\n word = wordArray.join(\" \")\r\n\r\n #Allow the player up to three guesses\r\n 3.times do |i| #i equals 0 on the first iteration of the loop\r\n\r\n Console_Screen.cls #Clear the display area\r\n\r\n #Prompt the player to try to guess the secret word\r\n puts \"I am thinking of a word.\\n\\n\\n\\n\\n\\n\"\r\n print \"Here is your clue: \" + word + \"\\n\\n\\n\\n\\n\\n\\n\\n\"\r\n print \"What do you think this word is? \"\r\n reply = STDIN.gets #Collect the player's reply\r\n reply.chop! #Remove the end of line marker\r\n reply = reply.upcase #Convert the reply to all uppercase\r\n\r\n #Analyze the players guess\r\n if reply == shortWord then #The player's guessed the secret word\r\n\r\n Console_Screen.cls #Clear the display area\r\n print \"Correct! Press Enter to continue.\"\r\n Console_Screen.pause #Pause the game\r\n break #Terminate the execution of the loop\r\n\r\n else #The player did not guess the secret word\r\n\r\n Console_Screen.cls #Clear the display area\r\n\r\n #Display a message based on how many turns remain\r\n if i == 1 then\r\n puts \"You entered: \" + reply.upcase #display user answer\r\n print \"Wrong! You have one guess left. Press Enter to \" +\r\n \"try again.\"\r\n elsif i == 2\r\n puts \"You entered: \" + reply.upcase #display user answer\r\n shortWord = shortWord.downcase #converts word to lowercase\r\n print \"Sorry, you lose.\\n\\n\"\r\n print \"The word was \" + shortWord.sub(/^./) {$&.upcase} +\r\n #regex reads as follows: substitute \"beginning\" for \"anything\"\r\n #'contains complete matched text of uppercase= $&.upcase'\r\n #method .capitalize would accomplish this as well\r\n \". Press Enter to continue.\"\r\n else\r\n puts \"You entered: \" + reply.upcase #display user answer\r\n print \"Wrong! Press Enter to try again.\"\r\n end\r\n\r\n Console_Screen.pause #Pause the game\r\n\r\n end\r\n\r\n end\r\n\r\n end",
"def display_game(word, guesses, chances)\n puts \"\\n***********************************\"\n puts \"Your word: #{word}\"\n puts \"\\nChances left: #{chances}\"\n puts \"Your guesses: #{guesses_s(guesses)}\"\n puts \"Enter a letter: \"\nend",
"def guessed_wrong_letter()\n if $hidden_word_arr.exclude?($input)\n $guessed.append($input)\n end\n end",
"def check_letter(input_letter)\n # Each time we check, the number of guesses is increased \n @guess_count += 1\n \n # Transform the words into arrays for convenience\n arr_word_to_guess = @word_to_guess.split('') \n arr_guessed_word = @guessed_word.split('') \n \n # Search for the input_letter in arr_word_to_guess\n index_found = arr_word_to_guess.each_index.select{|i| arr_word_to_guess[i] == input_letter}\n \n if (index_found == []) then\n return false \n else \n # if the letter is found, update the guessed word\n n_found = index_found.size\n i = 0 \n n_found.times do \n arr_guessed_word[index_found[i]] = input_letter\n i += 1\n end\n @guessed_word = arr_guessed_word.join('')\n return true\n end \n end",
"def guess_letter\n @unused_letters.pop\n end",
"def get_letter() \n loop do\n puts \"Please enter a letter.\"\n $input = gets.chomp\n $input = $input.downcase\n if $input.count(\"a-z\") == 0\n puts \"\"\n puts \"Sorry, that isn't a letter!\"\n elsif $input.size > 1\n puts \"\"\n puts \"You entered too many letters!\"\n elsif $guessed.exclude?($input) && $hidden_word_arr.exclude?($input)\n break\n else\n puts \"\"\n puts \"You already guessed that one!\"\n end\n end \n end"
] |
[
"0.7819657",
"0.74802244",
"0.74758935",
"0.7473382",
"0.7470513",
"0.7463379",
"0.7428028",
"0.74274343",
"0.742174",
"0.7416329",
"0.7352845",
"0.73427355",
"0.7332662",
"0.73032117",
"0.7283592",
"0.72802657",
"0.72511613",
"0.7247099",
"0.72414386",
"0.7233034",
"0.7227532",
"0.722172",
"0.72089607",
"0.7203208",
"0.7199962",
"0.7180056",
"0.71756893",
"0.71599954",
"0.71543646",
"0.71529865",
"0.7150731",
"0.7149049",
"0.71456665",
"0.7115167",
"0.7107585",
"0.70755416",
"0.70696723",
"0.7062845",
"0.705308",
"0.7050898",
"0.7049564",
"0.7042893",
"0.70308495",
"0.7030005",
"0.7029823",
"0.70191973",
"0.7017645",
"0.7014599",
"0.7004729",
"0.7004546",
"0.6995098",
"0.6978762",
"0.6971258",
"0.6964538",
"0.6935847",
"0.6922601",
"0.6913209",
"0.6909651",
"0.68922085",
"0.68797785",
"0.68767995",
"0.68664044",
"0.6835535",
"0.68354726",
"0.6834729",
"0.68305",
"0.68210894",
"0.6820403",
"0.6814158",
"0.6812437",
"0.68118274",
"0.67936605",
"0.6791754",
"0.6768164",
"0.6768104",
"0.67625487",
"0.67568576",
"0.6739096",
"0.6738611",
"0.6737566",
"0.67340004",
"0.67340004",
"0.6728206",
"0.6723809",
"0.6720386",
"0.67180157",
"0.6714404",
"0.6708003",
"0.67020065",
"0.6697147",
"0.6678812",
"0.66746557",
"0.6662716",
"0.6654334",
"0.665143",
"0.66490734",
"0.66395724",
"0.66372025",
"0.6635355",
"0.6627052"
] |
0.81299454
|
0
|
the method merges the letters to the word
|
def word
@letters.join
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def insertions\n new_words = []\n @words.each do |word|\n @word = word || '' \n (length + 1).times do |i|\n ('a'..'z').each { |c| new_words << \"#{@word[0...i]}#{c}#{@word[i..-1]}\" }\n end\n end\n new_words\n end",
"def ordered_letters\n @word.chars.sort.join\n end",
"def get_word\n @lettercollection.push(@string_as_array[@i])\n @lettercollection.join('')\nend",
"def insertions word\n n = word.length\n new_words = []\n (n+1).times {|i| ('a'..'z').each {|l| new_words << word[0...i]+l.chr+word[i..-1] } }\n new_words\n end",
"def replacements word\n n = word.length\n new_words = []\n n.times {|i| ('a'..'z').each {|l| new_words << word[0...i]+l.chr+word[i+1..-1] } }\n new_words\n end",
"def word_substituter (tweet=\"some thing need to be shorten, like two too\")\n tweet= tweet.strip\n temp_a = tweet.split(\" \")\n words_can_b_sh = dictionary.keys\n #puts words_can_b_sh\n temp = \"\"\n# puts temp_a\n temp_a.each do |word|\n if words_can_b_sh.include?(word.downcase)\n temp << dictionary[word.downcase]\n else\n temp << word\n end\n temp << \" \"\n end\n temp.strip\nend",
"def edits1 word\n n = word.length\n deletion = (0...n).collect {|i| word[0...i]+word[i+1..-1] }\n transposition = (0...n-1).collect {|i| word[0...i]+word[i+1,1]+word[i,1]+word[i+2..-1] }\n alteration = []\n n.times {|i| @letters.each_byte {|l| alteration << word[0...i]+l.chr+word[i+1..-1] } }\n insertion = []\n (n+1).times {|i| @letters.each_byte {|l| insertion << word[0...i]+l.chr+word[i..-1] } }\n result = deletion + transposition + alteration + insertion\n result.empty? ? nil : result\n end",
"def process_word word\n const_match = /^[BCDFGHIJKLMNPQRSTVWXYZbcdfhhtjklmnpqrstvwxyz]+/.match(word)\n letter_match = /^[a-zA-Z]+/.match(word) #Match letters only\n other_chars = word[letter_match.to_s.length..-1]\n if const_match.to_s.length > 0\n return const_trans(letter_match.to_s, const_match) + other_chars\n else\n return vowel_trans(letter_match.to_s) + other_chars \n end\n \n end",
"def replacements\n new_words = []\n @words.each do |word|\n @word = word || '' \n length.times do |i|\n ('a'..'z').each { |c| new_words << \"#{@word[0...i]}#{c}#{@word[i+1..-1]}\" }\n end\n end\n new_words\n end",
"def spell_out word6\n word6.downcase.split(\"\").join(\"-\")\nend",
"def code_name(word)\n#set a new word to an empty string, we are going to fill it using the rest of the loop:\n\tnew_word = \"\"\n#start index at 0\n\ti = 0\n#loop through the string:\n\twhile i < word.length\n#letter is going to be the index of the word put in, starting at the 0 position until the end of the word's length\n\tletter = word[i]\n#if a space is found, add a space to the new word\n\t\tif letter == ' '\n\t\tnew_word += ' '\n#everything else, find the next letter or the next vowel or next edge case, and add it to the new word\n\t\telse\n\t\t letter == letter.downcase\n\t\tnew_word += vowels_and_edges(letter)\n \t\tend\n \t\ti += 1\n end\n#should result in a new word, when all strings are pieced together \n new_word\nend",
"def nato(word)\n original = []\n value = ''\n letters = {\n \"A\"=> \"Alpha\", \"B\"=> \"Bravo\", \"C\"=> \"Charlie\",\n \"D\"=> \"Delta\", \"E\"=> \"Echo\", \"F\"=> \"Foxtrot\",\n \"G\"=> \"Golf\", \"H\"=> \"Hotel\", \"I\"=> \"India\",\n \"J\"=> \"Juliett\",\"K\"=> \"Kilo\", \"L\"=> \"Lima\",\n \"M\"=> \"Mike\", \"N\"=> \"November\",\"O\"=> \"Oscar\",\n \"P\"=> \"Papa\", \"Q\"=> \"Quebec\", \"R\"=> \"Romeo\",\n \"S\"=> \"Sierra\", \"T\"=> \"Tango\", \"U\"=> \"Uniform\",\n \"V\"=> \"Victor\", \"W\"=> \"Whiskey\", \"X\"=> \"X-ray\",\n \"Y\"=> \"Yankee\", \"Z\"=> \"Zulu\"\n }\n arr = word.split('')\n arr.each do |letter|\n value = letters.values_at(letter.upcase)\n original.concat(value)\n end\n original.join(' ')\nend",
"def word_substituter(tweet)\n tweet.split.map { |word| \n dictionary[word.downcase] || word }.join(\" \")\n end",
"def silly_talk(sent)\n vowels = 'aeiou'\n words = sent.split\n new_words = []\n\n words.each do |word|\n if vowels.include?(word[-1])\n new_words << word + word[-1] \n else \n new_words << word.split('').map { |c| vowels.include?(c) ? (c + 'b' + c) : c }.join\n end \n end \n\n new_words.join(' ')\n\nend",
"def join_alphabets(input)\n\toutput = \"\"\n\tinput.split(\"\").each do |letter|\n\t\tif (letter.ord >= 65) && (letter.ord <= 90)\n\t\t\toutput += letter \n\t\tend\n\tend\n\treturn output\nend",
"def word_substituter(tweet) \n\tfinal_tweet_array = []\n\ttweet_array = tweet.split(\" \")\n\tkeys = dictionary.keys\n\ttweet_symbols = []\n\ttweet_array.each do |word|\n\t\ttweet_symbols << word.to_sym\n\tend\n\tshortened_tweet_array = []\n\ttweet_symbols.each do |symbol|\n\t\tif keys.include?(symbol)\n\t\t\tsymbol = dictionary[symbol]\n\t\t\tshortened_tweet_array << symbol\n\t\telse\n\t\t\tshortened_tweet_array << symbol\n\t\tend\n\tend\n\tshortened_tweet_array.each do |symbol|\n\t\tfinal_tweet_array << symbol.to_s\n\tend\n\tfinal_tweet_array.join(\" \")\nend",
"def abbreviate_sentence(sent)\n # Write your code here\n empty_array = []\n sent.chars.each do |element|\n if element.length > 4\n element.each do |letters|\n letters.gsub(/[aeiou]/i, \" \" )\n letters << empty_array\n end\n end\n end\n p empty_array.join(\"\")\nend",
"def single_word(word)\n if word[0] =~ /[aeiou]/i\n word + \"way\"\n else\n # nueva condicionante para palabras de puras consonantes sin vocales. ej: by\n if word.split(/([aeiou].*)/).length > 1\n # Parte palabra en 2 y lo mete en un array. 1er elemento es de consonat(es) iniciales, 2o la parte restante de la palabra a partir de e incluyendo la primera vocal\n word.split(/([aeiou].*)/)[1] + word.split(/([aeiou].*)/)[0] + \"ay\"\n else\n word.split(/([aeiou].*)/)[0]\n end\n end\nend",
"def add_letter(word, index, let)\n word.split(\"\").insert(index,let).join\nend",
"def encode\n @word.chars.map do |letter|\n index = @abc.index(letter) \n @abc_reverse[index]\n end.join\n \n end",
"def get_word_for_print(letters, good_letters)\n result = ''\n letters.each do |item|\n result += if good_letters.include?(item)\n item + ' '\n else\n '__ '\n end\n end\n result\n end",
"def combine_anagrams(words)\n\n\twords.group_by{|word| word.downcase.chars.sort}.values\n\t\nend",
"def edits1(word)\n \n deletes = []\n i = 0\n while i < word.length\n deletes_word = word\n deletes << deletes_word.slice(0,i) + deletes_word.slice(i+1, word.length)\n i+=1\n end\n #all strings obtained by deleting a letter (each letter)\n transposes = []\n i = 0\n while i < word.length\n transpose_word = word\n letter_to_replace = transpose_word[i]\n\n transpose_word[i] = transpose_word[i-1]\n transpose_word[i-1] = letter_to_replace\n transposes << transpose_word\n\n transpose_word = word\n letter_to_replace = transpose_word[i]\n\n if(transpose_word[i+1] != nil)\n transpose_word[i] = transpose_word[i+1]\n transpose_word[i+1] = letter_to_replace\n transposes << transpose_word\n end\n\n i+=1\n end\n #all strings obtained by switching two consecutive letters\n inserts = []\n word\n inserts(word)\n\n # all strings obtained by inserting letters (all possible letters in all possible positions)\n replaces = []\n #all strings obtained by replacing letters (all possible letters in all possible positions)\n\n #return (deletes + transposes + replaces + inserts).to_set.to_a #eliminate duplicates, then convert back to array\n end",
"def concatenate_words(sentence)\nend",
"def word_substituter(tweet)\n newtweet = tweet.split \n dictionary.each do |phrase, subs|\n newtweet.map! do |word|\n if word == phrase\n word = subs\n elsif \n word == phrase.capitalize\n word = subs\n else \n word = word\n end\n end\n end \n newtweet.join(\" \")\nend",
"def edits1(word) \n deletes = [] \n #all strings obtained by deleting a letter (each letter) \n for i in 0..word.length-1\n\ttemp = word.dup\n\ttemp.slice!(i)\n\tdeletes.push(temp)\n end \n\n transposes = []\n #all strings obtained by switching two consecutive letters\n loop_count = word.length-2\n if loop_count > 0\n for i in 0..loop_count\n\ttemp = word.dup\n \ttemp[i+1] = word[i]\t\n\ttemp[i] = word[i+1]\n\ttransposes.push(temp)\n end\n end \n\n inserts = []\n # all strings obtained by inserting letters (all possible letters in all possible positions)\n for i in 0..word.length\n ALPHABET.each_char do |c|\n temp = word.dup\n temp = temp.insert(i,c)\n inserts.push(temp)\n end\n end\n\n replaces = []\n #all strings obtained by replacing letters (all possible letters in all possible positions)\n for i in 0..word.length-1\n ALPHABET.each_char do |c|\n temp = word.dup\n temp[i] = c\n replaces.push(temp)\n end\n end\n\n return (deletes + transposes + replaces + inserts).to_set.to_a #eliminate duplicates, then convert back to array\n end",
"def unite_words\n _, a_rest, a_word = %r{^(.* )?(\\w+)$}.match(a.text).to_a # a ends with word character\n _, b_word, b_rest = %r{^(\\w+\\s*)(.* )?$}.match(b.text).to_a # b starts with word character\n\n if a_word && b_word\n if a_word.length > b_word.length\n shift_backward(b_word)\n else\n shift_forward(a_word)\n end\n end\n end",
"def word_with_guesses\n word_to_display = ''\n self.word.chars do |letter|\n # if we find letter in the word to be in guessed letters\n # replace it with the actual letter\n if self.guesses.include? letter\n word_to_display += letter\n else\n word_to_display += '-'\n end\n end\n return word_to_display\n end",
"def word_substituter(tweet)\n new_arr = []\n tweet_arr = tweet.split\n keys_arr = dictionary.keys\n tweet_arr.each do |word|\n if keys_arr.include?(word)\n new_arr << dictionary[word]\n else\n new_arr << word\n end\n end\n return new_arr.join(\" \")\nend",
"def spell_out (foo)\n foo.downcase.split(\"\").join(\"-\")\n end",
"def add_letter(letter, locations)\n # for each occurrence of a letter, add the letter to the correct location in $build-word\n locations.each { |location| $build_word[location] = letter }\n word_test() # then run word_test()\nend",
"def translate words\n\tarray = words.split \n\ti = 0\n\ttotal = \"\"\n\twhile i < array.length\n\t\tstring = array[i]\n\t\tif string[0] =~ /[aeiou]/\n\t\t\tresult = string + \"ay\"\n\t\telse\n\t\t\tletters = \"\"\n\t\t\tcounter = 0\n\t\t\tnumberConsanants = 0\n\t\t\twhile counter < string.length\n\t\t\t\tif string[counter] =~ /[aeiou]/\n\t\t\t\t\tbreak\n\t\t\t\telse\n\t\t\t\t\tletters = letters + string[counter]\n\t\t\t\t\tif string[counter] == 'q' && string[counter+1] == 'u'\n\t\t\t\t\t\tletters = letters + 'u'\n\t\t\t\t\t\tnumberConsanants = numberConsanants + 1\n\t\t\t\t\tend\n\t\t\t\t\tnumberConsanants = numberConsanants + 1\n\t\t\t\tend\n\t\t\t\tcounter = counter + 1\n\t\t\tend\n\t\t\tresult = string.slice(numberConsanants, string.length) + letters + \"ay\"\n\t\tend\n\t\ttotal = total + result\n\t\tif i != array.length - 1\n\t\t\ttotal = total + \" \"\n\t\tend\n\t\ti = i + 1\n\tend\n\ttotal\nend",
"def create_display(word, letters)\n word.upcase.split(\"\").map{|letter| letters.include?(letter) ? letter : \"_\"}.join(\" \")\nend",
"def find_adjacent_words(word)\n alphabet = ('a'..'z').to_a\n all_adjacent_words = []\n\n word.each_char.with_index do |char, i|\n alphabet.each do |alpha_letter|\n dup_word = word.dup\n dup_word[i] = alpha_letter\n all_adjacent_words << dup_word if @dictionary.include?(dup_word)\n end\n end\n\n all_adjacent_words.uniq \n end",
"def combine_anagrams(words) \r\n anagrams = words.inject(Hash.new()) do |r, word|\r\n key = word.downcase.chars.sort.join\r\n r[key] ||=[]\r\n r[key] << word\r\n r\r\n end\r\n anagrams.values\r\nend",
"def get_word_for_print(letters, good_letters)\n result = \"\"\n\n letters.each do |letter|\n result += if good_letters.include?(letter)\n letter + \" \"\n else\n \"_ \"\n end\n end\n\n result\n end",
"def edits1(word)\n deletes = []\n letters = word.split(\"\")\n letters.each do |c|\n word2 = word\n deletes.push(word2.delete(c))\n end\n\n transposes = []\n for i in 0..word.length-1\n letters = word.split(\"\")\n letters2 = letters\n letters2.insert(i+1 , letters2.delete_at(i))\n transposes.push(letters2.join())\n end\n\n inserts = []\n ALPHABET.split(\"\").each do |c|\n for i in 0..word.length\n letters = word.split(\"\")\n letters2 = letters\n letters2.insert(i,c)\n inserts.push(letters2.join())\n end\n end\n\n replaces = []\n ALPHABET.split(\"\").each do |c|\n\tfor i in 0..word.length-1\n letters = word.split(\"\")\n letters2 = letters\n letters2.delete_at(i)\n letters2.insert(i,c)\n replaces.push(letters2.join())\n end\n end\n\n return (deletes + transposes + replaces + inserts).to_set.to_a #eliminate duplicates, then convert back to array\n end",
"def hackerSpeak(word)\n\tnew_word=''\n\tword.each_char do |c|\n\t\tif c.downcase=='a'\n\t\t\tnew_word=new_word+'4'\n\t\telsif c.downcase=='e'\n\t\t\tnew_word=new_word+'3'\n\t\telsif c.downcase=='i'\n\t\t\tnew_word=new_word+'1'\n\t\telsif c.downcase=='o'\n\t\t\tnew_word=new_word+'0'\n\t\telsif c.downcase=='s'\n\t\t\tnew_word=new_word+'5'\n\t\telse\n\t\t\tnew_word=new_word+ c\t\t\t\t\t\t\n\t\tend\t\n\tend\n\tnew_word\nend",
"def sentencify(words)\n \n words[0] = words[0].chr.upcase << words[0][1..-1]\n words.join(\" \")<<\".\"\nend",
"def eval_ele(word)\n\n formWord = []\n word.each_char.with_index do |let, idx|\n if idx == 0\n formWord << word[idx].upcase\n else\n formWord << word[idx].downcase\n end\n end\n\n return formWord.join(\"\")\n\nend",
"def char_concat(word)\n (1..word.length/2).map {|i| word[i - 1] + word[-i] + i.to_s}.join\nend",
"def word_substituter(string)\ntweet=string.split(\" \")\ni = 0 \nwhile i < tweet.length \nif dictionary.keys.include?(tweet[i].downcase)\ntweet[i] = dictionary[tweet[i].downcase]\nend \ni+=1\nend\ntweet.join(\" \")\nend",
"def add_word(word)\n \n end",
"def add_word(word)\r\n \r\n end",
"def replace(word, letter, ind)\n (word[0...ind] || '') << letter << (word[ind+1..-1] || '')\nend",
"def reverberate(sent) \n vowels = 'aeiou'\n words = sent.split\n new_words = []\n\n\n words.each do |word|\n if word.length < 3 \n new_words << word \n elsif vowels.include?(word[-1].downcase)\n new_words << word + word.downcase\n else\n i = word.length - 1\n while i >= 0 \n if vowels.include?(word[i]) \n new_words << word + word[i .. -1]\n break\n end \n\n i -= 1\n end \n end \n end \n\n new_words.join(' ')\n\nend",
"def combine_anagrams(words) \n # for each word, sort the word to create the \n # signature for the anagrams\n anagram_groups = {}\n words.each do |w|\n key = w.downcase.chars.sort.join\n if anagram_groups[key].nil?\n anagram_groups[key] = [w]\n else\n anagram_groups[key].push(w)\n end\n end\n \n return anagram_groups.values\n\nend",
"def combine_anagrams(words)\r\n\tanagrams = words.group_by { |word| word.chars.sort }.values\t\r\nend",
"def combine_anagrams(words)\r\n\tswords = Array.new\r\n\tnoDups = Array.new\r\n\tgroupWords = Array.new\r\n\tanagrams = Array.new\r\n\twords.each {|word| swords << word.downcase.chars.sort.join}\r\n\tswords.each{|word| noDups << word unless !noDups.index(word).nil? }\r\n\tnoDups.each do|tword|\r\n\t\t\t\t\t\r\n\t\t\t\t\tgroupWords = Array.new\r\n\t\t\t\t\twords.each {|word| groupWords << word unless word.downcase.chars.sort.join != tword}\r\n\t\t\t\t\tanagrams << groupWords\r\n\t\t\t\tend\r\n\t\t\t\t\r\n\treturn anagrams\r\nend",
"def combine_anagrams(words)\n hash = {}\n hash.default=[]\n words.each{|word|\n down_cased = word.downcase\n anagram = down_cased.chars.sort.join\n hash[anagram]= hash[anagram] + [word]\n }\n hash.values\nend",
"def combine_anagrams(words)\r\n words.group_by{|w| w.downcase.chars.sort.to_s}.values\r\nend",
"def word_substituter(tweet)\n tweetarr = tweet.split(' ')\n newtweet = []\n tweetarr.each do |word|\n if dictionary.key?(word.capitalize) \n newtweet << dictionary[word.capitalize].to_s\n \n else \n newtweet << word\n end\n \n end\n tweetstr = newtweet.join(' ')\n \n return tweetstr\nend",
"def adjacent_words(word)\n\t\tadj_words = []\n\t\tword.chars.each_with_index do |char, i|\n\t\t\t('a'..'z').to_a.each do |letter|\n\t\t\t\tnext if char == letter # change 25 times for each letter\n\t\t\t\t\n\t\t\t\tnew_word = word.dup\n\t\t\t\tnew_word[i] = letter\n\t\t\t\tadj_words << new_word if @dictionary.include?(new_word)\n\t\t\tend\n\t\tend\n\t\t\n\t\tadj_words\n\tend",
"def alteration\n (0...length).flat_map { |i|\n LETTERS.map { |letter|\n string.dup.tap { |w| w[i] = letter }\n }\n }.uniq\n end",
"def english_translate\n pig_latin_arr = []\n pig_latin = []\n print \"What word would you like to translate? \"\n input = gets.chomp!.downcase\n \n pig_latin_word_to_translate = input.split(/ /)\n\n pig_latin_word_to_translate.each do |word|\n pig_latin_arr = word.split(//)\n\n first_letter = pig_latin_word_to_translate.delete_at(0)\n new_letters = english_word_to_translate.join\n\n word = new_letters + first_letter + \"ay\"\n\n pig_latin << word\n end\n \n puts pig_latin.join(' ').capitalize\nend",
"def add(word)\n word.scan(/./) do |l|\n if ('a'..'z') === l\n @map[l] = Array.new unless @map.has_key? l\n @map[l] = @map[l] << word\n end\n end \n end",
"def transform_word(str)\n ary = str.split(\"\")\n ary_nums = convert_to_ascii(ary)\n new_nums = add_i(ary_nums)\n new_ary = convert_to_letters(new_nums)\nend",
"def pig_latin_translate\n english_word_arr = []\n vowel_array = %w(a e i o u)\n \n print \"What word would you like to translate? \"\n input = gets.chomp!.downcase\n \n english_word_to_translate = input.split(/ /)\n \n english_word_to_translate.each do |word|\n english_word_arr = word.split(//)\n\n\n\n #split by words\n #split by character\n #Take first letter move to end\n #add 'Ay'\n #join and return word\n end\nend",
"def pig_latin_name(word)\n \n letters = word.split(\"\")\n \n final_array = letters.clone\n letters.each do |letter| #[p, l, u, m]\n \n \n if is_consonants?(letter)\n final_array.rotate! \n # #puts \".........#{removed_consonant}\"\n # #letters.push(removed_consonant)\n # puts \".........#{final_array}..#{letters}\"\n else \n # puts \"*****#{final_array}.... #{letters}\"\n final_array.push(\"ay\")\n return final_array.join\n end\n end\nend",
"def translate(word)\r\n vowels = \"aeio\".split('').to_a\r\n consonant = \"bcdfghjklmnpqrstuvwxyz\".split('').to_a \r\n answer = []\r\n \r\n while word.split(' ').length == 1 \r\n words = word.split('')\r\n until vowels.include?(words[0])\r\n words = words.rotate(1)\r\n end\r\n words << \"ay\"\r\n return words.join('')\r\n end # one word ^^\r\n \r\n if word.split(' ').length > 1 \r\n words = word.split(' ')\r\n end \r\n words.each do |i|\r\n if vowels.include?(i[0])\r\n i << \"ay\"\r\n answer << i\r\n #return answer\r\n end\r\n end\r\n \r\n words.each do |j|\r\n if consonant.include?(j[0])\r\n j = j.split('').rotate(1).join('') until vowels.include?(j[0])\r\n j = j + \"ay\"\r\n #return j\r\n #j << j #correct format for 1 consonant but it doesnt add to array\r\n answer << j\r\n end\r\n end\r\n \r\n return answer.join(' ')\r\n end",
"def translate word\n\n\tsplit = word.split(\" \")\n\tlatin = \"\"\n\tvowels = [\"a\", \"e\", \"i\", \"o\", \"u\"]\n\t\n\n\n\tsplit.each do |string|\n\n\t\ta = 0\n\t\tconsts = 0\n\n\t\twhile vowels.include?(string[a]) === false\n\t\t\tconsts = consts + 1\n\t\t\ta = a + 1\n\t\tend\n\n\t\tif string[consts -1] === \"q\"\n\t\t\tif string[consts] === \"u\"\n\t\t\t\tconsts = consts + 1\n\t\t\tend\n\t\tend\n\n\t\tb = string[0, consts]\n\n\t\t\n\t\tif consts === 1\n\t\t\tlatin = latin + string[consts, string.length-1] + string[0] + \"ay\"\n\t\telsif\tconsts > 1\n\t\t\tlatin = latin + string[consts, string.length-1] + b + \"ay\"\n\t\telse\n\t\t\tlatin = latin + string + \"ay\"\n\t\tend\n\n\tlatin = latin + \" \"\n\n\tend\n\n\tlatin.strip\n\t\nend",
"def adjacent_words(word)\n one_letter_off = []\n (word.length - 1).times do |i|\n dup_word = word.dup\n dup_word[i] = \".\"\n one_letter_off += @dictionary.select {|word| word =~ (/\\A#{dup_word}\\z/) }\n end\n one_letter_off\n end",
"def build_words(letters)\n @letters = letters\n build!\n end",
"def word_substituter(tweet)\n short_tweet = tweet.split.map do |word|\n if dictionary.keys.include?(word)\n dictionary[word]\n else\n word\n end\n end\n short_tweet.join(\" \")\nend",
"def abbreviate_sentence(sent)\r\n \toutput = []\r\n\twords = sent.split(\" \")\r\n \twords.each do |word|\r\n if word.length > 4\r\n word.each_char do |char|\r\n \tif char == 'a' || char == 'e' || char == 'i' || char == 'o' || char == 'u'\r\n \t\tword[word.index(char)] = \"\"\r\n \tend\r\n \tend\r\n end\r\n output << word\r\n end\r\n return output.join(\" \")\r\nend",
"def swap_letters(sentence, letters)\n # your code goes here\n result = []\n\n l1, l2= letters[0], letters[1]\n sentence.split.each do |word|\n temp = \"\"\n word.chars.each do |ch|\n if ch == l1 || ch == l1.downcase\n ch = l2\n elsif ch == l2 || ch.downcase == l2\n ch = l1.downcase\n end\n temp << ch\n end\n result << temp\n end\n\n result.join(\" \")\nend",
"def aliass(full_name)\n alphabet = \"bcdfghjklmnpqrstvwxyz\"\n vowels = \"aeiou\"\n new_string = \"\"\n \n #break input word into array and iterate through each letter\n #if the letter is a vowel, take it and change it to next_vowel\n #if the letter is a consonant, take it and change it to consonant\n #else just add with no modification\n full_name.split('').each do |letter|\n if vowels.include?(letter)\n new_string += vowel(letter)\n elsif alphabet.include?(letter)\n new_string += consonant(letter)\n else\n new_string += letter\n end\n end\n #transform this new string into an array\n new_word = new_string.split(' ')\n #swap first and second word in array\n new_word.reverse!\n #turn new word into string\n new_word.map {|names| names.capitalize!}\n new_string = new_word.join(\" \")\n end",
"def recombiner (array_of_char)\n new_name = array_of_char.join.split(' ').reverse\n new_name.map! do | words |\n words.capitalize\n end\n new_name.join(' ')\nend",
"def wordprep(word)\n return word.gsub(/\\W/,'').downcase.chars.sort.join\nend",
"def aliass(full_name)\n\talphabet = \"bcdfghjklmnpqrstvwxyz\"\n\tvowels = \"aeiou\"\n\tnew_string = \"\"\n\n full_name.split('').each do |letter|\n \t\tif vowels.include?(letter)\n \t\t\tnew_string += vowel(letter)\n \t\telsif alphabet.include?(letter)\n \t\t\tnew_string += consonant(letter)\n \t\telse\n \t\t\tnew_string += letter\n \t\tend\nend\n#Transform this new string into an array\n#Swap first and second word in array\n#Turn new word into string\n#Create empty array outside of loop\nnew_word = new_string.split(' ')\n new_word.reverse!\n\nnew_word.map {|names| names.capitalize!}\nnew_string = new_word.join(\" \")\nend",
"def current_word\n #for each char in the word, either fill it in if its guessed or replace with '_'\n my_word = \"\"\n word.each_char do |c|\n if guesses.include? c\n my_word << c\n else\n my_word << \"_\"\n end\n end\n my_word\n\n end",
"def combine_anagrams(words)\n #h=Hash.new(0)\n output = Array.new\n words.map{|word| word.chars.sort.join }.uniq.each {|anagram|\n w = words.partition { |word| word.chars.sort.join==anagram}\n# puts \"w : \" + w.to_s\n output += [w[0]]\n# puts \"output : \" + output.to_s\n }\n return output\nend",
"def whisper_words(words)\nreturn words.map{ |elem| elem.downcase + \"...\"}\nend",
"def merge_word_strings str1, str2\n return str2||\"\" if str1.blank?\n return str1 if str2.blank?\n (str1.split(/\\s+/) + str2.split(/\\s+/)).uniq.join(' ')\nend",
"def staggered_case(words)\n mixed_chars = words.chars.each_with_index.map do |char, index|\n if index.even? && char =~ /[a-zA-Z]/\n char.upcase\n elsif index.odd? && char =~ /[a-zA-Z]/\n char.downcase\n else\n char\n end\n end\n mixed_chars.join\nend",
"def remove_letter_a(words)\nend",
"def word_substituter(tweet)\n dictionary_hash = {\n \"hello\" =>'hi',\n \"to\" => '2', \"two\" => '2', \"too\" => '2' ,\n \"for\"=>'4', \"four\" =>'4',\n 'be' => 'b',\n 'you' => 'u',\n \"at\" => \"@\",\n \"and\" => \"&\"\n }\n\n tweet_split = tweet.split(\" \")\n counter = 0\n tweet_split.each do |word|\n # puts \"************************word:#{word}\"\n # puts \"************************#{dictionary_hash}\"\n if dictionary_hash[word.downcase] == nil\n #do nothing\n else\n tweet_split[counter] = dictionary_hash[word.downcase]\n end\n counter += 1\n end\n # puts \"#{tweet_split}\"\n tweet_split.join(\" \")\nend",
"def typoglycemiaWord(input)\n if input.length <= 3\n input\n end\n letters = input.chars\n last = letters.pop\n first = letters.shift\n letters.shuffle!\n letters << first\n letters.rotate!(-1)\n letters << last\n letters.join\nend",
"def hipsterfy(str)\n finalArray = []\n alphabet = (\"a\"..\"z\").to_a\n wordArray = str.split(\" \")\n wordArray.each do |word|\n firstSeen = false\n reversed = word.split(\"\").reverse\n finalWord = []\n reversed.each do |letter|\n if firstSeen == true || letter != \"a\" && letter != \"e\" && letter != \"i\" && letter != \"o\" && letter != \"u\"\n finalWord.push(letter)\n\n elsif firstSeen == false && letter == \"a\" || letter == \"e\" || letter == \"i\" || letter == \"o\" || letter == \"u\"\n # don't add here\n firstSeen = true\n end\n end\n \n newString = \"\"\n finalWord.reverse.each do |element|\n newString += String(element)\n end\n finalArray.push(newString)\n \n end\n \n \n \n # print finalArray\n finalString = \"\"\n \n finalArray.each_with_index do |word, index|\n if index != finalArray.length - 1\n finalString += word + \" \"\n else\n finalString += word\n end\n end\n \n \n \n \n \n \n return finalString\n \n \n\n \nend",
"def join_multi_word_names(author_text)\n author_text.gsub(/\\b((?:van|von|der|den|de|di|le|el))\\s/si) {\n \"#{$1}_\"\n }\n end",
"def translate(word)\n split_words = word.split(' ')\n words = []\n vowels = %w[a e i o u]\n split_words.each do |word|\n word = qu_in_word(word)\n if vowels.include?(word[0])\n words.push(word + 'ay')\n else\n count = 0\n word.length.times do |number|\n vowels.include?(word[number]) ? break : count += 1\n end\n words.push(word[count..-1] + word[0..(count - 1)] + 'ay')\n end\n end\n words.join(' ')\nend",
"def translate s\n \n words = s.split.map{|word|\n if %w(a e i o u).include?(word[0])\n word << \"ay\"\n elsif %w(thr sch squ).include?(word[0..2])\n word[3..-1] << (word[0..2] << \"ay\")\n elsif %w(ch qu br th).include?(word[0..1])\n word[2..-1] << word[0..1] << \"ay\" \n else\n word[1..-1] << (word[0] << \"ay\") \n end\n }\n words.join(\" \")\n\nend",
"def asterisked(word)\n vowels = [\"a\", \"e\", \"i\", \"o\", \"u\"]\n new_word = \"\"\n word.each_char do |c|\n if vowels.include?(c)\n new_word << \"*\"\n else\n new_word << c\n end\n end\n new_word\nend",
"def remove_letter_a(words)\n\nend",
"def processed_content\n scan(/[a-z]/i).join.downcase\n\n # self.letters.downcase\n end",
"def combine_anagrams(words)\n\t[] unless words.empty?\n\tcombine = Hash.new\n\twords.each do |word|\n\t\tsorted = word.downcase.chars.sort.join\n\t\tif combine.has_key?(sorted)\n\t\t\tcombine[sorted] << word\n\t\telse\n\t\t\tcombine[sorted] = [word]\n\t\tend\t\n\tend\n\tcombine.values\nend",
"def translate word\n alpha = ('a'..'z').to_a\n vowels = %w[a e i o u]\n consonants = alpha - vowels\n\n if vowels.include?(word[0])\n word + 'ay'\n elsif consonants.include?(word[0]) && consonants.include?(word[1])\n word[2..-1] + word[0..1] + 'ay'\n elsif consonants.include?(word[0])\n word[1..-1] + word[0] + 'ay'\n else\n word # return unchanged\n end\nend",
"def add_letter(letter)\n char_list = @word.split(\"\")\n\n char_list.each_with_index do |character, index|\n if letter == character\n @display[index] = letter\n end\n end\n end",
"def get_word\n @word_to_guess.join\n end",
"def translate(str)\n\n\n\n # Vowels to consider\n vowels = [\"a\", \"e\", \"i\", \"o\", \"u\"]\n \n # Special cases to consider\n two_letter_consonants = [\"ch\", \"sh\", \"qu\", \"th\", \"br\"]\n three_letter_consonants = [\"thr\", \"sch\", \"squ\"]\n\n words = str.split(\" \")\n result = []\n\n words.each do |word|\n if vowels.include?(word[0])\n result.push word << \"ay\"\n else \n if three_letter_consonants.include? (word[0] + word[1] + word[2])\n first_three_letters = word.slice!(0,3)\n \n # Add letters to end of word with 'ay'\n result.push word << first_three_letters << 'ay'\n elsif two_letter_consonants.include?(word[0] + word[1])\n first_two_letters = word.slice!(0,2)\n result.push word << first_two_letters << \"ay\"\n else \n first_letter = word.slice!(0)\n \n # Add first letter to end of word with 'ay'\n result.push word << first_letter << 'ay'\n end #End of special consonant check\n end \n end \n return result.join(\" \")\nend",
"def encode\n @word.chars.map { |letter|\n index = @abc.index(letter)\n cipher_character = @abc_reverse[index]\n }.join\n end",
"def create_index1(word)\n word.chars.sort!.join\n end",
"def combine_anagrams(words)\n\toutput = Array.new # function result\n\twords.each do |word|\n\t\tsorted = word.upcase.chars.sort.join\n\t\tprint sorted, ' '\n\t\tgroup = output.find {|g| sorted == g[0].upcase.chars.sort.join}\n\t\tif not group\n\t\t\tgroup = []\n\t\t\toutput.push group\n\t\tend\n\t\tgroup.push word\n\tend\n\toutput\nend",
"def join_multi_word_names(author_text)\n author_text.gsub(/\\b((?:van|von|der|den|de|di|le|el))\\s/i) {\n \"#{$1}_\"\n }\n end",
"def word_substituter(tweet_string)\n\n dictionary_hash = dictionary\n tweet_to_array = tweet_string.split\n back_to_tweet = \"\"\n\n tweet_to_array.each_with_index do |word, index|\n dictionary.each do |full, truncated|\n if full.to_s == word\n tweet_to_array[index] = truncated\n end\n end\n end\n back_to_tweet = tweet_to_array.join(\" \")\n return back_to_tweet\n\nend",
"def scramble_words(chars = WordChars)\n\t\tgsub(/(#{chars})(#{chars}+)(?=#{chars})/) { $1 + $2.randomize }\n\tend",
"def word_substituter(tweet)\n tweet.split.collect do |word|\n if dictionary.keys.include?(word.downcase)\n word = dictionary[word.downcase]\n else\n word\n end\n end.join(\" \")\nend",
"def aliass(full_name)\n\talphabet = \"bcdfghjklmnpqrstvwxyz\"\n\tvowels = \"aeiou\"\n\tnew_string = \"\"\n\n\t#break input word into array and iterate through each letter\n\t#if the letter is a vowel, take it and change it to next_vowel\n\t#if the letter is a consonant, take it and change it to consonant\n\t#else just add with no modification\n\tfull_name.split('').each do |letter|\n\t\tif vowels.include?(letter)\n\t\t\tnew_string += vowel(letter)\n\t\telsif alphabet.include?(letter)\n\t\t\tnew_string += consonant(letter)\n\t\telse\n\t\t\tnew_string += letter\n\t\tend\n\tend\n\t#transform this new string into an array\n\tnew_word = new_string.split(' ')\n\t#swap first and second word in array\n\tnew_word.reverse!\n\t#turn new word into string\n\tnew_word.map {|names| names.capitalize!}\n\tnew_string = new_word.join(\" \")\nend",
"def adjacent_words(word)\n alphabet = (\"a\"..\"z\").to_a\n adjacent_words = []\n\n arrayOfWords = word.split(\"\")\n\n word.each_char_with_index do |old_letter, idx|\n charIndex = alphabet.index(char)\n\n (1..26).each do |num|\n newCharIndex = charIndex + num\n\n if newCharIndex > 26\n newCharIndex = newCharIndex % 26\n end\n arrayOfWords[idx] = alphabet[newCharIndex]\n new_word = arrayOfWords.join(\"\")\n\n next if new_word == word\n \n if @dictionary.include?(new_word)\n adjacent_words << new_word\n end\n end\n arrayOfWords[idx] = char\n end\n adjacent_words\n end",
"def gordon(a)\n\ta.upcase!\n\ta.gsub!(/[A]/, '@').gsub!(/[UIOE]/, '*')\n\tarr = a.split.each do |word|\n\t\tword << \"!!!!\"\n\tend\n\tarr.join \" \"\nend"
] |
[
"0.6957881",
"0.6812398",
"0.6796432",
"0.6794042",
"0.6770985",
"0.67527235",
"0.67447853",
"0.6704794",
"0.66879094",
"0.6662192",
"0.65762955",
"0.6547677",
"0.65325296",
"0.648715",
"0.64836806",
"0.6450129",
"0.6446887",
"0.64426637",
"0.64330477",
"0.643056",
"0.64281446",
"0.64015967",
"0.639543",
"0.63857687",
"0.637886",
"0.63705254",
"0.6358684",
"0.63585234",
"0.6357061",
"0.635049",
"0.63425845",
"0.63418317",
"0.6338174",
"0.6330558",
"0.6322963",
"0.63119614",
"0.6296418",
"0.6293537",
"0.62923115",
"0.6292239",
"0.62815523",
"0.6264859",
"0.6259372",
"0.6254818",
"0.6253089",
"0.62498003",
"0.6247859",
"0.62456816",
"0.6243362",
"0.623324",
"0.6226615",
"0.6222211",
"0.6221822",
"0.6219899",
"0.62155586",
"0.62134045",
"0.62120646",
"0.6210283",
"0.62040085",
"0.6202013",
"0.6199917",
"0.61932534",
"0.6192574",
"0.6192305",
"0.6190218",
"0.61888695",
"0.61849076",
"0.6184256",
"0.6181683",
"0.6179383",
"0.61780614",
"0.6172241",
"0.6164235",
"0.61579144",
"0.6155092",
"0.6146248",
"0.6134401",
"0.6133158",
"0.61330616",
"0.613046",
"0.61282223",
"0.61281097",
"0.6118571",
"0.6112053",
"0.610747",
"0.61061645",
"0.61050147",
"0.6103977",
"0.61039674",
"0.609459",
"0.60938734",
"0.6089857",
"0.6088198",
"0.608494",
"0.6084228",
"0.60820186",
"0.6077791",
"0.607645",
"0.60763586",
"0.6060788"
] |
0.72019935
|
0
|
Task body for the :docs_debug task
|
def do_docs_debug( task, args )
self.prompt.say( "Docs are published to:", color: :bright_green )
if ( publish_url = self.publish_to )
self.prompt.say( self.indent(publish_url, 4) )
else
self.prompt.say( self.indent("n/a"), color: :bright_yellow )
end
self.prompt.say( "\n" )
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def doc_task; end",
"def define_debug_tasks\n\t\ttask( :base_debug ) do\n\t\t\tself.output_documentation_debugging\n\t\t\tself.output_project_files_debugging\n\t\t\tself.output_dependency_debugging\n\t\tend\n\n\t\ttask :debug => :base_debug\n\tend",
"def rdoc_task_description\n 'Build RDoc HTML files'\n end",
"def doc_task=(_arg0); end",
"def rerdoc_task_description\n \"Rebuild RDoc HTML files\"\n end",
"def taskDescription _args\n \"taskDescription _args;\" \n end",
"def description\n \"This task hits the Google API and finds related content. Discovered domains are created.\"\nend",
"def description\n \"This task hits the Google API and finds related content. Discovered domains are created.\"\nend",
"def description\n\t\t\"Msf Wrapper Task\"\n\tend",
"def docs; end",
"def description\n \"This task hits the corpwatch API and adds detail for the organization.\"\nend",
"def description\n \"This task runs a web scan and adds webpages with interesting contents\"\nend",
"def description\n \"This task hits the Corpwatch API and creates an object for all found entities.\"\nend",
"def description\n \"This task hits the Corpwatch API and creates an entity for all found entities.\"\nend",
"def show_doc \n pp @doc\n end",
"def description\n \"This task converts a netblock into host records\"\nend",
"def explain_static(task); end",
"def simple_rake_task(task_name = 'test_task', indent: '', task_body: \"\\n\")\n \"\\n\" + indent +\n \"desc 'task named #{task_name}'\\n\" +\n indent + \"task :#{task_name} do\\n\" +\n indent + \" \" + task_body +\n indent + \"end\\n\\n\"\n\n end",
"def document_detail(node)\n node_data = node.data\n <<~DETAIL_SRC\n [[#{Giblish.to_valid_id(node.pathname.to_s, \"_\", \"_\", true)}]]\n === pass:[#{node_data.title.encode(\"utf-8\")}]\n\n #{\"Doc id::\\n_#{node_data.docid}_\" unless node_data.docid.nil?}\n\n #{\"Purpose::\\n#{node_data.purpose_str}\" unless node_data.purpose_str.to_s.empty?}\n\n #{if node_data.stderr.empty?\n \"\"\n else\n \"Conversion issues::\\n\"\\\n \"#{node_data.stderr.gsub(/^/, \" * \")}\"\n end\n }\n\n Source file::\n #{node_data.src_node.segment}\n\n '''\n\n DETAIL_SRC\n end",
"def fulldoc_template; end",
"def doc_text_info\n extra_javascript 'docs'\n @bugs = sorted_bugs\n end",
"def define_asciidoc_tasks\n if defined?(AsciiDocTasks) && File.exist?(\"#{doc_dir}/asciidoc.conf\") && asciidoc_available?\n man_pages = FileList[\"#{doc_dir}/*.[0-9].txt\"]\n articles = FileList[\"#{doc_dir}/*.txt\"] - man_pages\n desc \"Build AsciiDoc under #{doc_dir}\"\n AsciiDocTasks.new('doc:asciidoc') do |t|\n t.source_dir = doc_dir\n t.source_files = articles\n t.doc_type = :article\n t.config_file = \"#{doc_dir}/asciidoc.conf\"\n t.attributes = asciidoc_attributes\n end\n AsciiDocTasks.new('doc:asciidoc') do |t|\n t.source_dir = doc_dir\n t.source_files = man_pages\n t.doc_type = :manpage\n t.config_file = \"#{doc_dir}/asciidoc.conf\"\n t.attributes = asciidoc_attributes\n end\n else\n desc \"Build AsciiDoc (disabled)\"\n task 'asciidoc'\n task 'asciidoc:build'\n task 'asciidoc:clean'\n task 'asciidoc:rebuild'\n end\n task 'doc:build' => 'doc:asciidoc:build'\n task 'doc:clean' => 'doc:asciidoc:clean'\n task 'doc:rebuild' => 'doc:asciidoc:rebuild'\n end",
"def desc(*args)\n Rake.application.DescribeTask(*args)\n end",
"def description\n\t\t\"Msf Pro Wrapper Task\"\n\tend",
"def doc; end",
"def doc; end",
"def doc; end",
"def doc; end",
"def description\n \"This task runs a masscan scan for the top ports on the target range.\"\nend",
"def debug\n @transform_tasks.push(\n add_transform_task('debug')\n )\n response = UploadUtils.make_call(url, 'get')\n JSON.parse(response.body)\n end",
"def description\n \"This task simply attaches a note entity to the current entity.\"\nend",
"def clobber_task_description\n \"Remove RDoc HTML files\"\n end",
"def docstring; end",
"def docstring; end",
"def inspect\n puts @doc.inspect\n end",
"def inspect\n puts @doc.inspect\n end",
"def output_documentation_debugging\n\t\tsummary = self.extract_summary\n\t\tdescription = self.extract_description\n\t\thomepage = self.extract_homepage || DEFAULT_HOMEPAGE\n\n\t\tself.prompt.say( \"Documentation\", color: :bright_green )\n\t\tself.prompt.say( \"Authors:\" )\n\t\tself.authors.each do |author|\n\t\t\tself.prompt.say( \" • \" )\n\t\t\tself.prompt.say( author, color: :bold )\n\t\tend\n\t\tself.prompt.say( \"Summary: \" )\n\t\tself.prompt.say( summary, color: :bold )\n\t\tself.prompt.say( \"Description:\" )\n\t\tself.prompt.say( \" \" + description, color: :bold )\n\t\tself.prompt.say( \"Homepage:\" )\n\t\tself.prompt.say( \" \" + homepage, color: :bold )\n\t\tself.prompt.say( \"\\n\" )\n\tend",
"def description\n \"This task runs an nmap scan on the target host or domain.\"\nend",
"def description\n \"This is an example Tapir task. It associates a random host with the calling entity.\"\n end",
"def body\n description\n end",
"def base_docstring; end",
"def description\n \"This task runs a zmap scan on the target range.\"\nend",
"def description\n \"This is an example Tapir task. It associates a random host with the calling entity.\"\nend",
"def help\n str = \"====[ #{@name} ]====\\nUsage: #{@name} \"\n @doc_args.each do |key, _value|\n str += \"[#{key.upcase}] \"\n end\n @doc_options.each do |key, _value|\n str += \"(--#{key.name}) \"\n end\n str = \"#{str.rstrip}\\nDescription: #{description}\\n#{help_options_args}\"\n str.rstrip\n end",
"def description\n\t\"This task scrapes Hoovers for company info.\"\nend",
"def description; @doc['description']; end",
"def description; @doc['description']; end",
"def request_doc\n \n end",
"def what_it_does() \"Generate javadoc to '#{@name}' folder\" end",
"def define_seattlerb_tasks\n if Hoe.plugins.include? :publish then\n base = \"/data/www/docs.seattlerb.org\"\n rdoc_locations << \"docs-push.seattlerb.org:#{base}/#{remote_rdoc_dir}\"\n end\n end",
"def describe(detail=0, indent=0)\n i = ' ' * indent\n lines = [\"#{i}#{name} (#{self.class}) {\"]\n @tasks.each_value { |t|\n lines << t.describe(detail, indent + 2)\n }\n lines << i + \"}\"\n lines.join(\"\\n\")\n end",
"def define(&block)\n namespace :dm do\n namespace(:doc,&block)\n end\n\n task 'db:doc' => 'dm:doc'\n end",
"def define_publish_tasks\n Rake::RDocTask.new(:docs) do |rd|\n rd.main = readme_file\n rd.options << '-d' if (`which dot` =~ /\\/dot/) unless\n ENV['NODOT'] || Hoe::WINDOZE\n rd.rdoc_dir = 'doc'\n\n rd.rdoc_files += spec.require_paths\n rd.rdoc_files += spec.extra_rdoc_files\n\n title = \"#{name}-#{version} Documentation\"\n title = \"#{rubyforge_name}'s \" + title if rubyforge_name != name\n\n rd.options << \"-t\" << title\n end\n\n desc 'Generate ri locally for testing.'\n task :ridocs => :clean do\n sh %q{ rdoc --ri -o ri . }\n end\n\n desc 'Publish RDoc to RubyForge.'\n task :publish_docs => [:clean, :docs] do\n config = YAML.load(File.read(File.expand_path(\"~/.rubyforge/user-config.yml\")))\n host = \"#{config[\"username\"]}@rubyforge.org\"\n\n remote_dir = \"/var/www/gforge-projects/#{rubyforge_name}/#{remote_rdoc_dir}\"\n local_dir = 'doc'\n\n sh %{rsync #{rsync_args} #{local_dir}/ #{host}:#{remote_dir}}\n end\n\n # no doco for this one\n task :publish_on_announce do\n with_config do |config, _|\n Rake::Task['publish_docs'].invoke if config[\"publish_on_announce\"]\n end\n end\n\n desc 'Generate email announcement file.'\n task :email do\n require 'rubyforge'\n subject, title, body, urls = announcement\n\n File.open(\"email.txt\", \"w\") do |mail|\n mail.puts \"Subject: [ANN] #{subject}\"\n mail.puts\n mail.puts title\n mail.puts\n mail.puts urls\n mail.puts\n mail.puts body\n mail.puts\n mail.puts urls\n end\n puts \"Created email.txt\"\n end\n\n desc 'Post announcement to blog.'\n task :post_blog do\n require 'xmlrpc/client'\n\n with_config do |config, path|\n break unless config['blogs']\n\n subject, title, body, urls = announcement\n body += \"\\n\\n#{urls}\"\n\n config['blogs'].each do |site|\n server = XMLRPC::Client.new2(site['url'])\n content = site['extra_headers'].merge(:title => title,\n :description => body,\n :categories => blog_categories)\n\n result = server.call('metaWeblog.newPost',\n site['blog_id'],\n site['user'],\n site['password'],\n content,\n true)\n end\n end\n end\n\n desc 'Post announcement to rubyforge.'\n task :post_news do\n require 'rubyforge'\n subject, title, body, urls = announcement\n\n rf = RubyForge.new.configure\n rf.login\n rf.post_news(rubyforge_name, subject, \"#{title}\\n\\n#{body}\")\n puts \"Posted to rubyforge\"\n end\n\n desc 'Create news email file and post to rubyforge.'\n task :announce => [:email, :post_news, :post_blog, :publish_on_announce ]\n end",
"def generate_doc\n\n end",
"def docs=(_arg0); end",
"def explain_true(task); end",
"def description\n \"This task grabs the robots.txt and adds each line as a web page\"\nend",
"def build(rakeTask)\n\t\tprintAndCall(@cmd)\n\tend",
"def description\n description_section.join(\" \").tr(\"\\n\", ' ').gsub(/[{}]/,'').gsub(/\\[[^\\]]+\\]/,'') # strip rdoc\n end",
"def document\n comment_code\n super\n end",
"def rebuild_docs():\n\tprint 'rebuilding docs'\n\tfrom fabric.api import local, cd\n\tlocal('fab docs')\n\t\t\nTask.add('/vagrant', rebuild_docs)",
"def simpleTasks _args\n \"simpleTasks _args;\" \n end",
"def define(args, &task_block)\n desc \"Generate Swagger from AppMaps\" unless ::Rake.application.last_description\n\n task(name, *args) do |_, task_args|\n RakeFileUtils.__send__(:verbose, Rake.verbose == true) do\n task_block.call(*[self, task_args].slice(0, task_block.arity)) if task_block\n Command.new(:git_command).tap do |cmd|\n cmd.base = task_args[:base] || self.base\n cmd.swagger_file = task_args[:swagger_file] || self.swagger_file\n end.perform\n end\n end\n end",
"def inspect\n \"#<yardoc #{type} #{path}>\"\n end",
"def document\n capture_args\n capture_return\n super\n end",
"def displayRakeTasks\n Rake.application.tasks.each do |iTask|\n log_info \"+-#{iTask.name}: #{iTask.comment}\"\n iTask.prerequisites.each do |iPrerequisiteTaskName|\n log_info \"| +-#{iPrerequisiteTaskName}\"\n end\n log_info '|'\n end\n end",
"def show_documentation req, res\n store, path = documentation_source req.path\n\n if_modified_since req, res, store.cache_path\n\n generator = generator_for store\n\n case path\n when nil, '', 'index.html' then\n res.body = generator.generate_index\n when 'table_of_contents.html' then\n res.body = generator.generate_table_of_contents\n when 'js/search_index.js' then\n documentation_search store, generator, req, res\n else\n documentation_page store, generator, path, req, res\n end\n ensure\n res.content_type ||= 'text/html'\n end",
"def display_tasks_and_comments\n puts \"Displaying tasks... \\n\"\n puts\n if(options.show_tasks == :tasks)\n # Get the maximum width of all task names\n all_displayable_tasks = tasks.select { |t|\n t.comment && t.name =~ options.show_task_pattern\n }\n \n #puts \"Displayable tasks: #{all_displayable_tasks}\\n\"\n \n width = all_displayable_tasks.collect { |t| t.name_with_args.length }.max || 10\n max_column = truncate_output? ? terminal_width() - name.size - width - 7 : nil\n \n @ProjectFileLoader.LoadedProjectFiles().each do |projectFile|\n if(projectFile.HasTasks())\n headline = \"Tasks in project file: '#{projectFile.Path().RelativePath()}'\\n\"\n puts headline\n puts \"-\" * headline.length\n puts projectFile.GetTaskDescriptions(width, max_column)\n end \n end\n else\n super\n end\n end",
"def document\n capture_parameters\n capture_return_type\n super\n end",
"def desc(description)\n ConfigureTask.add_description(description)\n end",
"def description\n \"This task hits the Google API and creates an entity for all discovered subdomains.\"\nend",
"def show\n @tasks.each do |project_name, project_tasks|\n @output.puts project_name\n project_tasks.each do |task|\n @output.printf(\" [%c] %d: %s : %s \\n\", (task.done? ? 'x' : ' '), task.id, task.description, task.deadline)\n end\n @output.puts\n end\n end",
"def doc\n if @spec.key?('doc')\n Comment.new(\"@param #{@spec['name']} #{@spec['doc']}\")\n else\n Comment.new\n end\n end",
"def post #:doc:\n end",
"def define\n desc \"Generate rokko documentation\"\n task @name do\n # Find README file for `index.html` and delete it from `sources`\n if @options[:generate_index]\n readme_source = @sources.detect { |f| File.basename(f) =~ /README(\\.(md|text|markdown|mdown|mkd|mkdn)$)?/i }\n readme = readme_source ? File.read(@sources.delete(readme_source)) : ''\n end\n\n # Run each file through Rokko and write output\n @sources.each do |filename|\n rokko = Rokko.new(filename, @sources, @options)\n out_dest = File.join(@dest, filename.sub(Regexp.new(\"#{File.extname(filename)}$\"), \".html\"))\n puts \"rokko: #{filename} -> #{out_dest}\"\n FileUtils.mkdir_p File.dirname(out_dest)\n File.open(out_dest, 'wb') { |fd| fd.write(rokko.to_html) }\n end\n\n # Generate index.html if needed\n if @options[:generate_index]\n require 'rokko/index_layout'\n out_dest = File.join(@dest, 'index.html')\n puts \"rokko: #{out_dest}\"\n File.open(out_dest, 'wb') { |fd| fd.write(IndexLayout.new(@sources, readme, @options).render) }\n end\n\n # Run specified file through rokko and use it as index\n if @options[:index] && source_index = @sources.find{|s| s == @options[:index]}\n rokko = Rokko.new(source_index, @sources, @options.merge(preserve_urls: true))\n out_dest = File.join(@dest, 'index.html')\n puts \"rokko: #{source_index} -> index.html\"\n File.open(out_dest, 'wb') { |fd| fd.write(rokko.to_html) }\n end\n\n end\n end",
"def index\n @tasks = eval(get_query)\n @task = @project.tasks.build\r\n @archieved = @project.is_archieved?\n @learnmore = \"Tasks help you keep track of all the little things that need to get done. You can add them for yourself or assign them to someone else.\"\n render :layout => 'onebox_layout'\n end",
"def enable_db_doc(target_directory)\n task \"#{task_prefix}:db_doc\"\n task \"#{task_prefix}:pre_build\" => [\"#{task_prefix}:db_doc\"]\n\n (up_dirs + down_dirs).each do |relative_dir_name|\n dirs_for_database(relative_dir_name).each do |dir|\n task \"#{task_prefix}:db_doc\" => Dbt::DbDoc.define_doc_tasks(dir, \"#{target_directory}/#{relative_dir_name}\")\n end\n end\n end",
"def define_debug_tasks\n desc \"Create a fresh ~/.hoerc file.\"\n task :config_hoe do\n with_config do |config, path|\n File.open(path, \"w\") do |f|\n YAML.dump(Hoe::DEFAULT_CONFIG.merge(config), f)\n end\n\n editor = ENV[\"EDITOR\"] || \"vi\"\n system \"#{editor} #{path}\" if ENV[\"SHOW_EDITOR\"] != \"no\"\n end\n end\n\n desc \"Verify the manifest.\"\n task :check_manifest => :clean do\n check_manifest\n end\n\n desc \"Show information about the gem.\"\n task :debug_gem do\n puts spec.to_ruby\n end\n\n task :isolate # stub\n task :irb => :isolate do\n name = spec.name.gsub(\"-\", \"/\")\n file = (spec.files.grep(/^lib\\/#{name}\\.rb$/).first ||\n spec.files.grep(/^lib\\/[^\\/]*\\.rb$/).first)\n\n require = File.basename(file, \".rb\") if file\n require &&= \"-r#{require}\"\n\n ruby \"#{Hoe::RUBY_FLAGS} -S irb #{require}\"\n end\n end",
"def debug; end",
"def debug; end",
"def debug; end",
"def debug; end",
"def debug\n\t\t\texec_parsed_action('debug', [], false)\n\t\tend",
"def description\n \"This task searches for common social media profiles\"\nend",
"def description\n \"This task searches for common social media profiles\"\nend",
"def docs = require_relative 'scaffold/docs'",
"def description\n \"This task looks for usernames via google searchs.\"\nend",
"def doc=(_arg0); end",
"def doc=(_arg0); end",
"def doc=(_arg0); end",
"def taskOpts\nend",
"def pre #:doc:\n end",
"def docstring\n object.docstring.tr(\"\\n\", \" \")\n end",
"def message\n @doc\n end",
"def enable_db_doc(target_directory)\n task \"#{task_prefix}:db_doc\"\n task \"#{task_prefix}:pre_build\" => [\"#{task_prefix}:db_doc\"]\n\n (up_dirs + down_dirs).each do |relative_dir_name|\n dirs_for_database(relative_dir_name).each do |dir|\n task \"#{task_prefix}:db_doc\" => DbTasks::DbDoc.define_doc_tasks(dir, \"#{target_directory}/#{relative_dir_name}\")\n end\n end\n end",
"def taskHint _args\n \"taskHint _args;\" \n end",
"def description\n \"This task can be used to guess usernames, given a user.\"\nend",
"def docs_to_write; end",
"def show\n @notes = @task.task_notes\n @tasks = @task.sub_tasks\n end",
"def docstring=(_arg0); end"
] |
[
"0.70848274",
"0.65630335",
"0.6512884",
"0.640787",
"0.6406908",
"0.6014486",
"0.59714633",
"0.59714633",
"0.5910287",
"0.5891495",
"0.5885187",
"0.5845575",
"0.58450913",
"0.5750026",
"0.57377464",
"0.571465",
"0.57077557",
"0.5703094",
"0.5573421",
"0.5564845",
"0.55494595",
"0.55457133",
"0.5532716",
"0.5528308",
"0.5525727",
"0.5525727",
"0.5525727",
"0.5525727",
"0.5522796",
"0.5514792",
"0.5509885",
"0.5508428",
"0.5497348",
"0.5497348",
"0.548987",
"0.548987",
"0.5474336",
"0.5462212",
"0.54620427",
"0.5460573",
"0.54435754",
"0.54037493",
"0.539698",
"0.5389944",
"0.5379181",
"0.53593314",
"0.53593314",
"0.53534603",
"0.5340778",
"0.52960503",
"0.5290065",
"0.52653974",
"0.52647096",
"0.5243583",
"0.52354914",
"0.5231453",
"0.52295303",
"0.5203939",
"0.5199792",
"0.5188726",
"0.51887095",
"0.5178445",
"0.5170393",
"0.5155249",
"0.5153871",
"0.51521814",
"0.51399",
"0.51382774",
"0.5132009",
"0.5123296",
"0.5107098",
"0.5106174",
"0.51050276",
"0.51033473",
"0.51011246",
"0.5098445",
"0.5085913",
"0.50855786",
"0.5078958",
"0.5078958",
"0.5078958",
"0.5078958",
"0.5070622",
"0.5066938",
"0.5066938",
"0.5064181",
"0.5060601",
"0.5055622",
"0.5055622",
"0.5055622",
"0.5050756",
"0.504738",
"0.5046871",
"0.5039144",
"0.50361264",
"0.502017",
"0.50184304",
"0.50141966",
"0.50090176",
"0.49998724"
] |
0.6979061
|
1
|
Gets the IP and port from the peer that just sent data.
|
def peer_info
peer_bytes = get_peername[2, 6].unpack("nC4")
port = peer_bytes.first.to_i
ip = peer_bytes[1, 4].join(".")
[ip, port]
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def peeraddr\n @socket.peeraddr\n end",
"def peer_info; socket.peer_info if socket end",
"def peer_info\n peer_bytes = get_peername[2, 6].unpack(\"nC4\")\n port = peer_bytes.first.to_i\n ip = peer_bytes[1, 4].join(\".\")\n\n [ip, port]\n end",
"def peer_ip\n peername[0]\n end",
"def peer\n return @remote_address\n end",
"def get_peeraddr\n Socket.unpack_sockaddr_in(get_peername).reverse\n end",
"def peerinfo\n if self.conn\n pi = self.conn.peerinfo || nil\n if pi\n return {\n 'addr' => pi.split(':')[0],\n 'port' => pi.split(':')[1].to_i\n }\n end\n end\n nil\n end",
"def peer_ip; end",
"def peer\n @peer ||= begin\n addr = @socket.getpeername\n ip_address = Socket.getnameinfo(addr, Socket::NI_NUMERICHOST | Socket::NI_NUMERICSERV).first\n { :ip => ip_address, :port => @port.to_i, :host => @host }\n end\n end",
"def tunnel_peer\n\t\tbegin\n\t\t\t@peer_info = rstream.peerinfo\n\t\trescue ::Exception\n\t\t\t@peer_info ||= '127.0.0.1'\n\t\tend\n\tend",
"def remote_ip\n get_peername[2,6].unpack('nC4')[1..4].join('.')\n end",
"def addr\n @addr ||= @stream.connection.socket.peeraddr[3] rescue nil\n end",
"def getpeername\n ::Socket.sockaddr_in(port, host)\n end",
"def peer_ip(socket)\n if socket.respond_to?(:getpeername)\n # Non SSL\n sockaddr = socket.getpeername\n port, host = Socket.unpack_sockaddr_in(sockaddr)\n host\n else\n # SSL\n BasicSocket.do_not_reverse_lookup = true\n socket.peeraddr.last\n end\n end",
"def peer\n @peer ||= { ip: socket.peer_ip, port: @port.to_i, host: @host, canonized: host_as_string }\n end",
"def remote_ip\n return self[\"client-ip\"] || @forwarded_for || @peeraddr[3]\n end",
"def src_ip\n self[:sender_ip]\n end",
"def socket_address\n peer = get_peername\n Socket.unpack_sockaddr_in(peer)[1] if peer\n end",
"def peeraddr\n\t\tif self.instance_of?(UNIXServer) \n\t\t\traise Errno::ENOTCONN, \"Transport endpoint is not connected - getpeername(2)\", caller\n\t\telse\n\t\t\t[@af,@path]\n\t\tend\n\tend",
"def get_sockaddr\n Socket.unpack_sockaddr_in(get_sockname).reverse\n end",
"def to_s\n\t\treturn \"%s:%d\" % [ self.peer_host, self.peer_port ]\n\tend",
"def getpeerinfo\n @api.request 'getpeerinfo'\n end",
"def to_s\n\t\t\"%s:%d\" % [ @peerHost, @peerPort ]\n\tend",
"def peerinfo\n if (pi = getpeername_as_array)\n return pi[1] + ':' + pi[2].to_s\n end\n end",
"def port\n @socket.connect_address.ip_port\n rescue SocketError\n # Not bound to any local port\n rescue IOError\n # Socket has been closed\n end",
"def peeraddr(*) end",
"def peeraddr(*) end",
"def getpeername()\n Socket::Foreign.getpeername @descriptor\n end",
"def port\n return @forwarded_port || @port\n end",
"def port\n connect_address.ip_port\n rescue SocketError\n # Not bound to any local port\n rescue IOError\n # Socket has been closed\n end",
"def tunnel_peer\n \n sock=self.ssh.transport.socket\n misc, host, port= sock.getpeername\n return \"#{host}:#{port}\"\n end",
"def peerip=(_arg0); end",
"def peer\n \"#{rhost}:#{rport}\"\n end",
"def local_ip\n UDPSocket.open {|s| s.connect(\"64.233.187.99\", 1); s.addr.last}\n end",
"def remote_port\n return @remote_port\n end",
"def ip_address\n Socket.ip_address_list.find { |ai| ai.ipv4? && !ai.ipv4_loopback? }.ip_address\n end",
"def port\n data[:port]\n end",
"def get(timeout=nil)\n data, saddr, sport = recvfrom(65535, timeout)\n return data\n end",
"def host_ip\n Socket.gethostbyname(@backend.host)[3].unpack('CCCC') rescue [0, 0, 0, 0]\n end",
"def getpeerinfo\n node.pool.peers.map do |peer|\n local_addr = \"#{peer.remote_version.remote_addr.addr_string}:18333\"\n {\n id: peer.id,\n addr: \"#{peer.host}:#{peer.port}\",\n addrlocal: local_addr,\n services: peer.remote_version.services.to_even_length_hex.rjust(16, '0'),\n relaytxes: peer.remote_version.relay,\n lastsend: peer.last_send,\n lastrecv: peer.last_recv,\n bytessent: peer.bytes_sent,\n bytesrecv: peer.bytes_recv,\n conntime: peer.conn_time,\n pingtime: peer.ping_time,\n minping: peer.min_ping,\n version: peer.remote_version.version,\n subver: peer.remote_version.user_agent,\n inbound: !peer.outbound?,\n startingheight: peer.remote_version.start_height,\n best_hash: peer.best_hash,\n best_height: peer.best_height\n }\n end\n end",
"def get_ip_address\n request.remote_ip\n end",
"def get_outgoing_server\n @outgoing_server\n end",
"def port\n @connection.port\n end",
"def remote_i_p_address\n return @remote_i_p_address\n end",
"def ip\n @ip ||= Socket.ip_address_list.detect{|intf| intf.ipv4_private?}.ip_address\n end",
"def remote_host\n # NOTE: Celluloid::IO does not yet support non-blocking reverse DNS\n @socket.peeraddr(true)[2]\n end",
"def getpeername_as_array\n peer_name = nil\n begin\n peer_name = Socket.from_sockaddr(self.getpeername)\n rescue ::Errno::EINVAL => e\n # Ruby's getpeername method may call rb_sys_fail(\"getpeername(2)\")\n elog(\"#{e.message} (#{e.class})#{e.backtrace * \"\\n\"}\\n\", LogSource, LEV_3)\n end\n\n return peer_name\n end",
"def local_port\n return @local_port\n end",
"def get_ip_address \t\t\t\n\t\trequest.remote_ip \n\tend",
"def socket_port; end",
"def ip\n orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily\n UDPSocket.open do |s|\n s.connect '64.233.187.99', 1\n s.addr.last\n end\n ensure\n Socket.do_not_reverse_lookup = orig\n end",
"def remote_address\n socket_address\n rescue Exception => e\n log_error('Could not infer remote address', e)\n nil\n end",
"def remote_port_and_host\n [forwarding[2], forwarding[3] || \"127.0.0.1\"]\n end",
"def remote_addr; end",
"def get_ip_address_and_port_or_close_connection\n peername = get_peername\n if peername.nil?\n log(:error, :socket, 'new socket created, but unable to fetch ip & port, closing connection...')\n close_connection\n else\n @port, @ip_address = Socket::unpack_sockaddr_in(peername)\n log(:debug, :socket, \"new socket created (#{@ip_address}:#{@port})\")\n end\n end",
"def get_local_ip(network)\n UDPSocket.open do |sock|\n sock.connect network, 1\n sock.addr.last\n end\n end",
"def client_ip\n req = request\n return nil unless req\n # Look for an external address being forwarded\n split_ips = []\n PREFFERED_IP_HEADERS.each do |header_name|\n forwarded = req.env[header_name]\n ips = split_ip_addresses(forwarded)\n lip = ips.find { |ip| (ip !~ TRUSTED_PROXIES) && valid_ip?(ip) }\n split_ips << ips unless ips.empty?\n return lip unless lip.nil?\n end\n # Else fall back to declared remote addr\n r = req.env['REMOTE_ADDR']\n # If this is localhost get the last hop before\n if r.nil? || r =~ LOCALHOST\n split_ips.each do |ips|\n lip = ips.find { |ip| (ip !~ LOCALHOST) && valid_ip?(ip) }\n return lip unless lip.nil?\n end\n end\n r\n end",
"def protocol\n self[:ip_p]\n end",
"def peerinfo(peer)\n send_packet @utils.packet_mangler({\"NodeIdentifier\" => peer,\"WithVolatile\" => false,\"WithMetadata\" => true}, \"ListPeer\")\n wait_for :peer, /Peer/\n end",
"def receive_data data\n sender_port_ip_array = get_peername[2,6].unpack \"nC4\"\n sender_ip = sender_port_ip_array[1..4].join('.')\n sender_port = sender_port_ip_array[0]\n sender_addr = \"#{sender_ip}:#{sender_port}\"\n puts \"From #{sender_addr} received: #{data.to_hex}\" if $debug\n\n $remotes.each { |r|\n unless r[2] == sender_addr ## do not echo data back to sender\n # $stdout.print \"*\" unless $debug\n # $stdout.flush unless $debug\n puts \"Relaying #{data} to #{r[2]}\" if $debug\n send_datagram data, r[0], r[1]\n end\n }\n\n\n\n end",
"def get_internal_ip_address\r\n sock = UDPSocket.new\r\n sock.connect('1.0.0.1', 1) #@igd_location.split('//').last.split('/').first.split(':').first\r\n return sock.addr.last\r\n rescue Exception\r\n return \"127.0.0.1\"\r\n end",
"def peer_list\n ip_list = []\n raw_peers.each_slice(6) { |e| ip_list << e if e.length == 6 }\n\n ip_list.map! { |e| { :ip => e[0..3].join('.'), :port => (e[4] * 256) + e[5] } }\n end",
"def tunnel_peer\n\tend",
"def tunnel_peer\n\tend",
"def get_incoming_server\n @incoming_server\n end",
"def port\n request.port\n end",
"def ip\n @data[\"ip\"]\n end",
"def tunnel_local\n\t\tbegin\n\t\t\trstream.localinfo\n\t\trescue ::Exception\n\t\t\t'127.0.0.1'\n\t\tend\n\tend",
"def ip\n self.IP\n end",
"def local_port\n socket = Socket.new(:INET, :STREAM, 0)\n socket.bind(Addrinfo.tcp(\"127.0.0.1\", 0))\n port = socket.local_address.ip_port\n socket.close\n port\n end",
"def localIP\r\n @@local_ip_address\r\n end",
"def ipaddress\n @network_payload['IP']\n end",
"def getsockname\n Socket.from_sockaddr(super)\n end",
"def peer\r\n \"#{ssl ? 'https://' : 'http://' }#{rhost}:#{rport}\"\r\n end",
"def real_ip\n return @real_ip if @real_ip\n begin\n orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily\n\n UDPSocket.open do |s|\n s.connect '64.233.187.99', 1\n @real_ip = s.addr.last\n end\n ensure\n Socket.do_not_reverse_lookup = orig\n end\n @real_ip\n end",
"def dest_ip\n self[:dest_ip]\n end",
"def blocking_read\n raise RuntimeError, \"RAWIP: blocking_read: Not connected!\" unless connected?\n begin\n loop do\n data, sender = @rsock.recvfrom(8192)\n port, host = Socket.unpack_sockaddr_in(sender)\n #Assume a 20 byte IP header (yuck!)\n return data[20..-1] if host == @dest # only queue packets from our peer\n end\n rescue\n destroy_connection\n raise RuntimeError, \"RAWIP: blocking_read: Couldn't read from socket! (#{$!})\"\n end\n end",
"def fd\n return @sock\n end",
"def socket\n @socket\n end",
"def real_sender()\n\t\tself.received.last\n\tend",
"def post_init\n port, ip = Socket.unpack_sockaddr_in(get_peername)\n host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]\n ActiveRecord::Base.logger.info \"-- Collector connection established from #{host}\"\n end",
"def remote_addr\n nil\n end",
"def packet_length\n self[:ip_len]\n end",
"def local_ip\n orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily\n\n UDPSocket.open do |s|\n s.connect '64.233.187.99', 1\n s.addr.last\n end\n ensure\n Socket.do_not_reverse_lookup = orig\n end",
"def getpeername(*) end",
"def port\n nodes[0][1].to_i\n end",
"def remote_ip; end",
"def on_getaddr\n #addrs = @node.addrs.select{|a| a.time > Time.now.to_i - 10800 }.shuffle[0..250]\n #p \"<< addr (#{addrs.size})\"\n #send_data P::Addr.pkt(*addrs)\n end",
"def getPort()\n return @port\n\tend",
"def listening_port\n @dbi.endpoint.port\n end",
"def listening_port\n @dbi.endpoint.port\n end",
"def server_info\n check_connection\n @protocol.server_info\n end",
"def port\n self.port\n end",
"def getAddress()\n \"#{@mcAddress}:#{@port}\"\n end",
"def remote_ip\n return request.env['HTTP_X_FORWARDED_FOR'] if request.env['HTTP_X_FORWARDED_FOR']\n return request.remote_ip\n end",
"def get_open_port\n socket = Socket.new(:INET, :STREAM, 0)\n socket.bind(Addrinfo.tcp(\"127.0.0.1\", 0))\n port = socket.local_address.ip_port\n socket.close\n port\n end",
"def sendto(gram, peerhost, peerport, flags = 0)\n\n # Catch unconnected IPv6 sockets talking to IPv4 addresses\n peer = Rex::Socket.resolv_nbo(peerhost)\n if (peer.length == 4 and self.ipv == 6)\n peerhost = Rex::Socket.getaddress(peerhost, true)\n if peerhost[0,7].downcase != '::ffff:'\n peerhost = '::ffff:' + peerhost\n end\n end\n\n begin\n send(gram, flags, Rex::Socket.to_sockaddr(peerhost, peerport))\n rescue ::Errno::EHOSTUNREACH,::Errno::ENETDOWN,::Errno::ENETUNREACH,::Errno::ENETRESET,::Errno::EHOSTDOWN,::Errno::EACCES,::Errno::EINVAL,::Errno::EADDRNOTAVAIL\n return nil\n end\n\n end",
"def socket #:nodoc:\n return @socket\n end",
"def ip\n request.env['HTTP_X_FORWARDED_FOR'] || request.remote_ip \n end",
"def peeraddr s\n peeraddrs[s]\n end"
] |
[
"0.7378519",
"0.72397065",
"0.68629676",
"0.6758083",
"0.67207116",
"0.67115855",
"0.6645313",
"0.6644321",
"0.6608145",
"0.6522396",
"0.6482173",
"0.64643216",
"0.64508176",
"0.64470255",
"0.6435942",
"0.64194494",
"0.63981515",
"0.63876337",
"0.6315403",
"0.6253722",
"0.6195651",
"0.6146139",
"0.6129285",
"0.60859096",
"0.6081468",
"0.60602486",
"0.60602486",
"0.60327613",
"0.6024462",
"0.5973988",
"0.5961076",
"0.5960374",
"0.59519374",
"0.5927291",
"0.5900162",
"0.589492",
"0.58555263",
"0.5850634",
"0.5813278",
"0.5754958",
"0.57543284",
"0.5737972",
"0.57310486",
"0.5689246",
"0.565772",
"0.56557155",
"0.56511617",
"0.56475216",
"0.562147",
"0.5620017",
"0.559474",
"0.5584892",
"0.55783254",
"0.5576756",
"0.55639875",
"0.5523578",
"0.5512528",
"0.5508716",
"0.5488384",
"0.5476187",
"0.5474795",
"0.54464924",
"0.5442282",
"0.5442282",
"0.5440474",
"0.5436042",
"0.5412826",
"0.5407492",
"0.5395376",
"0.537402",
"0.53735226",
"0.53720725",
"0.53673834",
"0.5357011",
"0.5356687",
"0.53564817",
"0.53322697",
"0.5326865",
"0.5312752",
"0.53023416",
"0.52995473",
"0.52954715",
"0.5293982",
"0.5292641",
"0.5289768",
"0.528162",
"0.5268956",
"0.5262285",
"0.52559644",
"0.5253698",
"0.5253698",
"0.525344",
"0.5249032",
"0.5247894",
"0.5246992",
"0.52403903",
"0.52381897",
"0.52333975",
"0.52271754",
"0.5226557"
] |
0.68744177
|
2
|
Sets Socket options to allow for multicasting. If ENV["RUBY_TESTING_ENV"] is equal to "testing", then it doesn't turn off multicast looping.
|
def setup_multicast_socket
set_membership(IPAddr.new(MULTICAST_IP).hton + IPAddr.new('0.0.0.0').hton)
set_multicast_ttl(@ttl)
set_ttl(@ttl)
unless ENV["RUBY_TESTING_ENV"] == "testing"
switch_multicast_loop :off
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def socket\n @socket ||= UDPSocket.new.tap do |socket|\n socket.setsockopt Socket::IPPROTO_IP,\n Socket::IP_ADD_MEMBERSHIP,\n multicast_group\n socket.setsockopt Socket::IPPROTO_IP,\n Socket::IP_MULTICAST_TTL,\n 1\n socket.setsockopt Socket::SOL_SOCKET,\n Socket::SO_REUSEPORT,\n 1 \n end\n end",
"def setup_multicast_socket(socket, multicast_address)\n set_membership(socket,\n IPAddr.new(multicast_address).hton + IPAddr.new('0.0.0.0').hton)\n set_multicast_ttl(socket, MULTICAST_TTL)\n set_ttl(socket, MULTICAST_TTL)\n end",
"def configure_server(options={})\n socket.server.set(options)\n end",
"def configure_socket(options, env)\n bind = request_options(env)[:bind]\n return unless bind\n\n options[:bind] = {\n host: bind[:host],\n port: bind[:port]\n }\n end",
"def setsockopt(*) end",
"def setup_broadcast_socket\n set_sock_opt(Socket::SOL_SOCKET, Socket::SO_BROADCAST, true)\n end",
"def setupEventSocket(interface)\n socket = UDPSocket.new\n ip = IPAddr.new(PTP_MULTICAST_ADDR).hton + IPAddr.new(\"0.0.0.0\").hton\n socket.setsockopt(Socket::IPPROTO_IP, Socket::IP_ADD_MEMBERSHIP, ip)\n\n # If we are trying to do HW stamps, we need to initialise the network\n # interface to actually make the timestamps.\n if @ts_mode == :TIMESTAMPHW || true\n\n # Construct the command for the network interface in a slightly crude\n # way according to:\n # https://www.kernel.org/doc/Documentation/networking/timestamping.txt\n hwstamp_config = [0,1,1].pack(\"iii\")\n ifreq = interface.ljust(16,\"\\x00\") + [hwstamp_config].pack(\"P\")\n # Make sure things worked\n if socket.ioctl(SIOCSHWTSTAMP, ifreq) != 0\n @log.error \"Unable to initialise HW stamping\"\n end\n socket.setsockopt(:SOCKET, Socket::SO_TIMESTAMPING, 69)\n #socket.setsockopt(Socket::IPPROTO_IP, Socket::IP_MULTICAST_LOOP, true)\n end\n\n # Enable the software timestamps for comparison\n socket.setsockopt(:SOCKET, :TIMESTAMPNS, true)\n socket.bind(Socket::INADDR_ANY, EVENT_PORT)\n\n return socket\n end",
"def set_socket_time_options(socket)\n socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_TIMESTAMP, true)\n optval = [0, 1].pack(\"l_2\")\n socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_RCVTIMEO, optval)\n end",
"def create_socket\n\t\tiaddr = self.class.bind_addr\n\t\tsocket = UDPSocket.new\n\n\t\tsocket.setsockopt( :IPPROTO_IP, :IP_ADD_MEMBERSHIP, iaddr )\n\t\tsocket.setsockopt( :IPPROTO_IP, :IP_MULTICAST_TTL, self.class.multicast_ttl )\n\t\tsocket.setsockopt( :IPPROTO_IP, :IP_MULTICAST_LOOP, 1 )\n\t\tsocket.setsockopt( :SOL_SOCKET, :SO_REUSEPORT, 1 )\n\n\t\treturn socket\n\tend",
"def setup_socket\n self.socket = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)\n address = Socket.pack_sockaddr_in(@options[:port], @options[:host])\n socket.bind(address)\n socket.listen(@options[:max_connection_queue])\n log.info(\"Listening on #{@options[:host]}:#{@options[:port]}\")\n end",
"def test_em_get_sock_opt_unsupported\n assert true\n end",
"def configure_client(options={})\n socket.client.set(options)\n end",
"def new_socket\n membership = IPAddr.new(@broadcast).hton + IPAddr.new('0.0.0.0').hton\n ttl = [@ttl].pack 'i'\n\n socket = UDPSocket.new\n\n socket.setsockopt Socket::IPPROTO_IP, Socket::IP_ADD_MEMBERSHIP, membership\n socket.setsockopt Socket::IPPROTO_IP, Socket::IP_MULTICAST_LOOP, \"\\000\"\n socket.setsockopt Socket::IPPROTO_IP, Socket::IP_MULTICAST_TTL, ttl\n socket.setsockopt Socket::IPPROTO_IP, Socket::IP_TTL, ttl\n\n socket.bind '0.0.0.0', @port\n\n socket\n end",
"def socket_setup()\n ctx = { 'Msf' => self.options['Msf'], 'MsfExploit' => self.options['MsfExploit'] }\n self.socket = case self.handle.protocol\n\n when 'ncacn_ip_tcp'\n Rex::Socket.create_tcp(\n 'PeerHost' => self.handle.address,\n 'PeerPort' => self.handle.options[0],\n 'Context' => ctx,\n 'Timeout' => self.options['connect_timeout']\n )\n\n when 'ncacn_np'\n begin\n socket = Rex::Socket.create_tcp(\n 'PeerHost' => self.handle.address,\n 'PeerPort' => 445,\n 'Context' => ctx,\n 'Timeout' => self.options['connect_timeout']\n )\n rescue ::Timeout::Error, Rex::ConnectionRefused\n socket = Rex::Socket.create_tcp(\n 'PeerHost' => self.handle.address,\n 'PeerPort' => 139,\n 'Context' => ctx,\n 'Timeout' => self.options['connect_timeout']\n )\n end\n socket\n else nil\n end\n\n # Add this socket to the exploit's list of open sockets\n options['MsfExploit'].add_socket(self.socket) if (options['MsfExploit'])\n end",
"def configure_socket_keepalive\n @socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)\n if defined?(Socket::TCP_KEEPINTVL) # Not available on JRuby\n @socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_KEEPINTVL, 10)\n @socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_KEEPCNT, 5)\n end\n if defined?(Socket::TCP_KEEPIDLE) # Not available on BSD / OSX\n @socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_KEEPIDLE, 50)\n end\n end",
"def initialize **kwargs, &block\n @accept_listeners = []\n register_accept_listener &block if block_given?\n \n # @interface = kwargs.fetch :interface, nil\n @interface = kwargs.fetch :interface, nil\n @port = kwargs.fetch :port, nil\n \n # Automatically select UDP for the multicast range. Otherwise default to TCP.\n default_protocol = :tcp\n \n if @interface\n # TODO: This ivar may be incorrect for UDP -- bound interface is not destination.\n default_protocol = :udp if Ionian::Extension::Socket.multicast? @interface\n default_protocol = :unix if @interface.start_with? '/'\n end\n \n @protocol = kwargs.fetch :protocol, default_protocol\n \n \n # TODO: Move this to #listen.\n case @protocol\n when :tcp\n @interface ||= '0.0.0.0' # All interfaces.\n \n # Parse host out of \"host:port\" if specified.\n host_port_ary = @interface.to_s.split ':'\n @interface = host_port_ary[0]\n @port ||= host_port_ary[1]\n \n raise ArgumentError, \"Port not specified.\" unless @port\n @port = @port.to_i\n \n @server = TCPServer.new @interface, @port\n @server.setsockopt ::Socket::SOL_SOCKET, ::Socket::SO_REUSEADDR, [1].pack('i')\n \n when :udp\n raise ArgumentError, \"UDP should be implemented with Ionian::Socket.\"\n \n when :unix\n raise ArgumentError, \"Path not specified.\" unless @interface\n \n @server = UNIXServer.new @interface\n end\n \n listen if block_given?\n end",
"def initialize options = {}\n options[:DoNotListen] = true\n sockets_key = options.delete(:LaunchdSockets) || 'WEBrickSockets'\n\n super\n\n launch_checkin\n\n servers = launch_sockets sockets_key, TCPServer\n\n listeners.replace servers\n\n trap 'TERM' do shutdown end\n end",
"def initialize(*args)\n super\n register_advanced_options([ OptString.new('PayloadBindPort', [false, 'Port to bind reverse tcp socket to on target system.']) ], self.class)\n end",
"def get_options\n ARGV.options { |opt|\n opt.banner = \"Usage: ruby #{__FILE__} [options] ipv6addr port\"\n\n opt.on(\"--help\", \"What you see right now\"){ puts opt; exit 0}\n\n opt.on(\"--doc=DIRECTORY\", String, \"Output rdoc (Ruby HTML documentation) into directory\"){|dir|\n system(\"rdoc -o #{dir} #{__FILE__}\")\n }\n\n opt.on(\"--verbose\", \"-v\", \"print space separated timestamps to STDOUT\"){|@verbose|}\n\n opt.on(\"--interval=FLOAT\", \"-i\", Float, \"approximate interval to send packets at will sleep for this many seconds before sending. Not very accurate when doing less than 0.01. Will divide interval by 1000 when < 0.01 (inteval of 0.001 effective to reduce send interval to less than 0.01 but suddenly jumps up to 0.00005 and 100% cpu time) Probably need proper scheduling besides sleep to get better accuracy\"){|@interval|\n puts \"using interval of #{@interval}\" if not @verbose\n }\n\n opt.on(\"--data=STRING\", \"-d\", String, \"payload to send (by default sends timestamp\",\n \"like this #{Time.now().to_f})\"){|@payload|\n @use_payload = true\n puts \"using payload of #{@payload}\" if not @verbose\n }\n\n opt.on(\"-r\", \"Receive mode \"){|@receive|}\n\n opt.on_tail(\"default port is #{@port}\")\n opt.parse!\n } or exit(1);\n\n if @quit\n pp self\n (print ARGV.options; exit)\n end\n\n raise \"Missing host from the commandline.\" if ARGV.size < 1\n\n @host = ARGV.shift\n\n @port = ARGV.shift if not ARGV.empty?\n\n end",
"def setup(options = {})\n setup_events(options)\n setup_broadcast\n end",
"def configure_server(options = T.unsafe(nil)); end",
"def mode=(m)\n case m\n when :udp then attributes['mode'] = 'udp'\n else attributes['mode'] = 'tcp'\n end\n end",
"def initialize(options = {}, &block)\n options = options.dup\n @server = options.delete(:server)\n @udp_flags = options.delete(:udp_flags) || 0\n raise(ArgumentError, 'Missing mandatory argument: :server') unless @server\n\n super(options, &block)\n reopen\n end",
"def initialize options\n # stats\n\n @stats = {}\n\n clear_stats\n\n if options[:host]\n port = options[:port]\n port = DEFAULT_PORT if port.nil?\n @socket = TCPSocket.new options[:host], port\n elsif options[:socket]\n @socket = options[:socket]\n end\n\n @number = 0\n\n set_options options\n end",
"def initialize(options)\n @ip = options[:ip]\n @port = options[:port]\n @inport = options[:inport]\n @socket = nil\n @reply_id = USHRT_MAX - 1\n @data_recv = ''\n @session_id = 0\n end",
"def set_up_local_ports\n if @unix\n @udp_socket = Socket.new(:UNIX, :DGRAM, 0)\n address = Addrinfo.unix(@unix)\n @udp_socket.bind(address)\n else\n @udp_socket = UDPSocket.new\n @udp_socket.bind nil, @port\n end\n @logger.debug \"Binding UDP socket localhost:#{@port}\"\n @tcp_socket = nil\n end",
"def prepare_socket_server!\n _log { \"prepare_socket_server! #{port}\" }\n @server = TCPServer.open(port)\n @server.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, false)\n end",
"def send(message)\n\t\t\t\t \tsocket = UDPSocket.open\n\t\t\t\t \tsocket.setsockopt(Socket::IPPROTO_IP, Socket::IP_TTL, [1].pack('i'))\n\t\t\t\t \tsocket.send(message.to_json, 0, @multicast_address, @multicast_port)\n\t\t\t\tensure\n\t\t\t\t \tsocket.close \n\t\t\t\tend",
"def set_multicast_group(name = 'Vxlan1', opts = {})\n commands = command_builder('vxlan multicast-group', opts)\n configure_interface(name, commands)\n end",
"def setsockopt(name_or_const, value)\n const = xs_const name_or_const\n assert_rc @sock.setsockopt(const, value)\n end",
"def initsock(params = nil)\n if (params)\n self.peerhost = params.peerhost\n self.peerhostname = params.peerhostname\n self.peerport = params.peerport\n self.localhost = params.localhost\n self.localport = params.localport\n self.context = params.context || {}\n self.ipv = params.v6 ? 6 : 4\n end\n end",
"def SetMtu(node)\n\t@interfaces.each do |ifn|\n\t self.GetGroupInterface(node, ifn).mtu=\"1528\"\n\tend\n end",
"def init_socket\n @socket = Sockets::MasterServerSocket.new @ip_address, @port\n end",
"def reset!\n BasicSocket.do_not_reverse_lookup = true\n @desired_port = preferred_port\n begin\n @socket.close if @socket\n rescue IOError\n # Already closed\n end\n @socket = UDPSocket.new\n end",
"def options\n @networkmode.blank? ? __options__.merge(__name__) : __options__\n end",
"def reset\n @socket = self.class.context { |c| c.socket(ZMQ::REQ) }\n @socket.connect @address\n end",
"def to_options(options = {})\n options.merge(\n wsHost: socket_options[:host],\n wsPort: socket_options[:port],\n cluster: \"us-east-1\",\n forceTLS: false,\n disableStats: disable_stats\n )\n end",
"def set_mtu(name, opts = {})\n cmds = command_builder('mtu', opts)\n configure_interface(name, cmds)\n end",
"def socket(options = {})\n @socket ||= Net::SSH::Test::Socket.new\n end",
"def daemon=(options = {})\n if options.respond_to?(:keys)\n daemon.bind = options[:bind] if options[:bind]\n daemon.port = options[:port] if options[:port]\n daemon.log_file = options[:log_file] if options[:log_file]\n daemon.timer = options[:timer] if options[:timer]\n end\n end",
"def setup\n @log = Logger['MedRuleAgentServerTest']\n\t\t@socket = TCPSocket.new('localhost', 1729)\n end",
"def setup_mailer\n if self.ssl\n self.port = DEFAULT_SSL_PORT if self.port.nil?\n else\n self.port = DEFAULT_PORT if self.port.nil?\n end\n\n if old_server != server or old_port != port\n @mailer = Net::POP3.new( self.server, self.port )\n end\n\n if self.ssl\n @mailer.enable_ssl\n else\n @mailer.disable_ssl\n end\n\n # keep track of old server and port\n self.old_server = self.server\n self.old_port = self.port\n end",
"def setup_options\n @options = {\n :min_threads => 0,\n :max_threads => 16,\n :quiet => false,\n :debug => false,\n :binds => [],\n :workers => 0,\n :daemon => false,\n :before_worker_shutdown => [],\n :before_worker_boot => [],\n :before_worker_fork => [],\n :after_worker_boot => []\n }\n\n @parser = OptionParser.new do |o|\n o.on \"-b\", \"--bind URI\", \"URI to bind to (tcp://, unix://, ssl://)\" do |arg|\n @options[:binds] << arg\n end\n\n o.on \"-C\", \"--config PATH\", \"Load PATH as a config file\" do |arg|\n @options[:config_file] = arg\n end\n\n o.on \"--control URL\", \"The bind url to use for the control server\",\n \"Use 'auto' to use temp unix server\" do |arg|\n if arg\n @options[:control_url] = arg\n elsif jruby?\n unsupported \"No default url available on JRuby\"\n end\n end\n\n o.on \"--control-token TOKEN\",\n \"The token to use as authentication for the control server\" do |arg|\n @options[:control_auth_token] = arg\n end\n\n o.on \"-d\", \"--daemon\", \"Daemonize the server into the background\" do\n @options[:daemon] = true\n @options[:quiet] = true\n end\n\n o.on \"--debug\", \"Log lowlevel debugging information\" do\n @options[:debug] = true\n end\n\n o.on \"--dir DIR\", \"Change to DIR before starting\" do |d|\n @options[:directory] = d.to_s\n @options[:worker_directory] = d.to_s\n end\n\n o.on \"-e\", \"--environment ENVIRONMENT\",\n \"The environment to run the Rack app on (default development)\" do |arg|\n @options[:environment] = arg\n end\n\n o.on \"-I\", \"--include PATH\", \"Specify $LOAD_PATH directories\" do |arg|\n $LOAD_PATH.unshift(*arg.split(':'))\n end\n\n o.on \"-p\", \"--port PORT\", \"Define the TCP port to bind to\",\n \"Use -b for more advanced options\" do |arg|\n @options[:binds] << \"tcp://#{Configuration::DefaultTCPHost}:#{arg}\"\n end\n\n o.on \"--pidfile PATH\", \"Use PATH as a pidfile\" do |arg|\n @options[:pidfile] = arg\n end\n\n o.on \"--preload\", \"Preload the app. Cluster mode only\" do\n @options[:preload_app] = true\n end\n\n o.on \"--prune-bundler\", \"Prune out the bundler env if possible\" do\n @options[:prune_bundler] = true\n end\n\n o.on \"-q\", \"--quiet\", \"Quiet down the output\" do\n @options[:quiet] = true\n end\n\n o.on \"-R\", \"--restart-cmd CMD\",\n \"The puma command to run during a hot restart\",\n \"Default: inferred\" do |cmd|\n @options[:restart_cmd] = cmd\n end\n\n o.on \"-S\", \"--state PATH\", \"Where to store the state details\" do |arg|\n @options[:state] = arg\n end\n\n o.on '-t', '--threads INT', \"min:max threads to use (default 0:16)\" do |arg|\n min, max = arg.split(\":\")\n if max\n @options[:min_threads] = min\n @options[:max_threads] = max\n else\n @options[:min_threads] = 0\n @options[:max_threads] = arg\n end\n end\n\n o.on \"--tcp-mode\", \"Run the app in raw TCP mode instead of HTTP mode\" do\n @options[:mode] = :tcp\n end\n\n o.on \"-V\", \"--version\", \"Print the version information\" do\n puts \"puma version #{Puma::Const::VERSION}\"\n exit 1\n end\n\n o.on \"-w\", \"--workers COUNT\",\n \"Activate cluster mode: How many worker processes to create\" do |arg|\n @options[:workers] = arg.to_i\n end\n\n o.on \"--tag NAME\", \"Additional text to display in process listing\" do |arg|\n @options[:tag] = arg\n end\n\n o.banner = \"puma <options> <rackup file>\"\n\n o.on_tail \"-h\", \"--help\", \"Show help\" do\n log o\n exit 1\n end\n end\n end",
"def set_multicast\n @multicast = Multicast.find(params[:id])\n end",
"def set_server_option(opt)\n check_connection\n @protocol.set_option_command opt\n self\n end",
"def test_ipv6_udp_local_server\n @@received_data = nil\n @local_port = next_port\n @@remote_ip = nil\n setup_timeout(2)\n\n EM.run do\n EM.open_datagram_socket(@@public_ipv6, @local_port) do |s|\n def s.receive_data data\n _port, @@remote_ip = Socket.unpack_sockaddr_in(get_peername)\n @@received_data = data\n EM.stop\n end\n end\n\n EM.open_datagram_socket(@@public_ipv6, next_port) do |c|\n c.send_datagram \"ipv6/udp\", @@public_ipv6, @local_port\n end\n end\n assert_equal @@remote_ip, @@public_ipv6\n assert_equal \"ipv6/udp\", @@received_data\n end",
"def initialize( * )\n\t\t@multicast_address = self.class.multicast_address\n\t\t@port = self.class.port\n\t\t@socket = self.create_socket\n\tend",
"def getsockopt(*) end",
"def initialize(options={})\n @multi_message_max_count = 0\n \n self.host = options[:host] || DEFAULT_HOST\n self.port = options[:port] || DEFAULT_PORT\n end",
"def initialize(options={})\n @server_list = ServerList.new\n @groups = Hash.new { |h,k| h[k] = ServerList.new }\n @gateway = nil\n @open_groups = []\n @connect_threads = []\n @on_error = :fail\n @default_user = ENV['USER'] || ENV['USERNAME'] || \"unknown\"\n\n @open_connections = 0\n @pending_sessions = []\n @session_mutex = Mutex.new\n\n options.each { |opt, value| send(\"#{opt}=\", value) }\n end",
"def on_rpl_isupport(m)\n @server_config.set(m)\n end",
"def initialize(options = {})\n @seq = 0\n @bind_port = 0\n @bind_host = nil\n @data_size = 56\n\n @ping_id = (Thread.current.object_id ^ Process.pid) & 0xffff\n\n super(options)\n end",
"def test_options\n base_test_options.merge(connect_options).\n merge(ssl_options).merge(compressor_options).merge(retry_writes_options)\n end",
"def snmp_notification_receiver_set(opts = {})\n configure snmp_notification_receiver_cmd(opts)\n end",
"def notification=(options = {})\n if options.respond_to?(:keys)\n notification.port = options[:port] if options[:port]\n notification.host = options[:host] if options[:host]\n end\n end",
"def set_agent_listen_address(opts)\n opts = check_params(opts,[:agent_listen_addresses])\n super(opts)\n end",
"def initialize(options={})\n @host = options.fetch(:host)\n @port = options.fetch(:port)\n @use_ssl = options.fetch(:use_ssl, false)\n @logger = options.fetch(:logger, nil)\n @max_retries = options.fetch(:max_retries, DEFAULT_MAX_RETRIES)\n @max_connect_retries = options.fetch(:max_connect_retries, DEFAULT_MAX_CONNECT_RETRIES)\n @connect_retry_wait = options.fetch(:connect_retry_wait, DEFAULT_CONNECT_RETRY_WAIT)\n @msgid = 1\n @call_mutex = Mutex.new\n init_socket\n end",
"def set_rtcp_port(opts)\n opts = check_params(opts,[:ports])\n super(opts)\n end",
"def set_bridge_multicast_state(opts)\n opts = check_params(opts,[:states])\n super(opts)\n end",
"def set_mtu(opts)\n opts = check_params(opts,[:mtus])\n super(opts)\n end",
"def set_mtu(opts)\n opts = check_params(opts,[:mtus])\n super(opts)\n end",
"def initialize(info = {})\n super\n\n register_options(\n [\n Opt::LHOST,\n Opt::LPORT(4444)\n ], Msf::Handler::ReverseUdp)\n\n # XXX: Not supported by all modules\n register_advanced_options(\n [\n OptAddress.new('ReverseListenerBindAddress', [ false, 'The specific IP address to bind to on the local system']),\n OptInt.new('ReverseListenerBindPort', [ false, 'The port to bind to on the local system if different from LPORT' ]),\n OptString.new('ReverseListenerComm', [ false, 'The specific communication channel to use for this listener']),\n OptBool.new('ReverseListenerThreaded', [ true, 'Handle every connection in a new thread (experimental)', false])\n ] +\n Msf::Opt::stager_retry_options,\n Msf::Handler::ReverseUdp)\n\n self.conn_threads = []\n end",
"def options\n result = options_pre_mizuno\n result[:reuse_address] = true\n result\n end",
"def initialize(options = {})\n @options = DEFAULT_OPTIONS.merge options\n @protocol_options = (options.delete(:protocol) || {}).dup\n @run = true\n @thread_list = []\n @protocols = []\n end",
"def set_options(opt)\n @speed = opt[:speed] || 115200\n @model = opt[:model] || :reprap\n\n # 0 - Blocking indefinitely, -1 nonblocking.\n @blocking = 0\n end",
"def send_multicast(multicast_message, dry_run: false)\n messages = multicast_message.tokens.map do |token|\n Message.new(\n token: token,\n data: multicast_message.data,\n notification: multicast_message.notification,\n android: multicast_message.android,\n apns: multicast_message.apns,\n fcm_options: multicast_message.fcm_options\n )\n end\n send_all(messages, dry_run: dry_run)\n end",
"def set_socket\r\n @socket = TCPSocket.new(@server, @port) \r\n end",
"def initialize( * )\n\t\t@socket = UDPSocket.new\n\tend",
"def options_setting\n if OPTS[:s] then @@server = OPTS[:s] else @@server = SERVER end\n if OPTS[:p] then @@port = OPTS[:p].to_i else @@port = PORT.to_i end\n if OPTS[:n] then @@nick = OPTS[:n] else @@nick = NICK end\n\n # channel character (no # or head #)\n if OPTS[:c] then\n channel = OPTS[:c]\n if channel.start_with?(\"#\") == false then\n @@channel = \"#\" + channel\n else\n @@channel = channel\n end\n else\n @@channel = \"\"\n end\n if OPTS[:t] then @@topic = OPTS[:t] else @@topic = \"\" end\n end",
"def configure_tcp_server(tcp_server)\n tcp_server.setsockopt(::Socket::IPPROTO_TCP, ::Socket::TCP_NODELAY, true)\n end",
"def socket=(s)\n unless(s.respond_to?(:<<))\n raise ArgumentError.new('Please supply a socket')\n end\n @socket = s\n end",
"def set_port\n\t\tself.port = 389 if self.port == 0\n\tend",
"def default_socket_class=(_arg0); end",
"def multicast\n readConfig unless @@ClusterConfig\n addr=/<multicast addr=\"([^\"]*)\"/.match(@@ClusterConfig)\n return addr[1] unless addr.nil?\n end",
"def multicast_group\n IPAddr.new(address).hton + IPAddr.new(LOCAL_ADDRESS).hton\n end",
"def setup(options)\n @nick = options['nick'] if options['nick']\n @server = options['server'] if options['server']\n @port = options['port'].to_i if options['port']\n connect\n end",
"def create_datagram_socket(options=nil)\n if !block_given? && options == nil\n return ::Vertx::Util::Utils.safe_create(@j_del.java_method(:createDatagramSocket, []).call(),::Vertx::DatagramSocket)\n elsif options.class == Hash && !block_given?\n return ::Vertx::Util::Utils.safe_create(@j_del.java_method(:createDatagramSocket, [Java::IoVertxCoreDatagram::DatagramSocketOptions.java_class]).call(Java::IoVertxCoreDatagram::DatagramSocketOptions.new(::Vertx::Util::Utils.to_json_object(options))),::Vertx::DatagramSocket)\n end\n raise ArgumentError, \"Invalid arguments when calling create_datagram_socket(options)\"\n end",
"def initialize_server(port)\r\n set :port, port # Specify Port For Sinatra Server\r\n set :bind, \"0.0.0.0\" # Allow Ping From External Devices\r\n set :environment, :production # Allow External Nodes To Query Websocket\r\n set :run, true # Start Sinatra Server\r\nend",
"def setup_non_blocking_methods\n read_mod = @socket.respond_to?(:read_nonblock) ? NonblockingRead :\n BlockingRead\n write_mod = @socket.respond_to?(:write_nonblock) ? NonblockingWrite :\n BlockingWrite\n self.extend read_mod\n self.extend write_mod\n end",
"def disable(patch)\n @socket.disable\n end",
"def ws_options\n {\n host: Socket2me.config.ws_host,\n port: Socket2me.config.ws_port\n }\n end",
"def define_addrinfo_by_netmask_or_default\n # default ('host' mask)\n @options[:netmask] = 32 unless @options.key?(:netmask)\n define_addrinfo_with_netmask\n end",
"def set_servers(servers)\n Array(servers).each_with_index do |server, index|\n # Socket\n check_return_code(\n if server.is_a?(String) and File.socket?(server)\n args = [@struct, server, options[:default_weight].to_i]\n Lib.memcached_server_add_unix_socket_with_weight(*args)\n # Network\n elsif server.is_a?(String) and server =~ /^[\\w\\d\\.-]+(:\\d{1,5}){0,2}$/\n host, port, weight = server.split(\":\")\n args = [@struct, host, port.to_i, (weight || options[:default_weight]).to_i]\n if options[:use_udp]\n Lib.memcached_server_add_udp_with_weight(*args)\n else\n Lib.memcached_server_add_with_weight(*args)\n end\n else\n raise ArgumentError, \"Servers must be either in the format 'host:port[:weight]' (e.g., 'localhost:11211' or 'localhost:11211:10') for a network server, or a valid path to a Unix domain socket (e.g., /var/run/memcached).\"\n end\n )\n end\n end",
"def send_udp_broadcast packet\n\t\t\tudp = UDPSocket.new\n\t\t\tudp.setsockopt(:IPPROTO_IP, :IP_MULTICAST_TTL, 1)\n\t\t\tudp.send packet.to_str, 0, MULTICAST_ADDR, @udp_port\n\t\t\tudp.close\n\t\tend",
"def initialize(app, socket, options = {})\n @app = app\n @socket = socket\n @options = options\n @debug = options[:debug] || false\n @ssl = socket.backend.respond_to?(:ssl?) && socket.backend.ssl?\n\n socket.websocket = self\n socket.comm_inactivity_timeout = 0\n\n debug [:initialize]\n end",
"def default_socket_class; end",
"def bind_listen(address = '0.0.0.0:8080', opt = {})\n return address unless String === address\n\n sock = if address[0] == ?/\n if File.exist?(address)\n if File.socket?(address)\n begin\n UNIXSocket.new(address).close\n # fall through, try to bind(2) and fail with EADDRINUSE\n # (or succeed from a small race condition we can't sanely avoid).\n rescue Errno::ECONNREFUSED\n logger.info \"unlinking existing socket=#{address}\"\n File.unlink(address)\n end\n else\n raise ArgumentError,\n \"socket=#{address} specified but it is not a socket!\"\n end\n end\n old_umask = File.umask(opt[:umask] || 0)\n begin\n Kgio::UNIXServer.new(address)\n ensure\n File.umask(old_umask)\n end\n elsif /\\A\\[([a-fA-F0-9:]+)\\]:(\\d+)\\z/ =~ address\n new_tcp_server($1, $2.to_i, opt.merge(:ipv6=>true))\n elsif /\\A(\\d+\\.\\d+\\.\\d+\\.\\d+):(\\d+)\\z/ =~ address\n new_tcp_server($1, $2.to_i, opt)\n else\n raise ArgumentError, \"Don't know how to bind: #{address}\"\n end\n set_server_sockopt(sock, opt)\n sock\n end",
"def request_listen\n send_command RemoteListenCommand.new(@client.remote_listen_address)\n enable_tunnel_timeouts \n end",
"def initialize(options = {})\n @port = 7\n @service_check = false\n @data_must_match = true\n @data = \"net-ping2\\n\"\n @timeout = 10\n @bind_host = nil\n @bind_port = nil\n super(options)\n end",
"def initialize(app, socket, options = {})\n @app = app\n @socket = socket\n @options = options\n @debug = options[:debug] || false\n @ssl = socket.backend.respond_to?(:ssl?) && socket.backend.ssl?\n\n socket.websocket = self\n socket.comm_inactivity_timeout = 0\n\n debug [:initialize]\n end",
"def initialize(info = {})\n\t\tsuper\n\n\t\tregister_options(\n\t\t\t[\n\t\t\t\tOpt::LPORT(4444),\n\t\t\t\tOptAddress.new('RHOST', [false, 'The target address', '']),\n\t\t\t], Msf::Handler::BindTcp)\n\n\t\tself.conn_threads = []\n\t\tself.listener_threads = []\n\t\tself.listener_pairs = {}\n\tend",
"def initialize(info = {})\n\t\tsuper\n\t\tregister_options(\n\t\t\t[\n\t\t\t\tOpt::LPORT(4444),\n\t\t\t\t#OptAddress.new('RHOST', [false, 'The target address', '']),\n\t\t\t], Msf::Handler::BeEFBind)\n\tend",
"def server_flags; end",
"def bind_broadcast\n begin\n bsock = UDPSocket.open\n bsock.setsockopt :SOL_SOCKET, :SO_BROADCAST, 1\n bsock.setsockopt :SOL_SOCKET, :SO_REUSEADDR, 1\n bsock.bind '', RNCP::PORT\n return bsock\n rescue\n puts \"[!] Broadcast not supported\"\n return nil\n end\n end",
"def initialize(options={})\n @ssl = options.delete(:ssl)\n @port = options.delete(:port) || Net::POP3.default_port\n super(options)\n end",
"def send(options={})\n end",
"def nodelay=(flag)\n ensure_state :connected\n @socket.setsockopt(::Socket::IPPROTO_TCP, ::Socket::TCP_NODELAY, flag ? 1 : 0)\n end",
"def initialize(info = {})\n super\n\n # XXX: Not supported by all modules\n register_advanced_options(\n [\n OptAddress.new(\n 'ReverseListenerBindAddress',\n [ false, 'The specific IP address to bind to on the local system' ]\n ),\n OptBool.new(\n 'ReverseListenerThreaded',\n [ true, 'Handle every connection in a new thread (experimental)', false ]\n )\n ] +\n Msf::Opt::stager_retry_options,\n Msf::Handler::ReverseTcp\n )\n\n self.conn_threads = []\n end",
"def configure_ports(interface, min_port)\n interface ||= \"127.0.0.1\"\n min_port ||= 8080\n unless env[:riak_core][:http]\n env[:riak_core][:http] = [Tuple[interface, min_port]]\n min_port += 1\n end\n env[:riak_core][:http] = env[:riak_core][:http].map {|pair| Tuple[*pair] }\n env[pb_config_section][:pb_ip] = interface unless env[pb_config_section][:pb_ip]\n unless env[pb_config_section][:pb_port]\n env[pb_config_section][:pb_port] = min_port\n min_port += 1\n end\n unless env[:riak_core][:handoff_port]\n env[:riak_core][:handoff_port] = min_port\n min_port += 1\n end\n end",
"def override_ffserver\n @override_ffserver = true\n end"
] |
[
"0.6720747",
"0.6434258",
"0.6337197",
"0.6265162",
"0.61841965",
"0.5984235",
"0.5704508",
"0.5697548",
"0.566056",
"0.5625054",
"0.5582187",
"0.55817896",
"0.55669034",
"0.54880464",
"0.5358894",
"0.5306145",
"0.5298759",
"0.5297812",
"0.5286206",
"0.5280641",
"0.5195248",
"0.5192151",
"0.5151337",
"0.51398134",
"0.51344675",
"0.5116742",
"0.5088626",
"0.50612473",
"0.5045762",
"0.50452405",
"0.5006047",
"0.49992147",
"0.49804142",
"0.49709147",
"0.4955224",
"0.49368843",
"0.49115127",
"0.4910153",
"0.49071863",
"0.4899987",
"0.4895506",
"0.48878196",
"0.48672387",
"0.48640013",
"0.4859529",
"0.4848044",
"0.48220763",
"0.47974303",
"0.47951514",
"0.47859216",
"0.47846425",
"0.47772056",
"0.4775292",
"0.47725996",
"0.47721088",
"0.4770388",
"0.47698605",
"0.4763154",
"0.47577056",
"0.47556892",
"0.47556892",
"0.4753761",
"0.47523335",
"0.47511363",
"0.47493267",
"0.47335982",
"0.47238937",
"0.4714747",
"0.470689",
"0.4699824",
"0.46905977",
"0.46829033",
"0.46784168",
"0.4676896",
"0.46738422",
"0.465546",
"0.46511626",
"0.4641809",
"0.46412924",
"0.46399942",
"0.46372426",
"0.4633202",
"0.4623861",
"0.4618354",
"0.46133098",
"0.4590777",
"0.45906976",
"0.45883462",
"0.45883244",
"0.4585839",
"0.45722896",
"0.45680815",
"0.4564807",
"0.4561599",
"0.4555514",
"0.45518303",
"0.45482478",
"0.4540857",
"0.45379573",
"0.45258558"
] |
0.75971866
|
0
|
Element reference. Retrieves the value object corresponding to the key object. Returns nil if the key is not found. Raises an exception if the stored item raised an exception when the block was evaluated.
|
def [](key)
delay = data[key]
delay ? delay.value! : nil
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def get(key)\n position = find(key)\n if position != nil\n @values[position]\n else\n nil\n end\n end",
"def [](key)\n current_node = @buckets[index(key, size)].head\n if !current_node\n #raise InvalidKeyError \"Cannot retrieve that item - not instantiated\"\n return nil\n end\n while current_node.key != key\n current_node = current_node.next\n break unless current_node\n end\n\n if !current_node\n #raise InvalidKeyError \"Cannot retrieve that item - not instantiated\"\n return nil\n end\n\n return current_node.value\n end",
"def find(key)\n # TODO(himanshujaju) - possible improvement by not checking for contains.\n if contains?(key)\n return @key_data[key].value\n end\n\n return nil\n end",
"def get(key)\n return nil unless @items.key?(key)\n @items[key].call\n end",
"def get(key, &block)\n do_with_logging(:get, key) do\n retryable do\n val = self.adapter.get(key)\n handle_store_object(key, adapter.unmarshal(val), &block)\n end\n end\n end",
"def [](key)\n if (@items[index(key, size)] != nil) &&\n @items[index(key, size)].key == key\n @items[index(key, size)].value\n end\n end",
"def [](key)\n @lock.synchronize do\n ref = @references[key]\n value = ref.object if ref\n value\n end\n end",
"def get(key)\n index = key_index(key)\n if( index )\n @i_values.get(index)\n else\n nil\n end\n end",
"def fetch(key, value = nil)\n if read = self[key]\n return read\n end\n block_given? ? yield(key) : value\n end",
"def get_item(key)\n self[key]\n end",
"def value\n v = connection.get(key)\n rescue Memcached::NotFound\n if block\n value = block.call\n value\n end\n end",
"def fetch(key)\n if key.empty?\n return @value\n end\n child = @children[key.shift]\n if child\n child.fetch(key)\n else\n return nil\n end\n end",
"def [](key)\n return nil if @collection.nil?\n return_item_value key\n end",
"def get(key)\n index = key_index(key)\n if( index )\n self.values.get(index)\n else\n nil\n end\n end",
"def get(key)\r\n\t\treturn nil if !key\r\n\t\t# Get the hash of our key\r\n\t\tindex = key.hash % @size\r\n\t\t# If location in array is empty then return nil otherwise find the \r\n\t\t# key and return associated value from the list\r\n\t\treturn nil if !@arr[index]\r\n\t\treturn @arr[index].find(key)\r\n\tend",
"def value_for_data(key, item, value_key = :value)\n if item and item[:data] and item[:data][key]\n return item[:data][key][value_key]\n end\n return nil\n end",
"def get(key)\n position = search(key)\n return nil if (key <=> @keys[position]) != 0\n @values[position]\n end",
"def find(key)\n node = find_node(key)\n (node == nil ? nil : node.value)\n end",
"def [](key)\n result = default(key)\n result ? result.value : nil\n end",
"def get(key, &block)\n return if key.nil?\n @_lock.synchronize do\n if !has_key?(key.to_sym) && block_given?\n value = yield\n _publish(key.to_sym, :set, nil, value)\n store(key.to_sym, value)\n else\n self[key.to_sym]\n end\n end\n end",
"def [](key)\n find_value(key)\n end",
"def [](key)\n index = self.index(key, @items.length)\n if !@items[index].nil?\n current = @items[index].head\n until current.nil?\n if current.key === key\n return current.value\n else\n current = current.next\n end\n end\n end\n end",
"def [](key)\n @lock.synchronize do\n rkey = ref_key(key)\n @values[rkey] if rkey\n end\n end",
"def get_key_value(key)\n if v = storage.get(key.object_id)\n return key.object_id, v\n end\n storage.get_candidates(key.hash).find do |k,v|\n candidate_key = get_object(k) or next\n candidate_key.eql? key\n end\n end",
"def find(key)\n if !contains?(key)\n return nil\n end\n\n @semaphore.synchronize {\n @internal_clock += 1\n previous_data = @key_data[key]\n update_access_time_locked(key, @internal_clock, previous_data.access_time)\n\n return previous_data.value\n }\n end",
"def get(key)\n node = node_for_key(key)\n node.read(&@block)\n end",
"def [](key)\n if @items[index(key, @items.length)] != nil && @items[index(key, @items.length)].key == key\n puts @items.length\n return @items[index(key, @items.length)].value\n else\n puts \"This value does not exist in the hash\"\n end\n end",
"def [](key = nil)\n return @collection unless key\n\n result = @collection.find { |f| f.name == key }\n return result.value if result\n\n nil\n end",
"def [](key)\n dummy = Pair.new(key,nil)\n pair = @tree.get(dummy)\n return nil unless pair\n return pair.value\n end",
"def getValue(key)\r\n \r\n return @aHash[key]\r\n end",
"def get(key)\n return -1 if @h[key].nil?\n cut_list_item_and_put_it_first @h[key]\n @h[key].v\n end",
"def peek_item(key)\n leaf = find_key(key)\n return nil unless leaf\n leaf.peek_item\n end",
"def fetch(key)\n @monitor.synchronize do\n found, value = get(key)\n found ? value : store(key, yield)\n end\n end",
"def get_value(key)\n self[key]\n end",
"def get(key)\n node = get_rec(@root, key, 0)\n return nil if node.nil?\n return node.value\n end",
"def get(key)\n node = _get(@root, key)\n return nil unless node\n node.value\n end",
"def get_value(item, key, default: nil, **)\n return if key.blank?\n if key.is_a?(Array)\n key.find { |k| (v = get_value(item, k)) and break v }\n elsif item.respond_to?(key)\n item.send(key)\n elsif item.respond_to?(:emma_metadata) # Upload, etc.\n item.emma_metadata&.dig(key.to_sym)\n elsif item.is_a?(Hash)\n item[key.to_sym] || item[key.to_s]\n end.presence || default\n end",
"def get(key, &block)\n @store.synchronize do\n @store.get(key, &block)\n end\n end",
"def get_item_value(key)\n @attributes[key] = get_item_record(key) unless @attributes.has_key?(key)\n @attributes[key]\n end",
"def get(key, expires_in = 0, &block)\n\n #look for the cache item in the store\n items = @store.select { |i| i[:key] == build_key(key) }\n item = if !items.empty? then items[0] else nil end\n #check if a valid item was found in the store\n if item == nil || (item[:expires] != nil && item[:expires] <= Time.now.utc)\n #a valid item wasn't found so check if a hydration block was specified.\n if block_given?\n #create the item from the block\n value = yield\n #put the item in the store\n set(build_key(key), value, expires_in)\n return value\n else\n #no hydration block was specified\n\n #check if an expired item was found\n if item != nil\n #remove the expired item from the store\n remove(build_key(key))\n end\n return nil\n end\n end\n\n #return the item\n return item[:value]\n end",
"def find(key)\n if @root.nil?\n return nil\n elsif @root.key == key\n return @root.value\n else\n find_helper(@root, key)\n end\n end",
"def [](key)\n entry = find_entry(key)\n return(entry.nil? ? nil : entry[1])\n end",
"def fetch_value( oid, key )\n\t\toid = normalize_oid( oid )\n\t\tkey = normalize_key( key )\n\t\tdata = @storage[ oid ] or return nil\n\n\t\treturn data[ key ]\n\tend",
"def retrieve(key)\n found_element = @lookup[key]\n\n if found_element\n prev_elem = found_element.prev_elem\n Element.swap found_element.prev_elem, found_element\n @head = found_element if found_element.prev_elem.nil?\n @tail = prev_elem if prev_elem&.next_elem.nil?\n found_element.read\n end\n end",
"def [](key)\n @monitor.synchronize do\n _, value = get(key)\n value\n end\n end",
"def fetch( key, &block )\n fail NotImplementedError\n end",
"def element_value\n # Uses reduce to dig through the provided object to look for and return the\n # provided key that could be nested\n path = json_form.element_path_for_object(full_key, ignore_keys: %w(items properties))\n path.pop if path.last == 'index_id'\n\n # If an index is provided, insert it into the path\n unless options['index'].nil?\n if path.size == 1\n path << options['index']\n else\n path.insert(path.size - 1, options['index'])\n end\n end\n if options['indexes']\n if path.index('index_id')\n Array.wrap(options['indexes']).each do |index|\n path[path.index('index_id')] = index\n end\n end\n end\n\n # Look up the value in the object at the specified path\n path.reduce(json_form.object) { |a, e| a[e] }\n rescue\n nil\n end",
"def [](key)\n return @item[key]\n end",
"def value_of(key)\n @root.value_of(key)\n end",
"def value(key)\n @hash[key]\n end",
"def [](key)\n entry = @data.find { |d| d[:key] == key && d[:operation] != :remove }\n return entry[:value] if entry\n\n nil\n end",
"def try_get(namespace, key)\n begin\n return get(namespace, key)\n rescue ItemNotFoundError\n return nil\n end\n end",
"def get(key)\n @hash.get(key)\n end",
"def get(key, lifetime: 2**32, dirty: false, &block)\n if block_given?\n return @hash[key][:value] if (dirty || @dirty) && locked? && expired?(key) && @hash.key?(key)\n synchronized { calc(key, lifetime, &block) }\n else\n rec = @hash[key]\n if expired?(key)\n return rec[:value] if dirty || @dirty\n @hash.delete(key)\n rec = nil\n end\n raise 'The key is absent in the cache' if rec.nil?\n rec[:value]\n end\n end",
"def get(key)\n @first.get(key)\n end",
"def find(key)\n find_node(checked_get_node(key))\n end",
"def [](key)\n i = 1\n desired_index = index(key, size)\n while @items[desired_index].key != key\n desired_index += i**2\n i += 1\n end\n\n return @items[desired_index].value\n end",
"def get(key)\n node_for(key).get(key)\n end",
"def find(key)\r\n \t\t\t# Start at beginning of the List\r\n \t\t\tcurrent = @head\r\n \t\t\t# Go through list until nil\r\n\t\t\twhile current\r\n\t\t\t\t# If matching key is found return value at node\r\n\t\t\t\tif current.key == key\r\n\t\t\t\t\treturn current.value\r\n\t\t\t\tend\r\n\t\t\t\t# Go to next node\r\n\t\t\t\tcurrent = current.next\r\n\t\t\tend\r\n \t\tend",
"def get(key)\n i = key.hash % @table.size\n node = @table[i]\n while node\n return node.value if key == node.key\n node = node.next\n end\n nil\n end",
"def fetch(key, *args, &block)\n value = self[key]\n return value unless value.nil?\n\n @parameters.fetch(key, *args, &block)\n end",
"def search(id, key)\n if list = __send__(id)\n val = list.fetch(key) {return nil}\n block_given? ? yield(val) : val\n end\n end",
"def [](key)\n if @items[index(key,size)] != nil\n current = @items[index(key, size)].head #chooses head node\n while current != nil\n if current.key == key\n return current.value\n else\n current = current.next\n end\n end\n end\n end",
"def find(key)\n if empty?\n nil\n else\n if @val[0] == key\n @val\n elsif @val[0] < key && @right!=nil\n @right.find(key)\n elsif @left!=nil\n @left.find(key)\n else\n nil\n end\n end\n end",
"def get(key)\n @ivar.each_with_index do |ele, i|\n if ele[0] == key \n return ele[1]\n end\n end\n end",
"def [](key)\n node = root_node\n ba_key = Bitarray.new(key)\n\n # descend to the node or bail with null value hash\n 1.upto(KEY_SIZE) do |depth|\n bit = ba_key[depth - 1]\n node = (bit == 0) ? node.left : node.right\n return self.class.null_value_hash unless node\n end\n node.value\n end",
"def find_value(calling_node, key)\n @router.touch(calling_node)\n value = @values[key.to_bin]\n return value unless value.nil?\n return find_node(key)\n end",
"def lookup(key)\n return nil if @capacity <= 0\n\n @cache_mutex.synchronize do\n return nil unless @map.include?(key)\n\n element = @map.delete(key)\n return nil if element.stale?(@timeout)\n\n @map[key] = element\n\n element.value\n end\n end",
"def obtain!(key)\n raise \"Missing key #{key}\" unless @hash.key?(key)\n @hash[key]\n end",
"def [](key)\n fetch(key)\n end",
"def fetch(key)\n mon_synchronize do\n node = @hash[key]\n break unless node\n\n touch(node)\n node.value\n end\n end",
"def get(key, default=nil)\n find = KeyValue.find_by_key(key)\n find ? find.value : default\n end",
"def lookup(key)\n @map.each { |k, v| return v if key == k }\n nil\n end",
"def fetch(key)\n now = Time.now.public_send(_kind)\n value = get(key, now)\n\n if value.nil?\n clear_all(key)\n value = set(key, now, set_nil(yield))\n end\n\n unset_nil(value)\n end",
"def fetch_value(key)\n val = fetch_nested(key)\n return val if self[:no_pruning].include?(key)\n Prunable::VALUES.include?(val) ? Prunable::Value : val\n end",
"def get(key)\n node = @cache[key]\n return -1 if node.nil?\n move_to_head(node)\n node.value\n end",
"def get(key)\n v = Nvmkv::kv_get(@kv_id, @pool_id, key)\n return (v != nil ? NVMKVValue.new(v) : nil)\n end",
"def [](key)\n data.fetch(key) do\n _values.find {|data| !data[key].nil? }\n end\n end",
"def find(key)\n # If we are already on nil, just add it here\n return nil if @root.nil?\n #Return the root value if it is the value we are looking for\n return @root.value if @root.key == key\n #Otherwise, call in reinforcements\n return find_helper(@root, key)\n end",
"def get(key)\n self.map_var.each do |pair|\n return pair[1] if pair[0] == key\n end\n nil\n end",
"def [](key)\n\t\t\t\treturn(lookup(key))\n\t\t\tend",
"def [](key)\n\t\t\t\treturn(lookup(key))\n\t\t\tend",
"def nested_hash_value(obj, key)\n if obj.respond_to?(:key?) && obj.key?(key)\n obj[key]\n elsif obj.respond_to?(:each)\n r = nil\n obj.find do |*a|\n r = nested_hash_value(a.last, key)\n end\n r\n end\n end",
"def find(key)\n current_and_parent_pair = find_current_and_parent_nodes(key)\n if current_and_parent_pair[:current] \n return current_and_parent_pair[:current].value\n else\n return nil\n end\n end",
"def [](key)\n result = _process_value(value[key])\n Utils.recursive?(result) ? _new(result) : result\n end",
"def get(key); end",
"def get(key); end",
"def get(key); end",
"def get(key); end",
"def fetch(key)\n result.fetch(key)\n end",
"def get(key)\n\n\t\t#we will set the initial value of the variable as nil\n\t\tvalue = nil\n\t\t\n\t\t#iterate through the array\n\t\ti = 0\n\t\twhile i < @size\n\n\t\t\t#if we find the key inside the array\n\t\t\tif @array[i] == key\n\t\t\t\t#we will grab the next element (the value)\n\t\t\t\tvalue = @array[i+1]\n\t\t\t\t#and return it\n\t\t\t\treturn value\n\t\t\tend\n\n\t\t\t#go to all the even indexes\n\t\t\ti += 2\n\t\t\t\n\t\tend\n\n\t\t#if we don't find the key, return value as nil\n\t\treturn value\n\n\tend",
"def get_value (key)\r\n @redis.get key\r\n end",
"def read_entry(key, options) # :nodoc:\n entry = with { |c| c.get(key, options) }\n # NB Backwards data compatibility, to be removed at some point\n entry.is_a?(ActiveSupport::Cache::Entry) ? entry.value : entry\n rescue Dalli::DalliError => e\n log_dalli_error(e)\n instrument_error(e) if instrument_errors?\n raise if raise_errors?\n nil\n end",
"def get_value(collection, key)\n @data[collection][key]\n end",
"def get(key)\n data = request_data(:get, key_uri(key))\n return nil unless data\n if nodes = data[S_NODE][S_NODES]\n nodes.each_with_object({}) do |node, acc|\n acc[node[S_KEY]] = node[S_VALUE]\n end\n else\n data[S_NODE][S_VALUE]\n end\n end",
"def read(key, options = {})\n synchronize_block do\n set_key_access_strategy(key)\n return @data[key] ? dup_value(@data[key]) : nil\n end\n end",
"def fetch_if(key_or_proc, key, &block)\n if get(key)\n key_or_proc = key_or_proc.call if key_or_proc.is_a?(Proc)\n value = fetch(key_or_proc, &block)\n else\n value = block.call\n key_or_proc = key_or_proc.call if key_or_proc.is_a?(Proc)\n set(key_or_proc, Marshal.dump(value))\n end\n value\n end",
"def get key\n\t\t\tif @my_hash.has_key? key\n\t\t\t\tnode = @my_hash[key]\n\t\t\t\t@my_list.promote_node node\n\t\t\t\tnode.value\n\t\t\telse\n\t\t\t\tnil\n\t\t\tend\n\t\tend",
"def get(key)\n self.data[key] && self.data[key][:value]\n end",
"def [](key)\n content = list_map_db[key]\n content&.first\n end",
"def get(key)\n found = @hash[key]\n\n if found\n @list.move_node_to_head(found)\n return found\n end\n\n -1\n end"
] |
[
"0.70766985",
"0.6943284",
"0.6816638",
"0.68031996",
"0.6793584",
"0.6784317",
"0.6691365",
"0.6625085",
"0.6609999",
"0.65925",
"0.6563788",
"0.6562033",
"0.65612924",
"0.6545681",
"0.6545519",
"0.6540545",
"0.65398395",
"0.6539139",
"0.65385807",
"0.65362763",
"0.6536076",
"0.6504318",
"0.6502796",
"0.64939165",
"0.646772",
"0.64500356",
"0.6401375",
"0.6349466",
"0.6338598",
"0.6326954",
"0.6315656",
"0.6314919",
"0.6310576",
"0.6308785",
"0.6298381",
"0.6298021",
"0.6274347",
"0.6270063",
"0.6244336",
"0.6235218",
"0.62163985",
"0.62146354",
"0.6213436",
"0.61908805",
"0.6171703",
"0.61623704",
"0.6155902",
"0.61218196",
"0.6111829",
"0.60789806",
"0.60738397",
"0.6073457",
"0.60545856",
"0.60375315",
"0.6016332",
"0.60160273",
"0.60154533",
"0.6014688",
"0.60135794",
"0.59994704",
"0.59833974",
"0.5980266",
"0.59676874",
"0.5967409",
"0.5963438",
"0.5963002",
"0.596014",
"0.59594196",
"0.5938582",
"0.59343666",
"0.59245634",
"0.59223443",
"0.5919897",
"0.59183556",
"0.59129035",
"0.59094423",
"0.5908188",
"0.58986175",
"0.5897586",
"0.5894013",
"0.5886514",
"0.5886514",
"0.58805066",
"0.5877248",
"0.5876023",
"0.5875484",
"0.5875484",
"0.5875484",
"0.5875484",
"0.58748174",
"0.58706653",
"0.58651656",
"0.5855604",
"0.58522135",
"0.58514035",
"0.58299685",
"0.58271843",
"0.5822053",
"0.5821609",
"0.58197176",
"0.5817497"
] |
0.0
|
-1
|
Returns true if the given key is present.
|
def registered?(key)
data.key?(key)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def has_key?( key )\n key = UniMap.str_to_key( key ) unless key.is_a?( Key )\n key && contains_key( key )\n end",
"def has_key?(key)\n return self.fetch(key) ? true : false\n end",
"def has_key?(key)\n @hash.has_key?(key)\n end",
"def has_key?(key)\n return to_h().has_key?(key)\n end",
"def has_key? key; key? key; end",
"def has_key?(key)\n keys.include?(key)\n end",
"def has_key?(key)\n !get(key).nil?\n end",
"def has_key?(key)\n !get(key).nil?\n end",
"def has_key?(key); end",
"def has_key?(key); end",
"def has_key?(key)\n @h.has_key?(key.to_sym)\n end",
"def contains?(key)\n @key_data.has_key?(key)\n end",
"def has_key?(key)\n @stored[key] && !@stored[key].empty? ? true : false\n end",
"def include?(key)\n has_key?(key)\n end",
"def include?(key)\n @hash.has_key?(key.to_s)\n end",
"def exists?(key)\n unimplemented\n end",
"def has_key?(key)\n @table.get(key) != nil\n end",
"def has_key?(key)\n any? {|mod| mod.name == key}\n end",
"def has_key?(key)\n params.keys.include?(key)\n end",
"def has_key?(key)\n @map.has_key?(key.to_sym)\n end",
"def contains?(key)\n not get(key).nil?\n end",
"def has_key?(key)\n @db.each_key do\n\t|k|\n\treturn true if k == key\n end\n end",
"def has?(key)\n value = self[key]\n boolean_typecast(key, value)\n end",
"def has_key?(key)\n !!fetch(key)\n rescue ContextMiss\n false\n end",
"def has_key?(key)\n !find_node(key).nil?\n end",
"def has_key?(key)\n dummy = Pair.new(key,nil)\n return @tree.get(dummy)\n end",
"def has_key?(key)\n @cache.has_key?(key)\n end",
"def include_key?(key)\n\t\t\ttrue\n\t\tend",
"def key?(key)\n keys.include?(key) || keys.map(&:to_s).include?(key)\n end",
"def key?(key)\n keys.include?(key) || keys.map(&:to_s).include?(key)\n end",
"def key?(key)\n !self[key].nil?\n end",
"def exists(key)\n mon_synchronize do\n perform [\"exists\", key], proc: T_BOOL\n end\n end",
"def has_key? key\n @lock.read_sync{ @data.has_key? key }\n end",
"def exists?(key)\n key.present? && manager.key?(key)\n end",
"def has_key(hash, key)\n\thash.has_key? key\nend",
"def key?(key)\n public_method_defined?(key.to_sym)\n end",
"def has_key?(p0) end",
"def exists(key)\n mon_synchronize do\n perform [\"exists\", key], :proc => T_BOOL\n end\n end",
"def has?(key)\n respond_to? key\n end",
"def exists?(key)\n @data.has_key?(key) && @data[key].valid?(self)\n end",
"def has?(key)\n @properties.has_key?(key)\n end",
"def exists?(key)\n @redis.exists(prefix(key))\n end",
"def key? key\n each_pair.find {|k, _| key == k } && true\n end",
"def key?(key, options = {})\n load(key, options) != nil\n end",
"def contains?(key)\n @semaphore.synchronize {\n @key_data.has_key?(key)\n }\n end",
"def is_key_exist(key)\r\n (@redis.exists key) ? true : false \r\n end",
"def include?(key)\n # Ensure a Ruby true is returned\n item_exists(key) == true\n end",
"def has_key?(key)\n @configuration.has_key?(key.to_sym)\n end",
"def exists(key)\n call(key, [:exists, key], transform: Redis::Boolify, read: true)\n end",
"def exist?(key)\n with_client do |client|\n !client.exists(build_key(key)).zero?\n end\n end",
"def key?(key)\n lookup_map.key?(key.to_sym)\n end",
"def exist?(key)\n !@store.select { |i| i[:key] == build_key(key) }.empty?\n end",
"def exists?(key, bucket = nil)\n about(key, bucket)\n true\n rescue NoSuchKey\n false\n end",
"def key?(key)\n timeout_retry(3, 3){\n write \"EXISTS #{key}\\r\\n\"\n integer_reply == 1\n }\n end",
"def plist_key_exists?(key, file, opts={})\n plist_read(key, file, opts) != nil\n end",
"def exists?(key)\n s3_object(key).exists?\n end",
"def key?\n return true if @key; false\n end",
"def key?(key)\n configuration.key?(key)\n end",
"def contains?(key)\n position = search(key)\n (key <=> @keys[position]) == 0\n end",
"def exist?(key)\n\n end",
"def exists?\n retrieve\n true\n rescue Error::NoSuchKey\n false\n end",
"def has_key?(*args)\n @params.has_key?(*args)\n end",
"def has_key?(*args)\n @params.has_key?(*args)\n end",
"def has_key?(key)\n raise NotImplementedError\n end",
"def has_key(rsa)\n refresh_keys if @keys.nil?\n return false if @keys.empty?\n\n # loop through arrays checking against 'key'\n @keys.each do |key|\n return true if key[\"key\"] == rsa\n end\n\n return false # key not found\n end",
"def exist?(key)\n store.key?(key)\n end",
"def key?(key)\n @configuration.key?(key)\n end",
"def private_key_exists?\n full_key_path.exist?\n end",
"def has_key?(key)\n configs.has_key?(key) || store.has_key?(key) \n end",
"def exists?(key)\n raise \"Method not implemented. Called abstract class.\"\n end",
"def exist(key)\n check_return_code(\n Lib.memcached_exist(@struct, key),\n key\n )\n end",
"def exist?(key)\n !find(key).nil?\n end",
"def has?(key)\n [cache, values].any? { |store| store.keys.include?(key.to_sym) }\n end",
"def has_key(key, pos= 0, len= -1)\n end",
"def exist?(key)\n raise NotImplementedError\n end",
"def key?(key)\n @attr.key?(key)\n end",
"def has_key?(key)\n self.body.is_a?(Hash) && self.body.has_key?(key)\n end",
"def include?(key)\n Options.check_valid_key(key)\n @data.include?(key.to_sym)\n end",
"def hash_has_key?(hash, key)\r\n hash.key?(key) # Determines if hash has key with the argument of key.\r\nend",
"def member? key\n fetch(key, nil) && true\n end",
"def key?(key)\n\t\t\t\tif key\n\t\t\t\t\t@keyed.key?(key)\n\t\t\t\tend\n\t\t\tend",
"def exist? _key\n store.transaction(:read_only) do |s|\n s.roots.any? { |r| r.to_sym == _key.to_sym }\n end\n end",
"def has_key?(attr_name)\n keys.include?(attr_name.to_s)\n end",
"def in?(key)\n return true if get(key)\n false\n end",
"def has_key?(key)\n @config.has_key? key\n end",
"def has_key?(key)\n local?(key) || (!@parent.nil? && @parent.key?(key))\n end",
"def key?(key)\n config.resolver.key?(_container, key)\n end",
"def has_key?(key)\n super(convert_key(key))\n end",
"def has_key?(key)\n key.kind_of?(Symbol) ? self.has_key?(key.to_s) : super(key)\n end",
"def has_keypair?\n options.has_key?(:keypair) && options[:keypair] && !options[:keypair].empty?\n end",
"def exist?(key, options = {})\n invoke(:exist?, key) do |store|\n store.exists(namespaced_key(key, merged_options(options)))\n end\n end",
"def key?(key)\n return false if key.nil?\n return true if self.class.mutable? && mutations.key?(key)\n\n respond_to?(key) || fallback_data.key?(key)\n end",
"def has?(key)\n node = _get(@root, key)\n !node.nil? && !node.undefined?\n end",
"def key?(key)\n @items.key?(key)\n end",
"def has_key?(key)\n super(convert_key(key))\n end",
"def has_key? k\n @values.has_key?(k)\n end",
"def key?(key)\n !(head && head.commit.tree / key_for(key)).nil?\n end",
"def key?(key)\n !(head && head.commit.tree / key_for(key)).nil?\n end",
"def exists?(key)\n # Use recommended binary-returning method create [with this redis-rb commit](https://github.com/redis/redis-rb/commit/bf42fc9e0db4a1719d9b1ecc65aeb20425d44427).\n return Lit.redis.exists?(key) if Lit.redis.respond_to?(:exists?)\n\n # Fall back with older gem\n Lit.redis.exists(key)\n end",
"def key_set?\n !attributes['key'].nil?\n end",
"def params_has_key *args\n args.each do |key|\n unless params.has_key? key.to_s\n return false\n end\n end\n return true\nend"
] |
[
"0.85122937",
"0.8415955",
"0.8389183",
"0.83463675",
"0.833241",
"0.8325622",
"0.8322745",
"0.8322745",
"0.8290243",
"0.8290243",
"0.820581",
"0.8097412",
"0.8043171",
"0.7971588",
"0.7964369",
"0.7960991",
"0.7942686",
"0.78635514",
"0.7856147",
"0.78196037",
"0.78140944",
"0.7753635",
"0.7750968",
"0.7743845",
"0.7730705",
"0.7720378",
"0.77079934",
"0.76998305",
"0.76897436",
"0.76897436",
"0.768226",
"0.7679747",
"0.76742035",
"0.7664723",
"0.76611584",
"0.76599354",
"0.7644433",
"0.76069945",
"0.7593663",
"0.75932395",
"0.75810784",
"0.75789",
"0.7577391",
"0.7576053",
"0.7561412",
"0.7550262",
"0.7518783",
"0.75128955",
"0.7509527",
"0.7502481",
"0.7457272",
"0.74567896",
"0.74498934",
"0.7447644",
"0.74389344",
"0.7435705",
"0.7415055",
"0.74145025",
"0.74068356",
"0.7392565",
"0.7390137",
"0.7375314",
"0.7375314",
"0.7369673",
"0.73549587",
"0.73499715",
"0.7340423",
"0.73340315",
"0.7330893",
"0.73232555",
"0.7321247",
"0.7320148",
"0.72949916",
"0.7294808",
"0.72914803",
"0.72839946",
"0.72781074",
"0.7262751",
"0.7248743",
"0.72410506",
"0.7238355",
"0.7231082",
"0.7228482",
"0.7226674",
"0.72260255",
"0.72252923",
"0.7220026",
"0.7218604",
"0.7206761",
"0.72049415",
"0.72047126",
"0.7203892",
"0.7187133",
"0.71730673",
"0.7172851",
"0.71585804",
"0.71544164",
"0.71544164",
"0.7149924",
"0.7148194",
"0.7146919"
] |
0.0
|
-1
|
Element assignment. Associates the value given by value with the key given by key.
|
def register(key, &block)
delay = Delay.new(executor: :immediate, &block)
update_data { |h| h.merge(key => delay) }
self
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def assign(key, value)\n if lookup(key)\n @holder.each { |pair| pair[1] = value if pair[0] == key}\n else\n @holder << [key, value]\n end\n end",
"def assign(key, value)\n @map.each do |pair|\n k, _ = pair\n pair[1] = value if key == k\n return\n end\n\n @map << [key, value]\n end",
"def assign(key,value)\n #first check to see if the key value pair already exists\n pair_index = nil\n @map.each_with_index do |sub_array,idx|\n pair_index = idx if sub_array[0] == key\n end\n if pair_index.nil?\n @map << [key,value]\n else\n @map[pair_index]=[key,value]\n end\n end",
"def []= key, value\n @hash[key.to_s] = value\n end",
"def set(key, value)\n arr_pos = to_hash(key)\n list = @array[array_pos]\n node = list.find_by_key(key)\n if node\n node.data = value\n else\n self.put(key, value)\n end\n end",
"def assign(key, value)\n pair_idx = @map.index { |pair| pair[0] == key}\n if pair_idx.nil?\n @map << [key, value]\n else\n @map[pair_idx][1] = value\n end\n #refractored\n # pair_idx ? @map[pair_idx][1] = value : @map << [key, value]\n [key, value]\n end",
"def []= k,v\n @values[k.to_sym] = v\n end",
"def set(key , value)\n index = key_index(key)\n if( index )\n @i_values.set(index , value)\n else\n @i_keys.push(key)\n @i_values.push(value)\n end\n value\n end",
"def assign(key, value)\n pair_index = @map.index {|pair| pair[0] == key}\n pair_index ? @map[pair_index][1] = value : @map.push([key, value])\n [key, value]\n end",
"def []= key, value\n @internal_hash[key].push value\n value\n end",
"def []= key, value\n @map[key] = value\n end",
"def []= key, value\n key = @schema.resolve_key! key\n @schema.validate_value! key, value\n @values[key] = value\n end",
"def set(key, value)\n @value[key.to_sym] = value if key\n end",
"def []= key, value\n @data[key] = value\n end",
"def []= key, value\n @data[key] = value\n end",
"def setnx(key, value); end",
"def setnx(key, value); end",
"def []=(key, value); end",
"def []=(key, value); end",
"def []=(key, value); end",
"def []=(key, value); end",
"def []=(key, value); end",
"def []=(key, value); end",
"def []=(key, value); end",
"def []=(key, value); end",
"def []=(key, value); end",
"def []=(key, value); end",
"def []=(key, value); end",
"def []=(key, value); end",
"def []=(key, value); end",
"def []=(key, value); end",
"def []=(key, value); end",
"def []=(key, value); end",
"def set(key, value); end",
"def set(key, value); end",
"def []=(key, value)\n store(key, value)\n end",
"def []=(key, value)\n store(key, value)\n end",
"def []=(key, value)\n store(key, value)\n end",
"def set(key , value)\n index = key_index(key)\n if( index )\n self.keys.set(index , value)\n else\n self.keys.push(key)\n self.values.push(value)\n end\n value\n end",
"def update_key(key, val)\n @ivar.each_with_index do |ele, i|\n if ele[0] == key\n @ivar[i][1] = val \n end\n end\n end",
"def []= key, value\n @store.transaction { @store[key] = value }\n end",
"def key=(value); end",
"def []=(key, value)\n index = self.keys.index(key) unless @array.empty?\n if index\n @array[index][1] = value\n else\n @array[@array.size] = [key,value]\n end\n end",
"def set(key, value)\n @namehash[key.to_sym][0] = value\n end",
"def []= k,v\n\t set k,v\n\t end",
"def []=(key, value)\n regular_writer(convert_key(key), convert_value(value, conversion: :assignment))\n end",
"def []=(key, value)\n pairing[key] = value\n end",
"def []=(key, value)\n store(key, value)\n end",
"def []=(key, val); end",
"def []=(key, value)\n offset = append(key, value)\n index(key, offset)\n end",
"def []=(key , value)\n set(key, value)\n end",
"def set(key, value)\n pair_idx = @map_arr.index { |pair| pair[0] == key }\n\n if pair_idx\n @map_arr[pair_idx][1] = value\n else\n @map_arr << [key, value]\n end\n\n value\n end",
"def []=(key, value)\n put(key, value)\n end",
"def []=(key, value)\n values[key] = value\n values.save\n end",
"def set(key, value)\n end",
"def []=(key, value)\n field_set key, value\n end",
"def []=(key, value)\n key = namespaced_key(key)\n @keys << key\n set(key, value)\n end",
"def []=(key, value)\n set(key, value)\n end",
"def []=(key, value)\n set(key, value)\n end",
"def []=(key, value)\n set(key, value)\n end",
"def []=(key, value)\n self[key].value = value\n end",
"def []=(key, value)\n self[key].value = value\n end",
"def []=(key, value)\n entry = find_entry(key)\n @dirty = true\n if entry.nil?\n @entries << [key, value]\n else\n entry[1] = value\n end\n end",
"def set(key, value)\n\t\t\t\t# TODO This could be a bit more efficient:\n\t\t\t\tself.delete(key)\n\t\t\t\tself.add(key, value)\n\t\t\tend",
"def []=(*key_list, value)\n store_with_init(Array(key_list).flatten, value)\n end",
"def []=(key, value)\n set(key, :val => value)\n end",
"def []=(key, value)\n hash[key] = value\n end",
"def []=(k, v)\n @values[k] = v\n end",
"def []=(key, value)\n @hash[key.to_s] = value\n end",
"def []=(key, value)\n self.put(key, value)\n end",
"def []=(key, value)\n @_hash[key.to_sym] = value\n end",
"def []=(key, value)\n pair = Pair.new(key,value)\n @tree.add(pair)\n return value\n end",
"def set(k,v)\n each do |e|\n e.set k,v\n end\n self\n end",
"def []=(key_name, value)\n set(key_name, value)\n end",
"def []=(key, value)\n new_entry = entry_to_modify(key, value)\n new_entry[:key] = key\n new_entry[:value] = value\n end",
"def []=( key, value )\n context.store(key.to_s, value)\n end",
"def []=(key, value)\n @store[key] = value\n end",
"def []=(key, value)\n\n set_field(key.to_s, value)\n end",
"def set(key, value)\n @store[key] = value\n end",
"def []=(key, value)\n @hash[key] = value\n end",
"def set(key, value)\n updated = false\n if self.map_var[0].empty?\n self.map_var[0] = [key, value]\n updated = true\n else \n self.map_var.each do |pair| \n if pair[0] == key \n pair[1] = value \n updated = true\n end\n end \n end\n self.map_var << [key, value] if !updated\n updated \n end",
"def []= k, v \n split_fields if not @h\n kupper = k.upcase\n @h[kupper] = v\n @original_key[kupper] = k\n end",
"def []=(key,arg)\n @hash[key] = arg\n end",
"def put(key, value)\n position = search(key)\n if (key <=> @keys[position]) == 0\n @values[position] = value\n else\n @keys.insert(position, key)\n @values.insert(position, value)\n end\n end",
"def set(key, value)\n peek[key.to_sym] = value\n end",
"def []=(key, value)\n setValueForKey(key.to_s, value.to_s)\n end",
"def set( key, value )\n unless key.is_a?( Key )\n k = UniMap.str_to_key( key )\n unless k\n raise IndexError, \"No Key named #{key.inspect} in UniMap.KEY_SPACE\"\n end\n key = k\n end\n set_k( key, value )\n end",
"def update(key, value)\n set(key.to_sym => value)\n end",
"def []=(key, value)\n data[key] = value\n end",
"def []=(key,value)\n ruby_set(key&&key.to_s, value)\n end",
"def put(key, value)\n @first.put(key, value)\n end",
"def []=(k, v) \n @data[k] = v\n end",
"def []=(k, v) \n @data[k] = v\n end",
"def put(key, value)\n @root = put_rec(@root, key, value, 0)\n end",
"def put(key, value)\n @root = put_node(@root, key, value, 0)\n end",
"def []=( key, value )\n ensure_aggregate!\n @context[ key ] = value\n end",
"def []=(key, value)\n copy_on_write if @attrs.shared\n key = key.intern \n a = @attrs_hash[key]\n if a\n if value\n a.value = value\n else\n delete_attr!(key)\n end\n else\n put_attr(Attr.new(key,value)) if value\n end\n value\n end",
"def []=(key, value)\n @current[key] = value\n end",
"def []=(key, value)\n end",
"def []=(key, value)\n @h[key.to_sym] = value\n end",
"def set_tag(key, value)\n [key, value]\n end"
] |
[
"0.7496545",
"0.73874396",
"0.7198734",
"0.71013874",
"0.70804554",
"0.70544505",
"0.70484823",
"0.6979971",
"0.6978227",
"0.6965613",
"0.6951254",
"0.69112104",
"0.6888057",
"0.6871567",
"0.6871567",
"0.6861345",
"0.6861345",
"0.68330187",
"0.68330187",
"0.68330187",
"0.68330187",
"0.68330187",
"0.68330187",
"0.68330187",
"0.68330187",
"0.68330187",
"0.68330187",
"0.68330187",
"0.68330187",
"0.68330187",
"0.68330187",
"0.68330187",
"0.68330187",
"0.6812032",
"0.6812032",
"0.67636055",
"0.67636055",
"0.67636055",
"0.675582",
"0.6753044",
"0.6741487",
"0.673798",
"0.6736903",
"0.6736752",
"0.6735949",
"0.6725214",
"0.67202836",
"0.6692993",
"0.66741157",
"0.66631943",
"0.66453725",
"0.66209745",
"0.66025037",
"0.65990597",
"0.65986174",
"0.6595031",
"0.6593465",
"0.6590116",
"0.6590116",
"0.6589868",
"0.6587591",
"0.6587591",
"0.65856284",
"0.6560811",
"0.65451616",
"0.6543881",
"0.65419483",
"0.65010023",
"0.6496781",
"0.64945656",
"0.64931417",
"0.64912283",
"0.6485903",
"0.6466382",
"0.6460097",
"0.6456279",
"0.64553845",
"0.6450406",
"0.6449011",
"0.64470094",
"0.6445392",
"0.6443706",
"0.6441927",
"0.6440455",
"0.6439534",
"0.64371955",
"0.6432112",
"0.6426809",
"0.6421925",
"0.6400365",
"0.6399961",
"0.6399186",
"0.6399186",
"0.63898784",
"0.6382486",
"0.63808215",
"0.63784754",
"0.6376009",
"0.63731354",
"0.6371228",
"0.6367529"
] |
0.0
|
-1
|
Unregisters the object under key, realized or not.
|
def unregister(key)
update_data { |h| h.dup.tap { |j| j.delete(key) } }
self
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def unregister(key_or_instance)\n proxy_across_keytypes(:delete, key_or_instance)\n end",
"def unregister(object)\n\t\t\t@registered.delete(object)\n\t\tend",
"def unregister(key)\n @data.update { |h| h.dup.tap { |j| j.delete(key) } }\n self\n end",
"def registry_unloadkey(key)\n if session_has_registry_ext\n meterpreter_registry_unloadkey(key)\n else\n shell_registry_unloadkey(key)\n end\n end",
"def unsubscribe(key)\n @lock.synchronize do\n @handlers.clear\n @@name2inst.delete_if { |k, v| k == id.to_sym || k == address.to_sym}\n end\n end",
"def unregister\n @is_registered = false\n self\n end",
"def shell_registry_unloadkey(key)\n key = normalize_key(key)\n shell_registry_cmd_result(\"unload \\\"#{key}\\\"\")\n end",
"def unregister(symbol); end",
"def remove(instance)\n @registry.each_with_index do |item, i|\n if item.to_h == instance.to_h\n @registry.delete_at(i)\n end\n end\n sync\n end",
"def destroy\n self.class.remove(key)\n end",
"def destroy\n self.class.remove(key)\n end",
"def del(key)\n @meta.delete(key.to_sym) if key\n end",
"def delete key\n @internal_hash[key].clear\n end",
"def unregister(path)\n\t\t\t\tpath = path.to_sym\n\t\t\t\tif @@registry[path]\n\t\t\t\t\t@@registry_count[path] -= 1\n\t\t\t\t\tif @@registry_count[path] <= 0\n\t\t\t\t\t\tsub = @@registry.delete(path)\n\t\t\t\t\t\tsub.unsubscribe\n\t\t\t\t\t\t@@registry_count.delete(path)\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend",
"def remove(key); end",
"def dissociate klass, ident\n @associated_objects[klass].delete?(ident) != nil\n end",
"def clear!\n @key_registry = {}\n self\n end",
"def remove(key)\n a_hash[key] = nil\n end",
"def delete(object)\n @monitor.delete(object.key)\n object.unsubscribe(self)\n super(object)\n end",
"def delete(key)\n ref = @cache.delete(key)\n ref.__getobj__ rescue nil\n end",
"def unregister(obj)\n if @observers.include?(obj) then \n @observers.delete_at(@observers.index(obj))\n @logger.debug \"Removed observing object #{obj} from the list\" if not self.logger.nil?\n else\n raise FileStoreException, \"Object #{obj} isn't a registered observer\"\n end\n end",
"def delete key\n find_slot(key)&.free\nend",
"def delete(key)\n @internal_hash.delete(key)\n end",
"def delete(key)\n if Dottie.dottie_key?(key)\n Dottie.delete(wrapped_object_or_self, key)\n else\n super\n end\n end",
"def unset key\n storage.delete key\n end",
"def ungem(obj)\n return unless gems?(obj)\n\n run_hook(:before_ungem, obj)\n Recommendable.redis.srem(Recommendable::Helpers::RedisKeyMapper.gemd_set_for(obj.class, id), obj.id)\n Recommendable.redis.srem(Recommendable::Helpers::RedisKeyMapper.gemd_by_set_for(obj.class, obj.id), id)\n run_hook(:after_ungem, obj)\n\n true\n end",
"def del(key)\n @first.del(key)\n end",
"def unplug!\n return self unless exist?\n ole.Delete\n self\n end",
"def reset!\n registered_keys.each { |key| ClassConstants.new(key).deconstantize }\n @registered_keys = []\n container._container.clear\n end",
"def undisgem(obj)\n return unless disgems?(obj)\n\n run_hook(:before_undisgem, obj)\n Recommendable.redis.srem(Recommendable::Helpers::RedisKeyMapper.disgemd_set_for(obj.class, id), obj.id)\n Recommendable.redis.srem(Recommendable::Helpers::RedisKeyMapper.disgemd_by_set_for(obj.class, obj.id), id)\n run_hook(:after_undisgem, obj)\n\n true\n end",
"def remove(key)\n\n end",
"def unload_extra\n log \"Unloading extra baggage\" , Logger::Ultimate\n @mutex.synchronize do\n @ghash.delete_if do |goid, obj|\n if obj.busy?\n log \"#{obj} busy\" , Logger::Ultimate\n false\n elsif obj.is_a? Player or obj.is_a? Mobile\n false\n elsif obj.container.nil? or not self.loaded? obj.container\n puts \"Checking #{obj}\" , Logger::Ultimate\n if obj.can? :inventory\n if obj.inventory.has_any? Player or obj.inventory.has_any? Mobile\n log \"It contains a player or mobile:\" , Logger::Ultimate\n log obj.inventory.find_all('class', Player) , Logger::Ultimate\n log obj.inventory.find_all('class', Mobile) , Logger::Ultimate\n false\n else\n @storage.store_object(obj)\n true\n end\n else\n log \"Saving #{obj}\" , Logger::Ultimate\n @storage.store_object(obj)\n log \"Dropping #{obj}\\nContainer is #{obj.container}\\nNo Inventory\" , Logger::Ultimate\n log \"Saving #{obj}\" , Logger::Ultimate\n true\n end\n else\n puts \"#{obj} isn't a player or a mobile or busy and it has a container\" , Logger::Ultimate\n false\n end\n end\n end\n log \"Baggage unloaded\", Logger::Ultimate\n end",
"def remove_property(key)\n end",
"def registry_deletekey(key, view = REGISTRY_VIEW_NATIVE)\n if session_has_registry_ext\n meterpreter_registry_deletekey(key, view)\n else\n shell_registry_deletekey(key, view)\n end\n end",
"def unbind(key)\n\t\t@bindings[key] = nil\n\tend",
"def unset_value(key)\n database.delete(key)\n removed_keys << key\n end",
"def unhook\n Nest.get(base_module).remove(self)\n Agency.instance.retire(self)\n\n and_return(@original_value) if previously_defined?\n\n @original_value = @previously_defined = nil\n self\n end",
"def remove(key)\n\n if include?(key)\n self[key].delete(key)\n @count -= 1\n end\n\n end",
"def unregister_type\n types_list.delete self\n end",
"def delete(key)\n unimplemented\n end",
"def delete(key)\n key = alternate_key(key) unless has_key?(key)\n super\n end",
"def delete(key)\n super(convert_key(key))\n end",
"def delete key\n write_data_entry key, nil, true\n @keydict[key] = nil\n\n sync\n end",
"def remove( key )\n key = UniMap.str_to_key( key ) unless key.is_a?( Key )\n key && HTMapHelper.remove_map( self, key )\n end",
"def meterpreter_registry_unloadkey(key)\n begin\n client.sys.config.getprivs()\n root_key, base_key = session.sys.registry.splitkey(key)\n begin\n unloadres= session.sys.registry.unload_key(root_key,base_key)\n rescue Rex::Post::Meterpreter::RequestError => e\n case e.to_s\n when \"stdapi_registry_unload_key: Operation failed: The parameter is incorrect.\"\n #print_error(\"The KEY you provided does not appear to match a loaded Registry Hive: #{key}\")\n return false\n when /stdapi_registry_unload_key: Operation failed:/\n #print_error(\"An unknown error has occurred: #{unloadres.to_s}\")\n return false\n else\n return true\n end\n end\n rescue\n return false\n end\n end",
"def delete(key)\n super(convert_key(key))\n end",
"def getdel(key); end",
"def getdel(key); end",
"def pop_reg reg\n @fisk.pop reg.to_register\n end",
"def remove(klass)\n self.registered_items.delete(klass)\n end",
"def clear\n @registry = {}\n end",
"def decr(key); end",
"def decr(key); end",
"def delete_key(key)\n end",
"def unregister\n obj = nil\n\n synchronize do\n return false unless @parent\n obj, @parent = @parent, nil\n end\n\n obj.unregister(self)\n end",
"def clear_register\n @item_hash = {}\n @tax_hash = {}\n end",
"def delete(key); end",
"def delete(key); end",
"def delete(key); end",
"def delete(key); end",
"def delete(key); end",
"def delete key\n rv = self[key]\n self.removeField key\n return rv\n end",
"def unregister(option)\n @registry.delete(option)\n @options.delete_if {|key, value| option == value }\n option\n end",
"def delete(key)\n\t\t\t\t[self, self, false]\n\t\t\tend",
"def unregister(key)\n @@validator_initializers.delete(key)\n end",
"def delete(key)\n if item = super\n lru_delete(item)\n end\n end",
"def unregister_middleware(key); end",
"def invoke_drop(key); end",
"def finalizer(hash)\n proc { @keys.delete(hash) }\n end",
"def del\n connection.del(key_label)\n end",
"def deregister_object(local_object)\n siblings = siblings_by_local_object_id.delete(local_object.droby_id)\n siblings.each do |peer_id, droby_id|\n siblings_by_peer[peer_id].delete(droby_id)\n end\n\n if local_object.respond_to?(:name)\n n = local_object.name\n models_by_name.delete(n) if local_object == models_by_name[n]\n end\n end",
"def disassociate!(target)\n associate!(target,{:delete => 1})\n end",
"def delete(key)\n ref = @references.delete(key)\n if ref\n keys_to_id = @references_to_keys_map[ref.referenced_object_id]\n if keys_to_id\n keys_to_id.delete(key)\n @references_to_keys_map.delete(ref.referenced_object_id) if keys_to_id.empty?\n end\n ref.object\n else\n nil\n end\n end",
"def invalidate_object_for(association)\n @objects.delete(association.association_name)\n end",
"def clear_registrations_for(routing_key)\n _routing_key, head, tail, parts = process_routing_key(routing_key)\n\n mapping = mappings[head]\n\n if parts.length == 1\n mapping.subscriptions.clear\n else\n mapping.map.clear_registrations_for(tail)\n end\n end",
"def un_register\n unless @unregistered\n @unregistered = true\n RightLinkLog.info(\"SEND [un_register]\")\n @amq.fanout('registration', :no_declare => @options[:secure]).publish(@serializer.dump(UnRegister.new(@identity)))\n end\n true\n end",
"def delete(object)\n obj = super(object)\n @all_goids.delete(obj.goid) if obj\n end",
"def delete(instance)\n @cache[mapped_class(instance.class)].delete(instance.key)\n end",
"def ickunlink(ick_key)\n ickdel(ick_key,unlink: true)\n end",
"def delete\n self.class.redis_objects.each do |key, obj|\n obj = self.send(key.to_sym)\n if obj.class == Redis::Set || obj.class == Redis::HashKey || obj.class == Redis::List\n delete_key(key)\n else\n obj.delete\n end\n end\n end",
"def unregister(*args, &block)\n h = Unobservable.handler_for(*args, &block)\n index = @handlers.index(h)\n if index\n @handlers.slice!(index)\n return h\n else\n return nil\n end\n end",
"def rm(key)\n options.values.collect do |option| \n if option.key == key \n unregister(option)\n else\n nil\n end\n end.compact\n end",
"def unprotect(key)\n @_protected.reject! { |e| e == key.to_s }\n end",
"def destroy\n @key.destroy\n end",
"def delete(obj)\n if obj.is_a?(Symbol)\n object_type = obj\n obj = @params[object_type]\n @params.delete(object_type)\n else\n object_data_delete(obj)\n end\n obj.unregister unless obj.nil?\n end",
"def delete(key)\n @hash.delete key\n @key_hash.delete key\n end",
"def delete\n redis.del key\n end",
"def desist\n self.class.delete self\n end",
"def registry_deleteval(key, valname, view = REGISTRY_VIEW_NATIVE)\n if session_has_registry_ext\n meterpreter_registry_deleteval(key, valname, view)\n else\n shell_registry_deleteval(key, valname, view)\n end\n end",
"def del_reg(id)\n _registers.delete(id)\n end",
"def clear_by_key(key)\n delete(key)\n end",
"def delete_object(x, y)\n @generator_flag = false if @grid[y][x].object.class == MapAbxn::Generator\n @grid[y][x] = nil\n end",
"def unload(inst)\n # If the reference count drops to zero, remove it from the list of\n # loaded plugins. This will indirectly call the cleanup method on the\n # plugin.\n if (inst.deref == true)\n delete(inst)\n end\n end",
"def unlock(obj)\n logger\n if locked?(obj)\n RedisMutexer.config.redis.del(key(obj))\n end\n end",
"def remove_key(key)\n\t\tdelete(\"/user/keys/#{escape(key)}\")\n\tend",
"def remove_key(key)\n\t\tdelete(\"/user/keys/#{escape(key)}\")\n\tend",
"def clear_tag(key)\n meta.delete(key)\n end",
"def vash_munge_key(key); self.class.munge_option_name(key); end",
"def scrooge_dump_unflag_this\n Thread.current[:scrooge_dumping_objects].delete(object_id)\n end",
"def zrem(key, member); end"
] |
[
"0.75273377",
"0.688",
"0.67075807",
"0.67073613",
"0.66049284",
"0.65348727",
"0.6510028",
"0.63441205",
"0.61552733",
"0.6116446",
"0.6116446",
"0.60843295",
"0.6047581",
"0.60379755",
"0.6036565",
"0.59676427",
"0.59286934",
"0.58996606",
"0.58973217",
"0.5876665",
"0.5863048",
"0.5862134",
"0.5856639",
"0.5846458",
"0.5845827",
"0.5830643",
"0.5827178",
"0.58239037",
"0.5804398",
"0.58005875",
"0.57957345",
"0.5782241",
"0.57808846",
"0.57638234",
"0.57576823",
"0.5737985",
"0.5737249",
"0.57295275",
"0.57171637",
"0.57128155",
"0.57083684",
"0.57063895",
"0.5703403",
"0.570073",
"0.5700042",
"0.5696792",
"0.5695239",
"0.5695239",
"0.56860596",
"0.5682958",
"0.5675334",
"0.5665346",
"0.5665346",
"0.56568384",
"0.56554115",
"0.5648228",
"0.56432444",
"0.56432444",
"0.56432444",
"0.56432444",
"0.56432444",
"0.5623365",
"0.5615412",
"0.561517",
"0.56139785",
"0.5605817",
"0.56057185",
"0.5604036",
"0.5603006",
"0.55982125",
"0.5597158",
"0.5592769",
"0.5583943",
"0.55755055",
"0.5574785",
"0.5569126",
"0.5568014",
"0.5551134",
"0.5531631",
"0.55284494",
"0.55086285",
"0.55063075",
"0.5504024",
"0.5501194",
"0.5489187",
"0.5485554",
"0.54783493",
"0.5472912",
"0.5468826",
"0.54500157",
"0.5446771",
"0.54461783",
"0.5425894",
"0.54235625",
"0.541996",
"0.541996",
"0.5408513",
"0.54070723",
"0.53990114",
"0.53858745"
] |
0.67400557
|
2
|
prevents a `stack level too deep`
|
def as_json(options = {})
super(options.merge(except: %w[association_class unfiltered_collection collection]))
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def stack_trace; end",
"def stacktrace; end",
"def skip_backtrace; end",
"def backtrace_ignores; end",
"def stack; end",
"def stack; end",
"def error_yes_stack_trace!\n @@_error_stack_trace = true\n end",
"def full_backtrace; end",
"def backtrace; end",
"def backtrace_cleaner; end",
"def naked_top_level; end",
"def i_am_not_too_deep?(depth)\n depth <= @depth_to_explore\n end",
"def naked_top_level?; end",
"def check_overflow\r\n if @depth >= 100\r\n msgbox(Vocab::EventOverflow)\r\n exit\r\n end\r\n end",
"def amend_exception_call_stack!(ex)\n call_stack = ex.exception_call_stack\n\n # skip_until\n if intercept_object.skip_until_block\n idx = call_stack.each_with_index.find_index do |frame, idx|\n intercept_object.skip_until_block.call(LazyFrame.new(frame, idx, call_stack))\n end\n call_stack = call_stack.drop(idx) if idx\n\n # skip_while\n elsif intercept_object.skip_while_block\n idx = call_stack.each_with_index.find_index do |frame, idx|\n intercept_object.skip_while_block.call(LazyFrame.new(frame, idx, call_stack)) == false\n end\n call_stack = call_stack.drop(idx) if idx\n end\n\n ex.exception_call_stack = call_stack\n end",
"def pop_exception_handling_frames\n m = @thread.__method_at(i = 1)\n until ExceptionFrames.include?(m.__name) or i >= @thread.__stack_depth\n i += 1\n m = @thread.__method_at(i)\n end\n if i < @thread.__stack_depth\n until m.__env_id == RubyEnv or i >= @thread.__stack_depth\n i += 1\n m = @thread.__method_at(i)\n end\n end\n @thread.__trim_stack_to_level(i) unless i >= @thread.__stack_depth\n end",
"def backtrace_remove; end",
"def backtrace\n end",
"def too_nested\n \"#{\"#{\"#{\"#{\"#{\"#{\"#{\"#{\"#{\"#{\"#{\"#{\"#{\"#{\"#{\"#{\"#{\"#{\"#{\"#{\"#{\"#{\"#{\"#{\"#{\"#{\"#{\"#{\"#{\"#{\"#{\"#{nil}\"}\"}\"}\"}\"}\"}\"}\"}\"}\"}\"}\"}\"}\"}\"}\"}\"}\"}\"}\"}\"}\"}\"}\"}\"}\"}\"}\"}\"}\"}\"}\"\nend",
"def skip_backtrace=(_arg0); end",
"def backtrace_ignores=(_arg0); end",
"def stack_trace=(_arg0); end",
"def safe_level(*) end",
"def check_for_too_nested\n\t\tif commentable && commentable.parent_comment?\n\t\t\terrors.add(:base, \"Нельзя создать комментарий с уровнем вложенности больше 1 (считая с 0).\")\n\t\t\tthrow :abort\n\t\tend\n\tend",
"def cleaned_call_stack(call_stack)\n defined?(::Rails) && ::Rails.respond_to?(:backtrace_cleaner) ?\n ::Rails.backtrace_cleaner.clean(call_stack, :silent) :\n call_stack\n end",
"def set_backtrace(*) end",
"def stacktrace=(_arg0); end",
"def my_depth\n 1\n end",
"def too_deep?( depth )\n depth.to_i > 0 && (depth + 1) <= path.to_s.count( '/' )\n end",
"def trace_down(stack = [])\n stack << self\n return next_in_chain.trace_down(stack) if next_in_chain.present?\n stack\n end",
"def do_exclamation s; mega_pop(s) == 0 ? s[:stack].push(1) : s[:stack].push(0) ; end",
"def backtrace_level; end",
"def StopStack\n \n end",
"def backtrace(exc, level_meth = T.unsafe(nil)); end",
"def continued_exception; end",
"def nesting() end",
"def deepest_cause; end",
"def full_backtrace=(_arg0); end",
"def clean_backtrace(error)\n if $DEBUG\n error\n else\n bt = error.backtrace\n bt = bt.reject{ |e| /roll/ =~ e }\n error.set_backtrace(bt)\n error\n end\n end",
"def max_nesting()\n #This is a stub, used for indexing\n end",
"def max_nesting=(depth)\n #This is a stub, used for indexing\n end",
"def to_stack; end",
"def backtrace_includes; end",
"def show_stack(stack = nil)\n\tstack = 99999 if stack == nil || stack <= 0\n\tbegin\n\t raise Exception.new\n\trescue Exception=>e\n\t if e.backtrace.size >=2 \n\t stack += 1\n\t stack = e.backtrace.size-1 if stack >= e.backtrace.size\n\t return e.backtrace[1..stack].join(\"\\n\") \n\t end\n\tend\n\treturn \"\"\nend",
"def inner_method\n # code\n\n raise 'hello'\n\n # more code\nend",
"def depth=(_arg0); end",
"def __stack\n @stack\n end",
"def __stack\n @stack ||= []\n end",
"def fatal?\n @level <= 4\n end",
"def cond_stack; end",
"def cond_stack; end",
"def cond_stack; end",
"def oops exception\n error \"Unexpected error while checking for issue's parent newspaper object #{exception}\"\n error exception.backtrace\n return nil\n end",
"def depth; end",
"def max_level_depth\n MAXIMUM_LEVEL_DEPTH\n end",
"def StartStack\n #puts \"StartStack not defined!\"\n #exit 1\n end",
"def examine_context(ctx)\n exp, depth = *find_deepest_iterator(ctx)\n\n if depth && depth > value(MAX_ALLOWED_NESTING_KEY, ctx, DEFAULT_MAX_ALLOWED_NESTING)\n [SmellWarning.new(self,\n context: ctx.full_name,\n lines: [exp.line],\n message: \"contains iterators nested #{depth} deep\",\n parameters: { count: depth })]\n else\n []\n end\n # BUG: no longer reports nesting outside methods (eg. in Optparse)\n end",
"def test_should_block_recursion_in_tree\n group = Group.find @greeks_group.id\n\n assert_raises(RecursionInTree) { group.parent = Group.find @cretes_group.id }\n end",
"def add_boundary_stacks(ex, ruby_skip=0)\n if ex.instance_variable_defined?(:@spidermonkey_boundary_stacks)\n list = ex.instance_variable_get(:@spidermonkey_boundary_stacks)\n else\n list = ex.instance_variable_set(:@spidermonkey_boundary_stacks, [])\n end\n\n list << [:js, self.current_stack]\n list << [:ruby, caller(ruby_skip + 1)]\n\n rescue Object\n end",
"def stacktrace_includes=(_arg0); end",
"def validate_stack!\n return if config[:blank]\n\n ensure_mockup_processor_in_stack!\n ensure_dir_finalizer_in_stack!\n end",
"def too_many_hops?; end",
"def StartStack\n\n end",
"def fatal; end",
"def callstack\n @callstack.dup\n end",
"def deep_thaw!\n replace deep_thaw\n end",
"def clean_stack(stack)\n open_stack,keep=[],{}\n stack.each do |elt|\n if elt[1]==1\n open_stack << elt\n else\n if open_stack.empty?\n ##too many closed delimiters\n else\n keep[elt]=true\n keep[open_stack.pop]=true\n end\n end\n end\n=begin\n if Dyndoc.cfg_dir[:debug]\n tmp=stack.select{|elt| !keep[elt]}.select{|e| @tag_type==:call and e[2] and e[1]==1 and e[2]!='{'}\n begin p @txt;p tmp end unless tmp.empty?\n end\n=end\n stack.select{|elt| keep[elt]}\n end",
"def state_depth_must_be(level)\n states[0..level].each do |a|\n raise 'factory state error' if a.nil?\n end\n end",
"def backtrace_level=(_arg0); end",
"def shush_backtraces\n Kernel.module_eval do\n old_raise = Kernel.method(:raise)\n remove_method :raise\n define_method :raise do |*args|\n begin\n old_raise.call(*args)\n ensure\n if $!\n lib = File.expand_path(\"..\", __FILE__)\n $!.backtrace.reject! { |line| line.start_with?(lib) }\n end\n end\n end\n end\n end",
"def recursive => nil",
"def ignore_parent_exclusion; end",
"def close_stack indent_level\r\n while @token_stack.size > 0 and @token_stack[-1].indent_level >= indent_level\r\n if @token_stack.size > 1 # if this is not the last token, add to parents\r\n @token_stack[-2].add_block_code self.convert(@token_stack[-1])\r\n else # this is the last token in the stack\r\n dump self.convert(@token_stack[-1])\r\n end\r\n @token_stack.pop\r\n end\r\n end",
"def stacktrace_excludes=(_arg0); end",
"def fail\n\t\t# throw up this code and feed plezi your own lines :)\n\t\traise \"Plezi raising hell!\"\n\tend",
"def show_backtraces=(_arg0); end",
"def filter(backtrace); end",
"def filter(backtrace); end",
"def shush_backtraces\n Kernel.module_eval do\n old_raise = Kernel.method(:raise)\n remove_method :raise\n if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('3.2.0')\n define_method :raise do |*args, **kwargs|\n begin\n old_raise.call(*args, **kwargs)\n ensure\n if $!\n lib = File.expand_path(\"..\", __FILE__)\n $!.backtrace.reject! { |line| line.start_with?(lib) } unless $!.backtrace.frozen?\n end\n end\n end\n else\n define_method :raise do |*args|\n begin\n old_raise.call(*args)\n ensure\n if $!\n lib = File.expand_path(\"..\", __FILE__)\n $!.backtrace.reject! { |line| line.start_with?(lib) } unless $!.backtrace.frozen?\n end\n end\n end\n end\n private :raise\n end\n end",
"def raise_on_context_miss?\n self.class.raise_on_context_miss? || @raise_on_context_miss\n end",
"def no_circular_reference\n\n end",
"def keep_it_in\n raise \"rawr\"\nrescue\n # ahem\nend",
"def load_stack\n $LOAD_STACK\n end",
"def examine_context(ctx)\n exp, depth = *find_deepest_iterator(ctx)\n\n if depth && depth > value(MAX_ALLOWED_NESTING_KEY, ctx, DEFAULT_MAX_ALLOWED_NESTING)\n smell = SmellWarning.new(SMELL_CLASS, ctx.full_name, [exp.line],\n \"contains iterators nested #{depth} deep\",\n @source, SMELL_SUBCLASS,\n {NESTING_DEPTH_KEY => depth})\n [smell]\n else\n []\n end\n # BUG: no longer reports nesting outside methods (eg. in Optparse)\n end",
"def not_reset_scope?(node); end",
"def on_size_exceeded\n tracer.trace('operation.parent') do\n # Fill the trace over the capacity of the context\n max_size.times do |i|\n tracer.trace('operation.sibling') do |span|\n yield(span) if i + 1 == max_size\n end\n end\n end\n end",
"def stack_depth\n @stack.size\n end",
"def backtrace_remove=(_arg0); end",
"def push_local_depth\n <<-CODE\n next_int;\n k = (native_int)_int;\n next_int;\n t1 = c->active_context;\n for(j = 0; j < k; j++) {\n t2 = blokctx_env(state, t1);\n t1 = blokenv_get_home_block(t2);\n }\n stack_push(tuple_at(state, blokctx_locals(state, t1), _int));\n CODE\n end",
"def ignore_parent_exclusion?; end",
"def _smart_backtrace(e)\n prefix = File.expand_path('../../..', __FILE__)\n seen_own = false\n e.backtrace.select do |line|\n matches = line.start_with?(prefix)\n seen_own = true if matches\n matches || !seen_own\n end\n end",
"def foo\n return raise\n#> xxxxxx\n end",
"def try_soft_loud\n begin\n yield\n rescue => e\n puts \"PROBLEM!! #{e}\"\n puts e.backtrace\n end\nend",
"def big_bad; end",
"def off_test_stack32_014\n rsp = exec(\": test 2 4 6 depth ;\")\n stk = stack(rsp)\n assert_equal([2, 4, 6, 3], stk)\n end",
"def validate\n if (depth != parent.depth+1)\n no(\"#{short} has bad depth\")\n end\n ui.puts \"#{indent}ok (depth: #{depth})#{short}\"\n end",
"def ignore_parent_exclusion=(_arg0); end",
"def analysis_overflowed\n return @state_to_recursion_overflow_configurations_map.size > 0\n end",
"def parsed_stack\n @values.fetch('parsedStack') { \n @values['parsedStack'] = []\n }\n end",
"def fatal?; end",
"def fatal?; end"
] |
[
"0.66754025",
"0.6542896",
"0.6515862",
"0.6381898",
"0.62401146",
"0.62401146",
"0.6207577",
"0.6176437",
"0.61463374",
"0.6115131",
"0.6037843",
"0.6009631",
"0.59651744",
"0.5954186",
"0.5944497",
"0.58898026",
"0.58525807",
"0.5849964",
"0.58479804",
"0.58305657",
"0.58159626",
"0.5775705",
"0.5769927",
"0.57664",
"0.5757807",
"0.5748554",
"0.5722164",
"0.5699356",
"0.56729186",
"0.5669684",
"0.56686985",
"0.566761",
"0.56595945",
"0.56320816",
"0.56279075",
"0.561083",
"0.556222",
"0.5543191",
"0.55429673",
"0.5531719",
"0.55062515",
"0.55011326",
"0.54900783",
"0.54894847",
"0.54701084",
"0.5445373",
"0.5444742",
"0.5440345",
"0.5437739",
"0.5436299",
"0.5436299",
"0.5436299",
"0.5414363",
"0.5404017",
"0.5393877",
"0.53706515",
"0.532656",
"0.5321395",
"0.5309048",
"0.53054005",
"0.5301325",
"0.52995604",
"0.529746",
"0.5296019",
"0.52900046",
"0.52787596",
"0.5276947",
"0.52729666",
"0.5265186",
"0.5259159",
"0.5247154",
"0.5236802",
"0.52337563",
"0.52257305",
"0.5223348",
"0.521638",
"0.52115476",
"0.52115476",
"0.52081513",
"0.52032727",
"0.51960886",
"0.51941377",
"0.5192551",
"0.518292",
"0.5176198",
"0.517054",
"0.51646656",
"0.51566803",
"0.51554143",
"0.51547396",
"0.5147908",
"0.51466763",
"0.51381826",
"0.51360536",
"0.5136004",
"0.5126529",
"0.5117864",
"0.51101226",
"0.5109123",
"0.5108013",
"0.5108013"
] |
0.0
|
-1
|
here we pull the realtime info from SWAPI.COM, and put it in a hash. Copy and paste the URL and get familiar with what data is in there.
|
def planets
data = JSON.parse(open("http://swapi.co/api/planets").read)
@results = data["results"]
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def access_api(url)\n http = Net::HTTP.new(url.host, url.port)\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n file = File.open('bin/key.rb')\n request = Net::HTTP::Get.new(url)\n request[\"x-rapidapi-host\"] = 'skyscanner-skyscanner-flight-search-v1.p.rapidapi.com'\n request[\"x-rapidapi-key\"] = file.read\n\n response = http.request(request).read_body\n response_hash = JSON.parse(response) \nend",
"def swapi_fetch(url)\n JSON.parse(open(url).read)\nend",
"def web_request\n response_string = RestClient.get('http://www.swapi.co/api/people/')\n response_hash = JSON.parse(response_string)\nend",
"def show_page_api\n @url = 'https://api.coinmarketcap.com/v1/ticker/'\n @uri = URI(@url)\n @response = Net::HTTP.get(@uri)\n # converts response to a Ruby hash \n @show_crypto = JSON.parse(@response)\n end",
"def fetch_api_data\n addr = URI(API_URL)\n addr.query = URI.encode_www_form(form_params.transform_keys(&:to_s))\n\n data = JSON.parse(Net::HTTP.get(addr))\n\n @latest_report = {\n temp: data['main']['temp'].round.to_s + '°',\n desc: data['weather'][0]['description'],\n icon: weather_icon(data['weather'][0]['icon'][0..-2].to_i),\n wind_speed: data['wind']['speed'].floor,\n wind_dir: compass_dir(data['wind']['deg'])\n }\n end",
"def set_api\n @url = 'https://api.coinmarketcap.com/v1/ticker/'\n @uri = URI(@url)\n @response = Net::HTTP.get(@uri)\n # converts response to a Ruby hash \n @lookup_crypto = JSON.parse(@response)\n @gain_loss = 0\n end",
"def call\n url = URI(\"https://api.covid19api.com/summary\")\n https = Net::HTTP.new(url.host, url.port);\n https.use_ssl = true\n\n request = Net::HTTP::Get.new(url)\n response = https.request(request).read_body\n\n data_hash = JSON.parse(response)\n end",
"def get_titleinfo(mode)\n if mode\n url = \"https://api.vinaudit.com/pullreport.php?user=\" + Rails.application.secrets.vin_audit_username + \"&pass=\" + Rails.application.secrets.vin_audit_password +\n \"&vin=\" + @sell_request.vin + \"&key=\" + Rails.application.secrets.vin_audit_key + \"&format=json\" + \"&mode=test\" + \"&id=\" + rand(10**12).to_s\n else\n url = \"https://api.vinaudit.com/pullreport.php?user=\" + Rails.application.secrets.vin_audit_username + \"&pass=\" + Rails.application.secrets.vin_audit_password +\n \"&vin=\" + @sell_request.vin + \"&key=\" + Rails.application.secrets.vin_audit_key + \"&format=json\" +\"&id=\" + rand(10**12).to_s\n end\n\n clean = nil\n # try_times = 6 #do it for at most 6 times\n # TODO may need to discuss the times\n while clean == nil\n json = JSON.parse(OpenURI.open_uri(url, {ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE}).read)\n clean = json['clean']\n # try_times -= 1\n # if try_times == 0\n # break;\n # end\n end\n clean\n # if\n end",
"def get url\n puts \"COMMUNICATING WITH TOGGL SERVER COMMUNICATING WITH TOGGL SERVER\"\n uri = URI.parse( url )\n http = Net::HTTP.new( uri.host, uri.port )\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n request = Net::HTTP::Get.new( uri.request_uri )\n request.basic_auth( @api_key, \"api_token\" )\n request[\"Content-Type\"] = \"application/json\"\n response = http.request( request )\n \n if response.code.to_i==200 # OK\n hash = JSON.parse( response.body )\n elsif response.code.to_i==403 # Authentication\n raise Exceptions::AuthenticationError\n else\n puts \"Error, code #{ response.code }.\"\n puts response.body\n end\n end",
"def refresh\n json = JSON(Net::HTTP.get(URI.parse(base_url)))\n unpack(json)\n end",
"def get_events_from_api(name)\n #make the web request\n name1 = name\n performer_link = \"https://app.ticketmaster.com/discovery/v2/events.json?keyword=#{name1}&countrycode=US&apikey=ShI4Sd340EJ32f1k6rUgkYPocLSO2qTq\"\n response_string = RestClient.get(performer_link)\n response_hash = JSON.parse(response_string)\nend",
"def search_techcrunch\n response_string = RestClient.get\"https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=45aee5b7c7584064ac1b1de6297f5137\"\n response_hash = JSON.parse(response_string.body)\n end",
"def view_api\n api_string = RestClient.get(\"https://itunes.apple.com/search?term=star+wars&entity=song&attribute=movieTerm\")\n api_hash = JSON.parse(api_string)\n\n end",
"def get_profile_for_url(apikey, apisecret, url)\n\t# Generate a timestamp for the request\n\ttimestamp = Time.now.to_i # Current time in seconds since epoch\n\t\n\t# Store the url in a params hash to calculate the signature\n\tparameters = {}\n\tparameters[:url] = url\n\t\n\t# Calculate the signature for this call - used for authentication by the api server\n\tsig = calculate_hash(apikey, apisecret, timestamp, parameters)\n\t\n\t# Construct the HTTP request\n\thostname = @server #'int-api.sociocast.com'\n\tport = @port\n\tts_string = 'ts=' + timestamp.to_s\n\tapikey_string = 'apikey=' + apikey.to_s\n\tsig_string = 'sig=' + sig\n\t\n\tputs \"Trying to build GET request string for URL: #{url}\"\n # Encode the URL for safe passage and ensure that the calculated signature is appended to the call\n # along with the time stamp.\n\trequest_path = '/content/profile?url=' + \n\t ERB::Util.url_encode(url) + '&' + apikey_string + '&' + ts_string + '&' + sig_string \n\t\n\t# Send the request\n\theaders = { 'Content-Type' => 'application/json; charset=utf-8' }\n\trequest = Net::HTTP::Get.new(request_path, initheader = headers)\n\tresponse = Net::HTTP.new(hostname, port).start{|http| http.request(request)}\n\n\tputs \"Response #{response.code} #{response.message}: #{response.body}\"\nend",
"def get_surf_data\n url = \"http://magicseaweed.com/api/#{ENV['MAGIC_SEAWEED_API_KEY']}/forecast/?spot_id=6128&units=UK\"\n uri = URI(url)\n\n response = Net::HTTP.get(uri)\n ActiveSupport::JSON.decode(response) if response != ''\n end",
"def request(url, api_key)\n rover = get_data(\"#{url}#{api_key}\")\n\n return rover\nend",
"def net_http_get_package_info\n thread = @thread\n timestamp = Time.now.utc.strftime(\"%Y-%m-%dT%H:%M:%S\\+0000\")\n\n uri = URI(\"#{@sendsafely_url}/#{API}/package/#{@thread}/\")\n\n req = Net::HTTP::Get.new(uri)\n req['Content-Type'] = 'application/json'\n req['ss-api-key'] = @sendsafely_key_id\n req['ss-request-timestamp'] = timestamp\n req['ss-request-signature'] = OpenSSL::HMAC.hexdigest(\"SHA256\", @sendsafely_key_secret, @sendsafely_key_id+\"/#{API}/package/#{thread}\"+timestamp)\n\n res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) {|http|\n http.request(req)\n }\n\n puts res.body\n end",
"def look_up(url)\n all = RestClient.get(url)\n hash = JSON.parse(all)\nend",
"def request(url,token = nil)\n url = URI(\"#{url}&api_key=#{token}\") # se quita uri y parentesis\n #puts url_string\n \n \n https = Net::HTTP.new(url.host, url.port)\n https.use_ssl = true\n request = Net::HTTP::Get.new(url)\n response = https.request(request)\n data = JSON.parse(response.read_body)\n #puts data\nend",
"def fetchServerConfig()\n #Construct the URL for the request\n url = \"http://api.themoviedb.org/3/configuration?api_key=#{$apiKey}\"\n #Preform a restful reqeust for the data\n data = RestClient.get(url)\n #Parse the returned JSON and return it as a hash\n return JSON.parse(data)\nend",
"def main_page_api\n @url = 'https://api.coinmarketcap.com/v1/ticker/'\n @uri = URI(@url)\n @response = Net::HTTP.get(@uri)\n # converts response to a Ruby hash \n @coins = JSON.parse(@response)\n @my_coins = [\"XLM\", \"BTC\", \"ADA\", \"STEEM\", \"ETH\"] \n end",
"def fetchInstallations(token)\n url = URI(\"https://api.acceptance.hertekconnect.nl/api/v1/installations\")\n\n http = Net::HTTP.new(url.host, url.port);\n http.use_ssl = true\n request = Net::HTTP::Get.new(url)\n request[\"Content-Type\"] = \"application/json\"\n request[\"Authorization\"] = \"Bearer #{token}\"\n\n response = http.request(request)\n puts response.read_body\nend",
"def GETCall url\n \n a = Time.now.to_f\n \n uri = URI.parse url\n \n http = Net::HTTP.new(uri.host,443)\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n http.use_ssl = true if uri.scheme == 'https'\n req = Net::HTTP::Get.new uri.path\n response = http.request req\n code = response.code.to_f.round\n body = response.body\n \n b = Time.now.to_f\n c = ((b-a)*100).round.to_f/100\n \n final = {code: code}\n final = final.merge(body: body)\n final = final.merge(time: c)\n \n final\n \n end",
"def fetch_show\r\n live_hash = JSON.parse(open(LIVE_URL).read)\r\n\r\n if live_hash and live_hash.has_key?(\"live\") and live_hash[\"live\"]\r\n # Show is live, read show name\r\n broadcast = live_hash[\"broadcast\"] if live_hash.has_key? \"broadcast\"\r\n self.show = broadcast[\"slug\"] if broadcast.has_key? \"slug\"\r\n end\r\n end",
"def parse_api\n\t\t@api_data_on_electeds[\"results\"].map do |info|\n\t\t\tfirst_name = info[\"first_name\"]\n\t\t\tlast_name = info[\"last_name\"]\n\t\t\temail = info[\"oc_email\"]\n\t\t\tphone = info[\"phone\"]\n\t\t\ttwitter = info[\"twitter_id\"]\n\t\tputs \"Your elected official is #{first_name} #{last_name}. Their email is #{email} and you can call them at #{phone}. Also send them a tweet at @#{twitter}!\"\n\tend\nend",
"def show\n require 'net/http'\n require 'json'\n\n @url = 'https://api.coinmarketcap.com/v1/ticker/'\n @uri = URI(@url)\n @response = Net::HTTP.get(@uri)\n @show_crypto = JSON.parse(@response)\n end",
"def champs\n conn = Faraday.new(url, request: {open_timeout: 5, timeout: 5}) do |c|\n c.response :json, :content_type => /\\bjson$/\n c.use Faraday::Response::Logger # log request & response to STDOUT\n c.adapter Faraday.default_adapter\n end\n response = conn.get url\n #@hash = response.body['data']\n response.body['data']\n end",
"def url_hash(url)\n response_string = RestClient.get(url)\n JSON.parse(response_string)\nend",
"def film_api(url)\n film_response = RestClient.get(url)\n film_hash = JSON.parse(film_response)\nend",
"def get_info(refresh = false)\n if @info_got && !refresh\n return\n end\n resp = nil\n Net::HTTP.start('ext.nicovideo.jp') do |http|\n resp = http.get('/api/getthumbinfo/' + @video_id,\n {'Cookie' => 'user_session=' + @user_session.session_id})\n end\n resp.value\n xml = REXML::Document.new(resp.body)\n root = xml.root\n if root.attributes['status'] == 'ok'\n @title = root.elements['thumb/title'].text\n @description = root.elements['thumb/description'].text\n @thumbnail_url = root.elements['thumb/thumbnail_url'].text\n @first_retrieve = DateTime.parse(root.elements['thumb/first_retrieve'].text)\n length_string = root.elements['thumb/length'].text\n length_arr = length_string.split(':')\n @length = length_arr[0].to_i * 60 + length_arr[1].to_i\n @movie_type = root.elements['thumb/movie_type'].text\n @view_counter = root.elements['thumb/view_counter'].text.to_i\n @comment_num = root.elements['thumb/comment_num'].text.to_i\n @mylist_counter = root.elements['thumb/mylist_counter'].text.to_i\n @embeddable = root.elements['thumb/embeddable'].text == '1'\n @live_allowed = root.elements['thumb/no_live_play'].text == '0'\n @tags = {}\n root.elements.each('thumb/tags') do |tse|\n key = tse.attributes['domain']\n dtags = []\n tse.elements.each('tag') do |tge|\n dtags.push(Bnicovideo::Tag.new(tge.text,\n tge.attributes['lock'] == '1', tge.attributes['category'] == '1'))\n end\n @tags[key] = dtags\n end\n @user_id = root.elements['thumb/user_id'].text\n else\n @deleted = true\n end\n @info_got = true\n end",
"def scan_site_conf_for_one_bts(s1_ip,logger,username,passwd)\n\n site_conf=get_site_conf(s1_ip, username, passwd)\n hw_info_hash=scan(site_conf)[0]\n\n update_hw_info_hash(s1_ip,hw_info_hash)\n\nend",
"def api_url\n @instant = (1..4).to_a if @instant.empty?\n i = @instant.shift\n return \"http://#{i}-instant.okcupid.com/instantevents?random=#{rand}&server_gmt=#{Time.now.to_i}\"\n end",
"def fetch(query)\n # Returns the string if the API key is missing\n raise \"Missing API key\" if ENV['X_RAPIDAPI_KEY'].empty?\n\n # Builds the URL\n url = URI(API_URL + \"?#{query}\")\n\n # Given by UNOGS\n http = Net::HTTP.new(url.host, url.port)\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n request = Net::HTTP::Get.new(url)\n request[\"x-rapidapi-host\"] = 'unogs-unogs-v1.p.rapidapi.com'\n request[\"x-rapidapi-key\"] = ENV['X_RAPIDAPI_KEY']\n\n # If the API result includes an empty string we get an error and the call\n # execution stops, so we need to retry the request; below we set the code to\n # retry 3 times if we get the JSON::ParserError exception\n attempt_count = 0\n max_attempts = 3\n\n begin\n response = http.request(request)\n attempt_count += 1\n puts \"attempt ##{attempt_count} - #{url}\"\n JSON.parse response.read_body\n rescue JSON::ParserError => e\n puts \"error: #{e}\"\n sleep 3 * attempt_count\n retry if attempt_count < max_attempts\n end\n end",
"def call\n \n # create URI::HTTPS object using the url of the API \n url = URI(\"https://api.covid19api.com/summary\")\n \n # create new Net::HTTP object\n https = Net::HTTP.new(url.host, url.port); \n \n # turn on SSL flag \n https.use_ssl = true\n \n # create Net::HTTP::Get object with the url\n request = Net::HTTP::Get.new(url)\n \n # use the Net::HTTP object to send a request for the information\n # and return the data via a string \n response = https.request(request).read_body\n \n end",
"def scdisplay(id)\n\thttp = Net::HTTP.new(\"shell-storm.org\", 80)\n\treq = Net::HTTP::Get.new(\"/shellcode/files/shellcode-#{id}.php\", {'User-Agent' => 'Shell-Storm Ruby API - Display'})\n\tres = http.request(req)\n\tcase res\n\twhen Net::HTTPSuccess then\n\t\tputs \"#{HC}#{FGRN}[#{FWHT}*#{FGRN}] Displaying#{FWHT}: http://shell-storm.org/shellcode/files/shellcode-#{id}.php#{FCYN}\"\n\t\tputs res.body.split(\"\\n\")[7..-13].join(\"\\n\").gsub('"', '\"').gsub('>', '>').gsub('<', '<').gsub('&', '&')\n\t\tputs \"#{RS}\"\n\telse\n\t\tputs \"#{HC}#{FRED}Seems we made a bad request somehow#{FWHT}....#{RS}\"\n\t\tputs res.value\n\tend\nend",
"def track\n url = Rails.env.development? ? \"http://localhost:8000/stat\" : \"http://stats.universit.as/stat\"\n RestClient.get(url, :params => {\n :ip => request.remote_ip,\n :title => request.referrer\n })\n render :js => ''\n end",
"def analyze(url)\n\n\t#Preparing to call RESTapi and json results\n\tbase_uri = \"https://api.ssllabs.com/api/v2\"\n\tfanalyzeuri = URI.parse(\"#{base_uri}/analyze?host=#{url}&startNew=on\")\n\tanalyzeuri = URI.parse(\"#{base_uri}/analyze?host=#{url}\")\n fhttp = Net::HTTP.new(fanalyzeuri.host,fanalyzeuri.port)\n http = Net::HTTP.new(analyzeuri.host,analyzeuri.port)\n\n\t#Using SSL\n\tfhttp.use_ssl = true\n\tfhttp.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\thttp.use_ssl = true\n\thttp.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n\t#Receiving JSON\n\tfrequest = Net::HTTP::Get.new(fanalyzeuri.request_uri)\n fresponse = fhttp.request(frequest)\n\trequest = Net::HTTP::Get.new(analyzeuri.request_uri)\n\tresponse = fhttp.request(request)\n\n\t#Parsing JSON\n\tresult = JSON.parse(fresponse.body)\n\n\t#Waiting for endpoints to generate\n\tuntil result.has_key?(\"endpoints\")\n\t\t\tresponse = fhttp.request(request)\n\t\t\tresult = JSON.parse(response.body)\n\t \t\tsleep(2)\n\tend\n\n\t#Waiting for ipaddresses to populate\n\tresult[\"endpoints\"].each_index do |i|\n\t\tuntil result[\"endpoints\"][i].has_key?(\"ipAddress\")\n\t\t\tresponse = fhttp.request(request)\n\t\t\tresult = JSON.parse(response.body)\n\t\t\tsleep(5)\n\n\t\tend\n\n\t\t#Check for status if ready\n\t\tuntil result[\"endpoints\"][i][\"statusMessage\"] == \"Ready\"\n\t\t\tresponse = fhttp.request(request)\n\t\t\tresult = JSON.parse(response.body)\n\t\t\tsleep(30)\n\t\tend\n\tend\n\treturn result\nend",
"def generate_url\n api_key = WavecellOtpAndSms.configuration.api_key\n sub_account = WavecellOtpAndSms.configuration.sub_account\n details = [uid, code]\n parameters = {\n uid: uid,\n code: code\n }\n query_string = parameters.to_a.map { |x| \"#{x[0]}=#{x[1]}\" }.join(\"&\")\n url = \"https://api.wavecell.com/otp/v1/#{sub_account}/#{uid}?code=#{code}\"\n HTTParty.get(url.to_str,\n :body => parameters.to_json,\n :headers => {\n \"Content-Type\" => \"application/json\",\n \"Authorization\" => \"Bearer #{api_key}\"\n })\n end",
"def payload(temp)\n num = temp.values[0]\n {\n :url => \"http://jumpstartlab.com/blog#{num}\",\n :requestedAt => \"#{Time.new}\",\n :respondedIn => 37,\n :referredBy => \"http://jumpstartlab.com\",\n :requestType => \"GET\",\n :eventName => \"socialLogin\",\n :userAgent => \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2)\"\\\n \"AppleWebKit/537.17 (KHTML, like Gecko)\"\\\n \"Chrome/24.0.1309.0 Safari/537.17\",\n :resolutionWidth => \"1920\",\n :resolutionHeight => \"1280\",\n :ip => \"63.29.38.211\"\n }\nend",
"def get_champion_data(patch_number)\n response_string = RestClient.get(\"http://ddragon.leagueoflegends.com/cdn/#{patch_number}/data/en_US/champion.json\")\n response_hash = JSON.parse(response_string)\n champion_data = response_hash[\"data\"]\nend",
"def get_movies_from_api\n all_films = RestClient.get('http://www.swapi.co/api/films/')\n film_hash = JSON.parse(all_films) \nend",
"def site_data_hash; end",
"def query(action, hash = {})\n # uri = URI.parse(\"https://130.59.10.31\")\n # http = Net::HTTP.new(uri.host, uri.port)\n # http.use_ssl = true\n # http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n #\n # request = Net::HTTP::Get.new(uri.request_uri)\n #\n # response = http.request(request)\n # response.body\n # response.status\n # response[\"header-here\"] # All headers are lowercase\n uri = URI.parse(@url + \"/api/xml?action=#{action}\")\n hash.each_pair do |key, val|\n if val\n if key == \"filter\" or key == \"sort\"\n uri.query += val.query\n else\n uri.query += \"&\" + key + \"=\" + CGI::escape(\"#{val}\")\n end\n end\n end\n http = Net::HTTP.new(uri.host, uri.port)\n if uri.scheme == \"https\"\n http.use_ssl=true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n end\n request = Net::HTTP::Get.new(uri.request_uri)\n # logger = Logger.new('log/development.log')\n # logger.info(url.path + \"?\" + url.query)\n if @sessionid\n request.add_field(\"Cookie\", \"BREEZESESSION=\"+@sessionid)\n end\n puts \"ACS query - request: \" + request.path\n response = http.request(request)\n puts \"ACS query - response: \" + response.body.inspect\n return response\n end",
"def make_url\n [ \"http://ws.audioscrobbler.com/2.0/?method=#{api_method}#{identifier}\",\n \"&limit=#{max_items}&api_key=#{api_key}&format=json\",\n \"&page=#{page}\" ].join(\"\")\n end",
"def usd_base_json\n if @last_check.nil? || Time.now.to_i - @last_check.to_i > 30 * 60\n oxr_latest_uri = URI.parse(\"https://openexchangerates.org/api/latest.json?app_id=#{OXR_APP_ID}\")\n oxr_response = Net::HTTP.get_response(oxr_latest_uri)\n @json_storage = JSON.parse(oxr_response.body)\n @last_check = Time.now\n end\n @json_storage\nend",
"def state_events(state)\n api_return = RestClient.get('https://app.ticketmaster.com/discovery/v2/events.json?stateCode=' + state + '&apikey=' + $ticket_master_api_key)\n JSON.parse(api_return)\nend",
"def show\n # base url of the remote data\n # append the 'id' to this to generate the remote url\n baseUrl = 'https://api.gojimo.net/api/v4/'\n\n # request the meta data from the remote server and\n # extract the time its data was last updated\n meta = open(\"#{baseUrl}#{params[:id]}\").meta\n update_at = meta[\"last-modified\"].to_date\n\n # request new data when the local data timestamp pre dates the remote data\n requires_refresh = params[:update_at].blank? || update_at > params[:update_at].to_date\n\n # request the remote data if it is newer than the local copy\n data = open(\"#{baseUrl}#{params[:id]}\").read if requires_refresh\n # parse any data since we are going to add the data to an object which is then converted to json\n data = JSON.parse(data) unless data.blank?\n\n # return any data together with timestamps and a flag to show whetjer new data was retrieved\n render json: {new_data: requires_refresh, data: data, update_at: update_at.strftime('%a %d %b %Y'), check_at: Time.now.strftime('%H:%M %a %d %b %Y')}\n\n end",
"def show\n @sleuths = HTTParty.get('https://webservice.wikipathways.org/findPathwaysByText?query=' + @sleuth.ext_gene + '&species=homo+sapiens&format=json',\n :headers =>{'Content-Type' => 'application/json'} )\n @pubs = HTTParty.get('https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&retmode=json&term='+ @sleuth.ext_gene,\n :headers =>{'Content-Type' => 'application/json'} )\n end",
"def calc_url_response\r\n 'https://secure.bluepay.com/interfaces/shpf?' +\r\n 'SHPF_FORM_ID=' .concat(url_encode (@PARAM_HASH['SHPF_FORM_ID']) ) +\r\n '&SHPF_ACCOUNT_ID=' .concat(url_encode (@ACCOUNT_ID) ) +\r\n '&SHPF_TPS_DEF=' .concat(url_encode (@shpf_tps_def) ) +\r\n '&SHPF_TPS_HASH_TYPE='.concat(url_encode (@PARAM_HASH['SHPF_TPS_HASH_TYPE']) ) +\r\n '&SHPF_TPS=' .concat(url_encode (@shpf_tamper_proof_seal) ) +\r\n '&MODE=' .concat(url_encode (@PARAM_HASH['MODE']) ) +\r\n '&TRANSACTION_TYPE=' .concat(url_encode (@PARAM_HASH['TRANSACTION_TYPE']) ) +\r\n '&DBA=' .concat(url_encode (@PARAM_HASH['DBA']) ) +\r\n '&AMOUNT=' .concat(url_encode (@PARAM_HASH['AMOUNT']) ) +\r\n '&TAMPER_PROOF_SEAL=' .concat(url_encode (@bp10emu_tamper_proof_seal) ) +\r\n '&CUSTOM_ID=' .concat(url_encode (@PARAM_HASH['CUSTOM_ID']) ) +\r\n '&CUSTOM_ID2=' .concat(url_encode (@PARAM_HASH['CUSTOM_ID2']) ) +\r\n '&REBILLING=' .concat(url_encode (@PARAM_HASH['REBILLING']) ) +\r\n '&REB_CYCLES=' .concat(url_encode (@PARAM_HASH['REB_CYCLES']) ) +\r\n '&REB_AMOUNT=' .concat(url_encode (@PARAM_HASH['REB_AMOUNT']) ) +\r\n '&REB_EXPR=' .concat(url_encode (@PARAM_HASH['REB_EXPR']) ) +\r\n '&REB_FIRST_DATE=' .concat(url_encode (@PARAM_HASH['REB_FIRST_DATE']) ) +\r\n '&AMEX_IMAGE=' .concat(url_encode (@PARAM_HASH['AMEX_IMAGE']) ) +\r\n '&DISCOVER_IMAGE=' .concat(url_encode (@PARAM_HASH['DISCOVER_IMAGE']) ) +\r\n '&REDIRECT_URL=' .concat(url_encode (@receipt_url) ) +\r\n '&TPS_DEF=' .concat(url_encode (@bp10emu_tps_def) ) +\r\n '&TPS_HASH_TYPE=' .concat(url_encode (@PARAM_HASH['TPS_HASH_TYPE']) ) +\r\n '&CARD_TYPES=' .concat(url_encode (@card_types) )\r\n end",
"def show\n id = params.keys[1] # Query variable is the ID of the TV show that the user clicks on.\n\n #template = Addressable::Template.new('https://api.themoviedb.org/3/tv/{?query*}?api_key=fb6a1d3f38c3d97f67df6d141f936f29&language=en-US')\n #url = template.expand({\"query\" => id})\n #response = HTTParty.get(url)\n\n url = Addressable::URI.parse(\"https://api.themoviedb.org/3/tv/#{id}?api_key=fb6a1d3f38c3d97f67df6d141f936f29&language=en-US\")\n response = HTTParty.get(url)\n\n @show = JSON.parse(response.body, symbolize_names: true) \n end",
"def calc_url_response\r\n 'https://secure.bluepay.com/interfaces/shpf?' +\r\n 'SHPF_FORM_ID=' .concat(url_encode (@PARAM_HASH['SHPF_FORM_ID']) ) +\r\n '&SHPF_ACCOUNT_ID=' .concat(url_encode (@ACCOUNT_ID) ) +\r\n '&SHPF_TPS_DEF=' .concat(url_encode (@shpf_tps_def) ) +\r\n '&SHPF_TPS=' .concat(url_encode (@shpf_tamper_proof_seal) ) +\r\n '&MODE=' .concat(url_encode (@PARAM_HASH['MODE']) ) +\r\n '&TRANSACTION_TYPE=' .concat(url_encode (@PARAM_HASH['TRANSACTION_TYPE']) ) +\r\n '&DBA=' .concat(url_encode (@PARAM_HASH['DBA']) ) +\r\n '&AMOUNT=' .concat(url_encode (@PARAM_HASH['AMOUNT']) ) +\r\n '&TAMPER_PROOF_SEAL=' .concat(url_encode (@bp10emu_tamper_proof_seal) ) +\r\n '&CUSTOM_ID=' .concat(url_encode (@PARAM_HASH['CUSTOM_ID']) ) +\r\n '&CUSTOM_ID2=' .concat(url_encode (@PARAM_HASH['CUSTOM_ID2']) ) +\r\n '&REBILLING=' .concat(url_encode (@PARAM_HASH['REBILLING']) ) +\r\n '&REB_CYCLES=' .concat(url_encode (@PARAM_HASH['REB_CYCLES']) ) +\r\n '&REB_AMOUNT=' .concat(url_encode (@PARAM_HASH['REB_AMOUNT']) ) +\r\n '&REB_EXPR=' .concat(url_encode (@PARAM_HASH['REB_EXPR']) ) +\r\n '&REB_FIRST_DATE=' .concat(url_encode (@PARAM_HASH['REB_FIRST_DATE']) ) +\r\n '&AMEX_IMAGE=' .concat(url_encode (@PARAM_HASH['AMEX_IMAGE']) ) +\r\n '&DISCOVER_IMAGE=' .concat(url_encode (@PARAM_HASH['DISCOVER_IMAGE']) ) +\r\n '&REDIRECT_URL=' .concat(url_encode (@receipt_url) ) +\r\n '&TPS_DEF=' .concat(url_encode (@bp10emu_tps_def) ) +\r\n '&CARD_TYPES=' .concat(url_encode (@card_types) )\r\n end",
"def raw_stats\n url = URI.parse(stats_url)\n Net::HTTP.start(url.host, url.port) {|http|\n http.request(Net::HTTP::Get.new(url.path))\n }.body\nend",
"def get_api_json\n response_string = RestClient.get('http://www.swapi.co/api/people/')\n JSON.parse(response_string)\nend",
"def get(url = \"/api/system/info\")\n url = File.join(@client.url, url)\n request = Typhoeus::Request.new(url,\n method: :get,\n headers: headers,\n ssl_verifypeer: @client.ssl_verify_peer?,\n cookiefile: cookie_file_path, # read from\n cookiejar: cookie_file_path, # write to\n userpwd: [@client.user, @client.password].join(\":\"))\n request.run\n request.response\n end",
"def ping\n puts \"Getting all data from Twitch, please wait (there's a lot here).\"\n types = {games: \"games/top\", videos:\"videos/top\", streams:\"streams\"}\n master_hash = {}\n types.each do |key, value|\n master_hash[key] = JSON.parse(RestClient.get('https://api.twitch.tv/kraken/' + value + '?client_id=8c62koccz5yyd663djbo1lpydgcbnw'))\n end\n master_hash\n binding.pry\nend",
"def get_more_frontpage_info()\n specials = []\n top_sellers = []\n base_url = \"http://store.steampowered.com/api/featuredcategories/\"\n uri = URI(base_url)\n #get the body of the text\n body = page_refresh_no_id(uri,1)\n if valid_json?(body)\n hash = JSON(body)\n if has_top_sellers?(hash)\n top_seller = get_top_sellers(hash)\n top_seller.each do |cap|\n if has_id?(cap)\n top_sellers << get_id(cap)\n end\n end\n end\n if has_specials?(hash)\n special = get_specials(hash)\n special.each do |cap|\n if has_id?(cap)\n specials << get_id(cap)\n end\n end\n end\n else\n puts \"ERROR: PLEASE RELOAD WEBSITE\"\n end\n @large_capsules = \n (@large_capsules | specials | top_sellers).uniq\n end",
"def get_data\n if @url\n @page = fetch_url(@url)\n @parse_time = parse_dailydev_page\n @page = nil\n self.total_time\n end\n end",
"def request (url_requested, api_key)\n url_builded = url_requested + \"&api_key=\" + api_key\n\n url = URI(url_builded)\n\n https = Net::HTTP.new(url.host, url.port)\n https.use_ssl = true\n\n request = Net::HTTP::Get.new(url)\n\n response = https.request(request)\n\n JSON.parse(response.read_body)\nend",
"def webster_hall_parse!\n response = Net::HTTP.get('api.ticketweb.com', '/snl/EventAPI.action?key=kFiQQQiHkGJpeA5xCfHd&version=1&orgId=136373,141422,137573&method=json')\n json = JSON.parse(response)\n\n json['events'].each do |event|\n Event.where(\n name: event['eventname'],\n description: event['description'],\n url: event['eventurl'],\n date: event['dates']['startdate'].to_time(\"Eastern Time (US & Canada)\").utc,\n venue_id: id\n ).first_or_create!\n end\n end",
"def get_channel(channel_name, channel_num)\n puts \"Getting channel #{channel_name}, #{channel_num}\"\n url = URI.parse(\"http://xmltv.radiotimes.com/xmltv/channels.dat\")\n res = Net::HTTP.start(url.host, url.port) { |http|\n http.get(\"/xmltv/#{channel_num}.dat\")\n }\n\n res.body.split(\"\\n\").each do |line|\n line = line.chomp.split(\"~\")\n if line[16].eql? \"Film\"\n insert_film(line[0], line[19], channel_name, line[20], line[21], line[3], line[17], line[22])\n end\n end\nend",
"def initialize\n @url_s = 'https://deezerdevs-deezer.p.rapidapi.com/search?q='\n\n end",
"def retrieve(url)\n Hpricot(Net::HTTP.get(URI.parse(url)))\n end",
"def info\n standardize\n # Alphebatize the API hash\n @api_sort = @api_hash.sort\n # Convert to array because SQLite\n @api_arr = @api_sort.flat_map do |_, v|\n v.is_a?(Hash) ? v.map { |_, w| escape(w) } : escape(v)\n end\n end",
"def parse(id, site, name)\n data = {}\n SiteStandards::COMMON_CHECKS.each_key do |k|\n data[k.to_sym] = nil\n end\n data[:display_name] = name\n data[:uri] = site\n uri = URI.parse(site)\n begin\n Socket.getaddrinfo(uri.host, uri.scheme)\n rescue SocketError => se\n data[:errors] = se.message\n return data\n end\n begin\n uri, response, status = $cache.get(site.to_s)\n rescue IOError => ioe\n data[:errors] = ioe.message\n return data\n end\n puts \"#{id} #{uri} #{status}\"\n # Bail and return if getting the site returns an error code\n if response.respond_to? :code and response.code =~ /^[45]/\n data[:errors] = \"cache.get(#{site}) error code #{response.code}\"\n return data\n end\n doc = Nokogiri::HTML(response)\n data[:uri] = uri.to_s\n\n # FIRST: scan each link's a_href to see if we need to capture it\n doc.css('a').each do |a|\n # Normalize the text and href for our capture purposes\n a_href = a['href'].to_s.strip\n a_text = a.text.downcase.strip\n $stderr.puts \"#{a_text} #{a_href}\" if $verbose\n\n # Check the href urls for some patterns\n if a_href =~ SiteStandards::COMMON_CHECKS['foundation'][SiteStandards::CHECK_CAPTURE]\n img = a.at('img')\n if img\n # use the title (hover text) in preference to the source\n data[:foundation] = img['title'] ? squash(img['title']) : uri + img['src'].strip\n else\n data[:foundation] = squash(a.text)\n end\n end\n\n if a_href =~ SiteStandards::COMMON_CHECKS['events'][SiteStandards::CHECK_CAPTURE]\n img = a.at('img')\n if img\n data[:events] = uri + img['src'].strip\n else\n data[:events] = uri + a_href\n end\n end\n\n # Check the a_text strings for other patterns\n # Note this is an unusual case\n if (a_text =~ SiteStandards::COMMON_CHECKS['license'][SiteStandards::CHECK_TEXT]) and\n (a_href =~ SiteStandards::COMMON_CHECKS['license'][SiteStandards::CHECK_CAPTURE])\n begin\n data[:license] = uri + a_href\n rescue StandardError\n data[:license] = a_href\n end\n end\n\n %w(thanks security sponsorship privacy).each do |check|\n if a_text =~ SiteStandards::COMMON_CHECKS[check][SiteStandards::CHECK_CAPTURE]\n begin\n data[check.to_sym] = uri + a_href\n rescue StandardError\n data[check.to_sym] = a_href\n end\n end\n end\n end\n\n # SECOND: scan each text node to match and capture\n doc.traverse do |node|\n next unless node.is_a?(Nokogiri::XML::Text)\n txt = squash(node.text)\n # allow override if phrase looks good\n if (txt =~ SiteStandards::COMMON_CHECKS['trademarks'][SiteStandards::CHECK_CAPTURE] and not data[:trademarks]) or\n txt =~ /are trademarks of [Tt]he Apache Software/\n t, p = getText(txt, node)\n # drop previous text if it looks like Copyright sentence\n data[:trademarks] = t.sub(/^.*?Copyright .+? Foundation[.]?/, '').strip\n data[:tradeparent] = p if p\n end\n if txt =~ SiteStandards::COMMON_CHECKS['copyright'][SiteStandards::CHECK_CAPTURE]\n t, p = getText(txt, node)\n # drop text around the Copyright (or the symbol)\n data[:copyright] = t.sub(/^.*?((Copyright|©) .+? Foundation[.]?).*/, '\\1').strip\n data[:copyparent] = p if p\n end\n # Note we also check for incubator disclaimer (immaterial of tlp|podling)\n if txt =~ SiteStandards::PODLING_CHECKS['disclaimer'][SiteStandards::CHECK_CAPTURE]\n t, _p = getText(txt, node, / is an effort undergoing/)\n data[:disclaimer] = t\n end\n end\n # THIRD: see if an image has been uploaded\n data[:image] = ASF::SiteImage.find(id)\n\n # Check for resource loading from non-ASF domains\n cmd = ['node', '/srv/whimsy/tools/scan-page.js', site]\n out, err, status = exec_with_timeout(cmd, 30)\n if status\n ext_urls = out.split(\"\\n\").reject {|x| ASFDOMAIN.asfhost? x}.tally\n resources = ext_urls.values.sum\n data[:resources] = \"Found #{resources} external resources: #{ext_urls}\"\n else\n data[:resources] = err\n end\n\n # TODO: does not find js references such as:\n # ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';\n return data\nend",
"def call_api\n @client.build_url\n @client.get\n assign_data\n end",
"def apiAuth\n\t\tsignature = \"version=#{$CONFIG[:api_version]}&path=#{$CONFIG[:api_path]}&app_key=#{$CONFIG[:app_key]}&app_secret=#{$CONFIG[:app_secret]}×tamp=#{$CONFIG[:timestamp]}\"\n\t\tsignature_hash = Digest::SHA2.new << signature\n\t\turl = \"#{$CONFIG[:api_url]}#{$CONFIG[:api_version]}#{$CONFIG[:api_path]}?app_key=#{$CONFIG[:app_key]}×tamp=#{$CONFIG[:timestamp]}&signature=#{signature_hash}\"\n\t\n\t\turl\n\tend",
"def set_search_api\n @url = 'https://api.coinmarketcap.com/v1/ticker/'\n @uri = URI(@url)\n @response = Net::HTTP.get(@uri)\n # converts response to a Ruby hash \n @search_coin = JSON.parse(@response)\n @symbol = params[:sym]\n\n if @symbol\n @symbol = @symbol.upcase\n end \n end",
"def api_url time=nil\n today = Time.now\n [ \n \"#{config.protocol}:/\", \n API_URL, \n time && (time.year != today.year || time.yday != today.yday) ? \"historical/#{time.strftime(\"%Y-%m-%d\")}.json\" : \"latest.json\"\n ].join('/') + \"?app_id=#{config.app_id}\"\n end",
"def info(url)\n rest = RestClient::Request.execute(\n method: :get,\n url: url,\n user: ENV['USER'],\n password: ENV['KEY'],\n headers: {\"Content-Type\" => \"application/json\"}\n )\n JSON.parse(rest, :symbolize_names => true)\n rescue RestClient::Exception\n \"Sorry something went wrong with the API\"\n end",
"def history_data\n @id = params[:id]\n @item_history = []\n @item_name = @item_names[@id.to_i]\n json_str = Net::HTTP.get(URI.parse(\"http://#{THINGSPEAK_SERVER}/channels/#{OT_CHANNEL}/feed.json?results=200\")) \n parsed_hash = ActiveSupport::JSON.decode(json_str)\n parsed_hash[\"feeds\"].each do |e|\n if e[\"field1\"] == @id\n item = {}\n t = Time.strptime(e[\"created_at\"], \"%FT%T%z\")\n item[\"time\"] = t.strftime(\"%b %d, %Y %H:%M:%S\")\n item[\"curr_loc\"] = e[\"field4\"]\n @item_history.push(item)\n end\n end\n\n render :template => \"static/history_data\", :formats => [:json], :handlers => \"haml\", :layout => false\n end",
"def generate_url(api_key, page_number, username)\n %W[\n ws.audioscrobbler.com\n /2.0/?method=user.getrecenttracks&user=#{username}&api_key=#{api_key}&format=json&page=#{page_number}\n ]\n end",
"def update_from_api\n url = \"https://clinicaltrials.gov/api/query/full_studies?expr=AREA%5BNCTId%5D#{nct_id}&min_rnk=1&max_rnk=&fmt=json\"\n attempts = 0\n data = nil\n response = nil\n begin\n attempts += 1\n s = Time.now\n response = Faraday.get(url).body\n data = JSON.parse(response)\n puts \" fetch #{Time.now - s}\" if ENV['VERBOSE']\n rescue Faraday::ConnectionFailed\n return false if attempts > 5\n retry\n rescue JSON::ParserError\n return false if attempts > 5\n retry\n end\n data = data.dig('FullStudiesResponse', 'FullStudies').first\n begin\n if data\n self.content = data\n return false unless changed?\n return update content: data, download_date: Time.now\n end\n rescue => e\n Airbrake.notify(e)\n end\n end",
"def get_data_from_api\n # address1 = address.parameterize('+')\n # state1 = state.parameterize('+')\n # city1 = city.parameterize('+')\n# \trequest_string = \"https://www.googleapis.com/civicinfo/v2/representatives/?address=#{address}%2C+#{city}%2C+#{state}%2C+#{zipcode}&levels=country&roles=legislatorLowerBody&key=AIzaSyDFYpjPCBUVQLyfS39-lBKRWCkD7-u4zug\" \n# \tcreates a url to access API data\n request_string = \"https://www.googleapis.com/civicinfo/v2/representatives/?address=9+Melrose+Dr.%2C+Livingston%2C+NJ%2C+07039&levels=country&roles=legislatorLowerBody&key=AIzaSyDFYpjPCBUVQLyfS39-lBKRWCkD7-u4zug\"\n\tsample_response = HTTParty.get(request_string) #go grab the data in the portal\n\tsample_parsedResponse = JSON.parse(sample_response.body, {:symbolize_names => true}) #makes data easy to read\n puts sample_parsedResponse[:officials][0][:name] \n puts sample_parsedResponse[:officials][0][:party] \n puts sample_parsedResponse[:officials][0][:phones] \n #returns first element in items array\n end",
"def get_basic_info\n yahoo_client = YahooFinance::Client.new\n @data = yahoo_client.quotes([@stock.ticker_symbol], [:open, :high, :low, :close, :last_trade_price, :change, :change_in_percent, :dividend_yield])\n respond_to do |format|\n format.json { render json: @data, status: :ok }\n format.html { @data }\n end\n url = \"https://www.quandl.com/api/v3/datasets/SF0/\" + @stock.ticker_symbol + \"_BVPS_MRY.json?api_key=rWvJtw9jPu2px-yskKZ4\"\n resp = HTTP.get(url)\n @history = JSON.parse(resp, symbolize_keys: true)\n\n end_date = Date.today\n start_date = Date.today.prev_month \n\n fred_url = \"https://api.stlouisfed.org/fred/series/observations?series_id=DGS5&api_key=d9f592689a18d841cab93825d4e060c7&file_type=json&observation_start=\" + start_date.strftime('%Y-%m-%e') + \"&observation_end=\" + end_date.strftime('%Y-%m-%e') + \"\"\n fred_resp = HTTP.get(fred_url)\n five_year_interest_rates = JSON.parse(fred_resp, symbolize_keys: true)\n interest_rate = five_year_interest_rates[\"observations\"].last[\"value\"].to_f\n\n if @history[\"dataset\"].nil?\n @derivative_fypm = \"N/A\"\n @linear_fypm = \"N/A\"\n @rate_fypm = \"N/A\"\n else\n book_values = @history[\"dataset\"][\"data\"]\n # derivative FYPM values\n v1 = book_values[3][1].to_f - book_values[4][1].to_f\n v2 = book_values[2][1].to_f - book_values[3][1].to_f\n v3 = book_values[1][1].to_f - book_values[2][1].to_f\n v4 = book_values[0][1].to_f - book_values[1][1].to_f\n @div = @data[0].dividend_yield.to_f\n price = @data[0].last_trade_price.to_f\n five_year_div_yield = ((((@div * 0.01) + 1.0) ** 5.0) - 1.0) * 100.0\n five_year_interest_rate_yield = 100 * ((((interest_rate/100) + 1) ** 5) - 1)\n # variables for derivative book value linear fit\n sigma_x = 6.0\n sigma_x_squared = 14.0\n sigma_y = v1 + v2 + v3 + v4\n sigma_xy = v2 + v3*2.0 + v4*3.0\n n = 4.0\n # derivative book value linear fit\n a = ((sigma_y*sigma_x_squared) - (sigma_x*sigma_xy))/((n*sigma_x_squared)-(sigma_x**2))\n b = ((n*sigma_xy) - (sigma_x*sigma_y))/((n*sigma_x_squared)-(sigma_x**2))\n five_year_book_value_added = (6.5*b + a)*5.0\n five_year_book_value_yield = (five_year_book_value_added/price)*100\n # derivative FYPM final calc\n @derivative_fypm = ((five_year_book_value_yield + five_year_div_yield)/five_year_interest_rate_yield)\n\n # non- derivative FYPM values\n v1 = book_values[4][1].to_f\n v2 = book_values[3][1].to_f\n v3 = book_values[2][1].to_f\n v4 = book_values[1][1].to_f\n v5 = book_values[0][1].to_f\n # variables for non-derivative book value linear fit\n sigma_x = 10.0\n sigma_x_squared = 30.0\n sigma_y = v1 + v2 + v3 + v4 + v5\n sigma_xy = v2 + v3*2.0 + v4*3.0 + v5*4.0\n n = 5.0\n # non-derivative book value linear fit\n a = ((sigma_y*sigma_x_squared) - (sigma_x*sigma_xy))/((n*sigma_x_squared)-(sigma_x**2))\n b = ((n*sigma_xy) - (sigma_x*sigma_y))/((n*sigma_x_squared)-(sigma_x**2))\n five_year_book_value_added_linear = (10.0*b + a) - v5\n five_year_book_value_added_rate = 5.0*b\n five_year_book_value_yield_linear = (five_year_book_value_added_linear/price)*100\n five_year_book_value_yield_rate = (five_year_book_value_added_rate/price)*100\n # non-derivative FYPM final calc\n @linear_fypm = ((five_year_book_value_yield_linear + five_year_div_yield)/five_year_interest_rate_yield)\n @rate_fypm = ((five_year_book_value_yield_rate + five_year_div_yield)/five_year_interest_rate_yield)\n\n # get change from previous day\n last_fypm = StockDatum.where(ticker_symbol: @stock.ticker_symbol).order(\"created_at DESC\").first\n if last_fypm.nil?\n @linear_change = nil\n @rate_change = nil\n @derivative_change = nil\n else\n @linear_change = ((@linear_fypm / last_fypm.linear_fypm ) - 1.0) * 100.0\n @rate_change = ((@rate_fypm / last_fypm.rate_fypm ) - 1) * 100\n @derivative_change = ((@derivative_fypm / last_fypm.derivative_fypm ) - 1) * 100\n end\n\n end\n end",
"def refreshRealmAPI\n\t\tbegin\n\t\t\turi = \"https://\" + @regionURL + \"/wow/auction/data/\" + @realm + \"?locale=#{@locale}\" + \"&apikey=#{@apikey}\"\n\t\t\tputs uri\n\t\t\tjsontemp = Yajl::Parser.parse(open(uri)) # Parse JSON to ruby object.\n\n\t\t\t@dataURL = jsontemp[\"files\"][0][\"url\"]\n\t\t\t@lastModified = Time.at(jsontemp[\"files\"][0][\"lastModified\"]/1000)\n\n\t\t\tputs \"Successfully retrived data URL for #{uri}\\nURL: #{@dataURL}\\nLatest data is from #{@lastModified}\"\n\t\t\t@log.info \"Successfully retrived data URL for #{uri}\\nURL: #{@dataURL}\\nLatest data is from #{@lastModified}\"\n\n\t\t\treturn true\n\n\t\trescue => e\n\t\t\t\n\t\t\tputs \"Failed to get the Auction data URL.\"\n\t\t\t@log.error \"Failed to get the Auction data URL.\"\n\t\t\tputs \"Error message from the server:\\n\\n #{jsontemp}\\n\\n\"\n\t\t\t@log.error \"Error message from the server:\\n\\n #{jsontemp}\\n\\n\"\n\t\t\tputs e\n\t\t\t@log.error e\n\n\t\t\treturn false\n\n\t\tend\n\t\t\n\t\t\n\tend",
"def getinfo\n @api.request 'getinfo'\n end",
"def call_api\n\t\tputs \"Getting info on elected officials for zipcode: #{zip_code}\"\n\t\t@api_data_on_electeds = JSON.load RestClient.get \"https://congress.api.sunlightfoundation.com/legislators/locate?zip=#{zip_code}&apikey=952d630dfb75498ab63de7a362a85335\"\n\tend",
"def parse_api(link)\n movie_data ={}\n movie_url_link = RestClient.get(link)\n movie_data = JSON.parse(movie_url_link)\n # binding.pry\nend",
"def get_monster_info\n monster_string = RestClient.get('http://www.dnd5eapi.co/api/monsters/')\n monster_hash = JSON.parse(monster_string)\n monster_info = monster_hash[\"results\"]\n monster_info\nend",
"def sellsy_request(sellsy_request, sellsy_params)\n # Set the API URL\n url = URI(\"https://apifeed.sellsy.com/0/\")\n\n # Define the timestamp & a random nonce\n timestamp = Time.now.to_i\n nonce = SecureRandom.hex(6)\n\n # Setup the URL host and port, and force to use SSL (Sellsy don't authorize request without TLS)\n http = Net::HTTP.new(url.host, url.port)\n http.use_ssl = true\n\n # Store the POST request in a new var\n request = Net::HTTP::Post.new(url)\n # HTTP request headers\n request[\"cache-control\"] = 'no-cache'\n request[\"accept\"] = '*/*'\n request[\"content-type\"] = 'application/x-www-form-urlencoded'\n # HTTP request body\n request.set_form_data(\n \"do_in\" => {\n \"method\" => sellsy_request,\n \"params\" => sellsy_params\n }.to_json,\n \"io_mode\" => \"json\",\n \"request\" => 1,\n \"oauth_consumer_key\" => \"YOUR CONSUMER KEY\",\n \"oauth_token\" => \"YOUR TOKEN KEY\",\n \"oauth_signature_method\" => \"PLAINTEXT\",\n \"oauth_timestamp\" => timestamp,\n \"oauth_nonce\" => nonce,\n \"oauth_version\" => 1.0,\n \"oauth_signature\" => \"YOUR CONSUMER SECRET & YOUR TOKEN SECRET\"\n ).to_json\n\n # Launch the HTTP request\n response = http.request(request)\n # Return the response\n return response.read_body\nend",
"def fetch_json\n # Get raw JSON of GitHub API\n api_page = open(@api_url, http_basic_authentication: @login)\n # Parse the JSON into a hash\n @api_hash = JSON.parse(api_page.read)\n end",
"def APICall params = {}\n \n path = params[:path]\n method = params[:method] || 'GET'\n payload = params[:payload] || nil\n \n params.delete(:method)\n params.delete(:path)\n params.delete(:payload)\n \n a = Time.now.to_f\n \n http = Net::HTTP.new(@infra[:domain]+'.zendesk.com',443)\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n http.use_ssl = true\n \n uri = %{#{@infra[:path]}#{path}}\n uri << '?'+params.map{ |key,val| \"#{key}=#{val}\" }.join('&') if params && params.count > 0\n uri = URI.escape uri\n \n reqs = {\n 'GET' => Net::HTTP::Get.new(uri),\n 'POST' => Net::HTTP::Post.new(uri),\n 'PUT' => Net::HTTP::Put.new(uri),\n 'DELETE' => Net::HTTP::Delete.new(uri)\n }\n req = reqs[method]\n \n content_type = 'application/json'\n content_type = 'application/binary' if path.include? 'uploads'\n req.content_type = content_type\n \n req.basic_auth @username,@infra[:authentication]\n \n req.body = payload if method == 'POST' || method == 'PUT'\n \n response = http.request req\n \n code = response.code.to_f.round\n body = response.body\n \n b = Time.now.to_f\n c = ((b-a)*100).round.to_f/100\n \n final = {code: code.to_i,body: nil}\n final = final.merge(body: JSON.parse(body)) if method != 'DELETE' && code != 500\n final = final.merge(time: c)\n \n @api += 1\n \n final\n \n end",
"def getLineByID(id)\n\n # Get cookie\n cookie = open(\"https://store.line.me/stickershop/list?page=1&listType=top\", :ssl_verify_mode => OpenSSL::SSL::VERIFY_NONE).meta['set-cookie']\n newck = \"store_locale=zh_TW; store_lang=zh-hant; \" + cookie\n \n imglink = \"https://store.line.me/stickershop/detail?packageId=#{id}\" # Detail webpage link\n dpage = Nokogiri::HTML(open(imglink, \"Accept\" => \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\",\n \"Accept-Language\" => \"zh-TW,zh;q=0.8,en;q=0.6,en-US;q=0.4\",\n \"Cookie\" => newck,\n \"Connection\" => \"keep-alive\",\n \"User-Agent\" => \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36\"\n ))\n dpage.encoding = 'utf-8'\n\n # Next if Official Site do not have this sticker\n return if !dpage.css('p.mdMN07Desc')[0]\n\n did = imglink.split('=')[1]\n dtext = dpage.css('p.mdMN07Desc')[0].text\n dprice = dpage.css('p.mdMN05Price')[0].text.gsub!(/¥/,\"\").to_i*0.3\n imgtext = dpage.css('h2.mdMN05Ttl')[0].text\n imgsrc = dpage.css('div.mdMN05Img img')[0]['src']\n detailImg = dpage.css('div.mdMN07Img img')[0]['src']\n\n # Check Img Src Link \n begin\n open(imgsrc) {}\n rescue\n return \n end\n\n # property :id, Integer\n # property :name, String\n # property :tag, [String]\n # property :detail, String\n # property :description, String\n # property :thumbnail, String\n # property :detailImg, String\n # puts imglink\n # puts \"#{did} #{imgtext} #{imglink} #{dtext} #{imgsrc} \"\n\n doc = { \"id\" => did.to_i,\n \"sticker_id\" => did.to_i,\n \"name\" => imgtext,\n \"tag\" => { },\n \"detail\" => imglink,\n \"description\" => dtext,\n \"price\" => $priceTable[dprice.to_i],\n \"thumbnail\" => imgsrc,\n \"weigth\" => 1,\n \"detailImg\" => detailImg \n }\n\n $coll.insert(doc)\n puts \"=> Insert #{did} : #{imglink} ... \"\nend",
"def collect_site_details\n site = fetch('site','1')\n @site_name = site['name']\n @time_zone = site['time_zone']\n @language_code = site['language_code']\n end",
"def info(sid)\n xml = get('/feeds/showinfo.php', :query => {:sid => sid})\n xml[\"Showinfo\"]\n end",
"def lookup_remote(md5_hash)\n unhash_data = Scrubyt::Extractor.define do\n fetch \"http://gdataonline.com/qkhash.php?mode=txt&hash=#{md5_hash}\"\n unhash \"//table/tr[2]/td[2]/b\"\n end\n \n doc = Nokogiri::HTML.parse(unhash_data.to_xml)\n doc.xpath('//root/unhash').text.strip rescue nil\n end",
"def fetch_quote\n uri = URI('http://www.iheartquotes.com/api/v1/random?format=text&max_lines=4&max_characters=320')\n #open(@url).read.to_s\n req = Net::HTTP.get(uri)\n #puts req\n end",
"def serv_json\n \"http://api.dribbble.com/shots/popular?page=1\"\n end",
"def scrobble( params )\n LastFM.requires_authentication\n # Tracks are passed to the service using array notation for each of the above params\n array_params = {}\n params.each do |hkey, hval|\n hval = hval.to_i if hval.is_a?(Time)\n Array(hval).each_with_index do |aval, index|\n array_params[\"#{hkey}[#{index}]\"] = aval\n end\n end\n LastFM.post( \"track.scrobble\", array_params )\n end",
"def getLatestPrice(api_uri,curr)\n\n api_server = 'https://api.coinmarketcap.com'\n url = \"#{api_server}#{api_uri}/?convert=#{curr}\"\n api_json = getJsonObject(url)\n json_hash = Hash[*api_json.flatten]\n puts(json_hash['price_inr'])\n return json_hash['price_inr']\nend",
"def request_url\n base_url = \"http://#{api_host}#{PATH}?\"\n base_url << \"appid=#{app_id}\"\n base_url << \"&callname=#{call_name}\"\n base_url << \"&siteid=#{site_id}\"\n base_url << \"&version=#{API_VERSION}\"\n base_url\n end",
"def fetch!\n scrub_url\n\n parameters = Jewel.get_service(url)\n self.parameters = parameters\n\n if parameters[:service] == :twitter_status\n twitter = Twitter.status(parameters[:status_id])\n self.name = \"Tweet from #{twitter.user.name}\"\n self.name = twitter.text\n self.content = twitter.text\n tweet_media = twitter.media\n if tweet_media.length > 0\n self.avatar = URI.parse(tweet_media.first.media_url)\n end\n self.kind = Jewel::TYPES[:other]\n elsif parameters[:service] == :other\n page = MetaInspector.new(url, allow_redirections: :safe)\n self.name = page.title\n self.content = page.description\n if page.image\n self.avatar = URI.parse(page.image)\n elsif !page.images.empty?\n self.avatar = URI.parse(page.images.first)\n end\n self.kind = Jewel::TYPES[:other]\n self.fetch_embed!\n elsif parameters[:service] == :youtube\n page = MetaInspector.new(url, allow_redirections: :safe)\n self.name = page.title\n self.content = page.description\n self.avatar = URI.parse(page.image) if page.image\n self.kind = Jewel::TYPES[:video]\n self.fetch_embed!\n elsif parameters[:service] == :idealme\n if parameters[:kind] == :courses\n self.kind = Jewel::TYPES[:course]\n course = Course.where(slug: parameters[:slug]).first\n self.course_id = course.id\n elsif parameters[:kind] == :goals\n self.kind = Jewel::TYPES[:goal]\n goal = Goal.where(id: parameters[:slug]).first\n self.goal_id = goal.id\n end\n end\n\n self.save!\n self\n end",
"def get_url(stadium)\n 'http://www.hittrackeronline.com/index.php?h=&p=&b=' + stadium +\n '&perpage=10000'\nend",
"def info id\n get(\"ssl/v1/#{id}\")\n end",
"def fetch_latest_user_info\n\t\t@user_info = @client.execute(api_method: @info.userinfo.get).data\n\tend",
"def api_fetch(url)\n JSON.parse(URI.open(url).read)\nend",
"def api_fetch(url)\n JSON.parse(RestClient.get url)\nend",
"def get_report(api_key, client_api_id, interval, query = \"\")\n uri = URI(API_ENDPOINT) + URI.escape(\"?api_key=#{api_key}&client_api_id=#{client_api_id}&interval=#{interval}&query=#{query}\")\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = true\n request = Net::HTTP::Get.new(uri.request_uri)\n response = http.request(request)\n raise \"Server returned error #{response.code} processing your API request\" if response.code != \"200\"\n JSON.parse(response.body)\nend",
"def make_url\n # This works for most of the twitter calls\n \"http://ws.audioscrobbler.com/2.0/?method=#{resource_path}&artist=#{identifier}&limit=100&page=#{page}&api_key=#{api_key}&format=json\"\n end",
"def fetch_data(api_url)\n JSON.parse(RestClient.get(api_url))\nend",
"def bookdevice(token, duration = 5 , id)\n\nuri = URI.parse(\"https://device.pcloudy.com/api/book_device\")\n@toSend = {\n \"token\" => token ,\"duration\"=>duration, \"id\"=>id\n}.to_json\n\nhttps = Net::HTTP.new(uri.host,uri.port)\nhttps.use_ssl = true\n\nreq = Net::HTTP::Post.new(uri.path, initheader = {'Content-Type' =>'application/json'})\n\nreq.body = \"#{@toSend}\"\nres = https.request(req)\nputs \"Response #{res.code} #{res.message}: #{res.body}\"\nbookingdetails = JSON.parse(res.body)\n\nrid = bookingdetails[\"result\"][\"rid\"]\nreturn rid\nend"
] |
[
"0.63253504",
"0.62649316",
"0.6195579",
"0.61649805",
"0.60211533",
"0.60126346",
"0.5942441",
"0.58907443",
"0.58907175",
"0.58199507",
"0.5797443",
"0.57724017",
"0.5756063",
"0.574664",
"0.57190275",
"0.5710476",
"0.5671327",
"0.5658173",
"0.5651654",
"0.5606332",
"0.56001854",
"0.5589625",
"0.5573536",
"0.5572635",
"0.5566209",
"0.55500567",
"0.5545068",
"0.5539762",
"0.5512356",
"0.5503212",
"0.5496129",
"0.54888445",
"0.5482087",
"0.5474563",
"0.54695755",
"0.54676664",
"0.5452434",
"0.54357207",
"0.54263747",
"0.54195935",
"0.5405552",
"0.5394975",
"0.5382732",
"0.53815067",
"0.5366066",
"0.5354889",
"0.5351405",
"0.5342085",
"0.5341016",
"0.53365225",
"0.5328144",
"0.5321986",
"0.53129023",
"0.5309578",
"0.530937",
"0.5298961",
"0.52987736",
"0.5298556",
"0.52967715",
"0.5288955",
"0.5288451",
"0.52870834",
"0.52861685",
"0.5285264",
"0.528272",
"0.5270451",
"0.5268002",
"0.5265713",
"0.52569425",
"0.5253666",
"0.5249748",
"0.524793",
"0.5244834",
"0.52403677",
"0.5237685",
"0.52347517",
"0.5233878",
"0.5223515",
"0.5222776",
"0.5220064",
"0.5210681",
"0.5208879",
"0.5205819",
"0.52027607",
"0.5202436",
"0.5198292",
"0.5197951",
"0.5193006",
"0.5192892",
"0.5190003",
"0.51857305",
"0.5183635",
"0.5181946",
"0.51759225",
"0.5169977",
"0.5169884",
"0.51671374",
"0.5165623",
"0.5163736",
"0.51592565",
"0.5155657"
] |
0.0
|
-1
|
human readable description of modeling approach
|
def modeler_description
return 'Thermal zones will be named after the spac with a prefix added'
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def modeler_description\n return 'Gather orientation and story specific construction, fenestration (including overhang) specific information'\n end",
"def modeler_description\n return \"Example use case is adding special loads like an elevator to a model as part of an analysis workflow\"\n end",
"def modeler_description\n return 'Currently this is just setup for design level calculation method, but it could be extended as needed..'\n end",
"def modeler_description\n return 'shift or/and adjust heaing and cooling setpoint'\n end",
"def modeler_description\n return 'This model replaces the existing HVAC system with a VRF + DOAS system.'\n end",
"def modeler_description\n return \"This uses the OpenStudio::Model::Space::fromFloorPrint method, and is very much like the Create Spaaces From Diagram tool in the OpenStudio SketchUp plugin, but lets you draw teh diagram in the tool of your choice, and then imports it into the OpenStudio application via a measure.\"\n end",
"def modeler_description\n return 'This can be used in apply measure now, or can be used in a parametric workflow to load in any custom user profiles or floor/ceiling values.'\n end",
"def modeler_description\r\n return \"objective function\"\r\n end",
"def modeler_description\r\n return \"objective function\"\r\n end",
"def modeler_description\n return \"Any generators and electric load center distribution objects are removed. An electric load center distribution object is added with a track schedule equal to the hourly output from SAM. A micro turbine generator object is add to the electric load center distribution object. The fuel used to make the electricity is zeroed out.\"\n end",
"def modeler_description\r\n return \"For each model, find every DX cooling and heating coil and increase the COP to 6. Since very little information about this technology is available, do not change performance curves or upper/lower operating temperature limits.\"\r\n end",
"def modeler_description\n return 'Modify the cooling setpoint of the HVAC system during a DR event'\n end",
"def modeler_description\n return 'This a test measure in relation with https://github.com/NREL/OpenStudio/issues/4156'\n end",
"def modeler_description\n return \"When have existing OSM wanted to be able to grab geometry from model vs. trying to enter on website. This is useful when there is no built structures yet to use as reference on the website.\"\n end",
"def modeler_description\n return \"Grey water tank overflow will be dirrected to drainage. \"\n end",
"def modeler_description\n return \"NOTE: This will load and respond slowly in the OS app, especially if you select * on a variable with many possible keys or you select timestep data. Suggest you open it in a web browser like Chrome instead.\"\n end",
"def modeler_description\n return 'HVAC system creation logic uses [openstudio-standards](https://github.com/NREL/openstudio-standards) and efficiency values are defined in the openstudio-standards Standards spreadsheet under the *NREL ZNE Ready 2017* template.'\n end",
"def description()\n\t\tself.namespaced_class(:ModelDescriptor).goal(self)\n\tend",
"def modeler_description\n 'NOTE: This will load and respond slowly in the OS app, especially if you select * on a variable with many possible keys or you select timestep data. Suggest you open it in a web browser like Chrome instead.'\n end",
"def modeler_description\n return 'Not sure how I will handle arguments. Maybe lump together all spaces on same sotry that have the same multilier value. This will have variable number of arguments basd on the model pased in. Alternative is to either only allo w one group to be chosen at at time, or allow a comlex string that describes everything. Also need to see how to define shirting. There is an offset but it may be above and below and may not be equal. In Some cases a mid floor is halfway betwen floors which makes just copying the base surfaces as shading multiple times probemeatic, since there is overlap. It coudl be nice to stretch one surface over many stories. If I check for vertial adn orthogonal surface that may work fine. '\n end",
"def modeler_description\n return \"It does not even send anything related to the model. It just sends a simple pagkage at the end of every run, just to test if things really work.\"\n end",
"def modeler_description\n return ['Adds', 'the', 'properties', 'for', 'the', 'MoisturePenetrationDepthConductionTransferFunction', 'or', 'effective', 'moisture', 'penetration', 'depth', '(EMPD)', 'Heat', 'Balance', 'Model', 'with', 'inputs', 'for', 'penetration', 'depths.', \"\\n\\n\", 'Leaving', 'Change', 'heat', 'balance', 'algorithm?', 'blank', 'will', 'use', 'the', 'current', 'OpenStudio', 'heat', 'balance', 'algorithm', 'setting.', \"\\n\\n\", 'At', 'least', '1', 'interior', 'material', 'needs', 'to', 'have', 'moisture', 'penetration', 'depth', 'properties', 'set', 'to', 'use', 'the', 'EMPD', 'heat', 'balance', 'algorithm.'].join(' ')\n end",
"def modeler_description\n return \"Change water heater efficiency and fuel type.\"\n end",
"def modeler_description\n return \"Assume that the starting point technology is primarily 90.1-2013 T8 lighting, with an efficacy of 90 lm/W. According to Table 5.2, LED Efficacy Improvement, in (1), 2015 LED luminaire efficacy is 145 lm/W. Calculate the total lighting power of the model and divide by this initial efficacy to determine the total number of lumens needed. Assuming that this same number of lumens should be provided by LED lighting, divide by the LED efficacy to determine the total wattage of LEDs that would be necessary to achieve the same lighting. Reduce the overall building lighting power by the resulting multiplier. IE new LPD = old LPD * (1 - 90 lm/W /145 lm/W). This is a very crude estimate of the impact of current LED technology. In order to perform a more nuanced analysis, lighting in the prototype buildings should be broken down by use type (general space lighting, task lighting, etc.) and by currently assumed technology (T12, T8, metal halide, etc.). If this breakdown were available, each type of lighting could be modified according to its own efficacy characteristics. Additionally, this measure does not account for the impact of LEDs on outdoor lighting.\"\n end",
"def modeler_description\n return 'For each model, find every DX cooling and heating coil and increase the COP to 6. Since very little information about this technology is available, do not change performance curves or upper/lower operating temperature limits.'\n end",
"def modeler_description\n return \"This measure will replicate the functionality described in the EnergyPlus Energy Management System Application Guide, Example 2., based on user input.\"\n end",
"def modeler_description\n return 'This measure assigns load and flow information to a selected plant loop load profile.'\n end",
"def modeler_description\n return \"This is intended to run on an empty model. It will create the proper model associate it with the proper weather file, and add in necessary output requests. Internally to the measure the test case argument will be mapped to the proper inputs needed to assemble the model. The measure will make some objects on the fly, other objects will be pulled from existing data resources. This measure creates cases described all of section 5.3.\"\n end",
"def modeler_description\n return \"Each DX cooling coil in the model is replaced by a membrane heat pump. To represent the membrane heat pump, the DX cooling coil COP is increased to 7.62 (26 EER). Additionally, add a water use equipment object to account for the 3 gallons of water used per ton*hr of sensible cooling process.\"\n end",
"def modeler_description\n 'For the most part consumption data comes from the tabular EnergyPlus results, however there are a few requests added for time series results. Space type and loop details come from the OpenStudio model. The code for this is modular, making it easy to use as a template for your own custom reports. The structure of the report uses bootstrap, and the graphs use dimple js.'\n end",
"def modeler_description\n return 'Adds typical refrigeration equipment to a building'\n end",
"def modeler_description\r\n return \"\"\r\n end",
"def modeler_description\n return \"E+ RESNET\"\n end",
"def modeler_description\n return \"Reads the model and sql file to pull out the necessary information and run the model checks. The check results show up as warning messages in the measure's output on the PAT run tab.\"\n end",
"def modeler_description\n return \"\"\n end",
"def modeler_description\n return \"\"\n end",
"def modeler_description\n return \"\"\n end",
"def modeler_description\n return \"\"\n end",
"def modeler_description\n return \"\"\n end",
"def modeler_description\n return \"\"\n end",
"def modeler_description\n return \"\"\n end",
"def modeler_description\n return \"A measure that will take Annual Building Utilty Performance tables, Demand End use Components summary table, Source Energy End Use Components Summary and produce an output Json\"\n end",
"def modeler_description\n return \"Reads the model and sql file to pull out the necessary information and run the model checks. The check results show up as Warning messages in the measure's output on the PAT run tab.\"\n end",
"def modeler_description\n return 'The goal of this measure is to create a single space type that represents the loads and schedules of a collection of space types in a model. When possible the measure will create mulitple load instances of a specific type in the resulting blended space type. This allows the original schedules to be used, and can allow for down stream EE measures on specific internal loads. Design Ventilation Outdoor Air objects will have to be merged into a single object. Will try to maintain the load design type (power, per area, per person) when possible. Need to account for zone multipliers when createding blended internal loads. Also address what happens to daylighting control objets. Original space types will be left in the model, some may still be assigned to spaces not included in the building area.'\n end",
"def modeler_description\n 'It will be used for calibration maximum flow rate, efficiency, pressure rise and motor efficiency. User can choose between a SINGLE Fan or ALL the Fans.'\n end",
"def modeler_description\n return ''\n end",
"def modeler_description\n return ''\n end",
"def modeler_description\n return ''\n end",
"def modeler_description\n return ''\n end",
"def modeler_description\n return ''\n end",
"def modeler_description\n return ''\n end",
"def modeler_description\n return ''\n end",
"def modeler_description\n return 'This measure has optional arguments to apply recommendations from different sections of the Zero Energy Multifamily Design Guide.'\n end",
"def modeler_description\n 'It will be used for calibration of WaterHeaterMixed. User can choose between a SINGLE WaterHeaterMixed or ALL the WaterHeaterMixed objects.'\n end",
"def modeler_description\n return \"It will be used for calibration of inlet water temperatures, inlet and outlet air temperatures and design flowrates. User can choose between a SINGLE coil or ALL the Coils.\"\n end",
"def modeler_description\n return 'Find the exterior lighting template for the building, and assume the existing efficiency level in the model (low, medium, high). Find the desing level and multiplier for each category of the exterior lighting definition. Apply the lighting upgrades by reducing the design level associated with each outdoor lighting category by a percent (depends on starting and target efficiency levels).'\n end",
"def modeler_description\n return 'Change UrbanOpt Scenario CSV'\n end",
"def modeler_description\n return 'Calculate thermal capacitance and UA for surfaces, furniture, and spaces.'\n end",
"def modeler_description\n return 'Reports resilience metric(s) of interest.'\n end",
"def modeler_description\n return \"The default space types in the measure inputs are automatically filled by the spaces' standard space types. User can overwrite the default assumptions in the library.csv file in the measure's resources folder.\"\n end",
"def modeler_description\n return 'Find the interior lighting template for the building, and assume the existing efficiency level in the model (low, medium, high, very high). Find the LPD and LPD fractions for each space type. Apply the lighting upgrades by reducing the LPD associated with compact lighting by a percent (depends on starting and target efficiency levels).'\n end",
"def modeler_description\n 'Run a simulation to autosize HVAC equipment and then apply these autosized values back to the model.'\n end",
"def modeler_description\r\n return \"E+ measure to popolate the Kiva settings values\"\r\n end",
"def modeler_description\n return 'This method calculates the annualized coefficient of performance (Btu out / Btu in) of equipment in the model from the annual simulation. This is used in Scout as the equipment efficiency for the technology competition categories.'\n end",
"def modeler_description\n return 'This will only impact schedule rulesets. It will use methods in openstudio-standards to infer hours of operation, develop a parametric formula for all of the ruleset schedules, alter the hours of operation inputs to that formula and then re-apply the schedules. Input is expose to set ramp frequency of the resulting schedules. If inputs are such that no changes are requested, bypass the measure with NA so that it will not be parameterized. An advanced option for this measure would be bool to use hours of operation from OSM schedule ruleset hours of operation instead of inferring from standards. This should allow different parts of the building to have different hours of operation in the seed model.'\n end",
"def modeler_description\n return \"Replace this text with an explanation for the energy modeler specifically. It should explain how the measure is modeled, including any requirements about how the baseline model must be set up, major assumptions, citations of references to applicable modeling resources, etc. The energy modeler should be able to read this description and understand what changes the measure is making to the model and why these changes are being made. Because the Modeler Description is written for an expert audience, using common abbreviations for brevity is good practice.\"\n end",
"def modeler_description\n return \"Any supply components or baseboard convective electrics/waters are removed from any existing air/plant loops or zones. Any existing air/plant loops are also removed. A heating DX coil, cooling DX coil, electric supplemental heating coil, and an on/off supply fan are added to a unitary air loop. The unitary air loop is added to the supply inlet node of the air loop. This air loop is added to a branch for the living zone. A diffuser is added to the branch for the living zone as well as for the finished basement if it exists.\"\n end",
"def modeler_description\r\n return 'modify simulation timestep'\r\n end",
"def modeler_description\n return 'Will add the necessary UtilityCost objects and associated schedule into the model.'\n end",
"def modeler_description\n return 'Replace this text with an explanation for the energy modeler specifically. It should explain how the measure is modeled, including any requirements about how the baseline model must be set up, major assumptions, citations of references to applicable modeling resources, etc. The energy modeler should be able to read this description and understand what changes the measure is making to the model and why these changes are being made. Because the Modeler Description is written for an expert audience, using common abbreviations for brevity is good practice.'\n end",
"def modeler_description\n return 'Replace this text with an explanation for the energy modeler specifically. It should explain how the measure is modeled, including any requirements about how the baseline model must be set up, major assumptions, citations of references to applicable modeling resources, etc. The energy modeler should be able to read this description and understand what changes the measure is making to the model and why these changes are being made. Because the Modeler Description is written for an expert audience, using common abbreviations for brevity is good practice.'\n end",
"def modeler_description\n return 'Passes in all arguments from the options lookup, processes them, and then registers values to the runner to be used by other measures.'\n end",
"def modeler_description\n return 'Daylighting controls will physically add in daylighting controls to spaces in the building, while occupancy control will reduce lighting schedules by 10%.'\n end",
"def modeler_description\n return 'This measure is used to calibrate the BRICR baseline model.'\n end",
"def modeler_description\n return \"This measure will demonstrate how an OpenStudio measure calling EMS functions can be used to model the performance of HVAC equipment that cannot be represented well by using single “standard” performance curve objects (cubic, quadratic, biquadratic, etc.) For example, properly characterizing some HVAC equipment objects requires using different performance curves that cover operation of different parts of the performance regime. This measure will alter (overwrite) the Coil Cooling DX Single Speed Cooling Capacity as a function of temperature performance curve object and attributes used by the simulation if the outdoor air temperature falls below a user defined threshold. This measure allows the user to define the biquadratic curve coefficients associated with the Coil Cooling DX Single Speed Cooling Capacity.\"\n end",
"def modeler_description\n return \"This EEM adds EMS logic to the model that actuates the infiltration, HVAC operation, cooling set point, and heating set point schedules. The measure first identifies the schedule HVAC stopping point by day of week (Saturday, Sunday, and Weekdays). Early HVAC system shutoff is determined entirely by the outdoor air temperature (OAT). If the OAT is less than or equal to 2C or greater than or equal to 18C, then no action is taken. The HVAC system is shut off one hour early when the OAT is between 12C and 18C. The HVAC system shut off time varies linearly with OAT from one hour to zero hours between 12C and 2C, and between 18C and 28C. AvailabilityManager:OptimumStart objects are inserted for each HVAC system in the model and use the AdaptiveASHRAE algorithm to dynamically adjust HVAC startup time each day.\"\n end",
"def modeler_description\n return \"Multipliers for LPD, EPD, and people densities.\"\n end",
"def modeler_description\n return \"This measure takes the user selected standards space type and sets the interior lighting and equipment load definitions subcategory to match the space type name. \"\n end",
"def modeler_description\n return 'Will add the necessary UtilityCost objects into the model.'\n end",
"def modeler_description\n return \"This measure will demonstrate how an OpenStudio measure calling EMS functions can be used to override specified thermostat control logic and set alternate modes of operation. This EMS measure sets a specific (user defined) indoor VRF terminal unit to operate at a specific (user-defined) part load ratio, constrained by operate minimum and maximum outdoor temperature limits of the paired condenser unit. The main input objects that implement this example are the variable refrigerant flow actuators that control the VRF system and specific terminal unit. Note that the terminal unit PLR can be controlled without controlling the mode of the VRF condenser, however, the specific terminal unit will operate in whatever mode the existing operation control scheme chooses. This example program simply “sets” the operating mode and PLR, other more complex control algorithms can be developed by the user as needed\"\n end",
"def modeler_description\n return 'This measure swaps old cases with 2017 code compliant cases and more efficient ones.'\n end",
"def modeler_description\n return \"The example demonstrates the use of a thermostat schedule object as and EMS actuator object. The EMS program alters the scheduled values as a function of hour of day and day of week.\"\n end",
"def modeler_description\n 'This measure changes the Layer 0 properties of Thickness, Density, Thermal Absorptance, Solar Absorptance, Visible Absoptance, Thermal Conductivity, Specific Heat.'\n end",
"def modeler_description\n return \"The measure loops through the AirLoops associated with the model, and determines an occupancy weighted schedule with values of 1 or 0 based on the percent of peak occupancy at the timestep being above or below a set threshold value of 5 percent. The resulting occupancy schedule is applied to the airloop attribute for the availability schedule. The measure then loops through all thermal zones, examining if there are zone equipment objects attached. If there are one or more zone equipment object attached to the zone, a thermal zone occupancy weighted schedule with values of 1 or 0 based on the percent of peak occupancy at the timestep being above or below a set threshold value of 5 percent is generated. The schedule is then assigned to the availability schedule of the associated zone equipment. To prevent energy use by any corresponding plant loops, the pump control type attribute of Constant or Variable speed pump objects in the model are set to intermittent. The measure them adds heating and cooling unmet hours and Simplified ASHRAE Standard 55 warning reporting variable to each thermal zone. \"\n end",
"def modeler_description\r\n return \"This measure loops through the existing airloops, looking for loops that have a constant speed fan. (Note that if an object such as an AirloopHVAC:UnitarySystem is present in the model, that the measure will NOT identify that loop as either constant- or variable-speed, since the fan is located inside the UnitarySystem object.) The user can designate which constant-speed airloop they'd like to apply the measure to, or opt to apply the measure to all airloops. The measure then replaces the supply components on the airloop with an AirloopHVAC:UnitarySystem object. Any DX coils added to the UnitarySystem object are of the type CoilCoolingDXMultiSpeed / CoilHeatingDXMultiSpeed, with the number of stages set to either two or four, depending on user input. If the user opts for a gas furnace, an 80% efficient CoilHeatingGas object is added. Fan properties (pressure rise and total efficiency) are transferred automatically from the existing (but deleted) constant speed fan to the new variable-speed fan. Currently, this measure is only applicable to the Standalone Retail DOE Prototype building model, but it has been structured to facilitate expansion to other models with a minimum of effort.\"\r\n end",
"def modeler_description\n return \"The measure loops through the heating and cooling thermostat schedules associated each thermal zone. The existing heating and cooling schedules are cloned, and the all run period profiles are then modified by adding a +1.5 deg F shift to the all values of the cooling thermostat schedule and a -1.5 degree F shift to all values of the heating thermostat schedule. Design Day profiles are not modified. The modified thermostat schedules are then assigned to the thermal zone. For each Thermal Zone, ASHRAE 55 Thermal Comfort Warnings is also enabled. Zone Thermal Comfort ASHRAE 55 Adaptive Model 90% Acceptability Status output variables is also added to the model.\"\n end",
"def modeler_description\r\n return \"The Measure adds a Schedule Availability Manager to the Selected Plant Loop\"\r\n end",
"def modeler_description\n return 'Converts the OpenStudio model to vA3C JSON format and renders using Three.js, simulation data is applied to surfaces of the model'\n end",
"def modeler_description\n return 'This energy efficiency measure (EEM) replaces all cooling tower objects in a model of the following types: (OS:CoolingTowerPerformanceCoolTools, OS:CoolingTowerPerformanceYorkCalc, OS:CoolingTowerSingleSpeed, OS:CoolingTowerTwoSpeed, or OS:CoolingTowerVariableSpeed) with a new OS:CoolingTower:VariableSpeed object. If an existing cooling tower is already configured for variable speed, the measure will inform the user. When replacing an existing tower object, the following values from the existing tower configuration will be reused: Design Inlet Air Wet Bulb Temp, Design Approach Temperature, Design Range Temperature, Design Water Flow Rate, Design Air Flow Rate, Design Fan Power, Fraction of Tower Capacity in the Free Convection Regime, Basin Heater Capacity, Basin Heater Setpoint Temperature, Basin Heater Operating Schedule, Number of Cells, Cell Control, Cell Minimum and Maximum Water Flow Rate Fractions and Sizing Factor. A performance curve relating fan power to tower airflow rates is used. The curve assumes the fan power ratio is directly proportional to the air flow rate ratio cubed. A Minimum Air Flow Rate Ratio of 20% will be set. To model minimal but realistic water consumption, the Evaporation Loss Mode for new Tower objects will be set to ?Saturated Exit? and Drift Loss Percent will be set to a value of 0.05% of the Design Water Flow. Blowdown water usage will be based on maintaining a Concentration Ratio of 3.0.'\n end",
"def make_and_model; end",
"def modeler_description\n return 'Replaces exterior window constructions with a different construction from the model.'\n end",
"def modeler_description\n return \"This measure will demonstrate how an OpenStudio measure calling EMS functions can be used to investigate dynamic envelope technologies such as emulating thermochromic window performance using EMS actuators and control types. This measure will replace the construction description of a user-selected window based on the outside surface temperature of that window, evaluated at each timestep\"\n end",
"def modeler_description\n return \"This measure will demonstrate how EMS functions can be used to demonstrate how information from a sizing run can be used to select HVAC equipment from nominal product sizes where unit total capacity is directly related to the unit supply airflow (1 ton = 1200 cfm, 1.5 ton = 1600 cfm, etc.) of commercial packaged single-zone HVAC air systems. This measure is designed to work on AirLoops with packaged DX cooling equipment only. EMS functions will be used to extract the design supply airflow generated from system auto-sizing calculations. An interval variable is used to override the Sizing:System - 'Intermediate Air System Main Supply Volume Flow Rate' value variable. This measure approximates the manner that appropriate ‘real world’ equipment selections are made by HVAC design engineers. The table below will be used to map to the Maximum Flow rate of the packaged unit Fan:ConstantVolume object.\"\n end",
"def modeler_description\n return \"This measure adds active or passive chilled beam units to selected conditioned thermal zones. In addition the user can select an existing air loop to serve active beams, or create a new Dual Wheel DOAS. Users can also select an existing chilled water loop to provide chilled water to beams, or create a new high temperature chiller water loop. Users are highly encouraged to review and modify the control strategies that this measure creates, such that it reflects their modeling scenario of interest.\"\n end",
"def modeler_description\n return \"The difference between actual spaces and effective spaces takes into account the zone multipliers. The goal was to get average floor area assuming that each space represents a room vs. a collection of rooms. This was used to help determine average space sizes of different space types from the prototype buildings. In some cases I had to manaually adjust for where a space didn't map to a single room.\"\n end",
"def modeler_description\n return \"Any heating components or baseboard convective electrics/waters are removed from any existing air/plant loops or zones. A boiler along with constant speed pump and water baseboard coils are added to a hot water plant loop.\"\n end",
"def inspect\n \"#<#{self.class.name} @model=#{model.name} @relation_name=#{relation_name} @repository=#{self.class.repository}>\"\n end",
"def inspect\n \"#<#{self.class.name} @model=#{model.inspect} @name=#{name.inspect}>\"\n end",
"def modeler_description\n return \"Reduces runtime fraction of lights by user-specified amount during the user-specified time period (typically daytime). This is an attempt to represent the impact of using the light collected on the roof instead of electric lighting. This modeling approach does not capture the impact of using a PV cell to turn the IR spectrum of the captured light into electricity.\"\n end",
"def modeler_description\n return 'This measure receives the AntiSweat heater Control from the user. Then it looks for refrigerated display cases; it loops through them; it checks the current AntiSweat heater Control of each case and it substitute it with the one chosen by the user.'\n end"
] |
[
"0.7710149",
"0.76145315",
"0.75934714",
"0.74018747",
"0.7299891",
"0.7296635",
"0.727943",
"0.71912926",
"0.71912926",
"0.7191264",
"0.7100944",
"0.70977926",
"0.70629936",
"0.7045383",
"0.7044268",
"0.70413125",
"0.7040473",
"0.7032938",
"0.70267737",
"0.70182866",
"0.69875926",
"0.6980763",
"0.69496983",
"0.69420075",
"0.6936087",
"0.6927004",
"0.6908837",
"0.6901907",
"0.6893215",
"0.6888214",
"0.68663764",
"0.6865241",
"0.68641704",
"0.68588334",
"0.6852012",
"0.6852012",
"0.6852012",
"0.6852012",
"0.6852012",
"0.6852012",
"0.6852012",
"0.6833133",
"0.68219167",
"0.68055475",
"0.6791062",
"0.67879057",
"0.67879057",
"0.67879057",
"0.67879057",
"0.67879057",
"0.67879057",
"0.67879057",
"0.67796487",
"0.6773994",
"0.6751447",
"0.67244256",
"0.6720888",
"0.6716974",
"0.6708703",
"0.67021894",
"0.668961",
"0.66878057",
"0.6672712",
"0.6662903",
"0.6649447",
"0.6643762",
"0.6634445",
"0.66330194",
"0.662195",
"0.6616422",
"0.6616422",
"0.66100585",
"0.659982",
"0.6589568",
"0.6588373",
"0.65865505",
"0.6584234",
"0.65638506",
"0.6560483",
"0.6554784",
"0.65097153",
"0.64903986",
"0.64771026",
"0.6466807",
"0.6462787",
"0.6450267",
"0.6443914",
"0.64391804",
"0.6431919",
"0.6429849",
"0.6426015",
"0.6422519",
"0.6421918",
"0.64181775",
"0.6415888",
"0.6409096",
"0.64067763",
"0.6405944",
"0.64003026",
"0.6370144"
] |
0.64074343
|
96
|
define the arguments that the user will input
|
def arguments(model)
args = OpenStudio::Measure::OSArgumentVector.new
return args
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def arguments; end",
"def arguments; end",
"def arguments; end",
"def arguments\n \"\"\n end",
"def args; end",
"def args; end",
"def args; end",
"def args; end",
"def args; end",
"def args; end",
"def args; end",
"def args; end",
"def args; end",
"def args; end",
"def args; end",
"def args; end",
"def args; end",
"def args; end",
"def args; end",
"def args; end",
"def args; end",
"def args; end",
"def args; end",
"def args; end",
"def get_input \n puts \"to save this game, input 's,filename'\"\n puts \"to load a game, input 'l,filename'\"\n puts \"input a coordinate to access. prefix with r for reveal or f for flag\"\n puts \"example 'f,1,2' places a flag at 1,2\"\n input = gets.chomp\n \n args = input.split(',')\n end",
"def args(*) end",
"def arguments(required, *optional)\n puts \"required: #{required}\"\n puts \"optional: #{optional}\"\nend",
"def args()\n #This is a stub, used for indexing\n end",
"def arguments()\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n #make an argument for the variable name\n variable_name = OpenStudio::Ruleset::OSArgument::makeStringArgument(\"variable_name\",true)\n variable_name.setDisplayName(\"Enter Variable Name.\")\n variable_name.setDescription(\"Valid values can be found in the eplusout.rdd file after a simulation is run.\")\n args << variable_name\n \n #make an argument for the electric tariff\n reporting_frequency_chs = OpenStudio::StringVector.new\n reporting_frequency_chs << \"Detailed\"\n reporting_frequency_chs << \"Timestep\"\n reporting_frequency_chs << \"Zone Timestep\"\n reporting_frequency_chs << \"Hourly\"\n reporting_frequency_chs << \"Daily\"\n reporting_frequency_chs << \"Monthly\"\n reporting_frequency_chs << \"Runperiod\"\n reporting_frequency = OpenStudio::Ruleset::OSArgument::makeChoiceArgument('reporting_frequency', reporting_frequency_chs, true)\n reporting_frequency.setDisplayName(\"Reporting Frequency.\")\n reporting_frequency.setDefaultValue(\"Hourly\")\n args << reporting_frequency\n\n #make an argument for the key_value\n key_value = OpenStudio::Ruleset::OSArgument::makeStringArgument(\"key_value\",true)\n key_value.setDisplayName(\"Enter Key Name.\")\n key_value.setDescription(\"Enter * for all objects or the full name of a specific object to.\")\n key_value.setDefaultValue(\"*\")\n args << key_value\n \n env = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"env\", true)\n env.setDisplayName(\"availableEnvPeriods\")\n env.setDescription(\"availableEnvPeriods\")\n env.setDefaultValue(\"RUN PERIOD 1\")\n args << env\n \n return args\n end",
"def set_arguments (args)\n end",
"def arguments\n args = OpenStudio::Measure::OSArgumentVector.new\n\n # make an argument for the variable name\n variable_name = OpenStudio::Measure::OSArgument.makeStringArgument('variable_name', true)\n variable_name.setDisplayName('Enter Variable Name.')\n variable_name.setDescription('Valid values can be found in the eplusout.rdd file after a simulation is run.')\n args << variable_name\n\n # make an argument for the electric tariff\n reporting_frequency_chs = OpenStudio::StringVector.new\n reporting_frequency_chs << 'Detailed'\n reporting_frequency_chs << 'Timestep'\n reporting_frequency_chs << 'Zone Timestep'\n reporting_frequency_chs << 'Hourly'\n reporting_frequency_chs << 'Daily'\n reporting_frequency_chs << 'Monthly'\n reporting_frequency_chs << 'Runperiod'\n reporting_frequency = OpenStudio::Measure::OSArgument.makeChoiceArgument('reporting_frequency', reporting_frequency_chs, true)\n reporting_frequency.setDisplayName('Reporting Frequency.')\n reporting_frequency.setDefaultValue('Hourly')\n args << reporting_frequency\n\n # make an argument for the key_value\n key_value = OpenStudio::Measure::OSArgument.makeStringArgument('key_value', true)\n key_value.setDisplayName('Enter Key Name.')\n key_value.setDescription('Enter * for all objects or the full name of a specific object to.')\n key_value.setDefaultValue('*')\n args << key_value\n\n env = OpenStudio::Measure::OSArgument.makeStringArgument('env', true)\n env.setDisplayName('availableEnvPeriods')\n env.setDescription('availableEnvPeriods')\n env.setDefaultValue('RUN PERIOD 1')\n args << env\n\n args\n end",
"def handle_arguments(args)\n if input_file.nil?\n print_usage\n true\n else\n args.help || args.version\n end\n end",
"def arguments=(_arg0); end",
"def command_line\r\n ARGV.each do |arg|\r\n if arg == \"instructions\"\r\n instructions\r\n elsif arg == \"calculator\"\r\n ask_for_digits\r\n else\r\n \r\n end\r\n end\r\n \r\n end",
"def prescreen_input(args)\n if ((args.nil?) || (args.empty?))\n ['-eq', Date.today.strftime('%Y-%m-%d')]\n elsif ((args.length == 1) && (args[0].is_date?))\n ['-eq', args[0]]\n else\n args\n end\nend",
"def varios_args(*args)\n puts \"Tamanho de args: #{args.size}\"\n args.each { |x| p x}\n end",
"def process_arguments\n @e_addr = @options.email\n @r_name = @options.run_names\n @m_name = @options.machine_names\n @action = @options.action\n @snfs = @options.snfs\n end",
"def arguments\n args = OpenStudio::Measure::OSArgumentVector.new\n\n # url of the city database\n city_db_url = OpenStudio::Measure::OSArgument.makeStringArgument('city_db_url', true)\n city_db_url.setDisplayName('City Database Url')\n city_db_url.setDescription('Url of the City Database')\n city_db_url.setDefaultValue('')\n args << city_db_url\n\n # project id to update\n project_id = OpenStudio::Measure::OSArgument.makeStringArgument('project_id', true)\n project_id.setDisplayName('Project ID')\n project_id.setDescription('Project ID to generate reports for.')\n project_id.setDefaultValue('0')\n args << project_id\n\n # datapoint id to update\n datapoint_id = OpenStudio::Measure::OSArgument.makeStringArgument('datapoint_id', true)\n datapoint_id.setDisplayName('Datapoint ID')\n datapoint_id.setDescription('Datapoint ID to generate reports for.')\n datapoint_id.setDefaultValue('0')\n args << datapoint_id\n\n return args\n end",
"def validate_args (args)\n\t# todo\nend",
"def args() return @args end",
"def input=(_arg0); end",
"def process_inputs(args)\n @input = ((name = args[:in_file]) && (IO.read(name, mode: \"rb\"))) ||\n args[:in_str] ||\n fail(\"An input must be specified.\")\n\n @generator = args[:generator] ||\n ((key = args[:key]) && Generator.new(key)) ||\n fail(\"A key or generator must be specified.\")\n\n @window = args[:window] || 16\n\n #The filler value is for testing purposes only. It should\n #not be specified when secure operation is desired.\n @fill_value = args[:filler]\n end",
"def parse_args\r\n if(cmd.args =~ /\\=/)\r\n self.names = InputFormatter.titlecase_arg(cmd.args.before(\"=\"))\r\n self.action_args = cmd.args.after(\"=\")\r\n elseif (cmd.args && one_word_command)\r\n self.names = InputFormatter.titlecase_arg(cmd.args)\r\n self.action_args = \"\"\r\n else\r\n self.names = enactor.name\r\n self.action_args = cmd.args\r\n end\r\n\r\n self.names = self.names ? self.names.split(/[ ,]/) : nil\r\n\r\n self.combat_command = cmd.switch ? cmd.switch.downcase : nil\r\n end",
"def manage_args(*args)\n end",
"def arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n \n #make an argument for your name\n user_name = OpenStudio::Ruleset::OSArgument::makeStringArgument(\"user_name\",true)\n user_name.setDisplayName(\"What is your name?\")\n args << user_name\n\n #make an argument to add new space true/false\n add_space = OpenStudio::Ruleset::OSArgument::makeBoolArgument(\"add_space\",true)\n add_space.setDisplayName(\"Add a space to your model?\")\n add_space.setDefaultValue(true)\n args << add_space\n \n return args\n end",
"def greeting\n puts \"Hello, MTA rider! How can we help?\"\n puts \"please enter one of the following commands:\"\n puts \"lines / stops the_line / calculate Departing_Line Departing_Stop Arriving_Line Arriving_Stop\"\n user_call, *user_args = gets.chomp\n user_args.to_s\n # user_args.split(\" \")\n # puts user_input\n\n if user_call == lines\n show_lines()\n elsif user_call == stops\n show_stops(user_args[0])\n elsif user_call == calculate\n if user_args.length < 4\n puts 'please enter \"Departing_Line Departing_Stop Arriving_Line Arriving_Stop\"'\n puts 'or enter \"exit\" to return to the home screen' \n user_input = gets.chomp\n if user_input == \"exit\"\n greeting()\n end \n user_input = user_input.split(\" \")\n calculate(user_input[0], user_input[1], user_input[2], user_input[3])\n else\n calculate(user_args[0], user_args[1], user_args[2], user_args[3])\n end\n else\n \n end\nend",
"def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\n\n\n\n # Make an argument for evap effectiveness\n input_csv_path = OpenStudio::Measure::OSArgument::makeStringArgument(\"input_csv_folder_path\",true)\n input_csv_path.setDisplayName(\"raw_data_input_folder_path\")\n input_csv_path.setDefaultValue(\"data_file\")\n args << input_csv_path\n\n test_numbers = OpenStudio::StringVector.new\n test_numbers << 'Test_3'\n test_numbers << 'Test_6'\n test_numbers << 'Test_8'\n \n test_names = OpenStudio::StringVector.new\n test_names << 'UA_test'\n test_names << 'Cooling_test'\n test_names << 'Plenum_test'\n\n test_selections = OpenStudio::Ruleset::OSArgument::makeChoiceArgument('test_data',test_numbers,test_names,true)\n\n \n test_selections.setDisplayName(\"Experiment\")\n test_selections.setDefaultValue(\"Test_3\")\n args << test_selections\n\n \n return args\n end",
"def arguments\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n # URL of the DEnCity server that will be posted to\n hostname = OpenStudio::Ruleset::OSArgument::makeStringArgument('hostname', true)\n hostname.setDisplayName('URL of the DEnCity Server')\n hostname.setDefaultValue('http://www.dencity.org')\n args << hostname\n\n # DEnCity server user id at hostname\n user_id = OpenStudio::Ruleset::OSArgument::makeStringArgument('user_id',true)\n user_id.setDisplayName('User ID for DEnCity Server')\n args << user_id\n\n # DEnCIty server user id's password\n auth_code = OpenStudio::Ruleset::OSArgument::makeStringArgument('auth_code', true)\n auth_code.setDisplayName('Authentication code for User ID on DEnCity server')\n args << auth_code\n\n # Building type for DEnCity's metadata\n building_type = OpenStudio::Ruleset::OSArgument::makeStringArgument('building_type', false)\n building_type.setDisplayName('Building type')\n args << building_type\n\n # HVAC system for DEnCity's metadata\n primary_hvac = OpenStudio::Ruleset::OSArgument::makeStringArgument('primary_hvac', false)\n primary_hvac.setDisplayName('Primary HVAC system in building')\n args << primary_hvac\n\n args\n\n end",
"def arguments\r\n args = OpenStudio::Ruleset::OSArgumentVector.new\r\n\r\n #make choice argument for facade\r\n choices = OpenStudio::StringVector.new\r\n choices << \"MessagePack\"\r\n choices << \"CSV\"\r\n choices << \"Both\"\r\n output_format = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"output_format\", choices)\r\n output_format.setDisplayName(\"Output Format\")\r\n output_format.setDefaultValue(\"Both\")\r\n args << output_format\r\n\r\n args\r\n end",
"def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\n\t\n #make an argument for entering furnace installed afue\n afue = OpenStudio::Measure::OSArgument::makeDoubleArgument(\"afue\",true)\n afue.setDisplayName(\"Installed AFUE\")\n afue.setUnits(\"Btu/Btu\")\n afue.setDescription(\"The installed Annual Fuel Utilization Efficiency (AFUE) of the furnace, which can be used to account for performance derating or degradation relative to the rated value.\")\n afue.setDefaultValue(1.0)\n args << afue\n\n #make an argument for entering furnace installed supply fan power\n fanpower = OpenStudio::Measure::OSArgument::makeDoubleArgument(\"fan_power_installed\",true)\n fanpower.setDisplayName(\"Installed Supply Fan Power\")\n fanpower.setUnits(\"W/cfm\")\n fanpower.setDescription(\"Fan power (in W) per delivered airflow rate (in cfm) of the indoor fan for the maximum fan speed under actual operating conditions.\")\n fanpower.setDefaultValue(0.5)\n args << fanpower\t\n\t\n #make a string argument for furnace heating output capacity\n furnacecap = OpenStudio::Measure::OSArgument::makeStringArgument(\"capacity\", true)\n furnacecap.setDisplayName(\"Heating Capacity\")\n furnacecap.setDescription(\"The output heating capacity of the furnace. If using '#{Constants.SizingAuto}', the autosizing algorithm will use ACCA Manual S to set the capacity.\")\n furnacecap.setUnits(\"kBtu/hr\")\n furnacecap.setDefaultValue(Constants.SizingAuto)\n args << furnacecap\n \n return args\n end",
"def greeting(args)\r\n greet = args[:greet] || \"Hi\"\r\n title = args[:title] || \"Citizen\"\r\n name = args[:name] \r\n puts \"#{greet} #{title} #{name}\"\r\nend",
"def parse_args\n\t\t@args = @args_a.each_slice(2).to_a.inject({}) { |h, k| h[k[0]] = k[1]; h }\n\t\tkeys = @skeys + @lkeys\n\t\t@args.each do |k, v|\n\t\t\tif !keys.include?(k)\n\t\t\t\tputs \"Unknown option `#{k}'\"\n\t\t\t\texit\n\t\t\tend\n\n\t\t\tif keys.include?(v)\n\t\t\t\tputs \"Missing values for `#{k}' and `#{v}'\"\n\t\t\t\texit\n\t\t\tend\n\n\t\t\tif v != nil\n\t\t\t\tif v.start_with?('-')\n\t\t\t\t\tputs \"Warning: Value of `#{k}' appears to be a flag\"\n\t\t\t\tend\n\n\t\t\t\tif @static.has_key?(k)\n\t\t\t\t\tif !@static[k].include?(v)\n\t\t\t\t\t\tputs \"Unknown option `#{v}' for `#{k}'\"\n\t\t\t\t\t\texit\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t\n\t\tif remove_keys(@no_vals).has_blank?\n\t\t\tputs \"Missing argument(s)\"\n\t\t\texit\n\t\tend\t\t\t\n\tend",
"def command_line_arguments(array)\n array.size.times do\n if array.include?('-nc')\n colour_changer(:white)\n array.delete('-nc')\n elsif array.any? { |x| ['-d1', '-d2', '-d3', '-d4'].include? x }\n key = (array[0])[1, 2].to_sym\n @difficulty = DIFFICULTY[key]\n @promptarr = prompt_select(key)\n @intro = false\n end\n end\n end",
"def arguments()\n args = OpenStudio::Measure::OSArgumentVector.new\n \n #make an argument for the frequency\n reporting_frequency_chs = OpenStudio::StringVector.new\n reporting_frequency_chs << \"Detailed\"\n reporting_frequency_chs << \"Timestep\"\n reporting_frequency_chs << \"Hourly\"\n reporting_frequency_chs << \"Daily\"\n reporting_frequency_chs << \"Monthly\"\n reporting_frequency_chs << \"Runperiod\"\n reporting_frequency = OpenStudio::Ruleset::OSArgument::makeChoiceArgument('reporting_frequency', reporting_frequency_chs, true)\n reporting_frequency.setDisplayName(\"Reporting Frequency\")\n reporting_frequency.setDefaultValue(\"Hourly\")\n args << reporting_frequency\n \n # TODO: argument for subset of output meters\n \n return args\n end",
"def arguments()\n args = OpenStudio::Measure::OSArgumentVector.new\n\n #make an argument for the frequency\n reporting_frequency_chs = OpenStudio::StringVector.new\n reporting_frequency_chs << \"Timestep\"\n reporting_frequency_chs << \"Hourly\"\n reporting_frequency_chs << \"Daily\"\n reporting_frequency_chs << \"Monthly\"\n reporting_frequency_chs << \"RunPeriod\"\n arg = OpenStudio::Measure::OSArgument::makeChoiceArgument('reporting_frequency', reporting_frequency_chs, true)\n arg.setDisplayName(\"Reporting Frequency\")\n arg.setDefaultValue(\"Hourly\")\n args << arg\n\n #make an argument for including optional output variables\n arg = OpenStudio::Measure::OSArgument::makeBoolArgument(\"inc_output_variables\", true)\n arg.setDisplayName(\"Include Output Variables\")\n arg.setDefaultValue(false)\n args << arg\n\n return args\n end",
"def arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n #make an argument for entering furnace installed afue\n userdefined_eff = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"userdefinedeff\",true)\n userdefined_eff.setDisplayName(\"Efficiency\")\n\tuserdefined_eff.setUnits(\"Btu/Btu\")\n\tuserdefined_eff.setDescription(\"The efficiency of the electric baseboard.\")\n userdefined_eff.setDefaultValue(1.0)\n args << userdefined_eff\n\n #make a choice argument for furnace heating output capacity\n cap_display_names = OpenStudio::StringVector.new\n cap_display_names << Constants.SizingAuto\n (5..150).step(5) do |kbtu|\n cap_display_names << \"#{kbtu} kBtu/hr\"\n end\n\n #make a string argument for furnace heating output capacity\n selected_baseboardcap = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"selectedbaseboardcap\", cap_display_names, true)\n selected_baseboardcap.setDisplayName(\"Heating Output Capacity\")\n selected_baseboardcap.setDefaultValue(Constants.SizingAuto)\n args << selected_baseboardcap\n\t\n return args\n end",
"def user_input_command_line_menu\n\tcommand_line_input = gets.strip.to_i\n\tcommand_line_input_logic(command_line_input)\nend",
"def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\n\n #make an argument for entering baseboard efficiency\n baseboardeff = OpenStudio::Measure::OSArgument::makeDoubleArgument(\"efficiency\",true)\n baseboardeff.setDisplayName(\"Efficiency\")\n baseboardeff.setUnits(\"Btu/Btu\")\n baseboardeff.setDescription(\"The efficiency of the electric baseboard.\")\n baseboardeff.setDefaultValue(1.0)\n args << baseboardeff\n\n #make a string argument for baseboard heating output capacity\n baseboardcap = OpenStudio::Measure::OSArgument::makeStringArgument(\"capacity\", true)\n baseboardcap.setDisplayName(\"Heating Capacity\")\n baseboardcap.setDescription(\"The output heating capacity of the electric baseboard. If using '#{Constants.SizingAuto}', the autosizing algorithm will use ACCA Manual S to set the capacity.\")\n baseboardcap.setUnits(\"kBtu/hr\")\n baseboardcap.setDefaultValue(Constants.SizingAuto)\n args << baseboardcap\n\t\n return args\n end",
"def cmdarg; end",
"def cmdarg; end",
"def cmdarg; end",
"def check_inputs_g(args)\n raise TypeError, Ajaila::Messager.warning(\"Nothing to generate...\") if args == []\n raise TypeError, Ajaila::Messager.warning(\"Only miners, selectors, presenters supported\\n(ex. miner SomeMiner, selector SomeSelector,\\n presenter SomePresenter, table SomeTable)\") if KNOWN_INSTANCES.include?(args[0]) == false\n raise TypeError, Ajaila::Messager.warning(\"Your #{args[0]} needs a name!\") if args[1] == nil\n raise TypeError, Ajaila::Messager.warning(\"Wrong format of the #{args[0]} name (use only A-Z and a-z symbols)\") if args[1][/^[A-Z]+$/i] == nil\n return 0\n end",
"def arguments\n parser.arguments\n end",
"def valid_args(type)\n case type\n when 'search' then %i[q format addressdetails extratags namedetails viewbox bounded exclude_place_ids limit accept-language email]\n when 'reverse' then %i[format lat lon zoom addressdetails extratags namedetails accept-language email]\n else []\n end\n end",
"def madlib_inputs\n print \"Enter a noun: \" \n noun = gets.chomp\n print \"Enter a verb: \" \n verb = gets.chomp\n print \"Enter an adjective: \" \n adjective = gets.chomp\n print \"Enter an adverb: \" \n adverb = gets.chomp\n madlib_line(noun, verb, adjective, adverb)\nend",
"def arguments\n args = OpenStudio::Measure::OSArgumentVector.new\n\n id = OpenStudio::Measure::OSArgument.makeStringArgument('feature_id', false)\n id.setDisplayName('Feature unique identifier')\n id.setDefaultValue('1')\n args << id\n\n name = OpenStudio::Measure::OSArgument.makeStringArgument('feature_name', false)\n name.setDisplayName('Feature scenario specific name')\n name.setDefaultValue('name')\n args << name\n\n feature_type = OpenStudio::Measure::OSArgument.makeStringArgument('feature_type', false)\n feature_type.setDisplayName('URBANopt Feature Type')\n feature_type.setDefaultValue('Building')\n args << feature_type\n\n feature_location = OpenStudio::Measure::OSArgument.makeStringArgument('feature_location', false)\n feature_location.setDisplayName('URBANopt Feature Location')\n feature_location.setDefaultValue('0')\n args << feature_location\n\n # make an argument for the frequency\n reporting_frequency_chs = OpenStudio::StringVector.new\n reporting_frequency_chs << 'Detailed'\n reporting_frequency_chs << 'Timestep'\n reporting_frequency_chs << 'Hourly'\n reporting_frequency_chs << 'Daily'\n # reporting_frequency_chs << 'Zone Timestep'\n reporting_frequency_chs << 'BillingPeriod' # match it to utility bill object\n ## Utility report here to report the start and end for each fueltype\n reporting_frequency_chs << 'Monthly'\n reporting_frequency_chs << 'Runperiod'\n\n reporting_frequency = OpenStudio::Measure::OSArgument.makeChoiceArgument('reporting_frequency', reporting_frequency_chs, true)\n reporting_frequency.setDisplayName('Reporting Frequency')\n reporting_frequency.setDescription('The frequency at which to report timeseries output data.')\n reporting_frequency.setDefaultValue('Timestep')\n args << reporting_frequency\n\n return args\n end",
"def arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n \n #make a start date argument\n start_date = OpenStudio::Ruleset::OSArgument::makeStringArgument(\"start_date\",true)\n start_date.setDisplayName(\"Start date\")\n args << start_date\n \n #make an end date argument\n end_date = OpenStudio::Ruleset::OSArgument::makeStringArgument(\"end_date\",true)\n end_date.setDisplayName(\"End date\")\n args << end_date\n \n return args\n end",
"def check_arguments\n convert_boolean_strings\n check_output\n check_log_level\n check_input_entry\n check_input_types\n end",
"def process_arguments\n # clean unsupport symbols, e.g. JieFang;\n # or error argument due to option typo, e.g. '-list' will put 'ist' into the array in this src.\n @support_newspapers = Array.new #TODO: move to elsewhere\n @support_newspapers << :XM\n @support_newspapers << :WHB\n @support_newspapers << :YZ\n # ATTENTION: command line input is an array of string, to be consistent, internally I use only symbol when using this symbol\n @options.newspapers = @options.newspapers.collect { | item | item.to_sym } & @support_newspapers\n \n if @options.newspapers.size == 0\n @support_newspapers.each do | sym |\n @options.newspapers << sym\n end\n end\n end",
"def args\n raw_args\n end",
"def argv; end",
"def arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n \n #make an argument for your name\n code_choices = OpenStudio::StringVector.new \n code_choices << \"ASHRAE 90.1-2007\" \n code_choices << \"ASHRAE 90.1-2010\" \n energy_code = OpenStudio::Ruleset::OSArgument::makeChoiceArgument('energy_code', code_choices, true)\n energy_code.setDisplayName(\"Code baseline\")\n energy_code.setDefaultValue(\"ASHRAE 90.1-2010\")\n args << energy_code\n \n #make an argument to add new space true/false\n leed_check = OpenStudio::Ruleset::OSArgument::makeBoolArgument(\"leed_check\",true)\n leed_check.setDisplayName(\"Perform typical LEED checks?\")\n leed_check.setDefaultValue(true)\n args << leed_check\n \n return args\n end",
"def arguments(model)\n #list of arguments as they will appear in the interface. They are available in the run command as\n @argument_array_of_arrays = [\n [ \"variable_name\", \"type\", \"required\", \"model_dependant\", \"display_name\", \"default_value\", \"min_value\", \"max_value\", \"string_choice_array\", \t\"os_object_type\"\t],\n [ \"weather_file_name\", \"STRING\", true, false, \"Weather File Name\", nil, nil, nil, nil, \t nil\t\t\t\t\t],\n #Default set for server weather folder.\n [ \"weather_directory\", \"STRING\", true, false, \"Weather Directory\", \"../../weather\", nil, nil, nil,\t nil\t\t\t\t\t]\n \n ]\n #set up arguments. \n args = OpenStudio::Ruleset::OSArgumentVector.new\n self.argument_setter(args)\n return args\n end",
"def inflamed _args\n \"inflamed _args;\" \n end",
"def more_options\n puts Rainbow(\"Specify your additional options for your search: 'release date', 'search history', or go back\").yellow.underline\n input = gets.chomp.downcase\n \n if input == \"release date\"\n option_release_date\n \n elsif input == \"search history\"\n game_history\n\n elsif input == \"go back\"\n continue_or_exit\n \n else \n puts \"Input not recognized please try again\"\n more_options\n end\n end",
"def cmd(options={})\n arguments\n end",
"def user_input\n\tgets\nend",
"def arguments()\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n # this measure will require arguments, but at this time, they are not known\n geometry_profile = OpenStudio::Ruleset::OSArgument::makeStringArgument('geometry_profile', true)\n geometry_profile.setDefaultValue(\"{}\")\n os_model = OpenStudio::Ruleset::OSArgument::makeStringArgument('os_model', true)\n os_model.setDefaultValue('multi-model mode')\n user_id = OpenStudio::Ruleset::OSArgument::makeStringArgument('user_id', true)\n user_id.setDefaultValue(\"00000000-0000-0000-0000-000000000000\")\n job_id = OpenStudio::Ruleset::OSArgument::makeStringArgument('job_id', true)\n #job_id.setDefaultValue(SecureRandom.uuid.to_s)\n ashrae_climate_zone = OpenStudio::Ruleset::OSArgument::makeStringArgument('ashrae_climate_zone', false)\n ashrae_climate_zone.setDefaultValue(\"-1\")\n building_type = OpenStudio::Ruleset::OSArgument::makeStringArgument('building_type', false)\n building_type.setDefaultValue(\"BadDefaultType\")\n\n args << geometry_profile\n args << os_model\n args << user_id\n args << job_id\n args << ashrae_climate_zone\n args << building_type\n\n return args\n end",
"def input\n @input ||= args.dig(:input)\n end",
"def parse_args\n require 'optimist'\n opts = Optimist.options do\n opt :source, \"Inventory Source UID\", :type => :string, :required => ENV[\"SOURCE_UID\"].nil?, :default => ENV[\"SOURCE_UID\"]\n opt :ingress_api, \"Hostname of the ingress-api route\", :type => :string, :default => ENV[\"INGRESS_API\"] || \"http://localhost:9292\"\n opt :config, \"Configuration file name\", :type => :string, :default => ENV[\"CONFIG\"] || \"default\"\n opt :data, \"Amount & custom values of generated items\", :type => :string, :default => ENV[\"DATA\"] || \"default\"\n end\n\n opts\nend",
"def arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n # lat arg\n lat = OpenStudio::Ruleset::OSArgument.makeDoubleArgument(\"lat\", true)\n lat.setDisplayName(\"Latitude\")\n lat.setDefaultValue(39.7392000000)\n args << lat\n\n # long arg\n lon = OpenStudio::Ruleset::OSArgument.makeDoubleArgument(\"lon\", true)\n lon.setDisplayName(\"Longitude\")\n lon.setDefaultValue(-104.9903000000)\n args << lon\n\n return args\n end",
"def add args\n db = get_db\n if args.empty?\n print \"Enter a short summary: \"\n STDOUT.flush\n text = gets.chomp\n if text.empty?\n exit ERRCODE\n end\n else\n # if you add last arg as P1..P5, I'll update priority automatically\n if args.last =~ /P[1-5]/\n $default_priority = args.pop\n end\n text = args.join \" \"\n end\n # convert actual newline to C-a. slash n's are escapes so echo -e does not muck up.\n #atitle=$( echo \"$atitle\" | tr -cd '\\40-\\176' )\n text.tr! \"\\n\", '\u0001'\n title = text\n desc = nil\n if $prompt_desc\n # choice of vim or this XXX also how to store in case of error or abandon\n # and allow user to edit, so no retyping. This could be for mult fields\n message \"Enter a detailed description (. to exit): \"\n desc = Cmdapp.get_lines\n #message \"You entered #{desc}\"\n end\n type = $default_type || \"bug\"\n severity = $default_severity || \"normal\"\n status = $default_status || \"open\"\n priority = $default_priority || \"P3\"\n if $prompt_type\n type = Cmdapp._choice(\"Select type:\", %w[bug enhancement feature task] )\n #message \"You selected #{type}\"\n end\n if $prompt_priority\n #priority = Cmdapp._choice(\"Select priority:\", %w[normal critical moderate] )\n priority = ask_priority\n #message \"You selected #{severity}\"\n end\n if $prompt_severity\n severity = Cmdapp._choice(\"Select severity:\", %w[normal critical moderate] )\n #message \"You selected #{severity}\"\n end\n if $prompt_status\n status = Cmdapp._choice(\"Select status:\", %w[open started closed stopped canceled] )\n #message \"You selected #{status}\"\n end\n assigned_to = $default_assigned_to\n if $prompt_assigned_to\n message \"Assign to:\"\n #assigned_to = $stdin.gets.chomp\n assigned_to = Cmdapp._gets \"assigned_to\", \"assigned_to\", $default_assigned_to\n #message \"You selected #{assigned_to}\"\n end\n project = component = version = nil\n # project\n if $use_project\n project = Cmdapp.user_input('project', $prompt_project, nil, $valid_project, $default_project)\n end\n if $use_component\n component = Cmdapp.user_input('component', $prompt_component, nil, $valid_component, $default_component)\n end\n if $use_version\n version = Cmdapp.user_input('version', $prompt_version, nil, $valid_version, $default_version)\n end\n\n start_date = @now\n due_date = default_due_date\n comment_count = 0\n priority ||= \"P3\" \n description = desc\n fix = nil #\"Some long text\" \n #date_created = @now\n #date_modified = @now\n body = {}\n body[\"title\"]=title\n body[\"description\"]=description\n body[\"type\"]=type\n body[\"status\"]=status\n body[\"start_date\"]=start_date.to_s\n body[\"due_date\"]=due_date.to_s\n body[\"priority\"]=priority\n body[\"severity\"]=severity\n body[\"assigned_to\"]=assigned_to\n body[\"created_by\"] = $default_user\n # only insert if its wanted by user\n body[\"project\"]=project if $use_project\n body[\"component\"]=component if $use_component\n body[\"version\"]=version if $use_version\n\n rowid = db.table_insert_hash(\"bugs\", body)\n puts \"Issue #{rowid} created\"\n logid = db.sql_logs_insert rowid, \"create\", \"#{rowid} #{type}: #{title}\"\n body[\"id\"] = rowid\n mail_issue nil, body\n \n 0\n end",
"def arguments(model)\n #list of arguments as they will appear in the interface. They are available in the run command as\n @argument_array_of_arrays = [\n [ \"variable_name\", \"type\", \"required\", \"model_dependant\", \"display_name\", \"default_value\", \"min_value\", \"max_value\", \"string_choice_array\", \"os_object_type\"\t ],\n [ \"alternativeModel\", \"STRING\", true, false, \"Alternative Model\", 'FullServiceRestaurant.osm', nil, nil, nil, \t nil\t\t\t\t\t],\n [ \"osm_directory\", \"STRING\", true, false, \"OSM Directory\", \"../../lib/btap/resources/models/smart_archetypes\", nil, nil, nil,\t nil\t\t\t\t\t] \n ]\n #set up arguments. \n args = OpenStudio::Ruleset::OSArgumentVector.new\n self.argument_setter(args)\n return args\n end",
"def arguments(model)\n #list of arguments as they will appear in the interface. They are available in the run command as\n @argument_array_of_arrays = [\n [ \"variable_name\", \"type\", \"required\", \"model_dependant\", \"display_name\", \"default_value\", \"min_value\", \"max_value\", \"string_choice_array\", \"os_object_type\"\t ],\n [ \"alternativeModel\", \"STRING\", true, false, \"Alternative Model\", 'FullServiceRestaurant.osm', nil, nil, nil, \t nil\t\t\t\t\t],\n [ \"osm_directory\", \"STRING\", true, false, \"OSM Directory\", \"../../lib/btap/resources/models/smart_archetypes\", nil, nil, nil,\t nil\t\t\t\t\t] \n ]\n #set up arguments. \n args = OpenStudio::Ruleset::OSArgumentVector.new\n self.argument_setter(args)\n return args\n end",
"def arguments()\r\n args = OpenStudio::Ruleset::OSArgumentVector.new\r\n\r\n # the name of the sql file\r\n csv_name = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_name\", true)\r\n csv_name.setDisplayName(\"CSV file name\")\r\n csv_name.setDescription(\"CSV file name.\")\r\n csv_name.setDefaultValue(\"mtr.csv\")\r\n args << csv_name\r\n \r\n csv_time_header = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_time_header\", true)\r\n csv_time_header.setDisplayName(\"CSV Time Header\")\r\n csv_time_header.setDescription(\"CSV Time Header Value.\")\r\n csv_time_header.setDefaultValue(\"Date/Time\")\r\n args << csv_time_header\r\n \r\n csv_var = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_var\", true)\r\n csv_var.setDisplayName(\"CSV variable name\")\r\n csv_var.setDescription(\"CSV variable name\")\r\n csv_var.setDefaultValue(\"Whole Building:Facility Total Electric Demand Power [W](TimeStep)\")\r\n args << csv_var\r\n \r\n csv_var_dn = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_var_dn\", true)\r\n csv_var_dn.setDisplayName(\"CSV variable display name\")\r\n csv_var_dn.setDescription(\"CSV variable display name\")\r\n csv_var_dn.setDefaultValue(\"\")\r\n args << csv_var_dn\r\n \r\n years = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"year\", true)\r\n years.setDisplayName(\"Year in csv data\")\r\n years.setDescription(\"Year in csv data => mm:dd:yy or mm:dd\")\r\n years.setDefaultValue(true)\r\n args << years\r\n \r\n seconds = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"seconds\", true)\r\n seconds.setDisplayName(\"Seconds in csv data\")\r\n seconds.setDescription(\"Seconds in csv data => hh:mm:ss or hh:mm\")\r\n seconds.setDefaultValue(true)\r\n args << seconds\r\n \r\n sql_key = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"sql_key\", true)\r\n sql_key.setDisplayName(\"SQL key\")\r\n sql_key.setDescription(\"SQL key\")\r\n sql_key.setDefaultValue(\"Whole Building\")\r\n args << sql_key \r\n\r\n sql_var = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"sql_var\", true)\r\n sql_var.setDisplayName(\"SQL var\")\r\n sql_var.setDescription(\"SQL var\")\r\n sql_var.setDefaultValue(\"Facility Total Electric Demand Power\")\r\n args << sql_var \r\n \r\n norm = OpenStudio::Ruleset::OSArgument.makeDoubleArgument(\"norm\", true)\r\n norm.setDisplayName(\"norm of the difference of csv and sql\")\r\n norm.setDescription(\"norm of the difference of csv and sql\")\r\n norm.setDefaultValue(1)\r\n args << norm \r\n\r\n find_avail = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"find_avail\", true)\r\n find_avail.setDisplayName(\"find_avail\")\r\n find_avail.setDescription(\"find_avail\")\r\n find_avail.setDefaultValue(true)\r\n args << find_avail \r\n\r\n compute_diff = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"compute_diff\", true)\r\n compute_diff.setDisplayName(\"compute_diff\")\r\n compute_diff.setDescription(\"compute_diff\")\r\n compute_diff.setDefaultValue(true)\r\n args << compute_diff\r\n \r\n verbose_messages = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"verbose_messages\", true)\r\n verbose_messages.setDisplayName(\"verbose_messages\")\r\n verbose_messages.setDescription(\"verbose_messages\")\r\n verbose_messages.setDefaultValue(true)\r\n args << verbose_messages \r\n\r\n return args\r\n end",
"def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\t\t\n\n #Make a string argument for occupants (auto or number)\n num_occ = OpenStudio::Measure::OSArgument::makeStringArgument(\"num_occ\", false)\n num_occ.setDisplayName(\"Number of Occupants\")\n num_occ.setDescription(\"Specify the number of occupants. For a multifamily building, specify one value for all units or a comma-separated set of values (in the correct order) for each unit. A value of '#{Constants.Auto}' will calculate the average number of occupants from the number of bedrooms. Used to specify the internal gains from people only.\")\n num_occ.setDefaultValue(Constants.Auto)\n args << num_occ\n\n #Make a string argument for 24 weekday schedule values\n weekday_sch = OpenStudio::Measure::OSArgument::makeStringArgument(\"weekday_sch\", true)\n weekday_sch.setDisplayName(\"Weekday schedule\")\n weekday_sch.setDescription(\"Specify the 24-hour weekday schedule.\")\n weekday_sch.setDefaultValue(\"1.00000, 1.00000, 1.00000, 1.00000, 1.00000, 1.00000, 1.00000, 0.88310, 0.40861, 0.24189, 0.24189, 0.24189, 0.24189, 0.24189, 0.24189, 0.24189, 0.29498, 0.55310, 0.89693, 0.89693, 0.89693, 1.00000, 1.00000, 1.00000\")\n args << weekday_sch\n \n #Make a string argument for 24 weekend schedule values\n weekend_sch = OpenStudio::Measure::OSArgument::makeStringArgument(\"weekend_sch\", true)\n weekend_sch.setDisplayName(\"Weekend schedule\")\n weekend_sch.setDescription(\"Specify the 24-hour weekend schedule.\")\n weekend_sch.setDefaultValue(\"1.00000, 1.00000, 1.00000, 1.00000, 1.00000, 1.00000, 1.00000, 0.88310, 0.40861, 0.24189, 0.24189, 0.24189, 0.24189, 0.24189, 0.24189, 0.24189, 0.29498, 0.55310, 0.89693, 0.89693, 0.89693, 1.00000, 1.00000, 1.00000\")\n args << weekend_sch\n\n #Make a string argument for 12 monthly schedule values\n monthly_sch = OpenStudio::Measure::OSArgument::makeStringArgument(\"monthly_sch\", true)\n monthly_sch.setDisplayName(\"Month schedule\")\n monthly_sch.setDescription(\"Specify the 12-month schedule.\")\n monthly_sch.setDefaultValue(\"1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0\")\n args << monthly_sch\n\n return args\n end",
"def validate_arguments()\n usage unless ARGV.count > 0\nend",
"def input args\n if args.state.inputlist.length > 5\n args.state.inputlist.pop\n end\n\n should_process_special_move = (args.inputs.keyboard.key_down.j) ||\n (args.inputs.keyboard.key_down.k) ||\n (args.inputs.keyboard.key_down.a) ||\n (args.inputs.keyboard.key_down.d) ||\n (args.inputs.controller_one.key_down.y) ||\n (args.inputs.controller_one.key_down.x) ||\n (args.inputs.controller_one.key_down.left) ||\n (args.inputs.controller_one.key_down.right)\n\n if (should_process_special_move)\n if (args.inputs.keyboard.key_down.j && args.inputs.keyboard.key_down.k) ||\n (args.inputs.controller_one.key_down.x && args.inputs.controller_one.key_down.y)\n args.state.inputlist.unshift(\"shield\")\n elsif (args.inputs.keyboard.key_down.k || args.inputs.controller_one.key_down.y) &&\n (args.state.inputlist[0] == \"forward-attack\") && ((args.state.tick_count - args.state.lastpush) <= 15)\n args.state.inputlist.unshift(\"dash-attack\")\n args.state.player.dx = 20\n elsif (args.inputs.keyboard.key_down.j && args.inputs.keyboard.a) ||\n (args.inputs.controller_one.key_down.x && args.inputs.controller_one.key_down.left)\n args.state.inputlist.unshift(\"back-attack\")\n elsif ( args.inputs.controller_one.key_down.x || args.inputs.keyboard.key_down.j)\n args.state.inputlist.unshift(\"forward-attack\")\n elsif (args.inputs.keyboard.key_down.k || args.inputs.controller_one.key_down.y) &&\n (args.state.player.y > 128)\n args.state.inputlist.unshift(\"dair\")\n elsif (args.inputs.keyboard.key_down.k || args.inputs.controller_one.key_down.y)\n args.state.inputlist.unshift(\"up-attack\")\n elsif (args.inputs.controller_one.key_down.left || args.inputs.keyboard.key_down.a) &&\n (args.state.inputlist[0] == \"<\") &&\n ((args.state.tick_count - args.state.lastpush) <= 10)\n args.state.inputlist.unshift(\"<<\")\n args.state.player.dx = -15\n elsif (args.inputs.controller_one.key_down.left || args.inputs.keyboard.key_down.a)\n args.state.inputlist.unshift(\"<\")\n args.state.timeleft = args.state.tick_count\n elsif (args.inputs.controller_one.key_down.right || args.inputs.keyboard.key_down.d)\n args.state.inputlist.unshift(\">\")\n end\n\n args.state.lastpush = args.state.tick_count\n end\n\n if args.inputs.keyboard.space || args.inputs.controller_one.r2 # if the user presses the space bar\n args.state.player.jumped_at ||= args.state.tick_count # jumped_at is set to current frame\n\n # if the time that has passed since the jump is less than the player's jump duration and\n # the player is not falling\n if args.state.player.jumped_at.elapsed_time < args.state.player_jump_power_duration && !args.state.player.falling\n args.state.player.dy = args.state.player_jump_power # change in y is set to power of player's jump\n end\n end\n\n # if the space bar is in the \"up\" state (or not being pressed down)\n if args.inputs.keyboard.key_up.space || args.inputs.controller_one.key_up.r2\n args.state.player.jumped_at = nil # jumped_at is empty\n args.state.player.falling = true # the player is falling\n end\n\n if args.inputs.left # if left key is pressed\n if args.state.player.dx < -5\n args.state.player.dx = args.state.player.dx\n else\n args.state.player.dx = -5\n end\n\n elsif args.inputs.right # if right key is pressed\n if args.state.player.dx > 5\n args.state.player.dx = args.state.player.dx\n else\n args.state.player.dx = 5\n end\n else\n args.state.player.dx *= args.state.player_speed_slowdown_rate # dx is scaled down\n end\n\n if ((args.state.player.dx).abs > 5) #&& ((args.state.tick_count - args.state.lastpush) <= 10)\n args.state.player.dx *= 0.95\n end\nend",
"def arguments(model = nil)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n chs = OpenStudio::StringVector.new\n chs << 'Last OSM'\n chs << 'Last IDF'\n file_source = OpenStudio::Ruleset::OSArgument.makeChoiceArgument('file_source', chs, true)\n file_source.setDisplayName('Model Source')\n file_source.setDefaultValue('Last OSM')\n args << file_source\n\n chs = OpenStudio::StringVector.new\n chs << 'Timestep'\n chs << 'Hourly'\n reporting_frequency = OpenStudio::Ruleset::OSArgument.makeChoiceArgument('reporting_frequency', chs, true)\n reporting_frequency.setDisplayName('Reporting Frequency')\n reporting_frequency.setDefaultValue('Hourly')\n args << reporting_frequency\n\n variable1_name = OpenStudio::Ruleset::OSArgument.makeStringArgument('variable1_name', true)\n variable1_name.setDisplayName('Variable 1 Name')\n variable1_name.setDefaultValue('Surface Outside Face Temperature')\n args << variable1_name\n\n variable2_name = OpenStudio::Ruleset::OSArgument.makeStringArgument('variable2_name', true)\n variable2_name.setDisplayName('Variable 2 Name')\n variable2_name.setDefaultValue('Surface Inside Face Temperature')\n args << variable2_name\n\n variable3_name = OpenStudio::Ruleset::OSArgument.makeStringArgument('variable3_name', true)\n variable3_name.setDisplayName('Variable 3 Name')\n variable3_name.setDefaultValue('Zone Mean Radiant Temperature')\n args << variable3_name\n\n return args\n end",
"def arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n # Create a list of the names and handles of space types\n # used in the building.\n used_space_type_handles = OpenStudio::StringVector.new\n used_space_type_names = OpenStudio::StringVector.new\n model.getSpaceTypes.sort.each do |space_type|\n if space_type.spaces.size > 0 # only show space types used in the building\n used_space_type_handles << space_type.handle.to_s\n used_space_type_names << space_type.name.to_s\n end\n end\n\t\n # Make an argument for plenum space type\n ceiling_return_plenum_space_type = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"ceiling_return_plenum_space_type\", used_space_type_handles, used_space_type_names,false)\n ceiling_return_plenum_space_type.setDisplayName(\"This space type should be part of a ceiling return air plenum.\")\n args << ceiling_return_plenum_space_type\n\t\n # Make a bool argument to edit/not edit each space type\n\t\tmodel.getSpaceTypes.sort.each do |space_type|\n\t\t\tif space_type.spaces.size > 0 # only show space types used in the building\n\t\t\t\tspace_type_to_edit = OpenStudio::Ruleset::OSArgument::makeBoolArgument(space_type.name.get.to_s,false)\n\t\t\t\t# Make a bool argument for this space type\n\t\t\t\tspace_type_to_edit.setDisplayName(\"Add #{space_type.name.get} space type to GSHP system?\")\n\t\t\t\tspace_type_to_edit.setDefaultValue(false)\t\t\n\t\t\t\targs << space_type_to_edit\n\t\t\tend\n\t\tend\n\t \n\t\t# Heating COP of GSHP\n\t\tgshp_htg_cop = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"gshp_htg_cop\",false)\n\t\tgshp_htg_cop.setDisplayName(\"GSHP DX Heating Coil Heating COP\")\n\t\tgshp_htg_cop.setDefaultValue(4.0)\n\t\targs << gshp_htg_cop\n\t\t\n\t\t# Cooling EER of GSHP\n\t\tgshp_clg_eer = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"gshp_clg_eer\",false)\n\t\tgshp_clg_eer.setDisplayName(\"GSHP DX Cooling Coil Cooling EER\")\n\t\tgshp_clg_eer.setDefaultValue(14)\n\t\targs << gshp_clg_eer\n\t\t\n\t\t# GSHP Fan Type PSC or ECM\n\t\tfan_choices = OpenStudio::StringVector.new\n\t\tfan_choices << \"PSC\"\n\t\tfan_choices << \"ECM\"\n\t\tgshp_fan_type = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"gshp_fan_type\",fan_choices,true) # note ECM fan type may correspond to different set of heat pump performance curves\n\t\tgshp_fan_type.setDisplayName(\"GSHP Fan Type: PSC or ECM?\")\n\t\tgshp_fan_type.setDefaultValue(\"PSC\")\n args << gshp_fan_type\n\t\t\n\t\t# Condenser Loop Cooling Temperature\n\t\t# condLoopCoolingTemp = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"condLoopCoolingTemp\",false)\n\t\t# condLoopCoolingTemp.setDisplayName(\"Condenser Loop Cooling Temperature (F)\")\n\t\t# condLoopCoolingTemp.setDefaultValue(90)\n\t\t# args << condLoopCoolingTemp\n\t\t\n\t\t# Condenser Loop Heating Temperature\n\t\t# condLoopHeatingTemp = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"condLoopHeatingTemp\",false)\n\t\t# condLoopHeatingTemp.setDisplayName(\"Condenser Loop Heating Temperature (F)\")\n\t\t# condLoopHeatingTemp.setDefaultValue(60)\t\n\t\t# args << condLoopHeatingTemp\n\t\t\n\t\t# Vertical Bore HX\n\t\tbuilding_area = model.getBuilding.floorArea \n\t\tbuilding_cool_ton = building_area*10.7639/500\t\t# 500sf/ton estimated\n\t\tbore_hole_no = OpenStudio::Ruleset::OSArgument::makeIntegerArgument(\"bore_hole_no\",false)\n\t\tbore_hole_no.setDisplayName(\"Number of Bore Holes\")\n\t\tbore_hole_no.setDefaultValue(building_cool_ton.to_i) \n\t\targs << bore_hole_no\n\n\t\t\n\t\tbore_hole_length = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"bore_hole_length\",false)\n\t\tbore_hole_length.setDisplayName(\"Bore Hole Length (ft)\")\n\t\tbore_hole_length.setDefaultValue(200)\n\t\targs << bore_hole_length\n\n\t\tbore_hole_radius = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"bore_hole_radius\",false)\n\t\tbore_hole_radius.setDisplayName(\"Bore Hole Radius (inch)\")\n\t\tbore_hole_radius.setDefaultValue(6.0)\n\t\targs << bore_hole_radius\n\t\t\n\t\tground_k_value = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"ground_k_value\",false)\n\t\tground_k_value.setDisplayName(\"Ground Conductivity (Btu/hr.F.R\")\n\t\tground_k_value.setDefaultValue(0.75)\n\t\targs << ground_k_value\n\t\t\n\t\tgrout_k_value = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"grout_k_value\",false)\n\t\tgrout_k_value.setDisplayName(\"Grout Conductivity (Btu/hr.F.R\")\n\t\tgrout_k_value.setDefaultValue(0.75)\n\t\targs << grout_k_value\n\t\t\n\t\tchs = OpenStudio::StringVector.new\n\t\tchs << \"Yes\"\n\t\tchs << \"No\"\n\t\tsupplemental_boiler = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"supplemental_boiler\",chs, true)\n\t\tsupplemental_boiler.setDisplayName(\"Supplemental Heating Boiler?\")\n\t\tsupplemental_boiler.setDefaultValue(\"No\")\n\t\targs << supplemental_boiler\n\t\t\n\t\t# Boiler Capacity\n\t\tboiler_cap = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"boiler_cap\",false)\n\t\tboiler_cap.setDisplayName(\"boiler normal capacity (MBtuh)\")\n\t\tboiler_cap.setDefaultValue(500.0)\n\t\targs << boiler_cap\n\t\t\t\t\n\t\t# Boiler Efficiency\n\t\tboiler_eff = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"boiler_eff\",false)\n\t\tboiler_eff.setDisplayName(\"Boiler Thermal Efficiency\")\n\t\tboiler_eff.setDefaultValue(0.9)\n\t\targs << boiler_eff\n\t\t\n\t\t# Boiler fuel Type\n\t\tfuel_choices = OpenStudio::StringVector.new\n\t\tfuel_choices << \"NaturalGas\"\n\t\tfuel_choices << \"PropaneGas\"\n\t\tfuel_choices << \"FuelOil#1\"\n\t\tfuel_choices << \"FuelOil#2\"\n\t\tfuel_choices << \"Electricity\"\n\t\tboiler_fuel_type = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"boiler_fuel_type\",fuel_choices,false) \n\t\tboiler_fuel_type.setDisplayName(\"Boiler Fuel Type\")\n\t\tboiler_fuel_type.setDefaultValue(\"NaturalGas\")\n\t\targs << boiler_fuel_type\n\t\t\n\t\t# boiler Hot water supply temperature\n\t\tboiler_hw_st = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"boiler_hw_st\",false)\n\t\tboiler_hw_st.setDisplayName(\"Boiler Design Heating Water Outlet Temperature (F)\")\n\t\tboiler_hw_st.setDefaultValue(120)\t\n\t\targs << boiler_hw_st\n\t\t\n\t\t# DOAS Fan Type\n\t\tdoas_fan_choices = OpenStudio::StringVector.new\n\t\tdoas_fan_choices << \"Constant\"\n\t\tdoas_fan_choices << \"Variable\"\n\t\tdoas_fan_type = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"doas_fan_type\",doas_fan_choices,true)\n\t\tdoas_fan_type.setDisplayName(\"DOAS Fan Flow Control - Variable means DCV controls\")\n\t\tdoas_fan_type.setDefaultValue(\"Variable\")\n\t\targs << doas_fan_type\n\t\t\n\t\t# DOAS Energy Recovery\n\t\terv_choices = OpenStudio::StringVector.new\n\t\terv_choices << \"plate w/o economizer lockout\"\n\t\terv_choices << \"plate w/ economizer lockout\"\n\t\terv_choices << \"rotary wheel w/o economizer lockout\"\n\t\terv_choices << \"rotary wheel w/ economizer lockout\"\n\t\terv_choices << \"none\"\n\t\tdoas_erv = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"doas_erv\",erv_choices,true)\n\t\tdoas_erv.setDisplayName(\"DOAS Energy Recovery?\")\n\t\tdoas_erv.setDefaultValue(\"none\")\n\t\targs << doas_erv\n\t\t\n\t\t# DOAS Evaporative Cooling\n\t\tevap_choices = OpenStudio::StringVector.new\n\t\tevap_choices << \"Direct Evaporative Cooler\"\n\t\tevap_choices << \"none\"\n\t\tdoas_evap = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"doas_evap\",evap_choices,true)\n\t\tdoas_evap.setDisplayName(\"DOAS Direct Evaporative Cooling?\")\n\t\tdoas_evap.setDefaultValue(\"none\")\n\t\targs << doas_evap\n\t\t\n\t\t# DOAS DX Cooling\n\t\tdoas_dx_eer = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"doas_dx_eer\",false)\n\t\tdoas_dx_eer.setDisplayName(\"DOAS DX Cooling EER\")\n\t\tdoas_dx_eer.setDefaultValue(10.0)\n\t\targs << doas_dx_eer\n\t\n # make an argument for material and installation cost\n # todo - I would like to split the costing out to the air loops weighted by area of building served vs. just sticking it on the building\n cost_total_hvac_system = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"cost_total_hvac_system\",true)\n cost_total_hvac_system.setDisplayName(\"Total Cost for HVAC System ($).\")\n cost_total_hvac_system.setDefaultValue(0.0)\n args << cost_total_hvac_system\n \n #make an argument to remove existing costs\n remake_schedules = OpenStudio::Ruleset::OSArgument::makeBoolArgument(\"remake_schedules\",true)\n remake_schedules.setDisplayName(\"Apply recommended availability and ventilation schedules for air handlers?\")\n remake_schedules.setDefaultValue(true)\n args << remake_schedules\n\n return args\n end",
"def arguments()\r\n args = OpenStudio::Ruleset::OSArgumentVector.new\r\n\r\n # the name of the sql file\r\n csv_name = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_name\", true)\r\n csv_name.setDisplayName(\"CSV file name\")\r\n csv_name.setDescription(\"CSV file name.\")\r\n csv_name.setDefaultValue(\"mtr.csv\")\r\n args << csv_name\r\n \r\n csv_time_header = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_time_header\", true)\r\n csv_time_header.setDisplayName(\"CSV Time Header\")\r\n csv_time_header.setDescription(\"CSV Time Header Value.\")\r\n csv_time_header.setDefaultValue(\"Date/Time\")\r\n args << csv_time_header\r\n \r\n csv_var = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_var\", true)\r\n csv_var.setDisplayName(\"CSV variable name\")\r\n csv_var.setDescription(\"CSV variable name\")\r\n csv_var.setDefaultValue(\"Whole Building:Facility Total Electric Demand Power [W](TimeStep)\")\r\n args << csv_var\r\n \r\n csv_var_dn = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_var_dn\", true)\r\n csv_var_dn.setDisplayName(\"CSV variable display name\")\r\n csv_var_dn.setDescription(\"CSV variable display name\")\r\n csv_var_dn.setDefaultValue(\"\")\r\n args << csv_var_dn\r\n \r\n years = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"year\", true)\r\n years.setDisplayName(\"Year in csv data\")\r\n years.setDescription(\"Year in csv data => mm:dd:yy or mm:dd\")\r\n years.setDefaultValue(true)\r\n args << years\r\n \r\n seconds = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"seconds\", true)\r\n seconds.setDisplayName(\"Seconds in csv data\")\r\n seconds.setDescription(\"Seconds in csv data => hh:mm:ss or hh:mm\")\r\n seconds.setDefaultValue(true)\r\n args << seconds\r\n \r\n sql_key = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"sql_key\", true)\r\n sql_key.setDisplayName(\"SQL key\")\r\n sql_key.setDescription(\"SQL key\")\r\n sql_key.setDefaultValue(\"\")\r\n args << sql_key \r\n\r\n sql_var = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"sql_var\", true)\r\n sql_var.setDisplayName(\"SQL var\")\r\n sql_var.setDescription(\"SQL var\")\r\n sql_var.setDefaultValue(\"Facility Total Electric Demand Power\")\r\n args << sql_var \r\n \r\n stp = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"stp\", true)\r\n stp.setDisplayName(\"Timeseries Timestep\")\r\n stp.setDescription(\"Timeseries Timestep\")\r\n stp.setDefaultValue(\"Zone Timestep\")\r\n args << stp\r\n \r\n env = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"env\", true)\r\n env.setDisplayName(\"availableEnvPeriods\")\r\n env.setDescription(\"availableEnvPeriods\")\r\n env.setDefaultValue(\"RUN PERIOD 1\")\r\n args << env\r\n \r\n norm = OpenStudio::Ruleset::OSArgument.makeDoubleArgument(\"norm\", true)\r\n norm.setDisplayName(\"norm of the difference of csv and sql\")\r\n norm.setDescription(\"norm of the difference of csv and sql\")\r\n norm.setDefaultValue(1)\r\n args << norm \r\n\r\n scale = OpenStudio::Ruleset::OSArgument.makeDoubleArgument(\"scale\", true)\r\n scale.setDisplayName(\"scale factor to apply to the difference\")\r\n scale.setDescription(\"scale factor to apply to the difference\")\r\n scale.setDefaultValue(1)\r\n args << scale \r\n\r\n find_avail = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"find_avail\", true)\r\n find_avail.setDisplayName(\"find_avail\")\r\n find_avail.setDescription(\"find_avail\")\r\n find_avail.setDefaultValue(true)\r\n args << find_avail \r\n\r\n compute_diff = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"compute_diff\", true)\r\n compute_diff.setDisplayName(\"compute_diff\")\r\n compute_diff.setDescription(\"compute_diff\")\r\n compute_diff.setDefaultValue(true)\r\n args << compute_diff\r\n \r\n verbose_messages = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"verbose_messages\", true)\r\n verbose_messages.setDisplayName(\"verbose_messages\")\r\n verbose_messages.setDescription(\"verbose_messages\")\r\n verbose_messages.setDefaultValue(true)\r\n args << verbose_messages \r\n \r\n algorithm_download = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"algorithm_download\", true)\r\n algorithm_download.setDisplayName(\"algorithm_download\")\r\n algorithm_download.setDescription(\"algorithm_download\")\r\n algorithm_download.setDefaultValue(false)\r\n args << algorithm_download \r\n \r\n plot_flag = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"plot_flag\", true)\r\n plot_flag.setDisplayName(\"plot_flag timeseries data\")\r\n plot_flag.setDescription(\"plot_flag timeseries data\")\r\n plot_flag.setDefaultValue(true)\r\n args << plot_flag\r\n \r\n plot_name = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"plot_name\", true)\r\n plot_name.setDisplayName(\"Plot name\")\r\n plot_name.setDescription(\"Plot name\")\r\n plot_name.setDefaultValue(\"\")\r\n args << plot_name\r\n \r\n warning_messages = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"warning_messages\", true)\r\n warning_messages.setDisplayName(\"warning_messages\")\r\n warning_messages.setDescription(\"warning_messages\")\r\n warning_messages.setDefaultValue(false)\r\n args << warning_messages\r\n\r\n return args\r\n end",
"def arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n # the name of the space to add to the model\n setpoint = OpenStudio::Ruleset::OSArgument.makeDoubleArgument(\"setpoint_temperature\", true)\n setpoint.setUnits(\"Degrees Celsius\")\n setpoint.setDisplayName(\"Ambient Loop Temperature\")\n setpoint.setDefaultValue(20)\n setpoint.setDescription(\"Temperature setpoint for the ambient loop\")\n args << setpoint\n\n delta = OpenStudio::Ruleset::OSArgument.makeDoubleArgument(\"design_delta\", true)\n delta.setUnits(\"Delta Temperature\")\n delta.setDefaultValue(5.55) # 10 Deg F default delta\n delta.setDisplayName(\"Delta Design Loop Temperature\")\n delta.setDescription(\"Delta design temperature for the ambient loop\")\n args << delta\n\n return args\n end",
"def arguments\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n return args\n end",
"def print_two_again(arg1, arg2) # Non-variable list of inputs it will accept\n puts \"arg1: #{arg1}, arg2: #{arg2}\"\nend",
"def commander _args\n \"commander _args;\" \n end",
"def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\n\n # make a string argument for furnace fuel type\n fuel_display_names = OpenStudio::StringVector.new\n fuel_display_names << Constants.FuelTypeGas\n fuel_display_names << Constants.FuelTypeOil\n fuel_display_names << Constants.FuelTypePropane\n fuel_display_names << Constants.FuelTypeElectric\n fuel_type = OpenStudio::Measure::OSArgument::makeChoiceArgument('fuel_type', fuel_display_names, true)\n fuel_type.setDisplayName('Fuel Type')\n fuel_type.setDescription('Type of fuel used for heating.')\n fuel_type.setDefaultValue(Constants.FuelTypeGas)\n args << fuel_type\n\n # make an argument for entering furnace installed afue\n afue = OpenStudio::Measure::OSArgument::makeDoubleArgument('afue', true)\n afue.setDisplayName('Installed AFUE')\n afue.setUnits('Btu/Btu')\n afue.setDescription('The installed Annual Fuel Utilization Efficiency (AFUE) of the furnace, which can be used to account for performance derating or degradation relative to the rated value.')\n afue.setDefaultValue(0.78)\n args << afue\n\n # make an argument for entering furnace installed supply fan power\n fan_power_installed = OpenStudio::Measure::OSArgument::makeDoubleArgument('fan_power_installed', true)\n fan_power_installed.setDisplayName('Installed Supply Fan Power')\n fan_power_installed.setUnits('W/cfm')\n fan_power_installed.setDescription('Fan power (in W) per delivered airflow rate (in cfm) of the indoor fan for the maximum fan speed under actual operating conditions.')\n fan_power_installed.setDefaultValue(0.5)\n args << fan_power_installed\n\n # make a string argument for furnace heating output capacity\n capacity = OpenStudio::Measure::OSArgument::makeStringArgument('capacity', true)\n capacity.setDisplayName('Heating Capacity')\n capacity.setDescription(\"The output heating capacity of the furnace. If using '#{Constants.SizingAuto}', the autosizing algorithm will use ACCA Manual S to set the capacity.\")\n capacity.setUnits('kBtu/hr')\n capacity.setDefaultValue(Constants.SizingAuto)\n args << capacity\n\n # make a string argument for distribution system efficiency\n dse = OpenStudio::Measure::OSArgument::makeStringArgument('dse', true)\n dse.setDisplayName('Distribution System Efficiency')\n dse.setDescription('Defines the energy losses associated with the delivery of energy from the equipment to the source of the load.')\n dse.setDefaultValue('NA')\n args << dse\n\n # make a bool argument for open hvac flue\n has_hvac_flue = OpenStudio::Measure::OSArgument::makeBoolArgument('has_hvac_flue', true)\n has_hvac_flue.setDisplayName('Air Leakage: Has Open HVAC Flue')\n has_hvac_flue.setDescription('Specifies whether the building has an open flue associated with the HVAC system.')\n has_hvac_flue.setDefaultValue(true)\n args << has_hvac_flue\n\n return args\n end",
"def args\n @args\n end",
"def default_args(a,b,c=1)\n puts \"\\nValues of variables: \",a,b,c\nend",
"def arguments\n args = OpenStudio::Measure::OSArgumentVector.new\n\n return args\n end",
"def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\n \n \t#Make a string argument for 24 weekday cooling set point values\n clg_wkdy = OpenStudio::Measure::OSArgument::makeStringArgument(\"clg_wkdy\", false)\n clg_wkdy.setDisplayName(\"Weekday Setpoint\")\n clg_wkdy.setDescription(\"Specify a single cooling setpoint or a 24-hour comma-separated cooling schedule for the weekdays.\")\n clg_wkdy.setUnits(\"degrees F\")\n clg_wkdy.setDefaultValue(\"76\")\n args << clg_wkdy \n \n \t#Make a string argument for 24 weekend cooling set point values\n clg_wked = OpenStudio::Measure::OSArgument::makeStringArgument(\"clg_wked\", false)\n clg_wked.setDisplayName(\"Weekend Setpoint\")\n clg_wked.setDescription(\"Specify a single cooling setpoint or a 24-hour comma-separated cooling schedule for the weekend.\")\n clg_wked.setUnits(\"degrees F\")\n clg_wked.setDefaultValue(\"76\")\n args << clg_wked\t\n\t\n return args\n end",
"def arguments\n args = OpenStudio::Measure::OSArgumentVector.new\n # this measure does not require any user arguments, return an empty list\n return args\n end"
] |
[
"0.73748195",
"0.73748195",
"0.73748195",
"0.7087363",
"0.7008232",
"0.7008232",
"0.7008232",
"0.7008232",
"0.7008232",
"0.7008232",
"0.7008232",
"0.7008232",
"0.7008232",
"0.7008232",
"0.7008232",
"0.7008232",
"0.7008232",
"0.7008232",
"0.7008232",
"0.7008232",
"0.7008232",
"0.7008232",
"0.7008232",
"0.7008232",
"0.682961",
"0.6826167",
"0.6759192",
"0.6747159",
"0.6589147",
"0.6579065",
"0.65786225",
"0.6544587",
"0.6501246",
"0.64746875",
"0.64696026",
"0.64695764",
"0.6468071",
"0.64624786",
"0.6409045",
"0.6388565",
"0.6377955",
"0.6372687",
"0.6372046",
"0.63623196",
"0.63580847",
"0.634898",
"0.63470536",
"0.6346329",
"0.6328366",
"0.6327314",
"0.6293709",
"0.6288431",
"0.6271303",
"0.6256699",
"0.62562937",
"0.6239551",
"0.62357897",
"0.62354136",
"0.62218416",
"0.62218416",
"0.62218416",
"0.6203231",
"0.6194215",
"0.6180256",
"0.61709577",
"0.6168221",
"0.6167057",
"0.6164105",
"0.61599123",
"0.61444277",
"0.612839",
"0.6116114",
"0.6098567",
"0.608949",
"0.60889053",
"0.60807997",
"0.6075578",
"0.60739285",
"0.60689557",
"0.60689074",
"0.60529596",
"0.6047003",
"0.6036175",
"0.6036175",
"0.60353076",
"0.6028083",
"0.6026514",
"0.60262996",
"0.602028",
"0.60061544",
"0.6004837",
"0.5999588",
"0.5995959",
"0.59910905",
"0.5985314",
"0.5982308",
"0.5973571",
"0.5967936",
"0.59673434",
"0.5966534",
"0.5957761"
] |
0.0
|
-1
|
define what happens when the measure is run
|
def run(model, runner, user_arguments)
super(model, runner, user_arguments)
# use the built-in error checking
if !runner.validateUserArguments(arguments(model), user_arguments)
return false
end
# report initial condition of model
runner.registerInitialCondition("The building started with #{model.getThermalZones.size} thermal zones.")
# loop through spaces
model.getSpaces.sort.each do |space|
# if space doesn't have zone, then add, rename and assign
if !space.thermalZone.is_initialized
zone = OpenStudio::Model::ThermalZone.new(model)
zone.setName("Zone - #{space.name.get}")
space.setThermalZone(zone)
runner.registerInfo("Assigning #{space.name} to new thermal zone named #{zone.name}")
end
end
# report final condition of model
runner.registerFinalCondition("The building finished with #{model.getThermalZones.size} thermal zones.")
return true
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def measure; end",
"def measure=(_arg0); end",
"def measure\n\t\t1\n\tend",
"def measure(*args, &b)\n end",
"def communicate_measure_result(_ = nil, _ = nil); end",
"def communicate_measure_result(_ = nil, _ = nil); end",
"def called\n self.measurement.called\n end",
"def measure\n start = Time.now\n yield\n Time.now - start\n end",
"def measure\n start = Time.now\n yield\n Time.now - start\n end",
"def measure\n Measure.new(1, self)\n end",
"def measurement(n)\n @options[:before_hook].call(n)\n measure = measure(n, &@options[:fn])\n @options[:after_hook].call(n)\n measure\n end",
"def measure\n Measure.new(@counter+=1)\n end",
"def communicate_measure_result(_ = nil, _ = nil)\r\n end",
"def benchmark\nend",
"def calculated; end",
"def setup_metrics\n end",
"def setup_metrics\n end",
"def setup_metrics\n end",
"def run()\n\t\tputs \"#{@name} ran for #{@meters} meters in #{self.getTimeLapse} seconds\"\n\t\t# chiama funzione per stampare quante volte ha respirato\n\t\tself.breathe\n\tend",
"def runs; end",
"def statistics; end",
"def medical_use; end",
"def measure\n start_real = System.monotonic_time\n start_cpu = System.cpu_time\n retval = yield\n\n real_time = System.monotonic_time - start_real\n cpu_time = System.cpu_time - start_cpu\n\n @real_time += real_time\n @cpu_time += cpu_time\n @call_count += 1\n\n if call_measurement_enabled? && above_threshold?\n self.class.call_duration_histogram.observe(@transaction.labels.merge(labels), real_time / 1000.0)\n end\n\n retval\n end",
"def stats; end",
"def stats; end",
"def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n # Return N/A if not selected to run\n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\n if run_measure == 0\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\n return true \n end \n \n\n percent_runtime_reduction = runner.getDoubleArgumentValue(\"percent_runtime_reduction\",user_arguments)\n\n \n \n # Check arguments for reasonableness\n if percent_runtime_reduction >= 100\n runner.registerError(\"Percent runtime reduction must be less than 100.\")\n return false\n end\n\n # Find all the original schedules (before occ sensors installed)\n original_lts_schedules = []\n model.getLightss.each do |light_fixture|\n if light_fixture.schedule.is_initialized\n original_lts_schedules << light_fixture.schedule.get\n end\n end \n\n # Make copies of all the original lights schedules, reduced to include occ sensor impact\n original_schs_new_schs = {}\n original_lts_schedules.uniq.each do |orig_sch|\n # Copy the original schedule\n new_sch = orig_sch.clone.to_ScheduleRuleset.get\n new_sch.setName(\"#{new_sch.name.get} with occ sensor\")\n # Reduce each value in each profile (except the design days) by the specified amount\n runner.registerInfo(\"Reducing values in '#{orig_sch.name}' schedule by #{percent_runtime_reduction}% to represent occ sensor installation.\")\n day_profiles = []\n day_profiles << new_sch.defaultDaySchedule\n new_sch.scheduleRules.each do |rule|\n day_profiles << rule.daySchedule\n end\n multiplier = (100 - percent_runtime_reduction)/100\n day_profiles.each do |day_profile|\n #runner.registerInfo(\"#{day_profile.name}\")\n times_vals = day_profile.times.zip(day_profile.values)\n #runner.registerInfo(\"original time/values = #{times_vals}\")\n times_vals.each do |time,val|\n day_profile.addValue(time, val * multiplier)\n end\n #runner.registerInfo(\"new time/values = #{day_profile.times.zip(day_profile.values)}\")\n end \n #log the relationship between the old sch and the new, reduced sch\n original_schs_new_schs[orig_sch] = new_sch\n end\n \n # Replace the old schedules with the new, reduced schedules\n spaces_sensors_added_to = []\n model.getLightss.each do |light_fixture|\n next if light_fixture.schedule.empty?\n lights_sch = light_fixture.schedule.get\n new_sch = original_schs_new_schs[lights_sch]\n if new_sch\n runner.registerInfo(\"Added occupancy sensor for '#{light_fixture.name}'\")\n light_fixture.setSchedule(new_sch)\n spaces_sensors_added_to << light_fixture.space\n end\n end\n \n # Report if the measure is not applicable\n num_sensors_added = spaces_sensors_added_to.uniq.size\n if spaces_sensors_added_to.size == 0\n runner.registerAsNotApplicable(\"This measure is not applicable because there were no lights in the building.\")\n return true\n end \n \n # Report final condition\n runner.registerFinalCondition(\"Added occupancy sensors to #{num_sensors_added} spaces in the building.\")\n\n return true\n\n end",
"def run\n\t\t\tsummary\n\t\tend",
"def quick_stats\n\tend",
"def stats\n \n end",
"def benchmark(reporter); end",
"def stats\n end",
"def stats\n end",
"def measure(name, &block)\n if self.running? name\n yield\n else\n result = nil\n self.results[name] ||= 0\n self.running << name\n self.results[name] += Benchmark.measure{result = yield}.real\n self.running.delete(name)\n result\n end\n end",
"def measure\n start_real = System.monotonic_time\n start_cpu = System.cpu_time\n retval = yield\n\n real_time = System.monotonic_time - start_real\n cpu_time = System.cpu_time - start_cpu\n\n @real_time += real_time\n @cpu_time += cpu_time\n @call_count += 1\n\n if above_threshold?\n self.class.gitlab_method_call_duration_seconds.observe(@transaction.labels.merge(labels), real_time)\n end\n\n retval\n end",
"def measure_code(model,runner)\n measure_folder = \"#{File.dirname(__FILE__)}/\"\n baseline_spreadsheet = \"#{File.dirname(__FILE__)}/baseline.csv\"\n #Note: place output folder locally to run faster! (e.g. your C drive)\n output_folder = \"#{File.dirname(__FILE__)}/tests/output\"\n create_models = true\n simulate_models = true\n create_annual_outputs = true\n create_hourly_outputs = true\n #This creates the measures object and collects all the csv information for the\n # measure_id variant.\n csv_measures = BTAP::Measures::CSV_OS_Measures.new(\n baseline_spreadsheet,\n measure_folder#script root folder where all the csv relative paths are used.\n )\n csv_measures.create_cold_lake_vintages(output_folder) unless create_models == false\n BTAP::SimManager::simulate_all_files_in_folder(output_folder) unless simulate_models == false\n BTAP::Reporting::get_all_annual_results_from_runmanger(output_folder) unless create_annual_outputs == false\n #convert eso to csv then create terminus file.\n BTAP::FileIO::convert_all_eso_to_csv(output_folder, output_folder).each {|csvfile| BTAP::FileIO::terminus_hourly_output(csvfile)} unless create_hourly_outputs == false\n\n end",
"def cpu_metrics\n super\n end",
"def instrument; end",
"def profiler; end",
"def profiler; end",
"def setup\n\t\n # create an instance of the measure\n @measure = VentilationQAQC.new\n \n #create an instance of the runner\n @runner = OpenStudio::Ruleset::OSRunner.new\t\n\t\n # get arguments \n @arguments = @measure.arguments()\n\n # make argument map\n make_argument_map\n\t\n # Make an empty model\n @model = OpenStudio::Model::Model.new\n\t@runner.setLastOpenStudioModel(@model)\n\t\n\t# Create a fake sql file - our measure will crash if @runner has no sql file set.\n\t# We don't get data from this file because we get data from our patched SqlFile class instead (see above)\n\tsqlFile = OpenStudio::SqlFile.new(OpenStudio::Path.new(sqlPath))\n\t@runner.setLastEnergyPlusSqlFilePath(OpenStudio::Path.new(sqlPath))\n\t\n\t$serieses[\"Zone Mechanical Ventilation Mass Flow Rate|ZONE1\"] = OpenStudio::TimeSeries.new(OpenStudio::Date.new, OpenStudio::Time.new(1.0), (0..364).to_a.to_vector, \"m^3/s\")\n end",
"def monitor(*args, &bl)\n result = nil\n took = Benchmark.realtime {\n result = bl.call\n }\n Tools.info(args, op_took: took)\n result\n end",
"def measure_code(model,runner)\n ################ Start Measure code here ################################\n \n #Check weather directory Weather File\n unless (Pathname.new @lib_directory).absolute?\n @lib_directory = File.expand_path(File.join(File.dirname(__FILE__), @lib_directory))\n end\n lib_file = File.join(@lib_directory, @lib_file_name)\n if File.exists?(lib_file) and @lib_file_name.downcase.include? \".osm\"\n BTAP::runner_register(\"Info\",\"#{@lib_file_name} Found!.\", runner)\n else\n BTAP::runner_register(\"Error\",\"#{lib_file} does not exist or is not an .osm file.\", runner)\n return false\n end\n \n #load model and test.\n construction_set = BTAP::Resources::Envelope::ConstructionSets::get_construction_set_from_library( lib_file, @construction_set_name )\n #Set Construction Set.\n unless model.building.get.setDefaultConstructionSet( construction_set.clone( model ).to_DefaultConstructionSet.get )\n BTAP::runner_register(\"Error\",\"Could not set Default Construction #{@construction_set_name} \", runner)\n return false\n end\n BTAP::runner_register(\"FinalCondition\",\"Default Construction set to #{@construction_set_name} from #{lib_file}\",runner)\n ##########################################################################\n return true\n end",
"def run(workspace, runner, user_arguments)\n super(workspace, runner, user_arguments)\n\n # use the built-in error checking \n if !runner.validateUserArguments(arguments(workspace), user_arguments)\n return false\n end\n \n # Report that this is an anti-measure\n runner.registerValue('anti_measure',true) \n \n # Return N/A if not selected to run\n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\n if run_measure == 0\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\n return true \n end\n \n\t# Initialize counter variables\n\tno_economizer = 0\n\tfixed_dry_bulb = 0\n\tdifferential_dry_bulb = 0\t\n\tfixed_enthalpy = 0\n\tdifferential_enthalpy = 0\n\tfixed_dew_point_and_dry_bulb = 0\n\telectronic_enthalpy = 0\n\tdifferential_dry_bulb_and_enthalpy = 0\n\t\n\t# Retrieve all Controller:Outdoor air objects in the idf \t\n\toa_controllers = workspace.getObjectsByType(\"Controller:OutdoorAir\".to_IddObjectType)\n\t\n\t# Get the names of each Controller:Outdoor Air object\n\toa_controllers.each do |oa_controller|\n\n\t\toa_controller_name = oa_controller.getString(0).to_s #(0) is field Name\n\t\toa_controller_economizer_control_type = oa_controller.getString(7).to_s #(7) is field Economizer Control Type\n\t\n\t\t# test for presence No economizer controller setting \n\t\tif oa_controller_economizer_control_type == \"NoEconomizer\" # or empty\n\t\t\trunner.registerInfo(\"The Controller:Outdoor air object named #{oa_controller_name} has a disabled airside economizer. Economizer sensor faults will not be added.\")\n\t\t\tno_economizer = no_economizer + 1\n\t\tend\n\t\t\n\t\t# test for presence of differential dry bulb economizer controller setting \n\t\tif oa_controller_economizer_control_type == \"DifferentialDryBulb\"\n\t\t\t# Initialize array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:TemperatureSensorOffset:OutdoorAir \n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:TemperatureSensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Temp Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t1.11; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\n\t\t\t# Create IDF object text for FaultModel:TemperatureSensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:TemperatureSensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Temp Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-1.11; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\tdifferential_dry_bulb = differential_dry_bulb + 1\n\t\t\t# info message\n\t\t\trunner.registerInfo(\"To model dry bulb sensor drift, a FaultModel:TemperatureSensorOffset:ReturnAir object with an offset of -2 deg F and a FaultModel:TemperatureSensorOffset:OutdoorAir object with an offset of +2 deg F has been added to the #{oa_controller_economizer_control_type} controlled airside economizer associated with the Controller:Outdoor air object named #{oa_controller_name}. The fault availability is scheduled using the 'Always On Discrete' schedule.\")\n\t\t\t\n\n\t\tend # OA Controller Type DifferentialDryBulb\n\n\t\t# test for presence of fixed dry bulb economizer controller setting \n\t\tif oa_controller_economizer_control_type == \"FixedDryBulb\"\n\t\t\t# Initialize array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:TemperatureSensorOffset:OutdoorAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:TemperatureSensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Temp Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t1.11; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\t# Create IDF object text for FaultModel:TemperatureSensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:TemperatureSensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Temp Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-1.11; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\trunner.registerInfo(\"To model dry bulb sensor drift, a FaultModel:TemperatureSensorOffset:ReturnAir object with an offset of -2 deg F and a FaultModel:TemperatureSensorOffset:OutdoorAir object with an offset of +2 deg F has been added to the #{oa_controller_economizer_control_type} controlled airside economizer associated with the Controller:Outdoor air object named #{oa_controller_name}. The fault availability is scheduled using the 'Always On Discrete' schedule.\")\n\t\t\tfixed_dry_bulb = fixed_dry_bulb + 1\n\t\t\t\n\t\tend # OA Controller Type = FixedDryBulb \t\t\n\t\t\n\t\t# test for presence of fixed enthalpy economizer controller setting \t\t\t\t\n\t\tif oa_controller_economizer_control_type == \"FixedEnthalpy\"\n\t\t\t# Initialze array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:OutdoorAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t5; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-5; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\twworkspace.addObject(object)\n\n\t\t\trunner.registerInfo(\"To model enthalpy sensor drift, a FaultModel:EnthalpySensorOffset:ReturnAir object with an offset of -2 Btu/lb and a FaultModel:EnthalpySensorOffset:OutdoorAir object with an offset of +2 Btu/lb have been added to the #{oa_controller_economizer_control_type} controlled airside economizer associated with the Controller:Outdoor air object named #{oa_controller_name}. The fault availability is scheduled using the 'Always On Discrete' schedule.\")\n\t\t\tfixed_enthalpy = fixed_enthalpy + 1\n\t\tend # OA Controller Type = FixedEnthalpy \n\t\t\n\t\t# test for presence of differential enthalpy economizer controller setting \t\t\n\t\tif oa_controller_economizer_control_type == \"DifferentialEnthalpy\"\n\t\t\t# Initialze array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:OutdoorAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t5; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-5; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\n\t\t\trunner.registerInfo(\"To model enthalpy sensor drift, a FaultModel:EnthalpySensorOffset:ReturnAir object with an offset of -2 Btu/lb and a FaultModel:EnthalpySensorOffset:OutdoorAir object with an offset of +2 Btu/lb have been added to the #{oa_controller_economizer_control_type} controlled airside economizer associated with the Controller:Outdoor air object named #{oa_controller_name}. The fault availability is scheduled using the 'Always On Discrete' schedule.\")\n\t\t\tdifferential_enthalpy = differential_enthalpy + 1\n\t\t\t\n\t\tend # OA Controller Type =\"Differential Enthalpy\"\t\t\n\t\t\n\t\n\t\t# test for presence of electronic enthalpy economizer controller setting \n\t\tif oa_controller_economizer_control_type == \"ElectronicEnthalpy\"\n\t\t\t# Initialze array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:OutdoorAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t5; \t\t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-5; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\n\t\t\trunner.registerInfo(\"To model enthalpy sensor drift, a FaultModel:EnthalpySensorOffset:ReturnAir object with an offset of -2 Btu/lb and a FaultModel:EnthalpySensorOffset:OutdoorAir object with an offset of +2 Btu/lb have been added to the #{oa_controller_economizer_control_type} controlled airside economizer associated with the Controller:Outdoor air object named #{oa_controller_name}. The fault availability is scheduled using the 'Always On Discrete' schedule.\")\n\t\t\telectronic_enthalpy = electronic_enthalpy + 1\n\n\t\tend # OA Controller Type = \"ElectronicEnthalpy\" \t\t\n\t\t\n\t\t# test for presence of fixed dew point and dry bulb economizer controller setting \n\t\tif oa_controller_economizer_control_type == \"FixedDewPointAndDryBulb\" \n\t\t\t# Initialze array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:OutdoorAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t5; \t\t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-5; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\t# Initialize array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:TemperatureSensorOffset:OutdoorAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:TemperatureSensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Temp Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t1.11; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\t# Create IDF object text for FaultModel:TemperatureSensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:TemperatureSensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Temp Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-1.11; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\n\t\t\trunner.registerInfo(\"To model both enthalpy and dry bulb sensor drift, a FaultModel:EnthalpySensorOffset:ReturnAir object with an offset of -2 Btu/lb and a FaultModel:EnthalpySensorOffset:OutdoorAir object with an offset of +2 Btu/lb and a FaultModel:TemperatureSensorOffset:ReturnAir object with an offset of -2 deg F and a FaultModel:TemperatureSensorOffset:OutdoorAir object with an offset of +2 deg have been added to the #{oa_controller_economizer_control_type} controlled airside economizer associated with the Controller:Outdoor air object named #{oa_controller_name}. The fault availability is scheduled using the 'Always On Discrete' schedule.\")\n\t\t\tfixed_dew_point_and_dry_bulb = fixed_dew_point_and_dry_bulb + 1\n\n\t\tend # OA Controller Type = \"FixedDewPointAndDryBulb\" \n\t\n\t\t# test for presence of differential dry bulb and enthalpy economizer controller setting \t\t\n\t\tif oa_controller_economizer_control_type == \"DifferentialDryBulbAndEnthalpy\"\n\t\t\t# Initialze array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:OutdoorAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t5; \t\t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-5; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\t# Initialize array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:TemperatureSensorOffset:OutdoorAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:TemperatureSensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Temp Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t1.11; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\t\t\t\n\t\t\t# Create IDF object text for FaultModel:TemperatureSensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:TemperatureSensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Temp Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-1.11; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\n\t\t\trunner.registerInfo(\"To model both enthalpy and dry bulb sensor drift, a FaultModel:EnthalpySensorOffset:ReturnAir object with an offset of -2 Btu/lb and a FaultModel:EnthalpySensorOffset:OutdoorAir object with an offset of +2 Btu/lb and a FaultModel:TemperatureSensorOffset:ReturnAir object with an offset of -2 deg F and a FaultModel:TemperatureSensorOffset:OutdoorAir object with an offset of +2 deg have been added to the #{oa_controller_economizer_control_type} controlled airside economizer associated with the Controller:Outdoor air object named #{oa_controller_name}. The fault availability is scheduled using the 'Always On Discrete' schedule.\")\n\t\t\tdifferential_dry_bulb_and_enthalpy = differential_dry_bulb_and_enthalpy + 1\n\t\tend # OA Controller Type \"DifferentialDryBulbAndEnthalpy\"\n\t\t\n\t\t\t\t\n\tend # end loop through oa controller objects\n\n\t# reporting when N/A condition is appropriate\n\tif fixed_dry_bulb +\tdifferential_dry_bulb + fixed_enthalpy + differential_enthalpy + fixed_dew_point_and_dry_bulb +\telectronic_enthalpy + differential_dry_bulb_and_enthalpy == 0\n\t\trunner.registerAsNotApplicable(\"Measure not applicable because the model contains no OutdoorAir:Controller objects with operable economizers.\")\n\tend \n\t\n\ttotal = fixed_dry_bulb + differential_dry_bulb + fixed_enthalpy + differential_enthalpy + fixed_dew_point_and_dry_bulb + electronic_enthalpy + differential_dry_bulb_and_enthalpy\n\t\n\t# reporting initial condition of model\n\trunner.registerInitialCondition(\"The measure started with #{total} Outdoor Air Controllers configured for operational airside economizers. #{no_economizer} Outdoor Air Controller had the Economizer Contrrol Type set to 'NoEconomizer'.\")\n\t# reporting final condition of model\n\trunner.registerFinalCondition(\"The measure finished by adding outdoor and return air temperature and enthalpy sensor faults to #{total} economizer configurations.\")\n \n return true\n \n end",
"def calculation\n end",
"def monitor; end",
"def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # Return N/A if not selected to run\n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\n if run_measure == 0\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\n return true \n end \n \n # initialize variables\n affected_space_types = []\n affected_flag = false\n power_tot = 0\n power_tot_new = 0\n control_factor = 0.05 #90.1-2010 Table 9.6.2\n\n # standards space types\n affected_space_types << \"BreakRoom\"\n affected_space_types << \"Conference\"\n affected_space_types << \"Office\"\n affected_space_types << \"Restroom\"\n affected_space_types << \"Stair\"\n\n # get model objects\n space_types = model.getSpaceTypes\n\n # DO STUFF\n #TODO account for zone multipliers?\n space_types.each do |st|\n\n std_spc_typ = st.standardsSpaceType.to_s\n area = st.floorArea\n people = st.getNumberOfPeople(area)\n power = st.getLightingPower(area, people)\n power_tot += power\n\n #calcualte LPD\n lpd_area = power / area\n lpd_people = power / people\n\n affected_space_types.each do |ast|\n\n if ast == std_spc_typ\n\n #calculate adjustment and new power\n power_adj = power * control_factor\n power_new = power - power_adj\n\n lpd_area_new = power_new / area\n lpd_people_new = power_new / people\n\n #set new power\n if st.lightingPowerPerFloorArea.is_initialized\n\n runner.registerInfo(\"Adjusting interior lighting power for space type: #{st.name}\")\n st.setLightingPowerPerFloorArea(lpd_area_new)\n\n lpd_area_ip = OpenStudio.convert(lpd_area,\"ft^2\",\"m^2\").get\n lpd_area_new_ip = OpenStudio.convert(lpd_area_new,\"ft^2\",\"m^2\").get\n lpd_area_change = (1 - (lpd_area_new / lpd_area)) * 100\n\n runner.registerInfo(\"=> Initial interior lighting power = #{lpd_area_ip.round(2)} W/ft2\")\n runner.registerInfo(\"=> Final interior lighting power = #{lpd_area_new_ip.round(2)} W/ft2\")\n runner.registerInfo(\"=> Interior lighting power reduction = #{lpd_area_change.round(0)}%\")\n\n elsif st.lightingPowerPerPerson.is_initialized\n\n runner.registerInfo(\"Adjusting interior lighting power for space type: #{st.name}\")\n st.setLightingPowerPerPerson(lpd_people_new)\n\n lpd_people_change = (1 - (lpd_people_new / lpd_people)) * 100\n\n runner.registerInfo(\"=> Initial interior lighting power = #{lpd_people} W/person\")\n runner.registerInfo(\"=> Final interior lighting power = #{lpd_people_new} W/person\")\n runner.registerInfo(\"=> Interior lighting power reduction = #{lpd_people_change.round(0)}%\")\n\n else\n\n runner.registerWarning(\"Lighting power is specified using Lighting Level (W) for affected space type: #{st.name}\")\n\n end #set new power\n\n affected_flag = true\n\n end\n\n end #affected space types\n\n # calculate new total lighting power\n power = st.getLightingPower(area, people)\n power_tot_new += power\n\n end #space types\n\n # report not applicable\n if affected_flag == false\n runner.registerAsNotApplicable(\"No affected space types found\")\n end\n\n # report initial condition\n runner.registerInitialCondition(\"Total interior lighting power = #{power_tot.round(0)} W\")\n\n # report final condition\n runner.registerFinalCondition(\"Total interior lighting power = #{power_tot_new.round(0)} W\")\n\n return true\n\n end",
"def measure key,value\n @context= {}\n @path = \"#{key}\" \n @context[:callcount] = 1\n @context[:firsttimestampoffset] = Time.now.to_f*1000 - value\n @context[:name] = @path\n @context[:responsetime] = value\n @context_list << @context\n end",
"def total_time=(_arg0); end",
"def run(workspace, runner, user_arguments)\n super(workspace, runner, user_arguments)\n\n #use the built-in error checking \n if not runner.validateUserArguments(arguments(workspace), user_arguments)\n return false\n end\n \n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\n if run_measure == 0\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\n return true \n end\n \n require 'json'\n \n # Get the last openstudio model\n model = runner.lastOpenStudioModel\n if model.empty?\n runner.registerError(\"Could not load last OpenStudio model, cannot apply measure.\")\n return false\n end\n model = model.get\n \n results = {}\n \n #get all DX coils in model\n dx_single = workspace.getObjectsByType(\"Coil:Cooling:DX:SingleSpeed\".to_IddObjectType)\n dx_two = workspace.getObjectsByType(\"Coil:Cooling:DX:TwoSpeed\".to_IddObjectType)\n \n dx_single.each do |dx|\n dx_name = {}\n coil_name = dx.getString(0).get\n runner.registerInfo(\"DX coil: #{coil_name} Initial COP: #{dx.getDouble(4).get}\")\n dx.setDouble(4,7.62)\n runner.registerInfo(\"DX coil: #{coil_name} Final COP: #{dx.getDouble(4).get}\")\n dx_name[:dxname] = \"#{coil_name}\"\n results[\"#{coil_name}\"] = dx_name\n end\n\n dx_two.each do |dx|\n dx_name = {}\n coil_name = dx.getString(0).get\n runner.registerInfo(\"DX coil: #{coil_name} Initial High COP: #{dx.getDouble(4).get}, Initial Low COP: #{dx.getDouble(16).get}\")\n dx.setDouble(4,7.62)\n dx.setDouble(16,7.62)\n runner.registerInfo(\"DX coil: #{coil_name} Final High COP: #{dx.getDouble(4).get}, Final Low COP: #{dx.getDouble(16).get}\")\n dx_name[:dxname] = \"#{coil_name}\"\n results[\"#{coil_name}\"] = dx_name\n end\n \n if results.empty?\n runner.registerWarning(\"No DX coils are appropriate for this measure\")\n runner.registerAsNotApplicable(\"No DX coils are appropriate for this measure\")\n end\n \n #save airloop parsing results to ems_results.json\n runner.registerInfo(\"Saving ems_results.json\")\n FileUtils.mkdir_p(File.dirname(\"ems_results.json\")) unless Dir.exist?(File.dirname(\"ems_results.json\"))\n File.open(\"ems_results.json\", 'w') {|f| f << JSON.pretty_generate(results)}\n \n if results.empty?\n runner.registerWarning(\"No DX coils are appropriate for this measure\")\n runner.registerAsNotApplicable(\"No DX coils are appropriate for this measure\")\n #save blank ems_membrane_heat_pump_cooling_only.ems file so Eplus measure does not crash\n ems_string = \"\"\n runner.registerInfo(\"Saving blank ems_membrane_heat_pump_cooling_only file\")\n FileUtils.mkdir_p(File.dirname(\"ems_membrane_heat_pump_cooling_only.ems\")) unless Dir.exist?(File.dirname(\"ems_membrane_heat_pump_cooling_only.ems\"))\n File.open(\"ems_membrane_heat_pump_cooling_only.ems\", \"w\") do |f|\n f.write(ems_string)\n end\n return true\n end\n \n timeStep = model.getTimestep.numberOfTimestepsPerHour\n \n runner.registerInfo(\"Making EMS string for Membrane Heat Pump Cooling Only\")\n #start making the EMS code\n ems_string = \"\" #clear out the ems_string\n ems_string << \"\\n\" \n ems_string << \"Output:Variable,*,Cooling Coil Sensible Cooling Energy,timestep; !- HVAC Sum [J]\" + \"\\n\"\n ems_string << \"\\n\" \n \n results.each_with_index do |(key, value), i| \n ems_string << \"EnergyManagementSystem:Sensor,\" + \"\\n\"\n ems_string << \" MembraneHP#{i+1}SensibleClgJ,\" + \"\\n\"\n ems_string << \" #{value[:dxname]},\" + \"\\n\"\n ems_string << \" Cooling Coil Sensible Cooling Energy;\" + \"\\n\"\n ems_string << \"\\n\" \n ems_string << \"WaterUse:Equipment,\" + \"\\n\"\n ems_string << \" MembraneHP#{i+1}WaterUse, !- Name\" + \"\\n\"\n ems_string << \" Membrane HP Cooling, !- End-Use Subcategory\" + \"\\n\"\n ems_string << \" 0.003155, !- Peak Flow Rate {m3/s} = 3000 gal/hr\" + \"\\n\"\n ems_string << \" MembraneHP#{i+1}WaterUseSchedule; !- Flow Rate Fraction Schedule Name\" + \"\\n\"\n ems_string << \"\\n\" \n ems_string << \"Schedule:Constant,\" + \"\\n\"\n ems_string << \" MembraneHP#{i+1}WaterUseSchedule, !- Name\" + \"\\n\"\n ems_string << \" , !- Schedule Type Limits Name\" + \"\\n\"\n ems_string << \" 1; !- Hourly Value\" + \"\\n\"\n ems_string << \"\\n\" \n ems_string << \"EnergyManagementSystem:Actuator,\" + \"\\n\"\n ems_string << \" MembraneHP#{i+1}WaterUseCtrl,\" + \"\\n\"\n ems_string << \" MembraneHP#{i+1}WaterUseSchedule,\" + \"\\n\"\n ems_string << \" Schedule:Constant,\" + \"\\n\"\n ems_string << \" Schedule Value;\" + \"\\n\"\n ems_string << \"\\n\" \n end\n ems_string << \"EnergyManagementSystem:ProgramCallingManager,\" + \"\\n\"\n ems_string << \" MembraneHPWaterUseProgramControl, !- Name\" + \"\\n\"\n ems_string << \" AfterPredictorBeforeHVACManagers, !- EnergyPlus Model Calling Point\" + \"\\n\"\n ems_string << \" MembraneHPWaterUseProgram; !- Program Name 1\" + \"\\n\"\n ems_string << \"\\n\"\n ems_string << \"EnergyManagementSystem:Program,\" + \"\\n\"\n ems_string << \" MembraneHPWaterUseProgram, !- Name\" + \"\\n\"\n ems_string << \" SET TimeStepsPerHr = #{timeStep}\" + \"\\n\"\n results.each_with_index do |(key, value), i|\n ems_string << \" SET MembraneHP#{i+1}SensibleClgTonHr = MembraneHP#{i+1}SensibleClgJ * 0.0000007898,\" + \"\\n\"\n ems_string << \" SET MembraneHP#{i+1}SensibleWtrGal = MembraneHP#{i+1}SensibleClgTonHr * 3.0,\" + \"\\n\"\n ems_string << \" SET MembraneHP#{i+1}SensibleWtrGalPerHr = MembraneHP#{i+1}SensibleWtrGal * TimeStepsPerHr,\" + \"\\n\"\n ems_string << \" SET MembraneHP#{i+1}WaterUseCtrl = MembraneHP#{i+1}SensibleWtrGalPerHr / 3000.0,\" + \"\\n\"\n end \n ems_string << \" SET UnusedLine = 0;\" + \"\\n\"\n \n #save EMS snippet\n runner.registerInfo(\"Saving ems_membrane_heat_pump_cooling_only file\")\n FileUtils.mkdir_p(File.dirname(\"ems_membrane_heat_pump_cooling_only.ems\")) unless Dir.exist?(File.dirname(\"ems_membrane_heat_pump_cooling_only.ems\"))\n File.open(\"ems_membrane_heat_pump_cooling_only.ems\", \"w\") do |f|\n f.write(ems_string)\n end\n \n #unique initial conditions based on\n runner.registerInitialCondition(\"The building has #{results.size} DX coils for which this measure is applicable.\")\n\n #reporting final condition of model\n runner.registerFinalCondition(\"The efficiency of the following coils was increased to SEER 26 to reflect the replacement of these coils with membrane heatpumps: #{results.keys}\")\n \n ems_path = '../MembraneHeatPumpCoolingOnly/ems_membrane_heat_pump_cooling_only.ems'\n json_path = '../MembraneHeatPumpCoolingOnly/ems_results.json'\n if File.exist? ems_path\n ems_string = File.read(ems_path)\n if File.exist? json_path\n json = JSON.parse(File.read(json_path))\n end\n else\n ems_path2 = Dir.glob('../../**/ems_membrane_heat_pump_cooling_only.ems')\n ems_path1 = ems_path2[0]\n json_path2 = Dir.glob('../../**/ems_results.json')\n json_path1 = json_path2[0]\n if ems_path2.size > 1\n runner.registerWarning(\"more than one ems_membrane_heat_pump_cooling_only.ems file found. Using first one found.\")\n end\n if !ems_path1.nil? \n if File.exist? ems_path1\n ems_string = File.read(ems_path1)\n if File.exist? json_path1\n json = JSON.parse(File.read(json_path1))\n else\n runner.registerError(\"ems_results.json file not located\") \n end \n else\n runner.registerError(\"ems_membrane_heat_pump_cooling_only.ems file not located\")\n end \n else\n runner.registerError(\"ems_membrane_heat_pump_cooling_only.ems file not located\") \n end\n end\n if json.nil?\n runner.registerError(\"ems_results.json file not located\")\n return false\n end\n \n if json.empty?\n runner.registerWarning(\"No DX coils are appropriate for this measure\")\n return true\n end\n \n idf_file = OpenStudio::IdfFile::load(ems_string, 'EnergyPlus'.to_IddFileType).get\n runner.registerInfo(\"Adding EMS code to workspace\")\n workspace.addObjects(idf_file.objects)\n \n return true\n\n end",
"def apply_measure_to_model(test_name, args, model_name = nil, result_value = 'Success', warnings_count = 0, info_count = nil)\n # create an instance of the measure\n measure = ChangeBuildingLocation.new\n\n # create an instance of a runner with OSW\n osw_path = OpenStudio::Path.new(File.dirname(__FILE__) + '/test.osw')\n osw = OpenStudio::WorkflowJSON.load(osw_path).get\n runner = OpenStudio::Measure::OSRunner.new(osw)\n\n # get model\n if model_name.nil?\n # make an empty model\n model = OpenStudio::Model::Model.new\n else\n # load the test model\n translator = OpenStudio::OSVersion::VersionTranslator.new\n path = OpenStudio::Path.new(File.dirname(__FILE__) + '/' + model_name)\n model = translator.loadModel(path)\n assert(!model.empty?)\n model = model.get\n end\n\n # get arguments\n arguments = measure.arguments(model)\n argument_map = OpenStudio::Measure.convertOSArgumentVectorToMap(arguments)\n\n # populate argument with specified hash value if specified\n arguments.each do |arg|\n temp_arg_var = arg.clone\n if args.key?(arg.name)\n assert(temp_arg_var.setValue(args[arg.name]))\n end\n argument_map[arg.name] = temp_arg_var\n end\n\n # temporarily change directory to the run directory and run the measure (because of sizing run)\n start_dir = Dir.pwd\n begin\n unless Dir.exist?(run_dir(test_name))\n Dir.mkdir(run_dir(test_name))\n end\n Dir.chdir(run_dir(test_name))\n\n # run the measure\n measure.run(model, runner, argument_map)\n result = runner.result\n ensure\n Dir.chdir(start_dir)\n\n # delete sizing run dir\n FileUtils.rm_rf(run_dir(test_name))\n end\n\n # show the output\n puts \"measure results for #{test_name}\"\n show_output(result)\n\n # assert that it ran correctly\n if result_value.nil? then result_value = 'Success' end\n assert_equal(result_value, result.value.valueName)\n\n # check count of warning and info messages\n unless info_count.nil? then assert(result.info.size == info_count) end\n unless warnings_count.nil? then assert(result.warnings.size == warnings_count) end\n\n # if 'Fail' passed in make sure at least one error message (while not typical there may be more than one message)\n if result_value == 'Fail' then assert(result.errors.size >= 1) end\n\n # save the model to test output directory\n output_file_path = OpenStudio::Path.new(File.dirname(__FILE__) + \"/output/#{test_name}_test_output.osm\")\n model.save(output_file_path, true)\n end",
"def measure_code(model,runner)\n ################ Start Measure code here ################################\n # Argument will be passed as instance variable. So if your argument was height, your can access it using @height. \n\n # report initial condition\n site = model.getSite\n initial_design_days = model.getDesignDays\n if site.weatherFile.is_initialized\n weather = site.weatherFile.get\n runner.registerInitialCondition(\"The initial weather file path was '#{weather.path.get}' and the model had #{initial_design_days.size} design days.\")\n else\n runner.registerInitialCondition(\"The initial weather file has not been set and the model had #{initial_design_days.size} design days.\")\n end\n\n\n #Check form weather directory Weather File\n unless (Pathname.new @weather_directory).absolute?\n @weather_directory = File.expand_path(File.join(File.dirname(__FILE__), @weather_directory))\n end\n weather_file = File.join(@weather_directory, @weather_file_name)\n if File.exists?(weather_file) and @weather_file_name.downcase.include? \".epw\"\n BTAP::runner_register(\"Info\", \"The epw weather file #{weather_file} was found!\", runner)\n else\n BTAP::runner_register(\"Error\",\"'#{weather_file}' does not exist or is not an .epw file.\", runner)\n return false\n end\n\n begin\n weather = BTAP::Environment::WeatherFile.new(weather_file)\n #Set Weather file to model.\n weather.set_weather_file(model)\n #Store information about this run in the runner for output. This will be in the csv and R dumps.\n runner.registerValue( 'city',weather.city )\n runner.registerValue( 'state_province_region ',weather.state_province_region )\n runner.registerValue( 'country',weather.country )\n runner.registerValue( 'hdd18',weather.hdd18 )\n runner.registerValue( 'cdd18',weather.cdd18 )\n runner.registerValue( 'necb_climate_zone',BTAP::Compliance::NECB2011::get_climate_zone_name(weather.hdd18).to_s)\n runner.registerFinalCondition( \"Model ended with weatherfile of #{model.getSite.weatherFile.get.path.get}\" )\n rescue\n BTAP::runner_register(\"Error\",\"'#{weather_file}' could not be loaded into model.\", runner)\n\n return false\n end\n BTAP::runner_register(\"FinalCondition\",\"Weather file set to #{weather_file}\",runner)\n return true\n end",
"def run(workspace, runner, user_arguments)\r\n super(workspace, runner, user_arguments)\r\n\r\n #use the built-in error checking \r\n if not runner.validateUserArguments(arguments(workspace), user_arguments)\r\n return false\r\n end\r\n \r\n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\r\n if run_measure == 0\r\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\r\n return true \r\n end\r\n \r\n require 'json'\r\n \r\n # Get the last openstudio model\r\n model = runner.lastOpenStudioModel\r\n if model.empty?\r\n runner.registerError(\"Could not load last OpenStudio model, cannot apply measure.\")\r\n return false\r\n end\r\n model = model.get\r\n \r\n results = {}\r\n #get all DX coils in model\r\n dx_single = model.getCoilCoolingDXSingleSpeeds \r\n dx_two = model.getCoilCoolingDXTwoSpeeds\r\n \r\n if !dx_single.empty?\r\n dx_single.each do |dx|\r\n dx_name = {}\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Initial COP: #{dx.ratedCOP.get}\")\r\n dx.setRatedCOP(OpenStudio::OptionalDouble.new(7.62))\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Final COP: #{dx.ratedCOP.get}\")\r\n dx_name[:dxname] = \"#{dx.name.get}\"\r\n results[\"#{dx.name.get}\"] = dx_name\r\n end\r\n end\r\n if !dx_two.empty?\r\n dx_two.each do |dx|\r\n dx_name = {}\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Initial High COP: #{dx.ratedHighSpeedCOP.get} Low COP: #{dx.ratedLowSpeedCOP.get}\")\r\n dx.setRatedHighSpeedCOP(7.62)\r\n dx.setRatedLowSpeedCOP(7.62)\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Final High COP: #{dx.ratedHighSpeedCOP.get} Final COP: #{dx.ratedLowSpeedCOP.get}\")\r\n dx_name[:dxname] = \"#{dx.name.get}\"\r\n results[\"#{dx.name.get}\"] = dx_name\r\n end\r\n end\r\n \r\n if results.empty?\r\n runner.registerWarning(\"No DX coils are appropriate for this measure\")\r\n runner.registerAsNotApplicable(\"No DX coils are appropriate for this measure\")\r\n end\r\n \r\n #save airloop parsing results to ems_results.json\r\n runner.registerInfo(\"Saving ems_results.json\")\r\n FileUtils.mkdir_p(File.dirname(\"ems_results.json\")) unless Dir.exist?(File.dirname(\"ems_results.json\"))\r\n File.open(\"ems_results.json\", 'w') {|f| f << JSON.pretty_generate(results)}\r\n \r\n if results.empty?\r\n runner.registerWarning(\"No DX coils are appropriate for this measure\")\r\n runner.registerAsNotApplicable(\"No DX coils are appropriate for this measure\")\r\n #save blank ems_membrane_heat_pump_cooling_only.ems file so Eplus measure does not crash\r\n ems_string = \"\"\r\n runner.registerInfo(\"Saving blank ems_membrane_heat_pump_cooling_only file\")\r\n FileUtils.mkdir_p(File.dirname(\"ems_membrane_heat_pump_cooling_only.ems\")) unless Dir.exist?(File.dirname(\"ems_membrane_heat_pump_cooling_only.ems\"))\r\n File.open(\"ems_membrane_heat_pump_cooling_only.ems\", \"w\") do |f|\r\n f.write(ems_string)\r\n end\r\n return true\r\n end\r\n \r\n timeStep = model.getTimestep.numberOfTimestepsPerHour\r\n \r\n runner.registerInfo(\"Making EMS string for Membrane Heat Pump Cooling Only\")\r\n #start making the EMS code\r\n ems_string = \"\" #clear out the ems_string\r\n ems_string << \"\\n\" \r\n ems_string << \"Output:Variable,*,Cooling Coil Sensible Cooling Energy,timestep; !- HVAC Sum [J]\" + \"\\n\"\r\n ems_string << \"\\n\" \r\n \r\n results.each_with_index do |(key, value), i| \r\n ems_string << \"EnergyManagementSystem:Sensor,\" + \"\\n\"\r\n ems_string << \" MembraneHP#{i+1}SensibleClgJ,\" + \"\\n\"\r\n ems_string << \" #{value[:dxname]},\" + \"\\n\"\r\n ems_string << \" Cooling Coil Sensible Cooling Energy;\" + \"\\n\"\r\n ems_string << \"\\n\" \r\n ems_string << \"WaterUse:Equipment,\" + \"\\n\"\r\n ems_string << \" MembraneHP#{i+1}WaterUse, !- Name\" + \"\\n\"\r\n ems_string << \" Membrane HP Cooling, !- End-Use Subcategory\" + \"\\n\"\r\n ems_string << \" 0.003155, !- Peak Flow Rate {m3/s} = 3000 gal/hr\" + \"\\n\"\r\n ems_string << \" MembraneHP#{i+1}WaterUseSchedule; !- Flow Rate Fraction Schedule Name\" + \"\\n\"\r\n ems_string << \"\\n\" \r\n ems_string << \"Schedule:Constant,\" + \"\\n\"\r\n ems_string << \" MembraneHP#{i+1}WaterUseSchedule, !- Name\" + \"\\n\"\r\n ems_string << \" , !- Schedule Type Limits Name\" + \"\\n\"\r\n ems_string << \" 1; !- Hourly Value\" + \"\\n\"\r\n ems_string << \"\\n\" \r\n ems_string << \"EnergyManagementSystem:Actuator,\" + \"\\n\"\r\n ems_string << \" MembraneHP#{i+1}WaterUseCtrl,\" + \"\\n\"\r\n ems_string << \" MembraneHP#{i+1}WaterUseSchedule,\" + \"\\n\"\r\n ems_string << \" Schedule:Constant,\" + \"\\n\"\r\n ems_string << \" Schedule Value;\" + \"\\n\"\r\n ems_string << \"\\n\" \r\n end\r\n ems_string << \"EnergyManagementSystem:ProgramCallingManager,\" + \"\\n\"\r\n ems_string << \" MembraneHPWaterUseProgramControl, !- Name\" + \"\\n\"\r\n ems_string << \" AfterPredictorBeforeHVACManagers, !- EnergyPlus Model Calling Point\" + \"\\n\"\r\n ems_string << \" MembraneHPWaterUseProgram; !- Program Name 1\" + \"\\n\"\r\n ems_string << \"\\n\"\r\n ems_string << \"EnergyManagementSystem:Program,\" + \"\\n\"\r\n ems_string << \" MembraneHPWaterUseProgram, !- Name\" + \"\\n\"\r\n ems_string << \" SET TimeStepsPerHr = #{timeStep}\" + \"\\n\"\r\n results.each_with_index do |(key, value), i|\r\n ems_string << \" SET MembraneHP#{i+1}SensibleClgTonHr = MembraneHP#{i+1}SensibleClgJ * 0.0000007898,\" + \"\\n\"\r\n ems_string << \" SET MembraneHP#{i+1}SensibleWtrGal = MembraneHP#{i+1}SensibleClgTonHr * 3.0,\" + \"\\n\"\r\n ems_string << \" SET MembraneHP#{i+1}SensibleWtrGalPerHr = MembraneHP#{i+1}SensibleWtrGal * TimeStepsPerHr,\" + \"\\n\"\r\n ems_string << \" SET MembraneHP#{i+1}WaterUseCtrl = MembraneHP#{i+1}SensibleWtrGalPerHr / 3000.0,\" + \"\\n\"\r\n end \r\n ems_string << \" SET UnusedLine = 0;\" + \"\\n\"\r\n \r\n #save EMS snippet\r\n runner.registerInfo(\"Saving ems_membrane_heat_pump_cooling_only file\")\r\n FileUtils.mkdir_p(File.dirname(\"ems_membrane_heat_pump_cooling_only.ems\")) unless Dir.exist?(File.dirname(\"ems_membrane_heat_pump_cooling_only.ems\"))\r\n File.open(\"ems_membrane_heat_pump_cooling_only.ems\", \"w\") do |f|\r\n f.write(ems_string)\r\n end\r\n \r\n #unique initial conditions based on\r\n runner.registerInitialCondition(\"The building has #{results.size} DX coils for which this measure is applicable.\")\r\n\r\n #reporting final condition of model\r\n runner.registerFinalCondition(\"The efficiency of the following coils was increased to SEER 26 to reflect the replacement of these coils with membrane heatpumps: #{results.keys}\")\r\n \r\n ems_path = '../MembraneHeatPumpCoolingOnlyEms/ems_membrane_heat_pump_cooling_only.ems'\r\n json_path = '../MembraneHeatPumpCoolingOnlyEms/ems_results.json'\r\n if File.exist? ems_path\r\n ems_string = File.read(ems_path)\r\n if File.exist? json_path\r\n json = JSON.parse(File.read(json_path))\r\n end\r\n else\r\n ems_path2 = Dir.glob('../../**/ems_membrane_heat_pump_cooling_only.ems')\r\n ems_path1 = ems_path2[0]\r\n json_path2 = Dir.glob('../../**/ems_results.json')\r\n json_path1 = json_path2[0]\r\n if ems_path2.size > 1\r\n runner.registerWarning(\"more than one ems_membrane_heat_pump_cooling_only.ems file found. Using first one found.\")\r\n end\r\n if !ems_path1.nil? \r\n if File.exist? ems_path1\r\n ems_string = File.read(ems_path1)\r\n if File.exist? json_path1\r\n json = JSON.parse(File.read(json_path1))\r\n else\r\n runner.registerError(\"ems_results.json file not located\") \r\n end \r\n else\r\n runner.registerError(\"ems_membrane_heat_pump_cooling_only.ems file not located\")\r\n end \r\n else\r\n runner.registerError(\"ems_membrane_heat_pump_cooling_only.ems file not located\") \r\n end\r\n end\r\n if json.nil?\r\n runner.registerError(\"ems_results.json file not located\")\r\n return false\r\n end\r\n \r\n if json.empty?\r\n runner.registerWarning(\"No DX coils are appropriate for this measure\")\r\n return true\r\n end\r\n \r\n idf_file = OpenStudio::IdfFile::load(ems_string, 'EnergyPlus'.to_IddFileType).get\r\n runner.registerInfo(\"Adding EMS code to workspace\")\r\n workspace.addObjects(idf_file.objects)\r\n \r\n return true\r\n\r\n end",
"def modeler_description\n return 'The measure performs the following functions: (1) IDs all chillers, (2) Locates their performance curves and outputs the data, (3) Adds reporting variables for chiller-related data.'\n end",
"def build_timing; end",
"def measure_gc\n return unless enabled?\n\n @raw_data << { fake: true }\n @total_time += 1.1\n\n end",
"def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n # define if the measure should run to a specific time period or whole day\n apply_to_time = true\n\n # assign the user inputs to variables\n object = runner.getOptionalWorkspaceObjectChoiceValue('space_type', user_arguments, model)\n single_space_type = runner.getDoubleArgumentValue('single_space_type', user_arguments)\n occupied_space_type = runner.getDoubleArgumentValue('occupied_space_type', user_arguments)\n unoccupied_space_type = runner.getDoubleArgumentValue('unoccupied_space_type', user_arguments)\n starttime_winter2 = runner.getStringArgumentValue('starttime_winter2', user_arguments)\n endtime_winter2 = runner.getStringArgumentValue('endtime_winter2', user_arguments)\n starttime_winter1 = runner.getStringArgumentValue('starttime_winter1', user_arguments)\n endtime_winter1 = runner.getStringArgumentValue('endtime_winter1', user_arguments)\n starttime_summer = runner.getStringArgumentValue('starttime_summer', user_arguments)\n endtime_summer = runner.getStringArgumentValue('endtime_summer', user_arguments)\n auto_date = runner.getBoolArgumentValue('auto_date', user_arguments)\n alt_periods = runner.getBoolArgumentValue('alt_periods', user_arguments)\n demo_cost_initial_const=false\n\n winter_start_month1 = 1\n winter_end_month1 = 5\n summer_start_month = 6\n summer_end_month = 9\n winter_start_month2 = 10\n winter_end_month2 = 12\n\n######### GET CLIMATE ZONES ################\n if auto_date\n ashraeClimateZone = ''\n #climateZoneNUmber = ''\n climateZones = model.getClimateZones\n climateZones.climateZones.each do |climateZone|\n if climateZone.institution == 'ASHRAE'\n ashraeClimateZone = climateZone.value\n runner.registerInfo(\"Using ASHRAE Climate zone #{ashraeClimateZone}.\")\n end\n end\n\n if ashraeClimateZone == '' # should this be not applicable or error?\n runner.registerError(\"Please assign an ASHRAE Climate Zone to your model using the site tab in the OpenStudio application. The measure can't make AEDG recommendations without this information.\")\n return false # note - for this to work need to check for false in measure.rb and add return false there as well.\n # else\n # climateZoneNumber = ashraeClimateZone.split(//).first\n end\n # #runner.registerInfo(\"CLIMATE ZONE #{ashraeClimateZone}. Right now does not do anything.\")\n # if !['1', '2', '3', '4', '5', '6', '7', '8'].include? climateZoneNumber\n # runner.registerError('ASHRAE climate zone number is not within expected range of 1 to 8.')\n # return false # note - for this to work need to check for false in measure.rb and add return false there as well.\n # end\n\n if alt_periods\n if ashraeClimateZone == '3A'\n starttime_summer = '18:01:00'\n endtime_summer = '21:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '4A'\n starttime_summer = '18:01:00'\n endtime_summer = '21:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '5A'\n starttime_summer = '14:01:00'\n endtime_summer = '17:59:00'\n starttime_winter1 = '18:01:00'\n endtime_winter1 = '21:59:00'\n starttime_winter2 = '18:01:00'\n endtime_winter2 = '21:59:00'\n elsif ashraeClimateZone == '6A'\n starttime_summer = '13:01:00'\n endtime_summer = '16:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n end\n else\n if ashraeClimateZone == '2A'\n starttime_summer = '17:01:00'\n endtime_summer = '20:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '2B'\n starttime_summer = '17:01:00'\n endtime_summer = '20:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '3A'\n starttime_summer = '19:01:00'\n endtime_summer = '22:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '3B'\n starttime_summer = '18:01:00'\n endtime_summer = '21:59:00'\n starttime_winter1 = '19:01:00'\n endtime_winter1 = '22:59:00'\n starttime_winter2 = '19:01:00'\n endtime_winter2 = '22:59:00'\n elsif ashraeClimateZone == '3C'\n starttime_summer = '19:01:00'\n endtime_summer = '22:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '4A'\n starttime_summer = '12:01:00'\n endtime_summer = '15:59:00'\n starttime_winter1 = '16:01:00'\n endtime_winter1 = '19:59:00'\n starttime_winter2 = '16:01:00'\n endtime_winter2 = '19:59:00'\n elsif ashraeClimateZone == '4B'\n starttime_summer = '17:01:00'\n endtime_summer = '20:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '4C'\n starttime_summer = '17:01:00'\n endtime_summer = '20:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '5A'\n starttime_summer = '20:01:00'\n endtime_summer = '23:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '5B'\n starttime_summer = '17:01:00'\n endtime_summer = '20:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '5C'\n starttime_summer = '17:01:00'\n endtime_summer = '20:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '6A'\n starttime_summer = '16:01:00'\n endtime_summer = '19:59:00'\n starttime_winter1 = '18:01:00'\n endtime_winter1 = '21:59:00'\n starttime_winter2 = '18:01:00'\n endtime_winter2 = '21:59:00'\n elsif ashraeClimateZone == '6B'\n starttime_summer = '17:01:00'\n endtime_summer = '20:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '7A'\n starttime_summer = '16:01:00'\n endtime_summer = '19:59:00'\n starttime_winter1 = '18:01:00'\n endtime_winter1 = '21:59:00'\n starttime_winter2 = '18:01:00'\n endtime_winter2 = '21:59:00'\n end\n end\n end \n\n # check the lighting power reduction percentages and for reasonableness\n if occupied_space_type > 100\n runner.registerError('Please Enter a Value less than or equal to 100 for the Electric Equipment Power Reduction Percentage.')\n return false\n elsif occupied_space_type == 0\n runner.registerInfo('No Electric Equipment power adjustment requested, but some life cycle costs may still be affected.')\n elsif (occupied_space_type < 1) && (occupied_space_type > -1)\n runner.registerWarning(\"A Electric Equipment Power Reduction Percentage of #{occupied_space_type} percent is abnormally low.\")\n elsif occupied_space_type > 90\n runner.registerWarning(\"A Electric Equipment Power Reduction Percentage of #{occupied_space_type} percent is abnormally high.\")\n elsif occupied_space_type < 0\n runner.registerInfo('The requested value for Electric Equipment power reduction percentage was negative. This will result in an increase in Electric Equipment power.')\n end\n\n # check the equipment_power_reduction_percent and for reasonableness\n if unoccupied_space_type > 100\n runner.registerError('Please Enter a Value less than or equal to 100 for the Electric Equipment Power Reduction Percentage.')\n return false\n elsif unoccupied_space_type == 0\n runner.registerInfo('No Electric Equipment power adjustment requested, but some life cycle costs may still be affected.')\n elsif (unoccupied_space_type < 1) && (unoccupied_space_type > -1)\n runner.registerWarning(\"A Electric Equipment Power Reduction Percentage of #{unoccupied_space_type} percent is abnormally low.\")\n elsif unoccupied_space_type > 90\n runner.registerWarning(\"A Electric Equipment Power Reduction Percentage of #{unoccupied_space_type} percent is abnormally high.\")\n elsif unoccupied_space_type < 0\n runner.registerInfo('The requested value for Electric Equipment power reduction percentage was negative. This will result in an increase in Electric Equipment power.')\n end\n\n # check the equipment_power_reduction_percent and for reasonableness\n if single_space_type > 100\n runner.registerError('Please Enter a Value less than or equal to 100 for the Electric Equipment Power Reduction Percentage.')\n return false\n elsif single_space_type == 0\n runner.registerInfo('No Electric Equipment power adjustment requested, but some life cycle costs may still be affected.')\n elsif (single_space_type < 1) && (single_space_type > -1)\n runner.registerWarning(\"A Electric Equipment Power Reduction Percentage of #{single_space_type} percent is abnormally low.\")\n elsif single_space_type > 90\n runner.registerWarning(\"A Electric Equipment Power Reduction Percentage of #{single_space_type} percent is abnormally high.\")\n elsif single_space_type < 0\n runner.registerInfo('The requested value for Electric Equipment power reduction percentage was negative. This will result in an increase in Electric Equipment power.')\n end\n\n # check the time periods for reasonableness\n if (starttime_winter1.to_f > endtime_winter1.to_f) && (starttime_winter2.to_f > endtime_winter2.to_f) && (starttime_summer.to_f > endtime_summer.to_f)\n runner.registerError('The end time should be larger than the start time.')\n return false\n end\n\n # check the space_type for reasonableness\n space_type = nil\n if object.empty?\n handle = runner.getStringArgumentValue('space_type', user_arguments)\n if handle.empty?\n runner.registerError('No space type was chosen.')\n else\n runner.registerError(\"The selected space type with handle '#{handle}' was not found in the model. It may have been removed by another measure.\")\n end\n return false\n else\n if !object.get.to_SpaceType.empty?\n space_type = object.get.to_SpaceType.get\n elsif !object.get.to_Building.empty?\n apply_to_building = true\n else\n runner.registerError('Script Error - argument not showing up as space type or building.')\n return false\n end\n end\n\n\n ############################################\n\n # assign the time duration when DR strategy is applied, from shift_time1 to shift_time2, only applied when apply_to_time is ture\n shift_time1 = OpenStudio::Time.new(starttime_winter1)\n shift_time2 = OpenStudio::Time.new(endtime_winter1)\n shift_time3 = OpenStudio::Time.new(0, 24, 0, 0)\n shift_time4 = OpenStudio::Time.new(starttime_summer)\n shift_time5 = OpenStudio::Time.new(endtime_summer)\n shift_time6 = OpenStudio::Time.new(starttime_winter2)\n shift_time7 = OpenStudio::Time.new(endtime_winter2)\n \n \n # get space types in model\n if apply_to_building\n space_types = model.getSpaceTypes\n else\n space_types = []\n space_types << space_type # only run on a single space type\n end\n\n # make a hash of old defs and new equipments and luminaire defs\n cloned_equi_defs = {}\n # loop through space types\n space_types.each do |space_type|\n\n equi_set_schs = {}\n if apply_to_building # measure will be applied differently to space types, based on whether the space type is occupied\n if !space_type.people.empty?\n equipment_power_reduction_percent = 1 - (occupied_space_type/100)\n else\n equipment_power_reduction_percent = 1 - (unoccupied_space_type/100)\n end\n runner.registerInitialCondition(\"Equipment power will be reduced by #{occupied_space_type}% in occupied spaces, and reduced by #{unoccupied_space_type}% in unoccupied spaces\")\n\n else\n equipment_power_reduction_percent = 1 - (single_space_type/100) # measure will be applied evenly to all zones\n runner.registerInitialCondition(\"Equipment power will be reduced by #{single_space_type}% to '#{space_type.name}'.\")\n end\n\n space_type_equipments = space_type.electricEquipment\n space_type_equipments.each do |space_type_equipment|\n #clone of not already in hash\n equi_set_sch = space_type_equipment.schedule\n if !equi_set_sch.empty?\n # clone of not already in hash\n if equi_set_schs.key?(equi_set_sch.get.name.to_s)\n new_equi_set_sch = equi_set_schs[equi_set_sch.get.name.to_s]\n else\n new_equi_set_sch = equi_set_sch.get.clone(model)\n new_equi_set_sch = new_equi_set_sch.to_Schedule.get\n new_equi_set_sch_name = new_equi_set_sch.setName(\"#{new_equi_set_sch.name} adjusted #{equipment_power_reduction_percent}\")\n # add to the hash\n equi_set_schs[new_equi_set_sch.name.to_s] = new_equi_set_sch\n end\n # hook up clone to equipment\n \n if space_type_equipment.name.to_s != \"OfficeLarge Data Center Elec Equip\" && space_type_equipment.name.to_s != \"OfficeLarge Main Data Center Elec Equip\"\n space_type_equipment.setSchedule(new_equi_set_sch)\n runner.registerInfo(\"#{space_type_equipment.name} has a new electric equipment schedule\")\n end\n else\n runner.registerWarning(\"#{space_type.equipments.name} doesn't have a schedule.\")\n end\n end\n \n if apply_to_time\n runner.registerFinalCondition(\" equipment power is reduced from #{shift_time1} to #{shift_time2}.\")\n runner.registerFinalCondition(\" equipment power is reduced from #{shift_time4} to #{shift_time5} during special between month #{summer_start_month} and #{summer_end_month}\")\n else\n runner.registerFinalCondition(\" equipment power is reduced all day.\")\n end\n\n \n # make equipment schedule adjustments and rename.\n equi_set_schs.each do |k, v| # old name and new object for schedule\n if !v.to_ScheduleRuleset.empty?\n\n schedule = v.to_ScheduleRuleset.get\n default_rule = schedule.defaultDaySchedule\n rules = schedule.scheduleRules\n\n days_covered = Array.new(7, false)\n\n if rules.length > 0\n rules.each do |rule|\n summerStartMonth = OpenStudio::MonthOfYear.new(summer_start_month)\n summerEndMonth = OpenStudio::MonthOfYear.new(summer_end_month)\n summerStartDate = OpenStudio::Date.new(summerStartMonth, 1)\n summerEndDate = OpenStudio::Date.new(summerEndMonth, 30)\n \n summer_rule = rule.clone(model).to_ScheduleRule.get\n summer_rule.setStartDate(summerStartDate)\n summer_rule.setEndDate(summerEndDate)\n\n allDaysCovered(summer_rule, days_covered)\n\n cloned_day_summer = rule.daySchedule.clone(model)\n cloned_day_summer.setParent(summer_rule)\n\n summer_day = summer_rule.daySchedule\n day_time_vector = summer_day.times\n day_value_vector = summer_day.values\n summer_day.clearValues\n \n summer_day = createDaySchedule(summer_day, day_time_vector, day_value_vector, shift_time4, shift_time5, equipment_power_reduction_percent)\n \n ##############################################\n winterStartMonth1 = OpenStudio::MonthOfYear.new(winter_start_month1)\n winterEndMonth1 = OpenStudio::MonthOfYear.new(winter_end_month1)\n winterStartDate1 = OpenStudio::Date.new(winterStartMonth1, 1)\n winterEndDate1 = OpenStudio::Date.new(winterEndMonth1, 31)\n \n winter_rule1 = rule #rule.clone(model).to_ScheduleRule.get\n winter_rule1.setStartDate(winterStartDate1)\n winter_rule1.setEndDate(winterEndDate1)\n\n\n cloned_day_winter = rule.daySchedule.clone(model)\n cloned_day_winter.setParent(winter_rule1)\n\n winter_day1 = winter_rule1.daySchedule\n day_time_vector = winter_day1.times\n day_value_vector = winter_day1.values\n winter_day1.clearValues\n \n winter_day1 = createDaySchedule(winter_day1, day_time_vector, day_value_vector, shift_time6, shift_time7, equipment_power_reduction_percent)\n if shift_time1 != shift_time6 \n winter_day1 = createDaySchedule(winter_day1, day_time_vector, day_value_vector, shift_time1, shift_time2, equipment_power_reduction_percent)\n end\n ###################################################\n winterStartMonth2 = OpenStudio::MonthOfYear.new(winter_start_month2)\n winterEndMonth2 = OpenStudio::MonthOfYear.new(winter_end_month2)\n winterStartDate2 = OpenStudio::Date.new(winterStartMonth2, 1)\n winterEndDate2 = OpenStudio::Date.new(winterEndMonth2, 31)\n \n winter_rule2 = winter_rule1.clone(model).to_ScheduleRule.get\n winter_rule2.setStartDate(winterStartDate2)\n winter_rule2.setEndDate(winterEndDate2)\n \n cloned_day_winter2 = winter_day1.clone(model)\n cloned_day_winter2.setParent(winter_rule2)\n end\n end\n #runner.registerInfo(\"BEFORE #{days_covered}\")\n if days_covered.include?(false)\n summerStartMonth = OpenStudio::MonthOfYear.new(summer_start_month)\n summerEndMonth = OpenStudio::MonthOfYear.new(summer_end_month)\n summerStartDate = OpenStudio::Date.new(summerStartMonth, 1)\n summerEndDate = OpenStudio::Date.new(summerEndMonth, 30)\n \n summer_rule = OpenStudio::Model::ScheduleRule.new(schedule)\n summer_rule.setStartDate(summerStartDate)\n summer_rule.setEndDate(summerEndDate)\n coverSomeDays(summer_rule, days_covered)\n allDaysCovered(summer_rule, days_covered)\n\n cloned_day_summer = default_rule.clone(model)\n cloned_day_summer.setParent(summer_rule)\n\n summer_day = summer_rule.daySchedule\n day_time_vector = summer_day.times\n day_value_vector = summer_day.values\n summer_day.clearValues\n \n summer_day = createDaySchedule(summer_day, day_time_vector, day_value_vector, shift_time4, shift_time5, equipment_power_reduction_percent)\n \n ##############################################\n winterStartMonth1 = OpenStudio::MonthOfYear.new(winter_start_month1)\n winterEndMonth1 = OpenStudio::MonthOfYear.new(winter_end_month1)\n winterStartDate1 = OpenStudio::Date.new(winterStartMonth1, 1)\n winterEndDate1 = OpenStudio::Date.new(winterEndMonth1, 31)\n \n winter_rule1 = summer_rule.clone(model).to_ScheduleRule.get #OpenStudio::Model::ScheduleRule.new(schedule)\n winter_rule1.setStartDate(winterStartDate1)\n winter_rule1.setEndDate(winterEndDate1)\n\n #coverSomeDays(winter_rule1, days_covered)\n #allDaysCovered(summer_rule, days_covered)\n\n cloned_day_winter = default_rule.clone(model)\n cloned_day_winter.setParent(winter_rule1)\n\n winter_day1 = winter_rule1.daySchedule\n day_time_vector = winter_day1.times\n day_value_vector = winter_day1.values\n winter_day1.clearValues\n \n\n\n winter_day1 = createDaySchedule(winter_day1, day_time_vector, day_value_vector, shift_time6, shift_time7, equipment_power_reduction_percent)\n if shift_time1 != shift_time6 \n winter_day1 = createDaySchedule(winter_day1, day_time_vector, day_value_vector, shift_time1, shift_time2, equipment_power_reduction_percent)\n end\n ###################################################\n winterStartMonth2 = OpenStudio::MonthOfYear.new(winter_start_month2)\n winterEndMonth2 = OpenStudio::MonthOfYear.new(winter_end_month2)\n winterStartDate2 = OpenStudio::Date.new(winterStartMonth2, 1)\n winterEndDate2 = OpenStudio::Date.new(winterEndMonth2, 31)\n \n winter_rule2 = winter_rule1.clone(model).to_ScheduleRule.get #OpenStudio::Model::ScheduleRule.new(schedule)\n winter_rule2.setStartDate(winterStartDate2)\n winter_rule2.setEndDate(winterEndDate2)\n \n cloned_day_winter2 = winter_day1.clone(model)\n cloned_day_winter2.setParent(winter_rule2)\n end\n #runner.registerInfo(\"AFTER Summer #{days_covered}\")\n else\n runner.registerWarning(\"Schedule '#{k}' isn't a ScheduleRuleset object and won't be altered by this measure.\")\n v.remove # remove un-used clone\n end\n end\n\n end\n return true\n end",
"def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n #use the built-in error checking\n if not runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n #assume the occ sensors will last the full analysis\n expected_life = 25\n \n #assign the user inputs to variables\n space_type_object = runner.getOptionalWorkspaceObjectChoiceValue(\"space_type\",user_arguments,model)\n percent_runtime_reduction = runner.getDoubleArgumentValue(\"percent_runtime_reduction\",user_arguments)\n material_and_installation_cost_per_space = runner.getDoubleArgumentValue(\"material_and_installation_cost_per_space\",user_arguments)\n\n #check the space_type for reasonableness and see if measure should run on space type or on the entire building\n apply_to_building = false\n space_type = nil\n if space_type_object.empty?\n handle = runner.getStringArgumentValue(\"space_type\",user_arguments)\n if handle.empty?\n runner.registerError(\"No space type was chosen.\")\n else\n runner.registerError(\"The selected space type with handle '#{handle}' was not found in the model. It may have been removed by another measure.\")\n end\n return false\n else\n if not space_type_object.get.to_SpaceType.empty?\n space_type = space_type_object.get.to_SpaceType.get\n elsif not space_type_object.get.to_Building.empty?\n apply_to_building = true\n else\n runner.registerError(\"Script Error - argument not showing up as space type or building.\")\n return false\n end\n end\n \n #check arguments for reasonableness\n if percent_runtime_reduction >= 100\n runner.registerError(\"Percent runtime reduction must be less than 100.\")\n return false\n end\n\n #find all the original schedules (before occ sensors installed)\n original_lts_schedules = []\n if apply_to_building #apply to the whole building\n \n model.getLightss.each do |light_fixture|\n if light_fixture.schedule.is_initialized\n original_lts_schedules << light_fixture.schedule.get\n end\n end\n else #apply to the a specific space type\n #do the lights assigned to the space type itself\n space_type.lights.each do |light_fixture|\n if light_fixture.schedule.is_initialized\n original_lts_schedules << light_fixture.schedule.get\n end\n end\n #do the lights in each space of the selected space type\n space_type.spaces.each do |space|\n space.lights.each do |light_fixture|\n if light_fixture.schedule.is_initialized\n original_lts_schedules << light_fixture.schedule.get\n end\n end \n end\n end\n \n #make copies of all the original lights schedules, reduced to include occ sensor impact\n original_schs_new_schs = {}\n original_lts_schedules.uniq.each do |orig_sch|\n #TODO skip non-schedule-ruleset schedules\n \n #copy the original schedule\n new_sch = orig_sch.clone.to_ScheduleRuleset.get\n #reduce each value in each profile (except the design days) by the specified amount\n runner.registerInfo(\"Reducing values in '#{orig_sch.name}' schedule by #{percent_runtime_reduction}% to represent occ sensor installation.\")\n day_profiles = []\n day_profiles << new_sch.defaultDaySchedule\n new_sch.scheduleRules.each do |rule|\n day_profiles << rule.daySchedule\n end\n multiplier = (100 - percent_runtime_reduction)/100\n day_profiles.each do |day_profile|\n #runner.registerInfo(\"#{day_profile.name}\")\n times_vals = day_profile.times.zip(day_profile.values)\n #runner.registerInfo(\"original time/values = #{times_vals}\")\n times_vals.each do |time,val|\n day_profile.addValue(time, val * multiplier)\n end\n #runner.registerInfo(\"new time/values = #{day_profile.times.zip(day_profile.values)}\")\n end \n #log the relationship between the old sch and the new, reduced sch\n original_schs_new_schs[orig_sch] = new_sch\n #runner.registerInfo(\"***\")\n end\n \n #replace the old schedules with the new schedules\n spaces_sensors_added_to = []\n if apply_to_building #apply to the whole building\n runner.registerInfo(\"Adding occupancy sensors to whole building\")\n model.getLightss.each do |light_fixture|\n next if light_fixture.schedule.empty?\n lights_sch = light_fixture.schedule.get\n new_sch = original_schs_new_schs[lights_sch]\n if new_sch\n runner.registerInfo(\"Added occupancy sensor for '#{light_fixture.name}'\")\n light_fixture.setSchedule(new_sch)\n spaces_sensors_added_to << light_fixture.space\n end\n end\n else #apply to the a specific space type\n #do the lights assigned to the space type itself\n runner.registerInfo(\"Adding occupancy sensors to space type '#{space_type.name}'\")\n space_type.lights.each do |light_fixture|\n next if light_fixture.schedule.empty?\n lights_sch = light_fixture.schedule.get\n new_sch = original_schs_new_schs[lights_sch]\n if new_sch\n runner.registerInfo(\"Added occupancy sensor for '#{light_fixture.name}'\")\n light_fixture.setSchedule(new_sch)\n spaces_sensors_added_to << light_fixture.space\n end\n end\n #do the lights in each space of the selected space type\n space_type.spaces.each do |space|\n runner.registerInfo(\"Adding occupancy sensors to space '#{space.name}\")\n space.lights.each do |light_fixture|\n next if light_fixture.schedule.empty?\n lights_sch = light_fixture.schedule.get\n new_sch = original_schs_new_schs[lights_sch]\n if new_sch\n runner.registerInfo(\"Added occupancy sensor for '#{light_fixture.name}'\")\n light_fixture.setSchedule(new_sch)\n spaces_sensors_added_to << light_fixture.space\n end\n end \n end\n end \n \n #report if the measure is not applicable\n num_sensors_added = spaces_sensors_added_to.uniq.size\n if spaces_sensors_added_to.size == 0\n runner.registerAsNotApplicable(\"This measure is not applicable because there were no lights in the specified areas of the building.\")\n return true\n end\n \n #report initial condition\n runner.registerInitialCondition(\"The building has several areas where occupancy sensors could be used to reduce lighting energy by turning off the lights while no occupants are present.\") \n \n #add cost of adding occ sensors\n if material_and_installation_cost_per_space != 0\n cost = OpenStudio::Model::LifeCycleCost.createLifeCycleCost(\"Add #{material_and_installation_cost_per_space} Occ Sensors to the Building\", model.getBuilding, material_and_installation_cost_per_space * num_sensors_added, \"CostPerEach\", \"Construction\", expected_life, 0)\n if cost.empty?\n runner.registerError(\"Failed to add costs.\")\n end\n end \n \n #report final condition\n if apply_to_building\n runner.registerFinalCondition(\"Add occupancy sensors to #{num_sensors_added} spaces in the building. The total cost to perform this is $#{material_and_installation_cost_per_space.round} per space, for a total cost of $#{(material_and_installation_cost_per_space * num_sensors_added).round}\")\n else\n runner.registerFinalCondition(\"Add occupancy sensors to #{num_sensors_added} #{space_type.name} spaces in the building. The total cost to perform this is $#{material_and_installation_cost_per_space.round} per space, for a total cost of $#{(material_and_installation_cost_per_space * num_sensors_added).round}\")\n end\n \n return true\n \n end",
"def run(model, runner, user_arguments)\r\n super(model, runner, user_arguments)\r\n\r\n #use the built-in error checking \r\n if not runner.validateUserArguments(arguments(model), user_arguments)\r\n return false\r\n end\r\n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\r\n if run_measure == 0\r\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\r\n return true \r\n end\r\n \r\n require 'json'\r\n \r\n results = {}\r\n dx_name = []\r\n #get all DX coils in model\r\n dx_single = model.getCoilCoolingDXSingleSpeeds \r\n dx_two = model.getCoilCoolingDXTwoSpeeds\r\n dx_heat = model.getCoilHeatingDXSingleSpeeds\r\n \r\n if !dx_single.empty?\r\n dx_single.each do |dx|\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Initial COP: #{dx.ratedCOP.get}\")\r\n dx.setRatedCOP(OpenStudio::OptionalDouble.new(6.0))\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Final COP: #{dx.ratedCOP.get}\")\r\n dx_name << dx.name.get\r\n end\r\n end\r\n if !dx_two.empty?\r\n dx_two.each do |dx|\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Initial High COP: #{dx.ratedHighSpeedCOP.get} Low COP: #{dx.ratedLowSpeedCOP.get}\")\r\n dx.setRatedHighSpeedCOP(6.0)\r\n dx.setRatedLowSpeedCOP(6.0)\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Final High COP: #{dx.ratedHighSpeedCOP.get} Final COP: #{dx.ratedLowSpeedCOP.get}\")\r\n dx_name << dx.name.get\r\n end\r\n end\r\n if !dx_heat.empty?\r\n dx_heat.each do |dx|\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Initial COP: #{dx.ratedCOP}\")\r\n dx.setRatedCOP(6.0)\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Final COP: #{dx.ratedCOP}\")\r\n dx_name << dx.name.get\r\n end\r\n end\r\n \r\n if dx_name.empty?\r\n runner.registerWarning(\"No DX coils are appropriate for this measure\")\r\n runner.registerAsNotApplicable(\"No DX coils are appropriate for this measure\")\r\n end\r\n \r\n #unique initial conditions based on\r\n runner.registerInitialCondition(\"The building has #{dx_name.size} DX coils for which this measure is applicable.\")\r\n\r\n #reporting final condition of model\r\n runner.registerFinalCondition(\"The COP of the following coils was increased to 6: #{dx_name}\")\r\n return true\r\n\r\n end",
"def around_perform_stats(*args)\n start = Time.now\n yield\n time_taken = Time.now - start\n statsd.timing(\"duration:#{self}\", time_taken)\n statsd.increment(\"total_successful:#{self}\")\n statsd.increment(\"total_successful\")\n run_hooks(:duration, :duration, args) {|key| statsd.timing(key, time_taken)}\n end",
"def defMeasurement(name,&block)\n mp = {:mp => name, :fields => []}\n @fields = []\n # call the block with ourserlves to process its 'defMetric' statements\n block.call(self) if block\n @fields.each { |f| mp[:fields] << f }\n define_measurement_point(mp)\n end",
"def measure(heading)\n start_time = Time.now\n print heading\n result = yield\n end_time = Time.now - start_time\n puts \" (#{end_time} s)\"\n result\nend",
"def measure() @measure ||= (nb_weight == 0.0 ? 0.0 : sum_weight / nb_weight) end",
"def record_measure(label)\n $logger.debug(\n tms = Benchmark.measure(label) do\n yield\n end.format(\"%n: %10.6rreal %10.6u user %10.6y sys\")\n )\nend",
"def run_examination\n true\n end",
"def update\n if @clock1_measure.nil?\n discipline_freq\n else\n elapsed = @clock1.time - @clock1_measure.local_time\n discipline_freq if elapsed > @frequency_discipline_interval\n end\n if @clock2_measure.nil?\n discipline_phase\n else\n elapsed = @clock2.time - @clock2_measure.local_time\n discipline_phase if elapsed > @phase_discipline_interval\n end\n end",
"def benchmark!\n @benchmark = true\n end",
"def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n # Return N/A if not selected to run\n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\n if run_measure == 0\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\n return true \n end \n \n\n pct_red = runner.getDoubleArgumentValue(\"pct_red\",user_arguments)\n start_hr = runner.getDoubleArgumentValue(\"start_hr\",user_arguments)\n end_hr = runner.getDoubleArgumentValue(\"end_hr\",user_arguments)\n \n\n\n #check the fraction for reasonableness\n if not 0 <= pct_red and pct_red <= 100\n runner.registerError(\"Percent reduction value needs to be between 0 and 100.\")\n return false\n end\n\n #check start_hr for reasonableness and round to 15 minutes\n start_red_hr = nil\n start_red_min = nil\n if not 0 <= start_hr and start_hr <= 24\n runner.registerError(\"Time in hours needs to be between or equal to 0 and 24\")\n return false\n else\n rounded_start_hr = ((start_hr*4).round)/4.0\n if not start_hr == rounded_start_hr\n runner.registerInfo(\"Start time rounded to nearest 15 minutes: #{rounded_start_hr}\")\n end\n start_red_hr = rounded_start_hr.truncate\n start_red_min = (rounded_start_hr - start_red_hr)*60\n start_red_min = start_red_min.to_i\n end\n\n #check end_hr for reasonableness and round to 15 minutes\n end_red_hr = nil\n end_red_min = nil \n if not 0 <= end_hr and end_hr <= 24\n runner.registerError(\"Time in hours needs to be between or equal to 0 and 24.\")\n return false\n elsif end_hr > end_hr\n runner.registerError(\"Please enter an end time later in the day than end time.\")\n return false\n else\n rounded_end_hr = ((end_hr*4).round)/4.0\n if not end_hr == rounded_end_hr\n runner.registerInfo(\"End time rounded to nearest 15 minutes: #{rounded_end_hr}\")\n end\n end_red_hr = rounded_end_hr.truncate\n end_red_min = (rounded_end_hr - end_red_hr)*60\n end_red_min = end_red_min.to_i\n end\n\n # Translate the percent reduction into a multiplier\n red_mult = pct_red/100\n\n # Get schedules from all lights.\n original_lights_schs = []\n model.getLightss.each do |lights|\n if lights.schedule.is_initialized\n lights_sch = lights.schedule.get\n original_lights_schs << lights_sch\n end\n end\n\n # loop through the unique list of lights schedules, cloning\n # and reducing schedule fraction during the specified time range.\n original_lights_schs_new_schs = {}\n original_lights_schs.uniq.each do |lights_sch|\n if lights_sch.to_ScheduleRuleset.is_initialized\n new_lights_sch = lights_sch.clone(model).to_ScheduleRuleset.get\n new_lights_sch.setName(\"#{lights_sch.name} with Solar Cogeneration and Daylighting\")\n original_lights_schs_new_schs[lights_sch] = new_lights_sch\n new_lights_sch = new_lights_sch.to_ScheduleRuleset.get\n \n # method to adjust the values in a day schedule by a \n # specified percentage during a range of hours.\n def reduce_schedule(day_sch, red_mult, start_red_hr, start_red_min, end_red_hr, end_red_min)\n start_time = OpenStudio::Time.new(0, start_red_hr, start_red_min, 0)\n end_time = OpenStudio::Time.new(0, end_red_hr, end_red_min, 0)\n\n # Get the original values at the desired start and end times\n # and put points into the schedule at those times.\n day_sch.addValue(start_time, day_sch.getValue(start_time))\n day_sch.addValue(end_time, day_sch.getValue(end_time))\n \n # Store the original time/values then clear the schedule\n times = day_sch.times\n values = day_sch.values\n day_sch.clearValues\n\n # Modify the time/values and add back to the schedule\n for i in 0..(values.length - 1)\n if times[i] > start_time and times[i] <= end_time # Inside range\n day_sch.addValue(times[i], values[i] * red_mult)\n else\n day_sch.addValue(times[i], values[i])\n end\n end\n\n end #end reduce schedule\n\n # Reduce default day schedule\n if new_lights_sch.scheduleRules.size == 0\n runner.registerWarning(\"Schedule '#{new_lights_sch.name}' applies to all days. It has been treated as a Weekday schedule.\")\n end\n reduce_schedule(new_lights_sch.defaultDaySchedule, red_mult, start_red_hr, start_red_min, end_red_hr, end_red_min)\n \n # Reduce all other schedule rules\n new_lights_sch.scheduleRules.each do |sch_rule|\n reduce_schedule(sch_rule.daySchedule, red_mult, start_red_hr, start_red_min, end_red_hr, end_red_min)\n end\n \n end \n end #end of original_lights_schs.uniq.each do\n\n #loop through all lights instances, replacing old lights schedules with the reduced schedules\n model.getLightss.each do |lights|\n if lights.schedule.empty?\n runner.registerWarning(\"There was no schedule assigned for the lights object named '#{lights.name}. No schedule was added.'\")\n else\n old_lights_sch = lights.schedule.get\n lights.setSchedule(original_lights_schs_new_schs[old_lights_sch])\n runner.registerInfo(\"Schedule for the lights object named '#{lights.name}' was reduced to simulate the application of Solar Cogeneration and Daylighting.\")\n end\n end\n\n # NA if the model has no lights\n if model.getLightss.size == 0\n runner.registerNotAsApplicable(\"Not Applicable - There are no lights in the model.\")\n end\n\n # Reporting final condition of model\n runner.registerFinalCondition(\"#{original_lights_schs.uniq.size} schedule(s) were edited to reflect the addition of Solar Cogeneration and Daylighting to the building.\")\n \n return true\n\n end",
"def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n \n # Return N/A if not selected to run\n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\n if run_measure == 0\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\n return true \n end\n\n\t#initialize variables\n\ttz_count = 0\n\tclg_tstat_schedule = []\n\tthermal_zone_array = []\n\t\t\n\t# get the thermal zones and loop through them \n\tmodel.getThermalZones.each do |thermal_zone|\n\t\n\t\tthermal_zone_array << thermal_zone\n\t\t\n\t\t# test to see if thermal zone has a thermostat object assigned or is unconditioned. \n\t\tif thermal_zone.thermostatSetpointDualSetpoint.is_initialized\n\t\t\tzone_thermostat = thermal_zone.thermostatSetpointDualSetpoint.get\n\t\t\ttz_count += 1\n\t\t\t\n\t\t\tif zone_thermostat.coolingSetpointTemperatureSchedule.is_initialized\n\t\t\t\tclg_tstat_schedule = zone_thermostat.coolingSetpointTemperatureSchedule.get\n\t\t\t\t\n\t\t\t\t# clone the existing cooling T-stat schedule in case it is used somewhere else in the model\n\t\t\t\tcloned_clg_tstat_schedule = clg_tstat_schedule.clone\n\t\t\t\t@new_clg_tstat_schedule_name = (\"#{clg_tstat_schedule.name}+1.5F\")\n\t\t\t\n\t\t\t\tif cloned_clg_tstat_schedule.to_ScheduleRuleset.is_initialized\n\t\t\t\t\tschedule = cloned_clg_tstat_schedule.to_ScheduleRuleset.get\n\t\t\t\t\t# gather profiles of cloned schedule\n\t\t\t\t\tprofiles = []\n\t\t\t\t\tcooling_thermostat_array = []\n\t\t\t\t\tdefaultProfile = schedule.to_ScheduleRuleset.get.defaultDaySchedule\n\t\t\t\t\n\t\t\t\t\tprofiles << defaultProfile\n\t\t\t\t\trules = schedule.scheduleRules\n\t\t\t\t\n\t\t\t\t\trules.each do |rule|\n\t\t\t\t\t\tprofiles << rule.daySchedule\n\t\t\t\t\tend # end the do loop through the rulesetsdo\n\n\t\t\t\t\t#adjust profiles of temperature schedule of cloned schedule by + 1.5 deg F delta (0.833 C)\n\t\t\t\t\tprofiles.each do |profile|\n\t\t\t\t\t\ttime = profile.times\n\t\t\t\t\t\ti = 0\n\t\t\t\t\t\t#TODO - name new profile\n\t\t\t\t\t\tprofile.values.each do |value|\n\t\t\t\t\t\t\tdelta = 0.8333\n\t\t\t\t\t\t\tnew_value = value + delta # Note this is where the cooling setpoint is raised\n\t\t\t\t\t\t\tprofile.addValue(time[i], new_value)\n\t\t\t\t\t\t\ti += 1\n\t\t\t\t\t\t\tcloned_clg_tstat_schedule.setName(@new_clg_tstat_schedule_name)\n\t\t\t\t\t\t\tcooling_thermostat_array << cloned_clg_tstat_schedule\n\t\t\t\t\t\tend # end loop through each profile values\n\t\t\t\t\tend # end loop through each profile\n\t\t\t\t\t\n\t\t\t\t\tzone_thermostat.setCoolingSetpointTemperatureSchedule(cloned_clg_tstat_schedule.to_ScheduleRuleset.get)\n\t\t\t\t\trunner.registerInfo(\"The existing cooling thermostat '#{clg_tstat_schedule.name}' has been changed to #{cloned_clg_tstat_schedule.name}. Inspect the new schedule values using the OS App.\")\n\t\t\t\tend # end if statement for cloning and modifying cooling tstat schedule object\n\t\t\telse\n\t\t\t\trunner.registerInfo(\"The dual setpoint thermostat object named #{zone_thermostat.name} serving thermal zone #{thermal_zone.name} did not have a cooling setpoint temperature schedule associated with it. The measure will not alter this thermostat object\")\n\t\t\tend # end if statement for cooling Setpoint Temperature is initialized\n\t\t\t\n\t\t\tif zone_thermostat.heatingSetpointTemperatureSchedule.is_initialized\n\t\t\t\thtg_tstat_schedule = zone_thermostat.heatingSetpointTemperatureSchedule.get\n\t\t\t\t\t\t\n\t\t\t\t# clone the existing heating T-stat schedule in case it is used somewhere else\n\t\t\t\tcloned_htg_tstat_schedule = htg_tstat_schedule.clone\n\t\t\t\t\n\t\t\t\t#name cloned heating t-stat schedule\n\t\t\t\tcloned_htg_tstat_schedule.setName(\"#{htg_tstat_schedule.name}-1.5F\")\n\n\t\t\t\tif cloned_htg_tstat_schedule.to_ScheduleRuleset.is_initialized\n\t\t\t\t\tschedule = cloned_htg_tstat_schedule.to_ScheduleRuleset.get\n\t\t\t\t\n\t\t\t\t\t# gather profiles of cloned schedule\n\t\t\t\t\tprofiles_h = []\n\t\t\t\t\tdefaultProfile = schedule.to_ScheduleRuleset.get.defaultDaySchedule\n\t\t\t\t\t\n\t\t\t\t\tprofiles_h << defaultProfile\n\t\t\t\t\trules_h = schedule.scheduleRules\n\t\t\t\t\trules_h.each do |rule_h|\n\t\t\t\t\t\tprofiles_h << rule_h.daySchedule\n\t\t\t\t\tend # end the rule_h do\n\n\t\t\t\t\t#adjust profiles_h of temperature schedule of cloned schedule by + 1.5 deg F delta (0.833 C)\n\t\t\t\t\tprofiles_h.each do |profile_h|\n\t\t\t\t\t\ttime_h = profile_h.times\n\t\t\t\t\t\ti = 0\n\t\t\t\t\t\t#TODO - name new profile\n\t\t\t\t\t\tprofile_h.values.each do |value_h|\n\t\t\t\t\t\t\tdelta_h = 0.8333\n\t\t\t\t\t\t\tnew_value_h = value_h - delta_h # Note this is where the heating setpoint is lowered \n\t\t\t\t\t\t\tprofile_h.addValue(time_h[i], new_value_h)\n\t\t\t\t\t\t\ti += 1\n\t\t\t\t\t\tend # end loop through each profile values\n\t\t\t\t\tend # end loop through each profile_h\n\t\t\t\t\t\n\t\t\t\t\tzone_thermostat.setHeatingSetpointTemperatureSchedule(cloned_htg_tstat_schedule.to_ScheduleRuleset.get)\n\t\t\t\t\trunner.registerInfo(\"The existing heating thermostat '#{htg_tstat_schedule.name}' has been changed to #{cloned_htg_tstat_schedule.name}. Inspect the new schedule values using the OS App.\")\n\t\t\t\tend # end if statement for cloning and modifying heating tstat schedule object\t\n\t\t\telse\n\t\t\t\trunner.registerInfo(\"The dual setpoint thermostat object named #{zone_thermostat.name} serving thermal zone #{thermal_zone.name} did not have a heating setpoint temperature schedule associated with it. The measure will not alter this thermostat object\")\n\t\t\tend # end if statement for heating Setpoint Temperature is initialized\n\t\tend\t# end if statement for zone_thermstat cooling schedule\n\t\t\n\tend # end loop through thermal zones\t\t\t\n\t\t\t\n\t# Add ASHRAE 55 Comfort Warnings are applied to people objects\n\t# get people objects and people definitions in model\n\tpeople_defs = model.getPeopleDefinitions\n\tpeople_instances = model.getPeoples\n\n\t# loop through people objects\n\tpeople_def_counter = 0\n\tpeople_defs.sort.each do |people_def|\n\t next if not people_def.instances.size > 0\n\t people_def_counter += 1\n\t people_def.setEnableASHRAE55ComfortWarnings(true)\n\tend\n\t\t\t\n\treporting_frequency = \"Timestep\"\n\toutputVariable = OpenStudio::Model::OutputVariable.new(\"Zone Thermal Comfort ASHRAE 55 Adaptive Model 90% Acceptability Status []\",model)\n\toutputVariable.setReportingFrequency(reporting_frequency)\n\trunner.registerInfo(\"Adding output variable for 'Zone Thermal Comfort ASHRAE 55 Adaptive Model 90% Acceptability Status' reporting '#{reporting_frequency}'\")\n\n\t# write As Not Applicable message\n\tif tz_count == 0\n\t\trunner.registerAsNotApplicable(\"Measure is not applicable. There are no conditioned thermal zones in the model.\")\n\t\treturn true\n\tend\n\n\t# report initial condition of model\n\trunner.registerInitialCondition(\"The initial model contained #{tz_count} thermal zones with #{thermal_zone_array.length} 'Cooling Thermostat Schedule' and #{thermal_zone_array.length} 'Heating Thermostat Schedule' objects for which this measure is applicable.\")\n\n\t# report final condition of model\n\trunner.registerFinalCondition(\"The #{thermal_zone_array.length} Heating and #{thermal_zone_array.length} Cooling Thermostats schedules for #{thermal_zone_array.length} Thermal Zones were altered to reflect a additional deadband width of 3 Deg F . \")\n\treturn true\n\n end",
"def stat(*args)\n @recorder.call(*args) if @recorder\n end",
"def measure (n=1)\n cnt=0\nelapsed_time=Time.now\n\nn.times {\n cnt+=1\n yield} \nelapsed_time=(Time.now-elapsed_time)/cnt\n\nend",
"def run() end",
"def running_test_step; end",
"def stat() end",
"def measure(msg)\n start = Time.now\n yield\n printf \"%<msg>s in %<elapsed>.2f seconds\\n\", msg: msg, elapsed: Time.now - start\nend",
"def measure(msg)\n start = Time.now\n yield\n printf \"%<msg>s in %<elapsed>.2f seconds\\n\", msg: msg, elapsed: Time.now - start\nend",
"def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n # Return N/A if not selected to run\n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\n if run_measure == 0\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\n return true \n end \n \n #initialize variables\n zone_hvac_count = 0\n pump_count = 0\n air_loop_count = 0\n \n #loop through each air loop in the model\n model.getAirLoopHVACs.sort.each do |air_loop|\n\n # call the method to generate a new occupancy schedule based on a 5% threshold\n occ_sch = air_loop.get_occupancy_schedule(0.15)\n old_sch = air_loop.availabilitySchedule\n next unless compare_eflh(runner, old_sch, occ_sch)\n # set the availability schedule of the airloop to the newly generated schedule\n air_loop.setAvailabilitySchedule(occ_sch)\n runner.registerInfo(\"The availability schedule named #{old_sch.name} for #{air_loop.name} was replaced with a new schedule named #{occ_sch.name} which tracks the occupancy profile of the thermal zones on this airloop.\")\n air_loop_count +=1\n \n end\n\n #loop through each thermal zone\n model.getThermalZones.sort.each do |thermal_zone|\n \n # zone equipments assigned to thermal zones\n thermal_zone_equipment = thermal_zone.equipment \n \n if thermal_zone_equipment.size >= 1\n # run schedule method to create a new schedule ruleset, routines \n occ_sch = thermal_zone.get_occupancy_schedule(0.15)\n \n #loop through Zone HVAC Equipment\n thermal_zone_equipment.each do |equip|\n \n # getting the fan exhaust object & getting relevant information for it. \n if equip.to_FanZoneExhaust.is_initialized\n zone_equip = equip.to_FanZoneExhaust.get\n old_schedule = zone_equip.availabilitySchedule.get\n next unless compare_eflh(runner, old_schedule, occ_sch)\n #assign the 'occ_sch' here as exhaust's availability schedule\n zone_equip.setAvailabilitySchedule(occ_sch)\n runner.registerInfo(\"The availability schedule named #{old_schedule.name} for the OS_Fan_ZoneExhaust named #{zone_equip.name} was replaced with a new schedule named #{occ_sch.name} representing the occupancy profile of the thermal zone named #{thermal_zone.name}.\")\n zone_hvac_count += 1 \t\n elsif equip.to_RefrigerationAirChiller.is_initialized\n zone_equip = equip.to_RefrigerationAirChiller.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_WaterHeaterHeatPump.is_initialized\n zone_equip = equip.to_WaterHeaterHeatPump.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_ZoneHVACBaseboardConvectiveElectric.is_initialized\n zone_equip = equip.to_ZoneHVACBaseboardConvectiveElectric.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_ZoneHVACBaseboardConvectiveWater.is_initialized\n zone_equip = equip.to_ZoneHVACBaseboardConvectiveWater.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_ZoneHVACBaseboardRadiantConvectiveElectric.is_initialized\n zone_equip = equip.to_ZoneHVACBaseboardRadiantConvectiveElectric.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_ZoneHVACBaseboardRadiantConvectiveWater.is_initialized\n zone_equip = equip.to_ZoneHVACBaseboardRadiantConvectiveWater.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_ZoneHVACDehumidifierDX.is_initialized\n zone_equip = equip.to_ZoneHVACDehumidifierDX.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_ZoneHVACEnergyRecoveryVentilator.is_initialized\n zone_equip = equip.to_ZoneHVACEnergyRecoveryVentilator.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\t\n elsif equip.to_ZoneHVACFourPipeFanCoil.is_initialized\n zone_equip = equip.to_ZoneHVACFourPipeFanCoil.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\t\t\n elsif equip.to_ZoneHVACHighTemperatureRadiant.is_initialized\n zone_equip = equip.to_ZoneHVACHighTemperatureRadiant.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\t\n elsif equip.to_ZoneHVACIdealLoadsAirSystem.is_initialized\n zone_equip = equip.to_ZoneHVACIdealLoadsAirSystem.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\t \n elsif equip.to_ZoneHVACLowTemperatureRadiantElectric.is_initialized\n zone_equip = equip.to_ZoneHVACLowTemperatureRadiantElectric.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\t\t\n elsif equip.to_ZoneHVACLowTempRadiantConstFlow.is_initialized\n zone_equip = equip.to_ZoneHVACLowTempRadiantConstFlow.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\t\t \t\n elsif equip.to_ZoneHVACLowTempRadiantVarFlow.is_initialized\n zone_equip = equip.to_ZoneHVACLowTempRadiantVarFlow.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\t\t\n elsif equip.to_ZoneHVACPackagedTerminalAirConditioner.is_initialized\n zone_equip = equip.to_ZoneHVACPackagedTerminalAirConditioner.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_ZoneHVACPackagedTerminalHeatPump.is_initialized\n zone_equip = equip.to_ZoneHVACPackagedTerminalHeatPump.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_ZoneHVACTerminalUnitVariableRefrigerantFlow.is_initialized\n next unless compare_eflh(runner, old_schedule, occ_sch) \n equip.to_ZoneHVACTerminalUnitVariableRefrigerantFlow.get.setTerminalUnitAvailabilityschedule(occ_sch)\n runner.registerInfo(\"The availability schedule for the Zone HVAC Terminal Unit Variable Refrigerant Flow Object has been replaced with a new schedule named #{occ_sch.name} representing the occupancy profile of the thermal zone named #{thermal_zone.name}.\")\t\t\t\t\t\n zone_hvac_count += 1 \n elsif equip.to_ZoneHVACUnitHeater.is_initialized\n zone_equip = equip.to_ZoneHVACUnitHeater.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\n elsif equip.to_ZoneHVACUnitVentilator.is_initialized\n zone_equip = equip.to_ZoneHVACUnitVentilator.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\t\t\n elsif equip.to_ZoneVentilationDesignFlowRate.is_initialized\n runner.registerInfo(\"Thermal Zone named #{thermal_zone.name} has a Zone Ventilation Design Flow Rate object attacjhed as a ZoneHVACEquipment object. No modification were made to this object.\")\t\t\n end \t\n \n end # end loop through Zone HVAC Equipment\n \n else\n runner.registerInfo(\"Thermal Zone named #{thermal_zone.name} has no Zone HVAC Equipment objects attached - therefore no schedule objects have been altered.\")\t\n end # end of if statement\n \n end # end loop through thermal zones\n\n # Change pump control status if any airloops or\n # zone equipment were changed.\n if air_loop_count > 0 || zone_hvac_count > 0\n model.getPlantLoops.each do |plantLoop|\n #Loop through each plant loop demand component\n plantLoop.demandComponents.each do |dc|\n if dc.to_PumpConstantSpeed.is_initialized\n cs_pump = dc.to_PumpConstantSpeed.get\n if cs_pump.pumpControlType == (\"Intermittent\")\n runner.registerInfo(\"Demand side Constant Speed Pump object named #{cs_pump.name} on the plant loop named #{dc.name} had a pump control type attribute already set to intermittent. No changes will be made to this object.\")\n else \n cs_pump.setPumpControlType(\"Intermittent\")\n runner.registerInfo(\"Pump Control Type attribute of Demand side Constant Speed Pump object named #{cs_pump.name} on the plant loop named #{dc.name} was changed from continuous to intermittent.\")\n pump_count +=1\n end\n end\n \n if dc.to_PumpVariableSpeed.is_initialized\n vs_pump = dc.to_PumpVariableSpeed.get\n if vs_pump.pumpControlType == (\"Intermittent\")\n runner.registerInfo(\"Demand side Variable Speed Pump named #{vs_pump.name} on the plant loop named #{dc.name} had a pump control type attribute already set to intermittent. No changes will be made to this object.\")\n else \n cs_pump.setPumpControlType(\"Intermittent\")\n runner.registerInfo(\"Demand side Pump Control Type attribute of Variable Speed Pump named #{vs_pump.name} on the plant loop named #{dc.name} was changed from continuous to intermittent.\")\n pump_count +=1\n end\n end\n end\n \n #Loop through each plant loop supply component\n plantLoop.supplyComponents.each do |sc|\n if sc.to_PumpConstantSpeed.is_initialized\n cs_pump = sc.to_PumpConstantSpeed.get\n if cs_pump.pumpControlType == (\"Intermittent\")\n runner.registerInfo(\"Supply side Constant Speed Pump object named #{cs_pump.name} on the plant loop named #{sc.name} had a pump control type attribute already set to intermittent. No changes will be made to this object.\")\n else \n cs_pump.setPumpControlType(\"Intermittent\")\n runner.registerInfo(\"Supply Side Pump Control Type atteribute of Constant Speed Pump named #{cs_pump.name} on the plant loop named #{sc.name} was changed from continuous to intermittent.\")\n pump_count +=1\n end #end if statement\t\n end #end if statement for changing supply component constant speed pump objects\n \n if sc.to_PumpVariableSpeed.is_initialized\n vs_pump = sc.to_PumpVariableSpeed.get\n if vs_pump.pumpControlType == (\"Intermittent\")\n runner.registerInfo(\"Supply side Variable Speed Pump object named #{vs_pump.name} on the plant loop named #{sc.name} had a pump control type attribute already set to intermittent. No changes will be made to this object.\")\n else \n cs_pump.setPumpControlType(\"Intermittent\")\n runner.registerInfo(\"Pump Control Type attribute of Supply Side Variable Speed Pump named #{vs_pump.name} on the plant loop named #{sc.name} was changed from continuous to intermittent.\")\n pump_count +=1\n end #end if statement\t\n end #end if statement for changing supply component variable speed pump objects\n \n end # end loop throught plant loop supply side components\n \n end # end loop through plant loops\n end\n \n #Write N/A message\n if air_loop_count == 0 && zone_hvac_count == 0 && pump_count == 0 \n runner.registerAsNotApplicable(\"The model did not contain any Airloops, Thermal Zones having ZoneHVACEquipment objects or associated plant loop pump objects to act upon. The measure is not applicable.\")\n return true\n end\t\n \n #report initial condition of model\n runner.registerInitialCondition(\"The model started with #{air_loop_count} AirLoops, #{zone_hvac_count} Zone HVAC Equipment Object and #{pump_count} pump objects subject to modifications.\")\n \n # report final condition of model\n runner.registerFinalCondition(\"The measure modified the availability schedules of #{air_loop_count} AirLoops and #{zone_hvac_count} Zone HVAC Equipment objects. #{pump_count} pump objects had control settings modified.\")\n \n # Add ASHRAE Standard 55 warnings\n reporting_frequency = \"Timestep\"\n outputVariable = OpenStudio::Model::OutputVariable.new(\"Zone Thermal Comfort ASHRAE 55 Adaptive Model 90% Acceptability Status []\",model)\n outputVariable.setReportingFrequency(reporting_frequency)\n runner.registerInfo(\"Adding output variable for 'Zone Thermal Comfort ASHRAE 55 Adaptive Model 90% Acceptability Status' reporting at the model timestep.\")\n \n return true\n\t\n end",
"def calc_next_run\n nil\n end",
"def calc_next_run\n nil\n end",
"def running_test_case; end",
"def estimate\n # (native code) \n end",
"def run; end",
"def run; end",
"def run; end",
"def run; end",
"def run; end",
"def run; end",
"def run; end",
"def run; end",
"def run; end",
"def tick; end",
"def tick; end",
"def tick; end",
"def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n # assign the user inputs to variables\n verbose_info_statements = runner.getBoolArgumentValue(\"verbose_info_statements\",user_arguments)\n fixed_window_subsurface = runner.getOptionalWorkspaceObjectChoiceValue('fixed_window_subsurface', user_arguments, model) # model is passed in because of argument type\n internal_variable_availability_dictionary_reporting = runner.getStringArgumentValue('internal_variable_availability_dictionary_reporting', user_arguments)\n ems_runtime_language_debug_output_level = runner.getStringArgumentValue('ems_runtime_language_debug_output_level', user_arguments) \n actuator_availability_dictionary_reporting = runner.getStringArgumentValue('actuator_availability_dictionary_reporting', user_arguments) \n \n runner.registerInitialCondition(\"Measure began with #{model.getEnergyManagementSystemSensors.count} EMS sensors, #{model.getEnergyManagementSystemActuators.count} EMS Actuators, #{model.getEnergyManagementSystemPrograms.count} EMS Programs, #{model.getEnergyManagementSystemSubroutines.count} EMS Subroutines, #{model.getEnergyManagementSystemProgramCallingManagers.count} EMS Program Calling Manager objects\")\n \n # declare arrys for scope\n array_of_21_sets = []\n material_property_glazing_spectral_data_vector = []\n standard_glazing_layer_array = []\n construction_array = []\n ems_window_construction_array = []\n \n # load idf into workspace\n workspace = OpenStudio::Workspace::load(OpenStudio::Path.new(\"#{File.dirname(__FILE__)}/resources/EMSThermochromicWindow.idf\")).get\n \n # get all MaterialPropertyGlazingSpectralData objects from within the idf\n # material_property_glazing_spectral_datas = source_idf.getObjectsByType(\"MaterialProperty:GlazingSpectralData\".to_IddObjectType)\n material_property_glazing_spectral_datas = workspace.getObjectsByType(\"MaterialProperty:GlazingSpectralData\".to_IddObjectType)\n if verbose_info_statements == true\n runner.registerInfo(\"The model has #{material_property_glazing_spectral_datas.size} material_property_glazing_spectral_datas objects.\")\n end\n \n material_property_glazing_spectral_datas.each do |material_property_glazing_spectral_data|\n \n spectral_data = {\"name\" => \"\",\"properties\" => []}\n spectral_data[\"name\"] = material_property_glazing_spectral_data.getString(0).to_s\n \n # Note: EnergyPlus file MaterialProperty:GlazingSpectralData objects have 1764 /4 = 441 sets of 4 values each \n n = material_property_glazing_spectral_data.numFields\n (1..n).each do |i| \n spectral_data[\"properties\"] << material_property_glazing_spectral_data.getString(i).to_s \n end\n array_of_21_sets << spectral_data\n end\n \n array_of_21_sets.each do |set|\n \n props = set[\"properties\"]\n material_property_glazing_spectral_data = OpenStudio::Model::MaterialPropertyGlazingSpectralData.new(model)\n material_property_glazing_spectral_data.setName(\"#{set[\"name\"]}\")\n \n k = (props.length / 4) - 1\n (0..k).each do |i| # note 440 uniques (a, b, c, d) pairs of attributes for each spectral data field object\n material_property_glazing_spectral_data.addSpectralDataField(props[(i*4)+0].to_f, props[(i*4)+1].to_f, props[(i*4)+2].to_f, props[(i*4)+3].to_f)\t\n end\n \n material_property_glazing_spectral_data_vector << material_property_glazing_spectral_data\n end \n \n # create (2) required new air gas materials to used by all EMS window constructions \n air_gas_3mm_material = OpenStudio::Model::Gas.new(model, \"Air\", 0.003) \n air_gas_3mm_material.setName(\"AIR 3MM\")\n \n air_gas_8mm_material = OpenStudio::Model::Gas.new(model, \"Air\", 0.008) \n air_gas_8mm_material.setName(\"AIR 8MM\")\n \n # loop through array of OS MaterialPropertyGlazingSpectralData objects and create 21 new Standard Glazing objects \n material_property_glazing_spectral_data_vector.each do |spec_data_obj|\n spec_data_obj_name = spec_data_obj.name\n layer_name = spec_data_obj_name.to_s.slice(\"sp\")\n if ((spec_data_obj_name == \"WO18RT25SP\") || (spec_data_obj_name == \"Clear3PPGSP\"))\n layer = OpenStudio::Model::StandardGlazing.new(model, 'Spectral', 0.0075)\n else\n layer = OpenStudio::Model::StandardGlazing.new(model, 'Spectral', 0.003276)\n end\n layer.setName(\"#{layer_name}\")\n layer.setWindowGlassSpectralDataSet(spec_data_obj)\n layer.setInfraredTransmittanceatNormalIncidence(0) # same for all 21 constructions\n layer.setFrontSideInfraredHemisphericalEmissivity(0.84) # same for all 21 constructions\n layer.setBackSideInfraredHemisphericalEmissivity(0.84) # same for all 21 constructions\n if ((spec_data_obj_name == \"WO18RT25SP\") || (spec_data_obj_name == \"Clear3PPGSP\"))\n layer.setConductivity(1.0) \n else\n layer.setConductivity(0.6) \n end\n layer.setDirtCorrectionFactorforSolarandVisibleTransmittance(1) # same for all 21 constructions\n layer.setSolarDiffusing(false)\n standard_glazing_layer_array << layer\n end\n\n # Create (2) unique standard glazing layers not used for Thermochromatic performance \n sb60_clear_3_ppg_layer = standard_glazing_layer_array[0]\n clear_3ppg_layer = standard_glazing_layer_array[1]\n remaining_standard_glazing_layer_array = standard_glazing_layer_array.drop(2)\n \n # create (19) new arrays of layered constructions representing thermochromatic layers\n remaining_standard_glazing_layer_array.each do |remaining_standard_glazing_layer|\n construction = [sb60_clear_3_ppg_layer, air_gas_3mm_material, remaining_standard_glazing_layer, air_gas_8mm_material, sb60_clear_3_ppg_layer]\n construction_array << construction\n end\n \n # create 19 new OS:Construction objects representing EMS thermochromatic windows\n name_index_array = [25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 50, 55, 60, 65, 70, 75, 80, 85]\n index = 0\n \n construction_array.each do |const|\n ems_window_construction = OpenStudio::Model::Construction.new(const)\n ems_window_construction.setName(\"TCwindow_#{name_index_array[index]}\")\n if verbose_info_statements == true\n runner.registerInfo(\"Created a new Construction named #{ems_window_construction.name} representing a thermochromatic window construction.\")\n end\n ems_window_construction_array << ems_window_construction\n index +=1\n end\n\n # check the user argument of the fixed window subsurface for reasonableness\n if fixed_window_subsurface.empty?\n handle = runner.getStringArgumentValue('fixed_window_subsurface', user_arguments)\n if handle.empty?\n runner.registerError('No fixed window subsurface was chosen.')\n else\n runner.registerError(\"The selected fixed window subsurface with handle '#{handle}' was not found in the model. It may have been removed by another measure.\")\n end\n return false\n else\n if !fixed_window_subsurface.get.to_SubSurface.empty?\n fixed_window_subsurface = fixed_window_subsurface.get.to_SubSurface.get\n else\n runner.registerError('Script Error - argument not showing up as construction.')\n return false\n end\n end\n \n # Create a new EnergyManagementSystem:Sensor object representing the Surface Outside Face temp of the EMS thermochromatic window subsurface\n ems_win_Tout_sensor = OpenStudio::Model::EnergyManagementSystemSensor.new(model, \"Surface Outside Face Temperature\")\n ems_win_Tout_sensor.setName(\"Win1_Tout\")\n ems_win_Tout_sensor.setKeyName(\"#{fixed_window_subsurface.name}\")\n if verbose_info_statements == true\n runner.registerInfo(\"An EMS Sensor object named '#{ems_win_Tout_sensor.name}' representing the Surface Outside Face temp of the EMS thermochromatic window subsurface was added to the model.\") \n end\n \n # Create a new EMS Actuator Object representing the construction state of the EMS generated thermochromatic window \n ems_win_construct_actuator = OpenStudio::Model::EnergyManagementSystemActuator.new(fixed_window_subsurface, \"Surface\", \"Construction State\")\n ems_win_construct_actuator.setName(\"Win1_Construct\")\n if verbose_info_statements == true\n runner.registerInfo(\"An EMS Actuator object named '#{ems_win_construct_actuator.name}' representing construction state of the EMS generated thermochromatic window was added to the model.\") \n end\n \n # Create 19 EnergyManagementSystem:ConstructionIndexVariable objects for each unique thermochromatic construction\n ems_window_construction_array.each do |ems_window_construction|\n ems_constr_index_var = OpenStudio::Model::EnergyManagementSystemConstructionIndexVariable.new(model, ems_window_construction ) \n ems_constr_index_var.setName(\"#{ems_window_construction.name}\")\n if verbose_info_statements == true\n runner.registerInfo(\"An EMS SystemConstructionIndexVariable object named '#{ems_constr_index_var.name}' representing the the EMS construction state of the thermochromatic window was added to the model.\") \n end\n end\n \n # Create new EnergyManagementSystem:Program object for assigning different window constructions by dynamically evaluating the exterior surface temp of the fixed window subsurface \n ems_apply_thermochromatic_constructions_prgm = OpenStudio::Model::EnergyManagementSystemProgram.new(model)\n ems_apply_thermochromatic_constructions_prgm.setName(\"#{fixed_window_subsurface.name}_Control\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"IF #{ems_win_Tout_sensor.name} <= 26.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_25\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 28.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_27\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 30.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_29\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 32.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_31\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 34.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_33\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 36.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_35\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 38.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_37\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 40.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_39\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 42.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_41\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 44.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_43\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 47.5\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_45\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 52.5\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_50\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 57.5\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_55\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 62.5\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_60\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 67.5\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_65\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 72.5\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_70\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 77.5\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_75\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 82.5\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_80\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSE\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_85\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ENDIF\")\n if verbose_info_statements == true\n runner.registerInfo(\"An EMS Program Object named '#{ems_apply_thermochromatic_constructions_prgm.name}' for dynamically assigning different window constructions based on the exterior surface temp was added to the model.\") \n end\n \n # Create a new EnergyManagementSystem:ProgramCallingManager object configured to call the EMS programs\n ems_prgm_calling_mngr = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)\n ems_prgm_calling_mngr.setName(\"My thermochromic window emulator\")\n ems_prgm_calling_mngr.setCallingPoint(\"BeginTimestepBeforePredictor\")\n ems_prgm_calling_mngr.addProgram(ems_apply_thermochromatic_constructions_prgm)\n if verbose_info_statements == true\n runner.registerInfo(\"EMS Program Calling Manager object named '#{ems_prgm_calling_mngr.name}' added to call EMS program for dynamically applying a thermochromatic window.\") \n end\n \n # create unique object for OutputEnergyManagementSystems and configure to allow EMS reporting\n outputEMS = model.getOutputEnergyManagementSystem\n outputEMS.setInternalVariableAvailabilityDictionaryReporting(\"internal_variable_availability_dictionary_reporting\")\n outputEMS.setEMSRuntimeLanguageDebugOutputLevel(\"ems_runtime_language_debug_output_level\")\n outputEMS.setActuatorAvailabilityDictionaryReporting(\"actuator_availability_dictionary_reporting\")\n if verbose_info_statements == true\n runner.registerInfo(\"EMS OutputEnergyManagementSystem object configured per user arguments.\") \n end\n \n runner.registerFinalCondition(\"Measure finished with #{model.getEnergyManagementSystemSensors.count} EMS sensors, #{model.getEnergyManagementSystemActuators.count} EMS Actuators, #{model.getEnergyManagementSystemPrograms.count} EMS Programs, #{model.getEnergyManagementSystemSubroutines.count} EMS Subroutines, #{model.getEnergyManagementSystemProgramCallingManagers.count} EMS Program Calling Manager objects\")\n\n end",
"def bench(action, msg = nil)\n @t ||= Time.now\n @total ||= 0\n @step ||= 0\n case action\n when :start\n @step = 0\n @total = 0\n @t = Time.now\n when :step\n @step += 1\n int = Time.now - @t\n @total += int\n @t = Time.now\n dbg(\"Benchmark #{msg.nil? ? (\"%02d\" % @step) : msg}: #{\"%8.3fms\" % (int * 1000)} (Total: #{\"%8.3fms\" % (@total * 1000)}).\")\n end\nend",
"def apply_measure_and_run(test_name, measure, argument_map, osm_path, epw_path, run_model: false)\n assert(File.exist?(osm_path))\n assert(File.exist?(epw_path))\n\n # create run directory if it does not exist\n if !File.exist?(run_dir(test_name))\n FileUtils.mkdir_p(run_dir(test_name))\n end\n assert(File.exist?(run_dir(test_name)))\n\n # change into run directory for tests\n start_dir = Dir.pwd\n Dir.chdir run_dir(test_name)\n\n # remove prior runs if they exist\n if File.exist?(model_output_path(test_name))\n FileUtils.rm(model_output_path(test_name))\n end\n if File.exist?(report_path(test_name))\n FileUtils.rm(report_path(test_name))\n end\n\n # copy the osm and epw to the test directory\n new_osm_path = \"#{run_dir(test_name)}/#{File.basename(osm_path)}\"\n FileUtils.cp(osm_path, new_osm_path)\n new_epw_path = \"#{run_dir(test_name)}/#{File.basename(epw_path)}\"\n FileUtils.cp(epw_path, new_epw_path)\n # create an instance of a runner\n runner = OpenStudio::Measure::OSRunner.new(OpenStudio::WorkflowJSON.new)\n\n # load the test model\n model = load_model(new_osm_path)\n\n # set model weather file\n epw_file = OpenStudio::EpwFile.new(OpenStudio::Path.new(new_epw_path))\n OpenStudio::Model::WeatherFile.setWeatherFile(model, epw_file)\n assert(model.weatherFile.is_initialized)\n\n # run the measure\n puts \"\\nAPPLYING MEASURE...\"\n measure.run(model, runner, argument_map)\n result = runner.result\n\n # show the output\n show_output(result)\n\n # save model\n model.save(model_output_path(test_name), true)\n\n errs = []\n if run_model && (result.value.valueName == 'Success')\n puts \"\\nRUNNING ANNUAL SIMULATION...\"\n\n std = Standard.build('NREL ZNE Ready 2017')\n std.model_run_simulation_and_log_errors(model, run_dir(test_name))\n\n # check that the model ran successfully and generated a report\n assert(File.exist?(model_output_path(test_name)))\n assert(File.exist?(sql_path(test_name)))\n assert(File.exist?(report_path(test_name)))\n\n # set runner variables\n runner.setLastEpwFilePath(epw_path)\n runner.setLastOpenStudioModelPath(OpenStudio::Path.new(model_output_path(test_name)))\n runner.setLastEnergyPlusSqlFilePath(OpenStudio::Path.new(sql_path(test_name)))\n sql = runner.lastEnergyPlusSqlFile.get\n model.setSqlFile(sql)\n\n # test for unmet hours\n unmet_heating_hrs = std.model_annual_occupied_unmet_heating_hours(model)\n unmet_cooling_hrs = std.model_annual_occupied_unmet_cooling_hours(model)\n unmet_hrs = std.model_annual_occupied_unmet_hours(model)\n max_unmet_hrs = 550\n if unmet_hrs\n if unmet_hrs > 550\n errs << \"For #{test_name} there were #{unmet_heating_hrs.round(1)} unmet occupied heating hours and #{unmet_cooling_hrs.round(1)} unmet occupied cooling hours (total: #{unmet_hrs.round(1)}), more than the limit of #{max_unmet_hrs}.\" if unmet_hrs > max_unmet_hrs\n else\n puts \"There were #{unmet_heating_hrs.round(1)} unmet occupied heating hours and #{unmet_cooling_hrs.round(1)} unmet occupied cooling hours (total: #{unmet_hrs.round(1)}).\"\n end\n else\n errs << \"For #{test_name} could not determine unmet hours; simulation may have failed.\"\n end\n end\n\n # change back directory\n Dir.chdir(start_dir)\n\n assert(errs.empty?, errs.join(\"\\n\"))\n\n return result\n end",
"def after_assumption(name); end",
"def call\n result = while_measuring_memory_usage { action.call }\n\n Measurement.from_result(result)\n end",
"def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n # assign the user inputs to variables\n retrofit_month = runner.getStringArgumentValue('retrofit_month', user_arguments).to_i\n retrofit_day = runner.getStringArgumentValue('retrofit_day', user_arguments).to_i\n\n # report initial condition of model\n runner.registerInitialCondition(\"Measure started successfully.\")\n\n # TODO: check the month and day for reasonableness\n runner.registerInfo(\"User entered retrofit month: #{retrofit_month}\")\n runner.registerInfo(\"User entered retrofit day: #{retrofit_day}\")\n\n prog_calling_manager = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)\n prog_calling_manager.setCallingPoint('BeginTimestepBeforePredictor')\n\n # Remove old and add new equip with EMS by spaces\n hash_space_epd = Hash.new\n v_spaces = model.getSpaces\n v_spaces.each do |space|\n current_space_equip = space.electricEquipment[0]\n unless current_space_equip.nil?\n\n # Get equipment power density for each space type\n new_space_epd = runner.getOptionalDoubleArgumentValue(\"new_#{space.name.to_s}_epd\", user_arguments)\n if new_space_epd.is_initialized\n hash_space_epd[\"new_#{space.name.to_s}_epd\"] = new_space_epd\n runner.registerInfo(\"User entered new electric equipment power density for #{space.name.to_s} is #{new_space_epd} W/m2\")\n # Set ems\n current_space_equip_def = current_space_equip.electricEquipmentDefinition\n equip_sch_name = current_space_equip.schedule.get.nameString\n equip_sch_ems_sensor = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'Schedule Value')\n equip_sch_ems_sensor.setKeyName(equip_sch_name)\n runner.registerInfo(\"Delete old equip object for #{space.name}\")\n current_space_equip.remove\n\n new_equip = add_equip_space(space, current_space_equip_def)\n equip_level_w = new_space_epd.to_f * space.floorArea.to_f\n ems_equip_program = add_equip_ems(model, new_equip, equip_level_w, equip_sch_ems_sensor, retrofit_month, retrofit_day)\n prog_calling_manager.addProgram(ems_equip_program)\n runner.registerInfo(\"Add ems equipment control for #{space.name} succeeded.\")\n else\n # Get equipment power ratio for each space type\n new_space_ratio = runner.getDoubleArgumentValue(\"new_#{space.name.to_s}_ratio\", user_arguments)\n\n old_equip_sch = current_space_equip.schedule.get\n ems_equip_program = add_equip_ems_w_occ_var(model, current_space_equip, old_equip_sch, new_space_ratio, retrofit_month, retrofit_day)\n prog_calling_manager.addProgram(ems_equip_program)\n runner.registerInfo(\"Add ems equipment control for #{space.name} succeeded.\")\n # runner.registerInfo(\"Delete old equip object for #{space.name}\")\n # current_space_equip.remove\n end\n\n end\n end\n\n # Remove old and add new equip with EMS by space types\n hash_space_type_epd = Hash.new\n v_space_types = model.getSpaceTypes\n v_space_types.each do |space_type|\n current_spaces = space_type.spaces\n current_space_type_equip = space_type.electricEquipment[0]\n unless current_space_type_equip.nil?\n # Get equipment power density for each space type\n current_space_type_epd = runner.getStringArgumentValue(\"new_#{space_type.name.to_s}_epd\", user_arguments)\n hash_space_type_epd[\"new_#{space_type.name.to_s}_epd\"] = current_space_type_epd\n runner.registerInfo(\"User entered new electric equipment power density for #{space_type.name.to_s} is #{current_space_type_epd} W/m2\")\n\n # Set ems\n current_space_type_equip_def = current_space_type_equip.electricEquipmentDefinition\n current_space_type_sch_set = space_type.defaultScheduleSet.get\n current_space_type_equip_sch_set = current_space_type_sch_set.electricEquipmentSchedule.get\n\n equip_sch_name = current_space_type_equip_sch_set.nameString\n equip_sch_ems_sensor = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'Schedule Value')\n equip_sch_ems_sensor.setKeyName(equip_sch_name)\n\n puts \"Delete old equip object for #{space_type.name}\"\n current_space_type_equip.remove\n\n current_spaces.each do |space|\n # Calculate equipemtn electric power for each space\n new_equip = add_equip_space_type(model, space, space_type, current_space_type_equip_def)\n equip_level_w = current_space_type_epd.to_f * space.floorArea.to_f\n ems_equip_program = add_equip_ems(model, new_equip, equip_level_w, equip_sch_ems_sensor, retrofit_month, retrofit_day)\n prog_calling_manager.addProgram(ems_equip_program)\n runner.registerInfo(\"Add ems equipment control for #{space.name} succeeded.\")\n end\n end\n end\n\n # echo the model updates back to the user\n runner.registerInfo(\"The electric equipment retrofit measure is applied.\")\n\n # report final condition of model\n runner.registerFinalCondition(\"Measure ended successfully.\")\n\n return true\n end",
"def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n runner.registerInfo(\"Start to create lighting measure from occupant schedule\")\n\n ### Get user selected lighting space assumptions for each space\n v_space_types = model.getSpaceTypes\n i = 1\n lght_space_type_arg_vals = {}\n # Loop through all space types, group spaces by their types\n v_space_types.each do |space_type|\n # Loop through all spaces of current space type\n v_current_spaces = space_type.spaces\n next if not v_current_spaces.size > 0\n v_current_spaces.each do |current_space|\n lght_space_type_val = runner.getStringArgumentValue(@@v_space_args[current_space.nameString], user_arguments)\n lght_space_type_arg_vals[current_space.nameString] = lght_space_type_val\n i += 1\n end\n end\n\n puts lght_space_type_arg_vals\n\n ### Start creating new lighting schedules based on occupancy schedule\n occ_schedule_dir = runner.getStringArgumentValue('occ_schedule_dir', user_arguments)\n model_temp_run_path = Dir.pwd + '/'\n measure_root_path = File.dirname(__FILE__)\n\n puts '=' * 80\n puts measure_root_path\n\n if File.file?(occ_schedule_dir)\n # Check if user provided a occupancy schedule CSV file\n csv_file = occ_schedule_dir\n puts 'Use user provided occupancy schedule file at: ' + csv_file.to_s\n runner.registerInitialCondition('Location check:' + File.expand_path(\"../..\", measure_root_path))\n # runner.registerInitialCondition('Use user provided occupancy schedule file at: ' + csv_file.to_s)\n else\n # Check if schedule file at several places\n # 1. Default fils path when run with OSW in CLI\n csv_path_lookup_1 = File.expand_path(\"../..\", measure_root_path) + \"/files/#{@@default_occupant_schedule_filename}\"\n puts '#' * 80\n puts \"First lookup location: \" + csv_path_lookup_1\n runner.registerInfo(\"First lookup location: \" + csv_path_lookup_1)\n # 2. Default path when run with OpenStudio CLI\n csv_path_lookup_2 = File.expand_path(\"../..\", model_temp_run_path) + \"/files/#{@@default_occupant_schedule_filename}\"\n puts '#' * 80\n puts \"Second lookup location: \" + csv_path_lookup_2\n runner.registerInfo(\"Second lookup location: \" + csv_path_lookup_2)\n # 3. Default path when run with OpenStudio GUI\n csv_path_lookup_3 = File.expand_path(\"../../..\", model_temp_run_path) + \"/resources/files/#{@@default_occupant_schedule_filename}\"\n puts '#' * 80\n puts \"Third lookup location: \" + csv_path_lookup_3\n runner.registerInfo(\"Third lookup location: \" + csv_path_lookup_3)\n # 4. Generated files folder when run with rspec\n csv_path_lookup_4 = File.expand_path(\"..\", model_temp_run_path) + \"/generated_files/#{@@default_occupant_schedule_filename}\"\n puts '#' * 80\n puts \"Forth lookup location: \" + csv_path_lookup_4\n runner.registerInfo(\"Forth lookup location: \" + csv_path_lookup_4)\n # 5. Generated files folder with OpenStudio V2.9.0+\n csv_path_lookup_5 = File.join(File.expand_path(\"../..\", model_temp_run_path), 'generated_files', @@default_occupant_schedule_filename)\n puts '#' * 80\n puts \"Fifth lookup location: \" + csv_path_lookup_5\n runner.registerInfo(\"Fifth lookup location: \" + csv_path_lookup_5)\n\n if File.file?(csv_path_lookup_1)\n csv_file = csv_path_lookup_1\n elsif File.file?(csv_path_lookup_2)\n csv_file = csv_path_lookup_2\n elsif File.file?(csv_path_lookup_3)\n csv_file = csv_path_lookup_3\n elsif File.file?(csv_path_lookup_4)\n csv_file = csv_path_lookup_4 \n elsif File.file?(csv_path_lookup_5)\n csv_file = csv_path_lookup_5\n else\n csv_file = ''\n end\n puts 'Use default occupancy schedule file at: ' + csv_file.to_s\n runner.registerInfo('Use default occupancy schedule file at: ' + csv_file.to_s)\n end\n\n # Get the spaces with occupancy count schedule available\n v_spaces_occ_sch = File.readlines(csv_file)[3].split(',') # Room ID is saved in 4th row of the occ_sch file\n v_headers = Array.new\n v_spaces_occ_sch.each do |space_occ_sch|\n if !['Room ID', 'Outdoor', 'Outside building'].include? space_occ_sch and !space_occ_sch.strip.empty?\n v_headers << space_occ_sch\n end\n end\n v_headers = [\"Time\"] + v_headers\n\n # report initial condition of model\n runner.registerInfo(\"The building has #{v_headers.length - 1} spaces with available occupant schedule file.\")\n\n # Read the occupant count schedule file and clean it\n clean_csv = File.readlines(csv_file).drop(6).join\n csv_table_sch = CSV.parse(clean_csv, headers: true)\n new_csv_table = csv_table_sch.by_col!.delete_if do |column_name, column_values|\n !v_headers.include? column_name\n end\n\n runner.registerInfo(\"Successfully read occupant count schedule from CSV file.\")\n runner.registerInfo(\"Creating new lighting schedules...\")\n\n # Create lighting schedule based on the occupant count schedule\n v_cols = Array.new\n v_ts = new_csv_table.by_col!['Time']\n v_headers.each do |header|\n if header != 'Time'\n space_name = header\n v_occ_n = new_csv_table.by_col![space_name]\n v_light = create_lighting_sch_from_occupancy_count(space_name, v_ts, v_occ_n, @@off_delay)\n v_cols << v_light\n end\n end\n\n runner.registerInfo(\"Writing new lighting schedules to CSV file.\")\n # Write new lighting schedule file to CSV\n file_name_light_sch = \"#{model_temp_run_path}/#{@@lighting_schedule_CSV_name}\"\n vcols_to_csv(v_cols, file_name_light_sch)\n\n # Add new lighting schedule from the CSV file created\n runner.registerInfo(\"Removing old OS:Lights and OS:Lights:Definition for office and conference rooms.\")\n # Remove old lights definition objects for office and conference rooms\n v_space_types.each do |space_type|\n space_type.spaces.each do |space|\n selected_space_type = lght_space_type_arg_vals[space.name.to_s]\n if (@@office_type_names.include? selected_space_type) || (@@conference_room_type_names.include? selected_space_type)\n space_type.lights.each do |lght|\n puts 'Remove old lights definition object: ' + lght.lightsDefinition.name.to_s\n lght.lightsDefinition.remove\n end\n end\n end\n end\n\n # Remove old lights objects for office and conference rooms\n # Caution: the order of deletion matters\n v_space_types.each do |space_type|\n space_type.spaces.each do |space|\n selected_space_type = lght_space_type_arg_vals[space.name.to_s]\n if (@@office_type_names.include? selected_space_type) || (@@conference_room_type_names.include? selected_space_type)\n space_type.lights.each do |lght|\n puts 'Remove old lights object: ' + lght.name.to_s\n lght.remove\n end\n end\n end\n end\n\n puts '---> Create new lighting schedules from CSV.'\n\n runner.registerInfo(\"Adding new OS:Schedule:File objects to the model....\")\n v_spaces = model.getSpaces\n v_spaces.each do |space|\n v_headers.each_with_index do |s_space_name, i|\n if s_space_name == space.name.to_s\n col = i\n temp_file_path = file_name_light_sch\n sch_file_name = space.name.to_s + ' lght sch'\n schedule_file = get_os_schedule_from_csv(model, temp_file_path, sch_file_name, col, skip_row = 1)\n schedule_file.setMinutesperItem(@@minute_per_item.to_s)\n model = add_light(model, space, schedule_file)\n end\n end\n end\n\n # report final condition of model\n runner.registerFinalCondition(\"Finished creating and adding new lighting schedules for #{v_headers.length - 1} spaces.\")\n\n return true\n end",
"def span\n measure\n @span\n end",
"def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n \n #use the built-in error checking \n if not runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n # System Type 2: PTHP, Residential\n # This measure creates:\n # a constant volume packaged terminal heat pump unit with DX heating \n # and cooling for each zone in the building\n \n always_on = model.alwaysOnDiscreteSchedule\n\n # Make a PTHP for each zone\n model.getThermalZones.each do |zone|\n \n fan = OpenStudio::Model::FanConstantVolume.new(model,always_on)\n fan.setPressureRise(300)\n\n supplemental_htg_coil = OpenStudio::Model::CoilHeatingElectric.new(model,always_on)\n\n clg_cap_f_of_temp = OpenStudio::Model::CurveBiquadratic.new(model)\n clg_cap_f_of_temp.setCoefficient1Constant(0.942587793)\n clg_cap_f_of_temp.setCoefficient2x(0.009543347)\n clg_cap_f_of_temp.setCoefficient3xPOW2(0.0018423)\n clg_cap_f_of_temp.setCoefficient4y(-0.011042676)\n clg_cap_f_of_temp.setCoefficient5yPOW2(0.000005249)\n clg_cap_f_of_temp.setCoefficient6xTIMESY(-0.000009720)\n clg_cap_f_of_temp.setMinimumValueofx(17.0)\n clg_cap_f_of_temp.setMaximumValueofx(22.0)\n clg_cap_f_of_temp.setMinimumValueofy(13.0)\n clg_cap_f_of_temp.setMaximumValueofy(46.0)\n\n clg_cap_f_of_flow = OpenStudio::Model::CurveQuadratic.new(model)\n clg_cap_f_of_flow.setCoefficient1Constant(0.718954)\n clg_cap_f_of_flow.setCoefficient2x(0.435436)\n clg_cap_f_of_flow.setCoefficient3xPOW2(-0.154193)\n clg_cap_f_of_flow.setMinimumValueofx(0.75)\n clg_cap_f_of_flow.setMaximumValueofx(1.25)\n\n clg_energy_input_ratio_f_of_temp = OpenStudio::Model::CurveBiquadratic.new(model)\n clg_energy_input_ratio_f_of_temp.setCoefficient1Constant(0.342414409)\n clg_energy_input_ratio_f_of_temp.setCoefficient2x(0.034885008)\n clg_energy_input_ratio_f_of_temp.setCoefficient3xPOW2(-0.000623700)\n clg_energy_input_ratio_f_of_temp.setCoefficient4y(0.004977216)\n clg_energy_input_ratio_f_of_temp.setCoefficient5yPOW2(0.000437951)\n clg_energy_input_ratio_f_of_temp.setCoefficient6xTIMESY(-0.000728028)\n clg_energy_input_ratio_f_of_temp.setMinimumValueofx(17.0)\n clg_energy_input_ratio_f_of_temp.setMaximumValueofx(22.0)\n clg_energy_input_ratio_f_of_temp.setMinimumValueofy(13.0)\n clg_energy_input_ratio_f_of_temp.setMaximumValueofy(46.0)\n\n clg_energy_input_ratio_f_of_flow = OpenStudio::Model::CurveQuadratic.new(model)\n clg_energy_input_ratio_f_of_flow.setCoefficient1Constant(1.1552)\n clg_energy_input_ratio_f_of_flow.setCoefficient2x(-0.1808)\n clg_energy_input_ratio_f_of_flow.setCoefficient3xPOW2(0.0256)\n clg_energy_input_ratio_f_of_flow.setMinimumValueofx(0.5)\n clg_energy_input_ratio_f_of_flow.setMaximumValueofx(1.5)\n\n clg_part_load_fraction = OpenStudio::Model::CurveQuadratic.new(model)\n clg_part_load_fraction.setCoefficient1Constant(0.75)\n clg_part_load_fraction.setCoefficient2x(0.25)\n clg_part_load_fraction.setCoefficient3xPOW2(0.0)\n clg_part_load_fraction.setMinimumValueofx(0.0)\n clg_part_load_fraction.setMaximumValueofx(1.0)\n\n clg_coil = OpenStudio::Model::CoilCoolingDXSingleSpeed.new(model,\n always_on,\n clg_cap_f_of_temp,\n clg_cap_f_of_flow,\n clg_energy_input_ratio_f_of_temp,\n clg_energy_input_ratio_f_of_flow,\n clg_part_load_fraction)\n\n htg_cap_f_of_temp = OpenStudio::Model::CurveCubic.new(model)\n htg_cap_f_of_temp.setCoefficient1Constant(0.758746)\n htg_cap_f_of_temp.setCoefficient2x(0.027626)\n htg_cap_f_of_temp.setCoefficient3xPOW2(0.000148716)\n htg_cap_f_of_temp.setCoefficient4xPOW3(0.0000034992)\n htg_cap_f_of_temp.setMinimumValueofx(-20.0)\n htg_cap_f_of_temp.setMaximumValueofx(20.0)\n\n htg_cap_f_of_flow = OpenStudio::Model::CurveCubic.new(model)\n htg_cap_f_of_flow.setCoefficient1Constant(0.84)\n htg_cap_f_of_flow.setCoefficient2x(0.16)\n htg_cap_f_of_flow.setCoefficient3xPOW2(0.0)\n htg_cap_f_of_flow.setCoefficient4xPOW3(0.0)\n htg_cap_f_of_flow.setMinimumValueofx(0.5)\n htg_cap_f_of_flow.setMaximumValueofx(1.5)\n\n htg_energy_input_ratio_f_of_temp = OpenStudio::Model::CurveCubic.new(model)\n htg_energy_input_ratio_f_of_temp.setCoefficient1Constant(1.19248)\n htg_energy_input_ratio_f_of_temp.setCoefficient2x(-0.0300438)\n htg_energy_input_ratio_f_of_temp.setCoefficient3xPOW2(0.00103745)\n htg_energy_input_ratio_f_of_temp.setCoefficient4xPOW3(-0.000023328)\n htg_energy_input_ratio_f_of_temp.setMinimumValueofx(-20.0)\n htg_energy_input_ratio_f_of_temp.setMaximumValueofx(20.0)\n\n htg_energy_input_ratio_f_of_flow = OpenStudio::Model::CurveQuadratic.new(model)\n htg_energy_input_ratio_f_of_flow.setCoefficient1Constant(1.3824)\n htg_energy_input_ratio_f_of_flow.setCoefficient2x(-0.4336)\n htg_energy_input_ratio_f_of_flow.setCoefficient3xPOW2(0.0512)\n htg_energy_input_ratio_f_of_flow.setMinimumValueofx(0.0)\n htg_energy_input_ratio_f_of_flow.setMaximumValueofx(1.0)\n\n htg_part_load_fraction = OpenStudio::Model::CurveQuadratic.new(model)\n htg_part_load_fraction.setCoefficient1Constant(0.75)\n htg_part_load_fraction.setCoefficient2x(0.25)\n htg_part_load_fraction.setCoefficient3xPOW2(0.0)\n htg_part_load_fraction.setMinimumValueofx(0.0)\n htg_part_load_fraction.setMaximumValueofx(1.0)\n\n htg_coil = OpenStudio::Model::CoilHeatingDXSingleSpeed.new( model,\n always_on,\n htg_cap_f_of_temp,\n htg_cap_f_of_flow,\n htg_energy_input_ratio_f_of_temp,\n htg_energy_input_ratio_f_of_flow,\n htg_part_load_fraction ) \n\n pthp = OpenStudio::Model::ZoneHVACPackagedTerminalHeatPump.new(model,\n always_on, \n fan,\n htg_coil,\n clg_coil,\n supplemental_htg_coil)\n\n pthp.setName(\"#{zone.name} PTHP\")\n pthp.addToThermalZone(zone)\n\n end\n\n \n return true\n \n end"
] |
[
"0.79848564",
"0.7639647",
"0.76355976",
"0.7170129",
"0.66926914",
"0.66926914",
"0.66718984",
"0.66311747",
"0.6599127",
"0.65870225",
"0.65324444",
"0.6481582",
"0.6405596",
"0.64028287",
"0.6333309",
"0.6283632",
"0.6283632",
"0.6283632",
"0.6281165",
"0.6269874",
"0.62425435",
"0.62203735",
"0.6198304",
"0.6196627",
"0.6196627",
"0.61319697",
"0.6107745",
"0.60714525",
"0.60513526",
"0.601827",
"0.6008391",
"0.6008391",
"0.60008335",
"0.5976995",
"0.59641606",
"0.5962238",
"0.5958165",
"0.59570605",
"0.59570605",
"0.59439784",
"0.5934565",
"0.5928137",
"0.5920926",
"0.5916211",
"0.59129107",
"0.5911706",
"0.59022516",
"0.5872101",
"0.5865909",
"0.58645797",
"0.5847354",
"0.583844",
"0.58373237",
"0.57887447",
"0.5772885",
"0.57687855",
"0.5756301",
"0.5745138",
"0.5740855",
"0.5723286",
"0.57180965",
"0.5713821",
"0.5698708",
"0.5697907",
"0.56978434",
"0.56891346",
"0.5688938",
"0.5685465",
"0.56740844",
"0.5662743",
"0.5649326",
"0.56483626",
"0.5646554",
"0.56390476",
"0.56390476",
"0.5633756",
"0.56218606",
"0.56218606",
"0.5608723",
"0.5608213",
"0.55982304",
"0.55982304",
"0.55982304",
"0.55982304",
"0.55982304",
"0.55982304",
"0.55982304",
"0.55982304",
"0.55982304",
"0.559522",
"0.559522",
"0.559522",
"0.55878526",
"0.558349",
"0.55677843",
"0.5567233",
"0.5564496",
"0.55636495",
"0.55590993",
"0.5556679",
"0.5547891"
] |
0.0
|
-1
|
The size of the response body in bytes
|
def length
return unless headers['Content-Length']
headers['Content-Length'].to_i
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def size\n return self.body_data.size\n end",
"def size\n headers[:content_length].to_i\n end",
"def size\n headers[\"content-length\"].to_i\n end",
"def content_length\n @content_length ||= @response_impl.entity.content_length\n end",
"def size\n @content.bytesize\n end",
"def body_size\n request = $postgres.exec_prepared('wsfile_body_size', [self.id])\n request[0].map{|k,v| v.to_i || 0}.inject(:+)\n end",
"def size\n @heads['content-length'] || @size.to_s\n end",
"def content_length; end",
"def content_length; end",
"def content_length; end",
"def size\n @size ||= @request[FSIZE].to_i\n end",
"def size\n content.size\n end",
"def fix_length response\r\n size = 0\r\n response.body.each {|str| size += str.scan(/\\n/).size}\r\n size += response.headers['Content-Length'].to_i\r\n response.headers['Content-Length'] = size.to_s\r\n return response\r\n end",
"def content_length\n stat.size\n end",
"def size\n read.bytesize\n end",
"def size\n to_payload.bytesize\n end",
"def size\n execute_request(:get, '/size').body.to_i\n end",
"def size\n @contents.bytes.size\n end",
"def size_in_bytes\n @grpc.size_bytes\n end",
"def length\n (headers[\"content-length\"] || -1).to_i\n end",
"def content_length\n @resource.content_length\n end",
"def content_length\n @content_length ||= ((s = self[HttpClient::CONTENT_LENGTH]) &&\n (s =~ /^(\\d+)$/)) ? $1.to_i : nil\n end",
"def size\n easy = Curl::Easy.new\n easy.url = self.uri + \"/size\"\n easy.http_get\n\n raise(SesameException.new(easy.body_str)) unless easy.response_code == 200\n\n easy.body_str.to_i\n end",
"def size\n @data.bytesize\n end",
"def size_in_bytes\n to_i description['SizeInBytes']\n end",
"def size\n @content.size\n end",
"def size_in_byte\n return @size_in_byte\n end",
"def size\n @raw_page['totalSize'] || @raw_page['size']\n end",
"def size\n @io.size\n end",
"def size\n @data ? @data.size : header.sh_size\n end",
"def content_size; @message_impl.getContentSize; end",
"def content_length\n if raw? && raw.respond_to?(:length)\n raw.length\n else\n read.try(&:length).to_i\n end\n end",
"def body_count\n body.length\n end",
"def size\n @fetcher.size\n end",
"def bytesize\n stream_size\n end",
"def size\n @buffer.size\n end",
"def size\n @buffer.size\n end",
"def size\n @buffer.size\n end",
"def get_size\n\t\tend",
"def size(path)\n response = with_remote do |http|\n http.head(path)\n end\n response['Content-Length'].to_i\n end",
"def size\n Integer(metadata[\"size\"]) if metadata[\"size\"]\n end",
"def size\n @size ||= get_size(\"/yaml\")\n end",
"def length\n @content.length\n end",
"def size\n @size \n end",
"def size\n @size \n end",
"def size_page_body\n size - size_fil_trailer - size_fil_header\n end",
"def size\n get.size\n end",
"def size\n @info[:size]\n end",
"def content_length\n\t\treturn 0 unless self.header.member?( :content_length )\n\t\treturn Integer( self.header.content_length )\n\tend",
"def size\n @size ||= @buffer.size\n end",
"def size\n file.content_length\n end",
"def size\n stream_size * 8\n end",
"def extract_size(io)\n io.size\n end",
"def get_content_length\n\t\treturn 0 if self.bodiless?\n\n\t\tif self.body.pos.nonzero? && !self.body.eof?\n\t\t\tself.log.info \"Calculating content length based on an offset of %d\" % [ self.body.pos ]\n\t\t\treturn self.body.size - self.body.pos\n\t\telse\n\t\t\tself.log.debug \"Calculating body size via %p\" % [ self.body.method(:size) ]\n\t\t\treturn self.body.size\n\t\tend\n\tend",
"def getcontentlength\n 0\n end",
"def get_size\n\t\treturn @size\n\tend",
"def file_size\n stream.size\n end",
"def part_size_in_bytes\n data.part_size_in_bytes\n end",
"def num_bytes\n return @num_bytes\n end",
"def content_length\n raise NotImplementedError\n end",
"def size\n @size\n end",
"def size\n @size\n end",
"def size\n @size\n end",
"def remote_size\n return @remote_size if defined?(@remote_size)\n @remote_size = http_head['Content-Length'].to_i\n end",
"def uncompressed_size\n @header.size\n end",
"def content_length\n# stat.size\n @bson['length'] || 0\n end",
"def size\n return @size\n end",
"def size\n return @size\n end",
"def size\n blob.size\n end",
"def size\n return instance_get(:size)\n end",
"def size\n @result.size\n end",
"def size\n\n self.to_h.size\n end",
"def size\n return @data.size\n end",
"def size\n @data.size\n end",
"def size\n @data.size\n end",
"def size\n @data.size\n end",
"def size; @_io.size; end",
"def getSize() \n @obj.getSize()\n end",
"def body_info\n if is_io?\n \"#{body.class.name}, size: #{body.respond_to?(:lstat) ? body.lstat.size : body.size}, pos: #{body.pos}\"\n else\n \"size: #{body.to_s.bytesize}, first #{BODY_BYTES_TO_LOG} bytes:\\n#{body.to_s[0...BODY_BYTES_TO_LOG]}\"\n end\n end",
"def size\n @size\n end",
"def size\n return @size\n end",
"def size\n return @size\n end",
"def size\r\n @contents.size\r\n end",
"def size\n info[\"size\"]\n end",
"def size\n @info.size\n end",
"def size\n @info.size\n end",
"def size\n @info.size\n end",
"def size\n @size\n end",
"def size\n contents.size\n end",
"def size\n return @data.size\n end",
"def size\n @data.size\n end",
"def size\n @data.size\n end",
"def size\n @size.size\n end",
"def size\r\n self.data.length\r\n end",
"def size_in_bytes\n ( file_length * 16 ) / 8\n end",
"def size ; data['size'] ; end",
"def total_payload_size\n length + 16 * character_count\n end",
"def size()\n @requests.length\n end",
"def remote_size\n @remote_size ||= request_object_size\n end",
"def size\r\n @pack.size\r\n end"
] |
[
"0.8582555",
"0.81752867",
"0.8123521",
"0.7706874",
"0.7686452",
"0.75658625",
"0.7531498",
"0.75173146",
"0.75173146",
"0.75173146",
"0.75098795",
"0.74790996",
"0.7388736",
"0.7364366",
"0.7336657",
"0.7324811",
"0.7273663",
"0.7240597",
"0.7214723",
"0.72112787",
"0.7198508",
"0.7185079",
"0.71726227",
"0.7155225",
"0.71472365",
"0.7138895",
"0.71349305",
"0.71022063",
"0.7096536",
"0.7083373",
"0.7078753",
"0.70755726",
"0.7048625",
"0.70416296",
"0.7023857",
"0.6994379",
"0.6994379",
"0.6994379",
"0.69498986",
"0.6947303",
"0.6914736",
"0.69007486",
"0.6892136",
"0.6889044",
"0.6889044",
"0.68720657",
"0.68577",
"0.68574774",
"0.6852057",
"0.6845182",
"0.68246293",
"0.6821787",
"0.6808971",
"0.679865",
"0.6795153",
"0.6790881",
"0.67843944",
"0.6767046",
"0.676551",
"0.67620575",
"0.6761056",
"0.6761056",
"0.6761056",
"0.6757242",
"0.6752385",
"0.67368126",
"0.6733218",
"0.6733218",
"0.6731099",
"0.67244124",
"0.67155784",
"0.671518",
"0.6711028",
"0.67093736",
"0.67093736",
"0.67093736",
"0.67091835",
"0.66958785",
"0.6693681",
"0.6684411",
"0.667846",
"0.667846",
"0.6674391",
"0.66698486",
"0.6659759",
"0.6659759",
"0.6659759",
"0.665124",
"0.66458297",
"0.6645741",
"0.6638754",
"0.6638754",
"0.6625259",
"0.6617515",
"0.6612147",
"0.66057974",
"0.66028893",
"0.6598189",
"0.6593676",
"0.659314"
] |
0.7821559
|
3
|
The MD5 digest of the response body
|
def md5
headers['Content-MD5']
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def md5\n return self.body_data.md5\n end",
"def md5_of_body\n data[:md5_of_body]\n end",
"def digest\n Digest::MD5.digest(blob)\n end",
"def md5\n render :json => { :hash => Digest::MD5.hexdigest(md5_query.to_s) }\n end",
"def md5\n @gapi[\"md5Hash\"]\n end",
"def digest\n Digest::MD5.file(file).hexdigest\n end",
"def md5\n Base64.strict_encode64(@signature.md5)\n end",
"def digest\n decode[:digest]\n end",
"def digest\n metadata[:digest]\n end",
"def md5 hash\n\t\treturn Digest::MD5.hexdigest(hash.to_s).to_s\n\tend",
"def digest\n ''\n end",
"def digest\n ''\n end",
"def md5\n @md5 ||= digest(path, :md5)\n end",
"def md5sum\n @md5sum ||= Digest::MD5.hexdigest(self.to_checksum_string)\n end",
"def md5\n @attributes[:md5]\n end",
"def digest(data); end",
"def digest\n @digest ||= Digest::MD5.hexdigest(self.attributes[self.class.config[:digest]])[0, 8]\n end",
"def get_md5sum(file)\n get_sum(file, 'md5')\n end",
"def md5sum\n Digest::MD5.hexdigest(self)\n end",
"def file_remote_digestmd5(file_name)\n data = read_file(file_name)\n chksum = nil\n if data\n chksum = Digest::MD5.hexdigest(data)\n end\n return chksum\n end",
"def digest\n Digest::MD5.hexdigest(id.to_s+Interactiff::Application.config.secret_token).to_i(16).to_s[3,8]\n end",
"def digest_file( x)\n path = requested_file( x[:request] )\n if File.exist?(path) && !File.directory?(path)\n Digest::MD5.hexdigest(File.read(path))\n else\n nil\n end\n end",
"def etag_for content\n Digest::MD5.hexdigest(content)\n end",
"def checksum\n source[digest_type]\n end",
"def uri_to_md5 (uri)\n Digest::MD5.hexdigest(uri.to_s)\n end",
"def digest\n @digest ||= DEFAULT_DIGEST_PROC\n end",
"def md5_of_message_attributes\n data[:md5_of_message_attributes]\n end",
"def md5_hash(data)\n md5 = Digest::MD5.new\n md5 << data\n md5.hexdigest\n end",
"def hash\n digest = Digest::MD5.new\n digest << title.to_s\n digest << content.join('').to_s\n digest.to_s\n end",
"def digest\n Digest::SHA2.new\n end",
"def _hash_digest(key)\n m = Digest::MD5.new\n m.update(key)\n\n # No need to ord each item since ordinary array access\n # of a string in Ruby converts to ordinal value\n return m.digest\n end",
"def md5\n\t\tDigest::MD5.hexdigest(self)\n\tend",
"def fetch_md5\n # Create a hash digest for the current file.\n digest = Digest::MD5.new\n File.open(@path, 'r') do |handle|\n while buffer = handle.read(1024)\n digest << buffer\n end\n end\n digest\n end",
"def result\n @_result ||= Digest::MD5.hexdigest(param_string)\n end",
"def digest(subject)\n Digest::MD5.hexdigest subject.downcase\n end",
"def digest\n digest = ''\n @entries.each { |entry| digest << entry.digest << ' ' }\n digest\n end",
"def md5\n Digest::MD5.file(@path).to_s\n end",
"def digest\n digest = ''\n @elements.each { |element| digest << element.digest << ' '}\n digest\n end",
"def md5\n Digest::MD5.hexdigest(self)\n end",
"def digest\n Digest::SHA1.hexdigest(self)\n end",
"def createMD5Hash(data)\n\t\treturn Digest::MD5.digest(data)\n\tend",
"def cram_md5_challenge; end",
"def md5?; @md5; end",
"def hexdigest\n # Read bytes in chunks of the optimal digest size.\n while (chunk = @io.read(@digest.block_length))\n @digest.update(chunk)\n end\n @digest.hexdigest\n end",
"def checksum\n fil_header[:checksum]\n end",
"def digestmd5(file2md5)\n if not ::File.exists?(file2md5)\n raise \"File #{file2md5} does not exists!\"\n else\n require 'digest/md5'\n chksum = nil\n chksum = Digest::MD5.hexdigest(::File.open(file2md5, 'rb') { |f| f.read })\n return chksum\n end\n end",
"def calculate_payload_hash\n\t\treturn Digest::SHA2.hexdigest( self.payload )\n\tend",
"def digest\n @request.header('Authorization')\n end",
"def file_md5\n Digest::MD5.file(self).hexdigest\n end",
"def digest\n OpenSSL::HMAC.digest(\n OpenSSL::Digest.new('sha1'),\n secret,\n document\n )\n end",
"def md5(value)\n merge(md5: value.to_s)\n end",
"def expected_response(http_method, uri, credentials, password, password_is_ha1=true)\n ha1 = password_is_ha1 ? password : ha1(credentials, password)\n ha2 = ::Digest::MD5.hexdigest([http_method.to_s.upcase, uri].join(':'))\n ::Digest::MD5.hexdigest([ha1, credentials[:nonce], credentials[:nc], credentials[:cnonce], credentials[:qop], ha2].join(':'))\n end",
"def passive\t\t\n\tif @body.size > 4\n\t\thash=Digest::MD5.hexdigest(@body[0..500])\t\n\t\t[{:name=>\"hash\",:string=>hash}]\n\telse\n\t\t[]\n\tend\nend",
"def digest\n Digest::SHA1.hexdigest(@pub.to_der)\n end",
"def security_key\n params['x_MD5_Hash']\n end",
"def table_digest(table)\n digest = Digest::MD5.new\n table.flatten.each do |cell|\n digest.update(unescape(cell))\n end\n return digest.to_s\n end",
"def compute_checksum(h)\n begin\n signed_h = h.dup.with_indifferent_access\n CLEAR_OPTIONS.map{|o| signed_h.delete(o) }\n marshaled = ActionController::Routing::Route.new.build_query_string(signed_h)\n marshaled = marshaled.gsub(/^\\?/, '').split(/&/).sort.join('&')\n digest.call(self, Base64.encode64(marshaled.to_s.reverse)).to_s\n ensure\n end\n end",
"def hexdigest\n @digest.unpack('H*'.freeze).first\n end",
"def checksum_of(url, etag, last_modified)\n #noinspection RubyArgCount\n Zlib::crc32(url + etag + last_modified).to_s\n end",
"def md5(string)\n\tDigest::MD5.hexdigest(string)\nend",
"def digest\n case @signature_method\n when \"HMAC-SHA256\" then OpenSSL::Digest.new(\"sha256\")\n when \"HMAC-SHA1\" then OpenSSL::Digest.new(\"sha1\")\n else\n fail InvalidSignatureMethodError\n end\n end",
"def to_md5(salt = \"\")\n hashsum(:md5, salt)\n end",
"def etag_and_return(response)\n content_type 'application/json'\n etag Digest::MD5.hexdigest(response.inspect)\n JSON.dump(response)\n end",
"def digest(obj)\n build_digest(obj).digest\n end",
"def digest\n @digest ||= Digest::SHA1.new.update(version.to_s)\n @digest.dup\n end",
"def digested_canonicalized_data\n \n @string = \"\"\n @string << CGI::unescapeHTML(self.canonicalized_data.gsub(/\\n/, ''))\n return Base64::encode64(Digest::SHA1.digest(@string))\n \n end",
"def md5_sum(key)\n md5 = Digest::MD5.new\n buffer = ''\n with_input_io(key) do |io|\n while io.read(65536, buffer)\n md5 << buffer\n end\n end\n md5.base64digest\n end",
"def digest_for(entry) \n MD5.hexdigest( [ entry.title, entry.content, entry.date_published ].join )\n end",
"def security_key\n params['x_MD5_Hash']\n end",
"def checksum\n render json: content_files_checksums(druid).to_json\n end",
"def hash\n Digest::MD5.hexdigest(abs_filepath)[0..5]\n end",
"def block_hash\n\t\tdigest = Digest::SHA2.new\n\n\t\tdigest << '%d' % [ self.index ]\n\t\tdigest << self.timestamp.strftime( '%s%N' )\n\t\tdigest << self.payload\n\t\tdigest << self.payload_hash\n\t\tdigest << self.proof.to_s\n\t\tdigest << self.previous_hash\n\t\t\n\t\treturn digest.hexdigest\n\tend",
"def extract_digest_from_manifest(manifest)\n # https://docs.docker.com/registry/spec/api/#manifest\n return manifest.headers[:docker_content_digest]\n end",
"def checksum\n @checksum ||= begin\n if empty?\n EMPTY_CHECKSUM\n else\n ::Digest::MD5.hexdigest(children.map(&:checksum).join)\n end\n end.to_s\n end",
"def base64digest\n DigestUtils.pack_base64digest(digest)\n end",
"def to_md5(pass)\r\n return Digest::MD5.hexdigest(pass)\r\nend",
"def hexdigest\n DigestUtils.pack_hexdigest(digest)\n end",
"def digest\n image.ident\n end",
"def _md5(str)\n js_context.call('newrank_md5', str, bare: true)\n end",
"def digest_hash_function\n decode[:hash_function]\n end",
"def to_md5(pass)\n return Digest::MD5.hexdigest(pass)\nend",
"def digest_length\n check_valid\n md.md_size\n end",
"def upstream_md5=( checksum )\n @digest = Crate::Digest.md5( checksum )\n end",
"def digest(string)\n @digest_class.new(string).digest\n end",
"def hash\n return Digest::MD5.hexdigest(self.describe(' '))\n end",
"def digest\n OpenSSL::Digest::SHA256.file(path).hexdigest\n end",
"def hash!\n\t\t@@email.downcase!\n\t\thash = Digest::MD5.hexdigest(@@email)\n\t\treturn hash\n\tend",
"def md5_hash(ts, public_key)\n private_key = Rails.application.credentials.marvel[:private_key]\n Digest::MD5.hexdigest(ts + private_key + public_key)\n end",
"def to_s\n digest.to_s\n end",
"def to_md5(length = 32)\n Digest::MD5.hexdigest(self)[0,length]\n end",
"def checksum\n digest = @digest_klass.new\n buf = ''\n\n File.open(@path, \"rb\") do |f|\n while !f.eof\n begin\n f.readpartial(BUFFER_SIZE, buf)\n digest.update(buf)\n rescue EOFError\n # Although we check for EOF earlier, this seems to happen\n # sometimes anyways [GH-2716].\n break\n end\n end\n end\n\n digest.hexdigest\n end",
"def get_file_hash(fullPath)\n contents = File.read(fullPath)\n fileHash = Digest::MD5.hexdigest(contents)\n return fileHash\nend",
"def digest_length\n decode[:length]\n end",
"def calculate_checksum\n last_checksum = previous_event&.checksum\n attrs = attributes.except(\"checksum\", \"id\", \"updated_at\").merge(last_checksum: last_checksum)\n cs = Digest::SHA256.hexdigest(attrs.to_s)\n puts \"#{id} calculate_checksum: #{cs} <- #{attrs} \" if Rails.env.development?\n Rails.logger.info(\"#{id} calculate_checksum: #{cs} <- #{attrs} \")\n return cs\n end",
"def hexdigest\n @authenticator.unpack(\"H*\").last\n end",
"def md5sum_file(file)\n return `md5sum #{file}`\n end",
"def checksum!\n # Get a deep copy of hash to compare with\n @_original_hash = Marshal.load(Marshal.dump(to_hash))\n # create a copy of basic elements\n base = self.reject { |k,_| ['_id', '_rev', 'couchrest-hash'].include? k.to_s }\n\n result = nil\n\n flatten =\n lambda {|r|\n (recurse = lambda {|v|\n if v.is_a?(Hash) || v.is_a?(CouchRest::Document)\n v.to_a.map{|v| recurse.call(v)}.flatten\n elsif v.is_a?(Array)\n v.flatten.map{|v| recurse.call(v)}\n else\n v.to_s\n end\n }).call(r)\n }\n self['couchrest-hash'] = Digest::MD5.hexdigest(flatten.call(base).sort.join(''))\n end",
"def digest\n assert_file!\n Digest::SHA256.hexdigest(@name + Digest::SHA256.file(@path).to_s)\n end",
"def hash\n raw = [name, type, values.join('/')].join(' ')\n Digest::MD5.hexdigest(raw)\n end",
"def hexdigest\n self.class.hexdigest_for(path)\n end"
] |
[
"0.84057665",
"0.8236111",
"0.74144596",
"0.72782755",
"0.7249975",
"0.71416867",
"0.70871454",
"0.70627",
"0.7057871",
"0.6931921",
"0.6869169",
"0.6869169",
"0.6836221",
"0.6742051",
"0.67413205",
"0.6737911",
"0.6641898",
"0.6584662",
"0.65782964",
"0.6554568",
"0.6496937",
"0.6486453",
"0.6468057",
"0.64655334",
"0.645968",
"0.64366555",
"0.6432613",
"0.63796073",
"0.6377055",
"0.6371472",
"0.6359881",
"0.6349054",
"0.6343119",
"0.6340265",
"0.6326738",
"0.63047105",
"0.6277844",
"0.62585604",
"0.62310714",
"0.6222447",
"0.62044364",
"0.61622983",
"0.61606216",
"0.61559206",
"0.61502475",
"0.614112",
"0.6132601",
"0.60862815",
"0.6083564",
"0.6065606",
"0.6063364",
"0.60615724",
"0.6057905",
"0.6050356",
"0.60319686",
"0.6016471",
"0.6010865",
"0.6005614",
"0.6005087",
"0.5987909",
"0.59874296",
"0.59796876",
"0.5964799",
"0.5956595",
"0.59538686",
"0.5949294",
"0.59466684",
"0.5946613",
"0.59456354",
"0.59362936",
"0.5931181",
"0.5925064",
"0.59242994",
"0.5919782",
"0.5919093",
"0.59150803",
"0.59086704",
"0.5908286",
"0.59018683",
"0.5898784",
"0.58843386",
"0.5883475",
"0.5866542",
"0.5862569",
"0.5860478",
"0.58599424",
"0.58567494",
"0.5844271",
"0.5836264",
"0.58165264",
"0.5810293",
"0.5805193",
"0.5794987",
"0.5794967",
"0.57903385",
"0.57842505",
"0.5781213",
"0.5772292",
"0.57645136",
"0.57625395"
] |
0.83577657
|
1
|
The MIME type of the response
|
def media_type
return unless headers['Content-Type']
headers['Content-Type'].split(';').first
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def content_type\n response.content_type\n end",
"def content_type\n @response_headers[\"Content-Type\"]\n end",
"def response_content_type\n @response_headers[\"Content-Type\"]\n end",
"def content_type\n @mime_type\n end",
"def content_type\n response_headers[\"Content-Type\"]\n end",
"def content_mime_type; end",
"def content_type\n @response['content-type'].nil? ? 'text/plain' : @response['content-type']\n end",
"def mime_type\n return content_type\nend",
"def content_type\n ((response.headers.values_at('content-type', 'Content-Type').compact.first || '').split(';').first || '').strip\n end",
"def content_type\n self.class.response_content_type\n end",
"def mime_type\n MIME_TYPE\n end",
"def content_type\n self[\"Content-Type\"]\n end",
"def content_type\n headers[:content_type]\n end",
"def mime_type; end",
"def mime_type; end",
"def mime_type; end",
"def mime_type; end",
"def content_type\n @headers['Content-Type']\n end",
"def stringy_media_type\n request.content_mime_type.to_s\n end",
"def content_type; end",
"def content_type; end",
"def content_type; end",
"def content_type; end",
"def content_type; end",
"def content_type; end",
"def content_type; end",
"def content_type; end",
"def mime_type\n return @mime_type\n end",
"def content_type\n headers['content-type'].first\n end",
"def mime_type\n has_content_type? ? header[:content_type].string : nil rescue nil\n end",
"def content_type\n headers['content-type']\n end",
"def content_type\n end",
"def content_type\n @mime_type || @heads['content-type']\n end",
"def content_type\n headers['content-type'].first\n end",
"def content_type\n\t\treturn self.headers.content_type\n\tend",
"def content_type\n\t\treturn self.headers.content_type\n\tend",
"def mime_type type\n Rack::Mime.mime_type type\n end",
"def content_type\n response&.response&.content_type\n end",
"def mime_type\n Rack::Mime.mime_type(extname)\n end",
"def content_type\n @meta_content_type || response['content-type']\n end",
"def content_type\n @meta_content_type || response['content-type']\n end",
"def mimetype\n return @mimetype if defined? @mimetype\n\n type = metadata['Content-Type'].is_a?(Array) ? metadata['Content-Type'].first : metadata['Content-Type']\n\n @mimetype = MIME::Types[type].first\n end",
"def mime_type type\n @app.mime_type type\n end",
"def mimetype\n return attributes['mimetype'] if attributes['mimetype']\n return \"image/png\" if content =~ /^.PNG/\n return \"application/octet-stream\"\n end",
"def content_type\n ::MIME::Types.type_for(name).first.try(:content_type) || 'text/html'\n end",
"def content_type\n\t\treturn self.headers[ :content_type ]\n\tend",
"def mime_type\n @metadata[:mime_type]\n end",
"def mime_type\n _mime_type ? _mime_type.to_s : 'text/plain'\n end",
"def content_type\n @io.content_type\n end",
"def mime_type\n metadata[\"mime_type\"]\n end",
"def content_type\n if headers.key?('Content-Type')\n typename = headers['Content-Type'].value_without_parameters\n else\n typename = 'text/plain'\n end\n\n MIME::Types[typename].first\n end",
"def content_type\n @headers['content-type'][0] rescue nil\n end",
"def mimetype\n return @mimetype if defined? @mimetype\n\n content_type = metadata['Content-Type'].is_a?(Array) ? metadata['Content-Type'].first : metadata['Content-Type']\n @mimetype = Henkei.mimetype(content_type)\n end",
"def request_content_type\n @request_headers[\"Content-Type\"]\n end",
"def mime_type\n self.class.mime_type\n end",
"def to_s\n content_type\n end",
"def content_type\n mime = MIME_TYPES.fetch(format, DEFAULT_MIME_TYPE)\n headers.fetch(\"Content-Type\", mime)\n end",
"def media_type\r\ncontent_mime_type.to_s\r\nend",
"def content_type\n type, *parameters = content_type_parse\n type || 'application/octet-stream'\n end",
"def content_type\n @content_type ||= request.content_type\n end",
"def mime_type\n @mime_type ||= Rack::Mime.mime_type(\".#{ext}\")\n end",
"def mime_type\n meta['mime_type'] || app.mime_type_for(ext)\n end",
"def ext\n Rack::Mime::MIME_TYPES.invert[data_content_type]\n end",
"def mime_type\n @mime_type ||= message.mime_type\n end",
"def content_type(type)\n @response.content_type == type\n end",
"def content_type\n return @content_type\n end",
"def content_type\n file.try(:content_type)\n end",
"def content_type\n reader.format.content_type if valid?\n end",
"def mime_type\n MIME_TYPES[@file_type]\n end",
"def mime_type\n raise NotImplementedError.new 'This is only a function body for documentation'\n end",
"def content_type\n instance_read(:content_type)\n end",
"def content_type_header(request)\n request.content_type\n end",
"def content_type\n @content_type ||= begin\n if format_extension.nil?\n engine_content_type || 'application/octet-stream'\n else\n format_content_type ||\n engine_content_type ||\n 'application/octet-stream'\n end\n end\n end",
"def to_str\n content_type\n end",
"def content_type! type = nil, charset = nil\n __e__.explicit_charset = charset if charset\n charset ||= (content_type = response['Content-Type']) &&\n content_type.scan(%r[.*;\\s?charset=(.*)]i).flatten.first\n type && (Symbol === type) && (type = '.' << type.to_s)\n content_type = type ?\n (type =~ /\\A\\./ ? '' << mime_type(type) : type.split(';').first) : 'text/html'\n content_type << '; charset=' << charset if charset\n response['Content-Type'] = content_type\n end",
"def content_type\n #; [!95g9o] returns env['CONTENT_TYPE'].\n return @env['CONTENT_TYPE']\n end",
"def mime_type\n type = MIME::Types.type_for(self.filename)\n type.empty? ? nil : type.first\n end",
"def mime_type\n \"application/json\".freeze\n end",
"def content_type\n @content_type || file.content_type\n end",
"def mimetype\n mtype = MIME::Types.of(@filename).first\n if (mtype)\n mimetype = MIME::Type.simplified(mtype)\n end\n mimetype\n end",
"def mime_type\n @attributes[:mime_type]\n end",
"def content_type\n 'text/plain'\n end",
"def content_type\n if stat.directory?\n \"text/html\"\n else\n mime_type(file_path, DefaultMimeTypes)\n end\n end",
"def content_type(file_name)\n # Just grabbing the extension\n extension = ::File.extname(file_name.downcase)[1..-1]\n return @extension_map[extension] if @extension_map.key?(extension)\n 'application/octet-stream'\n end",
"def content_mime_type\n fetch_header(\"action_dispatch.request.content_type\") do |k|\n v = if get_header(\"CONTENT_TYPE\") =~ /^([^,;]*)/\n Mime::Type.lookup($1.strip.downcase)\n else\n nil\n end\n set_header k, v\n rescue ::Mime::Type::InvalidMimeType => e\n raise InvalidType, e.message\n end\n end",
"def file_ext extension\n response_object.mime extension\n end",
"def mime_type(type)\n roda_class.mime_type(type)\n end",
"def mime_type\n term = format_controlled_vocabulary.all.find { |x| x.definition == info_service.driver }\n term ? term.value : original_file.mime_type\n end",
"def file_mimetype\n @descriptive_detail.file_mimetype\n end",
"def get_mime_type(extension)\n begin\n return Rack::Mime.mime_type(extension)\n rescue\n @log.warn \"Couldn't find the MIME type for #{extension}.\"\n return 'text/json'\n end\n end",
"def content_type\n if format == :auto\n MIME_TYPES.values.join(',')\n elsif MIME_TYPES.has_key? format\n MIME_TYPES[format]\n else\n raise ArgumentError, \"Unknown format '#{format}'\"\n end\n end",
"def content_type\n if format == :auto\n MIME_TYPES.values.join(',')\n elsif MIME_TYPES.has_key? format\n MIME_TYPES[format]\n else\n raise ArgumentError, \"Unknown format '#{format}'\"\n end\n end",
"def mimetype\n process_upload\n return @file.file.file.content_type\n end",
"def content_type\n content_type = String(headers[\"Content-Type\"] || headers[\"type\"]).split(\";\")[0]\n content_type.blank? ? nil : content_type\n end",
"def content_type_string\n Mime::Type.lookup_by_extension(content_type).to_s\n end",
"def set_content_type raw_type\n response_object.mime_raw raw_type\n end",
"def file_content_type\n types = MIME::Types.type_for(original_filename)\n types.first\n end",
"def content_type\n return @content_type unless @content_type.blank?\n if has_attachments?\n return \"multipart/mixed\"\n elsif !body(:plain).blank? && !body(:html).blank?\n return \"multipart/alternative\"\n elsif body(:html)\n return \"text/html\"\n else\n return \"text/plain\"\n end\n end",
"def content_type\n environment.content_type_of(pathname)\n end",
"def content_type\n self.file_content_type\n end"
] |
[
"0.85328937",
"0.8530683",
"0.8527007",
"0.84796184",
"0.8414669",
"0.8400441",
"0.8399341",
"0.83585346",
"0.8248843",
"0.8213644",
"0.81921834",
"0.81689763",
"0.8116436",
"0.80897486",
"0.80897486",
"0.80897486",
"0.80897486",
"0.8055202",
"0.80551565",
"0.80487496",
"0.80487496",
"0.80487496",
"0.80487496",
"0.80487496",
"0.80487496",
"0.80487496",
"0.80487496",
"0.804033",
"0.8033456",
"0.802846",
"0.8021377",
"0.80198103",
"0.80182",
"0.8004003",
"0.80037135",
"0.80037135",
"0.8002264",
"0.8001126",
"0.7968858",
"0.79288894",
"0.79288894",
"0.79283154",
"0.79217046",
"0.790764",
"0.7899185",
"0.78951025",
"0.78938043",
"0.789372",
"0.7865206",
"0.7858079",
"0.7829408",
"0.78148264",
"0.7785825",
"0.77755874",
"0.77466184",
"0.77337337",
"0.7721924",
"0.7696805",
"0.7684126",
"0.76806146",
"0.7675532",
"0.76523143",
"0.76454675",
"0.7636524",
"0.7629187",
"0.7628092",
"0.7617505",
"0.75896883",
"0.75834143",
"0.7569624",
"0.7545021",
"0.75239366",
"0.75135314",
"0.7510087",
"0.7508068",
"0.7469919",
"0.7467286",
"0.74669975",
"0.7458695",
"0.74495864",
"0.7448536",
"0.7438678",
"0.743615",
"0.74351645",
"0.74135804",
"0.74133146",
"0.7410989",
"0.74086785",
"0.7408396",
"0.7405772",
"0.7395721",
"0.7395721",
"0.7395269",
"0.73908085",
"0.73859084",
"0.7383388",
"0.7381408",
"0.73788494",
"0.73772526",
"0.7371783"
] |
0.7698632
|
57
|
The general category into which the MIME type falls
|
def type
return unless media_type
media_type.split('/').first
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def type_category_string\n result = \"Manifestation\"\n result = \"Score\" if is_a_score?\n result = \"Recording\" if is_a_recording?\n result = \"Media on Demand\" if is_a_sounzmedia?\n result\n end",
"def mime_type; end",
"def mime_type; end",
"def mime_type; end",
"def mime_type; end",
"def class_type_from(content_type) \n case Mime::Type.lookup(content_type).to_sym \n when :text: 'SimpleText' \n when :jpg, :jpeg, :gif, \n :png, :tiff, :bmp: 'ImageData' \n when :xml: 'XmlData' \n when :pdf: 'PdfData' \n else name.demodulize \n end \n end",
"def category_type\n object.category.main_cat\n end",
"def name_of_content_type\n if self.content_type == 'application/vnd.ms-word'\n return \"Word document\"\n elsif self.content_type == 'application/pdf'\n return \"PDF file\"\n end\n end",
"def type\n self.category\n end",
"def content_type\n self.name[/::(.*)$/, 1].underscore.gsub(/_/, '/')\n end",
"def content_type\n ::MIME::Types.type_for(name).first.try(:content_type) || 'text/html'\n end",
"def get_category text\n #text = File.join(@path, t)\n if File.directory? text\n return :dir\n elsif File.executable? text\n return :executable\n elsif File.symlink? text\n return :link\n elsif File.exists? text\n if text =~ /\\.txt$/\n return :text\n elsif text =~ /\\.zip$/ or text =~ /gz$/ \n return :zip\n else\n return :file\n end\n else\n return :other\n end\n end",
"def description_of content_type\n case content_type.to_s.strip\n when \"image/jpeg\"\n \"JPEG graphic\"\n when \"application/vnd.ms-excel\"\n \"Excel worksheet\"\n when \"application/msword\"\n \"Word document\"\n when \"application/pdf\"\n \"PDF file\"\n else \"\"\n end\n end",
"def content_mime_type; end",
"def content_type\n end",
"def mime_type\n term = format_controlled_vocabulary.all.find { |x| x.definition == info_service.driver }\n term ? term.value : primary_file.mime_type\n end",
"def get_doc_type(item)\n if item['is_dir']\n \"folder\"\n elsif item['mime_type'].blank?\n \"misc\"\n elsif item['mime_type'] == 'application/pdf'\n \"pdf\"\n elsif item['mime_type'].include?('powerpoint')\n \"presentation\"\n elsif item['mime_type'] == 'application/zip'\n \"zip\"\n elsif item['mime_type'] == \"application/rtf\" || item['mime_type'] == 'text/plain' || item['mime_type'] == 'application/msword' || item['mime_type'].include?('wordprocessing')\n \"document\"\n elsif item['mime_type'].include?('spreadsheet') || item['mime_type'] == 'ms-excel'\n \"spreadsheet\"\n elsif item['mime_type'].include?('image') || item['mime_type'] == 'application/vnd.google-apps.drawing'\n \"image\"\n else\n \"misc\"\n end\n end",
"def get_category_type\n category_type ? category_type.short_name : '?'\n end",
"def main_type\n has_content_type? ? header[:content_type].main_type : nil rescue nil\n end",
"def mime_type=(_); end",
"def mime_type\n super || Mime::Type.lookup(DEFAULT_CONTENT_TYPE)\n end",
"def content_type ctype=nil\n @content_type = ctype if ctype\n @content_type ||=\n \"#{self.class.media_type}/#{self.class.api_name}+#{@env['kiwi.format']}\"\n end",
"def content_type; end",
"def content_type; end",
"def content_type; end",
"def content_type; end",
"def content_type; end",
"def content_type; end",
"def content_type; end",
"def content_type; end",
"def content_type\n @mime_type\n end",
"def categorize filename\n [filetype(filename), fileclass(filename)]\nend",
"def content_type\n @mime_type || @heads['content-type']\n end",
"def _mime_type\n if defined? @_mime_type\n @_mime_type\n else\n guesses = ::MIME::Types.type_for(extname.to_s)\n\n # Prefer text mime types over binary\n @_mime_type = guesses.detect { |type| type.ascii? } || guesses.first\n end\n end",
"def mime_type\n term = format_controlled_vocabulary.all.find { |x| x.definition == info_service.driver }\n term ? term.value : original_file.mime_type\n end",
"def mimetype\n return attributes['mimetype'] if attributes['mimetype']\n return \"image/png\" if content =~ /^.PNG/\n return \"application/octet-stream\"\n end",
"def get_category_type_name\n category_type ? category_type.short_name : '?'\n end",
"def get_content_type(filename)\n ext = File.extname(filename) # get the extension\n type = 'application/octed-stream'\n type = 'text/html' if ext == '.html' || ext == '.htm'\n type = 'text/plain' if ext == '.txt' || ext == '.rb'\n type = 'text/css' if ext == '.css'\n type = 'image/jpeg' if ext == '.jpeg' || ext == '.jpg'\n type = 'image/gif' if ext == '.gif'\n type = 'image/png' if ext == '.png'\n type = 'image/bmp' if ext == '.bmp'\n type = 'text/xml' if ext == '.xml' || ext == '.xsl'\n type # same as: return type\n end",
"def filter_content_type\n case record.filter_id\n when '', 'WymEditor'\n return \"text/html\"\n when 'Textile', 'Markdown'\n return \"text/plain\"\n end\n end",
"def content_type\n return @content_type unless @content_type.blank?\n if has_attachments?\n return \"multipart/mixed\"\n elsif !body(:plain).blank? && !body(:html).blank?\n return \"multipart/alternative\"\n elsif body(:html)\n return \"text/html\"\n else\n return \"text/plain\"\n end\n end",
"def mime_type\n MIME_TYPES[@file_type]\n end",
"def content_type(name)\n name_li(name).span(:class=>/(mylibrary_item_|searchcontent_result_)mimetype/).text\n end",
"def content_type\n return @content_type\n end",
"def mime_type\n raise NotImplementedError.new 'This is only a function body for documentation'\n end",
"def mime_type=(_arg0); end",
"def mime_type=(_arg0); end",
"def mime_type=(_arg0); end",
"def resourceType\n 'MedicinalProductContraindication'\n end",
"def media_type\r\ncontent_mime_type.to_s\r\nend",
"def mime_type\n metadata[\"mime_type\"]\n end",
"def meta_content_type(body); end",
"def mime_subtype\n mime_type.split(/\\//)[1]\n end",
"def related_mimetype(extension)\n if extension == \".gif\"\n \"image/gif\"\n elsif extension == \".png\"\n \"image/png\"\n else\n \"image/jpeg\"\n end\nend",
"def media_type; end",
"def media_type; end",
"def get_category_type_code\n category_type ? category_type.code : '?'\n end",
"def get_category_type_code\n category_type ? category_type.code : '?'\n end",
"def mediatype; end",
"def get_doc_type(item)\n if item.mimeType.blank?\n \"misc\"\n elsif item.mimeType == 'application/pdf'\n \"pdf\"\n elsif item.mimeType == 'application/vnd.google-apps.folder'\n \"folder\"\n elsif item.mimeType == 'application/vnd.google-apps.presentation'\n \"presentation\"\n elsif item.mimeType == 'application/zip'\n \"zip\"\n elsif item.mimeType == \"application/rtf\" || item.mimeType == 'text/plain' || item.mimeType == 'application/msword' || item.mimeType == 'application/vnd.google-apps.document' || item.mimeType.include?('wordprocessing')\n \"document\"\n elsif item.mimeType.include?('spreadsheet') || item.mimeType == 'ms-excel'\n \"spreadsheet\"\n elsif item.mimeType.include?('image') || item.mimeType == 'application/vnd.google-apps.drawing'\n \"image\"\n else\n \"misc\"\n end\n end",
"def mime_type(type)\n roda_class.mime_type(type)\n end",
"def mime_type\n return content_type\nend",
"def thing_name\n if asset.nil? || asset.content_type.blank?\n \"file\"\n elsif asset.content_type.start_with?(\"image/\")\n \"image\"\n elsif asset.content_type == \"application/pdf\"\n \"document\"\n else\n \"file\"\n end\n end",
"def file_mimetype\n @descriptive_detail.file_mimetype\n end",
"def content_type\n self[\"Content-Type\"]\n end",
"def mime_type\n MIME_TYPE\n end",
"def content_type(file_name)\n # Just grabbing the extension\n extension = ::File.extname(file_name.downcase)[1..-1]\n return @extension_map[extension] if @extension_map.key?(extension)\n 'application/octet-stream'\n end",
"def category; end",
"def extension_for_type(entry_type)\n case entry_type\n when :javascript then 'js'\n when :stylesheet then 'css'\n when :typescript then 'ts'\n else entry_type\n end\n end",
"def content_type(path)\r\n ext = File.extname(path).split(\".\").last\r\n CONTENT_TYPE_MAPPING.fetch(ext, DEFAULT_CONTENT_TYPE)\r\nend",
"def mediatype\n\t\treturn \"%s/%s\" % [ self.type || '*', self.subtype || '*' ]\n\tend",
"def content_type\n @resource.content_type\n end",
"def content_type_map\n Hash.new(\"text\").tap do |h|\n h[\"audio\"] = \"sound\"\n h[\"visual material\"] = \"image\"\n h[\"video\"] = \"video\"\n h[\"musical score\"] = \"sound\"\n h[\"map\"] = \"image\"\n end\n end",
"def content_type\n nil\n end",
"def resource_type\n return self.mime_type.slice(/^application\\/vnd.google-apps.(.+)$/, 1) || \"file\"\n end",
"def sub_type\n has_content_type? ? header[:content_type].sub_type : nil rescue nil\n end",
"def icon_css_class\n case file_mime_type\n when *ARCHIVE_FILE_TYPES\n then \"archive\"\n when *AUDIO_FILE_TYPES\n then \"audio\"\n when *IMAGE_FILE_TYPES\n then \"image\"\n when *VIDEO_FILE_TYPES\n then \"video\"\n when \"application/x-shockwave-flash\"\n then \"flash\"\n when \"image/x-psd\"\n then \"psd\"\n when \"text/plain\"\n then \"text\"\n when \"application/rtf\"\n then \"rtf\"\n when \"application/pdf\"\n then \"pdf\"\n when \"application/msword\"\n then \"word\"\n when \"application/vnd.ms-excel\"\n then \"excel\"\n when *VCARD_FILE_TYPES\n then \"vcard\"\n else \"file\"\n end\n end",
"def safe_content_type\n if safe_content_types.include?(content_type)\n content_type\n else\n \"image/jpeg\"\n end\n end",
"def mimetype\n return @mimetype if defined? @mimetype\n\n type = metadata['Content-Type'].is_a?(Array) ? metadata['Content-Type'].first : metadata['Content-Type']\n\n @mimetype = MIME::Types[type].first\n end",
"def mime_type\n return @mime_type\n end",
"def get_content_type\n self.content_type\n end",
"def content_type\n if format == :auto\n MIME_TYPES.values.join(',')\n elsif MIME_TYPES.has_key? format\n MIME_TYPES[format]\n else\n raise ArgumentError, \"Unknown format '#{format}'\"\n end\n end",
"def content_type\n if format == :auto\n MIME_TYPES.values.join(',')\n elsif MIME_TYPES.has_key? format\n MIME_TYPES[format]\n else\n raise ArgumentError, \"Unknown format '#{format}'\"\n end\n end",
"def category mt=nil\n return source.category.to_sym unless source.category.blank? \n mt ||= meta_data \n if mt.keys.include?(:season) || mt.keys.include?(:episode)\n return :tv_show\n elsif mt.keys.include?(:edition) || mt.keys.include?(:quality) || mt.keys.include?(:year)\n return :movie\n else\n return :unknown\n end \n end",
"def content_type\n# if stat.directory?\n# \"text/html\"\n# else \n# mime_type(file_path, DefaultMimeTypes)\n# end\n @bson['contentType'] || \"text/html\"\n end",
"def content_type\n raise NotImplementedError\n end",
"def mime_type\n @attributes[:mime_type]\n end",
"def attachment_content_type_for(joint)\n case File.extname(joint).downcase\n when '.txt' then 'text/plain'\n when '.html' then 'plain/html'\n when '.pdf' then 'application/octet-stream' #'application/x-pdf'\n when '.jpg', '.jpeg' then 'image/jpeg'\n when '.png' then 'image/png'\n when '.gif' then 'image/gif'\n when '.doc', '.docx' then 'application/msword'\n else \n 'plain/text' # par défaut\n end\nend",
"def type\n stype = \"file\"\n stype = \"atom\" if @filepath.nil? and !@metadata.empty?\n stype = \"multipart\" if !@filepath.nil? and !@metadata.empty?\n stype\n end",
"def mime_type\n\t\tsuffix_without_dot = extname ? extname.sub(/\\A\\./){''}.downcase : nil\n\n\t\tMechanize::Util::DefaultMimeTypes[suffix_without_dot]\n\tend",
"def asset_type\n \n if asset_content_type==\"application/pdf\"\n return :pdf\n elsif image?\n return :image\n elsif asset_content_type==\"application/msword\"\n return :doc\n elsif asset_content_type==\"application/vnd.ms-excel\"\n return :xls\n elsif asset_content_type==\"application/zip\"\n return :zip\n else\n return :generic\n end\n \n end",
"def mime_type\n @metadata[:mime_type]\n end",
"def [](content_type); end",
"def find_content_type_for_media_range(media_range)\n case media_range.to_s\n when '*/*'\n options[:default]\n when 'text/*'\n 'text/turtle'\n when 'application/*'\n 'application/ld+json'\n when 'application/json'\n 'application/ld+json'\n when 'application/xml'\n 'application/rdf+xml'\n when /^([^\\/]+)\\/\\*$/\n nil\n else\n media_range.to_s\n end\n end",
"def parsed_content_type_header; end",
"def type\n case namespace\n when /stix-\\d/, /cybox-\\d/\n :core\n when /common/\n :common\n when /vocabularies/\n :vocabularies\n when /cybox\\.mitre\\.org\\/objects#/\n :object\n when /\\.mitre\\.org\\/extensions\\//\n :extension\n when /stix\\.mitre\\.org/ # If it's STIX and not core, common, vocabs, or extensions, it's a component\n :component\n when 'http://data-marking.mitre.org/Marking-1'\n :marking\n else\n nil\n end\n end",
"def type_for(filename, platform = false)\r\n # call the original method\r\n type = mime_type_for(filename, platform)\r\n \r\n if type.empty? then\r\n case File.extname(filename)\r\n when '.cod'\r\n type = MIME::Type.from_array('application/vnd.rim.cod', 'cod', '8bit', 'linux')\r\n when '.apk'\r\n type = MIME::Type.from_array('application/vnd.android.package-archive', 'apk', '8bit', 'linux')\r\n when '.aetx'\r\n type = MIME::Type.from_array('application/x-aetx', 'aetx', '8bit', 'linux')\r\n when '.xap'\r\n type = MIME::Type.from_array('application/x-silverlight-app', 'xap', '8bit', 'linux')\r\n end\r\n end\r\n return type\r\n end",
"def mime_type\n type = MIME::Types.type_for(self.filename)\n type.empty? ? nil : type.first\n end",
"def content_type(ext)\n case ext\n when \"gif\": \"image/gif\"\n when \"jpg\": \"image/jpeg\"\n when \"png\": \"image/png\"\n else \"application/octet-stream\"\n end\nend",
"def mime_type\n _mime_type ? _mime_type.to_s : 'text/plain'\n end",
"def mimetype\n return @mimetype if defined? @mimetype\n\n content_type = metadata['Content-Type'].is_a?(Array) ? metadata['Content-Type'].first : metadata['Content-Type']\n @mimetype = Henkei.mimetype(content_type)\n end",
"def type_for(filename, platform = false)\n types = Array(filename).flat_map { |fn|\n @extension_index[File.basename(fn.chomp.downcase).gsub(/.*\\./o, '')]\n }.compact.sort { |a, b| a.priority_compare(b) }.uniq\n\n if platform\n MIME.deprecated(self, __method__,\n \"using the platform parameter\")\n types.select(&:platform?)\n else\n types\n end\n end"
] |
[
"0.68141365",
"0.66218483",
"0.66218483",
"0.66218483",
"0.66218483",
"0.66038316",
"0.6594756",
"0.656431",
"0.65294015",
"0.650641",
"0.650118",
"0.64929205",
"0.648406",
"0.645441",
"0.64491236",
"0.6405136",
"0.6386552",
"0.6379003",
"0.6378147",
"0.6361696",
"0.6330671",
"0.63035154",
"0.6302493",
"0.6302493",
"0.6302493",
"0.6302493",
"0.6302493",
"0.6302493",
"0.6302493",
"0.6302493",
"0.6290865",
"0.62874436",
"0.6267267",
"0.62569803",
"0.6235232",
"0.62279963",
"0.62212425",
"0.62188154",
"0.62033606",
"0.61785704",
"0.6171568",
"0.6167056",
"0.6162021",
"0.61546767",
"0.61505026",
"0.61505026",
"0.61505026",
"0.6144091",
"0.6143257",
"0.61382276",
"0.6129896",
"0.6129522",
"0.6124699",
"0.6124284",
"0.6124284",
"0.61233807",
"0.61233807",
"0.6122906",
"0.6119369",
"0.61178046",
"0.6113582",
"0.6111112",
"0.61028403",
"0.6101845",
"0.60839456",
"0.6082978",
"0.6080085",
"0.6079938",
"0.6079817",
"0.6078996",
"0.6078391",
"0.60756505",
"0.60743004",
"0.60665214",
"0.6065205",
"0.6062696",
"0.60573876",
"0.60480046",
"0.6046201",
"0.60450405",
"0.60438",
"0.60438",
"0.6041338",
"0.6034176",
"0.6029801",
"0.60197127",
"0.60115224",
"0.6009048",
"0.600475",
"0.60029626",
"0.59979445",
"0.59972185",
"0.59968626",
"0.5996387",
"0.59930253",
"0.597857",
"0.59760803",
"0.5975059",
"0.5972128",
"0.59693986",
"0.595984"
] |
0.0
|
-1
|
The exact kind of data of the specified type the MIME type represents
|
def subtype
return unless media_type
media_type.split('/').last
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def extract_content_type\n if data_content_type == \"application/octet-stream\" && !data_file_name.blank?\n content_types = MIME::Types.type_for(data_file_name)\n self.data_content_type = content_types.first.to_s unless content_types.empty?\n end\n end",
"def mime_type(type)\n roda_class.mime_type(type)\n end",
"def mime_type\n @metadata[:mime_type]\n end",
"def content_type\n @mime_type\n end",
"def content_type\n @io.content_type\n end",
"def content_type\n reader.format.content_type if valid?\n end",
"def extract_mime_type(io)\n if io.respond_to?(:mime_type)\n io.mime_type\n elsif io.respond_to?(:content_type)\n io.content_type\n end\n end",
"def mime_type\n @attributes[:mime_type]\n end",
"def type\n raw_data['type']\n end",
"def mimetype\n return attributes['mimetype'] if attributes['mimetype']\n return \"image/png\" if content =~ /^.PNG/\n return \"application/octet-stream\"\n end",
"def mime_type\n metadata[\"mime_type\"]\n end",
"def _extract_mime_type_with_mimemagic(io)\n MimeMagic.by_magic(io).type\n end",
"def get_data_type_from_response(response)\n return nil unless response\n return nil unless content_type = response['content-type']\n return nil unless m=content_type.match(/;\\s* type=([0-9A-Za-z:]+)/x)\n m[1]\n end",
"def content_type\n instance_read(:content_type)\n end",
"def ext\n Rack::Mime::MIME_TYPES.invert[data_content_type]\n end",
"def content_type\n end",
"def mime_type type\n Rack::Mime.mime_type type\n end",
"def type\n data.type\n end",
"def content_mime_type; end",
"def mime_type\n return @mime_type\n end",
"def content_type\n type, *parameters = content_type_parse\n type || 'application/octet-stream'\n end",
"def mime_type; end",
"def mime_type; end",
"def mime_type; end",
"def mime_type; end",
"def _mime_type\n if defined? @_mime_type\n @_mime_type\n else\n guesses = ::MIME::Types.type_for(extname.to_s)\n\n # Prefer text mime types over binary\n @_mime_type = guesses.detect { |type| type.ascii? } || guesses.first\n end\n end",
"def content_type\n @mime_type || @heads['content-type']\n end",
"def stringy_media_type\n request.content_mime_type.to_s\n end",
"def to_str\n content_type\n end",
"def type\n fil_header[:type]\n end",
"def mime_type\n MIME_TYPE\n end",
"def content_type; end",
"def content_type; end",
"def content_type; end",
"def content_type; end",
"def content_type; end",
"def content_type; end",
"def content_type; end",
"def content_type; end",
"def magic_mime_type\n return if new_record?\n return unless File.exists? io_stream.path\n FileMagic.mime.file(io_stream.path).split(/;\\s*/).first\n end",
"def mime_type\n has_content_type? ? header[:content_type].string : nil rescue nil\n end",
"def mime_type\n Blob.mime_type(self.name)\n end",
"def sniff_content_type str\n if (str.nil? or\n (not str.respond_to? :encoding ) or\n (str.encoding.to_s == \"ASCII-8BIT\"))\n \"application/octet-stream\"\n else\n \"text/plain; charset=#{str.encoding}\"\n end\n end",
"def to_s\n content_type\n end",
"def type(path)\n magic(path, Magic::MIME_TYPE)\n end",
"def mime_type type\n @app.mime_type type\n end",
"def mimetype\n return @mimetype if defined? @mimetype\n\n type = metadata['Content-Type'].is_a?(Array) ? metadata['Content-Type'].first : metadata['Content-Type']\n\n @mimetype = MIME::Types[type].first\n end",
"def type_from_detector\n begin\n ContentTypeDetector.new(@file.path).detect\n rescue Exception => e\n \"\"\n end\n end",
"def content_type\n headers['content-type'].first\n end",
"def content_type\n @content_type ||=\n identified_content_type ||\n declared_content_type ||\n guessed_safe_content_type ||\n Marcel::MimeType::BINARY\n end",
"def data_and_type\n fail_on_non_200_family_if_specified\n\n {\n data: to_s,\n type: content_type\n }\n end",
"def content_type\n @headers['content-type'][0] rescue nil\n end",
"def content_type\n headers['content-type'].first\n end",
"def content_type\n @headers['Content-Type']\n end",
"def content_type\n self[\"Content-Type\"]\n end",
"def get_data_type_from_body(body)\n return nil unless body\n body['_data_type'] || body['type']\n end",
"def mime_type(media_type: T.unsafe(nil)); end",
"def content_type\n headers[:content_type]\n end",
"def content_type\n file.try(:content_type)\n end",
"def content_type\n ::MIME::Types.type_for(name).first.try(:content_type) || 'text/html'\n end",
"def content_type\n return @content_type\n end",
"def to_str\n @content_type\n end",
"def mime_type\n self.class.mime_type\n end",
"def content_type\n headers['content-type']\n end",
"def content_type(type)\n @response.content_type == type\n end",
"def content_type\n\t\treturn self.headers.content_type\n\tend",
"def content_type\n\t\treturn self.headers.content_type\n\tend",
"def type\n stype = \"file\"\n stype = \"atom\" if @filepath.nil? and !@metadata.empty?\n stype = \"multipart\" if !@filepath.nil? and !@metadata.empty?\n stype\n end",
"def type\n @data['type']\n end",
"def type\n @data['type']\n end",
"def content_type\n if headers.key?('Content-Type')\n typename = headers['Content-Type'].value_without_parameters\n else\n typename = 'text/plain'\n end\n\n MIME::Types[typename].first\n end",
"def mime_type\n Rack::Mime.mime_type(extname)\n end",
"def media_type\n return unless headers['Content-Type']\n\n headers['Content-Type'].split(';').first\n end",
"def mime_type\n type = MIME::Types.type_for(self.filename)\n type.empty? ? nil : type.first\n end",
"def class_type_from(content_type) \n case Mime::Type.lookup(content_type).to_sym \n when :text: 'SimpleText' \n when :jpg, :jpeg, :gif, \n :png, :tiff, :bmp: 'ImageData' \n when :xml: 'XmlData' \n when :pdf: 'PdfData' \n else name.demodulize \n end \n end",
"def mime_type\n _mime_type ? _mime_type.to_s : 'text/plain'\n end",
"def content_type_string\n Mime::Type.lookup_by_extension(content_type).to_s\n end",
"def mime_type\n return content_type\nend",
"def filetype\n `file --mime-type -b #{@file_path}`.chomp\n end",
"def get_content_type(filename)\n ext = File.extname(filename) # get the extension\n type = 'application/octed-stream'\n type = 'text/html' if ext == '.html' || ext == '.htm'\n type = 'text/plain' if ext == '.txt' || ext == '.rb'\n type = 'text/css' if ext == '.css'\n type = 'image/jpeg' if ext == '.jpeg' || ext == '.jpg'\n type = 'image/gif' if ext == '.gif'\n type = 'image/png' if ext == '.png'\n type = 'image/bmp' if ext == '.bmp'\n type = 'text/xml' if ext == '.xml' || ext == '.xsl'\n type # same as: return type\n end",
"def mime_type\n raise NotImplementedError.new 'This is only a function body for documentation'\n end",
"def is_mime_type? m\n MIME::Type.new m rescue false\n end",
"def is_mime_type? m\n MIME::Type.new m rescue false\n end",
"def io_stream_mime_type\n mime = new_record? ? io_stream.content_type : magic_mime_type\n MIME::Types[mime].first\n end",
"def media_type\r\ncontent_mime_type.to_s\r\nend",
"def content_type\n @content_type ||= stream.content_type\n end",
"def file_content_type\n types = MIME::Types.type_for(original_filename)\n types.first\n end",
"def type\n\t\t\t@data[\"type\"]\n\t\tend",
"def content_type\n @meta_content_type || response['content-type']\n end",
"def content_type\n @meta_content_type || response['content-type']\n end",
"def content_type\n if format == :auto\n MIME_TYPES.values.join(',')\n elsif MIME_TYPES.has_key? format\n MIME_TYPES[format]\n else\n raise ArgumentError, \"Unknown format '#{format}'\"\n end\n end",
"def content_type\n if format == :auto\n MIME_TYPES.values.join(',')\n elsif MIME_TYPES.has_key? format\n MIME_TYPES[format]\n else\n raise ArgumentError, \"Unknown format '#{format}'\"\n end\n end",
"def type\n data['type'].to_sym\n end",
"def type\n return unless media_type\n\n media_type.split('/').first\n end",
"def _extract_mime_type_with_mime_types(io)\n if filename = extract_filename(io)\n mime_type = MIME::Types.of(filename).first\n mime_type.to_s if mime_type\n end\n end",
"def mime_type_of(f)\n MIME::Types.of(f).last || default_mime_type\n end",
"def content_type=(type)\n\t\t\tif type.index(C_slash)\n\t\t\t\t@content_type = type\n\t\t\telse\n\t\t\t\t@content_type = MIME::Types.type_for(type).first || BINARY_TYPE\n\t\t\tend\n\t\tend",
"def content_type\n raise NotImplementedError\n end",
"def data_type\n return @data_type\n end",
"def content_type(type)\n headers(HTTP::Headers::CONTENT_TYPE => HTTP::MimeType.normalize(type))\n end",
"def mime_type\n @mime_type ||= message.mime_type\n end"
] |
[
"0.7473459",
"0.7402594",
"0.7338831",
"0.7336066",
"0.73270863",
"0.7318867",
"0.7314381",
"0.73021454",
"0.730134",
"0.7298241",
"0.72869664",
"0.7284201",
"0.71382654",
"0.7135286",
"0.7133062",
"0.7126309",
"0.71207136",
"0.70700234",
"0.705728",
"0.70209634",
"0.7016326",
"0.70151705",
"0.70151705",
"0.70151705",
"0.70151705",
"0.70098644",
"0.70062613",
"0.7002524",
"0.6961577",
"0.6959887",
"0.69539106",
"0.69334453",
"0.69334453",
"0.69334453",
"0.69334453",
"0.69334453",
"0.69334453",
"0.69334453",
"0.69334453",
"0.69211763",
"0.6915423",
"0.69120514",
"0.690898",
"0.6900494",
"0.68794465",
"0.68734056",
"0.68685526",
"0.6867388",
"0.6861584",
"0.68439496",
"0.68427825",
"0.6826429",
"0.68193775",
"0.6818379",
"0.6808407",
"0.68074405",
"0.6805262",
"0.68047357",
"0.6804171",
"0.68037266",
"0.6791181",
"0.67895705",
"0.6766921",
"0.67559487",
"0.6746473",
"0.6744026",
"0.6744026",
"0.6743087",
"0.673762",
"0.6734084",
"0.6731136",
"0.6730904",
"0.67214406",
"0.6719005",
"0.67187166",
"0.6716679",
"0.67158735",
"0.6711207",
"0.66989434",
"0.66930205",
"0.6677564",
"0.6671374",
"0.6671374",
"0.6670586",
"0.6668425",
"0.6667964",
"0.66677815",
"0.66613597",
"0.66604865",
"0.66604865",
"0.6655843",
"0.6655843",
"0.66534597",
"0.66406506",
"0.6626015",
"0.6621474",
"0.66214526",
"0.6619424",
"0.6615095",
"0.66043794",
"0.66022915"
] |
0.0
|
-1
|
The character encoding of the response
|
def charset
match_data = headers['Content-Type']&.match(/charset=(.*);?/)
return unless match_data
Encoding.find(match_data[1])
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def content_encoding\n\t\treturn self.headers.content_encoding\n\tend",
"def content_encoding\n\t\treturn self.headers.content_encoding\n\tend",
"def encoding\n @connection.encoding.to_s\n end",
"def encoding\n Encoding::UTF_8\n end",
"def encoding\n Encoding::UTF_8\n end",
"def encoding\n @content[pn(:Encoding)]\n end",
"def encoding\n if @encoding.blank?\n if !self.http_headers.blank?\n if self.http_headers['content-type'] =~ /charset=([\\w\\d-]+)/\n @encoding = $1.downcase\n else\n @encoding = self.encoding_from_feed_data\n end \n else\n @encoding = self.encoding_from_feed_data\n end\n end\n return @encoding\n end",
"def encoding\n @body.encoding\n end",
"def encoding; end",
"def encoding; end",
"def encoding; end",
"def encoding; end",
"def encoding; end",
"def encoding; end",
"def encoding; end",
"def encoding; end",
"def encoding; end",
"def encoding; end",
"def encoding; end",
"def encoding; end",
"def encoding; end",
"def encoding; end",
"def encoding; end",
"def encoding\n @io.external_encoding\n end",
"def encoding\n @io.external_encoding\n end",
"def charset\n 'UTF8'\n end",
"def encoding\n @attributes[:encoding]\n end",
"def encoding\n\t'ISO-8859-1'\nend",
"def name\n 'Accept-Encoding'\n end",
"def charset\n 'utf-8'\n end",
"def charset! charset\n content_type! response['Content-Type'], charset\n end",
"def encodings; end",
"def meta_encoding; end",
"def meta_encoding; end",
"def encoding()\n #This is a stub, used for indexing\n end",
"def encoding\n @external_encoding\n end",
"def charset\n metadata[:charset]\n end",
"def transfer_encoding\n h = header.find('Content-Transfer-Encoding')\n return nil if h.nil?\n\n h[1]\n end",
"def default_encoding; end",
"def default_encoding; end",
"def default_encoding\n Encoding::UTF_8\n end",
"def found_encoding; end",
"def found_encoding; end",
"def force_header_encoding(s); s; end",
"def encoding_found; end",
"def encoding_found; end",
"def charset\n if @header\n has_content_type? ? content_type_parameters['charset'] : @charset\n else\n @charset\n end\n end",
"def content_encoding\n v = @meta['content-encoding']\n if v && %r{\\A#{RE_LWS}?#{RE_TOKEN}#{RE_LWS}?(?:,#{RE_LWS}?#{RE_TOKEN}#{RE_LWS}?)*}o =~ v\n v.scan(RE_TOKEN).map {|content_coding| content_coding.downcase}\n else\n []\n end\n end",
"def internal_encoding()\n #This is a stub, used for indexing\n end",
"def encoding\n # noop?\n end",
"def encoding_line; end",
"def convert_encoding(content); end",
"def charset; end",
"def charset; end",
"def charset; end",
"def get_encoding_from_headers(type_header)\n return nil unless type_header\n\n content_type, params = cgi_parse_header(type_header)\n\n if params.include?('charset')\n return params.fetch('charset').gsub(/(\\A[\"']*)|([\"']*\\z)/, '')\n end\n\n nil\n end",
"def charset\n @@charset\n end",
"def get_encoding()\n puts @csv_encoding\n end",
"def encoding(encoding); end",
"def encode_body\n body = response.body\n chosen_charset = metadata['Charset']\n chosen_encoding = metadata['Content-Encoding']\n charsetter = resource.charsets_provided && resource.charsets_provided.find {|c,_| c == chosen_charset }.last || :charset_nop\n encoder = resource.encodings_provided[chosen_encoding]\n response.body = case body\n when String # 1.8 treats Strings as Enumerable\n resource.send(encoder, resource.send(charsetter, body))\n when Fiber\n FiberEncoder.new(resource, encoder, charsetter, body)\n when Enumerable\n EnumerableEncoder.new(resource, encoder, charsetter, body)\n else\n if body.respond_to?(:call)\n CallableEncoder.new(resource, encoder, charsetter, body)\n else\n resource.send(encoder, resource.send(charsetter, body))\n end\n end\n if String === response.body\n response.headers['Content-Length'] = response.body.respond_to?(:bytesize) ? response.body.bytesize.to_s : response.body.length.to_s\n else\n response.headers.delete 'Content-Length'\n response.headers['Transfer-Encoding'] = 'chunked'\n end\n end",
"def mobile_encoding\n\t'ISO-8859-1'\nend",
"def response_content_type_with_charset(request, config)\n content_type_with_charset(\n response_content_type(request, config),\n config.default_charset || Action::DEFAULT_CHARSET\n )\n end",
"def content_type_options\n {charset: 'utf-8'}\n end",
"def charset\n perform! unless @performed\n content_type = @curl.content_type || ''\n charset = if content_type.match(/charset\\s*=\\s*([a-zA-Z0-9-]+)/ni)\n $1\n elsif ! body_str.nil? and (m = body_str.slice(0,1000).match(%r{<meta.*http-equiv\\s*=\\s*['\"]?Content-Type['\"]?.*?>}mi)) and\n m[0].match(%r{content=['\"]text/html.*?charset=(.*?)['\"]}mi)\n $1\n else\n ''\n end.downcase\n end",
"def content_encoding_hooks; end",
"def content_encoding_hooks; end",
"def encoding\n @gapi.encoding\n end",
"def encoding\n @gapi.encoding\n end",
"def external_encoding\n Encoding.default_external\n end",
"def charset\n #@data.charset ||= CharGuess.guess(document).downcase\n end",
"def content_encoding=( type )\n\t\treturn self.headers.content_encoding = type\n\tend",
"def content_encoding=( type )\n\t\treturn self.headers.content_encoding = type\n\tend",
"def utf8_character\n character.chr(Encoding::UTF_8)\n end",
"def force_default_encoding; end",
"def get\n self.data.force_encoding(Encoding::UTF_16BE).encode(Encoding::UTF_8)\n end",
"def charset\n @charset ||= (charset_from_meta_charset || charset_from_content_type)\n end",
"def content_transfer_encoding\n @j_del.contentTransferEncoding()\n end",
"def charset\n @charset ||= message.charset.upcase\n end",
"def encoding\n if @connection.respond_to?(:encoding)\n @connection.encoding.to_s\n else\n @connection.execute('PRAGMA encoding')[0]['encoding']\n end\n end",
"def encoding\n @gapi.csv_options.encoding\n end",
"def encoding\n @gapi.csv_options.encoding\n end",
"def encoding_for(character)\n encoding_for_bars(ENCODINGS[character])\n end",
"def encoding=(_arg0); end",
"def encoding=(_arg0); end",
"def encoding=(_arg0); end",
"def encoding=(_arg0); end",
"def encoding=(_arg0); end",
"def encoding=(_arg0); end",
"def encoding=(_arg0); end",
"def external_encoding()\n #This is a stub, used for indexing\n end",
"def default_encoding\n (@media_type == \"text\") ? \"quoted-printable\" : \"base64\"\n end",
"def test_encoding\n assert_equal \"UTF-8\", @conn.encoding\n end",
"def test_encoding\n assert_equal 'UTF-8', @conn.encoding\n end",
"def encoding\n @stdin.external_encoding\n end",
"def encoding\n @stdin.external_encoding\n end",
"def encoding\n @stdin.external_encoding\n end",
"def encode_body(response)\n body = response.body || ''\n\n # parse Content-Type\n begin\n content_type = response['Content-Type'] && ContentType.parse(response['Content-Type'])\n rescue Parslet::ParseFailed\n # unparsable\n end\n\n # look at charset and set body encoding if necessary\n encoding = encoding_for(content_type)\n if body.encoding != encoding\n body = body.dup if body.frozen?\n body.force_encoding(encoding)\n end\n\n # if :utf8, force body to UTF-8\n if options[:utf8] && content_type && response_text?(content_type)\n body = body.dup if body.frozen?\n begin\n body.encode!('UTF-8', invalid: :replace, undef: :replace, replace: '?')\n rescue Encoding::ConverterNotFoundError\n # rare, can't do anything here\n body = \"httpdisk could not convert from #{body.encoding.name} to UTF-8\"\n end\n end\n\n response.env[:body] = body\n end",
"def content_type\n @response['content-type'].nil? ? 'text/plain' : @response['content-type']\n end",
"def external_encoding; @_external_encoding || _external_encoding; end",
"def convert_encoding(content)\n return content if RUBY18\n if content =~ /\\A\\s*#.*coding:\\s*(\\S+)\\s*$/\n content.force_encoding($1)\n else\n content\n end\n end"
] |
[
"0.8135081",
"0.8135081",
"0.7707479",
"0.7593639",
"0.7593639",
"0.7574285",
"0.741583",
"0.7388208",
"0.72833616",
"0.72833616",
"0.72833616",
"0.72833616",
"0.72833616",
"0.72833616",
"0.72833616",
"0.72833616",
"0.72833616",
"0.72833616",
"0.72833616",
"0.72833616",
"0.72833616",
"0.72833616",
"0.72833616",
"0.72632813",
"0.72632813",
"0.7257723",
"0.7199599",
"0.7115357",
"0.7038035",
"0.70317245",
"0.69533855",
"0.69511265",
"0.69268245",
"0.69268245",
"0.69147354",
"0.6907842",
"0.6891978",
"0.68822634",
"0.6844704",
"0.6844704",
"0.6830306",
"0.67360353",
"0.67360353",
"0.67331666",
"0.6717425",
"0.6717425",
"0.6680368",
"0.65910894",
"0.65875506",
"0.6563994",
"0.6522928",
"0.6495865",
"0.64751595",
"0.64751595",
"0.64751595",
"0.64738774",
"0.64577436",
"0.6450613",
"0.6418124",
"0.6402657",
"0.6372929",
"0.637123",
"0.6350834",
"0.63427144",
"0.6330933",
"0.6330933",
"0.6329041",
"0.6329041",
"0.6320698",
"0.6305617",
"0.63014674",
"0.63014674",
"0.62966806",
"0.6255831",
"0.6243122",
"0.62363833",
"0.623346",
"0.62244654",
"0.6215431",
"0.61898047",
"0.61898047",
"0.6153791",
"0.61467403",
"0.61467403",
"0.61467403",
"0.61467403",
"0.61467403",
"0.6146676",
"0.6146676",
"0.6145177",
"0.614405",
"0.6142728",
"0.6138725",
"0.6117529",
"0.6117529",
"0.6117529",
"0.60945195",
"0.60893154",
"0.60880023",
"0.60758716"
] |
0.7280665
|
23
|
Whether the response is an XML document
|
def xml?
return unless subtype
subtype == 'xml'
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def is_xml?\n not (@headers['Content-Type'] =~ /^application\\/xml.*/).nil?\n end",
"def xml?\n type == DOCUMENT_NODE\n end",
"def is_xml_request? \n request.env['CONTENT_TYPE'] =~ %r[(application|text)/xml] \n end",
"def document?\n is_a? XML::Document\n end",
"def assert_valid_xml(res)\n assert_content_type res, \"application/xml\" \n end",
"def document?\n node_type == DOCUMENT_NODE\n end",
"def xml_post?\n post? && post_format == :xml\n end",
"def isxml?(xml)\n xml.lstrip.start_with?('<')\n end",
"def rendering_xml?(p = nil)\n p ||= params\n fmt = p[:format].to_s.downcase\n (fmt == 'xml') || (respond_to?(:request) && request.format.xml?)\n end",
"def plain_document?\n document.elements.empty?\n end",
"def xmldoc?\n sort == ::XMLDOC\n end",
"def content_type\n \"text/xml\"\n end",
"def valid_xml?(xml)\n create_document(xml) != nil\nend",
"def xml_document\n @xml_document ||= HTML::Document.new(@response.body, false, true)\n end",
"def xml_document\n @xml_document ||= HTML::Document.new(@response.body, false, true)\nend",
"def html_doc?\n node_type == HTML_DOCUMENT_NODE\n end",
"def is_xml_valid?(xml_text)\n return true #FIXME\n end",
"def rexml? ; false end",
"def parse_to_xml\n raise_if_error\n response_xml\n end",
"def document?\n @value.is_a?(Liquid::Document)\n end",
"def xml?; end",
"def xml?; end",
"def parse_response?\n parse_response\n end",
"def parse_response?\n parse_response\n end",
"def has_xml_content\n attr_accessor :xml_content\n end",
"def document?\n self.type == \"Document\"\n end",
"def html?\n type == HTML_DOCUMENT_NODE\n end",
"def xml_element?(xml)\n xml.kind_of? Nokogiri::XML::Element\n end",
"def successful_authorize_response\n <<-XML\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <EngineDocList>\n <DocVersion DataType=\"String\">1.0</DocVersion>\n <EngineDoc>\n <Overview>\n <AuthCode DataType=\"String\">889350</AuthCode>\n <CcErrCode DataType=\"S32\">1</CcErrCode>\n <CcReturnMsg DataType=\"String\">Approved.</CcReturnMsg>\n <DateTime DataType=\"DateTime\">1212066788586</DateTime>\n <Mode DataType=\"String\">Y</Mode>\n <OrderId DataType=\"String\">483e6382-7d12-3001-002b-0003bac00fc9</OrderId>\n <TransactionId DataType=\"String\">483e6382-7d13-3001-002b-0003bac00fc9</TransactionId>\n <TransactionStatus DataType=\"String\">A</TransactionStatus>\n </Overview>\n </EngineDoc>\n </EngineDocList>\n XML\n end",
"def xml_document(obj)\n case obj\n when XML::Document\n XML::Document.document(obj)\n else\n XML::Document.new('1.0')\n end\n end",
"def xml\n @xml ||= Nokogiri::XML.parse body\n end",
"def applies_to?(response)\n status, header, body = response\n\n # Some stati don't have to be processed\n return false if [301, 302, 303, 307].include?(status)\n\n # Check mime type\n return false if @mime_types.all? do |type|\n !header['Content-Type'].to_s.include?(type)\n end\n\n # Find ESI tags\n response[2] = [body = join_body(body)]\n body.include?('<esi:')\n end",
"def doc?\n (doc && !doc.empty?)\n end",
"def doc?\n (doc && !doc.empty?)\n end",
"def xml\n Nokogiri::XML(body)\n end",
"def docbook_doc?\n node_type == DOCB_DOCUMENT_NODE\n end",
"def xmldecl?\n @contents[0] == :xmldecl\n end",
"def xml_doc\n @xml_doc ||= unless @xml.blank?\n Nokogiri.parse(@xml)\n else\n Nokogiri::XML::Document.new\n end\n rescue\n raise RuntimeError, 'expected document to parse'\n end",
"def ok? \n @response.is_a? Net::HTTPOK\n end",
"def parse_response\n if @http_response.body && @http_response.respond_to?(:headers) && @http_response.headers['Content-Type']\n if @http_response.headers['Content-Type'].include?('xml')\n parse_xml_response\n elsif @http_response.headers['Content-Type'].include?('json')\n parse_json_response\n end\n else\n parse_unknown_response\n end\n end",
"def xml\n @xml ||= Nokogiri::XML(body)\n end",
"def non_empty_http_response?(http)\n http.response.present?\n end",
"def yadis_request?(request)\n (request.env['HTTP_ACCEPT'] && request.env['HTTP_ACCEPT'].include?('application/xrds+xml'))\n end",
"def doctype?\n node_type == DOCUMENT_TYPE_NODE\n end",
"def response?\n @type == :response\n end",
"def html?\n !!(content_type =~ %r{^(text/html|application/xhtml+xml)\\b})\n end",
"def html?\n !!(content_type =~ %r{^(text/html|application/xhtml+xml)\\b})\n end",
"def html?\n !!(content_type =~ %r{^(text/html|application/xhtml+xml)\\b})\n end",
"def html_format?()\n self.response_format == :html\n end",
"def respond\n respond_to do |format|\n format.html\n format.xml { render :xml => @response.to_xml }\n format.json { render :json => @response.to_json }\n end\n end",
"def render_empty?\n XML_RENDER_EMPTY\n end",
"def parser_type(x)\n 'libxml'\n end",
"def transact_successful?(doc)\n doc != nil &&\n doc.elements['XTMAILING_RESPONSE'] != nil &&\n doc.elements['XTMAILING_RESPONSE'].elements['ERROR_CODE'] != nil\n end",
"def to_xml\n response\n end",
"def has_response_body?\n !response.body.nil? && !response.body.empty?\n end",
"def generated_net_docfile?\n return false unless extname.downcase == \".xml\"\n return false unless lines.count > 3\n\n # .NET Docfiles always open with <doc> and their first tag is an\n # <assembly> tag\n return lines[1].include?(\"<doc>\") &&\n lines[2].include?(\"<assembly>\") &&\n lines[-2].include?(\"</doc>\")\n end",
"def set_xml_status\n if params[:xml_request]\n request.env[\"CONTENT_TYPE\"] = \"text/xml\"\n request.env[\"HTTP_ACCEPT\"] = \"application/xml\"\n @xml_request_enabled = true\n end\n end",
"def response?\n !response.nil?\n end",
"def has_schema?\n request || !responses.empty? || documentation\n end",
"def xml\n\t\theaders[\"Content-Type\"] = \"text/xml; charset=utf-8\"\n\t\trender :layout => false\n\tend",
"def response_must_validate_against_schema\n check_validity_against_schema(doc, 'application_response.xsd')\n end",
"def valid?\n build_xml\n\n validation = RelaxNGSchema.instance.validate(@xml.document)\n if validation.empty?\n true\n else\n logger.error validation.map(&:message).join(\"\\n\")\n logger.debug @xml.to_s\n false\n end\n end",
"def content_type(type)\n @response.content_type == type\n end",
"def has_response_body?\n @raw_link.media_type != \"null\"\n end",
"def has_body_as_html?\n if self.content_type == 'application/vnd.ms-word'\n return true\n elsif self.content_type == 'application/pdf'\n return true\n end\n return false\n end",
"def is_html?\n not (@headers['Content-Type'] =~ /^application\\/html.*/).nil?\n end",
"def test_isSupported07\n doc = nil\n rootNode = nil\n state = nil\n doc = load_document(\"staff\", false)\n rootNode = doc.documentElement()\n state = rootNode.isSupported(\"XML\", \"\")\n assertTrue(\"throw_True\", state)\n \n end",
"def render_nil?\n XML_RENDER_NIL\n end",
"def xml_authorized?\n self.documento.digital == true\n end",
"def typed?\n document.hereditary? ||\n document.class.descendants.any? ||\n document.polymorphic?\n end",
"def html?\n (@content_type =~ /text\\/html/) == 0\n end",
"def get_xml_of_type( asdcp_type, file )\n begin\n xml = Nokogiri::XML( open file )\n rescue Exception => e\n @logger.info \"#{ file }: #{ e.message }\"\n return FALSE\n end\n unless xml.errors.empty?\n xml.errors.each do |error|\n # expected errors from non-xml\n next if error.message =~ /Start tag expected/ or error.message =~ /Document is empty/\n @logger.info \"Syntax error: #{ file }: #{ error }\"\n end\n return FALSE\n end\n\n case xml.root.node_name\n when asdcp_type\n return xml\n else\n return FALSE\n end\nend",
"def xmlUrl?\n self.xmlUrl ? true : false\n end",
"def xml_nil?\n return @xml.nil?\n end",
"def check_for_xml \n return true unless is_xml_request? \n return(render(:text => '<Response>Error: bad xml</Response>')) unless @request.env['RAW_POST_DATA'] && !@request.env['RAW_POST_DATA'].strip.empty? \n\n # headers['Content-Type'], NOT headers['CONTENT_TYPE'] \n @response.headers['CONTENT_TYPE'] = 'text/xml; charset=utf-8' \n @response.headers['Content-Type'] = 'text/xml; charset=utf-8' \n\n xml = REXML::Document.new(request.env['RAW_POST_DATA']) \n login_user(xml) \n return(render(:text => '<Response>bad username or password</Response>') and false) unless current_user \n\n begin \n (delete_trust(xml) and return false) if is_delete_trust? \n (create_trust_xml(xml) and return false) if is_create_trust? \n (xml_profile_list(xml) and return false) if is_profile_list? \n (xml_query_profile(xml) and return false) if is_query_profile? \n\n params.merge!(get_params_from_xml(xml)) \n\n\t \t create_trust_if_necessary(xml) \n\t \trescue \n \t return(render(:text => '<Response>Error: bad xml format.</Response>')) \n end\n end",
"def to_xml\n if multipart?\n parts.first.body.decoded # we just assume the first part is the XML\n else\n http.body\n end\n end",
"def _convertXML() \n\n require 'rexml/document'\n return REXML::Document.new(self.response)\n\n raise \"Unimplemented.\"\n \n\t#\t\t\tfrom xml.dom.ext.reader import PyExpat\n#\t\t\tParser = PyExpat.Reader\n#\t\texcept ImportError :\n#\t\t\tfrom xml.dom.ext.reader import Sax2\n#\t\t\tParser = Sax2.Reader\n#\t\t\t#import warnings\n#\t\t\t#warnings.warn(\"Expat parser could not be loaded, using Sax2. Might slow down things...\")\n#\t\treader = Parser()\n#\t\treturn reader.fromStream(self.response)\n\n end",
"def check_format\n # This allows us to support content negotiation\n if request.headers['HTTP_ACCEPT'].nil? || request.format == '*/*'\n request.format = 'xml'\n end\n\n request_format = request.format.symbol\n if request_format != :xml && request_format != :json\n # 406 is the default status code when the format is not support\n head :not_acceptable\n end\n end",
"def xml_document\n if @xml_document.nil?\n return nil if self.feed_data.blank?\n if self.feed_data_type != :xml\n @xml_document = nil\n else\n begin\n @xml_document = REXML::Document.new(self.feed_data_utf_8)\n rescue Exception\n # Something failed, attempt to repair the xml with html5lib.\n begin\n @xml_document = HTML5::XMLParser.parse(self.feed_data_utf_8)\n rescue Exception\n # Failed again, give up.\n return nil\n end\n end\n end\n end\n return @xml_document\n end",
"def show\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @document }\n end\n end",
"def doctype?\n @contents[0] == :start_doctype\n end",
"def failed_authorize_response\n <<-XML\n <EngineDocList>\n <DocVersion DataType=\"String\">1.0</DocVersion>\n <EngineDoc>\n <OrderFormDoc>\n <Id DataType=\"String\">48b7024c-0322-3002-002a-0003ba9a87ff</Id>\n <Mode DataType=\"String\">Y</Mode>\n <Transaction>\n <Id DataType=\"String\">48b7024c-0323-3002-002a-0003ba9a87ff</Id>\n <Type DataType=\"String\">PreAuth</Type>\n </Transaction>\n </OrderFormDoc>\n <Overview>\n <CcErrCode DataType=\"S32\">1067</CcErrCode>\n <CcReturnMsg DataType=\"String\">System error.</CcReturnMsg>\n <DateTime DataType=\"DateTime\">1219953701297</DateTime>\n <Mode DataType=\"String\">Y</Mode>\n <Notice DataType=\"String\">Unable to determine card type. ('length' is '16')</Notice>\n <TransactionId DataType=\"String\">48b7024c-0323-3002-002a-0003ba9a87ff</TransactionId>\n <TransactionStatus DataType=\"String\">E</TransactionStatus>\n </Overview>\n </EngineDoc>\n </EngineDocList>\n XML\n end",
"def get_response_type\n return nil unless self.parsed_response.respond_to?(:xpath)\n response_type = self.parsed_response.xpath(\"//ns:Envelope/ns:Body\", \"ns\" => \"http://schemas.xmlsoap.org/soap/envelope/\").first.elements.first.name\n underscore(response_type.gsub(\"Response\",\"\"))\n end",
"def opendocument?\n false\n end",
"def opendocument?\n false\n end",
"def parse_response(xml)\n raise NotImplementedError\n end",
"def doc(response)\n Nokogiri::HTML(response.body) #selectionne le tag body de la reponse\nend",
"def extract_response_documents(response)\n return [response.body] unless @request_href.match(/\\.(atom|rss|xml)$|\\.(atom|rss|xml)\\?/)\n\n # RSS Feed case:\n response_bodies = []\n\n SimpleRSS.parse(response.body).items.each do |i|\n doc = \"\"\n i.each {|k, v| doc += \"#{k} is #{v}. \"}\n response_bodies.push doc\n end\n\n return response_bodies\n end",
"def document?\n self.type == \"Assetabler::Document\"\n end",
"def response?\n !!response\n end",
"def wellformed?\n Nokogiri::XML(File.read(@filename)) { |config| config.strict }\n\n true\n rescue Nokogiri::XML::SyntaxError => _\n @errors << 'XML file is not wellformed'\n\n false\n end",
"def content_type\n self.class.response_content_type\n end",
"def validate_document_support!\n return if ['rest-json', 'json'].include?(@service.protocol)\n\n # Check all shapes and raise if any are Document types\n @service.api.fetch('shapes', {}).each do |name, shape|\n if shape['type'] == 'structure' && shape['document']\n raise \"Shape #{name} is a document type. Document types are only supported in json protocols.\"\n end\n end\n end",
"def html?\n Page.html? content_type\n end",
"def xml!; @xml = true; end",
"def make_document(xml)\n xml.is_a?(Atom::XML::Document) ? xml : Atom::XML::Document.string(xml)\n end",
"def get_xml_of_type( asdcp_type, file, errors, errors_status )\n begin\n xml = Nokogiri::XML( open file )\n rescue Exception => e\n @logger.info \"#{ file }: #{ e.message }\"\n return false, errors, errors_status\n end\n\n unless xml.errors.empty?\n xml.errors.each do |error|\n # expected errors from non-xml\n next if error.message =~ /Start tag expected/ or error.message =~ /Document is empty/\n errors << \"Syntax error: #{ file }: #{ error }\"\n errors_status = true\n @logger.info errors.last\n end\n return false, errors, errors_status\n end\n\n if xml.root\n case xml.root.node_name\n when asdcp_type\n return xml, errors, errors_status\n else\n return false, errors, errors_status\n end\n else\n return false, errors, errors_status\n end\nend",
"def xml_http_request?; end",
"def xml; end",
"def render_xml\n end"
] |
[
"0.779974",
"0.76472497",
"0.74811816",
"0.74184513",
"0.68413216",
"0.67371863",
"0.6736005",
"0.6677461",
"0.6604043",
"0.65645057",
"0.65518534",
"0.64771414",
"0.6455537",
"0.6412899",
"0.63359034",
"0.6292246",
"0.6279942",
"0.62735593",
"0.62465644",
"0.6230246",
"0.6168813",
"0.6168813",
"0.61677366",
"0.6156741",
"0.61347663",
"0.61007917",
"0.60955226",
"0.6085149",
"0.6022358",
"0.59956455",
"0.59800065",
"0.5955045",
"0.59472877",
"0.59472877",
"0.5935829",
"0.59242964",
"0.5888725",
"0.5882479",
"0.5880709",
"0.587808",
"0.5872121",
"0.58674675",
"0.5866734",
"0.5863258",
"0.58542866",
"0.5851877",
"0.5850218",
"0.5850218",
"0.58424926",
"0.58308136",
"0.5823633",
"0.5815193",
"0.5813872",
"0.58089155",
"0.57967544",
"0.5789136",
"0.5784794",
"0.5780655",
"0.57739997",
"0.57673043",
"0.5764558",
"0.5757644",
"0.57515895",
"0.5742933",
"0.5741178",
"0.5729623",
"0.5725935",
"0.571263",
"0.5703914",
"0.5687096",
"0.5676003",
"0.56733304",
"0.5667105",
"0.56604064",
"0.565674",
"0.5655323",
"0.56508535",
"0.56137764",
"0.5588357",
"0.55803823",
"0.5557966",
"0.55489975",
"0.5545893",
"0.5529999",
"0.5529999",
"0.5526804",
"0.5523983",
"0.5521882",
"0.55167735",
"0.5514594",
"0.5483471",
"0.54637307",
"0.54493505",
"0.54383427",
"0.54345244",
"0.54325193",
"0.54245096",
"0.5420612",
"0.54204017",
"0.54203504"
] |
0.72053057
|
4
|
puts "this is a debug message"
|
def solution(a, b, k)
# write your code in Ruby 2.2
e = b / k
s = (a-1) / k
e - s
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def debug(msg)\n #puts msg\n end",
"def debug(s)\n\t#puts \"DEBUG: #{s}\"\nend",
"def print_debug(msg)\n puts msg if (@debug) \n STDOUT.flush\n end",
"def debug(message)\n puts message if debug?\n end",
"def debug(s) if $DEBUG then $stderr.print(\"#{s}\\n\") end end",
"def debug_msg( str )\n puts str if @debug == true\n end",
"def debug string\n puts string if $DEBUG\nend",
"def debug(text)\n\t\t\tputs text\n\t\t\tnil\n\t\tend",
"def debug(msg)\n $stderr.puts(\"DEBUG: #{msg}\") if $options['verbose']\nend",
"def debug(msg)\n $stderr.puts(\"DEBUG: #{msg}\") if $options['verbose']\nend",
"def debug(msg)\n $stderr.puts(\"DEBUG: #{msg}\") if $options['verbose']\nend",
"def debug(message)\n $stderr.puts(message) if @options[:debug]\nend",
"def debug(msg = \"\")\n puts \"\\n\\n\\n\"\n puts \" DEBUGGING \".white.on_red\n puts msg\n puts \"\\n\\n\\n\"\n exit\n end",
"def dprint(s)\n print s if $DEBUG\nend",
"def debug_msg msg\n puts msg if @options[:debug]\n end",
"def puts_debug(msg)\r\n if (self.debug) \r\n puts msg\r\n end # end debug\r\n end",
"def puts_debug(msg)\r\n if (self.debug) \r\n puts msg\r\n end # end debug\r\n end",
"def debug(msg)\n STDERR.puts msg if @debug\n end",
"def debug(message)\n puts \"#{Time.now.strftime(\"%H:%M:%S.%L\")} - \\t#{message}\" if DEBUG\nend",
"def debug1(text) debug text, 1 end",
"def say(word)\n require 'debug'\n puts word + ' to begin debugging.'\nend",
"def debug(stuff)\n puts \"DEBUG: #{stuff}\"\nend",
"def print_debug(s)\n config = BeEF::Core::Configuration.instance\n if config.get('beef.debug') || BeEF::Core::Console::CommandLine.parse[:verbose]\n puts Time.now.localtime.strftime(\"[%k:%M:%S]\")+'[>]'.yellow+' '+s.to_s\n end\nend",
"def debug_msg(msg=\"\")\n if(@config.debug)\n puts(\"Debug: #{msg}\")\n @file.puts(\"Debug: #{msg}\")\n end\n end",
"def debug(message)\n $stdout.puts \"D #{message}\" if @debug\n end",
"def debug(message)\n stdout.print(\"#{message}\\n\") if ENV['DEBUG']\n end",
"def debug(str)\n $stderr.puts(str) if @debug\n end",
"def debug_msg(msg)\n if(@options[:debug])\n @log.puts(msg)\n puts msg\n end\nend",
"def say_debug(message)\n puts yellow(message) if self.debug\n end",
"def puts(*strs); $stdout.puts(*strs) if ENV['DEBUG'] end",
"def debug_log( arg )\r\n print('DEBUG: ')\r\n puts (arg)\r\nend",
"def log(s)\n puts \"[Debug]: #{s}\"\nend",
"def log(s)\n puts \"[Debug]: #{s}\"\nend",
"def debug(msg)\n STDERR.puts msg if options.key? :debug\n end",
"def output_debug(string)\n if Command.ui\n Command.ui.debug string\n else\n $stderr.puts \"DEBUG: #{string}\"\n end\n end",
"def dputs str=\"\"\n\t\tputs str if debug?\n\tend",
"def debug(message)\n ostream.puts message if $DEBUG\n end",
"def debug (msg = \"\")\n if Object.const_defined?('Puppet')\n Puppet.debug msg\n else\n if ENV['FACTER_DEBUG'] == 'true'\n $stdout.puts msg\n $stdout.flush\n end\n end\nend",
"def dprint(str)\n if ANSIBLE_DEBUG\n print str\n end\nend",
"def debug(message)\n logger.debug(PROG_NAME) { message }\n end",
"def debug_msg( *msg )\n\t\treturn unless $DEBUG\n\t\t$stderr.puts( *msg )\n\tend",
"def debug_msg( *msg )\n\t\treturn unless $DEBUG\n\t\t$stderr.puts( *msg )\n\tend",
"def debug(*args); puts(*args) if $test; end",
"def debug(message) ; @log.debug(message) ; end",
"def debug(info)\n puts(info) if @debug\n end",
"def debug(message)\n return if quiet?\n say('[DEBUG] ' + message, :yellow) if $DEBUG\n end",
"def debug(msg)\n puts \"[watchr debug] #{msg}\" if options.debug\n end",
"def debugMsg( msg )\n\treturn unless $DEBUG\n\t$stderr.print \"#{msg}\\n\"\nend",
"def dmsg(msg)\n if $DEBUG\n case msg\n when String\n puts msg\n else\n puts msg.inspect\n end\n end\n end",
"def dmsg(msg)\n if $DEBUG\n case msg\n when String\n puts msg\n else\n puts msg.inspect\n end\n end\n end",
"def dmsg(msg)\n if $DEBUG\n case msg\n when String\n puts msg\n else\n puts msg.inspect\n end\n end\n end",
"def debug(msg) log(7, msg); end",
"def dputs(message)\n puts message\nend",
"def debug; end",
"def debug; end",
"def debug; end",
"def debug; end",
"def debug (what)\n ap what\n exit 2\nend",
"def dbg(msg, msgLevel = 1)\n\tif $options['debug'] >= msgLevel then\n\t\tputs \"#{msg}\"\n\tend\nend",
"def dbg(msg, msgLevel = 1)\n\tif $options['debug'] >= msgLevel then\n\t\tputs \"#{msg}\"\n\tend\nend",
"def debug(message)\n if DEBUG\n log message\n end\nend",
"def debug(msg)\n end",
"def puts_debug(*print_string)\n debug_code = true\n puts *print_string if debug_code\n end",
"def debug_out(debmsg)\n if $gDebug \n puts debmsg\n end\n if ($gTest_params[\"logfile\"])\n $fLOG.write(debmsg)\n end\nend",
"def debug(message)\n log(0, message)\n end",
"def debug_out(debmsg)\n if $gDebug\n puts debmsg\n end\n if ($gTest_params[\"logfile\"])\n $fLOG.write(debmsg)\n end\nend",
"def debug (msg = \"\")\n if Object.const_defined?('Puppet')\n Puppet.debug 'facter(extra_modulepath):'+msg\n else\n if ENV['FACTER_DEBUG'] == 'true'\n $stdout.puts msg\n $stdout.flush\n end\n end\nend",
"def debug!\n @client.debug_dev = STDOUT\n end",
"def debug(message)\n warn \"==== VLO DEBUG: \" + message if ENV[\"VLO_DEBUG\"] == 'true'\nend",
"def debug(text)\n puts \"#{text}\".foreground(:yellow)\n end",
"def debug(message = nil, progname = nil, &block)\n add(DEBUG, message, progname, &block)\n end",
"def debug( msg )\n puts Time.now.strftime(\"- %I:%M%p: \") + msg if @debug\nend",
"def debug_puts(puts_text)\n if Debug_Mode == true\n puts \"#{puts_text}\"\n end\n end",
"def debug(d)\n ap d\n puts\n exit 2\nend",
"def debug(msg)\n log.debug msg\n end",
"def debug(*args); end",
"def debug(*args); end",
"def debug(*args); end",
"def INFO(msg)\n if DEBUG\n puts \"INFO: \" + msg\n end\nend",
"def debug(*info)\n puts(info) if debug_mode?\n end",
"def debug(*text)\n if configuration.debug\n channel.write(\"command\" => \"debug\", \"text\" => text.join, \"on\" => on)\n end\n end",
"def debug_print(output, debug)\n\tif debug\n\t\tputs \"[*] #{output}\".red\n\tend\nend",
"def debug(str, ret = false)\r\n puts str if @debug\r\n return ret\r\n end",
"def debug(message = \"\", level = 5)\n if $config[:global][:verboselevel] and $config[:global][:verboselevel] >= level\n puts message \n\t\t#logger.info(message)\n Syslog.info(message)\n end\nend",
"def debug_print(returnedData, debug=\"false\")\n if debug == \"true\" then\n puts \"\\r\\n[DEBUG]\\r\\n\"\n pp(returnedData) \n end\nend",
"def debug(msg=nil)\n log \"DEBUG: #{msg}\" if $debug\n end",
"def debug(msg)\n return unless Fizzy::CFG.debug\n caller_info = caller\n .map { |c| c[/`.*'/][1..-2].split(\" \").first }\n .uniq[0..2]\n .join(\" → \")\n tell \"{m{⚫}}#{✏ caller_info, %w({b{<}} {b{>}})}{w{: #{msg}}}\"\n end",
"def debug_message(message)\n logger.debug \"**** - #{message}\"\n end",
"def debug(msg); @logger.debug(msg); end",
"def debug(msg, &block)\n result = yield\n puts \"-- #{msg} #{'-' * (74 - msg.length)}\" if $debug\n result\n end",
"def debug(msg) #:doc:\r\n if have_hook?(:on_debug)\r\n sync { self.class.debug msg }\r\n end\r\n end",
"def debug( msg )\n puts Time.now.strftime(\"- %I:%M%p: \") + msg\nend",
"def debug(msg, thread = nil)\n return nil unless $opt[:debug]\n function = (thread ? \"#{thread}.\" : '') + \\\n (caller[0][/`.*'/] ? caller[0][/`.*'/][1..-2].split(' ').last : 'core');\n puts \"#{function}#{(function.split(/\\.([^.]*)$/).last == 'core' ? '' : '()')}: #{msg}\".white\nend",
"def debug(msg) log(DEBUG, \"DEBUG \" << format(msg) << \", \" << caller[0][caller[0].rindex(\"/\").nil? ? 0 : caller[0].rindex(\"/\") + 1 .. -1]); end",
"def debug message; write DEBUG, message, caller[0] unless level > @level end",
"def debug(*args)\n $stderr.puts(sprintf(*args)) if @debug\n end",
"def debug(message)\n Edurange.logger.debug message\n end",
"def debug()\n # =========================================\n # DEBUG CODE FOR STEPPING\n # =========================================\n puts \"Curr char is: #{@curr_char}\"\n puts \"PC direction is: #{@curr_direction}\"\n puts \"Stack contents are: #{@stack}\"\n puts \"Skip is: #{@skip}\"\n puts \"Ascii_Mode is: #{@ascii_mode}\"\n prompt()\n STDIN.gets\n\n # =========================================\n # END DEBUG CODE\n # =========================================\n\n end",
"def write_debug( f )\n f.puts( $debug_buf )\n $debug_buf = \"\"\nend",
"def log_debug(message)\n Rails.logger.debug message\n puts message\n end",
"def debug?; end"
] |
[
"0.8406359",
"0.8268479",
"0.8211071",
"0.8138492",
"0.8107914",
"0.80671936",
"0.8004696",
"0.79987866",
"0.7975501",
"0.7975501",
"0.7975501",
"0.79284",
"0.78572273",
"0.78488684",
"0.7837523",
"0.7821288",
"0.7821288",
"0.7792199",
"0.7773948",
"0.7743215",
"0.7739327",
"0.77392334",
"0.77125454",
"0.7705425",
"0.77030075",
"0.7674084",
"0.7641472",
"0.7635617",
"0.76122314",
"0.7607222",
"0.7596653",
"0.7568291",
"0.7568291",
"0.75627065",
"0.7561845",
"0.7530402",
"0.75142545",
"0.7486465",
"0.74476266",
"0.7398443",
"0.7392124",
"0.7392124",
"0.7389751",
"0.7387766",
"0.73778945",
"0.7370045",
"0.73463976",
"0.73165655",
"0.7307878",
"0.7307878",
"0.7307878",
"0.7284727",
"0.7256834",
"0.72515905",
"0.72515905",
"0.72515905",
"0.72515905",
"0.7217113",
"0.7215761",
"0.7215761",
"0.7214241",
"0.7198336",
"0.7160688",
"0.715579",
"0.7149819",
"0.7127787",
"0.7125443",
"0.7106233",
"0.7096052",
"0.70934",
"0.7091538",
"0.7090718",
"0.7090086",
"0.7079579",
"0.70742637",
"0.7066664",
"0.7066664",
"0.7066664",
"0.70518154",
"0.7034283",
"0.70034087",
"0.70024234",
"0.6998635",
"0.6988879",
"0.69563323",
"0.6950195",
"0.69494313",
"0.6936724",
"0.6933031",
"0.69299227",
"0.69211537",
"0.69192326",
"0.6914229",
"0.6912095",
"0.69106394",
"0.6900422",
"0.68945295",
"0.6875811",
"0.68720067",
"0.68642783",
"0.6842386"
] |
0.0
|
-1
|
Find all existing volumes that belong to this cluster and cram their metadata into the existing logical volume
|
def adopt_existing_volumes!
Volume.all.each do |ec2_vol|
next if ec2_vol.deleted? || ec2_vol.deleting?
instance = Instance.find(ec2_vol.attached_instance_id) ; p instance ; next unless instance
cluster_node_id = instance.get_cluster_node_id(self.name) ; next unless cluster_node_id
cluster_vol_id = cluster_node_id + '-' + ec2_vol.device
volume_in_cluster = @all_volumes[cluster_vol_id] ; next unless volume_in_cluster
ec2_vol.update! volume_in_cluster.logical_attributes
@all_volumes[cluster_vol_id] = ec2_vol
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def get_volumes\n volumes = get(\"cloud-instances/#{guid}/volumes\")[\"volumes\"] || []\n\n volumes.map do |volume|\n get_volume(volume[\"volumeID\"])\n end\n end",
"def retrieve_volumes\n dbg { \"retrieving #{pool_info}, #{hv_info}\" }\n\n volumes = pool.list_all_volumes\n dbg { \"list_all_volumes #{pool_info}, #{hv_info}\" }\n\n storage_volumes = volumes.map.with_index do |vol, index|\n id = \"#{uuid}--#{index}\"\n StorageVolume.new(vol, pool: self, id: id)\n end\n\n dbg { \"retrieved size=#{storage_volumes.size}, #{pool_info}, #{hv_info}\" }\n storage_volumes\n end",
"def load_instances_and_volumes\n cluster_instances = cluster_config[:instances] or return\n cluster_instances.each do |role, instances_for_role|\n role = role.to_s\n instances_for_role.each_with_index do |instance_cfg, instance_idx|\n load_instance role, instance_idx, instance_cfg\n end\n end\n end",
"def list_volumes\n response = @connection.req(\"GET\", \"/#{@volume_path}\")\n volumes_hash = JSON.parse(response.body)[\"volumes\"]\n volumes_hash.inject([]){|res, current| res << OpenStack::Volume::Volume.new(current); res}\n end",
"def sync_from_tags(name)\n # First we'll do volumes\n found_volumes = @ec2.volumes.tagged(\"Name\").tagged_values(name)\n fv_count = found_volumes.count\n info \"Found #{fv_count} volumes tagged with #{name}\"\n# TODO: verify this against the other volumes?\n new_backupmeta = nil\n if fv_count > 0\n new_volsets = {}\n mount_point = nil\n size_vol = nil\n found_volumes.each do |vol|\n thetags = vol.tags.to_h\n unless new_volsets.has_key?(thetags[\"volset_uuid\"])\n new_volsets[thetags[\"volset_uuid\"]] = Volset.create()\n end\n new_volsets[thetags[\"volset_uuid\"]].volumes << Volume.create(:id => vol.id, :device_letter => thetags[\"device_letter\"])\n# these tags can be found on any volume\n mount_point = thetags[\"mount_point\"]\n size_vol = vol.size\n end\n new_backupmeta = Backupmeta.new(:name => name, :mount_point => mount_point, :size_vol => size_vol)\n new_volsets.each do |_,v|\n new_backupmeta.volsets << v\n v.save\n end\n new_backupmeta.save\n end\n # Then we'll do snaps\n found_snapshots = @ec2.snapshots.tagged(\"Name\").tagged_values(name)\n fs_count = found_snapshots.count\n info \"Found #{fs_count} snapshots tagged with #{name}\"\n if fs_count > 0\n new_snapsets = {}\n mount_point = nil\n size_vol = nil\n found_snapshots.each do |snap|\n thetags = snap.tags.to_h\n unless new_snapsets.has_key?(thetags[\"snapset_uuid\"])\n new_snapsets[thetags[\"snapset_uuid\"]] = Snapset.create(:started_at => snap.start_time.to_s)\n end\n new_snapsets[thetags[\"snapset_uuid\"]].snapshots << Snapshot.create(:id => snap.id, :device_letter => thetags[\"device_letter\"])\n size_vol = snap.volume_size\n mount_point = thetags[\"mount_point\"]\n end\n# Create a new backupmeta if it wasn't created in the snapsync\n unless new_backupmeta\n new_backupmeta = Backupmeta.new(:name => name, :mount_point => mount_point, :size_vol => size_vol)\n end\n new_snapsets.each do |_,v|\n new_backupmeta.snapsets << v\n v.save\n end\n new_backupmeta.save\n end\n end",
"def related_storage_volumes\n related_volumes.find_all do |volume|\n volume.provider_name == \"compellent\" || volume.provider_name == \"vnx\"\n end\n end",
"def list_all_volumes\n Docker::Volume.all({}, client)\n rescue\n []\n end",
"def load_volume cluster_node_id, volume_cfg\n cluster_vol_id = cluster_node_id + '-' + volume_cfg[:device]\n cluster_vol_params = {\n :cluster => self,\n :cluster_vol_id => cluster_vol_id, :cluster_node_id => cluster_node_id,\n }.merge(\n volume_cfg.slice(:mount_point, :size, :from_snapshot_id, :availability_zone, :device))\n @all_volumes[cluster_vol_id] = Volume.new(cluster_vol_params)\n end",
"def volumes\n @volumes.to_a.freeze\n end",
"def init_ebs_volumes\n @@client.describe_volumes.volumes\n end",
"def volumes\n service.list_pool_volumes uuid\n end",
"def domain_volumes\n # Use the domain name as our volume base name.\n base_name = domain_name\n\n if not config[:image_name]\n config[:image_name] = default_image\n end\n\n # Clone our root volume from our base image.\n root_volume = clone_volume(config[:image_name], \"#{base_name}-root\")\n\n # Return the array of created volumes\n [root_volume].concat(\n create_volumes(\n extra_volumes(base_name)\n )\n )\n end",
"def getVolumes\n require 'rest_client'\n require 'uri'\n\n if @role.nil? and !current_actor.superadmin\n json_response({ message: \"You don't have permission to view volumes\" }, :unauthorized)\n return\n end\n\n # Env variables for Manager host and port\n serviceManagerHost = Settings.service_manager_host\n serviceManagerPort = Settings.service_manager_port.to_s\n serviceManagerURI = 'http://' + serviceManagerHost + ':' + serviceManagerPort + '/v1/volume'\n\n # Create request for Service Manager\n stack = {\n 'engine-url' => @cluster.endpoint,\n 'ca-cert' => @cluster.ca,\n 'cert' => @cluster.cert,\n 'cert-key' => @cluster.key\n }.to_json\n\n begin\n response = RestClient.post(\n serviceManagerURI,\n stack,\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json'\n )\n puts \"Deploy Response: \" + response\n json_response(response, 200)\n rescue Exception => e\n # If error, respond with it\n puts e\n json_response({message: e}, :unprocessable_entity)\n end\n end",
"def update_volume_info\n\t\t#\t\t@pool = Pool.find(self.pool_id)\n\t\t#\t\t@host = Host.find(@pool.host_id)\n\t\t#\n\t\t#\t\tconnection = ConnectionsManager.instance\n\t\t#\t\tconnection_hash = connection.get(@host.name)\n\t\t#\t\tconn = connection_hash[:conn]\n\n\t\t# get pool reference in order to get a reference to the volume\n\t\t@pool = @conn.lookup_storage_pool_by_name(@pool.name)\n\t\tvolume = @pool.lookup_volume_by_name(self.name)\n\t\tvolume_info = volume.info\n\t\t\n\t\t# add some stats to pool object\n\t\tdivide_to_gigabytes = (1024 * 1024 * 1024).to_f\n\t\tself.allocation = (volume_info.allocation.to_f / divide_to_gigabytes).to_f\n\tend",
"def index\n @actual_volumes = ActualVolume.all\n end",
"def getmountedvolumes\n # only support Linux for now\n return {} unless Facter['kernel'] && Facter['kernel'].value == 'Linux'\n\n dir = \"/etc\"\n mounted = {}\n\n # AUTOFS - gather only files named auto[._]*\n Dir.glob(File.join(dir, \"*\")).each do |file|\n next if file !~ /^auto[._].*/\n\n # AUTOFS - match only lines that look like nfs syntax such as host:/path\n IO.foreach(file) do |line|\n if line =~ /\\w:\\S/ && line !~ /^\\s*#/\n # Parse it, Example : \" nventory_backup -noatime,intr irvnetappbk:/vol/nventory_backup \"\n if line =~ /^(\\w[\\w\\S]+)\\s+\\S+\\s+(\\w[\\w\\S]+):(\\S+)/\n mnt = $1\n host = $2\n vol = $3\n mounted[\"volumes[mounted][/mnt/#{mnt}][config]\"] = file\n mounted[\"volumes[mounted][/mnt/#{mnt}][volume_server]\"] = host\n mounted[\"volumes[mounted][/mnt/#{mnt}][volume]\"] = vol\n mounted[\"volumes[mounted][/mnt/#{mnt}][type]\"] = 'nfs'\n end\n end\n end # IO.foreach\n end # Dir.glob\n\n # FSTAB - has diff syntax than AUTOFS. Example: \"server:/usr/local/pub /pub nfs rsize=8192,wsize=8192,timeo=14,intr\"\n IO.foreach(\"/etc/fstab\") do |line|\n if line =~ /^(\\w[\\w\\S]+):(\\S+)\\s+(\\S+)\\s+nfs/\n host = $1\n vol = $2\n mnt = $3\n mounted[\"volumes[mounted][#{mnt}][config]\"] = \"/etc/fstab\"\n mounted[\"volumes[mounted][#{mnt}][volume_server]\"] = host\n mounted[\"volumes[mounted][#{mnt}][volume]\"] = vol\n mounted[\"volumes[mounted][#{mnt}][type]\"] = 'nfs'\n end\n end # IO.foreach\n return mounted\n end",
"def root_volumes\n volumes.select {|vol| vol.parent_id == nil}\n end",
"def volumes\n Collection::StorageVolumeCollection.new(self)\n end",
"def volume(volume_name, attrs={}, &block)\n volumes[volume_name] ||= Ironfan::Volume.new(:parent => self, :name => volume_name)\n volumes[volume_name].configure(attrs, &block)\n volumes[volume_name]\n end",
"def volumes\n volumes = @ec2.volumes\n volumes.delete_if {|v| v.instance_id != id}\n end",
"def sync_volume_attributes\n step(\" updating volume attributes\")\n end",
"def repair\n response = client.rest_post(BASE_URI + '/repair', 'body' => { resourceUri: @data['uri'], type: 'ExtraManagedStorageVolumePaths' })\n client.response_handler(response)\n end",
"def create!\n set_id = generate_set_id\n\n @volume_ids.each do |id|\n snapshot = @fog.snapshots.new\n\n snapshot.description = \"#{@hostname.split(\".\")[0]} #{@mount} (#{self.needed_types.join(\", \")}) (#{set_id})\"\n snapshot.volume_id = id\n\n # Actually do the snapshot\n snapshot.save\n\n # Reload to get snapshot.id so we can add tags\n snapshot.reload\n\n @fog.tags.create(:resource_id => snapshot.id, :key => \"Host\", :value => @hostname)\n @fog.tags.create(:resource_id => snapshot.id, :key => \"Mount\", :value => @mount)\n @fog.tags.create(:resource_id => snapshot.id, :key => \"SetID\", :value => set_id)\n @fog.tags.create(:resource_id => snapshot.id, :key => \"Type\", :value => self.needed_types.join(\",\"))\n end\n end",
"def mount_ephemerals(attrs={})\n owner.volume(:ephemeral0, attrs){ device '/dev/sdb'; volume_id 'ephemeral0' ; mount_point '/mnt' ; tags( :bulk => true, :local => true, :fallback => true) } if flavor_info[:ephemeral_volumes] > 0\n owner.volume(:ephemeral1, attrs){ device '/dev/sdc'; volume_id 'ephemeral1' ; mount_point '/mnt2'; tags( :bulk => true, :local => true, :fallback => true) } if flavor_info[:ephemeral_volumes] > 1\n owner.volume(:ephemeral2, attrs){ device '/dev/sdd'; volume_id 'ephemeral2' ; mount_point '/mnt3'; tags( :bulk => true, :local => true, :fallback => true) } if flavor_info[:ephemeral_volumes] > 2\n owner.volume(:ephemeral3, attrs){ device '/dev/sde'; volume_id 'ephemeral3' ; mount_point '/mnt4'; tags( :bulk => true, :local => true, :fallback => true) } if flavor_info[:ephemeral_volumes] > 3\n end",
"def attach_volumes(node, disk_sizes)\n if $provider == :virtualbox\n node.vm.provider :virtualbox do |v, override|\n disk_num = 0\n disk_sizes.each do |disk_size|\n disk_num += 1\n diskname = File.join(File.dirname(File.expand_path(__FILE__)), \".virtualbox\", \"#{node.vm.hostname}-#{disk_num}.vdi\")\n unless File.exist?(diskname)\n v.customize ['createhd', '--filename', diskname, '--size', disk_size * 1024]\n end\n v.customize ['storageattach', :id, '--storagectl', 'SATA Controller', '--port', disk_num, '--device', 0, '--type', 'hdd', '--medium', diskname]\n end\n end\n end\n\n if $provider == :vmware_fusion\n node.vm.provider :vmware_fusion do |v, override|\n vdiskmanager = '/Applications/VMware\\ Fusion.app/Contents/Library/vmware-vdiskmanager'\n unless File.exist?(vdiskmanager)\n dir = File.join(File.dirname(File.expand_path(__FILE__)), \".vmware\")\n unless File.directory?( dir )\n Dir.mkdir dir\n end\n\n disk_num = 0\n disk_sizes.each do |disk_size|\n disk_num += 1\n diskname = File.join(dir, \"#{node.vm.hostname}-#{disk_num}.vmdk\")\n unless File.exist?(diskname)\n `#{vdiskmanager} -c -s #{disk_size}GB -a lsilogic -t 1 #{diskname}`\n end\n\n v.vmx[\"scsi0:#{disk_num}.filename\"] = diskname\n v.vmx[\"scsi0:#{disk_num}.present\"] = 'TRUE'\n v.vmx[\"scsi0:#{disk_num}.redo\"] = ''\n end\n end\n end\n end\n\n if $provider == :parallels\n node.vm.provider :parallels do |v, override|\n disk_sizes.each do |disk_size|\n v.customize ['set', :id, '--device-add', 'hdd', '--size', disk_size * 1024]\n end\n end\n end\n\nend",
"def index\n @volumes = Volume.all\n end",
"def index\n @volumes = Volume.all\n end",
"def existing_kvms\n Dir.glob(File.join(KVM_HOME, 'storage', '*.qcow2')).map do |file|\n File.basename(file).sub('.qcow2', '')\n end\nend",
"def merge_volumes(original_volumes, new_volumes)\n new_volumes = process_volumes(new_volumes)\n\n merged_volumes = original_volumes.map do |orig_vol|\n volume = orig_vol\n\n new_volumes.each do |new_vol|\n if new_vol[:name] == orig_vol[:name]\n volume = new_volumes.delete(new_vol)\n end\n end\n\n volume\n end\n\n merged_volumes.push(new_volumes).flatten\n end",
"def manage_planned_volumes(&block)\n # state may have changed since timer calling this method was added, so\n # ensure we are still booting (and not stranded).\n return if InstanceState.value == 'stranded'\n\n # query for planned volume mappings belonging to instance.\n last_mappings = InstanceState.planned_volume_state.mappings || []\n payload = {:agent_identity => @agent_identity}\n req = RetryableRequest.new(\"/storage_valet/get_planned_volumes\", payload, :retry_delay => VolumeManagement::VOLUME_RETRY_SECONDS)\n req.callback do |res|\n res ||= [] # res is nil or an array of hashes\n begin\n mappings = merge_planned_volume_mappings(last_mappings, res)\n InstanceState.planned_volume_state.mappings = mappings\n if mappings.empty?\n # no volumes requiring management.\n @audit.append_info(\"This instance has no planned volumes.\")\n block.call if block\n elsif (detachable_volume_count = mappings.count { |mapping| is_unmanaged_attached_volume?(mapping) }) >= 1\n # must detach all 'attached' volumes if any are attached (or\n # attaching) but not yet managed on the instance side. this is the\n # only way to ensure they receive the correct device names.\n mappings.each do |mapping|\n if is_unmanaged_attached_volume?(mapping)\n detach_planned_volume(mapping) do\n detachable_volume_count -= 1\n if 0 == detachable_volume_count\n # add a timer to resume volume management later and pass the\n # block for continuation afterward (unless detachment stranded).\n Log.info(\"Waiting for volumes to detach for management purposes. \"\\\n \"Retrying in #{VolumeManagement::VOLUME_RETRY_SECONDS} seconds...\")\n EM.add_timer(VolumeManagement::VOLUME_RETRY_SECONDS) { manage_planned_volumes(&block) }\n end\n end\n end\n end\n elsif mapping = mappings.find { |mapping| is_detaching_volume?(mapping) }\n # we successfully requested detachment but status has not\n # changed to reflect this yet.\n Log.info(\"Waiting for volume #{mapping[:volume_id]} to fully detach. \"\\\n \"Retrying in #{VolumeManagement::VOLUME_RETRY_SECONDS} seconds...\")\n EM.add_timer(VolumeManagement::VOLUME_RETRY_SECONDS) { manage_planned_volumes(&block) }\n elsif mapping = mappings.find { |mapping| is_managed_attaching_volume?(mapping) }\n Log.info(\"Waiting for volume #{mapping[:volume_id]} to fully attach. Retrying in #{VolumeManagement::VOLUME_RETRY_SECONDS} seconds...\")\n EM.add_timer(VolumeManagement::VOLUME_RETRY_SECONDS) { manage_planned_volumes(&block) }\n elsif mapping = mappings.find { |mapping| is_managed_attached_unassigned_volume?(mapping) }\n manage_volume_device_assignment(mapping) do\n unless InstanceState.value == 'stranded'\n # we can move on to next volume 'immediately' if volume was\n # successfully assigned its device name.\n if mapping[:management_status] == 'assigned'\n EM.next_tick { manage_planned_volumes(&block) }\n else\n Log.info(\"Waiting for volume #{mapping[:volume_id]} to initialize using \\\"#{mapping[:mount_points].first}\\\". \"\\\n \"Retrying in #{VolumeManagement::VOLUME_RETRY_SECONDS} seconds...\")\n EM.add_timer(VolumeManagement::VOLUME_RETRY_SECONDS) { manage_planned_volumes(&block) }\n end\n end\n end\n elsif mapping = mappings.find { |mapping| is_detached_volume?(mapping) }\n attach_planned_volume(mapping) do\n unless InstanceState.value == 'stranded'\n unless mapping[:attempts]\n @audit.append_info(\"Attached volume #{mapping[:volume_id]} using \\\"#{mapping[:mount_points].first}\\\".\")\n Log.info(\"Waiting for volume #{mapping[:volume_id]} to appear using \\\"#{mapping[:mount_points].first}\\\". \"\\\n \"Retrying in #{VolumeManagement::VOLUME_RETRY_SECONDS} seconds...\")\n end\n EM.add_timer(VolumeManagement::VOLUME_RETRY_SECONDS) { manage_planned_volumes(&block) }\n end\n end\n elsif mapping = mappings.find { |mapping| is_unmanageable_volume?(mapping) }\n strand(\"State of volume #{mapping[:volume_id]} was unmanageable: #{mapping[:volume_status]}\")\n else\n # all volumes are managed and have been assigned and so we can proceed.\n block.call if block\n end\n rescue Exception => e\n strand(e)\n end\n end\n\n req.errback do |res|\n strand(\"Failed to retrieve planned volume mappings\", res)\n end\n\n req.run\n end",
"def extra_volumes(base_name)\n configs = []\n\n config[:extra_volumes].each_with_index do |data, index|\n disk_id = (index + 1).to_s.rjust(2, '0')\n data[:name] = \"#{base_name}-extra-#{disk_id}\"\n configs << data\n end\n\n configs\n end",
"def volume_from(name)\n volumes << VolumeFrom.new(name)\n end",
"def take_snapshots\n snapped_volumes = []\n logger.debug \"Issuing sync command\"\n system 'sync'\n\n logger.debug \"Walking attached volumes\"\n attached_volumes.each do |vol|\n dir = device_to_directory device_name vol\n logger.debug \"Found #{vol.id} mounted on #{dir}\"\n unless should_snap vol\n logger.debug \"Skipping #{vol.id}\"\n next\n end\n\n fs_freeze dir if options[:fs_freeze]\n take_snapshot vol\n snapped_volumes.push vol\n fs_unfreeze dir if options[:fs_freeze]\n end\n snapped_volumes\n end",
"def volume_names\n pool.list_volumes\n end",
"def fetch_mounted_nfs_shares\n if resource[:nfs_hostname]\n # Get list of all mounted NFS datastores, and add it to mounted NFS shares\n Puppet.debug(\"Getting list of mounted NFS datastores...\")\n host.esxcli.storage.nfs.list.each do |nfs_store|\n if nfs_store[:Host] && nfs_store[:Share] && nfs_store[:Mounted]\n key = nfs_store[:Host] + \":\" + nfs_store[:Share]\n @mounted_nfs_shares[key] = { :volume_name => nfs_store[:VolumeName], :new_mount => false }\n Puppet.debug(\"Found existing NFS mount #{key} on the ESX host\")\n end\n end\n end\n end",
"def child_volumes(name)\n parent = volume_by_name(name)\n volumes.select {|vol| vol.parent_id == parent.volume_id}\n end",
"def volume_by_id(ec2,volid)\n ec2.describe_volumes.body['volumeSet'].each do |volume|\n if volume['volumeId'] == volid\n x= {\n :type => volume['volumeType'],\n :status => volume['status'],\n :az => volume['availabilityZone'],\n :size => volume['size']\n }\n #puts \"VOLINFO #{volid}\\n\"+volume.to_yaml\n x[:instance_id] = volume['attachmentSet'].first['instanceId'] if volume['attachmentSet'].length>0 && volume['attachmentSet'].first.has_key?('instanceId')\n return x\n end\n end\n return {}\nend",
"def getservedvolumes\n # only support Linux for now\n return {} unless Facter['kernel'] && Facter['kernel'].value == 'Linux'\n\n # Don't do anything if exports file is not there\n return {} if !File.exists?(\"/etc/exports\")\n\n served = {}\n\n IO.foreach(\"/etc/exports\") do |line|\n if line =~ /(\\S+)\\s+/\n vol = $1\n served[\"volumes[served][#{vol}][config]\"] = \"/etc/exports\"\n served[\"volumes[served][#{vol}][type]\"] = 'nfs'\n end\n end\n return served\n end",
"def provision_storage host, vm\n if host['volumes']\n # Lazily create the volume client if needed\n volume_client_create\n host['volumes'].keys.each_with_index do |volume, index|\n @logger.debug \"Creating volume #{volume} for OpenStack host #{host.name}\"\n\n # The node defintion file defines volume sizes in MB (due to precedent\n # with the vagrant virtualbox implementation) however OpenStack requires\n # this translating into GB\n openstack_size = host['volumes'][volume]['size'].to_i / 1000\n\n # Create the volume and wait for it to become available\n vol = @volume_client.volumes.create(\n :size => openstack_size,\n :display_name => volume,\n :description => \"Beaker volume: host=#{host.name} volume=#{volume}\",\n )\n vol.wait_for { ready? }\n\n # Fog needs a device name to attach as, so invent one. The guest\n # doesn't pay any attention to this\n device = \"/dev/vd#{('b'.ord + index).chr}\"\n vm.attach_volume(vol.id, device)\n end\n end\n end",
"def setup_volumes\n # managing planned volumes is currently only needed in Windows and only if\n # this is not a reboot scenario.\n if !RightScale::Platform.windows? || RightScale::InstanceState.reboot?\n boot\n else\n RightScale::AuditProxy.create(@agent_identity, 'Planned volume management') do |audit|\n @audit = audit\n manage_planned_volumes do\n @audit = nil\n boot\n end\n end\n end\n true\n end",
"def add_persistent_volume(volume, host_spec = {:host_name => 'localhost'})\n @per_volumes_by_hosts[host_spec[:host_name]] << volume\n @hosts_specs[host_spec[:host_name]] ||= host_spec.to_h\n end",
"def all\n containers = service.list_containers\n data = []\n containers.each do |container|\n c = parse_storage_object(container)\n c[:acl] = 'unknown'\n data << c\n end\n load(data)\n end",
"def all_devices search = nil\n partitions = []\n devices = []\n device = nil\n has_extended = false\n if DEBUG_MODE or Platform.ubuntu? or Platform.fedora?\n command = \"lsblk\"\n params = \" #{search} -b -P -o VENDOR,MODEL,TYPE,SIZE,KNAME,UUID,LABEL,MOUNTPOINT,FSTYPE,RM\"\n end\n lsblk = CommandsExecutor.new command, params\n lsblk.execute\n raise \"Command execution error: #{lsblk.stderr.read}\" if not lsblk.success?\n\n lsblk.result.each_line do |line|\n data_hash = {}\n line.squish!\n line_data = line.gsub!(/\"(.*?)\"/, '\\1#').split \"#\"\n line_data.each do |data|\n data.strip!\n key, value = data.split \"=\"\n data_hash[key.downcase] = value\n end\n data_hash['rm'] = data_hash['rm'].to_i # rm = 1 if device is a removable/flash device, otherwise 0\n if data_hash['type'] == 'mpath'\n data_hash.except!('uuid', 'label', 'mountpoint', 'fstype')\n if device\n multipath_info = {'mkname' => data_hash['kname'], 'multipath' => true, 'size' => data_hash['size']}\n device.merge! multipath_info\n else\n data_hash['multipath'] = true\n device = data_hash\n devices.push device\n end\n next\n end\n if data_hash['type'] == 'disk'\n data_hash.except!('uuid', 'label', 'mountpoint', 'fstype')\n unless device.nil?\n device['partitions'] = partitions\n partitions = []\n devices.push device\n device = nil # cleanup the variable\n end\n device = data_hash\n next\n end\n if data_hash['type'] == 'part'\n data_hash.except!('model', 'vendor')\n data_hash.merge! self.usage data_hash['kname']\n\n partition_number = get_partition_number \"/dev/#{data_hash['kname']}\" # For reference: data_hash['kname'].match(/[0-9]*$/)[0].to_i\n extended_partition_types = ['0x05'.hex, '0x0F'.hex]\n if partition_type_hex(data_hash['kname']).in? extended_partition_types\n has_extended = true\n next\n end\n if has_extended and partition_number > 4\n data_hash['logical'] = true\n end\n # device['partitions'].nil? ? device['partitions'] = [data_hash] : device['partitions'].push(data_hash)\n partitions.push(data_hash)\n end\n end\n device['partitions'] = partitions if device\n devices.push device\n if search\n return devices.first || partitions.first\n else\n return devices\n end\n end",
"def populate_volume(server)\n server.spot_check_command(\" echo \\\"blah blah blah\\\" > #{@mount_point}/data.txt\")\n end",
"def volume(volume, server)\n new_volume = { server => { 'volume' => volume }}\n unless STREAM_DATA.stream_data[server].nil?\n m = STREAM_DATA.stream_data.merge!(new_volume) { |_key, left, right| left.merge!(right) }\n STREAM_DATA.add(m)\n else\n m = STREAM_DATA.stream_data.merge!(new_volume) { |_key, left, right| left.merge!(right) }\n STREAM_DATA.add(m)\n end\n end",
"def discover_new_disks\n logger.debug 'Discovering new virtual disks.'\n\n StorageNode.list_disks().each do |volume|\n disk = VirtualDisk.find_by_disk_number(volume)\n next if disk\n\n disk_size = StorageNode.volume_size(volume)\n logger.info 'autodiscovered virtual disk %d with size %d Mb' % [volume, disk_size]\n disk = VirtualDisk.new(volume, disk_size)\n disk.save('discovered')\n end\n end",
"def ebs_volumes\n @ebs_volumes ||= init_ebs_volumes.reject do |vol|\n vol.attachments.any? do |att|\n attached_instance = id_instances[att.instance_id]\n attached_instance.root_device_name == att.device\n end\n end\n end",
"def volumes\n client = Aws::EC2::Client.new\n client.describe_volumes({\n filters: [{\n name: \"tag:backup\",\n values: [\"true\"]\n }]\n }).volumes\nend",
"def volume_ls\n help = [\n '',\n \"Use: #{me} volume ls\",\n '',\n 'Lists the names of all cyber-dojo volumes',\n '',\n minitab + '--quiet Only display volume names'\n ]\n\n if ['help','--help'].include? ARGV[2]\n show help\n exit failed\n end\n\n # There is currently no [--filter label=LABEL] option on [docker volume ls]\n # https://github.com/docker/docker/pull/21567\n # So I have to inspect all volumes. Could be slow if lots of volumes.\n\n names = run(\"docker volume ls --quiet\").split\n names = names.select{ |name| cyber_dojo_volume?(name) }\n\n if ARGV[2] == '--quiet'\n names.each { |name| puts name }\n else\n types = names.map { |name| cyber_dojo_type(name) }\n urls = names.map { |name| cyber_dojo_label(name) }\n\n headings = { :name => 'NAME', :type => 'TYPE', :url => 'SRC' }\n\n gap = 3\n max_name = ([headings[:name]] + names).max_by(&:length).length + gap\n max_type = ([headings[:type]] + types).max_by(&:length).length + gap\n max_url = ([headings[:url ]] + urls ).max_by(&:length).length + gap\n\n spaced = lambda { |max,s| s + (space * (max - s.length)) }\n\n name = spaced.call(max_name, headings[:name])\n type = spaced.call(max_type, headings[:type])\n url = spaced.call(max_url , headings[:url ])\n puts name + type + url\n names.length.times do |n|\n name = spaced.call(max_name, names[n])\n type = spaced.call(max_type, types[n])\n url = spaced.call(max_url , urls[n])\n puts name + type + url\n end\n end\nend",
"def set_volume\n @volume = services.block_storage.get_volume(params[:id])\n end",
"def load_layout\n return unless cluster_config\n @all_volumes = {}\n @all_instances = {}\n load_attrs\n load_instances_and_volumes\n end",
"def sync_with_cluster\n fetch_cluster_data\n reconcile_old_releases\n reconcile_db_with_cluster\n end",
"def compile_metadata\n each do |cookbook_name, cookbook|\n compiled_metadata = cookbook.compile_metadata\n if compiled_metadata\n cookbook.all_files << compiled_metadata\n cookbook.cookbook_manifest.send(:generate_manifest)\n end\n end\n end",
"def create_volumes(volume_definitions)\n volume_definitions.each { |volume| client.volumes.create(volume) }\n end",
"def collectVMs(rf, db)\n\trf.childEntity.grep(RbVmomi::VIM::Datacenter).each do |dc|\n\t\tprogressbar = ProgressBar.create(:title => \"VMs\", :format => '%t |%b>>%i| %p%% %a')\n\t\tprogressbar.total = counter(dc, \"v\")\n\t\tdc.vmFolder.childEntity.each do |folder|\n\t\t\tfolder.childEntity.each do |vmlist|\n\t\t\t\tnext if vmlist.class.to_s == \"Folder\"\n\t\t\t\tdb.select(3)\n\t\t\t\tdb.hset(\"#{vmlist.name}\", \"Status\", \"#{vmlist.summary.overallStatus}\")\n\t\t\t\tdb.hset(\"#{vmlist.name}\", \"Uptime\", \"#{vmlist.summary.quickStats.uptimeSeconds}\")\n\t\t\t\tdb.hset(\"#{vmlist.name}\", \"CPUusage\", \"#{vmlist.summary.quickStats.overallCpuUsage}\")\n\t\t\t\tdb.hset(\"#{vmlist.name}\", \"CPUnum\", \"#{vmlist.summary.config.numCpu}\")\n\t\t\t\tdb.hset(\"#{vmlist.name}\", \"MemUsage\", \"#{vmlist.summary.quickStats.guestMemoryUsage}\")\n\t\t\t\tdb.hset(\"#{vmlist.name}\", \"MemTotal\", \"#{vmlist.summary.config.memorySizeMB}\")\n\t\t\t\tprogressbar.increment\n\t\t\tend\n\t\tend\n\tend\nend",
"def collectClusters(rf, db)\n\trf.childEntity.grep(RbVmomi::VIM::Datacenter).each do |dc|\n\t\tprogressbar = ProgressBar.create(:title => \"Clusters\", :format => '%t |%b>>%i| %p%% %a')\n\t\tprogressbar.total = counter(dc, \"c\")\n\t\tdc.hostFolder.childEntity.each do |cluster|\n\t\t\tdb.select(1)\n\t\t\tdb.hset(\"#{cluster.name}\", \"Status\", \"#{cluster.summary.overallStatus}\") \n\t\t\tdb.hset(\"#{cluster.name}\", \"NumberHosts\", \"#{cluster.summary.numHosts}\")\n\t\t\tdb.hset(\"#{cluster.name}\", \"EffectiveHosts\", \"#{cluster.summary.numEffectiveHosts}\") \n\t\t\tdb.hset(\"#{cluster.name}\", \"CPUtotal\", \"#{cluster.summary.totalCpu}\")\n\t\t\tdb.hset(\"#{cluster.name}\", \"EffectiveCPU\", \"#{cluster.summary.effectiveCpu}\")\n\t\t\tdb.hset(\"#{cluster.name}\", \"MemTotal\", \"#{cluster.summary.totalMemory}\")\n\t\t\tdb.hset(\"#{cluster.name}\", \"EffectiveMem\", \"#{cluster.summary.effectiveMemory}\")\n\t\t\tprogressbar.increment\n\t\tend\n\tend\nend",
"def volume_report\n get_resource_list('volume', 'volumes', 'volumes')\n @volume_csv_array = []\n @resource_id_list.each do |volumeid|\n volume = rest_get(\"#{@resource_url}/volumes/#{volumeid}\", @token_id)\n volume_array = JSON.parse(volume)['volume']\n volume_name = volume_array['name']\n volume_status = volume_array['status']\n volume_template = volume_array['volume_type']\n volume_size = volume_array['size']\n @volume_csv_headers = %w(Volume_Name Volume_Status Storage_Template Volume_Size)\n @volume_csv_array << [volume_name, volume_status, volume_template, volume_size]\n end\n end",
"def volinfo(compute,name)\n\t\tvolumes = compute.describe_volumes\n\t\tif (volumes.status == 200)\n\t\t\t# check each of the volumes in our availability zone which match our name.\n\t\t\tvolumes.body['volumeSet'].each {|x|\n\t\t\t\t# Match the name unless the volume is actually being deleted...\n\t\t\t\tif (x['tagSet']['Name'] == resource[:volume_name] )\n\t\t\t\t\t#print \"ebsvol[aws]->volinfo: Volume #{x['volumeId']} has Name = #{resource[:volume_name]}\\n\" if $debug\n\t\t\t\t\treturn x\n\t\t\t\tend\n\t\t\t}\n\t\telse\n\t\t\traise \"ebsvol[aws]->volinfo: I couldn't list the ebsvolumes\"\n\t\tend\n\t\tnil\n\tend",
"def metadata_with_clustering scope\n if @box_size >= 10\n grid_size = @box_size / 15\n elsif @box_size >= 5\n grid_size = @box_size / 30\n else\n # no clustering\n grid_size = nil\n end\n\n scope = scope.unscope(:select)\n projections = [\n \"pois.id\",\n \"to_char(pois.updated_at, 'YYYYMMDDHH24MISSUS000')\"\n ]\n\n if grid_size\n # The sorting expression of the `distinct on` clause conflicts\n # with the one we want to use to sort the results globally.\n # To solve this, we cluster in a CTE, then sort again in the main query.\n\n cte_projections = [\n \"pois.id\", \"pois.updated_at\", # for the metadata\n \"pois.latitude\", \"pois.longitude\" # for the sorting by distance\n ]\n\n # prefix a `distinct on` clause to the first expression for clustering\n cte_projections[0] = %{\n distinct on (\n ST_SnapToGrid(\n #{PostgisHelper.point(:\"pois.latitude\", :\"pois.longitude\")},\n #{grid_size * 1000})\n )\n #{cte_projections[0]}\n }\n\n sql = %(\n with pois as (\n #{scope.unscope(:order, :limit).select(*cte_projections).to_sql}\n )\n #{scope.unscope(:where, :joins).select(*projections).to_sql}\n ).squish\n else\n sql = scope.select(*projections).to_sql\n end\n\n result = ApplicationRecord.connection.execute(sql)\n metadata = result.values\n result.clear\n\n metadata\n end",
"def collectVMs(rf, db)\n\trf.childEntity.grep(RbVmomi::VIM::Datacenter).each do |dc|\n\t\tprogressbar = ProgressBar.create(:title => \"#{$single_folder}\", :format => '%t |%b>>%i| %p%% %a')\n\t\tif dc.vmFolder.childEntity.find { |x| x.name == \"#{$single_folder}\" }\n\t\t\tfolder = dc.vmFolder.childEntity.find { |x| x.name == \"#{$single_folder}\" }\n\t\t\tprogressbar.total = folder.childEntity.length\n\t\t\tfolder.childEntity.each do |vmlist|\n\t\t\t\tdb.select(3)\n\t\t\t\tdb.hset(\"#{vmlist.name}\", \"Status\", \"#{vmlist.summary.overallStatus}\")\n\t\t\t\tdb.hset(\"#{vmlist.name}\", \"Uptime\", \"#{vmlist.summary.quickStats.uptimeSeconds}\")\n\t\t\t\tdb.hset(\"#{vmlist.name}\", \"CPUusage\", \"#{vmlist.summary.quickStats.overallCpuUsage}\")\n\t\t\t\tdb.hset(\"#{vmlist.name}\", \"CPUnum\", \"#{vmlist.summary.config.numCpu}\")\n\t\t\t\tdb.hset(\"#{vmlist.name}\", \"MemUsage\", \"#{vmlist.summary.quickStats.guestMemoryUsage}\")\n\t\t\t\tdb.hset(\"#{vmlist.name}\", \"MemTotal\", \"#{vmlist.summary.config.memorySizeMB}\")\n\t\t\t\tprogressbar.increment\n\t\t\tend\n\t\tend\n\tend\nend",
"def storage_list(mixins = nil)\n storages = Occi::Core::Resources.new\n\n Backends::Ec2::Helpers::AwsConnectHelper.rescue_aws_service(@logger) do\n volumes = @ec2_client.describe_volumes.volumes\n volumes.each do |volume|\n next unless volume\n storages << storage_parse_backend_obj(volume)\n end if volumes\n end\n\n storages\n end",
"def fetch_volume_by_id\n vol = storage_api.find_by_id(volume_id)\n data = vol.body.fetch(\"volume\")\n @name = data.fetch('display_name')\n @volume_type = data.fetch('volume_type')\n @size = data.fetch('size')\n\n # Sometimes the Rackspace API takes time to update,\n # and newly-attached volumes don't report any attachments\n # yet.\n attachments = data.fetch('attachments')\n if attachments.any?\n @device = attachments.first.fetch('device')\n end\n end",
"def volume_mount(local_dir, container_dir)\n local_dir = File.expand_path(local_dir, reference_dir)\n volumes << VolumeMount.new(local_dir, container_dir)\n end",
"def fetch_cluster_data\n env = release_env(last_release(@project))\n env.cluster_deploy_groups.each do |cdg|\n cdg.cluster.client.get_pods(namespace: cdg.namespace, label_selector: \"project_id=#{@project.id}\").each do |pod|\n update_rc_pods(Kubernetes::Api::Pod.new(pod))\n end\n end\n end",
"def mount_kvm_volume(name)\n dev = available_dev\n enable_netblockdev(name, dev)\n vol_grp = lvm_volume_group(\n lvm_partition(dev)\n )\n root = lvm_root(vol_grp)\n lvm_enable(vol_grp) unless lvm_enabled?(root)\n mount(name, root)\n dev\nend",
"def create_lvm_volumes( opts = {} )\n opts = deep_merge_hashes( @aws_default_instance_options, opts )\n unless exist?( opts[ :lvm_volumes ].first[1] )\n create_lvm_volumes!( opts )\n end\n end",
"def find_metadata(*args)\n results = []\n @filesets.each do |volid, fileset|\n results += fileset.find_metadata(*args)\n end\n return results\n end",
"def attach_volumes!(server, volumes_count, size)\n #create a new block storage connection obj\n volume_service = Fog::Volume::OpenStack.new(\n :openstack_api_key => @os_password,\n :openstack_username => @os_username,\n :openstack_auth_url => @os_auth_url,\n :openstack_tenant => @os_tenant,\n )\n base = 'sdd'\n volumes_count.times do |i|\n base = base.next!\n #create a new volume\n vol = volume_service.volumes.create(\n :size => size,\n :display_name => \"#{server.name}-#{i}\",\n :description => \"Volume attached to #{server.name} - managed by ankus\"\n )\n vol.reload\n vol.wait_for { status == 'available' }\n server.attach_volume(vol.id, \"/dev/#{base}\")\n vol.wait_for { status == 'in-use' }\n end\n end",
"def snapshot_devices(devices, prefix, limit = 0, name = \"#{instance_id}\")\n log \"Snapshot limit set to #{limit} (0 means never purge)\"\n ts = DateTime.now.strftime(\"%Y-%m-%d-%H-%M\").to_s\n name = \"#{prefix} \" + name\n volumes = {}\n devices.each do |device|\n volumes[device] = find_volume_for_device(device)\n end\n sn = []\n volumes.each do |device, volume|\n log \"Creating volume snapshot for #{device} on instance #{instance_id}\"\n snapshot = volume.snapshots.new\n snapshot.description = name+\": #{device}\"\n snapshot.save\n sn << snapshot\n snapshot.reload\n\n @compute.tags.create(:resource_id => snapshot.id, :key =>\"device\", :value => device)\n @compute.tags.create(:resource_id => snapshot.id, :key =>\"instance_id\", :value =>instance_id)\n @compute.tags.create(:resource_id => snapshot.id, :key =>\"date\", :value => ts)\n end\n\n # DO NOT need to wait for creating EBS snapshot\n #log \"Waiting for snapshots to complete.\"\n #sn.each do |s|\n # begin\n # sleep(3)\n # s.reload\n # end while s.state == 'nil' || s.state == 'pending'\n #end\n\n if limit != 0\n # populate data structure with updated information\n snapshots = list_snapshots(devices)\n nsnaps = snapshots.keys.length\n if nsnaps-limit > 0\n dates = snapshots.keys.sort\n puts dates.inspect\n extra_snapshots = dates[0..-(limit+1)]\n remaining_snapshots = dates[-limit..-1]\n extra_snapshots.each do |date|\n snapshots[date].each do |snap|\n log \"Destroying #{snap.description} #{snap.id}\"\n snap.destroy\n end\n end\n end\n end\n end",
"def createVolume\n require 'rest_client'\n require 'uri'\n\n if @role.nil? and !current_actor.superadmin\n json_response({ message: \"You don't have permission to view the clusters in this project\" }, :unauthorized)\n return\n end\n\n # Service name in the query\n volumeName = params[\"volume_name\"]\n\n # Env variables for Manager host and port\n serviceManagerHost = Settings.service_manager_host\n serviceManagerPort = Settings.service_manager_port.to_s\n serviceManagerURI = 'http://' + serviceManagerHost + ':' + serviceManagerPort + '/v1/volume'\n\n # Create request for Service Manager\n stack = {\n 'name' => volumeName,\n 'engine-url' => @cluster.endpoint,\n 'ca-cert' => @cluster.ca,\n 'cert' => @cluster.cert,\n 'cert-key' => @cluster.key\n }.to_json\n\n begin\n response = RestClient.post(\n serviceManagerURI,\n stack,\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json'\n )\n puts \"Deploy Response: \" + response\n json_response(response, :created)\n rescue Exception => e\n # If error, respond with it\n puts e\n json_response({message: e}, :unprocessable_entity)\n end\n end",
"def find_volume(name)\n Volume.new pool.lookup_volume_by_name(name), self\n rescue Libvirt::RetrieveError\n nil\n end",
"def get_volume(volume_id)\n get(\"cloud-instances/#{guid}/volumes/#{volume_id}\")\n end",
"def find_issues_for_volume\n issue_ids = []\n relationships.each_statement do |statement|\n if statement.predicate =~ /isVolumeOf/\n issue_ids << statement.object.to_s.gsub(/info:fedora\\//,'')\n end\n end\n issue_ids.map { |v| { ark_id: v } } unless issue_ids.blank?\n end",
"def create_default_volume()\n # Create a default application_volume using the volume attributes from the cookbook\n create_node_volume(:application_volume)\n end",
"def objects\n # array to hold objects being backed up\n objects = []\n result = veeamconfig('job', 'info', '--name', \"#{@resource[:name]}\").lines\n\n # loop through every line of output\n result.each do |line|\n # the Include Disk lines are what we need\n if line.include? 'Include Disk:'\n # tease out the disk/volume being backed up\n object = line.split(': ')[1].strip\n # append the disk/volume to the array\n objects << object\n end\n end\n\n # return the disks/volumes being backed up, sorted properly\n return objects.sort_by(&:downcase)\n end",
"def prompt_volumes(plan_info, provision_type, options={}, api_client=nil, api_params={})\n #puts \"Configure Volumes:\"\n # return [] if plan_info['noDisks']\n\n no_prompt = (options[:no_prompt] || (options[:options] && options[:options][:no_prompt]))\n volumes = []\n plan_size = nil\n if plan_info['maxStorage']\n plan_size = plan_info['maxStorage'].to_i / (1024 * 1024 * 1024)\n end\n root_storage_types = []\n if plan_info['rootStorageTypes']\n plan_info['rootStorageTypes'].sort {|x,y| x['displayOrder'] <=> y['displayOrder'] }.each do |opt|\n if !opt.nil?\n root_storage_types << {'name' => opt['name'], 'value' => opt['id']}\n end\n end\n end\n\n storage_types = []\n if plan_info['storageTypes']\n plan_info['storageTypes'].sort {|x,y| x['displayOrder'] <=> y['displayOrder'] }.each do |opt|\n if !opt.nil?\n storage_types << {'name' => opt['name'], 'value' => opt['id']}\n end\n end\n end\n\n datastore_options = []\n if plan_info['supportsAutoDatastore']\n if plan_info['autoOptions']\n plan_info['autoOptions'].each do |opt|\n if !opt.nil?\n datastore_options << {'name' => opt['name'], 'value' => opt['id']}\n end\n end\n end\n end\n if plan_info['datastores']\n plan_info['datastores'].each do |k, v|\n v.each do |opt|\n if !opt.nil?\n k = 'datastores' if k == 'store'\n k = 'clusters' if k == 'cluster'\n datastore_options << {'name' => \"#{k}: #{opt['name']}\", 'value' => opt['id']}\n end\n end\n end\n end\n # api does not always return datastores, so go get them if needed..\n if plan_info['hasDatastore'] && datastore_options.empty?\n option_results = options_interface.options_for_source('datastores', api_params)\n option_results['data'].each do |it|\n datastore_options << {\"id\" => it[\"value\"] || it[\"id\"], \"name\" => it[\"name\"], \"value\" => it[\"value\"] || it[\"id\"]}\n end\n end\n\n #puts \"Configure Root Volume\"\n\n field_context = \"rootVolume\"\n\n volume_label = options[:root_volume_name] || 'root'\n volume = {\n 'id' => -1,\n 'rootVolume' => true,\n 'name' => volume_label,\n 'size' => plan_size,\n 'sizeId' => nil,\n 'storageType' => nil,\n 'datastoreId' => nil\n }\n if options[:options] && options[:options]['volumes'] && options[:options]['volumes'][0]\n volume = options[:options]['volumes'][0]\n end\n\n if root_storage_types.empty?\n # this means there's no configuration, just send a single root volume to the server\n storage_type_id = nil\n storage_type = nil\n else\n default_storage_type = root_storage_types.find {|t| t['value'].to_s == volume['storageType'].to_s}\n v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'storageType', 'type' => 'select', 'fieldLabel' => 'Root Storage Type', 'selectOptions' => root_storage_types, 'required' => true, 'defaultFirstOption' => true, 'skipSingleOption' => true, 'description' => 'Choose a storage type.', 'defaultValue' => default_storage_type ? default_storage_type['name'] : volume['storageType']}], options[:options])\n storage_type_id = v_prompt[field_context]['storageType']\n storage_type = plan_info['storageTypes'].find {|i| i['id'] == storage_type_id.to_i }\n volume['storageType'] = storage_type_id\n end\n\n # sometimes the user chooses sizeId from a list of size options (AccountPrice) and other times it is free form\n root_custom_size_options = []\n if plan_info['rootCustomSizeOptions'] && plan_info['rootCustomSizeOptions'][storage_type_id.to_s]\n plan_info['rootCustomSizeOptions'][storage_type_id.to_s].each do |opt|\n if !opt.nil?\n root_custom_size_options << {'name' => opt['value'], 'value' => opt['key']}\n end\n end\n end\n\n if plan_info['rootDiskCustomizable'] && storage_type && storage_type['customLabel']\n v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => 'Root Volume Label', 'required' => true, 'description' => 'Enter a volume label.', 'defaultValue' => volume['name']}], options[:options])\n volume['name'] = v_prompt[field_context]['name']\n end\n if plan_info['rootDiskCustomizable'] && storage_type && storage_type['customSize']\n # provision_type['rootDiskSizeKnown'] == false means size cannot be changed\n if provision_type['rootDiskSizeKnown'] == false\n # volume['size'] = plan_size if plan_size.to_i != 0\n else\n if root_custom_size_options.empty?\n v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'size', 'type' => 'number', 'fieldLabel' => 'Root Volume Size (GB)', 'required' => true, 'description' => 'Enter a volume size (GB).', 'defaultValue' => volume['size']}], options[:options])\n volume['size'] = v_prompt[field_context]['size']\n volume['sizeId'] = nil #volume.delete('sizeId')\n else\n v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'sizeId', 'type' => 'select', 'fieldLabel' => 'Root Volume Size', 'selectOptions' => root_custom_size_options, 'required' => true, 'description' => 'Choose a volume size.', 'defaultValue' => volume['sizeId']}], options[:options])\n volume['sizeId'] = v_prompt[field_context]['sizeId']\n volume['size'] = nil #volume.delete('size')\n end\n end\n else\n # might need different logic here ? =o\n #volume['size'] = plan_size\n #volume['sizeId'] = nil #volume.delete('sizeId')\n end\n \n if !datastore_options.empty?\n default_datastore = datastore_options.find {|ds| ds['value'].to_s == volume['datastoreId'].to_s}\n v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'datastoreId', 'type' => 'select', 'fieldLabel' => 'Root Datastore', 'selectOptions' => datastore_options, 'required' => true, 'description' => 'Choose a datastore.', 'defaultValue' => default_datastore ? default_datastore['name'] : volume['datastoreId']}], options[:options])\n volume['datastoreId'] = v_prompt[field_context]['datastoreId']\n end\n\n volumes << volume\n\n if plan_info['addVolumes']\n volume_index = 1\n has_another_volume = (options[:options] && options[:options][\"dataVolume#{volume_index}\"]) || (options[:options] && options[:options]['volumes'] && options[:options]['volumes'][volume_index])\n add_another_volume = has_another_volume || (!no_prompt && Morpheus::Cli::OptionTypes.confirm(\"Add data volume?\", {:default => (options[:defaultAddFirstDataVolume] == true && volume_index == 1)}))\n while add_another_volume do\n #puts \"Configure Data #{volume_index} Volume\"\n\n field_context = \"dataVolume#{volume_index}\"\n\n volume_label = (volume_index == 1 ? 'data' : \"data #{volume_index}\")\n volume = {\n #'id' => -1,\n 'rootVolume' => false,\n 'name' => volume_label,\n 'size' => plan_size,\n 'sizeId' => nil,\n 'storageType' => nil,\n 'datastoreId' => nil\n }\n if options[:options] && options[:options]['volumes'] && options[:options]['volumes'][volume_index]\n volume = options[:options]['volumes'][volume_index]\n end\n\n v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'storageType', 'type' => 'select', 'fieldLabel' => \"Disk #{volume_index} Storage Type\", 'selectOptions' => storage_types, 'required' => true, 'defaultFirstOption' => true, 'skipSingleOption' => true, 'description' => 'Choose a storage type.', 'defaultValue' => volume['storageType']}], options[:options])\n storage_type_id = v_prompt[field_context]['storageType']\n volume['storageType'] = storage_type_id\n storage_type = plan_info['storageTypes'].find {|i| i['id'] == storage_type_id.to_i }\n\n # sometimes the user chooses sizeId from a list of size options (AccountPrice) and other times it is free form\n custom_size_options = []\n if plan_info['customSizeOptions'] && plan_info['customSizeOptions'][storage_type_id.to_s]\n plan_info['customSizeOptions'][storage_type_id.to_s].each do |opt|\n if !opt.nil?\n custom_size_options << {'name' => opt['value'], 'value' => opt['key']}\n end\n end\n end\n\n if plan_info['customizeVolume'] && storage_type['customLabel']\n v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => \"Disk #{volume_index} Volume Label\", 'required' => true, 'description' => 'Enter a volume label.', 'defaultValue' => volume['name']}], options[:options])\n volume['name'] = v_prompt[field_context]['name']\n end\n if plan_info['customizeVolume'] && storage_type['customSize']\n if custom_size_options.empty?\n v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'size', 'type' => 'number', 'fieldLabel' => \"Disk #{volume_index} Volume Size (GB)\", 'required' => true, 'description' => 'Enter a volume size (GB).', 'defaultValue' => volume['size']}], options[:options])\n volume['size'] = v_prompt[field_context]['size']\n volume['sizeId'] = nil #volume.delete('sizeId')\n else\n v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'sizeId', 'type' => 'select', 'fieldLabel' => \"Disk #{volume_index} Volume Size\", 'selectOptions' => custom_size_options, 'required' => true, 'description' => 'Choose a volume size.', 'defaultValue' => volume['sizeId']}], options[:options])\n volume['sizeId'] = v_prompt[field_context]['sizeId']\n volume['size'] = nil #volume.delete('size')\n end\n else\n # might need different logic here ? =o\n volume['size'] = plan_size\n volume['sizeId'] = nil #volume.delete('sizeId')\n end\n if !datastore_options.empty?\n v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'datastoreId', 'type' => 'select', 'fieldLabel' => \"Disk #{volume_index} Datastore\", 'selectOptions' => datastore_options, 'required' => true, 'description' => 'Choose a datastore.', 'defaultValue' => volume['datastoreId']}], options[:options])\n volume['datastoreId'] = v_prompt[field_context]['datastoreId']\n end\n\n volumes << volume\n\n volume_index += 1\n if options[:options] && options[:options]['volumes'] && options[:options]['volumes'][volume_index]\n add_another_volume = true\n elsif plan_info['maxDisk'] && volume_index >= plan_info['maxDisk']\n # todo: should maxDisk check consider the root volume too?\n add_another_volume = false\n else\n has_another_volume = options[:options] && options[:options][\"dataVolume#{volume_index}\"]\n add_another_volume = has_another_volume || (!no_prompt && Morpheus::Cli::OptionTypes.confirm(\"Add another data volume?\", {:default => false}))\n end\n\n end\n\n end\n\n return volumes\n end",
"def volumes_for_account(accountid)\n api_call = {\n :method => \"ListVolumesForAccount\",\n :params => {\n :volumeID => accountid\n }\n }\n answer = query_sf(api_call)\n return answer\n end",
"def vaults\n @mapped_vaults ||= Basecamp3::Vault.all(bucket.id, id)\n end",
"def parse(output)\n volumes = []\n\n output.split(\"\\n\").each do |line|\n\n args = parse_attributes(line)\n\n\n # finally build our object\n volume = Disk.new(args)\n\n\n if block_given?\n yield volume\n else\n volumes << volume\n end\n end\n\n return volumes\n end",
"def prompt_resize_volumes(current_volumes, plan_info, provision_type, options={})\n #puts \"Configure Volumes:\"\n no_prompt = (options[:no_prompt] || (options[:options] && options[:options][:no_prompt]))\n\n current_root_volume = current_volumes[0]\n\n volumes = []\n\n plan_size = nil\n if plan_info['maxStorage']\n plan_size = plan_info['maxStorage'].to_i / (1024 * 1024 * 1024)\n end\n\n root_storage_types = []\n if plan_info['rootStorageTypes']\n plan_info['rootStorageTypes'].each do |opt|\n if !opt.nil?\n root_storage_types << {'name' => opt['name'], 'value' => opt['id']}\n end\n end\n end\n\n storage_types = []\n if plan_info['storageTypes']\n plan_info['storageTypes'].each do |opt|\n if !opt.nil?\n storage_types << {'name' => opt['name'], 'value' => opt['id']}\n end\n end\n end\n\n datastore_options = []\n if plan_info['supportsAutoDatastore']\n if plan_info['autoOptions']\n plan_info['autoOptions'].each do |opt|\n if !opt.nil?\n datastore_options << {'name' => opt['name'], 'value' => opt['id']}\n end\n end\n end\n end\n if plan_info['datastores']\n plan_info['datastores'].each do |k, v|\n v.each do |opt|\n if !opt.nil?\n datastore_options << {'name' => \"#{k}: #{opt['name']}\", 'value' => opt['id']}\n end\n end\n end\n end\n\n #puts \"Configure Root Volume\"\n\n field_context = \"rootVolume\"\n\n if root_storage_types.empty?\n # this means there's no configuration, just send a single root volume to the server\n storage_type_id = nil\n storage_type = nil\n else\n #v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'storageType', 'type' => 'select', 'fieldLabel' => 'Root Storage Type', 'selectOptions' => root_storage_types, 'required' => true, 'defaultFirstOption' => true, 'skipSingleOption' => true, 'description' => 'Choose a storage type.'}], options[:options])\n #storage_type_id = v_prompt[field_context]['storageType']\n storage_type_id = current_root_volume['type'] || current_root_volume['storageType']\n storage_type = plan_info['storageTypes'].find {|i| i['id'] == storage_type_id.to_i }\n end\n\n # sometimes the user chooses sizeId from a list of size options (AccountPrice) and other times it is free form\n root_custom_size_options = []\n if plan_info['rootCustomSizeOptions'] && plan_info['rootCustomSizeOptions'][storage_type_id.to_s]\n plan_info['rootCustomSizeOptions'][storage_type_id.to_s].each do |opt|\n if !opt.nil?\n root_custom_size_options << {'name' => opt['value'], 'value' => opt['key']}\n end\n end\n end\n\n volume = {\n 'id' => current_root_volume['id'],\n 'rootVolume' => true,\n 'name' => current_root_volume['name'],\n 'size' => current_root_volume['size'] > 0 ? current_root_volume['size'] : plan_size,\n 'sizeId' => nil,\n 'storageType' => storage_type_id,\n 'datastoreId' => current_root_volume['datastoreId']\n }\n\n if plan_info['rootDiskCustomizable'] && storage_type && storage_type['customLabel']\n v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => 'Root Volume Label', 'required' => true, 'description' => 'Enter a volume label.', 'defaultValue' => volume['name']}], options[:options])\n volume['name'] = v_prompt[field_context]['name']\n end\n if plan_info['rootDiskCustomizable'] && storage_type && storage_type['customSize']\n # provision_type['rootDiskSizeKnown'] == false means size cannot be changed\n if provision_type['rootDiskSizeKnown'] == false\n # volume['size'] = plan_size if plan_size.to_i != 0\n else\n if root_custom_size_options.empty?\n v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'size', 'type' => 'number', 'fieldLabel' => 'Root Volume Size (GB)', 'required' => true, 'description' => 'Enter a volume size (GB).', 'defaultValue' => volume['size']}], options[:options])\n volume['size'] = v_prompt[field_context]['size']\n volume['sizeId'] = nil #volume.delete('sizeId')\n else\n v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'sizeId', 'type' => 'select', 'fieldLabel' => 'Root Volume Size', 'selectOptions' => root_custom_size_options, 'required' => true, 'description' => 'Choose a volume size.'}], options[:options])\n volume['sizeId'] = v_prompt[field_context]['sizeId']\n volume['size'] = nil #volume.delete('size')\n end\n end\n else\n # might need different logic here ? =o\n # volume['size'] = plan_size\n # volume['sizeId'] = nil #volume.delete('sizeId')\n end\n # if !datastore_options.empty?\n # v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'datastoreId', 'type' => 'select', 'fieldLabel' => 'Root Datastore', 'selectOptions' => datastore_options, 'required' => true, 'description' => 'Choose a datastore.'}], options[:options])\n # volume['datastoreId'] = v_prompt[field_context]['datastoreId']\n # end\n\n volumes << volume\n\n # modify or delete existing data volumes\n (1..(current_volumes.size-1)).each do |volume_index|\n current_volume = current_volumes[volume_index]\n if current_volume\n\n field_context = \"dataVolume#{volume_index}\"\n\n action_options = [{'name' => 'Modify', 'value' => 'modify'}, {'name' => 'Keep', 'value' => 'keep'}, {'name' => 'Delete', 'value' => 'delete'}]\n v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'action', 'type' => 'select', 'fieldLabel' => \"Modify/Keep/Delete volume '#{current_volume['name']}'\", 'selectOptions' => action_options, 'required' => true, 'defaultValue' => 'keep', 'description' => 'Modify, Keep or Delete existing data volume?'}], options[:options])\n volume_action = v_prompt[field_context]['action']\n\n if volume_action == 'delete'\n # deleted volume is just excluded from post params\n next\n elsif volume_action == 'keep'\n volume = {\n 'id' => current_volume['id'].to_i,\n 'rootVolume' => false,\n 'name' => current_volume['name'],\n 'size' => current_volume['size'] > (plan_size || 0) ? current_volume['size'] : plan_size,\n 'sizeId' => nil,\n 'storageType' => (current_volume['type'] || current_volume['storageType']),\n 'datastoreId' => current_volume['datastoreId']\n }\n volumes << volume\n else\n # v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'storageType', 'type' => 'select', 'fieldLabel' => \"Disk #{volume_index} Storage Type\", 'selectOptions' => storage_types, 'required' => true, 'skipSingleOption' => true, 'description' => 'Choose a storage type.'}], options[:options])\n # storage_type_id = v_prompt[field_context]['storageType']\n storage_type_id = current_volume['type'] || current_volume['storageType']\n storage_type = plan_info['storageTypes'].find {|i| i['id'] == storage_type_id.to_i }\n # sometimes the user chooses sizeId from a list of size options (AccountPrice) and other times it is free form\n custom_size_options = []\n if plan_info['customSizeOptions'] && plan_info['customSizeOptions'][storage_type_id.to_s]\n plan_info['customSizeOptions'][storage_type_id.to_s].each do |opt|\n if !opt.nil?\n custom_size_options << {'name' => opt['value'], 'value' => opt['key']}\n end\n end\n end\n\n volume = {\n 'id' => current_volume['id'].to_i,\n 'rootVolume' => false,\n 'name' => current_volume['name'],\n 'size' => current_volume['size'] ? current_volume['size'] : (plan_size || 0),\n 'sizeId' => nil,\n 'storageType' => (current_volume['type'] || current_volume['storageType']),\n 'datastoreId' => current_volume['datastoreId']\n }\n\n if plan_info['customizeVolume'] && storage_type['customLabel']\n v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => \"Disk #{volume_index} Volume Label\", 'required' => true, 'description' => 'Enter a volume label.', 'defaultValue' => volume['name']}], options[:options])\n volume['name'] = v_prompt[field_context]['name']\n end\n if plan_info['customizeVolume'] && storage_type['customSize']\n if custom_size_options.empty?\n v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'size', 'type' => 'number', 'fieldLabel' => \"Disk #{volume_index} Volume Size (GB)\", 'required' => true, 'description' => 'Enter a volume size (GB).', 'defaultValue' => volume['size']}], options[:options])\n volume['size'] = v_prompt[field_context]['size']\n volume['sizeId'] = nil #volume.delete('sizeId')\n else\n v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'sizeId', 'type' => 'select', 'fieldLabel' => \"Disk #{volume_index} Volume Size\", 'selectOptions' => custom_size_options, 'required' => true, 'description' => 'Choose a volume size.'}], options[:options])\n volume['sizeId'] = v_prompt[field_context]['sizeId']\n volume['size'] = nil #volume.delete('size')\n end\n else\n # might need different logic here ? =o\n # volume['size'] = plan_size\n # volume['sizeId'] = nil #volume.delete('sizeId')\n end\n # if !datastore_options.empty?\n # v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'datastoreId', 'type' => 'select', 'fieldLabel' => \"Disk #{volume_index} Datastore\", 'selectOptions' => datastore_options, 'required' => true, 'description' => 'Choose a datastore.'}], options[:options])\n # volume['datastoreId'] = v_prompt[field_context]['datastoreId']\n # end\n\n volumes << volume\n\n end\n\n end\n end\n\n\n if plan_info['addVolumes']\n volume_index = current_volumes.size\n has_another_volume = options[:options] && options[:options][\"dataVolume#{volume_index}\"]\n add_another_volume = has_another_volume || (!no_prompt && Morpheus::Cli::OptionTypes.confirm(\"Add data volume?\", {:default => false}))\n while add_another_volume do\n #puts \"Configure Data #{volume_index} Volume\"\n\n current_root_volume_type = current_root_volume['type']\n storage_type_match = storage_types.find {|type| type['value'] == current_root_volume_type}\n default_storage_type = storage_type_match ? current_root_volume_type : storage_types[0]['value']\n field_context = \"dataVolume#{volume_index}\"\n v_prompt = Morpheus::Cli::OptionTypes.prompt([{'defaultValue' => default_storage_type, 'fieldContext' => field_context, 'fieldName' => 'storageType', 'type' => 'select', 'fieldLabel' => \"Disk #{volume_index} Storage Type\", 'selectOptions' => storage_types, 'required' => true, 'defaultFirstOption' => true, 'skipSingleOption' => true, 'description' => 'Choose a storage type.'}], options[:options])\n storage_type_id = v_prompt[field_context]['storageType']\n storage_type = plan_info['storageTypes'].find {|i| i['id'] == storage_type_id.to_i }\n\n # sometimes the user chooses sizeId from a list of size options (AccountPrice) and other times it is free form\n custom_size_options = []\n if plan_info['customSizeOptions'] && plan_info['customSizeOptions'][storage_type_id.to_s]\n plan_info['customSizeOptions'][storage_type_id.to_s].each do |opt|\n if !opt.nil?\n custom_size_options << {'name' => opt['value'], 'value' => opt['key']}\n end\n end\n end\n\n volume_label = (volume_index == 1 ? 'data' : \"data #{volume_index}\")\n volume = {\n 'id' => -1,\n 'rootVolume' => false,\n 'name' => volume_label,\n 'size' => plan_size,\n 'sizeId' => nil,\n 'storageType' => storage_type_id,\n 'datastoreId' => nil\n }\n\n if plan_info['customizeVolume'] && storage_type['customLabel']\n v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => \"Disk #{volume_index} Volume Label\", 'required' => true, 'description' => 'Enter a volume label.', 'defaultValue' => volume_label}], options[:options])\n volume['name'] = v_prompt[field_context]['name']\n end\n if plan_info['customizeVolume'] && storage_type['customSize']\n if custom_size_options.empty?\n v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'size', 'type' => 'number', 'fieldLabel' => \"Disk #{volume_index} Volume Size (GB)\", 'required' => true, 'description' => 'Enter a volume size (GB).', 'defaultValue' => plan_size}], options[:options])\n volume['size'] = v_prompt[field_context]['size']\n volume['sizeId'] = nil #volume.delete('sizeId')\n else\n v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'sizeId', 'type' => 'select', 'fieldLabel' => \"Disk #{volume_index} Volume Size\", 'selectOptions' => custom_size_options, 'required' => true, 'description' => 'Choose a volume size.'}], options[:options])\n volume['sizeId'] = v_prompt[field_context]['sizeId']\n volume['size'] = nil #volume.delete('size')\n end\n else\n # might need different logic here ? =o\n # volume['size'] = plan_size\n # volume['sizeId'] = nil #volume.delete('sizeId')\n end\n \n if datastore_options.empty? && storage_type['hasDatastore'] != false\n begin\n datastore_res = datastores_interface.list({'poolId' => current_root_volume['resourcePoolId'], 'resourcePoolId' => current_root_volume['resourcePoolId'], 'zoneId' => options['zoneId'], 'siteId' => options['siteId']})['datastores']\n datastore_res.each do |opt|\n datastore_options << {'name' => opt['name'], 'value' => opt['id']}\n end\n rescue\n datastore_options = []\n end\n end\n if !datastore_options.empty?\n v_prompt = Morpheus::Cli::OptionTypes.prompt([{'defaultValue' => current_root_volume['datastoreId'],'fieldContext' => field_context, 'fieldName' => 'datastoreId', 'type' => 'select', 'fieldLabel' => \"Disk #{volume_index} Datastore\", 'selectOptions' => datastore_options, 'required' => true, 'description' => 'Choose a datastore.'}], options[:options])\n volume['datastoreId'] = v_prompt[field_context]['datastoreId']\n end\n\n volumes << volume\n\n # todo: should maxDisk check consider the root volume too?\n if plan_info['maxDisk'] && volume_index >= plan_info['maxDisk']\n add_another_volume = false\n else\n volume_index += 1\n has_another_volume = options[:options] && options[:options][\"dataVolume#{volume_index}\"]\n add_another_volume = has_another_volume || (!no_prompt && Morpheus::Cli::OptionTypes.confirm(\"Add another data volume?\"))\n end\n\n end\n\n end\n\n return volumes\n end",
"def get_volume_id(sys_id,volume_name)\n response = request(:get, \"/devmgr/v2/storage-systems/#{sys_id}/volumes\")\n status(response, 200, 'Failed to get Volumes')\n volumes = JSON.parse(response.body)\n volumes.each do |vm|\n \t return vm['id'] if vm['name'] == volume_name\n \tend\n response = request(:get, \"/devmgr/v2/storage-systems/#{sys_id}/thin-volumes\")\n status(response, 200, 'Failed to get thin Volumes')\n volumes = JSON.parse(response.body)\n volumes.each do |vm|\n return vm['id'] if vm['name'] == volume_name\n end\n \tfalse\n end",
"def flush_when_ready\n flushing :ensure => :absent do\n eip = aws_item.elastic_ip\n\n volumes = aws_item.attachments.map do |mnt, att|\n att.delete(:force => true)\n att.volume\n end\n\n aws_item.delete\n\n # Avoid squating on current resource name while terminated\n aws_item.tags['Name'] = @property_hash[:name] + \"-terminated\"\n\n wait_until {aws_item.status == :terminated }\n\n volumes.each do |vol|\n if vol.state == :deleting or vol.state == :deleted\n wait_until { vol.state == :deleted }\n else\n wait_until { vol.state == :available || vol.state == :error }\n vol.delete\n end\n end\n\n eip.delete\n return # don't do any further flushing\n end\n\n flushing :ensure => :present do\n\n instance_config = {\n :image_id => resource[:image_id],\n :instance_type => resource[:instance_type],\n :subnet => lookup(:aws_subnet, resource[:subnet]).aws_item,\n :key_name => resource[:key_name],\n :associate_public_ip_address => resource[:associate_public_ip_address],\n :user_data => resource[:user_data],\n }\n if resource[:iam_role]\n profile = iam.client.get_instance_profile(\n :instance_profile_name => resource[:iam_role]\n )\n instance_config[:iam_instance_profile] = profile[:instance_profile][:arn]\n end\n\n if block_devices = resource[:block_device_mappings]\n block_devices.each_with_index do |dev, i|\n\n if dev['ebs'] and dev['ebs']['volume_size']\n # Fun fact: puppet resources aren't aware of ints\n dev['ebs']['volume_size'] = dev['ebs']['volume_size'].to_i\n end\n # Just auto-name, we can't actually get this name back and it pretty much\n # has to follow this pattern anyway\n dev['virtual_name'] = \"ephemeral#{i}\"\n end\n instance_config[:block_device_mappings] = block_devices\n end\n\n\n instance = collection.create(instance_config)\n\n # tag devices\n instance.block_devices.each do |dev|\n if dev[:ebs] and dev[:ebs][:volume_id]\n name = dev[:device_name].sub(/^\\/dev\\//, '')\n ec2.volumes[dev[:ebs][:volume_id]].add_tag('Name', :value => \"#{resource[:name]}-#{name}\")\n end\n end\n\n also_flush(:security_groups, :elastic_ip)\n\n instance # this becomes aws_item\n end\n\n flushing :security_groups do |sgs|\n aws_item.client.modify_instance_attribute(\n :instance_id => aws_item.id,\n :groups => sgs.collect {|sg| lookup(:aws_security_group, sg).aws_item.id }\n )\n end\n\n flushing :elastic_ip => true do\n eip = ec2.elastic_ips.create(:vpc => true)\n wait_until { eip.exists? }\n aws_item.associate_elastic_ip(eip)\n end\n\n flushing :elastic_ip => false do\n eip = aws_item.elastic_ip\n eip.dissasociate\n eip.release\n end\n\n super # taggable again\n end",
"def manage_cluster\n @nodes = Node.find(:all)\n end",
"def get_local_storage\n storage = {:hostname => Socket.gethostname, :mounts => [], :vgs => []}\n\n LVM::LVM.new({:command => \"/usr/bin/sudo /sbin/lvm\"}) do |lvm|\n lvm.volume_groups.each do |vg|\n vg.logical_volumes.each do |lv|\n mnt = get_mount(lv.name)\n fs = {:mount => mnt.mount_point, :fs => mnt.name, :lv => lv.name, :vg => vg.name}\n storage[:mounts] << fs\n end\n\n volg = {:vg => vg.name, :pvs => []}\n vg.physical_volumes.each do |pv|\n volg[:pvs] << {:pv => pv.name}\n end\n storage[:vgs] << volg\n end\n end\n storage\n end",
"def GetMountPoints\n mountPoints = {}\n swapPoints = []\n tg = GetTargetMap()\n Builtins.foreach(tg) do |targetdevice, target|\n partitions = Ops.get_list(target, \"partitions\", [])\n Builtins.foreach(partitions) do |partition|\n partitionName = Ops.get_string(partition, \"device\", \"\")\n mountPoint = Ops.get_string(partition, \"mount\", \"\")\n fsid = Ops.get_integer(partition, \"fsid\", 0)\n if mountPoint != \"\"\n raid_type = \"\"\n if Ops.get_symbol(partition, \"type\", :undefined) == :sw_raid\n raid_type = Ops.get_string(partition, \"raid_type\", \"\")\n end\n # partition has a mount point\n if mountPoint == \"swap\"\n swapPoints = Builtins.add(\n swapPoints,\n [partitionName, fsid, targetdevice, raid_type]\n )\n else\n mountPoints = Builtins.add(\n mountPoints,\n mountPoint,\n [partitionName, fsid, targetdevice, raid_type]\n )\n end\n end\n end\n end\n if Ops.greater_than(Builtins.size(swapPoints), 0)\n mountPoints = Builtins.add(mountPoints, \"swap\", swapPoints)\n end\n if !Stage.initial\n cm = Builtins.filter(Partitions.CurMounted) do |e|\n Builtins.search(Ops.get_string(e, \"spec\", \"\"), \"/dev/\") == 0\n end\n Builtins.foreach(cm) do |e|\n if !Builtins.haskey(mountPoints, Ops.get_string(e, \"file\", \"\"))\n p = GetPartition(tg, Ops.get_string(e, \"spec\", \"\"))\n if Ops.greater_than(Builtins.size(p), 0)\n raid_type = \"\"\n if Ops.get_symbol(p, \"type\", :undefined) == :sw_raid\n raid_type = Ops.get_string(p, \"raid_type\", \"\")\n end\n d = GetDiskPartition(Ops.get_string(e, \"spec\", \"\"))\n Ops.set(\n mountPoints,\n Ops.get_string(e, \"file\", \"\"),\n [\n Ops.get_string(p, \"device\", \"\"),\n Ops.get_integer(p, \"fsid\", 0),\n Ops.get_string(d, \"disk\", \"\"),\n raid_type\n ]\n )\n end\n end\n end\n end\n Builtins.y2milestone(\"ret %1\", mountPoints)\n deep_copy(mountPoints)\n end",
"def get_connectable_volume_templates(attributes = {})\n OneviewSDK::Resource.find_by(@client, attributes, BASE_URI + '/connectable-volume-templates')\n end",
"def find_compute_resources(folder)\n retval = []\n children = folder.children.find_all\n children.each do |child|\n if child.class == RbVmomi::VIM::ComputeResource\n retval << child\n elsif child.class == RbVmomi::VIM::ClusterComputeResource\n child.host.each do |h|\n retval << h\n end\n elsif child.class == RbVmomi::VIM::Folder\n retval.concat(find_computer_resources(child))\n end\n end\n retval\nend",
"def add_nfs_datastore\n vm_host = find_vm_host\n hds = vm_host.configManager.datastoreSystem\n nfsdatastoreconfig = {:remoteHost => get_host_management_ip,\n :remotePath => resource[:nfs][\"remote_path\"],\n :localPath => \"_nfs_asm_#{vm.name}\",\n :accessMode => \"readOnly\"\n }\n\n nfsds = get_nfs_datastore(hds)\n #checks if nfsdatastore already exists\n if nfsds\n Puppet.notice (\"nfs is already mounted as %s\" % nfsds.info.name )\n else\n nfsds = hds.CreateNasDatastore(:spec => VIM.HostNasVolumeSpec(nfsdatastoreconfig))\n Puppet.notice (\"added nfs datastore %s and mounted\" % nfsds.info.name )\n end\n\n nfsds\n end",
"def volumes_for_account(accountid)\n api_call = {\n :method => \"ListVolumesForAccount\",\n :params => {\n :accountID => accountid\n }\n }\n answer = query_sf(api_call)\n return answer\n end",
"def create_volume(volume_name, config:, **kwargs)\n object = { name: volume_name }.merge(config).merge(kwargs)\n log.info \"Creating volume: #{object}\"\n volumes << object\n end",
"def get_connectable_volume_templates(attributes = {})\n OneviewSDK::Resource.find_by(@client, attributes, BASE_URI + '/connectable-volume-templates')\n end",
"def compute_deltas \n req_disks = @new_resource.disks\n keyed_req = {} # for easy lookup, make a map of the requested disks \n cur = @ring_test\n name = @new_resource.name\n @to_add = []\n @to_rem = []\n \n \n ## figure out which disks need adding\n req_disks.each {|disk| \n key = RingInfo.dev_key disk[:ip],disk[:port],disk[:dev_name]\n @to_add << disk unless cur and cur.devices[key] # add unless present\n keyed_req[key] = disk\n } \n \n ### figure out which disks need removing\n cur.devices.each {|key, d|\n @to_rem << d unless keyed_req[key] # remove unless still requested\n } if cur\n \n Chef::Log.info(\"disks, to add #{@to_add.length} , to remove: #{@to_rem.length}\" ) \n Chef::Log.debug(\"disks, to add #{@to_add.join(\";\")} , to remove: #{@to_rem.join(\";\")}\" )\n \nend",
"def mounts\r\n @mounts.list\r\n end",
"def volumes_list(options = {})\n state = options.fetch(:state, 'active')\n startid = options.fetch(:startid, 0)\n limit = options.fetch(:limit, 1000)\n accounts = options.fetch(:accountid, nil)\n name = options.fetch(:name, nil)\n \n if name\n api_call = {\n :method => \"ListVolumes\",\n :params => {\n :VolumeName => name,\n :limit => 1\n }\n }\n elsif accounts\n accounts = [ accounts ] if accounts.class == String || Integer\n api_call = {\n :method => \"ListVolumes\",\n :params => {\n :accounts => accounts,\n :limit => limit\n }\n }\n else\n api_call = {\n :method => \"ListVolumes\",\n :params => {\n :VolumeStatus => state,\n :startVolumeID => startid,\n :limit => limit\n }\n }\n end\n\n answer = query_sf(api_call)\n return answer[\"volumes\"]\n end",
"def add_tmp_volume(volume, host_spec = {:host_name => 'localhost'})\n @tmp_volumes_by_hosts[host_spec[:host_name]] << volume\n @hosts_specs[host_spec[:host_name]] ||= host_spec.to_h\n end",
"def merge_planned_volume_mappings(last_mappings, current_planned_volumes)\n results = []\n vm = RightScale::Platform.volume_manager\n\n # merge latest mappings with last mappings, if any.\n current_planned_volumes.each do |planned_volume|\n raise VolumeManagement::InvalidResponse.new(\"Reponse for volume mapping was invalid: #{mapping.inspect}\") unless planned_volume.is_valid?\n if mount_point = planned_volume.mount_points.find { |mount_point| false == vm.is_attachable_volume_path?(mount_point) }\n raise VolumeManagement::UnsupportedMountPoint.new(\"Cannot mount a volume using \\\"#{mount_point}\\\".\")\n end\n\n mapping = {:volume_id => planned_volume.volume_id,\n :device_name => planned_volume.device_name,\n :volume_status => planned_volume.volume_status,\n :mount_points => planned_volume.mount_points.dup}\n if last_mapping = last_mappings.find { |last_mapping| last_mapping[:volume_id] == mapping[:volume_id] }\n # if device name or mount point(s) have changed then we must start\n # over (we can't prevent the user from doing this).\n if last_mapping[:device_name] != mapping[:device_name] || last_mapping[:mount_points] != mapping[:mount_points]\n last_mapping[:device_name] = mapping[:device_name]\n last_mapping[:mount_points] = mapping[:mount_points].dup\n last_mapping[:management_status] = nil\n end\n last_mapping[:volume_status] = mapping[:volume_status]\n mapping = last_mapping\n end\n results << mapping\n end\n\n # preserve any last mappings which do not appear in current mappings by\n # assuming that they are 'detached' to support a limitation of the initial\n # query implementation.\n last_mappings.each do |last_mapping|\n mapping = results.find { |mapping| mapping[:volume_id] == last_mapping[:volume_id] }\n unless mapping\n last_mapping[:volume_status] = 'detached'\n results << last_mapping\n end\n end\n\n return results\n end",
"def compute_deltas\n req_disks = @new_resource.disks\n keyed_req = {} # for easy lookup, make a map of the requested disks\n cur = @ring_test\n name = @new_resource.name\n @to_add = []\n @to_rem = []\n\n ## figure out which disks need adding\n req_disks.each {|disk|\n key = RingInfo.dev_key disk[:ip],disk[:port],disk[:dev_name]\n @to_add << disk unless cur and cur.devices[key] # add unless present\n keyed_req[key] = disk\n }\n\n ### figure out which disks need removing\n cur.devices.each {|key, d|\n @to_rem << d unless keyed_req[key] # remove unless still requested\n } if cur\n\n Chef::Log.info(\"disks, to add #{@to_add.length} , to remove: #{@to_rem.length}\")\n Chef::Log.debug(\"disks, to add #{@to_add.join(\";\")} , to remove: #{@to_rem.join(\";\")}\")\n\nend",
"def virtual_folders\n entries = @course.materials_virtual_entries\n entries.each { |entry|\n entry.files = entry.files.select { |file|\n file.file.is_public && (can?(:manage, file.parent) ||\n (\n file.parent.can_start?(curr_user_course) && # User has satisfied achievements\n file.parent.published? && # Staff has published\n can?(:read, file.parent) # Permissions allowed\n ))\n }\n }\n end",
"def patch_containers(containers)\n (containers || Array.new).each do |container|\n if container[\"image\"] =~ /.*velum.*/\n container[\"image\"] = \"sles12/velum:development\"\n container[\"volumeMounts\"] ||= Array.new\n container[\"volumeMounts\"] << {\n \"mountPath\" => \"/srv/velum\",\n \"name\" => \"velum-devel\"\n }\n container[\"env\"] ||= Array.new\n container[\"env\"].each do |env|\n env[\"value\"] = \"development\" if env[\"name\"] == \"RAILS_ENV\"\n end\n\n # Ensure the velum_production db is used, this is what the\n # salt mysql returner is configured to use\n container[\"env\"] << {\n \"name\" => \"VELUM_DB_NAME\",\n \"value\" => \"velum_production\"\n }\n end\n end\nend",
"def backupAllVolumes(profile,region,daystokeep,name,json,tags)\n parsed = JSON.parse(json)\n parsed[\"Volumes\"].each do |volume|\n backupVolume(profile,region,volume[\"VolumeId\"],daystokeep,name,tags)\n end\nend"
] |
[
"0.6234512",
"0.61205035",
"0.59852165",
"0.5910362",
"0.58662003",
"0.58459437",
"0.5731675",
"0.57041305",
"0.5700364",
"0.5600427",
"0.5520195",
"0.5516698",
"0.5514974",
"0.54641396",
"0.54414856",
"0.544014",
"0.5434479",
"0.54320407",
"0.5425922",
"0.5424895",
"0.5413794",
"0.53796154",
"0.5369367",
"0.5349345",
"0.5346158",
"0.5338218",
"0.5338218",
"0.53339833",
"0.5322428",
"0.52895147",
"0.5282793",
"0.52618545",
"0.5213723",
"0.5211398",
"0.51764274",
"0.5167963",
"0.5163051",
"0.5160789",
"0.5139679",
"0.5114885",
"0.5109735",
"0.509089",
"0.5087311",
"0.5080767",
"0.50807226",
"0.5074874",
"0.5051303",
"0.50400966",
"0.5032365",
"0.5024631",
"0.5024378",
"0.50211793",
"0.50193626",
"0.501142",
"0.5003733",
"0.49983236",
"0.4986671",
"0.49744564",
"0.4962013",
"0.4959179",
"0.4926311",
"0.49193984",
"0.4907958",
"0.4903051",
"0.48668152",
"0.48634276",
"0.48265257",
"0.48193032",
"0.4803004",
"0.48018637",
"0.47969744",
"0.4794573",
"0.47854888",
"0.47792313",
"0.4779129",
"0.47780547",
"0.47769305",
"0.477388",
"0.4771024",
"0.47704107",
"0.47491273",
"0.47479007",
"0.47382465",
"0.47376165",
"0.4734033",
"0.47329065",
"0.47215667",
"0.47212717",
"0.4718305",
"0.4712821",
"0.47064617",
"0.4701314",
"0.46982428",
"0.46927488",
"0.46850646",
"0.46756926",
"0.4668977",
"0.46655867",
"0.4659751",
"0.46589682"
] |
0.73872954
|
0
|
Recursively converts CamelCase and camelBack JSONstyle hash keys to Rubyish snake_case, suitable for use during instantiation of Ruby model attributes.
|
def snakecase_keys(value)
case value
when(Array)
value.map { |v| snakecase_keys(v) }
when(::Hash)
snake_hash(value)
else
value
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def deep_camelize_keys!(first_letter = :upper)\n deep_transform_keys! { |key| key.to_s.camelize(first_letter) rescue key }\n end",
"def deep_camelize_keys\n deep_transform_keys { |key| key.to_s.camelize(:lower) }\n end",
"def keys_to_snake_case(hash)\n hash.transform_keys do |key|\n key.gsub(%r{([A-Z]+)([A-Z][a-z])}, '\\1_\\2')\n .gsub(%r{([a-z\\d])([A-Z])}, '\\1_\\2')\n .downcase\n .to_sym\n end\n end",
"def downcase_keys(json)\n json.gsub(/\"\\w+\":/) { |m| m.downcase }\n end",
"def snake_case_hash_keys(object)\n snake_case_proc = proc { |key| snake_case(key) }\n apply_key_mutator(object, snake_case_proc)\n end",
"def camelize_keys!(first_letter = :upper)\n transform_keys! { |key| key.to_s.camelize(first_letter) rescue key }\n end",
"def recursively_normalize_keys\n recursively_transform_keys { |key| key.downcase.to_sym rescue key }\n end",
"def rubyize_keys\n transform_keys do |key|\n key\n .to_s\n .gsub(/([A-Z]+)([A-Z][a-z])/, '\\1_\\2')\n .gsub(/([a-z\\d])([A-Z])/, '\\1_\\2')\n .downcase\n .to_sym\n end\n end",
"def keys_to_camelcase(hash)\n hash.transform_keys do |key|\n key.to_s\n .gsub(%r{(?:_+)([a-z])}) { Regexp.last_match(1).upcase }\n .gsub(%r{(\\A|\\s)([A-Z])}) { Regexp.last_match(1) + Regexp.last_match(2).downcase }\n .to_sym\n end\n end",
"def normalize_keys\n transform_keys { |key| key.downcase.to_sym rescue key }\n end",
"def make_camelcase_keys\n json_data.mappable!\n end",
"def pascal_case_hash_keys(object)\n pascal_case_proc = proc { |key| pascal_case(key) }\n apply_key_mutator(object, pascal_case_proc)\n end",
"def auto_camelize(data)\n if Cody.settings[:auto_camelize]\n CfnCamelizer.transform(data)\n else\n data.deep_stringify_keys!\n end\n end",
"def recursively_capitalize_key\n recursively_transform_keys { |key| key.to_s.capitalize rescue key }\n end",
"def camelize_key(key, first_upper: true)\n case key\n when Symbol\n Surrealist::StringUtils.camelize(key.to_s, first_upper: first_upper).to_sym\n when String\n Surrealist::StringUtils.camelize(key, first_upper: first_upper)\n else\n key\n end\n end",
"def camelize(first_letter = :lower)\n hash = {}\n self.each do |k,v|\n symbol = k.is_a?(Symbol)\n new_key = k.to_s.camelize(first_letter)\n hash[symbol ? new_key.to_sym : new_key] = v.is_a?(Hash) ? v.camelize(first_letter) : v\n end\n hash\n end",
"def camelize_key(key, first_upper = true)\n if key.is_a? Symbol\n camelize(key.to_s, first_upper).to_sym\n elsif key.is_a? String\n camelize(key, first_upper)\n else\n key\n end\n end",
"def camelize_key(key, first_upper = true)\n if key.is_a? Symbol\n camelize(key.to_s, first_upper).to_sym\n elsif key.is_a? String\n camelize(key, first_upper)\n else\n key\n end\n end",
"def downcase_keys\n end",
"def to_snake_case\n gsub(/\\W/, '_')\n .gsub(/([A-Z]+)([A-Z][a-z])/, '\\1_\\2')\n .gsub(/([a-z])([A-Z])/, '\\1_\\2')\n .downcase\n .gsub(/_+/, '_')\n end",
"def camel_lower(value)\n case value\n when Hash then value.deep_transform_keys! { |key| camel_lower(key) }\n when Symbol then camel_lower(value.to_s).to_sym\n when String then StringSupport.camel_lower(value)\n else value\n end\n end",
"def capitalize_keys\n transform_keys { |key| key.to_s.capitalize rescue key }\n end",
"def camelize(properties)\n if ENV['UFO_CAMELIZE'] == '0' || settings[:auto_camelize] == false # provide a way to quickly test full camelize disable\n return properties.deep_stringify_keys\n end\n\n # transform keys: camelize\n properties.deep_stringify_keys.deep_transform_keys do |key|\n if key == key.upcase # trying to generalize special rule for dns.TTL\n key # leave key alone if key is already in all upcase\n else\n key.camelize\n end\n end\n end",
"def to_snake_case\n gsub(/::/, '/')\n .gsub(/([A-Z]+)([A-Z][a-z])/, '\\1_\\2')\n .gsub(/([a-z\\d])([A-Z])/, '\\1_\\2')\n .tr('-', '_')\n .downcase\n end",
"def snake_case\n return downcase if match(/\\A[A-Z]+\\z/)\n gsub(/([A-Z]+)([A-Z][a-z])/, '\\1_\\2').\n gsub(/([a-z])([A-Z])/, '\\1_\\2').\n downcase\n end",
"def downcase_keys_recursively!(object)\n if self.class === object\n object.downcase_keys!\n elsif ::Array === object\n object.each do |i|\n downcase_keys_recursively!(i)\n end\n object\n elsif object.respond_to?(:downcase_keys!)\n object.downcase_keys!\n else\n object\n end\n end",
"def camel_to_snake_case input\n input = input.to_s.dup\n\n # handle camel case like FooBar => Foo_Bar\n while input.gsub!(/([a-z]+)([A-Z])(\\w+)/) { $1 + '_' + $2 + $3 }\n end\n\n # handle abbreviations like XMLParser => XML_Parser\n while input.gsub!(/([A-Z]+)([A-Z])([a-z]+)/) { $1 + '_' + $2 + $3 }\n end\n\n input\n end",
"def flatten_keys(hash)\n hash.transform_keys(&:downcase).transform_keys(&:to_sym)\n end",
"def downcase_keys\n dup.downcase_keys!\n end",
"def upcase_keys!\n replace(upcase_keys)\n end",
"def camel_lower(value)\n case value\n when Array then value.map { |item| camel_lower(item) }\n when Hash then value.deep_transform_keys! { |key| camel_lower(key) }\n when Symbol then camel_lower(value.to_s).to_sym\n when String then value.underscore.camelize(:lower)\n else value\n end\n end",
"def hash_with_capitalised_keys(hash_in)\n hash_out = {}\n for key in hash_in.keys\n hash_out[key.to_s.capitalize] = hash_in[key]\n end\n return hash_out\n end",
"def snake_case\n gsub(/([A-Z]+)([A-Z][a-z])/, '\\1_\\2')\n .gsub(/([a-z\\d])([A-Z])/, '\\1_\\2')\n .tr('-', '_')\n .downcase\n end",
"def downcase_keys!\n replace(downcase_keys)\n end",
"def snake_case(object)\n # Implementation copied from: https://github.com/rubyworks/facets/blob/master/lib/core/facets/string/snakecase.rb\n # gsub(/::/, '/').\n should_symbolize = object.is_a?(Symbol)\n raise \"snake_case method only handles strings and symbols, passed a #{object.class}: #{object}\" unless should_symbolize || object.is_a?(String)\n\n text = object.to_s\n .gsub(/([A-Z]+)([A-Z][a-z])/, '\\1_\\2')\n .gsub(/([a-z\\d])([A-Z])/, '\\1_\\2')\n .tr('-', '_')\n .gsub(/\\s/, '_')\n .gsub(/__+/, '_')\n .downcase\n should_symbolize ? text.to_sym : text\n end",
"def camel_case_to_snake_case(camel_case)\n camel_case.to_s.gsub(/([a-z])([A-Z])/, '\\1_\\2').gsub(/([A-Z])([A-Z])([a-z])/, '\\1_\\2\\3').downcase\n end",
"def snake_case\n self.gsub(/([a-z])([A-Z])/) {|s| \"#{s[0]}_#{s[1]}\"}.gsub(/([A-Z])([A-Z][a-z])/) {|s| \"#{s[0]}_#{s[1..2]}\"}.downcase\n end",
"def snakecase\n str = dup\n str.gsub! /::/, '/'\n str.gsub! /([A-Z]+)([A-Z][a-z])/, '\\1_\\2'\n str.gsub! /([a-z\\d])([A-Z])/, '\\1_\\2'\n str.tr! \".\", \"_\"\n str.tr! \"-\", \"_\"\n str.downcase!\n str\n end",
"def camelize_keys(hash)\n return unless hash.is_a?(Hash)\n other = {}\n hash.keys.each do |k|\n key = k.to_s.camelize(:lower).to_sym\n other[key] = hash[k]\n end\n other\n end",
"def transform_param_keys_casing\n params.transform_keys!(&:underscore)\n end",
"def to_snake_case(s)\n s.to_s.split(/(?=[A-Z])/).join(\"_\").downcase\nend",
"def camelize_and_normalize_name(snake_cased_name)\n result = Client.camelize_name(snake_cased_name.to_s)\n PARAM_NORMALIZATION.each {|k, v| result.gsub!(/#{k}/, v) }\n result\n end",
"def camelize_keys(options)\n Inflector.process_keys(options) { |k| Inflector.camelize(k.to_s, false) }\n end",
"def deep_underscore_keys\n deep_transform_keys { |key| key.to_s.underscore }\n end",
"def to_snake_case(str)\n str.chars.map { |e| e == e.upcase ? \"_#{e.downcase}\" : e }.join\nend",
"def normalize_keys(hash)\n hash.inject(HashWithIndifferentAccess.new) do |new_hash, (key, value)|\n new_hash[key.parameterize(separator: \"_\")] = value\n new_hash\n end\n end",
"def to_attributes\n to_hash(downcase: true)\n end",
"def to_attributes\n to_hash(downcase: true)\n end",
"def to_attributes\n to_hash(downcase: true)\n end",
"def rubyify(entity)\n entity.map do |key, value|\n [key.to_s.gsub(/([A-Z])/) { '_' + $1.downcase }, value]\n end.to_h\n end",
"def normalize_abbreviation_key(key); end",
"def normalize(hash)\n result = {}\n hash.each do |key, value|\n result[key.to_s.upcase] = normalize_value(value)\n end\n result\n end",
"def normalized_key key\n key.downcase.parameterize.underscore.to_sym\n end",
"def shallow_snakeize_hash(value)\n return underscore(value) if value.is_a?(String)\n return value unless value.is_a?(Hash)\n\n value.reduce({}) do |hash, (k, v)|\n hash.tap do |h|\n h[underscore(k)] = v\n end\n end\n end",
"def pascalcase_to_snakecase(word)\n\tword.gsub(/\\B([A-Z])(?=[a-z0-9])|([a-z0-9])([A-Z])/, '\\2_\\+').downcase\nend",
"def snake_case(preserve_prefixed_underscores: true)\n LuckyCase.snake_case self, preserve_prefixed_underscores: preserve_prefixed_underscores\n end",
"def snake_case(str)\n str.gsub(/::/, '/').\n gsub(/([A-Z]+)([A-Z][a-z])/, '\\1_\\2').\n gsub(/([a-z\\d])([A-Z])/, '\\1_\\2').\n tr('-', '_').\n downcase\n end",
"def lower_camelcase\n str = dup\n str.gsub!(/\\/(.?)/) { \"::#{$1.upcase}\" }\n str.gsub!(/(?:_+|-+)([a-z])/) { $1.upcase }\n str.gsub!(/(\\A|\\s)([A-Z])/) { $1 + $2.downcase }\n str\n end",
"def snake_case_params!(val = params)\n case val\n when Array\n val.map { |v| deep_snake_case_params! v }\n when Hash\n val.keys.each do |k, v = val[k]|\n val.delete k\n val[k.underscore] = snake_case_params!(v)\n end\n val\n else\n val\n end\n end",
"def camel_to_snake(camel_string)\n camel_string.gsub(/[[:lower:]][[:upper:]]/) { |x| x.chars.join('_').downcase }\nend",
"def snakify\n return downcase if match(/\\A[A-Z]+\\z/)\n gsub(/([A-Z]+)([A-Z][a-z])/, '\\1_\\2').\n gsub(/([a-z])([A-Z])/, '\\1_\\2').\n downcase\n end",
"def deep_symbolize_keys!\n deep_transform_keys!{ |key| key.to_sym rescue key }\n end",
"def normalize\n inject({}) do |hash, kv|\n k, v = kv\n v = v.is_a?(Array) ? v.join(',') : v.to_s\n hash[k.to_s.split('_').map {|w| w[0, 1] = w[0, 1].upcase; w }.join] = v\n hash\n end\n end",
"def snake_case(str); end",
"def select_upcase_keys(hash)\n res_hash = {}\n hash.each{|k,v| res_hash[k] = v if k.upcase == k}\n res_hash\nend",
"def snake_to_camel(snake_string)\n string = snake_string.gsub(/(_[a-z])/) {|match| match[1].upcase}\n string\nend",
"def transform_params(params)\n case @case\n when 'snake', 'as_is'\n params\n when 'camel'\n snakecase_keys(params)\n else\n raise Blacksheep::Error, \"unknown_case #{@case}\"\n end\n end",
"def camelize(first_letter_in_uppercase=true)\n word = self.dup\n if first_letter_in_uppercase\n word.gsub(/\\/(.?)/) { \"::#{$1.upcase}\" }.gsub(/(?:^|_)(.)/) { $1.upcase }\n else\n word.to_s[0].chr.downcase + word.camelize[1..-1]\n end\n end",
"def deep_symbolize_keys!\n deep_transform_keys!{ |key| key.to_sym rescue key }\n end",
"def deep_symbolize_keys!\n deep_transform_keys!{ |key| key.to_sym rescue key }\n end",
"def deep_symbolize_keys!\n deep_transform_keys!{ |key| key.to_sym rescue key }\n end",
"def hash_key(key)\n key.downcase\n end",
"def deep_symbolize_keys!\n deep_transform_keys! { |key| key.to_sym rescue key }\n end",
"def deep_symbolize_keys!\n deep_transform_keys! { |key| key.to_sym rescue key }\n end",
"def deep_symbolize_keys!\n deep_transform_keys! { |key| key.to_sym rescue key }\n end",
"def to_snake_case(str)\n return downcase if match()\nend",
"def to_camel_case(uppercase_first_letter = false)\n string = self\n string = if uppercase_first_letter\n string.sub(/^[a-z\\d]*/, &:capitalize)\n else\n string.sub(/^(?:(?=\\b|[A-Z_])|\\w)/, &:downcase)\n end\n string.gsub(%r{(?:_|(/))([a-z\\d]*)}) { \"#{Regexp.last_match(1)}#{Regexp.last_match(2).capitalize}\" }.gsub('/', '::')\n end",
"def snake_case_ps_object_keys\n # this line might seem a bit odd, but it is necessary because there\n # are two paysimple methods that, depending on the context, will \n # return @ps_object where one of the elements is an instance of \n # NilClass.\n @ps_object.delete_if(&:nil?)\n @ps_object.map!(&:snake_case_keys)\n end",
"def snake_case(str)\n str.gsub(/::/, '/')\n .gsub(/([A-Z]+)([A-Z][a-z])/, '\\1_\\2')\n .gsub(/([a-z\\d])([A-Z])/, '\\1_\\2')\n .tr('-', '_').downcase\n end",
"def convert_key dbkey\n arr = dbkey.split('_')\n arr.each {|s|s[0]=s[0].upcase}\n newkey = arr.join('')\n newkey[0]=newkey[0].downcase\n newkey\n end",
"def camelize_hash(hash)\n if hash.is_a?(Hash)\n Hash[hash.map { |k, v| [camelize_key(k, false), camelize_hash(v)] }]\n else\n hash\n end\n end",
"def camelize_hash(hash)\n if hash.is_a?(Hash)\n Hash[hash.map { |k, v| [camelize_key(k, false), camelize_hash(v)] }]\n else\n hash\n end\n end",
"def camel_to_snake(input)\n input.gsub(/([a-z\\d])([A-Z])/,'\\1_\\2').downcase\n end",
"def translate_rails_key(key)\n key.to_s.camelize\n end",
"def snake_case(name); end",
"def camelcase_params!(params)\n params.keys.select {|key| key.is_a?(Symbol) && key.to_s.include?(?_) }.each do |key|\n camelcase_key = camelize(key)\n camelcase_key[0] = camelcase_key[0].chr.downcase\n params[camelcase_key] = params.delete(key)\n end\n end",
"def camel(value)\n case value\n when Hash then value.deep_transform_keys! { |key| camel(key) }\n when Symbol then camel(value.to_s).to_sym\n when String then StringSupport.camel(value)\n else value\n end\n end",
"def singularize_key\n ActiveSupport::Inflector.singularize(key)\n end",
"def snake_case_to_camel_case(value)\n pieces = value.to_s.split '_'\n\n (pieces[0] + pieces[1..-1].map(&:capitalize).join).to_sym\n end",
"def snake_case(str)\n str.gsub(/::/, '/')\n .gsub(/([A-Z]+)([A-Z][a-z])/, '\\1_\\2')\n .gsub(/([a-z\\d])([A-Z])/, '\\1_\\2')\n .tr('-', '_')\n .downcase\n end",
"def normalize_key(key)\n case key\n when Numeric, nil\n # nils never happen here in Ruby >= 2.3 since nils\n # skip the normalizer.\n key\n else\n key.to_s.downcase.strip\n .gsub(/(?:\\s+|-)/, '_')\n .gsub(/[^a-zA-Z0-9_]+/, '')\n .squeeze('_')\n .gsub(/_$/, '')\n .to_sym\n end\n end",
"def snake_case(str)\n str = str.dup\n str.gsub!(/[A-Z]/) {|s| \"_\" + s}\n str.downcase!\n str.sub!(/^\\_/, \"\")\n str\nend",
"def select_upcase_keys(hash)\n upcase_keys = Hash.new()\n hash.each { |k,v| upcase_keys[k] = v if k == k.upcase }\n return upcase_keys\nend",
"def recursively_symbolize_keys\n recursively_transform_keys { |key| key.to_sym rescue key }\n end",
"def convert_underscores(hash)\n hash.each_with_object({}) do |(k ,v), obj|\n key = k.to_s.gsub(/_/, '-').to_sym\n obj[key] = v\n end\nend",
"def camelize(_uppercase_first_letter = true)\n self.dup.camelize!\n end",
"def snake_sym(key)\n key.is_a?(String) ? key.gsub(/(.)([A-Z])/,'\\1_\\2').downcase.to_sym : key\n end",
"def deep_transform_keys!(&block); end",
"def deep_symbolize_keys\n deep_transform_keys{ |key| key.to_sym rescue key }\n end",
"def camel(snake_case)\n snake_case.to_s.capitalize.gsub(/_./) { |match| match[1].upcase }\n end"
] |
[
"0.806826",
"0.7979336",
"0.7728809",
"0.7555193",
"0.75383025",
"0.75021225",
"0.7479797",
"0.7421893",
"0.73681736",
"0.7238859",
"0.72013855",
"0.71686465",
"0.7094905",
"0.70542264",
"0.6968482",
"0.69405615",
"0.69333124",
"0.69333124",
"0.6917206",
"0.6794908",
"0.67814606",
"0.67725205",
"0.6739888",
"0.6673367",
"0.6655533",
"0.66469646",
"0.66193604",
"0.65594304",
"0.6553588",
"0.6547239",
"0.65283316",
"0.65212226",
"0.65112025",
"0.65013313",
"0.6486231",
"0.6466916",
"0.64429235",
"0.6431212",
"0.6420413",
"0.6358326",
"0.6343954",
"0.6321535",
"0.63066155",
"0.62860787",
"0.62468743",
"0.623668",
"0.62343186",
"0.62343186",
"0.62343186",
"0.62280333",
"0.62257266",
"0.62240255",
"0.62009895",
"0.6189529",
"0.61834896",
"0.6183233",
"0.6149113",
"0.6146196",
"0.61419886",
"0.61313283",
"0.61219454",
"0.6118319",
"0.60966676",
"0.6093777",
"0.60858417",
"0.6078259",
"0.60780627",
"0.60740227",
"0.60679156",
"0.60661286",
"0.60661286",
"0.6056907",
"0.60352635",
"0.60352635",
"0.60352635",
"0.6030058",
"0.60274947",
"0.6018588",
"0.601844",
"0.6016401",
"0.6014281",
"0.6014281",
"0.60114866",
"0.60100704",
"0.60063577",
"0.6000428",
"0.5999539",
"0.599253",
"0.59798515",
"0.5970348",
"0.5968466",
"0.5964705",
"0.59601784",
"0.59508806",
"0.59505177",
"0.59502506",
"0.5931653",
"0.5931022",
"0.5930889",
"0.5923218"
] |
0.6553973
|
28
|
Returns an unobtrusive link (with html5 data attributes) that lets you bring up an RPXNow Dialog.
|
def rpxnow_link(text, url, opts = {})
has_rpxnow
options = options_with_class_merged(opts, :class => 'rpxnow')
rpx_opts = options.delete(:rpx) || {}
auth_token_params = [Rack::Utils.escape(request_forgery_protection_token.to_s), Rack::Utils.escape(form_authenticity_token.to_s)] * "="
token_url = "#{url}#{url.include?("?") ? "&" : "?"}#{auth_token_params}"
rpx_opts[:realm] ||= Settings.rpx.realm
rpx_opts[:token_url] = token_url
rpx_opts.each_pair do |k, v|
options["data-rpxnow-#{k.to_s.gsub("_", "-")}"] = v
end
full_url = "http://#{rpx_opts[:realm]}.rpxnow.com/openid/v2/signin?token_url=#{Rack::Utils.escape(token_url)}"
link_to text, full_url, options
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def link_to_dialog(text, options, html_options = {})\n link_to(\n text,\n options.reverse_merge(:width => 650, :height => 500, \"TB_iframe\" => \"true\"),\n html_options.reverse_merge(:class => \"thickbox\", :title => text)\n )\n end",
"def auto_pop_up_link(text, target, options, url = nil)\n link_to text, (url || '#'), {\n :class => \"auto_pop_up_link#{ \" #{options[:class]}\" if options[:class]}\", \n :title => options[:title], \n :'data-div-id' => target, \n :'data-width' => options[:width], \n :'data-height' => options[:height],\n :'data-modal' => options[:modal]\n }\n end",
"def link_markup(descr = nil)\n descr = \"View resource.\" if descr == nil\n\n link = @reference_action_def.doi\n link = @reference_action_def.link if link.empty?\n return \"<a href=\\\"#{link}\\\" target=\\\"_blank\\\">#{descr}</a>\"\n end",
"def publication_link\n h.link_to \"Read Now\" , object.publication_url , title: 'Read Now' , class: 'btn waves-effect waves-light btn-primary custom-btn' , target: '_blank'\n end",
"def button_link content = nil, options = nil, html_options = nil, &block\n UiBibz::Ui::ButtonLink.new(content, options, html_options, &block).render\n end",
"def link(obj)\n return \"<a href='#{R(obj, self.id)}'>#{self.name}</a>\"\n end",
"def call_for_detail(entity, text, options = {}, html_options = {})\n text ||= \"...\"\n opt = options.dup\n opt[:controller] = options[:force_controller] || entity.controller_name\n opt[:action] = options[:force_action] || \"show\"\n opt[:id] = options[:force_id] || entity.to_param\n opt[:background_params] = @background_params\n if html_options[:popup] || html_options[:target]\n # for the case of new window to render\n opt[:layout] ||= \"base_layout_for_non_collection\"\n end\n link_to text, opt, html_options\n end",
"def get_linked_full_name_with_date\n h.link_to( \"#{get_full_name} (#{get_meeting_date})\", meeting_show_full_path(id: object.id), { 'data-toggle'=>'tooltip', 'title'=>I18n.t('meeting.show_results_tooltip') } )\n end",
"def link\n Html::Link.new(:href => url) << display_name\n end",
"def get_linked_full_name\n h.link_to( get_full_name, meeting_show_full_path(id: object.id), { 'data-toggle'=>'tooltip', 'title'=>I18n.t('meeting.show_results_tooltip') } )\n end",
"def my_link_to_show(data)\r\n link_to image_tag(\"info.png\", :border=>0), data, :title => \"Details anzeigen\"\r\n end",
"def mrl_popup_link\n @mrl_result = MrlResult.new\n @mrl_result.farm_code = session[:new_delivery].farm_code\n @mrl_result.puc_code = session[:new_delivery].puc_code\n @mrl_result.orchard_code = session[:new_delivery].orchard_code\n @mrl_result.mrl_result_type_code = session[:new_delivery].mrl_result_type\n\n sequence_number = nil\n mrl_results_overall = MrlResult.find_by_sql(\"select * from mrl_results\")\n if mrl_results_overall != nil\n mrl_results_seq = MrlResult.find_by_sql(\"select MAX(sequence_number) AS seq_num from mrl_results\")\n sequence_number = mrl_results_seq[0].seq_num.to_i + 1\n else\n sequence_number = 1\n end\n\n @mrl_result.sample_no = session[:new_delivery].farm_code.to_s + \"/\" + session[:new_delivery].rmt_variety_code.to_s + \"/\" + sequence_number.to_s\n render :inline => %{\n <%= build_mrl_result_form(@mrl_result,'print_mrl_label_link','print mrl result',is_edit = nil,is_create_retry = nil ) %>\n }, :layout => 'content'\n end",
"def render\n <<-HTML\n <div class=\"relative\">\n <a href=\"#{url}\"class=\"#{position_classes}f6 link dim br2 ph3 pv2 dib white bg-blue\" data-help-link=\"Y\" target=\"cbf-help\">#{Icon.new(:question).render} #{text}</a>\n </div>\n HTML\n end",
"def get_linked_name\n h.link_to( get_full_name, team_closed_goggle_cup_path(id: goggle_cup.id), { 'data-toggle'=>'tooltip', 'title'=>I18n.t('radiography.goggle_cup_closed_tooltip') } )\n end",
"def open_lid\n 'Click the <b>Open Lid</b> button'\n end",
"def open_lid\n 'Click the <b>Open Lid</b> button'\n end",
"def nexia_link # :doc:\n content_box.a(:text => \"nexiahome.com\")\n end",
"def link_to_solicitud_portal(solicitud, popup = false)\n return raw( link_to solicitud.codigo, solicitud_portal_path(:id => solicitud.id), :title => \"Haga click para ver contendido de Solicitud.\", :popup => popup )\n end",
"def link_to_with_data(*args, &block)\n if block_given?\n options = args.first || {}\n html_options = args.second\n concat(link_to(capture(&block), options, html_options))\n else\n name = args.first\n options = args.second || {}\n html_options = args.third\n\n url = url_for(options)\n\n if html_options\n html_options = html_options.stringify_keys\n href = html_options['href']\n convert_options_to_javascript_with_data!(html_options, url)\n tag_options = tag_options(html_options)\n else\n tag_options = nil\n end\n\n href_attr = \"href=\\\"#{url}\\\"\" unless href\n \"<a #{href_attr}#{tag_options}>#{h(name) || h(url)}</a>\"\n end\n end",
"def get_viewer_link(urn,access_token)\n #absolute url = request.base_url\n url = \"/viewer1.html?token=#{access_token}&urn=#{urn}\"\n link = \"<a href=\\\"#{url}\\\" target=\\\"_blank\\\">View Model</a>\"\n return link\n end",
"def href; end",
"def open_lid()\n \"Click the <b>Open Lid</b> button\"\n end",
"def jquery_link(name, options = {})\n content_tag :a, name, options.merge({:href => 'javascript:;'})\n end",
"def button_to_reference_window(url, javascript, options ={})\n link_to_function 'pickup', javascript, options\n end",
"def fries_offer_link\n fries_popup.find(:link_class => 'fries_cta')\n end",
"def mgs_feedback_link\n\t\t$tracer.trace(__method__)\n\t\treturn ToolTag.new(jquery(\"a[href='#']\"),__method__)\n\tend",
"def popup_attrs(feature)\n {\n :class=>'thickbox',\n :title=>link_to('Link to this Feature', feature_path(feature.fid))\n }\n end",
"def link_helper(note)\n onclick = note.onclick\n unless href = note.link\n href = '#'\n onclick ||= \"footnotes_toogle('#{note.to_sym}_debug_info');return false;\" if note.fieldset?\n end\n\n \"<a href=\\\"#{href}\\\" onclick=\\\"#{onclick}\\\">#{note.title}</a>\"\n end",
"def link_to_record_select(name, controller, options = {})\n options[:params] ||= {}\n options[:params].merge!(:controller => controller, :action => :browse)\n options[:onselect] = \"function(id, label) {#{options[:onselect]}}\" if options[:onselect]\n options[:html] ||= {}\n options[:html][:id] ||= \"rs_#{rand(9999)}\"\n\n assert_controller_responds(options[:params][:controller])\n\n html = link_to_function(name, '', options[:html])\n html << javascript_tag(\"new RecordSelect.Dialog(#{options[:html][:id].to_json}, #{url_for(options[:params].merge(:escape => false)).to_json}, {onselect: #{options[:onselect] || ''}})\")\n\n return html\n end",
"def old_button_link_to( title, url, options={} )\n#\t\tid = \"id='#{options[:id]}'\" unless options[:id].blank?\n#\t\tklass = if options[:class].blank?\n#\t\t\t\"class='link'\"\n#\t\telse\n#\t\t\t\"class='#{options[:class]}'\"\n#\t\tend\n#\t\ts = \"<button #{id} #{klass} type='button'>\"\n\t\tclasses = ['link']\n\t\tclasses << options[:class]\n\t\ts = \"<button class='#{classes.flatten.join(' ')}' type='button'>\"\n\t\ts << \"<span class='href' style='display:none;'>\"\n\t\ts << url_for(url)\n\t\ts << \"</span>\"\n\t\ts << title\n\t\ts << \"</button>\"\n\t\ts\n\tend",
"def link_to_modal_form project\n link_to \"##{ idify( project ) }\", :class => 'btn btn-mini btn-warning',\n :'data-toggle' => \"modal\", :role=>\"button\" do\n content_tag( :i, nil, :class => \"icon-wrench\" ) +\n \" Setup your project\"\n end\n end",
"def get_linked_short_name\n h.link_to( get_short_name, meeting_show_full_path(id: object.id), { 'data-toggle'=>'tooltip', 'title'=>I18n.t('meeting.show_results_tooltip') } )\n end",
"def apphelp_protected_show_link( obj, name = nil )\n return apphelp_unknown_quantity_warning() if ( obj.nil? )\n\n name = obj.name if ( name.nil? )\n link = apphelp_protected_link_to(\n :show,\n {\n :model => obj.class,\n :method => :url_for\n },\n obj\n ) { h( name ) }\n\n return ( link.empty? ) ? h( name ) : link\n end",
"def link\n '-'\n end",
"def fb_ui(name, options ={})\n callback = options.delete(:callback)\n callback.gsub!('\"', \"'\")\n\n data = \"FB.ui(#{options.to_json.gsub('\"', \"'\")}, #{callback});\"\n link_to(name, '#', :onclick => data.html_safe)\n end",
"def get_linked_custom_name( name )\n h.link_to( \"#{name}\", meeting_show_full_path(id: object.id), { 'data-toggle'=>'tooltip', 'title'=>I18n.t('meeting.show_results_tooltip') } )\n end",
"def generate_link(failure_file_details, file_path)\n \"<strong><a href='xdoclet/#{failure_file_details[0].gsub(/\\//, \"_\").gsub(/\\.rb/, \".rb.html\")}' target='_blank'>#{file_path}</a></strong><br/>\"\n end",
"def html(args = nil)\n if args and args[:edit]\n url = self.url_edit\n else\n url = self.url\n end\n\n return \"<a href=\\\"#{Knj::Web.ahref_parse(url)}\\\">#{self.name_html}</a>\"\n end",
"def link_button_to(*args, &block)\n if block_given?\n options = args.first || {}\n html_options = args.second\n link_button_to(capture(&block), options, html_options)\n else\n name = args[0]\n options = args[1] || {}\n html_options = args[2]\n\n url = url_for(options)\n html_options = convert_options_to_data_attributes(options, html_options.merge({ 'data-url' => url }))\n\n content_tag(:button, ERB::Util.html_escape(name || url), html_options)\n end\n end",
"def link_to_aid_funded(text)\n link = ''\n if opportunity.types.aid_funded.any?\n link = h.link_to 'https://www.gov.uk/guidance/aid-funded-business', target: '_blank', rel: 'noopener' do\n text\n end\n end\n link.html_safe\n end",
"def link(opts)\n \"#{opts[:name]} !LINK_OPEN_TAG!#{opts[:href]}!LINK_CLOSE_TAG!\"\n end",
"def view_link(resource, *args)\n link = ''.html_safe\n\n resource_name = normalized_resource_name(resource)\n object = determine_proper_resource(resource)\n options = args.first || {}\n\n # CSS classes for this crud link\n crud_link_css(options, 'view')\n # text to be displayed\n link_text = crud_link_text(options, 'view')\n\n # (optional) add a tooltip to the link\n if options.keys.include?(:tooltip)\n add_tooltip(options)\n end\n\n options[:id] = 'view-' + link_id(object)\n options[:title] = 'View this ' + resource_name\n\n if defined? CanCan\n link += link_to link_text, url_for(resource), options if can?(:read, object)\n else\n link += link_to link_text, url_for(resource), options\n end\n\n link\n end",
"def link_to_identifier; end",
"def link_to_identifier; end",
"def button_link_to( title, url, options={} )\n\t\tclasses = ['link']\n\t\tclasses << options[:class]\n\t\ts = \"<a href='#{url_for(url)}' style='text-decoration:none;'>\"\n\t\ts << \"<button type='button'>\"\n\t\ts << title\n\t\ts << \"</button></a>\\n\"\n\tend",
"def get_full_advisory_link(errata)\n \"#{request.protocol}#{request.host_with_port}/advisory/#{errata.id}\"\n end",
"def button_to_link(name, link, options={})\n\t confirm_option = options.delete(:confirm)\n\t popup_option = options.delete(:popup)\n\t link_function = popup_option ? redirect_function(link, :new_window => true) : redirect_function(link)\n\t link_function = \"if (confirm('#{escape_javascript(confirm_option)}')) { #{link_function}; }\" if confirm_option\n\t button_to_function name, link_function, options\n\tend",
"def ar_show_link resource= @resource\n link_to(controller.ardata.labels[:show], ar_resource_path('', resource))\n end",
"def ui_button_link(content = nil, options = nil, html_options = nil, &block)\n UiBibz::Ui::Core::Forms::Buttons::ButtonLink.new(content, options, html_options, &block).render\n end",
"def render_new_content_link(element)\n\t\t\t\tlink_to_overlay_window(\n\t\t\t\t\trender_icon('create') + t('add new content'),\n\t\t\t\t\talchemy.new_admin_element_content_path(element),\n\t\t\t\t\t{\n\t\t\t\t\t\t:size => '335x70',\n\t\t\t\t\t\t:title => t('Select an content'),\n\t\t\t\t\t\t:overflow => true\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t:id => \"add_content_for_element_#{element.id}\",\n\t\t\t\t\t\t:class => 'small button with_icon new_content_link'\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\tend",
"def tweet_link_for_new_free_episode_vland\n \t\t# TODO\n \tend",
"def link_to_ecoologic\n image = image_tag(Setting.ecoologic_link_image_url,\n {:alt => Setting.ecoologic_alt, :height => '64px'})\n url = Setting.ecoologic_link_url\n link_opts = {:title => Setting.ecoologic_link_title, :target => '_blank'}\n # :id => :ecoologic_link\n \n link_to image, url, link_opts\n end",
"def build_link(master_u)\n icon_edit = '<span class=\"glyphicon glyphicon-edit\"></span>'\n icon_show = '<span class=\"glyphicon glyphicon-info-sign\"></span>'\n link = link_to(raw(icon_show), master_u)\n link += link_to(raw(icon_edit), edit_master_unit_path(master_u))\n raw('<div class=\"datatable-actions\">'+link+'</div>')\n end",
"def generate_link\n 'autologin/'+code\n end",
"def link_popup_facture(dep)\n if dep.is_a?(Integer)\n facture = Facture.find(dep)\n else\n facture = Facture.find(dep[:id])\n end\n #affichage tableau\n out = '\n <a href=\" '+ facture_path(facture) +'\" class=\"tip\">'+ facture.name \n\n #affichage popup\n out += '\n <span> \n <fieldset class=\"popup\">\n <legend class=\"popup\"><b>'+ facture.name + '</b></legend>'\n\n #REPORT\n if facture.class.equal?(Report)\n out += '<p>Report de la facture: <b>' + facture.reportable.name + '</b></p>'\n end\n if facture.class.equal?(Reportable)\n out += '<p>Facture Reportable</p>'\n end\n\n #Description\n out += '\n <table class=\"table_data\">\n ' + tr_text(\"Id\", facture.id) + '\n ' + tr_text(\"Categorie\", facture.category.name) + '\n ' + tr_text(\"Prestataire\", facture.user.name) + '\n ' + tr_text(\"Surface\", facture.sum_surfaces.display, 'Ha') + '\n ' + tr_text(\"Cout\", facture.get_cout_total_sans_reduc.display, '€')\n if facture.charges? || facture.class.equal?(Reportable)\n out += '\n ' + tr_text(\"Cout Comptable\", facture.get_cout_total.display, euro)\n end\n out += tr_text(\"Desc\", facture.desc) + '\n </table> '\n\n #TOUS LES TYPE DE FACTURES\n unless facture.parcelles.empty?\n out += '<br><b>'+facture.parcelles.length.to_s+' parcelles : </b>'\n out += '\n <table class=\"table_data\">\n <tr>\n <td>Culture</td>\n <td>Nom</td>\n <td>Ha</td>\n </tr>'\n for parcelle in facture.parcelles.find(:all, :order => :typeculture_id)\n out += '<tr>'\n out += '<td>' + parcelle.typeculture.name + '</td>'\n out += '<td>' + parcelle.name + '</td>'\n out += '<td>' + parcelle.surface.display(0) + '</td>'\n out += '</tr>'\n end\n out += '</table>'\n end\n \n #REPORTABLE : Reports Associees\n if facture.class.equal?(Reportable)\n if facture.reports.count > 0\n out += '<br><b>'+facture.reports.length.to_s+' Reports : </b>'\n out += '<table class=\"table_data\">'\n for report in facture.reports\n out += '<tr>'\n out += '<td>' + report.name + '</td>'\n out += '<td>' + report.cout.to_s + ' ' + euro + '</td>'\n out += '</tr>'\n end\n out += '<tr><td>Total Reports</td>'\n out += sum_reports_cout(facture.id)\n out += '</tr>'\n out += '</table>'\n end\n end\n\n #DEBIT : Charges Associees (Labours et Pulves)\n if facture.labours.count > 0\n out += '<p><b>Labours</b></p>'\n out += '<table class=table_data>\n \t<tr class=bold>\n \t <td class=left><b>Labour</b></td>\n \t <td><b>cout</b></td>\n \t</tr>'\n facture.labtofactures.each do |labtofacture|\n out += '\n <tr>\n \t\t <td class=left>' + link_to(labtofacture.labour.name, labour_path(labtofacture.labour)) + '</td>\n \t\t <td>' + labtofacture.value.display + '</td>\n \t\t </tr>'\n end\n out += '\n <tr>\n \t <td class=bold>Somme :</td>\n \t <td class=bold>' + facture.sum_labours.display + '</td>\n \t </tr>\n </table>'\n end\n\n if facture.pulves.count > 0\n out += '<p><b>Pulves</b></p>'\n out += '<table class=table_data>\n \t<tr class=bold>\n \t <td class=left><b>Pulve</b></td>\n \t <td><b>cout</b></td>\n \t</tr>'\n facture.putofactures.each do |putofacture|\n out += '\n <tr>\n \t\t <td class=left>' + link_to(putofacture.pulve.name, pulve_path(putofacture.pulve)) + '</td>\n \t\t <td>' + putofacture.value.display + '</td>\n \t\t </tr>'\n end\n out += '\n <tr>\n \t <td class=bold>Somme :</td>\n \t <td class=bold>' + facture.sum_pulves.display + '</td>\n \t </tr>\n </table>'\n end\n\n # COMPTABILISATION\n if facture.comptable_diff? \n out += \"<br><b>Comptabilisation : diff</b>\n \t <table class=table_data>\n \t\t <tr>\n \t\t <td>Cout facture</td>\n \t\t <td><b></b></td>\n \t\t <td><b>#{facture.cout.display()}</b></td>\n \t\t </tr>\"\n if facture.sum_pulves > 0 \n out += \"<tr>\n <td>Pulves : </td>\n \t\t <td><b>-</b></td>\n \t\t <td><b#{facture.sum_pulves.display()}</b></td>\n \t\t </tr>\"\n end\n \t\tif facture.sum_labours > 0 \n \t\t out += \"<tr>\n \t\t <td>Labours : </td>\n \t\t <td><b>-</b></td>\n \t\t <td><b>#{facture.sum_labours.display()}</b></td>\n \t\t </tr>\"\n \t\tend\n if facture.sum_produits_assoc > 0 \n out += \"<tr>\n \t\t <td>Produits Consommés : </td>\n \t\t <td><b>-</b></td>\n \t\t <td><b>#{facture.sum_produits_used.display()}</b></td>\n \t\t </tr>\"\n \t\tend\n out += \"<tr>\n \t\t <td>Valeur comptable de la facture : </td>\n \t\t <td><b>=</b></td>\n \t\t <td><b>#{(facture.cout - facture.sum_charges).display()}</b></td>\n \t\t </tr>\n \t</table>\"\n elsif facture.comptable_null? \n out += \"<br><b>Comptabilisation : nulle</b>\"\n elsif facture.comptable_total? \n \t out += \"<br><b>Comptabilisation : total</b>\"\n end\n\n out += ' \n </fieldset>\n </span>\n </a>'\n return out\n end",
"def cancel_link\n $tracer.trace(format_method(__method__))\n return ToolTag.new(a.id(\"/btnClose$/\"), format_method(__method__))\n end",
"def stream_link path, options={}\n options[:onclick] = 'RP.stream.go(event);'\n options[:class] = \"#{options[:class]} stream-trigger\"\n options[:data] ||= {}\n options[:data][:path] = path\n options[:data][:container_selector] = response_service.container_selector\n link_to \"Click to load\", \"#\", options\n end",
"def to_link\n \"<a href=\\\"#{self.url}\\\">#{self.name}</a>\"\n end",
"def link_to(arg)\n text =\n if arg.respond_to?(:name)\n arg.name\n else arg.to_s\n end\n\n Doc::HTML.escape_html(text)\n end",
"def cancel_link\n $tracer.trace(format_method(__method__))\n return ToolTag.new(a.id(\"/CancelLinkButton$/\"), format_method(__method__), @spec)\n end",
"def if_data_link (data, href, classes = \"\", data_attrs = \"\")\n return \"<a href='#{href}' class='#{classes}' #{data_attrs}>#{data}</a>\"\n end",
"def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @chronopay_link }\n end\n end",
"def link\n h.content_tag :li do\n h.link_to h.content_tag(:i, '' , class: object.icon ) , object.url , target: \"_blank\" , title: object.name\n end\n end",
"def close_link\n $tracer.trace(format_method(__method__))\n return ToolTag.new(@tag.find.a.id(\"/lnkClosePopup$/\"), format_method(__method__))\n end",
"def link_to(name, url, options = {}); end",
"def link(link, title, content)\n link = OodAppkit.files.api(path: @app_path.to_s + '/' + link).to_s if @app_path && relative?(link)\n return \"<a href=\\\"#{link}\\\" rel=\\\"noopener\\\" target=\\\"_blank\\\">#{content}</a>\" unless id_link?(link)\n return \"<a href=\\\"#{link}\\\">#{content}</a>\"\n end",
"def href\n super || (modal ? '#' : nil)\n end",
"def render_create_content_link(element, options = {})\n\t\t\t\tdefaults = {\n\t\t\t\t\t:label => t('add new content')\n\t\t\t\t}\n\t\t\t\toptions = defaults.merge(options)\n\t\t\t\tlink_to(\n\t\t\t\t\toptions[:label],\n\t\t\t\t\talchemy.admin_contents_path(\n\t\t\t\t\t\t:content => {\n\t\t\t\t\t\t\t:name => options[:content_name],\n\t\t\t\t\t\t\t:element_id => element.id\n\t\t\t\t\t\t}\n\t\t\t\t\t),\n\t\t\t\t\t:method => 'post',\n\t\t\t\t\t:remote => true,\n\t\t\t\t\t:id => \"add_content_for_element_#{element.id}\",\n\t\t\t\t\t:class => 'button new_content_link'\n\t\t\t\t)\n\t\t\tend",
"def foreign_url_for(obj, opt={})\n host, path = nil, nil\n text, target = opt.values_at(:text, :target)\n case obj\n when IcuPlayer\n host = \"www.icu.ie\"\n path = \"admin/players/#{obj.id}\"\n text ||= obj.id\n target ||= \"_icu_ie\"\n when FidePlayer\n host = \"ratings.fide.com\"\n path = \"card.phtml?event=#{obj.id}\"\n text ||= obj.id\n target ||= \"_fide_com\"\n end\n return nil unless host && path\n link_to text, \"http://#{host}/#{path}\", target: target, class: \"external\"\n end",
"def ajax_link_to_new(text, resource, options = {})\n name = (\"<i class='icon-white icon-plus'></i> \" + text).html_safe\n attributes = {\n :remote => true,\n :class => \"btn btn-primary mr-s\"\n }.merge(options)\n link_to name, resource, attributes\n end",
"def link\n \"/events/#{id}\"\n end",
"def wish_list_link()\n $tracer.trace(format_method(__method__))\n return ToolTag.new(@tag.find.a.id(\"/btnAddToWishlist/\"), format_method(__method__), @spec)\n end",
"def link_to_show(text, path, options={})\n link_to_action(text, path, options.reverse_merge(:action => :show))\n end",
"def button(found, date_id, new_date)\n ret_btn = \"<a href='#{button_href(date_id)}' \"\n ret_btn += \"class='#{button_classes(found)}'>\"\n ret_btn += \"#{button_text(found, new_date)}</a>\"\n ret_btn\n end",
"def link(link, title, content)\n\t \"<u><link href='#{link}'>#{content}</link></u>\"\n\t end",
"def precinctsShowLink\n \"#{firstname} #{lastname}, #{office.name}\"\n end",
"def show_button_to(path, text = t('show'))\n link_to path, class: 'button small' do\n concat text\n end\n end",
"def _link(attribute, text=nil)\n link = \"##{attribute}\"\n %{<a href=\"#{link}\">#{text || attribute}</a>}\nend",
"def link_to(*args, &block)\n if block_given?\n super(*args)\n else\n options = args[1] || {}\n html_options = args[2] || {}\n unless html_options.has_key? :'data-id'\n begin\n path = URI.split(url_for(options) || html_options['href'])[5].split(/\\//).select {|x| !x.empty?}\n if path.size > 0\n max = path.size <= 3 ? path.size : 3\n id = path.last(max).join('_')\n else\n id = 'not_defined'\n end\n rescue Exception => e\n id = 'not_parseable'\n end\n html_options.merge!(:'data-id' => \"aid_#{id}\")\n end\n super(args[0], args[1], html_options)\n end\n end",
"def item_detail_url(id)\n \"#{@baseurl}/agdocs.aspx?doctype=agenda&itemid=#{id}\"\n end",
"def click_url\n \"http://www.awin1.com/awclick.php?mid=%s&id=%s\" % [merchant_id, ::AffiliateWindow.account.user]\n end",
"def new\n @link = Link.new :long => 'http://'\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @link }\n end\n end",
"def click(link); end",
"def href\n href = (@url || @dos).to_s.dup\n if @fragment\n href << client('#', 'UTF-8') << @fragment\n end\n href\n end",
"def get_linked_full_name_with_logo\n h.link_to( get_logo_for_season_type + ' ' + get_full_name, meeting_show_full_path(id: object.id), { 'data-toggle'=>'tooltip', 'title'=>I18n.t('meeting.show_results_tooltip') } )\n end",
"def linkwizard_confirm_button\n $tracer.trace(__method__)\n return ToolTag.new(button.id(\"/btnSubmit/\") ,__method__)\n end",
"def button_to( url, text = url, opts = {} )\n tag :button, text, opts.merge( url: url )\nend",
"def content_htm\n link_to @options[:url], link_html_options do\n concat glyph_and_content_html\n concat badge_html if @options[:badge]\n end\n end",
"def buy_gift_card_link_button\n\t\t$tracer.trace(__method__)\n\t\treturn ToolTag.new(a.className(\"ats-buyagiftcardlnk\"), __method__, self)\n end",
"def render_regenerate_challenge_link(sanitized_object_name, object, options = {}, html_options = {})\n text = options.delete(:text) || 'Regenerate Captcha'\n if options.delete(:jquery)\n onclick = \"jQuery.getJSON('#{regenerate_path}', function(result){jQuery('##{sanitized_object_name}_captcha_image').attr('src',result.captcha_image_path); jQuery('##{sanitized_object_name}_captcha_challenge').val(result.captcha_challenge); jQuery('##{sanitized_object_name}_captcha_solution').val('');});return false;\"\n link_to text, \"#\", options.reverse_merge(:onclick => onclick), html_options\n else\n success = \"var result = request.responseJSON; $('#{sanitized_object_name}_captcha_image').src = result.captcha_image_path; $('#{sanitized_object_name}_captcha_challenge').value = result.captcha_challenge; $('#{sanitized_object_name}_captcha_solution').value = '';\"\n link_to_remote text, options.reverse_merge(:url => regenerate_path, :method => :get, :success => success), html_options\n end\n end",
"def booking_link_target(property)\n property.booking_url.present? ? \"_blank\" : \"_self\"\n end",
"def to_html\n \"<a href='#{@graphs_and_data}'>\" + super + \"</a>\"\n end",
"def button_tag( title, url_hash, image=\"\", image_in_own_line=true, popup=false, class_name=\"\" )\n url = popup ? \"popWindow(\\\"#{url_for url_hash}\\\")\" : \"navigateTo(\\\"#{url_for url_hash}\\\")\";\n button_function_tag( title, url, image, image_in_own_line, class_name );\n end",
"def view_button(object, link = nil)\n link_to '<span class=\"glyphicon glyphicon-eye-open\"></span> View'.html_safe,\n link ? link : polymorphic_path(object),\n class: 'btn btn-default',\n title: \"View #{object_title(object)}\"\n end",
"def help_link(wiki_entry_name=nil)\n wiki_url = \"https://github.com/indykish/identityprov/wiki\"\n if wiki_entry_name\n wiki_url += \"/#{wiki_entry_name}\"\n link_text = \"Help for #{wiki_entry_name.underscore_humanize}\" \n else\n link_text =\"Help\" \n end\n link_to_ link_text, wiki_url, { :target => '_blank'}\n end",
"def help_link(help_id)\n link_to(image_tag(\"iconic/lightbulb_20x32.png\", size: \"8x13\"), admin_help_path(help_id),{remote: true, title: \"Open help for this page.\"})\n end",
"def link(text, target, attributes = {})\n if target.is_a? Fixnum\n attributes[:rel] = rel_value(target)\n target = url(target)\n end\n @template.link_to(text, target, attributes.merge(:remote => true))\n end",
"def show\n redirect_to show_path(:id=>@dataclip.link_token)\n end",
"def link(**opt)\n opt[:path] = show_path(id: object.identifier)\n super(**opt)\n end",
"def link\n\t\t\t@data['link']\n\t\tend"
] |
[
"0.63450676",
"0.6184522",
"0.611959",
"0.61178905",
"0.5927624",
"0.59202397",
"0.5888056",
"0.5853935",
"0.58501714",
"0.5845583",
"0.5833852",
"0.57989335",
"0.57746035",
"0.57730514",
"0.5762895",
"0.5762895",
"0.57399845",
"0.57364225",
"0.57300436",
"0.572508",
"0.5719432",
"0.5710297",
"0.5709395",
"0.57038194",
"0.570346",
"0.56973803",
"0.5692773",
"0.56829894",
"0.56792057",
"0.56791073",
"0.56679165",
"0.566457",
"0.5661807",
"0.566106",
"0.5646544",
"0.563692",
"0.5623644",
"0.562338",
"0.5623056",
"0.5615144",
"0.5613593",
"0.560328",
"0.5599363",
"0.5599363",
"0.5580459",
"0.5572893",
"0.55713797",
"0.5568476",
"0.55676603",
"0.55674493",
"0.5559099",
"0.5512542",
"0.5509638",
"0.5493948",
"0.5493033",
"0.5483529",
"0.54804283",
"0.54782104",
"0.5470285",
"0.54673135",
"0.54667753",
"0.54494804",
"0.5447278",
"0.5447075",
"0.5445972",
"0.5432734",
"0.54291016",
"0.5427621",
"0.5420474",
"0.5417655",
"0.54131097",
"0.53768533",
"0.53738534",
"0.5372826",
"0.53695446",
"0.53655887",
"0.53616023",
"0.5360365",
"0.5341238",
"0.53377354",
"0.53326243",
"0.5330765",
"0.53299934",
"0.5325521",
"0.5325004",
"0.5310423",
"0.5303267",
"0.53031194",
"0.5297642",
"0.5288021",
"0.52852434",
"0.52799416",
"0.5270475",
"0.526742",
"0.52669215",
"0.52632946",
"0.5259749",
"0.52595556",
"0.52543455",
"0.52533895"
] |
0.5593136
|
44
|
Automatically embeds the RPXNow Javascript once.
|
def has_rpxnow
return if defined?(@has_rpxnow) && @has_rpxnow
rpxnow_js = "#{request.ssl? ? 'https://' : 'http://static.'}rpxnow.com/js/lib/rpx.js"
has_js rpxnow_js
@has_rpxnow = true
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def js_reload\n riak_admin 'js_reload'\n end",
"def inject_js; end",
"def google_ajax_slideshow_scripts\n return '' if defined?(@google_ajax_slideshow_scripts_included)\n @google_ajax_slideshow_scripts_included = true\n '<script src=\"http://www.google.com/uds/solutions/slideshow/gfslideshow.js\" type=\"text/javascript\"></script>'.html_safe\n end",
"def initial_dynamic_javascript\n res = []\n # res << %(Ext.Ajax.extraParams = {authenticity_token: '#{form_authenticity_token}'}; // Rails' forgery protection)\n res << %{Ext.ns('Netzke');}\n res << %{Ext.ns('Netzke.core');}\n res << %{Netzke.RelativeUrlRoot = '#{ActionController::Base.config.relative_url_root}';}\n res << %{Netzke.RelativeExtUrl = '#{ActionController::Base.config.relative_url_root}/extjs';}\n\n res << %{Netzke.core.directMaxRetries = '#{Netzke::Core.js_direct_max_retries}';}\n\n res.join(\"\\n\")\n end",
"def javascript!\n @coffeescript = false\n end",
"def set_static_includes\r\n @javascripts = [JS_SCRIPTACULOUS_SKOBEE_DEFAULT, JS_SKOBEE_PLANS, JS_DATEPICKER, JS_JSON]\r\n end",
"def js!\n js(reset: true)\n end",
"def display_ipaper(options = {})\n <<-END\n <script type=\"text/javascript\" src=\"http://www.scribd.com/javascripts/view.js\"></script>\n <div id=\"embedded_flash\">#{options.delete(:alt)}</div>\n <script type=\"text/javascript\">\n var scribd_doc = scribd.Document.getDoc(#{ipaper_id}, '#{ipaper_access_key}');\n #{js_params(options)}\n scribd_doc.write(\"embedded_flash\");\n </script>\n END\n end",
"def re_run\n\n # scrpt will have the javascript specification\n scrpt = String.new\n\n # add bootstrap container if it wasn't specified by the user\n @scene.create_grid((keys = @charts.keys).size, keys) if !@scene.specified?\n scrpt << @scene.bootstrap\n\n # add charts\n @charts.each do |name, chart|\n # add the chart specification\n scrpt << chart.js_spec if !chart.nil?\n end\n \n # render all charts\n scrpt += \"dc.renderAll();\"\n\n # sends a message to the gui to execute the given script\n @bridge.send(:gui, :executeScript, scrpt)\n \n end",
"def init_autocrud\n javascript_include_tag('../autocrud/javascripts/autocrud.js', :cache => '../autocrud/javascripts/all_cached')\n end",
"def call_js_init(something_js)\n content_for :javascript do\n \"<script type='text/javascript'>\n $(document).ready(function(){\n #{something_js}\n });\n </script>\".html_safe\n end\n end",
"def call_reins_controller\n \"#{ update_reins_controller }r.call_js_controller();\".html_safe\n end",
"def render_iframe_updates(page_updates)\n script = apotomo_request_processor.render_page_updates(page_updates)\n escaped_script = Apotomo::JavascriptGenerator.escape(script)\n \n render :text => \"<html><body><script type='text/javascript' charset='utf-8'>\nvar loc = document.location;\nwith(window.parent) { setTimeout(function() { window.eval('#{escaped_script}'); window.loc && loc.replace('about:blank'); }, 1) }\n</script></body></html>\", :content_type => 'text/html'\n end",
"def render_js_realtime\n render_code(@js, :realtime)\n end",
"def render_inline_on_load_javascripts\n return '' if @content_for_jquery_onload.blank? && @content_for_javascript_files_onload.blank?\n js_code = \"\\n<!-- DEFFERRED On page load Javascripts -->\\n\"\n on_load_scripts = [ ]\n #write the onload inline javascripts\n on_load_scripts << @content_for_jquery_onload if @content_for_jquery_onload\n #write the javascript files which are jammed into the document head\n on_load_scripts << @content_for_javascript_files_onload if @content_for_javascript_files_onload\n js_code << javascript_tag(j_query_on_load_tag(on_load_scripts)) unless on_load_scripts.blank?\n js_code\n end",
"def google_ajax_api_scripts\n return '' if defined?(@google_ajax_api_scripts_included)\n script = '<script type=\"text/javascript\" src=\"http://www.google.com/jsapi'\n script << \"?key=#{Overlord.configuration.google_ajax_api_key}\" if Overlord.configuration.google_ajax_api_key\n script << '\"></script>'\n @google_ajax_api_scripts_included = true\n script.html_safe\n end",
"def set_static_includes\r\n @javascripts = [JS_SCRIPTACULOUS_SKOBEE_DEFAULT, JS_SKOBEE_COMMENTS]\r\n end",
"def has_js\n session[:surveyor_javascript] = \"enabled\"\n render :text => 'ok'\n end",
"def netzke_js\n js=\"Ext.Ajax.extraParams = {authenticity_token: '#{form_authenticity_token}'}; // Rails' forgery protection\\n\"\n\n\n js << <<-END_OF_JAVASCRIPT if(!ActionController::Base.relative_url_root.blank?)\n // apply relative URL root, if set\n Ext.widgetMixIn.buildApiUrl= function(apip){\n return \"#{ActionController::Base.relative_url_root}/netzke/\" + this.id + \"__\" + apip;\n };\n Ext.BLANK_IMAGE_URL = \"#{ActionController::Base.relative_url_root}/extjs/resources/images/default/s.gif\";\n END_OF_JAVASCRIPT\n\n js << <<-END_OF_JAVASCRIPT\n #{@content_for_netzke_js_classes}\n Ext.onReady(function(){\n #{@content_for_netzke_on_ready}\n });\n END_OF_JAVASCRIPT\n\n javascript_tag js\n \n end",
"def update!\n inject_js\n self\n end",
"def render_deferred_javascript_files\n #write any deffered javascript files\n return '' if @content_for_javascript_files.blank?\n js_code = \"\\n<!-- DEFFERRED Javascripts -->\\n#{@content_for_javascript_files}\"\n end",
"def netzke_js\n send :\"netzke_#{Netzke::Core.platform}_js\"\n end",
"def inject_js=(_arg0); end",
"def appoxy_javascripts\n '<script type=\"text/javascript\" src=\"http://www.google.com/jsapi?key=ABQIAAAAhes0f80sBcwL-h5xCNkkgxQBmiBpQeSpIciQPfZ5Ss-a60KXIRQOVvqzsNpqzhmG9tjky_5rOuaeow\"></script>\n <script type=\"text/javascript\">\n google.load(\"jquery\", \"1\");\n google.load(\"jqueryui\", \"1\");\n </script>\n '.html_safe\n end",
"def ajax_refresh\n\t\trender(file: 'sales/ajax_reload.js.erb')\n\tend",
"def render_inline_javascripts\n #write out any inline javascript\n return '' if @content_for_inline_javascripts.blank?\n js_code = \"\\n<!-- Inline Javascripts -->\\n#{@content_for_inline_javascripts}\"\n end",
"def javascript_doc_ready(&block)\n content = capture(&block)\n javascript_tag(\"$(document).ready(function(){#{content}});\")\n end",
"def url_script\n # Referrer check just to keep other sites from linking this in and getting our\n # user id too.\n if request.referrer.nil? || URI(request.referrer).host == Rails.application.secrets.qa_host\n if user_signed_in?\n code = \"var bz_current_user_openid_url = #{url_for_user.to_json};\"\n else\n code = 'var bz_current_user_openid_url = null;'\n end\n render :text => code, :content_type => 'text/javascript'\n end\n end",
"def install_sample_files\n super\n inject_line_before root.join('apps/web/templates/application.html.erb'), '</head>', <<-HTML\n <%= vite_client %>\n <%= vite_javascript 'application' %>\n HTML\n end",
"def render_deferred_javascript_tags\n # First write the onload inline javascripts\n js_code = ''\n js_code << render_deferred_javascript_files\n js_code << render_inline_javascripts\n js_code << render_inline_on_load_javascripts\n js_code\n end",
"def js_code\n '<script type=\"text/javascript\">' <<\n asset('webconsole.js') <<\n '</script>'\n end",
"def turn_javascript_on # :nologin: :norobots:\n session[:js_override] = :on\n flash_notice(:turn_javascript_on_body.t)\n redirect_to(:back)\n rescue ActionController::RedirectBackError\n redirect_to(\"/\")\n end",
"def bookmarklet_link_target_js\n %Q{javascript:void((function(b){var s=b.createElement('script');s.setAttribute('charset','UTF-8');s.setAttribute('type','text/javascript');s.setAttribute('src',\"//#{host}/assets/bookmarklet.js?r=\"+Math.random()*999);b.body.appendChild(s);setTimeout(function(){if (!window.ppBookmarklet){alert(\"It seems we were unable to connect to the server. Please try again shortly.\")}},5000);})(document))}\n end",
"def no_javascript # :nologin: :norobots:\n end",
"def run\n super\n\n uri = _get_entity_name\n\n # Get existing software details (in case this is a second run)\n existing_libraries = _get_entity_detail(\"javascript\") || []\n\n session = create_browser_session\n\n # Run the version checking scripts in our session (See lib/helpers/browser)\n new_libraries = gather_javascript_libraries(session, uri)\n\n # set the new details\n _set_entity_detail(\"javascript\", new_libraries)\n\n # cleanup\n destroy_browser_session(session)\n\n end",
"def initialize_calendar\n javascript_tag \"setTimeout('Calendar.initCalendar()', 250);\"\n end",
"def country_scripts\n return if defined?(@@country_scripts_included)\n @@country_scripts_included = true\n render :partial => 'scripts/country_scripts'\n end",
"def script(text)\n \"<script type=\\\"text/javascript\\\">jQuery(document).ready(function() {#{text};});</script>\"\n end",
"def inject_disable_jquery_animations\n inject_into_file \"app/views/layouts/application.html.erb\", before: \"</head>\" do\n \" <%= javascript_tag '$.fx.off = true;' if Rails.env.test? %>\\n\"\n end\n end",
"def netzke_js_include\n send :\"netzke_#{Netzke::Core.platform}_js_include\"\n end",
"def when_document_ready\n self << \"jQuery(document).ready(function() {\"\n yield self\n self << \"})\"\n end",
"def facebookJavascriptOnload\n if @opentok_session[:new_session?]\n \"inviteAllOnlineFriends();\" \n else\n \"setCanvasHeight(1400);\"\n end\n end",
"def js_includes\n end",
"def javascript_include_koala\n \"<div id=\\\"fb-root\\\"></div>\n <script src=\\\"http://connect.facebook.net/en_US/all.js\\\"></script>\n <script>\n FB.init({\n appId:'#{Devise::koala_app_id}', cookie:true,\n status:true, xfbml:true\n });\n </script>\"\n end",
"def push_relaunch\n\t\trequire \"config/initializers/launch_juggernaut.rb\"\n\t\trender :nothing => true\n\tend",
"def load_js\n AssetManager.include_contrib_library [:core_ui, :jquery_tab]\n AssetManager.include_local_library [ 'ckeditor/init']\n\n AssetManager.include_css [:blog_global]\n end",
"def go_function!\n @page << \"<script type='text/javascript'>go = function() \"\\\n '{window.hyper_spec_waiting_for_go = false}</script>'\n end",
"def donate_iframe\n #do not delete this function. It is necessary to render the corresponding view.\n end",
"def rating_script(argument)\n <<-STR\n<script type=\"text/javascript\">\n new Tip('#{argument_rate_id(argument)}' ,\n {closeButton: true,\n hook: { target: 'bottomRight', tip: 'bottomRight' },\n viewport: true,\n hideAfter: 0.2,\n hideOn: { element: 'closeButton', event: 'click'},\n ajax: {\n url: '#{tooltip_argument_url(argument)}'\n }}\n );\n</script>\n STR\n end",
"def run_init_script; end",
"def index\n @head = '<script type=\"text/javascript\" src=\"/js/index.js\"></script>'\n @title = \"TinyCDR - FreeSWITCH CDR Reporting\"\n end",
"def render(options = nil, extra_options = {}, &block) #:doc:\n @flash=flash\nputs \"RENGINE RENDER #1\"\n options=interpret_rengine_options(options)\nputs \"RENGINE RENDER #2\"\n #no layout\n super(options,extra_options,&block)\nputs \"RENGINE RENDER #3\"\n unless self.no_wrap\nputs \"RENGINE RENDER #4a\"\n \n \n txx=render_weblab(setUserJavascript+ self.response_body.join(\"\\n\"))\n puts \"RENGINE RENDER #4b\"\n\n # puts \"===========================\\n\"+txx.join(\"\\n\")+\"\\n!================================!\"\n\n if $render_translation_link\n txx << \"\\n<div style=\\\"background-color:#aaa;color:#0ff;\\\">\\n\"\n txx << translation_tool(@displayed_blurb_names)\n txx << \"\\n</div>\\n\"\n end\nputs \"RENGINE RENDER #5\"\n\n self.response_body=txx\n \n end\n end",
"def date_range_js\n if File.exist?('config/initializers/version.rb') && File.read('config/initializers/version.rb').include?('Hyku')\n unless File.read('app/assets/javascripts/application.js').include? \"//= require 'blacklight_range_limit'\\n// Moved the Hyku JS *above* the Hyrax JS\"\n rangejs = \"// For blacklight_range_limit built-in JS, if you don't want it you don't need\\n\"\n rangejs += \"// this:\\n\"\n rangejs += \"//= require 'blacklight_range_limit'\"\n\n rangejs_altered = \"// For blacklight_range_limit built-in JS, if you don't want it you don't need\\n\"\n rangejs_altered += \"// this:\\n\"\n rangejs_altered += \"// require 'blacklight_range_limit'\\n\"\n\n rangejs_new = \"\\n//= require 'flot/jquery.flot.js'\\n\"\n rangejs_new += \"//= require 'flot/jquery.flot.selection.js'\\n\"\n rangejs_new += \"//= require 'bootstrap-slider'\\n\"\n rangejs_new += \"//= require 'blacklight_range_limit/range_limit_distro_facets.js'\\n\"\n rangejs_new += \"//= require 'blacklight_range_limit/range_limit_shared.js'\\n\"\n rangejs_new += \"//= require 'blacklight_range_limit/range_limit_slider.js'\\n\\n\"\n\n gsub_file 'app/assets/javascripts/application.js', rangejs, rangejs_altered\n\n inject_into_file 'app/assets/javascripts/application.js', before: \"// Moved the Hyku JS *above* the Hyrax JS\" do\n rangejs_new\n end\n end\n end\n end",
"def scrapejunk(string)\n string.gsub('<script>', '').delete(';').gsub('</script>', '').gsub('window.scheduleMinebindings = ShiftNote.Bind(window.scheduleMinemodel)', '').gsub('window.scheduleMinemodel = ', '')\n end",
"def thelper_enable_javascript_for_this_test\n sleep 2 # Hack, avoids (very) intermittent obscure error from deep inside PostgreSQL adapter at switch over :-(\n\n Capybara.current_driver = :poltergeist\n thelper_enable_database_cleaner()\n\n self.class.teardown :thelper_disable_javascript_after_test\n end",
"def thelper_disable_javascript_after_test\n Capybara.current_driver = @@ukorgpondtrackrecord_nonjs_driver\n thelper_disable_database_cleaner()\n\n sleep 2\n\n self.class.skip_callback(:teardown, :after, :thelper_disable_javascript_after_test)\n end",
"def js_erb_auto_include\n # Refactor this for resource controller: use request.path and request.path_parameters to deterine which url\n #path_params = request.path_parameters\n #path_params.delete(:action)\n #puts request.path\n #puts path_params.inspect\n #@js_erb_auto_include_controller_url = url_for(path_params.merge({ :format => 'js' }))\n #puts url_for(path_params.merge({ :format => 'js' })).inspect\n @js_erb_auto_include_url = url_for(request.path_parameters.merge({ :format => 'js' }))\n #puts url_for(request.path_parameters.merge({ :format => 'js' })).inspect\n end",
"def meta_refresh; end",
"def <<(javascript)\n self.script << javascript\n \n javascript\n end",
"def render_js_application_reloader_expiration\n message = \"A new version of #{JsApplicationReloader.application_name} is available. \" +\n \"Please click <a href='#{JsApplicationReloader.redirect_url}'>here</a> to load it.\"\n\n respond_to do |format|\n format.html {\n render :text => message, :status => JsApplicationReloader.reload_required_http_status\n }\n format.json {\n render :json => {:message => message}, :status => JsApplicationReloader.reload_required_http_status\n }\n end\n end",
"def first_mandate\n # renders static page\n end",
"def generate_script\n init = Nyaplot.generate_init_code\n path = File.expand_path(\"../templates/static_script.erb\", __FILE__)\n template = File.read(path)\n ERB.new(template).result(binding)\n end",
"def initializer_function\n %{<script type=\"text/javascript\">\n var map_options = #{options_to_json};\n onload_before_#{name} = typeof window.onload == 'function' ? window.onload : function(){};\n window.onload = function(){\n onload_before_#{name};\n phoenix_cartographer.init_map('#{name}', map_options);\n map_options = null;\n }\n </script>\n }.minified!\n end",
"def web_browser_block_java_script\n return @web_browser_block_java_script\n end",
"def public_load\n @note = Note.find_by_user_id(current_user.id)\n respond_to do |format|\n if @note\n format.js\n else\n @note = Note.new\n @note.user_id = current_user.id\n @note.public = \"Click the edit link above to add your thought to share...\"\n @note.save\n format.js\n end\n end \n end",
"def wymiframe\n render :template => \"/wymiframe\", :layout => false\n end",
"def piwik\n \n # see the views/javascripts/piwik.js.erb \n \n end",
"def jrs_javascript(opts = {})\n opts[:wrap_id] ||= 'slideshow'\n opts[:active] ||= 'active'\n opts[:last_active] ||= 'last-active'\n opts[:cycle_time] ||= 4000\n opts[:selector] ||= 'img'\n opts[:transition_time] ||= 1000\n jq = (opts[:prototype] == true) ? 'jQuery' : '$'\n javascript_tag do\n str = <<STR\n #{\"jQuery.noConflict();\" if opts[:prototype]}\n function slideSwitch() {\n var $active = (#{jq}('##{opts[:wrap_id]} #{opts[:selector]}.#{opts[:active]}').length == 0) ? #{jq}('##{opts[:wrap_id]} #{opts[:selector]}:last') : #{jq}('##{opts[:wrap_id]} #{opts[:selector]}.#{opts[:active]}');\n var $next = $active.next().length ? $active.next('#{opts[:selector]}') : #{jq}('##{opts[:wrap_id]} #{opts[:selector]}:first');\n\n $active.addClass('#{opts[:last_active]}');\n\n $next.css({opacity: 0.0}).addClass('#{opts[:active]}').animate({opacity: 1.0}, #{opts[:transition_time]}, function() {\n $active.removeClass('#{opts[:active]} #{opts[:last_active]}');\n });\n }\n\n jQuery(function() { \n setInterval( \"slideSwitch()\", #{opts[:cycle_time]} );\n });\nSTR\n end\n end",
"def internal_frame_shown(title)\n append_to_script \"internal_frame_shown \\\"#{title}\\\"\"\n end",
"def show\n # Get the html, svg, css, and js code to render\n @code = get_article_code\n\n # The default layouts are not added as this page will be\n # embeded in an iframe\n render layout: false\n end",
"def actual_injection\n files_to_page\n set_vars(@default_vars + @custom_vars)\n all_scripts(@default_scripts + @custom_scripts)\n end",
"def thank_you_fp\n $tracer.trace(__method__)\n return ToolTag.new(script.src(\"//t.channeladvisor.com/v2/12019276.js\"), __method__)\n end",
"def google_load_template_script(method_name, javascript_callback, uri, content_id)\n included_name = \"@#{method_name}_included\"\n return '' if instance_variable_get(included_name) rescue false\n instance_variable_set(included_name, true)\n %Q{<script type=\"text/javascript\">\n function #{method_name}(uri, content_id, number_of_items){\n jQuery('#' + content_id).html('');\n var feed = new google.feeds.Feed(uri);\n feed.setNumEntries(number_of_items);\n feed.load(function(result) {\n if (!result.error) {\n jQuery.each(result.feed.entries, function(i,item){\n #{yield}\n #{javascript_callback}('#{uri}', '#{content_id}');\n });\n } \n if (result.error || result.feed.entries.length <= 0) {\n jQuery('#' + content_id).append('<div class=\"hentry\">#{t('overlord.no_entries_found')}</div>');\n }\n });\n }\n </script>}.html_safe\n end",
"def has_jammit_js(*args)\n content_for :extra_footer, include_javascripts(*args)\n nil\n end",
"def unobtrusive_datepicker_includes\n #javascript 'datepicker'\n #stylesheet 'datepicker'\n end",
"def page_script(context={})\n \n [\"/htmleditor/js/jquery.wysiwyg.js\",\n \"/htmleditor/js/ysd.editor.js\",\n \"/htmleditor/js/controls/wysiwyg.colorpicker.js\",\n \"/htmleditor/js/controls/wysiwyg.cssWrap.js\",\n \"/htmleditor/js/controls/wysiwyg.image.js\",\n \"/htmleditor/js/controls/wysiwyg.link.js\",\n \"/htmleditor/js/controls/wysiwyg.table.js\",\n ] \n \n end",
"def install_javascript_dependencies\n inject_into_file 'app/assets/javascripts/application.js', after: '//= require blacklight/blacklight' do\n \"\\n// Required by Arclight\" \\\n \"\\n//= require arclight/arclight\"\n end\n end",
"def setup_laplaya\n js false\n @laplaya_ide_params = {}\n @laplaya_ide_params['root_path'] = Rails.application.config.laplaya_root_path\n @laplaya_ide_params['server_load_time'] = (Time.now.to_f*1000).to_i\n end",
"def on_after_load\n end",
"def javascripts\n super + %w(js/custom.js)\nend",
"def print_js_onloads!(*structs) # Can't append comments to these.\n return nil if (structs_to_print = structs.empty? ? js_onloads : structs).empty?\n javascript_tag_without_flip_flop(\"Event.onReady(function(e) {\" + structs_to_print.map(&:to_s).join(\"\\n\") + \"});\")\n end",
"def render_ext_panel(items = [])\n items.each { |item| \n item[:html] = item[:html].gsub(/\"/,'\\\"').gsub(/\\n/,'')\n item[:id] ||= rand(10000)\n }\n render :partial => \"admin/extjs/panel\", :locals => {\n :items => items, :random_id => rand(10000)\n }\n end",
"def html_fallback_for_js; end",
"def setUserJavascript\n if logged_in?\n \"<script type=\\\"text/javascript\\\">\nlikeMachineUserLogin='#{current_user.login}';\n</script>\";\n else\n \"\"\n end\n end",
"def refresh\n render js: \"location.reload()\"\n end",
"def replace_external_frame\n end",
"def genAnalytics\n %{<script type=\"text/javascript\">\n var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");\n document.write(unescape(\"%3Cscript src='\" + gaJsHost + \"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E\"));\n </script>\n <script type=\"text/javascript\">\n try {\n var pageTracker = _gat._getTracker(\"UA-10612400-1\");\n pageTracker._trackPageview();\n } catch(err) {}</script>}\nend",
"def page_script(context={})\n \n ['/slider/js/jquery.nivo.slider.pack.js'] \n \n end",
"def render_javascript(template)\n assign(template: template)\n assign(nonce: @env[\"action_dispatch.content_security_policy_nonce\"])\n render(template: template, layout: \"layouts/javascript\")\n end",
"def touchpoints_js_string\n ApplicationController.new.render_to_string(partial: \"components/widget/fba.js\", locals: { touchpoint: self })\n end",
"def load_google_api\n content = ''\n content += javascript_include_tag(request.protocol + \"www.google.com/jsapi?key=#{AppConfig.google_api_key}\") unless @@google_api_loaded\n content += yield if block_given?\n @@google_api_loaded = true\n \n content_for(:js_libs) { \n concat content\n }\n end",
"def scripts\n #Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if offline\n script(:src => '//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js')\n script do\n rawtext(%{window.jQuery || document.write('<script src=\"#{js_urls(:lib).first}\"><\\\\/script>')})\n end\n #TODO should just be \"defer\" without attribute, but erector doesn't really do that\n js_urls(:app).each do |url|\n script(:defer => 'defer', :src => url) \n end\n \n #removed google analytics tag\n \n #Prompt IE 6 users to install Chrome Frame. Remove this if you want to support IE 6. \n # chromium.org/developers/how-tos/chrome-frame-getting-started\n comment('[if IE 7 ]') do\n script(:src => '//ajax.googleapis.com/ajax/libs/chrome-frame/1.0.3/CFInstall.min.js')\n script do\n rawtext(%{window.attachEvent('onload',function(){CFInstall.check({mode:'overlay'})})})\n end\n end\n \n yield if block_given?\n end",
"def scriptlink(scr = '/js/ajaxhelper.js')\n \"<script type='text/javascript' src='#{scr}'></script>\"\n end",
"def reload!\n Padrino.before_load.each(&:call) # Run before hooks\n Padrino::Reloader.reload! # detects the modified files\n Padrino.after_load.each(&:call) # Run after hooks\n end",
"def get_detection_html(user_agent)\n ua_info = fingerprint_user_agent(user_agent)\n os = ua_info[:os_name]\n client = ua_info[:ua_name]\n\n code = ERB.new(%Q|\n <%= js_base64 %>\n <%= js_os_detect %>\n <%= js_ajax_post %>\n <%= js_misc_addons_detect %>\n <%= js_ie_addons_detect if os.match(OperatingSystems::Match::WINDOWS) and client == HttpClients::IE %>\n\n function objToQuery(obj) {\n var q = [];\n for (var key in obj) {\n q.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));\n }\n return Base64.encode(q.join('&'));\n }\n\n function isEmpty(str) {\n return (!str \\|\\| 0 === str.length);\n }\n\n function sendInfo(info) {\n var query = objToQuery(info);\n postInfo(\"<%=get_resource.chomp(\"/\")%>/<%=@info_receiver_page%>/\", query, function(){\n window.location=\"<%= get_module_resource %>\";\n });\n }\n\n var flashVersion = \"\";\n var doInterval = true;\n var maxTimeout = null;\n var intervalTimeout = null;\n\n function setFlashVersion(ver) {\n flashVersion = ver\n if (maxTimeout != null) {\n clearTimeout(maxTimeout);\n maxTimeout = null\n }\n doInterval = false\n return;\n }\n\n function createFlashObject(src, attributes, parameters) {\n var i, html, div, obj, attr = attributes \\|\\| {}, param = parameters \\|\\| {};\n attr.type = 'application/x-shockwave-flash';\n if (window.ActiveXObject) {\n attr.classid = 'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000';\n param.movie = src;\n } else {\n attr.data = src;\n }\n\n html = '<object';\n for (i in attr) {\n html += ' ' + i + '=\"' + attr[i] + '\"';\n }\n html += '>';\n for (i in param) {\n html += '<param name=\"' + i + '\" value=\"' + param[i] + '\" />';\n }\n html += '</object>';\n div = document.createElement('div');\n div.innerHTML = html;\n obj = div.firstChild;\n div.removeChild(obj);\n return obj;\n }\n\n window.onload = function() {\n var osInfo = os_detect.getVersion();\n var d = {\n \"os_vendor\" : osInfo.os_vendor,\n \"os_device\" : osInfo.os_device,\n \"ua_name\" : osInfo.ua_name,\n \"ua_ver\" : osInfo.ua_version,\n \"arch\" : osInfo.arch,\n \"java\" : misc_addons_detect.getJavaVersion(),\n \"silverlight\" : misc_addons_detect.hasSilverlight(),\n \"flash\" : misc_addons_detect.getFlashVersion(),\n \"vuln_test\" : <%= js_vuln_test %>,\n \"os_name\" : osInfo.os_name\n };\n\n <% if os.match(OperatingSystems::Match::WINDOWS) and client == HttpClients::IE %>\n d['office'] = ie_addons_detect.getMsOfficeVersion();\n d['mshtml_build'] = ScriptEngineBuildVersion().toString();\n <%\n activex = @requirements[:activex]\n if activex\n activex.each do \\|a\\|\n clsid = a[:clsid]\n method = a[:method]\n %>\n var ax = ie_addons_detect.hasActiveX('<%=clsid%>', '<%=method%>');\n d['activex'] = \"\";\n if (ax == true) {\n d['activex'] += \"<%=clsid%>=><%=method%>=>true;\";\n } else {\n d['activex'] += \"<%=clsid%>=><%=method%>=>false;\";\n }\n <% end %>\n <% end %>\n <% end %>\n\n if (d[\"flash\"] != null && (d[\"flash\"].match(/[\\\\d]+.[\\\\d]+.[\\\\d]+.[\\\\d]+/)) == null) {\n var flashObject = createFlashObject('<%=get_resource.chomp(\"/\")%>/<%=@flash_swf%>', {width: 1, height: 1}, {allowScriptAccess: 'always', Play: 'True'});\n\n // After 5s stop waiting and use the version retrieved with JS if there isn't anything\n maxTimeout = setTimeout(function() {\n if (intervalTimeout != null) {\n doInterval = false\n clearInterval(intervalTimeout)\n }\n if (!isEmpty(flashVersion)) {\n d[\"flash\"] = flashVersion\n }\n sendInfo(d);\n }, 5000);\n\n // Check if there is a new flash version every 100ms\n intervalTimeout = setInterval(function() {\n if (!doInterval) {\n clearInterval(intervalTimeout);\n if (!isEmpty(flashVersion)) {\n d[\"flash\"] = flashVersion\n }\n sendInfo(d);\n }\n }, 100);\n\n document.body.appendChild(flashObject)\n } else {\n sendInfo(d)\n }\n }\n |).result(binding())\n\n js = ::Rex::Exploitation::JSObfu.new code\n js.obfuscate\n\n %Q|\n <script>\n #{js}\n </script>\n <noscript>\n <img style=\"visibility:hidden\" src=\"#{get_resource.chomp(\"/\")}/#{@noscript_receiver_page}/\">\n <meta http-equiv=\"refresh\" content=\"1; url=#{get_module_resource}\">\n </noscript>\n |\n end",
"def json_ld_script_block\n resource = eval('@' + controller_name.singularize)\n if resource && resource.rdf_supported?\n begin\n content_tag :script, type: 'application/ld+json' do\n resource.to_json_ld.html_safe\n end\n rescue Exception => exception\n if Seek::Config.exception_notification_enabled\n data[:message] = 'Error embedding JSON-LD into page HEAD'\n data[:item] = resource.inspect\n ExceptionNotifier.notify_exception(exception, data: data)\n end\n ''\n end\n end\n end",
"def display_scribd(object, alt_text_or_attribute = '', alt_text_if_paperclip = nil)\n # Resolve the right scribd ID, access key, and alt text.\n if object.respond_to?(\"scribd_id\")\n scribd_id = object.scribd_id\n scribd_ak = object.scribd_access_key\n\n alt_text = alt_text_or_attribute\n else\n scribd_id = object.send \"#{alt_text_or_attribute}_scribd_id\"\n scribd_ak = object.send \"#{alt_text_or_attribute}_scribd_access_key\"\n\n alt_text = alt_text_if_paperclip\n end\n\n begin\n # Collect a set of addParam statements to set up JS parameters for the scribd document\n # (only if they are valid).\n param_includes = options[:params].collect do |param, value|\n \"scribd_doc.addParam('#{param}', '#{value}');\" if AVAILABLE_JS_PARAMS.include?(param)\n end.compact.join(\"\\n\")\n rescue\n # Where is 'options' coming from???\n end\n\n <<-END\n <script type=\"text/javascript\" src=\"http://www.scribd.com/javascripts/view.js\"></script>\n <div id=\"embedded_flash\">#{alt_text}</div>\n <script type=\"text/javascript\">\n var scribd_doc = scribd.Document.getDoc(#{scribd_id}, '#{scribd_ak}');\n #{param_includes}\n scribd_doc.write(\"embedded_flash\");\n </script>\n END\n end",
"def set_submission_page_script\n @page_script = \"IG.submission = { id: #{@submission.id || 'null'} };\"\n end",
"def channel\n render inline: '<script src=\"//connect.facebook.net/en_US/all.js\"></script>', layout: false\n end",
"def sharethis_options(post)\n content_tag :script, :type=>\"text/javascript\" do \n <<-eos\n\tSHARETHIS.addEntry({\n\t\ttitle:'#{escape_javascript(post.title)}',\n content:'#{escape_javascript(truncate_words(post.post, 75, '...' ))}'\n\t}, {button:true});\n eos\n end\n end"
] |
[
"0.63585854",
"0.6316609",
"0.62955207",
"0.6079166",
"0.6002843",
"0.59913486",
"0.58566576",
"0.58550465",
"0.5832863",
"0.5830729",
"0.58221483",
"0.5816108",
"0.575655",
"0.57521373",
"0.57018924",
"0.56737095",
"0.5645401",
"0.56193215",
"0.5561888",
"0.55011255",
"0.5491943",
"0.54600805",
"0.5448625",
"0.5444466",
"0.54295826",
"0.54236853",
"0.53764194",
"0.5366402",
"0.53591377",
"0.53506786",
"0.5337546",
"0.5324086",
"0.53147626",
"0.5294148",
"0.52932096",
"0.52837145",
"0.52460134",
"0.52252746",
"0.5204754",
"0.51936835",
"0.5116369",
"0.5115948",
"0.5109783",
"0.5094266",
"0.50937223",
"0.5083299",
"0.5079092",
"0.5078501",
"0.5067087",
"0.5038236",
"0.5030763",
"0.5024887",
"0.50228673",
"0.50136673",
"0.50103956",
"0.5000199",
"0.49988467",
"0.4996261",
"0.49862736",
"0.4984777",
"0.49840778",
"0.4971083",
"0.49695927",
"0.4966748",
"0.49598014",
"0.49571165",
"0.495065",
"0.4948914",
"0.4948068",
"0.49444562",
"0.49328735",
"0.4927141",
"0.49238712",
"0.4922747",
"0.49127027",
"0.49067253",
"0.49030328",
"0.48923427",
"0.48915067",
"0.48866352",
"0.4886227",
"0.48780397",
"0.48734587",
"0.4873321",
"0.48680064",
"0.48655778",
"0.48651984",
"0.48631665",
"0.48458746",
"0.48442608",
"0.48435384",
"0.48324528",
"0.4832076",
"0.48302957",
"0.48298186",
"0.48256004",
"0.48252302",
"0.4820346",
"0.48200303",
"0.48163602"
] |
0.6403021
|
0
|
Finds the factorial of a number
|
def factorial(num)
product = 1
while num > 1
product = product*num
num -= 1
end
product
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def factorial(number)\n\tresult = 1\n\twhile number > 0\n\t\tresult *= number\n\t\tnumber -= 1\n\tend\n\treturn result\nend",
"def factorial(number)\n if number == 0\n \treturn 1\n elsif number == 1\n \treturn 1\n end\n i=number-1\n f=number*i\n while i > 1\n \ti=i-1\n \tf=f*i\n end\n return f\nend",
"def factorial(number)\n if number <= 1\n 1\n else\n number.downto(1).reduce(:*)\n end\nend",
"def factorial(number)\n\ttotal = 1\n\tif number == 0\n\t\treturn 1\n\telse\n\t\twhile number > 1\n\t\t\ttotal *= number\n\t\t\tnumber -= 1\n\t\tend\n\t\treturn total\n\tend\nend",
"def factorial((number))\nif number == 0\n return 1\n else\n result = 1\n while number > 1\n result = result * number\n number -= 1\n end\nend\n return result\nend",
"def factorial(number)\n raise ArgumentError if number.nil?\n if number == 0 || number == 1\n return 1\n end\n\n i = 0\n result = 1\n\n while i < number\n result *= (number - i)\n i += 1\n end\n return result\nend",
"def factorial(number)\n if number == 0\n return 1\n else\n i = number-1\n while i >= 1\n number = number * i\n i = i - 1\n end\n return number\n end\nend",
"def factorial(number)\n if number == 0\n return 1\n else\n i = number-1\n while i >= 1\n number = number * i\n i = i - 1\n end\n return number\n end\nend",
"def factorial(number)\n return 1 if number == 0\n result = 1\n while number > 0\n result = result * number\n number -= 1\n end\n return result\nend",
"def factorial(number)\n if number == 0\n return 1\n else\n n = number - 1\n while n >= 1\n number *= n\n n -= 1\n end\n return number\n end\nend",
"def factorial(number)\n if number == 0 \n \treturn 1\n end\n result = 1\n while number > 0\n \tresult = result * number\n \tnumber -= 1\n end\n return result\nend",
"def factorial(number)\n\tif number == 0 || number == 1\n\t\treturn 1\n\telse\n\t\tproduct = number\n\t\twhile number > 1\n \t\t product = product*(number - 1)\n \t\t number = (number - 1)\n \t\tend\n \tend\n\treturn product\nend",
"def factorial(number)\n\tproduct = 1\n\tif number == 0\n\t\treturn product\n\telse\n\t\twhile (number > 0)\n\t\t\tproduct *= number\n\t\t\tnumber -= 1\n\t\tend\n\t\treturn product\n\tend\nend",
"def factorial(number)\n\tnumber.downto(2).inject(1) {|sum, element| sum *= element}\nend",
"def factorial(num)\n\treturn nil if num < 0\n\treturn 1 if num.equal?(0)\n\ti = 1\n\ttotal = 1\n\tnum.times do\n\t\ttotal *= i\n\t\ti += 1\n\tend\n\treturn total\nend",
"def factorial(number)\n raise ArgumentError.new(\"L'argomento deve essere un numero\") unless number.is_a?(Numeric)\n return 1 if number.zero?\n (1..number).reduce :*\nend",
"def factorial(number)\n if number\t== 0\n \treturn 1\n end \t\n result = number \n i = 1\n while i < number\n result = result * i\n i += 1 \n end\n return result\nend",
"def factorial(number)\n result = 1\n while number > 0\n result = result * number\n number -= 1\n end\n\n return result\nend",
"def factorial(number)\n result=1\n if number == 0\n return 1\n else\n while (number>0)\n result *= (number)\n number -= 1\n end\n end\nreturn result\nend",
"def factorial(number)\n number.downto(1).reduce(:*)\nend",
"def factorial(number)\n counter = number.to_i - 1\n if number.to_i == 0\n return 1\n else\n while counter > 0\n number = number * counter\n counter = counter - 1\n end\nend\nreturn number\nend",
"def factorial(num)\n if num == 0\n return 1\n else\n value = num - 1\n until value == 0\n num *= value\n value -= 1\n end\n return num\n end\nend",
"def factorial(number)\n result = 1\n while number > 0\n result *= number\n number -= 1\n end\n result\nend",
"def factorial(number)\n result = 1\n while number > 0\n result *= number\n number -= 1\n end\n result\nend",
"def factorial(n)\n return 1 if n == 0\n n.downto(1).inject do |total, n|\n total = (total * n).to_s\n total[0..total.rindex(/[1-9]/)].to_i\n end\nend",
"def factorial(number)\n result = 1\n\n while number > 1\n result = result * number\n number -= 1\n end\n\n return result\nend",
"def factorial(number)\n if number <= 1\n 1\n else\n (1..number).each.reduce(:*)\n end\nend",
"def factorial (number)\n if number == 0\n return 1\n else\n\n total = 1\n for i in 1..number\n total *= i\n i += 1\n end\n return total\n end\nend",
"def factorial(number)\n i = number\n total = number\n if number == 0 || number == 1\n return 1\n else\n while i > 1\n total=total * (i - 1)\n i -= 1\n end\n end\n return total\nend",
"def factorial(number)\n # Your code goes here\n if number == 0\n return 1\n elsif number == 1\n return 1\n end\n n = 1\n while number > 1\n n *= number\n number -= 1\n end\n return n\nend",
"def factorial(number)\n result=1\n #if number == 0\n # return 1\n else\n while (number>0)\n result *= number\n number -= 1\n end\n end",
"def factorial(number)\n i = number\n output = number\n if number == 0\n return 1\n end\n while i > 1\n output *= number-1\n number-=1\n i-=1\n end\n return output\nend",
"def factorial num\n\tfactorial = 1\n\twhile num > 0\n\t\tfactorial *= num\n\t\tnum -= 1\n\tend\n\treturn factorial\nend",
"def factorial(number)\n\tresult = 1\n\tnumber.times do |index|\n\t\tresult *= (index + 1)\n\tend\n\tresult\nend",
"def factorial(number)\r\ntotal = 1\t\r\n\twhile number != 0\r\n\t\ttotal *= number\r\n\t\tnumber = number -1\r\n\tend\r\n\ttotal\r\nend",
"def factorial(n)\n result = 1\n\n while n > 1\n result *= n\n n -= 1\n end\n\n result\n end",
"def factorial(number)\n if number == 0\n return 1\n elsif number == 1\n return 1\n elsif number > 1 \n product = number\n while number > 1 do \n number -=1\n product *= number \n end\n return product\n end \nend",
"def factorial(number)\n result = 1\n counter = number\n while counter > 0\n result *= counter\n counter -= 1\n end\n return result\nend",
"def factorial(n)\n nil if n.negative?\n\n result = 1\n while n.positive?\n result *= n\n n -= 1\n end\n puts result\n end",
"def factorial(number)\n (1..number).inject(:*) || 1\nend",
"def getFactorial(number)\n factorial = 1\n if number > 0\n for i in 1..number\n factorial *= i\n end\n end\n return factorial\n end",
"def factorial(number)\n if number == 0\n return 1\n \n elsif number == 1\n return 1\n \n elsif\n x = number\n while x != 1\n x = (x - 1)\n number = (number * x)\n end\n return number\n end\nend",
"def factorial(number)\n\ttotal = 1\n\treturn 1 if number == 0\n\tnumber.downto(2) do |n|\n\t\ttotal = total * n\n\tend\n\ttotal\nend",
"def factorial(number)\n raise ArgumentError, \"Object cannot be nil.\" if number == nil\n\n return 1 if number == 0\n\n n = number\n total = number\n (number - 1).times do\n total = total * (n - 1)\n n -= 1\n end\n\n return total\nend",
"def factorial(num)\n i = num - 1\n out = num\n while i > 0\n out = out * i \n i -= 1\n end\n return out\nend",
"def factorial(number)\n num = 1\n until number == 0\n num *= number\n number -=1\n end\n num\nend",
"def factorial(number)\n total = 1\n if number == 0\n total\n else \n while number > 0\n total *= number\n number -= 1\n end\n end\n return total\nend",
"def factorial(number)\n\treturn 1 if number == 1 \n\treturn number * factorial(number-1)\nend",
"def factorial_of num \n\t(2..num).inject(1) {|product, x| product * x }\nend",
"def get_factorial(n)\r\n total = 1\r\n while n > 1\r\n total *= n\r\n n -= 1\r\n end\r\n return total\r\nend",
"def factorial(number)\n if number == 0 \n return 1\n elsif number > 1 \n return number * factorial(number - 1)\n else\n return number\n end\nend",
"def factorial_n(num)\n result = 1\n num.times { |i| result *= i + 1 }\n result\nend",
"def factorial(num)\n if num == 0\n 1\n else\n num * factorial(num - 1)\n end\nend",
"def factorial(number)\n i = 1\n while number >= 1\n \ti *= number\n \tnumber -= 1\n end\n return i\nend",
"def factorial(number)\n if number == 0\n p 1\nelsif\n i = 1\n num = i * number\n while number > i do\n num = i * num\n i += 1\n end\n p num\n end\nend",
"def iterative_factorial(num)\n if num < 0 || !is_integer?(num)\n return Float::NAN\n elsif num == 0 || num==1\n 1\n else\n (1..num).inject(:*) || 1\n end\nend",
"def factorial(num)\n i = 1\n fact = i\n while i <= num\n fact *= i\n i += 1\n end\n return fact\nend",
"def factorial(number)\n return 1 if number <= 1\n number * factorial(number - 1)\nend",
"def factorial(number)\n raise ArgumentError if number.nil?\n return 1 if number == 0 || number == 1\n \n i = number\n until i == 1\n i -= 1\n number = number * i\n end\n return number\nend",
"def factorial(n)\n if n != 0\n return n *= factorial(n-1)\nelse\n return 1\nend\nend",
"def factorial(number)\n sum = 1\n sum.upto(number) { |i| sum *= i}\n sum\nend",
"def factorial(number)\n sum = 1\n while number > 0\n \tsum = sum * number\n \tnumber = number -1\n end\n sum\nend",
"def factorial(number)\n # =begin\n # Pseudo-code here\n # Only accepts a positive number\n # Take number and calculate factorial\n # while number >= 0\n # number*(number-1)*(number-2)*...(1)\n # outputs result\n # =end\n\n if number < 0\n return None\n end\n result = 1\n while number > 1\n result = result * number\n number = number - 1\n end\n return result\nend",
"def factorial(number)\n if !(number.is_a? Integer)\n raise ArgumentError.new(\"ArgumentError: #{number} is not an integer\")\n end\n\n result = number ** 0\n \n until number == 0\n result *= number\n number -= 1\n end\n\n return result\nend",
"def factorial(n)\n\tif n < 0\n\t\treturn nil \n\tend\n\tvalue = 1\n\twhile n > 0\n\t\tvalue = value * n \n\t\tn -= 1 \n\tend\n\treturn value \n end",
"def factorial(number)\n\tvalue = 1\n\tif number == 0 || number == 1\n\t\tvalue\n\telse\n\t\t(2..number).each {|element| value *= element}\n\t\tvalue\n\tend\nend",
"def factorial(num)\n\tif num <= 1\n\t\treturn 1\n\telse\n\t\tnum * factorial(num - 1)\n\tend\nend",
"def factorial(number)\n raise 'Only postive numbers allowed' unless number >= 0\n if number == 0 then 1 else number * factorial(number-1) end\nend",
"def factorial(number)\n result = 1\n while number >= 1\n result = result * number\n number = number - 1\n end\np result\nend",
"def factorial(number)\n if number == 0\n return 1\n elsif number == 1\n return 1\n else\n number*factorial(number-1)\n end\nend",
"def factorial(number)\n if number == 1\n return 1\n else\n return number * factorial(number - 1)\n end\nend",
"def factorial(num)\n if num == 1\n 1\n else\n num * factorial(num - 1)\n end\nend",
"def factorial(number)\n raise ArgumentError, \"number can't be nil\" if !number\n factorial = number > 1 ? number: 1\n while number >= 2\n factorial *= (number - 1)\n number -= 1\n end\n return factorial\nend",
"def factorial(number)\n product = 1\n while number > 1\n product *= number\n number -= 1\n end\n product\nend",
"def factorial (number)\n i=1\n until number == 0\n i *= number\n number -= 1\n end\n i\nend",
"def factorial(number)\n if number < 0\n return \"Error, that is not a positive integer.\"\n else\n counter = number.to_i\n end\n total = 1\n while counter > 0\n total = total*counter\n counter -= 1\n end\n return total\nend",
"def factorial(n)\r\n\tif n < 0\r\n\t\tnil\r\n\tend\r\n\r\n\tresult = 1\r\n\twhile n > 0\r\n\t\tresult = result * n\r\n\r\n\t\tn -= 1\r\n\tend\r\n\tresult\r\n\r\n\r\nend",
"def factorial(num)\n i = num -1\n output = num\n while i > 0\n output *= i\n i -= 1\n end\n return output\nend",
"def factorial(n)\n if n == 0 || n == 1 \n \treturn 1\n else\n numbers = []\n n.downto(1) { |x| numbers << x }\n numbers.inject(1) { |x,y| x * y }\n end\nend",
"def factorial(input)\n if input == 0 \n return 1\n end\n num = input - 1 \n result = input \n \n while num >= 1\n result = result * num\n num -= 1\n end\n return result\nend",
"def factorial(number)\n if number <= 1\n return 1\n else\n result = 1\n (1..number).each {|x| result = result * x}\n return result\n end\nend",
"def factorial(number)\n if number == 0\n return 1\n else\n final_factorial = 1\n\n for x in 1..number\n final_factorial = final_factorial * x\n end\n\n return final_factorial\n end\nend",
"def factorial(number)\n if number == 0 || number == 1 \n return 1\n end\n total = 1\n number.downto(1) do |x|\n total *= x\n end\n return total\nend",
"def factorial(number)\n raise ArgumentError if number == nil\n return 1 if number == 0 || number == 1\n # raise NotImplementedError\n product = number #set the product, which will be returned, as number\n x = number #set another var as same value as number to start\n until x == 1\n product *= (x-1) #multiply the prduct by itself minues 1\n x -= 1 #subtract one from x\n end\n return product\nend",
"def factorial(n)\n if n < 0\n return false\n end\n return 1\n while n > 0\n factorial_number = n * factorial_number\n n-= 1\n end\n return factorial_number\nend",
"def factorial(number)\n total = 1\n while number >= 1 do\n total *= number\n number -= 1\n end\n total\nend",
"def factorial(num)\n fact = 1\n (1..num).each { |i| fact *= i }\n return fact\nend",
"def factorial(number)\n # Your code goes here\n product = number\n if number == 0\n \tproduct = 1\n end\n while number > 1\n \tproduct = product * (number - 1)\n \tnumber = number - 1\n end\n product\nend",
"def factorial(number)\n product = 1\n while number >= 1\n product *= number\n number = number - 1\n end\n product\nend",
"def factorial(n)\n \n result = 1\n while n > 0\n result *= n\n n -= 1\n end\n \n result\nend",
"def factorial(number)\n if number\n factorial = 1\n until number == 0\n factorial *= number\n number -= 1\n end\n return factorial \n else\n raise ArgumentError\n end\nend",
"def factorial n\n if n == 0\n return 1\n end\n return (1..n).inject(:*)\nend",
"def factorial(num)\n if num <= 1\n 1\n else\n num * factorial(num-1)\n end\nend",
"def factorial(num)\n product = 1\n\n while num > 0\n product *= num\n num -= 1\n end\n \n return product\nend",
"def factorial(number)\n if number < 0\n return \"Error, that is not a positive integer.\"\n else\n counter = number.to_i\n end\n total = 1\n while counter > 0\n total = total*counter\n counter -= 1\n end\n return total\nend",
"def factorial(number)\n\tif zero_and_one(number) == true\n\t\treturn 1\n\telse\n\t\tproduct = number *factorial(number-1)\n\tend\nend",
"def getFactorial(num)\n if (num == 1)\n sum = 1\n else\n sum = getFactorial(num-1)*num\n end\n return sum\nend",
"def factorial(n)\n\tif 0 == n or 1 == n\n\t\treturn 1\n\telse\n\t\treturn n * factorial(n - 1)\n\tend\nend",
"def factorial(number)\n # Your code goes here\n if(number > 1)\n number * factorial(number-1)\n else\n 1\n end\nend",
"def factorial(nombre)\n\tn = 0\n\tresultat = 1\n\twhile n < nombre\n\t\tresultat *= n + 1\n\t\tn += 1\n\tend\n\treturn resultat\nend"
] |
[
"0.8251041",
"0.8245552",
"0.82094663",
"0.8151356",
"0.8148111",
"0.8144532",
"0.81378406",
"0.81378406",
"0.8133121",
"0.8131653",
"0.8125608",
"0.8110506",
"0.81100917",
"0.8106182",
"0.80919045",
"0.8084357",
"0.80768204",
"0.8070229",
"0.80630404",
"0.8048175",
"0.8031807",
"0.80314946",
"0.80238026",
"0.80238026",
"0.8012672",
"0.8005752",
"0.8003099",
"0.8001293",
"0.7999299",
"0.7996943",
"0.7996648",
"0.7975169",
"0.7973843",
"0.7973068",
"0.79707986",
"0.79627067",
"0.7960131",
"0.7950847",
"0.7950369",
"0.7949244",
"0.7935151",
"0.79336554",
"0.79161",
"0.7914355",
"0.7908066",
"0.7901601",
"0.7900743",
"0.7895174",
"0.7889396",
"0.78863794",
"0.78863513",
"0.7882807",
"0.7882734",
"0.7881255",
"0.78794944",
"0.7879484",
"0.7870687",
"0.7867478",
"0.7862149",
"0.78567755",
"0.7856159",
"0.7856013",
"0.78507006",
"0.78478533",
"0.78445303",
"0.78388363",
"0.7838498",
"0.7833075",
"0.78325826",
"0.7832387",
"0.7826674",
"0.78265864",
"0.7819762",
"0.7818025",
"0.78156084",
"0.78145194",
"0.7812015",
"0.7806426",
"0.78052056",
"0.7801879",
"0.78008837",
"0.7797221",
"0.7796556",
"0.77925915",
"0.7791782",
"0.779057",
"0.77902985",
"0.7787494",
"0.7786999",
"0.77812505",
"0.77785075",
"0.77772343",
"0.777681",
"0.77725",
"0.777138",
"0.77701414",
"0.7768774",
"0.77632123",
"0.7762432",
"0.7758314"
] |
0.78369
|
67
|
Verifies that product is a common multiple of every number up to num
|
def check_number(num, product)
result = true
(1..num).each do |number|
if product % number != 0
result = false
break
end
end
return result
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def check_perfect(num)\n multiples_sum = 0\n\n (1..num / 2).each do |i|\n multiples_sum += i if (num % i).zero?\n break false if multiples_sum > num # for performance issues\n end\n\n multiples_sum == num\nend",
"def multiple_of(n, x)\n x.modulo(n).zero?\n end",
"def multiple?(num, base)\n num % base == 0\n end",
"def find_smallest_common_multiple(num)\n\tprimes = find_primes_under(num)\n\tproduct = factorial(num)\n\tcounter = 0\n\twhile counter < primes.size\n\t\twhile check_number(num, product)\n\t\t\tproduct = product / primes[counter]\n\t\tend\n\t\tproduct = product * primes[counter]\n\t\tcounter += 1\n\tend\n\tproduct\nend",
"def pair_product(nums, product)\n nums.combination(2) {|pair| return true if pair[0] * pair[1] == product}\n return false\nend",
"def least_common_multiple(num_1, num_2)\n\n (1..num_2).each do |i|\n prod = num_1 * i\n return prod if prod % num_2 == 0\n end \nend",
"def pair_product(numbers, product)\n (0...numbers.length).each do |i|\n (i+1...numbers.length).each do |j|\n return true if numbers[i] * numbers[j] == product\n end\n end\n false\nend",
"def perfect_square?(num)\n (1..num).each do |n|\n product = n*n\n return true if product == num\n return false if product > num # short-circuit: too big now!\n end\n\n return false\nend",
"def mult_of_three_nums(array)\n max_num = array.max\n array.each do |x|\n array.each do |y|\n array.each do |z|\n return true if (x * y * z) == max_num\n end\n end\n end\n false\nend",
"def permuted_multiples(range)\r\n (1..Float::INFINITY).lazy.each do |n|\r\n return n if range.map { |x| n*x }.all? do |x|\r\n x.digits.sort == n.digits.sort\r\n end\r\n end\r\nend",
"def prime_sums_equal_num(num) \n count = 0\n (1..num/2).each do |primeCount| \n all_primes_under(num).repeated_combination(primeCount).each do |sums|\n if array_sum(sums) == num\n count += 1\n end\n end\n end\n count\n end",
"def multiple?(num, input_array)\n\tbad = false\n\t# check to be sure that num * [an array element] != [an array element]\n\tinput_array.each do |i|\n\t\tres = i * num\n\t\tinput_array.each do |j|\n\t\t\tif (res == j)\n\t\t\t\tbad = true\n\t\t\tend\n\t\tend\n\tend\n\t# check that num / [an array element] != [an array element]\n\t# order numbers so that a smaller number by a larger number\n\tinput_array.each do |i|\n\t\tif (i > num)\n\t\t\tres = i.to_f / num.to_f\n\t\telse\n\t\t\tres = num.to_f / i.to_f\n\t\tend\n\t\tif (res == res.to_i) # is it a whole number?\n\t\t\tinput_array.each do |j|\n\t\t\t\tif (res == j.to_f)\n\t\t\t\t\tbad = true \n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\n\treturn bad\nend",
"def pair_product(numbers, product)\n\n numbers.each_with_index do |num, i|\n (i+1...numbers.length).each {|k| return true if num * numbers[k] == product}\n end\n false\nend",
"def mult_of_three_nums(arr)\n arr.combination(3).to_a.each do |subarr|\n return true if subarr.reduce(:*) == arr.max\n end\n false\nend",
"def find_mult_3(num)\n nums = num.digits\n i = 1\n array = []\n until i > nums.count\n a = nums.permutation(i).to_a.map{ |num| num.join.to_i }\n b = a.select{|num| num != 0 && num % 3 == 0}\n array << b.uniq\n i += 1\n end\n result = array.flatten.uniq\n return [result.count, result.max]\nend",
"def pair_product(arr, n)\n arr.each_with_index do |ele, i|\n arr.each_with_index do |ele2, i2|\n if i > i2\n if ele * ele2 == n\n return true\n end\n end\n end\n end\n false\nend",
"def min_divisible_by_all(num)\r\n (1..num).inject(:lcm)\r\nend",
"def pair_product(arr, product)\n combs = arr.combination(2)\n combs.any? do |comb|\n comb.inject {|acc, num| acc * num} == product\n end\nend",
"def forms_a_pair_with(product, divisor)\n (product % divisor).zero? && (product / divisor).to_s.length == divisor.to_s.length\nend",
"def multiple_of?(multiple, number)\n multiple % number == 0\nend",
"def least_common_multiple(num_1, num_2)\n match = false \n n = 0\n while !match \n n += 1\n if n % num_1 == 0 && n % num_2 == 0\n match = true \n end \n end \n n \n\nend",
"def pair_product(nums, product)\n iterator_i = 0\n while iterator_i < nums.length\n iterator_j = iterator_i + 1\n while iterator_j < nums.length\n return true if nums[iterator_i] * nums[iterator_j] == product\n iterator_j += 1\n end\n iterator_i += 1\n end\n return false\nend",
"def pair_product(arr,num)\n arr.each_with_index do |ele, idx|\n arr.each_with_index do |e2, idy|\n if idx != idy\n if ele * e2 == num \n return true\n end\n end\n end\n end \n return false\nend",
"def pair_product(nums, prod)\n nums.each_with_index do |num, i|\n nums[i+1..-1].each do |num2|\n return true if num * num2 == prod\n end\n end\n\n false\nend",
"def anti_prime? (num)\n # make a helper, that makes an array of all factors of num [1, 2, 3, 4, 5, 6, 8, 12, 24]\n # if I compare the factors array to every array up to it, it's length should be longer.\n # range 0 to num\n\n (1...num).each do |idx|\n if factors(num).length < factors(idx).length\n return false\n end\n end\n true\nend",
"def least_product(num)\n m = 2\n 2.upto(num) do |n|\n m = m.lcm(n)\n end\n return m\nend",
"def check_product? (array, product)\n\n # Get all 3-element combos and see if any of them produce the desired product\n return array.size > 2 &&\n array.combination(3).any? { |a, b, c| a * b * c == product }\n\nend",
"def larg_palin_product\n max_product = 1\n (100...1000).each do |x|\n (100...1000).each do |y|\n max_product = x*y if (isPalindome x*y) && (x*y > max_product)\n end\n end\n max_product\nend",
"def mult_of_three_nums(arr)\n max_num = arr.max\n\n arr.each_with_index do |num, idx|\n arr.each_with_index do |num2, idx2|\n next if idx2 == idx\n arr.each_with_index do |num3, idx3|\n next if idx3 == idx2 || idx3 == idx\n return true if (num * num2 * num3) == max_num\n end\n end\n end\n false\nend",
"def mult_of_three_nums(arr)\n max_num = arr.max\n\n arr.each_with_index do |num, idx|\n arr.each_with_index do |num2, idx2|\n next if idx2 == idx\n arr.each_with_index do |num3, idx3|\n next if idx3 == idx2 || idx3 == idx\n return true if (num * num2 * num3) == max_num\n end\n end\n end\n false\nend",
"def arr_mult(arr, num)\n\n\tarr.each do |mini_arr|\n\t\t# p \"mini_arr is #{mini_arr}\"\n\t\tproduct1 = mini_arr[0]*mini_arr[1]*mini_arr[2]*mini_arr[3]\n\t\tproduct2 = (mini_arr[0]**2)*mini_arr[1]*mini_arr[2]*mini_arr[3]\n\t\tproduct3 = (mini_arr[1]**2)*mini_arr[0]*mini_arr[2]*mini_arr[3]\n\t\tproduct4 = (mini_arr[2]**2)*mini_arr[1]*mini_arr[0]*mini_arr[3]\n\t\tproduct5 = (mini_arr[3]**2)*mini_arr[1]*mini_arr[0]*mini_arr[2]\n\t\tif product1 == num\n\t\t\tp \"product1 is #{product1}\"\n\t\t\tp \"mini_arr is #{mini_arr}\"\n\t\t\treturn true\n\t\telsif product2 == num\n\t\t\t\"product2 is #{product2}\"\n\t\t\tp \"mini_arr is #{mini_arr}\"\n\t\t\treturn true\n\t\telsif product3 == num\n\t\t\t\"product3 is #{product3}\"\n\t\t\tp \"mini_arr is #{mini_arr}\"\n\t\t\treturn true\n\t\telsif product4 == num\n\t\t\t\"product4 is #{product4}\"\n\t\t\tp \"mini_arr is #{mini_arr}\"\n\t\t\treturn true\n\t\telsif product5 == num\n\t\t\t\"product5 is #{product5}\"\n\t\t\tp \"mini_arr is #{mini_arr}\"\n\t\t\treturn true\t\t\t\n\t\t\t\t\n\t\tend\n\tend\n\treturn false\nend",
"def perfect_square?(num)\n (1..num).each do |factor|\n if factor * factor == num\n return true\n end\n end\n \n return false\nend",
"def test_multiples_of_three_are_not_prime\n mults_of_three = (6..100).step(3).to_a\n\n mults_of_three.each do |x|\n assert_equal(false, @primes_container.is_prime?(x), \"#{x} caused failure\")\n end \n end",
"def find_divisor(product, number_of_digits)\n divisor = largest(number_of_digits)\n lower_bound = smallest(number_of_digits)\n\n divisor -= 1 until forms_a_pair_with(product, divisor) || divisor < lower_bound\n\n return [divisor, product / divisor] if forms_a_pair_with(product, divisor)\n\n false\nend",
"def multiple_of_any_base?(num, base_numbers)\n base_numbers.each do |base|\n return true if multiple?(num, base)\n end\n return false\n end",
"def pair_product(arr, product)\n arr.each_with_index do |num_1, idx_1|\n arr.each_with_index do |num_2, idx_2|\n return true if num_1 * num_2 == product && idx_2 > idx_1\n end\n end\n false\nend",
"def check_compositions(n, k, i_min = 0, i_max = nil)\n i_max ||= Math.log2(n + 1).ceil.to_i\n span = i_max - i_min\n candidates = radix_sequence(k, span)\n count = 0\n candidates.each do |exponents|\n # p(exponents.map { |i| 2**i }) if exponents.map { |i| 2**i }.sum == n\n count += 1 if exponents.map { |i| 2**(i_min + i) }.sum == n\n end\n count\nend",
"def lcm_1_to_n (num)\n answer = 1\n answer_factors = Hash.new(0) #key is prime factor, val is number of occurences\n (0..num).each do |x|\n f = 2 #start with first possible prime factor\n x_factors = Hash.new(0)\n\n #find prime factors for x\n while (x >= f)\n while (x % f == 0)\n x_factors[f] += 1\n x /= f\n end\n f += 1\n end\n\n #the answer must have as many occurrences of each prime factor as each\n #individual number (1..num).\n x_factors.each do |factor, occurrences|\n if (occurrences > answer_factors[factor])\n answer_factors[factor] = occurrences\n end\n end\n end\n\n #answer_factors has correct factors. Multiply them for the answer\n answer_factors.each do |factor, occurrences|\n occurrences.times do\n answer *= factor\n end\n end\n answer\nend",
"def pair_product(arr, num)\n arr.each_with_index do |ele1, i|\n arr.each_with_index do |ele2, j|\n return true if i < j && ele1 * ele2 == num\n end\n end\n\n false\nend",
"def pair_product(arr, prod)\n \n arr.each.with_index do |num1, idx1|\n arr.each.with_index do |num2, idx2|\n if idx2 > idx1 && num1 * num2 == prod\n return true\n end\n end\n end\n\n false\nend",
"def test_multiples_of_two_are_not_prime\n mults_of_two = (4..100).step(2).to_a\n \n mults_of_two.each do |x|\n assert_equal(false, @primes_container.is_prime?(x), \"#{x} caused failure\")\n end\n end",
"def pair_product(arr, product)\n (0...arr.length).each do |idx_1|\n (idx_1+1...arr.length).each do |idx_2|\n return true if (arr[idx_1] * arr[idx_2]) == product\n end\n end\n return false\nend",
"def least_common_multiple(num_1, num_2)\n num_1, num_2 = [num_1, num_2].sort\n\n (1..num_2).each do |i|\n mutiple_1 = num_1 * i\n\n return mutiple_1 if mutiple_1 % num_2 == 0\n end\nend",
"def better_solution_to_multiples\n set.to_a.combination(2) do |number, number1|\n remainder = TOTAL - number - number1\n\n if set.include?(remainder)\n puts remainder * number * number1\n break\n end\n end\n end",
"def sample\n\n\tfor num in 1..100\n\t\tsum = 0\n\n\t\tfor j in 1..num-1\n\n\t\t\tif( num % j == 0 ) \n\t\t\t\tsum = sum + j\n\t\t\tend\n\n\t\tend\n\t\t\n\t\tif( sum == num ) \n\t\t\tputs \"perfect number : #{num}\"\n\t\tend\n\n\tend\n\nend",
"def least_common_multiple(num_1, num_2)\n multiple = 1\n multiple += 1 until multiple % num_1 == 0 && multiple % num_2 == 0\n multiple\nend",
"def perfect_square?(num)\n (1..num).each do |factor|\n if factor * factor == num\n return true\n end\n end\n return false\nend",
"def pair_product(arr, product)\n (0...arr.size).each do |i|\n (i + 1...arr.size).each do |j|\n return true if arr[i] * arr[j] == product\n end\n end\n false\nend",
"def power_of_two?(num)\n product = 1\n\n while product < num \n product *= 2\n end \n\n product == num \nend",
"def least_common_multiple(num_1, num_2)\n number = 1\n while ((number % num_1 != 0) || (number % num_2 != 0))\n number +=1\n end\n number\nend",
"def perfect_square?(num)\n (1...num).each{|ele| return true if ele * ele == num }\n false\nend",
"def perfect_square?(num)\n (1..num).each do |p|\n if p * p == num\n return true\n end\n end\n return false\nend",
"def multipleOfX? num, x\n\tif num % x == 0\n\t\treturn true\n\tend\nend",
"def prime_products(n)\n i = 2\n product = 1\n while i < n\n product *= i if i.prime?\n i += 1\n end\n product\nend",
"def digit_factorial_equal(max)\n solutions = []\n (3..max).each do |num|\n solutions << num if num == digit_factorial_sum(num)\n end\n puts solutions.inject(:+)\nend",
"def pair_product(numArr, product)\n numArr.each_with_index do |num, i|\n numArr.each_with_index do |num2, j|\n return true if j > i && (num * num2) == product\n end\n end\n false\nend",
"def divisible_by_mult?(number, *args)\n args.all? { |arg| divisible_by(number, arg) }\nend",
"def mult_of_three_nums(array)\n maximum = array.max\n combinations = []\n count = array.size\n count.times do |idx1|\n count.times do |idx2|\n count.times do |idx3|\n unless idx1 == idx2 || idx2 == idx3 || idx1 == idx3\n combinations << [array[idx1], array[idx2], array[idx3]]\n end\n end\n end\n end\n !!(combinations.detect{ |sub_array| sub_array.reduce(:*) == maximum})\nend",
"def least_common_multiple(num_1, num_2)\n value = [num_1, num_2].max\n while (value % num_1 != 0) || (value % num_2 != 0)\n value += 1\n end\n return value\nend",
"def least_common_multiple(num_1, num_2)\n larger_num = [num_1, num_2].max\n smaller_num = [num_1, num_2].min\n i = 1\n done = false\n until done\n if (i * larger_num) % smaller_num == 0\n answer = i * larger_num\n done = true\n end\n i += 1\n end\n answer\nend",
"def isMultiple(a, b, n)\n fractional_part = (a.to_f/b.to_f).round(1).to_s[-1].to_i\n return false if fractional_part <= 0\n fractional_part % n == 0 ? true : false\nend",
"def power_of_two?(num)\n product = 1\n while product < num\n product *= 2\n end\n\n num == product\nend",
"def bi_prime?(num)\n prime_nums = (0..num).select { |i| prime?(i) } \n\n prime_nums.any? do |prime_1|\n prime_nums.any? do |prime_2|\n prime_1 * prime_2 == num\n end\n end\nend",
"def mult_of_three_nums(arr)\n subarr = []\n max = arr.max\n 0.upto(arr.length - 3) do |first_num|\n 1.upto(arr.length - 2) do |second_num|\n 2.upto(arr.length - 1) do |third_num|\n return true if ((arr[first_num] * arr[second_num] * arr[third_num] == max) && (third_num > second_num) && (second_num > first_num))\n end\n end\n end\n return false\nend",
"def bi_prime?(num)\n prime_factors = []\n (2...num).each do |factor|\n if num % factor == 0\n prime_factors << factor if prime?(factor) # could use Prime class...do this for practice\n end\n end\n\n # do any of our prime factors have our num param as a product\n (0...prime_factors.length).each do |i|\n (i...prime_factors.length).each do |j|\n return true if (prime_factors[i] * prime_factors[j]) == num\n end\n end\n false\nend",
"def is_multiple?(num1, num2)\n num1 % num2 == 0\nend",
"def test_numbers_with_divisors_are_not_prime\n seed_array = (4..150).step(1).to_a\n seed_array.each do |x|\n x_square = Math.sqrt(x)\n for i in 4..x_square \n if x % i == 0\n assert_equal(false, @primes_container.is_prime?(x), \"#{i} caused failure #{x % i}\")\n end\n end\n end\n end",
"def Contained_Multiples(num1, num2)\n\tproduct_collection = []\n\tnum1_multiplier = 1\n\tnum2_multiplier = 1\n\n\t#multiply each by an increasing number until the product is larger than 1000\n\t#place each of those products into a product collection\n\twhile num1 * num1_multiplier < 1000 \n\t\tproduct_collection << num1 * num1_multiplier\n\t\tnum1_multiplier += 1\n\tend\n\n\twhile num2 * num2_multiplier < 1000\n\t\tproduct_collection << num2 * num2_multiplier\n\t\tnum2_multiplier += 1\n\tend\n\t\n\t#add each number in the product collection together to get a sum\n\tproduct_collection.inject(\"+\")\nend",
"def problem3(num)\n prime = num\n while num%2==0 do num/=2 end\n (3..Math.sqrt(num).to_i).step(2).each { |pf|\n break if num < pf\n while num%pf==0 do\n num/=pf\n prime = pf\n end\n }\n prime\nend",
"def prime_checker(num)\n digits = num.to_s.chars\n permutations = digits.permutation(digits.size).map { |n| n.join.to_i }.uniq\n # permutations.reject! { |num| num.to_s.size < digits.size }\n permutations.each do |permutation|\n return 1 if prime?(permutation)\n end\n 0\nend",
"def anti_prime?(num)\n (1...num).none? { |before| factors(before).length > factors(num).length}\nend",
"def anti_prime?(targ)\n amount = num_factors(targ)\n (1...targ).all? { |i| amount > num_factors(i) }\nend",
"def contains_pair_product?(arr, target)\n arr.each_with_index do |num1, idx1|\n arr.each_with_index do |num2, idx2|\n if (idx2 > idx1) && (num1 * num2 == target)\n return true\n end\n end\n end\n\n return false\n\nend",
"def pass?(num)\n (2..20).each do |factor|\n return false unless (num % factor).zero?\n end\n true\nend",
"def lcm(nums)\n # get prime factors of each num\n if nums.include?(0)\n return 0\n end\n\n pfs = prime_factorise(nums).uniq\n baseprimes = []\n\n # Extract all common primes, starting with 2\n $primes.each do |p|\n most_p = 0\n pfs.each do |pf|\n new_most_p = pf.count { |x| x == p }\n if new_most_p > most_p\n most_p = new_most_p\n end\n end\n most_p.times do\n baseprimes.push(p)\n end\n end\n\n puts baseprimes.to_s\n\n # multiply out\n baseprimes.reduce(:*)\nend",
"def is_perfect_square(num)\n return true if num < 2\n\n x = num / 2\n x = (x + num / x) / 2 while x * x > num\n\n x * x == num\nend",
"def pair_product(arr, prod)\n\n pairs(arr).any? {|pair| pair.inject(&:*) == prod}\n\n\nend",
"def least_common_multiple(num_1, num_2)\n new_array = [num_1, num_2]\n max_num = new_array.max\n\n (1...max_num).each do |i|\n (1...max_num).each do |i2|\n if num_1 * i == num_2 * i2\n return num_1 * i\n end\n end\n end\nend",
"def pair_product?(arr, target_product)\r\n\r\n i = 0\r\n while i < arr.length\r\n\r\n j = i+1\r\n while j < arr.length\r\n\r\n if arr[i]*arr[j] == target_product\r\n return true\r\n else\r\n return false\r\n end\r\n\r\n j += 1\r\n end\r\n\r\n i += 1\r\n end\r\nend",
"def multiples(num)\n (1...num).select { |n| n % 3 == 0 || n % 5 == 0 }.inject(:+)\nend",
"def smallest_common_multiple(n)\n\n\treturn 0\nend",
"def sum_to_n?(array, n)\n array.product(array).any? {|couple| sum(couple) == n}\nend",
"def perfect_square?(num)\n (1..num).each do |fact|\n return true if fact*fact == num\n end\n return false\nend",
"def multisum(num)\n multiples_3_and_5 = (1..num).to_a.map do |n|\n n if (n % 3).zero? || (n % 5).zero?\n end\n multiples_3_and_5.compact.inject(:+)\nend",
"def euler29(n)\n terms = []\n 2.upto(n) do |i|\n 2.upto(n) do |j|\n if terms.include?(i ** j) == false\n terms << i ** j\n end\n end\n end\n \n terms.length\nend",
"def abundant?(num)\n\n factors = []\n (1...num).each do |int|\n if num % int == 0\n factors << int\n end\n end\n\n sum_of_factors = factors.reduce(:+)\n\n if sum_of_factors > num\n return true\n end\n\n false\n\nend",
"def pair_product(array, product)\n (0...array.length).each do |i|\n (i + 1...array.length).each do |j|\n return true if array[i] * array[j] == product\n end\n end\n false\nend",
"def lcm(*nums)\n nums = nums.collect { |n| [* n] }.flatten.sort.reverse\n p_facs = []\n primes = Prime.new\n max = nums.first\n while (p = primes.next) and max > p\n while nums.detect { |n| (n % p).zero? }\n p_facs << p\n nums = nums.collect { |n| (n % p).zero? ? n / p : n }\n end\n end\n nums.each { |n| p_facs << n if n > 1 }\n p_facs.inject(1) { |l, n| l * n }\nend",
"def pretentious_primes(arr, num)\nend",
"def pair_product(array, product)\n (0...array.length).each do |i|\n (i + 1...array.length).each do |j|\n return true if array[i] * array[j] == product\n end\n end\n\n false\nend",
"def bi_prime?(num)\n arr = []\n (2...num).each do |i|\n if is_prime?(i) \n arr << i \n end\n end\n (0...arr.length).each do |first|\n (first...arr.length).each do |second|\n if arr[first] * arr[second] == num\n return true \n end\n end\n end\n false\nend",
"def anti_prime?(num)\n num_fact_len = factors(num).length\n\n (2...num).each do |n|\n n_fact_len = factors(n).length\n if n_fact_len > num_fact_len\n return false\n end\n end\n\n return true\nend",
"def smallest_multiple\n 9*16*5*7*11*13*17*19\nend",
"def least_common_multiple(num_1, num_2)\n max = (num_1 * num_2) \n (1..max).each do |n|\n if n % num_1 == 0 && n % num_2 == 0 \n return n\n end\n end\nend",
"def factor_primes n\n a=1;b=1\n while a < n do\n a=a+1\n next if not n.modulo(a).zero? or a == b\n b=b*a\n puts \"a=#{a};b=#{b}\"\n break if b == n\n end\nend",
"def pair_product?(arr, target_product)\n arr.each_with_index do |element, index|\n arr.each_with_index do |element2, index2|\n if index != index2 && element * element2 == target_product\n return true\n end\n end\n end\n return false\nend",
"def least_common_multiple(num_1, num_2)\n (1...num_1 * num_2).each do |num|\n if num % num_1 == 0 && num % num_2 == 0\n return num\n end\n end\nend",
"def anti_prime?(num) #24 => 1,2,3,4,6,8,12,24 => 8 #22 => 1,2,11,22 = > 4\n (1.upto(num-1)).none? { |n| factor_count(n) >= factor_count(num) }\nend",
"def is_abundant?(num)\n return false if proper_divs(num).length == 0\n return true if proper_divs(num).inject(:+) > num\n return false\nend",
"def armstrong? num\n n = num.length\n num.chars.inject(0) { |sum,d| sum + (d.to_i ** n) } == num.to_i\nend"
] |
[
"0.7245897",
"0.7108705",
"0.6874142",
"0.68720376",
"0.6817972",
"0.6805568",
"0.6805244",
"0.67951924",
"0.67475176",
"0.6743969",
"0.67405343",
"0.67225254",
"0.6716327",
"0.67162025",
"0.67034566",
"0.6678607",
"0.66688037",
"0.6667505",
"0.6648071",
"0.6639418",
"0.66376776",
"0.66314894",
"0.6626523",
"0.6623681",
"0.661886",
"0.6609137",
"0.660056",
"0.65877247",
"0.6587636",
"0.6587636",
"0.6566709",
"0.6556454",
"0.6555443",
"0.6550828",
"0.65407205",
"0.6522322",
"0.6515174",
"0.65036327",
"0.65014344",
"0.64992857",
"0.64950037",
"0.6491581",
"0.64807206",
"0.6477496",
"0.6475484",
"0.6470382",
"0.64690214",
"0.6464496",
"0.6459545",
"0.6437357",
"0.64328617",
"0.64227647",
"0.641909",
"0.6415235",
"0.64131176",
"0.6404424",
"0.63957304",
"0.6393794",
"0.63874763",
"0.6383959",
"0.63824946",
"0.6376003",
"0.63658273",
"0.6344592",
"0.63442457",
"0.634418",
"0.6334581",
"0.6333413",
"0.6329065",
"0.63259184",
"0.6321328",
"0.63181317",
"0.63115525",
"0.6311329",
"0.63107455",
"0.6310654",
"0.63077223",
"0.6306945",
"0.6305727",
"0.6304848",
"0.6294444",
"0.6284487",
"0.62793595",
"0.62744945",
"0.62700546",
"0.6263624",
"0.62620395",
"0.6257346",
"0.6257248",
"0.62527573",
"0.62484425",
"0.6247333",
"0.62465996",
"0.6241641",
"0.6237484",
"0.62216103",
"0.6219386",
"0.6218045",
"0.62120193",
"0.6204868"
] |
0.7446986
|
0
|
Returns a list of primes under num
|
def find_primes_under(num)
primes = [2]
counter = 3
while primes[-1] < num
counter2 = 2
while counter2 <= counter
if counter % counter2 == 0
break
elsif
counter2 * counter2 > counter
primes << counter
break
end
counter2 += 1
end
counter += 1
end
primes[0..-2]
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def primes_less_than(num)\n\toutput = []\n\t(2...num).each do |n|\n\t\toutput << n if is_prime?(n)\n\tend\n\toutput\nend",
"def primes_less_than(num)\n require 'prime'\n arr = []\n Prime.each(num) do |prime| arr.push(prime)\n end\n num.prime? ? arr.pop : arr\n return arr\n end",
"def primes_less_than(num)\n res = []\n (2...num).each do |i|\n res.push(i) if is_prime?(i) == true\n end\n res\nend",
"def primes_less_than(num)\n arr = []\n (2...num).each do |el|\n if is_prime?(el)\n arr << el\n end\n end\n arr\nend",
"def primes_less_than (num)\n arr=[]\n for n in 2..(num-1)\n if is_prime?(n)\n arr.push(n)\n end\n end\n p arr\n return arr\nend",
"def primes(num)\n\twhole_array = (2..num).to_a\n\tprime_array = [whole_array.shift]\n\n\tuntil whole_array == []\n\t\twhole_array.delete_if { |x| x % prime_array.last == 0 }\n\t\tprime_array << whole_array.shift\n\tend\n\tprime_array\nend",
"def get_primes num\n primes = []\n for i in 0 ... num do\n if check_prime?(i) == true\n primes.push(i)\n end\n end\n p primes\nend",
"def prime_numbers(num)\n all_factors = factors(num)\n only_prime = []\n i = 0\n while i < all_factors.length\n if prime?(all_factors[i])\n only_prime += all_factors[i]\n end\n i += 1\n end\n only_prime\n end",
"def pick_primes(numbers)\n\tprimes = []\n \tnumbers.each do |num| \n \tif isPrime(num) \n \tprimes.push(num)\n end\n end\n \treturn primes\nend",
"def prime_list(number_of_primes)\n return [] if number_of_primes < 1\n prime_numbers = Array.new\n for num in 2..9999999 do\n if is_prime_num(num, prime_numbers)\n prime_numbers.push(num)\n break if prime_numbers.length == number_of_primes\n end\n end\n return prime_numbers\n end",
"def all_primes(number)\n primes = []\n (2...number).each do |num|\n if prime?(num)\n primes << num \n end\n end\n primes\nend",
"def pretentious_primes(arr, num)\n new_arr = []\n if num > 0\n arr.each do |ele|\n i = ele + 1\n count = 0\n while true\n if is_prime?(i)\n count += 1\n end\n if count == num\n new_arr << i\n break\n end\n i += 1\n end\n end\n else\n num = -1 * num\n end\n new_arr\nend",
"def primes()\n return [] if @number < 2\n # build Boolean array to use for sieve with buffer to align indices\n sieve_array = Array.new(2, false) + Array.new(@number-1, true)\n # perform Sieve of Eratosthenes eliminations\n (2..Math.sqrt(@number).to_i).each do |i|\n (i**2..@number).step(i) {|j| sieve_array[j] = false} if sieve_array[i] == true\n end\n # return numbers by corresponding index that are still true\n (2..@number).collect {|index| index if sieve_array[index] == true}.compact\n end",
"def primes\n\t\t# primes = []\n\t\t# primes << 2\n\t\tprimes = [2] # combined previous two lines\n\t\tx = 3\n\n\t\tloop do\n\t\t\tbreak if primes.length == @n_primes # End loop when desired number has been calculated\n\t\t# while primes.length < @n_primes # Alternative 1 to loop do, break\n\t\t# until primes.length == @n_primes # Alternative 2 to loop do, break\n\t\t\ty = 3\n\t\t\ty += 2 until x % y == 0 # Loop to test if x is divisible by any odd number below it, y\n\t\t\tprimes << x if x == y # If the (odd) number was not divisible by any (odd) below itself, it is a prime\n\t\t\tx += 2\n\t\tend\n\n\t\treturn primes\n\tend",
"def get_primes\n j = 0\n\n while j < @limit \n prime_number = is_prime\n if prime_number\n @prime_numbers.push(prime_number)\n j += 1\n end\n @count += 1\n end\n\n return @prime_numbers\n end",
"def prime(number)\n prime_numbers = []\n (2..number).each do |current_number|\n if is_prime? current_number\n prime_numbers << current_number\n end\n end\n return prime_numbers\nend",
"def find_prime_numbers(num)\n\tarr =[]\n (2..num).each{|x| arr.push(x)}\n\n i = 0\n p = arr[i]\n\n while p != arr[-1]\n\t arr.delete_if{|n| n%p == 0 && n != p}\n\t i+= 1\n\t p = arr[i]\n end\n return arr\nend",
"def primes\n range = (min..max).to_a\n primes = (min..max).to_a\n\n range.each do |mod|\n primes.delete_if do |num| \n composite?(num, mod) unless num == mod\n end\n range = primes\n end\n primes\n end",
"def primes\n return [] if max_prime < 2\n\n candidates.each do |prime,_|\n # skip numbers we already know NOT to be prime (from previous iterations)\n next if candidates[prime] != :prime\n\n # find the prime number candidates greater than the current prime number\n candidates.select { |n,_| candidates[n].eql?(:prime) && n > prime }\n .each do |num,_|\n # mark numbers evenly divisible by the current prime as NOT PRIME\n @candidates[num] = :not_prime if (num % prime) == 0\n end\n end\n\n # convert numbers still marked as prime to an array of numbers\n candidates.map { |num,value| num if value.eql? :prime }.compact\n end",
"def primes\n return [] if self == 0\n return \"don't do that\" if self < 0\n list = [2]\n test = 3\n until list.length == self\n list << test if test.is_prime?\n test += 2\n end\n list\n end",
"def get_primes limit\n\tnums = (1...limit).select { |n| n.prime? }\n\n\tp nums\nend",
"def isPrime(number)\n\t\tdivisores=[]\n\t\t1.upto(number){|num| \n\t\t\tif (number % num == 0 )\n\t\t\t\tdivisores.push num\n\t\t\tend\t\t\n\t\t}\n\t\treturn divisores\n\tend",
"def primes (number)\n primes_array = []\n Prime.each(number) do |p|\n primes_array.push(p)\n end\n\n primes_array\nend",
"def primes_less_than number\n ps = (2..number).each\n primes_so_far = []\n enum = Enumerator.new do |y|\n loop do\n p = ps.next\n non_prime = false\n\n p_root = (p**0.5).floor\n # Filter for primes using an inverted version of the sieve of\n # Eratosthenes--a number is prime if it's not divisible by the primes\n # less than it's square root.\n primes_so_far.each {|prime|\n if prime > p_root\n # if p has no divisors in primes_so_far less than p^0.5\n # then p must be prime\n break\n elsif p % prime == 0\n # the current p is not prime\n non_prime = true\n break\n end\n }\n\n unless non_prime\n primes_so_far.push p\n y.yield p\n end\n end\n end\n\n enum.to_a\n\nend",
"def primes(num)\n \nend",
"def primes(num)\n \nend",
"def primes(num)\n \nend",
"def primes(num)\n \nend",
"def prime_factors(num)\n\tprimeFactors = []\n \t\n \t(1..num).each do |i|\n \tif num % i == 0 && isPrime(i)\n \tprimeFactors.push(i)\n end\n end\n \n \treturn primeFactors\nend",
"def prime_factors(num)\n array = []\n (1..num).each do |number|\n array << number if prime?(number) && num % number == 0\n end\n array.sort!\nend",
"def get_primes(limit)\n primes = []\n (2...limit).each do |number|\n primes << number if is_prime?(number)\n end\n primes\nend",
"def primes_less_than(n)\n arr = []\n n-=1\n while n>1 do\n if is_prime?(n)\n arr << n\n end\n n-=1\n end\n arr.sort\nend",
"def prime_factors(num)\n prime_facts = []\n \n (1..num).each do |i|\n if num % i == 0 && prime?(i)\n prime_facts << i\n end\n end\n \n return prime_facts\n end",
"def prime_factorization(num)\n return [num] if is_prime?(num)\n prime_fact = []\n (2..num).each do |n|\n return [n] + prime_factorization(num / n) if num % n == 0\n end\n prime_fact\n end",
"def collect_primes(number)\n \n sieve = [nil, nil] + (2 .. number).to_a\n \n (2 .. Math.sqrt(number)).each do |n|\n next unless sieve[n]\n (n*n).step(number, n) do |num|\n sieve[num] = nil\n end\n end\n \n primes = []\n sieve.each do |x|\n if x != nil\n primes << x\n end\n end\n return primes\nend",
"def primes(max)\n primes = []\n number = 2\n \n while number <= max\n primes << number if is_prime? number\n number += 1\n end\n primes\nend",
"def primes(max)\n primes = []\n number = 2\n \n while number <= max\n primes << number if is_prime? number\n number += 1\n end\n primes\nend",
"def prime_factors(num)\n arr = []\n (1...num).each do |number|\n if is_prime(number) && num % number == 0\n arr << number\n end\n end\n return arr\nend",
"def prime_factors(num)\n require \"prime\"\n primes = []\n Prime.each{|prime| primes << prime if num % prime ==0 ; break if prime > num }\n primes\nend",
"def pretentious_primes(arr, num)\nend",
"def prime_factors(num)\n arr = []\n\tPrime.each(num) { |prime| num % prime == 0 ? arr.push(prime) : false }\n return arr\nend",
"def prime_factorization(num)\n return [] if num < 2\n\n # get all primes up to num recursively\n primes_factors = prime_factorization(num - 1)\n if prime?(num)\n primes_factors << num\n end\n\n primes_factors\nend",
"def exclude_prime_numbers\n numbers = (1..100).to_a\n\n #=> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]\nend",
"def prime_factors(num)\n\tfactors(num).select { |n| prime?(n) }\nend",
"def primes_up_to(num)\n\n\tcross_limit = Math.sqrt(num).floor\n\n\t# create a new array with num number of elements, each set as true\n\tprime_bools = Array.new(num, true)\n\n\tprime_bools.each_with_index do |is_prime, i|\n\t\t# we can stop once our steps are at the square root of the limit\n\t\tbreak if i >= cross_limit\n\n\t\t# skip first step (0+0+1 steps over everything) and\n\t\t# non-prime steps, as they're redundant\n\t\tnext if i == 0 || !is_prime\n\n\t\t# set each bool we step over to false, starting at i+i+1, which\n\t\t# ensures we keep the first primes true \n\t\t(i+i+1 .. num).step(i+1) { |i| prime_bools[i] = false }\n\t\t# puts \"removed #{i+1}s #{prime_bools.each_index.select { |i| prime_bools[i] }.map { |j| j+1 }.drop(1)}\"\n\tend\n\n\t# select all the remaining trues from prime_bools\n\tprime_bools = prime_bools.each_index.select { |i| prime_bools[i] }\n\n\t# map the prime_bools to their index/number and drop the 1 (not a prime)\n\tprimes = prime_bools.map { |i| i+1 }.drop(1)\n\nend",
"def pick_primes(numbers)\n numbers.select { | n | is_prime(n) }\nend",
"def pick_primes(numbers)\r\n return numbers.select { |num| prime?(num)}\r\nend",
"def pick_primes(numbers)\n return numbers.select { |num| prime?(num)}\nend",
"def pick_primes(numbers)\n numbers.select { |num| prime?(num) }\nend",
"def prime_factors(num)\n factors = factors(num)\n result = []\n factors.each do |fac|\n if prime?(fac)\n result << fac\n end\n end\n result\nend",
"def getPrimes()\n oldlimit = $primelimit + 1\n $primelimit *= 2\n\n for i in oldlimit...$primelimit\n isPrime = true\n $primes.each do |p|\n if i % p == 0\n isPrime = false\n break\n end\n end\n if isPrime\n $primes << i\n end\n end\n\nend",
"def prime_factors(num)\n arr = []\n (1..num).each { |n| arr << n if num%n==0 && prime?(n)}\n return arr\nend",
"def divisors(num)\n divisors_results = [] \n 2.upto(num - 1) do |n|\n divisors_results << n if num % n == 0\n end\n return \"#{num} is prime\" if divisors_results.empty?\n divisors_results\nend",
"def largest_prime(num)\n\tresult = []\n\ti = 2\n\twhile i <= num\n\t\tif is_prime?(i)\n\t\t\tif num % i == 0 # Check for whole number if % by i \n\t\t\t\tnum = num / i # Update the num\n\t\t\t\tresult << i # Add i to the array\n\t\t\t\ti = 2 # Reset i to 2\t\n\t\t\tend\t\n\t\tend\n\t\ti += 1\t\n\tend\n\tresult\nend",
"def prime_set(n)\n\t\tprimes_arr =[]\n\t\ti = 1\n\t\t# keep inserting prime numbers into array until its length is equal to 'n'\n\t\tuntil primes_arr.count == n\n\t\t\tif is_prime(i) == true \n\t\t\t\tprimes_arr << i \n\t\t\tend \n\t\t\ti+=1\n\t\tend \n\t\tp primes_arr\n\tend",
"def prime_factorization(num)\n primes = [] \n i = 2 \n while num != 1\n while num % i == 0\n if is_prime?(i) \n num = num / i \n primes << i \n else\n i += 1 \n end \n end\n i += 1 \n end\n primes\nend",
"def prime_factors(num)\n arr = (2..Math.sqrt(num).round).to_a\n primes = arr.each do |i|\n arr.select! {|j| j%i != 0 or j==i}\n end\n pfacts = primes.select {|i| num%i == 0}\n\n return [num] if pfacts.empty?\n return pfacts\nend",
"def prime?(num)\n if num <= 1\n false\n elsif num == 2 || num == 3\n true\n elsif num > 3\n list_array = (2..num-1).to_a\n list_array.none? { |i| num % i == 0 }\n end\nend",
"def primes(max)\n array = []\n i = 2\n while i < max.abs\n if is_prime?(i)\n array << i\n end\n i += 1\n end\n array\nend",
"def primes (n)\n return (1..n).select { |x| x.prime? }\nend",
"def listOfPrimesUnderX (x)\n\n#Generate list of numbers 2 through x\n\nnumberList = []\nnumberList = (2..x).to_a\n\n# Create a loop that, first, removes the first number's multiples from numberList\n# and that loops up to the square root of x\n\nprimeList = []\n\n\nwhile numberList[0] < Math.sqrt(x)\n\n\tprimeList << numberList[0]\n\ty = numberList[0]\n\n\tnumberList.delete_if {|a| a % y == 0}\n\nend\n\n# now we have two arrays: primeList, which contains all primes up to the square root of x, and numberList\n# which contains primes between the square root of x and x\n# first we combine them to a single array, primeList, which contains all primes up to x\n\nprimeList = primeList + numberList\n\nreturn primeList\n\nend",
"def find_primes(number)\n\tprimes = []\n\ttry_num = 2\n\tx = 2\n\tfactors = []\n\t\n\twhile primes.length != number\n\t\t#puts \"primes : #{primes}\"\n\t\t#puts \"try_num : #{try_num}\"\n\t\t#puts \"x : #{x}\"\n\t\t#puts \"factors : #{factors}\"\n\t\t\n\t\tif factors.length >= 1 && factors[0] != try_num\n\t\t\t#puts \"#{try_num} is not prime\"\n\t\t\ttry_num += 1\n\t\t\tx = 2\n\t\t\tfactors = []\n\t\t \n\t\telsif try_num % x == 0 && x == try_num\n\t\t\t#puts \"#{try_num} is prime\"\n\t\t\tprimes << try_num\n\t\t\ttry_num += 1\n\t\t\tx = 1\n\t\t\n\t\telsif try_num % x == 0\n\t\t\t#puts \"#{x} is factor of #{try_num}\"\n\t\t\tfactors << x\n\t\telse\n\t\t\n\t\tend\n\t\t\n\t\tx += 1\n\tend\n\tputs primes\n\treturn primes\nend",
"def prime_factors(num)\n\tfactors = []\n\tfactor = 2\n\tremainder = num\n\n\twhile (remainder > 1) && (factor <= num)\n\t\twhile (remainder % factor == 0)\n\t\t\tfactors << factor\n\t\t\tremainder /= factor\n\t\tend\n\n\t\tfactor += 1\n\tend\n\tfactors\nend",
"def prime_factors(num)\n all_factors = factors(num)\n output_arr = []\n\n all_factors.each do |el|\n if prime?(el)\n output_arr << el\n end\n end\n\n output_arr.sort\nend",
"def find_primes(num,prime_array=[])\n i = 2\n until num % i == 0 \n i += 1\n end\n prime_array << i\n return prime_array if num == i\n find_primes(num/i, prime_array) \nend",
"def primes_under(n)\n candidates = (3..n).step(2).to_a\n primes = [2]\n\n until primes.last > n ** 0.5\n primes << candidates.shift\n candidates.reject! {|candidate| candidate % primes[-1] == 0}\n end\n\n primes + candidates\nend",
"def primes_to_n n\n non_primes = []\n non_primes[1] = 1\n (2..(n/2)).each do |factor|\n ((factor*2)..n).step(factor).each do |multiple_of_factor|\n non_primes[multiple_of_factor] = 1\n end\n end\n (1..n).reject {|i| non_primes[i]}\nend",
"def primes(n)\n result = []\n i = 2\n while i <= n\n j=2\n prime = true\n while j<=i**0.5\n (prime = false) if i%j==0\n j += 1\n end\n (result << i) if prime\n i +=1\n end\n return result\nend",
"def prime_numbers\n s = (0..self).to_a\n s[0] = s[1] = nil\n s.each do |p|\n next unless p\n break if p * p > self\n (p*p).step(self, p) { |m| s[m] = nil }\n end\n s.compact\n end",
"def primes(top)\n n = 2\n primes = []\n loop do\n primes << n if (2..Math.sqrt(n)).all? {|x| n % x != 0 }\n return primes.last if primes.count == top\n n += 1\n end\nend",
"def prime_factors(num)\n primes = (2..num).select { | n | isprime?(n) }\n primes.select { |prime| num % prime == 0 }\nend",
"def prime_factors(num)\n prime_facts = []\n\n (1..num).each do |i|\n if num % i == 0 && prime?(i)\n prime_facts << i\n end\n end\n\n return prime_facts\nend",
"def find_primes_magic_value(magic_number)\n @primes = []\n number = 2\n while magic_number > 1\n if magic_number % number == 0\n magic_number /= number\n @primes << number\n end\n number += 1\n end\n\n end",
"def select_primes(possible_primes)\n possible_primes.select { |num| is_prime?(num) }\nend",
"def prime_factors(num)\n facs = factors(num)\n p_facs = []\n facs.each{|n| p_facs.push(n) if prime?(n)}\n p_facs\nend",
"def print_all_primes(num)\n for i in (2..num)\n is_status = is_prime(i)\n if(is_status)\n puts i\n end\n end\nend",
"def count_primes(number)\n # create an array from 2-num\n # for each number in the array of possible primes\n # modulo the number by each n\n # if the number % n is 0, it's not a prime number\n # unless the number and n are the same\n possible_primes = (2...number).to_a\n possible_primes.select! do |num|\n # need to return true if num is prime, false if it is not\n # binding.pry if num == 3\n half_num = num\n results = (2...half_num).select do |n|\n # if num % n == 0, means that n evenly divides into num making it not prime\n num % n == 0\n end\n results.empty?\n # any number within results evenly divided into the num\n # making the num not prime\n # so if results is empty, it means that nothing divided into the num\n # making the num prime\n end\n possible_primes.count\nend",
"def prime_factors(number)\n return [] if number < 2\n return [number] if number < 4\n factors = []\n\n factor = 2\n while factor < number\n break if number % factor == 0\n factor += 1\n end\n factors << factor\n factors.concat(prime_factors(number / factor))\n factors.sort\nend",
"def prime_factors(number)\n return [] if number < 2\n return [number] if number < 4\n factors = []\n\n factor = 2\n while factor < number\n break if number % factor == 0\n factor += 1\n end\n factors << factor\n factors.concat(prime_factors(number / factor))\n factors.sort\nend",
"def primes\n Prime::EratosthenesGenerator.new.take_while {|i| i <= @base}\n end",
"def prime_factors num\n\tfactors = []\n\ttest_value = 2\n\twhile num > 1 do\n\t\twhile num % test_value == 0 do\n\t\t\tfactors.push num\n\t\t\tnum = num / test_value\n\t\tend\n\t\ttest_value += 1\n\tend\n\treturn factors\nend",
"def primes_less_than(n)\n primes = [2,3]\n (5..n).each do |i|\n if i%2 == 1\n primes << i if is_prime?(i, primes)\n end\n end\n primes\n end",
"def findPrimeFactorsofaNumber(number)\n listofprimefactors = []\n possiblePrime = 2\n while number > 1 \n if number % possiblePrime == 0\n number /= possiblePrime\n listofprimefactors.push possiblePrime\n elsif possiblePrime < 3\n possiblePrime += 1\n else\n possiblePrime += 2\n end\n end\n return listofprimefactors\n end",
"def prime_number(n)\n res = []\n prime = Array.new(n + 1, true)\n (2..n).each do |x|\n num = x * x\n break if num > n\n\n if prime[x]\n (num..n).step(x).each do |multiples|\n prime[multiples] = false\n end\n end\n end\n \n (2..n).each do |primes|\n res << primes if prime[primes]\n end\n res\nend",
"def primes_less_than n4\n prhyme = []\n (2..(n4-1)).each do |i|\n if is_prime?(i)\n prhyme.push(i)\n end\n end\n return prhyme\n end",
"def primes_up_to(max)\n repository = (0..max).collect{true} #=> Create flag array\n limit = (max ** 0.5) #=> establish search limit\n\n for index in 2..limit #=> search through flag aray\n next if !repository[index]\n num = (index * 2)\n while num <= max #=> unflag multiples of primes\n repository[num] = false\n num += index\n end\n end\n\n # => convert numbers into arrays\n primes = repository.collect.with_index do |flag, value|\n value if flag\n end\n\n # return cleaned array\n primes.shift\n primes.shift\n primes.compact\nend",
"def prime_factors(num)\n\n if prime?(num)\n return [num]\n end\n\n primes = (2...num).to_a.select { |factor| prime?(factor) }\n\n \n \n factors = []\n\n while num > 1\n candidate = primes.shift\n\n if num % candidate == 0\n factors << candidate\n while num % candidate == 0\n num /= candidate\n end\n end\n end\n\n return factors\n \nend",
"def ruby_prime(n1, n2)\n prime_numbers = []\n (n1..n2).each do |num|\n if Prime.prime?(num)\n prime_numbers << num\n end\n end\n prime_numbers\nend",
"def prime_factorization(num)\n (2...num).each do |fact|\n if num % fact == 0\n other_fact = num / fact\n return [ *prime_factorization(fact), *prime_factorization(other_fact) ]\n end\n end\n [ num ]\nend",
"def primes_below(n)\n a = 2\n output_array = []\n while a < n\n if is_prime?(a)\n output_array.push(a)\n end\n a = a + 1\n end\n return output_array\nend",
"def exclude_prime_numbers\n numbers = (1..100).to_a\n\n numbers.reject { |number| !Prime.prime? number }\n #=> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]\nend",
"def prime_factorization(num)\n (2...num).each do |fact|\n if num % fact == 0\n other_fact = num / fact\n return [*prime_factorization(fact), *prime_factorization(other_fact)]\n end\n end\n [num]\nend",
"def print_prime\n @n_primes = get_n_primes\n return [] if @n_primes == 0\n p_arr_len = @prime_numbers.length\n return @prime_numbers[0..@n_primes] if p_arr_len >= @n_primes\n (p_arr_len > 1) ? (n = @prime_numbers.last) : (n = 3)\n until @prime_numbers.length == @n_primes do\n @prime_numbers.push(n) if @prime_cache[n]\n (@prime_numbers.push(n) && @prime_cache[n] = true) if is_prime(n)\n n += 1\n end\n @prime_numbers\n end",
"def prime_factors(num)\n arr = factors(num)\n new_arr = []\n arr.each do |n|\n new_arr << n if prime?(n)\n end\n new_arr\nend",
"def get_primes(n)\n primes = [2]\n pp = 0\n i = 3\n while pp < n do\n if i%2 != 0\n counter = 0\n prime = 1\n while counter < primes.length do\n if (i%primes[counter] == 0)\n prime = 0\n break;\n end\n counter += 1\n end\n if prime == 1\n primes.push(i)\n pp +=1\n end\n end\n i+=1\n end\n return primes[n-1]\nend",
"def main()\n num = Integer(ARGV[0])\n res = []\n Prime.each(num) {|prime| res << prime}\n puts res.join(\", \")\nend",
"def find_primes(start_num, end_num)\n (start_num..end_num).select { |num| prime?(num) }.join(', ')\nend",
"def prime_factors(num)\n factors = []\n # Store all the factors in an array\n (2..num).each do |divisor|\n if num % divisor == 0\n factors << divisor\n end\n end\n\n # loop through factors array and return only the prime prime prime factors\n if factors.length > 0\n return factors.select { |factor| checkIfPrime(factor) }\n else\n return factors\n end\nend",
"def find_primes(int1, int2)\n nums = (int1..int2).to_a\n nums.select { |num| is_prime?(num) }\nend",
"def nth_Prime(num)\n\tprime_array = [2]\n\ti = 3\n\n\twhile prime_array.length < num\n\t\ti += 2\n\t\tif (i % 2 == 0)\n\t\t\tnext_num\n\t\tend\n\n\t\tprime = true\n\t\tprime_array.each do |j|\n\t\t\tif (i % j == 0)\n\t\t\t\tprime = false\n\t\t\t\tbreak\n\t\t\tend\n\t\tend\n\n\t\tif prime\n\t\t\tprime_array << i\n\t\tend\n\tend\n\tprime_array.last\nend"
] |
[
"0.814804",
"0.786815",
"0.786023",
"0.7813643",
"0.76659495",
"0.7612166",
"0.75990015",
"0.75051516",
"0.7378593",
"0.7349403",
"0.72536623",
"0.7174526",
"0.712673",
"0.70949775",
"0.7086163",
"0.70852816",
"0.70645124",
"0.70575565",
"0.70417",
"0.70211303",
"0.7012214",
"0.7008017",
"0.70001036",
"0.694752",
"0.6912866",
"0.6912866",
"0.6912866",
"0.6912866",
"0.6910196",
"0.68608445",
"0.6826108",
"0.6809043",
"0.6803759",
"0.67875564",
"0.6778627",
"0.67716783",
"0.67716783",
"0.67689884",
"0.6737101",
"0.67159927",
"0.6711856",
"0.6685129",
"0.6657887",
"0.6657849",
"0.665627",
"0.6650208",
"0.664142",
"0.6641379",
"0.6640316",
"0.66399896",
"0.66360813",
"0.6626627",
"0.66224796",
"0.65860575",
"0.6547273",
"0.6546029",
"0.6533915",
"0.65269804",
"0.6523165",
"0.6513344",
"0.6507597",
"0.65046835",
"0.64921474",
"0.64897114",
"0.64867795",
"0.64745337",
"0.6457704",
"0.64566493",
"0.6453006",
"0.64504176",
"0.6447131",
"0.64466494",
"0.6431927",
"0.6418182",
"0.64152646",
"0.63954264",
"0.6387901",
"0.6385578",
"0.6385578",
"0.6383787",
"0.63833815",
"0.6381417",
"0.63752985",
"0.63747764",
"0.6373087",
"0.63639015",
"0.63562787",
"0.6345838",
"0.6342488",
"0.63421434",
"0.6341644",
"0.6337706",
"0.6337334",
"0.6336915",
"0.63306737",
"0.6327775",
"0.63271606",
"0.63134086",
"0.6306359",
"0.62955356"
] |
0.7223245
|
11
|
Returns the smallest common multiple of all numbers 1num
|
def find_smallest_common_multiple(num)
primes = find_primes_under(num)
product = factorial(num)
counter = 0
while counter < primes.size
while check_number(num, product)
product = product / primes[counter]
end
product = product * primes[counter]
counter += 1
end
product
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def smallest_multiple(num)\n\t(2..num).inject(1) do |mul, i|\n\t\tif mul%i == 0\n\t\t\tmul\n\t\telse\n\t\t\t(i-1).downto(2) do |j| \n\t\t\t\tif i%j == 0\n\t\t\t\t\ti /= j\n\t\t\t\t\tbreak \n\t\t\t\tend\n\t\t\tend\n\t\t\tmul *= i\n\t\tend\n\tend\nend",
"def smallest_common_multiple(n)\n\n\treturn 0\nend",
"def least_common_multiple(num_1, num_2)\n (1...num_1 * num_2).each do |num|\n if num % num_1 == 0 && num % num_2 == 0\n return num\n end\n end\nend",
"def least_common_multiple(num_1, num_2)\n max = (num_1 * num_2) \n (1..max).each do |n|\n if n % num_1 == 0 && n % num_2 == 0 \n return n\n end\n end\nend",
"def smallest_multiple(input)\n range = (1..input)\n range.reduce(:lcm)\nend",
"def least_common_multiple(num_1, num_2)\n larger_num = [num_1, num_2].max\n smaller_num = [num_1, num_2].min\n i = 1\n done = false\n until done\n if (i * larger_num) % smaller_num == 0\n answer = i * larger_num\n done = true\n end\n i += 1\n end\n answer\nend",
"def smallest_multiple(n)\r\n dividers = (1..n)\r\n dividers.reduce(:lcm)\r\nend",
"def least_common_multiple(num_1, num_2)\n number = 1\n while ((number % num_1 != 0) || (number % num_2 != 0))\n number +=1\n end\n number\nend",
"def least_common_multiple(num_1, num_2)\n num_1, num_2 = [num_1, num_2].sort\n\n (1..num_2).each do |i|\n mutiple_1 = num_1 * i\n\n return mutiple_1 if mutiple_1 % num_2 == 0\n end\nend",
"def least_common_multiple(num_1, num_2)\n\n (1..num_2).each do |i|\n prod = num_1 * i\n return prod if prod % num_2 == 0\n end \nend",
"def smallest_multiple(input)\n\trange = (1..input)\n\trange.each do |num|\n\t\trunning_total = num\n\t\t\tif running_total % num != 0\n\t\t\t\trunning_total = num * running_total\n\t\t\telse\n\t\t\t\trunning_total\n\t\t\tend\n\tend\nend",
"def least_common_multiple(num_1, num_2)\n multiple = 1\n multiple += 1 until multiple % num_1 == 0 && multiple % num_2 == 0\n multiple\nend",
"def min_divisible_by_all(num)\r\n (1..num).inject(:lcm)\r\nend",
"def least_common_multiple(num_1, num_2)\n greatest = num_1 * num_2\n common_multiple = (2..greatest).select {|multiplo| multiplo % num_1 == 0 && multiplo % num_2 == 0}\n return common_multiple.first\n\nend",
"def least_common_multiple(num_1, num_2)\n min = [num_1, num_2].min\n max = [num_1, num_2].max\n (1..min).each { |num| return num*max if num*max % min == 0}\nend",
"def least_common_multiple(num_1, num_2)\n (1..num_1 * num_2).each do |el|\n return el if el % num_1 == 0 && el % num_2 == 0\n end\nend",
"def least_common_multiple(num_1, num_2)\n value = [num_1, num_2].max\n while (value % num_1 != 0) || (value % num_2 != 0)\n value += 1\n end\n return value\nend",
"def least_common_multiple(num_1, num_2)\n num_1, num_2 = num_2, num_1 if num_1 > num_2\n num_1 * num_2 / getGCD(num_1, num_2)\nend",
"def least_common_multiple(num_1, num_2)\n num_1 > num_2 ? max = num_1 : max = num_2\n (max..num_1 * num_2).each {|n| return n if n % num_1 == 0 && n % num_2 == 0}\nend",
"def least_common_multiple(num_1, num_2)\n # return [num_1, num_2].max if num_1 % num_2 == 0 || num_2 % num_1 == 0\n m = num_1\n while true\n return m if m % num_1 == 0 && m % num_2 == 0\n m += num_1\n end\nend",
"def least_common_multiple(num_1, num_2)\n check = num_1 <=> num_2\n return num_1 if check == 0\n if check == -1\n lcm = num_2\n while true\n return lcm if lcm % num_1 == 0\n lcm += num_2\n end\n else\n lcm = num_1\n while true\n return lcm if lcm % num_2 == 0\n lcm += num_1\n end\n end\n # (1..num_1 * num_2).each do |i|\n # return i if i % num_1 == 0 && i % num_2 == 0\n # end\nend",
"def least_common_multiple(num_1, num_2)\n match = false \n n = 0\n while !match \n n += 1\n if n % num_1 == 0 && n % num_2 == 0\n match = true \n end \n end \n n \n\nend",
"def smallest_multiple(num)\n\n curr = num\n\n loop do\n state = true\n for i in num.downto(1)\n if curr % i != 0\n state = false\n break\n end\n end\n if state == true\n return curr\n else\n curr += num\n end\n end\n\nend",
"def find_min_num(num)\n return 1 if num == 1\n n = 2\n minimum_num = nil\n loop do\n minimum_num = n if divisors(n).flatten.uniq.size == num\n n += 1\n break if minimum_num\n end\n minimum_num\nend",
"def least_common_multiple(num_1, num_2)\n (1...num_1 * num_2).each do |multiple|\n return multiple if multiple % num_1 === 0 && multiple % num_2 === 0\n end\nend",
"def least_common_multiple(num_1, num_2)\n (num_1 * num_2) / greatest_common_denominator(num_1, num_2)\nend",
"def least_common_multiple(num_1, num_2)\n find=true\n lcm=[num_1,num_2].max\n while find\n if lcm%num_1==0 && lcm%num_2==0\n return lcm\n end\n lcm+=1\n end\n\n\nend",
"def smallest_multiple\n (1..20).reduce(&:lcm)\nend",
"def least_common_multiple(num_1, num_2)\n i = [num_1,num_2].max\n while i > 0\n if i%num_1==0 && i%num_2==0\n return i\n end\n i+=1\n end\nend",
"def leastCommonMultiple( factors )\n return nil if factors.include?( 0 )\n\n maxFactor = 1\n minFactor = 1\n factorial = 1\n\n factors.each do | factor |\n maxFactor = factor if factor > maxFactor\n minFactor = factor if factor < minFactor\n factorial *= factor\n end\n\n Range.new( minFactor * minFactor, factorial ).each do | multiple |\n foundMultiple = true\n\n factors.each do | factor |\n if multiple % factor != 0\n foundMultiple = false\n break\n end\n end\n\n if foundMultiple == true\n return multiple\n end\n\n foundMultiple = true\n end\nend",
"def least_common_multiple(num_1, num_2)\n new_array = [num_1, num_2]\n max_num = new_array.max\n\n (1...max_num).each do |i|\n (1...max_num).each do |i2|\n if num_1 * i == num_2 * i2\n return num_1 * i\n end\n end\n end\nend",
"def find_smallest_multiple(divisors)\n max_product = divisors.reduce(1,:*)\n smallest = 1\n while smallest < max_product\n return smallest if check_divisibility(smallest, divisors)\n smallest += 1\n end\n max_product\nend",
"def smallest_multiple(n)\n m = 1\n while true\n n.downto(1) do |i|\n if (m % i != 0)\n break\n end\n if (i==1)\n return m\n end\n end\n m += 1\n end\nend",
"def smallest_multiple(max)\n\tcurrent_num = 1\n\tsolved = false\n\twhile solved == false do\n\t\t(1..max).to_a.reverse.each do |num|\n\t\t\tif current_num % num != 0\n\t\t\t\tcurrent_num += 1\n\t\t\t\tsolved = false\n\t\t\t\tbreak\n\t\t\tend #if no remainder\n\t\t\tsolved = true\n\t\tend #each\n\tend # while\n\treturn current_num\nend",
"def smallest_multiple(top_divisor)\n num = 1\n loop do\n return num if top_divisor.downto(1).all? { |divisor| num % divisor == 0 }\n num += 1\n end\nend",
"def least_product(num)\n m = 2\n 2.upto(num) do |n|\n m = m.lcm(n)\n end\n return m\nend",
"def smallest_multiple\n start_num = 20\n final_num = false\n while !final_num\n is_divisible = true\n (1...20).each do | num |\n remainder = start_num % num\n if remainder != 0\n is_divisible = false\n break\n end\n end\n is_divisible ? final_num = start_num : start_num += 20\n end\n return final_num\nend",
"def least_common_multiple(num_1, num_2)\n max = [num_1, num_2].max\n min = [num_1, num_2].min\n\n while true\n return max if max % num_1 == 0 && max % num_2 == 0\n max += 1\n end\nend",
"def smallest_multiple\n 9*16*5*7*11*13*17*19\nend",
"def smallest_multiple\r\n multiples = 1\r\n primes = Prime.entries 20\r\n\r\n primes.inject(1) { |memo, p| memo *= p ** max_power(p, 20) }\r\nend",
"def smallest_divisible_by_all_v2(range)\n return (range).inject(1) do |result, n| \n result.lcm n\n end\nend",
"def smallest_common_multiple(numbers)\n i = numbers.max\n \n until numbers.all? { |n| i % n == 0}\n puts i\n i += 20\n end\n puts i\nend",
"def least_common_multiple(num_1, num_2)\n #if not the smaller num is not a factor of the bigger num\n #we need to find the greatest common factor\n #and multiply bigger num by greatest common factor\n # common_factors = []\n # smaller_factors = (1..num_1).select { |n| num_1 % n == 0 }\n # larger_factors = (1..num_2).select { |n| num_2 % n == 0 }\n # p smaller_factors\n # p larger_factors\n # common_factors = \n num_1.lcm(num_2)\nend",
"def least_common_multiple(num_1, num_2)\n arr_1 = []\n arr_2 = []\n (1..num_2).each do |mult|\n arr_1 << num_1 * mult\n end\n (1..num_1).each do |mult|\n arr_2 << num_2 * mult\n end\n arr_1.each do |elem|\n if arr_2.include?(elem)\n return elem\n end\n end\n num_1 * num_2\nend",
"def smallest_multiple\n count = 0\n number = 1\n\n while true\n (1..20).each { |x| count += 1 if number % x == 0 }\n\n if count == 20\n number\n break\n else\n number += 1\n count = 0\n end\n end\n\n puts number\nend",
"def smallestMultiple a, b, start = 1\n \n # use start = 2520 for finding the solution in range [1,20]\n\tstart.step((Float::MAX).to_i) do |n| \n\t\tflag = (a..b).inject(true) do |flag, elem|\n\t\t\tflag &= (n % elem == 0)\n\t\t\tbreak if !flag\n\t\t\tflag\n\t\tend\t\n\t\treturn n if flag\n\tend\n\treturn -1\nend",
"def smallest_multiple(start)\n a = start\n while !(is_multiple_of_all?(a))\n a += 20\n end\n a.to_s\nend",
"def lcm_1_to_n (num)\n answer = 1\n answer_factors = Hash.new(0) #key is prime factor, val is number of occurences\n (0..num).each do |x|\n f = 2 #start with first possible prime factor\n x_factors = Hash.new(0)\n\n #find prime factors for x\n while (x >= f)\n while (x % f == 0)\n x_factors[f] += 1\n x /= f\n end\n f += 1\n end\n\n #the answer must have as many occurrences of each prime factor as each\n #individual number (1..num).\n x_factors.each do |factor, occurrences|\n if (occurrences > answer_factors[factor])\n answer_factors[factor] = occurrences\n end\n end\n end\n\n #answer_factors has correct factors. Multiply them for the answer\n answer_factors.each do |factor, occurrences|\n occurrences.times do\n answer *= factor\n end\n end\n answer\nend",
"def smallest_multiple(min, max)\n factors_hash = {}\n\n (min..max).each do |n|\n factor_hash = {}\n prime_factors(n).each do |factor|\n factor_hash[factor] = factor_hash[factor] ? factor_hash[factor] + 1 : 1\n end\n factor_hash.each do |factor, exponent|\n if factors_hash[factor] == nil || exponent > factors_hash[factor]\n factors_hash[factor] = exponent\n end\n end\n end\n factors_hash.inject(1) do |product, (factor, exponent)|\n product *= factor**exponent\n end\nend",
"def smallest_multiple(ceiling)\n count = ceiling\n\n loop do\n count += ceiling\n divisible = true\n\n ceiling.downto(1) do |num|\n if count % num != 0\n divisible = false\n next\n end\n end\n\n return count if divisible\n end\nend",
"def smallest_number()\r\n\tprime_numbers = [19,17,13,11,7,5,3,2] # primes numbers from 0-20.\r\n\tproduct_prime = prime_numbers.reduce(:*)\r\n\tnumber = product_prime\r\n\twhile (1)\r\n\t\treturn number if divisible_1to20?(number)\r\n\t\tnumber += product_prime\r\n\tend\r\nend",
"def find_smallest_multiple(num,count,acc)\n if count == max\n return acc\n #if number is divisible by one last than the number\n elsif !check_a_num(num,count)\n acc*num\n return check_a_num(num,count)\n \n \n end\n puts num\nend",
"def smallest_multiple(limit)\n powers_arr = largest_power(limit).slice(1..-1)\n start = largest_power(limit).shift\n answer = powers_arr.inject { |a, e| a * e }\n\n (start + 1..limit).each do |i|\n answer *= i if prime?(i)\n end\n puts answer\nend",
"def smallest_multiple_rec range = 1..20, value = 1\n return value if range.size == 1\n f, l = range.first, range.last\n value = value.lcm f\n smallest_multiple_rec((f + 1)..l, value)\nend",
"def smallest_multiple(values)\n max = values.reduce(:*)\n min_step = values.select { |v| v.prime? }.reduce(:*)\n min = min_step\n\n (min..max).step(min).find { |n|\n values.select { |v| n % v != 0 }.empty?\n }\nend",
"def smallest_multiple\n results = []\n values = (1..300000000).to_a\n\n values.each do |value|\n if value % 20 == 0 &&\n value % 19 == 0 &&\n value % 18 == 0 &&\n value % 17 == 0 &&\n value % 16 == 0 &&\n value % 15 == 0 &&\n value % 14 == 0 &&\n value % 13 == 0 &&\n value % 12 == 0 &&\n value % 11 == 0 &&\n value % 10 == 0 &&\n value % 9 == 0 &&\n value % 8 == 0 &&\n value % 7 == 0 &&\n value % 6 == 0 &&\n value % 5 == 0 &&\n value % 4 == 0 &&\n value % 3 == 0 &&\n value % 2 == 0\n results << value\n end\n\n end\n results\nend",
"def smallest_multiple(max_range)\n\tnumber = max_range\n\tcounter = 1\n\twhile counter != max_range\n\t\tcounter = 1\n\t\t(2..max_range).each do |i|\n\t\t\tif number % i == 0\n\t\t\t\tcounter += 1\n\t\t\tend\n\t\tend\n\t\tnumber += max_range\n\tend\n\n\tnumber - max_range\nend",
"def smallest_multiple(factors)\n primes = Hash.new(0)\n factors.each do |n|\n p_facts = prime_factors(n)\n p_facts.each do |factor, power|\n primes[factor] = power if power >= primes[factor]\n end\n end\n expand(primes)\nend",
"def smallest_number(limit)\n prime_factorization = {}\n 1.upto(limit).each do |i|\n factors = prime_factors(i)\n factors.each do |factor|\n times_repeated = factors.find_all { |f| f == factor }.count\n if !prime_factorization[factor] || prime_factorization[factor] < times_repeated\n prime_factorization[factor] = times_repeated\n end\n end\n end\n\n prime_factorization.map { |k,v| k ** v }.reduce(:*)\nend",
"def common_dividor(num1, num2)\n limit = [num1, num2].min\n limit.downto(1) do |int|\n return int if num1 % int == 0 && num2 % int == 0\n end\nend",
"def smallest(n)\n\tdivisible = false\n\tstart = 1\n\n\tuntil divisible == true\n\t\t(1...n).each do |i|\n\t\t\tif start % i != 0\n\t\t\t\tdivisible = false\n\t\t\telse\n\t\t\t\tdivisible = true\n\t\t\tend \n\t\t\tif divisible == false\n\t\t\t\tbreak\n\t\t\tend\n\t\tend\n\t\tstart += 1\n\tend\n\tp start - 1\nend",
"def find_lcm(n)\n (1..n).reduce(:lcm)\nend",
"def smallest_multiple max\n\tcontinue = true; count = 1; value = 0\n\twhile continue \n\t\tskip = false\n\t\tvalue = max * count\n\t\tputs value\n\t\tmax.downto(1).each do |i|\n\t\t\tnext if skip\n\t\t\tskip = true unless value % i == 0\n\t\tend\n\t\tcount += 1\n\t\tnext if skip\n\t\tcontinue = false\n\tend\n\tvalue\nend",
"def find_smallest_number(largest_divisor)\n smallest = largest_divisor\n found = false\n while !found\n found = true \n largest_divisor.downto(1) do |i| \n if smallest % i != 0\n smallest += largest_divisor\n found = false\n break\n end\n end\n end\n smallest\nend",
"def smallest_multiple\n # number = 2520\n number = 1\n # test_array = []\n while true\n num = 20 * number\n # for i in (11..20)\n # if number%i == 0\n # test_array.push(i)\n # if test_array == [11,12,13,14,15,16,17,18,19,20]\n # ans = number\n # break\n # end\n # else\n # test_array.clear\n # end\n # end\n if num % 1 == 0 and num % 2 == 0 and num % 3 == 0 and num % 4 == 0 and num % 5 == 0 and num % 6 == 0 and num % 7 == 0 and num % 8 == 0 and num % 9 == 0 and num % 10 == 0 and num % 11 == 0 and num % 12 == 0 and num % 13 == 0 and num % 14 == 0 and num % 15 == 0 and num % 16 == 0 and num % 17 == 0 and num % 18 == 0 and num % 19 == 0 and num % 20 == 0\n puts num\n return num\n end\n # if ans != \"\"\n # break\n # end\n number += 1\n end\n # puts number\n # puts \"ans: \" + ans.to_s\nend",
"def lcm(*nums)\n nums.reduce(1, :lcm)\nend",
"def lcm(nums)\n # get prime factors of each num\n if nums.include?(0)\n return 0\n end\n\n pfs = prime_factorise(nums).uniq\n baseprimes = []\n\n # Extract all common primes, starting with 2\n $primes.each do |p|\n most_p = 0\n pfs.each do |pf|\n new_most_p = pf.count { |x| x == p }\n if new_most_p > most_p\n most_p = new_most_p\n end\n end\n most_p.times do\n baseprimes.push(p)\n end\n end\n\n puts baseprimes.to_s\n\n # multiply out\n baseprimes.reduce(:*)\nend",
"def problem_five\n (1..20).reduce(1) { |res, n| res.lcm n }\n end",
"def greatest_common_factor(num1, num2)\n divisor = 1\n 2.upto([num1.abs, num2.abs].min) do |num|\n if num1 % num == 0 && num2 % num == 0\n divisor = num\n end\n end\n divisor\nend",
"def smallest_multiple(n)\n def get_prime_factors(n, factors=[])\n return n if n.prime?\n \n Prime.first(n).each do |prime|\n if n % prime == 0\n factors << prime\n n /= prime\n break\n end\n end\n \n \n factors + [get_prime_factors(n)].flatten\n end\n \n def get_highest_exponents(n, factors=[])\n (2..n).each do |m|\n if get_prime_factors(m).is_a? Array\n factors << get_prime_factors(m)\n else\n factors << [m]\n end\n end\n \n highest = []\n Prime.first(n).select { |p| p < n }.each do |factor|\n highest << factors.sort_by { |f| f.count(factor) }[-1].select { |num| num == factor }\n end\n \n \n highest.flatten\n end\n\n\n get_highest_exponents(n).reduce(:*)\nend",
"def lcm(*nums)\n nums = nums.collect { |n| [* n] }.flatten.sort.reverse\n p_facs = []\n primes = Prime.new\n max = nums.first\n while (p = primes.next) and max > p\n while nums.detect { |n| (n % p).zero? }\n p_facs << p\n nums = nums.collect { |n| (n % p).zero? ? n / p : n }\n end\n end\n nums.each { |n| p_facs << n if n > 1 }\n p_facs.inject(1) { |l, n| l * n }\nend",
"def find_gcd(nums)\n nums.minmax.reduce(:gcd)\nend",
"def lcm(num1, num2)\n num1.lcm(num2)\nend",
"def single_number(nums)\n (3 * nums.uniq.sum - nums.sum) / 2\nend",
"def lowest_number(number_list)\n number_list.map(&:to_s)\n .permutation\n .map(&:join)\n .map(&:to_i)\n .min\nend",
"def problem5 ( )\n lcm_1_to_n(20)\nend",
"def smallestMult()\n (2520...999999999).step(20) do |i|\n if divisionCheck(i)\n return i\n end\n end\nend",
"def find_min_prime_factor (n)\n # Find the minimum prime factor from 2 to √n.\n # If no element does, return nil.\n 2.upto(Math.sqrt(n)).lazy.select { |i| (n % i).zero? }.first\nend",
"def gcf(num1, num2)\n\tx = num1 < num2 ? num1 : num2\n\twhile x > 1 do\n\t\tif num1 % x == 0 && num2 % x == 0\n\t\t\treturn x\n\t\tend\n\t\tx -= 1\n\tend\n\treturn 1\nend",
"def greatest_common_factor(number1, number2)\n new = number1.to_i\n number2 = number2.to_i\n while number1 > 0\n if (number1 % new == 0.0) && (number2 % new == 0.0)\n return new\n end\n new -= 1.0\n end\nend",
"def greatest_common_factor(number1, number2)\n # get the smaller number\n n = number1 < number2 ? number1 : number2\n\n # check each number i\n # starting from this number n down to 1\n # if it divides both number1 and number2 evenly\n # if so, then this is the gcd\n n.downto(1).each do |i|\n if number1 % i == 0 and number2 % i == 0\n return i\n end\n end\n 1\nend",
"def smallest_one(num1,num2,num3)\n if num1 < num2 && num1 < num3\n num1\n elsif num2 < num1 && num2 < num3\n num2\n else num3 < num1 && num3 < num1\n num3\n end\nend",
"def greatest_common_factor(number1, number2)\n\t\n\tgreatest_num = nil\n\ti = 1\n\t\n\twhile i < 10\n\t\n\t if number1 % i == 0 && number2 % i == 0\n\t \n\t if greatest_num == nil || greatest_num < i\n\t \tgreatest_num = i\n\t\n end\n end\n\t\t\n\ti += 1\n end\n return greatest_num\n \nend",
"def greatest_common_factor(first_number, second_number)\n x, y = first_number, second_number\n n = x < y ? x : y\n n.downto(1).each do |i|\n if x % i == 0 and y % i == 0\n return i\n end\n end\n 1\nend",
"def common a\n a.reduce :gcd\nend",
"def Division(num1,num2)\n factors = []\n (1..10**3).each {|idx| factors << idx if (num1 % idx == 0 && num2 % idx == 0)}\n factors.max\nend",
"def first_triangle_number_with_divisors_of(num)\n\tcount = 0\n\ti = 0\n\tsum = 0\n\tuntil count >= num do\n\t\ti += 1\n\t\tsum += i\n\t\tcount = divisor_number_of(sum)\n\tend\n\tsum\nend",
"def lowest_product(input)\n if input.length < 4\n \"Number is too small\"\n else\n a = input.split(\"\").sort\n a.map! { |n| n.to_i }\n product = 1\n a[0..3].each { |n| product *= n }\n p product\n end\nend",
"def lcm(p0) end",
"def greatest_common_divisor(x, y)\n smallest_num = [x, y].min\n smallest_num.downto(1) do |num|\n return num if x % num == 0 && y % num == 0\n end\nend",
"def single_number(nums)\n 2 * nums.uniq.reduce(:+) - nums.reduce(:+)\nend",
"def Division(num1, num2)\n\t# start with the lowest number and then iterate one down from there until zero, and return the first number that\n\t# divides into both\n\n\tif num1 < num2\n\t\tgreatest_common_factor = num1\n\telse\n\t\tgreatest_common_factor = num2\n\tend\n\n\twhile greatest_common_factor > 0\n\t\tif num1 % greatest_common_factor == 0 && num2 % greatest_common_factor == 0\n\t\t\treturn greatest_common_factor\n\t\tend\n\t\tgreatest_common_factor -= 1\n\tend\nend",
"def boolean_smallest_miltiple (num, low, high)\n while low < high\n if num%low != 0\n return false\n end\n low = low + 1\n end\n true\nend",
"def greatest_common_factor(number1, number2)\n\n if number1 < number2\n smallest = number1\n largest = number2\n elsif number2 < number1\n smallest = number2\n largest = number1\n else \n puts 'Numbers must de different.'\n end \n\n factor = smallest\n\n while factor > 0\n if largest % factor == 0 && smallest % factor == 0\n puts factor # debug\n return factor\n else\n factor -= 1\n end\n \n end\nend",
"def getTotalX(a,b)\n least_common_multiple = a.reduce(:lcm)\n greatest_common_factor = b.reduce(:gcd)\n counter = 0\n\n (least_common_multiple..greatest_common_factor).each do |num|\n if num % least_common_multiple == 0 && greatest_common_factor % num == 0\n counter += 1\n end\n end\n\n return counter\nend",
"def lcm(a, b)\n #\n # your code goes here\n # create two empty arrays to accumulate mutliples of 'a' and 'b'\n # iterate 1 thru a and 1 thru b getting multiples for 'a' and 'b'\n # select multiples from both arrays if common (*)\n # choose the leat from above (*)\n multiples_of_a, multiples_of_b = [], []\n\n (1..b).each do |n|\n multiples_of_a << n * a\n end\n\n (1..a).each do |n|\n multiples_of_b << n * b\n end\n\n common_multiples = multiples_of_a.select do |multiple|\n multiples_of_b.include?(multiple)\n end\n\n common_multiples.first\nend",
"def smallest(number_of_digits)\n ('1' * number_of_digits).to_i\nend",
"def perfect_power(num)\n return num if num == nil\n\n for power in 2...500\n subject = num ** (1.0 / power)\n if subject == subject.to_i\n return [subject.to_i, power]\n end\n end\n nil\nend",
"def Division(num1,num2)\n lowest = num1 <= num2 ? num1 : num2\n\n while lowest > 0\n return lowest if num1 % lowest == 0 && num2 % lowest == 0\n lowest -= 1\n end\nend",
"def single_number(nums)\n nums.reduce(:^) # { |memo, num| memo ^ num }\nend"
] |
[
"0.8038764",
"0.8010712",
"0.79202425",
"0.7871839",
"0.7845951",
"0.77993315",
"0.77966326",
"0.7774211",
"0.77692664",
"0.7746873",
"0.77313554",
"0.77013797",
"0.7685281",
"0.7672937",
"0.76618665",
"0.7654444",
"0.76053",
"0.7604434",
"0.7579523",
"0.75754476",
"0.75596446",
"0.75542593",
"0.7512131",
"0.75024056",
"0.7501469",
"0.7497988",
"0.7497662",
"0.74846834",
"0.7440424",
"0.7438452",
"0.7429651",
"0.74135023",
"0.7360368",
"0.73274904",
"0.7307628",
"0.7293313",
"0.7281007",
"0.7264063",
"0.72433823",
"0.72342575",
"0.72195745",
"0.72195613",
"0.7214353",
"0.7162731",
"0.71567243",
"0.7097969",
"0.70655346",
"0.70446455",
"0.7005065",
"0.6997196",
"0.69884926",
"0.692687",
"0.686045",
"0.6844354",
"0.6834266",
"0.6820858",
"0.67818636",
"0.67675835",
"0.6765494",
"0.67443997",
"0.6726245",
"0.668702",
"0.66851276",
"0.66753715",
"0.6632197",
"0.6615832",
"0.6602794",
"0.6577764",
"0.65772706",
"0.65552175",
"0.65437865",
"0.653768",
"0.6529924",
"0.64910406",
"0.64908534",
"0.64874685",
"0.6484434",
"0.6475341",
"0.6475246",
"0.63768953",
"0.6372797",
"0.63563824",
"0.6348787",
"0.6340312",
"0.6324342",
"0.63241965",
"0.63075584",
"0.62932664",
"0.6281675",
"0.6270099",
"0.62672716",
"0.626358",
"0.62337035",
"0.6232085",
"0.6224541",
"0.6204996",
"0.62013984",
"0.61899996",
"0.61852616",
"0.6184317"
] |
0.8328037
|
0
|
Determine how much money was gained in one year
|
def grow_one_year(starting_balance, growth_rate)
starting_balance * (1.0 + growth_rate)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def years_needed\n 30\n end",
"def required_annual_savings\n needed_amount_less_savings / years_to_retirement\n end",
"def calculate_years(principal, interest, tax, desired)\n# principal amount\n year = 0\n while principal < desired\n year += 1\n income = principal * interest\n principal += income - income * tax\n end\n year\nend",
"def decades() 10 * years end",
"def real_study_years\n if finished?\n end_date = finished_on.to_time\n elsif absolved?\n end_date = disert_theme.defense_passed_on.to_time\n else\n end_date = Time.now\n end\n return (end_date - enrolled_on.to_time).div(1.year) + 1\n end",
"def calculate_yearly_rents_years\n convert_lease_transaction_date\n years = @lbtt_return.lease_end_date.year - @lbtt_return.lease_start_date.year\n years += 1 if @lbtt_return.lease_end_date >= @lbtt_return.lease_start_date.next_year(years)\n years\n end",
"def years ; self * 365.days ; end",
"def age_calc\n \t now = Time.now.to_date\n now.year - self.year - (self.change(:year=>now.year)>now ? 1 : 0) #rescue 0\n \tend",
"def years\n self.to_i * 31_557_600\n end",
"def annualized_portfolio_amount_needed\n savings_portion_needed * 12.0\n end",
"def calculate_years(principal, interest, tax, desired)\n total = principal\n years = 0\n loop do\n break if total >= desired\n total_interest = total*interest\n total += total_interest\n total -= total_interest*tax\n years += 1\n end\n years\nend",
"def years\n\t\treturn (self * 365.25.days).to_i\n\tend",
"def years\n\t\treturn (self * 365.25.days).to_i\n\tend",
"def donation_this_year\n donation_year = Donation.where(\"strftime('%Y', donation_date) = ?\", Time.now.year.to_s)\n currency(donation_year.sum(:amount))\n end",
"def yearly_rate\n\t\t yearly? ? rate : rate * 12\n\t\t end",
"def years() 365 * days end",
"def year(input) = new_year(input).year - 621",
"def years_until_retirement\n @retirement_age.to_i - @current_age.to_i\n end",
"def total_retirement_saving(your_age)\n child_age = your_age / 2\n saving_per_year = child_age * child_age\n years_to_retire = 65 - child_age\n saving_per_year * years_to_retire\nend",
"def calculate_century(year)\n (year % 100).zero? ? year / 100 : year / 100 + 1\nend",
"def daily_rate\n\t\t yearly_rate / 365\n\t\t end",
"def yearly_rate\n yearly? ? rate : rate * 12\n end",
"def total_years\n all_years = artists.map do |artist|\n artist.years_active\n end\n all_years.inject(:+)\n end",
"def make_one_year_older\n @age +=1\n end",
"def new_sale_price \n noi(num_years_to_hold + 1) / cap_rate(num_years_to_hold + 1)\n end",
"def gas_year\n y = year\n if self< Date.new(y,10,1)\n y\n else\n y+1\n end\n end",
"def withdrawal_rate\n (youngest_person_retirement_age - 15.0) / 1000.0\n end",
"def current_age_for_birth_year(birth_year)\n return 2016 - birth_year\nend",
"def make_one_year_older\n @age += 1\n end",
"def calculate_years(principal, interest, tax, desired)\n i = 0\n return i if principal == desired\n \n while principal < desired\n principal += (principal * interest) - (principal * interest * tax)\n i += 1\n end\n \n i\nend",
"def what_century(year)\n year % 100 == 0 ? year / 100 : year / 100 + 1\nend",
"def years; self * YEAR; end",
"def current_age_for_birth_year(birth_year)\n 2003 - birth_year\nend",
"def year1total\n @year1total = @year1 + @manage + @corporate\n end",
"def years_count\n ((@end_date - @start_date).to_f / 365).to_f.round(1)\n end",
"def year1totalcharges\n @year1totalcharges = @year1total + @profit\n end",
"def call(year)\n previous_year = Population.previous_known(year)\n\n return previous_year.population if previous_year.year == year # year entered is known\n\n next_year = Population.next_known(year)\n\n # there is no next year - unable to calculate\n return nil if next_year.nil? \n\n # calculate the percentage that year is between next and previous years\n mod_percentage = (year - previous_year.year).to_f / (next_year.year - previous_year.year).to_f\n delta_population = next_year.population - previous_year.population\n\n (delta_population * mod_percentage).to_i + previous_year.population\n end",
"def current_age_for_birth_year(year)\nage_of_person = 2003 - year\nend",
"def calc_years_till\n (calc_months_till / 12.00).round(2)\n end",
"def get_total_year(user)\n source = get_page_source(user)\n headers = source.css('h2')\n string = nil\n headers.each do |i|\n # Strip excess whitespace and newlines\n header_text = i.text.gsub(/(\\s+|\\n)/, ' ')\n if /contributions in the last year/ =~ header_text\n string = header_text.to_i_separated\n break\n end\n end\n string || 0\n end",
"def age_in_years(cur = Datet.new)\n years = (cur.year - self.year)\n years -= 1 if cur.day_in_year < self.day_in_year\n return years\n end",
"def paid_thru_now\n # Turn off March 1 of year following paid year\n paid_thru_year >= (Date.today - 59).year\n end",
"def current_age_for_birth_year(birth_year)\n Time.now.year - birth_year\nend",
"def start_year\n Time.now.year - 75\n end",
"def daily_interest\n @apr / 100.0 / 365\n end",
"def debt_rate\n ten_year_treasury + bps(200)\n end",
"def us_treas_10_year_rate\n # In real life call a web service to get it, but I will return a constant here\n 0.02124\n end",
"def annual_salary\n hourly_rate * 1950\n end",
"def get_price_change_ytd(stock)\n stock_price = get_stock_price(stock)\n ytd_pct_change = get_pct_change_ytd(stock)\n # Calculate the price at the start of the year\n year_start_price = stock_price - (ytd_pct_change*stock_price)\n # get the price change from the start of year to date\n ytd_price_change = stock_price - year_start_price\n return ytd_price_change.round(2)\nend",
"def total_amount_owed(principal, interest_rate_percentage, number_of_years)\n annual_percentage_rate = interest_rate_percentage / 100\n principal * (1 + annual_percentage_rate * number_of_years)\nend",
"def years_of_service(period=nil)\n # TODO: need a real general purpose date diff by year\n # function since this is likely needed in multiple places.\n return 0 if contract_start.nil?\n period = Period.current if period.nil?\n\n if (period.finish > contract_start)\n tmp_date = period.finish\n count = 0\n while (tmp_date.prev_year >= contract_start.to_date)\n tmp_date = tmp_date.prev_year\n count += 1\n end\n\n count\n else\n 0\n end\n end",
"def paid_days_remaining\n days_elapsed = (Time.now.to_i - self.trial_started_at.to_i) / 60 / 60 / 24\n remaining = 365 - days_elapsed\n remaining = 0 if remaining < 0\n remaining\n end",
"def human_years \n age * DOG_YEARS\n end",
"def years ; Duration[self * 365 * 86400, :years] ; end",
"def hours_in_a_year\n return 365.25 * 24\nend",
"def old_in_years\n (Time.now - @doj)/(60*60*24*365) unless self.doj.nil?\n end",
"def year_rome_founded\n bce(753)\n end",
"def daily_rate\n yearly_rate / 365\n end",
"def human_years\n age * DOG_YEARS\n end",
"def human_years\n age * DOG_YEARS\n end",
"def human_years\n age * DOG_YEARS\n end",
"def dog_years (human_years)\n human_years * 7\n end",
"def add_year_growth(coins)\r\n \r\n coins.each do |x|\r\n \r\n puts 'x.name: ' + x.name if @debug\r\n \r\n if @growth.has_key?(x.name) then\r\n x.percent_change_year = @growth[x.name].to_s\r\n else\r\n x.percent_change_year = '-'\r\n end\r\n end \r\n \r\n coins\r\n \r\n end",
"def dog_years(human_years)\n human_years * 7\n end",
"def year() end",
"def retire\n require 'date'\n\n puts \"What is your age?\"\n age = gets.chomp.to_i\n\n puts \"At what age would you like to retire?\"\n retire_at = gets.chomp.to_i\n\n current_year = DateTime.now.year\n when_will_retire = retire_at - age\n year_to_retirement = current_year + when_will_retire\n\n puts \"It's #{current_year}. You will retire in #{current_year + when_will_retire}.\"\n puts \"You have only #{year_to_retirement - current_year} years of work to go!\"\nend",
"def years_since(years)\n advance(years: years)\n end",
"def amy_kids_ages\n [ Time.now.year - 1996, Time.now.year - 1985].join(' to ')\n end",
"def count\n @count ||= Date.current.year - @release_date.year\n end",
"def amount_owed\n total_price - amount_paid\n end",
"def century(year)\n which_century(year) + numberth(which_century(year))\nend",
"def to_years; Rational === @val ? @val/12 : @val/12.0 end",
"def calc_century(year)\n if year.to_s.end_with?('0')\n year / 100\n else\n (year + 100) / 100\n end\nend",
"def human_years\n age * DOG_YEARS\n end",
"def cash_on_cash(year)\n if not self.cache[year][:cash_on_cash]\n val = after_tax_cash_flow(year) / down_payment.to_f\n self.cache[year][:cash_on_cash] = val\n end\n self.cache[year][:cash_on_cash]\n end",
"def needed_amount_less_savings\n recommended_min_portfolio - portfolio_after_growth\n end",
"def profit\n total_before_tax - total_cost\n end",
"def profit\n total_before_tax - total_cost\n end",
"def hours_in_year(year)\n hours = 365 * 24\n hours += 24 if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)\n hours\nend",
"def subyearstotal\n @subyearstotal =\n if @supplier_name\n @subsequent_length_years *\n (@year1totalcharges -\n (((@mobilisation + (@mobilisation * @rate_card.data['Variances'][@supplier_name]['Management Overhead %']) +\n (@mobilisation * @rate_card.data['Variances'][@supplier_name]['Corporate Overhead %'])) *\n (@rate_card.data['Variances'][@supplier_name]['Profit %'] + 1))))\n else\n @subsequent_length_years * (@year1totalcharges - (((@mobilisation + (@mobilisation * @framework_rates['M140']) + (@mobilisation * @framework_rates['M141'])) * (@framework_rates['M142'] + 1))))\n end\n end",
"def what_you_would_get_if_not_full\n if (qualifying_years + years_to_pension) < years_needed\n ((qualifying_years + years_to_pension).to_f / years_needed.to_f) * current_weekly_rate\n else\n current_weekly_rate\n end\n end",
"def annualy_insurance\n return @capital * @insurance * -1\n end",
"def nb_year(p0, percent, aug, p)\n years = 0\n while p >= p0 do\n p0 += (percent/100.0 * p0) + aug\n years += 1\n end\n p years\nend",
"def years(tech=nil) \n if tech\n tdata = nil\n @techs.each do |t|\n if t.name == tech\n tdata = t\n end\n end\n if tdata\n return tdata.years\n else\n return 0\n end\n # TODO: return just the time we worked with that technology\n end\n return (@to - @from).to_i / 365\n end",
"def disbursed_amount\n amount = 0\n loans.each do |project|\n amount += project.disbursed_amount.to_i\n end\n amount\n end",
"def days_in_year\n 365.25\nend",
"def unpaid_amount\n gross_amount - paid_amount\n end",
"def age_verifier( x, y)\n current_year = Time.now.year\n if x + y == current_year\n true\n else \n false\n end\nend",
"def expected_death_year\n if is_married?\n Chronic.parse(\"#{@years_to_live + 5} years from now\").year.to_s\n else\n Chronic.parse(\"#{@years_to_live} years from now\").year.to_s\n end\n end",
"def retire\nputs \"What is your age?\" \nage = gets.chomp.to_i\nputs \"When do you want to retire?\"\ndesired_retirement = gets.chomp.to_i\n\ncurrent_year = Time.now.year\n\nyears_before_retirement = desired_retirement - age\nretirement_year = current_year + years_before_retirement\n\nputs \"It's #{current_year}. You will retire in #{retirement_year}.\"\nputs \"You have only #{years_before_retirement} years of work to go!\"\nend",
"def artists_years_experienced\n years = self.all_artists.inject(0){|sum, artist| sum + artist.years_active}\nend",
"def birth_year\n @current_year - @age\n end",
"def amy_years\n (Time.now.year - 1977).ordinalize\n end",
"def expected_death_year\n Chronic.parse(\"#{@years_to_live} years from\nnow\").year\n end",
"def short_age(birth_year)\n Time.new.year - birth_year\nend",
"def start_year\n Time.now.year - 18\n end",
"def year1\n @year1 = @subtotal3 + @mobilisation + @tupe\n end",
"def centuryFromYear(year)\n if (year % 100 == 0)\n year/100\n else\n (year/100) + 1\n end\nend",
"def amount_of_people_alive_in(year)\n amount = 0\n\n each { |person| amount += 1 if person.alive_in?(year) }\n\n amount\n end",
"def end_year\n Time.now.year - 90\n end"
] |
[
"0.7728491",
"0.7486112",
"0.7358475",
"0.72229135",
"0.7221456",
"0.7133883",
"0.70664215",
"0.70331794",
"0.7014857",
"0.6978319",
"0.6974331",
"0.6954624",
"0.6954624",
"0.69497335",
"0.6942155",
"0.6935395",
"0.6931724",
"0.68987465",
"0.6813294",
"0.68056893",
"0.67869115",
"0.67766356",
"0.676304",
"0.6755433",
"0.6753659",
"0.6751034",
"0.6740696",
"0.67385817",
"0.67334133",
"0.6729574",
"0.6710015",
"0.6663451",
"0.66629624",
"0.6653479",
"0.6651774",
"0.6647491",
"0.6647004",
"0.6645593",
"0.6621871",
"0.6601745",
"0.659034",
"0.6580675",
"0.6575975",
"0.65574235",
"0.6551054",
"0.65454865",
"0.6544456",
"0.6540183",
"0.65320253",
"0.6530466",
"0.652486",
"0.6523568",
"0.65155303",
"0.65014356",
"0.6495482",
"0.6480657",
"0.64799744",
"0.647926",
"0.64667237",
"0.64667237",
"0.64667237",
"0.6462522",
"0.6453486",
"0.64528733",
"0.6451425",
"0.6439208",
"0.6431435",
"0.64313585",
"0.64217925",
"0.64212847",
"0.64203626",
"0.64120567",
"0.6410777",
"0.64082944",
"0.64055634",
"0.64040947",
"0.6401446",
"0.6401446",
"0.64001364",
"0.63987076",
"0.6397551",
"0.6397131",
"0.6382054",
"0.6376967",
"0.63719493",
"0.6369301",
"0.63621324",
"0.63616604",
"0.6358154",
"0.6353683",
"0.63502663",
"0.63477665",
"0.6346236",
"0.6346104",
"0.63413775",
"0.63249934",
"0.6322564",
"0.6321735",
"0.6320201",
"0.6314757"
] |
0.6900323
|
17
|
Open the TDB file. Accepts a URI and list of open modes: db = TokyoModel::Adapters::File.new("file:///tmp/database.tdb", :read, :write, :create, :trunc)
|
def initialize(uri, *args)
@db = TokyoCabinet::TDB::new
@db.open(uri.path, args.empty? ? File.default_open_mode : File.open_mode(*args))
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def open\n close\n @db = SQLite3::Database.new(@options[:filename])\n self\n end",
"def open(options)\n @db ||= options[:connection]\n return @db if @db\n\n if options[:path] && !File.exist?(options[:path])\n @db = SQLite3::Database.new(options[:path])\n setup\n end\n\n raise StoreException.new(\"Attempt to open missing database file #{options[:path]}\") unless File.exist?(options[:path])\n @db = SQLite3::Database.new(options[:path])\n end",
"def open(options)\n OptionsHash!(options)\n @tc_path = options.require(\"path\")\n @tc_bdb = BDB::new\n @tc_bdb.open(:path => @tc_path, :writer => true, :create => true)\n @tc_bdbcur = BDBCUR::new(@tc_bdb)\n nil\n end",
"def initialize(path, mode = :read)\n @path, @mode, @storages = path, mode, {}\n\n # we can manage our database (full monopoly access) or just read it\n store_mode = if :manage == mode\n TDB::OWRITER | TDB::OCREAT\n else\n TDB::OREADER\n end\n\n # initialize all storages in common manner\n STORAGES.each do |storage_name|\n filename = File.join(path, '%s.tct' % storage_name)\n\n # open our database in defined mode\n storage = TDB.new\n unless storage.open(filename, store_mode)\n raise storage.errmsg(storage.ecode)\n end\n\n # Let there be more Unicode (actually, this solution is full of shit)\n storage.class.class_eval { alias_method :cget, :get }\n\n # @private\n def storage.[] *args\n (r = cget(*args)) && r.each { |_, v| v.force_encoding 'UTF-8' }\n end\n\n # @private\n def storage.get *args\n (r = cget(*args)) && r.each { |_, v| v.force_encoding 'UTF-8' }\n end\n\n # Tokyo Cabinet Extension has strange issues with\n # DB#each method functionality, let's fix it.\n\n # @private\n def storage.each(&block)\n return [] unless iterinit\n while (key = iternext)\n block.call(key)\n end\n end\n\n storages[storage_name] = storage\n end\n\n storages.freeze\n\n super()\n end",
"def open(uri, options = T.unsafe(nil)); end",
"def open_database\n if File.exist? @database_path\n validate_database\n @db = SQLite3::Database.new @database_path\n else\n initialize_database\n end\n end",
"def initialize( path, mode = \"a+\", locking = true )\n mode_bits = Core.mode_to_bits( mode )\n raise Error.new( \"Invalid mode '#{mode}'\" ) unless mode_bits\n lock_bits = Core.locking_to_bits( locking )\n raise Error.new( \"Invalid Locking mode #{locking}\" ) unless lock_bits\n\n @db = lib.tcidbnew()\n\n lib.tcidbopen( @db, path, mode_bits | lock_bits ) || raise_error\n end",
"def open(opts)\n db = Database.new(opts)\n yield db if block_given?\n db\n end",
"def create_database # :nodoc:\n @db = HDB.new\n if !@db.open(@path, default_flags)\n raise CorpusError.new(\"Error creating the database: #{@db.errmsg(@db.ecode)}\")\n end\n end",
"def initialize(uri, options = {})\n @uri = self.class.looks_a_sqlite_file?(uri) ? \"sqlite://#{uri}\" : uri\n @options = options\n end",
"def open(options, *args)\n super(options, *args) do\n # Open options\n options = {:lock => true}.merge(options)\n path = options[:path]\n omode = (options[:writer] ? HDB::OWRITER : HDB::OREADER)\n omode |= HDB::OCREAT if options[:create]\n omode |= HDB::OTRUNC if options[:truncate]\n omode |= HDB::ONOLCK if options[:lock] == false\n omode |= HDB::OLCKNB if options[:lock] == :noblock\n [path, omode]\n end\n end",
"def read(path)\n @dbh = attempt_sqlite3_connection(path) if Pathname(path).exist?\n self\n end",
"def open(options, *args)\n super(options, *args) do\n setcmpfunc(@cmpfunc) if @cmpfunc\n # Open options\n options = {:lock => true}.merge(options)\n path = options[:path]\n omode = (options[:writer] ? BDB::OWRITER : BDB::OREADER)\n omode |= BDB::OCREAT if options[:create]\n omode |= BDB::OTRUNC if options[:truncate]\n omode |= BDB::ONOLCK if options[:lock] == false\n omode |= BDB::OLCKNB if options[:lock] == :noblock\n [path, omode]\n end\n end",
"def open(uri, text, version); end",
"def open_store(file, read_only = true)\n file = file.to_s\n if read_only\n flags = GDBM::READER + GDBM::NOLOCK\n else\n flags = GDBM::SYNC + GDBM::NOLOCK\n end\n @mutex.synchronize do\n GDBM.open(@path + file, 0666, flags) do |gd|\n yield gd\n end\n end\n end",
"def open\n @db.open(@db_path)\n\n #Create meta variables if they are absent\n unless @db.m_get(\"n\")\n @db.m_put(\"n\", \"0\") #Total node count\n @db.m_put(\"m\", \"0\") #Total edge count\n @db.m_put(\"node#{Config::DEFAULT_TYPE}\", \n \"0\") #Node count for default type\n @db.m_put(\"edge#{Config::DEFAULT_TYPE}\", \n Marshal.dump({:directed => false, :count => 0})) #Edge count for default type\n end\n\n end",
"def get_db\n # we want to check a couple levels 2011-09-28 \n unless @db\n unless File.exists? @file\n 3.times do |i|\n @file = \"../#{@file}\"\n break if File.exists? @file\n end\n end\n end\n @db ||= DB.new @file\n end",
"def open( tran: false, mode: :immediate ) # tran = true transaction\n #DBlog::stoD( parse_caller( caller.first ) ) if $debug == true\n @db = SQLite3::Database.new( @DBfile )\n @db.busy_timeout(1000)\n ecount = 0\n roll = false\n begin\n roll = false\n if tran == true\n @db.transaction( mode ) do\n roll = true\n yield self\n end\n else\n yield self\n end\n rescue SQLite3::BusyException => e\n DBlog::sto(\"SQLite3::BusyException tran = #{tran.to_s} #{ecount}\")\n begin\n @db.rollback() if roll == true\n rescue\n DBlog::sto(\"rollback fail #{$!}\")\n end\n if ecount > 59\n Commlib::errPrint( \"SQLite3::BusyException exit\", $!, e )\n return\n else\n #Commlib::errPrint( \"SQLite3::BusyException retry\", $!, e )\n ecount += 1\n sleep( 1 )\n DBlog::sto(\"retry\")\n retry\n end\n rescue => e\n Commlib::errPrint( \"SQLite3::another error\", $!, e )\n begin\n @db.rollback() if roll == true\n rescue\n DBlog::sto(\"rollback fail #{$!}\")\n end\n return\n ensure\n close()\n end\n end",
"def open(file_name, create = T.unsafe(nil), options = T.unsafe(nil)); end",
"def find_or_create_db(filename)\n SQLite3::Database.new(filename)\n end",
"def open(uri_s, options = T.unsafe(nil), &error_block); end",
"def initialize( file_name, mode=0 )\n @handle = SQLite::API.open( file_name, mode )\n @closed = false\n @results_as_hash = false\n @type_translation = false\n @translator = nil\n end",
"def open_db\n if Config.db =~ /^sqlite:\\/{3}(.+)$/\n dir = File.dirname($1)\n FileUtils.mkdir_p(dir) unless File.directory?(dir)\n end\n\n Sequel.datetime_class = Time\n\n @db = Sequel.connect(Config.db, :encoding => 'utf8')\n @db.test_connection\n\n if trait[:sql_log]\n require 'logger'\n @db.logger = Logger.new(trait[:sql_log])\n end\n\n rescue => e\n Ramaze::Log.error(\"Unable to connect to database: #{e}\")\n exit(1)\n end",
"def open(ctx,path,ffi)\n return wrap_context(ctx,__method__,path,ffi) if ctx\n fh = FileHandle.new(path,ffi.flags)\n\n #Save the value return from raw_open to be passed back in raw_read/write etc..\n if (FuseFS::RFUSEFS_COMPATIBILITY)\n fh.raw = @root.raw_open(path,fh.raw_mode,true)\n else\n fh.raw = @root.raw_open(path,fh.raw_mode)\n end\n\n unless fh.raw\n if fh.rdonly?\n fh.contents = @root.read_file(path)\n elsif fh.writing?\n unless @root.can_write?(path)\n raise Errno::EACCES.new(path)\n end\n\n if @created_files.has_key?(path)\n fh.create\n else\n if fh.rdwr? || fh.append?\n fh.contents = @root.read_file(path)\n else #wronly && !append\n #We should get a truncate 0, but might as well play it safe\n fh.contents = \"\"\n end\n end\n else\n raise Errno::ENOPERM.new(path)\n end\n end\n\n #If we get this far, save our filehandle in the FUSE structure\n ffi.fh=fh\n end",
"def open(path_or_url, ext = T.unsafe(nil), options = T.unsafe(nil)); end",
"def openFile path, mode\n\t\tFile.open(path, mode)\n\tend",
"def load_database(filename)\n \n handle = File.open(filename)\n uncompressed = Zlib::GzipReader.new(handle)\n records = DnaIO.new(uncompressed)\n records.to_a\nend",
"def openDB\n db =Rho::Database.new(Rho::Application.databaseFilePath('local'), \"local\");\n puts \"#{db.to_s}\"\n data = db\n data\n end",
"def open(filename, line_number = nil, column_number = nil)\n filename = filename.filepath if filename.is_a? RailsPath\n options = []\n options << \"url=file://#{filename}\"\n options << \"line=#{line_number + 1}\" if line_number\n options << \"column=#{column_number + 1}\" if column_number\n open_url \"txmt://open?\" + options.join(\"&\")\n end",
"def create\n File.open(@db_file, \"w\" ) do |file|\n end\n end",
"def open\n @tmpfile.close if @tmpfile\n \n # dbeswick\n mode = if !@binary\n 'r+'\n else\n 'r+b'\n end\n \n @tmpfile = _open_file(@tmpname, mode)\n @data[1] = @tmpfile\n __setobj__(@tmpfile)\n end",
"def database\n @database ||= opts.fetch(:database, parsed_uri.path[1..-1])\n end",
"def db_create_sqlite3(*args)\n\t\t\tcmd_db_disconnect()\n\n\t\t\tif(args[0] and (args[0] == \"-h\" || args[0] == \"--help\"))\n\t\t\t\tprint_status(\"Usage: db_create [database-file-path]\")\n\t\t\t\treturn\n\t\t\tend\n\n\t\t\tinfo = db_parse_db_uri_sqlite3(args[0])\n\t\t\tdbfile = info[:path]\n\t\t\topts = { 'adapter' => 'sqlite3', 'database' => dbfile }\n\n\t\t\tif (::File.exists?(dbfile))\n\t\t\t\tprint_status(\"The specified database already exists, connecting\")\n\t\t\telse\n\t\t\t\tprint_status(\"Creating a new database instance...\")\n\t\t\t\trequire_library_or_gem('sqlite3')\n\t\t\tend\n\n\t\t\tif (not framework.db.connect(opts))\n\t\t\t\traise RuntimeError.new(\"Failed to connect to the database: #{framework.db.error}\")\n\t\t\tend\n\n\t\t\tprint_status(\"Successfully connected to the database\")\n\n\t\t\tprint_status(\"File: #{dbfile}\")\n\t\tend",
"def open\n create_database\n end",
"def connect_to_db(path) \n db = SQLite3::Database.new(path)\n db.results_as_hash = true\n return db\n end",
"def open_table(path, name)\n name = name.to_s\n @tables[File.join(path, name)] ||= begin\n table = CT::Table.new(@session)\n table.path = path\n table.open(name, CT::OPEN_NORMAL)\n end\n end",
"def initialize(iFileName)\n @TmpFileName = nil\n require 'sqlite3'\n @DB = SQLite3::Database.new(iFileName)\n begin\n # Issue a single select to test if the database is in use\n @DB.execute(\"SELECT * FROM sqlite_master LIMIT 1\")\n rescue SQLite3::BusyException\n # The database is in use.\n # Try copying the file in another place.\n require 'tmpdir'\n @TmpFileName = \"#{Dir.tmpdir}/DB_#{self.object_id}.sqlite\"\n FileUtils::cp(iFileName, @TmpFileName)\n # Try again\n @DB.close\n @DB = SQLite3::Database.new(@TmpFileName)\n end\n end",
"def initialize(opts = {})\n if opts[:path]\n @path = opts[:path]\n else\n @path = DEFAULT_DB_PATH\n end\n\n @db = SQLite3::Database.new(@path)\n\n create()\n end",
"def open_uri(uri)\n case uri.scheme\n when \"file\"\n path = URI.decode(uri.path)\n @@logger.debug \"Attempting to open #{path}\"\n raise MissingAssetError unless File.exist?(path)\n io = File.open(path)\n when \"http\", \"https\"\n io = Tempfile.new(\"common_mapping_file\")\n Net::HTTP.start(uri.host, uri.port) do |http|\n http.request_get(uri.path) do |resp|\n raise MissingAssetError, \"Received a #{resp.code} while trying to retrieve #{uri}\" if resp.code != \"200\"\n resp.read_body do |segment|\n io.write(segment)\n end\n end\n end\n io.rewind\n else\n raise NotImplementedError\n end\n io\n end",
"def read_db()\n if File.exist?('public/tokens.db')\n db = SQLite3::Database.open './public/tokens.db'\n else\n db = []\n end\nend",
"def open(path, opts = {})\n Cubby.logger.warn OPEN_WARNING if defined?(@store) && !@store.nil?\n @store = Cubby::Store.new path, opts\n self\n end",
"def db_connect_sqlite3(*args)\n\t\t\tprint_error(\"Note that sqlite is not supported due to numerous issues.\")\n\t\t\tprint_error(\"It may work, but don't count on it\")\n\n\t\t\tif(args[0] and (args[0] == \"-h\" || args[0] == \"--help\"))\n\t\t\t\tprint_status(\"Usage: db_connect [database-file-path]\")\n\t\t\t\treturn\n\t\t\tend\n\n\t\t\tinfo = db_parse_db_uri_sqlite3(args[0])\n\t\t\tdbfile = info[:path]\n\t\t\topts = { 'adapter' => 'sqlite3', 'database' => dbfile }\n\n\t\t\tif (not ::File.exists?(dbfile))\n\t\t\t\tprint_status(\"Creating a new database file...\")\n\t\t\tend\n\n\t\t\tif (not framework.db.connect(opts))\n\t\t\t\traise RuntimeError.new(\"Failed to connect to the database: #{framework.db.error}\")\n\t\t\tend\n\n\t\t\tprint_status(\"Successfully connected to the database\")\n\t\t\tprint_status(\"File: #{dbfile}\")\n\t\tend",
"def open uri, text, version\n @change_semaphore.synchronize do\n library.open uri_to_file(uri), text, version\n @diagnostics_queue.push uri\n end\n end",
"def open(*args, &block)\n end",
"def initialize\n #Opens a SQLite 3 database file\n @db = SQLite3::Database.new File.join(Dir.pwd,\"lib\",\"app\",\"TentsAndTrees\",\"Game\",\"Core\",\"DB\",\"db.sqlite\")\n end",
"def sqlite(dbname)\n db = SQLite3::Database.new dbname + '.sqlite3'\n yield db\n db.close\nend",
"def open(options)\n OptionsHash!(options)\n @tc_path = options.require(\"path\")\n @tc_storage_path = options[\"storage_path\"] || (@tc_path + \".versions\")\n @tc_heads_path = options[\"heads_path\"] || (@tc_path + \".heads\")\n @tc_log_path = options[\"log_path\"] || (@tc_path + \".log\")\n @tc_storage = HDB::new\n @tc_heads = HDB::new\n @tc_log = BDB::new\n @tc_storage.open(:path => @tc_storage_path, :writer => true, :create => true)\n @tc_heads.open(:path => @tc_heads_path, :writer => true, :create => true)\n # FIXME: i don't really think we need this log file right now.\n @tc_log.open(:path => @tc_log_path, :writer => true, :create => true)\n # REFACTOR THIS\n # TODO: save repo uuid into the versions storage at the very top and ignore in the iterator.\n # brand new repository -> generate UUID for it\n if @tc_log.size == 0\n @uuid = generate_uuid(nil)\n @tc_log.put(REPO_UUID_TOKEN, @uuid)\n else\n @uuid = @tc_log.get(REPO_UUID_TOKEN)\n end\n nil\n end",
"def openthedatabase\n @db = SQLite3::Database.new(@thedatabase)\nend",
"def openDBRanked()\n\t\t@rankedDB \t\t= SQLite3::Database.new File.expand_path('../../../Data/ranked.db', File.dirname(__FILE__))\n\t\t@rankedTimeDB \t= SQLite3::Database.new File.expand_path('../../../Data/rankedTime.db', File.dirname(__FILE__))\n\tend",
"def database\n database = @writable_database || (@database ||= Xapian::Database.new(path))\n \n if self.expired?\n puts 'reloaded'\n database.reopen \n end\n \n database\n end",
"def open(path, max_pools = Nvmkv::MAX_POOLS, expiry_mode = 0, cache_size = 0)\n @file_fd = Nvmkv::file_open(path);\n kv_version = 0\n @kv_id = Nvmkv.kv_open(@file_fd, kv_version, max_pools, expiry_mode, cache_size);\n @kv_id\n end",
"def open_file(filename, line_number = nil, column_number = nil)\n options = []\n options << \"url=file://#{URI.escape(filename)}\"\n options << \"line=#{line_number + 1}\" if line_number\n options << \"column=#{column_number + 1}\" if column_number\n open_url \"txmt://open?\" + options.join(\"&\")\n end",
"def open(_filename, _mode = 'r')\n raise NotImplementedError\n end",
"def create_connection()\n\t\tconnection_properties = java.util.Properties.new\n\t\t@settings.each do |k,v|\n\t\t\tconnection_properties[k] = v\n\t\tend\n\t\treturn java.sql.DriverManager.getConnection(\"jdbc:sqlite:#{@file}\",connection_properties)\n\tend",
"def open(*args)\r\n\t\t\toptions={}\r\n\t\t\toptions[:name]=args.shift if !args[0].nil? and args[0].class==String\r\n\t\t\t@openoptions=options.merge(args[0]) unless @openoptions!=nil\r\n\t\t\toptions=options.merge(args[0])\r\n\t\t\tif @fh!=nil\r\n\t\t\t\tself.close\r\n\t\t\tend\r\n\t\t\texternal_fh=false\r\n\t\t\tif options[:name]=='-'\r\n\t\t\telse\r\n\t\t\t\tok=true\r\n\t\t\t\tif !options[:readonly]\r\n\t\t\t\t\tfh=File.new(options[:name],'w+')\r\n\t\t\t\t\trw=true\r\n\t\t\t\telse\r\n\t\t\t\t\tfh=File.new(options[:name],'r+')\r\n\t\t\t\t\trw=false\r\n\t\t\t\t\tok=true\r\n\t\t\t\tend\r\n\t\t\t\tif !ok\r\n\t\t\t\t\traise \"Error opening file #{options[:name]}: $!\\n\"\r\n\t\t\t\tend\r\n\t\t\tend\r\n\t\t\t@tell=0 if @SEEK_VIA_READ\r\n\t\t\tfh.flush\r\n\t\t\tfh.binmode unless external_fh\r\n\t\t\t@fh,@filename,@rw=fh,options[:name],rw\r\n\t\t\tself.read_header options\r\n\t\tend",
"def file(path, flags = 0, mode = 0)\n assert_type(String, path, \"path must be a String\")\n assert_type(Integer, flags, \"flags must be an Integer\")\n assert_type(Integer, mode, \"mode must be an Integer\")\n File.new(@loop, path, flags, mode)\n end",
"def open( uri, options = {} )\n cmd, args = cmd_and_args( uri, options )\n run( cmd, args )\n end",
"def open(filename, mode = 'r', &block)\n raise NotImplementedError\n end",
"def open path, mode=\"r\", &blk\n end",
"def database_type\n :sqlite\n end",
"def open\n _close\n mode = @mode & ~(File::CREAT|File::EXCL)\n @tmpfile = File.open(@tmpfile.path, mode, **@opts)\n __setobj__(@tmpfile)\n end",
"def file_via_connection(path)\n # TODO: can I replace this with a class that will work more efficiently with lxd api calls?\n Train::File::Remote::Linux.new(self, path)\n end",
"def database_path=(val)\n @database_path = val.index(\"://\").nil? ? \"sqlite3://#{val}\" : val\n load_signatures\n end",
"def db\n @db ||= (create_directory cache_path; SQLite3::Database.new cache_path)\n end",
"def open path, mode=\"r\", &blk\n end",
"def connect_to_db()\n SQLite3::Database.new('db/database.db')\n end",
"def open\n connection_string = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source='\n connection_string << @mdb\n @database = Sequel.ado(:conn_string=>connection_string) # connect to Access DB\n end",
"def open(fmode)\n\t\tres=true\n\t\tbegin\n\t\t\t@fp = File.open(@fname,fmode) \n\t\trescue\n\t\t\tSD::Log.msg('Err',\"ResultFile file open failed\", $!)\n\t\t\t@fp=nil\n\t\t\tres=false\n\t\tend\n\t\treturn res\n\tend",
"def initialize(uri)\n @uri = uri\n# create_database_if_missing!\n end",
"def file(path, flags = 0, mode: 0, **opts, &blk)\n assert_type(String, path, \"path must be a String\")\n assert_type(Integer, flags, \"flags must be an Integer\")\n assert_type(Integer, mode, \"mode must be an Integer\")\n File.new(@reactor, path, flags, mode: mode, **opts, &blk)\n end",
"def fopen(uri, *args, &block)\n\n # should I really care about blocks here ? ...\n\n u = URI.parse uri.to_s\n\n return File.open(uri.to_s, &block) \\\n if u.scheme == nil\n\n return File.open(uri.to_s[5..-1], &block) \\\n if u.scheme == 'file'\n\n if u.scheme == 'http' or u.scheme == 'https'\n\n r = EndPoint.request(:get, [ uri ] + args) \\\n\n if block\n block.call r\n return\n end\n\n class << r\n def read\n self.body\n end\n end unless r.respond_to?(:read)\n\n return r\n end\n\n raise \"can't handle scheme '#{u.scheme}' for #{u.to_s}\"\n end",
"def open(path, mode=\"rb\", options={})\n options = {\n :io_index => nil,\n :reindex => false,\n :auto_reindex => true\n }.merge(options)\n \n index = options[:io_index]\n if index == nil\n index = index_path(path)\n FileUtils.touch(index) unless File.exists?(index)\n end\n \n begin\n io = path == nil ? nil : File.open(path, mode)\n io_index = case index\n when Array, ExternalIndex then index\n else ExternalIndex.open(index, 'r+', :format => 'II')\n end\n rescue(Errno::ENOENT)\n io.close if io\n io_index.close if io_index\n raise\n end\n \n extarc = new(io, io_index)\n \n # reindex if necessary\n if options[:reindex] || (options[:auto_reindex] && extarc.empty? && extarc.io.length > 0)\n extarc.reindex\n end\n \n if block_given?\n begin\n yield(extarc)\n ensure\n extarc.close\n end\n else\n extarc\n end\n end",
"def readFromDB\n File.open('db.txt', 'r+') do |file|\n file.readlines\n end\nend",
"def create_db\n SQLite3::Database.new \"flatiron.db\"\nend",
"def initialize( path )\n @db = SQLite3::Database.new( path )\n @count_hits = false\n @busy_retries = 100\n\n # Wait up to 10 seconds to access locked database\n @db.busy_handler do |resource,retries|\n sleep 0.1\n retries<@busy_retries\n end\n \n # Create the table, if it doesn't exist\n if @db.table_info(TABLE_NAME).empty?\n @db.execute( %Q{\n CREATE TABLE #{TABLE_NAME} (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n key TEXT,\n value TEXT,\n hits INTEGER DEFAULT 0,\n created_at INTEGER,\n updated_at INTEGER\n );\n } )\n @db.execute( %Q{ CREATE UNIQUE INDEX key_index ON #{TABLE_NAME} (key) } )\n end\n end",
"def database\n @writable_database || (@database ||= Xapian::Database.new(path))\n end",
"def initialize(file = File.expand_path(File.join(File.dirname(__FILE__), '../../../db/ush.sqlite.db')))\n FileUtils.touch(file) unless File.exist?(file) # create the db if it doesnt already exist\n puts \"Database is being stored at #{file}\"\n @db = SQLite3::Database.new(file)\n @db.execute 'CREATE TABLE IF NOT EXISTS pairings(url TEXT, code TEXT)'\n end",
"def get_connection(dbfile)\n if defined?(JRUBY_VERSION) # JRuby\n require 'dbi'\n\n db = DBI.connect(\"DBI:Jdbc:SQLite:#{dbfile}\", nil, nil, 'driver' => 'org.sqlite.JDBC')\n class << db\n # jdbc/sqlite3 has no Database#execute_batch method\n def execute_batch(batch)\n batch.strip.split(';').each do |sth|\n self.do(sth.strip)\n end\n end\n\n # jdbc/sqlite3 instead of 'close' uses 'disconnect' method\n def close\n self.disconnect\n end\n\n alias_method :do_transaction, :transaction\n # Disable auto-commit, perform transaction and restore default DBI auto-commit behavior\n def transaction(&block)\n self['AutoCommit'] = false\n self.do_transaction(&block)\n self['AutoCommit'] = true\n end\n end\n else # MRI Ruby\n require 'sqlite3'\n db = SQLite3::Database.new(dbfile)\n end\n\n db\n end",
"def db_setup\n log_debug\n db_file = find_db\n db_tmp = '/tmp/plex_missing_tmp.db'\n @db = ''\n \n # cp to tmp as the db is locked if being used\n `cp \"#{db_file}\" #{db_tmp}`\n \n # not too sure why but i was having a problem where a 0 byte file was cp'd\n # def a local issue i assume but the check was needed\n if test ?s, db_tmp\n @db = SQLite3::Database.new db_tmp\n else \n puts \"error-> can not open #{db_tmp} for reasing\"\n exit 2\n end\n end",
"def open\n conn = connection.protocol::DbOpen.new(params(name: @name, storage: @storage, user: @user, password: @password)).process(connection)\n @session = conn[:session] || OrientdbBinary::OperationTypes::NEW_SESSION\n\n @clusters = conn[:clusters]\n self\n end",
"def file_open(*args, &block)\n if __transport_connection\n content = __transport_connection.file(args[0]).content\n string_io = StringIO.new content\n yield string_io if block_given?\n string_io\n else\n File.open(*args, &block)\n end\n end",
"def db_record\n db or MyBiaDJ::Table(:files)[:path => relative_path, :name => name.to_s]\n end",
"def open(file, mode='r', &block)\n if @default == :open_file\n open_file file, mode, &block\n else\n open_hg file, mode, &block\n end\n end",
"def open\n object.open\n end",
"def location= uri\n native.open uri\n end",
"def open?(uri); end",
"def initialize(file='corpus.db')\n @path = File.join(default_path, file)\n @filename = file\n FileUtils.mkdir_p(default_path) unless File.exists?(default_path)\n create_database\n end",
"def file(key, mode=nil, opts={}, &block)\n handle = Handle.new(self, key)\n case\n when mode then handle.open(mode, opts, &block) if mode\n when block then block.call(handle)\n else handle\n end\n end",
"def open!(file, *args, &block); end",
"def open(path, flags, options)\n flags = normalize_open_flags(flags)\n\n if flags & (IO::WRONLY | IO::RDWR) != 0\n sftp_flags = FV1::WRITE\n sftp_flags |= FV1::READ if flags & IO::RDWR != 0\n sftp_flags |= FV1::APPEND if flags & IO::APPEND != 0\n else\n sftp_flags = FV1::READ\n end\n\n sftp_flags |= FV1::CREAT if flags & IO::CREAT != 0\n sftp_flags |= FV1::TRUNC if flags & IO::TRUNC != 0\n sftp_flags |= FV1::EXCL if flags & IO::EXCL != 0\n\n attributes = attribute_factory.new(options)\n\n send_request(FXP_OPEN, :string, path, :long, sftp_flags, :raw, attributes.to_s)\n end",
"def database\n db = SQLite3::Database.new 'foosey.db'\n\n yield db\nrescue SQLite3::Exception => e\n puts e\n puts e.backtrace\nensure\n db.close if db\nend",
"def load_file_through_database(filename, extension = \"csv\", path = \"/tmp/\")\n full_file_path = \"#{q(path)}#{q(filename)}.#{q(extension)}\"\n logger.debug(\" >> load_file_through_database(#{filename})\")\n file = ActiveRecord::Base.connection.execute(\"select LOAD_FILE('#{full_file_path}')\") #.fetch_row()[0]\n if file.first[0]\n File.open(full_file_path, 'w') { |f| f.write(file.first[0].encode(\"UTF-8\", :invalid => :replace, :undef => :replace, :replace => \"?\")) }\n logger.debug(\" >> load_file_through_database = file\")\n return filename\n else\n logger.debug(\" << load_file_through_database = nil\")\n return nil\n end\n end",
"def initialize(file_name='persistance.db')\n require 'gdbm'\n # Creates database file if it doesn't exist\n @file_name = file_name\n unless File.directory?('db')\n Dir.mkdir('db/')\n end\n @db = GDBM.new('db/' + file_name)\n @wallet_db = GDBM.new('db/wallets_' + file_name)\n end",
"def _open(filename)\n File.open(filename, 'rb')\n end",
"def file\n TestIds.database_file(id)\n end",
"def database(loc)\n @db = GeoIPCity::Database.new(loc, :filesystem)\n end",
"def db_file\n self.class.db_root.join(id) if id\n end",
"def validate_database\n db = @database_path\n raise \"bad mode of #{db}\" unless File.world_readable?(db).nil?\n end",
"def open_uri(*args, &blk)\n OpenURI::DbCache::Page.fetch(*args, &blk)\n end",
"def init_db\n db_filename = './coord_cache.db'\n puts \"Creating db file '#{db_filename}'\" unless File.exist?(db_filename)\n @coord_db = SQLite3::Database.new(db_filename)\n @coord_db.execute('CREATE TABLE IF NOT EXISTS coords ' \\\n '(id INTEGER PRIMARY KEY AUTOINCREMENT, ' \\\n ' osm_id BIGINT, ' \\\n ' lat REAL, ' \\\n ' lon REAL)')\nend"
] |
[
"0.6886159",
"0.6755556",
"0.66981125",
"0.6550848",
"0.6532551",
"0.6516999",
"0.64219695",
"0.6117631",
"0.6093412",
"0.6080202",
"0.60689014",
"0.60628444",
"0.60472375",
"0.6038953",
"0.6009289",
"0.5993715",
"0.5974676",
"0.59687597",
"0.5957488",
"0.5949796",
"0.5936086",
"0.59124",
"0.58841217",
"0.578941",
"0.57864195",
"0.57433254",
"0.5726998",
"0.5702679",
"0.56536245",
"0.56444633",
"0.5643526",
"0.5642357",
"0.56096596",
"0.5588248",
"0.55787486",
"0.55607486",
"0.55237377",
"0.551984",
"0.54891324",
"0.5479942",
"0.5477463",
"0.5462912",
"0.54478174",
"0.5441543",
"0.5440427",
"0.5440029",
"0.5427638",
"0.54116",
"0.54096127",
"0.5409202",
"0.5392848",
"0.5390002",
"0.5388389",
"0.53764474",
"0.5365724",
"0.53601515",
"0.535856",
"0.5357584",
"0.5338218",
"0.5320262",
"0.53190356",
"0.53148085",
"0.53122556",
"0.5307365",
"0.5305839",
"0.5303947",
"0.5300372",
"0.5294688",
"0.5283268",
"0.5276153",
"0.5274585",
"0.5252756",
"0.5245812",
"0.5237503",
"0.52325857",
"0.52298915",
"0.52293885",
"0.52233934",
"0.5203258",
"0.519606",
"0.51896465",
"0.5185916",
"0.5159235",
"0.5136483",
"0.5136106",
"0.513318",
"0.5128907",
"0.511017",
"0.51086557",
"0.5105564",
"0.5064491",
"0.50516325",
"0.50474876",
"0.50242734",
"0.5020863",
"0.50206596",
"0.50169426",
"0.5011754",
"0.50046074",
"0.5001269"
] |
0.76090646
|
0
|
Takes an array of open mode symbols and returns the mode number: open_mode(:read, :write, :sync) 3 open_mode(:read, :write, :sync) 67
|
def open_mode(*modes)
modes.inject(0) { |memo, obj| memo | OPEN_MODES[obj.to_sym].to_i }
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def modes\n mode_codes.keys\n end",
"def modes\n fix_mode.modes\n end",
"def get_modes\n @_modes\n end",
"def mode\n \"%o\" % (self.stat(:mode) & 007777)\n end",
"def mode(io) \n readable, writable = try_handle(io, \"mode\")\n\n case\n when readable && writable then \"r+\"\n when readable then \"r\"\n when writable then \"w\"\n else\n # occurs for r+ mode, for some reason\n \"r+\"\n end\n end",
"def mode\n modes(false)[0]\n end",
"def mode\n modes(false)[0]\n end",
"def mode\n case @data_list\n when QRNumeric\n :mode_number\n when QRAlphanumeric\n :mode_alpha_numk\n else\n :mode_8bit_byte\n end\n end",
"def modes; end",
"def mode \n frequency_count = reduce(Hash.new(0)) { |freq, value| freq[value] += 1; freq}\n mode_count = frequency_count.values.max\n mode = frequency_count.select { |key, value| value == mode_count } # Select mode pairs\n return mode.keys.max # In case of multi-modes, return largest\n end",
"def mode() @mode ||= detect_mode end",
"def mode() end",
"def get_mode()\n end",
"def mode(path)\n stat('-c', '%a', path).oct\n end",
"def mode=(a_mode)\n @@mode = a_mode.to_sym\n end",
"def mode; end",
"def mode; end",
"def mode; end",
"def mode; end",
"def mode\n @mode\n end",
"def mode(mode)\n\tmode_return = mode.inject({}) { |k, v| k[v] = mode.count(v); k }\n\tmode_return.select { |k,v| v == mode_return.values.max }.keys\nend",
"def mode_name\n if mode >= 0 && mode <= 15\n MODES[mode]\n else\n \"(#{mode})\"\n end\n end",
"def mode array\n\tmode_array = Hash.new(0)\n\tarray.each{ |i| mode_array[i] +=1}\n\tmode_array = mode_array.sort_by{|a,b| b}\n\tmode_array.reverse!\n\treturn mode_array[0]\nend",
"def mode(mode)\n mode_return = mode.inject(Hash.new()) do |key, value|\n \tkey[value] = mode.count(value);\n \tkey\n end\n mode_return.select {|key, value| value == mode_return.values.max}.keys\nend",
"def get_mode(key)\n case key\n when \"S\", \"s\" then -1 # AUTO\n when \"N\", \"n\" then 0 # NUMERIC\n when \"A\", \"a\" then 1 # ALNUM - British number: 0-9 A-Z SP $% * + - /.:\n when \"8\" then 2 # 8BIT\n when \"K\", \"k\" then 3 # KANJI\n end\n end",
"def modes\n\t\tmodes_array = Array.new\n\t\tmost = self.most\n\t\tcounts = self.counts\n\t\tcounts.each_pair do |key,value|\n\t\t\tif value == most\n\t\t\t\tmodes_array.push(key)\n\t\t\tend\n\t\tend\n\t\treturn modes_array\n\t end",
"def mode\n if stat = resource.stat\n return (stat.mode & 007777).to_s(8)\n else\n return :absent\n end\n end",
"def get_mode()\n return(get_cmd('MD;',0.1,0.5,3).gsub(/^MD/,'').gsub(/;$/,'').to_i)\nend",
"def filemode(file)\n File.stat(file).mode & 007777\n end",
"def mode\n \"%o\" % (File.stat(@resource[:name]).mode & 007777)\n end",
"def run_mode(arr)\n stuff = start\n args_checker = ArgsChecker.new\n\n if args_checker.check_mode(arr)\n repl_mode = ReplMode.new\n repl_mode.run_repl(stuff[0], stuff[1])\n else\n file_mode = FileMode.new\n file_mode.run_file(arr, stuff[0], stuff[1])\n end\nend",
"def get_mode\n send_request(FUNCTION_GET_MODE, [], '', 1, 'C')\n end",
"def mode_sym\n (mode || :off).to_sym\n end",
"def mode=(m)\n @mode = m.to_sym\n end",
"def param_mode(opcode, param_index, mode)\n return 0 if opcode == 3 && mode == 1\n return 0 if param_index == 3 && mode == 1\n\n mode\n end",
"def mode(array)\n count = {}\n modes = []\n\n array.each do |el|\n count[el] = count[el].to_i + 1\n end\n\n most = count.invert.sort.to_a.last.first\n count.each_pair do |x, y|\n modes << x if y == most\n end\n\n return modes\nend",
"def fat_mode(window_size=10)\n\n fat_modes=[]\n max_fat=0\n\n self.length.times do |i|\n fat=get_window_value(i)\n\n fat_modes << fat\n\n if fat_modes[max_fat] < fat\n max_fat=i\n end\n\n end\n # puts \"algo\",max_fat\n return [max_fat,fat_modes[max_fat]]\n end",
"def modes\n @modes + autobuild.utilities.values.\n find_all { |u| u.enabled? }.\n map(&:name)\n end",
"def mode(mode)\n mode_return = mode.inject({}) { |k, v| k[v] = mode.count(v); k }\n mode_return.select { |k,v| v == mode_return.values.max }.keys\nend",
"def mode(mode)\n mode_return = mode.inject({}) { |k, v| k[v] = mode.count(v); k }\n mode_return.select { |k,v| v == mode_return.values.max }.keys\nend",
"def mode\n\t\treturn self.modes[0]\n\tend",
"def mode array\n hash = Hash.new(0)\n array.each { |i| hash[i]+=1 }\n hash\n end",
"def mode\n Mode.new(ENV).mode\n end",
"def target_mode\n return nil if resource.mode.nil?\n (resource.mode.respond_to?(:oct) ? resource.mode.oct : resource.mode.to_i) & 007777\n end",
"def mode(list)\nmax_count = 0\nmode = list[0]\n\n list.each do |n| # looking for a mode, number by number\n \n count = 0\n list.each do |m| # count how many \"n\"s there are\n if m == n\n count += 1\n end\n end\n if count > max_count\n max_count = count\n mode = n\n end\n end\n return mode\nend",
"def mode\n Initialize() if @_mode == nil\n\n @_mode\n end",
"def mode\n params['mode']\n end",
"def modes\n fre = frequencies\n max = fre.values.max\n fre.select { |k, f| f == max }\n end",
"def mode=(_arg0); end",
"def mode=(_arg0); end",
"def mode=(_arg0); end",
"def mode_options\n @mode_options ||= begin\n s_opts = symmetric_options if mode != :asymmetric\n a_opts = asymmetric_options if mode != :symmetric\n [s_opts, a_opts].compact.join(\" \")\n end\n end",
"def mode(array)\n\tmode = []\n\tmode = array.inject\nend",
"def modes(find_all = true)\n return nil if empty?\n\n histogram = each_with_object(Hash.new(0)) { |n, h| h[n] += 1 }\n modes = nil\n histogram.each_pair do |item, times|\n modes << item if find_all && !modes.nil? && times == modes[0]\n modes = [times, item] if (modes && times > modes[0]) || (modes.nil? && times > 1)\n end\n modes.nil? ? nil : modes[1...modes.size]\n end",
"def modes(find_all = true)\n return nil if empty?\n\n histogram = each_with_object(Hash.new(0)) { |n, h| h[n] += 1 }\n modes = nil\n histogram.each_pair do |item, times|\n modes << item if find_all && !modes.nil? && times == modes[0]\n modes = [times, item] if (modes && times > modes[0]) || (modes.nil? && times > 1)\n end\n modes.nil? ? nil : modes[1...modes.size]\n end",
"def mode\n if File.exists?(@resource[:name])\n \"%o\" % (File.stat(@resource[:name]).mode & 007777)\n else\n :absent\n end\n end",
"def mode\n options[:mode]\n end",
"def normalize_open_flags(flags)\n if String === flags\n case flags.tr(\"b\", \"\")\n when \"r\" then IO::RDONLY\n when \"r+\" then IO::RDWR\n when \"w\" then IO::WRONLY | IO::TRUNC | IO::CREAT\n when \"w+\" then IO::RDWR | IO::TRUNC | IO::CREAT\n when \"a\" then IO::APPEND | IO::CREAT | IO::WRONLY\n when \"a+\" then IO::APPEND | IO::CREAT | IO::RDWR\n else raise ArgumentError, \"unsupported flags: #{flags.inspect}\"\n end\n else\n flags.to_i\n end\n end",
"def mode=(new_mode)\n handle_old_mode\n @mode = new_mode\n handle_new_mode\n end",
"def mode (list)\n\tmodes = []\n\tmost_numbers = 0\n\tcounts = Hash.new 0\n\tlist.each do |number|\n\t\tlist.count(number)\n\t\tif most_numbers < list.count(number)\n\t\t\tmost_numbers = list.count(number)\n\t\tend\n\tend\n\tlist.each do |number|\n\t\tlist.count(number)\n\t\tif list.count(number) == most_numbers\n\t\t\tmodes.push(number)\n\t\tend\n\tend\n\tmodes = modes.uniq\n\treturn modes\nend",
"def io_mode(io)\n begin\n dup = io.dup\n \n # determine readable/writable by sending close methods\n # to the duplicated Io. If the io cannot be closed for \n # read/write then it will raise an error, indicating that \n # it was not open in the given mode. \n [:close_read, :close_write].collect do |method|\n begin\n dup.send(method)\n true\n rescue(IOError)\n false\n end\n end\n ensure\n # Be sure that the dup is fully closed before proceeding! \n # (Otherwise Tempfiles will not be properly disposed of\n # ... at least on Windows, perhaps on others)\n dup.close if dup && !dup.closed?\n end\n end",
"def get_mode()\n session['mode'] = session['mode'] || 'edit'\n return session['mode']\n end",
"def mode(array)\n mode = array.inject(Hash.new(0)) { |i,x| i[x] = i[x] + 1; i}\n mode.select{ |i,x| x == mode.values.max }.keys\nend",
"def set_mode(m)\n @mode = m\n end",
"def mode(array)\n frequency = Hash.new(0)\n\tarray.each do |key|\n\t\tfrequency[key] +=1\n\tend\n\tmode = []\n\tfrequency.each do |k, v|\n if k == frequency.values.max\n mode << v\n end\n end\n\treturn mode\nend",
"def has_mode?(mode)\r\n return false if @modes.nil?\r\n return @modes.include?(mode)\r\n end",
"def _stat_map(mode)\r\n mode = _fstat_map(mode)\r\n if $os <= Windows\r\n mode &= ~0022\r\n end\r\n mode\r\n end",
"def mode\n attributes.fetch(:mode) do\n Ably::Util::Crypto::DEFAULTS.fetch(:mode)\n end.downcase\n end",
"def mode(ary)\n\ti = 1\n\tmode = []\n\tary.each do |element|\n\t\tj = ary.count(element) \n\t\tif j > i \n\t\t\ti = j\n\t\t\tmode = [element]\n\t\telsif j == i && !mode.include?(element)\n\t\t\tmode += [element]\n\t\tend\n\tend\n\treturn mode\nend",
"def other_readable?(mode)\n mode & 00004 == 00004\n end",
"def mode(*modes, &block)\n modes.each do |mode|\n @modes[mode] ||= {}\n @modes[mode][:function] = block\n end\n end",
"def mode(target, modes = [], parameters = [])\n if modes.size > 3\n messages = (modes.size / 3 + 1).times.map do\n mode target, modes.shift(3), parameters.shift(3)\n end\n\n raw messages.join\n else\n parameters = Array(parameters)\n modes = Array(modes).map! { |m| m.to_s.start_with?('-') ? m : +m }\n groups = modes.group_by { |m| m[0] }\n pos, neg = Array(groups['+']), Array(groups['-'])\n\n mode_string = String.new\n mode_string << \"+#{pos.map { |m| m[1] }.join}\" unless pos.empty?\n mode_string << \"-#{neg.map { |m| m[1] }.join}\" unless neg.empty?\n\n raw \"MODE #{target} #{mode_string} #{parameters.join \" \"}\".strip << \"\\r\\n\"\n end\n end",
"def mode(array)\n\tvals = {}\n\tmode_vals = []\n\tarray.each {|x|\n\t\tif vals.include? x \n\t\t\tvals[x] += 1\n\t\telse\n\t\t\tvals[x] = 1\n\t\tend\n\t}\n\t#hash.values puts values in array. array.max returns the max!\n\tmax = vals.values.max\n\tvals.each {|key,value| \n\t\tmode_vals.push(key) if value == max\n\t}\n\tmode_vals\nend",
"def each_mode(&blk)\r\n return if @modes.nil?\r\n @modes.each_char do |c|\r\n yield c\r\n end\r\n end",
"def mode(array)\n\tvals = {}\n\tmode_vals = []\n\tarray.each {|element|\n\t\tif vals.include? element \n\t\t\tvals[element] += 1\n\t\telse\n\t\t\tvals[element] = 1\n\t\tend\n\t}\n\tmax = vals.values.max\n\tvals.each {|key,value| \n\t\tmode_vals.push(key) if value == max\n\t}\n\tmode_vals\nend",
"def mode?\n return @mode\n end",
"def prettymode\n m = mode\n om = '%04o' % m\n perms = ''\n\n 3.times {\n perms = ((m & 01) == 01 ? 'x' : '-') + perms\n perms = ((m & 02) == 02 ? 'w' : '-') + perms\n perms = ((m & 04) == 04 ? 'r' : '-') + perms\n m >>= 3\n }\n\n return \"#{om}/#{perms}\"\n end",
"def build_mode_from_options(options)\n if options[:mode]\n case options[:mode]\n when String\n return options[:mode]\n when Symbol\n return options[:mode].to_s.upcase\n else\n raise TypeError.new(INVALID_TYPE_MSG)\n end\n else\n return \"ASC\"\n end\n end",
"def next_mode new_mode\n if has_mode? new_mode\n @mode = new_mode\n else\n warn \"Robot #{self.class} switched to unknown mode :#{new_mode}!\"\n @mode = :idle\n end\n end",
"def mode=(mode)\n Nitro.mode = mode.to_sym\n end",
"def add_sec_modes *modes\n modes.flatten.each do |new_mode|\n add_sec_mode new_mode\n end\n end",
"def mode(array)\n table = Hash.new(0)\n for a in array\n table[a] = table[a] + 1\n end\n highest_freq = 0\n table.each do |k, v|\n if v > highest_freq\n highest_freq = v\n end\n end\n modes_hash = table.select{|k, v| highest_freq == v}\n modes = modes_hash.keys\nend",
"def selected_mode\n @selected_mode\n end",
"def mode=(type)\n @mode = type.to_s\n end",
"def mode=(mode)\n @mode = mode ? mode.to_sym : nil\n end",
"def mode(array)\n\tfrequency = Hash.new\n\n\tfor i in array\n\t\tfrequency[i] = array.count(i)\n\tend\n\n\tmost_frequent_key = frequency.values.max\n\tmode_list = []\n\n\tfor key, value in frequency\n\t\tif value == most_frequent_key\n\t\t\tmode_list << key\n\t\tend\n\tend\n\treturn mode_list\nend",
"def modes(id = nil, _options = {})\n id = nil if id.is_a?(Hash)\n if id\n _modes[id]\n else\n _modes.ids\n end\n end",
"def mode pin\n reg = pin / 10\n shift = (pin % 10) * 3\n (get_int_at(reg) >> shift) & 7\n end",
"def options_or_mode(oom)\n return fmode(oom) if oom.kind_of? String\n\n if FeatureGuard.enabled? :encoding\n oom\n else\n fmode(oom[:mode] || \"r:utf-8\")\n end\n end",
"def set_access_mode(mode = :r)\n modes = [:r, :w, :rw, :x]\n raise ArgumentError, \"Mode must be one of #{modes}\" unless modes.include? mode\n case mode\n when :r\n self.access_mode = 0\n when :w\n self.access_mode = 1\n when :rw\n self.access_mode = 2\n when :x\n self.access_mode = 3\n end\n end",
"def opcode\n if @extended\n return 0x00 | (@op << 5) | (a_param.mode_bits << 10)\n else\n return @op | (a_param.mode_bits << 10) | (b_param.mode_bits << 5)\n end\n end",
"def fileModeToFileType\n @@FM2FT[@mode & MSK_FILE_MODE]\n end",
"def fileModeToFileType\n @@FM2FT[@mode & MSK_FILE_MODE]\n end",
"def mode=(val)\n if val.blank? or val.kind_of? Fixnum then\n write_attribute(:mode, val)\n else\n write_attribute(:mode, Mode[val])\n end\n end",
"def mode(array)\n\tfrequencies = Hash.new(0)\n\tarray.each { |array_object| frequencies[array_object]+=1 }\n\tfrequencies = frequencies.select { |key,value| value>= frequencies.values.max }\n\tmode_array = []\n\tfrequencies.each_key {|key| mode_array << key}\n\treturn mode_array\nend",
"def mode=(new_mode)\n @mode , @previous_mode = new_mode, @mode\n build_chains() if @mode != @previous_mode && @previous_mode != nil && @previous_mode != \"\"\n end",
"def duplex_modes\n return @duplex_modes\n end",
"def mode(array)\n\tinitialCount = 1\n\tarrayMode = []\n\tarray.each do |element|\n\t count = array.count {|j| j == element}\n\t if count > initialCount\n\t \tinitialCount = count\n\t \tarrayMode = [element]\n\t elsif count == initialCount && count != 1\n\t \tarrayMode.push(element)\n\t end\n\tend\n\tarrayMode = arrayMode.uniq\n\treturn arrayMode\nend",
"def modes= m\n m.instance_eval \"def to_s; self.join(','); end\" if m.is_a?(Array) #override to_s\n @modes = m\n end",
"def mode\n raise \"Not implemented\"\n end"
] |
[
"0.7007333",
"0.63937294",
"0.63889694",
"0.62738407",
"0.62436235",
"0.61912835",
"0.61912835",
"0.6170272",
"0.60947335",
"0.6063899",
"0.605558",
"0.6018973",
"0.59452987",
"0.59145707",
"0.58938867",
"0.58720183",
"0.58720183",
"0.58720183",
"0.58720183",
"0.5861154",
"0.585568",
"0.584995",
"0.5844677",
"0.5840159",
"0.5809703",
"0.58034205",
"0.58024",
"0.5776098",
"0.576834",
"0.57666576",
"0.57467276",
"0.5746166",
"0.5732855",
"0.5719461",
"0.5685431",
"0.56746984",
"0.56645966",
"0.56593263",
"0.565635",
"0.565635",
"0.5634731",
"0.5600548",
"0.55813175",
"0.5575722",
"0.55752265",
"0.5575166",
"0.5568202",
"0.5566744",
"0.5543869",
"0.5543869",
"0.5543869",
"0.55409634",
"0.55391836",
"0.55297196",
"0.55297196",
"0.55256504",
"0.55181956",
"0.5503937",
"0.5488966",
"0.5471164",
"0.5438975",
"0.5433214",
"0.5423049",
"0.53869486",
"0.5370191",
"0.5361203",
"0.53599066",
"0.5355823",
"0.5354517",
"0.5346617",
"0.5338006",
"0.5334184",
"0.53263205",
"0.53163046",
"0.53161526",
"0.5300982",
"0.5282481",
"0.5277469",
"0.52621585",
"0.5262002",
"0.5254238",
"0.5252423",
"0.52523357",
"0.5242494",
"0.52384776",
"0.5226132",
"0.52074",
"0.52009135",
"0.51975036",
"0.51972306",
"0.5185058",
"0.5181879",
"0.5181879",
"0.5177134",
"0.5176586",
"0.51750016",
"0.5170806",
"0.5168931",
"0.5168741",
"0.51661956"
] |
0.81249195
|
0
|
Use callbacks to share common setup or constraints between actions.
|
def set_order
@order = Order.find(params[:id])
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def set_required_actions\n # TODO: check what fields change to asign required fields\n end",
"def action_hook; end",
"def run_actions; end",
"def define_action_hook; end",
"def actions; end",
"def define_action_helpers\n if super && action == :save\n @instance_helper_module.class_eval do\n define_method(:valid?) do |*args|\n self.class.state_machines.fire_event_attributes(self, :save, false) { super(*args) }\n end\n end\n end\n end",
"def add_actions; end",
"def callbacks; end",
"def callbacks; end",
"def setup *actions, &proc\n (@setup_procs ||= []) << [proc, actions.size > 0 ? actions : [:*]]\n end",
"def define_action_helpers; end",
"def post_setup\n end",
"def action_methods; end",
"def action_methods; end",
"def action_methods; end",
"def before_setup; end",
"def action_run\n end",
"def execute(setup)\n @action.call(setup)\n end",
"def define_action_helpers?; end",
"def set_actions\n actions :all\n end",
"def action_done(action)\n dispatch = { :migrate => :done_migrating, :map => :done_mapping, :reduce =>\n :done_reducing, :finalize => :done_finalizing } \n self.send dispatch[action[:action]], action\n end",
"def dependencies action, &block\n @actions.each do |other|\n if action[:requires].include? other[:provide]\n block.call other\n end\n end\n end",
"def setup!\n return unless @setup_procs\n http_actions = actions\n @setup_procs.each do |setup_proc|\n proc, actions = setup_proc\n @setup__actions = actions.map do |action|\n\n action.is_a?(Regexp) ?\n http_actions.select { |a| a.to_s =~ action } :\n action.is_a?(String) && action =~ /\\A\\./ ?\n http_actions.map { |a| a.to_s << action if format?(a).include?(action) }.compact :\n action\n\n end.flatten\n self.class_exec &proc\n @setup__actions = nil\n end\n @setup_procs = nil\n end",
"def before_actions(*logic)\n self.before_actions = logic\n end",
"def setup_handler\n end",
"def set_action(opts)\n opts = check_params(opts,[:actions])\n super(opts)\n end",
"def setup(action)\n @targets.clear\n unless action.item.target_filters.empty?\n @targets = SES::TargetManager.make_targets(action)\n else\n item = action.item\n if item.for_opponent?\n @targets = $game_troop.alive_members\n elsif item.for_dead_friend?\n @targets = $game_party.battle_members.select { |actor| actor.dead? }\n else\n $game_party.battle_members.select { |actor| actor.alive? }\n end\n end\n @item_max = @targets.size\n create_contents\n refresh\n show\n activate\n end",
"def action; end",
"def action; end",
"def action; end",
"def action; end",
"def action; end",
"def workflow\n end",
"def revisable_shared_setup(args, block)\n class << self\n attr_accessor :revisable_options\n end\n options = args.extract_options!\n self.revisable_options = Options.new(options, &block)\n \n self.send(:include, Common)\n self.send(:extend, Validations) unless self.revisable_options.no_validation_scoping?\n self.send(:include, WithoutScope::QuotedColumnConditions)\n end",
"def setup\n @action = SampleActionAndroid.new(os_name: 'android',\n app_name: APP_PATH)\n end",
"def before(action)\n invoke_callbacks *self.class.send(action).before\n end",
"def process_action(...)\n send_action(...)\n end",
"def before_dispatch(env); end",
"def after_actions(*logic)\n self.after_actions = logic\n end",
"def setup\n # override and do something appropriate\n end",
"def setup(client)\n return unless @setup\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n actions.each do |action|\n action.execute(client)\n end\n self\n end",
"def setup(_context)\n end",
"def setup(resources) ; end",
"def validate_actions\n errors.add(:base, :should_give_at_least_one_action) if !manage? && !forecasting? && !read? && !api?\n end",
"def setup\n @resource_config = {\n :callbacks => {\n :before_create => nil,\n :after_create => nil,\n :before_update => nil,\n :after_update => nil,\n :before_destroy => nil,\n :after_destroy => nil,\n },\n :child_assoc => nil,\n :model => nil,\n :parent => nil,\n :path => nil,\n :permission => {},\n :properties => {},\n :relation => {\n :create => nil,\n :delete => nil,\n },\n :roles => nil,\n }\n end",
"def determine_valid_action\n\n end",
"def process_shared\n handle_taxes\n handle_shippings\n create_adjustments_from_params\n handle_status\n handle_inventory_refunds\n handle_payment_transactions\n order.updater.update\n end",
"def startcompany(action)\n @done = true\n action.setup\n end",
"def init_actions\n am = action_manager()\n am.add_action(Action.new(\"&Disable selection\") { @selection_mode = :none; unbind_key(32); bind_key(32, :scroll_forward); } )\n am.add_action(Action.new(\"&Edit Toggle\") { @edit_toggle = !@edit_toggle; $status_message.value = \"Edit toggle is #{@edit_toggle}\" })\n end",
"def event_callbacks(event, metadata={})\n case event\n when :reset, :review\n if confirmed\n update_attributes(confirmed: false)\n end\n when :confirm\n confirm\n # trigger :order for all applicable items\n # NOTE: :order event is common to both physical and digital items\n items.each do |i|\n if i.event_permitted(:order)\n user_id = last_transition.user_id\n i.trigger!(:order, { order_id: id, user_id: user_id })\n end\n end\n when :complete_work\n request = metadata[:request]\n work_complete_notification(request)\n when :close\n close\n end\n if event != :close && !open\n reopen\n end\n end",
"def setup_action\n return unless PONY::ERRNO::check_sequence(current_act)\n new_sequence = @action_sequence[@sequence_index+1...@action_sequence.size]\n @sequence_index = 0\n new_sequence = DND::SkillSequence::ACTS[@acts[1]] + new_sequence\n execute_sequence\n end",
"def define_tasks\n define_weave_task\n connect_common_tasks\n end",
"def setup(&block)\n define_method(:setup, &block)\n end",
"def setup\n transition_to(:setup)\n end",
"def setup\n transition_to(:setup)\n end",
"def action\n end",
"def setup( *args )\n\t\t\tself.class.setupBlocks.each {|sblock|\n\t\t\t\tdebugMsg \"Calling setup block method #{sblock}\"\n\t\t\t\tself.send( sblock )\n\t\t\t}\n\t\t\tsuper( *args )\n\t\tend",
"def config(action, *args); end",
"def setup\n @setup_proc.call(self) if @setup_proc\n end",
"def before_action \n end",
"def setup_callbacks\n defined_callbacks.each do |meth|\n unless respond_to?(\"call_#{meth}_callbacks\".to_sym)\n self.class.module_eval <<-EOE\n def call_#{meth}_callbacks(*args)\n plugin_store.each {|a| a.call_#{meth}_callbacks(*args) } if respond_to?(:plugin_store) && plugin_store\n self.send :#{meth}, *args if respond_to?(:#{meth})\n end\n EOE\n end\n end\n end",
"def action\n end",
"def matt_custom_action_begin(label); end",
"def setup\n # override this if needed\n end",
"def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend",
"def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend",
"def action(options,&callback)\n new_action = Action===options ? options : Action.new(options,&callback)\n # replace any with (shared name/alias or both default) + same arity\n @actions.delete_if do |existing_action|\n ((existing_action.names & new_action.names).size > 0 ||\n existing_action.default? && new_action.default?) &&\n existing_action.required.size == new_action.required.size &&\n existing_action.optional.size <= new_action.optional.size\n end\n @actions = (@actions + [new_action]).sort\n new_action\n end",
"def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action\n end",
"def after(action)\n invoke_callbacks *options_for(action).after\n end",
"def pre_task\n end",
"def setup(server)\n server.on('beforeMethod', method(:before_method), 10)\n end",
"def add_actions\n attribute = machine.attribute\n name = self.name\n \n owner_class.class_eval do\n define_method(name) {self.class.state_machines[attribute].events[name].fire(self)}\n define_method(\"#{name}!\") {self.class.state_machines[attribute].events[name].fire!(self)}\n define_method(\"can_#{name}?\") {self.class.state_machines[attribute].events[name].can_fire?(self)}\n end\n end",
"def init_actions\n @select_action = SelectAction.new\n @endpoint_mouse_action = EndpointMouseAction.new\n @move_action = MoveAction.new\n end",
"def setup_signals; end",
"def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend",
"def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend",
"def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action.respond_to?('weak!') ? action.weak! : action\n end",
"def initialize(*args)\n super\n @action = :set\nend",
"def after_set_callback; end",
"def setup\n #implement in subclass;\n end",
"def lookup_action; end",
"def setup &block\n if block_given?\n @setup = block\n else\n @setup.call\n end\n end",
"def setup_action\n return TSBS.error(@acts[0], 1, @used_sequence) if @acts.size < 2\n actions = TSBS::AnimLoop[@acts[1]]\n if actions.nil?\n show_action_error(@acts[1])\n end\n @sequence_stack.push(@acts[1])\n @used_sequence = @acts[1]\n actions.each do |acts|\n @acts = acts\n execute_sequence\n break if @break_action\n end\n @sequence_stack.pop\n @used_sequence = @sequence_stack[-1]\n end",
"def release_actions; end",
"def around_hooks; end",
"def save_action; end",
"def setup(easy)\n super\n easy.customrequest = @verb\n end",
"def action_target()\n \n end",
"def setup\n callback(:setup) do\n notify(:setup)\n migration_check.last_deployed_commit\n end\n end",
"def setup\n return unless @setup\n\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n run_actions_and_retry(actions)\n self\n end",
"def before_setup\n # do nothing by default\n end",
"def my_actions(options)\n @setup = false\n get_template_part(\"custom_used\",\"action_users\",true)\n end",
"def default_action; end",
"def setup(&blk)\n @setup_block = blk\n end",
"def callback_phase\n super\n end",
"def advice\n end",
"def _handle_action_missing(*args); end",
"def duas1(action)\n action.call\n action.call\nend",
"def shared_action(name, &block)\n @controller.shared_actions[name] = block\n end",
"def before_action action, &block\n @audience[:before][action] ||= Set.new\n @audience[:before][action] << block\n end",
"def setup_initial_state\n\n state_a = State.new(\"a\", 0)\n state_b = State.new(\"b\", 0)\n state_c = State.new(\"c\", 10)\n\n move_to_b = Action.new(\"move_to_b\", 1, state_b)\n\n move_to_c = Action.new(\"move_to_c\", 1, state_c)\n\n state_a.actions = [move_to_b, move_to_c]\n\n return state_a\n \nend"
] |
[
"0.6163163",
"0.6045976",
"0.5946146",
"0.591683",
"0.5890051",
"0.58349305",
"0.5776858",
"0.5703237",
"0.5703237",
"0.5652805",
"0.5621621",
"0.54210985",
"0.5411113",
"0.5411113",
"0.5411113",
"0.5391541",
"0.53794575",
"0.5357573",
"0.53402257",
"0.53394014",
"0.53321576",
"0.53124547",
"0.529654",
"0.5296262",
"0.52952296",
"0.52600986",
"0.52442724",
"0.52385926",
"0.52385926",
"0.52385926",
"0.52385926",
"0.52385926",
"0.5232394",
"0.523231",
"0.5227454",
"0.52226824",
"0.52201617",
"0.5212327",
"0.52079266",
"0.52050185",
"0.51754695",
"0.51726824",
"0.51710224",
"0.5166172",
"0.5159343",
"0.51578903",
"0.51522785",
"0.5152022",
"0.51518047",
"0.51456624",
"0.51398855",
"0.5133759",
"0.5112076",
"0.5111866",
"0.5111866",
"0.5110294",
"0.5106169",
"0.509231",
"0.50873137",
"0.5081088",
"0.508059",
"0.50677156",
"0.50562143",
"0.5050554",
"0.50474834",
"0.50474834",
"0.5036181",
"0.5026331",
"0.5022976",
"0.5015441",
"0.50121695",
"0.5000944",
"0.5000019",
"0.4996878",
"0.4989888",
"0.4989888",
"0.49864885",
"0.49797225",
"0.49785787",
"0.4976161",
"0.49683493",
"0.4965126",
"0.4958034",
"0.49559742",
"0.4954353",
"0.49535993",
"0.4952725",
"0.49467874",
"0.49423352",
"0.49325448",
"0.49282882",
"0.49269363",
"0.49269104",
"0.49252945",
"0.4923091",
"0.49194667",
"0.49174926",
"0.49173003",
"0.49171105",
"0.4915879",
"0.49155936"
] |
0.0
|
-1
|
Only allow a list of trusted parameters through.
|
def order_params
params.require(:order).permit(:date, :status, :tracking_number, :shipping_address, :billing_address, :customer_id)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def allowed_params\n ALLOWED_PARAMS\n end",
"def strong_params\n params.require(:listing_member).permit(param_whitelist)\n end",
"def parameters_list_params\n params.require(:parameters_list).permit(:name, :description, :is_user_specific)\n end",
"def param_whitelist\n [:role, :title]\n end",
"def param_whitelist\n whitelist = [\n :username, :name,\n :parent_id,\n :headline, :description, :video,\n :policy, :signup_mode, :category,\n :website, :facebook, :twitter, :linkedin,\n :founded_at,\n privacy: [\n :events,\n :resources\n ],\n permission: [\n :profile,\n :members,\n :children,\n :statistics,\n :posts,\n :listings,\n :resources,\n :events\n ],\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:parent_id)\n unless current_user.role_in(@community) === 'owner'\n whitelist.delete(:privacy)\n whitelist.delete(:permission)\n end\n end\n \n whitelist\n end",
"def strong_params\n params.require(:user).permit(param_whitelist)\n end",
"def param_whitelist\n if @user.present? && current_user != @user\n return [:followed]\n end\n \n whitelist = [\n :username, :email, :password,\n :first_name, :last_name,\n :birthday, :gender,\n :headline, :biography, :ask_about, :focus,\n :website, :facebook, :linkedin, :twitter, :github,\n roles: [],\n skills: [],\n interests: [],\n privacy: { contact: [] },\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:email)\n whitelist.delete(:password)\n end\n \n whitelist\n end",
"def allow_params_authentication!; end",
"def whitelisted_args\n args.select &:allowed\n end",
"def safe_list_sanitizer; end",
"def safe_list_sanitizer; end",
"def safe_list_sanitizer; end",
"def filtered_parameters; end",
"def sanitize_params_for user, params, allowed_params\n params.each do |key, val|\n #if allowed_params.include?(key)\n #sanitize!(user, params, key) if key =~ /_attributes|_ids$/\n #else\n #params.delete(key)\n #end\n params.delete(key) unless allowed_params.include?(key.to_sym)\n end\n end",
"def strong_params\n params.require(:team_member).permit(param_whitelist)\n end",
"def expected_permitted_parameter_names; end",
"def sanitize_parameters!(sanitizer, params)\n # replace :readwrite with :onlyif\n if params.has_key?(:readwrite)\n warn \":readwrite is deprecated. Replacing with :onlyif\"\n params[:onlyif] = params.delete(:readwrite)\n end\n\n # add default parameters\n bindata_default_parameters.each do |k,v|\n params[k] = v unless params.has_key?(k)\n end\n\n # ensure mandatory parameters exist\n bindata_mandatory_parameters.each do |prm|\n if not params.has_key?(prm)\n raise ArgumentError, \"parameter ':#{prm}' must be specified \" +\n \"in #{self}\"\n end\n end\n\n # ensure mutual exclusion\n bindata_mutually_exclusive_parameters.each do |param1, param2|\n if params.has_key?(param1) and params.has_key?(param2)\n raise ArgumentError, \"params #{param1} and #{param2} \" +\n \"are mutually exclusive\"\n end\n end\n end",
"def strong_params\n params.require(:education).permit(param_whitelist)\n end",
"def safe_list_sanitizer=(_arg0); end",
"def safe_list_sanitizer=(_arg0); end",
"def safe_list_sanitizer=(_arg0); end",
"def safe_params\n resurce_name = self.class.resource_name\n params_method_name = \"#{resurce_name}_params\".to_sym\n if params[resurce_name]\n if respond_to?(params_method_name) || private_methods.include?(params_method_name)\n send(params_method_name)\n else\n raise ActiveModel::ForbiddenAttributesError, \"Please, define the '#{params_method_name}' method in #{self.class.name}\"\n end\n end\n end",
"def param_whitelist\n [:rating, :review]\n end",
"def check_params; true; end",
"def strong_params\n params.require(:experience).permit(param_whitelist)\n end",
"def validate_search_inputs\n @whitelisted = params.fetch(:user, nil)\n if @whitelisted.blank?\n render_error(400, \"#{I18n.t('general_error.params_missing_key')}\": [I18n.t('general_error.params_missing_value', model: \"review\")])\n return\n else\n @whitelisted = @whitelisted.permit(:name, :uen, :description)\n end\n end",
"def allowed?(*_)\n true\n end",
"def param_whitelist\n [\n :title,\n :description,\n :organization,\n :team_id,\n :started_at,\n :finished_at,\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n end",
"def allowed_params(parameters)\n parameters.select do |name, values|\n values.location != \"path\"\n end\n end",
"def secure_params\n return @secure_params if @secure_params\n\n defn = implementation_class.definition\n field_list = [:master_id] + defn.field_list_array\n\n res = params.require(controller_name.singularize.to_sym).permit(field_list)\n res[implementation_class.external_id_attribute.to_sym] = nil if implementation_class.allow_to_generate_ids?\n @secure_params = res\n end",
"def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end",
"def permitir_parametros\n \t\tparams.permit!\n \tend",
"def strong_params\n params.require(:community).permit(param_whitelist)\n end",
"def permit( params, whitelist, name = nil )\n raise 'Parametrization not yet configured' unless @configured\n whitelist ||= []\n px = params.respond_to?( :permit ) ? params : ActionController::Parameters.new( params )\n px = dig(px, name)\n px.permit( *whitelist )\n end",
"def valid_params?; end",
"def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end",
"def url_allowlist=(_arg0); end",
"def param_whitelist\n whitelist = [\n :description,\n :progress,\n :kpi_id\n ]\n \n unless action_name === 'create'\n whitelist.delete(:kpi_id)\n end\n \n whitelist\n end",
"def restricted_params\n #params.require(self.controller_name.classify.underscore.to_sym).permit([])\n raise(\"No strong params set, override restricted_params method in your controller. E.g. params.require(:model).permit(:attribute1, :attribute2)\")\n end",
"def list_params\n params.permit(:list_name)\n end",
"def valid_params_request?; end",
"def safe_params\n params.permit(:id, :name, :origin, :emails => []); #emails is an array\n end",
"def param_list(param_type, name, type, required, description = nil, allowed_values = [], hash = {})\n hash.merge!({allowable_values: {value_type: \"LIST\", values: allowed_values}})\n param(param_type, name, type, required, description, hash)\n end",
"def safelists; end",
"def authorize_own_lists\n authorize_lists current_user.lists\n end",
"def listed_params\n params.permit(:listed, :list_id, :listable_id, :listable_type, :campsite_id)\n end",
"def lists_params\n params.require(:list).permit(:name)\n\n end",
"def list_params\n params.require(:list).permit(:name, :user_id)\n end",
"def list_params\n params.require(:list).permit(:name, :description, :type, :privacy, :allow_edit, :rating, :votes_count, :user_id)\n end",
"def check_params\n true\n end",
"def authorize_own_or_shared_lists\n authorize_lists current_user.all_lists\n end",
"def user_pref_list_params\n\t\tparams.require(:user).permit(:preference_list)\n\tend",
"def may_contain!(*keys)\n self.allow_only_permitted = true\n self.permitted_keys = [*permitted_keys, *keys].uniq\n end",
"def filter_parameters; end",
"def filter_parameters; end",
"def whitelist; end",
"def article_params_whitelist\n params.require(:article).permit(:title, :description, category_ids: [])\n end",
"def list_params\n params.require(:list).permit(:name)\n end",
"def list_params\n params.permit(:name)\n end",
"def recipient_list_params\n params.require(:recipient_list).permit(:name, :list, :references)\n end",
"def cancan_parameter_sanitizer\n resource = controller_name.singularize.to_sym\n method = \"#{resource}_params\"\n params[resource] &&= send(method) if respond_to?(method, true)\n end",
"def list_params\n params.require(:list).permit(:name).merge(user_id: current_user.id)\n end",
"def whitelist_place_params\n params.require(:place).permit(:place_name, :unlock, :auth, :is_deep_checked, :parent_ADM4, :parent_ADM3, :parent_ADM2, :parent_ADM1, :parent_country, feature_code: [], same_as: [], related_authority: [], altlabel: [], note: []) # Note - arrays need to go at the end or an error occurs!\n end",
"def list_params\n params.fetch(:list, {}).permit(:user_id, :name, :active)\n end",
"def permitted_strong_parameters\n :all #or an array of parameters, example: [:name, :email]\n end",
"def secure_params(require_param, permit_keys)\n params.require(require_param).permit(*permit_keys)\n end",
"def grant_params\n @whitelisted = params.require(:grant).permit(:name, :description, :agency_id, :acronym)\n end",
"def permitted_params\n []\n end",
"def price_list_params\n params.fetch(:price_list, {}).permit(:name, :valid_from, :valid_to, :active,\n :all_warehouses, :all_users, :all_contact_groups,\n warehouse_ids: [], price_lists_user_ids: [], contact_group_ids: [])\n end",
"def params(list)\n @declared_params = list\n end",
"def admin_review_params\n params.fetch(:review, {}).permit(whitelisted_params)\n end",
"def saved_list_params\n params.require(:saved_list).permit(:user_id)\n end",
"def allow(ids); end",
"def list_params\n params.require(:list).permit(:name)\n end",
"def list_params\n params.require(:list).permit(:name)\n end",
"def list_params\n params.require(:list).permit(:name)\n end",
"def filter_params(param_set, **kwargs)\r\n begin\r\n key = kwargs[:key]\r\n params.require(key).permit(*param_set)\r\n rescue Exception\r\n params.permit(*param_set)\r\n end\r\n end",
"def valid_parameters\n sort_symbols(@interface.allowed_parameters)\n end",
"def validate_paramified_params\n self.class.paramify_methods.each do |method|\n params = send(method)\n transfer_errors_from(params, TermMapper.scope(params.group)) if !params.valid?\n end\n end",
"def list_params\n params.require(:list).permit(:name)\n end",
"def secure_params\n return @secure_params if @secure_params\n\n @implementation_class = implementation_class\n resname = @implementation_class.name.ns_underscore.gsub('__', '_').singularize.to_sym\n @secure_params = params.require(resname).permit(*permitted_params)\n end",
"def refine_permitted_params(param_list)\n res = param_list.dup\n\n ms_keys = res.select { |a| columns_hash[a.to_s]&.array }\n ms_keys.each do |k|\n res.delete(k)\n res << { k => [] }\n end\n\n res\n end",
"def recipient_list_params\n params.require(:recipient_list).permit(:name, :description, recipient_id_array: [])\n end",
"def safelist; end",
"def sponsor_params\n params.require(:sponsor).permit(WHITE_LIST)\n end",
"def valid_for_params_auth?; end",
"def default_param_whitelist\n [\"mode\"]\n end",
"def devise_filter\r\n logger.debug(\"In devise_filter =>PARAMS: #{params.inspect}\")\r\n\r\n # White list for sign_up\r\n devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(user_whitelist) }\r\n\r\n # White list for account update\r\n devise_parameter_sanitizer.for(:account_update) { |u| u.permit(user_whitelist, :current_password) }\r\n\r\n # White list for Invitation creation\r\n devise_parameter_sanitizer.for(:invite) { |u| u.permit(:account_type, :email, :invitation_token)}\r\n\r\n # White list for accept invitation\r\n devise_parameter_sanitizer.for(:accept_invitation) { |u| u.permit(user_whitelist, :invitation_token)}\r\n\r\n end",
"def shopping_list_params\n params.require(:shopping_list).permit!\n end",
"def permitted_params\n declared(params, include_missing: false)\n end",
"def permitted_params\n declared(params, include_missing: false)\n end",
"def safe_params\n params.except(:host, :port, :protocol).permit!\n end",
"def permitters\n @_parametrizr_permitters || {}\n end",
"def allow_params(action, keys: nil, except: nil, &blk)\n keys &&= Array.wrap(keys)\n keys ||= User.field_names\n except &&= Array.wrap(except)\n except ||= %i[id email]\n devise_parameter_sanitizer.permit(action, keys: keys, except: except, &blk)\n end",
"def list_params\n if current_user && current_user.role == 'admin'\n params.require(:list).permit(:name, :url, :description, :user_id,\n ideas_attributes: [:id, :list_id, :body, :due_date, :completion_status, :_destroy])\n else\n params.require(:list).permit(:name, :description,\n ideas_attributes: [:body, :due_date, :completion_status]) \n end\n end",
"def whitelist(params)\n send_request_of_type(GlobalConstant::PrivateOpsApi.private_ops_api_type, 'post', '/token-sale/whitelist', params)\n end",
"def valid_access_params\n params.require(:valid_access).permit(:wish_list_id, :user_id)\n end",
"def url_allowlist; end",
"def ensure_redirected_params_are_safe!(passed_params)\n unless passed_params.is_a?(ActionController::Parameters) && passed_params.permitted?\n error_message = if passed_params.is_a?(ActionController::Parameters)\n unsafe_parameters = passed_params.send(:unpermitted_keys, params)\n \"[Rails::Prg] Error - Must use permitted strong parameters. Unsafe: #{unsafe_parameters.join(', ')}\"\n else\n \"[Rails::Prg] Error - Must pass strong parameters.\"\n end\n raise error_message\n end\n end",
"def data_collection_params\n allow = [:name,:description,:institution,:collection_name,:country_id,:province_id,:city_id]\n params.require(:data_collection).permit(allow)\n end",
"def quote_params\n params.permit!\n end"
] |
[
"0.69497335",
"0.6812623",
"0.6803639",
"0.6795365",
"0.67448795",
"0.67399913",
"0.6526815",
"0.6518771",
"0.64931697",
"0.6430388",
"0.6430388",
"0.6430388",
"0.63983387",
"0.6356042",
"0.63535863",
"0.63464934",
"0.63444513",
"0.6337208",
"0.6326454",
"0.6326454",
"0.6326454",
"0.63140553",
"0.6299814",
"0.62642586",
"0.626006",
"0.62578833",
"0.6236823",
"0.6227561",
"0.6221758",
"0.62200165",
"0.620879",
"0.61983657",
"0.6195055",
"0.6172993",
"0.6156856",
"0.61558664",
"0.61521494",
"0.6135789",
"0.6121145",
"0.61118174",
"0.60736513",
"0.6071645",
"0.60632104",
"0.60549796",
"0.6043906",
"0.6034662",
"0.60207325",
"0.6018568",
"0.6016575",
"0.60103434",
"0.60084206",
"0.600763",
"0.6007443",
"0.6003619",
"0.6003619",
"0.5995791",
"0.5993301",
"0.5993231",
"0.5984926",
"0.597122",
"0.5968121",
"0.5965808",
"0.59640145",
"0.59632224",
"0.59602356",
"0.59332967",
"0.5927556",
"0.5922805",
"0.5909745",
"0.5905083",
"0.5904304",
"0.5893434",
"0.58888215",
"0.58823985",
"0.58823985",
"0.58823985",
"0.5873434",
"0.58619875",
"0.58533794",
"0.5845531",
"0.58426666",
"0.58360124",
"0.583218",
"0.5828041",
"0.5827927",
"0.5816121",
"0.5814705",
"0.5812719",
"0.581121",
"0.5803423",
"0.5803423",
"0.57995003",
"0.5794207",
"0.5784923",
"0.5781365",
"0.5776385",
"0.5774859",
"0.57671493",
"0.5766998",
"0.57618684",
"0.5758038"
] |
0.0
|
-1
|
send a pdu, receives a pdu
|
def send(pdu)
log { "sending request..." }
log(level: 2) { pdu.to_hex }
encoded_request = pdu.to_der
log { Hexdump.dump(encoded_request) }
encoded_response = @transport.send(encoded_request)
log { "received response" }
log { Hexdump.dump(encoded_response) }
response_pdu = PDU.decode(encoded_response)
log(level: 2) { response_pdu.to_hex }
response_pdu
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def process_pdu(pdu)\n case pdu\n when Pdu::DeliverSm\n write_pdu(Pdu::DeliverSmResponse.new(pdu.sequence_number))\n logger.debug \"ESM CLASS #{pdu.esm_class}\"\n if pdu.esm_class != 4\n # MO message; invoke MO proc\n @mo_proc.call(pdu.source_addr, pdu.destination_addr, pdu.short_message)\n else\n # Invoke DR proc (let the owner of the block do the mapping from msg_reference to mt_id)\n @dr_proc.call(pdu.msg_reference.to_s, pdu.stat)\n end \n when Pdu::BindTransceiverResponse\n case pdu.command_status\n when Pdu::Base::ESME_ROK\n logger.debug \"Bound OK.\"\n @state = :bound\n when Pdu::Base::ESME_RINVPASWD\n logger.warn \"Invalid password.\"\n EventMachine::stop_event_loop\n when Pdu::Base::ESME_RINVSYSID\n logger.warn \"Invalid system id.\"\n EventMachine::stop_event_loop\n else\n logger.warn \"Unexpected BindTransceiverResponse. Command status: #{pdu.command_status}\"\n EventMachine::stop_event_loop\n end\n when Pdu::SubmitSmResponse\n mt_message_id = @ack_ids[pdu.sequence_number]\n if !mt_message_id\n raise \"Got SubmitSmResponse for unknown sequence_number: #{pdu.sequence_number}\"\n end\n if pdu.command_status != Pdu::Base::ESME_ROK\n logger.error \"Error status in SubmitSmResponse: #{pdu.command_status}\"\n else\n logger.info \"Got OK SubmitSmResponse (#{pdu.message_id} -> #{mt_message_id})\"\n end\n # Now we got the SMSC message id; create pending delivery report\n @pdr_storage[pdu.message_id] = mt_message_id\n when Pdu::SubmitMultiResponse\n mt_message_id = @ack_ids[pdu.sequence_number]\n if !mt_message_id\n raise \"Got SubmitMultiResponse for unknown sequence_number: #{pdu.sequence_number}\"\n end\n if pdu.command_status != Pdu::Base::ESME_ROK\n logger.error \"Error status in SubmitMultiResponse: #{pdu.command_status}\"\n else\n logger.info \"Got OK SubmitMultiResponse (#{pdu.message_id} -> #{mt_message_id})\"\n end\n else\n super\n end \n end",
"def update(pdu)\n\n Utils_visiona.verifyInput(CFDP::PDUPacket, pdu.class)\n\n pdu = pdu.dup\n\n case pdu.pduPayload\n when CFDP::PDUMetadata\n\n if haspdumetadata?\n writeLog(\"Received duplicated pdu #{pdu.pduPayload.class}. Ignoring.\") unless isuplink?\n else\n @pdus.store \"METADATA\", pdu\n writeLog(\"Updated transaction with #{pdu.pduPayload.class} and buffer: #{pdu.pack.to_s}\")\n CFDP::CFDP_Indication(\"Metadata #{isuplink? ? \"sent\" : \"received\"} for transaction #{@ID}\")\n (hastimer?(\"INACTIVITY\") ? resetTimer(\"INACTIVITY\") : insertTimer(\"INACTIVITY\")) if isdownlink?\n end\n when CFDP::PDUFileData\n\n if haspdufiledata?(pdu.pduPayload.offset)\n writeLog(\"Received duplicated pdu #{pdu.pduPayload.class} with offset #{pdu.pduPayload.offset}. Ignoring.\") unless isuplink?\n else\n @pdus[\"FILEDATA\"].store pdu.pduPayload.offset, pdu\n writeLog(\"Updated transaction with #{pdu.pduPayload.class} and buffer: #{pdu.pack.to_s}\")\n resetTimer(\"INACTIVITY\") unless isuplink?\n end\n when CFDP::PDUEOF\n\n if haspdueof?\n writeLog(\"Received duplicated pdu #{pdu.pduPayload.class}. Ignoring.\") unless isuplink?\n else\n @pdus.store \"EOF\", pdu\n writeLog(\"Updated transaction with #{pdu.pduPayload.class} and buffer: #{pdu.pack.to_s}\")\n CFDP::CFDP_Indication(\"EOF #{isuplink? ? \"sent\" : \"received\"} for transaction #{@ID}\")\n insertTimer(\"EOF\") unless ((isclass1? && isuplink?) || isdownlink? || hastimer?(\"EOF\"))\n end\n when CFDP::PDUFinished\n\n if haspdufinished?\n writeLog(\"#{isuplink? ? \"Received\" : \"Sent\"} duplicated pdu #{pdu.pduPayload.class}. Ignoring.\") unless isuplink?\n else\n @pdus.store \"FINISHED\", pdu\n writeLog(\"Updated transaction with #{pdu.pduPayload.class} and buffer: #{pdu.pack.to_s}\")\n insertTimer(\"FINISHED\") unless (isuplink? || hastimer?(\"FINISHED\"))\n end\n when CFDP::PDUNAK\n\n if @pdus[\"NAK\"] == pdu\n writeLog(\"Received duplicated pdu #{pdu.pduPayload.class}. Ignoring.\") unless isdownlink?\n else\n if isdownlink?\n @pdus.store \"NAK\", pdu\n writeLog(\"Updated transaction with #{pdu.pduPayload.class} and buffer: #{pdu.pack.to_s}\")\n insertTimer(\"NAK\") unless hastimer?(\"NAK\")\n else\n nakHandler(pdu)\n end\n end\n else\n writeLog(\"Invalid PDU Class #{pdu.pduPayload.class} with buffer #{pdu.pack.to_s} in update method.\")\n end\n end",
"def b_rdt_send message\n puts 'B Sending Data Unreliably...'\n packet = Packet.new\n packet.payload = message.data\n b_udt_send packet\nend",
"def send(inc)\n @h.usb_control_msg(0x21, 0x09, 0x02, 0x01, (message_base << inc).bytes_to_string, 0)\n end",
"def send_and_receive( cmd_str )\n trans_send( cmd_str )\n trans_send( RPC::MSG_END )\n trans_receive()\n end",
"def send_command( command )\n cmd = \"MESSAGET #{command.size}\\n#{command}\\n\"\n logger.debug( \">>> Sending cmd #{cmd.gsub( /\\n/, ' ' )}\" )\n \n out_socket.send( cmd , 0 )\n result = out_socket.recv(100)\n logger.debug( \"<<< Result ==> #{result}\" )\n result\n end",
"def send_mt(message_id, source_addr, destination_addr, short_message, options={})\n logger.debug \"Sending MT: #{short_message}\"\n if @state == :bound\n \n pdu = Pdu::SubmitSm.new(source_addr, destination_addr, short_message, options)\n write_pdu pdu\n\n # keep the message ID so we can associate the SMSC message ID with our message\n # when the response arrives. \n @ack_ids[pdu.sequence_number] = message_id\n else\n raise InvalidStateException, \"Transceiver is unbound. Cannot send MT messages.\"\n end\n end",
"def get(s, id)\n out = [MESSAGE_GET, id].pack(\"II\")\n s.write(out)\n\n # Type (don't care)\n get_int(s)\n\n # Length\n len = get_int(s)\n\n #puts(\"Retrieving #{len} bytes\")\n data = s.recv(len)\n\n # It should end with this code\n receive_code(s, 0x00001004, \"get\")\n\n return data\n\nend",
"def test_REG_REGOK\r\n msg_out = \"REG macau 10.0.1.28\"\r\n msg_esperada = \"REGOK\"\r\n sock = UDPSocket.new\r\n sock.connect($central_ip, $central_porta)\r\n sock.print(msg_out)\r\n msg_in = sock.recvfrom(20)[0]\r\n assert_equal(msg_esperada, msg_in)\r\n end",
"def test_REG_FALHA\r\n msg_out = \"REG lajes \"\r\n msg_esperada = \"FALHA\"\r\n sock = UDPSocket.new\r\n sock.connect($central_ip, $central_porta)\r\n sock.print(msg_out)\r\n msg_in = sock.recvfrom(20)[0]\r\n assert_equal(msg_esperada, msg_in)\r\n end",
"def tcp_send(command, body = nil)\n @seq += 1\n header = {\n 'Command' => command.to_s.gsub('_', '-'),\n 'Seq' => seq\n }\n\n buff = MessagePack::Packer.new\n buff.write(header)\n buff.write(body) unless body.nil?\n\n res = socket.write(buff.to_str) unless buff.to_str.empty?\n @requests[seq] = { header: header, ack?: false }\n seq\n end",
"def send_command(command)\n SerialPort.open(self.device_path, 9600, 8, 1) do |port|\n # flush anything existing on the port\n port.flush\n flush_read_buffer(port)\n\n byte_string = command.to_bytes.pack('C*')\n\n begin\n while byte_string && byte_string.length != 0\n count = port.write_nonblock(byte_string)\n byte_string = byte_string[count,-1]\n\n port.flush\n end\n rescue IO::WaitWritable\n if IO.select([], [port], [], 5)\n retry\n else\n raise IOError, \"Timeout writing command to #{self.device_path}\"\n end\n end\n\n # wait for expected confirmation signals\n got_eot = false\n got_soh = false\n loop do\n begin\n c = port.read_nonblock(1)\n\n case c\n when \"\\x04\"\n if ! got_eot\n got_eot = true\n else\n raise IOError, \"Got EOT reply twice from #{self.device_path}\"\n end\n when \"\\x01\"\n if got_eot\n if ! got_soh\n got_soh = true\n\n break\n else\n raise IOError, \"Got SOH twice from #{self.device_path}\"\n end\n else\n raise IOError, \"Got SOH before EOT from #{self.device_path}\"\n end\n end\n rescue IO::WaitReadable\n if IO.select([port], [], [], 3)\n retry\n else\n raise IOError, \"Timeout waiting for command reply from #{self.device_path}. EOT:#{got_eot} SOH:#{got_soh}\"\n end\n end\n end\n end\n\n self\n end",
"def send_command(house_and_unit, command)\n house_code, unit_code = select_code(house_and_unit)\n @marshaller.send(X10_PREFIX + house_code + unit_code + ADDRESS_SUFFIX)\n @marshaller.send(X10_PREFIX + house_code + COMMAND_CODE_TABLE[command] +\n COMMAND_SUFFIX)\n end",
"def send_to_phone(ip_addr, data)\r\n\ts = TCPSocket.open(ip_addr, 5050)\r\n\ts.puts data\r\n\ts.close\r\nend",
"def test_REG_REGFALHA\r\n msg_out = \"REG #{$dominio_registrado} 127.0.0.1\"\r\n msg_esperada = \"REGFALHA\"\r\n sock = UDPSocket.new\r\n sock.connect($central_ip, $central_porta)\r\n sock.print(msg_out)\r\n msg_in = sock.recvfrom(20)[0]\r\n assert_equal(msg_esperada, msg_in)\r\n end",
"def send_udp message\n @sender.send_udp message, @ip\n end",
"def send_raw(to, msg, dlr_url='')\n raise \"To should not be a user in send_raw\" if to.instance_of?(User)\n\n log_an_event(\"send_raw\",\"#{to} #{msg} #{dlr_url}\")\n\n gateway_status = nil\n gateway_string = nil\n\n # could limit message here\n # msg = msg[0..MSG_MAX_LEN]\n\n # todo: ensure the page has valid characters\n # todo: ensure the to is only numbers\n url = \"http://#{@server}:#{@port}/cgi-bin/sendsms?\"+\n \"username=#{@username}&password=#{@password}\"\n wait_for_response = false\n if (@dlr_mask && @dlr_mask.to_i>0 && @dlr_url && dlr_url)\n url = url + \"&dlr-mask=#{@dlr_mask}&dlr-url=#{URI::escape(dlr_url)}\"\n wait_for_response = true\n end\n url = url + \"&to=#{URI::escape(to)}&text=#{URI::escape(msg)}\"\n log_an_event \"send_raw url\", url\n open(url) do |f|\n # status will give us a message\n # read the status as well\n\n # it could fail here\n # but it cannot succeed immediately since this is just queued\n # from Kannel user guide, return codes are:\n #200: 0: Accepted for delivery\n #202: 0: Accepted for delivery\n #The message has been accepted and is delivered onward to a SMSC driver.\n #Note that this status does not ensure that the intended recipient receives the message.\n #202\t3: Queued for later delivery\n #4xx\t(varies)\n #503\tTemporal failure, try again later.\n # it returns an array [\"202\",\"Accepted\"]\n f_status_code = f.status\n f_status_code = f.status[0] if f.status.is_a?(Array)\n if not [\"200\", \"202\"].member?(f.status[0])\n gateway_status = STATUS_FAILED\n gateway_string = f.status.to_s\n log_an_error(\"send_raw\", \"FAILED to send #{url}\\n#{f.status.inspect}\")\n else\n gateway_string = f.read\n\n # 2 modes for the kannel server\n # either we wait for a delivery receipt, or we just send it to the server and assume this has been sent\n if wait_for_response\n gateway_status = STATUS_PENDING\n else\n gateway_status = STATUS_DELIVERED\n end\n log_an_event(\"send_page\", \"SUCCESS #{url} #{gateway_string}\")\n end\n end\n [wait_for_response, gateway_status, gateway_string]\n end",
"def sendData(identKey,srcIP,dstIP,srcPort,dstPort,payload)\n\tudpPacket = udpConstruct(identKey,srcIP,srcPort,$dstIP,dstPort,payload)\n\tudpPacket.to_w # Sent\n\tprint \"Data Sent\\n\"\nend",
"def raw_send_recv(cmd, nsock = self.sock)\n nsock.put(cmd)\n res = nsock.get_once\n end",
"def send_recv(eiscp_packet)\n sock = TCPSocket.new @host, @port\n sock.puts eiscp_packet\n return Receiver.recv(sock, 0.5)\n end",
"def send_message(data, flag, host, port)\n\t\tsocket = UDPSocket.new\n\t\tserialized = Marshal.dump(data)\n\t\tsocket.send serialized, flag, host, port\n\t\tsocket.close\n\t\tputs \"Sending #{data} to #{host}:#{port}\"\n\t\tsleep(0.025)\n\tend",
"def send_cmd(command,check_command,check_value,sleep_time,timeout,tries)\n msg=''\n ret=tries\n success=nil\n if(not(ret))\n ret=1\n end\n $queue.synchronize do\n $rx_messages.clear()\n end\n while(ret>0 and (not(success)))\n ret=ret-1\n $serial_port.synchronize do\n $serialport.write(command)\n end\n sleep(sleep_time)\n if(check_command)\n $serial_port.synchronize do\n $serialport.write(check_command)\n end\n msg=''\n now=Time.now().to_f\n while((not(success)) and Time.now().to_f-now<=timeout)\n $queue.synchronize do\n if($rx_messages.length>0)\n msg=$rx_messages.pop()\n if(msg==check_value)\n success=true\n end\n end\n end\n sleep(0.1)\n end\n else\n return(true)\n end\n end\n if(success)\n return(msg)\n else\n return(nil)\n end\nend",
"def send_multi_mt(message_id, source_addr, destination_addr_arr, short_message, options={})\n logger.debug \"Sending Multiple MT: #{short_message}\"\n if @state == :bound\n pdu = Pdu::SubmitMulti.new(source_addr, destination_addr_arr, short_message, options)\n write_pdu pdu\n\n # keep the message ID so we can associate the SMSC message ID with our message\n # when the response arrives. \n @ack_ids[pdu.sequence_number] = message_id\n else\n raise InvalidStateException, \"Transceiver is unbound. Cannot send MT messages.\"\n end\n end",
"def test_IP_FALHA_1\r\n msg_out = \"IPacari\"\r\n msg_esperada = \"FALHA\"\r\n sock = UDPSocket.new\r\n sock.connect($central_ip, $central_porta)\r\n sock.print(msg_out)\r\n msg_in = sock.recvfrom(20)[0]\r\n assert_equal(msg_esperada, msg_in)\r\n end",
"def send_recv(eiscp)\n eiscp = Parser.parse(eiscp) if eiscp.is_a? String\n send eiscp\n sleep DEFAULT_TIMEOUT\n Parser.parse(\"#{eiscp.command}#{@state[eiscp.command]}\")\n end",
"def _transmit(used_socket, command, headers = {}, body = '')\n\n # p [ \"wirewrite\" ]\n # _dump_callstack()\n\n if @protocol >= Stomp::SPL_11 && command != Stomp::CMD_CONNECT\n headers = _encodeHeaders(headers)\n end\n @transmit_semaphore.synchronize do\n # Handle nil body\n body = '' if body.nil?\n # The content-length should be expressed in bytes.\n # Ruby 1.8: String#length => # of bytes; Ruby 1.9: String#length => # of characters\n # With Unicode strings, # of bytes != # of characters. So, use String#bytesize when available.\n body_length_bytes = body.respond_to?(:bytesize) ? body.bytesize : body.length\n\n # ActiveMQ interprets every message as a BinaryMessage\n # if content_length header is included.\n # Using :suppress_content_length => true will suppress this behaviour\n # and ActiveMQ will interpret the message as a TextMessage.\n # For more information refer to http://juretta.com/log/2009/05/24/activemq-jms-stomp/\n # Lets send this header in the message, so it can maintain state when using unreceive\n headers[:'content-length'] = \"#{body_length_bytes}\" unless headers[:suppress_content_length]\n headers[:'content-type'] = \"text/plain; charset=UTF-8\" unless headers[:'content-type'] || headers[:suppress_content_type]\n _wire_write(used_socket,command)\n headers.each do |k,v|\n if v.is_a?(Array)\n v.each do |e|\n _wire_write(used_socket,\"#{k}:#{e}\")\n end\n else\n _wire_write(used_socket,\"#{k}:#{v}\")\n end\n end\n _wire_write(used_socket,\"\")\n if body != ''\n if headers[:suppress_content_length]\n if tz = body.index(\"\\00\")\n used_socket.write body[0..tz-1]\n else\n used_socket.write body\n end\n else\n used_socket.write body\n end\n end\n used_socket.write \"\\0\"\n used_socket.flush if autoflush\n\n if @protocol >= Stomp::SPL_11\n @ls = Time.now.to_f if @hbs\n end\n\n end\n end",
"def raw_send_recv(cmd, nsock = self.sock)\n nsock.put(cmd)\n nsock.get_once\n end",
"def tcp_send(command, body = nil)\n @seq += 1\n header = {\n 'Command' => command.to_s.gsub('_', '-'),\n 'Seq' => seq\n }\n Log.info(\"#{__method__}|Header: #{header.inspect}\")\n buff = MessagePack::Buffer.new\n buff << header.to_msgpack\n buff << body.to_msgpack unless body.nil?\n res = socket.send(buff.to_str, 0)\n Log.info(\"#{__method__}|Res: #{res.inspect}\")\n @requests[seq] = { header: header, ack?: false }\n seq\n end",
"def send str\n\n @send_buffer.push [Time.now.to_i + @send_buffer_delay, str] if @send_buffer_delay > 0\n\n begin\n if @send_buffer_delay > 0\n Protocol.write @client, (@send_buffer.shift)[1], :debug => 5 if Time.now.to_i >= (@send_buffer.first)[0]\n else\n Protocol.write @client, str, :debug => 5\n end\n false\n rescue Exception=>e\n puts \"!D connection terminated: #{e}\" if Config.debug\n true\n end\n end",
"def receive_data(data)\n\t@buffer.clear if (@buffer.size + data.size) > 1000\n\t@buffer += data\n\n\tif @buffer.unpack('C4Nn2N4C16C192NC*').include?($DHCP_MAGIC)\n\t process_message(@buffer.dup)\n\t @buffer.clear\n\tend\n end",
"def select(aid)\n\t\t\tsend_apdu(\"\\x00\\xA4\\x04\\x00#{aid.size.chr}#{aid}\")\n end",
"def exchange(send_bytes, response_nbytes )\n @response = []\n @sp.rts = 0\n @sp.dtr = 0\n @sp.dtr = 1\n begin\n x = @sp.readbyte #should get an ETX after toggling the DTR\n raise Weather_exception, \"Bad packet: No ETX\" if x != ETX\n\n @sp.write(send_bytes)\n @sp.flush()\n x = @sp.readbyte #should get an ETX after toggling the DTR\n raise Weather_exception, \"Bad packet: No STX\" if x != STX\n\n length = @sp.readbyte\n STDERR.puts \"Length = #{length}\"\n\n i = 1\n escaped = false\n begin\n x = @sp.readbyte\n if length > 0\n STDERR.print \"#{i}: #{\"%02X\" % x} \"\n i += 1\n if x == ENQ\n escaped = true\n elsif escaped\n case x\n when DC2; @response << STX\n when DC3; @response << ETX\n when NAK; @response << ENQ\n else @response << x\n end\n escaped = false\n length -= 1\n else\n @response << x\n length -= 1\n end\n elsif length == 0\n @checksum = x\n length = -1\n raise Weather_exception, \"Checksum Error #{\"%02X\"%x}\" if x != checksum(@response)\n elsif x != ETX\n raise Weather_exception, \"Missing ETX\"\n end\n end while x != ETX\n\n # not available <STX 02h> <01h> <NAK 15h> <0E8h> <ETX 03h>\n if @response[0] == NAK #Got a NAK packet\n raise Weather_exception, \"Comms Error\"\n end\n ensure\n @sp.dtr = 0\n STDERR.puts\n end\n end",
"def test_IP_FALHA_2\r\n msg_out = \"IP \"\r\n msg_esperada = \"FALHA\"\r\n sock = UDPSocket.new\r\n sock.connect($central_ip, $central_porta)\r\n sock.print(msg_out)\r\n msg_in = sock.recvfrom(20)[0]\r\n assert_equal(msg_esperada, msg_in)\r\n end",
"def test_IP_FALHA_3\r\n msg_out = \"IP acari lixo\"\r\n msg_esperada = \"FALHA\"\r\n sock = UDPSocket.new\r\n sock.connect($central_ip, $central_porta)\r\n sock.print(msg_out)\r\n msg_in = sock.recvfrom(20)[0]\r\n assert_equal(msg_esperada, msg_in)\r\n end",
"def send_response\n\t # Create response packet\n udp_packet = PacketFu::UDPPacket.new(:config => @cfg)\n \n udp_packet.udp_src = @packet.udp_dst\n udp_packet.udp_dst = @packet.udp_src\n udp_packet.eth_daddr = @victim_mac\n udp_packet.ip_daddr = @victim_ip\n udp_packet.ip_saddr = @packet.ip_daddr\n udp_packet.payload = @packet.payload[0, 2]\n \n udp_packet.payload += \"\\x81\\x80\" + \"\\x00\\x01\" + \"\\x00\\x01\"\n udp_packet.payload += \"\\x00\\x00\" + \"\\x00\\x00\"\n \n @domain_name.split('.').each do |part|\n udp_packet.payload += part.length.chr\n udp_packet.payload += part\n end # @domain_name.split('.').each do |part|\n\n udp_packet.payload += \"\\x00\\x00\\x01\\x00\" + \"\\x01\\xc0\\x0c\\x00\"\n udp_packet.payload += \"\\x01\\x00\\x01\\x00\" + \"\\x00\\x1b\\xf9\\x00\" + \"\\x04\"\n \n # Address\n spoof_ip = @spoof_ip.split('.')\n udp_packet.payload += [spoof_ip[0].to_i, spoof_ip[1].to_i, spoof_ip[2].to_i, spoof_ip[3].to_i].pack('c*')\n \n udp_packet.recalc\n \n\t send(udp_packet, @iface) \n end",
"def test_IP_IPFALHA\r\n msg_out = \"IP oslo\"\r\n msg_esperada = \"IPFALHA\"\r\n sock = UDPSocket.new\r\n sock.connect($central_ip, $central_porta)\r\n sock.print(msg_out)\r\n msg_in = sock.recvfrom(20)[0]\r\n assert_equal(msg_esperada, msg_in)\r\n end",
"def send(cmd)\n return false unless connected?\n while read_nonblock do end # flush previous response data\n @client.send(cmd, 0)\n @client.recv(256).strip\n end",
"def send_message(command, message, headers = {})\n connect\n len = message.length\n @s.write(command + \" SPAMC/1.2\\r\\n\")\n headers.each do |k,v|\n @s.write(\"#{k}: #{v}\\r\\n\")\n end\n @s.write(\"Content-length: \" + len.to_s + \"\\r\\n\\r\\n\")\n @s.write(message)\n @s.shutdown(1) #have to shutdown sending side to get response\n lines = @s.readlines\n @s.close #might as well close it now\n @s = nil\n\n return lines\n\nend",
"def handlePDUSent(pduPacket)\n\n Utils_visiona.verifyInput(CFDP::PDUPacket, pduPacket.class)\n\n writeLog(\"Sent #{pduPacket.pduPayload.class}: #{pduPacket.pack.to_s}\")\n\n if isactive?\n #dcm - Slow down transmission to prevent KIT_CI overrun\n sleep(0.2)\n\n if pduPacket.pduPayload.is_a?(CFDP::PDUACK)\n\n if pduPacket.pduPayload.directiveCode == 5\n\n writeLog(\"Sending FINISHED Ack, must finish transaction\")\n writeLog(\"Transaction #{@ID} finished with <#{CFDP.conditionCodeToStr(pduPacket.pduPayload.conditionCode)}> condition\")\n CFDP::CFDP_Indication(\"Transaction #{@ID} finished with <#{CFDP.conditionCodeToStr(pduPacket.pduPayload.conditionCode)}> condition\")\n CFDP::HKPacket.instance.updateVar(pduPacket.pduPayload.conditionCode)\n finish(pduPacket.pduPayload.conditionCode == 0 ? \"SUCCESS\" : \"FAILED\")\n end\n else\n\n update(pduPacket)\n\n if (pduPacket.pduPayload.is_a?(CFDP::PDUEOF) && isclass1?)\n\n CFDP::CFDP_Indication(\"Transaction #{@ID} finished with <#{CFDP.conditionCodeToStr(pduPacket.pduPayload.conditionCode)}> condition.\")\n writeLog(\"Transaction #{@ID} finished with <#{CFDP.conditionCodeToStr(pduPacket.pduPayload.conditionCode)}> condition.\")\n CFDP::HKPacket.instance.updateVar(pduPacket.pduPayload.conditionCode)\n finish(pduPacket.pduPayload.conditionCode == 0 ? \"SUCCESS\" : \"FAILED\")\n end\n end\n end\n end",
"def received(data, command)\n\t\tlogger.debug \"Extron IPCP sent #{data}\"\n\t\t\n\t\tif command.nil? && data =~ /Copyright/i\n\t\t\tpass = setting(:password)\n\t\t\tif pass.nil?\n\t\t\t\tdevice_ready\n\t\t\telse\n\t\t\t\tdo_send(pass)\t\t# Password set\n\t\t\tend\n\t\telsif data =~ /Login/i\n\t\t\tdevice_ready\n\t\telse\n\t\t\tcase data[0..2].to_sym\n\t\t\twhen :Irs\t# IR Sent\n\t\t\twhen :Cpn\t# IO or Relay\n\t\t\t\tport = data[3..-1].to_i\n\t\t\t\t\n\t\t\t\tdata = data.split(' ')[1]\n\t\t\t\tcase data[0..2]\n\t\t\t\twhen 'Iom'\t# IO mode\n\t\t\t\t\tdata = data[3..-1].split(',')\n\t\t\t\t\tself[\"IO#{port}_mode\"] = data[0].to_i\n\t\t\t\t\tif data.length > 1\n\t\t\t\t\t\tself[\"IO#{port}_upper\"] = data[1].to_i\n\t\t\t\t\t\tself[\"IO#{port}_lower\"] = data[2].to_i\n\t\t\t\t\tend\n\t\t\t\twhen 'Sio'\n\t\t\t\t\tself[\"IO#{port}\"] = data[3..-1].to_i\n\t\t\t\t\t\n\t\t\t\twhen 'Rly'\t\t\t\t\t\t# Relay\n\t\t\t\t\tself[\"relay#{port}\"] = data[3..-1].to_i == 1\n\t\t\t\t\t\n\t\t\t\tend\n\t\t\twhen :Dcp\t# Power\n\t\t\t\tdata = data.split('*')\n\t\t\t\tport = data[0][5..-1].to_i\n\t\t\t\tself[\"power#{port}\"] = data[1] == '1'\n\t\t\telse\n\t\t\t\tif data == 'E22'\t# Busy! We should retry this one\n\t\t\t\t\tsleep(1)\n\t\t\t\t\treturn :failed\n\t\t\t\telsif data[0] == 'E'\n\t\t\t\t\tlogger.info \"Extron Error #{ERRORS[data[1..2].to_i]}\"\n\t\t\t\t\tlogger.info \"- for command #{command[:data]}\" unless command.nil?\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t\n\t\treturn :success\n\tend",
"def sendmsg(s)\n @sock.send \"#{s}\\n\", 0 \n end",
"def sms_deliver_first_octet\n octet = 0\n octet |= 0x04 unless @opts[:more_to_send]\n octet |= 0x80 if @opts[:has_udh]\n octet.chr\n end",
"def send_message(body)\n # checksum\n body << ((~body.sum+1) & 0x7F)\n\n # sysex wrapper and header\n msg = [\n 0xF0,\n 0x00,0x01,0x73,0x7E, # header: iConnectivity's manufacturer ID and message class\n *body,\n 0xF7\n ]\n\n # send sysex\n output = UniMIDI::Output.first\n output.puts(msg)\nend",
"def send_message(msg)\n # Build the message and get it's size\n message = msg.serialize_to_string\n message_size = [message.length].pack('N')\n\n # Try to send the message\n try_again = true\n begin\n data = \"\"\n @ssl_client.write(message_size + message)\n @ssl_client.readpartial(1000,data)\n rescue\n # Sometimes our connection might drop or something, so\n # we'll reconnect to the unit and try to send the message again.\n if try_again\n try_again = false\n connect_to_unit\n retry\n else\n # Looks like we couldn't connect to the unit after all.\n puts \"message not sent\"\n end\n end\n\n return data\n end",
"def send_io(p0) end",
"def perform_write(command)\n @tcp_socket.send(command.to_bytes.pack('C*'), 0)\n end",
"def select(aid)\n\t\t\tsend_apdu!(\"\\x00\\xA4\\x04\\x00#{aid.size.chr}#{aid}\")\n end",
"def send_packet(payload); end",
"def send data\n data = [data.bytesize, *data.bytes].pack 'NC*'\n\n @socket.send data, 0\n end",
"def raw_send_recv(cmd, nsock = self.sock)\n\t\tnsock.put(cmd)\n\t\tnsock.get_once\n\tend",
"def do_send(command, options = {})\n\t\t#logger.debug \"-- Sharp LCD, sending: #{command}\"\n\t\t\n\t\tcommand = command.clone\n\t\tcommand << 0x0D << 0x0A\n\t\t\n\t\tsend(command, options)\n\tend",
"def send_data(databuf)\n if active?\n msg = Message.new\n msg.from = @my_jid\n msg.to = @peer_jid\n\n data = msg.add REXML::Element.new('data')\n data.add_namespace NS_IBB\n data.attributes['sid'] = @session_id\n data.attributes['seq'] = @seq_send.to_s\n data.text = Base64::encode64(databuf)\n\n # TODO: Implement AMP correctly\n amp = msg.add REXML::Element.new('amp')\n amp.add_namespace 'http://jabber.org/protocol/amp'\n deliver_at = amp.add REXML::Element.new('rule')\n deliver_at.attributes['condition'] = 'deliver-at'\n deliver_at.attributes['value'] = 'stored'\n deliver_at.attributes['action'] = 'error'\n match_resource = amp.add REXML::Element.new('rule')\n match_resource.attributes['condition'] = 'match-resource'\n match_resource.attributes['value'] = 'exact'\n match_resource.attributes['action'] = 'error'\n\n @stream.send(msg)\n\n @seq_send += 1\n @seq_send = 0 if @seq_send > 65535\n else\n raise 'Attempt to send data when not activated'\n end\n end",
"def write(s)\n @port.write(s)\n sleep(@wait_after_send / 1000.0) if @wait_after_send\n end",
"def send_apdu!(apdu)\n \tsend_apdu(apdu).raise_errno!\n end",
"def send_to_port(message, port)\n s = EventMachine::Synchrony::TCPSocket.new('127.0.0.1', port)\n s.write message\n data = ''\n recv = s.read(1)\n while recv\n data += recv\n recv = s.read(1)\n end\n s.close\n data\nend",
"def send_to peer\n peer.semaphore.synchronize do \n data = { id: service_id, data: self.data }.to_json\n buffer = Buffer::Writer.new data\n buffer.segments.each { |segment| peer.send_data segment }\n peer.last_used_at = Time.now\n sleep 0.3\n end\n end",
"def send_with_reply( type, data=nil )\n send_packet type, data\n read_packet\n end",
"def send_cmd(cmd)\n full_cmd = '$' + cmd + '#' + checksum(cmd)\n vprint_status('Sending cmd: '+full_cmd)\n sock.put(full_cmd)\n read_ack\n end",
"def deliver(uuid, idents, data)\n self.send_resp(uuid, idents.join(' '), data)\n end",
"def send_tcp message\n @sender.send_tcp message, @ip\n end",
"def sendmsg(cmd)\n\tdst = cmd[0]\n msg = $hostname + \" \" + dst + \" \" + cmd[1..-1].join(\" \")\n error_msg = \"SNDMSG ERROR: HOST UNREACHABLE\"\n\n # Make sure dst is reachable by checking it's next table, making sure it's not NA\n # and that the client table can find the right client\n if ($next.include?(dst) && $next[dst] != \"NA\" &&\n $clients.has_key?($next[dst]))\n next_hop = $next[dst]\n else\n STDOUT.puts(error_msg)\n return\n end\n\n client = $clients[next_hop]\n \n # Construct the packet\n packet = Msg.new()\n packet.setConfig(\"type\", 5)\n packet.setConfig(\"code\", 0)\n packet.setMessage(msg)\n\n success = sendMessage(client, packet)\n if !success\n STDOUT.puts(error_msg)\n end\nend",
"def header_udp package_number, file_size, signal=\"send\"\n file_size = \"%0#{@header_file_size}b\" % file_size\n number_package = \"%0#{@header_number_package_size}b\" % package_number\n eof = \"0\" if signal == \"send\"\n eof = \"1\" if sd\nclass SendFileManager\n def initialize(socket, address=nil)\n @package_size = 1024\n @address = address\n # @header_package_data = 60\n @header_file_size = 60\n @header_number_package_size = 20\n @h000000000000000000000000000000000000000000010111000110111101eader_eof_size = 1\n @header_size = @header_file_size + @header_number_package_size + @hea\n def send_file file_name, file_position=0\n file = open(\"./#{file_name}\", \"rb\")\n send_size = file_position.to_i\n file.pos = file_position.to_i\n #wait_signal_int(send_size)\n # binding.pry\n while file.size > send_size\n package_data = file.read(@package_size-@header_file_size)\n puts package_data.size\n binding.pry if file.eof?\n package_header = file.eof? ? header(file.size, \"eof\") : header(file.size)\n puts package_header + package_data\n send_size += @socket.send(package_header + package_data, 0)\n \n send_size -= package_header.size\n \n end\n binding.pry\n file.close\n message = @socket.recv(50)\n answer, file_size = message.split\n if answer == 'success'\n puts \"File #{file_name} successfully uploaded!\"\n return true\n el000000000000000000000000000000000000000000010111000110111101se\n send_file(file_name, file_size)\n return false\n end \n end\n \n def wait_sd message OOB'\n puts \"Sent #{send_size} bytes to socket\"\n @socket.send(@oob_char, Socket::MSG_OOB)\n end\n end \n \n def header file_size, signal=\"send\"\n header = \"%0#{@header_file_size}b\" % file_size\n puts header.size\n header[0] = \"0\" if signal == \"send\"\n header[0] = \"1\" if signal == \"eof\"\n header\n end\n\n def send_file_udp file_name,en(\"./#{file_name}\", \"rb\")\n packages_count = (file.size / (@package_size-@header_size).to_f).ceil\n numbers_packages_to_upload = []\n 0.upto(packages_count-1) do |number|\n numbers_packages_to_upload.push(number) unless numbers_downloaded_packages.include?(number)\n end\n send_size = file_position.to_i\n file.pos = file_position.to_i\n numbers_packages_to_upload.each000000000000000000000000000000000000000000010111000110111101 do |package_number|\n file.pos = package_number * (@package_size-@header_size)\n package_data = file.read(@package_size-@header_size)\n package_header = file.eof? ? header_udp(package_number, numbers_packages_to_upload.size, \"eof\") : header_udp(package_number, numbers_packages_to_upload.size)\n package = package_header + package_data\n send_size += @address? @socket.send(package,0,@address) : @socket.send(package,0)\n send_size -= package_header.size\n end\n file.close\n message =s = message.split\n if answer == 'success'\n puts \"File #{file_name} successfully uploaded!\"\n return true\n else\n numbers_packages = numbers_packages.map {|numb| numb.to_i} + numbers_downloaded_packages\n send_file_udp(file_name, file_size, numbers_packages)\n return false\n end\n end\n\n def send_file_udp_server file_name, file_positi000000010111000110111101ackages=[]\n\n file = open(\"./#{file_name}\", \"rb\")\n packages_count = (file.size / (@package_size-@header_size).to_f).ceil\n numbers_packages_to_upload = []\n 0.upto(packages_count-1) do |number|\n numbers_packages_to_upload.push(number) unless numbers_downloaded_packages.include?(number)\n end\n send_size = file_position.to_i\n file.pos = file_position.to_i\n numbers_packages_to_upload.each do |package_number|\n file.pos = package_number * (@package_size-@header_size)\n package_data = file.read(@package_size-@header_size)\n package_header = file.eof? ? header_udp(package_number, numbers_packages_to_upload.size, \"eof\") : header_udp(package_number, numbers_packages_to_upload.size)\n send_size += @socket.send(package_header + package_data, 0)\n send_size -= package_header.size\n end\n file.close\n message = @socket.recv(80000)\n answer, file_size, *numbers_packages = message.split\n 000000010111000110111101'\n puts \"File #{file_name} successfully uploaded!\"\n return true\n else\n numbers_packages = numbers_packages.map {|numb| numb.to_i} + numbers_downloaded_packages\n send_file_udp(file_name, file_size, numbers_packages)\n return false\n end\n end\n #header size = 60\n def header_udp package_number, file_size, signaze\n number_package = \"%0#{@header_number_package_size}b\" % package_number\n eof = \"0\" if signal == \"send\"\n eof = \"1\" if signal == \"eof\"\n file_size + number_package + eof\n end\nend\nclass SendFileManager\n def initialize(socket, address=nil)\n @package_size = 1024\n @address = address\n # @header_package_data = 60\n @header_file_size = 60\n @header_number_package_size = 20\n @header_eof_size = 1\n @header_size = @header_file_size + @header_number_package_size + @header_eof_size\n @oob_char = '!'\n @socket = socket\n end\n\n def send000000000000000000000000000000000000000000010111000110111101_file file_name, file_position=0\n file = open(\"./#{file_name}\", \"rb\")\n send_size = file_position.to_i\n file.pos = file_position.to_i\n #wait_signal_int(send_size)\n # binding.pry\n while file.size > send_size\n package_data = file.read(@package_size-@header_file_size)\n puts package_data.size\n binding.pry if fi \"eof\") : header(file.size)\n puts package_header + package_data\n send_size += @socket.send(package_header + package_data, 0)\n \n send_size -= package_header.size\n \n end\n binding.pry\n file.close\n message = @socket.recv(50)\n answer, file_size = message.split\n if answer == 'success'\n puts \"File #{file_name} successfull_name, file_size)\n return false\n end \n end\n \n def wait_signal_int send_size\n Signal.trap(:INT) do\n puts 'Send message O000000000000000000000000000000000000000000010111000110111101OB'\n puts \"Sent #{send_size} bytes to socket\"\n @socket.send(@oob_char, Socket::MSG_OOB)\n end\n end \n \n def header file_size, signal=\"send\"\n header = \"%0#{@header_file_size}b\" % file_size\n puts header.size\n header[0] = \"0\" if signal == \"send\"\n header[0] = \"1\" if signal == \"eof\"\n header\n end\n\n def send_file_udp file_name, file_position, numbers_downloaded_packages=[]\n file = open(\"./#{file_name}\", \"rb\")\n packages_count = (file.size / (@package_size-@header_size).to_f).ceil\n numbers_packages_to_upload = []\n 0.upto(packages_count-1) do |number|\n numbers_packages_to_upload.push(number) unless numbers_downloaded_packages.include?(number)\n end\n send_size = file_position.to_i\n file.pos = file_position.to_ file.pos = package_number * (@package_size-@header_size)\n package_data = file.read(@package_size-@header_size)\n package_header000000000000000000000000000000000000000000010111000110111101 = file.eof? ? header_udp(package_number, numbers_packages_to_upload.size, \"eof\") : header_udp(package_number, numbers_packages_to_upload.size)\n package = packet.send(package,0,@address) : @socket.send(package,0)\n send_size -= package_header.size\n end\n file.close\n message = @socket.recv(80000)\n answer, file_size, *numbers_packages = message.split\n if answer == 'success'\n puts \"File #{file_name} successfully uploaded!\"\n return true\n else\n numbers_packages = numbers_packages.map {|numb| numb.to_i} + numbers_downloaded_packages\n send_file_udp(file_name, file_size, numbers_packages)\n return false\n end\n end\n\n def send_file_udp_server file_name, file_position, numbers_downloaded_packages=[]\n\n file = open(\"./#{file_name}\", \"rb\")\n packages_count = (file.size / (@package_size-@header_size).to_f).ceil\n numbers_packages_to_upload = []\n 000000000000000000000000000000000000000000010111000110111101 0.upto(packages_count-1) do |number|\n numbers_packages_to_upload.push(number) unless numbers_downloaded_packages.include?(number)\n end\n send_size = firs_packages_to_upload.each do |package_number|\n file.pos = package_number * (@package_size-@header_size)\n package_data = file.read(@package_size-@header_size)\n package_header = file.eof? ? header_udp(package_number, numbers_packages_to_upload.size, \"eof\") : header_udp(package_number, numbers_packages_to_upload.size)\n send_size += @socket.sende_header.size\n end\n file.close\n message = @socket.recv(80000)\n answer, file_size, *numbers_packages = message.split\n if answer == 'success'\n puts \"File #{file_name} successfully uploaded!\"\n return true\n else\n numbers_packages = numbers_packages.map {|numb| numb.to_i} + numbers_downl000000000000000000000000000000000000000000010111000110111101oaded_packages\n send_file_udp(file_name, file_size, numbers_packages)\n return false\n end\n end\n #header size = 60\n def header_udp package_number, file_size, signal=\"send\"\n file_size = \"%0#{@header_file_size}b\" % file_size\n number_package = \"%0#{@header_number_package_size}b\" % package_number\n eof = \"0\" if signal == \"send\"\n eof = \"1\" if signal == \"eof\"\n file_size + number_package + eof\n end\nend",
"def send(msg=\"\")\n\t\tif @connected\n\t\t\t@sock.write \"\\1#{msg}\\r\\n\" # leading \\1 for terse reply\n\t\tend\n\tend",
"def receive(data); end",
"def sendMessage(client, msg)\n packets = msg.fragment()\n packets.each do |packet|\n to_send = packet.toString() + \"\\n\"\n num_bytes = to_send.bytesize()\n check = client.write(to_send)\n if check < num_bytes\n return false\n end\n end\n return true\nend",
"def request(payload)\n payload = payload + \"\\0\" * ((16 - payload.length) % 16)\n req = [ @extra ].pack('S>')\n blocks = payload.length / 16\n req << blocks.chr\n req << @flags.chr\n req << @key\n req << @iv\n req << payload\n @udp.connect(@host, 1331)\n start_time = Time.now\n @udp.send(req, 0)\n resp = @udp.recvfrom(req.length).first\n end_time = Time.now\n reserved = resp.unpack('L>').first\n [ resp[4..-1], end_time - start_time ]\n end",
"def probe(host, port, message)\n message = message.to_binary_s if message.respond_to?('to_binary_s')\n replies = []\n begin\n udp_sock.sendto(message, host, port, 0)\n rescue ::Errno::EISCONN\n udp_sock.write(message)\n end\n reply = udp_sock.recvfrom(65535, datastore['WAIT'] / 1000.0)\n while reply && reply[1]\n replies << reply\n reply = udp_sock.recvfrom(65535, datastore['WAIT'] / 1000.0)\n end\n replies\n end",
"def send\n if @to.nil? || @from.nil? || @message.nil?\n raise ArgumentError, \"You need to include 'to' and 'from' numbers and a message to send an SMS\"\n end\n to = @to.gsub(\" \",\"\")\n from = @from.gsub(\" \",\"\")\n parameters = {\n \"sms-send-to\" => to,\n \"sms-send-from\" => from,\n \"sms-message\" => @message[0..159]\n }\n request = @browser.post(\"#{VoipfoneClient::API_POST_URL}?smsSend\", parameters)\n response = parse_response(request)\n if response == \"ok\"\n return true\n else\n raise VoipfoneAPIError, response\n end\n end",
"def send(message)\n\t\tbegin\n\t\t\t@conn.send_message(message)\n\t\trescue IOException, NativeException\n\t\t\traise IOError, 'Failed to send message to USAR server'\n\t\tend\n\tend",
"def send_msg\n req = Net::HTTP::Post.new('/nodes/receive', initheader = {'Content-Type' =>'application/json'})\n node = Cue.find_by_id(params[:id])\n if node then\n url = uri.parse(node.url)\n req.body = node.payload\n log_action \"sending single msg #{node.id}\"\n req2 = net::http.new(url.host, url.port)\n response = req2.start {|http| http.request(req) }\n response_parse = json.parse(response.body)\n log_action(\"received from node: \" + response.body)\n node.update_attribute :is_handled, true\n end\n redirect_to request.referer\n end",
"def send(message)\n socket.send(message, 0, address, port)\n end",
"def send_command_old(*args)\n # flatten the args, make sure each byte is between 0-0xFF, and send it.\n command_str = \"char-write-cmd 0x001b \" + args.flatten.map {|b| sprintf(\"%02X\", b & 0xFF)}.join\n # puts command_str\n @mip_writer.puts(command_str)\n \n # TODO: check to see if the reader has anything in the buffer, then read\n until @mip_reader.ready?\n sleep(1)\n end\n @response = @mip_reader.read_nonblock(1000)[command_str.length+1 .. -1]\n \n # return any response in packed byte format\n # pack_response(@mip_reader.read)\n end",
"def send(message)\n if message.length > 0\n # The client will return an empty string\n # on success, or it will return an error\n error = @client.transmit(message)\n if error.length > 0\n new_message(error)\n end\n end\n end",
"def process(m)\n if m.sender&.start_with?('org.freedesktop.DBus') && (m.destination && m.destination == $bus.unique_name || m.destination == $service.name)\n # Random crap calls from dbus itself, supposedly because we register.\n return super(m)\n end\n expected = $data[0].fetch(:msg)\n raise \"Not expected #{m.inspect}\" unless compat?(expected, m)\n\n # Track all serials. When we reply to a request we need to reference the\n # client's serial so the client knows what we replied to. BUT!\n # The serial is not consistent across runs and also not consistent between\n # playback runs. One additional client-side message and the serial is off.\n # To compensate we establish a fixed map of the client serials and the\n # serial of the recorded expectation. Later when replying we can then map\n # the recorded reply_serial to the reply_serial we need to actually make\n # it work.\n @client_reply_translator ||= {}\n @client_reply_translator[expected.serial] = m.serial\n\n $data.shift\n while $data[0] && $data[0].fetch(:type) != :client\n x = $data.shift.fetch(:msg)\n next if x.sender == 'org.freedesktop.DBus' # FIXME bogus recording\n next if x.destination == 'org.freedesktop.DBus' # FIXME bogus recording\n\n puts \" pushing ==>>> \"\n p x\n\n new_message = DBus::Message.new(x.message_type)\n new_message.path = x.path\n new_message.interface = x.interface\n new_message.member = x.member\n new_message.error_name = x.error_name\n new_message.destination = m.sender\n unless x.params.empty?\n params = x.params.dup\n DBus::Type::Parser.new(x.signature).parse.each do |t|\n new_message.add_param(t, params.shift)\n end\n else\n new_message.signature = x.signature\n end\n # .sender auto-set\n if x.reply_serial\n new_message.reply_serial = @client_reply_translator.fetch(x.reply_serial)\n end\n\n p new_message\n @message_queue.push(new_message)\n end\n exit 0 if $data.empty?\n puts \" -_- Zzzzz\"\n puts \"now waiting for #{$data[0]}\"\n end",
"def send!(message)\n if(self.msisdn_number.blank?)\n if(info = get_sim_info)\n self.update_attribute(:msisdn_number, response[:msisdn])\n end\n end\n\n JasperSmsGateway.send(self.msisdn_number, message)\n end",
"def send_raw(to, msg, dlr_url='')\n log_an_event(\"Gateway::TestSession\", \"send raw #{[to, msg, dlr_url].join(' ')} \")\n @events.push([\"send_raw\", {:to=>to, :msg=>msg, :dlr_url=>dlr_url}])\n\n wait_for_response = false\n status = \"sent\"\n status_string = \"TestSession\"\n [wait_for_response, status, status_string]\n end",
"def sendUDPMessage _args\n \"sendUDPMessage _args;\" \n end",
"def send_resp(uuid, conn_id, msg)\n header = \"%s %d:%s,\" % [uuid, conn_id.size, conn_id]\n string = header + ' ' + msg\n #puts \"DEBUG: #{string.inspect}\"\n @resp.send_string(string, 0)\n end",
"def send_method\n <<-CODE\n next_literal_into(msg.send_site);\n msg.recv = stack_pop();\n msg.block = Qnil;\n msg.args = 0;\n goto perform_send;\n CODE\n end",
"def send_request(data)\n \n if $DEBUG\n puts \"[request]data--------------\"\n puts data\n puts \"--------------------------\" \n end\n \n outgoing = Blix.to_binary_data(data)\n options = {}\n \n options[:key] = \"\"\n options[:reply_to] = @reply_to\n options[:content_type] = \"text/xml\"\n options[:message_id] = \"#{@time.to_i}#{rand(9999)}\"\n @out_exch.publish(outgoing, options )\n \n incoming = nil\n while (!incoming)\n msg = @in_queue.pop\n payload = msg[:payload]\n incoming = payload unless payload == :queue_empty\n end\n # \n if $DEBUG\n puts \"[request]response data-----\"\n puts incoming\n puts \"--------------------------\" \n end\n incoming\n end",
"def do_command\n _, cmd, _, atype, addr_length = @data.unpack(\"C5\")\n header_length = 0\n\n case atype\n when 1, 4 # 1: ipv4, 4 bytes / 4: ipv6, 16 bytes\n ip_length = 4 * atype\n host = IPAddr.ntop @data[4, ip_length]\n port = @data[4 + ip_length, 2].unpack('S>').first\n header_length = ip_length + 6\n when 3 # domain name\n host = @data[5, addr_length]\n port = @data[5 + addr_length, 2].unpack('S>').first\n header_length = addr_length + 7\n else\n panic :address_type_not_supported\n end\n\n case cmd\n when 1\n send_data reply_data(:success)\n @connection = EventMachine.connect(Config.remote_server_host, Config.remote_server_port, Connection)\n @connection.server = self\n @connection.send_encoded_data(\"#{host}:#{port}\")\n @connection.send_encoded_data(@data[header_length, -1])\n clear_data\n Fiber.yield\n when 2, 3 # bind, udp\n panic :command_not_supported\n else\n panic :command_not_supported\n end\n end",
"def send( data )\n # Final text data header:\n header = 0b10000001\n\n # Payload size to use (data will always be unmasked):\n size = \"#{data}\".size\n\n # Standard payload:\n if size < 126 then\n @connection.write [ header, size, \"#{data}\" ].pack \"C2A#{size}\"\n\n # 16-bit extended payload:\n elsif size <= 65535 then\n bytes = [ size ].pack( \"S\" ).unpack( \"C2\" ).reverse.map( &:to_i )\n @connection.write [ header, 126, *bytes, \"#{data}\" ]\n .pack \"C4A#{size}\"\n\n # 64-bit extended payload:\n else\n bytes = [ size ].pack( \"S\" ).unpack( \"C8\" ).reverse.map( &:to_i )\n @connection.write [ header, 127, *bytes, \"#{data}\" ]\n .pack \"C10A#{size}\"\n end\n end",
"def httpu_get(ip, port, data)\r\n socket = UDPSocket.new\r\n debug(\"Sending httpu data to #{ip} #{port}\")\r\n socket.send(data, 0, ip, port)\r\n sleep(0.25)\r\n max_times = 3\r\n times = 1\r\n begin\r\n debug(\"Attempt to receive data n°#{times}\")\r\n return_data = socket.recvfrom_nonblock(4096)\r\n return return_data\r\n rescue IO::WaitReadable\r\n if times < max_times\r\n times += 1\r\n IO.select([socket], nil, nil, 0.5)\r\n debug(\"Resending data httpu data\")\r\n socket.send(data, 0, ip, port)\r\n retry\r\n end\r\n end\r\n return nil\r\n end",
"def run\n if not @receive then\n sendUDPStream\n else\n receiveUDPStream\n end\n end",
"def message_send_device_id() -1003; end",
"def send_request(ref, msg_id, arg, b)\n if @receiver_socket\n ref = DRbObject.new_with_uri(\"receiver://%s:%s\" % [\"localhost\", Global.relay_port])\n #p ref.__drburi if ref.kind_of?(DRbObject)\n #p msg_id\n #p arg\n @receiver_msg.send_request(@receiver_socket, ref, msg_id, arg, b)\n else\n @proxy_msg.send_request(@proxy_socket, ref, msg_id, arg, b)\n end\n end",
"def send msg\n rencoded = REncode.dump([msg]).pack('C*')\n #rencoded = [193, 196, 1, 139, 100, 97, 101, 109, 111, 110, 46, 105, 110, 102, 111, 192, 102].pack('C*')\n compressed = Zlib::Deflate.deflate(rencoded)\n raw = compressed.bytes\n\n # all commented out stuff is for version 4, which we do not yet support\n # Store length as a signed integer (using 4 bytes), network byte order\n # header = [raw.length].pack('N').bytes\n\n #every message begins with an ASCII 'D'\n # header.insert(0, 'D'.ord)\n\n # header_str = header.pack('C*')\n message_str = raw.pack('C*')\n\n # puts \"Writing header:\"\n # p header_str.bytes\n # puts\n # puts \"Writing message:\"\n # p rencoded.bytes\n # puts\n\n\n # @con.write(header_str)\n @con.write(message_str)\n @con.flush\n\n nil\n end",
"def receive_data(data)\n @client.send_command(SendDataCommand.new(@connection_id, data))\n end",
"def snd(msg)\n MsgQ.msgsnd(@qid, msg)\n end",
"def send_message(message) \n @SocketHandle = TCPSocket.open(@Host,@Port)\n @SocketHandle.puts message \n server_reply = @SocketHandle.gets \n\n server_reply \n end",
"def transmit packets, delay: 0.1\r\n Ionian::Socket.new host: \"#{SOUNDWEB_IP}:#{SOUNDWEB_PORT}\" do |socket|\r\n packets.each do |packet|\r\n socket.write packet.pack(packet.map { 'C' }.join)\r\n socket.flush\r\n sleep delay\r\n end\r\n end\r\nend",
"def send_packet( type, data=nil )\n buffer = @buffers.writer\n buffer.write_long( ( data ? data.length : 0 ) + 1 )\n buffer.write_byte type.to_i\n buffer.write data.to_s if data\n @socket.send buffer.to_s, 0\n end",
"def send(args, &block)\n args = {\"obj\" => args} if !args.is_a?(Hash)\n \n my_id = nil\n raise \"No 'obj' was given.\" if !args[\"obj\"]\n str = Marshal.dump(args[\"obj\"])\n \n if args.key?(\"type\")\n type = args[\"type\"]\n else\n type = \"send\"\n end\n \n raise \"Invalid type: '#{type}'.\" if type.to_s.strip.length <= 0\n args[\"wait_for_answer\"] = true if !args.key?(\"wait_for_answer\")\n \n @out_mutex.synchronize do\n my_id = @out_count\n @out_count += 1\n \n if block\n if type == \"send\"\n if args[\"buffer_use\"]\n type = \"send_block_buffer\"\n @blocks[my_id] = {:block => block, :results => [], :finished => false, :buffer => args[\"buffer_use\"], :mutex => Mutex.new}\n else\n type = \"send_block\"\n end\n end\n end\n \n $stderr.print \"Writing #{type}:#{my_id}:#{args[\"obj\"]} to socket.\\n\" if @debug\n @out.write(\"#{type}:#{my_id}:#{str.length}\\n#{str}\")\n end\n \n #If block is broken it might never give us control to return anything - thats why we use ensure.\n begin\n if type == \"send_block\"\n loop do\n res = self.send(\"obj\" => my_id, \"type\" => \"send_block_res\")\n \n if res == \"StopIteration\"\n break\n elsif res.is_a?(Hash) and res.key?(\"result\")\n #do nothing.\n else\n raise \"Unknown result: '#{res}'.\"\n end\n \n block.call(res[\"result\"])\n end\n end\n ensure\n #Tell the subprocess we are done with the block (if break, exceptions or anything else like that was used).\n if type == \"send_block\"\n res = self.send(\"obj\" => my_id, \"type\" => \"send_block_end\")\n raise \"Unknown result: '#{res}'.\" if res != \"ok\"\n end\n \n if args[\"wait_for_answer\"]\n #Make very, very short sleep, if the result is almost instant this will heavily optimize the speed, because :sleep_answer-argument wont be used.\n sleep 0.00001\n return self.read_answer(my_id)\n end\n \n return {:id => my_id}\n end\n end",
"def send(*args)\n cmd = args.first\n if cmd == :kill\n return if @killed # It's not undead; you can't kill it twice.\n @killed = true\n @_connection.close_connection_after_writing\n end\n @_connection.send_raw_message(args)\n end",
"def send_msg(data)\n @send_lock.synchronize{\n TCP.em.schedule { send_data(data) }\n }\n end",
"def recvfrom(*rest) end",
"def recvfrom(*rest) end",
"def recvfrom(*rest) end",
"def receive_data data\n sender_port_ip_array = get_peername[2,6].unpack \"nC4\"\n sender_ip = sender_port_ip_array[1..4].join('.')\n sender_port = sender_port_ip_array[0]\n sender_addr = \"#{sender_ip}:#{sender_port}\"\n puts \"From #{sender_addr} received: #{data.to_hex}\" if $debug\n\n $remotes.each { |r|\n unless r[2] == sender_addr ## do not echo data back to sender\n # $stdout.print \"*\" unless $debug\n # $stdout.flush unless $debug\n puts \"Relaying #{data} to #{r[2]}\" if $debug\n send_datagram data, r[0], r[1]\n end\n }\n\n\n\n end",
"def send_message\n self.get_message\n self.conn.get.status\n end"
] |
[
"0.62173456",
"0.5727398",
"0.5652252",
"0.556148",
"0.55610675",
"0.5502294",
"0.5496475",
"0.54655826",
"0.5443902",
"0.54054236",
"0.53878194",
"0.5355966",
"0.53243285",
"0.5301934",
"0.52953327",
"0.5294901",
"0.52764934",
"0.52762645",
"0.5273468",
"0.5272399",
"0.52670157",
"0.5256872",
"0.52099544",
"0.5196167",
"0.519548",
"0.51886815",
"0.51820034",
"0.5170346",
"0.51599264",
"0.5123452",
"0.5091047",
"0.5082759",
"0.5079284",
"0.5074107",
"0.50708294",
"0.5069233",
"0.50382406",
"0.50296783",
"0.5026714",
"0.50239974",
"0.50211436",
"0.5017328",
"0.50091004",
"0.5002248",
"0.49982136",
"0.49955183",
"0.49949908",
"0.49946228",
"0.49936178",
"0.49783596",
"0.49661693",
"0.4958317",
"0.49485052",
"0.4924792",
"0.49215686",
"0.49194232",
"0.49098957",
"0.4901898",
"0.48968318",
"0.48923716",
"0.48922786",
"0.48861507",
"0.48856378",
"0.48805028",
"0.48785317",
"0.4878203",
"0.48708305",
"0.4870589",
"0.48665893",
"0.48521003",
"0.48483223",
"0.48469073",
"0.48465317",
"0.48441383",
"0.48428315",
"0.48399055",
"0.48335278",
"0.48297563",
"0.48264763",
"0.48254535",
"0.48254204",
"0.48134863",
"0.48127663",
"0.48096415",
"0.48051983",
"0.47997847",
"0.4786142",
"0.47831056",
"0.47795615",
"0.4777239",
"0.47769845",
"0.4770109",
"0.4765175",
"0.47633758",
"0.4756808",
"0.4752699",
"0.4752699",
"0.4752699",
"0.4747411",
"0.4745431"
] |
0.65175533
|
0
|
TODO escollir un dels metodes per la instancia d'usuari actual
|
def set_user
@user = User.find(params[:id])
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def set_usuario\n \n end",
"def usuario_actual\n \t#se guarda al usuario actual que esta loggeado por cuestion de eficiencia\n \t#para no accesar a la base de datos todo el tiempo\n \t@usuario_actual ||= Alumno.find(session[:alumno_id]) if session[:alumno_id]\n end",
"def creador\n\t\tusuario\n\tend",
"def set_usuario\n @user = Usuario.select('id,nombre,apellido,usuario,twitter').find(params[:id])\n end",
"def user_from_omni omni=@omni\n #raise omni.to_yaml\n return User.new(\n :email => omni[:info][:email],\n :name => omni[:info][:name],\n :password => pw=Devise.friendly_token[0,20],\n :password_confirmation => pw\n )\n end",
"def current_user\n #carico l'user da sessione con auth esterna tramite omniauth\n @current_user ||= AuthHub::User.find_by(id: session['warden.user.user.key'][0][0]) unless session['warden.user.user.key'].blank?\n #se non ho fatto login esterna carico id salvato (usato in sign_in omniauth e anche login con email e psw devise)\n @current_user ||= AuthHub::User.find_by(id: session[:user_id], stato: 'confermato')\n #se ho uno user corrente carico in sessione l'ente corrente\n #se ha un ente principale carico quello, altrimenti l'ho fissato col cambia ente\n if !@current_user.blank? && session['ente_corrente'].blank?\n ente_principale ||= ( AuthHub::EnteGestito.ente_principale_da_user(@current_user.id)[0] unless AuthHub::EnteGestito.ente_principale_da_user(@current_user.id).blank? )\n #se non era stato inserito l'ente principale per lo user prendo il primo dell'array\n ente_principale ||= @current_user.enti_gestiti[0] unless @current_user.enti_gestiti.blank?\n session['ente_corrente'] = ente_principale #unless ente_principale.blank?\n end\n #se session['ente_corrente'] è un hash devo caricare l'istanza di ente_gestito\n if session['ente_corrente'].is_a?(Hash)\n begin\n session['ente_corrente'] = AuthHub::EnteGestito.find(session['ente_corrente']['id'])\n rescue ActiveRecord::RecordNotFound => exc\n #metto l'ente principale\n unless AuthHub::EnteGestito.ente_principale_da_user(@current_user.id).blank?\n session['ente_corrente'] = AuthHub::EnteGestito.ente_principale_da_user(@current_user.id)[0] \n else\n session['ente_corrente'] = nil\n end\n end \n end\n @current_user\n end",
"def create_user_information # for new users. runs last according to rails.\n self.dj_name = name\n self.roles = Role.where(:title => 'noob')\n self.active = true\n set_password\n end",
"def set_user; end",
"def current_user\n \tsuper || guest_user\n \t#Super quiere decir que exactamente con los valores \n \t#del metodo original sin cambiar nada\n end",
"def current_user\n current_usuario\n end",
"def comprobar_usuario_login\n @usuario_actual=nil\n return unless session[:user_id]\n @usuario_actual = Usuario.find_by_id(session[:user_id])\n end",
"def getUsuario\n\t\treturn @usuario\n\tend",
"def usuario_params\n \n end",
"def set_usuario\n @usu = Usuario.find(params[:id])\n end",
"def verifica_usuarios\n# @user_pages, @usuarios = paginate :users, :per_page => 10\n @usuarios = User.find(:all, :order => 'nombre')\n @rol = Rol.find(params[:id])\n @usuarios = @rol.users\n end",
"def registrar_usuario\n business_user = User.new\n business_user.email = self.email\n business_user.password = business_user.generar_password\n business_user.client_type = 'empresa'\n business_user.save\n update(user_id: business_user.id, user_created_id: business_user.id)\n #luego de registrar al usuario se almacena la contraseña en la tabla Historypassword\n #donde se almacenaran las 3 ultimas usadas\n password_business = HistoryPassword.new\n password_business.password = business_user.password\n password_business.user_id = business_user.id\n password_business.save\n end",
"def set_user\n\t @usuario = User.find(params[:id])\n\t end",
"def user\n user = User.new\n user.read_creddentials\n user.login\n puts user.to_str\n end",
"def make_user\n end",
"def set_usuario\n @usuario = Usuario.find_by_email(current_usuario.email)\n end",
"def set_usuario\n #Rails.logger = Logger.new(STDOUT)\n #logger.debug \"current_usuario \" + current_usuario.inspect\n #logger.debug \"params \" + params.inspect\n \n if (params[:id] == '0')\n params[:id] = current_usuario.id\n end\n\n @usuario = Usuario.find(params[:id]) \n if (@usuario != nil)\n if (current_usuario.id_tipo_usuario == 0 or\n @usuario.id == current_usuario.id)\n else\n @usuario = nil\n end\n end\n end",
"def connect\n \t\t#Se sigue la convencion para la identificacion del usuario\n \t\t#y buscamos alusuario que se intenta conectar\n \t\tself.current_user = find_user\n \tend",
"def create_user_and_login \n\t\tinsert_into :users, {\n\t\t\tid: 1 ,\n\t\t\tfirst_name: 'First',\n\t\t\tlast_name: 'Last',\n\t\t\tlogin: 'login',\n\t\t\tpassword: 'password',\n\t\t\trole_id: 1,\n\t\t\tuid: \"a\"\n\t\t}\n\n\t\tproxy.post( 'http://my.ownet/api/session',{\n\t\t\tlogin: 'login',\n\t\t\tpassword: 'password'\n\t\t}.to_json)\n\tend",
"def user; end",
"def user; end",
"def usuario_actual\n\t\tif (id_usuario = session[:id_usuario])\n\t\t\t@usuario_actual ||= Usuario.find_by(id: id_usuario)\n\t\telsif (id_usuario = cookies.signed[:id_usuario])\n\t\t\t#raise # Error provocado para la prueba de test/helpers/sesiones_helper_test.rb\n\t\t\tusuario = Usuario.find_by(id: id_usuario)\n\t\t\tif usuario && usuario.autentificado?(:recuerda, cookies[:token_recuerda])\n\t\t\t\tdar_acceso_a usuario\n\t\t\t\t@usuario_actual = usuario\n\t\t\tend\n\t\tend\n\tend",
"def conf_universidad\n reset_session\n @valin = params['in']\n @alert = params['alert']\n valor = @valin.split(\"_\")\n cod = desencriptar(valor[0].to_i)\n id = desencriptar(valor[1].to_i)\n data = Usuario.find_by(cod_recovery: cod, id: id)\n if data.blank?\n redirect_to({:action=>\"index\", :controller=>\"perfil\"})\n else\n if data['validado'] == SIN_VALIDAR\n @nombre = data['nombre']\n session[:id] = id\n session[:email] = data['correo']\n render layout: \"login\"\n else\n redirect_to({:action => 'index', :controller=>\"login\"})\n end\n end\n end",
"def preencher_usuario2 (nome, sobrenome, email, endereco, universidade, profissao, genero, idade)\n self.nome.set nome\n self.sobrenome.set sobrenome\n self.email.set email\n self.endereco.set endereco\n self.universidade.set universidade\n self.profissao.set profissao\n self.genero.set genero\n self.idade.set idade\n self.btn_criar.click\n end",
"def set_usuario\n @user = User.find(params[:id])\n end",
"def set_usuario\r\n @usuario = User.find(params[:id])\r\n end",
"def pundit_user\n \tcurrent_usuario\n end",
"def control_usuario \n usuarios = Usuario.all\n usuarios.each do |u|\n if cuentum_signed_in? && current_cuentum.id == u.cuenta_id\n if u.rol == \"USUARIO\" \n redirect_to \"welcome/index\" \n end\n end\n end\n end",
"def control_usuario \n usuarios = Usuario.all\n usuarios.each do |u|\n if cuentum_signed_in? && current_cuentum.id == u.cuenta_id\n if u.rol == \"USUARIO\" \n redirect_to \"welcome/index\" \n end\n end\n end\n end",
"def set_user\n zeus = User.find(@zeus_user.id)\n zeus.state = User.states['retrieved_password']\n zeus.save!\n \n request.session[:rbac_user_id] = @zeus_user.id\n end",
"def user_credentials\n keys = %w[nome cognome email password]\n user_params = select_params(params, keys)\n user_params\n end",
"def index\n # @usuarios = @topico.perguntas.usuarios\n end",
"def set_fatura\n @fatura = Fatura.find(params[:id])\n @fatura.contrato.conexoes.each { |c| c.current_user = current_user }\n end",
"def index\n if current_cuentum.email == \"admin@admin.com\"\n @usuarios = Usuario.all\n @div_admin = true\n end\n @usuariosAux = Usuario.all\n @cuentas = Cuentum.all\n @usuariosAux.each do |u| \n if cuentum_signed_in? && current_cuentum.id == u.cuenta_id\n if u.rol == \"ADMINISTRADOR\"\n @usuarios = @usuariosAux\n @div_admin = true\n end\n if u.rol == \"USUARIO\" || u.rol == \"OPERARIO\"\n @usuarios = []\n @usuarios << u\n end\n end\n end\n end",
"def set_usuario\n #if UsuarioUsuario.find(params[:id]).exists?\n @usuario = Usuario.find(params[:id])\n #else\n # @usuario = Nil\n #end\n end",
"def user_params #este metodo SE PUEDE LLAMAR COMO QUIERAS, pero es necesario para que al crear un objeto se autorice su creacion (porque si no nos podrían meter codigo malicioso)\n\t\tparams.require(:user).permit(:name, :email, :password)\n\tend",
"def proxy_user; end",
"def login_as\n @page_title = _('Login_as')\n @page_icon = 'key.png'\n\n\n @users = User.select(\"*, #{SqlExport.nice_user_sql}\").where(hidden: 0).order(\"nice_user ASC\")\n\n end",
"def current_utente\n @current_utente ||= Utente.find_by(username: session[:user_id])\n end",
"def set_usuario\n @usuario = User.find(params[:id])\n end",
"def set_usuario_m\n @usuario_m = UsuarioM.find(params[:id])\n end",
"def current_user\n \t#se guarda al usuario actual que esta loggeado por cuestion de eficiencia\n \t#para no accesar a la base de datos todo el tiempo\n \t@current_user ||= Chef.find(session[:chef_id]) if session[:chef_id]\n end",
"def cria_user\n return if user.present?\n User.create(email: self.end_email, password: '123123', password_confirmation: '123123',\n tb_empregado_id: self.id, e_admin: self.e_admin || false).encrypted_password\n end",
"def set_usua\n @usua = Usua.find(params[:id])\n end",
"def inicia_analista\n current_usuario = Usuario.create!(PRUEBA_USUARIO_AN)\n current_usuario.grupo_ids = [20]\n current_usuario.save\n return current_usuario\n end",
"def inicia_analista\n current_usuario = Usuario.create!(PRUEBA_USUARIO_AN)\n current_usuario.grupo_ids = [20]\n current_usuario.save\n return current_usuario\n end",
"def inicia_analista\n current_usuario = Usuario.create!(PRUEBA_USUARIO_AN)\n current_usuario.grupo_ids = [20]\n current_usuario.save\n return current_usuario\n end",
"def inicia_analista\n current_usuario = Usuario.create!(PRUEBA_USUARIO_AN)\n current_usuario.grupo_ids = [20]\n current_usuario.save\n return current_usuario\n end",
"def inicia_analista\n current_usuario = Usuario.create!(PRUEBA_USUARIO_AN)\n current_usuario.grupo_ids = [20]\n current_usuario.save\n return current_usuario\n end",
"def inicia_analista\n current_usuario = Usuario.create!(PRUEBA_USUARIO_AN)\n current_usuario.grupo_ids = [20]\n current_usuario.save\n return current_usuario\n end",
"def new\n \t@usuario = Usuario.new\n end",
"def current_user\n User.first || User.create(username: 'mario', surname: 'rossi',email:\"example@tld.it\")\n end",
"def user_init; end",
"def user_data\n User.user_data login\n end",
"def login_user(user = User.create!(email: 'marcos@iugu.com.br', password: '123456'))\n \tlogin_as user, scope: :user\n user\n end",
"def current_user\n @current_user ||= Admin.find_by(id: session[:admin_id]) #Lay session id cho nhung trang tiep theo\n end",
"def userinfo\n if @user.nil?\n nil\n elsif @password.nil?\n @user\n else\n @user + ':' + @password\n end\n end",
"def actual_user\n User.find_by_id(session[:user_id])\n end",
"def load_user_and_authorization\n @owner_user = User.find( params[:user_id] )\n @current_user_is_owner = ( current_user_id == params[:user_id].to_i )\n end",
"def current_usuario\n if (user_id = session[:user_id])\n @current_user ||= User.find_by(id: user_id)\n elsif (user_id = cookies.signed[:user_id])\n usuario = User.find_by(id: usuario_id)\n if usuario && usuario.authenticated?(:remember, cookies[:remember_token])\n #log_in usuario\n render 'inicio'\n @current_user = usuario\n end\n end\n end",
"def instruct_user!\n end",
"def set_usuario\n @usuario = Usuario.find(params[:id])\n end",
"def set_usuario\n @usuario = Usuario.find(params[:id])\n end",
"def set_usuario\n @usuario = Usuario.find(params[:id])\n end",
"def set_usuario\n @usuario = Usuario.find(params[:id])\n end",
"def user_details; @user_details ||= login end",
"def get_user \n\t\treturn User.find(self.user_id)\n\tend",
"def login(user)\n\tif $users_profil.include?(user)\n\t\tputs \"Username: #{user}\"\n\t\tputs \"Profil: #{$users_profil[user]}\" \n\telse \n\t\tputs \"Numele de utilizator este gresit.\"\n\t\tprima # daca a scris usernamul gresit sau daca acel username nu exista atunci scriptul practic se reinitializeaza\n\tend\nend",
"def user\n end",
"def set_utilisateur\n @utilisateur = Utilisateur.find(params[:id])\n end",
"def user(*eras); end",
"def login\n @table_title = '使用者登入'\n @title = ['main1'=>'登入', 'LOGIN'=>'Users','sub1'=>'首頁' , 'sub2'=>'登入']\n @user = User.new\n end",
"def build_from_current_user!(user)\n self.nombres = user.name\n self.email = user.info[\"email\"]\n end",
"def liaison\n inverse_accounts.last.user\n end",
"def user\n authentication.user\n end",
"def current_user\n # super: don't change anything, i just want the exact same behavior \n # as in the method that we are overriding\n\n # what this line means is that if the user is logged in, super is true,\n # then call super treat everything normal, and ignore right hand side\n # if super == false, call right hand side\n\n # super comes from devise class\n # meanwhile the r.h.s comes from open struct class\n super || guest_user\n end",
"def set_user\n #User.user = session[:user_id]\n #User.password = session[:passwd]\n Api::Base.user = session[:user_id]\n Api::Base.password = session[:passwd]\n\n begin\n @user = User.find(params[:id])\n rescue ActiveResource::ResourceNotFound\n redirect_to :action => 'not_found'\n rescue ActiveResource::ResourceConflict, ActiveResource::ResourceInvalid\n redirect_to :action => 'new'\n end\n end",
"def set_usuario\n @usuario = Usuario.find(params[:id])\n end",
"def set_usuario\n @usuario = Usuario.find(params[:id])\n end",
"def set_usuario\n @usuario = Usuario.find(params[:id])\n end",
"def set_usuario\n @usuario = Usuario.find(params[:id])\n end",
"def set_usuario\n @usuario = Usuario.find(params[:id])\n end",
"def set_usuario\n @usuario = Usuario.find(params[:id])\n end",
"def set_usuario\n @usuario = Usuario.find(params[:id])\n end",
"def set_usuario\n @usuario = Usuario.find(params[:id])\n end",
"def set_usuario\n @usuario = Usuario.find(params[:id])\n end",
"def set_usuario\n @usuario = Usuario.find(params[:id])\n end",
"def set_usuario\n @usuario = Usuario.find(params[:id])\n end",
"def set_usuario\n @usuario = Usuario.find(params[:id])\n end",
"def set_usuario\n @usuario = Usuario.find(params[:id])\n end",
"def set_usuario\n @usuario = Usuario.find(params[:id])\n end",
"def set_usuario\n @usuario = Usuario.find(params[:id])\n end",
"def set_usuario\n @usuario = Usuario.find(params[:id])\n end",
"def create\n @user = User.new(params[:user])\n\n if current_user.local_access?\n @user.uo_id = current_user.uo_id\n end\n\n respond_to do |format|\n @user.password_string = @user.password\n if verify_super_admin(@user) && @user.save\n format.html { redirect_to admin_users_path, notice: 'Usuário foi criado com sucesso.' }\n format.json { render action: 'show', status: :created, location: @user }\n else\n if current_user.local_access?\n @uos = {current_user.uo.nome => current_user.uo.id}\n else\n @uos = Uo.order(\"nome ASC\").all.collect {|uo| [uo.nome, uo.id]}\n end\n @roles = Role.order(\"nome ASC\").all.collect { |role| [role.nome, role.id] }\n if !verify_super_admin(@user)\n flash.now[:error] = \"Apenas um usuário com papel de SuperAdmin pode criar outro usuário SuperAdmin\"\n end\n format.html { render action: 'new' }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def current_user\n\t\t@current_user ||= Usuario.find_by(id: session[:user_id]) if session[:user_id]\n\tend",
"def set_usuario\n @usuario = Usuario.where(id: params[:id]).first\n end",
"def current_user\n @current_user ||= Usuario.find(session[:usuario_id]) if session[:usuario_id]\n end"
] |
[
"0.7111474",
"0.69214624",
"0.66324705",
"0.66009986",
"0.65543723",
"0.6552042",
"0.65221125",
"0.65024304",
"0.6491112",
"0.648705",
"0.6483188",
"0.64307773",
"0.63644356",
"0.6316527",
"0.62829286",
"0.6266864",
"0.6185615",
"0.6170581",
"0.6170501",
"0.61475515",
"0.61368954",
"0.61360365",
"0.6117445",
"0.61014295",
"0.61014295",
"0.6097463",
"0.60477215",
"0.6045443",
"0.6026123",
"0.6022567",
"0.6008849",
"0.5993842",
"0.5993842",
"0.5991293",
"0.5982754",
"0.59802616",
"0.59714913",
"0.59713775",
"0.5965506",
"0.59579873",
"0.5936618",
"0.59325296",
"0.5926634",
"0.5920334",
"0.5919725",
"0.5916268",
"0.5911018",
"0.590723",
"0.58902323",
"0.58902323",
"0.58902323",
"0.58902323",
"0.58902323",
"0.58902323",
"0.5882646",
"0.58814013",
"0.5876994",
"0.58696043",
"0.58695585",
"0.5863981",
"0.584842",
"0.5844583",
"0.5837522",
"0.5834837",
"0.58328825",
"0.5827274",
"0.5827274",
"0.5827274",
"0.5827274",
"0.58262813",
"0.58208215",
"0.5816995",
"0.581588",
"0.57998264",
"0.5791027",
"0.57904947",
"0.5790141",
"0.5784944",
"0.57830805",
"0.57829845",
"0.578169",
"0.577922",
"0.577922",
"0.577922",
"0.577922",
"0.577922",
"0.577922",
"0.577922",
"0.577922",
"0.577922",
"0.577922",
"0.577922",
"0.577922",
"0.577922",
"0.577922",
"0.577922",
"0.577922",
"0.5775857",
"0.57726556",
"0.57636535",
"0.5759427"
] |
0.0
|
-1
|
Deploys the given app_id on the given instance_id in the given stack_id Blocks until AWS confirms that the deploy was successful Returns a Aws::OpsWorks::Types::CreateDeploymentResult
|
def deploy(stack_id:, app_id:, instance_id:, revision:, deploy_timeout: 1800)
# App IDs can be passed as a CSV to deploy multiple apps in the same stack
app_ids = app_id.split(",")
deploy_id = []
app_ids.each do |id|
# Update the branch/revision to the given parameter, if any.
unless revision.to_s.empty?
@opsworks_client.update_app(
{
app_id: id,
app_source: {revision: revision}
}
)
end
instance_id = [instance_id] unless instance_id.is_a?(Array)
response = @opsworks_client.create_deployment(
stack_id: stack_id,
app_id: id,
instance_ids: instance_id,
command: {
name: 'deploy'
}
)
log("Deploy process running (id: #{response[:deployment_id]})...")
deploy_id.push(response[:deployment_id])
end
deploy_id.each do |id|
wait_until_deploy_completion(id, deploy_timeout)
end
log("✓ deploy completed")
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def deploy_application(app_id, options = {:comment => nil, :migrate => false})\n json_command = JSON.dump(:command => 'deploy', \n :comment => options[:comment], \n :migrate => options[:migrate])\n http_post_request(Scalarium.applications_url+\"/#{app_id}/deploy\", json_command) \n end",
"def create_deployment(command, instances, timeout)\n instance_ids = nil\n instance_description = \"all instances\"\n\n if !instances.nil?\n instance_ids = instances.map(&:instance_id)\n instance_description = instances.map(&:hostname).join(',')\n end\n\n deployment_config = {\n stack_id: opsworks_app[:stack_id],\n app_id: app_id,\n instance_ids: instance_ids,\n command: command,\n comment: \"Git Sha: #{current_sha}\"\n }\n\n deployment = opsworks_client.create_deployment(deployment_config)\n print \"Running command \".light_blue\n print \"#{command[:name]}\".light_blue.bold\n puts \" on #{instance_description}\".light_blue\n\n begin\n _wait_until_deployed(deployment[:deployment_id], timeout)\n puts \"Deployment successful\".green\n true\n rescue Aws::Waiters::Errors::WaiterFailed => e\n puts \"Failed to deploy: #{e.message}\".red\n false\n end\n end",
"def deploy_app(app, deploy_params = {})\n deploy_generated(app.services_xml, app.sd_files,\n deploy_params.merge(app.deploy_params), app.hosts_xml, nil, app.validation_overrides_xml)\n end",
"def deploy(id, host, xml_text, lcm_state, deploy_id)\n # Restore if we need to\n if lcm_state != \"BOOT\" && lcm_state != \"BOOT_FAILURE\"\n restore(deploy_id)\n return deploy_id\n end\n\n # Otherwise deploy the VM\n\n begin\n ec2_info = get_deployment_info(host, xml_text)\n rescue Exception => e\n raise e\n end\n\n load_default_template_values\n\n if !ec2_value(ec2_info, 'AMI')\n raise \"Cannot find AMI in deployment file\"\n end\n\n opts = generate_options(:run, ec2_info, {\n :min_count => 1,\n :max_count => 1})\n\n # The OpenNebula context will be only included if not USERDATA\n # is provided by the user\n if !ec2_value(ec2_info, 'USERDATA')\n xml = OpenNebula::XMLElement.new\n xml.initialize_xml(xml_text, @provision_type == :host ? 'HOST' : 'VM')\n\n if xml.has_elements?('TEMPLATE/CONTEXT')\n # if requested, we generated cloud-init compatible data\n if ec2_value(ec2_info, 'CLOUD_INIT') =~ /^(yes|true)$/i\n context_str = generate_cc(xml, 'TEMPLATE/CONTEXT')\n else\n # Since there is only 1 level ',' will not be added\n context_str = xml.template_like_str('TEMPLATE/CONTEXT')\n\n if xml['TEMPLATE/CONTEXT/TOKEN'] == 'YES'\n # TODO use OneGate library\n token_str = generate_onegate_token(xml)\n if token_str\n context_str << \"\\nONEGATE_TOKEN=\\\"#{token_str}\\\"\"\n end\n end\n end\n\n userdata_key = EC2[:run][:args][\"USERDATA\"][:opt]\n opts[userdata_key] = Base64.encode64(context_str)\n end\n end\n\n instances = @ec2.create_instances(opts)\n instance = instances.first\n\n start_time = Time.now\n\n while Time.now - start_time < @state_change_timeout\n begin\n break if instance.exists?\n rescue => e\n OpenNebula::log_error(\"RESCUE: #{e.inspect}\")\n end\n\n sleep 2\n end\n\n tags = generate_options(:tags, ec2_info)[:tags] || {}\n\n tag_array = []\n tags.each{ |key,value|\n tag_array << {\n :key => key,\n :value => value\n }\n }\n\n instance.create_tags(:tags => tag_array) if tag_array.length > 0\n\n elastic_ip = ec2_value(ec2_info, 'ELASTICIP')\n\n wait_state('running', instance.id)\n\n if elastic_ip\n\n if elastic_ip.match(Resolv::IPv4::Regex)\n address_key = :public_ip\n else\n address_key = :allocation_id\n end\n\n address = {\n :instance_id => instance.id,\n address_key => elastic_ip\n }\n\n @ec2.client.associate_address(address)\n end\n\n if @provision_type == :host\n instance.create_tags(tags: [{\n key: 'Name',\n value: host['//HOST/TEMPLATE/PROVISION/HOSTNAME']\n },{\n key: 'ONE_HOST_ID',\n value: 'TODO'\n }])\n else\n instance.create_tags(tags: [{\n key: 'ONE_ID',\n value: id\n }])\n end\n\n puts(instance.id)\n end",
"def regional_rolling_deploy(stack_id:, layer_id:, app_id:, revision: '')\n log(\"Starting opsworks deploy for app #{app_id}\\n\\n\")\n\n instances = @opsworks_client.describe_instances(layer_id: layer_id)[:instances]\n\n instances_by_group = instances.map {|v| v.to_h}.group_by { |d| d[:availability_zone] }\n\n instances_by_group.each do |region, instance_group|\n # Only deploy to online instances\n online_instance = instance_group.select{|k| k[:status] == 'online'}\n instances_ids = online_instance.map{|k| k[:instance_id]}\n instances_names = online_instance.map{|k| k[:hostname]}\n\n next if instances_names.empty?\n\n puts \"#{instances_names} in #{region}\"\n\n begin\n load_balancers = {}\n log(\"=== Starting deploy for #{instances_names} ===\")\n\n online_instance.each do |instance|\n instance = Aws::OpsWorks::Types::Instance.new(instance)\n load_balancers[instance.instance_id] = detach_from_elbs(instance: instance)\n end\n\n wait_for_detach(@lb_wait_params)\n\n deploy(\n stack_id: stack_id,\n app_id: app_id,\n instance_id: instances_ids,\n revision: revision\n )\n ensure\n online_instance.each do |instance|\n instance = Aws::OpsWorks::Types::Instance.new(instance)\n attach_to_elbs(instance: instance, load_balancers: load_balancers[instance.instance_id]) if load_balancers[instance.instance_id]\n end\n\n wait_for_re_attach(@lb_wait_params)\n\n log(\"=== Done deploying on #{instances_names} ===\\n\\n\")\n end\n end\n\n log(\"SUCCESS: completed opsworks deploy for all instances on app #{app_id}\")\n end",
"def deploy\n unless serverside_version\n # only set serverside version if it's not set, to imitate the api\n # behavior of choosing its own serverside version if one is not\n # sent\n update :serverside_version => AWSM_SERVERSIDE_VERSION\n end\n finished!(\n :successful => true,\n :output => 'Deployment triggered by the API'\n )\n end",
"def deploy!(archive, env)\n archive.upload(Beanstalk.api)\n \n if env.status.empty?\n puts \"Creating stack '#{@stack}' for #{archive.app_name}-#{archive.version}...\"\n env.create!(archive, @stack, @cnames, @config)\n env.wait_until_status_is_not \"Launching\"\n else\n puts \"Deploying #{archive.version} to #{env.name}...\"\n env.deploy!(archive, @config)\n env.wait_until_status_is_not \"Updating\"\n end\n \n env.wait_until_healthy\n puts \"Done. Visit http://#{env.url} in your browser.\"\n DeploymentInfo.new env, archive\n end",
"def deploy\n cmd = \"deploy #{@resource[:source]} --name=#{@resource[:name]}#{runtime_name_param_with_space_or_empty_string}\"\n if @resource[:runasdomain]\n cmd = append_groups_to_cmd(cmd, @resource[:servergroups])\n end\n cmd = \"#{cmd} --force\" if force_deploy?\n display_lines 100\n bring_up 'Deployment', cmd\n @resource[:name]\n end",
"def deploy(options={})\n buffer = \"Starting application #{application_name}\\n\"\n\n if options[:out]\n options[:out].puts(buffer)\n end\n\n buffer << start_gear(secondary_only: true,\n user_initiated: true,\n hot_deploy: options[:hot_deploy],\n out: options[:out],\n err: options[:err])\n\n @state.value = ::OpenShift::Runtime::State::DEPLOYING\n\n web_proxy_cart = @cartridge_model.web_proxy\n if web_proxy_cart\n buffer << @cartridge_model.do_control('deploy',\n web_proxy_cart,\n pre_action_hooks_enabled: false,\n prefix_action_hooks: false,\n out: options[:out],\n err: options[:err])\n end\n\n buffer << @cartridge_model.do_control('deploy',\n @cartridge_model.primary_cartridge,\n pre_action_hooks_enabled: false,\n prefix_action_hooks: false,\n out: options[:out],\n err: options[:err])\n\n buffer << start_gear(primary_only: true,\n user_initiated: true,\n hot_deploy: options[:hot_deploy],\n out: options[:out],\n err: options[:err])\n\n buffer << @cartridge_model.do_control('post-deploy',\n @cartridge_model.primary_cartridge,\n pre_action_hooks_enabled: false,\n prefix_action_hooks: false,\n out: options[:out],\n err: options[:err])\n\n buffer\n end",
"def run_stack(ctn, payload, directory, action)\n unless([:create, :update].include?(action.to_sym))\n abort ArgumentError.new(\"Invalid action argument `#{action}`. Expecting `create` or `update`!\")\n end\n ctn.exec!('bundle install', :cwd => directory, :timeout => 120)\n stack_name = payload.get(:data, :stacks, :name)\n\n event!(:info, :info => \"Starting stack #{action} - #{stack_name}!\", :message_id => payload[:message_id])\n\n stream = Fission::Utils::RemoteProcess::QueueStream.new\n env_vars = build_environment_variables(payload)\n future = Zoidberg::Future.new do\n begin\n ctn.exec(\n \"bundle exec sfn #{action} #{stack_name} --defaults --no-interactive-parameters --file #{payload.get(:data, :stacks, :template)} --yes\",\n :stream => stream,\n :cwd => directory,\n :environment => env_vars.merge(\n 'HOME' => directory,\n 'USER' => 'SparkleProvision'\n ),\n :timeout => 3600 # TODO: This will probably need to be tunable!\n )\n rescue => e\n error \"Stack #{action} failed (ID: #{payload[:message_id]}): #{e.class} - #{e}\"\n debug \"#{e.class}: #{e}\\n#{e.backtrace.join(\"\\n\")}\"\n Fission::Utils::RemoteProcess::Result.new(-1, \"Build failed (ID: #{payload[:message_id]}): #{e.class} - #{e}\")\n ensure\n stream.write :complete\n end\n end\n\n until((lines = stream.pop) == :complete)\n lines.split(\"\\n\").each do |line|\n line = line.sub(/^\\[.+?\\]/, '').strip\n next if line.empty?\n debug \"Log line: #{line}\"\n event!(:info, :info => line, :message_id => payload[:message_id])\n end\n end\n\n result = future.value\n ctn.terminate\n\n if(result && result.success?)\n event!(:info, :info => \"Stack #{action} completed - #{stack_name}!\", :message_id => payload[:message_id])\n else\n error \"Stack #{action} failed for stack #{stack_name}\"\n error \"Stack #{action} failed with exit status of `#{result.exit_code}`\"\n error = Fission::Error::RemoteProcessFailed.new(\"Stack #{action} failed - Exit code: #{result.exit_code}\")\n raise error\n end\n end",
"def deploy(id, drv_message)\n error = \"Action not implemented by driver #{self.class}\"\n send_message(ACTION[:deploy],RESULT[:failure],id,error)\n end",
"def deploy_stack(stack_name, parameters, template,\n capabilities = ['CAPABILITY_IAM'], disable_rollback: false)\n wait_options = {\n max_attempts: @wait_max_attempts,\n delay: @wait_delay\n }\n\n stack_parameters = {\n stack_name: stack_name,\n template_body: File.read(template),\n capabilities: capabilities,\n parameters: params(parameters)\n }\n\n attempt_to_update_stack(stack_name, stack_parameters, wait_options)\n rescue Aws::CloudFormation::Errors::ValidationError => error\n if error.to_s.include? 'No updates are to be performed.'\n puts 'Nothing to do.' if ENV['DEBUG']\n elsif error.to_s.include? 'Template error'\n raise error\n else\n stack_parameters[:disable_rollback] = disable_rollback\n attempt_to_create_stack(stack_name, stack_parameters, wait_options)\n end\n end",
"def deploy(id, host, xml_text, lcm_state, deploy_id)\n if %w[BOOT BOOT_FAILURE].include? lcm_state\n one_info = get_deployment_info(host, xml_text)\n\n # load_default_template_values\n\n tid = one_value(one_info, 'TEMPLATE_ID')\n\n if tid.nil? || tid == ''\n STDERR.puts('Cannot find TEMPLATE_ID in deployment file')\n exit(-1)\n end\n\n extra_template = \"REMOTE_OPENNEBULA = YES\\n\"\\\n \"REMOTE_OPENNEBULA_VM_ID = #{id}\\n\"\n\n # The OpenNebula context will be included\n xml = OpenNebula::XMLElement.new\n xml.initialize_xml(xml_text, 'VM')\n\n if xml.has_elements?('TEMPLATE/CONTEXT')\n # Since there is only 1 level ',' will not be added\n context_str = xml.template_like_str('TEMPLATE/CONTEXT')\n\n if xml['TEMPLATE/CONTEXT/TOKEN'] == 'YES'\n # TODO: use OneGate library. See ec2_driver.rb\n token_str = generate_onegate_token(xml)\n if token_str\n context_str << \"\\nONEGATE_TOKEN=\\\"#{token_str}\\\"\"\n end\n end\n\n extra_template << context_str\n end\n\n t = OpenNebula::Template.new_with_id(tid, @client)\n rc = t.instantiate(REMOTE_NAME_PREFIX+id, true, extra_template,\n false)\n\n if OpenNebula.is_error?(rc)\n STDERR.puts(rc.to_str)\n exit(-1)\n end\n\n deploy_id = \"#{DEPLOY_ID_PREFIX}#{rc}\"\n vm = get_remote_vm(deploy_id)\n\n if !context_str.nil?\n new_context_update = 'CONTEXT = [' << context_str << ']'\n new_context_update = new_context_update.gsub(\"\\n\", \",\\n\")\n rc = vm.updateconf(new_context_update)\n end\n\n if OpenNebula.is_error?(rc)\n STDERR.puts(rc.to_str)\n exit(-1)\n end\n\n vm.release\n\n rc = vm.update(\"REMOTE_OPENNEBULA_DEPLOY_ID = \\\"#{deploy_id}\\\"\",\n true)\n\n if OpenNebula.is_error?(rc)\n STDERR.puts('Error adding REMOTE_OPENNEBULA_DEPLOY_ID ' \\\n \"attribute to VM #{rc}: #{rc.to_str}\")\n end\n\n puts(deploy_id)\n else\n restore(deploy_id)\n deploy_id\n end\n end",
"def deploy\n update_repositories\n sync_service_environment_files\n # deploy_services\n response\n end",
"def deploy(environment, status, version)\n return if SharedStatus.dry_run?\n return unless status == 'success'\n\n sha = ReleaseTools::Qa::Ref.new(version).ref\n now = Time.now.utc.iso8601\n\n params = {\n environment: environment,\n dateStarted: now,\n dateFinished: now\n }\n\n logger.info('Creating Sentry deploy', version: sha, environment: environment)\n client.post(\"#{API_ENDPOINT}#{sha}/deploys/\", json: params)\n end",
"def deploy\n if phase.has_key?('deploy')\n execute(\"deploy\", phase['deploy'])\n end\n end",
"def _wait_until_deployed(deployment_id, timeout)\n opsworks_client.wait_until(:deployment_successful, deployment_ids: [deployment_id]) do |w|\n w.before_attempt do |attempt|\n puts \"Attempt #{attempt} to check deployment status\".light_black\n end\n w.interval = 10\n w.max_attempts = timeout / w.interval\n end\n end",
"def create\n GITHUB.create_deployment(\n @project.repository_path,\n @deploy.job.commit,\n payload: {\n deployer: @deploy.user.attributes.slice(\"id\", \"name\", \"email\"),\n buddy: @deploy.buddy&.attributes&.slice(\"id\", \"name\", \"email\"),\n },\n environment: @stage.name,\n description: @deploy.summary,\n production_environment: @stage.production?,\n auto_merge: false, # make deployments on merge commits not produce Octokit::Conflict and do not merge PRs\n required_contexts: [], # also create deployments when commit statuses show failure (CI failed)\n accept: \"application/vnd.github.ant-man-preview+json\" # special header so we can use production_environment field\n )\n end",
"def deploy\n @operation = \"Deploy\"\n build_env = project[:build_env] || \"\"\n\n prepare_local_dir do\n run_cmd \"cap -q deploy #{build_env}\"\n run_cmd \"cap -q deploy:migrate #{build_env}\"\n run_cmd \"cap -q deploy:cleanup #{build_env}\"\n end\n end",
"def elastic_beanstalk_app(app_name,\n stack_name,\n ssh_key: app_name,\n solution_stack_name: '64bit Amazon Linux 2015.09 v2.0.4 running Ruby 2.2 (Passenger Standalone)',\n instance_type: 't2.small')\n\n properties = {\n ApplicationName: app_name,\n Description: \"#{app_name} in #{stack_name} stack\",\n ConfigurationTemplates:\n [\n {\n TemplateName: 'DefaultConfiguration',\n Description: 'Default Configuration Version 1.0 - with SSH access',\n SolutionStackName: solution_stack_name,\n OptionSettings: [\n {\n 'Namespace': 'aws:autoscaling:launchconfiguration',\n 'OptionName': 'EC2KeyName',\n 'Value': ssh_key\n },\n {\n 'Namespace': 'aws:ec2:vpc',\n 'OptionName': 'VPCId',\n 'Value': vpc.id\n },\n {\n 'Namespace': 'aws:ec2:vpc',\n 'OptionName': 'Subnets',\n 'Value': { 'Fn::Join': [',', ref_application_subnets] }\n },\n {\n 'Namespace': 'aws:ec2:vpc',\n 'OptionName': 'ELBSubnets',\n 'Value': { 'Fn::Join': [',', public_subnets] }\n },\n {\n 'Namespace': 'aws:autoscaling:launchconfiguration',\n 'OptionName': 'SecurityGroups',\n 'Value': { 'Fn::Join': [',', [ref_application_security_group, ref_private_security_group]] }\n },\n {\n 'Namespace': 'aws:autoscaling:launchconfiguration',\n 'OptionName': 'InstanceType',\n 'Value': instance_type\n }\n ]\n }\n ]\n }\n\n elastic_beanstalk_resource_name = \"#{app_name}BeanstalkApp\"\n\n resource elastic_beanstalk_resource_name,\n Type: 'AWS::ElasticBeanstalk::Application',\n Properties: properties\n\n elastic_beanstalk_resource_name\n end",
"def deploy\n Kb8Run.update_context(@kb8context)\n @deploy_units.each do | deploy_unit |\n deploy_unit.deploy\n end\n end",
"def deploy\n # ensure the resource group is created\n params = @client.model_classes.resource_group.new.tap do |rg|\n rg.location = 'westus'\n end\n @client.resource_groups.create_or_update(@resource_group, params)\n\n # build the deployment from a json file template from parameters\n template = File.read(File.expand_path(File.join(__dir__, '../templates/template.json')))\n deployment = @client.model_classes.deployment.new\n deployment.properties = @client.model_classes.deployment_properties.new\n deployment.properties.template = JSON.parse(template)\n deployment.properties.mode = Azure::Resources::Profiles::Latest::Mgmt::Models::DeploymentMode::Incremental\n\n # build the deployment template parameters from Hash to {key: {value: value}} format\n deploy_params = DEPLOYMENT_PARAMETERS.merge(sshKeyData: @pub_ssh_key)\n deployment.properties.parameters = Hash[*deploy_params.map{ |k, v| [k, {value: v}] }.flatten]\n\n # log the request and response contents of Template Deployment.\n # By default, ARM does not log any content. By logging information about the request or response, you could\n # potentially expose sensitive data that is retrieved through the deployment operations.\n debug_settings = @client.model_classes.debug_setting.new\n debug_settings.detail_level = 'requestContent, responseContent'\n deployment.properties.debug_setting = debug_settings\n\n # put the deployment to the resource group\n @client.deployments.create_or_update(@resource_group, 'azure-sample', deployment)\n\n # See logged information related to the deployment operations\n operation_results = @client.deployment_operations.list(@resource_group, 'azure-sample')\n unless operation_results.nil?\n operation_results.each do |operation_result|\n puts \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\"\n puts \"operation_id = #{operation_result.operation_id}\"\n unless operation_result.properties.nil?\n puts \"provisioning_state = #{operation_result.properties.provisioning_state}\"\n puts \"status_code = #{operation_result.properties.status_code}\"\n puts \"status_message = #{operation_result.properties.status_message}\"\n puts \"target_resource = #{operation_result.properties.target_resource.id}\" unless operation_result.properties.target_resource.nil?\n puts \"request = #{operation_result.properties.request.content}\" unless operation_result.properties.request.nil?\n puts \"response = #{operation_result.properties.response.content}\" unless operation_result.properties.response.nil?\n end\n end\n end\n end",
"def wait_until_deploy_completion(deployment_id, timeout)\n started_at = Time.now\n Timeout::timeout(timeout) do\n @opsworks_client.wait_until(\n :deployment_successful,\n deployment_ids: [deployment_id]\n ) do |w|\n # disable max attempts\n w.max_attempts = nil\n end\n end\n end",
"def deploy(id, host, remote_dfile, not_used)\n error = \"Action not implemented by driver #{self.class}\"\n send_message(ACTION[:deploy],RESULT[:failure],id,error)\n end",
"def save(deploy_id)\n wait_state('running', deploy_id)\n ec2_action(deploy_id, :stop)\n wait_state('stopped', deploy_id)\n end",
"def create\n @deployment = current_user.deployments.new(params[:deployment])\n\n respond_to do |format|\n if @deployment.save\n unless @deployment.environment.running?\n @deployment.environment.start!\n end\n format.html { redirect_to(@deployment.app, :notice => 'Application was successfully deployed.') }\n format.xml { render :xml => @deployment, :status => :created, :location => @deployment }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @deployment.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def deploy\n\n $active_deploy = true\n bucket = JSON.parse($deploy_bucket.last.to_json)\n unless bucket.nil?\n puts \"Deploying code for: #{bucket.inspect}\"\n system(\"./deploy.sh #{bucket['git_account']} #{bucket['launch_branch_name']} #{bucket['git_appname']} #{bucket['heroku_appname']} #{bucket['folder_name']}\")\n end\n $deploy_bucket.pop\n puts \"Now making active_deploy as false\"\n $active_deploy = false\n check_build bucket\nend",
"def remote_deploy(options={})\n @cartridge_model.do_control('update-configuration',\n @cartridge_model.primary_cartridge,\n pre_action_hooks_enabled: false,\n post_action_hooks_enabled: false,\n out: options[:out],\n err: options[:err])\n\n deploy(options)\n\n if options[:init]\n primary_cart_env_dir = PathUtils.join(@container_dir, @cartridge_model.primary_cartridge.directory, 'env')\n primary_cart_env = ::OpenShift::Runtime::Utils::Environ.load(primary_cart_env_dir)\n ident = primary_cart_env.keys.grep(/^OPENSHIFT_.*_IDENT/)\n _, _, version, _ = Runtime::Manifest.parse_ident(primary_cart_env[ident.first])\n\n @cartridge_model.post_install(@cartridge_model.primary_cartridge,\n version,\n out: options[:out],\n err: options[:err])\n\n end\n end",
"def deploy_instance_rolling(instance, elb, timeout = 600)\n if !elb.nil?\n elb.remove_instance(instance)\n end\n\n success = create_deployment({name: 'deploy'}, [instance], timeout)\n\n # only add instance back to elb if deployment succeeded\n if !elb.nil? && success\n success = elb.add_instance(instance)\n end\n\n success\n end",
"def deploy(yaml_manifest)\n status, task_id = api.deploy(yaml_manifest)\n [status, task_id]\n end",
"def deploy(id, host, remote_dfile, not_used)\n local_dfile = get_local_deployment_file(remote_dfile)\n\n if !local_dfile || File.zero?(local_dfile)\n send_message(ACTION[:deploy],RESULT[:failure],id,\n \"Can not open deployment file #{local_dfile}\")\n return\n end\n \n local_action(\"#{@actions_path}/deploy #{host} #{local_dfile}\",id,:deploy)\n end",
"def create\n\t\t@app \t\t\t\t= find_deployable_application_by(\"public_token\", params[:deployment][:deployable_application_id])\n\n\t\t# Chech if the branch and the environment are correct, otherwise kill the request with raise HTTPUnauthorized\n\t\tvalidate_branch_and_environment(@app, params)\n\n\n\t\t# CREATE NEW RAKE DEPLOY\n\t\t@deployment \t\t= @app.deployments.create!(deployment_params)\n\n\t\tRakeInvoker.run(pull_requests: :fetch_for_app, PUBLIC_TOKEN: @app.public_token, APP_ID: @app.id, DEPLOYMENT_ID: @deployment.id)\n\n\t\t# @deployment.user \t= User.first\n\n\t\tif @deployment.save\n\t\t\trender :json => \"Done\"\n\t\telse\n\t\t\trender :json => \"Errors\"\n\t\tend\n\tend",
"def deploy_application\n deploy(selfdir + \"app\")\n end",
"def deployment(project, id)\n get(\"/projects/#{url_encode project}/deployments/#{id}\")\n end",
"def deploy(options={})\n self.mclient = get_metadata_client \n soapbody = \"<zipFile>#{options[:zip_file]}</zipFile>\"\n soapbody << \"<DeployOptions>#{options[:deploy_options]}</DeployOptions>\" unless options[:deploy_options].nil?\n begin\n response = self.mclient.request :deploy do |soap|\n soap.header = get_soap_header\n soap.body = soapbody\n end\n #puts \"raw deploy response: \" + response.inspect\n create_hash = response.to_hash\n rescue Savon::SOAP::Fault => fault\n raise Exception.new(fault.to_s)\n end\n \n update_id = create_hash[:deploy_response][:result][:id]\n is_finished = false\n timer = 0\n is_timeout = false\n \n while ! is_finished\n sleep 1\n timer += 1\n response = self.mclient.request :check_status do |soap|\n soap.header = get_soap_header\n soap.body = { :id => update_id }\n end\n check_status_hash = response.to_hash\n is_finished = check_status_hash[:check_status_response][:result][:done] \n\n if timer == ENV['FM_TIMEOUT'].to_i\n is_timeout = true\n break\n end\n end\n \n if is_timeout == true\n return { \n :is_success => false,\n :message => \"TIMEOUT\"\n }\n end\n \n response = self.mclient.request :check_deploy_status do |soap|\n soap.header = get_soap_header\n soap.body = { :id => update_id }\n end\n \n deploy_hash = response.to_hash\n #puts \"deploy result is: \" + deploy_hash.inspect\n \n return deploy_hash \n end",
"def deploy(gear, hot_deploy=false, force_clean_build=false, ref=nil, artifact_url=nil)\n result_io = ResultIO.new\n\n args = build_base_gear_args(gear)\n\n args['--with-hot-deploy'] = hot_deploy\n args['--with-force-clean-build'] = force_clean_build\n args['--with-ref'] = ref if ref.present?\n args['--with-artifact-url'] = artifact_url if artifact_url.present?\n\n result_io = run_cartridge_command(@@C_CONTROLLER, gear, \"deploy\", args)\n return result_io\n end",
"def push(app)\n deployer.execute(app, push_only: true)\n end",
"def do_deploy()\n require 'digest/md5'\n require 'aws-sdk'\n require 'progressbar'\n require 'simple-cloudfront-invalidator'\n require 'yaml'\n\n # Validation check for environment variables\n if (!ENV['AWS_S3_BUCKET'] ||\n !ENV['AWS_ACCESS_KEY_ID'] ||\n !ENV['AWS_SECRET_ACCESS_KEY'] ||\n !ENV['AWS_CLOUDFRONT_DIST_ID'] ||\n !ENV['AWS_HOST_NAME'] )\n puts(\"The below required environment variable(s) have not been defined.\\n\"\\\n \"Without them, the Deploy process cannot complete.\\n\"\\\n \"Please verify that they have been correctly defined.\")\n puts(\" * AWS_S3_BUCKET\") if (!ENV['AWS_S3_BUCKET'])\n puts(\" * AWS_ACCESS_KEY_ID\") if (!ENV['AWS_ACCESS_KEY_ID'])\n puts(\" * AWS_SECRET_ACCESS_KEY\") if (!ENV['AWS_SECRET_ACCESS_KEY'])\n puts(\" * AWS_CLOUDFRONT_DIST_ID\") if (!ENV['AWS_CLOUDFRONT_DIST_ID'])\n puts(\" * AWS_HOST_NAME\") if (!ENV['AWS_HOST_NAME'])\n exit()\n end\n\n puts(\"========================================\")\n puts(\"Beginning Deploy Process...\")\n\n # Capture Hugo's config.yaml while we're in the same directory\n config_file = YAML.load_file('config.yaml')\n\n # Make sure we actually loaded a file, and didn't just set `config_file` to\n # the string \"config.yaml\".\n if (config_file == \"config.yaml\")\n Kernel.abort(\"ERROR: Could not find 'config.yaml'. Are you running Rake \"\\\n \"from the correct directory?\")\n end\n\n # Move into the Hugo destination directory, so file names are only prefixed\n # with \"./\"\n Dir.chdir(File.join(Dir.pwd, \"#{$hugo_dest}\"))\n\n # Generate a list of every file in $hugo_dest, and `map` them into the form,\n # [[\"«file_name»\", \"«md5sum»\"], ... ]\n puts(\" Aggregating Local Hash List...\")\n local_file_list = Dir[\"./**/*\"]\n .select { |f| File.file?(f) }\n .sort_by { |f| f }\n .map { |f|\n # The file names have a leading `./`. Strip those.\n [f[2..-1], Digest::MD5.file(f).hexdigest] }\n\n\n # Open up a connection to our S3 target bucket\n puts(\" Opening S3 Connection...\")\n aws_bucket = Aws::S3::Bucket.new(ENV['AWS_S3_BUCKET'], {\n :region => \"us-east-1\",\n :access_key_id => ENV['AWS_ACCESS_KEY_ID'],\n :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'],\n })\n\n # Fetch all objects from the remote, and `map` them into the form,\n # [[\"«file_name»\", \"«md5sum»\"], ... ]\n puts(\" Fetching Remote Object List (this may take up to ~30 seconds)...\")\n aws_file_list = aws_bucket\n .objects()\n .sort_by { |objs| objs.key }\n .map { |objs|\n # the etag (which is the md5sum) is wrapped in double-quotes. Strip those\n # by 'translating' them into empty strings.\n [objs.key, objs.etag.tr('\"','')] }\n\n\n # Now that we have the two lists, we need to compare them and generate the\n # list of files we need to upload, and the list of files we need to delete.\n # To do this, we're going to use some brute force.\n puts(\" Comparing Object Hashes...\")\n new_list = []\n updated_list = []\n delete_list = []\n lcl_i = 0\n aws_i = 0\n lcl_len = local_file_list.length\n aws_len = aws_file_list.length\n progress = ProgressBar.new(\" Hash check\", lcl_len)\n while true\n # Check if we've reached the end of either list and should break\n break if (lcl_i == lcl_len || aws_i == aws_len)\n lcl_file_name = local_file_list[lcl_i][0]\n aws_file_name = aws_file_list[aws_i][0]\n\n # Compare the file/object names\n case lcl_file_name <=> aws_file_name\n when 0 # File names are identical\n # Compare md5sums. If they don't match, add the file to the updated list.\n if (local_file_list[lcl_i][1] != aws_file_list[aws_i][1])\n updated_list.push(lcl_file_name)\n end\n # In either case, increment both index variables\n lcl_i += 1; progress.inc\n aws_i += 1\n when -1 # Local file name sorts first...\n # The local file doesn't exist on AWS. Add it to the new list.\n new_list.push(lcl_file_name)\n # And only increment the local index variable.\n lcl_i += 1; progress.inc\n when 1 # AWS object name sorts first...\n # The AWS object doesn't (or no longer) exist in the locally built\n # artifacts. Schedule it for deletion.\n delete_list.push(aws_file_name)\n # And only increment the aws index variable.\n aws_i += 1\n end\n end\n\n # If we're not at the end of the local file list, we need to add any new files\n # to the new list.\n while (lcl_i < lcl_len)\n new_list.push(local_file_list[lcl_i][0])\n lcl_i += 1; progress.inc\n end\n\n # If we're not at the end of the aws object list, we need to add those file to\n # the delete list.\n while (aws_i < aws_len)\n delete_list.push(aws_file_list[aws_i][0])\n aws_i += 1\n end\n progress.finish\n\n upload_list = updated_list + new_list\n\n puts(\" Hash Check complete\")\n puts(\" #{new_list.length} new files, and #{updated_list.length} updated..\")\n puts(\" #{upload_list.length} files need to be uploaded to the remote\")\n puts(\" #{delete_list.length} files need to be deleted from the remote\")\n current_time = Time.now.getutc.to_s.gsub(\" \",\"_\")\n File.open(\"new_file_list-#{current_time}.txt\", \"w+\") do |f|\n f.puts(new_list)\n end\n File.open(\"updated_file_list-#{current_time}.txt\", \"w+\") do |f|\n f.puts(upload_list)\n end\n File.open(\"deleted_list-#{current_time}.txt\", \"w+\") do |f|\n f.puts(delete_list)\n end\n\n\n # Upload the files in the upload updated and new lists, and delete the files\n # in the delete list.\n if (upload_list.length > 0)\n puts(\" Uploading files...\")\n progress = ProgressBar.new(\" Uploads\", upload_list.length)\n upload_list.each { |obj_path|\n #TODO: Generate a log of the uploaded files?\n #TODO: Error checking.\n #TODO: Stop publishing read/write.\n aws_bucket.put_object({\n acl: \"public-read-write\",\n key: obj_path,\n body: File.open(obj_path)\n })\n progress.inc\n }\n progress.finish\n else\n puts(\" No files to upload...\")\n end\n\n if (delete_list.length > 0)\n delete_list.each_slice(1000).with_index do |slice, index|\n index_from = index * 1000\n index_to = ((index+1)*1000) < delete_list.length ? ((index+1)*1000) : delete_list.length\n puts(\" Requesting Batch Delete for objects #{index_from}-#{index_to}...\")\n # Generate a Aws::S3::Types::Delete hash object.\n delete_hash = {\n delete: {\n objects: slice.map{ |f| { key: f } },\n quiet: false\n }\n }\n #TODO: Generate a log of the deleted files?\n begin\n response = aws_bucket.delete_objects(delete_hash)\n rescue Exception => e\n require 'pp'\n Kernel.abort(\"ERRROR: Batch Deletion returned with errors.\\n\"\\\n \" Delete Hash Object:\\n\"\\\n \"#{pp(delete_hash)}\\n\"\\\n \" Error message:\\n\"\\\n \"#{e.message}\")\n end\n if (response.errors.length > 0)\n require 'pp'\n Kernel.abort(\"ERRROR: Batch Deletion returned with errors\\n\"\\\n \" Delete Hash Object:\\n\"\\\n \"#{pp(delete_hash)}\\n\"\\\n \" Response Object:\\n\"\\\n \"#{pp(response)}\")\n end\n end\n else\n puts(\" No files to delete...\")\n end\n\n # Fetch and rewrite the S3 Routing Rules to make sure the 'latest' of every\n # project correctly re-route.\n puts(\" Configuring S3 Bucket Website redirect rules...\")\n\n # Open an S3 connection to the Bucket Website metadata\n aws_bucket_website = Aws::S3::BucketWebsite.new(ENV['AWS_S3_BUCKET'], {\n :region => \"us-east-1\",\n :access_key_id => ENV['AWS_ACCESS_KEY_ID'],\n :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'],\n })\n\n # Build the routing rules based on the config.yaml's 'project_descripts'. One\n # routing rule per project.\n routing_rules = []\n config_file['params']['project_descriptions'].each do |project, description|\n path = description['path']\n archived_path = description['archived_path']\n ver = description['latest']\n routing_rules.push(\n {\n :condition => { :key_prefix_equals => \"#{archived_path}/latest/\" },\n :redirect => { :replace_key_prefix_with => \"#{path}/#{ver}/\",\n :host_name => ENV['AWS_HOST_NAME'] }\n }\n )\n routing_rules.push(\n {\n :condition => { :key_prefix_equals => \"#{archived_path}/latest\" },\n :redirect => { :replace_key_prefix_with => \"#{path}/#{ver}/\",\n :host_name => ENV['AWS_HOST_NAME'] }\n }\n )\n routing_rules.push(\n {\n :condition => { :key_prefix_equals => \"#{path}/latest/\" },\n :redirect => { :replace_key_prefix_with => \"#{path}/#{ver}/\",\n :host_name => ENV['AWS_HOST_NAME'] }\n }\n )\n routing_rules.push(\n {\n :condition => { :key_prefix_equals => \"#{path}/latest\" },\n :redirect => { :replace_key_prefix_with => \"#{path}/#{ver}/\",\n :host_name => ENV['AWS_HOST_NAME'] }\n }\n )\n end\n #TODO: We need to implement some way of adding arbitrary routing rules. Maybe\n # add a section in config.yaml that's just a JSON string that we parse?\n riak_path = config_file['params']['project_descriptions']['riak_kv']['path']\n riak_ver = config_file['params']['project_descriptions']['riak_kv']['latest']\n routing_rules.push(\n {\n :condition => { :key_prefix_equals => \"riakee/latest/\" },\n :redirect => { :replace_key_prefix_with => \"#{riak_path}/#{riak_ver}/\",\n :host_name => ENV['AWS_HOST_NAME'] }\n }\n )\n routing_rules.push(\n {\n :condition => { :key_prefix_equals => \"riakee/latest\" },\n :redirect => { :replace_key_prefix_with => \"#{riak_path}/#{riak_ver}\",\n :host_name => ENV['AWS_HOST_NAME'] }\n }\n )\n routing_rules.push(\n {\n :condition => { :key_prefix_equals => \"riakts/\" },\n :redirect => { :replace_key_prefix_with => \"riak/ts/\",\n :host_name => ENV['AWS_HOST_NAME'] }\n }\n )\n\n new_website_configuration = {\n :error_document => {:key => \"404.html\"},\n :index_document => aws_bucket_website.index_document.to_hash,\n :routing_rules => routing_rules\n }\n\n aws_bucket_website.put({ website_configuration: new_website_configuration })\n\n # Invalidate any files that were deleted or modified.\n cf_client = SimpleCloudfrontInvalidator::CloudfrontClient.new(\n ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY'],\n ENV['AWS_CLOUDFRONT_DIST_ID'])\n invalidation_list = updated_list + delete_list\n if (invalidation_list.length == 0)\n puts(\" No files to invalidate...\")\n elsif (invalidation_list.length < 500)\n # The invalidation list is sufficiently short that we can invalidate each\n # individual file\n invalidation_list.each_slice(100).with_index do |slice, index|\n index_from = (index*100)\n index_to = ((index+1)*100) < delete_list.length ? ((index+1)*100) : delete_list.length\n puts(\" Sending Invalidation Request for objects #{index_from}-#{index_to}...\")\n cf_report = cf_client.invalidate(slice)\n end\n else\n # The invalidation list is large enough that we should skip getting charged\n # and invalidate the entire site.\n puts(\" Sending Invalidation Request for the entire site (\\\"/*\\\")...\")\n cf_report = cf_client.invalidate(['/*'])\n end\n\n puts(\"\")\n puts(\"Deploy Process Complete!\")\n puts(\"========================================\")\nend",
"def create_deployment\n @api.account_id = @options[:src]\n inputs = format_inputs(@old_deployment.show.inputs)\n\n params = {\n :deployment => {\n :name => @old_deployment.name,\n :description => @old_deployment.description\n }\n }\n\n puts \"\\nCreating deployment: \\\"#{params[:deployment][:name]}\\\" in account: #{@options[:dst]} ...\\n\\n\"\n\n @api.account_id = @options[:dst]\n result = @api.deployments.create(params)\n @new_deployment = result.href\n\n # Set deployment level inputs. Cannot set them at create time, so do it now\n deployment = @api.resource(@new_deployment)\n deployment_inputs = {}\n deployment_inputs[:inputs] = inputs\n deployment.inputs.multi_update(deployment_inputs)\nend",
"def deploy_in_background!\n notify_hipchat_on_execute\n unless Rails.env.test?\n Rails.logger.info \"Calling other ruby process in the background in order to deploy deployment #{self.id} (stage #{self.stage.id}/#{self.stage.name})\"\n\n system <<\"EOS\"\ncd #{Rails.root} && rails runner -e #{Rails.env} 'deployment = Deployment.find(#{self.id}); deployment.prompt_config = #{self.prompt_config.inspect.gsub('\"', '\\\"')} ; Webistrano::Deployer.new(deployment).invoke_task! ' >> #{Rails.root}/log/#{Rails.env}.log 2>&1 &\nEOS\n end\n end",
"def deploy!(options={})\n params = {}\n params['api_key'] = @api_key\n params['deploy[rails_env]'] = options[:framework_env] || 'development'\n params['deploy[local_username]'] = options[:username] || %x(whoami).strip\n params['deploy[scm_repository]'] = options[:scm_repository]\n params['deploy[scm_revision]'] = options[:scm_revision]\n response(@deploy_url, params)\n end",
"def perform(user_id, github_repo, github_deployment_id)\n # get the slashdeploy User object.\n user = User.find(user_id)\n\n # get the Github Deployment by id.\n github_deployment = SlashDeploy.service.github.get_deployment(user, github_repo, github_deployment_id)\n\n # get the latest Github Deployment Status.\n deployment_status = SlashDeploy.service.github.last_deployment_status(user, github_deployment.url)\n\n # if the lastest deployment_status is success exit happily without notifying user.\n return logger.debug \"The Github Deployment #{github_deployment.id} has at least one status, nothing to do.\" if deployment_status\n\n logger.info \"The Github Deployment #{github_deployment.id} of #{github_deployment.repository} @ #{github_deployment.sha} or #{github_deployment.ref} to *#{github_deployment.environment}* did _not_ start. For more details, please read: https://slashdeploy.io/docs#error-1\"\n\n # fetch the user's slack_account related to this deployments Github Org.\n slack_account = user.slack_account_for_github_organization(github_deployment.organization)\n\n SlashDeploy.service.direct_message(\n slack_account,\n GithubNoDeploymentStatusMessage,\n github_deployment: github_deployment,\n account: slack_account\n )\n end",
"def ecs_deploy(id, &block)\n service = Aws::Ecs.services(ecs_cluster_name, [resource(id)]).first\n taskdef = get_taskdef(service)\n\n ## convert to a hash and modify in block\n hash = taskdef_to_hash(taskdef)\n yield(hash) if block_given?\n\n taskdef = register_taskdef(hash)\n update_service(service, taskdef)\n end",
"def create\n deploy\n end",
"def deploy\n unless ITEMS[:project].has_value? SETTINGS[:project]\n raise \"Invalid project: #{SETTINGS[:project]}.\"\n end\n\n # Call the original deploy method.\n orig_deploy\n end",
"def provision_aks(name, config)\n # @step: define the resource group\n resource_group_name = name\n\n # @step: check the resource group exists\n if resource_group?(resource_group_name)\n info \"skipping the resource group creation: #{resource_group_name}, already exists\"\n else\n info \"creating the resource group: #{resource_group_name} in azure\"\n params = ::Azure::Resources::Mgmt::V2019_05_10::Models::ResourceGroup.new.tap do |x|\n x.location = @region\n end\n # ensure the resource group is created\n @client.resource_groups.create_or_update(resource_group_name, params)\n\n # wait for the resource group to be created\n wait(max_retries: 20, interval: 10) do\n resource_group?(resource_group_name)\n end\n end\n\n info \"provisioning the azure deployment manifest: '#{name}', resource group: '#{resource_group_name}'\"\n # @step: generate the ARM deployments\n template = YAML.safe_load(cluster_template(config))\n\n # @step: check if a deployment is already underway and wait for completion - which\n # makes it eaisier to rerun quickly\n if deployment?(resource_group_name, name)\n info \"deployment: #{name}, resource group: #{resource_group_name} already underway, waiting for completion\"\n wait(interval: 30, max_retries: 20) do\n if deployment?(resource_group_name, name)\n d = deployment(resource_group_name, name)\n d.properties.provisioning_state == 'Succeeded'\n end\n end\n end\n\n # @step: kick off the deployment and cross fingers\n deployment = ::Azure::Resources::Mgmt::V2019_05_10::Models::Deployment.new\n deployment.properties = ::Azure::Resources::Mgmt::V2019_05_10::Models::DeploymentProperties.new\n deployment.properties.template = template\n deployment.properties.mode = ::Azure::Resources::Mgmt::V2019_05_10::Models::DeploymentMode::Incremental\n\n # put the deployment to the resource group\n @client.deployments.create_or_update_async(resource_group_name, name, deployment)\n # wait for the deployment to finish\n wait(interval: 30, max_retries: 20) do\n if deployment?(resource_group_name, name)\n d = deployment(resource_group_name, name)\n d.properties.provisioning_state == 'Succeeded'\n end\n end\n end",
"def deploy_heroku(name, app_url)\n deploy_loader = loader(\"Deploying and running installation of app...\", nil)\n branch_name = \"#{name}#{Time.now.strftime(\"%d-%m-%Y-%H-%M\")}\"\n url = get_stripped_url(app_url, false)\n stripped_url = get_stripped_url(app_url, true)\n @cmd.run(\"rm -rf .git\")\n @cmd.run(\"git init\")\n @cmd.run(\"heroku git:remote -a #{name}\")\n @cmd.run(\"heroku config:set SECRET_KEY_BASE=$(rake secret)\") rescue TTY::Command::ExitError\n @cmd.run(\"heroku config:set APP_URL=#{url}\") rescue TTY::Command::ExitError\n @cmd.run(\"heroku config:set APP_STRIPPED_URL=#{stripped_url}\") rescue TTY::Command::ExitError\n unless @cmd.run(\"heroku addons\").out.include? \"heroku-redis\"\n begin\n @cmd.run(\"heroku addons:create heroku-redis:hobby-dev\")\n rescue TTY::Command::ExitError\n error_box(\"App #{name} failed. Please ensure that you are on the Hobby Dev payment tier or above.\")\n raise ArgumentError\n end\n end\n unless @cmd.run(\"heroku domains -a #{name}\").out.include? stripped_url\n begin\n @cmd.run(\"heroku domains:add #{stripped_url} -a #{name}\")\n rescue TTY::Command::ExitError\n error_box(\"Setting custom URL #{stripped_url} failed.\")\n raise ArgumentError\n end\n end\n unless @cmd.run(\"heroku buildpacks -a #{name}\").out.include? \"apt\"\n begin\n @cmd.run(\"heroku buildpacks:add --index 1 https://github.com/heroku/heroku-buildpack-apt.git -a #{name}\")\n @cmd.run(\"heroku buildpacks:add --index 2 heroku/ruby -a #{name}\")\n @cmd.run(\"heroku config:set GI_TYPELIB_PATH=/app/.apt/usr/lib/x86_64-linux-gnu/girepository-1.0\") rescue TTY::Command::ExitError\n rescue TTY::Command::ExitError\n error_box(\"Setting buildpacks failed.\")\n raise ArgumentError\n end\n end\n\n @cmd.run(\"git config --global core.autocrlf true\")\n @cmd.run(\"git checkout -b #{branch_name}\")\n @cmd.run(\"git add .\")\n @cmd.run(\"git add -f config\")\n @cmd.run(\"git commit -m '#{name}'\")\n @cmd.run(\"git push -f heroku #{branch_name}:main\")\n deploy_loader.stop\n stripped_url\nend",
"def run_deploys(deployments, app_name, app_data)\n did_we_deploy = false\n\n deployments.each do |application, deploy|\n\n if application != app_name\n debug_log(\"#{application} skipped: #{app_name}\")\n next\n end\n\n layer_name = app_data['layer']\n next unless allow_deploy(application, app_name, layer_name)\n\n debug_log('Deployment started')\n debug_log(\"Deploying as user: #{deploy['user']} and #{deploy['group']}\")\n\n easybib_deploy application do\n deploy_data deploy\n end\n\n did_we_deploy = true\n\n nginx_config = app_data.fetch('nginx', nil)\n next if nginx_config.nil? # no nginx\n\n config_template = get_template(nginx_config)\n next if config_template.nil? # no nginx\n\n config_cookbook = get_cookbook(nginx_config)\n\n listen_opts = get_additional('listen_opts', app_data)\n\n easybib_nginx application do\n cookbook config_cookbook\n config_template config_template\n domain_name deploy['domains'].join(' ')\n doc_root deploy['document_root']\n htpasswd \"#{deploy['deploy_to']}/current/htpasswd\"\n listen_opts listen_opts\n notifies :reload, 'service[nginx]', :delayed\n notifies node['php-fpm']['restart-action'], 'service[php-fpm]', :delayed\n end\n end\n\n did_we_deploy\nend",
"def deploy_in_background! \n unless RAILS_ENV == 'test' \n RAILS_DEFAULT_LOGGER.info \"Calling other ruby process in the background in order to deploy deployment #{self.id} (stage #{self.stage.id}/#{self.stage.name})\"\n system(\"sh -c \\\"cd #{RAILS_ROOT} && ruby script/runner -e #{RAILS_ENV} ' deployment = Deployment.find(#{self.id}); deployment.prompt_config = #{self.prompt_config.inspect.gsub('\"', '\\\"')} ; Webistrano::Deployer.new(deployment).invoke_task! ' >> #{RAILS_ROOT}/log/#{RAILS_ENV}.log 2>&1\\\" &\")\n end\n end",
"def deploy_in_background! \n unless Rails.env.test?\n Rails.logger.info \"Calling other ruby process in the background in order to deploy deployment #{self.id} (stage #{self.stage.id}/#{self.stage.name})\"\n\n system(\"sh -c \\\"cd #{Rails.root} && rails runner -e #{Rails.env} ' deployment = Deployment.find(#{self.id}); deployment.prompt_config = #{self.prompt_config.inspect.gsub('\"', '\\\"')} ; Webistrano::Deployer.new(deployment).invoke_task! ' >> #{Rails.root}/log/#{Rails.env}.log 2>&1\\\" &\")\n end\n end",
"def index\n branch = shift_argument || 'master'\n validate_arguments!\n\n Heroku::Auth.check\n\n unless remotes = git_remotes\n error('No Heroku remotes detected.'.red)\n end\n\n unless remote = remotes.key(app)\n error(\"Remote for #{app} was not found.\".red)\n end\n\n begin\n pack = Pack.detect.new(app, remote, options)\n pack.deploy!(branch)\n display('Deployment successful.'.green)\n rescue Pack::NotFound\n error('No suitable deploy pack found.'.red)\n rescue Pack::AmbiguousApp\n error('Ambiguous application, multiple deploy packs apply.'.red)\n rescue CommandExecutionFailure\n error('Deployment aborted.'.red.blink)\n end\n end",
"def deploy(environment_options, client, region = 'AWS_REGION')\r\n super\r\n puts \"Deploying API: #{@api_name} to Environment: #{environment_options.name}\"\r\n @stage_variables = environment_options.variables || {}\r\n @stage_variables.store('environment', environment_options.name)\r\n\r\n api_id = get_id_for_api(@api_name)\r\n service_response =\r\n if api_id\r\n options = {\r\n fail_on_warnings: false, mode: @import_mode, rest_api_id:\r\n api_id, body: File.binread(@path_to_swagger_file)\r\n }\r\n @client.put_rest_api(options)\r\n else\r\n options = {\r\n fail_on_warnings: false,\r\n body: File.binread(@path_to_swagger_file)\r\n }\r\n @client.import_rest_api(options)\r\n end\r\n\r\n raise \"Failed to create API gateway with name #{@api_name}\" if service_response.nil? || service_response.id.nil?\r\n\r\n if api_id\r\n \"Created API Gateway Object: #{@api_name} having id #{service_response.id}\"\r\n else\r\n \"Updated API Gateway Object: #{@api_name} having id #{service_response.id}\"\r\n end\r\n\r\n create_stage(service_response.id, environment_options)\r\n\r\n service_uri = \"https://#{service_response.id}.execute-api.#{@region}.amazonaws.com/#{environment_options.name}/\"\r\n\r\n puts \"API: #{@api_name} deployed at #{service_uri}\"\r\n\r\n service_uri\r\n end",
"def _deploy(zip_file, options={})\n request :deploy do |soap|\n soap.body = { :zip_file => zip_file, :deploy_options => options }\n end\n end",
"def deploy\n params = {\n :migrate => migrate,\n :ref => ref,\n }\n params[:serverside_version] = serverside_version if serverside_version\n params[:migrate_command] = migrate_command if migrate\n update_with_response api.post(collection_uri + \"/deploy\", 'deployment' => params)\n end",
"def create\n @deployment = Deployment.new\n \n respond_to do |format|\n if populate_deployment_and_fire\n \n @deployment.deploy_in_background!\n\n format.html { redirect_to project_stage_deployment_url(@project, @stage, @deployment)}\n format.xml { head :created, :location => project_stage_deployment_url(@project, @stage, @deployment) }\n else\n @deployment.clear_lock_error\n format.html { render :action => \"new\" }\n format.xml { render :xml => @deployment.errors.to_xml }\n end\n end\n end",
"def find_or_create(name)\n @log.info \"Looking for deployment: '#{name}'...\"\n deployment = @api_shim.find_deployment_by_name(name)\n @log.info \"Deployment #{deployment.nil? ? \"not found\" : \"found\"}.\"\n unless deployment\n deployment = @api_shim.create_deployment(name)\n @log.info \"Deployment created: '#{name}'\"\n end\n deployment\n end",
"def shutdown\n requires :id\n begin\n response = service.post_shutdown_vapp(id)\n rescue Fog::VcloudDirector::Compute::BadRequest => ex\n Fog::Logger.debug(ex.message)\n return false\n end\n service.process_task(response.body)\n end",
"def deploy(id, host, remote_dfile, not_used)\n\n local_dfile = get_local_deployment_file(remote_dfile)\n\n if !local_dfile || File.zero?(local_dfile)\n send_message(ACTION[:deploy],RESULT[:failure],id,\n \"Can not open deployment file #{local_dfile}\")\n return\n end\n\n tmp = File.new(local_dfile)\n domain = tmp.read\n tmp.close()\n\n images_path = File.dirname remote_dfile\n cmd = \"mkdir -p #{images_path} && cat > #{remote_dfile} && \" \\\n \"#{LIBVIRT[:create]} #{remote_dfile}\"\n\n deploy_exe = SSHCommand.run(\"'#{cmd}'\", host, log_method(id), domain)\n\n if deploy_exe.code != 0\n send_message(ACTION[:deploy],RESULT[:failure],id)\n elsif deploy_exe.stdout.match(/^Domain (.*) created from .*$/)\n send_message(ACTION[:deploy],RESULT[:success],id,$1)\n else\n send_message(ACTION[:deploy],RESULT[:failure],id,\n \"Domain id not found in #{LIBVIRT[:create]} output.\")\n end\n end",
"def deploy()\n release = create_release_name()\n\n write_deploy_version_file()\n\n DirectorySync.sync(server, from_dir, cache_dir, server[:deployer])\n copy_cache_dir_to_release(release)\n\n symlink_shared_directories(release)\n\n send_scripts()\n run_script(:before, release)\n symlink_release_dir(release)\n run_script(:after, release)\n end",
"def restore(deploy_id)\n ec2_action(deploy_id, :start)\n wait_state('running', deploy_id)\n end",
"def deploy(attrs)\n Deployment.deploy(api, self, attrs)\n end",
"def deploy!\n write_previous_revision\n update_repository\n write_revision\n end",
"def run_deployment_job(options={})\n timeout = options.delete(:timeout) || 5 * 60\n method = options.delete(:method) || raise(ArgumentError, \"Missing required method option\")\n raise(ArgumentError, \"Invalid method option\") unless respond_to?(method)\n\n # LC must be ready for deployment jobs to succeed\n poll_for_lc_ready\n\n logger.info(\"Creating %s deployment job with ISO %s on %s\" % [method, options[:image_name], host])\n resp = send(method, options)\n logger.info(\"Initiated %s job %s on %s\" % [method, resp[:job], host])\n resp = poll_deployment_job(resp[:job], :timeout => timeout)\n logger.info(\"%s succeeded with ISO %s on %s: %s\" % [method, options[:image_name], host, Parser.response_string(resp)])\n nil\n end",
"def deploy\n what = ARGV.shift\n\n case what\n when 'packages'\n deploy_packages\n else\n ARGV.unshift what\n original_deploy\n end\n end",
"def create_deployment_manifest\n cloud_properties = {\n \"instance_type\" => \"m1.small\",\n }\n cloud_properties[\"persistent_disk\"] = flags[:disk] if flags[:disk]\n cloud_properties[\"static_ips\"] = ip_addresses\n director_uuid = Bosh::Gen::Models::BoshConfig.new.target_uuid\n manifest = Bosh::Gen::Models::DeploymentManifest.new(\n name, director_uuid,\n release_properties, cloud_properties, default_properties)\n manifest.jobs = job_manifests\n create_file manifest_file_name, manifest.to_yaml, :force => flags[:force]\n end",
"def stop_deploy(stack, stage)\n if deployname = get_deploy_process_title(stack,stage)\n return system(\"pkill -f '#{deployname}'\")\n end\n false\n end",
"def create_deployment_manifest\n cloud_properties = { \"instance_type\" => \"m1.small\", \"availability_zone\" => \"us-east-1e\" }\n cloud_properties[\"persistent_disk\"] = flags[:disk] if flags[:disk]\n cloud_properties[\"static_ips\"] = ip_addresses\n manifest = Bosh::Gen::Models::DeploymentManifest.new(name, director_uuid, release_properties, cloud_properties)\n manifest.jobs = job_manifests\n create_file manifest_file_name, manifest.to_yaml, :force => flags[:force]\n end",
"def deployment_exists?(name)\n exists?(\"deployment\", name)\n end",
"def deploy(sites, env, action=\"deploy\")\n\t\t# Detect if we need to go into maintenance mode\n\t\tmaintenance_flag = maintenance?()\n\n\t\tif maintenance_flag\n\t\t\tvalidate_execution(maintenance('on', @maintenance_list, env))\n\t\tend\n\n\t\t#Deploy...\n\t\tsites.each do |site| \n\t\t\tvalidate_execution(cap_deploy(site, env, maintenance_flag, action))\n\t end\n\n\t # Go out from maintenance if needed\n\t\tif maintenance_flag\n\t\t\tvalidate_execution(maintenance('off', @maintenance_list, env))\n\t\tend\n\n\tend",
"def cap_deploy(site, env, maintenance_flag, action=\"deploy\")\n\t\tif action == \"deploy\"\n\t\t\ts3object = @options[:s3object] || \"\"\n\t\t\tprint_disclaimer(\"call cap #{env} #{site}\")\n\t\t\tsystem \"cap #{env} #{site} BEAVER_S3_OBJECT_PATH=#{s3object}\"\n\t\telsif action == \"rollback\"\n\t\t\tprint_disclaimer(\"call cap #{env} #{site}:#{action}\")\n\t\t\tsystem \"cap #{env} #{site}:#{action}\"\n\t\tend\n\tend",
"def update(deployment)\n GITHUB.create_deployment_status(\n deployment.url,\n state,\n target_url: @deploy.url,\n description: @deploy.summary\n )\n end",
"def deploy()\n return Error.new('ID not defined') unless @id\n \n node_types().each do |node_type|\n node_type.set_action(\"DEPLOY\")\n end\n end",
"def call( env )\n\n if env[ 'options.confirm' ] && !confirm?( env[ 'remote' ], env[ 'branch' ] )\n raise Interrupt, 'Use cancelled the deployment.'\n end\n\n @app.call env\n end",
"def suspend\n requires :id\n begin\n response = service.post_suspend_vapp(id)\n rescue Fog::VcloudDirector::Compute::BadRequest => ex\n Fog::Logger.debug(ex.message)\n return false\n end\n service.process_task(response.body)\n end",
"def apply_step\n # Create deploy directories\n cap 'deploy:setup'\n # Deploy the configured step\n $?.success? ? (cap 'deploy') : (return $?)\n # Download dynamic step modules through librarian-puppet\n $?.success? ? (cap 'puppet:bundle_modules') : (return $?)\n # Install the step provision through puppet\n $?.success? ? (cap 'puppet:apply') : (return $?)\n $?\n end",
"def deploy(&block)\n in_directory do\n self.setup!\n self.push_with_retry!\n block.call(self, platform_api, output) if block_given?\n end\n ensure\n self.teardown!\n end",
"def run!(configuration:, deployment_policy:)\n containers = find_containers_to_deploy(configuration, deployment_policy)\n\n cloner = Indocker::Repositories::Cloner.new(configuration, @logger)\n build_server_pool = Indocker::ServerPools::BuildServerPool.new(configuration: configuration, logger: @logger)\n deployer = Indocker::ContainerDeployer.new(configuration: configuration, logger: @logger)\n\n @global_logger.info(\"Establishing ssh sessions to all servers...\")\n build_server_pool.create_sessions!\n\n build_servers = configuration\n .build_servers\n .uniq { |s| s.host }\n\n deploy_servers = containers\n .map(&:servers)\n .flatten\n .uniq { |s| s.host }\n\n servers = (deploy_servers + build_servers).uniq { |s| s.host }\n\n @progress.setup(\n binaries_servers: servers,\n build_servers: build_servers,\n deploy_servers: deploy_servers,\n env_files: configuration.env_files.keys,\n repositories: configuration.repositories.keys,\n force_restart: deployment_policy.force_restart,\n skip_build: deployment_policy.skip_build,\n skip_deploy: deployment_policy.skip_deploy,\n containers: containers,\n artifact_servers: configuration.artifact_servers,\n )\n\n remote_operations = sync_indocker(servers)\n wait_remote_operations(remote_operations)\n\n remote_operations = sync_env_files(deploy_servers, configuration.env_files)\n wait_remote_operations(remote_operations)\n\n remote_operations = pull_repositories(cloner, build_servers, configuration.repositories)\n wait_remote_operations(remote_operations)\n\n remote_operations = sync_artifacts(cloner, configuration.artifact_servers)\n wait_remote_operations(remote_operations)\n\n update_crontab_redeploy_rules(configuration, build_servers.first)\n\n containers.uniq.each do |container|\n recursively_deploy_container(\n configuration,\n deployer,\n build_server_pool,\n container,\n containers,\n deployment_policy.skip_build,\n deployment_policy.skip_deploy,\n deployment_policy.force_restart,\n deployment_policy.skip_force_restart\n )\n end\n\n Thread\n .list\n .each { |t| t.join if t != Thread.current }\n ensure\n build_server_pool.close_sessions if build_server_pool\n deployer.close_sessions if deployer\n end",
"def report_deployments(gear_env, options = {})\n broker_addr = @config.get('BROKER_HOST')\n domain = gear_env['OPENSHIFT_NAMESPACE']\n app_name = gear_env['OPENSHIFT_APP_NAME']\n app_uuid = gear_env['OPENSHIFT_APP_UUID']\n url = \"https://#{broker_addr}/broker/rest/domain/#{domain}/application/#{app_name}/deployments\"\n\n params = broker_auth_params\n if params\n deployments = calculate_deployments\n deployments.reject! { |d| d[:activations].empty? }\n\n params['deployments[]'] = deployments\n params[:application_id] = app_uuid\n\n begin\n request = RestClient::Request.new(method: :post,\n url: url,\n timeout: 30,\n headers: {accept: 'application/json;version=1.6', user_agent: 'OpenShift'},\n payload: params)\n\n response = request.execute { |response, request, result| response }\n rescue => e\n options[:out].puts \"Failed to report deployment to broker. This will be corrected on the next git push. Message: #{e.message}\" if options[:out]\n else\n if 300 <= response.code\n options[:out].puts \"Failed to report deployment to broker with status #{response.code}. This will be corrected on the next git push.\" if options[:out]\n end\n end\n end\n end",
"def deploy_in_background! (opts={})\n unless Rails.env == 'test'\n logger.info \"Calling other ruby process in the background in order to deploy deployment #{self.id} (stage #{self.stage.id}/#{self.stage.name})\"\n system_command = \"sh -c \\\"cd #{Rails.root} && bundle exec rails runner -e #{Rails.env} ' deployment = Deployment.find(#{self.id}); deployment.prompt_config = #{self.prompt_config.inspect.gsub('\"', '\\\"')} ; Webistrano::Deployer.new(deployment).invoke_task! ' >> #{Rails.root}/log/#{Rails.env}.log 2>&1\\\" &\"\n logger.info \"SYSTEM_COMMAND: #{system_command}\"\n system(system_command)\n\n # Webistrano::Deployer.new(Deployment.find(self.id)).invoke_task!\n end\n end",
"def deploy(server, location, deployment)\r\n IIS.server.deploy(server, location, deployment)\r\n end",
"def filesync_deploy\n @logger.debug('Pem::filesync_deploy') { 'starting filesync deploy' }\n\n ssl_options = {\n 'client_cert' => OpenSSL::X509::Certificate.new(File.read(@conf['filesync_cert'])),\n 'client_key' => OpenSSL::PKey::RSA.new(File.read(@conf['filesync_cert_key'])),\n 'ca_file' => @conf['filesync_ca_cert'],\n }\n\n conn = Faraday.new(url: \"https://#{@conf['master']}:8140\", ssl: ssl_options) do |faraday|\n faraday.request :json\n faraday.options[:timeout] = 300\n faraday.adapter Faraday.default_adapter\n end\n\n @logger.debug('Pem::filesync_deploy') { 'Hitting filesync commit endpoint...' }\n conn.post '/file-sync/v1/commit', 'commit-all' => true\n @logger.debug('Pem::filesync_deploy') { 'Done.' }\n\n @logger.debug('Pem::filesync_deploy') { 'Hitting filesync force-sync endpoint...' }\n conn.post '/file-sync/v1/force-sync'\n @logger.debug('Pem::filesync_deploy') { 'Done.' }\n\n @logger.debug('Pem::filesync_deploy') { 'Hitting puppet-admin-api env endpoint...' }\n conn.delete '/puppet-admin-api/v1/environment-cache'\n @logger.debug('Pem::filesync_deploy') { 'Done.' }\n\n @logger.debug('Pem::filesync_deploy') { 'completed filesync deploy' }\n end",
"def create\n response = get_request(URI.parse(\"http://\"+(sesh :donabe_ip)+\"/\"+(sesh :current_tenant)+\"/containers/\"+params[:containerID].to_s+\"/deploy.json\"), (sesh :current_token))\n json_respond response.body\n end",
"def deploy\n require 'rest_client'\n require 'uri'\n\n if (@role.nil? or !(@role.services_permissions)) and !current_actor.superadmin\n json_response({ message: \"You don't have permission to deploy services in this project\" }, :unauthorized)\n return\n end\n\n # Env variables for Manager host and port\n serviceManagerHost = Settings.service_manager_host\n serviceManagerPort = Settings.service_manager_port.to_s\n serviceManagerURI = 'http://' + serviceManagerHost + ':' + serviceManagerPort + '/v1/stack'\n\n # Service name in query\n serviceName = params[\"service_name\"]\n service = Service.find(params[\"service_id\"])\n if service.nil? then\n return\n end\n\n # Find Service type to retrieve deploy template\n serviceType = ServiceType.find(service.service_type_id)\n serviceTypeName = serviceType.name\n serviceTypeVersion = serviceType.version\n composeData = serviceType.deploy_template\n\n # Getting external files needed by the compose\n externalFiles = []\n if !serviceType.local_path.nil? && serviceType.local_path != ''\n for path in Dir['./' + serviceType.local_path + '/*']\n externalFileName = File.basename(path)\n if (externalFileName != \"docker-compose.yml\" && externalFileName != \"mastermind.yml\" && !externalFileName.end_with?('.md'))\n externalFileContents = File.read(path)\n externalFiles.append({\"#{externalFileName}\" => externalFileContents})\n end\n end\n end\n\n # Making env variable string for Service Manager (YAML format)\n envVariables = \"\"\n begin\n serviceConf = JSON.parse(service.configuration)\n serviceConf.each do |k, v|\n envVariables = envVariables + k + \": \" + v.to_s + \"\\n\"\n end\n rescue JSON::ParserError\n json_response({message: \"Invalid configuration\"}, :unprocessable_entity)\n return\n end\n envVariables = envVariables.chomp(\"\\n\")\n\n # Preparing message for Service Manager\n stack = {\n 'name' => serviceName,\n 'engine-url' => @cluster.endpoint,\n 'compose-file' => composeData,\n 'compose-vars' => envVariables,\n 'external_files' => externalFiles,\n 'ca-cert' => @cluster.ca,\n 'cert' => @cluster.cert,\n 'cert-key' => @cluster.key\n }.to_json\n\n begin\n response = RestClient.post(\n serviceManagerURI,\n stack,\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json'\n )\n puts \"Deploy Response: \" + response\n json_response(response, :created)\n # Update service as Active if successfully deployed\n # TODO: Perhaps make a better check\n service.update({endpoint: URI.parse(@cluster.endpoint).host, status: \"Active\", docker_service_id: serviceName})\n rescue Exception => e\n # If error, return it to the client\n puts e\n json_response({message: e}, :unprocessable_entity)\n end\n end",
"def create_stages(api_id, env, stage_variables)\r\n deployment_description = 'Deployment of service to ' + env\r\n deployment = @client.create_deployment(\r\n rest_api_id: api_id, stage_name: env, cache_cluster_enabled: false, description: deployment_description,\r\n variables: stage_variables\r\n ).data\r\n puts deployment\r\n end",
"def redeploy\n shelly.redeploy(code_name)[\"deployment\"][\"id\"]\n end",
"def deploy(open_vz_data, container)\n OpenNebula.log_debug(\"Deploying vm #{open_vz_data.vmid} using ctid:#{container.ctid}\")\n\n # create symlink to enable ovz to find image\n template_name = container.ctid\n template_cache = create_template template_name, open_vz_data.disk\n\n # options to be passed to vzctl create\n options = process_options open_vz_data.raw, {:ostemplate => template_name}\n\n # create and run container\n container.create( options )\n container.start\n\n # set up networking\n apply_network_settings container, open_vz_data.networking\n\n # and contextualise it\n contextualise container, open_vz_data.context_disk, open_vz_data.context\n \n container.ctid\n rescue RuntimeError => e\n raise OpenVzDriverError, \"Container #{container.ctid} can't be deployed. Details: #{e.message}\"\n ensure\n # cleanup template cache - we don't need it anymore\n File.delete template_cache if template_cache and File.exists? template_cache\n end",
"def reboot\n requires :id\n begin\n response = service.post_reboot_vapp(id)\n rescue Fog::VcloudDirector::Compute::BadRequest => ex\n Fog::Logger.debug(ex.message)\n return false\n end\n service.process_task(response.body)\n end",
"def deploy\n ::Taxi::Status.list_by_status(status: 'deploy', format: options[:format], agency: options[:agency])\n end",
"def reboot(deploy_id)\n ec2_action(deploy_id, :reboot)\n wait_state('running', deploy_id)\n end",
"def execute(message)\n failure_wrap(message) do |payload|\n directory = asset_store.unpack(asset_store.get(payload.get(:data, :stacks, :asset)), workspace(payload))\n begin\n unless(payload.get(:data, :stacks, :template))\n payload.set(:data, :stacks, :template, 'infrastructure')\n end\n unless(payload.get(:data, :stacks, :name))\n payload.set(:data, :stacks, :name, stack_name(payload))\n end\n store_stable_asset(payload, directory)\n begin\n stack = stacks_api.stacks.get(payload.get(:data, :stacks, :name))\n rescue\n stack = nil\n end\n if(stack)\n info \"Stack currently exists. Applying update [#{stack}]\"\n run_stack(payload, directory, :update)\n payload.set(:data, :stacks, :updated, true)\n else\n info \"Stack does not currently exist. Building new stack [#{payload.get(:data, :stacks, :name)}]\"\n init_provider(payload)\n run_stack(payload, directory, :create)\n payload.set(:data, :stacks, :created, true)\n end\n ensure\n FileUtils.rm_rf(directory)\n end\n job_completed(:stacks, payload, message)\n end\n end",
"def deploy()\n connection.nodes.deploy(uuid).tap{ self.forget }\n end",
"def create_stack(response, resource, properties, parameters, message)\n stack = remote_api(properties[:location]).stacks.build(\n :name => generate_stack_name(resource),\n :template => properties.fetch(:stack, fetch_template(properties[:template_url])),\n :parameters => Hash[parameters.map{|k,v| [Bogo::Utility.camel(k), v] }]\n )\n stack.save\n until(stack.state.to_s.end_with?('complete'))\n message.touch!\n debug \"Waiting for created stack to reach completion...\"\n sleep 5\n stack.reload\n end\n if(stack.state.to_s.end_with?('complete') || stack.state.to_s.end_with?('failed'))\n stack.outputs.each do |output|\n response['Data'][\"Outputs.#{output.key}\"] = output.value\n end\n response['PhysicalResourceId'] = [\n properties[:location],\n stack.id\n ].join(LOCATION_JOINER)\n true\n else\n response['Status'] = 'FAILED'\n response['Reason'] = 'Stack creation failed!'\n stack.destroy\n false\n end\n end",
"def deploy(deploy_params, servers)\n params = deploy_params.join(\" \")\n cmd = nil\n if ENV['TPKG_HOME']\n # Preserve TPKG_HOME when deploying to remote systems so that users can\n # perform operations against different tpkg base directories.\n cmd = \"tpkg #{params} --base #{ENV['TPKG_HOME']} -n\"\n else\n cmd = \"tpkg #{params} -n\"\n end\n user = @user\n\n if @user.nil? && !@use_ssh_key\n @user = prompt_username\n end\n\n if @password.nil? && !@use_ssh_key\n @password = prompt_password\n end\n\n tp = ThreadPool.new(@max_worker)\n statuses = {}\n deploy_to = []\n if servers.kind_of?(Proc)\n deploy_to = servers.call\n elsif servers.size == 1 && File.exists?(servers[0])\n puts \"Reading server list from file #{servers[0]}\"\n File.open(servers[0], 'r') do |f|\n while line = f.gets\n deploy_to << line.chomp.split(\",\")\n end\n end\n deploy_to.flatten!\n else\n deploy_to = servers\n end\n\n deploy_to.each do | server |\n tp.process do\n status = ssh_execute(server, @user, @password, @ssh_key, cmd).call\n statuses[server] = status\n end\n end\n tp.shutdown\n puts \"Exit statuses: \"\n puts statuses.inspect\n\n return statuses\n end",
"def postBoot(instance_id = nil)\n @cloud_id ||= instance_id\n _node, _config, deploydata = describe(cloud_id: @cloud_id)\n\n raise MuError, \"Couldn't find instance #{@mu_name} (#{@cloud_id})\" if !cloud_desc\n return false if !MU::MommaCat.lock(@cloud_id+\"-orchestrate\", true)\n return false if !MU::MommaCat.lock(@cloud_id+\"-groom\", true)\n\n getIAMProfile\n\n finish = Proc.new { |status|\n MU::MommaCat.unlock(@cloud_id+\"-orchestrate\")\n MU::MommaCat.unlock(@cloud_id+\"-groom\")\n return status\n }\n\n MU::Cloud::AWS.createStandardTags(\n @cloud_id,\n region: @region,\n credentials: @credentials,\n optional: @config['optional_tags'],\n nametag: @mu_name,\n othertags: @config['tags']\n )\n\n # Make double sure we don't lose a cached mu_windows_name value.\n if (windows? or !@config['active_directory'].nil?)\n @mu_windows_name ||= deploydata['mu_windows_name']\n end\n\n loop_if = Proc.new {\n !cloud_desc(use_cache: false) or cloud_desc.state.name != \"running\"\n }\n MU.retrier([Aws::EC2::Errors::ServiceError], max: 30, wait: 40, loop_if: loop_if) { |retries, _wait|\n if cloud_desc and cloud_desc.state.name == \"terminated\"\n logs = if !@config['basis'].nil?\n pool = @deploy.findLitterMate(type: \"server_pools\", name: @config[\"name\"])\n if pool\n MU::Cloud::AWS.autoscale(region: @region, credentials: @credentials).describe_scaling_activities(auto_scaling_group_name: pool.cloud_id).activities\n else\n nil\n end\n end\n raise MuError.new, \"#{@cloud_id} appears to have been terminated mid-bootstrap!\", details: logs\n end\n if retries % 3 == 0\n MU.log \"Waiting for EC2 instance #{@mu_name} (#{@cloud_id}) to be ready...\", MU::NOTICE\n end\n }\n\n allowBastionAccess\n\n setAlarms\n\n # Unless we're planning on associating a different IP later, set up a\n # DNS entry for this thing and let it sync in the background. We'll come\n # back to it later.\n if @config['static_ip'].nil? and !@named\n MU::MommaCat.nameKitten(self)\n @named = true\n end\n\n if !@config['src_dst_check'] and !@config[\"vpc\"].nil?\n MU.log \"Disabling source_dest_check #{@mu_name} (making it NAT-worthy)\"\n MU::Cloud::AWS.ec2(region: @region, credentials: @credentials).modify_instance_attribute(\n instance_id: @cloud_id,\n source_dest_check: { value: false }\n )\n end\n\n # Set console termination protection. Autoscale nodes won't set this\n # by default.\n MU::Cloud::AWS.ec2(region: @region, credentials: @credentials).modify_instance_attribute(\n instance_id: @cloud_id,\n disable_api_termination: { value: true}\n )\n\n tagVolumes\n configureNetworking\n saveCredentials\n\n if !@config['image_then_destroy']\n notify\n end\n\n finish.call(false) if !bootstrapGroomer\n\n # Make sure we got our name written everywhere applicable\n if !@named\n MU::MommaCat.nameKitten(self)\n @named = true\n end\n\n finish.call(true)\n end",
"def create_virtual_machine(params, options = {})\n image = get_image(params[:image])\n options[:os_type] = image.os_type\n validate_deployment_params(params, options)\n options[:deployment_name] ||= options[:cloud_service_name]\n Azure::Loggerx.info 'Creating deployment...'\n\n options[:cloud_service_name] ||= generate_cloud_service_name(params[:vm_name])\n options[:storage_account_name] ||= generate_storage_account_name(params[:vm_name])\n optionals = {}\n if options[:virtual_network_name]\n virtual_network_service = client.network_management\n virtual_networks = virtual_network_service.list_virtual_networks.select { |x| x.name == options[:virtual_network_name] }\n if virtual_networks.empty?\n Azure::Loggerx.error_with_exit \"Virtual network #{options[:virtual_network_name]} doesn't exists\"\n else\n vnet = virtual_networks.first\n if !vnet.affinity_group.empty?\n options[:affinity_group_name] = vnet.affinity_group\n else\n optionals[:location] = vnet.location\n end\n end\n elsif options[:affinity_group_name]\n optionals[:affinity_group_name] = options[:affinity_group_name]\n else\n optionals[:location] = params[:location]\n end\n cloud_service = client.cloud_service_management\n cloud_service.create_cloud_service(options[:cloud_service_name], optionals)\n cloud_service.upload_certificate(options[:cloud_service_name], params[:certificate]) unless params[:certificate].empty?\n unless image.category == 'User'\n options[:storage_account_name] ||= generate_storage_account_name(params[:vm_name])\n client.storage_management.create_storage_account(options[:storage_account_name], optionals)\n end\n body = Serialization.deployment_to_xml(params, image, options)\n path = \"/services/hostedservices/#{options[:cloud_service_name]}/deployments\"\n Azure::Loggerx.info 'Deployment in progress...'\n request = client.management_request(:post, path, body)\n request.call\n get_virtual_machine(params[:vm_name], options[:cloud_service_name])\n rescue Exception => e\n Azure::Loggerx.error_with_exit \"Failed to create virtual machine : \"+e.message\n end",
"def gen_deploy(deploy_id, slug_url, config)\n require 'erb'\n require 'shellwords'\n template = ERB.new(File.read(File.join(data_dir, 'deploy.bash.erb')))\n template.result(binding)\n end",
"def create(gear, quota_blocks=nil, quota_files=nil, sshkey_required=false, initial_deployment_dir_required=true)\n app = gear.application\n result = nil\n (1..10).each do |i|\n args = build_base_gear_args(gear, quota_blocks, quota_files, sshkey_required)\n\n # set the secret token for new gear creations\n # log an error if the application does not have its secret_token set\n if app.secret_token.present?\n args['--with-secret-token'] = app.secret_token\n else\n Rails.logger.error \"The application #{app.name} (#{app._id.to_s}) does not have its secret token set\"\n end\n\n args['--with-initial-deployment-dir'] = initial_deployment_dir_required\n\n mcoll_reply = execute_direct(@@C_CONTROLLER, 'app-create', args)\n\n begin\n result = parse_result(mcoll_reply, gear)\n rescue OpenShift::OOException => ooex\n # destroy the gear in case of failures\n # the UID will be unreserved up as part of rollback\n destroy(gear, true)\n\n # raise the exception if this is the last retry\n raise ooex if i == 10\n\n result = ooex.resultIO\n if result != nil && result.exitcode == 129 && has_uid_or_gid?(gear.uid) # Code to indicate uid already taken\n gear.uid = reserve_uid\n app.save!\n else\n raise ooex\n end\n else\n break\n end\n end\n result\n end",
"def deployed?\n success =\n @deploy_details[:deploy_name] == self.deploy_name if @deploy_details\n\n return success if success\n\n deploy_details(true)[:deploy_name] == self.deploy_name rescue false\n end",
"def stage_wp_site\n # Note - this assumes that the wordpress files are saved in the repository that\n # the WPDeploy script will look for them in a particular directory\n begin \n if AppConfig.wp_deploy_enabled?\n LOGGER.debug \"Staging original wordpress site for project #{self.label}\"\n wpd = WpDeploy.new(self.label)\n wpd.deploy\n else\n LOGGER.info \"Skipping staging of WordPress site for #{self.label} as wp_deploy is disabled\"\n end\n rescue Exception => e\n LOGGER.error \"Error occurred staging original wordpress site: #{e.message}\"\n end\n end",
"def deploySite\n verifyOS\n timeDate = Time.new\n vConfig(CONFIG['configWebsite'])\n read_json(CONFIG['configWebsite'])\n compileP = @parse_json_config['deploy']['compile']['built']\n branchBuilt = @parse_json_config['deploy']['branch']['built']\n msgCommit = @parse_json_config['deploy']['github']['config']['commit']\n if compileP == \"yes\"\n system_commands(\"rake build\")\n end\n # enter_folder(\"./_site\") # DEPRECATED\n add_repo_git(SITEDIR)\n add_remoteurl(SITEDIR)\n pull_execute(branchBuilt, SITEDIR)\n system_commands(\"echo Deploy source files. Wait ...\")\n git_checkout(branchBuilt, SITEDIR)\n system_commands(\"cd #{SITEDIR}; git add .\")\n system_commands(\"cd #{SITEDIR}; git commit -m \\\"#{msgCommit} - #{timeDate.inspect}\\\"\")\n system_commands(\"cd #{SITEDIR}; git push origin -u #{branchBuilt}\")\n\n end"
] |
[
"0.6109779",
"0.60810125",
"0.60790414",
"0.5944442",
"0.5917404",
"0.57502055",
"0.56585085",
"0.56419224",
"0.5638102",
"0.56327844",
"0.5585359",
"0.55598646",
"0.5558177",
"0.5551345",
"0.549737",
"0.5492338",
"0.5491895",
"0.54425794",
"0.5421702",
"0.54156965",
"0.5346972",
"0.5339159",
"0.53336143",
"0.53242505",
"0.5323694",
"0.53232694",
"0.53160304",
"0.5313411",
"0.5291523",
"0.5275536",
"0.52716184",
"0.52714807",
"0.52458286",
"0.5225947",
"0.5194075",
"0.51715785",
"0.51647294",
"0.5139412",
"0.513153",
"0.5123719",
"0.510477",
"0.5102205",
"0.5094006",
"0.508156",
"0.5076376",
"0.50614345",
"0.503684",
"0.503475",
"0.50303924",
"0.50191146",
"0.50052184",
"0.49840304",
"0.49567932",
"0.4956681",
"0.4946063",
"0.49345407",
"0.49299023",
"0.4894679",
"0.48740026",
"0.48481512",
"0.48307392",
"0.47876224",
"0.47731084",
"0.47635934",
"0.47575426",
"0.4744152",
"0.47346914",
"0.47305283",
"0.470494",
"0.46904927",
"0.46808982",
"0.4671899",
"0.46686688",
"0.46576455",
"0.46315488",
"0.46307483",
"0.46274376",
"0.4622391",
"0.46123362",
"0.46091053",
"0.46062437",
"0.4603668",
"0.4595301",
"0.45952284",
"0.45938987",
"0.4583847",
"0.45832485",
"0.45762712",
"0.45735505",
"0.45623928",
"0.45401436",
"0.45247114",
"0.45203522",
"0.45143133",
"0.45077682",
"0.4498614",
"0.4496026",
"0.4495983",
"0.44858798",
"0.4475389"
] |
0.7538104
|
0
|
Loop through all instances in layer Deregister from ELB (elastic load balancer) Wait connection draining timeout (default up to maximum of 300s) Initiate deploy and run migrations Register instance back to ELB Wait for AWS to confirm the instance as registered and healthy Once complete, move onto the next instance and repeat
|
def regional_rolling_deploy(stack_id:, layer_id:, app_id:, revision: '')
log("Starting opsworks deploy for app #{app_id}\n\n")
instances = @opsworks_client.describe_instances(layer_id: layer_id)[:instances]
instances_by_group = instances.map {|v| v.to_h}.group_by { |d| d[:availability_zone] }
instances_by_group.each do |region, instance_group|
# Only deploy to online instances
online_instance = instance_group.select{|k| k[:status] == 'online'}
instances_ids = online_instance.map{|k| k[:instance_id]}
instances_names = online_instance.map{|k| k[:hostname]}
next if instances_names.empty?
puts "#{instances_names} in #{region}"
begin
load_balancers = {}
log("=== Starting deploy for #{instances_names} ===")
online_instance.each do |instance|
instance = Aws::OpsWorks::Types::Instance.new(instance)
load_balancers[instance.instance_id] = detach_from_elbs(instance: instance)
end
wait_for_detach(@lb_wait_params)
deploy(
stack_id: stack_id,
app_id: app_id,
instance_id: instances_ids,
revision: revision
)
ensure
online_instance.each do |instance|
instance = Aws::OpsWorks::Types::Instance.new(instance)
attach_to_elbs(instance: instance, load_balancers: load_balancers[instance.instance_id]) if load_balancers[instance.instance_id]
end
wait_for_re_attach(@lb_wait_params)
log("=== Done deploying on #{instances_names} ===\n\n")
end
end
log("SUCCESS: completed opsworks deploy for all instances on app #{app_id}")
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def cleanup(vpc_id, client, asg, elbv1, elbv2, region)\n begin\n response = client.describe_vpcs(vpc_ids: [vpc_id])\n rescue Aws::EC2::Errors::InvalidVpcIDNotFound => e\n puts \"Error: vpc_id [#{vpc_id}] does not exist... exiting.\"\n puts \"Make sure you passed the correct region on the command-line if it's not in the default us-west-2\"\n exit 0\n end\n\n # 1) Delete Auto Scaling group\n begin\n asg.delete_auto_scaling_group(auto_scaling_group_name: 'asg-nginx_auto', force_delete: true)\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n\n sleep 2\n # TODO: properly wait here until ASG is fully deleted before proceeding...\n begin\n asg.delete_launch_configuration(launch_configuration_name: 'lc-nginx_auto')\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n sleep 2\n\n # 2) instance handling\n term_error = 0\n instances_to_term = []\n terminate_states = %w[pending running shutting-down stopping stopped]\n puts 'Checking for nginx and nat instances, of all states...'\n begin\n response = client.describe_instances(filters: [{name: 'tag:Name', values: ['autoASG nginx server',\n 'nat instance']}])\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n response.reservations.each do |reservation|\n reservation.instances.each do |instance|\n puts \"Check #1: instance-id=[#{instance.instance_id}] AMI=[#{instance.image_id}] state=[#{instance.state.name}]\"\n instances_to_term.push(instance.instance_id) if terminate_states.include? instance.state.name\n end\n end\n\n if instances_to_term.any? # If array has content, proceed.\n term_error = 0\n instance_cnt = instances_to_term.length # TODO: Check before/after termination attempts and ensure = 0\n before_terminate = Time.now\n begin\n client.wait_until(:instance_terminated,instance_ids: instances_to_term) do |wait|\n wait.interval = 8 # Seconds between polling attempts. Same as wait.delay\n wait.max_attempts = 15 # Polling attempts before giving up. Wait time is 15*8=120 seconds.\n puts \"Attempting to terminate [#{instance_cnt}] instance(s), please wait up to 120 seconds...\"\n begin\n client.terminate_instances(instance_ids: instances_to_term)\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n end\n rescue Aws::Waiters::Errors::WaiterFailed => error\n term_error = 1 # TODO: Do something more reliable if this ever occurs.\n puts \"Exception: failed waiting for instance running: #{error.message}\"\n end\n puts \"#{Time.now - before_terminate.to_time} seconds elapsed while terminating.\" if term_error.zero?\n end\n\n if term_error.zero?\n # Debug with final instance check... this shouldn't print anything aside from terminated instances.\n begin\n response = client.describe_instances(filters: [{name: 'tag:Name', values: ['autoASG nginx server',\n 'nat instance']}])\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n response.reservations.each do |reservation|\n reservation.instances.each do |instance|\n puts \"Check #2: instance-id=[#{instance.instance_id}] AMI=[#{instance.image_id}] state=[#{instance.state.name}]\"\n end\n end\n end\n\n puts 'Sleeping for 5 seconds...'\n sleep 5\n\n # 3) Delete listeners\n printf 'Deleting ALB listeners... '\n begin\n response = elbv2.describe_load_balancers(names: ['AutoALB'])\n alb_arn = response.load_balancers[0].load_balancer_arn\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n sleep 2\n begin\n response = elbv2.describe_listeners(load_balancer_arn: alb_arn)\n listener_arn = response.listeners[0].listener_arn\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n begin\n elbv2.delete_listener(listener_arn: listener_arn)\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n sleep 2\n puts 'done.'\n\n # 4) Delete target groups\n printf 'Deleting ALB target groups... '\n begin\n response = elbv2.describe_target_groups(names: ['AutoALBTargetGroup'])\n target_group_arn = response.target_groups[0].target_group_arn\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n begin\n elbv2.delete_target_group(target_group_arn: target_group_arn)\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n sleep 5\n puts 'done.'\n\n # 5) Delete load balancers\n printf 'Deleting application and classic load balancers... '\n begin\n elbv1.delete_load_balancer(load_balancer_name: 'AutoCLB')\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n begin\n elbv2.delete_load_balancer(load_balancer_arn: alb_arn)\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n puts 'done.'\n\n puts 'Sleeping for 120 seconds, enough time for the ASG to fully disappear before deleting subnets.'\n sleep 120\n\n # 6) subnets\n begin\n response = client.describe_subnets(filters: [{name: 'vpc-id', values: [vpc_id]}])\n response.subnets.each do |sn|\n printf \"Removing subnet: #{sn.subnet_id}, #{sn.vpc_id}, #{sn.cidr_block}, #{sn.availability_zone}; \"\n client.delete_subnet(subnet_id: sn.subnet_id)\n puts 'Done.'\n end\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n\n # 7) security groups\n begin\n response = client.describe_security_groups(filters: [{name: 'vpc-id', values: [vpc_id]}])\n response.security_groups.each do |sg|\n next if sg.group_name == 'default' # This name is reserved by aws and cannot be removed.\n printf \"Removing security group: #{sg.group_id}, #{sg.vpc_id}, #{sg.group_name}, Desc='#{sg.description}'; \"\n client.delete_security_group(group_id: sg.group_id)\n puts 'Done.'\n end\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n\n # 8) Internet gateway\n begin\n response = client.describe_internet_gateways(filters: [{name: 'attachment.vpc-id', values: [vpc_id]}])\n response.internet_gateways.each do |igw|\n printf \"Detaching Internet gateway: #{igw.internet_gateway_id} <-> #{igw.attachments[0].vpc_id}; \"\n client.detach_internet_gateway(internet_gateway_id: igw.internet_gateway_id, vpc_id: igw.attachments[0].vpc_id)\n printf \"Removing Internet gateway: #{igw.internet_gateway_id} <-> #{igw.attachments[0].vpc_id}; \"\n client.delete_internet_gateway(internet_gateway_id: igw.internet_gateway_id)\n puts 'Done.'\n end\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n\n # 9) Route tables\n begin\n response = client.describe_route_tables(filters: [{name: 'vpc-id', values: [vpc_id]}])\n response.route_tables.each do |rtl|\n if rtl.associations[0] != nil\n if rtl.associations[0].route_table_association_id != nil\n puts \"Skipping #{rtl.associations[0].route_table_association_id}, causes exception.\"\n end\n next\n end\n printf \"Removing route table: #{rtl.route_table_id}, #{rtl.vpc_id}; \"\n client.delete_route_table(route_table_id: rtl.route_table_id)\n puts 'Done.'\n end\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n\n # 10) Delete VPC\n begin\n puts \"Attempting to delete VPC [#{vpc_id}]\"\n client.delete_vpc(vpc_id: vpc_id)\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n\n begin\n response = client.describe_vpcs(vpc_ids: [vpc_id])\n rescue Aws::EC2::Errors::InvalidVpcIDNotFound => e\n puts \"Deletion of vpc_id=[#{vpc_id}] was a success.\"\n exit 0\n end\n\n # Shouldn't get here, but sometimes does due to the ASG taking too long to\n # release subnet dependencies, or if running a cleanup before a launch has\n # fully completed, etc.\n puts 'Oops. Termination sometimes fails for various reasons.'\n puts 'Note: running this twice usually clears up any lingering dependencies.'\n puts ' With that said, there is still work to be done. Execute again.'\n exit 0\nend",
"def scale_down\n \n num_stopped = 0\n # lets figure out what we can shut down.\n logger.info \"Looking for unused instances to scale down...\"\n EventLog.info \"Looking for unused instances to scale down...\"\n instances.each do |i|\n #this is actually pretty complicated. we have to figure out the exact range for each instance, based on the instance launch time\n lt = i.launch_time\n lt_diff = 60 - lt.min\n lower_range = HOUR_MOD - lt_diff #careful, it could be negative!\n lower_range = lower_range + 60 if lower_range < 0 # adjust for negative!\n\n upper_range = lower_range + (60 - HOUR_MOD) #upper range for mins, could be > 59!\n upper_range = upper_range - 60 if upper_range > 59 #correct for over 59\n\n now_min = DateTime.now.min\n \n ### DEBUG shutdown logic\n # puts \"Instance: #{i.aws_instance_id}\"\n # puts \"Now: #{now_min}\"\n # puts \"Upper: #{upper_range}\"\n # puts \"Lower: #{lower_range}\"\n\n if (now_min > lower_range && now_min < upper_range) || ((upper_range < lower_range) && (now_min < upper_range || now_min > lower_range))\n #so lets shutdown, but only if it won't bring us below the min_running threshold\n\n #first find out how many instances are running of this type\n total_running = (instances.select{ |j| j.running? }).size\n unless ((total_running - 1) < min || (! i.available? && ! i.error? ) || (farm_type.eql?('admin')))\n # for now we shutdown via aws but this will change as we figure out a better way\n logger.info \"Shutting down #{i.farm.ami_id} -- #{i.instance_id} due to IDLE timeout.\"\n EventLog.info \"Shutting down #{i.farm.ami_id} -- #{i.instance_id} due to IDLE timeout.\"\n i.terminate\n num_stopped += 1\n end\n end\n end\n\n return num_stopped\n\n end",
"def reconcile\n \n #First sync instances \n Instance.sync_with_ec2\n \n #then make sure this farm is operating withing limits... start and stop based on limits\n #now lets go through our configs and sync what is running with what is configured to run\n\n num_stop = 0\n num_start = 0\n\n logger.info \"Reconciling farm #{ami_id}...\"\n EventLog.info \"Reconciling farm #{ami_id}...\"\n \n ia = instances.select{ |i| i.running?} \n if ia.size < min\n num_start = min.to_i - ia.size\n # need to start some of them\n logger.info \"Attempting to start #{num_start} #{ami_id} instances... may take a few moments.\"\n EventLog.info \"Attempting to start #{num_start} #{ami_id} instances... may take a few moments.\"\n start_and_create_instances(num_start)\n\n elsif ia.size > max\n # need to stop some of the instances, if they are either 'IDLE' or 'LAUNCHED' state or \"ERROR\"\n num_stop = ia.size - max.to_i\n count = 0\n ia.each do |ri|\n break if count >= num_stop\n if ri.available? || ri.error?\n #shut it down!\n logger.info \"Shutting down instance #{ami_id} -- #{ri.instance_id}...\"\n EventLog.info \"Shutting down instance #{ami_id} -- #{ri.instance_id}...\"\n ri.terminate\n count += 1\n end \n end\n end\n \n # shutdown what we can from idle\n \n num_stop += scale_down\n \n #########################\n #\n # now that we scaled down, lets recycle those compute nodes that have not checked in for a while (15 mins)\n # we're looking for those that are available or busy and are compute nodes\n #\n \n ia = instances.select{ |i| i.running?} \n \n ia.each do |ri|\n if (ri.available? || ri.state.eql?('busy')) && ri.farm.farm_type.eql?('compute') && ri.silent_since?(NODE_TIMEOUT)\n #shut down silent nodes\n logger.info \"Shutting down instance #{ri.farm.ami_id} -- #{ri.instance_id} because it was unresponsive.\"\n EventLog.info \"Shutting down instance #{ri.farm.ami_id} -- #{ri.instance_id} because it was unresponsive.\"\n ri.terminate\n \n #recycle if not heard from in a while\n # if ri.cycle_count < NODE_CYCLE_MAX\n # logger.info \"Recycling instance #{ri.farm.ami_id} -- #{ri.instance_id}...\"\n # EventLog.info \"Recycling instance #{ri.farm.ami_id} -- #{ri.instance_id}...\"\n # ri.recycle\n # else\n # logger.info \"Shutting down instance #{ri.farm.ami_id} -- #{ri.instance_id} because it was unresponsive and exceeded max recycle tries.\"\n # EventLog.info \"Shutting down instance #{ri.farm.ami_id} -- #{ri.instance_id} because it was unresponsive and exceeded max recycle tries.\"\n # ri.terminate \n # end\n end \n end\n \n \n return {:farm_name => name, :message => 'Finished reconciling', :num_shutdown => num_stop, :num_started => num_start}\n \n end",
"def terminate_instances\n @task.unsafe(\"Stopping #{@name} Launch process\") do\n autoscaling_group.suspend_processes('Launch')\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Terminating instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.terminate\n end\n end\n end",
"def terminate_instances\n @task.unsafe(\"Stopping #{@name} Launch process\") do\n autoscaling_group.suspend_processes('Launch')\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Terminating instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.terminate\n end\n end\n end",
"def shutdown()\n \n #shutdown all the instances we have.\n ids = id()\n \n @ec2.terminate_instances(ids)\n \n # wait for them to shut down for a couple of minutes\n attempts = 0\n stats = state_code()\n while (stats.any? {|s| s<=16 }) do\n if attempts > 6 \n raise CaTPAWS::EC2::Error::InstanceShutdown, \"Instances still running after a long wait. Check your EC2 account manually?\"\n end\n puts \"Terminating instances, please wait...\"\n sleep(10)\n attempts+=1\n get_instances(true)\n stats = state_code()\n end\n \n #and delete the associated security group\n @ec2.delete_security_group(@group_name)\n \n end",
"def cleanup_dead_deployment\n @@recover_count = @@recover_count + 1\n @@logger.info(\"Recover count: \" + @@recover_count.to_s);\n if @@recover_count >= 2\n @@logger.info(\"To many recover process running, skip it\");\n @@recover_count = @@recover_count - 1\n return\n end\n ScheduleTask.cleanup_dead_deployment(11, 0)\n @@recover_count = @@recover_count - 1\nend",
"def stop_instances\n @task.unsafe(\"Stopping #{@name} processes\") do\n autoscaling_group.suspend_all_processes\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Stopping instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.stop\n end\n end\n end",
"def detach_from_elbs(instance:)\n unless instance.is_a?(Aws::OpsWorks::Types::Instance)\n fail(ArgumentError, \"instance must be a Aws::OpsWorks::Types::Instance struct\")\n end\n\n all_load_balancers = @elb_client.describe_load_balancers\n .load_balancer_descriptions\n\n load_balancers = detach_from(all_load_balancers, instance)\n\n @lb_wait_params = []\n\n load_balancers.each do |lb|\n params = {\n load_balancer_name: lb.load_balancer_name,\n instances: [{ instance_id: instance.ec2_instance_id }]\n }\n\n remaining_instances = @elb_client\n .deregister_instances_from_load_balancer(params)\n .instances\n\n log(<<-MSG.split.join(\" \"))\n Will detach instance #{instance.hostname} from\n #{lb.load_balancer_name} (remaining attached instances:\n #{remaining_instances.count.to_s})\n MSG\n\n @lb_wait_params << params\n end\n \n unless @regional_deploy\n if @lb_wait_params.any?\n wait_for_detach(@lb_wait_params)\n else\n log(\"No load balancers found for instance #{instance.hostname}\")\n end\n end\n\n load_balancers\n end",
"def stop_instances\n @task.unsafe(\"Stopping #{@name} processes\") do\n save_to_s3(@task.bucket)\n autoscaling_group.suspend_all_processes\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Stopping instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.stop\n end\n end\n end",
"def postBoot(instance_id = nil)\n @cloud_id ||= instance_id\n _node, _config, deploydata = describe(cloud_id: @cloud_id)\n\n raise MuError, \"Couldn't find instance #{@mu_name} (#{@cloud_id})\" if !cloud_desc\n return false if !MU::MommaCat.lock(@cloud_id+\"-orchestrate\", true)\n return false if !MU::MommaCat.lock(@cloud_id+\"-groom\", true)\n\n getIAMProfile\n\n finish = Proc.new { |status|\n MU::MommaCat.unlock(@cloud_id+\"-orchestrate\")\n MU::MommaCat.unlock(@cloud_id+\"-groom\")\n return status\n }\n\n MU::Cloud::AWS.createStandardTags(\n @cloud_id,\n region: @region,\n credentials: @credentials,\n optional: @config['optional_tags'],\n nametag: @mu_name,\n othertags: @config['tags']\n )\n\n # Make double sure we don't lose a cached mu_windows_name value.\n if (windows? or !@config['active_directory'].nil?)\n @mu_windows_name ||= deploydata['mu_windows_name']\n end\n\n loop_if = Proc.new {\n !cloud_desc(use_cache: false) or cloud_desc.state.name != \"running\"\n }\n MU.retrier([Aws::EC2::Errors::ServiceError], max: 30, wait: 40, loop_if: loop_if) { |retries, _wait|\n if cloud_desc and cloud_desc.state.name == \"terminated\"\n logs = if !@config['basis'].nil?\n pool = @deploy.findLitterMate(type: \"server_pools\", name: @config[\"name\"])\n if pool\n MU::Cloud::AWS.autoscale(region: @region, credentials: @credentials).describe_scaling_activities(auto_scaling_group_name: pool.cloud_id).activities\n else\n nil\n end\n end\n raise MuError.new, \"#{@cloud_id} appears to have been terminated mid-bootstrap!\", details: logs\n end\n if retries % 3 == 0\n MU.log \"Waiting for EC2 instance #{@mu_name} (#{@cloud_id}) to be ready...\", MU::NOTICE\n end\n }\n\n allowBastionAccess\n\n setAlarms\n\n # Unless we're planning on associating a different IP later, set up a\n # DNS entry for this thing and let it sync in the background. We'll come\n # back to it later.\n if @config['static_ip'].nil? and !@named\n MU::MommaCat.nameKitten(self)\n @named = true\n end\n\n if !@config['src_dst_check'] and !@config[\"vpc\"].nil?\n MU.log \"Disabling source_dest_check #{@mu_name} (making it NAT-worthy)\"\n MU::Cloud::AWS.ec2(region: @region, credentials: @credentials).modify_instance_attribute(\n instance_id: @cloud_id,\n source_dest_check: { value: false }\n )\n end\n\n # Set console termination protection. Autoscale nodes won't set this\n # by default.\n MU::Cloud::AWS.ec2(region: @region, credentials: @credentials).modify_instance_attribute(\n instance_id: @cloud_id,\n disable_api_termination: { value: true}\n )\n\n tagVolumes\n configureNetworking\n saveCredentials\n\n if !@config['image_then_destroy']\n notify\n end\n\n finish.call(false) if !bootstrapGroomer\n\n # Make sure we got our name written everywhere applicable\n if !@named\n MU::MommaCat.nameKitten(self)\n @named = true\n end\n\n finish.call(true)\n end",
"def cleanup_dead_deployment\n @@recover_count = @@recover_count + 1\n puts \"Recover count: \" + @@recover_count.to_s\n if @@recover_count >= 2\n puts \"To many recover process running, skip it\"\n @@recover_count = @@recover_count - 1\n return\n end\n ScheduleTask.cleanup_dead_deployment \n @@recover_count = @@recover_count - 1\nend",
"def migrate_elbs\n elbs_dir = \"#{@migration_root}/elb-load-balancers\"\n policies_dir =\"#{@migration_root}/elb-policies\"\n\n if !Dir.exists?(@migration_root)\n Dir.mkdir(@migration_root)\n end\n if !Dir.exists?(elbs_dir)\n Dir.mkdir(elbs_dir)\n end\n if !Dir.exists?(policies_dir)\n Dir.mkdir(policies_dir)\n end\n\n ELB::elbs.map do |elb_name, elb|\n puts \"Migrating load balancer #{elb_name}\"\n\n local_elb = LoadBalancerConfig.new(elb_name)\n tags = ELB::elb_tags(elb_name)\n attributes = ELB::elb_attributes(elb_name)\n local_elb.populate!(elb, tags, attributes)\n\n # Migrate the backend and listener policies if they do not already\n # exist locally and are not the default AWS policies\n listener_policies = local_elb.listeners.flat_map { |l| l.policies }\n backend_policies = local_elb.backend_policies.flat_map { |b| b.policy_names }\n\n (listener_policies + backend_policies).uniq.map do |policy_name|\n policy_file = \"#{policies_dir}/#{policy_name}.json\"\n # If it is not already migrated and not a default policy, create it\n if !File.file? policy_file\n if !ELB::default_policies.has_key? policy_name\n # Get the full policy description from the elb policies\n full_policy = ELB::elb_policies(elb_name)[policy_name]\n\n if full_policy.nil?\n puts \"Unable to migrate policy #{policy_name}\"\n else\n puts \"Migrating policy #{policy_name}\"\n json = JSON.pretty_generate(full_policy.to_cumulus_hash)\n File.open(policy_file, \"w\") { |f| f.write(json) }\n end\n end\n end\n end\n\n File.open(\"#{elbs_dir}/#{elb_name}.json\", \"w\") { |f| f.write(local_elb.pretty_json) }\n end\n\n end",
"def deploy_layer_rolling(layer_name, timeout = 600)\n instances = get_instances(layer_name)\n elb = get_elb(layer_name)\n success = true\n instances.each do |instance|\n success = deploy_instance_rolling(instance, elb, timeout)\n break if !success\n end\n success\n end",
"def cleanup_dead_deployment\n @@recover_count = @@recover_count + 1\n puts \"Recover count: \" + @@recover_count.to_s\n if @@recover_count >= 2\n puts \"To many recover process running, skip it\"\n @@recover_count = @@recover_count - 1\n return\n end\n ScheduleTask.cleanup_dead_deployment(9, 2, \"id desc\") \n @@recover_count = @@recover_count - 1\nend",
"def restart_ecs_tasks instances\n instances.each do |i_id, meta|\n tries = 0\n begin\n tries = tries + 1\n Logging.log \"Restarting ECS task for #{meta['name']} (##{tries} try)\".colorize(:yellow)\n fail 'not running' unless AWS::CLI_Interface.ec2_instance_status(i_id) == AWS::EC2_CONS::RUNNING\n AWS::CLI_Interface.ecs_run_task meta['ecs']['cluster'], meta['ecs']['task']\n rescue\n Logging.log \"#{meta['name']} not fully running yet. Waiting 120 seconds for next try\".colorize(:red)\n progressbar = ProgressBar.create\n 100.times do\n progressbar.increment\n sleep 1.2\n end\n retry if tries < 5\n end\n end\n end",
"def create_instances\n min_count = max_count = @bs.number_of_nodes\n puts \"\\nCreating #{max_count} on-demand instance(s)\"\n options = {\n 'ClientToken' => generate_token,\n 'KeyName' => Chef::Config[:knife][:aws_ssh_key_id],\n 'InstanceType' => @bs.flavor,\n 'SubnetId' => @bs[:novpc] ? nil : @bs.subnet_id,\n 'Placement.AvailabilityZone' => @bs.mixins.az.data,\n 'SecurityGroupId' => @bs.mixins.sg.data\n }\n options['EbsOptimized'] = !! @bs[:ebs_optimized]\n\n ## REVIEW\n if ami.root_device_type == \"ebs\"\n ami_map = ami.block_device_mapping.first\n block_device_mapping = {\n 'DeviceName' => ami_map['deviceName'],\n 'Ebs.VolumeSize' => ami_map['volumeSize'].to_s,\n 'Ebs.DeleteOnTermination' => ami_map['deleteOnTermination']\n }\n options['BlockDeviceMapping'] = [block_device_mapping]\n end\n\n ## Optionally only include mapped devices\n ## This way we get all of the ephemeral drives, some unmapped however\n if @bs.mixins.volume.data[:ephemeral_available]\n ephmap = @bs.mixins.volume.data.ephemeral_available.each_with_index.map do |d,i|\n {\n 'VirtualName' => \"ephemeral#{i}\",\n 'DeviceName' => d\n }\n end\n options['BlockDeviceMapping'].concat( ephmap )\n end\n\n if (max_count == 1) and @bs[:private_ip_address]\n options['PrivateIpAddress'] = @bs.private_ip_address\n puts \"Assigning IP ADDRESS : #{options['PrivateIpAddress']}\"\n end\n\n if Chef::Config[:knife][:aws_user_data]\n begin\n options['UserData']= File.read(Chef::Config[:knife][:aws_user_data])\n rescue\n ui.warn(\"Cannot read #{Chef::Config[:knife][:aws_user_data]}:\"\\\n \" #{$!.inspect}. Ignoring option.\")\n end\n end\n\n # -----------------------------------------------------------------\n tries = 5\n print_table(options, 'Launch Config')\n begin\n puts \"\\nSending request...\"\n response = connection.run_instances(@bs.image, min_count,\n max_count, options)\n ui.msg(response.inspect)\n rescue Exception => e\n ui.warn(\"#{e.message}\\nException creating instances\")\n if (tries -= 1) <= 0\n ui.warn(\"\\n\\nMax tries reached. Exiting.\\n\\n\")\n exit 1\n else\n ui.msg(\"Trying again.\\n\")\n retry\n end\n end\n # now we have our servers\n instances = response.body['instancesSet']\n # select only instances that have instanceId key and collect those ids\n # into an array\n @bs[:instance_ids] =\n instances.select {|i| i.has_key?('instanceId')}.collect do |i|\n i['instanceId']\n end\n\n puts \"\\nNumber of instances started: #{@bs.instance_ids.size}\\n\"\n sleep 10\n puts \"Getting servers..\"\n # collect an array of servers retrieved based on the instance ids we\n # obtained above\n @bs[:servers] = @bs.instance_ids.collect do |id|\n begin\n server = connection.servers.get(id)\n rescue Exception => e\n sleep 7\n retry\n end\n raise Ec2Error.new(\"server #{id} was nil\") if server.nil?\n server\n end\n end",
"def deploy_instance_rolling(instance, elb, timeout = 600)\n if !elb.nil?\n elb.remove_instance(instance)\n end\n\n success = create_deployment({name: 'deploy'}, [instance], timeout)\n\n # only add instance back to elb if deployment succeeded\n if !elb.nil? && success\n success = elb.add_instance(instance)\n end\n\n success\n end",
"def index\n\n credentials = Aws::Credentials.new('AKIAJ2JD2EKKFVDSR37A', 'cnZUnzuyYPqUevEPb045VJUnW55VR+rUCQrplzd/')\n ec2 = Aws::EC2::Client.new(\n region: \"us-east-1\",\n credentials: credentials\n )\n #i = ec2.instances.create(:image_id => \"ami-e3106686\")\n resp = ec2.run_instances({\n dry_run: true,\n image_id: \"ami-e3106686\", # required\n min_count: 1, # required\n max_count: 1, # required\n instance_type: \"t1.micro\", # accepts t1.micro, m1.small, m1.medium, m1.large, m1.xlarge, m3.medium, m3.large, m3.xlarge, m3.2xlarge, m4.large, m4.xlarge, m4.2xlarge, m4.4xlarge, m4.10xlarge, t2.micro, t2.small, t2.medium, t2.large, m2.xlarge, m2.2xlarge, m2.4xlarge, cr1.8xlarge, i2.xlarge, i2.2xlarge, i2.4xlarge, i2.8xlarge, hi1.4xlarge, hs1.8xlarge, c1.medium, c1.xlarge, c3.large, c3.xlarge, c3.2xlarge, c3.4xlarge, c3.8xlarge, c4.large, c4.xlarge, c4.2xlarge, c4.4xlarge, c4.8xlarge, cc1.4xlarge, cc2.8xlarge, g2.2xlarge, cg1.4xlarge, r3.large, r3.xlarge, r3.2xlarge, r3.4xlarge, r3.8xlarge, d2.xlarge, d2.2xlarge, d2.4xlarge, d2.8xlarge\n placement: {\n tenancy: \"default\", # accepts default, dedicated\n },\n\n block_device_mappings: [\n {\n virtual_name: \"String\",\n device_name: \"String\",\n ebs: {\n snapshot_id: \"String\",\n volume_size: 1,\n delete_on_termination: true,\n volume_type: \"standard\", # accepts standard, io1, gp2\n iops: 1,\n encrypted: true,\n },\n\n },\n ],\n monitoring: {\n enabled: true, # required\n },\n disable_api_termination: true,\n instance_initiated_shutdown_behavior: \"stop\", # accepts stop, terminate\n network_interfaces: [\n {\n delete_on_termination: true,\n private_ip_addresses: [\n {\n private_ip_address: \"172.31.2.177\", # required\n primary: true,\n },\n ],\n secondary_private_ip_address_count: 1,\n associate_public_ip_address: true,\n },\n ],\n ebs_optimized: true,\n })\n @ec2_instances = Ec2Instance.all\n end",
"def update_lb_servers\n clean_up\n @hosts.each do |host|\n Docker.url = \"tcp://#{host}:#{@docker_port}/\"\n containers = Docker::Container.all(all: true, filters: { ancestor: [@ws_image], status:['running'] }.to_json)\n containers.each do |container|\n port = container.json['HostConfig']['PortBindings']['8070/tcp'][0]['HostPort']\n register_container(host, port, container.id)\n end\n end\n end",
"def ecs_wait_container_instances\n @ecs_wait_container_instances = true\n end",
"def attach_to_elbs(instance:, load_balancers:)\n check_arguments(instance: instance, load_balancers: load_balancers)\n\n if load_balancers.empty?\n log(\"No load balancers to attach to\")\n return {}\n end\n\n @lb_wait_params = []\n registered_instances = {} # return this\n\n load_balancers.each do |lb|\n params = {\n load_balancer_name: lb.load_balancer_name,\n instances: [{ instance_id: instance.ec2_instance_id }]\n }\n\n result = @elb_client.register_instances_with_load_balancer(params)\n\n registered_instances[lb.load_balancer_name] = result\n @lb_wait_params << params\n end\n\n log(\"Re-attaching instance #{instance.hostname} to all load balancers\")\n\n unless @regional_deploy\n wait_for_re_attach(@lb_wait_params)\n end\n\n registered_instances\n end",
"def replace_instances\n log_options\n\n unless stack_exists?(name)\n raise StackDoesNotExistError, \"Stack #{name} does not exist.\"\n end\n\n stack = cfn.stacks[name]\n unless stack_was_just_updated?(stack)\n logger.info \"stack was not updated recently, not replacing instances.\"\n return\n end\n\n ex = WaitTimedOutError.new \"Timed out waiting to replace instances.\"\n wait_until(ex) do\n ok_to_replace_instances?(stack.status, stack.last_updated_time)\n end\n\n logger.info \"replacing all auto-scaling instances in #{name}\"\n\n if stack_asg.nil?\n raise MissingAutoScalingGroupError, \"No ASG found for stack #{name}\"\n end\n\n stack_asg.ec2_instances.each do |i|\n if i.status == :running\n logger.info \"terminating instance #{i.id}\"\n i.terminate\n else\n logger.info \"Not terminating #{i.id} due to status: #{i.status}\"\n end\n end\n end",
"def run_instances(num_vms, opts, roles, disks)\n # Make a copy (the options are a simple hash so shallow copy does the\n # trick) to not modify the original.\n options = opts.clone\n options['num_vms'] = num_vms.to_s\n\n uri = URI(\"http://#{@ip}:#{SERVER_PORT}/instances\")\n headers = {'Content-Type' => 'application/json',\n 'AppScale-Secret' => @secret}\n request = Net::HTTP::Post.new(uri.path, headers)\n\n request.body = JSON.dump(options)\n\n run_result = JSON.parse(make_call(request, uri))\n Djinn.log_debug(\"[IM] Run instances info says [#{run_result}]\")\n operation_id = run_result['operation_id']\n\n vm_info = {}\n loop {\n begin\n describe_result = describe_operation(operation_id)\n rescue Djinn::FailedNodeException => error\n Djinn.log_warn(\n \"[IM] Error describing run instances operation #{operation_id}. \" \\\n \"Error: #{error.message}\")\n next\n end\n Djinn.log_debug(\"[IM] Describe run operation has vm_info \" \\\n \"#{describe_result['vm_info'].inspect}.\")\n\n if describe_result['state'] == 'success'\n vm_info = describe_result['vm_info']\n break\n elsif describe_result['state'] == 'failed'\n raise AppScaleException.new(describe_result['reason'])\n end\n Kernel.sleep(SMALL_WAIT)\n }\n\n # ip:role:instance-id\n instances_created = []\n vm_info['public_ips'].each_index { |index|\n tmp_roles = roles[index]\n tmp_roles = 'open' if roles[index].nil?\n instances_created << {\n 'public_ip' => vm_info['public_ips'][index],\n 'private_ip' => vm_info['private_ips'][index],\n 'roles' => tmp_roles,\n 'instance_id' => vm_info['instance_ids'][index],\n 'disk' => disks[index],\n 'instance_type' => options['instance_type']\n }\n }\n\n instances_created\n end",
"def start_instances\n started = 0\n autoscaling_instances.each do |instance|\n ec2_instance = instance.ec2_instance\n next if !ec2_instance.exists?\n\n if ec2_instance.status == :stopped\n @task.unsafe(\"Starting instance #{instance.instance_id}\") do\n ec2_instance.start\n load_balancers.each do |elb|\n elb.instances.register(instance.instance_id)\n end\n started += 1\n end\n else\n @task.debug { \"Instance #{instance.instance_id} already running\" }\n end\n end\n\n # FIXME\n # This is to give instances a little more time to start up and become\n # healthy before restarting autoscaling processes.\n # If an instance isn't started and healthy in time, the autoscale will kill\n # it for being unhealthy.\n #\n # The \"right\" way to do it would be to actually poll the instances until\n # they are healthy (or a timeout is reached). With the current task model,\n # other actions are blocked while this is waiting, so I can't afford to\n # wait too long.\n sleep(@grace_period) if started > 0\n end",
"def start_instances\n started = 0\n autoscaling_instances.each do |instance|\n ec2_instance = instance.ec2_instance\n next if !ec2_instance.exists?\n\n if ec2_instance.status == :stopped\n @task.unsafe(\"Starting instance #{instance.instance_id}\") do\n ec2_instance.start\n load_balancers.each do |elb|\n elb.instances.register(instance.instance_id)\n end\n started += 1\n end\n else\n @task.debug { \"Instance #{instance.instance_id} already running\" }\n end\n end\n\n # FIXME\n # This is to give instances a little more time to start up and become\n # healthy before restarting autoscaling processes.\n # If an instance isn't started and healthy in time, the autoscale will kill\n # it for being unhealthy.\n #\n # The \"right\" way to do it would be to actually poll the instances until\n # they are healthy (or a timeout is reached). With the current task model,\n # other actions are blocked while this is waiting, so I can't afford to\n # wait too long.\n sleep(@grace_period) if started > 0\n end",
"def update_instances(elb_name, instances_added, instances_removed = [])\n\n # deregister instances that were removed\n if !instances_removed.empty?\n @elb.deregister_instances_from_load_balancer({\n load_balancer_name: elb_name,\n instances: instances_removed.map do |i|\n {\n instance_id: i\n }\n end\n })\n end\n\n # register instances that were added\n if !instances_added.empty?\n @elb.register_instances_with_load_balancer({\n load_balancer_name: elb_name,\n instances: instances_added.map do |i|\n {\n instance_id: i\n }\n end\n })\n end\n end",
"def fetch_from_ec2_loadbalancer\n instances_for_deploy = []\n loadbalancer lb_webserver, :web\n instances_for_deploy\nend",
"def fetch_from_ec2_loadbalancer\n instances_for_deploy = []\n loadbalancer lb_webserver, :web\n instances_for_deploy\nend",
"def iterate\n\t\t\t# First off, if we can free up resources, we should do that first.\n\t\t\tModel::Instance.marked_on_host(AppManager.host).each { |i|\n\t\t\t\tAppManager.kill_marked i\n\t\t\t}\n\n\t\t\t# We do this right after to avoid too long a wait for instances to\n\t\t\t# spin up.\n\t\t\tModel::Instance.started_on_host(AppManager.host).each { |i|\n\t\t\t\tAppManager.check_startup i\n\t\t\t}\n\n\t\t\tModel::Instance.live_on_host(AppManager.host).each { |i|\n\t\t\t\tAppManager.check_running i\n\t\t\t}\n\n\t\t\t# TODO: ready_dataset needs a .where(:some_criterion => foo); JG\n\t\t\t# suggests a distributed hashing algorithm for selecting instances,\n\t\t\t# which from the sound of it would avoid collisions. The goal is\n\t\t\t# to distribute load semi-optimally for capacity, ideally without\n\t\t\t# requiring that the nodes communicate with or monitor each other.\n\t\t\ti = Model::Instance.ready_dataset.first\n\t\t\tif i\n\t\t\t\tAppManager.spin_up i\n\t\t\tend\n\t\tend",
"def createEc2Instance\n\t\t name = @server[\"name\"]\n\t\t node = @server['mu_name']\n\t\t\tbegin\n\t\t\t\t@server['iam_role'] = MU::Server.createIAMProfile(\"Server-\"+name, base_profile: @server['iam_role'], extra_policies: @server['iam_policies'])\n\t\t\trescue Aws::EC2::Errors::RequestLimitExceeded => e\n\t\t\t\tsleep 10\n\t\t\t\tretry\n\t\t\tend\n\t\t\t@server['iam_role'] = @server['iam_role']\n\n\t\t\tbegin\n\t\t\t\t@deploy.createEc2SSHKey\n\t\t\trescue Aws::EC2::Errors::RequestLimitExceeded => e\n\t\t\t\tsleep 10\n\t\t\t\tretry\n\t\t\tend\n\n\t\t instance_descriptor = {\n\t\t :image_id => @server[\"ami_id\"],\n\t\t :key_name => @deploy.keypairname,\n\t\t :instance_type => @server[\"size\"],\n\t\t :disable_api_termination => true,\n\t\t :min_count => 1,\n\t\t :max_count => 1,\n\t\t\t\t:network_interfaces => [\n\t\t\t\t\t{\n\t\t\t\t\t\t:associate_public_ip_address => name[\"associate_public_ip\"]\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t }\n\t\t\t\n\t\t\tif !@server['private_ip'].nil?\n\t\t\t\tinstance_descriptor[:private_ip_address] = @server['private_ip']\n\t\t\tend\n\n\t\t\tvpc_id=subnet_id=nat_host_name=nat_ssh_user = nil\n\t\t\tsubnet_retries = 0\n\t\t\tif !@server[\"vpc\"].nil?\n\t\t\t\tbegin\n\t\t\t\t\tvpc_id, subnet_ids, nat_host_name, nat_ssh_user = MU::VPC.parseVPC(@server['vpc'])\n\t\t\t\trescue Aws::EC2::Errors::ServiceError => e\n\t\t\t\t\tMU.log e.message, MU::ERR, details: @server\n\t\t\t\t\tif subnet_retries < 5\n\t\t\t\t\t subnet_retries = subnet_retries + 1\n\t\t\t\t\t sleep 15\n\t\t\t\t\t retry\n\t\t\t\t\tend\n\t\t\t\t\traise e\n\t\t\t\tend\n\t\t\t\tsubnet_id = subnet_ids.first\n\t\t\t\tif subnet_id.nil? or subnet_id.empty?\n\t\t\t\t\tMU.log \"Got null Subnet id out of #{@server['vpc']}\", MU::ERR\n\t\t\t\t\traise \"deploy failure\"\n\t\t\t\tend\n\n\t\t\t\tMU.log \"Deploying #{node} into VPC #{vpc_id} Subnet #{subnet_id}\"\n\n\t\t\t\tif !@server[\"vpc\"][\"nat_host_name\"].nil? or !@server[\"vpc\"][\"nat_host_id\"].nil?\n\t\t\t\t\tadmin_sg = MU::Server.punchAdminNAT(@server, node)\n\t\t\t\telse\n\t\t\t\t\tadmin_sg = MU::FirewallRule.setAdminSG(vpc_id: vpc_id, region: @server['region'])\n\t\t\t\tend\n\n\t\t\t\tinstance_descriptor[:subnet_id] = subnet_id\n\t\t\t\tnode_sg = MU::FirewallRule.createEc2SG(\n\t\t\t\t\t\t@server[\"name\"].upcase,\n\t\t\t\t\t\t@server[\"ingress_rules\"],\n\t\t\t\t\t\tdescription: \"SG holes for #{node}\",\n\t\t\t\t\t\tvpc_id: vpc_id,\n\t\t\t\t\t\tregion: @server['region']\n\t\t\t\t)\n\t\t\telse\n\t\t\t\tadmin_sg = MU::FirewallRule.setAdminSG(region: @server['region'])\n\t\t\t\tnode_sg = MU::FirewallRule.createEc2SG(\n\t\t\t\t\t\t@server[\"name\"].upcase,\n\t\t\t\t\t\t@server[\"ingress_rules\"],\n\t\t\t\t\t\tdescription: \"SG holes for #{node}\",\n\t\t\t\t\t\tregion: @server['region']\n\t\t\t\t)\n\t\t\tend\n\t\t\tsecurity_groups = Array.new\n\t\t\tsecurity_groups << admin_sg\n\t\t\tsecurity_groups << node_sg\n\t\t\tif !@server[\"add_firewall_rules\"].nil?\n\t\t\t\t@server[\"add_firewall_rules\"].each { |acl|\n\t\t\t\t\tsg = MU::FirewallRule.find(sg_id: acl[\"rule_id\"], name: acl[\"rule_name\"], region: @server['region'])\n\t\t\t\t\tif sg.nil?\n\t\t\t\t\t\tMU.log \"Couldn't find dependent security group #{acl} for server #{node}\", MU::ERR\n\t\t\t\t\t\traise \"deploy failure\"\n\t\t\t\t\tend\n\t\t\t\t\tsecurity_groups << sg.group_id\n\t\t\t\t}\n\t\t\tend\n\n\t\t\tinstance_descriptor[:security_group_ids] = security_groups\n\n\t\t if !@userdata.nil? and !@userdata.empty?\n\t\t instance_descriptor[:user_data] = Base64.encode64(@userdata)\n\t\t end\n\n\t\t if !@server[\"iam_role\"].nil?\n\t\t instance_descriptor[:iam_instance_profile] = { name: @server[\"iam_role\"]}\n\t\t end\n\n\t\t\tconfigured_storage = Array.new\n\t\t\tif @server[\"storage\"]\n\t\t\t\t@server[\"storage\"].each { |vol|\n\t\t\t\t\tconfigured_storage << MU::Server.convertBlockDeviceMapping(vol)\n\t\t\t\t}\n\t\t\tend\n\t\t\n\t\t\tMU::Server.waitForAMI(@server[\"ami_id\"], region: @server['region'])\n\n\t\t\tinstance_descriptor[:block_device_mappings] = configured_storage\n\t\t\tinstance_descriptor[:block_device_mappings].concat(@ephemeral_mappings)\n\n\t\t\tinstance_descriptor[:monitoring] = { enabled: @server['monitoring'] }\n\n\t\t\tMU.log \"Creating EC2 instance #{node}\"\n\t\t\tMU.log \"Instance details for #{node}: #{instance_descriptor}\", MU::DEBUG\n#\t\t\t\tif instance_descriptor[:block_device_mappings].empty?\n#\t\t\t\t\tinstance_descriptor.delete(:block_device_mappings)\n#\t\t\t\tend\n#pp instance_descriptor[:block_device_mappings]\n\t\t\tretries = 0\n\t\t\tbegin\n\t\t\t\tresponse = MU.ec2(@server['region']).run_instances(instance_descriptor)\n\t\t\trescue Aws::EC2::Errors::InvalidGroupNotFound, Aws::EC2::Errors::InvalidSubnetIDNotFound, Aws::EC2::Errors::InvalidParameterValue, Aws::EC2::Errors::RequestLimitExceeded => e\n\t\t\t\tif retries < 10\n\t\t\t\t\tif retries > 7\n\t\t\t\t\t\tMU.log \"Seeing #{e.inspect} while trying to launch #{node}, retrying a few more times...\", MU::WARN, details: instance_descriptor\n\t\t\t\t\tend\n\t\t\t\t\tsleep 10\n\t\t\t\t\tretries = retries + 1\n\t\t\t\t\tretry\n\t\t\t\telse\n\t\t\t\t\traise e\n\t\t\t\tend\n\t\t\tend\n\n\t\t\tinstance = response.instances.first\n\t\t\tMU.log \"#{node} (#{instance.instance_id}) coming online\"\n\n\n\t\t\treturn instance\n\n\t\tend",
"def stop_all_instances\n Spinup.logger.info('Attempting to stop all running instances')\n running_instances = ec2.instances\n\n Spinup.logger.info(\" Found #{running_instances.count} running instances\")\n\n running_instances.each do |running_instance|\n instance_stopped?(running_instance)\n end\n end",
"def wait_for_status_checks(status)\n @logger.notify(\"netscaler: Now wait for all hosts' status checks to reach state #{status}\")\n @hosts.each do |host|\n instance = host['instance']\n name = host.name\n\n @logger.notify(\"netscaler: Wait for status check #{status} for node #{name}\")\n\n # TODO: should probably be a in a shared method somewhere\n for tries in 1..10\n begin\n if instance.client.describe_instance_status({:instance_ids => [instance.id]})[:instance_status_set].first[:system_status][:status] == status\n # Always sleep, so the next command won't cause a throttle\n backoff_sleep(tries)\n break\n elsif tries == 10\n raise \"Instance never reached state #{status}\"\n end\n rescue AWS::EC2::Errors::InvalidInstanceID::NotFound => e\n @logger.debug(\"Instance #{name} not yet available (#{e})\")\n end\n backoff_sleep(tries)\n end\n end\n end",
"def find_instances(tags)\n attempts = 0\n begin\n ec2.servers.select { |server| tags.reject { |k,v| server.tags[k] == tags[k] }.empty? }\n rescue Excon::Errors::ServiceUnavailable\n sleep 5\n attempts += 1\n return [] if attempts == 5\n retry\n end\n end",
"def flush_when_ready\n flushing :ensure => :absent do\n eip = aws_item.elastic_ip\n\n volumes = aws_item.attachments.map do |mnt, att|\n att.delete(:force => true)\n att.volume\n end\n\n aws_item.delete\n\n # Avoid squating on current resource name while terminated\n aws_item.tags['Name'] = @property_hash[:name] + \"-terminated\"\n\n wait_until {aws_item.status == :terminated }\n\n volumes.each do |vol|\n if vol.state == :deleting or vol.state == :deleted\n wait_until { vol.state == :deleted }\n else\n wait_until { vol.state == :available || vol.state == :error }\n vol.delete\n end\n end\n\n eip.delete\n return # don't do any further flushing\n end\n\n flushing :ensure => :present do\n\n instance_config = {\n :image_id => resource[:image_id],\n :instance_type => resource[:instance_type],\n :subnet => lookup(:aws_subnet, resource[:subnet]).aws_item,\n :key_name => resource[:key_name],\n :associate_public_ip_address => resource[:associate_public_ip_address],\n :user_data => resource[:user_data],\n }\n if resource[:iam_role]\n profile = iam.client.get_instance_profile(\n :instance_profile_name => resource[:iam_role]\n )\n instance_config[:iam_instance_profile] = profile[:instance_profile][:arn]\n end\n\n if block_devices = resource[:block_device_mappings]\n block_devices.each_with_index do |dev, i|\n\n if dev['ebs'] and dev['ebs']['volume_size']\n # Fun fact: puppet resources aren't aware of ints\n dev['ebs']['volume_size'] = dev['ebs']['volume_size'].to_i\n end\n # Just auto-name, we can't actually get this name back and it pretty much\n # has to follow this pattern anyway\n dev['virtual_name'] = \"ephemeral#{i}\"\n end\n instance_config[:block_device_mappings] = block_devices\n end\n\n\n instance = collection.create(instance_config)\n\n # tag devices\n instance.block_devices.each do |dev|\n if dev[:ebs] and dev[:ebs][:volume_id]\n name = dev[:device_name].sub(/^\\/dev\\//, '')\n ec2.volumes[dev[:ebs][:volume_id]].add_tag('Name', :value => \"#{resource[:name]}-#{name}\")\n end\n end\n\n also_flush(:security_groups, :elastic_ip)\n\n instance # this becomes aws_item\n end\n\n flushing :security_groups do |sgs|\n aws_item.client.modify_instance_attribute(\n :instance_id => aws_item.id,\n :groups => sgs.collect {|sg| lookup(:aws_security_group, sg).aws_item.id }\n )\n end\n\n flushing :elastic_ip => true do\n eip = ec2.elastic_ips.create(:vpc => true)\n wait_until { eip.exists? }\n aws_item.associate_elastic_ip(eip)\n end\n\n flushing :elastic_ip => false do\n eip = aws_item.elastic_ip\n eip.dissasociate\n eip.release\n end\n\n super # taggable again\n end",
"def run\n info 'Starting the deployment process'\n loop do\n if all_nodes_are_successful?\n info 'All nodes are deployed successfully. Stopping the deployment process'\n break true\n end\n if has_failed_critical_nodes?\n failed_names = failed_critical_nodes.map { |n| n.name }.join ', '\n info \"Critical nodes failed: #{failed_names}. Stopping the deployment process.\"\n break false\n end\n if all_nodes_are_finished?\n if has_failed_nodes?\n failed_names = failed_nodes.map { |n| n.name }.join ', '\n info \"All nodes are finished and some have failed: #{failed_names}. Stopping the deployment process.\"\n else\n info 'All nodes are finished. Stopping the deployment process.'\n end\n break false\n end\n process_all_nodes\n end\n end",
"def shutdown(group)\n cfmshutdown = AWS::CloudFormation.new\n ec2shutdown = AWS::EC2.new\n puts \"XXXXXXXXXX DAILY CHECKING HERE SHUT DOWN XXXXXXXXXXXX\"\n puts group.name\n puts \"Shut down Job is working now\"\n puts group.users.length\n puts \"-------------\"\n if group.users.length > 0\n allinstanceids = []\n group.users.each do |user|\n if user.stacks.length > 0\n user.stacks.each do |stack|\n if stack.ec2instance_ids.length > 0 \n allinstanceids.concat stack.ec2instance_ids\n end\n end\n end\n end\n puts \"BUBBBUBUBBBB\"\n puts allinstanceids.class\n allinstanceids = allinstanceids.uniq\n puts allinstanceids.class\n puts \"BUBBBUBUBBBB\"\n if allinstanceids.length > 0\n $ec2_resource.instances({instance_ids: allinstanceids}).batch_stop # To job stop\n end\n end \n puts \"YYYYYYYYYYYYYYYYYYYYYYYY\"\n end",
"def tag_instances(instances)\n instances.each do |instance|\n sleep 1 until instance.status != :pending\n instance.add_tag('Class', :value => \"Development\")\n end\n end",
"def destroy_all\n c = self.get_connection\n c.servers.each do |s|\n server = c.get_server(s[:id])\n if !server.delete!\n Rails.logger.error \"Unable to delete server on backend: #{server.inspect}\"\n return false\n end\n end\n self.instances.each do |i|\n if not i.update_attributes(:deployment_completed => false, :deployment_started => false, :reachable => false)\n Rails.logger.error \"Unable to update instance after destroying on backend: #{i.inspect}\"\n return false\n end\n end\n return true\n end",
"def destroy_all\n c = self.get_connection\n c.servers.each do |s|\n server = c.get_server(s[:id])\n if !server.delete!\n Rails.logger.error \"Unable to delete server on backend: #{server.inspect}\"\n return false\n end\n end\n self.instances.each do |i|\n if not i.update_attributes(:deployment_completed => false, :deployment_started => false, :reachable => false)\n Rails.logger.error \"Unable to update instance after destroying on backend: #{i.inspect}\"\n return false\n end\n end\n return true\n end",
"def reboot\n # There is no trackable status change for the instance being\n # rebooted, so it's up to CPI client to keep track of agent\n # being ready after reboot.\n # Due to this, we can't deregister the instance from any load\n # balancers it might be attached to, and reattach once the\n # reboot is complete, so we just have to let the load balancers\n # take the instance out of rotation, and put it back in once it\n # is back up again.\n @aws_instance.reboot\n end",
"def postBoot(instance_id = nil)\n if !instance_id.nil?\n @cloud_id = instance_id\n end\n node, config, deploydata = describe(cloud_id: @cloud_id)\n instance = cloud_desc\n raise MuError, \"Couldn't find instance #{@mu_name} (#{@cloud_id})\" if !instance\n @cloud_id = instance.instance_id\n return false if !MU::MommaCat.lock(instance.instance_id+\"-orchestrate\", true)\n return false if !MU::MommaCat.lock(instance.instance_id+\"-groom\", true)\n\n MU::MommaCat.createStandardTags(instance.instance_id, region: @config['region'], credentials: @config['credentials'])\n MU::MommaCat.createTag(instance.instance_id, \"Name\", node, region: @config['region'], credentials: @config['credentials'])\n\n if @config['optional_tags']\n MU::MommaCat.listOptionalTags.each { |key, value|\n MU::MommaCat.createTag(instance.instance_id, key, value, region: @config['region'], credentials: @config['credentials'])\n }\n end\n\n if !@config['tags'].nil?\n @config['tags'].each { |tag|\n MU::MommaCat.createTag(instance.instance_id, tag['key'], tag['value'], region: @config['region'], credentials: @config['credentials'])\n }\n end\n MU.log \"Tagged #{node} (#{instance.instance_id}) with MU-ID=#{MU.deploy_id}\", MU::DEBUG\n\n # Make double sure we don't lose a cached mu_windows_name value.\n if windows? or !@config['active_directory'].nil?\n if @mu_windows_name.nil?\n @mu_windows_name = deploydata['mu_windows_name']\n end\n end\n\n retries = -1\n max_retries = 30\n begin\n if instance.nil? or instance.state.name != \"running\"\n retries = retries + 1\n if !instance.nil? and instance.state.name == \"terminated\"\n raise MuError, \"#{@cloud_id} appears to have been terminated mid-bootstrap!\"\n end\n if retries % 3 == 0\n MU.log \"Waiting for EC2 instance #{node} (#{@cloud_id}) to be ready...\", MU::NOTICE\n end\n sleep 40\n # Get a fresh AWS descriptor\n instance = MU::Cloud::Server.find(cloud_id: @cloud_id, region: @config['region'], credentials: @config['credentials']).values.first\n if instance and instance.state.name == \"terminated\"\n raise MuError, \"EC2 instance #{node} (#{@cloud_id}) terminating during bootstrap!\"\n end\n end\n rescue Aws::EC2::Errors::ServiceError => e\n if retries < max_retries\n MU.log \"Got #{e.inspect} during initial instance creation of #{@cloud_id}, retrying...\", MU::NOTICE, details: instance\n retries = retries + 1\n retry\n else\n raise MuError, \"Too many retries creating #{node} (#{e.inspect})\"\n end\n end while instance.nil? or (instance.state.name != \"running\" and retries < max_retries)\n\n punchAdminNAT\n\n\n # If we came up via AutoScale, the Alarm module won't have had our\n # instance ID to associate us with itself. So invoke that here.\n # XXX might be possible to do this with regular alarm resources and\n # dependencies now\n if !@config['basis'].nil? and @config[\"alarms\"] and !@config[\"alarms\"].empty?\n @config[\"alarms\"].each { |alarm|\n alarm_obj = MU::MommaCat.findStray(\n \"AWS\",\n \"alarms\",\n region: @config[\"region\"],\n deploy_id: @deploy.deploy_id,\n name: alarm['name']\n ).first\n alarm[\"dimensions\"] = [{:name => \"InstanceId\", :value => @cloud_id}]\n\n if alarm[\"enable_notifications\"]\n topic_arn = MU::Cloud::AWS::Notification.createTopic(alarm[\"notification_group\"], region: @config[\"region\"], credentials: @config['credentials'])\n MU::Cloud::AWS::Notification.subscribe(arn: topic_arn, protocol: alarm[\"notification_type\"], endpoint: alarm[\"notification_endpoint\"], region: @config[\"region\"], credentials: @config[\"credentials\"])\n alarm[\"alarm_actions\"] = [topic_arn]\n alarm[\"ok_actions\"] = [topic_arn]\n end\n\n alarm_name = alarm_obj ? alarm_obj.cloud_id : \"#{node}-#{alarm['name']}\".upcase\n\n MU::Cloud::AWS::Alarm.setAlarm(\n name: alarm_name,\n ok_actions: alarm[\"ok_actions\"],\n alarm_actions: alarm[\"alarm_actions\"],\n insufficient_data_actions: alarm[\"no_data_actions\"],\n metric_name: alarm[\"metric_name\"],\n namespace: alarm[\"namespace\"],\n statistic: alarm[\"statistic\"],\n dimensions: alarm[\"dimensions\"],\n period: alarm[\"period\"],\n unit: alarm[\"unit\"],\n evaluation_periods: alarm[\"evaluation_periods\"],\n threshold: alarm[\"threshold\"],\n comparison_operator: alarm[\"comparison_operator\"],\n region: @config[\"region\"],\n credentials: @config['credentials']\n )\n }\n end\n\n # We have issues sometimes where our dns_records are pointing at the wrong node name and IP address.\n # Make sure that doesn't happen. Happens with server pools only\n if @config['dns_records'] && !@config['dns_records'].empty?\n @config['dns_records'].each { |dnsrec|\n if dnsrec.has_key?(\"name\")\n if dnsrec['name'].start_with?(MU.deploy_id.downcase) && !dnsrec['name'].start_with?(node.downcase)\n MU.log \"DNS records for #{node} seem to be wrong, deleting from current config\", MU::WARN, details: dnsrec\n dnsrec.delete('name')\n dnsrec.delete('target')\n end\n end\n }\n end\n\n # Unless we're planning on associating a different IP later, set up a\n # DNS entry for this thing and let it sync in the background. We'll come\n # back to it later.\n if @config['static_ip'].nil? && !@named\n MU::MommaCat.nameKitten(self)\n @named = true\n end\n\n if !@config['src_dst_check'] and !@config[\"vpc\"].nil?\n MU.log \"Disabling source_dest_check #{node} (making it NAT-worthy)\"\n MU::Cloud::AWS.ec2(region: @config['region'], credentials: @config['credentials']).modify_instance_attribute(\n instance_id: @cloud_id,\n source_dest_check: {:value => false}\n )\n end\n\n # Set console termination protection. Autoscale nodes won't set this\n # by default.\n MU::Cloud::AWS.ec2(region: @config['region'], credentials: @config['credentials']).modify_instance_attribute(\n instance_id: @cloud_id,\n disable_api_termination: {:value => true}\n )\n\n has_elastic_ip = false\n if !instance.public_ip_address.nil?\n begin\n resp = MU::Cloud::AWS.ec2(region: @config['region'], credentials: @config['credentials']).describe_addresses(public_ips: [instance.public_ip_address])\n if resp.addresses.size > 0 and resp.addresses.first.instance_id == @cloud_id\n has_elastic_ip = true\n end\n rescue Aws::EC2::Errors::InvalidAddressNotFound => e\n # XXX this is ok to ignore, it means the public IP isn't Elastic\n end\n end\n\n win_admin_password = nil\n ec2config_password = nil\n sshd_password = nil\n if windows?\n ssh_keydir = \"#{Etc.getpwuid(Process.uid).dir}/.ssh\"\n ssh_key_name = @deploy.ssh_key_name\n\n if @config['use_cloud_provider_windows_password']\n win_admin_password = getWindowsAdminPassword\n elsif @config['windows_auth_vault'] && !@config['windows_auth_vault'].empty?\n if @config[\"windows_auth_vault\"].has_key?(\"password_field\")\n win_admin_password = @groomer.getSecret(\n vault: @config['windows_auth_vault']['vault'],\n item: @config['windows_auth_vault']['item'],\n field: @config[\"windows_auth_vault\"][\"password_field\"]\n )\n else\n win_admin_password = getWindowsAdminPassword\n end\n\n if @config[\"windows_auth_vault\"].has_key?(\"ec2config_password_field\")\n ec2config_password = @groomer.getSecret(\n vault: @config['windows_auth_vault']['vault'],\n item: @config['windows_auth_vault']['item'],\n field: @config[\"windows_auth_vault\"][\"ec2config_password_field\"]\n )\n end\n\n if @config[\"windows_auth_vault\"].has_key?(\"sshd_password_field\")\n sshd_password = @groomer.getSecret(\n vault: @config['windows_auth_vault']['vault'],\n item: @config['windows_auth_vault']['item'],\n field: @config[\"windows_auth_vault\"][\"sshd_password_field\"]\n )\n end\n end\n\n win_admin_password = MU.generateWindowsPassword if win_admin_password.nil?\n ec2config_password = MU.generateWindowsPassword if ec2config_password.nil?\n sshd_password = MU.generateWindowsPassword if sshd_password.nil?\n\n # We're creating the vault here so when we run\n # MU::Cloud::Server.initialSSHTasks and we need to set the Windows\n # Admin password we can grab it from said vault.\n creds = {\n \"username\" => @config['windows_admin_username'],\n \"password\" => win_admin_password,\n \"ec2config_username\" => \"ec2config\",\n \"ec2config_password\" => ec2config_password,\n \"sshd_username\" => \"sshd_service\",\n \"sshd_password\" => sshd_password\n }\n @groomer.saveSecret(vault: @mu_name, item: \"windows_credentials\", data: creds, permissions: \"name:#{@mu_name}\")\n end\n\n subnet = nil\n if !@vpc.nil? and @config.has_key?(\"vpc\") and !instance.subnet_id.nil?\n subnet = @vpc.getSubnet(\n cloud_id: instance.subnet_id\n )\n if subnet.nil?\n raise MuError, \"Got null subnet id out of #{@config['vpc']} when asking for #{instance.subnet_id}\"\n end\n end\n\n if !subnet.nil?\n if !subnet.private? or (!@config['static_ip'].nil? and !@config['static_ip']['assign_ip'].nil?)\n if !@config['static_ip'].nil?\n if !@config['static_ip']['ip'].nil?\n public_ip = MU::Cloud::AWS::Server.associateElasticIp(instance.instance_id, classic: false, ip: @config['static_ip']['ip'])\n elsif !has_elastic_ip\n public_ip = MU::Cloud::AWS::Server.associateElasticIp(instance.instance_id)\n end\n end\n end\n\n nat_ssh_key, nat_ssh_user, nat_ssh_host, canonical_ip, ssh_user, ssh_key_name = getSSHConfig\n if subnet.private? and !nat_ssh_host and !MU::Cloud::AWS::VPC.haveRouteToInstance?(cloud_desc, region: @config['region'], credentials: @config['credentials'])\n raise MuError, \"#{node} is in a private subnet (#{subnet}), but has no NAT host configured, and I have no other route to it\"\n end\n\n # If we've asked for additional subnets (and this @config is not a\n # member of a Server Pool, which has different semantics), create\n # extra interfaces to accomodate.\n if !@config['vpc']['subnets'].nil? and @config['basis'].nil?\n device_index = 1\n @vpc.subnets { |subnet|\n subnet_id = subnet.cloud_id\n MU.log \"Adding network interface on subnet #{subnet_id} for #{node}\"\n iface = MU::Cloud::AWS.ec2(region: @config['region'], credentials: @config['credentials']).create_network_interface(subnet_id: subnet_id).network_interface\n MU::MommaCat.createStandardTags(iface.network_interface_id, region: @config['region'], credentials: @config['credentials'])\n MU::MommaCat.createTag(iface.network_interface_id, \"Name\", node+\"-ETH\"+device_index.to_s, region: @config['region'], credentials: @config['credentials'])\n\n if @config['optional_tags']\n MU::MommaCat.listOptionalTags.each { |key, value|\n MU::MommaCat.createTag(iface.network_interface_id, key, value, region: @config['region'], credentials: @config['credentials'])\n }\n end\n\n if !@config['tags'].nil?\n @config['tags'].each { |tag|\n MU::MommaCat.createTag(iface.network_interface_id, tag['key'], tag['value'], region: @config['region'], credentials: @config['credentials'])\n }\n end\n\n MU::Cloud::AWS.ec2(region: @config['region'], credentials: @config['credentials']).attach_network_interface(\n network_interface_id: iface.network_interface_id,\n instance_id: instance.instance_id,\n device_index: device_index\n )\n device_index = device_index + 1\n }\n end\n elsif !@config['static_ip'].nil?\n if !@config['static_ip']['ip'].nil?\n public_ip = MU::Cloud::AWS::Server.associateElasticIp(instance.instance_id, classic: true, ip: @config['static_ip']['ip'])\n elsif !has_elastic_ip\n public_ip = MU::Cloud::AWS::Server.associateElasticIp(instance.instance_id, classic: true)\n end\n end\n\n\n if !@config['image_then_destroy']\n notify\n end\n\n MU.log \"EC2 instance #{node} has id #{instance.instance_id}\", MU::DEBUG\n\n @config[\"private_dns_name\"] = instance.private_dns_name\n @config[\"public_dns_name\"] = instance.public_dns_name\n @config[\"private_ip_address\"] = instance.private_ip_address\n @config[\"public_ip_address\"] = instance.public_ip_address\n\n ext_mappings = MU.structToHash(instance.block_device_mappings)\n\n # Root disk on standard CentOS AMI\n # tagVolumes(instance.instance_id, \"/dev/sda\", \"Name\", \"ROOT-\"+MU.deploy_id+\"-\"+@config[\"name\"].upcase)\n # Root disk on standard Ubuntu AMI\n # tagVolumes(instance.instance_id, \"/dev/sda1\", \"Name\", \"ROOT-\"+MU.deploy_id+\"-\"+@config[\"name\"].upcase)\n\n # Generic deploy ID tag\n # tagVolumes(instance.instance_id)\n\n # Tag volumes with all our standard tags.\n # Maybe replace tagVolumes with this? There is one more place tagVolumes is called from\n volumes = MU::Cloud::AWS.ec2(region: @config['region'], credentials: @config['credentials']).describe_volumes(filters: [name: \"attachment.instance-id\", values: [instance.instance_id]])\n volumes.each { |vol|\n vol.volumes.each { |volume|\n volume.attachments.each { |attachment|\n MU::MommaCat.listStandardTags.each_pair { |key, value|\n MU::MommaCat.createTag(attachment.volume_id, key, value, region: @config['region'], credentials: @config['credentials'])\n\n if attachment.device == \"/dev/sda\" or attachment.device == \"/dev/sda1\"\n MU::MommaCat.createTag(attachment.volume_id, \"Name\", \"ROOT-#{MU.deploy_id}-#{@config[\"name\"].upcase}\", region: @config['region'], credentials: @config['credentials'])\n else\n MU::MommaCat.createTag(attachment.volume_id, \"Name\", \"#{MU.deploy_id}-#{@config[\"name\"].upcase}-#{attachment.device.upcase}\", region: @config['region'], credentials: @config['credentials'])\n end\n }\n\n if @config['optional_tags']\n MU::MommaCat.listOptionalTags.each { |key, value|\n MU::MommaCat.createTag(attachment.volume_id, key, value, region: @config['region'], credentials: @config['credentials'])\n }\n end\n\n if @config['tags']\n @config['tags'].each { |tag|\n MU::MommaCat.createTag(attachment.volume_id, tag['key'], tag['value'], region: @config['region'], credentials: @config['credentials'])\n }\n end\n }\n }\n }\n\n canonical_name = instance.public_dns_name\n canonical_name = instance.private_dns_name if !canonical_name or nat_ssh_host != nil\n @config['canonical_name'] = canonical_name\n\n if !@config['add_private_ips'].nil?\n instance.network_interfaces.each { |int|\n if int.private_ip_address == instance.private_ip_address and int.private_ip_addresses.size < (@config['add_private_ips'] + 1)\n MU.log \"Adding #{@config['add_private_ips']} extra private IP addresses to #{instance.instance_id}\"\n MU::Cloud::AWS.ec2(region: @config['region'], credentials: @config['credentials']).assign_private_ip_addresses(\n network_interface_id: int.network_interface_id,\n secondary_private_ip_address_count: @config['add_private_ips'],\n allow_reassignment: false\n )\n end\n }\n notify\n end\n\n begin\n if @config['groom'].nil? or @config['groom']\n if windows?\n # kick off certificate generation early; WinRM will need it\n cert, key = @deploy.nodeSSLCerts(self)\n if @config.has_key?(\"basis\")\n @deploy.nodeSSLCerts(self, true)\n end\n if !@groomer.haveBootstrapped?\n session = getWinRMSession(50, 60, reboot_on_problems: true)\n initialWinRMTasks(session)\n begin\n session.close\n rescue Exception\n # this is allowed to fail- we're probably rebooting anyway\n end\n else # for an existing Windows node: WinRM, then SSH if it fails\n begin\n session = getWinRMSession(1, 60)\n rescue Exception # yeah, yeah\n session = getSSHSession(1, 60)\n # XXX maybe loop at least once if this also fails?\n end\n end\n else\n session = getSSHSession(40, 30)\n initialSSHTasks(session)\n end\n end\n rescue BootstrapTempFail\n sleep 45\n retry\n ensure\n session.close if !session.nil? and !windows?\n end\n\n if @config[\"existing_deploys\"] && !@config[\"existing_deploys\"].empty?\n @config[\"existing_deploys\"].each { |ext_deploy|\n if ext_deploy[\"cloud_id\"]\n found = MU::MommaCat.findStray(\n @config['cloud'],\n ext_deploy[\"cloud_type\"],\n cloud_id: ext_deploy[\"cloud_id\"],\n region: @config['region'],\n dummy_ok: false\n ).first\n\n MU.log \"Couldn't find existing resource #{ext_deploy[\"cloud_id\"]}, #{ext_deploy[\"cloud_type\"]}\", MU::ERR if found.nil?\n @deploy.notify(ext_deploy[\"cloud_type\"], found.config[\"name\"], found.deploydata, mu_name: found.mu_name, triggering_node: @mu_name)\n elsif ext_deploy[\"mu_name\"] && ext_deploy[\"deploy_id\"]\n MU.log \"#{ext_deploy[\"mu_name\"]} / #{ext_deploy[\"deploy_id\"]}\"\n found = MU::MommaCat.findStray(\n @config['cloud'],\n ext_deploy[\"cloud_type\"],\n deploy_id: ext_deploy[\"deploy_id\"],\n mu_name: ext_deploy[\"mu_name\"],\n region: @config['region'],\n dummy_ok: false\n ).first\n\n MU.log \"Couldn't find existing resource #{ext_deploy[\"mu_name\"]}/#{ext_deploy[\"deploy_id\"]}, #{ext_deploy[\"cloud_type\"]}\", MU::ERR if found.nil?\n @deploy.notify(ext_deploy[\"cloud_type\"], found.config[\"name\"], found.deploydata, mu_name: ext_deploy[\"mu_name\"], triggering_node: @mu_name)\n else\n MU.log \"Trying to find existing deploy, but either the cloud_id is not valid or no mu_name and deploy_id where provided\", MU::ERR\n end\n }\n end\n\n # See if this node already exists in our config management. If it does,\n # we're done.\n if @groomer.haveBootstrapped?\n MU.log \"Node #{node} has already been bootstrapped, skipping groomer setup.\", MU::NOTICE\n if @config['groom'].nil? or @config['groom']\n @groomer.saveDeployData\n end\n MU::MommaCat.unlock(instance.instance_id+\"-orchestrate\")\n MU::MommaCat.unlock(instance.instance_id+\"-groom\")\n return true\n end\n\n begin\n @groomer.bootstrap if @config['groom'].nil? or @config['groom']\n rescue MU::Groomer::RunError\n MU::MommaCat.unlock(instance.instance_id+\"-groom\")\n MU::MommaCat.unlock(instance.instance_id+\"-orchestrate\")\n return false\n end\n\n # Make sure we got our name written everywhere applicable\n if !@named\n MU::MommaCat.nameKitten(self)\n @named = true\n end\n\n MU::MommaCat.unlock(instance.instance_id+\"-groom\")\n MU::MommaCat.unlock(instance.instance_id+\"-orchestrate\")\n return true\n end",
"def destroy_backend\n Rails.logger.info \"Removing tenant #{self.name} with tenant id #{self.uuid}.\"\n\n Rails.logger.info \"Undeploying all instances for tenant #{self.name}...\"\n # Delete all instances\n if self.instances.count > 0\n success = self.instances.each {|i| i.undeploy }\n if success\n Rails.logger.info \"Removed all instances for tenant #{self.name}.\"\n else\n Rails.logger.error \"Could not remove instance during project deletion:\"\n Rails.logger.error \"Instance: #{i.name} #{i.id} #{i.uuid}\"\n return false\n end\n end\n\n compute_c = get_connection(\"compute\")\n network_c = get_connection(\"network\")\n identity_c = get_connection(\"identity\")\n\n # Unallocate floating ips\n floating_ips = compute_c.get_floating_ips\n floating_ips.each do |ip|\n Rails.logger.info \"Deleting floating ip #{ip.ip} with id #{ip.id}\"\n compute_c.delete_floating_ip(ip.id)\n end\n\n routers = network_c.list_routers.select {|router| router.tenant_id == self.uuid}\n subnets = network_c.list_subnets.select {|subnet| subnet.tenant_id == self.uuid}\n networks = network_c.list_networks.select {|network| network.tenant_id == self.uuid}\n\n # Clear all router gateways\n routers.each do |router|\n Rails.logger.info \"Clearing router gateway for #{router.name} with id #{router.id}.\"\n # Remove gateway from the router\n network_c.update_router(router.id, {\"external_gateway_info\" => {}})\n end\n\n # loop through each network\n # For each router, remove any subnet interfaces\n networks.each do |network|\n subnets.select {|subnet| subnet.network_id == network.id}.each do |subnet|\n routers.each do |router|\n begin\n Rails.logger.info \"Attempting to remove router interface for subnet #{subnet.name} with id #{subnet.id} from router #{router.name} with id #{router.id}.\"\n network_c.remove_router_interface(router.id, subnet.id)\n Rails.logger.info \"Successfully removed router interface for subnet #{subnet.name}.\"\n rescue => e\n Rails.logger.error \"Tried to remove router interface for subnet #{subnet.name} with id #{subnet.id} from router #{router.name} with id #{router.id}.\"\n end\n end\n end\n end\n\n # Delete all subnets\n subnets.each do |subnet|\n Rails.logger.info \"Deleting subnet #{subnet.name} with id #{subnet.id}\"\n network_c.delete_subnet(subnet.id)\n end\n\n # Delete all routers\n routers.each do |router|\n Rails.logger.info \"Deleting router #{router.name} with id #{router.id}\"\n network_c.delete_router(router.id)\n end\n\n # Delete all networks\n networks.each do |network|\n Rails.logger.info \"Deleting network #{network.name} with id #{network.id}\"\n network_c.delete_network(network.id)\n end\n\n # Finally, delete the tenant\n Rails.logger.info \"Deleting tenant #{self.name} with id #{self.uuid}\"\n identity_c.delete_tenant(self.uuid)\n\n Rails.logger.info \"Removal of tenant #{self.name} on the OpenStack backend succeeded.\"\n end",
"def boot\n # Raise an exception if the limit of vms is reachable\n raise Exceptions::NextDeployException.new(\"Vms limit is reachable\") if Vm.count > Rails.application.config.limit_vm\n\n osapi = Apiexternal::Osapi.new\n\n begin\n self.name = vm_name\n self.technos = project.technos if technos.size == 0\n self.status = 0\n generate_hiera\n user_data = generate_userdata\n sshname = user.sshkeys.first ? user.sshkeys.first.shortname : ''\n self.nova_id = osapi.boot_vm(name, systemimage.glance_id, sshname, vmsize.title, user_data)\n save\n generate_authorizedkeys\n rescue Exceptions::NextDeployException => me\n self.status = 1\n save\n me.log_e\n end\n\n # Wait that vm is well running\n sleep(15)\n init_extra_attr\n # if foatingip is not yet setted by openstack, sleep 15s more\n if @floating_ip.nil?\n sleep(15)\n init_extra_attr\n end\n\n generate_host_all\n end",
"def puppetRunBatch(cluster, layer, interval)\n\n epoch = Time.now.to_i\n\n mc = rpcclient \"puppet\"\n mc.compound_filter \"deploop_collection=#{cluster} and deploop_category=/.*#{layer}/\"\n mc.progress = false\n\n nodes = mc.discover\n nodes = mc.discover.sort\n\n puts \"Deploying Puppet Run for nodes:\"\n puts nodes\n\n result = mc.runonce(:forcerun => true, :batch_size => interval)\n waitPuppetRun = Thread.new{checkForPuppetRun nodes, epoch}\n puts 'waiting for puppet run all catalog finished'\n\n waitPuppetRun.join\n puts 'DONE!'\n end",
"def deregister_instances_from_load_balancer(instance_ids, lb_name)\n params = Fog::AWS.indexed_param('Instances.member.%d.InstanceId', [*instance_ids])\n request({\n 'Action' => 'DeregisterInstancesFromLoadBalancer',\n 'LoadBalancerName' => lb_name,\n :parser => Fog::Parsers::AWS::ELB::DeregisterInstancesFromLoadBalancer.new\n }.merge!(params))\n end",
"def wait(timeout = 60)\n Timeout::timeout(timeout) do\n deployments = nil\n while deployments.nil? or deployments.select{|e| e.id == deploymentId}.size > 0 do\n sleep(RECHECK_INTERVAL)\n deployments = Marathon::Deployment.list\n end\n end\n end",
"def get_available_host\n @hosts.each do |host|\n return host if ws_running?([host]) < @ws_limit\n end\n puts \"No host available! Providing a new one on aws\"\n json = `aws ec2 run-instances --image-id ami-689cc908 --instance-type t2.medium --key-name mior --security-group-id sg-5bb3af3f`\n json = JSON.parse(json)\n internal_ip = json[\"Instances\"][0][\"NetworkInterfaces\"][0][\"PrivateIpAddress\"]\n public_ip = nil\n while public_ip.nil?\n cmd = \"aws ec2 describe-instances --filter \\\"Name=private-ip-address, Values=#{internal_ip}\\\"\"\n json = JSON.parse(`#{cmd}`)\n public_ip = json[\"Reservations\"][0][\"Instances\"][0][\"NetworkInterfaces\"][0][\"Association\"][\"PublicIp\"]\n end\n puts \"New instance on aws: #{public_ip}\"\n @hosts.push(public_ip)\n puts 'Waiting the host powers up..'\n sleep 30\n public_ip\n # The elegant way should be instantiate a new host to receive more requests\n end",
"def postBoot(instance_id = nil)\n if !instance_id.nil?\n @cloud_id = instance_id\n end\n\n node, _config, deploydata = describe(cloud_id: @cloud_id)\n instance = cloud_desc\n raise MuError, \"Couldn't find instance of #{@mu_name} (#{@cloud_id})\" if !instance\n return false if !MU::MommaCat.lock(@cloud_id+\"-orchestrate\", true)\n return false if !MU::MommaCat.lock(@cloud_id+\"-groom\", true)\n\n# MU::Cloud::AWS.createStandardTags(@cloud_id, region: @config['region'])\n# MU::Cloud::AWS.createTag(@cloud_id, \"Name\", node, region: @config['region'])\n#\n# if @config['optional_tags']\n# MU::MommaCat.listOptionalTags.each { |key, value|\n# MU::Cloud::AWS.createTag(@cloud_id, key, value, region: @config['region'])\n# }\n# end\n#\n# if !@config['tags'].nil?\n# @config['tags'].each { |tag|\n# MU::Cloud::AWS.createTag(@cloud_id, tag['key'], tag['value'], region: @config['region'])\n# }\n# end\n# MU.log \"Tagged #{node} (#{@cloud_id}) with MU-ID=#{MU.deploy_id}\", MU::DEBUG\n#\n # Make double sure we don't lose a cached mu_windows_name value.\n if windows? or !@config['active_directory'].nil?\n if @mu_windows_name.nil?\n @mu_windows_name = deploydata['mu_windows_name']\n end\n end\n\n# punchAdminNAT\n#\n#\n# # If we came up via AutoScale, the Alarm module won't have had our\n# # instance ID to associate us with itself. So invoke that here.\n# if !@config['basis'].nil? and @config[\"alarms\"] and !@config[\"alarms\"].empty?\n# @config[\"alarms\"].each { |alarm|\n# alarm_obj = MU::MommaCat.findStray(\n# \"AWS\",\n# \"alarms\",\n# region: @config[\"region\"],\n# deploy_id: @deploy.deploy_id,\n# name: alarm['name']\n# ).first\n# alarm[\"dimensions\"] = [{:name => \"InstanceId\", :value => @cloud_id}]\n#\n# if alarm[\"enable_notifications\"]\n# topic_arn = MU::Cloud::AWS::Notification.createTopic(alarm[\"notification_group\"], region: @config[\"region\"])\n# MU::Cloud::AWS::Notification.subscribe(arn: topic_arn, protocol: alarm[\"notification_type\"], endpoint: alarm[\"notification_endpoint\"], region: @config[\"region\"])\n# alarm[\"alarm_actions\"] = [topic_arn]\n# alarm[\"ok_actions\"] = [topic_arn]\n# end\n#\n# alarm_name = alarm_obj ? alarm_obj.cloud_id : \"#{node}-#{alarm['name']}\".upcase\n#\n# MU::Cloud::AWS::Alarm.setAlarm(\n# name: alarm_name,\n# ok_actions: alarm[\"ok_actions\"],\n# alarm_actions: alarm[\"alarm_actions\"],\n# insufficient_data_actions: alarm[\"no_data_actions\"],\n# metric_name: alarm[\"metric_name\"],\n# namespace: alarm[\"namespace\"],\n# statistic: alarm[\"statistic\"],\n# dimensions: alarm[\"dimensions\"],\n# period: alarm[\"period\"],\n# unit: alarm[\"unit\"],\n# evaluation_periods: alarm[\"evaluation_periods\"],\n# threshold: alarm[\"threshold\"],\n# comparison_operator: alarm[\"comparison_operator\"],\n# region: @config[\"region\"]\n# )\n# }\n# end\n#\n# # We have issues sometimes where our dns_records are pointing at the wrong node name and IP address.\n# # Make sure that doesn't happen. Happens with server pools only\n# if @config['dns_records'] && !@config['dns_records'].empty?\n# @config['dns_records'].each { |dnsrec|\n# if dnsrec.has_key?(\"name\")\n# if dnsrec['name'].start_with?(MU.deploy_id.downcase) && !dnsrec['name'].start_with?(node.downcase)\n# MU.log \"DNS records for #{node} seem to be wrong, deleting from current config\", MU::WARN, details: dnsrec\n# dnsrec.delete('name')\n# dnsrec.delete('target')\n# end\n# end\n# }\n# end\n\n # Unless we're planning on associating a different IP later, set up a\n # DNS entry for this thing and let it sync in the background. We'll\n # come back to it later.\n if @config['static_ip'].nil? && !@named\n MU::MommaCat.nameKitten(self)\n @named = true\n end\n\n _nat_ssh_key, _nat_ssh_user, nat_ssh_host, _canonical_ip, _ssh_user, _ssh_key_name = getSSHConfig\n if !nat_ssh_host and !MU::Cloud.resourceClass(\"Google\", \"VPC\").haveRouteToInstance?(cloud_desc, credentials: @config['credentials'])\n# XXX check if canonical_ip is in the private ranges\n# raise MuError, \"#{node} has no NAT host configured, and I have no other route to it\"\n end\n\n # See if this node already exists in our config management. If it does,\n # we're done.\n if @groomer.haveBootstrapped?\n MU.log \"Node #{node} has already been bootstrapped, skipping groomer setup.\", MU::NOTICE\n @groomer.saveDeployData\n MU::MommaCat.unlock(@cloud_id+\"-orchestrate\")\n MU::MommaCat.unlock(@cloud_id+\"-groom\")\n return true\n end\n\n @groomer.bootstrap\n\n # Make sure we got our name written everywhere applicable\n if !@named\n MU::MommaCat.nameKitten(self)\n @named = true\n end\n\n MU::MommaCat.unlock(@cloud_id+\"-groom\")\n MU::MommaCat.unlock(@cloud_id+\"-orchestrate\")\n return true\n end",
"def remove_instance(instance)\n deregister_response = client.deregister_instances_from_load_balancer(load_balancer_name: name,\n instances: [{instance_id: instance.ec2_instance_id}])\n remaining_instance_count = deregister_response.instances.size\n puts \"Removed #{instance.hostname} from ELB #{name}. Remaining instances: #{remaining_instance_count}\".light_blue\n _wait_for_connection_draining\n end",
"def createEc2Instance\n\n instance_descriptor = {\n :image_id => @config[\"image_id\"],\n :key_name => @deploy.ssh_key_name,\n :instance_type => @config[\"size\"],\n :disable_api_termination => true,\n :min_count => 1,\n :max_count => 1\n }\n\n instance_descriptor[:iam_instance_profile] = getIAMProfile\n\n security_groups = myFirewallRules.map { |fw| fw.cloud_id }\n if security_groups.size > 0\n instance_descriptor[:security_group_ids] = security_groups\n else\n raise MuError, \"Didn't get any security groups assigned to be in #{@mu_name}, that shouldn't happen\"\n end\n\n if @config['private_ip']\n instance_descriptor[:private_ip_address] = @config['private_ip']\n end\n\n if !@vpc.nil? and @config.has_key?(\"vpc\")\n subnet = mySubnets.sample\n if subnet.nil?\n raise MuError, \"Got null subnet id out of #{@config['vpc']}\"\n end\n MU.log \"Deploying #{@mu_name} into VPC #{@vpc.cloud_id} Subnet #{subnet.cloud_id}\"\n allowBastionAccess\n instance_descriptor[:subnet_id] = subnet.cloud_id\n end\n\n if !@userdata.nil? and !@userdata.empty?\n instance_descriptor[:user_data] = Base64.encode64(@userdata)\n end\n\n MU::Cloud::AWS::Server.waitForAMI(@config[\"image_id\"], region: @region, credentials: @credentials)\n\n instance_descriptor[:block_device_mappings] = MU::Cloud::AWS::Server.configureBlockDevices(image_id: @config[\"image_id\"], storage: @config['storage'], region: @region, credentials: @credentials)\n\n instance_descriptor[:monitoring] = {enabled: @config['monitoring']}\n\n if @tags and @tags.size > 0\n instance_descriptor[:tag_specifications] = [{\n :resource_type => \"instance\",\n :tags => @tags.keys.map { |k|\n { :key => k, :value => @tags[k] }\n }\n }]\n end\n\n MU.log \"Creating EC2 instance #{@mu_name}\", details: instance_descriptor\n\n instance = resp = nil\n loop_if = Proc.new {\n instance = resp.instances.first if resp and resp.instances\n resp.nil? or resp.instances.nil? or instance.nil?\n }\n\n bad_subnets = []\n mysubnet_ids = if mySubnets\n mySubnets.map { |s| s.cloud_id }\n end\n begin\n MU.retrier([Aws::EC2::Errors::InvalidGroupNotFound, Aws::EC2::Errors::InvalidSubnetIDNotFound, Aws::EC2::Errors::InvalidParameterValue], loop_if: loop_if, loop_msg: \"Waiting for run_instances to return #{@mu_name}\") {\n resp = MU::Cloud::AWS.ec2(region: @region, credentials: @credentials).run_instances(instance_descriptor)\n }\n rescue Aws::EC2::Errors::Unsupported => e\n bad_subnets << instance_descriptor[:subnet_id]\n better_subnet = (mysubnet_ids - bad_subnets).sample\n if e.message !~ /is not supported in your requested Availability Zone/ and\n (mysubnet_ids.nil? or mysubnet_ids.empty? or\n mysubnet_ids.size == bad_subnets.size or\n better_subnet.nil? or better_subnet == \"\")\n raise MuError.new e.message, details: mysubnet_ids\n end\n instance_descriptor[:subnet_id] = (mysubnet_ids - bad_subnets).sample\n if instance_descriptor[:subnet_id].nil?\n raise MuError.new \"Specified subnet#{bad_subnets.size > 1 ? \"s do\" : \" does\"} not support instance type #{instance_descriptor[:instance_type]}\", details: bad_subnets\n end\n MU.log \"One or more subnets does not support instance type #{instance_descriptor[:instance_type]}, attempting with #{instance_descriptor[:subnet_id]} instead\", MU::WARN, details: bad_subnets\n retry\n rescue Aws::EC2::Errors::InvalidRequest => e\n MU.log e.message, MU::ERR, details: instance_descriptor\n raise e\n end\n\n MU.log \"#{@mu_name} (#{instance.instance_id}) coming online\"\n\n instance\n end",
"def when_no_pending_instances(&block)\n reset! \n if list_of_pending_instances.size == 0\n block.call if block\n else\n vprint \".\"\n wait \"5.seconds\"\n when_no_pending_instances(&block)\n end\n end",
"def wait_for_completion\n until terminated? do\n Kernel.sleep(Gosen::DeploymentRun::POLLING_TIME)\n @deployment_resource.reload\n end\n raise Gosen::Error.new(\"Deployment error: #{@deployment_resource['output']}\") if @deployment_resource['status'] == 'error'\n end",
"def restart_cluster\n #stop balancing hbase tables in order to restart nodes\n run_balancer(false)\n\n region_servers.each { |region_server|\n unless move_regions(region_server) then\n raise \"unable to move regions #{region_server}\"\n end\n\n unless restart_region_server(region_server) then\n raise \"unable to restart RS #{region_server}\"\n end\n }\n\n run_balancer(true)\n end",
"def start!\n\n # Best thing to avoid run conditions are to wait\n sleep rand(10)\n\n # Find out who is who, instances alive\n # If discover() returns an Array full of nil(s), alive will become an empty Array\n alive = cleanup(@aws.discover())\n\n # Given the alive instances, find our prefix\n # If alive an empty array, selection will return the number '1'\n @prefix = ensurezero(selection(alive))\n\n # Put together hostname/fqdn\n construction()\n\n # Set the Name tag on this instance\n @aws.settag!(@hostname)\n\n # Find out who is who, instances alive\n # If discover() returns an Array full of nil(s), alive will become an empty Array\n alive = cleanup(@aws.discover())\n\n # Only enter recursion if the uniq() length of the alive array does not equal the actual length\n # On AutoScalingGroup initalization, the cleanup() should ensure the alive array is empty not nil so uniq() works\n unless alive.uniq.length == alive.length\n # There are duplicates, remove tag, wait, restart\n @aws.removetag!()\n sleep rand(10)\n start!()\n end\n\n # Register in DNS\n @aws.setroute53(@options[:zone], @fqdn)\n\n # Set the localhost hostname\n setlocal()\n\n # Set /etc/hosts\n sethostsfile()\n\n # Throw the hostname in /etc/sysconfig/httpd (if exists)\n givetohttpd()\n\n # All done\n finish!()\n end",
"def catch_up\n Log.error LOG_COMP, 'Catching up...'\n\n @srv_pool.info_all\n\n @srv_pool.each do |service|\n recover_action(nil, service.id) if service.transient_state?\n end\n end",
"def run\n ready_nodes = each_ready_task.to_a.join ', '\n info \"Starting the deployment process. Starting tasks: #{ready_nodes}\"\n hook 'internal_pre_run'\n hook 'pre_run'\n topology_sort\n result = loop do\n if all_nodes_are_successful?\n status = 'All nodes are deployed successfully. '\\\n 'Stopping the deployment process!'\n result = {\n :success => true,\n :status => status,\n }\n break result\n end\n gracefully_stop! \"failed_critical_nodes: #{failed_critical_nodes.inspect}\" if has_failed_critical_nodes?\n\n if all_nodes_are_finished?\n status = \"All nodes are finished. Failed tasks: \"\\\n \"#{failed_tasks.join ', '} Stopping the \"\\\n \"deployment process!\"\n result = if has_failed_critical_nodes?\n {\n :success => false,\n :status => status,\n :failed_nodes => failed_nodes,\n :skipped_nodes => skipped_nodes,\n :failed_tasks => failed_tasks\n }\n else\n {\n :success => true,\n :status => status,\n :failed_nodes => failed_nodes,\n :skipped_nodes => skipped_nodes,\n :failed_tasks => failed_tasks\n }\n end\n break result\n end\n # run loop over all nodes\n process_all_nodes\n end\n info result[:status]\n hook 'post_run', result\n result\n end",
"def elb_registration_check(type)\n details = obj_behavior(@elb, :describe_load_balancers, @elb_name)\n instances = details.first[:instances]\n case type\n when :all\n @servers.each do |server|\n obj_behavior(server, :settings)\n aws_id = server[\"aws-id\"]\n unless obj_behavior(instances, :include?, aws_id)\n raise \"ERROR: Did not find aws id for #{aws_id}. ID list: #{instances.inspect}\"\n end\n end\n when :none\n unless obj_behavior(instances, :empty?)\n raise \"ERROR: found registered instances when there should be none. ID list: #{instances.inspect}\"\n end\n else\n raise \"ERROR: only check types of :none and :all are currently supported\" \n end\n end",
"def run\n ngen_auth\n @validate = Validator.new\n stack = EcoSystem.new\n @instanceparameters = stack.yaml_reader(config[:yaml])\n stack.validate = @validate\n config[:action] = 'create'\n stack.options = config\n stack.supress_output ='1'\n stack.instanceparameters = @instanceparameters\n inst_result = stack.opt_parse\n ho_hum\n \n inst_result.each do |server|\n config[:inst] = server['server']['display_name']\n instance = {}\n # puts chef_attrs = server['server']['userdata'].at(0)['chef']\n chef_attrs = server['server']['userdata'].at(0)['chef'] if !server['server']['userdata'].at(0)['chef'].nil?\n chef_attrs.each do |attr, value|\n instance[attr] = value\n end\n chef_node_configuration(instance)\n config[:chef_node_name] = config[:inst]\n inst_details = AttrFinder.new(server)\n inst_details.options = config\n inst_details.validate = @validate\n inst_details.function = 'server' \n inst = InstanceClient.new\n inst.validate = @validate\n inst.options = config\n inst.supress_output ='1'\n inst.instanceparameters = @instanceparameters\n ssh_host = inst.list_instance_ip(inst_details.compartment, inst_details.instance).at(1)\n bootstrap_for_linux_node(ssh_host).run\n node_attributes(ssh_host, 'IaaS')\n end\n end",
"def cleanup()\n attempts = @options[:timeout].to_i / SLEEPWAIT\n start = Time.now\n\n @gce_helper.delete_firewall(@firewall, start, attempts)\n\n @hosts.each do |host|\n @gce_helper.delete_instance(host['vmhostname'], start, attempts)\n @logger.debug(\"Deleted Google Compute instance #{host['vmhostname']} for #{host.name}\")\n @gce_helper.delete_disk(host['diskname'], start, attempts)\n @logger.debug(\"Deleted Google Compute disk #{host['diskname']} for #{host.name}\")\n end\n\n end",
"def graceful_shutdown\n while reap_dead_workers(\"shutdown\") > 0\n logger.error \"Waiting for #{@workers.list.length} requests to finish, could take #{@timeout + @throttle} seconds.\"\n sleep @timeout / 10\n end\n end",
"def deregister_instances_from_lb(lb_name, instance_ids)\n instances = instance_ids.map { |instance_id| { :instance_id => instance_id } }\n link = generate_request(\"DeregisterInstancesFromLoadBalancer\",\n :load_balancer_name => lb_name, :instances => instances\n )\n request_info(link, QElbInstancesParser.new)\n rescue Exception\n on_exception\n end",
"def aws_wait_for_peers\n loop do\n aws_find_peers\n\n Chef::Log.info(\"etcd_service[#{ new_resource.name }] Found \"\\\n \"#{ new_resource.peers.length + 1 }/#{ new_resource.quorum } AWS \"\\\n \"peers, #{ active_peers.length } active\")\n\n break if new_resource.peers.length >= (new_resource.quorum - 1)\n break if active_peers.length > 0\n sleep 5\n end\n end",
"def run!()\n\t\t\tif(@options[:elb])\n\t\t\t\tprocess_elbs()\n\t\t\tend\n\t\t\tnext_precience()\n\t\t\tif(@options[:ec2_tags])\n\t\t\t\t@options[:ec2_tags].each do |tag_name|\n\t\t\t\t\tprocess_ec2_tag_name(tag_name)\n\t\t\t\t\tnext_precience()\n\t\t\t\tend\n\t\t\tend\n\t\t\treduce_dns_pool()\n\t\t\tprocess_zone_updates()\n\t\t\treturn nil\n\t\tend",
"def reboot_instances(*instances)\n instances = instances.flatten\n link = generate_request(\"RebootInstances\", amazonize_list('InstanceId', instances))\n request_info(link, RightBoolResponseParser.new(:logger => @logger))\n rescue Exception\n on_exception\n end",
"def aws_terminate_instance_and_ebs_volumes( iprops )\n ec2 = AWS::EC2.new.regions[ iprops[ :region ] ]\n inst = ec2.instances[ iprops[ :id ] ]\n unless inst.exists?\n raise \"Instance #{iprops[:id]} does not exist in #{iprops[:region]}\"\n end\n\n ebs_volumes = inst.block_devices.map do |dev|\n ebs = dev[ :ebs ]\n if ebs && dev[:device_name] =~ /dh\\d+$/ && !ebs[:delete_on_termination]\n ebs[ :volume_id ]\n end\n end.compact\n\n inst.terminate\n wait_until( \"termination of #{inst.id}\", 2.0 ) { inst.status == :terminated }\n\n ebs_volumes = ebs_volumes.map do |vid|\n volume = ec2.volumes[ vid ]\n if volume.exists?\n volume\n else\n puts \"WARN: #{volume} doesn't exist\"\n nil\n end\n end.compact\n\n ebs_volumes.each do |vol|\n wait_until( \"deletion of vol #{vol.id}\" ) do\n vol.status == :available || vol.status == :deleted\n end\n vol.delete if vol.status == :available\n end\n\n found = aws_find_instance( iprops )\n if found\n aws_instance_removed( found )\n aws_write_instances\n end\n end",
"def start\n\n @settings['accounts'].each do |account,keys|\n\n puts \"Account: #{account}\"\n @aws_access_key_id = keys['access_key_id']\n @aws_secret_access_key = keys['secret_access_key']\n\n # Find all servers with tags matching the supplied Hash\n find_instances(@tags).each do |server|\n\n # Begin snapshotting each volume attached to the server\n #\n server.block_device_mapping.each do |block_device|\n\n log \"\\e[0;32m Searching for matching snapshots \\e[0m(#{server.id}:#{block_device})..\"\n snapshots = volume_snapshots(block_device['volumeId'])\n\n # Create each type of backup we'll be using\n #\n %w(hourly daily weekly monthly).each do |snapshot_type|\n\n # Build snapshot history for the working volume and return all snapshots\n # matching our particular snapshot type\n history = snapshots.select do |snapshot|\n snapshot.tags['snapshot_type'] == snapshot_type &&\n snapshot.tags['volume_id'] == block_device['volumeId'] &&\n snapshot.tags['protected'] == 'false'\n end\n\n history.sort_by! { |snapshot| snapshot.created_at }\n\n unless too_soon?(history,snapshot_type) || instance_variable_get(\"@#{snapshot_type}_snapshots\") == 0\n\n # Check against threshold limits for backup history and delete as needed\n #\n while history.size >= instance_variable_get(\"@#{snapshot_type}_snapshots\")\n delete_snapshot(history.first.id)\n history.delete(history.first)\n end\n\n log \"Creating #{snapshot_type} for #{block_device['volumeId']}..\"\n create_snapshot({\n 'volume_id' => block_device['volumeId'],\n 'snapshot_type' => snapshot_type,\n 'description' => \"Snapshot::#{snapshot_type.capitalize}> Server: #{server.id}\",\n 'tags' => {\n 'snapshot_time' => \"#{Time.now}\",\n 'snapshot_type' => snapshot_type,\n 'instance_id' => server.id,\n 'volume_id' => block_device['volumeId'],\n 'deviceName' => block_device['deviceName'],\n 'protected' => 'false'\n }\n })\n end\n end\n end\n end\n end\n\n end",
"def deploy()\n connection.nodes.deploy(uuid).tap{ self.forget }\n end",
"def request_termination\n instance_id = AlgRunner.fetch_url(INSTANCE_ID_URL)\n\n logger.info { \"Requesting terminating for #{instance_id}\" }\n @bunny.queue INSTANCE_SERVICE_QUEUE\n @bunny.exchange('').publish(\n { :instance_id => instance_id.to_s, :action => :termination }.to_yaml, \n :key => INSTANCE_SERVICE_QUEUE, :routing_key => INSTANCE_SERVICE_QUEUE\n )\n end",
"def init_instances\n instances = []\n next_token = nil\n all_records_retrieved = false\n\n until all_records_retrieved\n response = @@client.describe_instances({\n next_token: next_token\n })\n next_token = response.next_token\n all_records_retrieved = next_token.nil? || next_token.empty?\n instances << response.reservations.map { |r| r.instances }\n end\n\n instances.flatten\n end",
"def bootstrap\n hpool = OpenNebula::HostPool.new(@client)\n rc = hpool.info\n\n if OpenNebula.is_error?(rc)\n # Wait 5 seconds and retry\n sleep 5\n rc = hpool.info\n if OpenNebula.is_error?(rc)\n raise \"Could not get hosts information - #{rc.message}\"\n end\n end\n\n $logger.info('Bootstraping list of clusters')\n\n hpool.each do |h|\n next if h['IM_MAD'] != 'vcenter' || h['STATE'] == '8' # offline\n\n $logger.info(\"Adding host #{h.name} (#{h.id})\")\n\n add(h.id, nil)\n end\n end",
"def bootstrap_server\n bootstrap_config\n\n bootstrap_init\n bootstrap_run\n bootstrap_cleanup\n rescue Hazetug::Exception => e\n ui.error(e.message); 1\n ensure \n knife and knife.ui.stdout.close\n end",
"def boot\n if self.stopped?\n self.status = \"booting\"\n # delayed_job, 5.times sleep 10 sec, print to /scenarios/#{1}\n debug \"Booting scenario...\"\n\n \n # Boot Clouds\n self.clouds.each { |cloud| cloud.boot }\n \n # Final Setup\n self.final_setup\n self.status = \"booted\"\n self.save!\n end\n end",
"def terminate(instance, decrement=false)\n Log.log \"Detaching #{instance.instance_id.light_yellow} from ASG\"\n client.detach_instances(\n instance_ids: [ instance.instance_id ],\n auto_scaling_group_name: asg_name,\n should_decrement_desired_capacity: false)\n\n # need to describe the instance status in the asg here so that we wait till connections have drained.\n count = 0\n Log.log \"Awaiting connection draining... \", newline: false\n while present?(instance.instance_id) && count < 120\n sleep 1\n count += 1\n end\n Log.log \"done\", timestamp: false\n\n Log.log \"Terminating #{instance.instance_id.light_red}... \", newline: false\n ec2_client.terminate_instances(instance_ids: [ instance.instance_id ])\n Log.log \"done\", timestamp: false\n end",
"def cleanup\n @logger.notify \"Cleaning up OpenStack\"\n @vms.each do |vm|\n cleanup_storage(vm)\n @logger.debug \"Release floating IPs for OpenStack host #{vm.name}\"\n floating_ips = vm.all_addresses # fetch and release its floating IPs\n floating_ips.each do |address|\n @compute_client.disassociate_address(vm.id, address['ip'])\n @compute_client.release_address(address['id'])\n end\n @logger.debug \"Destroying OpenStack host #{vm.name}\"\n vm.destroy\n if @options[:openstack_keyname].nil?\n @logger.debug \"Deleting random keypair\"\n @compute_client.delete_key_pair vm.name\n end\n end\n end",
"def bootstrap_post\n # only create if no other netwroks\n if Network.where(:name=>Network::ADMIN_NET).count == 0\n deployment = Deployment.system\n Network.transaction do\n # admin network\n net = Network.create :name=>Network::ADMIN_NET, :description=>I18n.t('support.bootstrap.admin_net'), :deployment_id=>deployment.id, :conduit=>Network::DEFAULTCONDUIT, :v6prefix => Network::V6AUTO\n NetworkRange.create :name=>'admin', :network_id=>net.id, :first=>\"192.168.124.10/24\", :last=>\"192.168.124.11/24\"\n NetworkRange.create :name=>'dhcp', :network_id=>net.id, :first=>\"192.168.124.21/24\", :last=>\"192.168.124.80/24\"\n NetworkRange.create :name=>'host', :network_id=>net.id, :first=>\"192.168.124.81/24\", :last=>\"192.168.124.254/24\"\n # bmc network\n bmc = Network.create :name=>Network::BMC_NET, :description=>I18n.t('support.bootstrap.bmc_net'), :deployment_id=>deployment.id, :conduit=>Network::BMCCONDUIT, :v6prefix => Network::V6AUTO\n NetworkRange.create :name=>'admin', :network_id=>bmc.id, :first=>\"192.168.128.10/24\", :last=>\"192.168.128.20/24\"\n NetworkRange.create :name=>'host', :network_id=>bmc.id, :first=>\"192.168.128.21/24\", :last=>\"192.168.128.254/24\"\n\n end\n end\n end",
"def stop_all(wait=true)\n if script_to_run?('terminate')\n options = { \"DB_TERMINATE_SAFETY\" => \"text:off\" }\n run_script_on_set('terminate', @servers.select { |s| s.state != 'stopped' }, wait, options)\n # @servers.each { |s|run_script('terminate', s, options) unless s.state == 'stopped' }\n else\n @servers.each { |s| obj_behavior(s, :stop) }\n end\n \n wait_for_all(\"stopped\") if wait\n # unset dns in our local cached copy..\n @servers.each { |s| s.params['dns-name'] = nil } \n end",
"def apply(iteration)\n return if DateTime.now < @next_check\n @next_check = @next_update.call\n\n @gears.each do |uuid|\n path = PathUtils.join(@config.get('GEAR_BASE_DIR', '/var/lib/openshift'), uuid, '.env', 'OPENSHIFT_GEAR_DNS')\n unless File.file? path\n Syslog.warning(\"watchman unable to determine application setup for gear #{uuid}. #{path} missing.\")\n end\n end\n end",
"def reboot_instances(list)\n link = generate_request(\"RebootInstances\", hash_params('InstanceId', list.to_a))\n request_info(link, RightBoolResponseParser.new(:logger => @logger))\n rescue Exception\n on_exception\n end",
"def monitor_all_vms\n totalmemory = 0\n totalcpu = 0\n\n # Get last cloudwatch monitoring time\n host_obj = OpenNebula::Host.new_with_id(@host_id,\n OpenNebula::Client.new)\n host_obj.info\n cw_mon_time = host_obj[\"/HOST/TEMPLATE/CWMONTIME\"]\n capacity = host_obj.to_hash[\"HOST\"][\"TEMPLATE\"][\"CAPACITY\"]\n if !capacity.nil? && Hash === capacity\n capacity.each{ |name, value|\n name = parse_inst_type(name)\n cpu, mem = instance_type_capacity(name)\n totalmemory += mem * value.to_i\n totalcpu += cpu * value.to_i\n }\n else\n raise \"you must define CAPACITY section properly! check the template\"\n end\n\n host_info = \"HYPERVISOR=ec2\\n\"\n host_info << \"PUBLIC_CLOUD=YES\\n\"\n host_info << \"PRIORITY=-1\\n\"\n host_info << \"TOTALMEMORY=#{totalmemory.round}\\n\"\n host_info << \"TOTALCPU=#{totalcpu}\\n\"\n host_info << \"CPUSPEED=1000\\n\"\n host_info << \"HOSTNAME=\\\"#{@host}\\\"\\n\"\n\n vms_info = \"VM_POLL=YES\\n\"\n\n #\n # Add information for running VMs (running and pending).\n #\n usedcpu = 0\n usedmemory = 0\n\n # Build an array of VMs and last_polls for monitoring\n vpool = OpenNebula::VirtualMachinePool.new(OpenNebula::Client.new,\n OpenNebula::VirtualMachinePool::INFO_ALL_VM)\n vpool.info\n onevm_info = {}\n\n\n if !cw_mon_time\n cw_mon_time = Time.now.to_i\n else\n cw_mon_time = cw_mon_time.to_i\n end\n\n do_cw = (Time.now.to_i - cw_mon_time) >= 360\n vpool.each{\n |vm| onevm_info[vm.deploy_id] = vm\n }\n\n\n work_q = Queue.new\n @ec2.instances.each{|i| work_q.push i }\n\t\tworkers = (0...20).map do\n Thread.new do\n begin\n while i = work_q.pop(true)\n next if i.state.name != 'pending' && i.state.name != 'running'\n one_id = i.tags.find {|t| t.key == 'ONE_ID' }\n one_id = one_id.value if one_id\n poll_data=parse_poll(i, onevm_info[i.id], do_cw, cw_mon_time)\n vm_template_to_one = vm_to_one(i)\n vm_template_to_one = Base64.encode64(vm_template_to_one).gsub(\"\\n\",\"\")\n vms_info << \"VM=[\\n\"\n vms_info << \" ID=#{one_id || -1},\\n\"\n vms_info << \" DEPLOY_ID=#{i.instance_id},\\n\"\n vms_info << \" VM_NAME=#{i.instance_id},\\n\"\n vms_info << \" IMPORT_TEMPLATE=\\\"#{vm_template_to_one}\\\",\\n\"\n vms_info << \" POLL=\\\"#{poll_data}\\\" ]\\n\"\n if one_id\n name = i.instance_type\n cpu, mem = instance_type_capacity(name)\n usedcpu += cpu\n usedmemory += mem\n end\n end\n rescue Exception => e\n end\n end\n end; \"ok\"\n workers.map(&:join); \"ok\"\n\n host_info << \"USEDMEMORY=#{usedmemory.round}\\n\"\n host_info << \"USEDCPU=#{usedcpu.round}\\n\"\n host_info << \"FREEMEMORY=#{(totalmemory - usedmemory).round}\\n\"\n host_info << \"FREECPU=#{(totalcpu - usedcpu).round}\\n\"\n\n if do_cw\n host_info << \"CWMONTIME=#{Time.now.to_i}\"\n else\n host_info << \"CWMONTIME=#{cw_mon_time}\"\n end\n\n puts host_info\n puts vms_info\n end",
"def openvz_fog_test_cleanup\n at_exit do\n unless Fog.mocking?\n server = openvz_service.servers.find { |s| s.name == '104' }\n if server\n server.wait_for(120) do\n reload rescue nil; ready?\n end\n end\n server.stop\n openvz_fog_test_server_destroy\n end\n end\nend",
"def spin_up_instance ami_name, vpc_id, key_name, security_group_id, subnet_id, instance_type = \"t2.micro\"\n resp = client.run_instances({\n dry_run: false,\n image_id: ami_name, # required\n min_count: 1, # required\n max_count: 1, # required\n key_name: key_name,\n instance_type: instance_type, # accepts t1.micro, t2.nano, t2.micro, t2.small, t2.medium, t2.large, m1.small, m1.medium, m1.large, m1.xlarge, m3.medium, m3.large, m3.xlarge, m3.2xlarge, m4.large, m4.xlarge, m4.2xlarge, m4.4xlarge, m4.10xlarge, m4.16xlarge, m2.xlarge, m2.2xlarge, m2.4xlarge, cr1.8xlarge, r3.large, r3.xlarge, r3.2xlarge, r3.4xlarge, r3.8xlarge, x1.16xlarge, x1.32xlarge, i2.xlarge, i2.2xlarge, i2.4xlarge, i2.8xlarge, hi1.4xlarge, hs1.8xlarge, c1.medium, c1.xlarge, c3.large, c3.xlarge, c3.2xlarge, c3.4xlarge, c3.8xlarge, c4.large, c4.xlarge, c4.2xlarge, c4.4xlarge, c4.8xlarge, cc1.4xlarge, cc2.8xlarge, g2.2xlarge, g2.8xlarge, cg1.4xlarge, p2.xlarge, p2.8xlarge, p2.16xlarge, d2.xlarge, d2.2xlarge, d2.4xlarge, d2.8xlarge\n monitoring: {\n enabled: true, # required\n },\n network_interfaces: [\n {\n subnet_id: subnet_id,\n groups: [security_group_id],\n device_index: 0,\n associate_public_ip_address: true\n }\n ],\n\n instance_initiated_shutdown_behavior: \"stop\", # accepts stop, terminate\n })\n\n error \"Error starting EC2 instance #{resp.inspect}\" if resp.instances.nil? || resp.instances.size == 0\n\n return resp.instances[0]\n end",
"def terminate\n waiters.each do |k,v|\n v[:threads].each do |thread|\n thread.raise ::Zoidberg::DeadException.new('Instance in terminated state!', object_id)\n end\n end\n end",
"def boot_aws_inception_vm\n say \"\" # glowing whitespace\n\n unless settings[\"inception\"][\"ip_address\"]\n say \"Provisioning IP address for inception VM...\"\n settings[\"inception\"][\"ip_address\"] = acquire_ip_address\n save_settings!\n end\n\n unless settings[\"inception\"] && settings[\"inception\"][\"server_id\"]\n username = \"ubuntu\"\n size = \"m1.small\"\n ip_address = settings[\"inception\"][\"ip_address\"]\n key_name = settings[\"inception\"][\"key_pair\"][\"name\"]\n say \"Provisioning #{size} for inception VM...\"\n inception_vm_attributes = {\n :groups => [settings[\"inception\"][\"security_group\"]],\n :key_name => key_name,\n :private_key_path => inception_vm_private_key_path,\n :flavor_id => size,\n :bits => 64,\n :username => \"ubuntu\",\n :public_ip_address => ip_address\n }\n if vpc?\n raise \"must create subnet before creating VPC inception VM\" unless settings[\"subnet\"] && settings[\"subnet\"][\"id\"]\n inception_vm_attributes[:subnet_id] = settings[\"subnet\"][\"id\"]\n inception_vm_attributes[:private_ip_address] = \"10.0.0.5\"\n end\n server = provider.bootstrap(inception_vm_attributes)\n unless server\n error \"Something mysteriously cloudy happened and fog could not provision a VM. Please check your limits.\"\n end\n\n settings[\"inception\"].delete(\"create_new\")\n settings[\"inception\"][\"server_id\"] = server.id\n settings[\"inception\"][\"username\"] = username\n save_settings!\n end\n\n server ||= fog_compute.servers.get(settings[\"inception\"][\"server_id\"])\n\n unless settings[\"inception\"][\"disk_size\"]\n disk_size = DEFAULT_INCEPTION_VOLUME_SIZE # Gb\n device = \"/dev/sdi\"\n provision_and_mount_volume(server, disk_size, device)\n\n settings[\"inception\"][\"disk_size\"] = disk_size\n settings[\"inception\"][\"disk_device\"] = device\n save_settings!\n end\n\n # settings[\"inception\"][\"host\"] is used externally to determine\n # if an inception VM has been assigned already; so we leave it\n # until last in this method to set this setting.\n # This way we can always rerun the CLI and rerun this method\n # and idempotently get an inception VM\n unless settings[\"inception\"][\"host\"]\n settings[\"inception\"][\"host\"] = server.dns_name\n save_settings!\n end\n\n confirm \"Inception VM has been created\"\n display_inception_ssh_access\n end",
"def step_up(address)\n client = direct_client(address)\n start = Mongo::Utils.monotonic_time\n loop do\n begin\n client.database.command(replSetStepUp: 1)\n break\n rescue Mongo::Error::OperationFailure => e\n # Election failed. (125)\n if e.code == 125\n # Possible reason is the node we are trying to elect has deny-listed\n # itself. This is where {replSetFreeze: 0} should make it eligible\n # for election again but this seems to not always work.\n else\n raise\n end\n\n if Mongo::Utils.monotonic_time > start + 10\n raise e\n end\n end\n end\n reset_server_states\n end",
"def stop\n system(\"ps -aux | grep rackup\")\n puts \"Stoping clusters...\"\n for app in @apps\n if @env == :deployment\n pid_file = \"#{APP_PATH}/log/doozer.#{app[:port]}.pid\"\n puts \"=> Reading pid from #{pid_file}\" \n if File.exist?(pid_file)\n File.open(pid_file, 'r'){ | f | \n pid = f.gets.to_i\n puts \"=> Shutting down process #{pid}\"\n system(\"kill -9 #{pid}\")\n\n }\n File.delete(pid_file) \n else\n puts \"ERROR => pid file doesn't exist\"\n end\n end\n end\n sleep(1)\n system(\"ps -aux | grep rackup\")\nend",
"def terminate(server_name, access_key, secret, snapshot_removal = true, force = false)\n ##############################\n # Initialize AWS and create EC2 connection\n ##############################\n initialize_aws(access_key, secret)\n ec2 = AWS::EC2.new\n\n ##############################\n # Find instance\n ##############################\n instance = nil\n AWS.memoize do\n instances = ec2.instances.filter(\"tag:Name\", server_name)\n instances.each do |i|\n unless i.status == :shutting_down || i.status == :terminated\n instance = i\n break\n end # unless status\n end # instance loop\n end # memoize\n\n if instance\n environment_name = nil\n AWS.memoize do\n environment_name = instance.tags[\"environment\"].strip if instance.tags[\"environment\"]\n end\n\n ##############################\n # ENVIRONMENT\n ##############################\n if environment_name.nil? && ! force\n @log.fatal \"No environment tag found for host. Use the --force option to override and terminate.\"\n exit 3\n end\n\n if (! @environments.has_key?(environment_name)) && (! force)\n @log.fatal \"Environment not found: '#{environment_name}'\"\n exit 2\n end\n @environment = @environments[environment_name] if environment_name\n\n ##############################\n # Create Route53 connection\n ##############################\n aws_route53 = nil\n if @environment && @environment.route53_zone_id\n aws_route53 = AWS::Route53.new\n route53 = EC2Launcher::Route53.new(aws_route53, @environment.route53_zone_id, @log)\n end\n\n ##############################\n # EBS Volumes\n ##############################\n # Find EBS volumes\n attachments = nil\n AWS.memoize do\n attachments = instance.block_device_mappings.values\n\n # Remove snapshots\n remove_snapshots(ec2, attachments) if snapshot_removal\n\n # Remove volumes, if necessary\n remove_volumes(ec2, attachments)\n end\n\n private_ip_address = instance.private_ip_address\n \n run_with_backoff(30, 1, \"terminating instance: #{server_name} [#{instance.instance_id}]\") do\n instance.terminate\n end\n\n if route53\n @log.info(\"Deleting A record from Route53: #{server_name} => #{private_ip_address}\")\n route53.delete_record_by_name(server_name, 'A')\n end\n\n @log.info(\"Deleting node/client from Chef: #{server_name}\")\n node_result = `echo \"Y\" |knife node delete #{server_name}`\n client_result = `echo \"Y\" |knife client delete #{server_name}`\n @log.debug(\"Deleted Chef node: #{node_result}\")\n @log.debug(\"Deleted Chef client: #{client_result}\")\n else\n @log.error(\"Unable to find instance: #{server_name}\")\n end\n end",
"def cleanup_unused_ip_addresses\n fog_compute.addresses.each do |a|\n unless a.server\n print \"Deleting unused IP address #{a.public_ip}... \"\n a.destroy\n puts \"done\"\n end\n end\n end",
"def pool_loop\n loop do\n pool_check\n sleep 5\n end\n end",
"def deploy()\n connection.node_clusters.deploy(uuid).tap{ self.forget }\n end",
"def ensure_all_roles_are_running\n roles_to_add = []\n ZKInterface.lock_and_run {\n ip_info = ZKInterface.get_ip_info()\n ip_info['ips'].each { |ip|\n if !ZKInterface.is_node_done_loading?(ip)\n next\n end\n\n if ZKInterface.is_node_live?(ip)\n next\n else\n failed_job_data = ZKInterface.get_job_data_for_ip(ip)\n failed_node = DjinnJobData.new(failed_job_data, @creds['keyname'])\n roles_to_add << failed_node.jobs\n\n remove_app_hosting_data_for_node(ip)\n remove_node_from_local_and_zookeeper(ip)\n Djinn.log_info(\"Will recover [#{failed_node.jobs.join(', ')}] \" +\n \" roles that were being run by the failed node at #{ip}\")\n end\n }\n\n if !roles_to_add.empty?\n start_new_roles_on_nodes(roles_to_add, @creds['instance_type'],\n @@secret)\n end\n }\n\n return roles_to_add\n end",
"def init_boot\n RightScale::Sender.instance.initialize_offline_queue\n payload = {:agent_identity => @agent_identity,\n :right_link_version => ::RightLink.version,\n :r_s_version => ::RightScale::AgentConfig.protocol_version,\n :resource_uid => ::RightScale::InstanceState.resource_uid}\n req = RightScale::RetryableRequest.new('/booter/declare', payload, :retry_on_error => true)\n req.callback do |res|\n begin\n RightScale::Sender.instance.start_offline_queue\n init_fetch_tags\n rescue Exception => e\n RightScale::Log.error(\"Failed handling /booter/declare response\", e, :trace)\n end\n end\n req.errback do |res|\n RightScale::Log.error(\"Failed making /booter/declare (#{res.inspect}\")\n end\n req.run\n true\n end",
"def shutdown_all( url, &block )\n dispatchers.connect( url ).stats {\n |stats|\n log.dispatcher_global_shutdown( env, url )\n\n stats['running_jobs'].each {\n |instance|\n\n next if instance['helpers']['rank'] == 'slave'\n\n save_and_shutdown( instance['url'] ){\n log.instance_shutdown( env, instance['url'] )\n }\n }\n block.call\n }\n end",
"def deploy\n Kb8Run.update_context(@kb8context)\n @deploy_units.each do | deploy_unit |\n deploy_unit.deploy\n end\n end",
"def graceful_shutdown\n while reap_dead_workers(\"shutdown\") > 0\n DTR.info \"Waiting for #{workers.list.length} threads to finish, could take #{timeout} seconds.\"\n sleep timeout / 60\n end\n end",
"def execute_restore_stripe(options={})\n new_vol_name = \"#{options[:lineage]}-#{ENV['EC2_INSTANCE_ID']}\"\n json_result = self.find_latest_ebs_backup(options[:lineage], options[:from_master], options[:timestamp])\n\n if json_result.nil? \n STDERR.puts \"No existing snapshot found for the specified nickname lineage. Aborting...\"\n exit(-1)\n end\n STDERR.puts \"Restoring.. #{json_result.inspect}\"\n options[:new_size_gb] = (options[:new_volume_size_in_gb] / json_result.size.to_f).ceil if options[:new_volume_size_in_gb]\n\n @disk.sync\n @disk.umount\n @disk.disable_volume\n\n self.execute_terminate_volumes if options[:force]\n\n json_result.each do |snapshot|\n \n# create volume from snap\n create_result = ( options[:new_size_gb] ? create_volume_from_snap_size_gb(snapshot[\"aws_id\"],new_vol_name,options[:new_size_gb] ) : create_volume_from_snap(snapshot[\"aws_id\"], new_vol_name ) )\n raise \"FATAL: error occured in create_volume_from_snap(#{snapshot['aws_id']}, #{new_vol_name})\" if create_result.nil?\n\n# attach volume to instance\n retry_seconds = 0\n while retry_seconds < 200\n begin \n attach_result = attach_volume(create_result['aws_id'], snapshot['device'])\n raise \"FATAL: error occured in attach_volume(#{create_result['aws_id']}, #{snapshot['device']}\" if attach_result.nil?\n break if attach_result\n rescue => e\n puts \"CAUGHT EXCEPTION in execute_restore_stripe. Device attachment. #{e}, Retrying #{retry_seconds} of 200 seconds\"\n retry_seconds += 30\n sleep 30 \n end\n end\n raise \"FATAL: error occured in attach_volume(#{create_result['aws_id']}, #{snapshot['device']}\" if attach_result.nil?\n end\n\n# wait for devices to attach, after completing ALL the api calls\n json_result.each { |s| wait_for_attachment(s['device']) }\n @disk.enable_volume\n raise \"FATAL: mount failed!\" unless @disk.mount\n @disk.write_fstab\n# TODO - grow the filesystem if a new size was given\n end",
"def run_deploys(deployments, app_name, app_data)\n did_we_deploy = false\n\n deployments.each do |application, deploy|\n\n if application != app_name\n debug_log(\"#{application} skipped: #{app_name}\")\n next\n end\n\n layer_name = app_data['layer']\n next unless allow_deploy(application, app_name, layer_name)\n\n debug_log('Deployment started')\n debug_log(\"Deploying as user: #{deploy['user']} and #{deploy['group']}\")\n\n easybib_deploy application do\n deploy_data deploy\n end\n\n did_we_deploy = true\n\n nginx_config = app_data.fetch('nginx', nil)\n next if nginx_config.nil? # no nginx\n\n config_template = get_template(nginx_config)\n next if config_template.nil? # no nginx\n\n config_cookbook = get_cookbook(nginx_config)\n\n listen_opts = get_additional('listen_opts', app_data)\n\n easybib_nginx application do\n cookbook config_cookbook\n config_template config_template\n domain_name deploy['domains'].join(' ')\n doc_root deploy['document_root']\n htpasswd \"#{deploy['deploy_to']}/current/htpasswd\"\n listen_opts listen_opts\n notifies :reload, 'service[nginx]', :delayed\n notifies node['php-fpm']['restart-action'], 'service[php-fpm]', :delayed\n end\n end\n\n did_we_deploy\nend",
"def run!\n\n if File.exist?(EXPO_METADATA) then\n previous_run_metadata = YAML::load(File.read(EXPO_METADATA))\n if previous_run_metadata[:validity] > Time.now.to_i then\n logger.info \"Reusing previous reservation\"\n ### replacing resources of the experiment ## Fix-me I have to find a cleaner way to do this\n ## reading g5k metadata\n g5k_metadata = YAML::load(File.read(Dir.glob(\".g5k*\").first))\n MyExperiment.resources.resources=YAML::load(File.read(RESOURCE_SET_FILE)).resources\n MyExperiment.jobs = g5k_metadata[:job]\n return true\n end\n end\n reset!\n\n env = self.class.defaults.dup\n ### copying some variables defined by the user\n env[:environment] = @environment\n env[:walltime] = @walltime\n env[:resources] = @resources\n env[:name] = @name\n\n env[:public_key] = @public_key unless @public_key.nil?\n\n unless @jobs_id.empty? then\n env[:no_submit] = true\n end\n\n envs=[]\n\n nodes = []\n\n change_dir do\n # I separate the deployment part from the submission part.\n ## if the environment is not defined we do just the reservation part\n reserve_log_msg =\"[ Expo Engine Grid5000 API ] \"\n if env[:environment].nil?\n ### Timing the reservation part\n start_reserve=Time::now()\n\n env = execute_with_hooks(:reserve!,env) do |env|\n\n env[:nodes] = env[:job]['assigned_nodes']\n\n synchronize{\n nodes.push(env[:nodes]).flatten!\n\n }\n\n # if @wait then\n\n # end\n\n end # reserve!\n\n #env[:parallel_reserve].loop!\n\n end_reserve=Time::now()\n logger.info reserve_log_msg +\"Total Time Spent waiting for resources #{end_reserve-start_reserve} secs\"\n ###############################\n else#if the deployment is defined we do as g5k-campaign\n ### Timing deployment part\n start_deploy=Time::now()\n ### Default user management root\n env = execute_with_hooks(:reserve!, env) do |env|\n\n env[:nodes] = env[:job]['assigned_nodes']\n\n env = execute_with_hooks(:deploy!, env) do |env|\n env[:nodes] = env[:deployment]['result'].reject{ |k,v|\n v['state'] != 'OK'\n }.keys.sort\n\n synchronize { nodes.push(env[:nodes]).flatten! }\n\n if defined? env[:job]['resources_by_type']['vlans'][0]\n # I have to redifined the resource Set.\n # MyExperiment.each do |node| ### Need to check this part is using the all resource Set\n # node.name =\n # \"#{node.name.split('.')[0]}-kavlan-#{env[:job]['resources_by_type']['vlans'][0]}.#{node.properties[:site]}.grid5000.fr\"\n # end\n end\n end#deploy!\n end#reserv!\n end_deploy=Time::now()\n logger.info reserve_log_msg +\"Total Time Spent deploying #{end_deploy-start_deploy}\"\n end# if environment\n\n ### Deletes the resources from the Resource Set that had problems in the deployment fase ####\n # $all.delete_if { |resource|\n # not nodes_deployed.include?(resource.name)\n #}\n\n ##########################\n\n end #change_dir\n return env\n end",
"def restart_running_instances_services\n nodes.each do |node|\n node.restart_with_monit\n end\n end",
"def shutdown_vms()\n @vm_manager.shutdown_vms()\n end"
] |
[
"0.6748874",
"0.6607542",
"0.647271",
"0.6321144",
"0.6321144",
"0.614825",
"0.6131076",
"0.6112433",
"0.60040367",
"0.5997861",
"0.59794253",
"0.59636694",
"0.5842088",
"0.5836976",
"0.5833665",
"0.5812568",
"0.57130706",
"0.5691821",
"0.5683815",
"0.5674697",
"0.5658734",
"0.5657702",
"0.5656751",
"0.5641429",
"0.5615335",
"0.5615335",
"0.5611906",
"0.5603467",
"0.5603467",
"0.56005234",
"0.5534277",
"0.55253154",
"0.55109173",
"0.55063933",
"0.5488265",
"0.5449666",
"0.5394893",
"0.5367057",
"0.5363571",
"0.5363571",
"0.5360511",
"0.5343881",
"0.53359854",
"0.5330489",
"0.5326769",
"0.5311102",
"0.5296985",
"0.5283402",
"0.52640575",
"0.5263608",
"0.5261863",
"0.5251669",
"0.52506727",
"0.5241517",
"0.52327454",
"0.52226394",
"0.52125716",
"0.52116907",
"0.5207461",
"0.5204817",
"0.51904196",
"0.51650333",
"0.5161917",
"0.51618963",
"0.51588213",
"0.51463896",
"0.5138903",
"0.5136101",
"0.5123739",
"0.51234585",
"0.5122829",
"0.51159763",
"0.511422",
"0.5111419",
"0.511141",
"0.51024157",
"0.51015466",
"0.5100885",
"0.50978774",
"0.50889283",
"0.50711334",
"0.5048719",
"0.50345427",
"0.5034055",
"0.50312585",
"0.5027559",
"0.50253165",
"0.50245124",
"0.5018475",
"0.5008531",
"0.49931392",
"0.49916765",
"0.49856097",
"0.4983473",
"0.4981544",
"0.49772912",
"0.49767324",
"0.49765858",
"0.49755606",
"0.49667734"
] |
0.6166761
|
5
|
Polls Opsworks for timeout seconds until deployment_id has completed
|
def wait_until_deploy_completion(deployment_id, timeout)
started_at = Time.now
Timeout::timeout(timeout) do
@opsworks_client.wait_until(
:deployment_successful,
deployment_ids: [deployment_id]
) do |w|
# disable max attempts
w.max_attempts = nil
end
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def _wait_until_deployed(deployment_id, timeout)\n opsworks_client.wait_until(:deployment_successful, deployment_ids: [deployment_id]) do |w|\n w.before_attempt do |attempt|\n puts \"Attempt #{attempt} to check deployment status\".light_black\n end\n w.interval = 10\n w.max_attempts = timeout / w.interval\n end\n end",
"def wait(timeout = 60)\n Timeout::timeout(timeout) do\n deployments = nil\n while deployments.nil? or deployments.select{|e| e.id == deploymentId}.size > 0 do\n sleep(RECHECK_INTERVAL)\n deployments = Marathon::Deployment.list\n end\n end\n end",
"def wait_for_completion\n until terminated? do\n Kernel.sleep(Gosen::DeploymentRun::POLLING_TIME)\n @deployment_resource.reload\n end\n raise Gosen::Error.new(\"Deployment error: #{@deployment_resource['output']}\") if @deployment_resource['status'] == 'error'\n end",
"def wait_for_pod_ready(name, namespace, timeout=300)\n run %W(\n kubectl wait pod/#{name}\n --for condition=Ready\n --namespace #{namespace}\n --timeout #{timeout}s\n ).join(\" \").chomp\nend",
"def _poll_server\n server_uri = @config.get(PROVISIONER_SERVER_URI)\n poll_error_interval = @config.get(PROVISIONER_WORKER_POLL_ERROR_INTERVAL).to_i || 10\n postdata = { 'provisionerId' => @provisioner_id, 'workerId' => @worker_id, 'tenantId' => @tenant }.to_json\n loop do\n begin\n response = Coopr::RestHelper.post \"#{server_uri}/v2/tasks/take\", postdata\n break response\n rescue StandardError => e\n log.error \"Unable to connect to Coopr Server #{server_uri}/v2/tasks/take: #{e}\"\n sleep poll_error_interval\n end\n end\n end",
"def wait_for_provisioning\n while !self.provisioned?\n sleep Profitbricks::Config.polling_interval\n end\n end",
"def poll_deployment_job(job, options={})\n options = {:timeout => 600}.merge(options)\n max_sleep_secs = 60\n resp = ASM::Util.block_and_retry_until_ready(options[:timeout], RetryException, max_sleep_secs) do\n resp = get_deployment_job(job)\n unless %w[Success Failed].include?(resp[:job_status])\n logger.info(\"%s status on %s: %s\" % [job, host, Parser.response_string(resp)])\n raise(RetryException)\n end\n resp\n end\n raise(ResponseError.new(\"Deployment job %s failed\" % job, resp)) unless resp[:job_status] == \"Success\"\n\n resp\n rescue Timeout::Error\n raise(Error, \"Timed out waiting for job %s to complete. Final status: %s\" % [job, Parser.response_string(resp)])\n end",
"def wait_task(index_name, task_id, time_before_retry = WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, opts = {})\n loop do\n status = get_task_status(index_name, task_id, opts)\n if status == 'published'\n return\n end\n sleep(time_before_retry.to_f / 1000)\n end\n end",
"def wait_termination(timeout = nil)\n result, @terminated_deployments =\n terminated_deployments, Hash.new\n result\n end",
"def poll(id, deploy_id)\n i = get_instance(deploy_id)\n vm = OpenNebula::VirtualMachine.new_with_id(id, OpenNebula::Client.new)\n vm.info\n cw_mon_time = vm[\"LAST_POLL\"] ? vm[\"LAST_POLL\"].to_i : Time.now.to_i\n do_cw = (Time.now.to_i - cw_mon_time) >= 360\n puts parse_poll(i, vm, do_cw, cw_mon_time)\n end",
"def wait_for_jobs(namespace, delay=10)\n loop do\n success = true\n jobs = capture(\"kubectl get jobs --namespace=#{namespace} --output=name\")\n jobs.split.each do |job|\n status = JSON.load capture(\"kubectl get --namespace=#{namespace} --output=json #{job}\")\n puts status['status'].to_json\n success = false unless status['status']['succeeded']\n end\n break if success\n sleep delay\n end\nend",
"def wait_deploy_action(external_user, service_id, role_name, nodes, report)\n if report\n Log.info LOG_COMP, \"Waiting #{nodes} to report ready\"\n rc = wait_report_ready(nodes)\n else\n Log.info LOG_COMP, \"Waiting #{nodes} to be (ACTIVE, RUNNING)\"\n rc = wait(nodes, 'ACTIVE', 'RUNNING')\n end\n\n if rc[0]\n @lcm.trigger_action(:deploy_cb,\n service_id,\n external_user,\n service_id,\n role_name,\n rc[1])\n else\n @lcm.trigger_action(:deploy_failure_cb,\n service_id,\n external_user,\n service_id,\n role_name)\n end\n end",
"def wait_for_namespace(namespace, sleep_duration=10)\n puts \"#{c_blue}# Waiting for: #{namespace}, every #{sleep_duration}s#{c_reset}\"\n loop do\n output, status = capture_with_status(\"kubectl get pods --namespace #{namespace} --no-headers\")\n ready = status.success? && !output.empty?\n if ready\n output.each_line do |line|\n name, readiness, state, restarts, age = line.split\n next if state == 'Completed'\n next if state == 'Running' && /^(\\d+)\\/\\1$/ =~ readiness\n puts \"# Waiting for: #{line}\"\n ready = false\n end\n end\n break if ready\n sleep sleep_duration\n end\nend",
"def wait_cooldown_action(external_user, service_id, role_name, cooldown_time)\n Log.info LOG_COMP, \"Waiting #{cooldown_time}s for cooldown for \" \\\n \"service #{service_id} and role #{role_name}.\"\n\n sleep cooldown_time.to_i\n\n @lcm.trigger_action(:cooldown_cb,\n service_id,\n external_user,\n service_id,\n role_name)\n end",
"def test_for_node\n deploy_info = @deployer.deployment_info_from(@node)[@node]\n if deploy_info.key?(:error)\n error \"Error while getting deployment info: #{deploy_info[:error]}\"\n elsif Time.now.utc - deploy_info[:deployment_info][:date] > MAX_ACCEPTABLE_REFRESH_PERIOD_SECS\n error \"Last deployment has been done on #{deploy_info[:deployment_info][:date].strftime('%F')}. Should refresh it.\"\n end\n end",
"def retry_later\n IngestWorkflowMonitorJob.set(wait: 15.minutes).perform_later(flow.id, @params)\n end",
"def regional_rolling_deploy(stack_id:, layer_id:, app_id:, revision: '')\n log(\"Starting opsworks deploy for app #{app_id}\\n\\n\")\n\n instances = @opsworks_client.describe_instances(layer_id: layer_id)[:instances]\n\n instances_by_group = instances.map {|v| v.to_h}.group_by { |d| d[:availability_zone] }\n\n instances_by_group.each do |region, instance_group|\n # Only deploy to online instances\n online_instance = instance_group.select{|k| k[:status] == 'online'}\n instances_ids = online_instance.map{|k| k[:instance_id]}\n instances_names = online_instance.map{|k| k[:hostname]}\n\n next if instances_names.empty?\n\n puts \"#{instances_names} in #{region}\"\n\n begin\n load_balancers = {}\n log(\"=== Starting deploy for #{instances_names} ===\")\n\n online_instance.each do |instance|\n instance = Aws::OpsWorks::Types::Instance.new(instance)\n load_balancers[instance.instance_id] = detach_from_elbs(instance: instance)\n end\n\n wait_for_detach(@lb_wait_params)\n\n deploy(\n stack_id: stack_id,\n app_id: app_id,\n instance_id: instances_ids,\n revision: revision\n )\n ensure\n online_instance.each do |instance|\n instance = Aws::OpsWorks::Types::Instance.new(instance)\n attach_to_elbs(instance: instance, load_balancers: load_balancers[instance.instance_id]) if load_balancers[instance.instance_id]\n end\n\n wait_for_re_attach(@lb_wait_params)\n\n log(\"=== Done deploying on #{instances_names} ===\\n\\n\")\n end\n end\n\n log(\"SUCCESS: completed opsworks deploy for all instances on app #{app_id}\")\n end",
"def wait_on_status(jobid)\r\n uri = URI(\"http://api.idolondemand.com/1/job/status/\" + jobid)\r\n uri.query = URI.encode_www_form(:apikey => $api_key)\r\n res = Net::HTTP.get_response(uri, p_addr = $proxy_host, p_port = $proxy_port)\r\n obj = JSON.parse(res.body)\r\n\r\n if obj['status'] == 'queued'\r\n puts \"job [#{jobid}] #{obj['status']}, waiting #{$status_wait} seconds\"\r\n sleep($status_wait)\r\n wait_on_status(jobid)\r\n end\r\nend",
"def deploy_in_background! \n unless RAILS_ENV == 'test' \n RAILS_DEFAULT_LOGGER.info \"Calling other ruby process in the background in order to deploy deployment #{self.id} (stage #{self.stage.id}/#{self.stage.name})\"\n system(\"sh -c \\\"cd #{RAILS_ROOT} && ruby script/runner -e #{RAILS_ENV} ' deployment = Deployment.find(#{self.id}); deployment.prompt_config = #{self.prompt_config.inspect.gsub('\"', '\\\"')} ; Webistrano::Deployer.new(deployment).invoke_task! ' >> #{RAILS_ROOT}/log/#{RAILS_ENV}.log 2>&1\\\" &\")\n end\n end",
"def deploy_in_background!\n notify_hipchat_on_execute\n unless Rails.env.test?\n Rails.logger.info \"Calling other ruby process in the background in order to deploy deployment #{self.id} (stage #{self.stage.id}/#{self.stage.name})\"\n\n system <<\"EOS\"\ncd #{Rails.root} && rails runner -e #{Rails.env} 'deployment = Deployment.find(#{self.id}); deployment.prompt_config = #{self.prompt_config.inspect.gsub('\"', '\\\"')} ; Webistrano::Deployer.new(deployment).invoke_task! ' >> #{Rails.root}/log/#{Rails.env}.log 2>&1 &\nEOS\n end\n end",
"def status\n begin\n Timeout::timeout(5) do\n ping '-q', '-c', '1', '-W', '3', @resource[:name]\n end\n rescue Timeout::Error, Puppet::ExecutionFailure\n return :down\n end\n :up\n end",
"def verify_prior_nodes_live(node)\n if node.workorder.has_key?(\"rfcCi\")\n ci = node.workorder.rfcCi\n actionName = node.workorder.rfcCi.rfcAction\n else\n ci = node.workorder.ci\n actionName = node.workorder.actionName\n end\n \n timeout_sec = node['solr_api_timeout_sec'].to_i\n \n #get the map with all cloud's id & deployment order in the form |key,value| => |cloudId, deployment_order|\n #ex {34951930=>\"7\", 35709237=>\"8\", 34951924=>\"4\"}\n cloudIdsWithDpmtOrderMap = cloud_deployment_order(node)\n Chef::Log.info(\"Cloud id & deployment order map : #{cloudIdsWithDpmtOrderMap.to_json}\")\n \n #get array of solrcloud nodes for the action selected\n #get list of all solrcloud nodes which are selected for this action in the deployment\n nodesInAction = get_solrcloud_instances_by_action(node, actionName)\n \n thisNodeCiName = ci[:ciName]\n Chef::Log.info(\"This solrcloud node's ciName : #{thisNodeCiName}\")\n \n #get the node cloud id \"solrcloud-34951924-1\" => \"34951924\"\n thisCloudId = thisNodeCiName.split('-')[1]\n \n #get the deployment order of this node's cloud\n thisNodeCloudDpmtOrder = cloudIdsWithDpmtOrderMap.fetch(thisCloudId.to_i)\n Chef::Log.info(\"This node's cloud deployment order : #{thisNodeCloudDpmtOrder}\")\n \n #get all cloud ids having deployment order <= node_cloud_deployment_order. This is required to make sure that all prior cloud deployment was completed\n #ex From all clouds {34951930=>\"7\", 35709237=>\"8\", 34951924=>\"4\"} for node_cloud_deployment_order = 7 => {34951930=>\"7\", 34951924=>\"4\"}\n #same node_cloud_id is inclusive because there may be multiple nodes in node's cloud.\n #This list is used to make sure that all nodes across this cloud list are deployed first\n cloudIdsTobeDeployedPrior = []\n cloudIdsWithDpmtOrderMap.each do |k, v|\n if v.to_i <= thisNodeCloudDpmtOrder.to_i\n cloudIdsTobeDeployedPrior.push k\n end\n end\n Chef::Log.info(\"Cloud ids to be deployed before : #{cloudIdsTobeDeployedPrior.to_json}\")\n \n #get solrcloud nodes for cloud ids to be deployed prior\n nodeIndexesTobeDeployedPrior = []\n nodesInAction.each do |n|\n ciName = n['ciName']\n cloudId = ciName.split('-')[1]\n index = ciName.split('-', 2)[1]\n if cloudIdsTobeDeployedPrior.include? cloudId.to_i\n # prefx the cloud deployment order to determine the order of solr instace in the deployment\n # User might select the lower cloudId with higher deployment order and vice-versa so deployment order will be useful\n nodeIndexesTobeDeployedPrior.push cloudIdsWithDpmtOrderMap[cloudId.to_i]+\"-\"+index\n end\n end\n \n #sort solrcloud_nodes_tobe_deployed_prior by ciName (cloudId & compute index)\n nodeIndexesTobeDeployedPrior.sort! {|a, b| b <=> a}\n #default sorting is in descending order, we want to process the deployment in the ascending order of compute number\n #so reverse the order\n nodeIndexesTobeDeployedPrior.reverse!\n Chef::Log.info(\"solrclouds to executed before #{nodeIndexesTobeDeployedPrior.to_json}\")\n \n computeCloudIdIpMap = get_compute_number_to_ip_map(node)\n Chef::Log.info(\"compute number to ip map : #{computeCloudIdIpMap.to_json}\")\n # prefx the cloud deployment order to determine the order of solr instace in the deployment\n # User might select the lower cloudId with higher deployment order and vice-versa so deployment order will be useful\n thisNodeIndex = thisNodeCloudDpmtOrder+\"-\"+thisNodeCiName.split('-',2)[1]\n Chef::Log.info(\"This node index : #{thisNodeIndex}\")\n \n # select only the nodes with lower index & this node index\n nodeIndexesTobeDeployedPrior = nodeIndexesTobeDeployedPrior.select {|cloudIdIndex| cloudIdIndex <= thisNodeIndex}\n \n index = nodeIndexesTobeDeployedPrior.index {|id| id == thisNodeIndex}\n Chef::Log.info(\"index = #{index}\")\n \n wait_time = index * 10;\n Chef::Log.info(\"Allowing #{wait_time} seconds for prior nodes to start the deployment before\")\n sleep wait_time\n \n nodeIpsTobeDeployedPrior = []\n nodeIndexesTobeDeployedPrior.each do |nodeIndex|\n if !nodeIndex.eql? thisNodeIndex\n nodeIndexWithoutDpmtOrder = nodeIndex.split('-',2)[1]\n Chef::Log.info(\"nodeIndexWithoutDpmtOrder = #{nodeIndexWithoutDpmtOrder}\")\n nodeIpsTobeDeployedPrior.push computeCloudIdIpMap[nodeIndexWithoutDpmtOrder]\n end\n end\n \n # No need to check for other nodes to confirm those are live before processing this node as there are no prior nodes in the list\n if nodeIpsTobeDeployedPrior.empty?\n return\n end\n \n Chef::Log.info(\"nodeIpsTobeDeployedPrior = #{nodeIpsTobeDeployedPrior.to_json}\")\n host = nodeIpsTobeDeployedPrior[0]\n cluster_state = get_cluster_state(host, node['port_no'], timeout_sec)\n nodes_up_status = nodes_live?(host, node['port_no'], nodeIpsTobeDeployedPrior, timeout_sec)\n Chef::Log.info(\"Node live status : #{nodes_up_status}\")\n if !nodes_up_status \n error = \"Some of the prior nodes from list #{nodeIpsTobeDeployedPrior.to_json} in the deployment are not live.\"\n puts \"***FAULT:FATAL=#{error}\"\n raise error\n end\n end",
"def application_specific_tasks\n # system 'cap deploy:whenever:update_crontab'\n # system 'cap deploy:delayed_job:stop'\n # system 'cap deploy:delayed_job:start n=1'\n # system 'cap deploy:run_command command='ls -la''\nend",
"def wait_for_condition script, timeout\r\n command 'waitForCondition', script, timeout\r\n end",
"def wait_for_condition script, timeout\r\n command 'waitForCondition', script, timeout\r\n end",
"def wait(*desired_states)\n Timeout.timeout(60) do\n loop do\n states = self.service_states\n break if desired_states.include?(states[:current]) && states[:next].nil?\n Kernel.sleep(1)\n end\n end\n rescue Timeout::Error\n raise Puppet::Error.new(\"Timed out waiting for #{@resource[:name]} to transition states\")\n end",
"def deploy_in_background! \n unless Rails.env.test?\n Rails.logger.info \"Calling other ruby process in the background in order to deploy deployment #{self.id} (stage #{self.stage.id}/#{self.stage.name})\"\n\n system(\"sh -c \\\"cd #{Rails.root} && rails runner -e #{Rails.env} ' deployment = Deployment.find(#{self.id}); deployment.prompt_config = #{self.prompt_config.inspect.gsub('\"', '\\\"')} ; Webistrano::Deployer.new(deployment).invoke_task! ' >> #{Rails.root}/log/#{Rails.env}.log 2>&1\\\" &\")\n end\n end",
"def eventually(label, &block)\n current_time = Time.now\n timeout_treshold = current_time + TIMEOUT\n while (block.call == false) && (current_time <= timeout_treshold) do\n sleep 5\n current_time = Time.now\n end\n if (current_time > timeout_treshold)\n fail \"Action '#{label}' did not resolve within timeout: #{TIMEOUT}s\"\n end\nend",
"def wait(desired_state)\n Timeout.timeout(60) do\n loop do\n status = self.status\n break if status == desired_state.to_sym\n sleep(1)\n end\n end\n rescue Timeout::Error\n raise Puppet::Error.new(\"Timed out waiting for #{@resource[:name]} to transition states\")\n end",
"def application_specific_tasks\n # system 'cap deploy:whenever:update_crontab'\n # system 'cap deploy:delayed_job:stop'\n # system 'cap deploy:delayed_job:start n=1'\n # system 'cap deploy:run_command command=\"ls -la\"'\nend",
"def application_specific_tasks\n # system 'cap deploy:whenever:update_crontab'\n # system 'cap deploy:delayed_job:stop'\n # system 'cap deploy:delayed_job:start n=1'\n # system 'cap deploy:run_command command=\"ls -la\"'\nend",
"def application_specific_tasks\n # system 'cap deploy:whenever:update_crontab'\n # system 'cap deploy:delayed_job:stop'\n # system 'cap deploy:delayed_job:start n=1'\n # system 'cap deploy:run_command command=\"ls -la\"'\nend",
"def implicit_wait=(seconds); end",
"def wait_state(state, deploy_id)\n ready = (state == 'stopped') || (state == 'pending') || (state == 'running') || (state == 'terminated')\n raise \"Waiting for an invalid state\" if !ready\n t_init = Time.now\n begin\n wstate = get_instance(deploy_id).state.name rescue nil\n raise \"Ended in invalid state\" if Time.now - t_init > @state_change_timeout\n sleep 3\n end while wstate != state\n end",
"def wait\n loop do\n refresh\n fail Exceptions::PushJobFailed, @job if timed_out?\n fail Exceptions::PushJobFailed, @job if failed?\n break if successful?\n pause\n end\n end",
"def update_for_wait\n update_basic\n end",
"def buildwise_montior_parallel_execution(build_id, opts = {}) \r\n start_time = Time.now \r\n \r\n default_opts = {:max_wait_time => 3600, :check_interval => 15}\r\n # default to checking ervery 10 seconds for one hour, unless specified\r\n the_opts = default_opts.merge(opts)\r\n \r\n max_wait_time = the_opts[:max_wait_time]\r\n check_interval = the_opts[:check_interval]\r\n \r\n max_wait_time = 1800 if max_wait_time < 60\r\n check_interval = 15 if check_interval < 5\r\n \r\n puts \"[buildwise.rake] Keep checking build |#{build_id} for max #{max_wait_time} for every #{check_interval} seconds\"\r\n \r\n fio = nil\r\n if ENV[\"ARTIFACT_DIR\"] && Dir.exist?(ENV[\"ARTIFACT_DIR\"])\r\n tmp_log_file = File.join(ENV[\"ARTIFACT_DIR\"], \"rake_parallel.log\") \r\n FileUtils.rm(tmp_log_file) if File.exist?(tmp_log_file)\r\n puts(\"[buildwise.rake] logging parallel monitoring to #{tmp_log_file}\")\r\n fio = File.open(tmp_log_file, \"a\") \r\n fio.puts(\"[#{Time.now}] Keep checking build |#{build_id}| for max #{max_wait_time} for every #{check_interval} seconds\")\r\n end\r\n \r\n begin \r\n Timeout::timeout(max_wait_time + 120) { \r\n \r\n $last_buildwise_server_build_status = nil\r\n while ((Time.now - start_time ) < max_wait_time) # test exeuction timeout\r\n the_build_status = buildwise_build_ui_test_status(build_id) rescue \"Pending\"\r\n if fio\r\n fio.puts(\"[#{Time.now}] build status => |#{the_build_status}|\")\r\n fio.flush\r\n end\r\n \r\n if ($last_buildwise_server_build_status != the_build_status)\r\n puts \"[Rake] #{Time.now} Checking build status: |#{the_build_status}|\"\r\n $last_buildwise_server_build_status = the_build_status\r\n end\r\n \r\n if the_build_status == \"OK\"\r\n fio.close\r\n exit 0\r\n elsif the_build_status == \"Failed\"\r\n fio.close\r\n exit -1\r\n else \r\n if (the_build_status != \"Pending\")\r\n puts(\"[Rake] functional testing status => #{the_build_status}, next check in #{check_interval} seconds\")\r\n end\r\n sleep check_interval # check the build status every minute\r\n end\r\n end\r\n \r\n }\r\n rescue Timeout::Error => e\r\n if fio\r\n fio.puts(\"[#{Time.now}] execution timeouts!\")\r\n fio.close\r\n end \r\n puts(\"[Rake] execution time outs!\")\r\n exit -3 \r\n end\r\n \r\n puts \"[Rake] Execution UI tests expired\"\r\n if fio\r\n fio.puts(\"[#{Time.now}] ends normally\")\r\n fio.close\r\n end\r\n exit -2\r\nend",
"def poll(id, host, deploy_id, not_used)\n\n exe = SSHCommand.run(\"#{LIBVIRT[:poll]} #{deploy_id}\", host,\n log_method(id))\n\n if exe.code != 0\n result = :failure\n info = \"-\"\n\n if exe.stderr.match(/^error: failed to get domain '#{deploy_id}'/)\n info = \"#{POLL_ATTRIBUTE[:state]}=#{VM_STATE[:deleted]}\"\n result = :success\n end\n\n send_message(ACTION[:poll], RESULT[result], id, info)\n return\n end\n\n info = \"\"\n\n exe.stdout.each_line {|line|\n columns=line.split(\":\").collect {|c| c.strip }\n\n case columns[0]\n when 'Used memory'\n info << \" #{POLL_ATTRIBUTE[:usedmemory]}=\" \\\n << (columns[1].to_i).to_s\n when 'State'\n case columns[1]\n when \"running\",\"blocked\",\"shutdown\",\"dying\"\n state = VM_STATE[:active]\n when \"paused\"\n state = VM_STATE[:paused]\n when \"crashed\"\n state = VM_STATE[:error]\n else\n state = VM_STATE[:unknown]\n end\n\n info << \" #{POLL_ATTRIBUTE[:state]}=#{state}\"\n end\n }\n\n send_message(ACTION[:poll], RESULT[:success], id, info)\n end",
"def wait_for_operation(op_uuid, timeout=DEFAULT_EXEC_TIMEOUT)\n op_uuid = op_uuid.sub(\"/#{version}/operations/\", '')\n request(\n :path => \"operations/#{op_uuid}/wait\",\n :params => {\n :status_code => 200,\n :timeout => timeout\n }\n )\n true\n end",
"def docker_wait_ready\n bash 'docker-wait-ready' do\n code <<-EOF\n timeout=0\n while [ $timeout -lt 20 ]; do\n ((timeout++))\n #{docker_cmd} ps | head -n 1 | grep ^CONTAINER\n if [ $? -eq 0 ]; then\n break\n fi\n sleep 1\n done\n [[ $timeout -eq 20 ]] && exit 1\n exit 0\n EOF\n not_if \"#{docker_cmd} ps | head -n 1 | grep ^CONTAINER\"\n end\n end",
"def aws_instance_wait_till_status_equals(obj, status, time)\n log \"AWS: waiting for #{obj.class.to_s.split(\"::\").last} '#{obj.id}' status to change to ':#{status}'\"\n begin\n Timeout.timeout(time) do \n sleep 1 while aws_call(\n 'aws_instance_status', \n instance: obj,\n errs: { AWS::EC2::Errors::InvalidInstanceID::NotFound => 60 }\n ) != status\n end\n rescue Timeout::Error => e\n raise \"AWS: timeout while waiting for #{obj.class.to_s.split(\"::\").last} '#{obj.id} status to change to ':#{status}'\"\n end\n end",
"def wait_for_task(recipe, task, timeout=600, interval=5)\n desired_summary = \"completed: #{recipe}\"\n last_state = nil\n i = 0\n while i <= timeout do\n summary = task.show.summary\n return true if summary == desired_summary\n \n # print in the output if task changed state, and reset timeout\n if summary != last_state\n last_state = summary\n i = 0\n msg = \"Task is now #{summary}, waiting for #{desired_summary}\"\n write_output \"#{msg}\\n\"\n Maestro.log.info msg\n else\n Maestro.log.debug \"Server state is #{summary}, waiting for #{desired_summary} (#{i}/#{timeout})\"\n end\n \n sleep interval\n i += interval\n end\n \n msg = \"Timed out after #{timeout}s waiting for receipe #{recipe} to complete, is currently #{task.show.summary}\"\n Maestro.log.info msg\n set_error msg\n end",
"def request_termination\n instance_id = AlgRunner.fetch_url(INSTANCE_ID_URL)\n\n logger.info { \"Requesting terminating for #{instance_id}\" }\n @bunny.queue INSTANCE_SERVICE_QUEUE\n @bunny.exchange('').publish(\n { :instance_id => instance_id.to_s, :action => :termination }.to_yaml, \n :key => INSTANCE_SERVICE_QUEUE, :routing_key => INSTANCE_SERVICE_QUEUE\n )\n end",
"def worker_boot_timeout(timeout); end",
"def docker_waiting_containers\n puts \"Waiting 40s for ensure that containers are up ...\"\n sleep 40\n end",
"def wait_undeploy_action(external_user, service_id, role_name, nodes)\n Log.info LOG_COMP, \"Waiting #{nodes} to be (DONE, LCM_INIT)\"\n rc = wait(nodes, 'DONE', 'LCM_INIT')\n\n if rc[0]\n @lcm.trigger_action(:undeploy_cb,\n service_id,\n external_user,\n service_id,\n role_name,\n rc[1])\n else\n @lcm.trigger_action(:undeploy_failure_cb,\n service_id,\n external_user,\n service_id,\n role_name,\n rc[1])\n end\n end",
"def wait_for_running\n while !self.running?\n sleep Profitbricks::Config.polling_interval\n end\n end",
"def cancel(deploy_id, lcm_state=nil)\n case lcm_state\n when 'SHUTDOWN_POWEROFF', 'SHUTDOWN_UNDEPLOY'\n ec2_action(deploy_id, :stop)\n wait_state('stopped', deploy_id)\n else\n ec2_action(deploy_id, :terminate)\n wait_state('terminated', deploy_id)\n end\n end",
"def confirm_running(container_id)\n ip = get_ip_of_container container_id\n port = get_port_of_container container_id\n\n tried_count = 1\n begin\n @logger.info \"Checking application is ready... trying count:#{tried_count}\"\n req = Net::HTTP.new(ip, port)\n res = req.get('/')\n unless res.kind_of?(Net::HTTPSuccess) or res.kind_of?(Net::HTTPRedirection)\n raise \"Response status is not ready: #{res.code}\"\n end\n @logger.info(\"Application is ready! forwarding to port #{port}\")\n @logger.info 'FINISHED'\n @ws.send 'FINISHED'\n rescue\n if tried_count <= 30\n sleep 1\n tried_count += 1\n retry\n end\n raise\n end\n end",
"def _poll_server_and_retrieve_task\n poll_interval = @config.get(PROVISIONER_WORKER_POLL_INTERVAL).to_i || 1\n poll_error_interval = @config.get(PROVISIONER_WORKER_POLL_ERROR_INTERVAL).to_i || 10\n loop do\n begin\n response = _poll_server\n if response.code == 200 && response.to_str && response.to_str != ''\n task = JSON.parse(response.to_str)\n log.debug \"Received task from server <#{response.to_str}>\"\n break task\n elsif response.code == 204\n sleep poll_interval\n next\n else\n log.error \"Received error code #{response.code} from coopr server: #{response.to_str}\"\n end\n rescue StandardError => e\n log.error \"Caught exception processing response from coopr server: #{e.inspect}\"\n end\n sleep poll_error_interval\n end\n end",
"def wait_resource_status(url, status, timeout: 300, interval: 10)\n res = nil\n success = wait_for(timeout) {\n res = rest_run(url, :get, nil, os_token)\n if res[:success]\n if res[:parsed].all? {|k, v| v[\"status\"] == status}\n return res[:parsed]\n end\n else\n raise \"error obtaining resource:\\n\" << res.to_yaml\n end\n }\n\n raise \"after timeout status not #{status} but: \" + res[:parsed].map {|k, v| \"#{k}:#{v[\"status\"]}\"}.join(',')\n end",
"def wait_for_async_service_operation(service_instance_name, retries=0)\n duration = 5\n puts \"#{c_blue}# Waiting for service instance #{service_instance} to complete, every #{duration}s, #{retries} times#{c_reset}\"\n service_instance_guid = capture(\"cf service --guid #{service_instance_name}\")\n return { success: false, reason: :not_found } if service_instance_guid == 'FAILED'\n attempts = 0\n loop do\n service_instance_info = cf_curl(\"/v2/service_instances/#{service_instance_guid}\")\n return { success: true } unless service_instance_info['entity']\n return { success: true } unless service_instance_info['entity']['last_operation']\n return { success: true } unless service_instance_info['entity']['last_operation']['state']\n state = service_instance_info['entity']['last_operation']['state']\n return { success: true } if state != 'in progress'\n return { success: false, reason: :max_retries } if attempts >= retries\n sleep duration\n attempts += 1\n end\nend",
"def wait_for_resources_to_complete(release_docs, timeout)\n waiting_for_ready = true\n wait_start_time = Time.now.to_i\n @output.puts \"Waiting for resources to come up\" unless release_docs.all?(&:delete_resource)\n\n loop do\n statuses = resource_statuses(release_docs)\n pod_statuses, non_pod_statuses = statuses.partition { |s| s.kind == \"Pod\" }\n display_statuses = pod_statuses + non_pod_statuses.reject(&:live) # show what is interesting\n not_ready = too_many_not_ready(statuses)\n\n if waiting_for_ready # readiness phase\n print_statuses(\"Deploy status:\", display_statuses, exact: false) if display_statuses.any?\n\n if not_ready\n if failed = too_many_failed(statuses)\n print_statuses(\"UNSTABLE, resources failed:\", failed, exact: true)\n return false, statuses\n elsif time_left(wait_start_time, timeout) == 0\n @output.puts \"TIMEOUT, pods took too long to get live\"\n return false, statuses\n else # rubocop:disable Style/EmptyElse\n # keep waiting for more ready\n end\n elsif statuses.select(&:live).all?(&:finished)\n return success, statuses\n else\n @output.puts \"READY, starting stability test\"\n waiting_for_ready = false\n wait_start_time = Time.now.to_i\n end\n else # stability phase\n if not_ready\n if failed = too_many_failed(statuses)\n print_statuses(\"UNSTABLE, resources failed:\", failed, exact: true)\n else\n print_statuses(\"UNSTABLE, resources not ready:\", not_ready, exact: true)\n end\n return false, statuses\n else\n remaining = time_left(wait_start_time, STABILITY_CHECK_DURATION)\n @output.puts \"Testing for stability: #{remaining}s remaining\"\n return success, statuses if remaining == 0\n end\n end\n\n sleep TICK\n end\n end",
"def implicit_wait; end",
"def poll\n raise Deployment::NotImplemented, 'This method is abstract and should be implemented in a subclass'\n end",
"def wait_for_execution_request(execution_request_id, options={}, print_output = true)\n refresh_interval = 10\n if options[:refresh_interval].to_i > 0\n refresh_interval = options[:refresh_interval]\n end\n execution_request = execution_request_interface.get(execution_request_id)['executionRequest']\n refresh_display_seconds = refresh_interval % 1.0 == 0 ? refresh_interval.to_i : refresh_interval\n # unless options[:quiet]\n # print cyan, \"Execution request has not yet finished. Refreshing every #{refresh_display_seconds} seconds...\", \"\\n\", reset\n # end\n while execution_request['status'] == 'pending' || execution_request['status'] == 'new' do\n sleep(refresh_interval)\n execution_request = execution_request_interface.get(execution_request_id)['executionRequest']\n end\n if print_output && options[:quiet] != true\n if execution_request['stdErr'].to_s.strip != '' && execution_request['stdErr'] != \"stdin: is not a tty\\n\"\n print_h2 \"Error\"\n print execution_request['stdErr'].to_s.strip, reset, \"\\n\"\n end\n if execution_request['stdOut'].to_s.strip != ''\n print_h2 \"Output\"\n print execution_request['stdOut'].to_s.strip, reset, \"\\n\"\n end\n print reset, \"\\n\"\n end\n return execution_request\n end",
"def shutdown(id, host, deploy_id, not_used)\n cmd=\"#{LIBVIRT[:shutdown]} #{deploy_id} && \" \\\n \"while [ $(#{LIBVIRT[:poll]} #{deploy_id} > /dev/null 2>&1; \" \\\n \"echo $?) -eq \\\"0\\\" ]; do sleep 2; done ; sleep 4\"\n\n execution=SSHCommand.run('bash', host, log_method(id), cmd)\n\n if execution.code !=0\n send_message(ACTION[:shutdown], RESULT[:failure], id)\n else\n send_message(ACTION[:shutdown], RESULT[:success], id)\n end\n end",
"def worker_timeout(timeout); end",
"def wait_release_action(external_user, service_id, role_name, nodes, report)\n if report\n Log.info LOG_COMP, \"Waiting #{nodes} to report ready\"\n rc = wait_report_ready(nodes)\n else\n Log.info LOG_COMP, \"Waiting #{nodes} to be (ACTIVE, RUNNING)\"\n rc = wait(nodes, 'ACTIVE', 'RUNNING')\n end\n\n if rc[0]\n @lcm.trigger_action(:release_cb,\n service_id,\n external_user,\n service_id,\n role_name,\n rc[1])\n else\n @lcm.trigger_action(:deploy_failure_cb,\n service_id,\n external_user,\n service_id,\n role_name)\n end\n end",
"def check_server_status\n @server_status_array = Array.new(@lpar_id_array)\n until @server_status_array.empty?\n @server_status_array.each do |lpar|\n lpar_name_index = @server_status_array.find_index(lpar)\n @lpar_name_deployed = @lpar_name_array[lpar_name_index]\n puts \"Checking status of #{@lpar_name_deployed}\"\n get_url('compute')\n @server_status = rest_get(\"#{@resource_url}/servers/#{lpar}\", @token_id)\n @server_id_status = JSON.parse(@server_status)['server']['status']\n puts \"Status of #{@lpar_name_deployed} is #{@server_id_status}\"\n if @server_id_status =~ /ACTIVE/ || @server_id_status =~ /ERROR/\n @server_status_array.delete(lpar)\n else\n puts 'Waiting for 20 seconds'\n sleep 20\n end\n end\n end\n puts 'All LPARs have been deployed, proceed to login to the LPARs.'\n end",
"def calculate_retry_after(env); end",
"def run!(configuration:, deployment_policy:)\n containers = find_containers_to_deploy(configuration, deployment_policy)\n\n cloner = Indocker::Repositories::Cloner.new(configuration, @logger)\n build_server_pool = Indocker::ServerPools::BuildServerPool.new(configuration: configuration, logger: @logger)\n deployer = Indocker::ContainerDeployer.new(configuration: configuration, logger: @logger)\n\n @global_logger.info(\"Establishing ssh sessions to all servers...\")\n build_server_pool.create_sessions!\n\n build_servers = configuration\n .build_servers\n .uniq { |s| s.host }\n\n deploy_servers = containers\n .map(&:servers)\n .flatten\n .uniq { |s| s.host }\n\n servers = (deploy_servers + build_servers).uniq { |s| s.host }\n\n @progress.setup(\n binaries_servers: servers,\n build_servers: build_servers,\n deploy_servers: deploy_servers,\n env_files: configuration.env_files.keys,\n repositories: configuration.repositories.keys,\n force_restart: deployment_policy.force_restart,\n skip_build: deployment_policy.skip_build,\n skip_deploy: deployment_policy.skip_deploy,\n containers: containers,\n artifact_servers: configuration.artifact_servers,\n )\n\n remote_operations = sync_indocker(servers)\n wait_remote_operations(remote_operations)\n\n remote_operations = sync_env_files(deploy_servers, configuration.env_files)\n wait_remote_operations(remote_operations)\n\n remote_operations = pull_repositories(cloner, build_servers, configuration.repositories)\n wait_remote_operations(remote_operations)\n\n remote_operations = sync_artifacts(cloner, configuration.artifact_servers)\n wait_remote_operations(remote_operations)\n\n update_crontab_redeploy_rules(configuration, build_servers.first)\n\n containers.uniq.each do |container|\n recursively_deploy_container(\n configuration,\n deployer,\n build_server_pool,\n container,\n containers,\n deployment_policy.skip_build,\n deployment_policy.skip_deploy,\n deployment_policy.force_restart,\n deployment_policy.skip_force_restart\n )\n end\n\n Thread\n .list\n .each { |t| t.join if t != Thread.current }\n ensure\n build_server_pool.close_sessions if build_server_pool\n deployer.close_sessions if deployer\n end",
"def aws_wait_for_peers\n loop do\n aws_find_peers\n\n Chef::Log.info(\"etcd_service[#{ new_resource.name }] Found \"\\\n \"#{ new_resource.peers.length + 1 }/#{ new_resource.quorum } AWS \"\\\n \"peers, #{ active_peers.length } active\")\n\n break if new_resource.peers.length >= (new_resource.quorum - 1)\n break if active_peers.length > 0\n sleep 5\n end\n end",
"def get_standalone_worker_spec_timeout\n if timeout = ENV['STANDALONE_WORKER_SPEC_TIMEOUT']\n puts \"STANDALONE_WORKER_SPEC_TIMEOUT=#{timeout}\"\n timeout.to_i\n else\n 10\n end\nend",
"def wait(duration)\n info \"Request from Experiment Script: Wait for #{duration}s....\"\n warn \"Calling 'wait' or 'sleep' will block entire EC event loop. Please try 'after' or 'every'\"\n sleep duration\n end",
"def aws_obj_wait_till_available(obj)\n log \"AWS: waiting for #{obj.class.to_s.split(\"::\").last} '#{obj.id}' status to change to ':available'\"\n begin\n Timeout.timeout(120) do \n sleep 1 while aws_call(\n 'aws_obj_state', \n obj: obj, \n errs: { \n AWS::EC2::Errors::InvalidVpcID::NotFound => 60,\n AWS::EC2::Errors::InvalidSubnetID::NotFound => 60\n } \n ) != :available\n end\n rescue Timeout::Error => e\n raise \"AWS: timeout while waiting for #{obj.class.to_s.split(\"::\").last} '#{obj.id} status to change to ':available'\"\n end\n end",
"def reboot_and_wait_for_host\n host.RebootHost_Task({:force => false}).wait_for_completion\n wait_for_host(300, resource[:reboot_timeout])\n end",
"def timeout\n node['redmine']['executor']['timeout']\n end",
"def wait_for_completion(options = {})\n options = {\n max_lost_retries: 10,\n max_fail_retries: 0,\n poll_duration_in_seconds: 10,\n timeout_in_seconds: 3600\n }.merge(options)\n options[:start_time] ||= Time.now\n if Time.now - options[:start_time] < options[:timeout_in_seconds]\n # When waiting for ids we will hold by monitoring for the result\n # files directly, rather than using the generatic classify routine.\n # This is because the most common use case for this is when jobs\n # are idling remotely on the LSF and don't want to run into contention\n # issues when multiple processes try to classify/save the status.\n if options[:id] || options[:ids]\n ids = extract_ids([options[:id], options[:ids]].flatten.compact)\n if ids.any? { |id| job_running?(id) }\n sleep options[:poll_duration_in_seconds]\n wait_for_completion(options)\n end\n\n else\n classify_jobs\n print_status(print_insructions: false)\n sleep options[:poll_duration_in_seconds]\n classify_jobs\n resumitted = false\n lost_jobs.each do |job|\n if job[:submissions] < options[:max_lost_retries] + 1\n resubmit_job(job)\n resumitted = true\n end\n end\n failed_jobs.each do |job|\n if job[:submissions] < options[:max_fail_retries] + 1\n resubmit_job(job)\n resumitted = true\n end\n end\n classify_jobs\n if outstanding_jobs? || resumitted\n wait_for_completion(options)\n else\n print_status\n end\n end\n end\n end",
"def lock_timeout_retry_delay; end",
"def deploy(stack_id:, app_id:, instance_id:, revision:, deploy_timeout: 1800)\n # App IDs can be passed as a CSV to deploy multiple apps in the same stack\n app_ids = app_id.split(\",\")\n deploy_id = []\n\n app_ids.each do |id|\n # Update the branch/revision to the given parameter, if any.\n unless revision.to_s.empty?\n @opsworks_client.update_app(\n {\n app_id: id,\n app_source: {revision: revision}\n }\n )\n end\n\n instance_id = [instance_id] unless instance_id.is_a?(Array)\n\n response = @opsworks_client.create_deployment(\n stack_id: stack_id,\n app_id: id,\n instance_ids: instance_id,\n command: {\n name: 'deploy'\n }\n )\n log(\"Deploy process running (id: #{response[:deployment_id]})...\")\n deploy_id.push(response[:deployment_id])\n end\n\n deploy_id.each do |id|\n wait_until_deploy_completion(id, deploy_timeout)\n end\n\n log(\"✓ deploy completed\")\n end",
"def exit_on_deployment\n if ! @marathon.deployments.empty?\n puts \"Deployment in progess\"\n exit 0\n end\nend",
"def tango_poll(course, assessment, submissions, output_file)\n feedback = nil\n begin\n Timeout.timeout(80) do\n loop do\n response = TangoClient.poll(\"#{course.name}-#{assessment.name}\", \"#{URI.encode(output_file)}\")\n # json is returned when a job is not complete\n unless response.content_type == \"application/json\"\n feedback = response.body\n break\n end\n sleep 3\n end\n end\n rescue Timeout::Error\n return -11\n rescue TangoClient::TangoException => e\n flash[:error] = \"Error while polling for job status: #{e.message}\"\n return -11\n end\n\n if feedback.nil?\n return -12\n else\n if assessment.overwrites_method?(:autogradeDone)\n assessment.config_module.autogradeDone(submissions, feedback)\n else\n # this doesn't work because autogradeDone is defined in submissions_controller\n autogradeDone(submissions, feedback)\n end\n\n return 0\n end\n end",
"def wait\n if collecting?\n if @options[:timeout]\n @task.with_timeout(@options[:timeout]) { @condition.wait }\n else\n @condition.wait\n end\n end\n @status\n rescue Async::TimeoutError\n @error = RSMP::TimeoutError.new describe_progress\n @status = :timeout\n end",
"def test_ps_and_schedules\n\n pdef = Ruote.define do\n concurrence do\n wait '4h'\n wait '2h'\n end\n end\n\n wfid = @dashboard.launch(pdef)\n\n @dashboard.wait_for(4)\n\n #assert_equal 1, @dashboard.processes.size\n assert_equal [ wfid ], @dashboard.processes.collect { |ps| ps.wfid }\n end",
"def wait_for_termination(timeout)\n @executor.awaitTermination(1000 * timeout, java.util.concurrent.TimeUnit::MILLISECONDS)\n end",
"def verify_job_complete(base_64_urn,access_token)\n Timeout::timeout(120) do # 2 min\n loop do\n response = RestClient.get(\"#{API_URL}/modelderivative/v2/designdata/#{base_64_urn}/manifest\",\n { Authorization: \"Bearer #{access_token}\"} )\n json = JSON.parse(response.body)\n p \"Translate file to SVF - status: #{json['status']}, progress: #{json['progress']}\"\n \n return response if json[\"progress\"]==\"complete\"\n sleep 1\n end\n end\n end",
"def wait_while_present\n container.wait_while_present\n end",
"def deployed_or_running_deploy\n deploys.joins(:job).find_by(\"jobs.status\" => Job::ACTIVE_STATUSES + [\"succeeded\"])\n end",
"def get_package_manager_servlet_status_wait_until_ready(\n opts = {\n _retries: {\n max_tries: 30,\n base_sleep_seconds: 2,\n max_sleep_seconds: 2\n }\n }\n )\n opts[:_retries] ||= {}\n opts[:_retries][:max_tries] ||= 30\n opts[:_retries][:base_sleep_seconds] ||= 2\n opts[:_retries][:max_sleep_seconds] ||= 2\n\n # ensure integer retries setting (Puppet 3 passes numeric string)\n opts[:_retries][:max_tries] = opts[:_retries][:max_tries].to_i\n opts[:_retries][:base_sleep_seconds] = opts[:_retries][:base_sleep_seconds].to_i\n opts[:_retries][:max_sleep_seconds] = opts[:_retries][:max_sleep_seconds].to_i\n\n result = nil\n with_retries(max_tries: opts[:_retries][:max_tries], base_sleep_seconds: opts[:_retries][:base_sleep_seconds], max_sleep_seconds: opts[:_retries][:max_sleep_seconds]) { |retries_count|\n result = get_package_manager_servlet_status\n puts format('Check CRX Package Manager service attempt #%<retries_count>d: %<result_message>s', retries_count: retries_count, result_message: result.message)\n raise StandardError.new(result.message) if result.data == false\n }\n result\n end",
"def ecs_wait_container_instances\n @ecs_wait_container_instances = true\n end",
"def wait_for_job(job_id, timeout_seconds)\n states = ['FINISHED', 'CANCELED', 'FAILED']\n wait_interval = 2 # seconds\n total_taken = 0\n while total_taken < timeout_seconds\n sleep wait_interval\n total_taken += wait_interval\n status = @cp.get_job(job_id)\n if states.include? status['state']\n return\n end\n end\n end",
"def cleanup(vpc_id, client, asg, elbv1, elbv2, region)\n begin\n response = client.describe_vpcs(vpc_ids: [vpc_id])\n rescue Aws::EC2::Errors::InvalidVpcIDNotFound => e\n puts \"Error: vpc_id [#{vpc_id}] does not exist... exiting.\"\n puts \"Make sure you passed the correct region on the command-line if it's not in the default us-west-2\"\n exit 0\n end\n\n # 1) Delete Auto Scaling group\n begin\n asg.delete_auto_scaling_group(auto_scaling_group_name: 'asg-nginx_auto', force_delete: true)\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n\n sleep 2\n # TODO: properly wait here until ASG is fully deleted before proceeding...\n begin\n asg.delete_launch_configuration(launch_configuration_name: 'lc-nginx_auto')\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n sleep 2\n\n # 2) instance handling\n term_error = 0\n instances_to_term = []\n terminate_states = %w[pending running shutting-down stopping stopped]\n puts 'Checking for nginx and nat instances, of all states...'\n begin\n response = client.describe_instances(filters: [{name: 'tag:Name', values: ['autoASG nginx server',\n 'nat instance']}])\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n response.reservations.each do |reservation|\n reservation.instances.each do |instance|\n puts \"Check #1: instance-id=[#{instance.instance_id}] AMI=[#{instance.image_id}] state=[#{instance.state.name}]\"\n instances_to_term.push(instance.instance_id) if terminate_states.include? instance.state.name\n end\n end\n\n if instances_to_term.any? # If array has content, proceed.\n term_error = 0\n instance_cnt = instances_to_term.length # TODO: Check before/after termination attempts and ensure = 0\n before_terminate = Time.now\n begin\n client.wait_until(:instance_terminated,instance_ids: instances_to_term) do |wait|\n wait.interval = 8 # Seconds between polling attempts. Same as wait.delay\n wait.max_attempts = 15 # Polling attempts before giving up. Wait time is 15*8=120 seconds.\n puts \"Attempting to terminate [#{instance_cnt}] instance(s), please wait up to 120 seconds...\"\n begin\n client.terminate_instances(instance_ids: instances_to_term)\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n end\n rescue Aws::Waiters::Errors::WaiterFailed => error\n term_error = 1 # TODO: Do something more reliable if this ever occurs.\n puts \"Exception: failed waiting for instance running: #{error.message}\"\n end\n puts \"#{Time.now - before_terminate.to_time} seconds elapsed while terminating.\" if term_error.zero?\n end\n\n if term_error.zero?\n # Debug with final instance check... this shouldn't print anything aside from terminated instances.\n begin\n response = client.describe_instances(filters: [{name: 'tag:Name', values: ['autoASG nginx server',\n 'nat instance']}])\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n response.reservations.each do |reservation|\n reservation.instances.each do |instance|\n puts \"Check #2: instance-id=[#{instance.instance_id}] AMI=[#{instance.image_id}] state=[#{instance.state.name}]\"\n end\n end\n end\n\n puts 'Sleeping for 5 seconds...'\n sleep 5\n\n # 3) Delete listeners\n printf 'Deleting ALB listeners... '\n begin\n response = elbv2.describe_load_balancers(names: ['AutoALB'])\n alb_arn = response.load_balancers[0].load_balancer_arn\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n sleep 2\n begin\n response = elbv2.describe_listeners(load_balancer_arn: alb_arn)\n listener_arn = response.listeners[0].listener_arn\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n begin\n elbv2.delete_listener(listener_arn: listener_arn)\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n sleep 2\n puts 'done.'\n\n # 4) Delete target groups\n printf 'Deleting ALB target groups... '\n begin\n response = elbv2.describe_target_groups(names: ['AutoALBTargetGroup'])\n target_group_arn = response.target_groups[0].target_group_arn\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n begin\n elbv2.delete_target_group(target_group_arn: target_group_arn)\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n sleep 5\n puts 'done.'\n\n # 5) Delete load balancers\n printf 'Deleting application and classic load balancers... '\n begin\n elbv1.delete_load_balancer(load_balancer_name: 'AutoCLB')\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n begin\n elbv2.delete_load_balancer(load_balancer_arn: alb_arn)\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n puts 'done.'\n\n puts 'Sleeping for 120 seconds, enough time for the ASG to fully disappear before deleting subnets.'\n sleep 120\n\n # 6) subnets\n begin\n response = client.describe_subnets(filters: [{name: 'vpc-id', values: [vpc_id]}])\n response.subnets.each do |sn|\n printf \"Removing subnet: #{sn.subnet_id}, #{sn.vpc_id}, #{sn.cidr_block}, #{sn.availability_zone}; \"\n client.delete_subnet(subnet_id: sn.subnet_id)\n puts 'Done.'\n end\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n\n # 7) security groups\n begin\n response = client.describe_security_groups(filters: [{name: 'vpc-id', values: [vpc_id]}])\n response.security_groups.each do |sg|\n next if sg.group_name == 'default' # This name is reserved by aws and cannot be removed.\n printf \"Removing security group: #{sg.group_id}, #{sg.vpc_id}, #{sg.group_name}, Desc='#{sg.description}'; \"\n client.delete_security_group(group_id: sg.group_id)\n puts 'Done.'\n end\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n\n # 8) Internet gateway\n begin\n response = client.describe_internet_gateways(filters: [{name: 'attachment.vpc-id', values: [vpc_id]}])\n response.internet_gateways.each do |igw|\n printf \"Detaching Internet gateway: #{igw.internet_gateway_id} <-> #{igw.attachments[0].vpc_id}; \"\n client.detach_internet_gateway(internet_gateway_id: igw.internet_gateway_id, vpc_id: igw.attachments[0].vpc_id)\n printf \"Removing Internet gateway: #{igw.internet_gateway_id} <-> #{igw.attachments[0].vpc_id}; \"\n client.delete_internet_gateway(internet_gateway_id: igw.internet_gateway_id)\n puts 'Done.'\n end\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n\n # 9) Route tables\n begin\n response = client.describe_route_tables(filters: [{name: 'vpc-id', values: [vpc_id]}])\n response.route_tables.each do |rtl|\n if rtl.associations[0] != nil\n if rtl.associations[0].route_table_association_id != nil\n puts \"Skipping #{rtl.associations[0].route_table_association_id}, causes exception.\"\n end\n next\n end\n printf \"Removing route table: #{rtl.route_table_id}, #{rtl.vpc_id}; \"\n client.delete_route_table(route_table_id: rtl.route_table_id)\n puts 'Done.'\n end\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n\n # 10) Delete VPC\n begin\n puts \"Attempting to delete VPC [#{vpc_id}]\"\n client.delete_vpc(vpc_id: vpc_id)\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n\n begin\n response = client.describe_vpcs(vpc_ids: [vpc_id])\n rescue Aws::EC2::Errors::InvalidVpcIDNotFound => e\n puts \"Deletion of vpc_id=[#{vpc_id}] was a success.\"\n exit 0\n end\n\n # Shouldn't get here, but sometimes does due to the ASG taking too long to\n # release subnet dependencies, or if running a cleanup before a launch has\n # fully completed, etc.\n puts 'Oops. Termination sometimes fails for various reasons.'\n puts 'Note: running this twice usually clears up any lingering dependencies.'\n puts ' With that said, there is still work to be done. Execute again.'\n exit 0\nend",
"def lock_timeout_retry_delay=(_arg0); end",
"def clientPoll(jobId)\n printDebugMessage('clientPoll', 'Begin', 1)\n status = 'PENDING'\n while(status == 'PENDING' || status == 'RUNNING') do\n status = getStatus(jobId)\n printOutputMessage(status, 1)\n sleep(5) if(status == 'PENDING' || status == 'RUNNING')\n end\n printDebugMessage('clientPoll', 'End', 1)\n end",
"def retry_block_until_true\n (0..RETRY_COUNT).each do\n return if yield\n sleep RETRY_STEP\n end\n Puppet.debug get_cluster_debug_report if is_online?\n fail \"Execution timeout after #{RETRY_COUNT * RETRY_STEP} seconds!\"\n end",
"def wait_for_tag (tag, should_exists)\n require 'timeout'\n done = false\n begin\n status = Timeout::timeout(TIMEOUT) do\n until done\n tags = get_server_tags\n if should_exists\n done = true unless tag_exists?(tag).empty?\n else\n done = true if tag_exists?(tag).empty?\n end\n unless done\n Chef::Log.info(\"Waiting for tag exists #{should_exists}. Retry in 10 seconds...\")\n sleep 10\n end\n end\n end\n rescue Timeout::Error => e\n fail(\"=== ERROR === Timed out waiting for tag exists #{should_exists}\")\n end\n end",
"def poll_monitors\n (1..MAX_POLL_COUNT).each do |count|\n if @monitors.all? {|monitor| monitor.done?}\n show_complete\n break\n end\n @monitors.each{|monitor| monitor.poll}\n @verbose && print(\"Poll #{count} of #{MAX_POLL_COUNT}: \")\n print @monitors.inject(0) {|sum, monitor| sum + monitor.servers_not_done.length}, ' '\n @verbose && print(\"servers remain\\n\")\n sleep(POLL_SLEEP_SECONDS)\n end\n\n unless @monitors.all? {|monitor| monitor.done?}\n puts \"\\nTIME OUT.\\nSpent #{MAX_POLL_COUNT * POLL_SLEEP_SECONDS} seconds waiting for the deployment\\n\" +\n \"to finish. I can't wait any longer!\"\n show_complete\n end\n end",
"def ping\n start = Time.now\n\n # use exclusive mode to prevent the task from suspending and causing the Timeout::Error to crash the actor thread instead\n exclusive {\n Timeout.timeout(@timeout) do\n @block.call\n end\n }\n\n rescue Timeout::Error => exc\n error exc\n abort(exc)\n rescue => exc\n error exc\n abort(exc)\n else\n delay = Time.now - start\n debug { \"watchdog delay is %.3fs\" % [delay] }\n end",
"def wait_for_resources_to_complete(release, release_docs)\n @wait_start_time = Time.now\n stable_ticks = CHECK_STABLE / TICK\n @output.puts \"Waiting for pods to be created\"\n\n loop do\n statuses = pod_statuses(release, release_docs)\n return success if statuses.none?\n not_ready = statuses.reject(&:live)\n\n if @testing_for_stability\n if not_ready.any?\n print_statuses(statuses)\n unstable!('one or more pods are not live', not_ready)\n return statuses\n else\n @testing_for_stability += 1\n @output.puts \"Stable #{@testing_for_stability}/#{stable_ticks}\"\n return success if stable_ticks == @testing_for_stability\n end\n else\n print_statuses(statuses)\n if not_ready.any?\n if stopped = not_ready.select(&:stop).presence\n unstable!('one or more pods stopped', stopped)\n return statuses\n elsif seconds_waiting > WAIT_FOR_LIVE\n @output.puts \"TIMEOUT, pods took too long to get live\"\n return statuses\n end\n elsif release_docs.all?(&:job?)\n return success\n else\n @output.puts \"READY, starting stability test\"\n @testing_for_stability = 0\n end\n end\n\n sleep TICK\n return statuses if stopped?\n end\n end",
"def _wait_tasks\n @wait_tasks\n end",
"def wait_until(timeout=self.class.default_timeout, cycle=1, fatigue=1.2, &block)\n waited = 0\n until block.call\n debug \"#{self} is waiting for resource (%5.2f/%2ds +%5.2f)...\"% [waited, timeout, cycle]\n sleep cycle\n waited += cycle\n cycle *= fatigue\n if waited > timeout\n raise WaitTimeoutError, \"Waiting for aws resources timed out after #{waited} seconds!\"\n end\n end\n end",
"def poll_cycle\n begin\n if !access_key.empty?\n puts \"Connecting to #{region} using access key #{access_key}\"\n @cw = Aws::CloudWatch::Client.new(region: region || 'us-east-1', access_key_id: access_key, secret_access_key: secret_key) \n else\n puts \"Connecting to #{region} using (hopefully) iam role from the instance\"\n @cw = Aws::CloudWatch::Client.new(region: region || 'us-east-1') \n end\n @connection = self.connect\n puts 'Connected to database'\n report_metrics\n puts 'Completed report of metrics'\n puts ''\n rescue Exception => e\n puts e.message \n puts e.backtrace.inspect \n ensure\n @connection.finish if @connection\n end\n end",
"def deploy_in_background! (opts={})\n unless Rails.env == 'test'\n logger.info \"Calling other ruby process in the background in order to deploy deployment #{self.id} (stage #{self.stage.id}/#{self.stage.name})\"\n system_command = \"sh -c \\\"cd #{Rails.root} && bundle exec rails runner -e #{Rails.env} ' deployment = Deployment.find(#{self.id}); deployment.prompt_config = #{self.prompt_config.inspect.gsub('\"', '\\\"')} ; Webistrano::Deployer.new(deployment).invoke_task! ' >> #{Rails.root}/log/#{Rails.env}.log 2>&1\\\" &\"\n logger.info \"SYSTEM_COMMAND: #{system_command}\"\n system(system_command)\n\n # Webistrano::Deployer.new(Deployment.find(self.id)).invoke_task!\n end\n end",
"def wait_until_exit!\n trap_signals!\n\n until @outbound_pool.wait_for_termination(60)\n debug_log Ambo.random_beep_boops\n end\n end",
"def await_event(type=\"Scaleout\", delay=120)\n des = description.desired_capacity\n result = false\n count = 0\n Log.log \"Awaiting #{type}... \", newline: false\n while count < delay && !result\n s = summary\n result = (s[:size] == des && s[:in_service] && s[:healthy])\n sleep 1\n count += 1\n end\n Log.log \"done\", timestamp: false\n Log.log \"Summary: #{summary.inspect}\"\n end",
"def run_template\n launched_job.update(status_message: \"Running TplDevTest job\")\n launched_job.job_log.info \"Logging within TplDevTest job\"\n\n sleep self.sleep_seconds\n\n launched_job.status\n end",
"def do_poll\n\t\tstatus_lamp\n\t\tstatus_input\n\t\tprojector_information\n\t\tstatus_error\n\tend",
"def wait_for_host_in_dashboard(host)\n hostname = host.node_name\n retry_command(\"Wait for #{hostname} to be in the console\", dashboard, \"! curl --sslv3 -k -I https://#{dashboard}/nodes/#{hostname} | grep '404 Not Found'\")\n end",
"def wait_for_launching\n sleep @delay\n end"
] |
[
"0.74300927",
"0.69848865",
"0.6737966",
"0.6208974",
"0.612199",
"0.60591793",
"0.5990514",
"0.58479667",
"0.58325887",
"0.57840073",
"0.57760847",
"0.5765682",
"0.57396877",
"0.57095104",
"0.5659073",
"0.56037563",
"0.55957127",
"0.55913246",
"0.5573044",
"0.5542815",
"0.551733",
"0.55101514",
"0.5486363",
"0.54835963",
"0.54835963",
"0.5461857",
"0.54600686",
"0.54568434",
"0.54543877",
"0.5439303",
"0.5439303",
"0.5439303",
"0.54194856",
"0.5419467",
"0.5418819",
"0.5395259",
"0.536386",
"0.53571206",
"0.5354011",
"0.53493756",
"0.53244054",
"0.53149676",
"0.53104234",
"0.5305675",
"0.5299297",
"0.5290589",
"0.528851",
"0.52876776",
"0.52792704",
"0.5277168",
"0.52761656",
"0.5273955",
"0.52356386",
"0.52339387",
"0.5229488",
"0.5216078",
"0.5213725",
"0.5212823",
"0.5211629",
"0.52041817",
"0.5190873",
"0.51884633",
"0.5188187",
"0.51880026",
"0.51806396",
"0.5178632",
"0.5172193",
"0.515368",
"0.5148987",
"0.5136047",
"0.5126768",
"0.51225907",
"0.5116344",
"0.5115826",
"0.5104338",
"0.5094411",
"0.5090259",
"0.50856334",
"0.50814694",
"0.5066215",
"0.5051576",
"0.5045761",
"0.50425047",
"0.50383246",
"0.50329083",
"0.50298256",
"0.5027332",
"0.5024474",
"0.5023158",
"0.50164014",
"0.50129557",
"0.50115395",
"0.5005917",
"0.50044817",
"0.5004409",
"0.5002159",
"0.4999492",
"0.4995966",
"0.49926886",
"0.4990251"
] |
0.7276278
|
1
|
Takes a Aws::OpsWorks::Types::Instance Detaches the provided instance from all of its load balancers Returns the detached load balancers as an array of Aws::ElasticLoadBalancing::Types::LoadBalancerDescription Blocks until AWS confirms that all instances successfully detached before returning Does not wait and instead returns an empty array if no load balancers were found for this instance
|
def detach_from_elbs(instance:)
unless instance.is_a?(Aws::OpsWorks::Types::Instance)
fail(ArgumentError, "instance must be a Aws::OpsWorks::Types::Instance struct")
end
all_load_balancers = @elb_client.describe_load_balancers
.load_balancer_descriptions
load_balancers = detach_from(all_load_balancers, instance)
@lb_wait_params = []
load_balancers.each do |lb|
params = {
load_balancer_name: lb.load_balancer_name,
instances: [{ instance_id: instance.ec2_instance_id }]
}
remaining_instances = @elb_client
.deregister_instances_from_load_balancer(params)
.instances
log(<<-MSG.split.join(" "))
Will detach instance #{instance.hostname} from
#{lb.load_balancer_name} (remaining attached instances:
#{remaining_instances.count.to_s})
MSG
@lb_wait_params << params
end
unless @regional_deploy
if @lb_wait_params.any?
wait_for_detach(@lb_wait_params)
else
log("No load balancers found for instance #{instance.hostname}")
end
end
load_balancers
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def detach_from(load_balancers, instance)\n check_arguments(instance: instance, load_balancers: load_balancers)\n\n load_balancers.select do |lb|\n matched_instance = lb.instances.any? do |lb_instance|\n instance.ec2_instance_id == lb_instance.instance_id\n end\n\n if matched_instance && lb.instances.count > 1\n # We can detach this instance safely because there is at least one other\n # instance to handle traffic\n true\n elsif matched_instance && lb.instances.count == 1\n # We can't detach this instance because it's the only one\n log(<<-MSG.split.join(\" \"))\n Will not detach #{instance.hostname} from load balancer\n #{lb.load_balancer_name} because it is the only instance connected\n MSG\n\n false\n else\n # This load balancer isn't attached to this instance\n false\n end\n end\n end",
"def attach_to_elbs(instance:, load_balancers:)\n check_arguments(instance: instance, load_balancers: load_balancers)\n\n if load_balancers.empty?\n log(\"No load balancers to attach to\")\n return {}\n end\n\n @lb_wait_params = []\n registered_instances = {} # return this\n\n load_balancers.each do |lb|\n params = {\n load_balancer_name: lb.load_balancer_name,\n instances: [{ instance_id: instance.ec2_instance_id }]\n }\n\n result = @elb_client.register_instances_with_load_balancer(params)\n\n registered_instances[lb.load_balancer_name] = result\n @lb_wait_params << params\n end\n\n log(\"Re-attaching instance #{instance.hostname} to all load balancers\")\n\n unless @regional_deploy\n wait_for_re_attach(@lb_wait_params)\n end\n\n registered_instances\n end",
"def deregister_instances_from_load_balancer(instance_ids, lb_name)\n params = Fog::AWS.indexed_param('Instances.member.%d.InstanceId', [*instance_ids])\n request({\n 'Action' => 'DeregisterInstancesFromLoadBalancer',\n 'LoadBalancerName' => lb_name,\n :parser => Fog::Parsers::AWS::ELB::DeregisterInstancesFromLoadBalancer.new\n }.merge!(params))\n end",
"def fetch_from_ec2_loadbalancer\n instances_for_deploy = []\n loadbalancer lb_webserver, :web\n instances_for_deploy\nend",
"def fetch_from_ec2_loadbalancer\n instances_for_deploy = []\n loadbalancer lb_webserver, :web\n instances_for_deploy\nend",
"def load_balancer_data(balancer = nil)\n params = Smash.new(\"Action\" => \"DescribeLoadBalancers\")\n if balancer\n params[\"LoadBalancerNames.member.1\"] = balancer.id || balancer.name\n end\n result = all_result_pages(nil, :body,\n \"DescribeLoadBalancersResponse\", \"DescribeLoadBalancersResult\",\n \"LoadBalancerDescriptions\", \"member\") do |options|\n request(\n :method => :post,\n :path => \"/\",\n :form => options.merge(params),\n )\n end\n if balancer\n health_result = all_result_pages(nil, :body,\n \"DescribeInstanceHealthResponse\", \"DescribeInstanceHealthResult\",\n \"InstanceStates\", \"member\") do |options|\n request(\n :method => :post,\n :path => \"/\",\n :form => options.merge(\n \"LoadBalancerName\" => balancer.id || balancer.name,\n \"Action\" => \"DescribeInstanceHealth\",\n ),\n )\n end\n end\n result.map do |blr|\n (balancer || Balancer.new(self)).load_data(\n Smash.new(\n :id => blr[\"LoadBalancerName\"],\n :name => blr[\"LoadBalancerName\"],\n :state => :active,\n :status => \"ACTIVE\",\n :created => blr[\"CreatedTime\"],\n :updated => blr[\"CreatedTime\"],\n :public_addresses => [\n Balancer::Address.new(\n :address => blr[\"DNSName\"],\n :version => 4,\n ),\n ],\n :servers => [blr.get(\"Instances\", \"member\")].flatten(1).compact.map { |i|\n Balancer::Server.new(self.api_for(:compute), :id => i[\"InstanceId\"])\n },\n ).merge(\n health_result.nil? ? {} : Smash.new(\n :server_states => health_result.nil? ? nil : health_result.map { |i|\n Balancer::ServerState.new(\n self.api_for(:compute),\n :id => i[\"InstanceId\"],\n :status => i[\"State\"],\n :reason => i[\"ReasonCode\"],\n :state => i[\"State\"] == \"InService\" ? :up : :down,\n )\n },\n )\n )\n ).valid_state\n end\n end",
"def describe_load_balancers(ids = [], options = {})\n ids = [*ids]\n params = {}\n params['Marker'] = options[:marker] if options[:marker]\n params['PageSize'] = options[:page_size] if options[:page_size]\n params.merge!(Fog::AWS.serialize_keys('LoadBalancerArns', ids)) if ids.any?\n params.merge!(Fog::AWS.serialize_keys('Names', options[:names])) if options[:names]\n request({\n 'Action' => 'DescribeLoadBalancers',\n :parser => Fog::Parsers::AWS::ELBV2::DescribeLoadBalancers.new\n }.merge!(params))\n end",
"def deregister_instances_from_lb(lb_name, instance_ids)\n instances = instance_ids.map { |instance_id| { :instance_id => instance_id } }\n link = generate_request(\"DeregisterInstancesFromLoadBalancer\",\n :load_balancer_name => lb_name, :instances => instances\n )\n request_info(link, QElbInstancesParser.new)\n rescue Exception\n on_exception\n end",
"def instance_list(next_token=nil)\n self.ec2_client.describe_instances(\n {\n filters: [\n {\n name: \"tag:Branch\",\n values: [\"*\"],\n },\n {\n name: \"instance-state-name\",\n values: [\"running\"],\n }\n ],\n next_token: next_token\n })\n end",
"def list_instances()\n response = dbreq(\"GET\",lbmgmthost,\"#{lbmgmtpath}/instances\",lbmgmtport,lbmgmtscheme)\n CloudDB::Exception.raise_exception(response) unless response.code.to_s.match(/^20.$/)\n instances = CloudDB.symbolize_keys(JSON.parse(response.body)[\"instances\"])\n return instances\n end",
"def detach()\n $ec2.describe_volumes([self.id]).each do |result|\n if result[:aws_attachment_status] == 'attached'\n $ec2.detach_volume(self.id)\n end\n end\n self.attached_instance = nil\n self.save()\n end",
"def fetch_instances(allow_states = nil, reject_states = nil)\n Egi::Fedcloud::Vmhound::Log.debug \"[#{self.class}] Retrieving instances: \" \\\n \"allow_states=#{allow_states.inspect} & \" \\\n \"reject_states=#{reject_states.inspect}\"\n return if allow_states && allow_states.empty?\n reject_states ||= []\n\n @vm_pool_ary ||= fetch_instances_batch_pool(@vm_pool)\n @vm_pool_ary.collect { |vm| fetch_instances_vm(vm, allow_states, reject_states) }.compact\n end",
"def clean_instances(allowed_age, whitelist=nil)\n deleted = []\n undeleted = []\n @gate.instances.each do |instance|\n if is_opsworks_instance instance\n undeleted << instance.inspect\n else\n if expired(instance.launch_time,allowed_age) and instance.status != :terminated\n begin\n if whitelisted(instance.instance_id, whitelist)\n undeleted << instance.inspect\n else\n instance.api_termination_disabled=false\n instance.delete\n deleted << instance.inspect\n end\n rescue AWS::Errors::Base => e\n undeleted << instance.inspect\n end\n end\n end\n end\n return deleted, undeleted\n end",
"def terminate_instances\n @task.unsafe(\"Stopping #{@name} Launch process\") do\n autoscaling_group.suspend_processes('Launch')\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Terminating instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.terminate\n end\n end\n end",
"def terminate_instances\n @task.unsafe(\"Stopping #{@name} Launch process\") do\n autoscaling_group.suspend_processes('Launch')\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Terminating instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.terminate\n end\n end\n end",
"def stop_instances\n @task.unsafe(\"Stopping #{@name} processes\") do\n autoscaling_group.suspend_all_processes\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Stopping instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.stop\n end\n end\n end",
"def aws_terminate_instance_and_ebs_volumes( iprops )\n ec2 = AWS::EC2.new.regions[ iprops[ :region ] ]\n inst = ec2.instances[ iprops[ :id ] ]\n unless inst.exists?\n raise \"Instance #{iprops[:id]} does not exist in #{iprops[:region]}\"\n end\n\n ebs_volumes = inst.block_devices.map do |dev|\n ebs = dev[ :ebs ]\n if ebs && dev[:device_name] =~ /dh\\d+$/ && !ebs[:delete_on_termination]\n ebs[ :volume_id ]\n end\n end.compact\n\n inst.terminate\n wait_until( \"termination of #{inst.id}\", 2.0 ) { inst.status == :terminated }\n\n ebs_volumes = ebs_volumes.map do |vid|\n volume = ec2.volumes[ vid ]\n if volume.exists?\n volume\n else\n puts \"WARN: #{volume} doesn't exist\"\n nil\n end\n end.compact\n\n ebs_volumes.each do |vol|\n wait_until( \"deletion of vol #{vol.id}\" ) do\n vol.status == :available || vol.status == :deleted\n end\n vol.delete if vol.status == :available\n end\n\n found = aws_find_instance( iprops )\n if found\n aws_instance_removed( found )\n aws_write_instances\n end\n end",
"def remove_instance(instance)\n deregister_response = client.deregister_instances_from_load_balancer(load_balancer_name: name,\n instances: [{instance_id: instance.ec2_instance_id}])\n remaining_instance_count = deregister_response.instances.size\n puts \"Removed #{instance.hostname} from ELB #{name}. Remaining instances: #{remaining_instance_count}\".light_blue\n _wait_for_connection_draining\n end",
"def get_balancer_rejections(args)\n if args.key? 'LIMIT'\n limit = args['LIMIT']\n else\n limit = 250\n end\n\n log_type = 'BALANCER_REJECTION'\n log_dest = org.apache.hadoop.hbase.client.ServerType::MASTER\n balancer_rejections_responses = @admin.getLogEntries(nil, log_type, log_dest, limit, nil)\n balancer_rejections_resp_arr = []\n balancer_rejections_responses.each { |balancer_dec_resp|\n balancer_rejections_resp_arr << balancer_dec_resp.toJsonPrettyPrint\n }\n balancer_rejections_resp_arr\n end",
"def diff(aws)\n diffs = []\n\n if aws.ebs_optimized != @ebs_optimized\n diffs << InstanceDiff.new(InstanceChange::EBS, aws.ebs_optimized, @ebs_optimized)\n end\n\n if aws.profile != @profile\n diffs << InstanceDiff.new(InstanceChange::PROFILE, aws.profile, @profile)\n end\n\n if aws.monitoring != @monitoring\n diffs << InstanceDiff.new(InstanceChange::MONITORING, aws.monitoring, @monitoring)\n end\n\n if aws.network_interfaces != @network_interfaces\n diffs << InstanceDiff.new(InstanceChange::INTERFACES, aws.network_interfaces, @network_interfaces)\n end\n\n if aws.source_dest_check != @source_dest_check\n diffs << InstanceDiff.new(InstanceChange::SDCHECK, aws.source_dest_check, @source_dest_check)\n end\n\n if aws.security_groups.sort != @security_groups.sort\n changes = Common::ListChange::simple_list_diff(aws.security_groups, @security_groups)\n diffs << InstanceDiff.new(InstanceChange::SECURITY_GROUPS, aws.security_groups, @security_groups, changes)\n end\n\n if aws.subnet != @subnet\n diffs << InstanceDiff.new(InstanceChange::SUBNET, aws.subnet, @subnet)\n end\n\n if aws.type != @type\n diffs << InstanceDiff.new(InstanceChange::TYPE, aws.type, @type)\n end\n\n if aws.tenancy != @tenancy\n diffs << InstanceDiff.new(InstanceChange::TENANCY, aws.tenancy, @tenancy)\n end\n\n if aws.tags != @tags\n diffs << InstanceDiff.new(InstanceChange::TAGS, aws.tags, @tags)\n end\n\n # Check for diffs in volume groups and diffs in how many volumes are attached\n\n # Get the volumes that are attached to the instance\n aws_instance = EC2::named_instances[aws.name]\n attached_volumes = aws_instance.nonroot_devices.map do |m|\n EC2::id_ebs_volumes[m.ebs.volume_id]\n end\n # Group by volume group, reject nil groups\n group_volumes = attached_volumes.group_by(&:group).reject { |k, v| k.nil? }\n\n aws_ebs_groups = Hash[group_volumes.map { |group, vols| [group, EbsGroupConfig.new(group).populate!(vols)] }]\n local_ebs_groups = Hash[@volume_groups.map { |vg| [vg, EC2::group_ebs_volumes[vg]] }]\n\n added_groups = Hash[local_ebs_groups.reject { |k, v| aws_ebs_groups.has_key?(k) }.map do |group_name, group_config|\n [group_name, EbsGroupDiff.added(group_config)]\n end]\n removed_groups = Hash[aws_ebs_groups.reject { |k, v| aws_ebs_groups.has_key?(k) }.map do |group_name, group_config|\n [group_name, EbsGroupDiff.unmanaged(group_config)]\n end]\n changed_groups = Hash[local_ebs_groups.select { |k, v| aws_ebs_groups.has_key?(k) }.map do |group_name, group_config|\n aws_config = aws_ebs_groups[group_name]\n group_diffs = group_config.diff(aws_config)\n if !group_diffs.empty?\n [group_name, EbsGroupDiff.modified(aws_config, group_config, group_diffs)]\n end\n end.reject { |v| v.nil? }]\n\n ebs_changes = Common::ListChange.new(added_groups, removed_groups, changed_groups)\n if !ebs_changes.empty?\n diffs << InstanceDiff.new(InstanceChange::VOLUME_GROUPS, aws_ebs_groups, local_ebs_groups, ebs_changes)\n end\n\n diffs\n end",
"def ebs_volumes\n @ebs_volumes ||= init_ebs_volumes.reject do |vol|\n vol.attachments.any? do |att|\n attached_instance = id_instances[att.instance_id]\n attached_instance.root_device_name == att.device\n end\n end\n end",
"def find_instances(tags)\n attempts = 0\n begin\n ec2.servers.select { |server| tags.reject { |k,v| server.tags[k] == tags[k] }.empty? }\n rescue Excon::Errors::ServiceUnavailable\n sleep 5\n attempts += 1\n return [] if attempts == 5\n retry\n end\n end",
"def list_deadservers\n @admin.listDeadServers.to_a\n end",
"def instances\n @instances ||= init_instances.reject(&:terminated?)\n end",
"def get_instances(incl_stopped=false)\n \n instances = @ec2.describe_instances\n instances = instances.select { |x| x[:aws_groups].include? @group_name }\n \n if(instances.length == 0)\n raise CaTPAWS::EC2::Error::InstanceRetrieval, \"No instances found in this group\"\n end \n \n unless (incl_stopped)\n instances = instances.select {|x| x[:aws_state_code].to_i <= 16}\n end\n @instances = instances\n end",
"def when_no_pending_instances(&block)\n reset! \n if list_of_pending_instances.size == 0\n block.call if block\n else\n vprint \".\"\n wait \"5.seconds\"\n when_no_pending_instances(&block)\n end\n end",
"def get_balancer_decisions(args)\n if args.key? 'LIMIT'\n limit = args['LIMIT']\n else\n limit = 250\n end\n log_type = 'BALANCER_DECISION'\n log_dest = org.apache.hadoop.hbase.client.ServerType::MASTER\n balancer_decisions_responses = @admin.getLogEntries(nil, log_type, log_dest, limit, nil)\n balancer_decisions_resp_arr = []\n balancer_decisions_responses.each { |balancer_dec_resp|\n balancer_decisions_resp_arr << balancer_dec_resp.toJsonPrettyPrint\n }\n balancer_decisions_resp_arr\n end",
"def init_instances\n instances = []\n next_token = nil\n all_records_retrieved = false\n\n until all_records_retrieved\n response = @@client.describe_instances({\n next_token: next_token\n })\n next_token = response.next_token\n all_records_retrieved = next_token.nil? || next_token.empty?\n instances << response.reservations.map { |r| r.instances }\n end\n\n instances.flatten\n end",
"def retrieve_elb(name)\n Clients.elb.describe_load_balancers(\n load_balancer_names: [name],\n ).load_balancer_descriptions[0]\nend",
"def stop_instances\n @task.unsafe(\"Stopping #{@name} processes\") do\n save_to_s3(@task.bucket)\n autoscaling_group.suspend_all_processes\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Stopping instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.stop\n end\n end\n end",
"def manage_planned_volumes(&block)\n # state may have changed since timer calling this method was added, so\n # ensure we are still booting (and not stranded).\n return if InstanceState.value == 'stranded'\n\n # query for planned volume mappings belonging to instance.\n last_mappings = InstanceState.planned_volume_state.mappings || []\n payload = {:agent_identity => @agent_identity}\n req = RetryableRequest.new(\"/storage_valet/get_planned_volumes\", payload, :retry_delay => VolumeManagement::VOLUME_RETRY_SECONDS)\n req.callback do |res|\n res ||= [] # res is nil or an array of hashes\n begin\n mappings = merge_planned_volume_mappings(last_mappings, res)\n InstanceState.planned_volume_state.mappings = mappings\n if mappings.empty?\n # no volumes requiring management.\n @audit.append_info(\"This instance has no planned volumes.\")\n block.call if block\n elsif (detachable_volume_count = mappings.count { |mapping| is_unmanaged_attached_volume?(mapping) }) >= 1\n # must detach all 'attached' volumes if any are attached (or\n # attaching) but not yet managed on the instance side. this is the\n # only way to ensure they receive the correct device names.\n mappings.each do |mapping|\n if is_unmanaged_attached_volume?(mapping)\n detach_planned_volume(mapping) do\n detachable_volume_count -= 1\n if 0 == detachable_volume_count\n # add a timer to resume volume management later and pass the\n # block for continuation afterward (unless detachment stranded).\n Log.info(\"Waiting for volumes to detach for management purposes. \"\\\n \"Retrying in #{VolumeManagement::VOLUME_RETRY_SECONDS} seconds...\")\n EM.add_timer(VolumeManagement::VOLUME_RETRY_SECONDS) { manage_planned_volumes(&block) }\n end\n end\n end\n end\n elsif mapping = mappings.find { |mapping| is_detaching_volume?(mapping) }\n # we successfully requested detachment but status has not\n # changed to reflect this yet.\n Log.info(\"Waiting for volume #{mapping[:volume_id]} to fully detach. \"\\\n \"Retrying in #{VolumeManagement::VOLUME_RETRY_SECONDS} seconds...\")\n EM.add_timer(VolumeManagement::VOLUME_RETRY_SECONDS) { manage_planned_volumes(&block) }\n elsif mapping = mappings.find { |mapping| is_managed_attaching_volume?(mapping) }\n Log.info(\"Waiting for volume #{mapping[:volume_id]} to fully attach. Retrying in #{VolumeManagement::VOLUME_RETRY_SECONDS} seconds...\")\n EM.add_timer(VolumeManagement::VOLUME_RETRY_SECONDS) { manage_planned_volumes(&block) }\n elsif mapping = mappings.find { |mapping| is_managed_attached_unassigned_volume?(mapping) }\n manage_volume_device_assignment(mapping) do\n unless InstanceState.value == 'stranded'\n # we can move on to next volume 'immediately' if volume was\n # successfully assigned its device name.\n if mapping[:management_status] == 'assigned'\n EM.next_tick { manage_planned_volumes(&block) }\n else\n Log.info(\"Waiting for volume #{mapping[:volume_id]} to initialize using \\\"#{mapping[:mount_points].first}\\\". \"\\\n \"Retrying in #{VolumeManagement::VOLUME_RETRY_SECONDS} seconds...\")\n EM.add_timer(VolumeManagement::VOLUME_RETRY_SECONDS) { manage_planned_volumes(&block) }\n end\n end\n end\n elsif mapping = mappings.find { |mapping| is_detached_volume?(mapping) }\n attach_planned_volume(mapping) do\n unless InstanceState.value == 'stranded'\n unless mapping[:attempts]\n @audit.append_info(\"Attached volume #{mapping[:volume_id]} using \\\"#{mapping[:mount_points].first}\\\".\")\n Log.info(\"Waiting for volume #{mapping[:volume_id]} to appear using \\\"#{mapping[:mount_points].first}\\\". \"\\\n \"Retrying in #{VolumeManagement::VOLUME_RETRY_SECONDS} seconds...\")\n end\n EM.add_timer(VolumeManagement::VOLUME_RETRY_SECONDS) { manage_planned_volumes(&block) }\n end\n end\n elsif mapping = mappings.find { |mapping| is_unmanageable_volume?(mapping) }\n strand(\"State of volume #{mapping[:volume_id]} was unmanageable: #{mapping[:volume_status]}\")\n else\n # all volumes are managed and have been assigned and so we can proceed.\n block.call if block\n end\n rescue Exception => e\n strand(e)\n end\n end\n\n req.errback do |res|\n strand(\"Failed to retrieve planned volume mappings\", res)\n end\n\n req.run\n end",
"def diff(aws)\n diffs = []\n\n if @target != aws.target\n diffs << DeadLetterDiff.new(DeadLetterChange::TARGET, aws.target, @target)\n end\n\n if @max_receives != aws.max_receives\n diffs << DeadLetterDiff.new(DeadLetterChange::RECEIVE, aws.max_receives, @max_receives)\n end\n\n diffs\n end",
"def check_pool()\n\n machines_up = []\n machines_down = []\n machines = @resource[:pool]\n machines.each do |machine|\n if alive?(machine)\n machines_up << machine\n else\n machines_down << machine\n end\n end\n return machines_up, machines_down\n \n end",
"def beanstalks\n return @beanstalks ||= @beanstalk_servers.map(&:beanstalk)\n end",
"def list_instance_snapshots(rds_resource)\n instance_snapshots = []\n rds_resource.db_snapshots.each do |s|\n instance_snapshots.append({\n \"id\": s.snapshot_id,\n \"status\": s.status\n })\n end\n instance_snapshots\nrescue Aws::Errors::ServiceError => e\n puts \"Couldn't list instance snapshots:\\n #{e.message}\"\nend",
"def describe_listeners(load_balancer_arn, options = {})\n request({\n 'Action' => 'DescribeListeners',\n 'LoadBalancerArn' => load_balancer_arn,\n :parser => Fog::Parsers::AWS::ELBV2::DescribeListeners.new\n }.merge!(options))\n end",
"def pending_snapshots(rds_instance)\n snaps = rds_instance.snapshots\n snaps.select do |snap|\n snap.status == 'creating'\n end\n end",
"def grab_scannable_instances(address_blob, active_addresses)\n # list to hold all addresses of a region\n ec2_addresses_list = []\n address_blob.each do |address|\n # gathers all ip addresses for a region and pushes all of them to ec2_addresses_list\n # if they are still active in the account\n ec2_addresses_list.push(address['public_ip_address']) if active_addresses.include?(address['public_ip_address'])\n end\n ec2_addresses_list\nend",
"def check_arguments(instance:, load_balancers:)\n unless instance.is_a?(Aws::OpsWorks::Types::Instance)\n fail(ArgumentError,\n \":instance must be a Aws::OpsWorks::Types::Instance struct\")\n end\n unless load_balancers.respond_to?(:each) &&\n load_balancers.all? do |lb|\n lb.is_a?(Aws::ElasticLoadBalancing::Types::LoadBalancerDescription)\n end\n fail(ArgumentError, <<-MSG.split.join(\" \"))\n :load_balancers must be a collection of\n Aws::ElasticLoadBalancing::Types::LoadBalancerDescription objects\n MSG\n end\n end",
"def terminate\n waiters.each do |k,v|\n v[:threads].each do |thread|\n thread.raise ::Zoidberg::DeadException.new('Instance in terminated state!', object_id)\n end\n end\n end",
"def cleanup(vpc_id, client, asg, elbv1, elbv2, region)\n begin\n response = client.describe_vpcs(vpc_ids: [vpc_id])\n rescue Aws::EC2::Errors::InvalidVpcIDNotFound => e\n puts \"Error: vpc_id [#{vpc_id}] does not exist... exiting.\"\n puts \"Make sure you passed the correct region on the command-line if it's not in the default us-west-2\"\n exit 0\n end\n\n # 1) Delete Auto Scaling group\n begin\n asg.delete_auto_scaling_group(auto_scaling_group_name: 'asg-nginx_auto', force_delete: true)\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n\n sleep 2\n # TODO: properly wait here until ASG is fully deleted before proceeding...\n begin\n asg.delete_launch_configuration(launch_configuration_name: 'lc-nginx_auto')\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n sleep 2\n\n # 2) instance handling\n term_error = 0\n instances_to_term = []\n terminate_states = %w[pending running shutting-down stopping stopped]\n puts 'Checking for nginx and nat instances, of all states...'\n begin\n response = client.describe_instances(filters: [{name: 'tag:Name', values: ['autoASG nginx server',\n 'nat instance']}])\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n response.reservations.each do |reservation|\n reservation.instances.each do |instance|\n puts \"Check #1: instance-id=[#{instance.instance_id}] AMI=[#{instance.image_id}] state=[#{instance.state.name}]\"\n instances_to_term.push(instance.instance_id) if terminate_states.include? instance.state.name\n end\n end\n\n if instances_to_term.any? # If array has content, proceed.\n term_error = 0\n instance_cnt = instances_to_term.length # TODO: Check before/after termination attempts and ensure = 0\n before_terminate = Time.now\n begin\n client.wait_until(:instance_terminated,instance_ids: instances_to_term) do |wait|\n wait.interval = 8 # Seconds between polling attempts. Same as wait.delay\n wait.max_attempts = 15 # Polling attempts before giving up. Wait time is 15*8=120 seconds.\n puts \"Attempting to terminate [#{instance_cnt}] instance(s), please wait up to 120 seconds...\"\n begin\n client.terminate_instances(instance_ids: instances_to_term)\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n end\n rescue Aws::Waiters::Errors::WaiterFailed => error\n term_error = 1 # TODO: Do something more reliable if this ever occurs.\n puts \"Exception: failed waiting for instance running: #{error.message}\"\n end\n puts \"#{Time.now - before_terminate.to_time} seconds elapsed while terminating.\" if term_error.zero?\n end\n\n if term_error.zero?\n # Debug with final instance check... this shouldn't print anything aside from terminated instances.\n begin\n response = client.describe_instances(filters: [{name: 'tag:Name', values: ['autoASG nginx server',\n 'nat instance']}])\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n response.reservations.each do |reservation|\n reservation.instances.each do |instance|\n puts \"Check #2: instance-id=[#{instance.instance_id}] AMI=[#{instance.image_id}] state=[#{instance.state.name}]\"\n end\n end\n end\n\n puts 'Sleeping for 5 seconds...'\n sleep 5\n\n # 3) Delete listeners\n printf 'Deleting ALB listeners... '\n begin\n response = elbv2.describe_load_balancers(names: ['AutoALB'])\n alb_arn = response.load_balancers[0].load_balancer_arn\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n sleep 2\n begin\n response = elbv2.describe_listeners(load_balancer_arn: alb_arn)\n listener_arn = response.listeners[0].listener_arn\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n begin\n elbv2.delete_listener(listener_arn: listener_arn)\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n sleep 2\n puts 'done.'\n\n # 4) Delete target groups\n printf 'Deleting ALB target groups... '\n begin\n response = elbv2.describe_target_groups(names: ['AutoALBTargetGroup'])\n target_group_arn = response.target_groups[0].target_group_arn\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n begin\n elbv2.delete_target_group(target_group_arn: target_group_arn)\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n sleep 5\n puts 'done.'\n\n # 5) Delete load balancers\n printf 'Deleting application and classic load balancers... '\n begin\n elbv1.delete_load_balancer(load_balancer_name: 'AutoCLB')\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n begin\n elbv2.delete_load_balancer(load_balancer_arn: alb_arn)\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n puts 'done.'\n\n puts 'Sleeping for 120 seconds, enough time for the ASG to fully disappear before deleting subnets.'\n sleep 120\n\n # 6) subnets\n begin\n response = client.describe_subnets(filters: [{name: 'vpc-id', values: [vpc_id]}])\n response.subnets.each do |sn|\n printf \"Removing subnet: #{sn.subnet_id}, #{sn.vpc_id}, #{sn.cidr_block}, #{sn.availability_zone}; \"\n client.delete_subnet(subnet_id: sn.subnet_id)\n puts 'Done.'\n end\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n\n # 7) security groups\n begin\n response = client.describe_security_groups(filters: [{name: 'vpc-id', values: [vpc_id]}])\n response.security_groups.each do |sg|\n next if sg.group_name == 'default' # This name is reserved by aws and cannot be removed.\n printf \"Removing security group: #{sg.group_id}, #{sg.vpc_id}, #{sg.group_name}, Desc='#{sg.description}'; \"\n client.delete_security_group(group_id: sg.group_id)\n puts 'Done.'\n end\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n\n # 8) Internet gateway\n begin\n response = client.describe_internet_gateways(filters: [{name: 'attachment.vpc-id', values: [vpc_id]}])\n response.internet_gateways.each do |igw|\n printf \"Detaching Internet gateway: #{igw.internet_gateway_id} <-> #{igw.attachments[0].vpc_id}; \"\n client.detach_internet_gateway(internet_gateway_id: igw.internet_gateway_id, vpc_id: igw.attachments[0].vpc_id)\n printf \"Removing Internet gateway: #{igw.internet_gateway_id} <-> #{igw.attachments[0].vpc_id}; \"\n client.delete_internet_gateway(internet_gateway_id: igw.internet_gateway_id)\n puts 'Done.'\n end\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n\n # 9) Route tables\n begin\n response = client.describe_route_tables(filters: [{name: 'vpc-id', values: [vpc_id]}])\n response.route_tables.each do |rtl|\n if rtl.associations[0] != nil\n if rtl.associations[0].route_table_association_id != nil\n puts \"Skipping #{rtl.associations[0].route_table_association_id}, causes exception.\"\n end\n next\n end\n printf \"Removing route table: #{rtl.route_table_id}, #{rtl.vpc_id}; \"\n client.delete_route_table(route_table_id: rtl.route_table_id)\n puts 'Done.'\n end\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n\n # 10) Delete VPC\n begin\n puts \"Attempting to delete VPC [#{vpc_id}]\"\n client.delete_vpc(vpc_id: vpc_id)\n rescue StandardError => e\n puts \"Exception caught: #{e}, attempting to complete.\"\n end\n\n begin\n response = client.describe_vpcs(vpc_ids: [vpc_id])\n rescue Aws::EC2::Errors::InvalidVpcIDNotFound => e\n puts \"Deletion of vpc_id=[#{vpc_id}] was a success.\"\n exit 0\n end\n\n # Shouldn't get here, but sometimes does due to the ASG taking too long to\n # release subnet dependencies, or if running a cleanup before a launch has\n # fully completed, etc.\n puts 'Oops. Termination sometimes fails for various reasons.'\n puts 'Note: running this twice usually clears up any lingering dependencies.'\n puts ' With that said, there is still work to be done. Execute again.'\n exit 0\nend",
"def unmonitor_instances( options = {} )\n options = { :instance_id => [] }.merge(options)\n raise ArgumentError, \"No :instance_id provided\" if options[:instance_id].nil? || options[:instance_id].empty?\n params = pathlist(\"InstanceId\", options[:instance_id])\n return response_generator(:action => \"UnmonitorInstances\", :params => params)\n end",
"def list_blurbs \\\n parent,\n page_size,\n page_token,\n options: nil,\n &block\n request = {\n parent: parent,\n page_size: page_size,\n page_token: page_token\n }.delete_if { |_, v| v.nil? }\n request = Google::Gax.to_proto request, Google::Showcase::V1alpha3::ListBlurbsRequest\n @list_blurbs.call(request, options, &block)\n end",
"def balancer_all(options = {})\n load_balancer_data\n end",
"def terminate(instance, decrement=false)\n Log.log \"Detaching #{instance.instance_id.light_yellow} from ASG\"\n client.detach_instances(\n instance_ids: [ instance.instance_id ],\n auto_scaling_group_name: asg_name,\n should_decrement_desired_capacity: false)\n\n # need to describe the instance status in the asg here so that we wait till connections have drained.\n count = 0\n Log.log \"Awaiting connection draining... \", newline: false\n while present?(instance.instance_id) && count < 120\n sleep 1\n count += 1\n end\n Log.log \"done\", timestamp: false\n\n Log.log \"Terminating #{instance.instance_id.light_red}... \", newline: false\n ec2_client.terminate_instances(instance_ids: [ instance.instance_id ])\n Log.log \"done\", timestamp: false\n end",
"def remote_node_bags\n bags = []\n bag_query = { admin_node: remote_node.namespace }\n local_client.bags(bag_query) do |response|\n bags << response.body if response.success?\n end\n bags.flatten\n end",
"def list_instances()\n response = dbreq(\"GET\", dbmgmthost, \"#{dbmgmtpath}/instances\", dbmgmtport, dbmgmtscheme)\n CloudDB::Exception.raise_exception(response) unless response.code.to_s.match(/^20.$/)\n instances = CloudDB.symbolize_keys(JSON.parse(response.body)[\"instances\"])\n return instances\n end",
"def list_of_pending_instances(list = list_of_nonterminated_instances)\n list.select {|a| a if a.pending? }\n end",
"def load_balancer_names\n @group.load_balancer_names\n end",
"def instances\n Egi::Fedcloud::Vmhound::Log.info \"[#{self.class}] Retrieving active instances\"\n fetch_instances\n end",
"def test_00_describe_load_balancers\n items = @elb.describe_load_balancers\n assert items.is_a?(Array)\n end",
"def list_of_pending_instances(list = list_of_nonterminated_instances)\n list.select {|a| a.pending? }\n end",
"def list_of_terminating_instances(list = remote_instances_list)\n list.reject {|i| true if !i.terminating? }\n end",
"def list_of_terminating_instances(list = remote_instances_list)\n list.reject {|i| true if !i.terminating? }\n end",
"def active_instances\n Egi::Fedcloud::Vmhound::Log.info \"[#{self.class}] Retrieving running instances\"\n fetch_instances ['ACTIVE']\n end",
"def balancer_set_instances(balancer)\n balancer\n end",
"def diff(aws)\n diffs = []\n\n if @load_balancer_protocol != aws.listener.protocol\n diffs << ListenerDiff.new(ListenerChange::LB_PROTOCOL, aws.listener.protocol, @load_balancer_protocol)\n end\n\n if @load_balancer_port != aws.listener.load_balancer_port\n diffs << ListenerDiff.new(ListenerChange::LB_PORT, aws.listener.load_balancer_port, @load_balancer_port)\n end\n\n if @instance_protocol != aws.listener.instance_protocol\n diffs << ListenerDiff.new(ListenerChange::INST_PROTOCOL, aws.listener.instance_protocol, @instance_protocol)\n end\n\n if @instance_port != aws.listener.instance_port\n diffs << ListenerDiff.new(ListenerChange::INST_PORT, aws.listener.instance_port, @instance_port)\n end\n\n if @ssl_certificate_id != aws.listener.ssl_certificate_id\n diffs << ListenerDiff.new(ListenerChange::SSL, aws.listener.ssl_certificate_id, @ssl_certificate_id)\n end\n\n if @policies.sort != aws.policy_names.sort\n diffs << ListenerDiff.policies(aws.policy_names, @policies)\n end\n\n diffs\n end",
"def list_instances_detail()\n response = dbreq(\"GET\", dbmgmthost, \"#{dbmgmtpath}/instances/detail\", dbmgmtport, dbmgmtscheme)\n CloudDB::Exception.raise_exception(response) unless response.code.to_s.match(/^20.$/)\n instances = CloudDB.symbolize_keys(JSON.parse(response.body)[\"instances\"])\n return instances\n end",
"def scale_down\n \n num_stopped = 0\n # lets figure out what we can shut down.\n logger.info \"Looking for unused instances to scale down...\"\n EventLog.info \"Looking for unused instances to scale down...\"\n instances.each do |i|\n #this is actually pretty complicated. we have to figure out the exact range for each instance, based on the instance launch time\n lt = i.launch_time\n lt_diff = 60 - lt.min\n lower_range = HOUR_MOD - lt_diff #careful, it could be negative!\n lower_range = lower_range + 60 if lower_range < 0 # adjust for negative!\n\n upper_range = lower_range + (60 - HOUR_MOD) #upper range for mins, could be > 59!\n upper_range = upper_range - 60 if upper_range > 59 #correct for over 59\n\n now_min = DateTime.now.min\n \n ### DEBUG shutdown logic\n # puts \"Instance: #{i.aws_instance_id}\"\n # puts \"Now: #{now_min}\"\n # puts \"Upper: #{upper_range}\"\n # puts \"Lower: #{lower_range}\"\n\n if (now_min > lower_range && now_min < upper_range) || ((upper_range < lower_range) && (now_min < upper_range || now_min > lower_range))\n #so lets shutdown, but only if it won't bring us below the min_running threshold\n\n #first find out how many instances are running of this type\n total_running = (instances.select{ |j| j.running? }).size\n unless ((total_running - 1) < min || (! i.available? && ! i.error? ) || (farm_type.eql?('admin')))\n # for now we shutdown via aws but this will change as we figure out a better way\n logger.info \"Shutting down #{i.farm.ami_id} -- #{i.instance_id} due to IDLE timeout.\"\n EventLog.info \"Shutting down #{i.farm.ami_id} -- #{i.instance_id} due to IDLE timeout.\"\n i.terminate\n num_stopped += 1\n end\n end\n end\n\n return num_stopped\n\n end",
"def wait_for_status_checks(status)\n @logger.notify(\"netscaler: Now wait for all hosts' status checks to reach state #{status}\")\n @hosts.each do |host|\n instance = host['instance']\n name = host.name\n\n @logger.notify(\"netscaler: Wait for status check #{status} for node #{name}\")\n\n # TODO: should probably be a in a shared method somewhere\n for tries in 1..10\n begin\n if instance.client.describe_instance_status({:instance_ids => [instance.id]})[:instance_status_set].first[:system_status][:status] == status\n # Always sleep, so the next command won't cause a throttle\n backoff_sleep(tries)\n break\n elsif tries == 10\n raise \"Instance never reached state #{status}\"\n end\n rescue AWS::EC2::Errors::InvalidInstanceID::NotFound => e\n @logger.debug(\"Instance #{name} not yet available (#{e})\")\n end\n backoff_sleep(tries)\n end\n end\n end",
"def instances\n instances = []\n JSON.parse(resource['/instances'].get)[\"instances\"].each do |i|\n instances << Instance.new(i)\n end\n return instances\n end",
"def remove_from_lb(group)\n @haproxy.identity_filter(@load_balancer)\n # We don't have to identify the nodes in the group\n # for every action. I'm doing it here to make each\n # method easier to read\n @rpcutil.class_filter(group)\n begin\n @rpcutil.ping.each do |node|\n hostname = node.results[:sender]\n # Disable the nodes\n @haproxy.disable(:backend => 'puppetcamp', :server => hostname).each do |rpcresult|\n if rpcresult.results[:statuscode] != 0\n raise LoadBalancerRemoveException, hostname\n end\n end\n end\n ensure\n @haproxy.reset_filter\n @rpcutil.reset_filter\n end\nend",
"def load_bills()\n params = {'history.active' => true}\n params['order'] = 'last_action_at'\n @bills = process('bills', 'bills', params)\n end",
"def live_bets\n self.bets.select {|bet| bet.status == \"Pending\"}\n end",
"def describe_listeners(lb_id = nil, listener_ids = [], options = {})\n listener_ids = Array(listener_ids)\n params = {}\n params['Marker'] = options[:marker] if options[:marker]\n params['PageSize'] = options[:page_size] if options[:page_size]\n\n params['LoadBalancerArn'] = lb_id if lb_id\n params.merge!(Fog::AWS.serialize_keys('ListenerArns', listener_ids)) if listener_ids.any?\n request({\n 'Action' => 'DescribeListeners',\n :parser => Fog::Parsers::AWS::ELBV2::DescribeListeners.new\n }.merge(params))\n end",
"def attach_to_elb(instance, elb_name, subnet = nil)\n begin\n @log.info \"\"\n @log.info \"Adding to ELB: #{elb_name}\"\n elb = AWS::ELB.new\n AWS.memoize do\n unless subnet\n # Build list of availability zones for any existing instances\n zones = { }\n zones[instance.availability_zone] = instance.availability_zone\n elb.load_balancers[elb_name].instances.each do |elb_instance|\n zones[elb_instance.availability_zone] = elb_instance.availability_zone\n end\n \n # Build list of existing zones\n existing_zones = { }\n elb.load_balancers[elb_name].availability_zones.each do |zone|\n existing_zones[zone.name] = zone\n end\n \n # Enable zones\n zones.keys.each do |zone_name|\n elb.load_balancers[elb_name].availability_zones.enable(zones[zone_name])\n end\n \n # Disable zones\n existing_zones.keys.each do |zone_name|\n elb.load_balancers[elb_name].availability_zones.disable(existing_zones[zone_name]) unless zones.has_key?(zone_name)\n end\n end\n \n elb.load_balancers[elb_name].instances.register(instance)\n end\n rescue StandardError => bang\n @log.error \"Error adding to load balancers: \" + bang.to_s\n end\n end",
"def update_instances(elb_name, instances_added, instances_removed = [])\n\n # deregister instances that were removed\n if !instances_removed.empty?\n @elb.deregister_instances_from_load_balancer({\n load_balancer_name: elb_name,\n instances: instances_removed.map do |i|\n {\n instance_id: i\n }\n end\n })\n end\n\n # register instances that were added\n if !instances_added.empty?\n @elb.register_instances_with_load_balancer({\n load_balancer_name: elb_name,\n instances: instances_added.map do |i|\n {\n instance_id: i\n }\n end\n })\n end\n end",
"def get_running_instances(group)\n get_instances(group).select{ |instance| instance.ready? }\n end",
"def demand_broken_bikes_from(container)\n while should_collect_broken_bikes?(container) do\n collected_bike = container.offload_broken_bike\n load(collected_bike)\n end\n end",
"def instances\n @instances ||= aws_client.instances(filters: instance_filters).map do |instance|\n OpenStruct.new(\n with_tags(instance, private_ip: instance.private_ip_address,\n public_ip: instance.public_ip_address,\n instance: instance.instance_id)\n )\n end\n end",
"def fetch_instance(shortname = :all, options = {})\n return instances if instances && !options[:force]\n\n fetch_stack\n unless instance_list\n self.instance_list = self.instances =\n aws_client.describe_instances(stack_id: stack[:stack_id])[:instances]\n end\n\n if shortname != :all\n fetch_layer(shortname, force: true)\n self.instances = []\n\n layers.each do |layer|\n instance = aws_client.describe_instances(\n layer_id: layer[:layer_id])\n self.instances << instance[:instances]\n end\n\n self.instances.flatten!\n end\n end",
"def delete_instances(count)\n instances_to_delete = current_instances.last(count) \n parent.terminate_instances(Group.instance_ids(instances_to_delete))\n # remaining_instances under alive\n Output.new(current_instances.first(current_instances.size - count), instances_to_delete)\n end",
"def detach_disks_specs\n detach_disk_array = []\n extra_config = []\n keys = disk_keys.invert\n\n ipool = VCenterDriver::VIHelper.one_pool(OpenNebula::ImagePool)\n disks_each(:detached?) do |d|\n key = d.key.to_s\n source = VCenterDriver::FileHelper.escape_path(d.path)\n persistent =\n VCenterDriver::VIHelper\n .find_persistent_image_by_source(\n source, ipool\n )\n\n op = { :operation => :remove, :device => d.device }\n if !persistent && d.type != 'CDROM'\n op[:fileOperation] = :destroy\n end\n detach_disk_array << op\n\n # Remove reference opennebula.disk if exist from vmx and cache\n extra_config << d.config(:delete) if keys[key]\n end\n\n [detach_disk_array, extra_config]\n end",
"def down_ballot_voters(*conds, &block)\n __eager_ballot_voters(\n find_ballots_for(*conds, &block).where(vote: false)\n )\n end",
"def stop_instances_by_group_id(group_id)\n instances = @os_aws.describe_running_instances(group_id)\n ids = instances.map { |k, _| k[:instance_id] }\n\n puts \"Stoping the following instances #{ids}\"\n resp = []\n resp = @os_aws.stop_instances(ids).to_hash unless ids.empty?\n resp\n end",
"def reboot_instances(list)\n link = generate_request(\"RebootInstances\", hash_params('InstanceId', list.to_a))\n request_info(link, RightBoolResponseParser.new(:logger => @logger))\n rescue Exception\n on_exception\n end",
"def instances_list\n return [] unless configured?\n\n @service.fetch_all do |token|\n @service.list_instances(@gcp_config['project'], @gcp_config['zone'], page_token: token)\n end.map(&:name)\n end",
"def instances()\n return @instances\n end",
"def list_databases\n response = @connection.dbreq(\"GET\", @lbmgmthost, \"#{@lbmgmtpath}/instances/#{CloudDB.escape(@id.to_s)}/databases\",@lbmgmtport,@lbmgmtscheme)\n CloudDB::Exception.raise_exception(response) unless response.code.to_s.match(/^20.$/)\n CloudDB.symbolize_keys(JSON.parse(response.body)[\"databases\"])\n end",
"def stop_all_instances\n Spinup.logger.info('Attempting to stop all running instances')\n running_instances = ec2.instances\n\n Spinup.logger.info(\" Found #{running_instances.count} running instances\")\n\n running_instances.each do |running_instance|\n instance_stopped?(running_instance)\n end\n end",
"def health\n health = AWS.memoize do\n load_balancer.instances.health.inject({}) do |h,i|\n instance = i[:instance]\n h[instance.id] = i\n h\n end\n end rescue nil\n end",
"def ballot_down_votables(*conds, &block)\n __eager_ballot_votables(\n find_ballots_by(*conds, &block).where(vote: false)\n )\n end",
"def get_elb(layer_name)\n layer_id = layers[layer_name].layer_id\n elbs = opsworks_client.describe_elastic_load_balancers(layer_ids:[layer_id])\n if elbs.elastic_load_balancers.size > 0\n name = elbs.elastic_load_balancers.first.elastic_load_balancer_name\n ELB.new(name)\n else\n nil\n end\n end",
"def volumes\n volumes = @ec2.volumes\n volumes.delete_if {|v| v.instance_id != id}\n end",
"def work_with_droplets\n load_droplets\n dispatch_droplets\n logger.debug 'Working with list of DigitalOcean droplets'\n thread_chain\n end",
"def offload_broken_bike\n released_bike = broken_bikes.pop\n bikes.delete(released_bike)\n released_bike\n end",
"def remote_ledgers\n remote_splits.collect(&:ledger)\n end",
"def migrate_elbs\n elbs_dir = \"#{@migration_root}/elb-load-balancers\"\n policies_dir =\"#{@migration_root}/elb-policies\"\n\n if !Dir.exists?(@migration_root)\n Dir.mkdir(@migration_root)\n end\n if !Dir.exists?(elbs_dir)\n Dir.mkdir(elbs_dir)\n end\n if !Dir.exists?(policies_dir)\n Dir.mkdir(policies_dir)\n end\n\n ELB::elbs.map do |elb_name, elb|\n puts \"Migrating load balancer #{elb_name}\"\n\n local_elb = LoadBalancerConfig.new(elb_name)\n tags = ELB::elb_tags(elb_name)\n attributes = ELB::elb_attributes(elb_name)\n local_elb.populate!(elb, tags, attributes)\n\n # Migrate the backend and listener policies if they do not already\n # exist locally and are not the default AWS policies\n listener_policies = local_elb.listeners.flat_map { |l| l.policies }\n backend_policies = local_elb.backend_policies.flat_map { |b| b.policy_names }\n\n (listener_policies + backend_policies).uniq.map do |policy_name|\n policy_file = \"#{policies_dir}/#{policy_name}.json\"\n # If it is not already migrated and not a default policy, create it\n if !File.file? policy_file\n if !ELB::default_policies.has_key? policy_name\n # Get the full policy description from the elb policies\n full_policy = ELB::elb_policies(elb_name)[policy_name]\n\n if full_policy.nil?\n puts \"Unable to migrate policy #{policy_name}\"\n else\n puts \"Migrating policy #{policy_name}\"\n json = JSON.pretty_generate(full_policy.to_cumulus_hash)\n File.open(policy_file, \"w\") { |f| f.write(json) }\n end\n end\n end\n end\n\n File.open(\"#{elbs_dir}/#{elb_name}.json\", \"w\") { |f| f.write(local_elb.pretty_json) }\n end\n\n end",
"def detach(options)\n memory_limit = options[:memory_limit] || Float::INFINITY\n max_requests = options[:max_requests] || Float::INFINITY\n\n return if memory <= memory_limit && processed <= max_requests\n\n log({ :type => 'passenger-detach' }.merge(as_json).to_json)\n run(*%W(passenger-config detach-process #{pid}))\n end",
"def list_items_inactive\n return_list = Array.new\n for s in self.offers\n unless s.auction\n if !s.active && !s.auction\n return_list.push(s)\n end\n end\n end\n return return_list\n end",
"def load_droplets\n logger.debug 'Loading list of DigitalOcean droplets'\n self.droplets = api.droplets\n end",
"def detach_planned_volume(mapping)\n payload = {:agent_identity => @agent_identity, :device_name => mapping[:device_name]}\n Log.info(\"Detaching volume #{mapping[:volume_id]} for management purposes.\")\n req = RetryableRequest.new(\"/storage_valet/detach_volume\", payload, :retry_delay => VolumeManagement::VOLUME_RETRY_SECONDS)\n\n req.callback do |res|\n # don't set :volume_status here as that should only be queried\n mapping[:management_status] = 'detached'\n mapping[:attempts] = nil\n yield if block_given?\n end\n\n req.errback do |res|\n unless InstanceState.value == 'stranded'\n # volume could already be detaching or have been deleted\n # which we can't see because of latency; go around again\n # and check state of volume later.\n Log.error(\"Failed to detach volume #{mapping[:volume_id]} (#{res})\")\n mapping[:attempts] ||= 0\n mapping[:attempts] += 1\n # retry indefinitely so long as core api instructs us to retry or else fail after max attempts.\n if mapping[:attempts] >= VolumeManagement::MAX_VOLUME_ATTEMPTS\n strand(\"Exceeded maximum of #{VolumeManagement::MAX_VOLUME_ATTEMPTS} attempts detaching volume #{mapping[:volume_id]} with error: #{res}\")\n else\n yield if block_given?\n end\n end\n end\n\n req.run\n end",
"def elb_listener(elb)\n resp = aws_api_connect(\"ELB_Client\")\n begin\n pants = resp.create_load_balancer_listeners({\n load_balancer_name: elb[:name],\n listeners: [\n {\n protocol: elb[:protocol],\n load_balancer_port: elb[:port],\n instance_protocol: elb[:instnace_protocol],\n instance_port: elb[:instance_port],\n ssl_certificate_id: elb[:ssl_cert],\n },\n ],\n })\n rescue Aws::ElasticLoadBalancing::Errors::DuplicateListener\n puts \"Load Balancer listener #{elb[:name]} duplicate exists, skipping\"\n end\n end",
"def get_volume_attachment_hrefs\n attachments = @api_client.volume_attachments.index(filter: [\"instance_href==#{get_instance_href}\"])\n\n # Reject following attachments:\n # - attachments whose device parameter is set to 'unknown'\n # - gce boot disk - shown by resource_uid of /disks/boot-*\n # - aws ebs boot disk - shown by device_id as '/dev/sda1'\n # - cloudstack boot disk - shown by device_id as 'device_id:0'\n attachments.reject! do |attachment|\n attachment.device == 'unknown' ||\n attachment.resource_uid =~ %r{\\/disks\\/boot-} ||\n (node['cloud']['provider'] == 'ec2' && attachment.device_id == '/dev/sda1') ||\n (node['cloud']['provider'] == 'cloudstack' && attachment.device_id == 'device_id:0')\n end\n\n attachments.map(&:href)\n end",
"def ecs_wait_container_instances\n @ecs_wait_container_instances = true\n end",
"def abort_instance(instance, interfaces, wait, unlock=false)\n @mgr.unlock() if unlock\n if interfaces.size > 0\n interfaces.each() do |iface|\n iface.delete()\n end\n end\n return unless instance\n yield \"#{@mgr.timestamp()} Aborting instance #{instance.id()}\"\n instance.block_device_mappings().each() do |b|\n v = @resource.volume(b.ebs.volume_id)\n # Volumes without a Name should be deleted. Note that if an\n # instance is aborted after tagging, the volume will get left\n # behind. This should be extremely rare, since the most likely\n # collision is two people creating an instance with the same\n # name at the same time.\n unless get_tag(v, \"Name\")\n yield \"#{@mgr.timestamp()} Marking new unnamed volume #{b.ebs.volume_id} (#{b.device_name}) for automatic deletion\"\n instance.modify_attribute({\n attribute: \"blockDeviceMapping\",\n block_device_mappings: [\n {\n device_name: b.device_name,\n ebs: {\n volume_id: b.ebs.volume_id,\n delete_on_termination: true,\n },\n },\n ],\n })\n end\n end\n yield \"#{@mgr.timestamp()} Sending termination command\"\n instance.terminate()\n return unless wait\n yield \"#{@mgr.timestamp()} Waiting for instance to terminate...\"\n instance.wait_until_terminated()\n yield \"#{@mgr.timestamp()} Terminated\"\n end",
"def disable_availability_zones_for_load_balancer(availability_zones, lb_name)\n params = Fog::AWS.indexed_param('AvailabilityZones.member', [*availability_zones])\n request({\n 'Action' => 'DisableAvailabilityZonesForLoadBalancer',\n 'LoadBalancerName' => lb_name,\n :parser => Fog::Parsers::AWS::ELB::DisableAvailabilityZonesForLoadBalancer.new\n }.merge!(params))\n end",
"def instances\n @instances ||= []\n end",
"def wait_until( waiter_name=:load_balancer_available, &block )\n self.class.client.wait_until(waiter_name, load_balancer_arns: [load_balancer_arn], &block)\n end",
"def is_instance_healthy(instance)\n instance_health = client.describe_instance_health(load_balancer_name: name,\n instances: [{instance_id: instance.ec2_instance_id}])\n state_info = instance_health.instance_states.first\n status_detail = ''\n if state_info.state != 'InService'\n status_detail = \"#{state_info.reason_code} - #{state_info.description}.\"\n end\n puts \"Instance state is #{state_info.state} #{status_detail}\"\n state_info.state == 'InService'\n end"
] |
[
"0.7349848",
"0.64322937",
"0.5938487",
"0.55990577",
"0.55990577",
"0.55371326",
"0.5396752",
"0.5392787",
"0.5200122",
"0.5149061",
"0.51062137",
"0.50860155",
"0.50319856",
"0.5029228",
"0.5029228",
"0.5000057",
"0.4997184",
"0.49925008",
"0.4931991",
"0.48914087",
"0.48863772",
"0.48784545",
"0.4871172",
"0.48304427",
"0.48300737",
"0.48055476",
"0.47910905",
"0.4783613",
"0.4782936",
"0.47760764",
"0.47673875",
"0.4760222",
"0.47592753",
"0.47453335",
"0.47384858",
"0.47257596",
"0.4721201",
"0.47141442",
"0.4713962",
"0.47058514",
"0.46992275",
"0.4689165",
"0.4689078",
"0.46851406",
"0.46841338",
"0.4663217",
"0.46607634",
"0.46586773",
"0.46491238",
"0.46470255",
"0.46143946",
"0.46016192",
"0.45788908",
"0.45703292",
"0.45650643",
"0.45557132",
"0.4543054",
"0.45283067",
"0.45260975",
"0.4509995",
"0.4508659",
"0.45009357",
"0.44962126",
"0.44952798",
"0.44854456",
"0.44783145",
"0.4477584",
"0.4466715",
"0.4460948",
"0.44546482",
"0.44519937",
"0.4440988",
"0.44383016",
"0.4431973",
"0.44168732",
"0.4412535",
"0.44123906",
"0.44071576",
"0.440321",
"0.4403092",
"0.4398995",
"0.439652",
"0.4394797",
"0.43929204",
"0.4389722",
"0.43897107",
"0.43858293",
"0.43853235",
"0.4378263",
"0.43735912",
"0.43725857",
"0.43682134",
"0.4346699",
"0.4345548",
"0.43430063",
"0.43327484",
"0.4331278",
"0.43246526",
"0.4316358",
"0.43118992"
] |
0.8192437
|
0
|
Accepts load_balancers as array of Aws::ElasticLoadBalancing::Types::LoadBalancerDescription and instances as a Aws::OpsWorks::Types::Instance Returns only the LoadBalancerDescription objects that have the instance attached and should be detached from Will not include a load balancer in the returned collection if the supplied instance is the ONLY one connected. Detaching the sole remaining instance from a load balancer would probably cause undesired results.
|
def detach_from(load_balancers, instance)
check_arguments(instance: instance, load_balancers: load_balancers)
load_balancers.select do |lb|
matched_instance = lb.instances.any? do |lb_instance|
instance.ec2_instance_id == lb_instance.instance_id
end
if matched_instance && lb.instances.count > 1
# We can detach this instance safely because there is at least one other
# instance to handle traffic
true
elsif matched_instance && lb.instances.count == 1
# We can't detach this instance because it's the only one
log(<<-MSG.split.join(" "))
Will not detach #{instance.hostname} from load balancer
#{lb.load_balancer_name} because it is the only instance connected
MSG
false
else
# This load balancer isn't attached to this instance
false
end
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def detach_from_elbs(instance:)\n unless instance.is_a?(Aws::OpsWorks::Types::Instance)\n fail(ArgumentError, \"instance must be a Aws::OpsWorks::Types::Instance struct\")\n end\n\n all_load_balancers = @elb_client.describe_load_balancers\n .load_balancer_descriptions\n\n load_balancers = detach_from(all_load_balancers, instance)\n\n @lb_wait_params = []\n\n load_balancers.each do |lb|\n params = {\n load_balancer_name: lb.load_balancer_name,\n instances: [{ instance_id: instance.ec2_instance_id }]\n }\n\n remaining_instances = @elb_client\n .deregister_instances_from_load_balancer(params)\n .instances\n\n log(<<-MSG.split.join(\" \"))\n Will detach instance #{instance.hostname} from\n #{lb.load_balancer_name} (remaining attached instances:\n #{remaining_instances.count.to_s})\n MSG\n\n @lb_wait_params << params\n end\n \n unless @regional_deploy\n if @lb_wait_params.any?\n wait_for_detach(@lb_wait_params)\n else\n log(\"No load balancers found for instance #{instance.hostname}\")\n end\n end\n\n load_balancers\n end",
"def deregister_instances_from_load_balancer(instance_ids, lb_name)\n params = Fog::AWS.indexed_param('Instances.member.%d.InstanceId', [*instance_ids])\n request({\n 'Action' => 'DeregisterInstancesFromLoadBalancer',\n 'LoadBalancerName' => lb_name,\n :parser => Fog::Parsers::AWS::ELB::DeregisterInstancesFromLoadBalancer.new\n }.merge!(params))\n end",
"def attach_to_elbs(instance:, load_balancers:)\n check_arguments(instance: instance, load_balancers: load_balancers)\n\n if load_balancers.empty?\n log(\"No load balancers to attach to\")\n return {}\n end\n\n @lb_wait_params = []\n registered_instances = {} # return this\n\n load_balancers.each do |lb|\n params = {\n load_balancer_name: lb.load_balancer_name,\n instances: [{ instance_id: instance.ec2_instance_id }]\n }\n\n result = @elb_client.register_instances_with_load_balancer(params)\n\n registered_instances[lb.load_balancer_name] = result\n @lb_wait_params << params\n end\n\n log(\"Re-attaching instance #{instance.hostname} to all load balancers\")\n\n unless @regional_deploy\n wait_for_re_attach(@lb_wait_params)\n end\n\n registered_instances\n end",
"def check_arguments(instance:, load_balancers:)\n unless instance.is_a?(Aws::OpsWorks::Types::Instance)\n fail(ArgumentError,\n \":instance must be a Aws::OpsWorks::Types::Instance struct\")\n end\n unless load_balancers.respond_to?(:each) &&\n load_balancers.all? do |lb|\n lb.is_a?(Aws::ElasticLoadBalancing::Types::LoadBalancerDescription)\n end\n fail(ArgumentError, <<-MSG.split.join(\" \"))\n :load_balancers must be a collection of\n Aws::ElasticLoadBalancing::Types::LoadBalancerDescription objects\n MSG\n end\n end",
"def describe_load_balancers(ids = [], options = {})\n ids = [*ids]\n params = {}\n params['Marker'] = options[:marker] if options[:marker]\n params['PageSize'] = options[:page_size] if options[:page_size]\n params.merge!(Fog::AWS.serialize_keys('LoadBalancerArns', ids)) if ids.any?\n params.merge!(Fog::AWS.serialize_keys('Names', options[:names])) if options[:names]\n request({\n 'Action' => 'DescribeLoadBalancers',\n :parser => Fog::Parsers::AWS::ELBV2::DescribeLoadBalancers.new\n }.merge!(params))\n end",
"def deregister_instances_from_lb(lb_name, instance_ids)\n instances = instance_ids.map { |instance_id| { :instance_id => instance_id } }\n link = generate_request(\"DeregisterInstancesFromLoadBalancer\",\n :load_balancer_name => lb_name, :instances => instances\n )\n request_info(link, QElbInstancesParser.new)\n rescue Exception\n on_exception\n end",
"def clean_instances(allowed_age, whitelist=nil)\n deleted = []\n undeleted = []\n @gate.instances.each do |instance|\n if is_opsworks_instance instance\n undeleted << instance.inspect\n else\n if expired(instance.launch_time,allowed_age) and instance.status != :terminated\n begin\n if whitelisted(instance.instance_id, whitelist)\n undeleted << instance.inspect\n else\n instance.api_termination_disabled=false\n instance.delete\n deleted << instance.inspect\n end\n rescue AWS::Errors::Base => e\n undeleted << instance.inspect\n end\n end\n end\n end\n return deleted, undeleted\n end",
"def balancer_set_instances(balancer)\n balancer\n end",
"def fetch_from_ec2_loadbalancer\n instances_for_deploy = []\n loadbalancer lb_webserver, :web\n instances_for_deploy\nend",
"def fetch_from_ec2_loadbalancer\n instances_for_deploy = []\n loadbalancer lb_webserver, :web\n instances_for_deploy\nend",
"def other_instances\n\t\tinstances.reject { |i| i == self }\n\tend",
"def load_balancer_data(balancer = nil)\n params = Smash.new(\"Action\" => \"DescribeLoadBalancers\")\n if balancer\n params[\"LoadBalancerNames.member.1\"] = balancer.id || balancer.name\n end\n result = all_result_pages(nil, :body,\n \"DescribeLoadBalancersResponse\", \"DescribeLoadBalancersResult\",\n \"LoadBalancerDescriptions\", \"member\") do |options|\n request(\n :method => :post,\n :path => \"/\",\n :form => options.merge(params),\n )\n end\n if balancer\n health_result = all_result_pages(nil, :body,\n \"DescribeInstanceHealthResponse\", \"DescribeInstanceHealthResult\",\n \"InstanceStates\", \"member\") do |options|\n request(\n :method => :post,\n :path => \"/\",\n :form => options.merge(\n \"LoadBalancerName\" => balancer.id || balancer.name,\n \"Action\" => \"DescribeInstanceHealth\",\n ),\n )\n end\n end\n result.map do |blr|\n (balancer || Balancer.new(self)).load_data(\n Smash.new(\n :id => blr[\"LoadBalancerName\"],\n :name => blr[\"LoadBalancerName\"],\n :state => :active,\n :status => \"ACTIVE\",\n :created => blr[\"CreatedTime\"],\n :updated => blr[\"CreatedTime\"],\n :public_addresses => [\n Balancer::Address.new(\n :address => blr[\"DNSName\"],\n :version => 4,\n ),\n ],\n :servers => [blr.get(\"Instances\", \"member\")].flatten(1).compact.map { |i|\n Balancer::Server.new(self.api_for(:compute), :id => i[\"InstanceId\"])\n },\n ).merge(\n health_result.nil? ? {} : Smash.new(\n :server_states => health_result.nil? ? nil : health_result.map { |i|\n Balancer::ServerState.new(\n self.api_for(:compute),\n :id => i[\"InstanceId\"],\n :status => i[\"State\"],\n :reason => i[\"ReasonCode\"],\n :state => i[\"State\"] == \"InService\" ? :up : :down,\n )\n },\n )\n )\n ).valid_state\n end\n end",
"def instances\n @instances ||= aws_client.instances(filters: instance_filters).map do |instance|\n OpenStruct.new(\n with_tags(instance, private_ip: instance.private_ip_address,\n public_ip: instance.public_ip_address,\n instance: instance.instance_id)\n )\n end\n end",
"def ebs_volumes\n @ebs_volumes ||= init_ebs_volumes.reject do |vol|\n vol.attachments.any? do |att|\n attached_instance = id_instances[att.instance_id]\n attached_instance.root_device_name == att.device\n end\n end\n end",
"def diff(aws)\n diffs = []\n\n if aws.ebs_optimized != @ebs_optimized\n diffs << InstanceDiff.new(InstanceChange::EBS, aws.ebs_optimized, @ebs_optimized)\n end\n\n if aws.profile != @profile\n diffs << InstanceDiff.new(InstanceChange::PROFILE, aws.profile, @profile)\n end\n\n if aws.monitoring != @monitoring\n diffs << InstanceDiff.new(InstanceChange::MONITORING, aws.monitoring, @monitoring)\n end\n\n if aws.network_interfaces != @network_interfaces\n diffs << InstanceDiff.new(InstanceChange::INTERFACES, aws.network_interfaces, @network_interfaces)\n end\n\n if aws.source_dest_check != @source_dest_check\n diffs << InstanceDiff.new(InstanceChange::SDCHECK, aws.source_dest_check, @source_dest_check)\n end\n\n if aws.security_groups.sort != @security_groups.sort\n changes = Common::ListChange::simple_list_diff(aws.security_groups, @security_groups)\n diffs << InstanceDiff.new(InstanceChange::SECURITY_GROUPS, aws.security_groups, @security_groups, changes)\n end\n\n if aws.subnet != @subnet\n diffs << InstanceDiff.new(InstanceChange::SUBNET, aws.subnet, @subnet)\n end\n\n if aws.type != @type\n diffs << InstanceDiff.new(InstanceChange::TYPE, aws.type, @type)\n end\n\n if aws.tenancy != @tenancy\n diffs << InstanceDiff.new(InstanceChange::TENANCY, aws.tenancy, @tenancy)\n end\n\n if aws.tags != @tags\n diffs << InstanceDiff.new(InstanceChange::TAGS, aws.tags, @tags)\n end\n\n # Check for diffs in volume groups and diffs in how many volumes are attached\n\n # Get the volumes that are attached to the instance\n aws_instance = EC2::named_instances[aws.name]\n attached_volumes = aws_instance.nonroot_devices.map do |m|\n EC2::id_ebs_volumes[m.ebs.volume_id]\n end\n # Group by volume group, reject nil groups\n group_volumes = attached_volumes.group_by(&:group).reject { |k, v| k.nil? }\n\n aws_ebs_groups = Hash[group_volumes.map { |group, vols| [group, EbsGroupConfig.new(group).populate!(vols)] }]\n local_ebs_groups = Hash[@volume_groups.map { |vg| [vg, EC2::group_ebs_volumes[vg]] }]\n\n added_groups = Hash[local_ebs_groups.reject { |k, v| aws_ebs_groups.has_key?(k) }.map do |group_name, group_config|\n [group_name, EbsGroupDiff.added(group_config)]\n end]\n removed_groups = Hash[aws_ebs_groups.reject { |k, v| aws_ebs_groups.has_key?(k) }.map do |group_name, group_config|\n [group_name, EbsGroupDiff.unmanaged(group_config)]\n end]\n changed_groups = Hash[local_ebs_groups.select { |k, v| aws_ebs_groups.has_key?(k) }.map do |group_name, group_config|\n aws_config = aws_ebs_groups[group_name]\n group_diffs = group_config.diff(aws_config)\n if !group_diffs.empty?\n [group_name, EbsGroupDiff.modified(aws_config, group_config, group_diffs)]\n end\n end.reject { |v| v.nil? }]\n\n ebs_changes = Common::ListChange.new(added_groups, removed_groups, changed_groups)\n if !ebs_changes.empty?\n diffs << InstanceDiff.new(InstanceChange::VOLUME_GROUPS, aws_ebs_groups, local_ebs_groups, ebs_changes)\n end\n\n diffs\n end",
"def ensure_at_most_two_instances_exist\n all_instances = self.class.order_by([[:created_at, :desc]]).to_a\n return unless all_instances.length > max_collection_snapshot_instances\n all_instances[max_collection_snapshot_instances..-1].each(&:destroy)\n end",
"def list_instances()\n response = dbreq(\"GET\",lbmgmthost,\"#{lbmgmtpath}/instances\",lbmgmtport,lbmgmtscheme)\n CloudDB::Exception.raise_exception(response) unless response.code.to_s.match(/^20.$/)\n instances = CloudDB.symbolize_keys(JSON.parse(response.body)[\"instances\"])\n return instances\n end",
"def instances\n @instances ||= init_instances.reject(&:terminated?)\n end",
"def test_00_describe_load_balancers\n items = @elb.describe_load_balancers\n assert items.is_a?(Array)\n end",
"def update_instances(elb_name, instances_added, instances_removed = [])\n\n # deregister instances that were removed\n if !instances_removed.empty?\n @elb.deregister_instances_from_load_balancer({\n load_balancer_name: elb_name,\n instances: instances_removed.map do |i|\n {\n instance_id: i\n }\n end\n })\n end\n\n # register instances that were added\n if !instances_added.empty?\n @elb.register_instances_with_load_balancer({\n load_balancer_name: elb_name,\n instances: instances_added.map do |i|\n {\n instance_id: i\n }\n end\n })\n end\n end",
"def remove_instance(instance)\n deregister_response = client.deregister_instances_from_load_balancer(load_balancer_name: name,\n instances: [{instance_id: instance.ec2_instance_id}])\n remaining_instance_count = deregister_response.instances.size\n puts \"Removed #{instance.hostname} from ELB #{name}. Remaining instances: #{remaining_instance_count}\".light_blue\n _wait_for_connection_draining\n end",
"def load_balancer # rubocop:disable AbcSize\n raise 'Can not determine hostname to load client for' if @new_resource.f5.nil?\n @@load_balancers ||= []\n add_lb(@new_resource.f5) if @@load_balancers.empty?\n add_lb(@new_resource.f5) if @@load_balancers.find { |lb| lb.name == @new_resource.f5 }.nil?\n @@load_balancers.find { |lb| lb.name == @new_resource.f5 }\n end",
"def disable_availability_zones_for_load_balancer(availability_zones, lb_name)\n params = Fog::AWS.indexed_param('AvailabilityZones.member', [*availability_zones])\n request({\n 'Action' => 'DisableAvailabilityZonesForLoadBalancer',\n 'LoadBalancerName' => lb_name,\n :parser => Fog::Parsers::AWS::ELB::DisableAvailabilityZonesForLoadBalancer.new\n }.merge!(params))\n end",
"def init_instances\n instances = []\n next_token = nil\n all_records_retrieved = false\n\n until all_records_retrieved\n response = @@client.describe_instances({\n next_token: next_token\n })\n next_token = response.next_token\n all_records_retrieved = next_token.nil? || next_token.empty?\n instances << response.reservations.map { |r| r.instances }\n end\n\n instances.flatten\n end",
"def purge_instances!\n @@instances = [] and true\n end",
"def balancer_all(options = {})\n load_balancer_data\n end",
"def stop_instances\n @task.unsafe(\"Stopping #{@name} processes\") do\n autoscaling_group.suspend_all_processes\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Stopping instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.stop\n end\n end\n end",
"def describe_load_balancers(optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'DescribeLoadBalancers'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :host_id\n\t\t\targs[:query]['HostId'] = optional[:host_id]\n\t\tend\n\t\tif optional.key? :load_balancer_id\n\t\t\targs[:query]['LoadBalancerId'] = optional[:load_balancer_id]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tif optional.key? :server_id\n\t\t\targs[:query]['ServerId'] = optional[:server_id]\n\t\tend\n\t\tself.run(args)\n\tend",
"def instance_list(next_token=nil)\n self.ec2_client.describe_instances(\n {\n filters: [\n {\n name: \"tag:Branch\",\n values: [\"*\"],\n },\n {\n name: \"instance-state-name\",\n values: [\"running\"],\n }\n ],\n next_token: next_token\n })\n end",
"def fetch_instances(allow_states = nil, reject_states = nil)\n Egi::Fedcloud::Vmhound::Log.debug \"[#{self.class}] Retrieving instances: \" \\\n \"allow_states=#{allow_states.inspect} & \" \\\n \"reject_states=#{reject_states.inspect}\"\n return if allow_states && allow_states.empty?\n reject_states ||= []\n\n @vm_pool_ary ||= fetch_instances_batch_pool(@vm_pool)\n @vm_pool_ary.collect { |vm| fetch_instances_vm(vm, allow_states, reject_states) }.compact\n end",
"def elb_registration_check(type)\n details = obj_behavior(@elb, :describe_load_balancers, @elb_name)\n instances = details.first[:instances]\n case type\n when :all\n @servers.each do |server|\n obj_behavior(server, :settings)\n aws_id = server[\"aws-id\"]\n unless obj_behavior(instances, :include?, aws_id)\n raise \"ERROR: Did not find aws id for #{aws_id}. ID list: #{instances.inspect}\"\n end\n end\n when :none\n unless obj_behavior(instances, :empty?)\n raise \"ERROR: found registered instances when there should be none. ID list: #{instances.inspect}\"\n end\n else\n raise \"ERROR: only check types of :none and :all are currently supported\" \n end\n end",
"def fetch_instance(shortname = :all, options = {})\n return instances if instances && !options[:force]\n\n fetch_stack\n unless instance_list\n self.instance_list = self.instances =\n aws_client.describe_instances(stack_id: stack[:stack_id])[:instances]\n end\n\n if shortname != :all\n fetch_layer(shortname, force: true)\n self.instances = []\n\n layers.each do |layer|\n instance = aws_client.describe_instances(\n layer_id: layer[:layer_id])\n self.instances << instance[:instances]\n end\n\n self.instances.flatten!\n end\n end",
"def terminate_instances\n @task.unsafe(\"Stopping #{@name} Launch process\") do\n autoscaling_group.suspend_processes('Launch')\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Terminating instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.terminate\n end\n end\n end",
"def terminate_instances\n @task.unsafe(\"Stopping #{@name} Launch process\") do\n autoscaling_group.suspend_processes('Launch')\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Terminating instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.terminate\n end\n end\n end",
"def grab_scannable_instances(address_blob, active_addresses)\n # list to hold all addresses of a region\n ec2_addresses_list = []\n address_blob.each do |address|\n # gathers all ip addresses for a region and pushes all of them to ec2_addresses_list\n # if they are still active in the account\n ec2_addresses_list.push(address['public_ip_address']) if active_addresses.include?(address['public_ip_address'])\n end\n ec2_addresses_list\nend",
"def get_instances(incl_stopped=false)\n \n instances = @ec2.describe_instances\n instances = instances.select { |x| x[:aws_groups].include? @group_name }\n \n if(instances.length == 0)\n raise CaTPAWS::EC2::Error::InstanceRetrieval, \"No instances found in this group\"\n end \n \n unless (incl_stopped)\n instances = instances.select {|x| x[:aws_state_code].to_i <= 16}\n end\n @instances = instances\n end",
"def remove_instance(params)\n Fog::Logger.deprecation(\n \"#{self.class}.#{__method__} is deprecated, use Fog::Compute::Google::InstanceGroup.#{__method__} instead [light_black](#{caller(0..0)})[/]\"\n )\n params[:instance] = [params[:instance]] unless params[:instance] == Array\n service.remove_instance_group_instances(params[:group], params[:zone], params[:instance])\n end",
"def instances\n Egi::Fedcloud::Vmhound::Log.info \"[#{self.class}] Retrieving active instances\"\n fetch_instances\n end",
"def instances\n @instances ||= []\n end",
"def describe_abnormal_d_b_instances(optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'DescribeAbnormalDBInstances'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :client_token\n\t\t\targs[:query]['ClientToken'] = optional[:client_token]\n\t\tend\n\t\tif optional.key? :d_b_instance_id\n\t\t\targs[:query]['DBInstanceId'] = optional[:d_b_instance_id]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tif optional.key? :owner_id\n\t\t\targs[:query]['OwnerId'] = optional[:owner_id]\n\t\tend\n\t\tif optional.key? :page_number\n\t\t\traise ArgumentError, 'page_number must be equal or greater than 1' unless optional[:page_number] < 1\n\t\t\targs[:query]['PageNumber'] = optional[:page_number]\n\t\tend\n\t\tif optional.key? :page_size\n\t\t\traise ArgumentError, 'page_size must be equal or greater than 1' unless optional[:page_size] < 1\n\t\t\traise ArgumentError, 'page_size must be equal or less than 1000' unless optional[:page_size] > 1000\n\t\t\targs[:query]['PageSize'] = optional[:page_size]\n\t\tend\n\t\tif optional.key? :proxy_id\n\t\t\targs[:query]['proxyId'] = optional[:proxy_id]\n\t\tend\n\t\tif optional.key? :resource_owner_account\n\t\t\targs[:query]['ResourceOwnerAccount'] = optional[:resource_owner_account]\n\t\tend\n\t\tif optional.key? :resource_owner_id\n\t\t\targs[:query]['ResourceOwnerId'] = optional[:resource_owner_id]\n\t\tend\n\t\tself.run(args)\n\tend",
"def instances\n instances = []\n JSON.parse(resource['/instances'].get)[\"instances\"].each do |i|\n instances << Instance.new(i)\n end\n return instances\n end",
"def instances()\n return @instances\n end",
"def create_ec2_instances(ec2_instance_collection)\n ec2_instance_collection.reject! { |e| e.count.zero? } # filter out empty collections\n\n ec2_instance_collection.each do |collection|\n collection.each do |instance|\n _create_entity 'AwsEC2Instance', {\n 'name' => instance.public_dns_name.empty? ? instance.private_dns_name : instance.public_dns_name,\n 'region' => instance.placement.availability_zone.chop,\n 'availability_zone' => instance.placement.availability_zone,\n 'public_ip_address' => instance.public_ip_address,\n 'private_dns_name' => instance.private_dns_name,\n 'private_ip_address' => instance.private_ip_address,\n 'public_dns_name' => instance.public_dns_name\n }\n end\n end\n end",
"def instances\n @instances ||= begin\n instances_channel = channel(\n Admin::V2::BigtableInstanceAdminClient::SERVICE_ADDRESS\n )\n Admin::V2::BigtableInstanceAdminClient.new(\n credentials: instances_channel,\n timeout: timeout,\n client_config: client_config,\n lib_name: \"gccl\",\n lib_version: Google::Cloud::Bigtable::VERSION\n )\n end\n end",
"def list_instances()\n response = dbreq(\"GET\", dbmgmthost, \"#{dbmgmtpath}/instances\", dbmgmtport, dbmgmtscheme)\n CloudDB::Exception.raise_exception(response) unless response.code.to_s.match(/^20.$/)\n instances = CloudDB.symbolize_keys(JSON.parse(response.body)[\"instances\"])\n return instances\n end",
"def list_of_terminating_instances(list = remote_instances_list)\n list.reject {|i| true if !i.terminating? }\n end",
"def remove_from_lb(group)\n @haproxy.identity_filter(@load_balancer)\n # We don't have to identify the nodes in the group\n # for every action. I'm doing it here to make each\n # method easier to read\n @rpcutil.class_filter(group)\n begin\n @rpcutil.ping.each do |node|\n hostname = node.results[:sender]\n # Disable the nodes\n @haproxy.disable(:backend => 'puppetcamp', :server => hostname).each do |rpcresult|\n if rpcresult.results[:statuscode] != 0\n raise LoadBalancerRemoveException, hostname\n end\n end\n end\n ensure\n @haproxy.reset_filter\n @rpcutil.reset_filter\n end\nend",
"def check_missing_instances(instances)\n missing_instances = instances.reject { |i| all_clusters.include?(i) }\n unknown(\"Passed instance(s): #{missing_instances.join(',')} not found\") unless missing_instances.empty?\n end",
"def stop_all_instances\n Spinup.logger.info('Attempting to stop all running instances')\n running_instances = ec2.instances\n\n Spinup.logger.info(\" Found #{running_instances.count} running instances\")\n\n running_instances.each do |running_instance|\n instance_stopped?(running_instance)\n end\n end",
"def beanstalks\n return @beanstalks ||= @beanstalk_servers.map(&:beanstalk)\n end",
"def load_balancer_names\n @group.load_balancer_names\n end",
"def volumes\n volumes = @ec2.volumes\n volumes.delete_if {|v| v.instance_id != id}\n end",
"def describe_load_balancers(optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'DescribeLoadBalancers'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :address\n\t\t\targs[:query]['Address'] = optional[:address]\n\t\tend\n\t\tif optional.key? :address_type\n\t\t\targs[:query]['AddressType'] = optional[:address_type]\n\t\tend\n\t\tif optional.key? :internet_charge_type\n\t\t\targs[:query]['InternetChargeType'] = optional[:internet_charge_type]\n\t\tend\n\t\tif optional.key? :load_balancer_id\n\t\t\targs[:query]['LoadBalancerId'] = optional[:load_balancer_id]\n\t\tend\n\t\tif optional.key? :master_zone_id\n\t\t\targs[:query]['MasterZoneId'] = optional[:master_zone_id]\n\t\tend\n\t\tif optional.key? :network_type\n\t\t\targs[:query]['NetworkType'] = optional[:network_type]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tif optional.key? :owner_id\n\t\t\targs[:query]['OwnerId'] = optional[:owner_id]\n\t\tend\n\t\tif optional.key? :resource_owner_account\n\t\t\targs[:query]['ResourceOwnerAccount'] = optional[:resource_owner_account]\n\t\tend\n\t\tif optional.key? :resource_owner_id\n\t\t\targs[:query]['ResourceOwnerId'] = optional[:resource_owner_id]\n\t\tend\n\t\tif optional.key? :security_status\n\t\t\targs[:query]['SecurityStatus'] = optional[:security_status]\n\t\tend\n\t\tif optional.key? :server_id\n\t\t\targs[:query]['ServerId'] = optional[:server_id]\n\t\tend\n\t\tif optional.key? :slave_zone_id\n\t\t\targs[:query]['SlaveZoneId'] = optional[:slave_zone_id]\n\t\tend\n\t\tif optional.key? :v_switch_id\n\t\t\targs[:query]['VSwitchId'] = optional[:v_switch_id]\n\t\tend\n\t\tif optional.key? :vpc_id\n\t\t\targs[:query]['VpcId'] = optional[:vpc_id]\n\t\tend\n\t\tself.run(args)\n\tend",
"def stop_instances\n @task.unsafe(\"Stopping #{@name} processes\") do\n save_to_s3(@task.bucket)\n autoscaling_group.suspend_all_processes\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Stopping instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.stop\n end\n end\n end",
"def list_of_terminating_instances(list = remote_instances_list)\n list.reject {|i| true if !i.terminating? }\n end",
"def find_instances(tags)\n attempts = 0\n begin\n ec2.servers.select { |server| tags.reject { |k,v| server.tags[k] == tags[k] }.empty? }\n rescue Excon::Errors::ServiceUnavailable\n sleep 5\n attempts += 1\n return [] if attempts == 5\n retry\n end\n end",
"def ec2_instances\n instances = EC2::InstanceCollection.new(:config => config)\n instances.tagged('aws:autoscaling:groupName').tagged_values(name)\n end",
"def get_balancer_rejections(args)\n if args.key? 'LIMIT'\n limit = args['LIMIT']\n else\n limit = 250\n end\n\n log_type = 'BALANCER_REJECTION'\n log_dest = org.apache.hadoop.hbase.client.ServerType::MASTER\n balancer_rejections_responses = @admin.getLogEntries(nil, log_type, log_dest, limit, nil)\n balancer_rejections_resp_arr = []\n balancer_rejections_responses.each { |balancer_dec_resp|\n balancer_rejections_resp_arr << balancer_dec_resp.toJsonPrettyPrint\n }\n balancer_rejections_resp_arr\n end",
"def aws_terminate_instance_and_ebs_volumes( iprops )\n ec2 = AWS::EC2.new.regions[ iprops[ :region ] ]\n inst = ec2.instances[ iprops[ :id ] ]\n unless inst.exists?\n raise \"Instance #{iprops[:id]} does not exist in #{iprops[:region]}\"\n end\n\n ebs_volumes = inst.block_devices.map do |dev|\n ebs = dev[ :ebs ]\n if ebs && dev[:device_name] =~ /dh\\d+$/ && !ebs[:delete_on_termination]\n ebs[ :volume_id ]\n end\n end.compact\n\n inst.terminate\n wait_until( \"termination of #{inst.id}\", 2.0 ) { inst.status == :terminated }\n\n ebs_volumes = ebs_volumes.map do |vid|\n volume = ec2.volumes[ vid ]\n if volume.exists?\n volume\n else\n puts \"WARN: #{volume} doesn't exist\"\n nil\n end\n end.compact\n\n ebs_volumes.each do |vol|\n wait_until( \"deletion of vol #{vol.id}\" ) do\n vol.status == :available || vol.status == :deleted\n end\n vol.delete if vol.status == :available\n end\n\n found = aws_find_instance( iprops )\n if found\n aws_instance_removed( found )\n aws_write_instances\n end\n end",
"def describe_d_b_instances(optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'DescribeDBInstances'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :client_token\n\t\t\targs[:query]['ClientToken'] = optional[:client_token]\n\t\tend\n\t\tif optional.key? :connection_mode\n\t\t\targs[:query]['ConnectionMode'] = optional[:connection_mode]\n\t\tend\n\t\tif optional.key? :d_b_instance_id\n\t\t\targs[:query]['DBInstanceId'] = optional[:d_b_instance_id]\n\t\tend\n\t\tif optional.key? :d_b_instance_status\n\t\t\targs[:query]['DBInstanceStatus'] = optional[:d_b_instance_status]\n\t\tend\n\t\tif optional.key? :d_b_instance_type\n\t\t\targs[:query]['DBInstanceType'] = optional[:d_b_instance_type]\n\t\tend\n\t\tif optional.key? :engine\n\t\t\targs[:query]['Engine'] = optional[:engine]\n\t\tend\n\t\tif optional.key? :instance_network_type\n\t\t\targs[:query]['InstanceNetworkType'] = optional[:instance_network_type]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tif optional.key? :owner_id\n\t\t\targs[:query]['OwnerId'] = optional[:owner_id]\n\t\tend\n\t\tif optional.key? :page_number\n\t\t\traise ArgumentError, 'page_number must be equal or greater than 0' unless optional[:page_number] < 0\n\t\t\traise ArgumentError, 'page_number must be equal or less than 2147483647' unless optional[:page_number] > 2147483647\n\t\t\targs[:query]['PageNumber'] = optional[:page_number]\n\t\tend\n\t\tif optional.key? :page_size\n\t\t\traise ArgumentError, 'page_size must be equal or greater than 1' unless optional[:page_size] < 1\n\t\t\traise ArgumentError, 'page_size must be equal or less than 100' unless optional[:page_size] > 100\n\t\t\targs[:query]['PageSize'] = optional[:page_size]\n\t\tend\n\t\tif optional.key? :proxy_id\n\t\t\targs[:query]['proxyId'] = optional[:proxy_id]\n\t\tend\n\t\tif optional.key? :resource_owner_account\n\t\t\targs[:query]['ResourceOwnerAccount'] = optional[:resource_owner_account]\n\t\tend\n\t\tif optional.key? :resource_owner_id\n\t\t\targs[:query]['ResourceOwnerId'] = optional[:resource_owner_id]\n\t\tend\n\t\tif optional.key? :search_key\n\t\t\targs[:query]['SearchKey'] = optional[:search_key]\n\t\tend\n\t\tself.run(args)\n\tend",
"def diff(aws, autoscaling)\n diffs = []\n\n if @cooldown != aws.default_cooldown\n diffs << AutoScalingDiff.new(AutoScalingChange::COOLDOWN, aws, self)\n end\n if @enabled_metrics.deep_sort != aws.enabled_metrics.map { |k| k.metric }.deep_sort\n diffs << AutoScalingDiff.new(AutoScalingChange::METRICS, aws, self)\n end\n if @check_type != aws.health_check_type\n diffs << AutoScalingDiff.new(AutoScalingChange::CHECK_TYPE, aws, self)\n end\n if @check_grace != aws.health_check_grace_period\n diffs << AutoScalingDiff.new(AutoScalingChange::CHECK_GRACE, aws, self)\n end\n if @launch != aws.launch_configuration_name and Configuration.instance.autoscaling.override_launch_config_on_sync\n diffs << AutoScalingDiff.new(AutoScalingChange::LAUNCH, aws, self)\n end\n if @load_balancers.sort != aws.load_balancer_names.sort\n diffs << AutoScalingDiff.new(AutoScalingChange::LOAD_BALANCER, aws, self)\n end\n\n # Get the actual subnet objects from aws using either the id or vpc/subnet combination\n local_subnets = subnets_to_aws.sort_by(&:subnet_id)\n aws_subnets = aws.vpc_zone_identifier.split(\",\").map do |subnet_id|\n EC2::id_subnets[subnet_id]\n end.sort_by(&:subnet_id)\n\n if local_subnets != aws_subnets\n diffs << AutoScalingDiff.new(AutoScalingChange::SUBNETS, aws_subnets, local_subnets)\n end\n\n if @tags != Hash[aws.tags.map { |tag| [tag.key, tag.value] }]\n diffs << AutoScalingDiff.new(AutoScalingChange::TAGS, aws, self)\n end\n if @termination != aws.termination_policies\n diffs << AutoScalingDiff.new(AutoScalingChange::TERMINATION, aws, self)\n end\n\n # check for changes in scheduled actions\n aws_scheduled = autoscaling.describe_scheduled_actions({\n auto_scaling_group_name: @name\n }).scheduled_update_group_actions\n\n scheduled_diff = AutoScalingDiff.scheduled(aws_scheduled, @scheduled)\n if scheduled_diff\n diffs << scheduled_diff\n end\n\n aws_min = aws.min_size\n aws_max = aws.max_size\n aws_desired = aws.desired_capacity\n local_min = @min\n local_max = @max\n local_desired = @desired\n update_desired = Configuration.instance.autoscaling.force_size\n\n # If there is local scheduled actions, use the most recent one to determine the local min/max\n if !@scheduled.empty? and !Configuration.instance.autoscaling.force_size\n local_last_scheduled = last_scheduled\n\n if local_last_scheduled\n local_min = local_last_scheduled.min\n local_max = local_last_scheduled.max\n local_desired = local_last_scheduled.desired\n end\n end\n\n # If desired was not specified, assume it is the min\n local_desired = local_min if !local_desired\n\n # If the aws desired value is outside of the new min/max bounds then we need to\n # update desired to be in the bounds\n if local_min and aws_desired < local_min\n local_desired = local_min if local_desired < local_min\n update_desired = true\n elsif local_max and aws_desired > local_max\n local_desired = local_max if local_desired > local_max\n update_desired = true\n end\n\n if local_min and local_min != aws_min\n diffs << AutoScalingDiff.new(AutoScalingChange::MIN, aws_min, local_min)\n end\n if local_max and local_max != aws_max\n diffs << AutoScalingDiff.new(AutoScalingChange::MAX, aws_max, local_max)\n end\n if update_desired\n diffs << AutoScalingDiff.new(AutoScalingChange::DESIRED, aws_desired, local_desired)\n end\n\n # check for changes in scaling policies\n aws_policies = autoscaling.describe_policies({\n auto_scaling_group_name: @name\n }).scaling_policies\n policy_diffs = diff_policies(aws_policies)\n if !policy_diffs.empty?\n diffs << AutoScalingDiff.policies(self, policy_diffs)\n end\n\n diffs\n end",
"def retract(*instances)\n Array(instances).each do |i|\n i.retract\n end\n self\n end",
"def diff(aws)\n diffs = []\n\n if @load_balancer_protocol != aws.listener.protocol\n diffs << ListenerDiff.new(ListenerChange::LB_PROTOCOL, aws.listener.protocol, @load_balancer_protocol)\n end\n\n if @load_balancer_port != aws.listener.load_balancer_port\n diffs << ListenerDiff.new(ListenerChange::LB_PORT, aws.listener.load_balancer_port, @load_balancer_port)\n end\n\n if @instance_protocol != aws.listener.instance_protocol\n diffs << ListenerDiff.new(ListenerChange::INST_PROTOCOL, aws.listener.instance_protocol, @instance_protocol)\n end\n\n if @instance_port != aws.listener.instance_port\n diffs << ListenerDiff.new(ListenerChange::INST_PORT, aws.listener.instance_port, @instance_port)\n end\n\n if @ssl_certificate_id != aws.listener.ssl_certificate_id\n diffs << ListenerDiff.new(ListenerChange::SSL, aws.listener.ssl_certificate_id, @ssl_certificate_id)\n end\n\n if @policies.sort != aws.policy_names.sort\n diffs << ListenerDiff.policies(aws.policy_names, @policies)\n end\n\n diffs\n end",
"def describe_listeners(load_balancer_arn, options = {})\n request({\n 'Action' => 'DescribeListeners',\n 'LoadBalancerArn' => load_balancer_arn,\n :parser => Fog::Parsers::AWS::ELBV2::DescribeListeners.new\n }.merge!(options))\n end",
"def list_instance_snapshots(rds_resource)\n instance_snapshots = []\n rds_resource.db_snapshots.each do |s|\n instance_snapshots.append({\n \"id\": s.snapshot_id,\n \"status\": s.status\n })\n end\n instance_snapshots\nrescue Aws::Errors::ServiceError => e\n puts \"Couldn't list instance snapshots:\\n #{e.message}\"\nend",
"def get_instances_description\n instances\n end",
"def destroy_load_balancer(action_handler, lb_spec, lb_options)\n end",
"def list_instances_detail()\n response = dbreq(\"GET\", dbmgmthost, \"#{dbmgmtpath}/instances/detail\", dbmgmtport, dbmgmtscheme)\n CloudDB::Exception.raise_exception(response) unless response.code.to_s.match(/^20.$/)\n instances = CloudDB.symbolize_keys(JSON.parse(response.body)[\"instances\"])\n return instances\n end",
"def aws_import_instances\n\n instances = []\n\n aws_regions.each do |region|\n ec2 = AWS::EC2.new.regions[ region ]\n\n found = ec2.instances.map do |inst|\n next unless [ :running, :pending ].include?( inst.status )\n aws_instance_to_props( region, inst )\n end\n\n instances += found.compact\n end\n\n @aws_instances = instances\n end",
"def filter_instances(instances, filters)\n filtered = instances\n # Include only instances that match all filters.\n filters.each do |filter|\n key, value = filter.first\n filtered = filtered.select { |i|\n found_tag = i.tags.find { |t|\n t.key == key.to_s\n }\n next if found_tag.nil?\n\n found_tag.value == value\n }\n end\n filtered\n end",
"def attach_to_elb(instance, elb_name, subnet = nil)\n begin\n @log.info \"\"\n @log.info \"Adding to ELB: #{elb_name}\"\n elb = AWS::ELB.new\n AWS.memoize do\n unless subnet\n # Build list of availability zones for any existing instances\n zones = { }\n zones[instance.availability_zone] = instance.availability_zone\n elb.load_balancers[elb_name].instances.each do |elb_instance|\n zones[elb_instance.availability_zone] = elb_instance.availability_zone\n end\n \n # Build list of existing zones\n existing_zones = { }\n elb.load_balancers[elb_name].availability_zones.each do |zone|\n existing_zones[zone.name] = zone\n end\n \n # Enable zones\n zones.keys.each do |zone_name|\n elb.load_balancers[elb_name].availability_zones.enable(zones[zone_name])\n end\n \n # Disable zones\n existing_zones.keys.each do |zone_name|\n elb.load_balancers[elb_name].availability_zones.disable(existing_zones[zone_name]) unless zones.has_key?(zone_name)\n end\n end\n \n elb.load_balancers[elb_name].instances.register(instance)\n end\n rescue StandardError => bang\n @log.error \"Error adding to load balancers: \" + bang.to_s\n end\n end",
"def attach_load_balancer_to_subnets(subnet_ids, lb_name)\n params = Fog::AWS.indexed_param('Subnets.member', [*subnet_ids])\n request({\n 'Action' => 'AttachLoadBalancerToSubnets',\n 'LoadBalancerName' => lb_name,\n :parser => Fog::Parsers::AWS::ELB::AttachLoadBalancerToSubnets.new\n }.merge!(params))\n end",
"def remove_load_balancer_properties\n properties = []\n properties << :AccessLoggingPolicy\n properties << :AppCookieStickinessPolicy\n properties << :ConnectionDrainingPolicy\n properties << :CrossZone\n properties << :LBCookieStickinessPolicy\n properties << :LoadBalancerName\n properties << 'Listeners.PolicyNames'\n properties << 'Listeners.SSLCertificateId '\n properties << :Policies\n properties << :Scheme\n properties << :SecurityGroups\n properties << :Subnets\n add_patch Patches::RemoveProperty.new 'AWS::ElasticLoadBalancing::LoadBalancer', properties\n end",
"def cascading_elements\n instances\n end",
"def unmonitor_instances( options = {} )\n options = { :instance_id => [] }.merge(options)\n raise ArgumentError, \"No :instance_id provided\" if options[:instance_id].nil? || options[:instance_id].empty?\n params = pathlist(\"InstanceId\", options[:instance_id])\n return response_generator(:action => \"UnmonitorInstances\", :params => params)\n end",
"def instances_list\n return [] unless configured?\n\n @service.fetch_all do |token|\n @service.list_instances(@gcp_config['project'], @gcp_config['zone'], page_token: token)\n end.map(&:name)\n end",
"def retrieve_elb(name)\n Clients.elb.describe_load_balancers(\n load_balancer_names: [name],\n ).load_balancer_descriptions[0]\nend",
"def destroy_instances_if_ami_changed\n self.instances.each { |i| i.destroy } if self.ami_id_changed?\n end",
"def excluded_hosts\n res = []\n self.excluded_host_ids.each do |h_id|\n res << (Host.find(h_id) rescue nil)\n end\n res.compact\n end",
"def excluded_hosts\n res = []\n self.excluded_host_ids.each do |h_id|\n res << (Host.find(h_id) rescue nil)\n end\n res.compact\n end",
"def excluded_hosts\n res = []\n self.excluded_host_ids.each do |h_id|\n res << (Host.find(h_id) rescue nil)\n end\n res.compact\n end",
"def excluded_hosts\n res = []\n self.excluded_host_ids.each do |h_id|\n res << (Host.find(h_id) rescue nil)\n end\n res.compact\n end",
"def delete_instances(count)\n instances_to_delete = current_instances.last(count) \n parent.terminate_instances(Group.instance_ids(instances_to_delete))\n # remaining_instances under alive\n Output.new(current_instances.first(current_instances.size - count), instances_to_delete)\n end",
"def active_instances\n Egi::Fedcloud::Vmhound::Log.info \"[#{self.class}] Retrieving running instances\"\n fetch_instances ['ACTIVE']\n end",
"def modify_load_balancer_attributes(lb_name, options)\n attributes = Fog::AWS.serialize_keys 'LoadBalancerAttributes', options\n request(attributes.merge(\n 'Action' => 'ModifyLoadBalancerAttributes',\n 'LoadBalancerName' => lb_name,\n :parser => Fog::Parsers::AWS::ELB::Empty.new\n ))\n end",
"def diff(aws)\n diffs = []\n\n if @ttl != aws.ttl\n diffs << SingleRecordDiff.new(RecordChange::TTL, aws, self)\n end\n if !@value.nil? and @value.sort != aws.resource_records.map(&:value).sort\n diffs << SingleRecordDiff.new(RecordChange::VALUE, aws, self)\n end\n if !@alias_target.nil?\n if aws.alias_target.nil? or\n (is_elb_alias? and aws.alias_target.elb_dns_name != ELB::get_aws(@alias_target.name).dns_name) or\n (aws.alias_target.chomped_dns != @alias_target.dns_name)\n diffs << SingleRecordDiff.new(RecordChange::ALIAS, aws, self)\n end\n end\n\n diffs\n end",
"def instance_tags\n return ['allow-all-traffic'] unless use_existing_network?\n\n @gcp_config['tags']\n end",
"def diff(aws)\n diffs = []\n\n if @target != aws.target\n diffs << DeadLetterDiff.new(DeadLetterChange::TARGET, aws.target, @target)\n end\n\n if @max_receives != aws.max_receives\n diffs << DeadLetterDiff.new(DeadLetterChange::RECEIVE, aws.max_receives, @max_receives)\n end\n\n diffs\n end",
"def diff(aws)\n diffs = []\n\n aws_inbound = aws.diffable_entries.select { |entry| !entry.egress }\n inbound_diff = NetworkAclDiff.entries(NetworkAclChange::INBOUND, aws_inbound, @inbound)\n if inbound_diff\n diffs << inbound_diff\n end\n\n aws_outbound = aws.diffable_entries.select { |entry| entry.egress }\n outbound_diff = NetworkAclDiff.entries(NetworkAclChange::OUTBOUND, aws_outbound, @outbound)\n if outbound_diff\n diffs << outbound_diff\n end\n\n aws_tags = Hash[aws.tags.map { |tag| [tag.key, tag.value] }]\n if @tags != aws_tags\n diffs << NetworkAclDiff.new(NetworkAclChange::TAGS, aws_tags, @tags)\n end\n\n diffs\n end",
"def list_instances request_pb, options = nil\n raise ::ArgumentError, \"request must be provided\" if request_pb.nil?\n\n verb, uri, query_string_params, body = ServiceStub.transcode_list_instances_request request_pb\n query_string_params = if query_string_params.any?\n query_string_params.to_h { |p| p.split \"=\", 2 }\n else\n {}\n end\n\n response = @client_stub.make_http_request(\n verb,\n uri: uri,\n body: body || \"\",\n params: query_string_params,\n options: options\n )\n operation = ::Gapic::Rest::TransportOperation.new response\n result = ::Google::Cloud::Notebooks::V1::ListInstancesResponse.decode_json response.body, ignore_unknown_fields: true\n\n yield result, operation if block_given?\n result\n end",
"def instances\n IbmCloudRest.get \"#{@uri}/instances\"\n end",
"def register_instances_with_lb(lb_name, instance_ids)\n instances = instance_ids.map { |instance_id| { :instance_id => instance_id } }\n link = generate_request(\"RegisterInstancesWithLoadBalancer\",\n :load_balancer_name => lb_name, :instances => instances)\n request_info(link, QElbInstancesParser.new)\n rescue Exception\n on_exception\n end",
"def detach()\n $ec2.describe_volumes([self.id]).each do |result|\n if result[:aws_attachment_status] == 'attached'\n $ec2.detach_volume(self.id)\n end\n end\n self.attached_instance = nil\n self.save()\n end",
"def describe_listeners(lb_id = nil, listener_ids = [], options = {})\n listener_ids = Array(listener_ids)\n params = {}\n params['Marker'] = options[:marker] if options[:marker]\n params['PageSize'] = options[:page_size] if options[:page_size]\n\n params['LoadBalancerArn'] = lb_id if lb_id\n params.merge!(Fog::AWS.serialize_keys('ListenerArns', listener_ids)) if listener_ids.any?\n request({\n 'Action' => 'DescribeListeners',\n :parser => Fog::Parsers::AWS::ELBV2::DescribeListeners.new\n }.merge(params))\n end",
"def instance_ids\n @instance_ids ||= groups.map { |gr| gr.instances.map { |i| i.instance_id } }.flatten\n end",
"def list_instances request_pb, options = nil\n raise ::ArgumentError, \"request must be provided\" if request_pb.nil?\n\n verb, uri, query_string_params, body = ServiceStub.transcode_list_instances_request request_pb\n query_string_params = if query_string_params.any?\n query_string_params.to_h { |p| p.split \"=\", 2 }\n else\n {}\n end\n\n response = @client_stub.make_http_request(\n verb,\n uri: uri,\n body: body || \"\",\n params: query_string_params,\n options: options\n )\n operation = ::Gapic::Rest::TransportOperation.new response\n result = ::Google::Cloud::BareMetalSolution::V2::ListInstancesResponse.decode_json response.body, ignore_unknown_fields: true\n\n yield result, operation if block_given?\n result\n end",
"def delete_load_balancer(optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'DeleteLoadBalancer'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :load_balancer_id\n\t\t\targs[:query]['LoadBalancerId'] = optional[:load_balancer_id]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tif optional.key? :owner_id\n\t\t\targs[:query]['OwnerId'] = optional[:owner_id]\n\t\tend\n\t\tif optional.key? :resource_owner_account\n\t\t\targs[:query]['ResourceOwnerAccount'] = optional[:resource_owner_account]\n\t\tend\n\t\tif optional.key? :resource_owner_id\n\t\t\targs[:query]['ResourceOwnerId'] = optional[:resource_owner_id]\n\t\tend\n\t\tself.run(args)\n\tend",
"def index\n @cabinet_balancers = Balancer.all\n end",
"def get_elb(layer_name)\n layer_id = layers[layer_name].layer_id\n elbs = opsworks_client.describe_elastic_load_balancers(layer_ids:[layer_id])\n if elbs.elastic_load_balancers.size > 0\n name = elbs.elastic_load_balancers.first.elastic_load_balancer_name\n ELB.new(name)\n else\n nil\n end\n end",
"def destroy!\n response = @connection.lbreq(\"DELETE\", @lbmgmthost, \"#{@lbmgmtpath}/loadbalancers/#{CloudLB.escape(@id.to_s)}\",@lbmgmtport,@lbmgmtscheme)\n CloudLB::Exception.raise_exception(response) unless response.code.to_s.match(/^202$/)\n true\n end"
] |
[
"0.7493718",
"0.6402033",
"0.6297438",
"0.60137606",
"0.57810754",
"0.56451625",
"0.5547521",
"0.5476744",
"0.54553556",
"0.54553556",
"0.5338663",
"0.53209645",
"0.5208643",
"0.50709707",
"0.50377965",
"0.502718",
"0.4977642",
"0.49732804",
"0.4951387",
"0.49166682",
"0.4907017",
"0.48813826",
"0.48756605",
"0.485258",
"0.4851363",
"0.48437405",
"0.48296568",
"0.4794163",
"0.4794026",
"0.47856197",
"0.47768676",
"0.47686034",
"0.4746113",
"0.4746113",
"0.47184128",
"0.4715149",
"0.46982256",
"0.4680248",
"0.4675581",
"0.4672492",
"0.4657542",
"0.46448576",
"0.46421832",
"0.4624074",
"0.45956725",
"0.45920458",
"0.45915657",
"0.4581627",
"0.45814326",
"0.45688304",
"0.45685065",
"0.45583212",
"0.4553079",
"0.45443484",
"0.45426622",
"0.45376712",
"0.45364326",
"0.45343745",
"0.45256963",
"0.4520904",
"0.4515572",
"0.4504096",
"0.44917738",
"0.44785774",
"0.4473905",
"0.44702253",
"0.4456926",
"0.4452175",
"0.4450787",
"0.4438742",
"0.44324094",
"0.44212407",
"0.44171634",
"0.4410275",
"0.44056454",
"0.43875661",
"0.4384228",
"0.4383995",
"0.43765533",
"0.43765533",
"0.43765533",
"0.43765533",
"0.43705475",
"0.4364455",
"0.43390542",
"0.43385485",
"0.43348154",
"0.4327499",
"0.4324201",
"0.4318897",
"0.43111402",
"0.42987555",
"0.429806",
"0.42892542",
"0.42884123",
"0.4285601",
"0.42815426",
"0.42802536",
"0.42731336",
"0.42717996"
] |
0.7582588
|
0
|
Takes an instance as a Aws::OpsWorks::Types::Instance and load balancers as an array of Aws::ElasticLoadBalancing::Types::LoadBalancerDescription Attaches the provided instance to the supplied load balancers and blocks until AWS confirms that the instance is attached to all load balancers before returning Does nothing and instead returns an empty hash if load_balancers is empty Otherwise returns a hash of load balancer names each with a Aws::ElasticLoadBalancing::Types::RegisterEndPointsOutput
|
def attach_to_elbs(instance:, load_balancers:)
check_arguments(instance: instance, load_balancers: load_balancers)
if load_balancers.empty?
log("No load balancers to attach to")
return {}
end
@lb_wait_params = []
registered_instances = {} # return this
load_balancers.each do |lb|
params = {
load_balancer_name: lb.load_balancer_name,
instances: [{ instance_id: instance.ec2_instance_id }]
}
result = @elb_client.register_instances_with_load_balancer(params)
registered_instances[lb.load_balancer_name] = result
@lb_wait_params << params
end
log("Re-attaching instance #{instance.hostname} to all load balancers")
unless @regional_deploy
wait_for_re_attach(@lb_wait_params)
end
registered_instances
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def attach_to_elb(instance, elb_name, subnet = nil)\n begin\n @log.info \"\"\n @log.info \"Adding to ELB: #{elb_name}\"\n elb = AWS::ELB.new\n AWS.memoize do\n unless subnet\n # Build list of availability zones for any existing instances\n zones = { }\n zones[instance.availability_zone] = instance.availability_zone\n elb.load_balancers[elb_name].instances.each do |elb_instance|\n zones[elb_instance.availability_zone] = elb_instance.availability_zone\n end\n \n # Build list of existing zones\n existing_zones = { }\n elb.load_balancers[elb_name].availability_zones.each do |zone|\n existing_zones[zone.name] = zone\n end\n \n # Enable zones\n zones.keys.each do |zone_name|\n elb.load_balancers[elb_name].availability_zones.enable(zones[zone_name])\n end\n \n # Disable zones\n existing_zones.keys.each do |zone_name|\n elb.load_balancers[elb_name].availability_zones.disable(existing_zones[zone_name]) unless zones.has_key?(zone_name)\n end\n end\n \n elb.load_balancers[elb_name].instances.register(instance)\n end\n rescue StandardError => bang\n @log.error \"Error adding to load balancers: \" + bang.to_s\n end\n end",
"def load_balancer_data(balancer = nil)\n params = Smash.new(\"Action\" => \"DescribeLoadBalancers\")\n if balancer\n params[\"LoadBalancerNames.member.1\"] = balancer.id || balancer.name\n end\n result = all_result_pages(nil, :body,\n \"DescribeLoadBalancersResponse\", \"DescribeLoadBalancersResult\",\n \"LoadBalancerDescriptions\", \"member\") do |options|\n request(\n :method => :post,\n :path => \"/\",\n :form => options.merge(params),\n )\n end\n if balancer\n health_result = all_result_pages(nil, :body,\n \"DescribeInstanceHealthResponse\", \"DescribeInstanceHealthResult\",\n \"InstanceStates\", \"member\") do |options|\n request(\n :method => :post,\n :path => \"/\",\n :form => options.merge(\n \"LoadBalancerName\" => balancer.id || balancer.name,\n \"Action\" => \"DescribeInstanceHealth\",\n ),\n )\n end\n end\n result.map do |blr|\n (balancer || Balancer.new(self)).load_data(\n Smash.new(\n :id => blr[\"LoadBalancerName\"],\n :name => blr[\"LoadBalancerName\"],\n :state => :active,\n :status => \"ACTIVE\",\n :created => blr[\"CreatedTime\"],\n :updated => blr[\"CreatedTime\"],\n :public_addresses => [\n Balancer::Address.new(\n :address => blr[\"DNSName\"],\n :version => 4,\n ),\n ],\n :servers => [blr.get(\"Instances\", \"member\")].flatten(1).compact.map { |i|\n Balancer::Server.new(self.api_for(:compute), :id => i[\"InstanceId\"])\n },\n ).merge(\n health_result.nil? ? {} : Smash.new(\n :server_states => health_result.nil? ? nil : health_result.map { |i|\n Balancer::ServerState.new(\n self.api_for(:compute),\n :id => i[\"InstanceId\"],\n :status => i[\"State\"],\n :reason => i[\"ReasonCode\"],\n :state => i[\"State\"] == \"InService\" ? :up : :down,\n )\n },\n )\n )\n ).valid_state\n end\n end",
"def detach_from_elbs(instance:)\n unless instance.is_a?(Aws::OpsWorks::Types::Instance)\n fail(ArgumentError, \"instance must be a Aws::OpsWorks::Types::Instance struct\")\n end\n\n all_load_balancers = @elb_client.describe_load_balancers\n .load_balancer_descriptions\n\n load_balancers = detach_from(all_load_balancers, instance)\n\n @lb_wait_params = []\n\n load_balancers.each do |lb|\n params = {\n load_balancer_name: lb.load_balancer_name,\n instances: [{ instance_id: instance.ec2_instance_id }]\n }\n\n remaining_instances = @elb_client\n .deregister_instances_from_load_balancer(params)\n .instances\n\n log(<<-MSG.split.join(\" \"))\n Will detach instance #{instance.hostname} from\n #{lb.load_balancer_name} (remaining attached instances:\n #{remaining_instances.count.to_s})\n MSG\n\n @lb_wait_params << params\n end\n \n unless @regional_deploy\n if @lb_wait_params.any?\n wait_for_detach(@lb_wait_params)\n else\n log(\"No load balancers found for instance #{instance.hostname}\")\n end\n end\n\n load_balancers\n end",
"def describe_load_balancers(ids = [], options = {})\n ids = [*ids]\n params = {}\n params['Marker'] = options[:marker] if options[:marker]\n params['PageSize'] = options[:page_size] if options[:page_size]\n params.merge!(Fog::AWS.serialize_keys('LoadBalancerArns', ids)) if ids.any?\n params.merge!(Fog::AWS.serialize_keys('Names', options[:names])) if options[:names]\n request({\n 'Action' => 'DescribeLoadBalancers',\n :parser => Fog::Parsers::AWS::ELBV2::DescribeLoadBalancers.new\n }.merge!(params))\n end",
"def load_balancer # rubocop:disable AbcSize\n raise 'Can not determine hostname to load client for' if @new_resource.f5.nil?\n @@load_balancers ||= []\n add_lb(@new_resource.f5) if @@load_balancers.empty?\n add_lb(@new_resource.f5) if @@load_balancers.find { |lb| lb.name == @new_resource.f5 }.nil?\n @@load_balancers.find { |lb| lb.name == @new_resource.f5 }\n end",
"def health\n health = AWS.memoize do\n load_balancer.instances.health.inject({}) do |h,i|\n instance = i[:instance]\n h[instance.id] = i\n h\n end\n end rescue nil\n end",
"def fetch_from_ec2_loadbalancer\n instances_for_deploy = []\n loadbalancer lb_webserver, :web\n instances_for_deploy\nend",
"def fetch_from_ec2_loadbalancer\n instances_for_deploy = []\n loadbalancer lb_webserver, :web\n instances_for_deploy\nend",
"def add_instance(instance)\n register_response = client.register_instances_with_load_balancer(load_balancer_name: name,\n instances: [{instance_id: instance.ec2_instance_id}])\n remaining_instance_count = register_response.instances.size\n puts \"Added #{instance.hostname} to ELB #{name}. Attached instances: #{remaining_instance_count}\".light_blue\n _wait_for_instance_health_check(instance)\n end",
"def check_arguments(instance:, load_balancers:)\n unless instance.is_a?(Aws::OpsWorks::Types::Instance)\n fail(ArgumentError,\n \":instance must be a Aws::OpsWorks::Types::Instance struct\")\n end\n unless load_balancers.respond_to?(:each) &&\n load_balancers.all? do |lb|\n lb.is_a?(Aws::ElasticLoadBalancing::Types::LoadBalancerDescription)\n end\n fail(ArgumentError, <<-MSG.split.join(\" \"))\n :load_balancers must be a collection of\n Aws::ElasticLoadBalancing::Types::LoadBalancerDescription objects\n MSG\n end\n end",
"def detach_from(load_balancers, instance)\n check_arguments(instance: instance, load_balancers: load_balancers)\n\n load_balancers.select do |lb|\n matched_instance = lb.instances.any? do |lb_instance|\n instance.ec2_instance_id == lb_instance.instance_id\n end\n\n if matched_instance && lb.instances.count > 1\n # We can detach this instance safely because there is at least one other\n # instance to handle traffic\n true\n elsif matched_instance && lb.instances.count == 1\n # We can't detach this instance because it's the only one\n log(<<-MSG.split.join(\" \"))\n Will not detach #{instance.hostname} from load balancer\n #{lb.load_balancer_name} because it is the only instance connected\n MSG\n\n false\n else\n # This load balancer isn't attached to this instance\n false\n end\n end\n end",
"def create_elb(elb)\n resp = aws_api_connect(\"ELB_Client\")\n begin\n pants = resp.create_load_balancer({\n load_balancer_name: elb[:name],\n listeners: [\n {\n protocol: elb[:protocol],\n load_balancer_port: elb[:port],\n instance_protocol: elb[:instnace_protocol],\n instance_port: elb[:instance_port],\n ssl_certificate_id: elb[:ssl_cert],\n },\n ],\n subnets: elb[:subnets],\n security_groups: elb[:security_groups],\n })\n rescue Aws::ElasticLoadBalancing::Errors::DuplicateLoadBalancerName\n puts \"Load Balancer #{elb[:name]} already exists, bypassing\"\n rescue Aws::ElasticLoadBalancing::Errors::Throttling\n puts \"api throttled, retrying\"\n # TODO: Add exponential backoff\n sleep(5)\n retry\n end\n end",
"def register_instances_with_lb(lb_name, instance_ids)\n instances = instance_ids.map { |instance_id| { :instance_id => instance_id } }\n link = generate_request(\"RegisterInstancesWithLoadBalancer\",\n :load_balancer_name => lb_name, :instances => instances)\n request_info(link, QElbInstancesParser.new)\n rescue Exception\n on_exception\n end",
"def describe_load_balancers(optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'DescribeLoadBalancers'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :host_id\n\t\t\targs[:query]['HostId'] = optional[:host_id]\n\t\tend\n\t\tif optional.key? :load_balancer_id\n\t\t\targs[:query]['LoadBalancerId'] = optional[:load_balancer_id]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tif optional.key? :server_id\n\t\t\targs[:query]['ServerId'] = optional[:server_id]\n\t\tend\n\t\tself.run(args)\n\tend",
"def elb_listener(elb)\n resp = aws_api_connect(\"ELB_Client\")\n begin\n pants = resp.create_load_balancer_listeners({\n load_balancer_name: elb[:name],\n listeners: [\n {\n protocol: elb[:protocol],\n load_balancer_port: elb[:port],\n instance_protocol: elb[:instnace_protocol],\n instance_port: elb[:instance_port],\n ssl_certificate_id: elb[:ssl_cert],\n },\n ],\n })\n rescue Aws::ElasticLoadBalancing::Errors::DuplicateListener\n puts \"Load Balancer listener #{elb[:name]} duplicate exists, skipping\"\n end\n end",
"def elb_registration_check(type)\n details = obj_behavior(@elb, :describe_load_balancers, @elb_name)\n instances = details.first[:instances]\n case type\n when :all\n @servers.each do |server|\n obj_behavior(server, :settings)\n aws_id = server[\"aws-id\"]\n unless obj_behavior(instances, :include?, aws_id)\n raise \"ERROR: Did not find aws id for #{aws_id}. ID list: #{instances.inspect}\"\n end\n end\n when :none\n unless obj_behavior(instances, :empty?)\n raise \"ERROR: found registered instances when there should be none. ID list: #{instances.inspect}\"\n end\n else\n raise \"ERROR: only check types of :none and :all are currently supported\" \n end\n end",
"def balancer_set_instances(balancer)\n balancer\n end",
"def add_lb(hostname)\n @@load_balancers << LoadBalancer.new(hostname, create_icontrol(hostname))\n end",
"def create_load_balancer_listeners(lb_name, listeners)\n params = {}\n\n listener_protocol = []\n listener_lb_port = []\n listener_instance_port = []\n listener_instance_protocol = []\n listener_ssl_certificate_id = []\n listeners.each do |listener|\n listener_protocol.push(listener['Protocol'])\n listener_lb_port.push(listener['LoadBalancerPort'])\n listener_instance_port.push(listener['InstancePort'])\n listener_instance_protocol.push(listener['InstanceProtocol'])\n listener_ssl_certificate_id.push(listener['SSLCertificateId'])\n end\n\n params.merge!(Fog::AWS.indexed_param('Listeners.member.%d.Protocol', listener_protocol))\n params.merge!(Fog::AWS.indexed_param('Listeners.member.%d.LoadBalancerPort', listener_lb_port))\n params.merge!(Fog::AWS.indexed_param('Listeners.member.%d.InstancePort', listener_instance_port))\n params.merge!(Fog::AWS.indexed_param('Listeners.member.%d.InstanceProtocol', listener_instance_protocol))\n params.merge!(Fog::AWS.indexed_param('Listeners.member.%d.SSLCertificateId', listener_ssl_certificate_id))\n\n request({\n 'Action' => 'CreateLoadBalancerListeners',\n 'LoadBalancerName' => lb_name,\n :parser => Fog::Parsers::AWS::ELB::Empty.new\n }.merge!(params))\n end",
"def describe_load_balancers(optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'DescribeLoadBalancers'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :address\n\t\t\targs[:query]['Address'] = optional[:address]\n\t\tend\n\t\tif optional.key? :address_type\n\t\t\targs[:query]['AddressType'] = optional[:address_type]\n\t\tend\n\t\tif optional.key? :internet_charge_type\n\t\t\targs[:query]['InternetChargeType'] = optional[:internet_charge_type]\n\t\tend\n\t\tif optional.key? :load_balancer_id\n\t\t\targs[:query]['LoadBalancerId'] = optional[:load_balancer_id]\n\t\tend\n\t\tif optional.key? :master_zone_id\n\t\t\targs[:query]['MasterZoneId'] = optional[:master_zone_id]\n\t\tend\n\t\tif optional.key? :network_type\n\t\t\targs[:query]['NetworkType'] = optional[:network_type]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tif optional.key? :owner_id\n\t\t\targs[:query]['OwnerId'] = optional[:owner_id]\n\t\tend\n\t\tif optional.key? :resource_owner_account\n\t\t\targs[:query]['ResourceOwnerAccount'] = optional[:resource_owner_account]\n\t\tend\n\t\tif optional.key? :resource_owner_id\n\t\t\targs[:query]['ResourceOwnerId'] = optional[:resource_owner_id]\n\t\tend\n\t\tif optional.key? :security_status\n\t\t\targs[:query]['SecurityStatus'] = optional[:security_status]\n\t\tend\n\t\tif optional.key? :server_id\n\t\t\targs[:query]['ServerId'] = optional[:server_id]\n\t\tend\n\t\tif optional.key? :slave_zone_id\n\t\t\targs[:query]['SlaveZoneId'] = optional[:slave_zone_id]\n\t\tend\n\t\tif optional.key? :v_switch_id\n\t\t\targs[:query]['VSwitchId'] = optional[:v_switch_id]\n\t\tend\n\t\tif optional.key? :vpc_id\n\t\t\targs[:query]['VpcId'] = optional[:vpc_id]\n\t\tend\n\t\tself.run(args)\n\tend",
"def ready_load_balancer(action_handler, lb_spec, lb_options, machine_specs)\n end",
"def allocate_load_balancer(action_handler, lb_spec, lb_options, machine_specs)\n end",
"def balancer_all(options = {})\n load_balancer_data\n end",
"def update_instances(elb_name, instances_added, instances_removed = [])\n\n # deregister instances that were removed\n if !instances_removed.empty?\n @elb.deregister_instances_from_load_balancer({\n load_balancer_name: elb_name,\n instances: instances_removed.map do |i|\n {\n instance_id: i\n }\n end\n })\n end\n\n # register instances that were added\n if !instances_added.empty?\n @elb.register_instances_with_load_balancer({\n load_balancer_name: elb_name,\n instances: instances_added.map do |i|\n {\n instance_id: i\n }\n end\n })\n end\n end",
"def retrieve_elb(name)\n Clients.elb.describe_load_balancers(\n load_balancer_names: [name],\n ).load_balancer_descriptions[0]\nend",
"def add_loadbalancer_groups\n if any_hosts_as?(:loadbalancer)\n loadbalancer_group = {\n \"name\" => \"HAProxy Loadbalancer\",\n \"rule\" => [\"or\", [\"=\", \"name\", loadbalancer.node_name]], # pinned node\n \"parent\" => pe_infra_uuid,\n \"classes\" => {\n \"profile::loadbalancer\" => {}\n }\n }\n\n dispatcher.find_or_create_node_group_model(loadbalancer_group)\n end\n\n return unless any_hosts_as?(:compile_master)\n\n lb_export_rules = [\"or\"]\n lb_export_rules += [compile_master].flatten.map do |server|\n [\"=\", \"name\", server.node_name]\n end\n\n loadbalancer_exports_group = {\n \"name\" => \"Loadbalancer Exports(Compile Masters)\",\n \"rule\" => lb_export_rules, # pinned node\n \"parent\" => pe_infra_uuid,\n \"classes\" => {\n \"profile::loadbalancer_exports\" => {}\n }\n }\n dispatcher.find_or_create_node_group_model(loadbalancer_exports_group)\nend",
"def deregister_instances_from_load_balancer(instance_ids, lb_name)\n params = Fog::AWS.indexed_param('Instances.member.%d.InstanceId', [*instance_ids])\n request({\n 'Action' => 'DeregisterInstancesFromLoadBalancer',\n 'LoadBalancerName' => lb_name,\n :parser => Fog::Parsers::AWS::ELB::DeregisterInstancesFromLoadBalancer.new\n }.merge!(params))\n end",
"def get_elb(layer_name)\n layer_id = layers[layer_name].layer_id\n elbs = opsworks_client.describe_elastic_load_balancers(layer_ids:[layer_id])\n if elbs.elastic_load_balancers.size > 0\n name = elbs.elastic_load_balancers.first.elastic_load_balancer_name\n ELB.new(name)\n else\n nil\n end\n end",
"def attach_load_balancer_to_subnets(subnet_ids, lb_name)\n params = Fog::AWS.indexed_param('Subnets.member', [*subnet_ids])\n request({\n 'Action' => 'AttachLoadBalancerToSubnets',\n 'LoadBalancerName' => lb_name,\n :parser => Fog::Parsers::AWS::ELB::AttachLoadBalancerToSubnets.new\n }.merge!(params))\n end",
"def balancer_health_check(balancer)\n balancer\n end",
"def add_to_lb(group)\n @haproxy.identity_filter(@load_balancer)\n # We don't have to identify the nodes in the group\n # for every action. I'm doing it here to make each\n # method easier to read\n @rpcutil.class_filter(group)\n begin\n @rpcutil.ping.each do |node|\n hostname = node.results[:sender]\n # Disable the nodes\n @haproxy.enable(:backend => 'puppetcamp', :server => hostname).each do |rpcresult|\n if rpcresult.results[:statuscode] != 0\n raise LoadBalancerAddException, hostname\n end\n end\n end\n ensure\n @haproxy.reset_filter\n @rpcutil.reset_filter\n end\nend",
"def elastic_load_balancer(name=nil, &block)\n @elastic_load_balancer ||= name ? _elastic_load_balancer(name, &block) : _elastic_load_balancer\n end",
"def test_00_describe_load_balancers\n items = @elb.describe_load_balancers\n assert items.is_a?(Array)\n end",
"def describe_listeners(load_balancer_arn, options = {})\n request({\n 'Action' => 'DescribeListeners',\n 'LoadBalancerArn' => load_balancer_arn,\n :parser => Fog::Parsers::AWS::ELBV2::DescribeListeners.new\n }.merge!(options))\n end",
"def modify_load_balancer_attributes(lb_name, options)\n attributes = Fog::AWS.serialize_keys 'LoadBalancerAttributes', options\n request(attributes.merge(\n 'Action' => 'ModifyLoadBalancerAttributes',\n 'LoadBalancerName' => lb_name,\n :parser => Fog::Parsers::AWS::ELB::Empty.new\n ))\n end",
"def createCLB(elbv1, sg_tcp_80_lb, pub_net1_id, pub_net2_id)\n # TODO: Remove CLB by name if create fails to fully create\n\n # Create CLB\n response = elbv1.create_load_balancer(load_balancer_name: 'AutoCLB',\n subnets: [pub_net1_id, pub_net2_id],\n security_groups: [sg_tcp_80_lb],\n listeners: [{ protocol: 'HTTP',\n load_balancer_port: 80,\n instance_protocol: 'HTTP',\n instance_port: 80 }])\n clb_dns_name = response.dns_name\n puts \"clb_dns_name = #{clb_dns_name}\"\n clb_dns_name # return\nend",
"def populate\n response = @connection.lbreq(\"GET\",@lbmgmthost,\"#{@lbmgmtpath}/loadbalancers/#{CloudLB.escape(@id.to_s)}\",@lbmgmtport,@lbmgmtscheme)\n CloudLB::Exception.raise_exception(response) unless response.code.to_s.match(/^20.$/)\n data = JSON.parse(response.body)['loadBalancer']\n @id = data[\"id\"]\n @name = data[\"name\"]\n @protocol = data[\"protocol\"]\n @port = data[\"port\"]\n @algorithm = data[\"algorithm\"]\n @connection_logging = data[\"connectionLogging\"][\"enabled\"]\n @status = data[\"status\"]\n @timeout = data[\"timeout\"]\n true\n end",
"def load_balancer_names\n @group.load_balancer_names\n end",
"def instance\n node = 'AWS_EC2_INSTANCE'\n q = []\n\n # instance node\n q.push(_upsert({ node: node, id: @name }))\n\n # vpc node and relationship\n if @data.vpc_id\n opts = {\n parent_node: node,\n parent_name: @name,\n child_node: 'AWS_VPC',\n child_name: @data.vpc_id,\n relationship: 'MEMBER_OF_VPC'\n }\n\n q.push(_upsert_and_link(opts))\n end\n\n # network_interfaces and relationship\n @data.network_interfaces.each do |ni|\n opts = {\n parent_node: node,\n parent_name: @name,\n child_node: 'AWS_NETWORK_INTERFACE',\n child_name: ni.network_interface_id,\n relationship: 'ATTACHED_TO_INSTANCE'\n }\n\n q.push(_upsert_and_link(opts))\n end\n\n # security_groups and relationship\n @data.security_groups.each do |sg|\n opts = {\n child_node: 'AWS_SECURITY_GROUP',\n child_name: sg.group_id,\n parent_node: node,\n parent_name: @name,\n relationship: 'IN_SECURITY_GROUP'\n }\n\n q.push(_upsert_and_link(opts))\n end\n\n # subnet and relationship\n if @data.subnet_id\n opts = {\n parent_node: node,\n parent_name: @name,\n child_node: 'AWS_SUBNET',\n # child_name: \"arn:aws:ec2:#{@region}:#{@account}:subnet/#{@data.subnet_id}\",\n child_name: @data.subnet_id,\n relationship: 'IN_SUBNET'\n }\n\n q.push(_upsert_and_link(opts))\n end\n\n if @data.iam_instance_profile\n opts = {\n node: 'AWS_EC2_IAM_PROFILE',\n id: @data.iam_instance_profile.arn\n }\n\n q.push(_merge(opts))\n\n opts = {\n from_node: node,\n from_name: @name,\n to_node: 'AWS_EC2_IAM_PROFILE',\n to_name: @data.iam_instance_profile.arn,\n relationship: 'HAS_IAM_PROFILE'\n }\n\n q.push(_link(opts))\n end\n\n if @data.metadata_options\n metadata_options = \"#{@name}-metadata-options\"\n\n opts = {\n node: 'AWS_EC2_INSTANCE_METADATA_OPTIONS',\n id: metadata_options\n }\n\n q.push(_merge(opts))\n\n opts = {\n from_node: node,\n from_name: @name,\n to_node: 'AWS_EC2_INSTANCE_METADATA_OPTIONS',\n to_name: metadata_options,\n relationship: 'HAS_METADATA_OPTIONS',\n relationship_attributes: @data.metadata_options.to_h\n }\n\n q.push(_link(opts))\n end\n\n q\n end",
"def add_load_balancer(name, ports, ip_address)\n\n unless ports.is_a? Array\n ports = [ ports ]\n end\n\n if name.nil?\n name = \"lb#{RandomName.create(5,3)}\"\n end\n\n if ip_address.is_a? String\n ip_address = public_ipaddress \"#{name}-addr\" do\n dns_settings domain_name_label: ip_address\n end\n end\n\n lb = load_balancer name do\n\n if ip_address.nil?\n fics = frontend_ipconfigurations name: name + '-feconf'\n else\n fics = frontend_ipconfigurations name: name + '-feconf',\n public_ipaddress: ip_address\n end\n\n pools = backend_address_pools name: name + '-pool'\n\n ports.each do |port|\n\n p = probes name: name + \"-probe#{port}\",\n protocol: 'Tcp',\n port: port,\n number_of_probes: 2,\n interval_in_seconds: 15\n\n load_balancing_rules name: \"rule#{port}\",\n frontend_ipconfiguration: fics[0],\n backend_address_pool: pools[0],\n protocol: 'Tcp',\n frontend_port: port,\n backend_port: port,\n idle_timeout_in_minutes: 15,\n probe: p[0]\n end\n\n end\n\n end",
"def is_load_balancer_member?\n debug \"checking load balancer membership\"\n\n if @property_hash.size > 0\n connect()\n\n load_balancer = get_loadbalancer()\n if load_balancer and load_balancer.instances.include?(@property_hash[:id])\n debug \"Instance #{@property_hash[:id]} already a member of #{resource[:load_balancer]}\"\n return resource[:load_balancer]\n else\n debug \"Registering #{@property_hash[:id]} with #{resource[:load_balancer]}\"\n return false\n end\n end\n nil\n end",
"def ec2_instance_data # rubocop:disable Metrics/MethodLength, Metrics/AbcSize\n i = {\n :placement => {\n :availability_zone => config[:availability_zone]\n },\n :instance_type => config[:instance_type],\n :ebs_optimized => config[:ebs_optimized],\n :image_id => config[:image_id],\n :key_name => config[:aws_ssh_key_id],\n :subnet_id => config[:subnet_id],\n :private_ip_address => config[:private_ip_address]\n }\n i[:block_device_mappings] = block_device_mappings unless block_device_mappings.empty?\n i[:security_group_ids] = config[:security_group_ids] if config[:security_group_ids]\n i[:user_data] = prepared_user_data if prepared_user_data\n if config[:iam_profile_name]\n i[:iam_instance_profile] = { :name => config[:iam_profile_name] }\n end\n if !config.fetch(:associate_public_ip, nil).nil?\n i[:network_interfaces] =\n [{\n :device_index => 0,\n :associate_public_ip_address => config[:associate_public_ip],\n :delete_on_termination => true\n }]\n # If specifying `:network_interfaces` in the request, you must specify\n # network specific configs in the network_interfaces block and not at\n # the top level\n if config[:subnet_id]\n i[:network_interfaces][0][:subnet_id] = i.delete(:subnet_id)\n end\n if config[:private_ip_address]\n i[:network_interfaces][0][:private_ip_address] = i.delete(:private_ip_address)\n end\n if config[:security_group_ids]\n i[:network_interfaces][0][:groups] = i.delete(:security_group_ids)\n end\n end\n i\n end",
"def load_current_resource\n\n @current_lb = load_balancer_by_name(new_resource.lb_name)\n\n @current_resource = Chef::Resource::LbLoadBalancer.new(new_resource.lb_name)\n @current_resource.lb_name(new_resource.lb_name)\n @current_resource.aws_access_key(new_resource.aws_access_key)\n @current_resource.aws_secret_access_key(new_resource.aws_secret_access_key)\n @current_resource.region(new_resource.region)\n @current_resource.listeners(new_resource.listeners)\n @current_resource.timeout(new_resource.timeout)\n\n if @current_lb\n @current_resource.availability_zones(@current_lb['AvailabilityZones'])\n @current_resource.instances(@current_lb['Instances'])\n end\n @current_resource.availability_zones || @current_resource.availability_zones([])\n @current_resource.instances || @current_resource.instances([])\n\n if new_resource.instances.nil? && new_resource.search_query\n new_resource.instances(search(:node, new_resource.search_query).map { |n| n['ec2']['instance_id']})\n end\n\n all_zones = availability_zone_for_instances(new_resource.instances)\n unique_zones = all_zones.compact.uniq\n\n if new_resource.availability_zones.nil?\n new_resource.availability_zones(unique_zones)\n end\nend",
"def is_instance_healthy(instance)\n instance_health = client.describe_instance_health(load_balancer_name: name,\n instances: [{instance_id: instance.ec2_instance_id}])\n state_info = instance_health.instance_states.first\n status_detail = ''\n if state_info.state != 'InService'\n status_detail = \"#{state_info.reason_code} - #{state_info.description}.\"\n end\n puts \"Instance state is #{state_info.state} #{status_detail}\"\n state_info.state == 'InService'\n end",
"def _wait_for_instance_health_check(instance)\n health_threshold = health_check.healthy_threshold\n interval = health_check.interval\n\n # wait a little longer than the defined threshold to account for application launch time\n timeout = ((health_threshold + 2) * interval)\n\n begin\n client.wait_until(:instance_in_service, {load_balancer_name: name,\n instances: [{instance_id: instance.ec2_instance_id}]}) do |w|\n w.before_attempt do |attempt|\n puts \"Attempt #{attempt} to check health status for #{instance.hostname}\".light_black\n end\n w.interval = 10\n w.max_attempts = timeout / w.interval\n end\n puts \"Instance #{instance.hostname} is now InService\".green\n true\n rescue Aws::Waiters::Errors::WaiterFailed => e\n puts \"Instance #{instance.hostname} failed to move to InService, #{e.message}\".red\n false\n end\n\n end",
"def migrate_elbs\n elbs_dir = \"#{@migration_root}/elb-load-balancers\"\n policies_dir =\"#{@migration_root}/elb-policies\"\n\n if !Dir.exists?(@migration_root)\n Dir.mkdir(@migration_root)\n end\n if !Dir.exists?(elbs_dir)\n Dir.mkdir(elbs_dir)\n end\n if !Dir.exists?(policies_dir)\n Dir.mkdir(policies_dir)\n end\n\n ELB::elbs.map do |elb_name, elb|\n puts \"Migrating load balancer #{elb_name}\"\n\n local_elb = LoadBalancerConfig.new(elb_name)\n tags = ELB::elb_tags(elb_name)\n attributes = ELB::elb_attributes(elb_name)\n local_elb.populate!(elb, tags, attributes)\n\n # Migrate the backend and listener policies if they do not already\n # exist locally and are not the default AWS policies\n listener_policies = local_elb.listeners.flat_map { |l| l.policies }\n backend_policies = local_elb.backend_policies.flat_map { |b| b.policy_names }\n\n (listener_policies + backend_policies).uniq.map do |policy_name|\n policy_file = \"#{policies_dir}/#{policy_name}.json\"\n # If it is not already migrated and not a default policy, create it\n if !File.file? policy_file\n if !ELB::default_policies.has_key? policy_name\n # Get the full policy description from the elb policies\n full_policy = ELB::elb_policies(elb_name)[policy_name]\n\n if full_policy.nil?\n puts \"Unable to migrate policy #{policy_name}\"\n else\n puts \"Migrating policy #{policy_name}\"\n json = JSON.pretty_generate(full_policy.to_cumulus_hash)\n File.open(policy_file, \"w\") { |f| f.write(json) }\n end\n end\n end\n end\n\n File.open(\"#{elbs_dir}/#{elb_name}.json\", \"w\") { |f| f.write(local_elb.pretty_json) }\n end\n\n end",
"def describe_instances\n return { reservations: [] } unless configured?\n\n @client.describe_instances.to_h\n end",
"def wait_until( waiter_name=:load_balancer_available, &block )\n self.class.client.wait_until(waiter_name, load_balancer_arns: [load_balancer_arn], &block)\n end",
"def balancer_reload(balancer)\n if balancer.persisted?\n begin\n load_balancer_data(balancer)\n rescue Miasma::Error::ApiError::RequestError => e\n if e.response_error_msg.include?(\"LoadBalancerNotFound\")\n balancer.state = :terminated\n balancer.status = \"terminated\"\n balancer.valid_state\n else\n raise\n end\n end\n end\n balancer\n end",
"def create_load_balancer(optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'CreateLoadBalancer'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :address\n\t\t\targs[:query]['Address'] = optional[:address]\n\t\tend\n\t\tif optional.key? :client_token\n\t\t\targs[:query]['ClientToken'] = optional[:client_token]\n\t\tend\n\t\tif optional.key? :is_public_address\n\t\t\targs[:query]['IsPublicAddress'] = optional[:is_public_address]\n\t\tend\n\t\tif optional.key? :load_balancer_mode\n\t\t\targs[:query]['LoadBalancerMode'] = optional[:load_balancer_mode]\n\t\tend\n\t\tif optional.key? :load_balancer_name\n\t\t\targs[:query]['LoadBalancerName'] = optional[:load_balancer_name]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tif optional.key? :owner_id\n\t\t\targs[:query]['OwnerId'] = optional[:owner_id]\n\t\tend\n\t\tif optional.key? :resource_owner_account\n\t\t\targs[:query]['ResourceOwnerAccount'] = optional[:resource_owner_account]\n\t\tend\n\t\tif optional.key? :resource_owner_id\n\t\t\targs[:query]['ResourceOwnerId'] = optional[:resource_owner_id]\n\t\tend\n\t\tself.run(args)\n\tend",
"def add_pool_members pool_names, member_lists\n response = post(\"http://#{@host}/loadbalancers/tenant/#{@tenant}/pools\",\n {\n :pool =>\n (pool_names.zip member_lists).map do |pool_name, members| {\n :services => members.map do |address,port| {\n :ip => address,\n :enabled => 'true',\n :name => address + ':' + port.to_s,\n :weight => \"10\",\n :port => port\n } end,\n :name => pool_name\n } end\n }.to_json)\n raise LBModelException.new \"Expected HTTP 202 but got #{response.code} instead\" unless response.code == 202\n\n parse_jobids response\n end",
"def create_instances\n min_count = max_count = @bs.number_of_nodes\n puts \"\\nCreating #{max_count} on-demand instance(s)\"\n options = {\n 'ClientToken' => generate_token,\n 'KeyName' => Chef::Config[:knife][:aws_ssh_key_id],\n 'InstanceType' => @bs.flavor,\n 'SubnetId' => @bs[:novpc] ? nil : @bs.subnet_id,\n 'Placement.AvailabilityZone' => @bs.mixins.az.data,\n 'SecurityGroupId' => @bs.mixins.sg.data\n }\n options['EbsOptimized'] = !! @bs[:ebs_optimized]\n\n ## REVIEW\n if ami.root_device_type == \"ebs\"\n ami_map = ami.block_device_mapping.first\n block_device_mapping = {\n 'DeviceName' => ami_map['deviceName'],\n 'Ebs.VolumeSize' => ami_map['volumeSize'].to_s,\n 'Ebs.DeleteOnTermination' => ami_map['deleteOnTermination']\n }\n options['BlockDeviceMapping'] = [block_device_mapping]\n end\n\n ## Optionally only include mapped devices\n ## This way we get all of the ephemeral drives, some unmapped however\n if @bs.mixins.volume.data[:ephemeral_available]\n ephmap = @bs.mixins.volume.data.ephemeral_available.each_with_index.map do |d,i|\n {\n 'VirtualName' => \"ephemeral#{i}\",\n 'DeviceName' => d\n }\n end\n options['BlockDeviceMapping'].concat( ephmap )\n end\n\n if (max_count == 1) and @bs[:private_ip_address]\n options['PrivateIpAddress'] = @bs.private_ip_address\n puts \"Assigning IP ADDRESS : #{options['PrivateIpAddress']}\"\n end\n\n if Chef::Config[:knife][:aws_user_data]\n begin\n options['UserData']= File.read(Chef::Config[:knife][:aws_user_data])\n rescue\n ui.warn(\"Cannot read #{Chef::Config[:knife][:aws_user_data]}:\"\\\n \" #{$!.inspect}. Ignoring option.\")\n end\n end\n\n # -----------------------------------------------------------------\n tries = 5\n print_table(options, 'Launch Config')\n begin\n puts \"\\nSending request...\"\n response = connection.run_instances(@bs.image, min_count,\n max_count, options)\n ui.msg(response.inspect)\n rescue Exception => e\n ui.warn(\"#{e.message}\\nException creating instances\")\n if (tries -= 1) <= 0\n ui.warn(\"\\n\\nMax tries reached. Exiting.\\n\\n\")\n exit 1\n else\n ui.msg(\"Trying again.\\n\")\n retry\n end\n end\n # now we have our servers\n instances = response.body['instancesSet']\n # select only instances that have instanceId key and collect those ids\n # into an array\n @bs[:instance_ids] =\n instances.select {|i| i.has_key?('instanceId')}.collect do |i|\n i['instanceId']\n end\n\n puts \"\\nNumber of instances started: #{@bs.instance_ids.size}\\n\"\n sleep 10\n puts \"Getting servers..\"\n # collect an array of servers retrieved based on the instance ids we\n # obtained above\n @bs[:servers] = @bs.instance_ids.collect do |id|\n begin\n server = connection.servers.get(id)\n rescue Exception => e\n sleep 7\n retry\n end\n raise Ec2Error.new(\"server #{id} was nil\") if server.nil?\n server\n end\n end",
"def describe_listeners(lb_id = nil, listener_ids = [], options = {})\n listener_ids = Array(listener_ids)\n params = {}\n params['Marker'] = options[:marker] if options[:marker]\n params['PageSize'] = options[:page_size] if options[:page_size]\n\n params['LoadBalancerArn'] = lb_id if lb_id\n params.merge!(Fog::AWS.serialize_keys('ListenerArns', listener_ids)) if listener_ids.any?\n request({\n 'Action' => 'DescribeListeners',\n :parser => Fog::Parsers::AWS::ELBV2::DescribeListeners.new\n }.merge(params))\n end",
"def describe_load_balancer_attributes(lb_id)\n request({\n 'Action' => 'DescribeLoadBalancerAttributes',\n 'LoadBalancerArn' => lb_id,\n :parser => Fog::Parsers::AWS::ELBV2::DescribeLoadBalancerAttributes.new\n })\n end",
"def test\n connection = Fog::Compute.new(:provider => \"google\")\n health = connection.http_health_checks.create(:name => \"test-checks\")\n instance1 = connection.servers.get(\"fog-l7-instance-1\")\n instance2 = connection.servers.get(\"fog-l7-instance-2\")\n instance3 = connection.servers.get(\"fog-l7-instance-3\")\n\n resource_view1 = connection.resource_views.create(\n :name => \"fog-l7-resource-view-1\",\n :numMembers => 1,\n :members => [instance1.self_link],\n :zone => \"us-central1-a\"\n )\n resource_view1.add_resources(instance1.self_link)\n resource_view2 = connection.resource_views.create(\n :name => \"fog-l7-resource-view-2\",\n :numMembers => 1,\n :members => [instance2.self_link],\n :zone => \"us-central1-a\"\n )\n resource_view2.add_resources(instance2.self_link)\n resource_view3 = connection.resource_views.create(\n :name => \"fog-l7-resource-view-3\",\n :members => [instance3.self_link],\n :zone => \"us-central1-b\"\n )\n resource_view3.add_resources(instance3.self_link)\n backend_service1 = connection.backend_services.create(\n :name => \"fog-l7-backend-service-1\",\n :health_checks => [health.self_link],\n :backends => [{ \"balancingMode\" => \"RATE\", \"maxRate\" => 100, \"group\" => resource_view1.self_link }]\n )\n backend_service2 = connection.backend_services.create(\n :name => \"fog-l7-backend-service-2\",\n :health_checks => [health.self_link],\n :backends => [{ \"balancingMode\" => \"RATE\", \"maxRate\" => 100, \"group\" => resource_view2.self_link }]\n )\n backend_service3 = connection.backend_services.create(\n :name => \"fog-l7-backend-service-3\",\n :health_checks => [health.self_link],\n :backends => [{ \"balancingMode\" => \"RATE\", \"maxRate\" => 100, \"group\" => resource_view3.self_link }]\n )\n url_map = connection.url_maps.create(\n :name => \"fog-l7-url-map\",\n :pathMatchers => [{\n \"name\" => \"pathmatcher\",\n \"defaultService\" => backend_service1.self_link,\n \"pathRules\" => [\n {\n \"paths\" => [\"/one/*\"],\n \"service\" => backend_service1.self_link\n },\n {\n \"paths\" => [\"/two/*\"],\n \"service\" => backend_service2.self_link\n },\n {\n \"paths\" => [\"/three/*\"],\n \"service\" => backend_service3.self_link\n }\n ]\n }],\n :hostRules => [{ \"hosts\" => [\"*\"], \"pathMatcher\" => \"pathmatcher\" }],\n :default_service => backend_service1.self_link\n )\n proxy = connection.target_http_proxies.create(\n :name => \"fog-l7-proxy\",\n :url_map => url_map.self_link\n )\n\n connection.global_forwarding_rules.create(:name => \"fog-l7-fwd-rule\", :target => proxy.self_link)\nend",
"def instances\n @instances ||= aws_client.instances(filters: instance_filters).map do |instance|\n OpenStruct.new(\n with_tags(instance, private_ip: instance.private_ip_address,\n public_ip: instance.public_ip_address,\n instance: instance.instance_id)\n )\n end\n end",
"def create_load_balancer_pool_with_http_info(lb_pool, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ManagementPlaneApiServicesLoadbalancerApi.create_load_balancer_pool ...'\n end\n # verify the required parameter 'lb_pool' is set\n if @api_client.config.client_side_validation && lb_pool.nil?\n fail ArgumentError, \"Missing the required parameter 'lb_pool' when calling ManagementPlaneApiServicesLoadbalancerApi.create_load_balancer_pool\"\n end\n # resource path\n local_var_path = '/loadbalancer/pools'\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = @api_client.object_to_http_body(lb_pool)\n auth_names = ['BasicAuth']\n data, status_code, headers = @api_client.call_api(:POST, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'LbPool')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ManagementPlaneApiServicesLoadbalancerApi#create_load_balancer_pool\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def available_instances\n @available_instances ||= {}\n end",
"def grab_scannable_instances(address_blob, active_addresses)\n # list to hold all addresses of a region\n ec2_addresses_list = []\n address_blob.each do |address|\n # gathers all ip addresses for a region and pushes all of them to ec2_addresses_list\n # if they are still active in the account\n ec2_addresses_list.push(address['public_ip_address']) if active_addresses.include?(address['public_ip_address'])\n end\n ec2_addresses_list\nend",
"def balancer\n @balancer ||= RightSupport::Net::RequestBalancer.new(@@hostnames,\n :policy=>RightSupport::Net::Balancing::StickyPolicy)\n end",
"def enable_availability_zones_for_lb(lb_name, availability_zones)\n link = generate_request(\"EnableAvailabilityZonesForLoadBalancer\",\n :load_balancer_name => lb_name, :availability_zones => availability_zones)\n request_info(link, QElbAvailabilityZonesParser.new)\n rescue Exception\n on_exception\n end",
"def create name, type, attributes = {}\n\n attribute_list = []\n\n attributes.each do |attr_name,values|\n [values].flatten.each do |value|\n attribute_list << { \n :attribute_name => attr_name, \n :attribute_value => value.to_s \n }\n end\n end\n\n client.create_load_balancer_policy(\n :load_balancer_name => load_balancer.name,\n :policy_name => name.to_s,\n :policy_type_name => type.to_s,\n :policy_attributes => attribute_list)\n\n LoadBalancerPolicy.new(load_balancer, name, :type => type.to_s)\n\n end",
"def get_available_host\n @hosts.each do |host|\n return host if ws_running?([host]) < @ws_limit\n end\n puts \"No host available! Providing a new one on aws\"\n json = `aws ec2 run-instances --image-id ami-689cc908 --instance-type t2.medium --key-name mior --security-group-id sg-5bb3af3f`\n json = JSON.parse(json)\n internal_ip = json[\"Instances\"][0][\"NetworkInterfaces\"][0][\"PrivateIpAddress\"]\n public_ip = nil\n while public_ip.nil?\n cmd = \"aws ec2 describe-instances --filter \\\"Name=private-ip-address, Values=#{internal_ip}\\\"\"\n json = JSON.parse(`#{cmd}`)\n public_ip = json[\"Reservations\"][0][\"Instances\"][0][\"NetworkInterfaces\"][0][\"Association\"][\"PublicIp\"]\n end\n puts \"New instance on aws: #{public_ip}\"\n @hosts.push(public_ip)\n puts 'Waiting the host powers up..'\n sleep 30\n public_ip\n # The elegant way should be instantiate a new host to receive more requests\n end",
"def deregister_instances_from_lb(lb_name, instance_ids)\n instances = instance_ids.map { |instance_id| { :instance_id => instance_id } }\n link = generate_request(\"DeregisterInstancesFromLoadBalancer\",\n :load_balancer_name => lb_name, :instances => instances\n )\n request_info(link, QElbInstancesParser.new)\n rescue Exception\n on_exception\n end",
"def create_load_balancer(optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'CreateLoadBalancer'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :address_type\n\t\t\targs[:query]['AddressType'] = optional[:address_type]\n\t\tend\n\t\tif optional.key? :bandwidth\n\t\t\traise ArgumentError, 'bandwidth must be equal or greater than -1' unless optional[:bandwidth] < -1\n\t\t\traise ArgumentError, 'bandwidth must be equal or less than 1000' unless optional[:bandwidth] > 1000\n\t\t\targs[:query]['Bandwidth'] = optional[:bandwidth]\n\t\tend\n\t\tif optional.key? :client_token\n\t\t\targs[:query]['ClientToken'] = optional[:client_token]\n\t\tend\n\t\tif optional.key? :internet_charge_type\n\t\t\targs[:query]['InternetChargeType'] = optional[:internet_charge_type]\n\t\tend\n\t\tif optional.key? :load_balancer_name\n\t\t\targs[:query]['LoadBalancerName'] = optional[:load_balancer_name]\n\t\tend\n\t\tif optional.key? :master_zone_id\n\t\t\targs[:query]['MasterZoneId'] = optional[:master_zone_id]\n\t\tend\n\t\tif optional.key? :max_conn_limit\n\t\t\targs[:query]['MaxConnLimit'] = optional[:max_conn_limit]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tif optional.key? :owner_id\n\t\t\targs[:query]['OwnerId'] = optional[:owner_id]\n\t\tend\n\t\tif optional.key? :resource_owner_account\n\t\t\targs[:query]['ResourceOwnerAccount'] = optional[:resource_owner_account]\n\t\tend\n\t\tif optional.key? :resource_owner_id\n\t\t\targs[:query]['ResourceOwnerId'] = optional[:resource_owner_id]\n\t\tend\n\t\tif optional.key? :security_status\n\t\t\targs[:query]['SecurityStatus'] = optional[:security_status]\n\t\tend\n\t\tif optional.key? :slave_zone_id\n\t\t\targs[:query]['SlaveZoneId'] = optional[:slave_zone_id]\n\t\tend\n\t\tif optional.key? :v_switch_id\n\t\t\targs[:query]['VSwitchId'] = optional[:v_switch_id]\n\t\tend\n\t\tif optional.key? :vpc_id\n\t\t\targs[:query]['VpcId'] = optional[:vpc_id]\n\t\tend\n\t\tself.run(args)\n\tend",
"def modify_load_balancer_attributes(lb_id, attributes)\n attributes = Fog::AWS.serialize_keys 'Attributes', attributes.map{ |property, value| { :Key => property, :Value => value } }\n request(attributes.merge(\n 'Action' => 'ModifyLoadBalancerAttributes',\n 'LoadBalancerArn' => lb_id,\n :parser => Fog::Parsers::AWS::ELBV2::ModifyLoadBalancerAttributes.new\n ))\n end",
"def get_mapped_elbs( hostname = nil, layers = nil )\n get_mapped_resources( BAG_NAME, hostname, layers )\n end",
"def update_lb_servers\n clean_up\n @hosts.each do |host|\n Docker.url = \"tcp://#{host}:#{@docker_port}/\"\n containers = Docker::Container.all(all: true, filters: { ancestor: [@ws_image], status:['running'] }.to_json)\n containers.each do |container|\n port = container.json['HostConfig']['PortBindings']['8070/tcp'][0]['HostPort']\n register_container(host, port, container.id)\n end\n end\n end",
"def list_configs(lb_id, headers = {})\n get!(\"loadbalancers/#{lb_id}/configs\", {}, headers)\n end",
"def dns_check\n gen_host_records # These are the hosts we have\n load_all_subnets # These are the DNS entries\n \n # We want a standard layout, with the hypervisor API entries being \n @host_record.each do |hr| # Array of host record Hash's\n hn = hr[:hostname]\n shn = hn.split('.',2)[0] # Remove the domain\n forward_hr = @forward_host_record[hn] # Find Host Record\n if forward_hr.nil?\n # We have no IPAM entry for this hostname\n if (rhr = @reverse_host_records[hr[:ip]])\n puts \"Only Reverse IPAM entry for #{shn}: #{rhr}\"\n @infoblox.create_host_record(ip_address: hr[:ip], hostname: hn, aliases: hr[:aliases])\n else\n puts \"No IPAM entry for hostrecord: #{hr}\"\n @infoblox.create_host_record(ip_address: hr[:ip], hostname: hn, aliases: hr[:aliases])\n end\n else\n # We have an IPAM record for this hostname\n if forward_hr[:ip] != hr[:ip]\n puts \"IP mismatch #{shn} #{hr[:ip]} != #{forward_hr[:ip]} for IPAM: #{forward_hr}\"\n elsif forward_hr[:hostname] != hn\n # Reference must be via ALIASES or CNAMES\n if forward_hr[:aliases].include?(shn)\n puts \"Hostname #{shn} is an ALIAS. IPAM: #{forward_hr}\"\n elsif forward_hr[:cnames].include?(hn)\n puts \"Hostname #{shn} is a CNAME. IPAM: #{forward_hr}\"\n end\n end\n end\n end\n \n # We want to find IPAM entries, not matching existing @host_record entries\n @reverse_host_records.each do |ip, ahr| # Hash to array of host records from IPAM, indexed by IP\n ahr.each do |hr| # One IP can have multiple host records, with associated ALIAS and CNAME records\n local_hr = @host_record_index[hr[:hostname]]\n if local_hr.nil?\n puts \"No local entry #{hr[:hostname]} for #{hr}\"\n end\n end\n end\nend",
"def services_web_application_name_servers_web_server_name_load_balancing_put(authorization, web_application_name, web_server_name, load_balancing, opts = {})\n data,status_code,headers = services_web_application_name_servers_web_server_name_load_balancing_put_with_http_info(authorization, web_application_name, web_server_name, load_balancing, opts)\n return data,status_code,headers\n end",
"def describe_load_balancer_attribute(optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'DescribeLoadBalancerAttribute'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :host_id\n\t\t\targs[:query]['HostId'] = optional[:host_id]\n\t\tend\n\t\tif optional.key? :load_balancer_id\n\t\t\targs[:query]['LoadBalancerId'] = optional[:load_balancer_id]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tself.run(args)\n\tend",
"def is_load_balancer?\n node_type.is_loadbalancer?\n end",
"def add_instance(params)\n Fog::Logger.deprecation(\n \"#{self.class}.#{__method__} is deprecated, use Fog::Compute::Google::InstanceGroup.#{__method__} instead [light_black](#{caller(0..0)})[/]\"\n )\n params[:instance] = [params[:instance]] unless params[:instance] == Array\n service.add_instance_group_instances(params[:group], params[:zone], params[:instance])\n end",
"def get_loadbalancer(name=resource[:load_balancer])\n get_cloud_connection()\n args = []\n\n args << @connection_resource[:user]\n args << @connection_resource[:pass]\n args << @connection_resource[:location] if @connection_resource[:location]\n\n @loadbalancer_connection = Puppet::Type::Loadbalancer::ProviderElb.connection(*args)\n\n load_balancer = @loadbalancer_connection.load_balancers.find {|lb|\n lb.id == name\n }\n end",
"def backend_instances(refresh=false)\n if @backend_instances.nil? or refresh\n @backend_instances = {}\n backend_data = @socket.execute( \"show stat -1 4 -1\" )[1..-1].collect{|item| item.split(\",\")[0..1]}\n backend_servers = backend_data.inject({}){|hash, items|\n (hash[items[0]] ||=[]) << items[1]; hash\n }\n backend_servers.each do |backend, servers|\n @backend_instances[backend] = HAProxyManager::Backend.new(backend, @socket)\n end\n end\n @backend_instances\n end",
"def aws_instance_elastic_ip_associate(opts)\n opts[:instance].associate_elastic_ip(opts[:elastic_ip])\n end",
"def create\n @loadbalancer = Loadbalancer.new(params[:loadbalancer])\n @loadbalancer.account_id = @oeaccount.id\n respond_to do |format|\n if @loadbalancer.save\n format.html { redirect_to loadbalancers_url, notice: 'Loadbalancer was successfully created.' }\n format.json { render json: @loadbalancer, status: :created, location: @loadbalancer }\n else\n format.html { render action: \"new\" }\n format.json { render json: @loadbalancer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def add_http_load_balancer(name, ip_address=nil)\n\n add_load_balancer name, 80, ip_address\n\n end",
"def update_health_check(elb_name, health_check)\n @elb.configure_health_check({\n load_balancer_name: elb_name,\n health_check: health_check.to_aws\n })\n end",
"def list_instance_snapshots(rds_resource)\n instance_snapshots = []\n rds_resource.db_snapshots.each do |s|\n instance_snapshots.append({\n \"id\": s.snapshot_id,\n \"status\": s.status\n })\n end\n instance_snapshots\nrescue Aws::Errors::ServiceError => e\n puts \"Couldn't list instance snapshots:\\n #{e.message}\"\nend",
"def dependencies(use_cache: false)\n @dependencies = {} if @dependencies.nil?\n @loadbalancers = [] if @loadbalancers.nil?\n if @config.nil?\n return [@dependencies, @vpc, @loadbalancers]\n end\n if use_cache and @dependencies.size > 0\n return [@dependencies, @vpc, @loadbalancers]\n end\n @config['dependencies'] = [] if @config['dependencies'].nil?\n\n # First, general dependencies. These should all be fellow members of\n # the current deployment.\n @config['dependencies'].each { |dep|\n @dependencies[dep['type']] ||= {}\n next if @dependencies[dep['type']].has_key?(dep['name'])\n handle = @deploy.findLitterMate(type: dep['type'], name: dep['name']) if !@deploy.nil?\n if !handle.nil?\n MU.log \"Loaded dependency for #{self}: #{dep['name']} => #{handle}\", MU::DEBUG\n @dependencies[dep['type']][dep['name']] = handle\n else\n # XXX yell under circumstances where we should expect to have\n # our stuff available already?\n end\n }\n\n # Special dependencies: my containing VPC\n if self.class.can_live_in_vpc and !@config['vpc'].nil?\n MU.log \"Loading VPC for #{self}\", MU::DEBUG, details: @config['vpc']\n if !@config['vpc'][\"vpc_name\"].nil? and @deploy\n sib_by_name = @deploy.findLitterMate(name: @config['vpc']['vpc_name'], type: \"vpcs\", return_all: true)\n if sib_by_name.is_a?(Array)\n if sib_by_name.size == 1\n @vpc = matches.first\n else\n# XXX ok but this is the wrong place for this really the config parser needs to sort this out somehow\n # we got multiple matches, try to pick one by preferred subnet\n # behavior\n sib_by_name.each { |sibling|\n all_private = sibling.subnets.map { |s| s.private? }.all?(true)\n all_public = sibling.subnets.map { |s| s.private? }.all?(false)\n if all_private and [\"private\", \"all_private\"].include?(@config['vpc']['subnet_pref'])\n @vpc = sibling\n break\n elsif all_public and [\"public\", \"all_public\"].include?(@config['vpc']['subnet_pref'])\n @vpc = sibling\n break\n else\n MU.log \"Got multiple matching VPCs for #{@mu_name}, so I'm arbitrarily choosing #{sibling.mu_name}\"\n @vpc = sibling\n break\n end\n }\n end\n else\n @vpc = sib_by_name\n end\n end\n\n if !@vpc and !@config['vpc'][\"vpc_name\"].nil? and\n @dependencies.has_key?(\"vpc\") and\n @dependencies[\"vpc\"].has_key?(@config['vpc'][\"vpc_name\"])\n @vpc = @dependencies[\"vpc\"][@config['vpc'][\"vpc_name\"]]\n elsif !@vpc\n tag_key, tag_value = @config['vpc']['tag'].split(/=/, 2) if !@config['vpc']['tag'].nil?\n if !@config['vpc'].has_key?(\"vpc_id\") and\n !@config['vpc'].has_key?(\"deploy_id\") and !@deploy.nil?\n @config['vpc'][\"deploy_id\"] = @deploy.deploy_id\n end\n vpcs = MU::MommaCat.findStray(\n @config['cloud'],\n \"vpc\",\n deploy_id: @config['vpc'][\"deploy_id\"],\n cloud_id: @config['vpc'][\"vpc_id\"],\n name: @config['vpc'][\"vpc_name\"],\n tag_key: tag_key,\n tag_value: tag_value,\n region: @config['vpc'][\"region\"],\n calling_deploy: @deploy,\n dummy_ok: true\n )\n @vpc = vpcs.first if !vpcs.nil? and vpcs.size > 0\n end\n if !@vpc.nil? and (\n @config['vpc'].has_key?(\"nat_host_id\") or\n @config['vpc'].has_key?(\"nat_host_tag\") or\n @config['vpc'].has_key?(\"nat_host_ip\") or\n @config['vpc'].has_key?(\"nat_host_name\")\n )\n\n nat_tag_key, nat_tag_value = @config['vpc']['nat_host_tag'].split(/=/, 2) if !@config['vpc']['nat_host_tag'].nil?\n\n @nat = @vpc.findBastion(\n nat_name: @config['vpc']['nat_host_name'],\n nat_cloud_id: @config['vpc']['nat_host_id'],\n nat_tag_key: nat_tag_key,\n nat_tag_value: nat_tag_value,\n nat_ip: @config['vpc']['nat_host_ip']\n )\n\n if @nat.nil?\n if !@vpc.cloud_desc.nil?\n @nat = @vpc.findNat(\n nat_cloud_id: @config['vpc']['nat_host_id'],\n nat_filter_key: \"vpc-id\",\n region: @config['vpc'][\"region\"],\n nat_filter_value: @vpc.cloud_id,\n credentials: @config['credentials']\n )\n else\n @nat = @vpc.findNat(\n nat_cloud_id: @config['vpc']['nat_host_id'],\n region: @config['vpc'][\"region\"],\n credentials: @config['credentials']\n )\n end\n end\n end\n elsif self.class.cfg_name == \"vpc\"\n @vpc = self\n end\n\n # Special dependencies: LoadBalancers I've asked to attach to an\n # instance.\n if @config.has_key?(\"loadbalancers\")\n @loadbalancers = [] if !@loadbalancers\n @config['loadbalancers'].each { |lb|\n MU.log \"Loading LoadBalancer for #{self}\", MU::DEBUG, details: lb\n if @dependencies.has_key?(\"loadbalancer\") and\n @dependencies[\"loadbalancer\"].has_key?(lb['concurrent_load_balancer'])\n @loadbalancers << @dependencies[\"loadbalancer\"][lb['concurrent_load_balancer']]\n else\n if !lb.has_key?(\"existing_load_balancer\") and\n !lb.has_key?(\"deploy_id\") and !@deploy.nil?\n lb[\"deploy_id\"] = @deploy.deploy_id\n end\n lbs = MU::MommaCat.findStray(\n @config['cloud'],\n \"loadbalancer\",\n deploy_id: lb[\"deploy_id\"],\n cloud_id: lb['existing_load_balancer'],\n name: lb['concurrent_load_balancer'],\n region: @config[\"region\"],\n calling_deploy: @deploy,\n dummy_ok: true\n )\n @loadbalancers << lbs.first if !lbs.nil? and lbs.size > 0\n end\n }\n end\n\n return [@dependencies, @vpc, @loadbalancers]\n end",
"def update_listeners(elb_name, local_listeners, aws_listeners, listener_changes)\n # First delete the removed listeners\n deleted_ports = listener_changes.removed.map { |port, _| port }\n deleted_listeners = aws_listeners.select { |l| deleted_ports.include? l.listener.load_balancer_port }\n\n if !deleted_ports.empty?\n @elb.delete_load_balancer_listeners({\n load_balancer_name: elb_name,\n load_balancer_ports: deleted_ports\n })\n end\n\n # Add the added listeners. If anything goes wrong, attempt a rollback (if listeners were deleted)\n added_ports = listener_changes.added.map { |port, _| port }\n added_listeners = local_listeners.select { |l| added_ports.include? l.load_balancer_port}\n if !added_listeners.empty?\n # create the listeners\n update_rollback(\"listeners\", !deleted_ports.empty?,\n # update\n Proc.new {\n @elb.create_load_balancer_listeners({\n load_balancer_name: elb_name,\n listeners: added_listeners.map { |l| l.to_aws }\n })\n },\n # rollback\n Proc.new {\n @elb.create_load_balancer_listeners({\n load_balancer_name: elb_name,\n listeners: deleted_listeners.map { |l| l.listener }\n })\n\n deleted_listeners.each { |l| update_listener_policies(elb_name, l.listener.load_balancer_port, l.policy_names) }\n }\n )\n\n # set the policies of each created listener\n added_listeners.each { |listener| update_listener_policies(elb_name, listener.load_balancer_port, listener.policies) }\n end\n\n\n # For listeners where only the policy was modified, just set the listener policies\n policy_only_listeners = listener_changes.modified.select do |port, diffs|\n diffs.size == 1 && diffs.first.type == ListenerChange::POLICIES\n end\n\n policy_only_listeners.each do |port, diffs|\n listener = local_listeners.select { |l| port == l.load_balancer_port }.first\n update_listener_policies(elb_name, listener.load_balancer_port, listener.policies)\n end\n\n # For listeners with other changes, remove the old modified listeners and add the new ones, then update the listeners for each\n modified_ports = (listener_changes.modified.reject { |port, _| policy_only_listeners.has_key? port }).map { |port, _| port }\n modified_listeners = local_listeners.select { |l| modified_ports.include? l.load_balancer_port }\n\n if !modified_listeners.empty?\n @elb.delete_load_balancer_listeners({\n load_balancer_name: elb_name,\n load_balancer_ports: modified_ports\n })\n\n # recreate the modified listeners with the new attributes\n update_rollback(\"listeners\", true,\n # update\n Proc.new {\n # create the listeners\n @elb.create_load_balancer_listeners({\n load_balancer_name: elb_name,\n listeners: modified_listeners.map { |l| l.to_aws }\n })\n },\n Proc.new {\n # create the listeners using the old config\n old_modified_listeners = aws_listeners.select { |l| modified_ports.include? l.listener.load_balancer_port }\n\n @elb.create_load_balancer_listeners({\n load_balancer_name: elb_name,\n listeners: old_modified_listeners.map { |l| l.listener }\n })\n\n # set the old policies\n old_modified_listeners.each { |l| update_listener_policies(elb_name, l.listener.load_balancer_port, l.policy_names) }\n }\n )\n\n # set the policies\n modified_listeners.each { |listener| update_listener_policies(elb_name, listener.load_balancer_port, listener.policies) }\n end\n end",
"def find(options = {})\n raise \"Unable to locate the LoadBalancer named '#{options[:name]}'\" unless options[:id]\n response = Profitbricks.request :get_load_balancer, load_balancer_id: options[:id]\n PB::LoadBalancer.new(response)\n end",
"def balancer_ids(region, env, balancer)\n h = config.lb_hash\n\n # if either the <region> or <region>.<environment> key is missing: bail out\n raise MissingKey, t('general.missing_region', region: region) unless h.key?(region)\n raise MissingKey, t('general.missing_env', region: region, env: env) unless h[region].key?(env)\n\n # if the <region>.<environment>.<balancer> key is missing: bail out\n unless h[region][env].key?(balancer)\n raise MissingKey, t('general.missing_balancer', region: region, env: env, balancer: balancer)\n end\n\n # if the value for <region>.<environment>.<balancer> is not an Array: bail out\n raise MissingKey, t('general.balancer_not_arr') unless h[region][env][balancer].kind_of?(Array)\n\n # return the Array of IDs\n h[region][env][balancer]\n end",
"def list_load_balancer_pools_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ManagementPlaneApiServicesLoadbalancerApi.list_load_balancer_pools ...'\n end\n if @api_client.config.client_side_validation && !opts[:'page_size'].nil? && opts[:'page_size'] > 1000\n fail ArgumentError, 'invalid value for \"opts[:\"page_size\"]\" when calling ManagementPlaneApiServicesLoadbalancerApi.list_load_balancer_pools, must be smaller than or equal to 1000.'\n end\n\n if @api_client.config.client_side_validation && !opts[:'page_size'].nil? && opts[:'page_size'] < 0\n fail ArgumentError, 'invalid value for \"opts[:\"page_size\"]\" when calling ManagementPlaneApiServicesLoadbalancerApi.list_load_balancer_pools, must be greater than or equal to 0.'\n end\n\n # resource path\n local_var_path = '/loadbalancer/pools'\n\n # query parameters\n query_params = {}\n query_params[:'cursor'] = opts[:'cursor'] if !opts[:'cursor'].nil?\n query_params[:'included_fields'] = opts[:'included_fields'] if !opts[:'included_fields'].nil?\n query_params[:'page_size'] = opts[:'page_size'] if !opts[:'page_size'].nil?\n query_params[:'sort_ascending'] = opts[:'sort_ascending'] if !opts[:'sort_ascending'].nil?\n query_params[:'sort_by'] = opts[:'sort_by'] if !opts[:'sort_by'].nil?\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['BasicAuth']\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'LbPoolListResult')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ManagementPlaneApiServicesLoadbalancerApi#list_load_balancer_pools\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def services_web_application_name_servers_web_server_name_load_balancing_put_with_http_info(authorization, web_application_name, web_server_name, load_balancing, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: LoadBalancingApi.services_web_application_name_servers_web_server_name_load_balancing_put ...\"\n end\n # verify the required parameter 'authorization' is set\n if @api_client.config.client_side_validation && authorization.nil?\n fail ArgumentError, \"Missing the required parameter 'authorization' when calling LoadBalancingApi.services_web_application_name_servers_web_server_name_load_balancing_put\"\n end\n # verify the required parameter 'web_application_name' is set\n if @api_client.config.client_side_validation && web_application_name.nil?\n fail ArgumentError, \"Missing the required parameter 'web_application_name' when calling LoadBalancingApi.services_web_application_name_servers_web_server_name_load_balancing_put\"\n end\n # verify the required parameter 'web_server_name' is set\n if @api_client.config.client_side_validation && web_server_name.nil?\n fail ArgumentError, \"Missing the required parameter 'web_server_name' when calling LoadBalancingApi.services_web_application_name_servers_web_server_name_load_balancing_put\"\n end\n # verify the required parameter 'load_balancing' is set\n if @api_client.config.client_side_validation && load_balancing.nil?\n fail ArgumentError, \"Missing the required parameter 'load_balancing' when calling LoadBalancingApi.services_web_application_name_servers_web_server_name_load_balancing_put\"\n end\n # resource path\n local_var_path = \"/services/{Web Application Name}/servers/{Web Server Name}/load-balancing\".sub('{' + 'Web Application Name' + '}', web_application_name.to_s).sub('{' + 'Web Server Name' + '}', web_server_name.to_s)\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n header_params[:'Authorization'] = authorization\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = @api_client.object_to_http_body(load_balancing)\n auth_names = []\n data, status_code, headers = @api_client.call_api(:PUT, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: LoadBalancingApi#services_web_application_name_servers_web_server_name_load_balancing_put\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def register_new_agent_with_instance (agent_instance)\n throw \"not an aws instance!\" if !agent_instance.is_a?AwsInstance\n url_string=\"http://#{@server_address}:#{@server_port}/agents\"\n url=URI(url_string)\n req = Net::HTTP::Post.new(url)\n agent_instance.notify \"registering new agent\"\n res=Net::HTTP.start(url.hostname,url.port) do |http|\n req.basic_auth @username,@password\n req.body=\"name=#{agent_instance.name}&ip=#{agent_instance.aws_instance_data.private_ip_address}\"\n http.request(req)\n end\n if res.code.to_i <=399\n agent_instance.notify \"registered ok! getting key\"\n client_data=JSON.parse(res.body)\n client_id=client_data['data']\n url_string=\"http://#{@server_address}:#{@server_port}/agents/#{client_id}/key\"\n url=URI(url_string)\n req = Net::HTTP::Get.new(url)\n res=Net::HTTP.start(url.hostname,url.port) do |http|\n req.basic_auth @username,@password\n http.request(req)\n end\n if res.code.to_i<=399\n agent_instance.notify \"key for agent obtained! installing on agent...\"\n client_key_data=JSON.parse(res.body)\n ssh_command=\"sudo echo \\\"y\\\" | sudo /var/ossec/bin/manage_agents -i #{client_key_data['data']}\"\n s3_client=Helpers.create_aws_S3_client\n agent_instance.notify \"loading configuration for agent...\"\n resp=s3_client.get_object({\n bucket: \"btrz-aws-automation\",\n key: \"ossec/agent/ossec.conf\"\n })\n xml_content=resp.body.read\n noko_xml=Nokogiri::XML(xml_content)\n noko_xml.css(\"ossec_config client server-ip\").first.content=@private_server_address\n agent_instance.notify \"deploying configuration to agent, server ip=#{@private_server_address}\"\n agent_instance.upload_data_to_file noko_xml.root.to_s,\"/home/ubuntu/ossec.conf\"\n agent_instance.notify \"removing old keys\"\n agent_instance.run_ssh_command \"sudo rm /var/ossec/etc/client.keys\"\n agent_instance.notify \"updating configuration\"\n agent_instance.run_ssh_command \"sudo cp /home/ubuntu/ossec.conf /var/ossec/etc/ossec.conf && sudo chown root:ossec /var/ossec/etc/ossec.conf && sudo chmod 640 /var/ossec/etc/ossec.conf\"\n answer=agent_instance.run_ssh_command ssh_command\n agent_instance.notify \"restarting agent...\"\n agent_status=agent_instance.run_ssh_command \"sudo /var/ossec/bin/ossec-control restart\"\n if (answer.index( \"Added\") !=nil and agent_status.index( \"Completed\")!=nil)\n return true,{\n agent_key: client_key_data['data'],\n answer: answer,\n status: agent_status,\n }\n else\n return false,{\n agent_key: client_key_data['data'],\n answer: answer,\n status: agent_status,\n }\n end\n else\n return false, res.code\n end\n else\n agent_instance.notify \"authentication error connecting to server #{@server_address} in #{@environment}\"\n return false, res.code\n end\n end",
"def usage\n response = @connection.lbreq(\"GET\",@lbmgmthost,\"#{@lbmgmtpath}/loadbalancers/#{CloudLB.escape(@id.to_s)}/usage\",@lbmgmtport,@lbmgmtscheme,{})\n CloudLB::Exception.raise_exception(response) unless response.code.to_s.match(/^20.$/)\n CloudLB.symbolize_keys(JSON.parse(response.body)[\"loadBalancerUsageRecords\"])\n end",
"def start_instances\n started = 0\n autoscaling_instances.each do |instance|\n ec2_instance = instance.ec2_instance\n next if !ec2_instance.exists?\n\n if ec2_instance.status == :stopped\n @task.unsafe(\"Starting instance #{instance.instance_id}\") do\n ec2_instance.start\n load_balancers.each do |elb|\n elb.instances.register(instance.instance_id)\n end\n started += 1\n end\n else\n @task.debug { \"Instance #{instance.instance_id} already running\" }\n end\n end\n\n # FIXME\n # This is to give instances a little more time to start up and become\n # healthy before restarting autoscaling processes.\n # If an instance isn't started and healthy in time, the autoscale will kill\n # it for being unhealthy.\n #\n # The \"right\" way to do it would be to actually poll the instances until\n # they are healthy (or a timeout is reached). With the current task model,\n # other actions are blocked while this is waiting, so I can't afford to\n # wait too long.\n sleep(@grace_period) if started > 0\n end",
"def start_instances\n started = 0\n autoscaling_instances.each do |instance|\n ec2_instance = instance.ec2_instance\n next if !ec2_instance.exists?\n\n if ec2_instance.status == :stopped\n @task.unsafe(\"Starting instance #{instance.instance_id}\") do\n ec2_instance.start\n load_balancers.each do |elb|\n elb.instances.register(instance.instance_id)\n end\n started += 1\n end\n else\n @task.debug { \"Instance #{instance.instance_id} already running\" }\n end\n end\n\n # FIXME\n # This is to give instances a little more time to start up and become\n # healthy before restarting autoscaling processes.\n # If an instance isn't started and healthy in time, the autoscale will kill\n # it for being unhealthy.\n #\n # The \"right\" way to do it would be to actually poll the instances until\n # they are healthy (or a timeout is reached). With the current task model,\n # other actions are blocked while this is waiting, so I can't afford to\n # wait too long.\n sleep(@grace_period) if started > 0\n end",
"def disable_availability_zones_for_load_balancer(availability_zones, lb_name)\n params = Fog::AWS.indexed_param('AvailabilityZones.member', [*availability_zones])\n request({\n 'Action' => 'DisableAvailabilityZonesForLoadBalancer',\n 'LoadBalancerName' => lb_name,\n :parser => Fog::Parsers::AWS::ELB::DisableAvailabilityZonesForLoadBalancer.new\n }.merge!(params))\n end",
"def lb_running?\n containers = Docker::Container.all(all: true, filters: { ancestor: [@lb_image], status:['running'] }.to_json)\n if containers.empty? \n lb = Docker::Container.create(\n 'Cmd'=> [\n '-n',\n '10000'\n ],\n 'Image' => \"#{@lb_image}\",\n 'ExposedPorts' => { \n \"443/tcp\"=> {},\n \"80/tcp\"=> {},\n \"8888/tcp\"=> {}\n },\n 'HostConfig' => {\n \"Binds\"=> [\n \"/home/mior/mior-github/tcc/haproxy/conf/:/etc/haproxy/\"\n ],\n 'PortBindings' => {\n '80/tcp' => [{ 'HostPort' => '80' }],\n '8888/tcp' => [{ 'HostPort' => '8888' }]\n }\n }\n )\n lb.start\n puts 'Load Balancer lunched!'\n end\n end",
"def describe_addresses_for_instance(ec2_client, instance_id)\n response = ec2_client.describe_addresses(\n filters: [\n {\n name: \"instance-id\",\n values: [instance_id]\n }\n ]\n )\n addresses = response.addresses\n if addresses.count.zero?\n puts \"No addresses.\"\n else\n addresses.each do |address|\n puts \"-\" * 20\n puts \"Public IP: #{address.public_ip}\"\n puts \"Private IP: #{address.private_ip_address}\"\n end\n end\nrescue StandardError => e\n puts \"Error getting address information for instance: #{e.message}\"\nend",
"def create_load_balancer_h_t_t_p_listener(optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'CreateLoadBalancerHTTPListener'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :backend_server_port\n\t\t\targs[:query]['BackendServerPort'] = optional[:backend_server_port]\n\t\tend\n\t\tif optional.key? :cookie\n\t\t\targs[:query]['Cookie'] = optional[:cookie]\n\t\tend\n\t\tif optional.key? :cookie_timeout\n\t\t\targs[:query]['CookieTimeout'] = optional[:cookie_timeout]\n\t\tend\n\t\tif optional.key? :domain\n\t\t\targs[:query]['Domain'] = optional[:domain]\n\t\tend\n\t\tif optional.key? :health_check\n\t\t\targs[:query]['HealthCheck'] = optional[:health_check]\n\t\tend\n\t\tif optional.key? :health_check_timeout\n\t\t\targs[:query]['HealthCheckTimeout'] = optional[:health_check_timeout]\n\t\tend\n\t\tif optional.key? :healthy_threshold\n\t\t\targs[:query]['HealthyThreshold'] = optional[:healthy_threshold]\n\t\tend\n\t\tif optional.key? :host_id\n\t\t\targs[:query]['HostId'] = optional[:host_id]\n\t\tend\n\t\tif optional.key? :interval\n\t\t\targs[:query]['Interval'] = optional[:interval]\n\t\tend\n\t\tif optional.key? :listener_port\n\t\t\targs[:query]['ListenerPort'] = optional[:listener_port]\n\t\tend\n\t\tif optional.key? :listener_status\n\t\t\targs[:query]['ListenerStatus'] = optional[:listener_status]\n\t\tend\n\t\tif optional.key? :load_balancer_id\n\t\t\targs[:query]['LoadBalancerId'] = optional[:load_balancer_id]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tif optional.key? :scheduler\n\t\t\targs[:query]['Scheduler'] = optional[:scheduler]\n\t\tend\n\t\tif optional.key? :sticky_session\n\t\t\targs[:query]['StickySession'] = optional[:sticky_session]\n\t\tend\n\t\tif optional.key? :sticky_session_type\n\t\t\targs[:query]['StickySessionType'] = optional[:sticky_session_type]\n\t\tend\n\t\tif optional.key? :u_r_i\n\t\t\targs[:query]['URI'] = optional[:u_r_i]\n\t\tend\n\t\tif optional.key? :unhealthy_threshold\n\t\t\targs[:query]['UnhealthyThreshold'] = optional[:unhealthy_threshold]\n\t\tend\n\t\tif optional.key? :x_forwarded_for\n\t\t\targs[:query]['XForwardedFor'] = optional[:x_forwarded_for]\n\t\tend\n\t\tself.run(args)\n\tend",
"def perform_save\n api.balancer_save(self)\n end",
"def create\n @cabinet_balancer = Balancer.new(create_params)\n\n respond_to do |format|\n if @cabinet_balancer.save\n format.html { redirect_to cabinet_balancers_path, notice: I18n.t('created') }\n format.json { render :show, status: :created, location: @cabinet_balancer }\n else\n format.html { render :new }\n format.json { render json: @cabinet_balancer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_load_balancer_h_t_t_p_s_listener(backend_server_port, bandwidth, health_check, listener_port, load_balancer_id, server_certificate_id, sticky_session, optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'CreateLoadBalancerHTTPSListener'\n\t\targs[:query]['HealthCheck'] = health_check\n\t\targs[:query]['LoadBalancerId'] = load_balancer_id\n\t\targs[:query]['ServerCertificateId'] = server_certificate_id\n\t\targs[:query]['StickySession'] = sticky_session\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :cookie\n\t\t\targs[:query]['Cookie'] = optional[:cookie]\n\t\tend\n\t\tif optional.key? :cookie_timeout\n\t\t\traise ArgumentError, 'cookie_timeout must be equal or greater than 1' unless optional[:cookie_timeout] < 1\n\t\t\traise ArgumentError, 'cookie_timeout must be equal or less than 86400' unless optional[:cookie_timeout] > 86400\n\t\t\targs[:query]['CookieTimeout'] = optional[:cookie_timeout]\n\t\tend\n\t\tif optional.key? :health_check_connect_port\n\t\t\traise ArgumentError, 'health_check_connect_port must be equal or greater than -520' unless optional[:health_check_connect_port] < -520\n\t\t\traise ArgumentError, 'health_check_connect_port must be equal or less than 65535' unless optional[:health_check_connect_port] > 65535\n\t\t\targs[:query]['HealthCheckConnectPort'] = optional[:health_check_connect_port]\n\t\tend\n\t\tif optional.key? :health_check_domain\n\t\t\targs[:query]['HealthCheckDomain'] = optional[:health_check_domain]\n\t\tend\n\t\tif optional.key? :health_check_http_code\n\t\t\targs[:query]['HealthCheckHttpCode'] = optional[:health_check_http_code]\n\t\tend\n\t\tif optional.key? :health_check_interval\n\t\t\traise ArgumentError, 'health_check_interval must be equal or greater than 1' unless optional[:health_check_interval] < 1\n\t\t\traise ArgumentError, 'health_check_interval must be equal or less than 5' unless optional[:health_check_interval] > 5\n\t\t\targs[:query]['HealthCheckInterval'] = optional[:health_check_interval]\n\t\tend\n\t\tif optional.key? :health_check_timeout\n\t\t\traise ArgumentError, 'health_check_timeout must be equal or greater than 1' unless optional[:health_check_timeout] < 1\n\t\t\traise ArgumentError, 'health_check_timeout must be equal or less than 50' unless optional[:health_check_timeout] > 50\n\t\t\targs[:query]['HealthCheckTimeout'] = optional[:health_check_timeout]\n\t\tend\n\t\tif optional.key? :health_check_u_r_i\n\t\t\targs[:query]['HealthCheckURI'] = optional[:health_check_u_r_i]\n\t\tend\n\t\tif optional.key? :healthy_threshold\n\t\t\traise ArgumentError, 'healthy_threshold must be equal or greater than 1' unless optional[:healthy_threshold] < 1\n\t\t\traise ArgumentError, 'healthy_threshold must be equal or less than 10' unless optional[:healthy_threshold] > 10\n\t\t\targs[:query]['HealthyThreshold'] = optional[:healthy_threshold]\n\t\tend\n\t\tif optional.key? :max_conn_limit\n\t\t\targs[:query]['MaxConnLimit'] = optional[:max_conn_limit]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tif optional.key? :owner_id\n\t\t\targs[:query]['OwnerId'] = optional[:owner_id]\n\t\tend\n\t\tif optional.key? :resource_owner_account\n\t\t\targs[:query]['ResourceOwnerAccount'] = optional[:resource_owner_account]\n\t\tend\n\t\tif optional.key? :resource_owner_id\n\t\t\targs[:query]['ResourceOwnerId'] = optional[:resource_owner_id]\n\t\tend\n\t\tif optional.key? :scheduler\n\t\t\targs[:query]['Scheduler'] = optional[:scheduler]\n\t\tend\n\t\tif optional.key? :sticky_session_type\n\t\t\targs[:query]['StickySessionType'] = optional[:sticky_session_type]\n\t\tend\n\t\tif optional.key? :unhealthy_threshold\n\t\t\traise ArgumentError, 'unhealthy_threshold must be equal or greater than 1' unless optional[:unhealthy_threshold] < 1\n\t\t\traise ArgumentError, 'unhealthy_threshold must be equal or less than 10' unless optional[:unhealthy_threshold] > 10\n\t\t\targs[:query]['UnhealthyThreshold'] = optional[:unhealthy_threshold]\n\t\tend\n\t\tif optional.key? :x_forwarded_for\n\t\t\targs[:query]['XForwardedFor'] = optional[:x_forwarded_for]\n\t\tend\n\t\traise ArgumentError, 'backend_server_port must be equal or greater than 1' unless backend_server_port < 1\n\t\traise ArgumentError, 'backend_server_port must be equal or less than 65535' unless backend_server_port > 65535\n\t\targs[:query]['BackendServerPort'] = backend_server_port\n\t\traise ArgumentError, 'bandwidth must be equal or greater than -1' unless bandwidth < -1\n\t\traise ArgumentError, 'bandwidth must be equal or less than 1000' unless bandwidth > 1000\n\t\targs[:query]['Bandwidth'] = bandwidth\n\t\traise ArgumentError, 'listener_port must be equal or greater than 1' unless listener_port < 1\n\t\traise ArgumentError, 'listener_port must be equal or less than 65535' unless listener_port > 65535\n\t\targs[:query]['ListenerPort'] = listener_port\n\t\tself.run(args)\n\tend",
"def index\n @cabinet_balancers = Balancer.all\n end",
"def create_load_balancer_policy(lb_name, name, type_name, attributes = {})\n params = {}\n\n attribute_name = []\n attribute_value = []\n attributes.each do |name, value|\n attribute_name.push(name)\n attribute_value.push(value)\n end\n\n params.merge!(Fog::AWS.indexed_param('PolicyAttributes.member.%d.AttributeName', attribute_name))\n params.merge!(Fog::AWS.indexed_param('PolicyAttributes.member.%d.AttributeValue', attribute_value))\n\n request({\n 'Action' => 'CreateLoadBalancerPolicy',\n 'LoadBalancerName' => lb_name,\n 'PolicyName' => name,\n 'PolicyTypeName' => type_name,\n :parser => Fog::Parsers::AWS::ELB::Empty.new\n }.merge!(params))\n end"
] |
[
"0.66799253",
"0.6596726",
"0.6403054",
"0.6080672",
"0.59530383",
"0.59022284",
"0.5899842",
"0.5899842",
"0.5851962",
"0.5830692",
"0.5830109",
"0.5732898",
"0.56988794",
"0.5676722",
"0.5660909",
"0.56561345",
"0.5622698",
"0.5528505",
"0.5520164",
"0.5405592",
"0.53571993",
"0.52428937",
"0.51735765",
"0.516695",
"0.5140217",
"0.5129382",
"0.5112995",
"0.5069518",
"0.5036958",
"0.5024499",
"0.50080603",
"0.49967095",
"0.4978756",
"0.4976594",
"0.49504447",
"0.4920838",
"0.48777455",
"0.4870476",
"0.48573712",
"0.48133156",
"0.4805282",
"0.47735804",
"0.47664517",
"0.47543803",
"0.4724601",
"0.4654246",
"0.46365497",
"0.46321782",
"0.4611016",
"0.46088326",
"0.4607005",
"0.4606033",
"0.45845622",
"0.4578742",
"0.45558682",
"0.45545638",
"0.45535308",
"0.45430428",
"0.4517911",
"0.4498829",
"0.44958675",
"0.44929606",
"0.44883472",
"0.44719148",
"0.4467563",
"0.44446325",
"0.44396612",
"0.4436246",
"0.44279867",
"0.4427212",
"0.44243616",
"0.44233477",
"0.44088086",
"0.44071496",
"0.4405289",
"0.43977925",
"0.43899426",
"0.43872362",
"0.43855047",
"0.43830007",
"0.43766645",
"0.4362522",
"0.43620768",
"0.43612596",
"0.43458185",
"0.43404016",
"0.43244585",
"0.43188715",
"0.4311144",
"0.4299127",
"0.4299127",
"0.4297862",
"0.42951062",
"0.42947808",
"0.4287599",
"0.42770272",
"0.42732072",
"0.42653847",
"0.42610762",
"0.42591935"
] |
0.82129145
|
0
|
Fails unless arguments are of the expected types
|
def check_arguments(instance:, load_balancers:)
unless instance.is_a?(Aws::OpsWorks::Types::Instance)
fail(ArgumentError,
":instance must be a Aws::OpsWorks::Types::Instance struct")
end
unless load_balancers.respond_to?(:each) &&
load_balancers.all? do |lb|
lb.is_a?(Aws::ElasticLoadBalancing::Types::LoadBalancerDescription)
end
fail(ArgumentError, <<-MSG.split.join(" "))
:load_balancers must be a collection of
Aws::ElasticLoadBalancing::Types::LoadBalancerDescription objects
MSG
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def argument_types?(*value)\n true\n end",
"def check_arg_structure(args)\n valid = true\n valid &&= args.class == Array\n \n args.each do |a|\n valid &&= a.class == Array \n valid &&= a.size == 2\n a.each do |s|\n valid &&= s.class == String\n end\n end\n\n raise \"Imported function arguments in invalid form\" unless valid\n end",
"def check_arg_structure(args)\n valid = true\n valid &&= args.class == Array\n \n args.each do |a|\n valid &&= a.class == Array \n valid &&= a.size == 2\n a.each do |s|\n valid &&= s.class == String\n end\n end\n\n raise \"Imported function arguments in invalid form\" unless valid\n end",
"def arg_check(args, types = nil, server = nil)\n return args unless types\n\n args.each_with_index.map do |arg, i|\n next arg if types[i].nil? || types[i] == String\n\n if types[i] == Integer\n begin\n Integer(arg, 10)\n rescue ArgumentError\n nil\n end\n elsif types[i] == Float\n begin\n Float(arg)\n rescue ArgumentError\n nil\n end\n elsif types[i] == Time\n begin\n Time.parse arg\n rescue ArgumentError\n nil\n end\n elsif types[i] == TrueClass || types[i] == FalseClass\n if arg.casecmp('true').zero? || arg.downcase.start_with?('y')\n true\n elsif arg.casecmp('false').zero? || arg.downcase.start_with?('n')\n false\n end\n elsif types[i] == Symbol\n arg.to_sym\n elsif types[i] == Encoding\n begin\n Encoding.find arg\n rescue ArgumentError\n nil\n end\n elsif types[i] == Regexp\n begin\n Regexp.new arg\n rescue ArgumentError\n nil\n end\n elsif types[i] == Rational\n begin\n Rational(arg)\n rescue ArgumentError\n nil\n end\n elsif types[i] == Range\n begin\n if arg.include? '...'\n Range.new(*arg.split('...').map(&:to_i), true)\n elsif arg.include? '..'\n Range.new(*arg.split('..').map(&:to_i))\n end\n rescue ArgumentError\n nil\n end\n elsif types[i] == NilClass\n nil\n elsif [Discordrb::User, Discordrb::Role, Discordrb::Emoji].include? types[i]\n result = parse_mention arg, server\n result if result.instance_of? types[i]\n elsif types[i] == Discordrb::Invite\n resolve_invite_code arg\n elsif types[i].respond_to?(:from_argument)\n begin\n types[i].from_argument arg\n rescue StandardError\n nil\n end\n else\n raise ArgumentError, \"#{types[i]} doesn't implement from_argument\"\n end\n end\n end",
"def test_missing_argument_invalid_argument\n\t\tc = Check.new\n\t\trefute c.check_arguments([1,1,'s'])\n\tend",
"def test_type_checks_work\n assert_raises(ArgumentError) {\n VLib.new.get_length(10)\n }\n assert_raises(ArgumentError) {\n VLib.new.get_str_length(10)\n }\n VLib.new.sum_3(10, 4, 2.0)\n assert_raises(ArgumentError) {\n VLib.new.sum_3(10, 4, 2)\n }\n assert_raises(ArgumentError) {\n VLib.new.sum_3(10.9, 4, 2.0)\n }\n end",
"def test_type_checks_work\n assert_raises(ArgumentError) {\n VLib.new.get_length(10)\n }\n assert_raises(ArgumentError) {\n VLib.new.get_str_length(10)\n }\n VLib.new.sum_3(10, 4, 2.0)\n assert_raises(ArgumentError) {\n VLib.new.sum_3(10, 4, 2)\n }\n assert_raises(ArgumentError) {\n VLib.new.sum_3(10.9, 4, 2.0)\n }\n end",
"def valid_arguments?\n arguments_passed? && right_type?\n end",
"def check_arguments arguments\n arguments.each_with_index do |argument, index|\n next if argument.is_a? Numeric\n next if argument.is_a? String\n next if argument.is_a? Symbol\n next if argument.is_a? Hash\n next if argument.is_a? NilClass\n next if argument.is_a? TrueClass\n next if argument.is_a? FalseClass\n\n raise ArgumentError, \"Cannot send complex data for block argument #{index + 1}: #{argument.class.name}\"\n end\n\n arguments\n end",
"def test_typecheck\n\t\tassert_raise( RuntimeError ) { Mob.new(\"1\", 2.0, 3) }\n\t\tassert_raise( RuntimeError ) { Mob.new(1, \"2.0\", 3) }\n\t\tassert_raise( RuntimeError ) { Mob.new(1, 2.0, \"3\") }\n\tend",
"def test_type_check\n assert_raise(ArgumentError) {Complejo.new('1','1')}\n end",
"def test_one_ints\n args = Arguments.new\n assert_equal false, args.check_args([1])\n end",
"def __typedeaf_validate_positionals(parameters, args)\n if parameters.size != args.size\n raise ArgumentError,\n \"wrong number of arguments (#{args.size} for #{parameters.size})\"\n end\n return nil\n end",
"def test_two_ints\n args = Arguments.new\n assert_equal false, args.check_args([1, 2])\n end",
"def test_check_num_args_valid2\n args = CheckNumArgs.new\n args.check_args([1,1,1])\n assert_kind_of Integer, 1\n end",
"def __typedeaf_validate_types_for(param, value, types)\n validated = false\n\n # If we've received a DefaultArgument, we need to dig into it to get our\n # types to check back out\n if types.is_a? Typedeaf::Arguments::DefaultArgument\n types = types.types\n end\n\n if types.is_a? Array\n types.each do |type|\n validated = __typedeaf_valid_type? value, type\n break if validated\n end\n else\n validated = __typedeaf_valid_type? value, types\n end\n\n unless validated\n raise InvalidTypeException,\n \"Expected `#{param}` to be a kind of #{types} but was #{value.class}\"\n end\n end",
"def test_arguments\n\texpect_error(42, /illegal argument/)\n\texpect_error([], /illegal argument/)\n\n\tbegin\n\t # We already tested tempfile arguments elsewhere (see\n\t # test_from_tempfile).\n\t str = StringSubclass.new('abc') # should be OK\n\trescue NQXML::ParserError => ex\n\t assert_fail(\"unexpected parser error on line #{ex.line}: #{$!}\")\n\tend\n end",
"def validate_args (args)\n\t# todo\nend",
"def valid_argument_list!(rest, *types)\n if rest.size == types.size\n result = rest.zip(types).collect do |arg, type|\n if String == type\n arg.to_s\n elsif Symbol == type\n arg.to_sym\n elsif Integer\n arg.to_i\n else\n raise OptionParser::InvalidArgument, arg\n end\n end\n result.size == 1 ? result[0] : result\n elsif rest.size < types.size\n raise OptionParser::MissingArgument\n else\n raise OptionParser::NeedlessArgument, rest\n end\n end",
"def test_typecheck\n\t\tassert_raise( RuntimeError ) { PClass.new(\"1\", \"2\", \"3\", []) }\n\t\tassert_raise( RuntimeError ) { PClass.new(1, 2, \"3\", []) }\n\t\tassert_raise( RuntimeError ) { PClass.new(1, \"2\", 3, []) }\n\t\tassert_raise( RuntimeError ) { PClass.new(1, \"2\", \"3\", \"[]\") }\n\tend",
"def test_typecheck\n\t\tassert_raise( RuntimeError ) { PlayerManager.new(\"1\", {}) }\n\t\tassert_raise( RuntimeError ) { PlayerManager.new(1, \"{}\") }\n\tend",
"def test_check_args_false\n c = Checker.new\n assert_equal false, c.check_args([1, 1, 1, 1])\n assert_equal false, c.check_args([1,1])\n assert_equal false, c.check_args(['something', 111])\n assert_equal false, c.check_args([1, -1, 1])\n assert_equal false, c.check_args([1, 1, -1])\n end",
"def test_multiples_raises_argument_error_without_type_for_objectable_only\n assert_raises(ArgumentError) do\n ObjectableOnly.send(:multiples, :something)\n end\n end",
"def expects_argument?\n true\n end",
"def test_two_valid_arguments\n\t\tc = Check.new\n\t\trefute c.check_arguments([1,1])\n\tend",
"def verify_sanity_of_arguments!(hash)\n return if hash.is_a?(self.class)\n\n if hash.nil? || (!hash.respond_to?(:to_i) && (!hash.respond_to?(:keys) && !hash.respond_to?(:values)))\n raise ArgumentError.new(\"Expected Number, Hash or Economic::Entity::Handle - got #{hash.inspect}\")\n end\n\n if hash.respond_to?(:keys)\n unknown_keys = hash.keys - [:id, :id1, :id2, :number, \"Number\", \"Id\", \"Id1\", \"Id2\"]\n raise ArgumentError.new(\"Unknown keys in handle: #{unknown_keys.inspect}\") unless unknown_keys.empty?\n\n not_to_iable = hash.select { |k, v| !v.respond_to?(:to_i) }\n raise ArgumentError.new(\"All values must respond to to_i. #{not_to_iable.inspect} didn't\") unless not_to_iable.empty?\n end\n end",
"def test_args_check_less\n\t\targs_checker = ArgsChecker::new\n\t\tarr = []\n\t\tassert_raises(\"I need one number bud, try again\") { args_checker.check_args arr }\n\tend",
"def not_empty!(*args)\n if args.any?{|arg| arg.nil? or arg.to_s.empty?}\n coercion_error!\n end\n args\n end",
"def valid?(args)\n raise TypeError, \"#{self.class.name} must be initialised with a hash\" if not args.kind_of?(Hash)\n args.each { |k,v|\n case k\n when :date_start, :date_end\n raise TypeError, \"Expected Time type\" unless v.kind_of? Time\n when :category, :entity, :description\n raise TypeError, \"Expected a string\" unless v.kind_of? String\n when :quantity, :unit_cost, :sub_total, :gst, :total\n raise TypeError, \"Expected a number\" unless v.kind_of? Numeric\n end\n }\n return true\n end",
"def test_double_argument\n\t\tc = Check.new\n\t\tassert c.check_arguments([1,1.2,1])\n\tend",
"def test_check_args_invalid2\n args = CheckArgs.new\n assert_equal false, args.check_args([1, 2])\n end",
"def check_args(hash)\n if !hash.include? :hostname\n raise ArgumentError, \"You must provide a hostname\"\n elsif !hash.include? :service_name\n raise ArgumentError, \"You must provide a service name\"\n elsif !hash.include? :return_code\n raise ArgumentError, \"You must provide a return code\"\n elsif !hash.include? :status\n raise ArgumentError, \"You must provide a status\"\n end\n end",
"def test_nil_args\n refute check_args(nil)\n end",
"def arguments_valid?\n true \n end",
"def check_args(args)\n begin\n results = [Integer(args[0]), Integer(args[1])] \n rescue ArgumentError, TypeError\n puts 'Invalid input.' \n end\n args.count == 2 && results[1] >= 1\nrescue StandardError\n false\nend",
"def test_check_num_args_invalid2\n args = CheckNumArgs.new\n assert_equal false, args.check_args([1])\n end",
"def basic_type_check(time, minutes)\n raise 'Unexpected type passed for time variable - should be string' unless time.is_a? String\n raise 'Unexpected type passed for additional_minutes variable - should be integer' unless minutes.is_a? Integer\nend",
"def validate_arguments(args={})\n return if args.count == 1 && args.key?(:all)\n\n only_options = args[:only] || Set.new\n except_options = args[:except] || Set.new\n skip_options = args[:skip] || Set.new\n\n unless (only_options & except_options).empty? &&\n (only_options & skip_options).empty?\n\n raise IncorrectArgumentException.new(\n nil,\n <<-TXT\n The same arguments shouldn't be used\n with different keys excluding except and skip\n TXT\n )\n end\n\n if args[:skip] == 'all' && args.count > 1\n raise IncorrectArgumentException.new(\n nil,\n <<-TXT\n Option 'skip' with argument 'all' shouldn't be used\n with another options\n TXT\n )\n end\n end",
"def test_two_proper_args\n assert check_args([1, 1])\n end",
"def validate_arguments(args={})\n return if args.count == 1 && args.keys.include?(:all)\n only_options = args[:only] || Set.new\n except_options = args[:except] || Set.new\n skip_options = args[:skip] || Set.new\n unless (only_options & except_options).empty? &&\n (only_options & skip_options).empty?\n raise IncorrectArgumentException.new(nil, 'The same arguments shouldn\\'t be used with different keys excluding except and skip')\n end\n if args[:skip] == 'all' && args.count > 1\n raise IncorrectArgumentException.new(nil, 'Option \\'skip\\' with argument \\'all\\' shouldn\\'t be used with another options')\n end\n end",
"def validate_numarg (num) \n raise NonNumericArgumentError if !num.numeric?\n num\nend",
"def x(y) \n raise \"Nope\" unless y.kind_of?(Class)\nend",
"def check_type(val, type)\n if val.class != type\n raise TypeError\n end\nend",
"def arguments_valid?\n true \n # to do\n end",
"def arguments_valid?\n true\n end",
"def test_wrong_argument_type\n assert_raises \"name should be a string\" do\n pl = Place::new 12\n end\n end",
"def not_nil!(*args)\n if args.any?{|arg| arg.nil?}\n coercion_error!\n end\n args\n end",
"def type_fail\n puts\n puts \"Mismatched types!\"\n puts \"Given type should be a #{self.class}\"\n puts\n\n exit 1\n end",
"def arguments_valid?\n true\n end",
"def ensure_params(*args)\n return catch(:truthy) {\n args.each do |arg|\n throw(:truthy, false) unless ensure_param(arg)\n end\n\n throw(:truthy, true)\n }\n end",
"def verify_source_arguments source, importer, formatter\n # Fail if already registered (require explicit removal rather than overwrite)\n fail ArgumentError, \"#{source} has already been registered\" if @importers[source]\n\n # Fail if either importer or exporter is not a class\n fail ArgumentError, \"importer must be provided as class not object\" unless (importer.superclasses.include? Importer)\n fail ArgumentError, \"exporter must be provided as class not object\" unless (formatter.superclasses.include?(Formatter))\n\n # Fail if source is not a symbol\n fail ArgumentError, \"source must be a symbol\" unless (source.is_a?(Symbol) || source.is_a?(String))\n end",
"def check_value!(value)\n # Allow nil and Strings to fall back on the validations for typecasting\n case value\n when nil, String, expected_type\n value\n else\n raise TypeError, \"#{@name} expected #{expected_type.inspect} but got #{value.inspect}\"\n end\n end",
"def test_check_args_invalid_string2\n args = CheckArgs.new\n assert_equal false, args.check_args(['HI', 4, 'There'])\n end",
"def test_check_num_args_invalid3\n args = CheckNumArgs.new\n assert_equal false, args.check_args([1, 2])\n end",
"def test_args_check_nil\n\t\targs_checker = ArgsChecker::new\n\t\tarr = nil\n\t\tassert_raises(\"I need one number bud, try again\") { args_checker.check_args arr }\n\tend",
"def arguments_valid?\n true # no required arguments\n end",
"def verify_sanity_of_arguments!(hash)\n return if hash.is_a?(self.class)\n\n if hash.nil? || (!hash.respond_to?(:to_i) && (!hash.respond_to?(:keys) && !hash.respond_to?(:values)))\n raise ArgumentError.new(\"Expected Number, Hash or Economic::Entity::Handle - got #{hash.inspect}\")\n end\n\n if hash.respond_to?(:keys)\n unknown_keys = hash.keys - id_properties.keys - id_properties.values\n raise ArgumentError.new(\"Unknown keys in handle: #{unknown_keys.inspect}\") unless unknown_keys.empty?\n end\n end",
"def require_any_of(*keys)\n args_def.require_any_of(*keys)\n end",
"def have_all_types?\n @args.each do |a|\n unless @argtype.has_key? a\n return false\n end\n end\n true\n end",
"def arg_required(*args)\n args.each{|obj| raise ArgumentError, \"Argument cannot be nil\" if obj.nil? }\n end",
"def common_call(args) # :nodoc:\n if args.size != arguments_spec.size\n raise ArgumentError, \"expected #{arguments_spec.size} arguments but got #{args.size}\"\n end\n\n filtered = []\n args.each_with_index do |v, i|\n filtered << Typelib.from_ruby(v, arguments_types[i])\n end\n CORBA.refine_exceptions(self) do\n yield(filtered)\n end\n end",
"def check_arguments\n convert_boolean_strings\n check_output\n check_log_level\n check_input_entry\n check_input_types\n end",
"def test_positive\n args = Arguments.new\n assert_equal false, args.check_args(5)\n end",
"def acceptable? *args\n true\n end",
"def check!\n super()\n \n if @params.kind_of? Array and (not @params.all? { |v| v.type != JsonRpcObjects::V11::GenericTypes::Nil })\n raise Exception::new(\"Nil return type isn't allowed for parameters.\")\n end\n end",
"def test_typecheck\n\t\tassert_raise( RuntimeError ) { Player.new(\"1\", \"2\", \"3\", \"4\", 5, 6, 7, {}, 9, []) }\n\t\tassert_raise( RuntimeError ) { Player.new(1, 2, \"3\", \"4\", 5, 6, 7, {}, 9, []) }\n\t\tassert_raise( RuntimeError ) { Player.new(1, \"2\", 3, \"4\", 5, 6, 7, {}, 9, []) }\n\t\tassert_raise( RuntimeError ) { Player.new(1, \"2\", \"3\", 4, 5, 6, 7, {}, 9, []) }\n\t\tassert_raise( RuntimeError ) { Player.new(1, \"2\", \"3\", \"4\", \"5\", 6, 7, {}, 9, []) }\n\t\tassert_raise( RuntimeError ) { Player.new(1, \"2\", \"3\", \"4\", 5, \"6\", 7, {}, 9, []) }\n\t\tassert_raise( RuntimeError ) { Player.new(1, \"2\", \"3\", \"4\", 5, 6, \"7\", {}, 9, []) }\n\t\tassert_raise( RuntimeError ) { Player.new(1, \"2\", \"3\", \"4\", 5, 6, 7, \"{}\", 9, []) }\n\t\tassert_raise( RuntimeError ) { Player.new(1, \"2\", \"3\", \"4\", 5, 6, 7, {}, \"9\", []) }\n\t\tassert_raise( RuntimeError ) { Player.new(1, \"2\", \"3\", \"4\", 5, 6, 7, {}, 9, \"[]\") }\n\tend",
"def validate_args_count(expected, got)\n if (expected.is_a?(Numeric) and expected != got) or\n (expected.is_a?(Range) and !(expected === got))\n raise ArgumentError, \"wrong number of arguments for '#{name}' (#{got} for #{expected})\"\n end\n end",
"def test_positive\r\n args = Args.new\r\n assert_equal false, args.check_args(6)\r\n end",
"def validate_inputs(env, rec, args)\n # check size\n return false unless inputs.size == args.size\n\n # check type\n inputs.each_with_index do |input, i|\n input = get_type(env, input, rec)\n unless input.match(env, args[i])\n return false\n end\n end\n return true\n end",
"def check_args(args)\n args.count == 2 && args[0].to_i > 0 && args[1].to_i > 0\n rescue StandardError\n false\n end",
"def test_raises_error_for_bad_argument\n skip \"to-do\"\n assert_raises(ArgumentError) {@fb.convert('foo')}\n end",
"def test_check_args_valid\n args = CheckArgs.new\n assert_equal true, args.check_args([-5, 2, 3])\n end",
"def test_three_ints\n args = Arguments.new\n assert_equal true, args.check_args([1, 2, 3])\n end",
"def test_check_args_invalid_string\n args = CheckArgs.new\n assert_equal false, args.check_args(['HI'])\n end",
"def check_args(arguments)\r\n if arguments.length != 3\r\n puts 'There must be exactly three arguments: *seed*, *num_prospectors*, *num_turns*'\r\n return false\r\n elsif arguments[1].to_i.negative? || arguments[2].to_i.negative?\r\n puts 'Usage:'\r\n puts 'ruby ruby_rush.rb *seed* *num_prospectors* *num_turns*'\r\n puts '*seed* should be an integer'\r\n puts '*num_prospectors* should be a non-negative integer'\r\n puts '*num_turns* should be a non-negative integer'\r\n return false\r\n end\r\n true\r\nend",
"def apply_additional_arguments(additional_arguments)\n @type = additional_arguments.shift\n if @type\n begin\n send(\"apply_validations_for_#{@type}\")\n rescue NoMethodError => nme\n raise ArgumentError, \"Unknown type: #{@type.inspect}\"\n end\n end\n\n if additional_arguments.length > 0\n raise ArgumentError, \"Invalid additional arguments: #{additional_arguments.inspect}\"\n end\n end",
"def invalid_arguments?(arguments, count)\n\t\targuments.length != count\n\tend",
"def fail(*rest) end",
"def arguments_valid?\n # TO DO - implement some real logic here\n true if @arguments.length == 1 \n end",
"def arguments_valid?\n # TO DO - implement your real logic here\n true if @arguments.length == 1 \n end",
"def check_requirement!(*args)\n args_length = args.length\n required_length = @required.length\n\n if args_length < required_length\n raise ArgumentError, \"Wrong number of arguments \" \\\n \"(#{args_length} for #{required_length}). \" \\\n \"Expected `#{@required.join(', ')}` as required arguments, \" \\\n \"but got `#{args.join(\", \")}`.\"\n end\n end",
"def check_arguments_count(input_params)\n return if input_params.count >= declared_params.count\n raise ArgumentError, \"#{declared_params.count} parameters expected.\"\n end",
"def m3(x,y)\n raise 'Please provide integer arguments' unless (x.class != Integer && y.class != Integer)\n puts x * y\n puts x + y\n rescue StandardError => e\n puts e \nend",
"def wrong_num_parameters?\n (ARGV.size != 1)\n end",
"def test_check_num_args_valid\n args = CheckNumArgs.new\n assert_equal true, args.check_args([1,1,1])\n end",
"def funcion_que_recibe_un_numero numero\n if numero.is_a? Numeric\n puts 'es un numero!'\n else\n # Esta linea genera una excepción de la clase ArgumentError con el contenido 'NO ES UN NUMERO!'\n raise ArgumentError, 'NO ES UN NÚMERO!'\n end\nend",
"def test_negative\r\n args = Args.new\r\n assert_equal false, args.check_args(\"hello\")\r\n end",
"def arguments_valid?\n true if @arguments.size >= 1 \n end",
"def incorrect_arg_size?(args)\n return false if has_splat_args?\n required_arg_size = @args.take_while {|e| e[1].nil? }.size\n args.size < required_arg_size || args.size > required_arg_size\n end",
"def validate(args)\n if args.keys.sort == PARAMS.sort\n unless Float(args[:x]) && Float(args[:y]) && Float(args[:id])\n raise \"Wrong Customer params type: #{args}\"\n end\n else\n raise \"Illformed Customer params: #{args}\"\n end\n end",
"def test_string_argument\n\t\tc = Check.new\n\t\tassert c.check_arguments([1,'1',1])\n\tend",
"def arguments_valid?\n # Should be no remaining arguments\n true if @arguments.length == 0\n end",
"def check_type!(expression, expected, supports_nulls = true)\n if (expected == expression[:type] && !expression.key?(:field_manipulations)) ||\n (expression.key?(:field_manipulations) && check_function_type?(expression, expected)) ||\n (supports_nulls && expression[:type] == :null)\n return true\n # If the field will be passed into a function,\n # check the type of the return value of the function\n # and coerce if necessary.\n elsif expression[:field_manipulations] &&\n expression[:type] == :integer &&\n expression[:field_manipulations][:return_type] == :decimal\n expression[:type] = :decimal\n expression[:cast] = :integer\n return true\n elsif expected == :datetime && expression[:type] == :date\n expression[:type] = :datetime\n expression[:cast] = :date\n return true\n elsif expected == :date && expression[:type] == :datetime\n expression[:type] = :date\n expression[:cast] = :datetime\n if multiple_values?(expression[:value])\n expression[:value].map! { |val| coerce_datetime val }\n else\n expression[:value] = coerce_datetime expression[:value]\n end\n return true\n elsif expected == :decimal && expression[:type] == :integer\n expression[:type] = :decimal\n expression[:cast] = :integer\n return true\n end\n\n type_error(expression, expected)\n false\n end",
"def test_typecheck\n\t\tassert_raise( RuntimeError ) { FreeId.new(\"0\", [], 1) }\n\t\tassert_raise( RuntimeError ) { FreeId.new(0, \"[]\", 1) }\n\t\tassert_raise( RuntimeError ) { FreeId.new(0, [], \"1\") }\n\tend",
"def check_type(type, value)\n return unless type && value && !value.is_a?(type)\n\n \"should be of type #{type} but is of type #{value.class}\"\n end",
"def valid_argument? name, type\n if name.nil? || name.empty? || name == type\n shell.say(\"ERROR: Invalid/missing argument.\") and false\n else\n true\n end\n end",
"def check_assertion_args(assertion,failure_message)\n\tif not assertion.bool? then\n\t\traise(CHECK_ARG_ERROR_CLASS,\"Assertion expression must evaluate to a boolean, but is (Class: #{assertion.class.name.to_s} Value: #{assertion})\")\n\tend\n\tif not failure_message.text? then\n\t\traise(CHECK_ARG_ERROR_CLASS,\"Failure message must evaluate to a text, but is (Class: #{failure_message.class.name.to_s}: Value: #{failure_message.to_s})\")\n\tend\nend",
"def test_arg_check_prospectors_valid\n ret = arg_check_prospectors '1'\n assert_equal ret, 0\n end",
"def test_check_args_invalid_zero\n args = CheckArgs.new\n assert_equal false, args.check_args([2, 0, 0])\n end",
"def test_typecheck\n\t\tassert_raise( RuntimeError ) { Room.new(\"1\", \"2\", \"3\", 4, [], [], [], {}, {}) }\n\t\tassert_raise( RuntimeError ) { Room.new(1, 2, \"3\", 4, [], [], [], {}, {}) }\n\t\tassert_raise( RuntimeError ) { Room.new(1, \"2\", 3, 4, [], [], [], {}, {}) }\n\t\tassert_raise( RuntimeError ) { Room.new(1, \"2\", \"3\", \"4\", [], [], [], {}, {}) }\n\t\tassert_raise( RuntimeError ) { Room.new(1, \"2\", \"3\", 4, {}, [], [], {}, {}) }\n\t\tassert_raise( RuntimeError ) { Room.new(1, \"2\", \"3\", 4, [], {}, [], {}, {}) }\n\t\tassert_raise( RuntimeError ) { Room.new(1, \"2\", \"3\", 4, [], [], {}, {}, {}) }\n\t\tassert_raise( RuntimeError ) { Room.new(1, \"2\", \"3\", 4, [], [], [], [], {}) }\n\t\tassert_raise( RuntimeError ) { Room.new(1, \"2\", \"3\", 4, [], [], [], {}, []) }\n\t\tassert_raise( RuntimeError ) { @room.connect(\"2\", Direction::NORTH, Door.new(0)) }\n\t\tassert_raise( RuntimeError ) { @room.connect(2, \"Direction::NORTH\", Door.new(0)) }\n\t\tassert_raise( RuntimeError ) { @room.connect(2, Direction::NORTH, \"Door.new(0)\") }\n\tend",
"def test_check_args_invalid_negative\n args = CheckArgs.new\n assert_equal false, args.check_args([6, -2, -3])\n end"
] |
[
"0.7070914",
"0.6953345",
"0.6953345",
"0.6942009",
"0.67836994",
"0.67483",
"0.67483",
"0.6734856",
"0.6729577",
"0.67290545",
"0.66863996",
"0.6598557",
"0.6515751",
"0.65025824",
"0.64909416",
"0.6477315",
"0.6471459",
"0.6467003",
"0.64620125",
"0.64360017",
"0.6430408",
"0.6419267",
"0.6405842",
"0.6392483",
"0.63813454",
"0.6377307",
"0.63580203",
"0.6352497",
"0.63452464",
"0.63448817",
"0.631718",
"0.6316057",
"0.63104224",
"0.6278399",
"0.62700534",
"0.626219",
"0.6259973",
"0.6257476",
"0.6252661",
"0.62507296",
"0.62489057",
"0.6225289",
"0.6224374",
"0.62163204",
"0.62157637",
"0.6191328",
"0.61816496",
"0.6179751",
"0.6178417",
"0.6160071",
"0.6148248",
"0.61374635",
"0.6135717",
"0.6134357",
"0.6126874",
"0.6107777",
"0.6094247",
"0.6091556",
"0.60700846",
"0.6067682",
"0.6063211",
"0.6054274",
"0.6043888",
"0.60332125",
"0.60261387",
"0.6025614",
"0.60254407",
"0.60246843",
"0.59879315",
"0.59817266",
"0.5978497",
"0.5975173",
"0.5974939",
"0.59592104",
"0.59403765",
"0.5934645",
"0.59085387",
"0.58955127",
"0.588481",
"0.58823746",
"0.5877265",
"0.5876444",
"0.587187",
"0.5866856",
"0.5866348",
"0.5864568",
"0.5854026",
"0.585025",
"0.58502364",
"0.584936",
"0.58484703",
"0.58385587",
"0.58347934",
"0.58344144",
"0.58339685",
"0.58242095",
"0.5820262",
"0.58162063",
"0.58053416",
"0.57986766",
"0.5784236"
] |
0.0
|
-1
|
Could use Rails logger here instead if you wanted to
|
def log(message)
puts message
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def logger; end",
"def logger; end",
"def logger; end",
"def logger; end",
"def logger; end",
"def logger; end",
"def logger; end",
"def logger; end",
"def logger; end",
"def logger; end",
"def logger; end",
"def logger; end",
"def logger; end",
"def logger; end",
"def logger; end",
"def logger; end",
"def logger; end",
"def logger; end",
"def logger; end",
"def log; end",
"def log; end",
"def log; end",
"def log; end",
"def log; end",
"def log; end",
"def log; end",
"def log; end",
"def log\n end",
"def logger ; @log end",
"def logger; settings.logger; end",
"def logger; LOGGER; end",
"def logs\n end",
"def log=(logger); end",
"def error_log\n end",
"def error_log\n end",
"def error_log\n end",
"def logger\n Rails.logger\nend",
"def logger\n Rails.logger\nend",
"def log_writer; end",
"def logs\n\n end",
"def log(message); logger.info(message); end",
"def logger_output; end",
"def log\n @log\n end",
"def get_logger; @logger; end",
"def log(msg)\n Rails::logger.debug msg\n end",
"def request_log(request); end",
"def logger\n LOGGER\n end",
"def log=(log); end",
"def log\n self.class.log\n end",
"def log()\n @log\n end",
"def logger\n Rails.logger\n end",
"def logger; settings(:logger); end",
"def logger=(logger); end",
"def logger=(logger); end",
"def log\n Engine.logger\n end",
"def logged?; false end",
"def logged?; false end",
"def access_logger\n Rails.application.config.another_logger.info(\"#{request.method} '#{request.path}' #{request.version} from: #{request.remote_ip}\")\n end",
"def logger\n raise NotImplementedError\n end",
"def log(message)\n puts \"[ dev/rails ] #{message}\"\nend",
"def logger\n @log\n end",
"def logger\n @log\n end",
"def log_file; end",
"def logger\n @logger\n end",
"def log\n LOGGER\n end",
"def debug(msg); @logger.debug(msg); end",
"def colorize_logging; end",
"def logger\n initialize_logger unless @logger\n @logger\n end",
"def log\n Engines.log\n end",
"def dynflow_logger\n ::Rails.logger\n end",
"def logger=(_arg0); end",
"def logger=(_arg0); end",
"def logger=(_arg0); end",
"def logger=(_arg0); end",
"def logger=(_arg0); end",
"def logger=(_arg0); end",
"def logger=(_arg0); end",
"def log\n advanced[:log]\n end",
"def do_logging\n Log.debug \"debugging\"\n Log.info \"a piece of info\"\n Log.warn \"Danger, Will Robinson, danger!\"\n Log.error \"I dropped my Wookie! :(\"\n Log.fatal \"kaboom!\"\nend",
"def do_logging\n Log.debug \"debugging\"\n Log.info \"a piece of info\"\n Log.warn \"Danger, Will Robinson, danger!\"\n Log.error \"I dropped my Wookie! :(\"\n Log.fatal \"kaboom!\"\nend",
"def logger\n Logging.logger\n end",
"def logger\n SpotifyWeb.logger\n end",
"def logging_prefs; end",
"def verbose_logging; end",
"def logger\n FacebookApi.logger\n end",
"def autoflush_log; end",
"def autoflush_log; end",
"def error(msg); @logger.error(msg); end",
"def do_log( msg )\n log( msg )\n end",
"def logger\r\n self.class.logger\r\n end",
"def logL\n raise \"No implemented\"\n end",
"def log_file\n end",
"def log\n @log ||= Logging.logger[self]\n end",
"def with_logger\n yield\n end",
"def enable_logging\n initialize_logger\n end",
"def log_stuff\r\n log.info(\"TestLogger is here to log stuff.\")\r\n log.warn(\"TestLogger is finishged logging. Be careful.\")\r\n end",
"def action_logger\n ::Rails.logger\n end",
"def logger\n @logger ||= Rails.logger\n end",
"def logger\n @logger ||= Rails.logger\n end",
"def log\n Howitzer::Log.instance\nend",
"def logger\n Restfulness.logger\n end"
] |
[
"0.7967993",
"0.7967993",
"0.7967993",
"0.7967993",
"0.7967993",
"0.7967993",
"0.7967993",
"0.7967993",
"0.7967993",
"0.7967993",
"0.7967993",
"0.7967993",
"0.7967993",
"0.7967993",
"0.7967993",
"0.7967993",
"0.7967993",
"0.7967993",
"0.7967993",
"0.78018904",
"0.78018904",
"0.78018904",
"0.78018904",
"0.78018904",
"0.78018904",
"0.78018904",
"0.78018904",
"0.7590579",
"0.7579546",
"0.73408157",
"0.72883725",
"0.7266318",
"0.7208463",
"0.71854186",
"0.71854186",
"0.71854186",
"0.7174346",
"0.7174346",
"0.712584",
"0.7123739",
"0.70758086",
"0.70252204",
"0.69971645",
"0.6992406",
"0.69692713",
"0.69546914",
"0.69526625",
"0.6941485",
"0.6940201",
"0.6938025",
"0.6936609",
"0.6929846",
"0.6908317",
"0.6908317",
"0.6839842",
"0.6836917",
"0.6836917",
"0.67865914",
"0.6780855",
"0.6767283",
"0.67669785",
"0.67669785",
"0.6754709",
"0.67379415",
"0.67205065",
"0.6686036",
"0.6671371",
"0.666971",
"0.6660637",
"0.66527486",
"0.6648102",
"0.6648102",
"0.6648102",
"0.6648102",
"0.6648102",
"0.6648102",
"0.6648102",
"0.6647301",
"0.66450524",
"0.66450524",
"0.6644283",
"0.66365993",
"0.66343313",
"0.66274685",
"0.6614584",
"0.6606661",
"0.6606661",
"0.660632",
"0.66061604",
"0.66047335",
"0.6599981",
"0.65963376",
"0.65843797",
"0.6575531",
"0.65729505",
"0.6568136",
"0.6558845",
"0.65582776",
"0.65582776",
"0.65561676",
"0.6554135"
] |
0.0
|
-1
|
This should return the minimal set of values that should be in the session in order to pass any filters (e.g. authentication) defined in RondasController. Be sure to keep this updated too.
|
def valid_session
{}
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def get_session_variables_from_authenticated_system\n @return_to_query = session[:return_to_query] || params[:return_to_query]\n @return_to = session[:return_to] || params[:return_to]\n @previous_protocol = session[:previous_protocol] || params[:previous_protocol]\n session[:return_to_query] = session[:return_to] = session[:previous_protocol] = nil\n end",
"def valid_session\n {\"warden.user.user.key\" => session[\"warden.user.user.key\"]}\n end",
"def valid_session\n { \"warden.user.user.key\" => session[\"warden.user.user.key\"] }\n end",
"def session\n raw_session[\"warden.user.#{scope}.session\"] ||= {}\n end",
"def valid_session\n {:user => @admin, :user_id => @admin.id}\n end",
"def valid_session\r\n {}\r\n end"
] |
[
"0.63934624",
"0.63851434",
"0.6296908",
"0.62675595",
"0.6119653",
"0.6057895"
] |
0.0
|
-1
|
rollback: it's a select, nothing to rollback, blank override
|
def rollback
true
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def rollback\n query 'rollback'\n self\n end",
"def rollback; end",
"def rollback; end",
"def rollback; end",
"def rollback; end",
"def rollback; end",
"def rollback_db_transaction\n execute(\"ROLLBACK\")\n end",
"def rollback_db_transaction\n execute(\"ROLLBACK\")\n end",
"def rollback_transaction_sql\n SQL_ROLLBACK\n end",
"def rollback_transaction_sql\n SQL_ROLLBACK\n end",
"def rollback\n @MySQLConnection.query('rollback')\n end",
"def rollback\n # implement in subclasses\n end",
"def rollback\n end",
"def rollback()\n #This is a stub, used for indexing\n end",
"def rollback_db_transaction() end",
"def rollback_db_transaction() end",
"def rollback_transaction(tx)\n # nothing to do\n end",
"def rollback\n @db.rollback\n end",
"def rollback\n IBM_DB.rollback(@conn)\n end",
"def rollback\n current_transaction.rollback\n last_transaction = @all_transactions.pop\n end",
"def exec_rollback_db_transaction\n log('ROLLBACK', 'TRANSACTION') { @connection.rollback }\n end",
"def rollback\n raise TransactionRollback.new\n end",
"def rollback_transaction(tx)\n tx.rollback\n end",
"def rollback()\n check_return_code(PureHailDB.ib_trx_rollback(@trx_ptr))\n end",
"def rollback_db_transaction\n @transaction = @connection.rollback\n end",
"def rollback\n puts colorBlue('rolling back to commit blah')\n end",
"def rollback_db_transaction\n log('rollback transaction', nil) { @connection.rollback }\n end",
"def tx_rollback\n write_bytes FrameBytes.tx_rollback(@id)\n expect :tx_rollback_ok\n nil\n end",
"def rollback_transaction(conn)\n log_info(TRANSACTION_ROLLBACK)\n conn.rollback\n end",
"def rollback transaction\n service.rollback project_id: project, database_id: database, transaction: transaction\n end",
"def exec_rollback_db_transaction\n @connection.rollback\n @connection.autocommit = true\n end",
"def rollback_db_transaction() \n log('Rolling back boxcar', 'rollback_db_transaction()')\n @command_boxcar = []\n end",
"def rollback\n raise \"Illegal state for rollback: #{@state}\" unless @state == :begin\n each_adapter(:rollback_adapter_if_begin, [:rollback_and_close_adapter_if_begin, :close_adapter_if_none])\n each_adapter(:rollback_prepared_adapter_if_prepare, [:rollback_prepared_and_close_adapter_if_begin, :close_adapter_if_none])\n each_adapter(:close_adapter_if_open, [:log_fatal_transaction_breakage])\n @state = :rollback\n end",
"def rollback\n sanity_check\n @handle.rollback\n end",
"def rollback opts = {}\n update opts.merge(:data => xml.rollback)\n end",
"def rollback!\n restore_attributes\n end",
"def rollback\n @repo.rollback\n end",
"def rollback_transaction(conn, opts=OPTS)\n if in_savepoint?(conn)\n log_connection_yield('Transaction.rollback_savepoint', conn){conn.rollback(savepoint_obj(conn))}\n else\n log_connection_yield('Transaction.rollback', conn){conn.rollback}\n end\n end",
"def rollback_transaction(conn, opts={})\n log_yield(TRANSACTION_ROLLBACK){conn.rollback}\n end",
"def rollback(&block)\n block_given? ? transaction {yield; rollback} : (raise Rollback)\n end",
"def rollback\n each {|transition| transition.rollback}\n end",
"def rollback\n each { |transition| transition.rollback }\n end",
"def rollback\n objects.clear\n load\n finish_transaction\n end",
"def rollback\n Rails.logger.debug \"Rollback not implemented: #{self.class.to_s}\"\n end",
"def rollback_transaction(conn, opts=OPTS)\n log_connection_yield('Transaction.rollback', conn){conn.rollback}\n end",
"def tx_rollback(&block)\n @connection.send_frame(Protocol::Tx::Rollback.encode(@id))\n\n self.redefine_callback :tx_rollback, &block\n self\n end",
"def rollback!\n self.revert_to! self.previous_version\n end",
"def exec_rollback_to_savepoint(name = current_savepoint_name)\n log(\"ROLLBACK TO SAVEPOINT #{name}\", 'TRANSACTION') { @connection.rollback_savepoint(name) }\n end",
"def rollback\n self.revert_to self.previous_version\n end",
"def rollback_savepoint_sql(depth)\n SQL_ROLLBACK_TO_SAVEPOINT % depth\n end",
"def disconnect_connection(conn)\n conn.RollbackTrans rescue nil\n super\n end",
"def rolledback!\n @on_rollback.each do |callback|\n callback.call\n end\n clear\n end",
"def post_transaction_process\n fail(ActiveRecord::Rollback) unless @status\n end",
"def undo\n\t\t\t\t\n\t\t\tend",
"def rollback transaction_id\n service.rollback path, transaction_id\n @last_updated_at = Time.now\n true\n end",
"def undo\n\t\t\n\tend",
"def undo\n\t\t\n\tend",
"def rollback\n each {|transition| transition.machine.write(object, :event, transition.event)}\n super\n end",
"def remove_transaction(conn, committed)\n if jdbc_level = _trans(conn)[:original_jdbc_isolation_level]\n log_connection_yield(\"Transaction.restore_isolation_level\", conn){conn.setTransactionIsolation(jdbc_level)}\n end\n unless in_savepoint?(conn)\n conn.setAutoCommit(true)\n end\n ensure\n super\n end",
"def rollback()\n conn = connection(@rollback_uri)\n resp = conn.post \n return DeziResponse.new(resp)\n end",
"def run(*args, &block)\n Sequel::Model.db.transaction(rollback: :always, auto_savepoint: true) { super }\n end",
"def rollback\n { rollback: {} }.to_json\n end",
"def rollback\n if @id.nil?\n raise TransactionError, \"Cannot rollback when not in a transaction.\"\n end\n\n ensure_service!\n service.rollback @id\n true\n end",
"def rollback\n super\n each { |transition| transition.machine.write(object, :event, transition.event) unless transition.transient? }\n end",
"def void_last_transaction\n @total-=self.total\n end",
"def add_rollback(&block)\n existing_rollback = task_call_frames.last.rollback\n task_call_frames.last.rollback = lambda { block.call ; existing_rollback.call }\n end",
"def rollback_item\n ingreso_producto = self.ingreso_producto\n ingreso_producto.cantidad = ingreso_producto.cantidad + self.cantidad\n ingreso_producto.producto.stock = ingreso_producto.producto.stock + self.cantidad #suma al stock si se anula\n Lineakardex.create(:kardex => ingreso_producto.producto.kardex, :tipo => \"Entrada\", :fecha => Time.now, :cantidad => self.cantidad, :v_unitario => self.ingreso_producto.producto.precio_venta, :modulo => \"Hospitalizacion\", :observaciones => \"Pedido Anulado\" )\n ingreso_producto.save\n ingreso_producto.producto.save\n end",
"def revert\n end",
"def rollback\n FileUtils.rm_r(path) if File.exist?(path)\n transaction.rollback\n end",
"def rollback_transaction?\n false\n end",
"def rollback\n without_transactions do\n repository.transactions_log.delete_if do |(method, options)|\n\n begin\n case method\n when :ingest\n repository.purge_object :pid => options[:pid]\n\n when :modify_object\n repository.modify_object options\n\n when :add_datastream\n repository.purge_datastream :pid => options[:pid], :dsid => options[:dsid]\n\n when :add_relationship\n repository.purge_relationship options[:options].merge(:pid => options[:pid])\n\n when :purge_relationship\n repository.add_relationship options[:options].merge(:pid => options[:pid])\n\n when :purge_object\n repository.ingest :pid => options[:pid], :file => options[:foxml]\n\n when :set_datastream_options\n repository.set_datastream_options options\n\n when :modify_datastream\n repository.purge_object :pid => options[:pid] rescue nil\n repository.ingest :pid => options[:pid], :file => options[:foxml]\n\n when :purge_datastream\n repository.purge_object :pid => options[:pid] rescue nil\n repository.ingest :pid => options[:pid], :file => options[:foxml]\n end\n rescue\n # no-op\n end\n\n run_hook :after_rollback, :pid => options[:pid], :method => method, :options => options\n\n end\n end\n true\n end",
"def transaction\n start\n yield self\n rescue Object => ex\n rollback\n debug \"#{ex.class}: #{ex.message}\"\n ex.backtrace.each { |line| debug line }\n else\n commit\n end",
"def rollback\n _called.reverse_each do |command|\n begin\n command.rollback\n rescue => error\n raise Errors::InvokerRollbackError.new(error: error, command: command, invoker: self, backtrace: error.backtrace)\n end\n end\n end",
"def rollback(step = 1)\n files = File.migrated.reverse.first(step)\n Migrate::Down.new(files).perform\n end",
"def rollback_balance(transaction)\n if transaction.succeeded?\n sign = transaction.payment? ? -1 : 1\n self.balance.update_attributes!(amount: (self.balance.amount + (BigDecimal.new(transaction.amount_was) * sign)))\n end\n end",
"def rollback!\n if (@status == 'DELETED')\n self.errors.add(:base, 'Campaign is already deleted.')\n return false\n end\n\n self.errors.clear\n\n self.update(\n :name => \"#{@name}_DELETED_#{(Time.now.to_f * 1000).to_i}\",\n :status => 'DELETED'\n )\n end",
"def transaction; end",
"def transaction; end",
"def transaction; end",
"def transaction(object)\n object.db.transaction {raise ::Sequel::Error::Rollback unless yield}\n end",
"def rollback_name\n result = ActiveRecord::Base.connection.select_all <<~SQL\n SELECT * FROM person_name\n WHERE voided = 1\n AND person_id = #{secondary_patient}\n AND void_reason LIKE 'Merged into patient ##{primary_patient}:%'\n SQL\n process_name(voided_names: result)\n ActiveRecord::Base.connection.execute <<~SQL\n UPDATE person_name SET #{common_void_columns} #{extra_fields} WHERE person_id = #{common_void_reason}\n SQL\n end",
"def rollback()\n oldpos = @checkpoints.pop\n unless oldpos\n oldpos = 0\n end\n self.pos = oldpos\n return self \n end",
"def undo\n transaction do\n undoables = self.class.find(:not_undone, :all, :to => self.id, :include => :changes)\n raise Stale unless undoables.include? self\n undoables.each do |op|\n op.changes.each { |change| change.undo }\n op.undone = true\n op.save!\n end\n end\n end",
"def commit_db_transaction() end",
"def commit_db_transaction() end",
"def restart_transaction\n ActiveRecord::Base.connection.execute(\"COMMIT\")\n ActiveRecord::Base.connection.execute(\"BEGIN\")\n end",
"def void_last_transaction\n self.total = self.total - self.last_transaction\n end",
"def void_last_transaction\n self.total = self.total - self.last_transaction\n end",
"def void_last_transaction\n self.total = self.total - self.last_transaction\n end",
"def rollback\n release = args.shift.downcase.strip rescue nil\n rolled_back = heroku.rollback(app, release)\n display \"Rolled back to #{rolled_back}\"\n end",
"def commit_db_transaction\n execute(\"COMMIT\")\n end",
"def commit_db_transaction\n execute(\"COMMIT\")\n end",
"def pay_back\n return false unless valid?\n\n commit_or_rollback do\n res = save_expense\n res = create_ledger\n\n set_errors(expense, ledger) unless res\n\n res\n end\n end",
"def commit_transaction_sql\n SQL_COMMIT\n end",
"def commit_transaction_sql\n SQL_COMMIT\n end",
"def void_last_transaction\n self.total -= @last_transaction.pop\n end",
"def remove_transaction(conn, committed)\n conn.autocommit = true\n ensure\n super\n end",
"def abort_transaction!\n @ignore_trace = true\n end",
"def disable_rollback\n data[:disable_rollback]\n end",
"def rollback()\n rollback_to_release = releases[-2]\n\n if rollback_to_release.nil?\n server[:logger].warn('No release to rollback to')\n else\n current_release_dir = release_dir(releases.last)\n skip_current_release_dir = release_dir(\"skip-#{releases.last}\")\n cmd.ssh(\"mv #{current_release_dir} #{skip_current_release_dir}\")\n symlink_release_dir(rollback_to_release)\n end\n end"
] |
[
"0.8083688",
"0.7993103",
"0.7993103",
"0.7993103",
"0.7993103",
"0.7993103",
"0.7931139",
"0.7931139",
"0.78960973",
"0.78960973",
"0.7890218",
"0.78374106",
"0.7815932",
"0.780877",
"0.77449536",
"0.77449536",
"0.7737373",
"0.7704847",
"0.7653238",
"0.75757515",
"0.7551363",
"0.7540986",
"0.7458644",
"0.7414693",
"0.74084044",
"0.7350373",
"0.7348169",
"0.7233633",
"0.7232542",
"0.7223387",
"0.72105867",
"0.72064644",
"0.71123785",
"0.71038574",
"0.71032727",
"0.7046439",
"0.70317",
"0.70229226",
"0.70110345",
"0.68897814",
"0.68588656",
"0.68474054",
"0.68170846",
"0.6807589",
"0.6771392",
"0.66769564",
"0.66582215",
"0.6656187",
"0.6645354",
"0.66169804",
"0.65669703",
"0.655426",
"0.65531975",
"0.6468558",
"0.64501244",
"0.6421816",
"0.6421816",
"0.63716596",
"0.6344815",
"0.62924784",
"0.62873864",
"0.62851363",
"0.6249723",
"0.62002516",
"0.6199998",
"0.6188377",
"0.612804",
"0.6127648",
"0.6119403",
"0.60850495",
"0.60836834",
"0.6076014",
"0.6059353",
"0.6051037",
"0.5981297",
"0.5978033",
"0.59271044",
"0.59271044",
"0.59271044",
"0.59246707",
"0.59020454",
"0.5899926",
"0.5890493",
"0.5890429",
"0.5890429",
"0.5870077",
"0.584208",
"0.584208",
"0.584208",
"0.5835527",
"0.58196914",
"0.58196914",
"0.579732",
"0.57936865",
"0.57936865",
"0.57921547",
"0.57895076",
"0.5764969",
"0.57569104",
"0.57565147"
] |
0.6803823
|
44
|
input array find the maximum number in the array build an array of fibonacci numbers up to the max numbers iterate over the original array slect see if current item is included in the fibonacci array output array 1 1 2 3 5 8 13
|
def fibonacci_index(array)
fibonacci_sequence = create_fibonacci(array.size)
new_array = array.select { |num| fibonacci_sequence.include?(array.index(num)) }
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def fibonacci_array(max_num)\n while @fibon_array[-1] < max_num do\n new_num = @fibon_array[-2] + @fibon_array[-1]\n @fibon_array.push new_num\n end\n # Deletes last element if loop's new element exceeds max_num\n if @fibon_array[-1] > max_num\n @fibon_array.delete_at(-1)\n end\n @fibon_array\n end",
"def generate_fibonacci_array max_number\n current_val = 0\n i = 2\n while current_val < max_number do\n current_val = @fibonacci_array[i-1] + @fibonacci_array[i-2]\n @fibonacci_array << current_val\n i += 1\n end\n @fibonacci_array.pop\n end",
"def find_fibonaccis(limit)\n fib_array = []\n i = 1\n while i <= limit\n first_num = fib_array[i-1] ||= 1 # 1, \n second_num = fib_array[i] ||= 1 # 1, \n result = first_num + second_num\n if result > limit\n break\n end\n fib_array << result\n i += 1\n end\n fib_array\nend",
"def fib_numbers(max) #max must be integer 1 or greater\n\tfib = [1,1]\n\n\ti = 1\n\n\twhile fib[i] < max\n\t\tfib << fib[i] + fib[i-1]\n\t\ti += 1\n\tend\n\n\tfib.delete_at(fib.length - 1) if fib.last > max\n\n\treturn fib\nend",
"def fib_sequence(max)\n fib_array = [1,2]\n until fib_array.last >= max do\n fib_array << (fib_array.last + fib_array[-2])\n end\n return fib_array\nend",
"def is_fibonacci?(num) #thanks to Hing for inspiration on this solution. \n\tfib_seq = [0,1] #setting the base numbers in the sequence\n\twhile num >= fib_seq[fib_seq.length-1] #setting the loop so it continues until the last number in the seq is greater or equal to the input\n\t\tfib_seq.push(fib_seq[fib_seq.length-1] + fib_seq[fib_seq.length - 2]) #with each loop, pushs the new value into the array\n\tend\n\tfib_seq.include?(num)\nend",
"def is_fibonacci?(num)\n newarray = [0,1]\n x = 0\n while num > x\n x = newarray[-1] + newarray[-2]\n newarray.push(x)\n end\n newarray.include?(num)\nend",
"def buildFibbs(fibbs, max)\n while fibbs[fibbs.length-1] < max do\n fibbs.push(fibbs[fibbs.length-1] + fibbs[fibbs.length-2])\n end\n fibbs\nend",
"def problem_2_build_fib_array(upper_limit)\n fib_array = [1,2]\n while fib_array.last < upper_limit\n next_fib = fib_array[-1] + fib_array[-2]\n fib_array << next_fib\n end\n fib_array.pop\n fib_array\nend",
"def output_els_with_fib_index(arr)\n matching_els = []\n arr.each_with_index do |el, i|\n matching_els << el if is_fib?(i)\n end\n matching_els\nend",
"def get_fibonacci_numbers(number_terms, fibonacci_max_term_value)\n fibonacci_numbers = [1,1]\n\n i = 0\n fibonacci_next_new_number = 0\n until i == number_terms - 1 || fibonacci_next_new_number > fibonacci_max_term_value\n fibonacci_new_number = fibonacci_numbers[i] + fibonacci_numbers[i+1]\n fibonacci_numbers << fibonacci_new_number\n i += 1\n fibonacci_next_new_number = fibonacci_numbers[i] + fibonacci_numbers[i+1]\n end\n puts \"The loop broke after #{i+1} terms for max value term set at #{fibonacci_max_term_value} :\"\n return fibonacci_numbers\nend",
"def is_fibonacci?(num)\n array = [0, 1, 1]\n current = 0\n while current <= num\n array << array[array.length - 1] + array[array.length - 2]\n current = array[array.length - 1]\n end\n if array.include?(num)\n p true\n else \n p false\n end\nend",
"def fibs(num)\n array = []\n 0.upto(num) do |i|\n array << i if i.zero? || i == 1\n array << array[i - 1] + array[i - 2] if i > 1\n end\n array\nend",
"def is_fibonacci?(num)\n\tarray = [0,1]\n\twhile array[-1] < num do\n\t\tarray << (array[-1] + array[-2])\n\tend\n\treturn array[-1] == num\nend",
"def fib(input_fibonacci)\n fib_array = []\n if input_fibonacci == 1\n fib_array.push(0)\n elsif input_fibonacci == 2\n fib_array.push(0)\n fib_array.push(1)\n else\n fib_array = [0, 1,]\n until fib_array.length == input_fibonacci\n fib_array.push(fib_array[-1]+fib_array[-2])\n end\n end\n p fib_array\nend",
"def fib_arry\n arr = [1, 1]\n a = 0\n b = 1\n while arr[a] + arr[b] <= 4000000\n arr << (arr[a] + arr[b])\n a += 1\n b += 1\n end\n # step 2 determine which are even\n evens = arr.select { |num| num.even? }\n # step 3 sum\n puts \"This is the sum of all even fibonacci numbers less than 4,000,000: #{evens.reduce(:+)}\"\nend",
"def fib( max_val )\n x = [ 1, 2 ]\n while\n next_val = ( x[ -2 ] + x[ -1 ] )\n return x if next_val > max_val\n x << next_val \n end\nend",
"def create_fibonacci(integer, array=[])\n\n return [] if integer <= 0\n\n array.size < 2 ? array << 1 : array << array[-2] + array[-1]\n\n if array.last >= integer\n array.pop\n return array\n end\n\n create_fibonacci(integer, array)\nend",
"def sum_evens max_number\n fibonacci_array.each do |value|\n even_number_array << value if value.even?\n end\n even_number_array.sum\n end",
"def sum_even_fibonacci(max)\r\n arr = [1,2]\r\n while arr[-1] + arr[-2] <= max\r\n arr << arr[-1] + arr[-2]\r\n end\r\n total = 0\r\n arr.each { |x| total += x if x.even? }\r\n total\r\nend",
"def fib(i)\n fib_array = []\n index = 0\n if i <= 0\n puts \"Please use numbers greater than 0.\"\n elsif i == 1\n fib_array << 0\n elsif i == 2\n fib_array << 0\n fib_array << 1\n else\n fib_array << 0\n fib_array << 1\n until fib_array.length >= i\n fib_array << (fib_array[-1] + fib_array[-2])\n end\n p fib_array\n end\nend",
"def is_fibonacci?(num)\n fib_array = [0, 1]\n if num == fib_array[-1]\n return true\n elsif num > fib_array[-1]\n while num > fib_array[-1]\n fib_array.push(fib_array[-1] + fib_array[-2])\n end\n if num == fib_array[-1]\n return true\n else\n return false\n end\n end\nend",
"def bottom_up(max)\n fib = []\n fib[0] = 1\n fib[1] = 2\n\n for i in 2..Float::INFINITY\n sum = fib[i-1] + fib[i-2]\n\n if sum > max\n break\n else\n fib[i] = sum\n end\n end\n\n return fib\n end",
"def fibs(n, ary = [0,1])\n n.times { ary << ary[-2] + ary[-1] until ary.length == n }\n return ary\nend",
"def fib(n) #n indicates # of elements we want in array\r\n a = 0\r\n b = 1\r\n fib_arr = []\r\n #loop starts iff n >= 1, but x starts from 0 (when n=1, x=0; n=2, x=0,1)\r\n n.times do |x| \r\n if x == 0\r\n fib_arr << a\r\n elsif x == 1\r\n fib_arr << b\r\n else\r\n c = a+b #c is the new fib # we are generating\r\n fib_arr << c\r\n a = b\r\n b = c\r\n end\r\n end\r\n return fib_arr\r\nend",
"def fib \n arr = [0, 1]\n\n while arr[-1] + arr[-2] <= 4_000_000\n arr << arr[-1] + arr[-2]\n end\n arr.select(&:even?).inject(:+)\nend",
"def fib_it(n)\n fib_array = [1, 1]\n return fib_array if n == 2\n return [1] if n == 1\n\n (3..n).count { fib_array << fib_array[-2] + fib_array[-1] }\n\n fib_array\nend",
"def is_fibonacci?(num)\n arr = [0,1]\n\n while num > arr.last\n last = arr.pop\n first = arr.pop\n\n arr.push(last, last + first)\n end\n\n num == arr.last ? true : false\nend",
"def fib(num)\n array= [0,1]\n\twhile (array.length < num)\n\t\tlast_nums = array[-2..-1]\n\t\tnew_number = last_nums.first + last_nums.last\n\t\tarray.push(new_number)\n\tend\n\tarray\nend",
"def fibs_rec(number, array=[1])\n\t\n\tif number>2 then array.push(array[-2]+array[-1]); \n\t\tfibs_rec(number-1, array);\n\telsif number==2\n\t\treturn [1,1]\n\tend\n\treturn array\nend",
"def fib(num)\n fib_seq_arr = []\n\n (0..num).each do |number|\n fib_seq_arr << number if number <= 1\n fib_seq_arr << fib_seq_arr[-1] + fib_seq_arr[-2] if fib_seq_arr.length > 1\n end\n return fib_seq_arr\nend",
"def fibs(num)\n arr = [0, 1]\n\n (2..num).each do |_i|\n arr << arr[-1] + arr[-2]\n end\n\n arr.last\nend",
"def generate_fibonacci_numbers(limit)\n i = 1\n fibonacci_numbers = [0, 1]\n sum = 0\n check = true\n\n while check == true do\n if fibonacci_numbers[i - 1] + fibonacci_numbers[i] > limit\n check = false\n else\n fibonacci_numbers << fibonacci_numbers[i - 1] + fibonacci_numbers[i]\n end\n\n i += 1\n end\n\n # return fibonacci_numbers.inspect\n\n fibonacci_numbers.each do |fib|\n if fib % 2 == 0\n sum += fib\n end\n end\n\n return sum\nend",
"def is_fibonacci(num)\n\tfib_container = [1,1]\n\tfib_counter = 2\n\tuntil fib_container.last >= num\n\t\tfib_container << fib_container[-2] + fib_container.last\n\t\tfib_counter += 1\n\tend\n\tresult = [num, fib_container.last, (num == fib_container.last), fib_counter]\nend",
"def fib(number)\narray = []\n if number == 0\narray = []\n return array\n else \n number == 1\narray = [0, 1]\nend\n\nwhile array.length < number\narray[array.length] = array[-1] + array[-2]\nend\nreturn array\nend",
"def fibonacci\n\n # write a fibonacci sequence\n # make an array\n fibonacci_sequence = [1, 2, 3, 5, 8]\n while true\n the_length = fibonacci_sequence.count - 1\n if fibonacci_sequence[the_length] + fibonacci_sequence[the_length - 1] > 4000000\n break\n end\n fibonacci_sequence << (fibonacci_sequence[the_length] + fibonacci_sequence[the_length - 1])\n end\n # p fibonacci_sequence\n\n # find the even numbers in an array\n # find if a particular number is even\n # make a loop to check them all\n even_array = []\n fibonacci_sequence.each do |number|\n if number % 2 == 0\n even_array << number\n else\n end\n end\n\n p even_array\n\n sum = 0\n even_array.each do |number|\n sum += number\n end\n\n p sum\nend",
"def is_fibonacci?(n)\n fibonacci_numbers = [0, 1]\n while n > fibonacci_numbers[-1]\n x = fibonacci_numbers[-1] # Last number in the array\n y = fibonacci_numbers[-2] # Second to last number in the array\n fibonacci_numbers.push(x+y) # We add them and push them into the array\n end\n fibonacci_numbers.include?(n)? true : false\nend",
"def fancy_fib(num, arr = [0,1])\n if arr.length != num\n arr= fancy_fib(num, arr.push(arr[-1]+ arr[-2]))\n end\n arr\nend",
"def fibonacci(number)\n arr = []\n counter = 0\n sum = 1\n loop do\n arr << sum\n sum = arr[counter] + arr[counter - 1]\n counter += 1\n break if sum > number\n end\n arr\nend",
"def fibonacci(n)\n fib_array = [0,1]\n\tfib = n - 2\n fib.times do |fib|\n fib_array << fib_array[-1] + fib_array[-2]\n end\n\n\tif fib_array.count < 20\n \tp fib_array\n else\n \tp fib_array.last \n end\t\nend",
"def create_fibonacci(max)\n fibonacci = [1,2]\n until fibonacci[-1] > max\n fibonacci << fibonacci[-1] + fibonacci[-2]\n end\n fibonacci\nend",
"def fib_array1(n)\n return n if n < 2\n array = [0]\n f = 1\n n.times do\n array.push(f)\n f = f + array[-2]\n end\n return array.last\nend",
"def fibonacci(int)\n range_array = (1..int).to_a\n final_array = [1,1]\n range_array.each do |num|\n p num > 2 ? final_array << final_array[num-3] + final_array[num-2] : nil\n end\n final_array[-1]\nend",
"def is_fibonacci?(num)\n fibo_list = []\n penultimate_number = 0\n last_number = 1\n until last_number > num\n next_number = penultimate_number + last_number\n fibo_list << next_number\n penultimate_number = last_number\n last_number = next_number\n end\n return fibo_list.include? num\nend",
"def fib(number)\n array = []\n if number == 0\n return array\n elsif number == 1\n array << 0\n return array\n elsif number == 2\n array << 0\n array << 1\n return array\n elsif number > 2\n index = 2\n array << 0\n array << 1\n while index < number\n array << array[index - 1] + array[index - 2]\n index += 1\n end\n return array\n end \nend",
"def is_fibonacci?(num)\n arr = [0,1]\n while num > arr.last\n a,b = arr.pop(2)\n arr.push(a,b, a + b);\n end\n if num == arr.last then return true else return false end\nend",
"def fib_method(number)\n\ncounter = 0\nfib_array = [0,1]\n\n\n#create a loop that breaks down the array into its parts\nuntil counter == number\n\n# if counter is at zero do nothing.\n\nif counter == 0\n#else not at zero subtract from fib_array index current counter -1\n# add too fib_array index counter\n# store the sum of those two numbers into a result variable\n\nelse\n result = fib_array[counter-1] + fib_array[counter]\n fib_array << result\nend\n\n# add to counter to get to the end of the fib_array loop\ncounter += 1\nend\n\n#strip the last index of the array\nfib_array.delete_at(-1)\np fib_array\n\nend",
"def fibonacci_numer_no_array(num)\n if num <= 2\n return 1\n end\n # for educational purposes\n counter = 2\n second_to_last = 1\n last = 1\n next_fib = 2\n # calculate the next number until the array has the one we want\n while counter < num\n second_to_last = last\n last = next_fib\n next_fib = second_to_last + last\n counter +=1\n puts \"second_to_last = #{second_to_last}\"\n puts \"last = #{last}\"\n puts \"next_fib = #{next_fib}\"\n puts \"counter = #{counter}\"\n puts \"After #{counter} iterations, the last number is #{last}\"\n puts \"===========================================\"\n end\n next_fib\nend",
"def fibonacci_array(size)\n fib_array = [1, 1]\n count = 0\n loop do\n fib_array << fib_array[count] + fib_array[count + 1]\n count += 1\n break if count == size\n end\n fib_array\nend",
"def fibs(n)\n arr = []\n i = 0\n while i < n\n if i < 1\n arr << 0\n elsif i == 1\n arr << 1\n else\n arr << arr[i-1] + arr[i-2]\n end\n i += 1\n end\n arr\nend",
"def iterative_fib (num)\n fib_arr = []\n (1..num).each do |i|\n if i == 1 || i == 2\n fib_arr << 1\n else\n fib_arr << fib_arr[-1] + fib_arr[-2]\n end\n end\n fib_arr\nend",
"def fibonacci(int)\n range_array = (1..int).to_a\n final_array = [1,1]\n range_array.each do |num|\n num > 2 ? final_array << final_array[num-3] + final_array[num-2] : nil\n end\n final_array[-1]\nend",
"def is_fibonacci? num\n fib_seq = [0,1]\n while num > fib_seq.last\n x,y = fib_seq.pop(2)\n fib_seq.push(x,y,x+y)\n end\n fib_seq.include? num \nend",
"def fibs(num)\n arr = [0,1]\n counter = 2\n return [0] if num == 1\n\n until counter == num\n arr << arr[-1] + arr[-2]\n counter +=1\n end\n arr\nend",
"def fibonacci(number)\n array = []\n if number == 0\n array\n else number == 1\n array = [0, 1]\n end\n\n while array.length < number\n array[array.length] = array[-2] + array[-1]\n end\n array\nend",
"def fibonacci(num)\n arr = []\n (1..num).each do |number|\n number == 1 || number == 2 ? arr << 1 : arr << arr[-1] + arr[-2]\n end\n arr.last\nend",
"def fibsBelow(limit)\n\tfibs = [1, 2]\n\ti = 0\n\tloop do\n\t\tnextFib = fibs[i] + fibs[i+1]\n\t\tbreak if nextFib > limit\n\t\tfibs << nextFib\n\t\ti += 1\n\tend\n\treturn fibs\nend",
"def max_sub_array(numbers)\n max = numbers[0]\n\n (1...numbers.size).each do |idx|\n current_sum = numbers[idx] + numbers[idx - 1]\n numbers[idx] = current_sum if current_sum > numbers[idx]\n max = numbers[idx] if numbers[idx] > max\n end\n\n max\nend",
"def fibb (num=6,i=0,y=0,x=0,arr=[])\n if i >= num \n return arr\n else\n temp = x\n x = y > 0 ? (x+y) : 1\n return fibb(num,i+1,temp,x,arr.push(x))\n end\nend",
"def even_fib\n x=[0,1]\n i = 0\n a = []\n\n while x.last < 4000000\n x.push(x[i] + x[i+1])\n i += 1\n end\n\n x.pop\n\n x.each do |blah|\n if blah.even?\n a.push(blah)\n end\n \n end\n\n a.reduce(:+)\n\nend",
"def fibonacci_sequence(max, seq = [1,2])\n seq << (seq[-2] + seq[-1])\n seq[-1] >= max ? seq[0..-2] : fibonacci_sequence(max, seq)\nend",
"def fibo(n)\n (1..n).inject([]) { |memo, i| [1, 2].include?(i) ? memo << i : memo << (memo.last + i) }\nend",
"def is_fibonacci?(num)\n arr = [0, 1]\n while num > arr.last\n x, y = arr.pop(2)\n arr.push(x, y, x + y)\n end\n\n return true if num == arr.last\n return false\nend",
"def sum_of_even_fibonaccis(limit)\n # Fibonacci sequence starts with 1,2\n holder = [1,2]\n\n # Adding the last 2 elements of the array together\n while (holder[-1] + holder[-2]) < limit\n # Push the sum of the last 2 numbers into the existing array\n holder << holder[-1] + holder[-2]\n # Repeat the while loop\n end\n # Return the array, but select only the even numbers and add them together\n return holder.select { |num| num.even? }.reduce(:+)\nend",
"def fibo_finder(n)\n fib_array = [0, 1]\n (2..n).each do |i|\n fib_array << fib_array[i-1] + fib_array[i-2]\n end\n fib_array[n]\nend",
"def fib(integer)\n\nfib_arr = [0,1]\n#declaring the beginning portion of the fibanocci sequence\nindex = 2\n#starting at two because the array is already filled with the 0 & 1 index's filled \n\tuntil index == integer \n# the integer will be the fib(x) for the sequence\n\tnext_number = fib_arr[-1] + fib_arr[-2]\n#the next number in the sequence will equal the last number in the array, represented by -1, and the second to\n#last number represented by -2 added together.\n\tfib_arr << next_number\n#feeding the next_number into the array\n\tindex += 1\n#changing to the next index in the array\n\tend\n\tputs fib_arr\n#printing the new array\nend",
"def largest_fib\n\n fib = [1,1]\n x = 0\n\n\n\nwhile fib[-1].to_s.length != 1000\n fib << (fib[x] + fib[x + 1])\n x += 1\n\nend\n\n\nfib.each_with_index { |x, index| puts \"#{x.to_s.length} and index:#{index}\"}\n\nend",
"def fib(num)\n \n if num == 0\n return []\n \n elsif num == 1\n return [0]\n \n else\n start_array = [0, 1]\n while start_array.length < num\n start_array << (start_array[-1] + start_array[-2])\n end\n end\n return start_array\nend",
"def fibs(number)\n\n\tfibonacci=[1]\n\tcount=0\n\tnum1=1\n\tnum2=0\n\twhile fibonacci.size<number\n\t\tsum=num1+num2\n\t\tfibonacci.push(sum)\n\t\tnum2=num1\n\t\tnum1=sum\n\tend\n\n\treturn fibonacci\nend",
"def fibonacci(num)\n return 1 if num == 1\n\n fibo_arr = [1, 1]\n\n until fibo_arr.size == num\n f = fibo_arr[-1] + fibo_arr[-2]\n fibo_arr << f\n end\n fibo_arr.pop\nend",
"def fibonacci_calculator(num)\n fib_arr = []\n\n\n if num == 0\n fib_arr = []\n return fib_arr\n elsif num == 1\n fib_arr = [0]\n return fib_arr\n elsif num == 2\n return fib_arr = [0,1]\n else\n fib_arr = [0,1]\n end\n\n while fib_arr.length < num\n fib_arr[fib_arr.length ] = fib_arr[-1] + fib_arr[-2]\n end\n\n return fib_arr\nend",
"def fibo(target_number)\n\ta=0;\n\tb=1;\n\tseries = Array.new #this global variable will contains series \n\t(0..target_number).each do |i|\n\t\tif i<2\n\t\t\tseries[i]=i\n\t\telse\n\t\t\tc=a+b\n\t\t\ta,b=b,c\n\t\t\tseries[i]=c\n\t\tend\t\n\tend\n\treturn series\nend",
"def max_sequence(arr)\n puts arr\n index = 0\n numIndexes = 0\n highestSum = arr.min\n \n length = arr.count\n \n highestNum = arr.max\n\n if arr != [] && highestNum < 0 \n return 0\n elsif arr == []\n return 0\n end\n \n arr.map.with_index do |n,i|\n\n for c in 0..i\n \n sum = arr.slice(c,length-i).inject(:+)\n\n if sum > highestSum\n highestSum = sum\n index = i\n numIndexes = length-i\n end\n \n end\n \n end\n \n highestSum\n \nend",
"def get_all_fibs(num)\n a = 1; b = 2; c = 0;\n fibs = [a, b];\n while ((c = a + b) < num)\n fibs << c;\n a = b;\n b = c;\n end\n fibs.select {|x| x.even?}.inject(:+)\nend",
"def fib(num)\n array = [0, 1]\n index = 0\n until index == num.to_i - 2\n next_number = array[-1] + array[-2]\n array.push(next_number)\n index +=1\n end\n array\nend",
"def fib(number)\n\narr = [0, 1]\n\n\ti = 0\n\t\n\twhile i < number - 2\t\t\n\t\tarr.push(arr[i] + arr[i+1])\n\t\ti += 1\n\tend\n\t\narr\t\nend",
"def fib_generator(number)\n fib_array = Array.new(number) # Create a new array of the size of the defined number\n counter = 0 # Setting a counter equal to zero to set up a loop\n # Logic to fill in the empty array with Fibinacci numbers\n while counter < fib_array.length\n if counter == 0 # Need to define the first number as zero\n fib_array[counter] = counter # Note counter is zero for first loop\n counter += 1\n elsif counter == 1 # Need to define the second number as one\n fib_array[counter] = counter # Note counter is one for second loop\n counter += 1\n else\n \t# Define all other numbers as the last sum of the last two elements in the array\n\t fib_array[counter] = (fib_array[counter -1] + fib_array[counter -2]) \n\t counter += 1\n end\n end \n return fib_array \nend",
"def fibonacci3(num)\n array = [0,1]\n def inner(num,array)\n array += [array[-1] + array[-2]]\n if array[-1] < num\n array = inner(num,array)\n end\n return array\n end\n array = inner(num,array)\n return array\nend",
"def fibs(num)\n fibs = [0,1]\n until fibs.size == num\n fibs << (fibs[-1] + fibs[-2])\n end\n fibs\nend",
"def fibonacci(num)\n fib_arr = []\n\n\n if num == 0\n fib_arr = []\n return fib_arr\n elsif num == 1\n fib_arr = [0]\n return fib_arr\n elsif num == 2\n return fib_arr = [0,1] \n else \n fib_arr = [0,1]\n end\n\n while fib_arr.length < num\n fib_arr[fib_arr.length ] = fib_arr[-1] + fib_arr[-2]\n end\n\n return fib_arr\nend",
"def fibonacci(amount)\r\n fib_array = [0, 1]\r\n current_value = 0\r\n if (amount == 0) ; return 0; end # Edge case...\r\n if (amount == 1) ; return 1; end # Edge case...\r\n\r\n index = 2 # Start indexing after the edge cases.\r\n until index == amount\r\n current_value = fib_array[-1] + fib_array[-2] # Equation for Fib-sequence. push it onto array afterwards.\r\n fib_array.push(current_value)\r\n index += 1 # counter approaching amount\r\n end \r\n return fib_array[-1] # return the last value we did!\r\nend",
"def fibonacci_it(n)\n arr = [1, 1]\n return [] if n <= 0\n return [1] if n == 1\n until arr.length == n\n arr << arr[-1] + arr[-2]\n end\n arr\nend",
"def is_fib?(target)\n a = 0\n b = 1\n\n loop do\n return true if b == target\n a, b = [b, b + a]\n break if b > target\n end\n\n false\nend",
"def the_fib(number)\r\n\tfib_array = Array.new \r\n\r\n\tif number == 0 \r\n\t\treturn fib_array = []\r\n\telsif number == 1\r\n\t\treturn fib_array = [0]\r\n\telsif number == 2 \r\n\t\treturn fib_array = [0, 1]\r\n\telse \r\n\t\tfib_array = [0, 1]\r\n\tend \r\n\r\n\twhile fib_array.length < number \r\n\t\tfib_array[fib_array.length] = fib_array[-1] + fib_array[-2]\r\n\tend\r\n\treturn fib_array\r\nend",
"def sum_of_even_fibonaccis(limit)\n\n holder = [1,2]\n\n while ( holder[-1] + holder[-2] ) < limit\n holder << holder[-1] + holder[-2]\n end\n\n return holder.select { |n| n.even? }.reduce(:+)\n\nend",
"def cool_fib(number)\n (0..number).inject([1,0]) {|i_arr| [i_arr.last, i_arr.first + i_arr.last]}.first\nend",
"def fib(array, num)\n (num-2).times do |x|\n array.push((array[-1] + array[-2]))\n end\n return array[num-1] \nend",
"def fib_test(num)\n\n return 1 if num == 1\n return 1 if num == 2\n arr = [1, 1]\n (3..num).map {|n| arr << fib_num(n-1) + fib_num(n-2) }\n # next_num = fib_num(num-1) + fib_num(num-2)\n # fib_test(num-1) + [next_num]\nend",
"def fibonacci_sequence(limit)\n fib_seq = [1,2]\n i = 1\n until fib_seq[i] + fib_seq[i-1] > limit\n fib_seq.push(fib_seq[i] + fib_seq[i-1])\n i += 1\n end\n\n return fib_seq\nend",
"def fibonacci(num)\n if num == 0\n return 0\n end\n array = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n array[num - 1] + fibonacci(num - 2)\nend",
"def Fibonacci_max()\n\ts = [1,1]\n\tputs s\n\tx = s.last\n\teven_sum = 0\n\twhile x < 4000000 \n\t\tc = s.count\n\t\tn = s[c-2]+s[c-1]\n\t\ts.push(n)\n\t\teven_sum = even_sum + n if n%2 == 0\n\t\tx = s.last\n\tend\t\n\ts.delete(s.last)\n\tputs even_sum\n\nend",
"def fibonacci number\n sequence = []\n a = 1\n b = 1\n while true\n sequence << b\n newa = b\n b = a+b\n a = newa\n break if b > number\n end\n sequence\nend",
"def fib(n)\n fib_arr = [0, 1] # Add stuff to arr so that we can get [-2], [-1] index later\n i = 0\n while i < n - 2 # The -2 is to account for the 2 items already in fib_arr\n fib_term = fib_arr[-2] + fib_arr[-1]\n fib_arr << fib_term\n i += 1\n end\n return fib_arr\nend",
"def fibs(num)\n return [] if num == 0\n return [0] if num == 1\n\n fibs = [0, 1]\n \n while fibs.count < num\n fibs << fibs[-1] + fibs[-2]\n end\n\n fibs\nend",
"def fibs(num)\n return [] if num == 0\n return [0] if num == 1\n\n fibs = [0, 1]\n while fibs.count < num\n fibs << fibs[-1] + fibs[-2]\n end\n\n fibs\nend",
"def fibonacci(number_output)\n fibonacci=[1] #default with only one number\n if number_output > 1\n fibonacci << 1 #second digit in fibonnacci sequence\n if number_output > 2\n #already has two numbers in array\n (number_output-2).times do |count|\n fibonacci << fibonacci[-1] + fibonacci[-2]\n end\n end\n end\n print fibonacci\nend",
"def even_fib_sum(array)\n# finds sum of array's even-valued terms\n array.select{ |i| i.even? }.reduce(&:+)\nend",
"def fib(i)\r\n arr = [0]\r\na = 0\r\nb = 1 \r\nif i >= 1 \r\narr << 1 \r\nend \r\nwhile arr.length < i \r\n if i > 1 \r\n c = a + b \r\n arr << c \r\n a = b \r\n b = c \r\n end \r\nend \r\np arr \r\nend",
"def iter_fib(n)\n arr=[0,1]\n while arr.length < n\n arr << arr[-1] + arr[-2]\n end\n arr\nend",
"def is_fibonacci?(num)\n fibonacci_sequence = [0, 1] \n i = 1\n while i <= num #1 is less than monster num\n previous_num = fibonacci_sequence[-2] \n next_num = fibonacci_sequence[-1] \n sum = previous_num + next_num\n fibonacci_sequence << sum\n i = i + previous_num\n end\n p fibonacci_sequence\n if fibonacci_sequence.include?(num) \n p true\n else\n p false\n end \nend"
] |
[
"0.7869513",
"0.762418",
"0.74886507",
"0.74170476",
"0.7282167",
"0.72431725",
"0.7222658",
"0.72156733",
"0.7176839",
"0.7012384",
"0.6919703",
"0.6915713",
"0.6906009",
"0.69046134",
"0.6883087",
"0.6873593",
"0.68718475",
"0.6855647",
"0.68548",
"0.68377537",
"0.6798123",
"0.6782961",
"0.6768961",
"0.6757787",
"0.67448384",
"0.6736521",
"0.67339146",
"0.6714327",
"0.67107964",
"0.6709866",
"0.6707479",
"0.6697185",
"0.6694449",
"0.6692156",
"0.6680049",
"0.6668567",
"0.66586465",
"0.66575205",
"0.6633816",
"0.6612787",
"0.6604644",
"0.6600325",
"0.65939915",
"0.65832794",
"0.65829635",
"0.657838",
"0.6572556",
"0.656879",
"0.6564703",
"0.6562429",
"0.65601856",
"0.6552093",
"0.6547328",
"0.65395117",
"0.65356964",
"0.65292263",
"0.65274066",
"0.6518887",
"0.6514406",
"0.651212",
"0.65093297",
"0.6506271",
"0.6503701",
"0.6502632",
"0.64937544",
"0.64919496",
"0.64894915",
"0.64894456",
"0.6485584",
"0.64725876",
"0.6468389",
"0.6465763",
"0.64598143",
"0.64589727",
"0.64511657",
"0.644092",
"0.64399797",
"0.6433558",
"0.6432471",
"0.6430695",
"0.6429908",
"0.6429554",
"0.64289933",
"0.6424952",
"0.64190894",
"0.64183486",
"0.64054626",
"0.6404411",
"0.6402458",
"0.6395043",
"0.6394708",
"0.63934207",
"0.6391451",
"0.63819987",
"0.6379991",
"0.63792986",
"0.63757676",
"0.63738585",
"0.63720596",
"0.63652885"
] |
0.7086137
|
9
|
def skills user_skills = object.skills.collect do |skill| user_skill = skill end end
|
def liked_users
users = object.liked_users.collect do |liked_user|
# user = User.find_by(id: liked_user.liked_user_id)
# user.attributes.except!("created_at", :updated_at, :email)
user = User.select(:id, :name, :gender, :age, :bio).find_by(id: liked_user.liked_user_id)
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def skills\n\t\t[]\n\tend",
"def set_user\n @user = User.find(params[:id])\n @skills = Skill.all\n @my_skills = @user.skills.all.map { |k| k[:name] }\n end",
"def find_skills\n @user = User.find(params[:id])\n @user_skill = UserSkill.where(\"user_id = @user.id\")\n end",
"def get_actor_skills(actor)\n return actor.skills.clone\n end",
"def skillsNeeded\n\t\t[]\n\tend",
"def get_skills_with_scores \n self.skills.map do |skill|\n score = skill.grades.find_by(user_id: self.id).score\n {skill: skill, score: score}\n end\n end",
"def all_skills\n self.skills.map(&:name).join(', ')\n end",
"def all_skills\n self.skills.map(&:name).join(\", \")\n end",
"def index\n @skills = current_user.skills.all\n end",
"def skills_view(skills)\n skills.map { |skill| skill_view(skill) }\n end",
"def skill_tags\n return @skill_tags\n end",
"def get_skills_with_scores\n self.skills.map do |skill|\n #need to figure out how to get the score of the grade\n #grade user_id, skill_id, score\n score = skill.grades.find_by(user_id: self.id).score \n {skill: skill, score: score}\n end\n end",
"def blue_magic_skills\n @skills.select { |id| $data_skills[id].blue_magic }\n end",
"def index\n @skills_users = SkillsUser.all\n end",
"def skills\n pers_all = (!$game_persistent_skills[0].nil? ? $game_persistent_skills[0] : [])\n pers_class = (!$game_persistent_skills[@class_id].nil? ? $game_persistent_skills[@class_id] : [])\n pers_subclass = (!$game_persistent_skills[@subclass_id].nil? ? $game_persistent_skills[@subclass_id] : [])\n (@skills | added_skills | pers_all | pers_class | pers_subclass).uniq.sort.collect {|id| $data_skills[id] }\n end",
"def index\n @user_skills = UserSkill.all.where(user_id: current_user)\n @result = @user_skills\n @result_first = @user_skills.first\n end",
"def skills_tab\n skill_bonuses = @character.skill_bonuses.select_ability_total_bonus.select_skill_name.joins(:skill).joins(:ability_bonus)\n @insight = skill_bonuses.insight\n @perception = skill_bonuses.perception\n @skill_bonuses = skill_bonuses.sort_by(&:fr_name)\n @klass_choosable_skill_bonus = @character.klass.try(&:choosable_skills_to_a)\n end",
"def initialize\n self.skills = [] \nend",
"def set_skills_user\n @skills_user = SkillsUser.find(params[:id])\n end",
"def map_skills_to_users\n puts 'Giving Users a random set of Skills'\n\n skills = Skill.all\n locations_skills_users = []\n User.find_each do |user|\n #generates a random number (between 1 and 3) of skills per person, and gives a random proficiency level\n max_num_skills = 3\n user_skills = Set.new\n (1..rand(1..max_num_skills)).each do\n random_skill = skills.sample\n user_skills.include?(random_skill) ? next : user_skills.add(random_skill)\n\n\n random_proficiency_level = rand(1..5)\n locations_skills_users << LocationsSkillsUsers.new(location_id: user.location.id, skill_id: random_skill.id,\n user_id: user.id, proficiency_level: random_proficiency_level)\n end\n end\n LocationsSkillsUsers.import(locations_skills_users)\n end",
"def get_students \n User.joins(learnables: {skill: {teachables: :user}}).where(\"users_users_skills.id = ? and users.id != ?\", id, id).distinct\n end",
"def get_new_skills(level)\n self.skills.select do |skill|\n skill.min_level == level\n end\n end",
"def get_profile_skills(wrapper)\n profile_skills = find_elements PROFILE_SKILLS_LOCATOR, wrapper\n get_skills profile_skills\n end",
"def index\n\t@skills = Skill.all\n end",
"def index\n @computer_skills = current_user.computer_skills.all\n @computerSkillList = ComputerSkillList.all\n @skillLevel = SkillLevel.all\n end",
"def proficiency_for(skill)\n SkillsUser.find_by_user_id_and_skill_id(self.id, skill.id).skill_level\n end",
"def user_tags\n return @user_tags\n end",
"def set_user_skill\n @user_skill = UserSkill.find_by(id: user_skill_params[:user_skill_id])\n end",
"def students\n users.students\n end",
"def set_user_skill\n @user_skill = UserSkill.find(params[:id])\n end",
"def convert_all_skill\n item_json = @data.collect { |item| convert_single_skill(item) }\n return item_json\n end",
"def index\n @skills = Skill.all\n skills = Skill.all.map { |skill| [skill.name, skill.id] }\n @options = skills.unshift(['指定なし', nil])\n\n if params[:skill_id].present?\n @users = User.joins(:skills).where(skills: { id: params[:skill_id] })\n else\n @users = User.all\n end\n end",
"def get_team_members\n team_members = []\n self.students.each do |student|\n team_members.append(student.user)\n end\n return team_members\n end",
"def skill_bonus(_skill)\n\t\tbonus = nil\n\t\t@abilities.each do |ability|\n\t\t\tb = ability.skill_bonus(_skill, proficiency_bonus)\n\t\t\tbonus = b if b != nil\n\t\tend\n\t\tbonus\n\tend",
"def get_skills(locator, freelancer)\n find_all(locator, freelancer).map {|skill| skill.text}\n end",
"def index\n @myskills = Myskill.all\n end",
"def users\n recipes.map {|recipe| recipe.user}\n end",
"def index\n @skills = @user.skills\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @skills }\n end\n end",
"def students\n course_enrollments.where(course_role: CourseRole.student).map(&:user)\n end",
"def students\n users\n end",
"def skill_tags=(value)\n @skill_tags = value\n end",
"def index\n @current_skills = CurrentSkill.all\n end",
"def index\n @skill_user_profiles = SkillUserProfile.all\n\n render json: @skill_user_profiles\n end",
"def index\n @skills = Skill.all\n end",
"def index\n @skills = Skill.all\n end",
"def list_skills\n\t\trender json: Skill.where(language_id: params[:language_id]).to_json\n\tend",
"def index\n @desired_skills = DesiredSkill.all\n end",
"def init_skills\n @skills = Array.new(4) { |index| Summary_Skill.new(@viewport, index) }\n end",
"def get_first_n_skills(n)\n return '' if self.skill_ids.blank?\n self.skills.take(n).collect(&:name).join(', ')\n # @skills = Rails.cache.fetch(\"skills-#{self.id}-#{n}\", expires_in: 1.hours) do\n # self.skills.take(n).collect(&:name).join(', ')\n # end\n # return @skills\n end",
"def show\n @user = User.includes(:skill_tags,:industry_tags).find(params[:id])\n \n end",
"def skills\n respond_with get_tags_for_contexts([\"skills\", \"reject_skills\"], params[:exclude_tags])\n end",
"def pupils\n return [] unless self.is_teacher\n return User.where(\"teacher_id = ? \",self.id)\n end",
"def currentStudents\n @users = User.all\n end",
"def students\n self.boating_tests.collect{|test| test.student} \n end",
"def user_with_proficiency(skill_level)\n skill = SkillsUser.where(skill_level: skill_level, skill_id: self.id).first\n user_id = skill.user_id\n User.find_by_id(user_id)\n end",
"def laughers \n self.funnies.map {|funny| funny.user_id}\n end",
"def my_followers_mottos \n BloodOath.all.map{|bloodoath|bloodoath.follower.life_motto}\n end",
"def index\n @profession_skills = ProfessionSkill.all\n end",
"def users\n self.user_cards.map do |card|\n card.user\n end\n end",
"def pick_skills_for_lilly\n assigned_skills = []\n unassigned_skills = []\n unless params[:sp_id].nil? or params[:sp_id].blank?\n assigned_skills = ServiceProvider.find(params[:sp_id]).skills.collect {|e| e.skill}\n unassigned_skills = Physical::Liviaservices::SkillType.find(:all).find_all {|e| !assigned_skills.include?(e)}\n end\n\t\tsp_list = ServiceProvider.find(:all)\n sp_id = params[:sp_id]\n\t\trender :partial => \"assign_skill\", :locals=> {:sp_list=>sp_list, :sp_id=>sp_id, :assigned_skills=>assigned_skills,:unassigned_skills=>unassigned_skills}\n\tend",
"def skills(id={}, options={})\n options = parse_id(id, options)\n path = \"#{profile_path(options, false)}/skills\"\n get(path, options)\n end",
"def users\n my_recipe_cards.map do |recipecard|\n recipecard.user\n end\n end",
"def risky_users\n return @risky_users\n end",
"def burned\n self.spicies.map {|spicy| spicy.user_id}\n end",
"def index\n @culinary_skills = CulinarySkill.all\n end",
"def personalities\r\n villagers.map{ |villager| villager.personality}\r\n end",
"def find_my_students \n User.joins(learnables: {skill: {teachables: :user}}).where(\"users_relationships.id = ? and users.id != ?\", id, id).distinct\n end",
"def getUserList\n @userList\n end",
"def computed_skills\n skills_hash = Hash[skills_count] # {\"générosité\"=>1, \"passion\"=>2}\n wanted_skills_hash = Hash[wanted_skills.map { |s| [s.name, 0] }] # {\"jonglage\"=>0, \"passion\"=>0}\n wanted_skills_hash.merge(skills_hash).except(*unwanted_skills.map(&:name)) # {\"générosité\"=>1, \"jonglage\"=>0}\n end",
"def profils()\n return @profils\n end",
"def index\n @skill_levels = SkillLevel.all\n end",
"def users\n recipe_cards.map do |r|\n r.user\n end\n end",
"def merge_skills(skills, newSkill)\n\n if newSkill!=\"\"\n skills = skills + \" \" + newSkill \n end\n\n return skills\n end",
"def get_talents\n\n # skills = [ self.skill_mandatory1, self.skill_mandatory2, self.skill_mandatory3,\n # self.skill_elective1, self.skill_elective2, self.skill_elective3 ]\n\n talents = {}\n\n # skills.each do |skill|\n # # TODO CHECK FOR RANDOM/CAREER SKILL\n # talents[skill] = Talent.where( skill: skill ).find_each\n # end\n\n talents\n\n end",
"def users\n\t\tproficiencies_by_type(\"User\")\n\tend",
"def get_users_added_interest \n\n users = self.adding_users \n\nend",
"def my_followers_motto\n my_followers.collect {|bloodoath| bloodoath.follower.life_motto}\n end",
"def data\n GameData::Skill[@id]\n end",
"def robotags\n object.tags User.super_id\n end",
"def user_battles\n @battles = current_user.battles\n end",
"def users\n self.recipe_cards.map {|recipe_card| recipe_card.user}\n end",
"def update_skills(pokemon)\n pokemon.skills_set.compact!\n @skills.each_with_index do |skill_stack, index|\n skill_stack.data = pokemon.skills_set[index]\n end\n end",
"def roles\n # rocking this in memory because eager-loading\n roles = object.paper_roles.select { |role|\n role.user_id == scoped_user.id\n }.map(&:description)\n roles << \"My Paper\" if object.user_id == scoped_user.id\n roles\n end",
"def users\n return @users_array\n \tend",
"def differentiat_users_on_skills(users, work_subtype, work_subtype_complexity = nil)\n skill_users,other_users=[],[]\n for user in users\n if work_subtype_complexity\n complexity = user.work_subtype_complexities.select{|c|c.work_subtype_id==work_subtype.id}.first\n if complexity && complexity.complexity_level >= work_subtype_complexity.complexity_level\n skill_users << user\n else\n other_users << user if user\n end\n elsif user && user.work_subtypes.include?(work_subtype)\n skill_users << user\n else\n other_users << user if user\n end\n end\n @users_select = [[\"-------Skilled Users-------\",\"\"]]\n @users_select += skill_users.collect {|u| [ u.full_name, u.id ]}\n @users_select << [\"No skilled User\",\"\"] if skill_users.blank?\n @users_select << [\"-------Other Users-------\",\"\"]\n @users_select += other_users.collect {|u| [ u.full_name, u.id ]}\n end",
"def active_students\n Student.where(:user_id => id).all\n end",
"def users_enrolled\r\n @users_enrolled\r\n end",
"def get_students\n StudentInCourse.where(:course_id => id).collect(&:user_id)\n end",
"def student_array\n @students1 = []\n @selected_students = User.only_students\n @students1 << @selected_students\n end",
"def index\n @skill_categories = SkillCategory.includes(:skills)\n # @skills = Skill.all\n end",
"def index\n @special_skills = SpecialSkill.all\n end",
"def index\n @s_skills = SSkill.all\n end",
"def add_skills(skill_names,created_by_id)\r\n job_seeker = JobSeeker.find(created_by_id)\r\n JobSeekerProficiency.delete_all(\"job_seeker_id = '#{self.id}'\")\r\n \r\n for skill in skill_names\r\n\r\n skill_split = skill.split(\"__\");\r\n skill_obj = Proficiency.find_by_name(skill_split[0])\r\n if skill_obj.nil?\r\n skill_obj = Proficiency.create({:name=>skill_split[0],:created_by=>created_by_id,:activated=>\"0\"})\r\n end\r\n\r\n JobSeekerProficiency.create!(:job_seeker_id => created_by_id, :proficiency_id => skill_obj.id, :education_id => skill_split[1].split(\"_\")[0], :skill_id => skill_split[2].split(\"_\")[0])\r\n\r\n end\r\n end",
"def call\n count_skill_users\n end",
"def find_skill_list(doc)\n\t\tskill_list = Array.new\n\t\tdoc.xpath('//*[@id=\"skills-list\"]/li').each do |li|\n\t\t\tskill = li.xpath('./span/text()').to_s.strip\n\t\t\tfixed_skill = skill.gsub(/\\s+/, ' ')\n\t\t\t#puts \"skill #{skill}\"\n\t\t\tskill_list << fixed_skill\n\t\tend\n\t\treturn skill_list\n\tend",
"def show\n @skill_array = []\n @people.skill_counts.each do |skill_count|\n hash = {:text => skill_count.name, :weight => skill_count.taggings_count, :link => \"/tags/#{skill_count.name}\"}\n @skill_array.push hash\n end\n end",
"def users\n self.triples.map(&:first)\n end",
"def users\n users_arr = RecipeCard.all.select do |recipe_card_ob|\n #binding.pry\n recipe_card_ob.recipe == self\n end\n users_arr.map do |user_ob|\n #binding.pry\n user_ob.user\n end\nend",
"def index\n @crew_skills = CrewSkill.all\n end",
"def index\n @skill_lists = SkillList.all\n end",
"def index\n @opening_skills = OpeningSkill.all\n end"
] |
[
"0.78938305",
"0.78287256",
"0.7669298",
"0.73693365",
"0.7175361",
"0.71368074",
"0.7071474",
"0.70691925",
"0.6984617",
"0.68977475",
"0.6890607",
"0.6882244",
"0.6812113",
"0.6764663",
"0.67484546",
"0.6596831",
"0.65946275",
"0.6462516",
"0.6448141",
"0.6298137",
"0.6286424",
"0.62674725",
"0.6138981",
"0.61349386",
"0.6117659",
"0.6094896",
"0.6079722",
"0.6061837",
"0.603891",
"0.6005744",
"0.60020626",
"0.59992063",
"0.5987455",
"0.5968438",
"0.5965315",
"0.5964133",
"0.59509915",
"0.5937663",
"0.592278",
"0.59198684",
"0.59091175",
"0.5906996",
"0.58934146",
"0.58922",
"0.58922",
"0.5880338",
"0.5869778",
"0.58675265",
"0.5862008",
"0.58596367",
"0.58419174",
"0.58387256",
"0.5819153",
"0.5812129",
"0.5807204",
"0.57875234",
"0.5785117",
"0.5770225",
"0.5767787",
"0.5754378",
"0.57533354",
"0.57261914",
"0.57229304",
"0.57221913",
"0.5703463",
"0.57021064",
"0.5692116",
"0.56897724",
"0.5685205",
"0.5684309",
"0.5680288",
"0.5675914",
"0.56743574",
"0.56656677",
"0.565777",
"0.5643882",
"0.5631783",
"0.5625402",
"0.56230897",
"0.562012",
"0.56157184",
"0.56152254",
"0.5614745",
"0.559858",
"0.55940384",
"0.5592236",
"0.5587219",
"0.55870736",
"0.5570846",
"0.55680627",
"0.5562536",
"0.55586594",
"0.5551186",
"0.55510265",
"0.5546474",
"0.5545451",
"0.5544164",
"0.55405635",
"0.553733",
"0.5515855",
"0.551532"
] |
0.0
|
-1
|
=begin :type x: Integer :rtype: Void =end
|
def push(x)
@stack.push(x)
@min_stack.push(x) if @min_stack.empty? || @min_stack[-1] >= x
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def x\n 0\n end",
"def x(n)\n end",
"def x\n end",
"def x\n end",
"def x\n end",
"def return_value(x)\n\tif x > 1\n\t\treturn x\n\telse\n\tend\nend",
"def x; 1; end",
"def x; end",
"def x; end",
"def x; end",
"def x; end",
"def x; end",
"def cnt; xparam(6); end",
"def get_x; \t\t@x \t\t\tend",
"def E\n @x += 1\n end",
"def s(x); 1; end",
"def plusOne(x)\n\tputs x+1\nend",
"def incr(x) x + 1 end",
"def number=(_arg0); end",
"def f(x)\n return x + 1\nend",
"def x \n @x \n end",
"def basic_3\n x_range = (1..255)\n sum = 0\n x_range.step(1) { |n| sum = sum + n; print \"New number: #{n} Sum: #{sum}\\n\"; }\n puts\nend",
"def x\n @x\n end",
"def l(x)\n 2 * ( x + 1 ) - @n\n end",
"def add_up(integer)\n x = 0\n for i in 1..integer\n x+=i\n end \n puts x\n return x\nend",
"def length(x)\r\n\t\tif @lista_exp != nil\r\n\t\t\tx = x +1\r\n\t\t\t@lista_exp.length(x)\r\n\t\telse\r\n\t\t\tx = x +1\r\n\t\t\treturn x\r\n\t\tend\r\n\tend",
"def x() @x end",
"def attack_bonus; xparam(0); end",
"def trg; xparam(9); end",
"def Integer(p0) end",
"def mystery(n)\n 0\nend",
"def handle(x, low, mid, high)\n case x\n when 0 then ''\n when 1 then low\n when 2 then low * 2\n when 3 then low * 3\n when 4 then low + mid\n when 5 then mid\n when 6 then mid + low\n when 7 then mid + low * 2\n when 8 then mid + low * 3\n when 9 then low + high\n else raise ArgumentError.new(\"passed #{x}\")\n end\n end",
"def W\n @x -= 1\n end",
"def xx\n raise InvalidInstruction\n end",
"def x=(x)\n end",
"def initialize() @x = 8 end",
"def x=(x)\n if !x.nil? && x < 0\n fail ArgumentError, 'invalid value for \"x\", must be greater than or equal to 0.'\n end\n\n @x = x\n end",
"def x=(x)\n if x.nil?\n fail ArgumentError, 'invalid value for \"x\", x cannot be nil.'\n end\n if x < 0\n fail ArgumentError, 'invalid value for \"x\", must be greater than or equal to 0.'\n end\n @x = x\n end",
"def num; end",
"def num; end",
"def x #getter method\n\t\t@x\n\tend",
"def square(x)\n\treturn 0 unless x.is_a? Integer\n\tx * x\nend",
"def f(x)\n x*(x+1)\nend",
"def mev; xparam(4); end",
"def foo (x)\nend",
"def xbonacci(starting_sequence, number_of_xbonacci_numbers_to_return)\n\nend",
"def mrg; xparam(8); end",
"def x!() @x.value end",
"def foo()\n x = 0\n p(x)\nend",
"def zero(x)\n if x <= 0\n puts x\n else \n puts x\n zero(x - 1)\n end\nend",
"def h(x)\n 2*x - @n - 1\n end",
"def signum x\n return -1 if x < 0\n return 1 if x > 0\n return 0\n end",
"def recursion(x)\n return \"HEYO!\" if x >= 5\n puts x\n recursion x += 1\nend",
"def recursion(x)\n return \"HEYO!\" if x >= 5\n puts x\n recursion x += 1\nend",
"def hrg; xparam(7); end",
"def magic_numbers(count)\nend",
"def int1; end",
"def int1; end",
"def set_psi x\n if x>200\n x=200\n elsif x<0\n x=0\n end\n @@psi = x\n end",
"def number; end",
"def number; end",
"def x=(_arg0); end",
"def x=(_arg0); end",
"def x=(_arg0); end",
"def counter_2(x)\n (1..x).each { |n| puts n }\nend",
"def setX(x) \n @x = x\n end",
"def foo=(x)\n @num=x\n end",
"def add_two(x)\n\tx + 5\nend",
"def recursion(x)\n return \"HEYO!\" if x >= 5\n puts x\n recursion(x += 1)\nend",
"def calc(x)\n puts x*3\nend",
"def consume_number; end",
"def sum_ints(x,y)\n\tx + y\nend",
"def txXX_(n, x); tdist(n, x); end",
"def *(x); end",
"def setX(x)\n @x = x\n end",
"def x=(_); end",
"def x=(_); end",
"def N\n @y += 1\n end",
"def addOne(x=5)\n\tputs x +_1\nend",
"def method(int)\n\t\treturn int*2\n\tend",
"def positive; end",
"def positive; end",
"def sum(int)\n int = 1\nend",
"def x=(value)\n end",
"def basic_1\n x_range = (1..255)\n x_range.step(1) { |n| print \"#{n} \" }\n puts\nend",
"def numbers(n)\n\nend",
"def get_signo(x)\n return [\"+1\", \"+1\", \"-1\"][x <=> 0].to_i\n end",
"def x2\n x + width\n end",
"def inc(n)\n n+1\nend",
"def integer_print_10\n 10.times do |x|\n puts x \n end \nend",
"def entry_num(x)\n if x < 1\n raise \"Invalid entry number!\"\n end\n if x > @list_of_positions.length()\n raise \"There are only #{@list_of_positions.length} entries\"\n end\n # 1-based\n x -= 1\n @current_iteration = x\n self.next()\n end",
"def up\n self.x = ((x-1)+10)%10\n end",
"def pixel_x; @x / PIXEL_WIDTH; end",
"def pixel_x; @x / PIXEL_WIDTH; end",
"def number_counting_seq(n)\r\n\r\nend",
"def no_bar\r\n\t return x \r\n\tend",
"def void0(*args)\n return 0\n end",
"def getX() \n @x \n end",
"def m(x) x end",
"def fun(x)\n puts x\nend",
"def factorial(x)\n\tres = 1\n\t# use a block that multiply the variable res by each value of the range\n\t(1..x).each { |i| res *= i }\n\treturn res\nend"
] |
[
"0.6999597",
"0.6869975",
"0.6671123",
"0.66127646",
"0.66127646",
"0.6536892",
"0.6503381",
"0.64305717",
"0.64305717",
"0.64305717",
"0.64305717",
"0.64305717",
"0.64080566",
"0.6362651",
"0.62267184",
"0.6217009",
"0.61672753",
"0.61467487",
"0.61237484",
"0.61100554",
"0.6021121",
"0.601926",
"0.5956549",
"0.5955247",
"0.59465015",
"0.59414476",
"0.5937001",
"0.5934482",
"0.59277934",
"0.59241533",
"0.59189767",
"0.59155303",
"0.5906098",
"0.5895665",
"0.5870541",
"0.5865828",
"0.58551997",
"0.5847181",
"0.58449984",
"0.58449984",
"0.5828979",
"0.5796989",
"0.5793323",
"0.5791201",
"0.5777426",
"0.57704544",
"0.57478136",
"0.5740434",
"0.57315797",
"0.5710468",
"0.57078725",
"0.56957597",
"0.5682544",
"0.5682544",
"0.5680041",
"0.56781733",
"0.56742644",
"0.56742644",
"0.56671417",
"0.5665162",
"0.5665162",
"0.56632465",
"0.56632465",
"0.56632465",
"0.5640186",
"0.56381124",
"0.5629507",
"0.5623716",
"0.55770963",
"0.5573533",
"0.557016",
"0.5563564",
"0.5557547",
"0.5554134",
"0.5533118",
"0.55312335",
"0.55312335",
"0.5521107",
"0.5519872",
"0.5515735",
"0.5511857",
"0.5511857",
"0.55113196",
"0.5506665",
"0.55021083",
"0.55011463",
"0.5496936",
"0.549354",
"0.54889727",
"0.54709125",
"0.54660314",
"0.546287",
"0.5445789",
"0.5445789",
"0.54448044",
"0.54230034",
"0.5422089",
"0.5401106",
"0.5393573",
"0.5390772",
"0.538248"
] |
0.0
|
-1
|
=begin :rtype: Void =end
|
def pop()
@min_stack.pop() if @min_stack[-1] == @stack[-1]
@stack.pop()
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def end; end",
"def end; end",
"def end; end",
"def void\n \"Void\"\n end",
"def incomplete\r\n\r\n end",
"def begin; end",
"def void()\n nil\n end",
"def complete?; end",
"def handle; end",
"def begin() end",
"def done; end",
"def suivre; end",
"def end() end",
"def schubert; end",
"def end\n end",
"def end\n end",
"def proceed!; end",
"def proceed!; end",
"def probers; end",
"def private; end",
"def ...\nend",
"def complete\n nil\n end",
"def complete\n nil\n end",
"def returns; end",
"def void(val)\n # Void does nothing\n self\n end",
"def finished; end",
"def do()\r\n\tend",
"def success; end",
"def success; end",
"def ibu; end",
"def perform; end",
"def perform; end",
"def final; end",
"def pass; end",
"def pass; end",
"def operation; end",
"def operations; end",
"def operations; end",
"def perform\n \n end",
"def end\n end",
"def finished=(_arg0); end",
"def complete!\n raise NotImplementedError\n end",
"def villian; end",
"def execute; end",
"def execute; end",
"def reap; end",
"def guct\n end",
"def zuruecksetzen()\n end",
"def process; end",
"def process; end",
"def process; end",
"def process; end",
"def process; end",
"def process; end",
"def process; end",
"def process; end",
"def call; end",
"def call; end",
"def call; end",
"def call; end",
"def call; end",
"def call; end",
"def call; end",
"def call; end",
"def done?; end",
"def _end!; end",
"def signature; end",
"def signature; end",
"def signature; end",
"def signature; end",
"def signature; end",
"def signature; end",
"def signature; end",
"def signature; end",
"def signature; end",
"def signature; end",
"def r; end",
"def r; end",
"def at_end; end",
"def complete\n end",
"def void0(*args)\n return 0\n end",
"def call() end",
"def end_field=(_arg0); end",
"def nothing; end",
"def end_point=(_arg0); end",
"def run; end",
"def run; end",
"def run; end",
"def run; end",
"def run; end",
"def run; end",
"def run; end",
"def run; end",
"def run; end",
"def diagnostic; end",
"def returns=(_arg0); end",
"def finish; end",
"def finish; end",
"def finish; end",
"def finish; end",
"def finish; end"
] |
[
"0.7076286",
"0.7076286",
"0.7076286",
"0.7042917",
"0.7006871",
"0.6946303",
"0.6753771",
"0.6736687",
"0.6684566",
"0.66822404",
"0.66349524",
"0.66205233",
"0.6619803",
"0.65918946",
"0.65669674",
"0.65669674",
"0.6561827",
"0.6561827",
"0.65405864",
"0.6527296",
"0.6500946",
"0.6486529",
"0.6486529",
"0.64508057",
"0.64462537",
"0.6422791",
"0.642053",
"0.6416459",
"0.6416459",
"0.6404361",
"0.6404128",
"0.6404128",
"0.6400557",
"0.6384068",
"0.6384068",
"0.63782644",
"0.63600796",
"0.63600796",
"0.63582593",
"0.63263935",
"0.6324234",
"0.6321326",
"0.63052845",
"0.629552",
"0.629552",
"0.6294288",
"0.6286154",
"0.6284205",
"0.6278275",
"0.6278275",
"0.6278275",
"0.6278275",
"0.6278275",
"0.6278275",
"0.6278275",
"0.6278275",
"0.6264103",
"0.6264103",
"0.6264103",
"0.6264103",
"0.6264103",
"0.6264103",
"0.6264103",
"0.6264103",
"0.620939",
"0.6189846",
"0.6184386",
"0.6184386",
"0.6184386",
"0.6184386",
"0.6184386",
"0.6184386",
"0.6184386",
"0.6184386",
"0.6184386",
"0.6184386",
"0.6180728",
"0.6180728",
"0.6179174",
"0.61714935",
"0.61674386",
"0.61650586",
"0.6165017",
"0.6160322",
"0.6157941",
"0.61551565",
"0.61551565",
"0.61551565",
"0.61551565",
"0.61551565",
"0.61551565",
"0.61551565",
"0.61551565",
"0.61551565",
"0.6150566",
"0.61480886",
"0.6144247",
"0.6144247",
"0.6144247",
"0.6144247",
"0.6144247"
] |
0.0
|
-1
|
=begin :rtype: Integer =end
|
def top()
@stack[-1]
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def range; end",
"def range; end",
"def range; end",
"def length\n @end - @start + 1\n end",
"def length\n @end - @start\n end",
"def start_num\n return @start_num\n end",
"def length\r\n return self.stop - self.start + 1\r\n end",
"def length\n return self.stop - self.start + 1\n end",
"def length\n return self.stop - self.start + 1\n end",
"def size\n\t\tlast - first + (exclude_end? ? 0 : 1)\n\tend",
"def count()\n return @i\n end",
"def m_range\r\n end",
"def offset; end",
"def offset; end",
"def offset; end",
"def num; end",
"def num; end",
"def size\n @range.size\n end",
"def ig\n\t\tig_ind.reduce(0, :+)/ig_ind.size\n\tend",
"def Integer(p0) end",
"def begin_pos; end",
"def length\n stop - start + 1 unless coverage == 0\n end",
"def size()\r\n\t\tif num1 != nil\r\n\t\t\tif signo1 != nil\r\n\t\t\t\tif signo2 != nil\r\n\t\t\t\t\treturn -@num2.valor.to_s().to_i()+@num1.valor.to_s().to_i() + 1\r\n\t\t\t\telse\r\n\t\t\t\t\treturn @num2.valor.to_s().to_i()+@num1.valor.to_s().to_i() + 1\r\n\t\t\t\tend\r\n\t\t\telsif signo2 != nil\r\n\t\t\t\treturn -@num2.valor.to_s().to_i()+@num1.valor.to_s().to_i() + 1\r\n\t\t\telse\r\n\t\t\t\treturn @num2.valor.to_s().to_i()-@num1.valor.to_s().to_i()\t+ 1\r\n\t\t\tend\r\n\t\tend\t\r\n\tend",
"def outidx\n @index_range.begin\n end",
"def get_integer_value\n\t\tend",
"def num()\n\t\treturn @num\n\tend",
"def to_i()\n #This is a stub, used for indexing\n end",
"def end; self.begin + self.size - 1; end",
"def length()\n #This is a stub, used for indexing\n end",
"def number_of_values\n Integer((@upper - @lower) / @step) + 1\n end",
"def span\r\n if @range.none?\r\n 0\r\n else\r\n @range.max - @range.min + 1\r\n end\r\n end",
"def to_i()\n #This is a stub, used for indexing\n end",
"def total\n 2**64 - 1\n end",
"def starting_position; end",
"def length()\n #This is a stub, used for indexing\n end",
"def last_i\n size - 1\n end",
"def number_returned; 0; end",
"def block_count; @data[17].to_i; end",
"def count; @value.size; end",
"def number_indents\n 0\n end",
"def total_set\n @field.each_byte.inject(0) { |a, byte| (a += 1; byte &= byte - 1) while byte > 0 ; a }\n end",
"def zero_or_more\n -1\n end",
"def sequence_number; end",
"def range_start; range.first; end",
"def length() end",
"def length() end",
"def length() end",
"def length() end",
"def count; end",
"def count; end",
"def count; end",
"def range\n @range ||= 0.upto(@limit)\n end",
"def to_i(start = 0, rel_to = nil)\n if rel_to == :self\n 0\n else\n @address - rel_to.to_i + (@reloc ? start : 0)\n end unless dummy?\n end",
"def seuil()\n\t\treturn 0\n\tend",
"def number_counting_seq(n)\r\n\r\nend",
"def begin_pos=(_); end",
"def y(from = 0)\n self[1,2].to_i - 1 + from\n end",
"def end_result_number\n start_result_number + (results.size) - 1\n end",
"def min\n @range.begin\n end",
"def size\n last - first\n end",
"def length\n length = 0; each {length += 1}; length\n end",
"def range(input); end",
"def range_correct_index at\n index = at\n index = self.length + at if at < 0\n raise \"index must be positive , not #{at}\" if (index <= 0)\n raise \"index too large #{at} > #{self.length}\" if (index > self.length)\n return index\n end",
"def to_i\n\t\t\t(a1.to_i << 96) + (a2.to_i << 64) + (a3.to_i << 32) + a4.to_i\n\t\tend",
"def number; end",
"def number; end",
"def ntCount\n return @ntIndex.length\n end",
"def length_in(range)\n (self & range)&.length || 0\n end",
"def begin(p0) end",
"def begin\n empty? ? 0 : first.begin\n end",
"def sign_count; end",
"def n\n x.size\n end",
"def length; count end",
"def sum; end",
"def lengthOfSequence(element)\n\nend",
"def length\n @count\n end",
"def length(start_t, end_t, geores)\n return do_length(start_t, end_t, geores)\n end",
"def count=(_arg0); end",
"def current_length; end",
"def to_int() end",
"def to_int() end",
"def size() end",
"def size() end",
"def size() end",
"def size() end",
"def size() end",
"def size() end",
"def to_int\n end",
"def ndp_sum=(i); typecast i; end",
"def bc_count\n \t@generic.size + @initial.size + @final.size + @cyclic.size\n end",
"def length\n reduce(0) {|sum,_| sum + 1 }\n end",
"def length; end",
"def length; end",
"def length; end",
"def length; end",
"def length; end",
"def length; end",
"def length; end",
"def getNbRecompense\n return 0\n end",
"def upper_bound; end",
"def size_from_range(range)\n size = range.end - range.begin + 1\n raise NegativeRangeSpan, \"The resulting size for range #{range} is negative\" if size < 0\n size\n end"
] |
[
"0.68839365",
"0.68839365",
"0.68839365",
"0.6832226",
"0.6770915",
"0.65820575",
"0.6458765",
"0.64062536",
"0.64062536",
"0.6389018",
"0.6268534",
"0.62334067",
"0.61995095",
"0.61995095",
"0.61995095",
"0.6191786",
"0.6191786",
"0.6191563",
"0.6190707",
"0.61641645",
"0.61553586",
"0.61267126",
"0.6125403",
"0.60952806",
"0.6085276",
"0.6065244",
"0.6047411",
"0.6043025",
"0.6020434",
"0.600915",
"0.60025835",
"0.59879714",
"0.59836364",
"0.59807193",
"0.5980499",
"0.59706044",
"0.59556824",
"0.5949657",
"0.5945405",
"0.5942585",
"0.5941379",
"0.59285784",
"0.58926475",
"0.58844113",
"0.5877592",
"0.5877592",
"0.5877592",
"0.5877592",
"0.58666134",
"0.58666134",
"0.58666134",
"0.5866053",
"0.58639216",
"0.58622646",
"0.5836902",
"0.5834981",
"0.5828989",
"0.5825883",
"0.58251923",
"0.58213437",
"0.5805815",
"0.5799385",
"0.57860255",
"0.5778401",
"0.57703763",
"0.57703763",
"0.5769836",
"0.57683045",
"0.57671595",
"0.57573825",
"0.5757143",
"0.57537645",
"0.574803",
"0.57462865",
"0.5739271",
"0.57357603",
"0.57309836",
"0.5730078",
"0.5729926",
"0.5729287",
"0.5729287",
"0.5725265",
"0.5725265",
"0.5725265",
"0.5725265",
"0.5725265",
"0.5725265",
"0.57225573",
"0.5721215",
"0.5705846",
"0.57051116",
"0.5704157",
"0.5704157",
"0.5704157",
"0.5704157",
"0.5704157",
"0.5704157",
"0.5704157",
"0.5696494",
"0.56956005",
"0.56892717"
] |
0.0
|
-1
|
=begin :rtype: Integer =end
|
def get_min()
@min_stack[-1]
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def range; end",
"def range; end",
"def range; end",
"def length\n @end - @start + 1\n end",
"def length\n @end - @start\n end",
"def start_num\n return @start_num\n end",
"def length\r\n return self.stop - self.start + 1\r\n end",
"def length\n return self.stop - self.start + 1\n end",
"def length\n return self.stop - self.start + 1\n end",
"def size\n\t\tlast - first + (exclude_end? ? 0 : 1)\n\tend",
"def count()\n return @i\n end",
"def m_range\r\n end",
"def offset; end",
"def offset; end",
"def offset; end",
"def ig\n\t\tig_ind.reduce(0, :+)/ig_ind.size\n\tend",
"def size\n @range.size\n end",
"def num; end",
"def num; end",
"def Integer(p0) end",
"def begin_pos; end",
"def length\n stop - start + 1 unless coverage == 0\n end",
"def size()\r\n\t\tif num1 != nil\r\n\t\t\tif signo1 != nil\r\n\t\t\t\tif signo2 != nil\r\n\t\t\t\t\treturn -@num2.valor.to_s().to_i()+@num1.valor.to_s().to_i() + 1\r\n\t\t\t\telse\r\n\t\t\t\t\treturn @num2.valor.to_s().to_i()+@num1.valor.to_s().to_i() + 1\r\n\t\t\t\tend\r\n\t\t\telsif signo2 != nil\r\n\t\t\t\treturn -@num2.valor.to_s().to_i()+@num1.valor.to_s().to_i() + 1\r\n\t\t\telse\r\n\t\t\t\treturn @num2.valor.to_s().to_i()-@num1.valor.to_s().to_i()\t+ 1\r\n\t\t\tend\r\n\t\tend\t\r\n\tend",
"def outidx\n @index_range.begin\n end",
"def get_integer_value\n\t\tend",
"def num()\n\t\treturn @num\n\tend",
"def to_i()\n #This is a stub, used for indexing\n end",
"def end; self.begin + self.size - 1; end",
"def length()\n #This is a stub, used for indexing\n end",
"def number_of_values\n Integer((@upper - @lower) / @step) + 1\n end",
"def span\r\n if @range.none?\r\n 0\r\n else\r\n @range.max - @range.min + 1\r\n end\r\n end",
"def to_i()\n #This is a stub, used for indexing\n end",
"def total\n 2**64 - 1\n end",
"def starting_position; end",
"def length()\n #This is a stub, used for indexing\n end",
"def last_i\n size - 1\n end",
"def number_returned; 0; end",
"def block_count; @data[17].to_i; end",
"def count; @value.size; end",
"def number_indents\n 0\n end",
"def total_set\n @field.each_byte.inject(0) { |a, byte| (a += 1; byte &= byte - 1) while byte > 0 ; a }\n end",
"def zero_or_more\n -1\n end",
"def sequence_number; end",
"def range_start; range.first; end",
"def length() end",
"def length() end",
"def length() end",
"def length() end",
"def range\n @range ||= 0.upto(@limit)\n end",
"def to_i(start = 0, rel_to = nil)\n if rel_to == :self\n 0\n else\n @address - rel_to.to_i + (@reloc ? start : 0)\n end unless dummy?\n end",
"def count; end",
"def count; end",
"def count; end",
"def seuil()\n\t\treturn 0\n\tend",
"def number_counting_seq(n)\r\n\r\nend",
"def begin_pos=(_); end",
"def y(from = 0)\n self[1,2].to_i - 1 + from\n end",
"def min\n @range.begin\n end",
"def end_result_number\n start_result_number + (results.size) - 1\n end",
"def size\n last - first\n end",
"def length\n length = 0; each {length += 1}; length\n end",
"def range(input); end",
"def range_correct_index at\n index = at\n index = self.length + at if at < 0\n raise \"index must be positive , not #{at}\" if (index <= 0)\n raise \"index too large #{at} > #{self.length}\" if (index > self.length)\n return index\n end",
"def to_i\n\t\t\t(a1.to_i << 96) + (a2.to_i << 64) + (a3.to_i << 32) + a4.to_i\n\t\tend",
"def ntCount\n return @ntIndex.length\n end",
"def number; end",
"def number; end",
"def length_in(range)\n (self & range)&.length || 0\n end",
"def begin(p0) end",
"def begin\n empty? ? 0 : first.begin\n end",
"def sign_count; end",
"def n\n x.size\n end",
"def length; count end",
"def sum; end",
"def lengthOfSequence(element)\n\nend",
"def length\n @count\n end",
"def length(start_t, end_t, geores)\n return do_length(start_t, end_t, geores)\n end",
"def to_int() end",
"def to_int() end",
"def current_length; end",
"def count=(_arg0); end",
"def size() end",
"def size() end",
"def size() end",
"def size() end",
"def size() end",
"def size() end",
"def to_int\n end",
"def ndp_sum=(i); typecast i; end",
"def bc_count\n \t@generic.size + @initial.size + @final.size + @cyclic.size\n end",
"def length\n reduce(0) {|sum,_| sum + 1 }\n end",
"def length; end",
"def length; end",
"def length; end",
"def length; end",
"def length; end",
"def length; end",
"def length; end",
"def getNbRecompense\n return 0\n end",
"def upper_bound; end",
"def size_from_range(range)\n size = range.end - range.begin + 1\n raise NegativeRangeSpan, \"The resulting size for range #{range} is negative\" if size < 0\n size\n end"
] |
[
"0.6883764",
"0.6883764",
"0.6883764",
"0.68318415",
"0.67707014",
"0.6582689",
"0.645833",
"0.64058447",
"0.64058447",
"0.6388362",
"0.6267844",
"0.62336147",
"0.6198298",
"0.6198298",
"0.6198298",
"0.6191344",
"0.6191187",
"0.6190641",
"0.6190641",
"0.6163565",
"0.61551654",
"0.6125833",
"0.6125323",
"0.6095764",
"0.6085551",
"0.6065232",
"0.60468423",
"0.6042029",
"0.60188293",
"0.6009249",
"0.6003659",
"0.5987707",
"0.5983606",
"0.59802246",
"0.59785897",
"0.5969448",
"0.595372",
"0.59493744",
"0.59425366",
"0.5941633",
"0.59406036",
"0.5927211",
"0.5891871",
"0.58846664",
"0.5875135",
"0.5875135",
"0.5875135",
"0.5875135",
"0.5866378",
"0.5864577",
"0.58644915",
"0.58644915",
"0.58644915",
"0.5860918",
"0.5836488",
"0.58345044",
"0.58290654",
"0.5826333",
"0.58257115",
"0.5820722",
"0.58043593",
"0.5799245",
"0.578558",
"0.5779708",
"0.57698184",
"0.57693845",
"0.57693845",
"0.57684815",
"0.5767767",
"0.5757715",
"0.57555664",
"0.57526064",
"0.57454985",
"0.5744997",
"0.57371956",
"0.5734424",
"0.57303977",
"0.5729162",
"0.5729162",
"0.57279974",
"0.5727855",
"0.57228374",
"0.57228374",
"0.57228374",
"0.57228374",
"0.57228374",
"0.57228374",
"0.5722448",
"0.5720685",
"0.5706098",
"0.57036895",
"0.5701678",
"0.5701678",
"0.5701678",
"0.5701678",
"0.5701678",
"0.5701678",
"0.5701678",
"0.56947887",
"0.5694506",
"0.5689595"
] |
0.0
|
-1
|
reset the Sequence to its initial state
|
def reset
@index = -1
@element = nil
@value = nil
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def reset\n set InitialPosition\n end",
"def reset\n\t\tself.rs \t= 0\n\t\tself.ps \t= 0\n\t\tself.ss \t= 0\n\t\tself.gen\t= Random.new(SEED)\n\tend",
"def reset_state\n @state = nil\n end",
"def reset\n @current = nil\n @pos = 0\n end",
"def reset\n @position = 0\n @rotor_array = @reset_rotor.dup\n end",
"def reset\n clear\n @position = 0\n @current_index = 0\n end",
"def reset\n each(&:reset)\n self\n end",
"def reset\n end",
"def reset\n end",
"def reset\n # TODO\n end",
"def reset!\n initialize\n end",
"def reset\n end",
"def reset\n end",
"def reset\n end",
"def reset\n end",
"def reset\n # Empty, but subclasses will override this.\n end",
"def reset\n self\n end",
"def reset\n\t\t@r = 0\n\t\t@p = 0\n\t\t@t = 0\n\t\t@l = 0\n\t\t@s = 0\n\tend",
"def reset\n self.x, self.y, self.o = self.sequence.first\n end",
"def reset\n @current = 0\n @state = :stopped\n end",
"def reset()\n \n end",
"def reset\n super\n @first_iteration = true\n end",
"def reset\n end",
"def reset\n end",
"def reset\n\n end",
"def reset()\n #This is a stub, used for indexing\n end",
"def reset()\n #This is a stub, used for indexing\n end",
"def reset\n initialize\n setup\n end",
"def reset() end",
"def reset\n\n end",
"def reset\n setup\n end",
"def reset\n @state = :entry\n end",
"def reset ; end",
"def reset\n @value = nil\n end",
"def reset\n @count = 0\n end",
"def reset\n @value = nil\n @count = 0\n end",
"def reset\n\t\tend",
"def test_reset\n @sequence.reset\n @sequence.next\n assert_equal(@sequence.current, 5)\n end",
"def reset!\n end",
"def reset!\n end",
"def reset\n @number = nil\n end",
"def reset()\n end",
"def reset\n raise \"Not implemented\"\n end",
"def reset\n @rotor_array = @reset_rotor.dup\n end",
"def reset\n @offset = 0\n end",
"def reset; end",
"def reset; end",
"def reset; end",
"def reset; end",
"def reset; end",
"def reset; end",
"def reset; end",
"def reset; end",
"def reset; end",
"def reset; end",
"def reset; end",
"def reset; end",
"def reset; end",
"def reset; end",
"def reset; end",
"def reset; end",
"def reset; end",
"def reset; end",
"def reset\n dup.reset!\n end",
"def reset\n @source.each_value(&:reset)\n nil\n end",
"def reset\n @left_generator.reset\n @right_generator.reset\n\n nil\n end",
"def reset\n @array = nil\n end",
"def internal_reset(initial_value); end",
"def reset\n @hand = []\n @value = nil\n @status = \"unfinished\"\n end",
"def reset_start!\n @start = nil\n end",
"def reset\n \n end",
"def reset\n @crc = @init_crc\n end",
"def reset\n @current = 0\n @matched = false\n end",
"def reset\n\t\tself.gen = Random.new(SEED)\n\tend",
"def reset\n\t\tself.gen = Random.new(SEED)\n\tend",
"def reset()\n @x\n \n end",
"def reset!; end",
"def reset!; end",
"def reset!; end",
"def reset!; end",
"def reset_initial_version\n @initial_version = last_committed_sequence_number\n end",
"def reset\n\t\tdo_send('ARST 2')\n\tend",
"def reset\n @count = @options[:start]\n end",
"def resets; end",
"def reset!\n instance.reset!\n end",
"def reset!\n instance.reset!\n end",
"def reset\n @pointer = 0\n self\n end",
"def reset()\n @rand_count = 0\n @sideup = nil\n end",
"def reset\n invoke_on_reset_callbacks\n self\n end",
"def reset\n @prev_pos = @pos = 0\n @match = nil\n self\n end",
"def reset\n @attempt = 0\n end",
"def reset()\n raise NotImplementedError\n @lineno = 1\n\t\t@line_offset = 0\n @token_pos = 0\n end",
"def reset\n cleanup(true)\n end",
"def reset()\n\n\t\t@aChecksum = [ 0xFF, 0xFF ];\n\n\tend",
"def clearState()\n\t\t\t@_previous_state = @_state\n\t\t\t@_state = nil\n\t\tend",
"def reset\n @assigned = false\n end",
"def do_reset\n\t\t\n\t\t\t# Mark state as reset\n\t\t\t@reset = true\n\t\t\t\n\t\t\t# Revert text and palette\n\t\t\tself.text = nil \n\t\t\tself.palette = @palette_normal\t\t\t\n\t\tend",
"def reset\n @parsers = nil\n @transformer = nil\n @cache = nil\n end",
"def reset!\n executions.reset\n end",
"def reset\n API.finalize( @vm )\n commence\n @eof = false\n end",
"def initialize\n reset\n end"
] |
[
"0.74213105",
"0.74012727",
"0.7366204",
"0.73131",
"0.72967213",
"0.7280663",
"0.7239951",
"0.7237613",
"0.7237613",
"0.7229263",
"0.7212357",
"0.7146484",
"0.7146484",
"0.7146484",
"0.7146484",
"0.711822",
"0.7105732",
"0.707575",
"0.7070327",
"0.7061152",
"0.704653",
"0.7035812",
"0.7027884",
"0.7027884",
"0.702311",
"0.70228976",
"0.70228976",
"0.6997843",
"0.69951457",
"0.69940984",
"0.69803745",
"0.6973577",
"0.6959825",
"0.695761",
"0.6953838",
"0.69427633",
"0.69337213",
"0.69324094",
"0.69299513",
"0.69299513",
"0.6917472",
"0.6912117",
"0.6909055",
"0.69036156",
"0.690096",
"0.6875047",
"0.6875047",
"0.6875047",
"0.6875047",
"0.6875047",
"0.6875047",
"0.6875047",
"0.6875047",
"0.6875047",
"0.6875047",
"0.6875047",
"0.6875047",
"0.6875047",
"0.6875047",
"0.6875047",
"0.6875047",
"0.6875047",
"0.6875047",
"0.6872793",
"0.68700546",
"0.68364674",
"0.6827611",
"0.6815152",
"0.6813236",
"0.6811276",
"0.67809504",
"0.6780213",
"0.6774012",
"0.67719114",
"0.67719114",
"0.677089",
"0.67598945",
"0.67598945",
"0.67598945",
"0.67598945",
"0.6747033",
"0.671136",
"0.66939586",
"0.6691162",
"0.6687942",
"0.6687942",
"0.6676093",
"0.66754854",
"0.6668358",
"0.66668314",
"0.6663155",
"0.6642579",
"0.6637587",
"0.6637071",
"0.66311395",
"0.66253567",
"0.6621212",
"0.6612992",
"0.6588202",
"0.6579729",
"0.6573875"
] |
0.0
|
-1
|
The value of the next element in the Sequence. The sequence goes back to the first element if there are no more elements.
|
def next
if @elements and not @elements.empty?
@index = (@index + 1) % @elements.length
element = @elements[@index]
value = value_of(element)
@element, @value = element, value
end
@value
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def next\r\n next_values[0]\r\n end",
"def next\n next? ? @current + 1 : nil\n end",
"def next\n @next && @next.value\n end",
"def next()\n result = current\n @index += 1\n @got_next_element = false\n @next_element = nil\n result\n end",
"def next_value_for_sequence(sequence_name)\n %{#{sequence_name}.nextval}\n end",
"def next_number\n Sequence.next_val\n end",
"def next\n @proc.call(@value)\n ensure\n @value = @value.next\n end",
"def next_element\n\t\treturn next_element_of @current_node\n\tend",
"def next\n at(position + 1)\n end",
"def next\n self.offset(1)\n end",
"def peek\n @first.val\n end",
"def first\n @current = self.head if self.head\n @current.value rescue nil\n end",
"def next\n last? ? nil : locate + 1\n end",
"def next\n last? ? nil : @collection[index + 1]\n end",
"def nextval current\n if ::Integer === current\n current + 1\n else\n intval = current.to_i\n if intval.to_s != current.to_s\n (current[0].ord + 1).chr\n else\n intval + 1\n end\n end\n end",
"def next_sequence_number\n last_sequence_number ? last_sequence_number.next : 0\n end",
"def next_element; end",
"def next\n @next||=after.first\n end",
"def next(object)\n elements[elements.index(object) + 1]\n end",
"def next\n\t\tself + 1\n\tend",
"def next_sequence_value(sequence_name)\n FireRuby::Generator.new(sequence_name, @connection).next(1)\n end",
"def get_next()\n\t\t\treturn @next\n\t\tend",
"def next\n peek.tap { @position += 1 }\n end",
"def next()\n x = @arr[@i]\n @i += 1\n x\n end",
"def get_next()\n return @next_node\n end",
"def get_Next()\n \t return @outputs[\"Next\"]\n \tend",
"def get_Next()\n \t return @outputs[\"Next\"]\n \tend",
"def get_Next()\n \t return @outputs[\"Next\"]\n \tend",
"def get_Next()\n \t return @outputs[\"Next\"]\n \tend",
"def get_Next()\n \t return @outputs[\"Next\"]\n \tend",
"def get_Next()\n \t return @outputs[\"Next\"]\n \tend",
"def nextModVal()\r\n\t\ttemp = @valArray[@iterator]\r\n\t\t\r\n\t\tif @iterator == (@keyLength - 1)\r\n\t\t\t@iterator = 0\r\n\t\telse\r\n\t\t\t@iterator += 1\r\n\t\tend\r\n\t\t\r\n\t\treturn temp\r\n\tend",
"def next_element\n validates_possibility_of :next\n self.index += 1\n self.current\n end",
"def next_number\n self.to_a.size + 1\n end",
"def next_sequence_value(sequence_name)\n @connection.query(\"SELECT NEXT VALUE FOR #{sequence_name} FROM RDB$DATABASE\")[0][0]\n end",
"def advance\n @current += 1 unless at_end?\n return previous\n end",
"def peek_first\n raise 'No such element' if @size == 0\n @head.value\n end",
"def next\n (successors.length == 1) ? successors.first : nil\n end",
"def get_next\n\n if (@local_iterator)\n @local_iterator.get_next\n else\n raise \"No iterator defined! Cannot get next element\"\n end\n\n end",
"def next\n unless @push.nil?\n t = @push\n @push = nil\n return t\n end\n return nil if @input.nil?\n return nil if @input.size == 0\n return nil if @index >= @input.size\n\n t = @input[@index]\n @index += 1\n t\n end",
"def next\n @idx += 1\n if @seq[@idx].nil? then\n \tbegin\n \t\tfirst = 0\n \t\tlast = 1\n \t\tfor i in 0..(@idx-2)\n \t\t\tf = first + last\n \t\t\tfirst = last\n \t\t\tlast = f\n \t\tend\n \tend\n @seq[@idx] = f\n return f\n else\n return @seq[@idx]\n end\n end",
"def next_token\r\n if !@token.following.nil?\r\n\t\t\t@token = @token.following\r\n\t\t\treturn @token.value\r\n\t\tend\r\n\r\n\t\tscan(@token)\r\n\t\treturn @token.value\r\n end",
"def next\n parent[parent.place(self) + 1]\n end",
"def next\n\n if (@local_iterator && @local_iterator.has_next?)\n @local_iterator.get_next\n else\n nil\n end\n\n end",
"def _next_element\n unless @got_next_element\n unless @thread\n if @enum\n @thread = @queue._run_enum(@enum.each)\n else\n @thread = @queue._run(&@block)\n end\n end\n @next_element = @queue.pop\n if Exception === @next_element\n raise @next_element\n end\n @got_next_element = true\n end\n @next_element\n end",
"def next\n\t\t# Use up all of the extras\n\t\treturn @extras.pop if !@extras.empty?\n\t\t# Then track the last freeid used (which should always be the max)\n\t\treturn (@last+=1)-1\n\tend",
"def peek\n @head ? @head.value : nil\n end",
"def next_var(v)\n return v.next \n end",
"def nextValue\n while setDataSource do\n result = @valueCreator.nextValue\n if (@valueCreator.hasValue) then\n if (!@filter.filter(result.value)) then\n result.setValue(@transformer.transform(result.value))\n return result\n end\n else\n @valueCreator.resetSequenceSource\n end\n end\n return nil\n end",
"def next\n @pointer += 1\n end",
"def next_key\n @next && @next.key\n end",
"def next\n @next\n end",
"def next()\n @array[@k+=1]\n end",
"def next\n block.instructions[index+1] || (block.next ? block.next.instructions.first : nil)\n end",
"def next_sequence_value(sequence_name)\n select_one(\"select #{sequence_name}.nextval id from dual\")['id']\n end",
"def see_next\n if @index >= @normalized_numbers.length\n return -1\n else\n return @normalized_numbers[@index]\n end\n end",
"def next\n v_ = @vector.dup\n @structure._inc_vector(v_) ? nil : Position.new(@structure, v_)\n end",
"def peek\n\t return nil if self.curr == 0\n\t self.arr[self.curr - 1]\n end",
"def next\n token = next_token\n token = next_token while token&.empty?\n token\n end",
"def next(val)\n @q.shift if @q.count >= @size\n @q.push(val)\n @q.reduce(:+) / @q.count.to_f\n end",
"def current()\n raise EOFError, \"no more elements available\" if end?\n _next_element\n end",
"def next_token\n\t\tif ((tok = @tokensList.shift) != nil)\n\t\t\t@tokensAux << tok\n\t\t\treturn tok.idAndValue\n\t\telse\n\t\t\treturn nil\n\t\tend\n\tend",
"def next\n @history_idx -= 1 if @history_idx > -1\n current\n end",
"def next_seq\n @seq = (@seq + 1) & 0xffffffff\n end",
"def next_value\n value = $options.send(getter)\n return (value + @values[:increment]).clamp(@values[:min], @values[:max]) if @type == :slider\n value_index = @values.index(value)\n new_value = @values[(value_index || 0) + 1]\n new_value = @values.first if new_value.nil?\n return new_value\n end",
"def next\n return nil if @struct.next.null?\n self.class.new(@struct.next)\n end",
"def next\n @mut.synchronize{@array.sort![-1]}\n end",
"def first\n @enumerable.first\n end",
"def next!\n rotate!.first\n end",
"def peek\n raise 'No such element' if @elements.length == 0\n @elements[-1]\n end",
"def next_number\n process_next_block if @numbers.empty?\n\n @numbers.shift\n end",
"def next\n after.first\n end",
"def get_next\n while next_item = @queue.peek\n if next_item.cancelled?\n @queue.shift\n else\n return next_item\n end\n end\n\n return nil\n end",
"def next\n if has_next?\n node = @stack.pop\n # keep next ready\n look_left node.right if node.right\n node.data\n end\n end",
"def next\n units_sorted = self.order.units.sort_by {|unit| unit.id}\n if units_sorted.find_index(self) < units_sorted.length\n return units_sorted[units_sorted.find_index(self)+1]\n else\n return nil\n end\n end",
"def peek()\n @head.nil? ? nil : @head.val\n end",
"def next\n predict (@size + 1)\n end",
"def item_at_head\n\t\t\t@head.next\n\t\tend",
"def next\n @tok ||= read_token\n @tok, tok = nil, @tok\n @prev = tok\n return tok\n end",
"def next_item\n index = self.simple_acts_as_list_scope.index(self)\n self.simple_acts_as_list_scope[index + 1]\n end",
"def next(current)\n if (@position < @history.length - 1)\n @position = @position + 1\n return @history[@position]\n end\n return current\n end",
"def next\n DOM::Element.from_node `#{@el}.nextElementSibling || Opal.nil`\n end",
"def first\n @head.val\n end",
"def next\n displacement = @file.gets.try(:chomp).try(:to_f)\n return nil unless displacement\n\n ret = @curr_val\n @curr_val += displacement\n ret\n end",
"def getSequence\r\n\t\t\t\t\treturn @sequence\r\n\t\t\t\tend",
"def first_value\r\n get(@first_index)\r\n end",
"def next_argument\n if @remaining.empty?\n return nil\n else\n return @remaining.shift\n end\n end",
"def next\n master_files_sorted = self.sorted_set\n if master_files_sorted.find_index(self) < master_files_sorted.length\n return master_files_sorted[master_files_sorted.find_index(self)+1]\n else\n return nil\n end\n end",
"def next_exp\n return (@exp_list[@level+1] > 0 ? @exp_list[@level+1]-@exp_list[@level] : 0)\n end",
"def next()\n if has_next()\n @strings[0][1]-=1\n c = @strings[0][0]\n while has_next() and @strings[0][1] == 0\n @strings.shift\n end\n return c\n end\n return \" \"\n end",
"def sequence\n return @sequence\n end",
"def next_item\n return nil if @link == nil\n link.kernel.select {|item| item.rule == @rule}.first\n end",
"def peek\n empty? ? nil : @head.value\n end",
"def peek()\n return nil if @items.empty?\n return @items[-1]\n end",
"def next\n update_current(list_index_of(@current))\n end",
"def next\n return nil unless @node\n @node = @node.next\n while @index < @table.size and @node == nil\n @index += 1\n @node = @table[@index]\n end\n @node == nil ? nil : (@is_value ? @node.value : @node.key)\n end",
"def current\n return nil if @stack.empty?\n @stack.top[1] == 1 ? @stack.top[0].value1 : @stack.top[0].value2\n end",
"def next_exp\n return @exp_list[@level+1] > 0 ? @exp_list[@level+1] - @exp_list[@level] : 0\n end",
"def next_exp\n return @exp_list[@level+1] > 0 ? @exp_list[@level+1] - @exp_list[@level] : 0\n end",
"def next_exp\n return @exp_list[@level+1] > 0 ? @exp_list[@level+1] - @exp_list[@level] : 0\n end"
] |
[
"0.78649074",
"0.7677277",
"0.7610153",
"0.7523153",
"0.74460936",
"0.74261945",
"0.7173325",
"0.7046524",
"0.7042904",
"0.70228416",
"0.6932574",
"0.6907588",
"0.690667",
"0.6889075",
"0.68485904",
"0.6822495",
"0.6812803",
"0.680058",
"0.6792862",
"0.67672247",
"0.67133975",
"0.6707787",
"0.6705944",
"0.6682906",
"0.66629547",
"0.6606161",
"0.6606161",
"0.6606161",
"0.6606161",
"0.6606161",
"0.6606161",
"0.6597306",
"0.6593641",
"0.6548644",
"0.65249664",
"0.6517749",
"0.6510574",
"0.6510206",
"0.65038085",
"0.6486069",
"0.6466834",
"0.64375955",
"0.64333445",
"0.6419302",
"0.6402361",
"0.6388842",
"0.63850856",
"0.63849664",
"0.6382298",
"0.63745904",
"0.63596934",
"0.63562196",
"0.6338871",
"0.633833",
"0.63356173",
"0.63275707",
"0.6327047",
"0.6315542",
"0.63073933",
"0.63051623",
"0.62980974",
"0.629317",
"0.6291874",
"0.6280437",
"0.6272417",
"0.62401044",
"0.624009",
"0.62257475",
"0.6217729",
"0.6217097",
"0.6214743",
"0.6200684",
"0.619299",
"0.61901504",
"0.6189102",
"0.6182741",
"0.61664146",
"0.61661637",
"0.61633545",
"0.6149038",
"0.61455554",
"0.61259735",
"0.6109419",
"0.6094487",
"0.6089052",
"0.6080337",
"0.60701984",
"0.60688084",
"0.60648113",
"0.6062522",
"0.6059175",
"0.6049191",
"0.6037394",
"0.60263467",
"0.60258824",
"0.60171795",
"0.60058916",
"0.59989977",
"0.59989977",
"0.59989977"
] |
0.8077969
|
0
|
def set_variant return unless params[:variant].in?(%w(phone tablet desktop)) request.variant = params[:variant].to_sym end o tambien se puede por medio del user_agent:
|
def set_variant
# request.variant = :phone if request.user_agent.include?('iPhone')
# o con la gema browser
request.variant = :phone if browser.device.mobile?
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def set_request_variant\n request.variant = :mobile if request.user_agent =~ /android|Android|blackberry|iphone|ipod|iemobile|mobile|webos/\n request.variant = :android_app if request.user_agent =~ /AndroidApp/\n puts \"--------------\"+request.variant.to_s+\"--------------\"\n end",
"def set_variant\n if request.user_agent =~\n /mobile|android|touch|webos|hpwos|iphone|iPhone|iPad|ipod|\n android|blackberry|opera|mini|windows\\sce|palm|smartphone|iemobile|\n ipad|android 3.0|xoom|sch-i800|playbook|tablet|kindle/\n\n request.variant = :mobile\n else\n request.variant = :desktop\n end\n end",
"def set_variant_template\n request.variant = :mobile if request.user_agent =~ /iPad/\n end",
"def variant=(variant)\n variant = Array(variant)\n\n if variant.all?(Symbol)\n @variant = ActiveSupport::ArrayInquirer.new(variant)\n else\n raise ArgumentError, \"request.variant must be set to a Symbol or an Array of Symbols.\"\n end\n end",
"def set_variant\n @variant = Variant.find(params[:id])\n end",
"def set_variant\n @variant = Variant.find(params[:id])\n end",
"def set_variant\n @variant = Variant.find(params[:id])\n end",
"def set_variant\n @variant = Variant.find(params[:id])\n end",
"def set_variant\n @variant = Variant.find(params[:id])\n end",
"def set_device\n # if HTTP_USER_AGENT is blank/nil defaults to blank, i.e. desktop \n agent = request.env[\"HTTP_USER_AGENT\"].blank? ? \"\" : request.env[\"HTTP_USER_AGENT\"].downcase \n if agent =~ tablet_agents\n \"tablet\"\n elsif (agent =~ mobile_agents_one) || (agent[0..3] =~ mobile_agents_two)\n \"mobile\"\n else\n \"desktop\"\n end \n end",
"def variant=(variant); end",
"def variant_params\n # перебираются типы свойств товара,\n # проставляются свойства исходя из пришедших в параметрах\n # обсуждалось, что этот функционал будет не нужен, т.к. во многом упростили схему\n\n property_types = {}\n params[:variant][:property_types].permit!.each{|k, p| property_types[k] = p[:property_id]}\n\n params.require(:variant).permit(:is_material)\n\n params = permit_params\n params[:property_types] = property_types\n\n [:picture, :material].each do |i|\n params[i] = nil if params[i] == ''\n end\n\n params\n end",
"def set_variant\n @product = Product.find(params[:product_id])\n @variant = @product.variants.new\n end",
"def load_variant\r\n @variant_id = cookies.delete(:load_variant)\r\n if @variant_id\r\n params[:id] = @variant_id\r\n end\r\n end",
"def set_variant_value\n @variant_value = VariantValue.find(params[:id])\n end",
"def set_product_variant\n @product_variant = ProductVariant.find(params[:id])\n end",
"def set_product_variant\n @product_variant = ProductVariant.find(params[:id])\n end",
"def set_variation_storage_type\n cid = VirtualMonkey::Toolbox::determine_cloud_id(s_one)\n if cid == 232\n @storage_type = \"ros\"\n else\n pick = rand(100000) % 2\n if pick == 1\n @storage_type = \"ros\"\n else\n @storage_type = \"volume\"\n end\n end\n \n @storage_type = ENV['STORAGE_TYPE'] if ENV['STORAGE_TYPE']\n puts \"STORAGE_TYPE: #{@storage_type}\"\n @deployment.nickname += \"-STORAGE_TYPE_#{@storage_type}\"\n @deployment.save\n \n obj_behavior(@deployment, :set_input, \"db_mysql/backup/storage_type\", \"text:#{@storage_type}\")\n end",
"def set_user_agent_override(user_agent:, accept_language: nil, platform: nil)\n {\n method: \"Emulation.setUserAgentOverride\",\n params: { userAgent: user_agent, acceptLanguage: accept_language, platform: platform }.compact\n }\n end",
"def variant\n shop = params[:shop]\n product_id = params[:id]\n variant_id = params[:variant_id]\n image_url = params[:url]\n\n begin\n url = \"http://variantimages.shopifyapps.com/jquery-preload.js?shop=#{shop}&id=#{product_id}\"\n content = open(url).read\n\n if match = content.match(/variantData = ([^;]+);/)\n variant_url = URI(image_url)\n variant_url.path = variant_path([\n File.dirname(variant_url.path),\n JSON.parse(match[1])[variant_id][\"filename\"].split('.').first,\n File.basename(variant_url.path).split('_').last,\n ])\n image_url = variant_url.to_s\n end\n rescue => e\n end\n\n redirect_to image_url\n end",
"def variant_params\n params.require(:variant).permit(:name, :precio, :product)\n end",
"def variant_params\n params.require(:variant).permit(:name)\n end",
"def device_selective_request(request_args, ua_type)\n method, action, parameters, session, flash = request_args\n unless ua_type == :galapagos\n ks_ajax method, action, parameters\n else\n process(action, parameters, session, flash, method.to_s.upcase)\n end \n end",
"def product_variant_params\n params.require(:product_variant).permit(:product_id, :brand, :price, :location, :service_price, :value)\n end",
"def user_agent=(user_agent); end",
"def variant; end",
"def variant; end",
"def set_media_fixed_or_sfp(opts)\n opts = check_params(opts,[:media_types])\n super(opts)\n end",
"def get_selected_variant_data\n @variant = Spree::Variant.where(:id => params[:variant_id]).first\n @sku = @dispatch_no = @variant.sku+\"_\"+Time.now.strftime('%y%m%d%H%L')\n price = @variant.price\n respond_to do |format|\n format.json { render :json => {:variant => @variant,\n :sku => @sku, :price => price }}\n end\n end",
"def variant_params\n params.require(:supply_variant).permit(:price, :compare_at_price, :option1, :option2, :option3)\n end",
"def variant_params\n params.require(:variant).permit(:size, :color, :stock, :product_id, :_destroy)\n end",
"def prepare_for_mobile\r\n session[:mobile_param] = params[:mobile] if params[:mobile]\r\n request.format = :mobile if mobile_device?\r\n end",
"def variant_params\n params.require(:variant).permit(:sku, :product_id, :position, :price, :variant_price, option_value_ids: [], assets_attributes: [:id, :image, :_destroy])\n end",
"def set_viewable\n viewable_id = params[:image][:viewable_id]\n\n if viewable_id.is_a?(Hash)\n @product.errors.add(:attachment, 'Erro')\n option_values_array = viewable_id.map {|option_type, option_values| option_values.map(&:to_i) }\n option_values_combinations = option_values_array.shift\n option_values_array.each do |option_value|\n option_values_combinations = option_values_combinations.product(option_value)\n end\n option_values_combinations = option_values_combinations.map(&:flatten) if option_values_combinations.count > 1\n\n @product.variants.each do |variant|\n option_values_combinations.each do |ov_combination|\n variant_option_ids = variant.option_values.pluck(:id)\n\n if ([ov_combination].flatten - variant_option_ids).empty?\n create_image(variant, permitted_resource_params)\n end\n end\n end\n else\n viewable_id = params[:master_option] if params[:master_option]\n @image.viewable_type = 'Spree::Variant'\n @image.viewable_id = viewable_id\n end\n end",
"def prepare_for_mobile\n session[:mobile_param] = params[:mobile] if params[:mobile]\n request.format = :mobile if mobile_device?\n end",
"def variant(*args)\n Rscons.application.variant(*args)\n end",
"def _normalize_render(*args, &block)\n\t options = _normalize_args(*args, &block)\n\t #TODO: remove defined? when we restore AP <=> AV dependency\n\t if defined?(request) && request && request.variant.present?\n\t options[:variant] = request.variant\n\t end\n\t _normalize_options(options)\n\t options\n\t end",
"def set_type\n if self.mp3.present?\n self.type = \"Audio::UploadedAudio\"\n\n elsif self.enco_number.present? && self.enco_date.present?\n self.type = \"Audio::EncoAudio\"\n\n elsif self.external_url.present?\n self.type = \"Audio::DirectAudio\"\n\n end\n end",
"def create\n @variant = @product.variants.new(params.require(:variant).permit!)\n @variant.price = params[:variant][:price]\n respond_to do |format|\n if @variant.save\n format.html { redirect_to admin_product_variants_url(@product), notice: 'Variant was successfully created.' }\n format.json { render action: 'show', status: :created, location: @variant }\n else\n format.html { render action: 'new' }\n format.json { render json: @variant.errors, status: :unprocessable_entity }\n end\n end\n end",
"def check_platform\n mobile_override = params[:mobile] && params[:mobile] == \"1\"\n desktop_override = params[:mobile] && params[:mobile] == \"0\"\n if ( (browser.mobile? and !browser.ipad?) or mobile_override ) and !request.xhr? and !desktop_override\n @platform = 'mobile'\n request.format = :mobile\n else\n @platform = 'desktop'\n end\n end",
"def create_variant(type, value)\n value_type = Spree::OptionType.find_or_initialize_by name: type\n value_type.update! presentation: type.capitalize unless value_type.id\n\n # ensure we have propper variant\n option_value = Spree::OptionValue.find_or_create_by! name: value, presentation: value, option_type_id: value_type.id\n\n # this will link variant to size\n Spree::OptionValuesVariant.find_or_create_by! variant_id: @variant.id, option_value_id: option_value.id\n end",
"def is_brand? brand\n Handset.is_brand? request.user_agent, brand\n end",
"def update!(**args)\n @empty_mid_variant = args[:empty_mid_variant] if args.key?(:empty_mid_variant)\n @spotify_variant = args[:spotify_variant] if args.key?(:spotify_variant)\n @youtube_variant = args[:youtube_variant] if args.key?(:youtube_variant)\n end",
"def prepare_for_mobile\n if Rails.env.development?\n session[:mobile_param] = params[:mobile] if params[:mobile]\n request.format = :mobile if mobile_device?\n end\n end",
"def set_media_sfp(opts)\n opts = check_params(opts,[:media_types])\n super(opts)\n end",
"def variant!\n @control = false\n end",
"def enable_variants\n unless @_variants_enabled\n if @enabled_variants != \"\"\n exact = !(@enabled_variants =~ /^(\\+|-)/)\n enabled_variants = @enabled_variants.split(\",\")\n specified_variants = {}\n enabled_variants.each do |enable_variant|\n enable_variant =~ /^(\\+|-)?(.*)$/\n enable_disable, variant_name = $1, $2\n specified_variants[variant_name] = enable_disable != \"-\"\n end\n each_variant do |variant|\n if specified_variants.include?(variant[:name])\n variant[:enabled] = specified_variants[variant[:name]]\n elsif exact\n variant[:enabled] = false\n end\n end\n end\n @_variants_enabled = true\n end\n check_enabled_variants\n end",
"def set_request_from_bot_flag\n res = http_user_agent.match(/\\b(Baidu|Baiduspider|Gigabot|Googlebot|thefind|webmeup-crawler.com|libwww-perl|lwp-trivial|msnbot|SiteUptime|Slurp|ZIBB|wget|ia_archiver|ZyBorg|bingbot|AdsBot-Google|AhrefsBot|FatBot|shopstyle|pinterest.com|facebookexternalhit|Twitterbot|crawler.sistrix.net|PolyBot|rogerbot|Pingdom|Mediapartners-Google|bitlybot|BlapBot|Python|www.socialayer.com|Sogou|Scrapy|ShopWiki|Panopta|websitepulse|NewRelicPinger|Sailthru|JoeDog|SocialWire|CCBot|yacybot|Halebot|SNBot|SEOENGWorldBot|SeznamBot|libfetch|QuerySeekerSpider|A6-Indexer|PAYONE|GrapeshotCrawler|curl|ShowyouBot|NING|kraken|MaxPointCrawler|efcrawler|YisouSpider|BingPreview|MJ12bot)\\b/i)\n params[:is_bot] = res.present? ? 1 : 0\n end",
"def set_request_from_bot_flag\n res = http_user_agent.match(/\\b(Baidu|Baiduspider|Gigabot|Googlebot|thefind|webmeup-crawler.com|libwww-perl|lwp-trivial|msnbot|SiteUptime|Slurp|ZIBB|wget|ia_archiver|ZyBorg|bingbot|AdsBot-Google|AhrefsBot|FatBot|shopstyle|pinterest.com|facebookexternalhit|Twitterbot|crawler.sistrix.net|PolyBot|rogerbot|Pingdom|Mediapartners-Google|bitlybot|BlapBot|Python|www.socialayer.com|Sogou|Scrapy|ShopWiki|Panopta|websitepulse|NewRelicPinger|Sailthru|JoeDog|SocialWire|CCBot|yacybot|Halebot|SNBot|SEOENGWorldBot|SeznamBot|libfetch|QuerySeekerSpider|A6-Indexer|PAYONE|GrapeshotCrawler|curl|ShowyouBot|NING|kraken|MaxPointCrawler|efcrawler|YisouSpider|BingPreview|MJ12bot)\\b/i)\n params[:is_bot] = res.present? ? 1 : 0\n end",
"def set_request_from_bot_flag\n res = http_user_agent.match(/\\b(Baidu|Baiduspider|Gigabot|Googlebot|thefind|webmeup-crawler.com|libwww-perl|lwp-trivial|msnbot|SiteUptime|Slurp|ZIBB|wget|ia_archiver|ZyBorg|bingbot|AdsBot-Google|AhrefsBot|FatBot|shopstyle|pinterest.com|facebookexternalhit|Twitterbot|crawler.sistrix.net|PolyBot|rogerbot|Pingdom|Mediapartners-Google|bitlybot|BlapBot|Python|www.socialayer.com|Sogou|Scrapy|ShopWiki|Panopta|websitepulse|NewRelicPinger|Sailthru|JoeDog|SocialWire|CCBot|yacybot|Halebot|SNBot|SEOENGWorldBot|SeznamBot|libfetch|QuerySeekerSpider|A6-Indexer|PAYONE|GrapeshotCrawler|curl|ShowyouBot|NING|kraken|MaxPointCrawler|efcrawler|YisouSpider|BingPreview|MJ12bot)\\b/i)\n params[:is_bot] = res.present? ? 1 : 0\n end",
"def get_variant\n @product = Spree::Product.find_by :slug => params[:product_id]\n @variant = @product.find_variant_by_options(params[:ids].split(','))\n if @variant\n respond_to do |format|\n format.json {render json: {variant_id: @variant.id, image_ids: @variant.image_ids}}\n end\n end\n end",
"def sku\n variant.sku if variant\n end",
"def set_mobile_format\n if is_mobile_device?\n request.format = session[:mobile_view] == false ? :html : :mobile\n session[:mobile_view] = true if session[:mobile_view].nil?\n end\n end",
"def variant_value_params\n params.permit(:value, :Variant_id)\n end",
"def variants_params\n params.require(:product).permit(:name, :permalink, :skuid, :price, :cost_price, :tax_rate_id, :size_id, :quantity, :product_id)\n end",
"def variants; end",
"def set_mobile_format\n if !mobile_exempt? && is_mobile_device? && !request.xhr?\n request.format = session[:mobile_view] == false ? :html : :mobile\n session[:mobile_view] = true if session[:mobile_view].nil?\n end\n end",
"def user_agent= user_agent\n @agent.user_agent = user_agent\n end",
"def apply_variant_template(variant)\n result = true\n variant.options.each do |variant|\n variants.new(:name => variant).save! rescue (result = false)\n end\n result\n end",
"def set_device_type(response, device_type)\n response.set_cookie('mobvious.device_type',\n { value: device_type.to_s, path: '/', expires: Time.now + @cookie_expires, domain: base_domain(response) }) if base_domain(response)\n end",
"def set_mobile_format\n if is_mobile_device? && !request.xhr?\n request.format = session[:mobile_view] == false ? :html : :mobile\n session[:mobile_view] = true if session[:mobile_view].nil?\n end\n end",
"def set_mobile_format\n if is_mobile_device?\n request.format = session[:mobile_view] == false ? :html : :mobile\n session[:mobile_view] = true if session[:mobile_view].nil?\n end\n end",
"def mobilesetting_params\n params.require(:mobilesetting).permit(:user_id, :securephrase, :access_via_mobile)\n end",
"def site_sku_params\n if params[:site_sku][:site_id] == nil\n params[:site_sku][:selected] = false\n end\n \n params.require(:site_sku).permit(:site_id, :sku, :product_id, :selected)\n end",
"def append_user_agent_to_params\n params[:browser_user_agent] = http_user_agent\n end",
"def mobile_standard\n if request.env[\"HTTP_X_MOBILE_GATEWAY\"]\n out = nil\n else\n\n # request.env[\"HTTP_USER_AGENT\"].match(\"iPhone\") ? \"mobile\" : \"callc\"\n if session[:layout_t]\n if session[:layout_t].to_s == \"mini\"\n\n if request.env[\"HTTP_USER_AGENT\"].to_s.match(\"iPhone\")\n out = \"iphone\"\n end\n end\n if session[:layout_t].to_s == \"full\" or session[:layout_t].to_s == nil\n out = \"callc\"\n end\n if session[:layout_t].to_s == \"callcenter\"\n out = \"callcenter\"\n end\n else\n if !(request.env[\"HTTP_USER_AGENT\"].to_s.match(\"iPhone\") or request.env[\"HTTP_USER_AGENT\"].to_s.match(\"iPod\"))\n out = \"callc\"\n end\n if request.env[\"HTTP_USER_AGENT\"].to_s.match(\"iPhone\")\n out = \"iphone\"\n end\n end\n end\n return out\n end",
"def has_variant?(variant)\n return false unless @variants\n v = variant.downcase\n @variants.any? { |var| v == var || v == var.downcase }\n end",
"def set_iphone_format\n if is_iphone_request? || is_iphone_format? || is_iphone_subdomain?\n request.format = cookies[\"browser\"] == \"desktop\" ? :html : :iphone \n end\n end",
"def set_mobile_format\n if is_mobile_device? && !request.xhr?\n request.format = session[:mobile_view] == false ? :html : :mobile\n session[:mobile_view] = true if session[:mobile_view].nil?\n end\n end",
"def set_country_from_http_accept_language\n\n #\"HTTP_ACCEPT_LANGUAGE\\\"=>\\\"en-us,en;q=0.5\\\"\n accept_language = request.env['HTTP_ACCEPT_LANGUAGE']\n \n language = 'en'\n locale = 'us'\n \n unless accept_language.nil?\n language = accept_language[0,2] unless accept_language.length < 2\n locale = accept_language[3,2] unless accept_language.length < 5\n end\n \n case locale\n when 'us' then\n @customer.country = 'US'\n when 'ca' then\n @customer.country = 'CA'\n when 'gb' then \n @customer.country = 'GB'\n end \n end",
"def create\n @master_variant = Variant.find(params[:product_id])\n params[:variant][:is_master] = false\n params[:variant][:master_id] = @master_variant.id\n params[:variant][:product] = @master_variant.product\n @variant = Variant.new(params[:variant])\n\n respond_to do |format|\n if @variant.save\n format.html { redirect_to admin_product_variants_path(@variant.master_id), notice: 'Variant was successfully created.' }\n format.json { render json: admin_product_variant_path(@variant.master_id, @variant),\n status: :created, location: admin_product_variant_path(@variant.master_id, @variant) }\n else\n @path = admin_product_variants_path(@master_variant)\n format.html { render action: \"new\" }\n format.json { render json: @variant.errors, status: :unprocessable_entity }\n end\n end\n end",
"def product_variant_params\n params.require(:product_variant).permit(:size, :quantity, :product_id, :color_id)\n end",
"def useragent=(value)\n Curl.set_option(:useragent, value_for(value, :string), handle)\n end",
"def set_mobile_format\n if self.mobylette_options[:fallback_chains]\n self.mobylette_options[:fallback_chains].keys.each do |device|\n return device if request_device?(device)\n end\n end\n :mobile \n end",
"def user_agent=(name)\n @user_agent = USER_AGENT[name] || USER_AGENT['bot']\n end",
"def set_store_flavor\n @store_flavor = StoreFlavor.find(params[:id])\n end",
"def user_agent(user_agent)\n @user_agent = user_agent\n end",
"def use_agent=(use_agent); end",
"def kgio_accept(*several_variants)\n #This is a stub, used for indexing\n end",
"def set_variation\n @variation ||= Variation.find(params[:id])\n end",
"def set_media(opts)\n opts = check_params(opts,[:media_types])\n super(opts)\n end",
"def show\n # if params.has_key?(:english)\n # @eng= (params[:english]==\"1\")\n # else\n # @eng=false\n # end\n end",
"def process_page_with_mobile(page)\n page.app = app?\n page.mobile = app? || mobile?\n process_page_without_mobile(page)\n end",
"def set_virus\n @virus = Virus.find(params[:id])\n end",
"def device_type\n case request.user_agent\n when /mobile/i\n \"mobile\"\n when /iPad/i\n \"tablet\"\n when /Android/i\n \"tablet\"\n else\n \"desktop\"\n end\n end",
"def variants=(value)\n subtags = Array(value).flatten\n if subtags.empty?\n self.variants_sequence = nil\n else\n self.variants_sequence = subtags.join(HYPHEN)\n @variants = subtags\n end\n end",
"def new\n\n @compliance = Compliance.new\n @compliance.status = \"vendor_input\"\n if params[:sku]\n @compliance.sku = params[:sku]\n end\n if params[:vendor_id]\n @compliance.vendor_id = params[:vendor_id]\n elsif session[:type] == \"vendor\"\n @compliance.vendor_id = session[:id]\n else\n redirect_to sign_up_path\n end\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @compliance }\n end\n end",
"def is_device? type\n request.user_agent.to_s.downcase.include?(type.to_s.downcase)\n end",
"def update\n respond_to do |format|\n if @variant.update(variant_params)\n format.html { redirect_to edit_admin_good_url(@variant.good, anchor: \"variants\"), notice: 'Variant was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @variant.errors, status: :unprocessable_entity }\n end\n end\n end",
"def is_device?(type)\n\t\trequest.user_agent.to_s.downcase.include?(type.to_s.downcase)\n\tend",
"def put_on_sale(value, params = {})\n all_variants = params[:all_variants] || true\n run_on_variants(all_variants) { |v| v.put_on_sale(value, params) }\n self.touch\n end",
"def update\n respond_to do |format|\n if @variant.update(variant_params)\n format.html { redirect_to admin_product_variants_url(@product), notice: 'Variant was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @variant.errors, status: :unprocessable_entity }\n end\n end\n end",
"def user_agent(value)\n value || DEFAULT_USER_AGENT\n end",
"def set_media_type\n media_types = self.class.head(@endpoint).headers['accept']\n Occi::Log.debug(\"Available media types: #{media_types}\")\n @media_type = case media_types\n when /application\\/occi\\+json/\n 'application/occi+json'\n else\n 'text/plain'\n end\n end",
"def set_variation\n @variation = Variation.find(params[:id])\n end",
"def admin_choice\n @choice = params[:choice]\n end",
"def type=(val)\n @type = val.to_sym if %w(UNSPECIFIED MEDIA MASTER).include? val.to_s\n end",
"def set_admin_vehicle\n @admin_vehicle = Vehicle.find(params[:id])\n @vehicle_type = @admin_vehicle.vehicle_type\n @utility_id = @admin_vehicle.utility_id\n @italian_type = {parking:'Parcheggi', bike:'Bici', taxi:'Taxi'}\n end",
"def set_variation\n @variation = Variation.find(params[:id])\n end",
"def is_device?(type)\n request.user_agent.to_s.downcase.include? type.to_s.downcase\n end"
] |
[
"0.8481653",
"0.83958817",
"0.7845817",
"0.6666438",
"0.645645",
"0.645645",
"0.645645",
"0.645645",
"0.6431474",
"0.6211851",
"0.6140318",
"0.6060406",
"0.6022627",
"0.59794176",
"0.5893816",
"0.58839273",
"0.58839273",
"0.5853466",
"0.58247656",
"0.5782216",
"0.5780708",
"0.5744604",
"0.5740753",
"0.56718826",
"0.55713594",
"0.55474734",
"0.55474734",
"0.5535169",
"0.5511538",
"0.55069196",
"0.5472831",
"0.54647547",
"0.5459038",
"0.54540807",
"0.5446125",
"0.5444415",
"0.54376197",
"0.54239494",
"0.54210174",
"0.5402545",
"0.540172",
"0.53831357",
"0.53310347",
"0.5308796",
"0.53063655",
"0.52886224",
"0.528781",
"0.52822304",
"0.52822304",
"0.52822304",
"0.5281118",
"0.5274114",
"0.5263681",
"0.52592456",
"0.5253899",
"0.5253813",
"0.5247826",
"0.52454525",
"0.5242327",
"0.5237192",
"0.5206531",
"0.52062476",
"0.51956093",
"0.51904494",
"0.51831424",
"0.5181508",
"0.51716554",
"0.5154558",
"0.5150169",
"0.51455903",
"0.51399267",
"0.5134812",
"0.5129031",
"0.510913",
"0.51037765",
"0.51036936",
"0.5102634",
"0.507861",
"0.50706947",
"0.50597686",
"0.50593674",
"0.5033045",
"0.5027797",
"0.50265115",
"0.5022181",
"0.5018086",
"0.5014589",
"0.5014372",
"0.5010421",
"0.5005207",
"0.50006616",
"0.4993863",
"0.49929652",
"0.49919686",
"0.49865755",
"0.49857295",
"0.49844816",
"0.49841198",
"0.4983141",
"0.49801886"
] |
0.8770161
|
0
|
definimos el 404 que se esta pasando en el rescue_from
|
def render_404
render 'web/404', status: 404
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def rescue_not_found\n render nothing: true, status: 404\n end",
"def error_rescue(exception = nil)\n return render_error_status(404, exception.message)\n end",
"def rescue404\n render 'public/404'\n end",
"def not_found\n raise ActionController::RoutingError.new('Not Found')\n rescue\n render_404\n end",
"def status_not_found\n @status = 404\n @e.error 'The requested page does not exist.', 404\n throw :exit\n end",
"def render_404\n raise ActionController::RoutingError.new('Not Found')\n end",
"def check_404\n end",
"def not_found\n respond_with 404\n end",
"def not_found\n respond_with 404\n end",
"def halt_not_found(exception)\n halt 404, json({ message: exception.reason })\n end",
"def method_missing(*args)\n rescue_404\n end",
"def rescue_not_found\n render \"#{Rails.root}/public/404.html\", status: 404\n end",
"def rescue_not_found\n render \"#{Rails.root}/public/404.html\", status: 404\n end",
"def not_found\n rescue_404(ActionController::RoutingError.new(\"No route matches #{request.request_method} #{request.path}\"))\n end",
"def resource_not_found_for(env)\n raise case env[:url].path\n when /\\A\\/_api\\/document/ then Ashikawa::Core::DocumentNotFoundException\n when /\\A\\/_api\\/collection/ then Ashikawa::Core::CollectionNotFoundException\n when /\\A\\/_api\\/index/ then Ashikawa::Core::IndexNotFoundException\n else Ashikawa::Core::ResourceNotFound\n end\n end",
"def handle_not_found(exception)\n raise exception\n end",
"def not_found(&block)\n error 404, &block\n end",
"def resource_not_found_for(env)\n raise case env[:url].path\n when %r{\\A(/_db/[^/]+)?/_api/document} then Ashikawa::Core::DocumentNotFoundException\n when %r{\\A(/_db/[^/]+)?/_api/collection} then Ashikawa::Core::CollectionNotFoundException\n when %r{\\A(/_db/[^/]+)?/_api/index} then Ashikawa::Core::IndexNotFoundException\n else Ashikawa::Core::ResourceNotFound\n end\n end",
"def not_found\n raise ActionController::RoutingError.new('Not Found')\n end",
"def not_found\n raise ActionController::RoutingError.new('Not Found')\n end",
"def not_found\n raise ActionController::RoutingError.new('Not Found')\n end",
"def not_found\n raise ActionController::RoutingError.new('Not Found')\n end",
"def not_found\n raise ActionController::RoutingError.new('Not Found')\n end",
"def not_found\n raise ActionController::RoutingError.new('Not Found')\n end",
"def not_found\n raise ActionController::RoutingError.new('Not Found')\n end",
"def render_missing\r\n RenderError.new('404')\r\n end",
"def not_found\n raise ActionController::RoutingError.new 'Not Found'\n end",
"def not_found\n logger.error \"404 from #{request.referer}\"\n render :template => 'errors/404', :status => 404\n end",
"def not_found\n raise ActionController::RoutingError.new 'Not found'\n end",
"def not_found\n raise ActionController::RoutingError, 'Not Found'\n end",
"def not_found\n render :status => 404\n end",
"def error_route_not_found\n render 'errors/route_not_found', status: :not_found rescue last_chance\n end",
"def what_are_you_looking_for?\n raise Exceptions::NotFound.new(404, 'Not Found; You did not find what you were expecting because it is not here. What are you looking for?')\n end",
"def response_not_found\n render status: 404,\n json: {\n source: {\n pointer: request.original_url\n },\n errors: [ { message: \"Not Found\" } ]\n }\n end",
"def return_not_found\n return_error(error_code: 404, message: 'Not Found')\n end",
"def not_found(message='Not Found')\n raise ActionController::RoutingError.new(message)\n end",
"def not_found\n status 404\n body \"not found\\n\"\n end",
"def not_found\n status 404\n body \"not found\\n\"\n end",
"def not_found\n status 404\n body \"not found\\n\"\n end",
"def not_found\n render :template => \"shared/rescues/not_found\", :status => 404 \n end",
"def give404(response, msg)\n\tgive_X(response, 404, \"plain/text\", msg)\n end",
"def render_404\n render :template => \"errors/404\", :status => :not_found, :layout => false\n end",
"def render_404\n render \"404\", :status => 404\n end",
"def render_not_found exception\n\n #logger.info\"==========error 404=========\"\n #Rails.logger.error(exception)\n #render :template => \"/errors/404.html.erb\", :status => 404\n @not_found_path = exception.message\n respond_to do |format|\n format.html { render template: 'errors/error_404', status: 404, layout:false }\n format.all { render nothing: true, status: 404 }\n end\n log_exception_handler(exception)\n end",
"def return_404_error\n\n render json: { success: false, error: I18n.t('errors.e_404'),\n status_code: 404 }, status: :not_found\n end",
"def not_found\n raise ActionController::RoutingError.new('Page Not Found. Please contact the system administrator.')\n end",
"def render_404(exception = nil)\n @not_found_path = exception.message if exception\n respond_to do |format|\n format.html { render template: 'errors/not_found', layout: 'application', status: 404 }\n format.all { render nothing: true, status: 404 }\n end\n end",
"def not_found\n raise ActionController::RoutingError.new('Permalink Not Found')\n end",
"def not_found(body = nil)\n error(404, body)\n end",
"def render_404\n render_optional_error_file(404)\n end",
"def not_found! redirect = root_path\n raise ActionController::RoutingError.new(\"Sorry, I could not find the requested item!\")\n end",
"def handle_not_found(request, response)\n response.flush\n response.status = 404\n\n response.layout = \"layouts/exception\" if Harbor::View.exists?(\"layouts/exception\")\n\n if Harbor::View.exists?(\"exceptions/404.html.erb\")\n response.render \"exceptions/404.html.erb\"\n else\n response.puts \"The page you requested could not be found\"\n end\n\n raise_event(:not_found, Events::NotFoundEvent.new(request, response))\n end",
"def not_found\n render_error status: :not_found, body: 'page not found'\n end",
"def record_not_found!\n render partial: 'errors/404', status: 404 && return\n end",
"def render_404\n render_error(\"The remote resource was not found\")\n end",
"def not_found\n render :nothing => true, :status => 404\n end",
"def render_not_found(exception)\n render :file => 'public/404', :format => :html, :status => :not_found, :layout => nil\n end",
"def render_not_found(exception)\n render :file => 'public/404', :format => :html, :status => :not_found, :layout => nil\n end",
"def render_404\n render json: {\n message: '404 Not Found',\n details: exception.error_codes\n }, status: 404\n end",
"def not_found(env)\n [404,{'Content-Type'=>'text/plain','X-Cascade'=>'pass'},['Ooooopppps 404!']]\n end",
"def routes_not_found\n respond_to do |f|\n f.html{ render :template => \"errors/404\", :status => 404}\n end\n end",
"def render_404\n render :text => '404 Error: not found', :status => 404 \n end",
"def not_found?\n 404 == code\n end",
"def not_found\n render nothing: true, status: 404\n end",
"def catch_not_found\n yield\n rescue ActiveRecord::RecordNotFound\n redirect_to root_url, :flash => { :error => \"Nº de protocolo inexistente!\" }\n end",
"def handle_not_found(exception = nil)\n render \"shared/not_found\".freeze, status: 404\n end",
"def render_404\n redirect_to not_found_path\n end",
"def raise_not_found!\n\n raise ActionController::RoutingError.new(\"No route matches #{params[:unmatched_route]}\")\n\n end",
"def respond_with_not_found(exception = nil, error_code = \"not_found\")\n msg = exception ? exception.message : \"Not Found\"\n render partial: \"api/error\", locals: { message: msg, error_code: error_code }, status: 404\n return false\n end",
"def not_found\n render file: \"#{Rails.root}/public/404\", layout: true, status: :not_found\n end",
"def raise_not_found\n\t\traise ActionController::RoutingError.new(\"No route matches #{params[:unmatched_route]}\")\n\tend",
"def record_not_found\n render :partial => \"shared/error\", :layout => \"one_box\", :status => 404, :locals => {:error_title => 'No hemos encontrado lo que buscabas', :error_message => 'Puedes haber tecleado mal la dirección o la página puede haber sido movida.'}\n end",
"def render_not_found\n\n respond_to do |message|\n \n message.html{ render :template => \"errors/404\", :status => 404 }\n \n end\n\n end",
"def page_not_found\n render 'shared/http_status', formats: [:html], locals: { code: '404', message: HttpStatusHelper::ERROR_CODE['message']['404'] }, status: 404, layout: false\n end",
"def error_404\n # Note: If you want to separate your view logic from \n # your controller logic you will need to use render_file\n # - simply using a view does not work when the 404 is\n # generated by a path not mapped to this controller.\n #\n # Keep in mind that render_file takes a full path -\n # so you should use something like 'Ramaze.options.views[0]'\n # to get at your view directory\n event(:status_404)\n render_file(\"#{Ramaze.options.views[0]}/error_404.xhtml\")\n end",
"def not_found(exception)\n render json: { error: exception.message }, status: :not_found\n end",
"def render_404\n render file: \"#{Rails.root}/public/404.html\", layout: false, status: 404\n end",
"def bad_request\n #redirect_to \"#{Rails.root}/public/400.html\"\n raise ActionController::RoutingError.new('Bad Request')\n end",
"def send_e404(cli, request)\n resp = Response::E404.new\n\n resp['Content-Type'] = 'text/html'\n\n resp.body =\n \"<html><head>\" +\n \"<title>404 Not Found</title>\" +\n \"</head><body>\" +\n \"<h1>Not found</h1>\" +\n \"The requested URL #{html_escape(request.resource)} was not found on this server.<p><hr>\" +\n \"</body></html>\"\n\n # Send the response to the client like what\n cli.send_response(resp)\n end",
"def render_404(_exception = nil)\n errors = JsonApiServer.errors(\n status: 404,\n title: I18n.t('json_api_server.render_404.title'),\n detail: I18n.t('json_api_server.render_404.detail', name: _i18n_name)\n )\n render json: errors.to_json, status: 404\n end",
"def record_not_found\n \t\trender :file => File.join(RAILS_ROOT, 'public', '404.html'), :status => 404\n \tend",
"def build_checker_404?(e)\n e.is_a?(Faraday::ResourceNotFound) &&\n ::User.find_by(email: 'build_checker_fake_email').try(:onapp_user) == @config[:user] &&\n e.backtrace.join.match(/vm_monitor_destroy/)\n end",
"def record_not_found\n render file: \"#{Rails.root}/public/404.html\", layout: false, status: :not_found\n end",
"def error_404(exception=nil)\n @meta_title = \"The page you were looking for doesn't exist (404)\"\n render :template => '/errors/404', :formats => [:html], :status => 404\n return false\n end",
"def not_found\n\n render_error( :not_found )\n\n end",
"def error_404\n error_layout 404, '404 Not Found', %[\n <p>\n The requested URL <code>#{h(request.REQUEST_URI)}</code> was not\n found on this server.\n </p>\n ]\n end",
"def catch_not_found\n yield\n rescue ActiveRecord::RecordNotFound\n flash[:notice] = \"Hittades inte\"\n redirect_to root_url\n end",
"def not_found(exception)\n render json: { status: \"404\", \"#{exception.message}\": \"page not found\"}\n end",
"def render_404\n render :file => \"#{Rails.root}/public/404.html\", :status => 404\n end",
"def not_found?\n 404 == @code\n end",
"def not_found?\n 404 == @code\n end",
"def not_found?\n 404 == @code\n end",
"def not_found?\n 404 == @code\n end",
"def show_404\n show_error 'Page Not Found', :not_found\n end",
"def render_404 \n render :file => \"/public/404.html\", :status => 404,:layout => false\n end",
"def render_404 \n render :file => \"/public/404.html\", :status => 404,:layout => false\n end",
"def render_404 \n render :file => \"/public/404.html\", :status => 404,:layout => false\n end",
"def render_404 \n render :file => \"/public/404.html\", :status => 404,:layout => false\n end",
"def render_404 \n render :file => \"/public/404.html\", :status => 404,:layout => false\n end",
"def render_404 \n render :file => \"/public/404.html\", :status => 404,:layout => false\n end"
] |
[
"0.77110696",
"0.77004844",
"0.7574277",
"0.7554923",
"0.7553312",
"0.75440806",
"0.75062716",
"0.7448863",
"0.73879445",
"0.73638684",
"0.7361964",
"0.7356699",
"0.7356699",
"0.73452425",
"0.7318466",
"0.7318195",
"0.73162687",
"0.7300782",
"0.7261687",
"0.7255709",
"0.7255709",
"0.7255709",
"0.7255709",
"0.7255709",
"0.7255709",
"0.7230335",
"0.7215414",
"0.7213748",
"0.7205581",
"0.7202793",
"0.72026765",
"0.71875155",
"0.71855277",
"0.7185455",
"0.7146375",
"0.71341825",
"0.71212757",
"0.71212757",
"0.71212757",
"0.70985353",
"0.7079312",
"0.707025",
"0.7063335",
"0.70568156",
"0.7050614",
"0.70420027",
"0.70330626",
"0.70242053",
"0.7022713",
"0.7009118",
"0.7005322",
"0.7003797",
"0.7002645",
"0.6994472",
"0.6969397",
"0.6966194",
"0.69641024",
"0.69641024",
"0.6963687",
"0.69600946",
"0.69599897",
"0.6951552",
"0.69514745",
"0.69279027",
"0.6923178",
"0.6921182",
"0.6920275",
"0.69062066",
"0.6890604",
"0.68892866",
"0.688417",
"0.6882717",
"0.6877071",
"0.68692833",
"0.6863622",
"0.68607163",
"0.68569714",
"0.6836934",
"0.6833947",
"0.68324876",
"0.68315655",
"0.6827974",
"0.6823009",
"0.68185115",
"0.6817795",
"0.6815866",
"0.6812595",
"0.68115586",
"0.6807027",
"0.67977643",
"0.67977643",
"0.67977643",
"0.67977643",
"0.67961925",
"0.67936176",
"0.67936176",
"0.67936176",
"0.67936176",
"0.67936176",
"0.67936176"
] |
0.6971189
|
54
|
Replace this with your real tests.
|
def test_truth
assert true
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def testing\n # ...\n end",
"def __dummy_test__\n end",
"def tests; end",
"def tests; end",
"def spec; end",
"def spec; end",
"def self_test; end",
"def self_test; end",
"def test \n end",
"def test_0_dummy\n\t\tend",
"def test\n\n end",
"def test\n end",
"def test\n end",
"def test\n end",
"def private; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def test_method\n end",
"def before_test(test); end",
"def before_test(test); end",
"def graffiti_test\n end",
"def test_truth\n end",
"def test_should_get_index \n get :index\n assert_response :success #making sure the request was successful\n assert_not_nil (:products) # ensuring that it assigns a valid products instance variable.\n end",
"def test_case; end",
"def test_cases; end",
"def running_test_case; end",
"def test_connection\n end",
"def testloop\n \n end",
"def should; super end",
"def test_nothing\n end",
"def default_test\r\n end",
"def my_tests\n end",
"def test_setup\r\n \r\n end",
"def test_intialize\r\n\tassert_equal 0, @test_prospector.current_gold\r\n\tassert_equal 0, @test_prospector.current_silver\r\n\tassert_equal 0, @test_prospector.total_gold\r\n\tassert_equal 0, @test_prospector.total_silver\r\n\tassert_equal 0, @test_prospector.move_count\r\n\tassert_nil @test_prospector.previous_location\r\n\tassert_equal 0, @test_prospector.num_days\r\n\tassert_equal 'Sutter Creek', @test_prospector.current_location\r\n end",
"def testing_end\n end",
"def test_next_song\n \n \n assert true\n end",
"def specie; end",
"def specie; end",
"def specie; end",
"def specie; end",
"def assertions; end",
"def assertions; end",
"def test_hack\n assert(true)\n end",
"def setup\n\n end",
"def setup\n\n end",
"def setup\n\n end",
"def test_attributes\n assert_equal \"Gallery 1\", @gallery.title\n assert @gallery.active?\n assert_equal \"f82dd0bd-4711-4578-ac47-4661257e69a6\", @gallery.guid\n end",
"def teardown; end",
"def teardown; end",
"def setup\n \n end",
"def setup\n \n end",
"def setup\n \n end",
"def setup\n \n end",
"def setup\n \n end",
"def setup\n \n end",
"def setup\n \n end",
"def before_assert\n end",
"def test_fake_rubies_found\n\t\ttest_main = Main.new(3, 4, 6)\n\t\ttest_graph = Graph.new(10)\n\t\ttest_main.fake_rubies_found(7)\n\t\ttest_main.fake_rubies_found(7)\n\t\tassert test_main.num_fake_rubies, 14\n\tend",
"def setup\n end",
"def setup\n end",
"def setup\n end",
"def setup\n end",
"def setup\n end",
"def setup\n end",
"def test_entry\n raise \"Implement this method in your test class\"\n end",
"def tests_song_not_found\n assert_equal =\n end\n\nend",
"def test_playlist\n end",
"def test_listchunk_attributes\n\t\t\n\tend",
"def love_test\nend",
"def test_entry_attrs\n raise \"Implement this method in your test class\"\n end",
"def test_truth\n assert true\n end",
"def stest_method_1(test); end",
"def teardown\r\n end",
"def default_test\n end",
"def test_037\n\n login\n\n #Create some PUs\n\n for i in 0..2\n create_pu('sample_pu'+i.to_s)\n end\n\n pus = Pu.find_all_by_name('sample_pu1')\n pu = pus.last\n pu.created_at =\"2009-05-08 11:30:50\"\n pu.save\n pus = Pu.find_all_by_name('sample_pu2')\n pu = pus.last\n pu.created_at =\"2008-05-08 14:30:50\"\n pu.save\n @@year = \"2009\"\n @@hour = \"14\"\n\n # Open PU management page\n open_pu_management_page_1\n\n # Arbitrary filtering is performed to PU name.\n assert_equal _(\"PU name\"), get_selected_label(\"find_box\")\n\n\n # you have no relevance\n filtering('3')\n assert !is_text_present('sample_pu1')\n assert !is_text_present('sample_pu2')\n assert is_text_present(_('A PU does not exist.'))\n sleep 2\n\n # Delete created data\n @@pu= Pu.find_by_name('sample_pu1')\n @@pu2= Pu.find_by_name('sample_pu2')\n @@pu.destroy\n @@pu2.destroy\n logout\n end",
"def run_fe_tests\n end",
"def after_test(_test); end",
"def after_test(_test); end",
"def after_test(_test); end",
"def setup; end",
"def tests=(_arg0); end",
"def tests=(_arg0); end",
"def test_truth\n april = riders(:rider_1)\n assert_equal \"April Jones\", april.name\n trigger = horses(:horse_1)\n assert_equal \"Trigger\", trigger.name\n event2 = events(:event_2)\n assert_equal \"5 Horse Scramble\", event2.name\n \n end",
"def test_BooksForAnAuthor\n loginRegisterBazzarVoice\n writeReview \n assert true \n end"
] |
[
"0.7446459",
"0.6956364",
"0.69155836",
"0.69155836",
"0.6864151",
"0.6864151",
"0.66406286",
"0.66406286",
"0.66253287",
"0.6547665",
"0.6524571",
"0.6484549",
"0.6484549",
"0.6484549",
"0.6403847",
"0.6389188",
"0.6389188",
"0.6389188",
"0.6389188",
"0.6389188",
"0.6389188",
"0.6389188",
"0.6389188",
"0.6389188",
"0.6389188",
"0.6389188",
"0.6389188",
"0.6389188",
"0.6389188",
"0.6389188",
"0.6389188",
"0.6389188",
"0.6389188",
"0.6389188",
"0.6385941",
"0.6354074",
"0.6354074",
"0.6350063",
"0.6317573",
"0.6271346",
"0.62341285",
"0.6210424",
"0.6183045",
"0.61626923",
"0.61574936",
"0.6137384",
"0.61362237",
"0.61194503",
"0.611745",
"0.61087",
"0.6098303",
"0.606717",
"0.6058555",
"0.6057699",
"0.6057699",
"0.6057699",
"0.6057699",
"0.6045397",
"0.6045397",
"0.6029009",
"0.60160005",
"0.60160005",
"0.60160005",
"0.6014079",
"0.5998994",
"0.5998994",
"0.5991374",
"0.5991374",
"0.5991374",
"0.5991374",
"0.5991374",
"0.5991374",
"0.5991374",
"0.5989936",
"0.59822077",
"0.59556234",
"0.59556234",
"0.59556234",
"0.59556234",
"0.59556234",
"0.59556234",
"0.5950605",
"0.59497803",
"0.5943133",
"0.59424186",
"0.5932352",
"0.59296894",
"0.5929659",
"0.5917424",
"0.59144044",
"0.5913393",
"0.5905494",
"0.5899468",
"0.58910733",
"0.58910733",
"0.58910733",
"0.5889112",
"0.5883961",
"0.5883961",
"0.5880121",
"0.5877717"
] |
0.0
|
-1
|
Reschedules appointment (only if patient already has one scheduled)
|
def index
appointment_can_cancel_and_reschedule
# If patient already had a dose, keep it in the same UBS.
# This is an optimized query, hence a little odd using +pick+s.
ubs_id = Appointment.where(id: current_patient.doses.pick(:appointment_id)).pick(:ubs_id)
# Otherwise limit to where they can schedule
ubs_id = allowed_ubs_ids if ubs_id.blank?
@days = parse_days
@appointments = scheduler.open_times_per_ubs(from: @days.days.from_now.beginning_of_day,
to: @days.days.from_now.end_of_day,
filter_ubs_id: ubs_id)
rescue AppointmentScheduler::NoFreeSlotsAhead
redirect_to home_community_appointments_path, flash: { alert: 'Não há vagas disponíveis para reagendamento.' }
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def reschedule_appointment\n if @patient.appointments.length < 1\n puts \"You currently have no appointments\"\n sleep(2)\n else\n @prompt.select \"Which appointment would you like to Reschedule?\" do |menu|\n @patient.appointments.each do |appt|\n menu.choice appt.time, -> { change_appt(appt) }\n end\n menu.choice \"<Go Back>\", -> { appointment_system } #back \n end\n end\n @patient.reload\n appointment_system\n end",
"def reschedule_appointment\n if @client.appointments.length < 1\n puts \"You currently have no appointments\"\n sleep(2)\n else\n @prompt.select \"Which appointment would you like to Reschedule?\" do |menu|\n @client.appointments.each do |appt|\n menu.choice appt.time, -> { change_appt(appt) }\n end\n menu.choice \"<Go Back>\", -> { appointment_system } #back \n end\n end\n @client.reload\n\n appointment_system\n end",
"def appointment_reschedule_for_tutor(appointment_id, original_time)\n @appt = Appointment.find(appointment_id)\n @original_time = original_time\n set_appt_variables\n mail(to: @tutor.email, subject: \"Your Axon tutoring appointment has changed\")\n end",
"def schedule_reminder_email\n \tstart_time = Time.at(available_slot.start_time).strftime(' %H:%M')\n \tdate = appointment_date.to_s\n \tschedule_time = (Date.parse(date + start_time) - 30.minutes)\n \tReminderMailer.send_reminder(patient).deliver_later(wait_until: schedule_time)\n end",
"def update_remaining_appointments!(time_to_add)\n remaining_appointments_today.each do |appt|\n appt.update_attribute(:appointment_delayed_time,\n appt.appointment_delayed_time + time_to_add.minutes)\n appt.send_delay_email\n appt.push_delay_notification\n end\n end",
"def perform(appointment_id)\n @appt = Appointment.find(appointment_id)\n @date = @appt.appt_reminder_email_time.to_date\n if @date == Date.today && @appt.status != 'Cancelled'\n AppointmentMailer.appointment_reminder_for_tutor(appointment_id)\n AppointmentMailer.appointment_reminder_for_student(appointment_id)\n end\n end",
"def confirm_reschedule\n reschedule = ApptRescheduler.new(@appt.id, params).format_new_time\n if reschedule[:success] == true\n @new_start_time = reschedule[:new_start_time]\n @new_slot_id = reschedule[:new_slot_id]\n end\n render layout: '../dashboard/student/home/confirm_reschedule'\n end",
"def cancel_appointment appointment\n time_range = TimeRange.new appointment.started_at, appointment.finished_at\n if appointment.daily_schedule_id == self.id\n self.free time_range\n true\n end\n false\n end",
"def update\n appointment = current_user.appointments.find(params[:appointment_id])\n case params[:command]\n when 'schedule'\n appointment.schedule!\n when 'start'\n appointment.start!\n when 'complete'\n appointment.complete!(params[:time_spent_in_min])\n # else\n # TO DO: handle error\n end\n redirect_to root_path\n end",
"def extend()\n # Get the appointment\n appointment = current_user.appointments.last\n student_id = current_user.id\n tutor_id = appointment.tutor.id\n # Get the sidekiq job\n jids = appointment.jids.split('|')\n jid_reminder = jids[0]\n jid_complete = jids[1]\n job_reminder = Sidekiq::ScheduledSet.new.find_job(jid_reminder)\n job_complete = Sidekiq::ScheduledSet.new.find_job(jid_complete)\n complete_new_time = job_complete.at + Settings.call_extend_time\n reminder_new_time = complete_new_time - Settings.call_speak_reminder_time\n\n if job_complete.reschedule(complete_new_time) &&\n job_reminder.reschedule(reminder_new_time)\n # update the appointment cost and call time\n appointment.update_attribute(:amount, appointment.amount + Settings.call_extend_cost)\n appointment.update_attribute(:tutor_earned, appointment.tutor_earned + Settings.call_extend_earned)\n # notify the student and the tutor\n msg = I18n.t('appointment.conference_room.call_extend', \n time: Settings.call_extend_time)\n MessageBroadcastJob.perform_later(msg, 'notification',\n student_id: student_id,\n tutor_id: tutor_id)\n else\n msg = I18n.t('students.errors.appointment.call_extend')\n MessageBroadcastJob.perform_later(msg, 'notification',\n student_id: student_id)\n end\n end",
"def schedule_appointment(appointment, which)\n # sendgrid_category \"Sell Request\"\n @appointment = appointment\n if which == 1\n mail to: @appointment.user.email, subject: \"Appointment schedule confirmation\"\n else\n email = \"tripalink.dev@gmail.com\" if !@appointment.expert\n mail to: email, subject: \"Appointment schedule confirmation\"\n end\n end",
"def update_appointment(appointment_uuid, params={})\n scope 'user_schedule'\n\n put_one(\"schedule/appointments\", appointment_uuid, params)\n end",
"def create\n @appointment = Appointment.new(appointment_params)\n if @appointment.starts_at != nil\n @appointment.ends_at = @appointment.starts_at + 30.minutes\n end\n respond_to do |format|\n if @appointment.save\n format.html { redirect_to new_appointment_path, notice: 'Agendamento realizado.' }\n format.json { render :show, status: :created, location: @appointment }\n else\n format.html { render :schedule }\n format.json { render json: @appointment.errors, status: :unprocessable_entity }\n end\n end\n end",
"def reschedule\n\n h.schedule_id = @context.storage.put_schedule(\n 'cron',\n h.fei,\n h.schedule,\n 'action' => 'reply',\n 'fei' => h.fei,\n 'workitem' => h.applied_workitem)\n\n @context.storage.delete_schedule(h.schedule_id) if try_persist\n #\n # if the persist failed, immediately unschedule\n # the just scheduled job\n #\n # this is meant to cope with cases where one worker reschedules\n # while another just cancelled\n end",
"def book_appointment(appointment_uuid, params = {})\n scope 'user_schedule'\n \n put_one(\"schedule/appointments\", appointment_uuid, params)\n end",
"def process_recurrence(recurrence)\n return true unless recurrence.today?\n recurrence.update_job\n end",
"def resched\n action('resched')\n end",
"def reschedule\n @req = Request.last\n RequestMailer.reschedule(@req)\n end",
"def schedule_repetition\n self.due = Date.today + interval\n self.studied_at = Date.today\n end",
"def expire_appointment\n #if the appointment has not been booked on the day of, the appointment expires. \n if self.expired?\n self.status = Status::EXPIRED\n self.save\n end\n end",
"def reschedule(time)\r\n \"missing time\" if time.nil?\r\n\r\n time_rufus = Rufus.to_datetime time\r\n\r\n @job.unschedule unless (self.time == :forever)\r\n\r\n @job = @scheduler.at time_rufus.to_s do\r\n @timed_out = true\r\n @subscribers.each { |object| object.timed_out }\r\n end\r\n\r\n @time = time\r\n end",
"def destroy\n @appointment = appointment_can_cancel_and_reschedule\n\n scheduler.cancel_schedule(appointment: @appointment)\n\n redirect_to home_community_appointments_path\n end",
"def update_associated_appointments()\n if self.is_payed? # When the receipt is flagged as 'payed', make sure all appointments are too:\n # [Steve, 20100501] The added check on the structure of Appointments is\n # needed to be compliant with the previous version of the structure of the\n # table, otherwise the migration from older DB version fails.\n Appointment.update_all( \"is_payed=1\", ['receipt_id = ?', self.id] ) if Appointment.new.attributes.include?('receipt_id')\n end\n end",
"def appointment_reminder_for_tutor(appointment_id)\n @appt = Appointment.find(appointment_id)\n set_appt_variables \n mail(to: @tutor.email, subject: \"Your upcoming Axon tutoring appointment\")\n end",
"def appt_reminder_email_time\n if self.start_time.to_date > (self.created_at.to_date + 1)\n self.start_time - 12.hours\n end\n end",
"def reschedule\n reminders = DB.read_all(:shrk_reminders)\n reminders.each do |reminder|\n begin\n if Time.parse(reminder[:at]) <= Time.now\n send_reminder(\n SHRK.user(reminder[:user]),\n SHRK.channel(reminder[:channel]),\n Time.parse(reminder[:scheduled]),\n reminder[:message],\n )\n DB.delete_value(:shrk_reminders, :job_id, reminder[:job_id])\n else\n schedule_reminder(\n SHRK.user(reminder[:user]),\n SHRK.channel(reminder[:channel]),\n reminder[:at],\n reminder[:message],\n renew: true\n )\n end\n rescue Exception\n # Bot doesn't have the permissions to send a reminder somewhere.\n DB.delete_value(:shrk_reminders, :job_id, reminder[:job_id])\n end\n end\n end",
"def add_delay\n appointment = Appointment.find(params[:appointment_id])\n time_to_add = params[:delay_time].to_i\n new_time = appointment.appointment_delayed_time + time_to_add.minutes\n if appointment.update_attribute(:appointment_delayed_time, new_time)\n flash[:success] = \"Appointments updated\"\n appointment.send_delay_email\n appointment.push_delay_notification\n if params.keys.include?(\"apply_to_all\")\n appointment.update_remaining_appointments!(time_to_add)\n end\n render status: 200, json: {\n message: 'Appointments updated'\n }\n else\n render status: 400, json: {\n message: 'An error has occured please try again'\n }\n end\n end",
"def update\n\n params[:appointment]['scheduled_at(5i)'] = '0'\n\n @appointment.scheduled_at = DateTime.new(params[:appointment]['scheduled_at(1i)'].to_i,\n params[:appointment]['scheduled_at(2i)'].to_i,\n params[:appointment]['scheduled_at(3i)'].to_i,\n params[:appointment]['scheduled_at(4i)'].to_i,\n params[:appointment]['scheduled_at(5i)'].to_i, 0)\n\n check_for_errors if params[:staff_ids].present?\n\n if @appointment.errors.present?\n render :json => {:success => false, :html => render_to_string(:partial => \"/appointments/errors\")}.to_json\n else\n if @appointment.update(appointment_params)\n create_appointment_users if params[:staff_ids].present?\n flash[:notice]= 'Appointment was successfully updated.'\n render :json => {:success => true,\n :html => render_to_string(:partial => \"/appointments/calandar\"),\n :flash => render_to_string(:partial => \"layouts/flash\")}.to_json\n else\n render :json => {:success => false, :html => render_to_string(:partial => \"/appointments/errors\")}.to_json\n end\n end\n\n end",
"def create\n @app_schedule = AppSchedule.new(app_schedule_params)\n @app_schedule.user_id = current_user.id\n# \n\n\n respond_to do |format|\n if @app_schedule.save\n format.html { redirect_to @app_schedule, notice: 'Appointment was successfully scheduled. Please check your email for confirmation and further details!' }\n format.json { render :show, status: :created, location: @app_schedule }\n @app_schedule.app_time.update_attribute(:booked, true)\n #method from AppointmentMailer that is supposed to prepare mail to be sent\n AppointmentMailer.with(app_schedule: @app_schedule).notify_appointment.deliver!\n AppointmentMailer.with(app_schedule: @app_schedule, user: current_user).appointment_scheduled.deliver!\n #AppointmentMailer.with(app_schedule: @app_schedule, user: current_user).appointment_scheduled.deliver!\n \n\n else\n format.html { render :new }\n format.json { render json: @app_schedule.errors, status: :unprocessable_entity }\n end\n end\n end",
"def next_meeting(after_time = Time.now.utc )\n # puts \"Looking up next meeting after #{after_time}\"\n if recurrence_frequency.blank?\n return start_time\n end\n\n if after_time < start_time\n return start_time\n end \n\n after_time = after_time.local_from_utc(self.time_zone) \n\n\n # Advance the starting time in the case when it falls after the beginning of\n # a meeting on the same day. We do this so that we can use \"day precision\"\n # (PDate.day) in the Runt library instead of \"minute precision\" (PDate.min),\n # which performs terribly.\n start_time = start_time_local\n if(after_time.hour > start_time.hour or ( after_time.hour == start_time.hour and after_time.min > start_time.min))\n after_time = after_time + 1.day\n after_time = Time.gm(after_time.year, after_time.month, after_time.day, 0, 0)\n end\n\n case recurrence_frequency\n when 'daily'\n end_time = after_time + 25.hours \n # after_time -= 1.day\n start_date = PDate.day(after_time.year, after_time.month, after_time.day , after_time.hour, after_time.min)\n end_date = PDate.day(end_time.year, end_time.month, end_time.day, end_time.hour, end_time.min)\n when 'weekdays'\n # Make the range over 3 days so that Friday night searches will still turn\n # up Monday as the next day.\n end_time = after_time + 3.days\n start_date = PDate.day(after_time.year, after_time.month, after_time.day, after_time.hour, after_time.min)\n end_date = PDate.day(end_time.year, end_time.month, end_time.day, end_time.hour, end_time.min)\n when 'monthly'\n eom = (after_time + 40.days)\n start_date = PDate.day(after_time.year, after_time.month, after_time.day)\n end_date = PDate.day(eom.year, eom.month, eom.day)\n when 'weekly'\n eow = (after_time + 8.days)\n start_date = PDate.day(after_time.year, after_time.month, after_time.day)\n end_date = PDate.day(eow.year, eow.month, eow.day)\n when 'yearly'\n # Just doing \"after_time + 367.days\" results in a bit of a performance hit\n # as hundreds of days are compared. We'll try to narrow it a bit. Not too\n # much, because we don't have time to actually write unit tests and make\n # sure the narrowing code works. :) Which is why the comment is here.\n st = after_time + 250.days\n et = st + 150.days\n start_date = PDate.day(st.year, st.month, st.day)\n end_date = PDate.day(et.year, et.month, et.day)\n end \n # puts \" Range #{start_date.to_s} - #{end_date.to_s}\"\n d_range = DateRange.new(start_date, end_date)\n sched = Schedule.new\n event = Event.new((self.invitation.name rescue \"no name\"))\n sched.add(event,self.runt_expression)\n dates = sched.dates(event,d_range)\n\n next_mtg = dates.first\n next_mtg_time = Time.gm(next_mtg.year, next_mtg.month, next_mtg.day, start_time_local.hour, start_time_local.min)\n result = nil\n begin\n result = next_mtg_time.local_to_utc(self.time_zone)\n rescue TZInfo::PeriodNotFound\n # This only happens when the time is during the one hour which is skipped\n # during the transition to DST. For example, only on Sun Mar 08 02:15:00\n # (see ticket #744).\n next_hour = start_time_local.hour + 1\n next_mtg_time = Time.gm(next_mtg.year, next_mtg.month, next_mtg.day, next_hour, start_time_local.min)\n retry\n end\n return result\n end",
"def reschedule(job, time = T.unsafe(nil)); end",
"def complete_appointment\n self.update(completed_appointments: self.completed_appointments += 1)\n end",
"def reschedule\n Logger.debug(klass: self.class, name: :reschedule, message: '')\n timers = @timers.to_a.dup\n @timers.clear\n\n timers.each do |timer|\n timer.reschedule\n add timer\n end\n end",
"def send_update_or_cancel_appt_email(appt_id, appt_params)\n if appt_params[:status] == 'Scheduled'\n AppointmentMailer.delay.appointment_update_for_tutor(appt_id)\n AppointmentMailer.delay.appointment_update_for_student(appt_id)\n end\n if appt_params[:status] == 'Cancelled'\n AppointmentMailer.delay.appointment_cancellation_for_tutor(appt_id)\n AppointmentMailer.delay.appointment_cancellation_for_student(appt_id)\n end\n end",
"def set_app_schedule\n @app_schedule = AppSchedule.find(params[:id])\n end",
"def do_scheduling?\n\t\t!self.scheduled_at.blank?\n\tend",
"def reschedule(time)\n assert_kind_of(Time, time)\n fail \"Time should not be in past\" if time < Time.now\n\n time = Rufus.to_datetime time\n\n self.job.unschedule\n\n self.job = self.scheduler.at time.to_s do\n self.timed_out = true\n self.subscribers.each { |object| object.timed_out }\n end\n end",
"def create\n @appointment = Appointment.new(params[:appointment])\n @appointment.patient_id = current_user.id if current_user.is_patient? \n @appointment.approve_status = 1\n if @appointment.save\n DoctorPatient.create({:patient_id => @appointment.patient_id, :doctor_id => @appointment.doctor_id })\n UserMailer.appointment_pending(@appointment).deliver\n redirect_to \"/appointments\"\n else\n render :new\n end\n end",
"def inspection_shedule#(last_inspect_date)\n \t#self.inspection_at = Date.today\n if self.inspection_at.nil?\n else\n if self.rebuke == true\n next_inspect_at = self.inspection_at.next_day()\n else\n next_inspect_at = self.inspection_at.next_year()\n end\n if next_inspect_at.cwday == 6\n \tself.next_inspection_at = next_inspect_at.next_day(2)\n elsif next_inspect_at.cwday == 7\n \tself.next_inspection_at = next_inspect_at.next_day()\n else\n self.next_inspection_at = next_inspect_at\n end\n end\n end",
"def appointment_complete\n end",
"def create\n if params[:start_date].present?\n mes_para_consulta = params[:start_date].to_date\n else\n mes_para_consulta = Date.current\n end\n\n beginning_of_month = mes_para_consulta.beginning_of_month\n end_of_month = beginning_of_month.end_of_month\n\n @appointments_todos = Appointment.where(schedule_on: beginning_of_month..end_of_month)\n @appointments_todos = @appointments_todos.para_o_calendar(current_user.calendar_id)\n\n\n\n @appointment = Appointment.new(appointment_params)\n @appointment.calendar_id = current_user.calendar_id\n\n respond_to do |format|\n if @appointment.save\n format.html { redirect_to @appointment, notice: t('create_success') }\n format.json { render :show, status: :created, location: @appointment }\n else\n format.html { render :new }\n format.json { render json: @appointment.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @appointment = Appointment.find(params[:id])\n if @appointment.update_attributes(params[:appointment])\n @appointment.approve_status = 1\n @appointment.save\n UserMailer.appointment_pending(@appointment).deliver\n redirect_to \"/appointments\"\n else\n render :edit\n end\n end",
"def schedule_prediction(appointment_id)\n\tend",
"def appointment_pending(appoint_obj)\n @doctor = Doctor.find_by_id(appoint_obj.doctor_id)\n @patient = Patient.find_by_id(appoint_obj.patient_id)\n mail(:to => @doctor.email, :subject => \"New Appointment\")\n end",
"def reschedule (scheduler)\n to_reschedule(scheduler)\n end",
"def appointment(params = {})\n @appointment_id = params.delete :appointment_id\n scope 'user_schedule'\n\n get_one('schedule/appointmenttypes/', @appointment_id, params)\n end",
"def has_appointment?(date, time)\n datetime = Temporal.generate_datetime(date, time)\n\n !is_available?(datetime, 20) #the time is broken up into 20 minute blocks\n end",
"def create\n appointment_request = current_user.pending_requests.new(\n appointment_request_params\n )\n\n if appointment_request.save\n if appointment_request.initialize_appointment!(appointment_params)\n redirect_to root_path\n else\n render json: {\n status: 500,\n error: 'This expert is not available on the scheduled date'\n }, status: 500\n end\n else\n render json: {\n status: 500, error: appointment_request.errors\n }, status: 500\n end\n end",
"def create\n if params.has_key?(:appointment)\n @appointment = Appointment.new(appointment_params)\n @selected_timeslot = Timeslot.where(start: @appointment.start.to_datetime).first\n @appointment.end = (@appointment.start.to_time + 1.hours).to_datetime\n @appointment.faculty_id = @selected_timeslot.faculty_id\n @application_form = ApplicationForm.find(@appointment.application_form_id)\n @candidate = Candidate.find(@application_form.candidate_id)\n @responsible_faculty = Faculty.find(@selected_timeslot.faculty_id)\n @appointment.title = \"Appt. for #{@candidate.full_name} with #{@responsible_faculty.full_name}\"\n @appointment.save\n Timeslot.where(start: @appointment.start.to_datetime).delete_all\n NotificationMailer.appointment_notification(@appointment).deliver_later\n render :json => {success: true, id: @candidate.id}\n else\n render :json => {success: false}\n end\n end",
"def update\n if !Appointment.registred_this_day.where(user_id: current_user.id, appointment_type: appointment_params[:appointment_type]).blank?\n flash[:alert] = t('flash.actions.alert.appointment_exists')\n redirect_to '/appointments'\n return \n end\n respond_to do |format|\n if @appointment.update(appointment_params)\n format.html { redirect_to @appointment, notice: t('flash.actions.notice.appointment_updated') }\n format.json { render :show, status: :ok, location: @appointment }\n else\n format.html { render :edit }\n format.json { render json: @appointment.errors, status: :unprocessable_entity }\n end\n end\n end",
"def set_scheduled_flag(value)\n self.scheduled = value\n self.save!\n end",
"def cancel_appointment(appointment_uuid, params={})\n scope 'user_schedule'\n\n delete_one(\"schedule/appointments\", appointment_uuid, params)\n end",
"def cancel_appointment\n if @patient.appointments.length < 1\n puts \"You currently have no appointments\"\n sleep(2)\n else\n @prompt.select \"Which appointment would you like to cancel?\" do |menu|\n @patient.appointments.each do |appt|\n menu.choice appt.time, -> { appt.destroy } \n end\n menu.choice \"<Go Back>\", -> { appointment_system } #back\n end\n end\n @patient.reload\n appointment_system\n end",
"def update\n respond_to do |format|\n if @app_schedule.update(app_schedule_params)\n AppointmentMailer.with(app_schedule: @app_schedule).update_appointment.deliver!\n AppointmentMailer.with(app_schedule: @app_schedule).notify_appointment_update.deliver!\n format.html { redirect_to @app_schedule, notice: 'Appointment was successfully updated.' }\n format.json { render :show, status: :ok, location: @app_schedule }\n else\n format.html { render :edit }\n format.json { render json: @app_schedule.errors, status: :unprocessable_entity }\n end\n end\n end",
"def makeRecurr\n if repeats\n if recurrence.present?\n if recurrence.events.count == 1\n #We are the only event yet, HOOORAY\n dates = recurrence.getDatesAllInOne\n dates.each do |date|\n date = DateTime.parse(date.to_time.to_s)\n date = date.to_date\n if date != start.to_date\n\n #We do not want to override ourselve\n if !date.past?\n #We do not want to add past events\n time = start.to_time\n newStart = start\n newStart= newStart.to_time.change(day: date.to_time.day, year: date.to_time.year, month: date.to_time.month)\n newEnd = self.end\n newEnd = newEnd.to_time.change(day: date.to_time.day, year: date.to_time.year, month: date.to_time.month)\n newStart = DateTime.parse(newStart.to_s)\n newEnd = DateTime.parse(newEnd.to_s)\n\n newEvent= Event.new(title: self.title, description: self.description,\n event_category: self.event_category, ort: self.ort, role_ids: self.role_ids, url: self.url,\n imageURL: self.imageURL, start: newStart, end: newEnd, repeats: false,\n priority: self.priority, flag: self.flag, author: self.author, manager: self.manager, admin: self.admin, state: self.state, recurrence: self.recurrence)\n newEvent.save!(:validate => false)\n end\n end\n end\n end\n end\n end\n end",
"def notify_ready\n appointment = Appointment.find(params[:appointment_id])\n flash[:danger] = 'Patient has not checked in' unless appointment.checked_in?\n appointment.push_notify_ready\n redirect_to admin_appointments_path(@admin)\n end",
"def update_practice_schedule\n if self.event_type == \"Practice Schedule\"\n update_practice_schedule = PracticeSchedule.find_by(id: self.practice_tag)\n if update_practice_schedule.title != self.title || update_practice_schedule.start_time != self.start_time \n update_practice_schedule.update :title => self.title, :start_time => self.start_time\n end \n end\n end",
"def evaulate_schedule\n true\n end",
"def ask_fill_appointment(user, orig_appointment, new_time)\n @user = user\n @orig_appointment = orig_appointment\n @new_time = new_time\n\n mail to: user.email, subject: 'Appointment time change request'\n end",
"def reschedule\n timers = nil\n\n timers = @timers.dup\n @timers.clear\n\n timers.each do |timer|\n timer.reschedule\n add timer\n end\n end",
"def add_to_scheduler\n name = \"for_survey_#{@schedulable.company_survey.id}\"\n config = {}\n config[:every] = [\"#{@schedulable.repeat_every}#{@schedulable.repeat_mode}\",\n { first_at: calculate_next_delivery }]\n config[:class] = 'SendEmailsJob'\n config[:queue] = 'send_emails'\n config[:persist] = true\n config[:args] = @schedulable.company_survey.id\n Resque.set_schedule(name, config)\n end",
"def reschedule_at(time, attempts)\n case attempts\n when (0..4)\n interval = 1.minute\n when (5..6)\n interval = 5.minutes\n else\n interval = 10.minutes\n end\n time + interval\n end",
"def reschedule_at(time, attempts)\n case attempts\n when (0..4)\n interval = 1.minute\n when (5..6)\n interval = 5.minutes\n else\n interval = 10.minutes\n end\n time + interval\n end",
"def update\n @scheduled_appointment = ScheduledAppointment.find(params[:id])\n\n respond_to do |format|\n if @scheduled_appointment.update_attributes(params.require(:scheduled_appointment).permit(:actual_date_time, :date_time, :purpose, :status, :store_id, :vehicle_id))\n format.html { redirect_to scheduled_appointments_url,\n notice: 'ScheduledAppointment was successfully updated.' }\n format.json { head :no_content }\n else\n prepFormVariables(@scheduled_appointment)\n format.html { render action: \"edit\" }\n format.json { render json: @scheduled_appointment.errors, status: :unprocessable_entity }\n end\n end\n end",
"def set_appointment\n @appointment = current_user.appointments.find(params[:id])\n end",
"def set_app_appointment\n @app_appointment = AppAppointment.find(params[:id])\n end",
"def add_appointment(appointment)\n @appointments << appointment\n appointment.patient = self\n end",
"def reschedule_at(current_time, attempts)\n current_time + ((attempts**4) + 1).hours\n end",
"def update\n @appointment = Appointment.find(params[:id])\n @appointment.available = true\n @appointment.student_id = nil\n @appointment.save\n if @appointment.save\n redirect_to :back and return\n else\n flash[:notice] = \"Post successfully created\"\n end\n end",
"def set_appointment\n @appointment = Appointment.find_by(id: params[:id])\n end",
"def populate_with_appointments(\n appointments_start_dates\n )\n appointments_start_dates.each do |start_date|\n expert = Expert.find(expert_id)\n if expert.available_for_datetime(start_date)\n appointment = appointments.new(\n user_id: user_id,\n service_id: service_id,\n expert_id: expert_id,\n description: description,\n start_date: start_date,\n duration_in_min: service.duration_in_min,\n type: 'OpenAppointment'\n )\n\n if appointment.save\n appointments << appointment\n true\n else\n puts \"---- 🔸 FAILURE | while saving appointment \\\n error:#{appointment.errors.messages}🔸\\\n in populate_with_appointments\"\n false\n end\n else\n puts \"---- 🔸 FAILURE | Expert(#{expert.id}) not available for \\\n start_date #{start_date}🔸in populate_with_appointments\"\n return false\n end\n end\n end",
"def update\n begin\n @appointment = Appointment.find(params[:id])\n rescue\n respond_info('error', 'internal_server_error', 'Update Appointment Failed', :internal_server_error)\n return\n end\n if @appointment.update(appointment_params)\n render :json => @appointments, :status => :no_content #HTTP status code: 204 No Content\n else\n render json: @appointment.errors, status: :unprocessable_entity\n end\n end",
"def preschedule_ct(ct)\n assign_package_for(ct, reservation: true)\n end",
"def set_appointment\n @appointment = Appointment.find(params[:id])\n end",
"def set_appointment\n @appointment = Appointment.find(params[:id])\n end",
"def set_appointment\n @appointment = Appointment.find(params[:id])\n end",
"def set_appointment\n @appointment = Appointment.find(params[:id])\n end",
"def set_appointment\n @appointment = Appointment.find(params[:id])\n end",
"def set_appointment\n @appointment = Appointment.find(params[:id])\n end",
"def set_appointment\n @appointment = Appointment.find(params[:id])\n end",
"def set_appointment\n @appointment = Appointment.find(params[:id])\n end",
"def set_appointment\n @appointment = Appointment.find(params[:id])\n end",
"def set_appointment\n @appointment = Appointment.find(params[:id])\n end",
"def set_appointment\n @appointment = Appointment.find(params[:id])\n end",
"def set_appointment\n @appointment = Appointment.find(params[:id])\n end",
"def set_appointment\n @appointment = Appointment.find(params[:id])\n end",
"def set_appointment\n @appointment = Appointment.find(params[:id])\n end",
"def set_appointment\n @appointment = Appointment.find(params[:id])\n end",
"def set_appointment\n @appointment = Appointment.find(params[:id])\n end",
"def set_appointment\n @appointment = Appointment.find(params[:id])\n end",
"def set_appointment\n @appointment = Appointment.find(params[:id])\n end",
"def set_appointment\n @appointment = Appointment.find(params[:id])\n end",
"def set_appointment\n @appointment = Appointment.find(params[:id])\n end",
"def setAppointment\n @appointment = Appointment.find(params[:id])\n end",
"def set_timer\n request = Request.find_by(pet_id: @pet.id)\n request.schedule = params[\"request\"][\"schedule\"]\n request.save\n flash[:notice] = \"Your feeding has been scheduled. You can schedule another feeding time by clicking 'Schedule a Feeding'\"\n\n add_new_schedule\n\n redirect_to root_path\n end",
"def set_appointment\n @appointment = Appointment.find(params[:id])\n end",
"def set_appointment\n @appointment = Appointment.find(params[:id])\n end",
"def set_appointment\n @appointment = Appointment.find(params[:id])\n end",
"def set_appointment\n @appointment = Appointment.find(params[:id])\n end",
"def set_appointment\n @appointment = Appointment.find(params[:id])\n end"
] |
[
"0.7332421",
"0.68552125",
"0.662466",
"0.66214067",
"0.6618574",
"0.63865274",
"0.6362172",
"0.62956506",
"0.62207866",
"0.60593146",
"0.6054434",
"0.5986129",
"0.5941495",
"0.59408975",
"0.5926577",
"0.5901622",
"0.58974963",
"0.5870843",
"0.58073866",
"0.58059263",
"0.58036286",
"0.57954717",
"0.57952803",
"0.5789994",
"0.5772522",
"0.57513756",
"0.5743676",
"0.57272553",
"0.5701549",
"0.5698414",
"0.56925404",
"0.5689114",
"0.56787497",
"0.56442136",
"0.56148344",
"0.56019765",
"0.56007004",
"0.55922633",
"0.55769676",
"0.55555487",
"0.55499184",
"0.55476665",
"0.5543226",
"0.55173856",
"0.5510438",
"0.5503333",
"0.55002415",
"0.54966843",
"0.5494585",
"0.5484707",
"0.54366237",
"0.5434744",
"0.5408356",
"0.5407082",
"0.5400666",
"0.5399713",
"0.5389987",
"0.5388334",
"0.5375292",
"0.5372191",
"0.53704953",
"0.53628445",
"0.53628445",
"0.5355398",
"0.5354346",
"0.53432006",
"0.5340576",
"0.5338213",
"0.5323033",
"0.53077364",
"0.530622",
"0.5296487",
"0.5275348",
"0.5273287",
"0.5273287",
"0.5273287",
"0.5273287",
"0.5273287",
"0.5273287",
"0.5273287",
"0.5273287",
"0.5273287",
"0.5273287",
"0.5273287",
"0.5273287",
"0.5273287",
"0.5273287",
"0.5273287",
"0.5273287",
"0.5273287",
"0.5273287",
"0.5273287",
"0.5273287",
"0.5261374",
"0.5258067",
"0.5257632",
"0.5257632",
"0.5257632",
"0.5257632",
"0.5257632"
] |
0.5329317
|
68
|
rubocop:enable Metrics/AbcSize NOTE: we are ignoring params[:id] in here
|
def destroy
@appointment = appointment_can_cancel_and_reschedule
scheduler.cancel_schedule(appointment: @appointment)
redirect_to home_community_appointments_path
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def id_param\n params[:id]\n end",
"def id\n @params[\"id\"]\n end",
"def id\n params[:id] \n end",
"def id\n params[:id]\n end",
"def params\n { id: 3 }\n end",
"def get_id\n params[:id]\n end",
"def paramsid\n @order = Order.find_by(params[:id])\n params[:id]= @order.id\n end",
"def id_params\n params.require(:id).permit(:url, :hashcode, :created, :updated)\n end",
"def to_param\n id\n end",
"def to_param\n id\n end",
"def add_dummy_destroy_id\n params[:id] ||= 0\n end",
"def initialize(params)\n super\n @id = params[:id]\n end",
"def resource_id_param\n params[:id]\n end",
"def raise_if_no_id(params)\n raise 'No ID to make request' unless !params[:id].nil?\n end",
"def id\n object.to_param\n end",
"def to_param\n id\n end",
"def get_id\n allowed_params = params.permit(:id, :ref, :path)\n\n id = [allowed_params[:id] || allowed_params[:ref]]\n id << \"/\" + allowed_params[:path] unless allowed_params[:path].blank?\n id.join\n end",
"def id\n [\"#{name}_id\", \"#{model_name}_id\", 'id'].uniq.\n map { |id| controller.params[id] }.find(&:present?)\n end",
"def user_id_params\n @user_id = User.find_by(id: params[:id])\n @user_id\n end",
"def validation\n param! :id, String, required: true, blank: false\n end",
"def params_permit\n params.permit(:id)\n end",
"def add_dummy_create_id\n params[:data] ||= {}\n params[:data][:id] ||= 0\n end",
"def set_id\n @id = Id.find(params[:id])\n end",
"def to_param\n id && id.to_s\n end",
"def prefecture_params\n params.require(:id)\n end",
"def receive_id\n id = params[:id] # receive Id from\n @movie = Movie.find(id)\n end",
"def find_params_id(model)\n model.find(params[:id])\n rescue Exception => e\n redirect_with_flash(e.message) and return nil\n end",
"def to_param\n # We can't use alias_method here, because method 'id' optimizes itself on the fly.\n id&.to_s # Be sure to stringify the id for routes\n end",
"def show\n @id = params[:id].to_i\n end",
"def to_param\n self.id.to_s\n end",
"def to_param\n id.to_s\n end",
"def id_or_param(id)\n id = id.to_param if id.respond_to?(:to_param)\n id\nend",
"def params_for_get\n \"params[:id]\"\n end",
"def id\n\t\t@id\n\tend",
"def to_param\n # We can't use alias_method here, because method 'id' optimizes itself on the fly.\n id && id.to_s # Be sure to stringify the id for routes\n end",
"def update\n respond_to do |format|\n if @id.update(id_params)\n format.html { redirect_to @id, notice: 'Id was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @id.errors, status: :unprocessable_entity }\n end\n end\n end",
"def id_param(options)\n options.delete(:id)\n end",
"def find(id)\n end",
"def id\n @id\n end",
"def id\n @id\n end",
"def by_id(id)\n raise NotImplementedError.new\n end",
"def to_param\n id.to_s\n end",
"def to_param\n id.to_s\n end",
"def find\n if !request.accept || request.accept == \"*/*\"\n render plain: \"#{params[:id]}\"\n elsif request.accept && request.accept != \"*/*\"\n if params[:id].exists?\n render plain: \"\", status: :ok\n else\n render plain: \"\", status: 404\n end\n else\n end\n end",
"def trackable_id\n params['id'] || first_item_on_page_id\n end",
"def clean_params_for_save!\n if params[resource_param_name].present?\n params[resource_param_name].delete(:id)\n params[resource_param_name].delete(:user_id)\n end\n end",
"def find(id); end",
"def find(id); end",
"def to_param\n hashed_id\n end",
"def get_id\n\t\treturn id\n\tend",
"def show\n @id = params[:id]\n end",
"def show\n @id = params[:id]\n end",
"def get_listing_from_id\n #convert URL id to integer and set into instance var listing_id\n @listing_id = params[:id].to_i\n #look up the listing based on id and cast into instance var\n @listing = Listing.find_by_id(@listing_id)\n #if no listing found redirect back to previous page with error\n if !@listing\n flash[:error] = \"That listing does not exist\"\n custom_redirect_back\n end\n end",
"def id; end",
"def id; end",
"def id; end",
"def id; end",
"def id; end",
"def id; end",
"def id; end",
"def id; end",
"def id; end",
"def id; end",
"def id; end",
"def id; end",
"def id\n data[:id]\n end",
"def get_id\n @id\n end",
"def get_id\n @id\n end",
"def get_id\n @id\n end",
"def get_id\n @id\n end",
"def return_to_current_user\n\t\tparams[:id] = params[:id].eql?(current_user.id) ? params[:id] : current_user.id\n\tend",
"def identify(id)\n @id = id\n end",
"def id\n #NOOP\n end",
"def show(params = {})\n validate_id(params)\n submit(id_url(params.delete(:id)), :get)\n end",
"def show\n unless /\\d+/.match(params[:id])\n return \n end\n end",
"def id\n return @id\n end",
"def get_param_by_id(id)\n param = nil\n @params.each do |p|\n if p['id'] == id\n param = p\n end\n end\n return param\n end",
"def get_param_by_id(id)\n param = nil\n @params.each do |p|\n if p['id'] == id\n param = p\n end\n end\n return param\n end",
"def set_id(erb_id)\n params[:id] = nil\n dyn_params[:id] = erb_id\n end",
"def actual_id\n args = params[:id].split('-')\n args[0]\n end",
"def create\n @id = Id.new(id_params)\n\n respond_to do |format|\n if @id.save\n format.html { redirect_to @id, notice: 'Id was successfully created.' }\n format.json { render action: 'show', status: :created, location: @id }\n else\n format.html { render action: 'new' }\n format.json { render json: @id.errors, status: :unprocessable_entity }\n end\n end\n end",
"def id\n nil\n end",
"def id\n nil\n end",
"def id\n nil\n end",
"def id\n nil\n end",
"def id\n nil\n end",
"def id\n nil\n end",
"def id\n nil\n end",
"def id\n nil\n end",
"def id\n nil\n end",
"def customer_order_details\n @id = params[:id]\n end",
"def find(id)\n\nend",
"def validate_id_params!\n raise ArgumentError, 'Only one of :identifier, :id is permitted' if params[:identifier] && params[:id]\n raise ArgumentError, ':identifier must be scoped to a :project or :common' if params[:identifier] && !(params[:project] || params[:common])\n end",
"def id\r\n @id\r\n end",
"def id=(id)\n end",
"def find(id, params = {})\n from_base id, params\n end",
"def id\n @options[:id] \n end",
"def id_param_keys\n %i[selected id]\n end",
"def id\n raise \"Method 'id' must be defined\"\n end",
"def id\n get_val(:id)\n end",
"def id\n @id\n end"
] |
[
"0.7004771",
"0.68418974",
"0.6832365",
"0.6828235",
"0.6719394",
"0.67067164",
"0.63821185",
"0.6354838",
"0.6291008",
"0.6250319",
"0.61564755",
"0.6141194",
"0.6127795",
"0.61110264",
"0.60916585",
"0.60757804",
"0.60621786",
"0.6051046",
"0.60508794",
"0.6040015",
"0.60282046",
"0.6018497",
"0.6003921",
"0.59689695",
"0.59548855",
"0.59023464",
"0.5880742",
"0.5873847",
"0.5864447",
"0.58559245",
"0.5818927",
"0.5816093",
"0.5812716",
"0.5796988",
"0.57947224",
"0.5789843",
"0.5762309",
"0.57484996",
"0.57474774",
"0.57474774",
"0.5740904",
"0.5723409",
"0.5723409",
"0.5719481",
"0.57173705",
"0.5705976",
"0.56833977",
"0.56833977",
"0.5677557",
"0.5676058",
"0.5669592",
"0.5669592",
"0.56631345",
"0.5658568",
"0.5658568",
"0.5658568",
"0.5658568",
"0.5658568",
"0.5658568",
"0.5658568",
"0.5658568",
"0.5658568",
"0.5658568",
"0.5658568",
"0.5658568",
"0.5639997",
"0.56379956",
"0.56379956",
"0.56379956",
"0.56379956",
"0.56295824",
"0.5620028",
"0.5617979",
"0.56038",
"0.55951524",
"0.5585285",
"0.55723685",
"0.55723685",
"0.5560968",
"0.5557017",
"0.5550174",
"0.55401933",
"0.55401933",
"0.55401933",
"0.55401933",
"0.55401933",
"0.55401933",
"0.55401933",
"0.55401933",
"0.55401933",
"0.55377555",
"0.5524395",
"0.55200076",
"0.5517702",
"0.5509592",
"0.550809",
"0.5505974",
"0.55052584",
"0.5498818",
"0.54906356",
"0.5489489"
] |
0.0
|
-1
|
Loads pages for the Index, between 0 and max possible allowed
|
def parse_days
[
[
0,
params[:page].presence&.to_i || scheduler.days_ahead_with_open_slot
].compact.max,
Rails.configuration.x.schedule_up_to_days
].min
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def index\n get_own_documents\n if @page > @pages_amount && @pages_amount != 0\n @page = @pages_amount\n get_own_documents\n end\n render_js_or_html_index\n end",
"def max_pages() 1 end",
"def pages; end",
"def index\n get_own_lessons\n if @page > @pages_amount && @pages_amount != 0\n @page = @pages_amount\n get_own_lessons\n end\n render_js_or_html_index\n end",
"def index_pages\n debug_msg \" generating pages search index\"\n\n pages = @files.select do |file|\n file.text?\n end\n\n pages.each do |page|\n debug_msg \" #{page.page_name}\"\n record = page.search_record\n @index[:searchIndex] << search_string(record.shift)\n @index[:longSearchIndex] << ''\n record.shift\n @index[:info] << record\n end\n end",
"def index\n @root_pages = [fetch_root_page].flatten\n end",
"def index\n #Page.all is fine for small sets of data, for larger sets pagination would be best\n @pages = data_cache('pages', 10.minutes) do\n Page.all\n end\n respond_to do |format|\n format.json { render action: 'index', status: :ok, location: api_pages_url(@pages) }\n format.xml { render xml: @pages, location: api_pages_url(@pages) }\n end\n end",
"def index\n respond_with(@pages = Page.all.paginate(:page => params[:page] || 1, :per_page => params[:per_page] || 5))\n end",
"def index\n @all_entries = Entry.all\n @max_pages = @all_entries.max_pages\n @recent = @all_entries.page\n\n if page_params[:page]\n\n if page_params[:page].to_i > @max_pages.to_i or page_params[:page].to_i < 1\n redirect_to root_url, notice: 'Page does not exist. Only 1 through ' + @max_pages.to_s + ' pages exist.'\n end\n\n @entries = @all_entries.page(page_params[:page].to_i)\n @current_page = page_params[:page]\n else\n @entries = @all_entries.page\n @current_page = 1\n end\n\n end",
"def index\n get_own_media_elements\n if @page > @pages_amount && @pages_amount != 0\n @page = @pages_amount\n get_own_media_elements\n end\n render_js_or_html_index\n end",
"def generate_indexes\n @first_page = first_page\n generate_index('index')\n generate_index('indexes')\n end",
"def index\n #@long_pages = LongPage.all\n @long_pages = LongPage.all.page params[:page]\n end",
"def index\n pages = Page.find_by_sql(\"select * from pages\").map { |page| {page: page} }\n if params[:page]\n @pages = get_page_and_offset(13, params[:page].to_i, pages)\n else\n @pages = get_page_and_offset(13, 1, pages)\n end\n\n respond_to do |format|\n format.html\n format.js {render 'paginate_pages.js.erb'}\n end\n end",
"def pages\n end",
"def index\n @page_chunks = PageChunk.all\n end",
"def index\n @pages = Page.all\n end",
"def index\n @pages = Page.all.order(\"id desc\").page(params[:page]).per_page(8)\n \n end",
"def index\n authorize IndexPage\n @index_pages = IndexPage.\n where(institution: current_institution).\n order(:name)\n end",
"def index\n @pages = Page.all\n end",
"def index\n @pages = Page.all\n end",
"def index\n @pages = Page.all\n end",
"def index\n @pages = Page.all\n end",
"def index\n @pages = Page.all\n end",
"def index\n @pages = Page.all\n end",
"def index\n @pages = Page.all\n end",
"def index\n @pages = Page.all\n end",
"def index\n @pages = Page.all\n end",
"def index\n @pages = Page.all\n end",
"def index\n @root_pages = Page.root_pages\n @uncategorized_pages = Page.uncategorized\n end",
"def index\n @pages = Page.all\n respond_with(@pages)\n end",
"def index\n @urls = Url.all.order(\"pageviews DESC\").limit(100)\n end",
"def index\n @page_pages = PagePage.all\n end",
"def index\n\t\t@page = ContentPage.find_by_home(true)\n\tend",
"def index\n @main_pages = MainPage.all\n end",
"def index\n @pages = apply_scopes(Page.includes(:versions)).by_title.page params[:page]\n authorize @pages\n end",
"def index\n if params.count <= 3 && cookies['st_admin_setup']\n CGI.parse(cookies['st_admin_setup']).each{|x|\n name = x[0]\n value = x[1][0]\n params[name] = value\n }\n end\n # Update number of items to show on page (if supplied)\n Page.per_page = params[:per_page].to_i if params[:per_page]\n Page.per_page = 10 if Page.per_page <= 0\n\n @authors = Page.select('DISTINCT(author_id)')\n\n @pages = Page.get_my_pages :user => current_user,\n :page_no => params[:page] || 1,\n :locale => I18n.locale,\n :sort => (\"#{sort_column} #{sort_direction}\"),\n :search => params[:search],\n :flocale => params[:flocale],\n :filter => {:status => params[:status], :page_type => params[:page_type], :author => params[:author]}\n end",
"def index\n respond_with(pages)\n end",
"def pages\n @pages ||= []\n end",
"def index\n @title = \"All pages\"\n @pages = Page.all\n end",
"def index\n return check_logged_in unless current_user\n @pages = current_user.pages\n end",
"def index\n @pages = Page.paginate(\n :select => 'id, name, protected', \n :page => params[:page], \n :order => sort_calc('name', {:table => 'pages'})\n )\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @pages }\n end\n end",
"def index\n @contentperpages = Contentperpage.all\n end",
"def index\n @pages = Page.all\n render layout: 'application'\n end",
"def index\n @admin_pages = Page.all\n\n respond_to do |format|\n format.html # index.html.erb\n end\n end",
"def index\n @pages = Static.all\n end",
"def index\n respond_with(@navlinks = Navlink.all_main_links.paginate(:page => params[:page] || 1, :per_page => params[:per_page] || 10))\n end",
"def scan_pages0( index, directory )\n unless index\n index = Page.new( File.join( directory, \"index.src\" ) )\n @root = index \n end\n \n @subdir_pages = get_nondir_pages( directory )\n @nondir_pages = get_subdir_pages( directory )\n \n @nondir_pages.each do |page_src|\n Page.new( page_src, index )\n end\n @subdir_pages.each do |page_src|\n page = Page.new( page_src, index )\n scan_pages( config, page, File.dirname( page_src ) )\n end\n end",
"def index\n self.resources = resource_class.all.paginate(per_page: 15, page: (params[:page] || 1).to_i)\n end",
"def pages\n @pages ||= get_pages\n end",
"def get_pages\n @pages << base_gallery_url\n (@doc/\"a\").select{|a| a[\"href\"] =~ /ndxpage/}.each do |e|\n @pages << base_gallery_url_prefix + e[\"href\"]\n end\n puts \"got pages!\"\n puts @pages.inspect\n puts \"---\"\n end",
"def index\n\t\t@section = 'pages'\n\t\t@key = params[:key]\n\t\tif params[:id] and params[:id].to_i > 0\n\t\t\t@page = Page.find(params[:id], :include=>[:children, :path])\n\t\t\t@pages = @page.children\n\t\t\t@key = nil\n\t\t\t@page_title = \"Site Index: #{@page.title}\"\n\t\telsif !(@key.blank?)\n\t\t\t@page = nil\n\t\t\t@pages = Page.find(:all,\n\t\t\t\t:conditions=>Page.search_conditions({:key=>@key, :u=>current_user}),\n\t\t\t\t:order=>Page.default_order, :include=>Page.default_include)\n\t\t\t@page_title = \"Site Index: ‘#{params[:key]}’\"\n\t\telse\n\t\t\t# find all top-level pages\n\t\t\t@page = nil\n\t\t\t@pages = Page.find_homes\n\t\t\t#if @page\n\t\t\t#\tconditions = ['(pages.parent_id IS NULL OR pages.parent_id = ?) AND pages.id != ?',\n\t\t\t#\t\t@page.id, @page.id]\n\t\t\t#else\n\t\t\t#\tconditions = ['pages.parent_id IS NULL']\n\t\t\t#end\n\t\t\t#@pages = Page.find(:all,\n\t\t\t#\t:conditions=>conditions,\n\t\t\t#\t:order=>'pages.title',\n\t\t\t#\t:include=>:children)\n\t\t\t@page_title = \"Site Index\"\n\t\tend\n\t\trespond_to do |format|\n\t\t\tformat.html # index.html.erb\n\t\t\tformat.js { render :action=>'index_sublist', :layout=>false }\n\t\t\tformat.xml { render :xml => @pages.to_xml }\n\t\tend\n\tend",
"def index\n @organization_pages, @organizations = paginate :organizations, :per_page => 25, :order => \"position\"\n render :action => \"index\", :layout => false if request.xhr?\n end",
"def index\n @scraping_pages = ScrapingPage.all\n end",
"def index\n @instances = Instance.page params[:page]\n authorize! :read, @instances\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @instances }\n end\n end",
"def index\n @pages = @club.all_pages\n \n @page_title = \"Page Listing\"\n @site_section = \"clubs\"\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @pages }\n end \n end",
"def index\n @memories = Memory.paginate(page: params[:page], per_page: 4)\n end",
"def index\n @pages = Page.paginate :page => params[:page], :order => 'id DESC'\n end",
"def index\n if @current_website.present?\n @pages = @current_website.pages\n else\n @pages = Page.all\n end\n render layout: \"themes/basic/layout\"\n end",
"def index\n @pages = Page.all\n respond_with(@pages)\n end",
"def index\n @pages = Page.all\n respond_with(@pages)\n end",
"def index\n @map_nodes = Map::Node.paginate(:page => params[:page], :per_page => 64)\n\n respond_to do |format|\n format.html # index.html.erb\n end\n end",
"def index\n load_data\n end",
"def index\n @page = Page.find(params[:page_id])\n @urls = Url.where(page_id: params[:page_id])\n end",
"def index\n \n # Check if there is parameter num_to_return, otherwise set to the default number\n #num_to_return = params[:num_to_return].nil? ? 12 : params[:num_to_return]\n #@locations = Location.limit(num_to_return)\n @locations = Location.paginate(page: params[:page], :per_page => 18, :total_entries => 900)\n\n end",
"def load_page\n @page = params[:page] || '1'\n @per_page = (params[:limit] || '30').to_i\n @per_page = 30 if @per_page > 30\n true\n end",
"def index\n @dynamic_project_pages = DynamicProjectPage.all\n end",
"def index\n #@site_pages = SitePage.all\n end",
"def c_page(n)\n BestiaryConfig::PAGEFX.play\n self.index += n\n end",
"def max_numbered_pages\n 1_000\n end",
"def index\r\n @admin_heuristics = Admin::Heuristic.paginate(page: params[:page], per_page: 10)\r\n end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end"
] |
[
"0.7411076",
"0.68576556",
"0.6827612",
"0.67234236",
"0.66899747",
"0.6652818",
"0.6623177",
"0.6610252",
"0.65775007",
"0.657468",
"0.65723723",
"0.65657055",
"0.6531315",
"0.6527085",
"0.65252155",
"0.64960486",
"0.643862",
"0.6435568",
"0.6403065",
"0.6403065",
"0.6403065",
"0.6403065",
"0.6403065",
"0.6403065",
"0.6403065",
"0.6403065",
"0.6403065",
"0.6403065",
"0.6396225",
"0.6394692",
"0.63649625",
"0.63640296",
"0.6264581",
"0.6254633",
"0.6238429",
"0.6212832",
"0.6205106",
"0.6181164",
"0.6162269",
"0.6158776",
"0.6158381",
"0.6154852",
"0.6153691",
"0.6153543",
"0.6148823",
"0.614733",
"0.61261743",
"0.6123792",
"0.61171156",
"0.61159694",
"0.61146337",
"0.6114567",
"0.6114188",
"0.610178",
"0.60943836",
"0.60875505",
"0.60835624",
"0.6081156",
"0.6079658",
"0.6079658",
"0.6067524",
"0.6059595",
"0.6046686",
"0.6044807",
"0.60379285",
"0.6032781",
"0.60305417",
"0.60289633",
"0.60267264",
"0.6019004",
"0.6011105",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936",
"0.60104936"
] |
0.0
|
-1
|
Returns a Hash for the given Recipe id ID of the recipe Returns a Hash
|
def show(id)
response = request(:get, "/recipes/#{id}.json")
response.first[1]
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def recipe (recipe_id, name)\n if recipe_id\n this_recipe = Recipe.find(recipe_id.to_i)\n else\n this_recipe = Recipe.find_by(name)\n end\n\n creation = {\n :name => this_recipe[:name],\n :instructions => this_recipe.instructions.all,\n :ingredients => this_recipe.ingredients.all\n }\n # return the object\n creation\n end",
"def hash\n id\n end",
"def hash\n id.hash\n end",
"def hash\n id.hash\n end",
"def hash\n id.hash\n end",
"def hash\n id.hash\n end",
"def hash\n id.hash\n end",
"def hash\n id.hash\n end",
"def hash\n id.hash\n end",
"def hash\n id.hash\n end",
"def hash\n id.hash\n end",
"def hash\n id.hash\n end",
"def hash\n id.hash\n end",
"def hash\r\n id.hash\r\n end",
"def get_recipe_by_id(recipe_id)\n\t\t\t\trecipe = Recipe.find_by(id: recipe_id)\n\t\t\t\trecipe.tags = RecipeTag.where('recipe_id = ?', recipe.id).pluck(:tag)\n\t\t\t\trecipe.ingredients = RecipeIngredient.where('recipe_id = ?', recipe.id).pluck(:ingredient)\n\n\t\t\t\treturn recipe\n\t\t\tend",
"def hash\n id.hash\n end",
"def hash\n id.hash\n end",
"def hash\n @id.hash\n end",
"def hash\n @id\n end",
"def hash\n return @id.hash\n end",
"def hash\n @id\n end",
"def id_to_hash(id)\n return \"\" unless id\n Base64.encode64(id.to_s + DIVIDER + encode(id)).chomp\n end",
"def hash\n\t\t[@id].hash\n\tend",
"def get_id_checksum_hash(locale)\n #Gather all ids to retrieve from the db\n ids = Array.new\n Dir.glob(\"*/*\") do | file_name |\n if (file_name.end_with? \"deliverable_metadata.json\")\n ids.push(get_deliverable_metadata_id(locale, Settings[:CURRENT_VERSION], file_name.split(\"/\")[0])) \n elsif (file_name.end_with? \".toc\")\n ids.push(get_toc_id(locale, Settings[:CURRENT_VERSION], file_name.split(\"/\")[0]))\n elsif (file_name.end_with?(\".htm\", \".html\"))\n ids.push(get_topic_or_image_id(locale, Settings[:CURRENT_VERSION], file_name))\n end\n end\n \n #get the id,hash results \n rows = @db.view(\"content_views/checksum_by_id\", :keys => ids)['rows']\n id_checksum_hash = Hash.new(rows.size)\n \n #store it in a hash\n rows.each { |result|\n id_checksum_hash[result[\"key\"]] = result[\"value\"]\n }\n return id_checksum_hash\n end",
"def to_hash\n {\n 'id' => id,\n }\n end",
"def hash\n id.hash + 32 * bs_request.hash\n end",
"def hash\n [searchable_id].hash\n end",
"def to_hash\n { :id => @id }\n end",
"def hash\n [@id].hash\n end",
"def id\n @hash[\"id\"]\n end",
"def get_recipe(id)\n recipe = Recipe.find(id)\n url = \"https://api2.bigoven.com/recipe/steps/#{recipe.id}?&api_key=#{ENV['API_KEY']}\"\n uri = URI(url)\n response = Net::HTTP.get(uri)\n # puts response\n\n JSON.parse(response)[\"Ingredients\"].each do |ingredient|\n # recipe.ingredients.create!(\n if (!Ingredient.exists?(ingredient[\"IngredientID\"])) \n Ingredient.create!(\n id: ingredient[\"IngredientID\"],\n name: ingredient[\"Name\"],\n html_name: ingredient[\"HTMLName\"]\n )\n end\n end\n\n if (recipe.recipe_ingredients.count > 0)\n recipe.recipe_ingredients.destroy_all\n recipe.save\n recipe.reload\n end\n\n JSON.parse(response)[\"Ingredients\"].each do |ingredient|\n \n # if (!recipe.recipe_ingredients.find_by(ingredient_id: ingredient[\"IngredientID\"]))\n recipe.recipe_ingredients.create!(\n ingredient_id: ingredient[\"IngredientID\"],\n quantity: ingredient[\"Quantity\"],\n display_quantity: ingredient[\"DisplayQuantity\"],\n unit: ingredient[\"Unit\"],\n metric_quantity: ingredient[\"MetricQuantity\"],\n metric_display_quantity: ingredient[\"MetricDisplayQuantity\"],\n metric_unit: ingredient[\"MetricUnit\"],\n preparation_notes: ingredient[\"PreparationNotes\"]\n )\n # end\n end\n \n recipe.steps = ''\n steps = JSON.parse(response)[\"Steps\"]\n steps.each do |step|\n step != steps.last ? recipe.steps += step[\"Text\"] + '$' : recipe.steps += step[\"Text\"]\n # recipe.steps += step[\"Text\"] + ','\n end\n \n recipe.save\n end",
"def id\n @hash['id']\n end",
"def recipe_info_for(id)\n response = Faraday.get(\"https://api.spoonacular.com/recipes/#{id}/information?includeNutrition=true&apiKey=#{spoonacular_key}\")\n JSON.parse response.body\n end",
"def hash\n return (path + file_id.to_s).hash\n end",
"def hash_id\n @hid\n end",
"def hash\n guid.hash\n end",
"def hash\n value_id.hash\n end",
"def parse_recipe(id)\n rec_id = id\n recipe = Recipe.find(rec_id)\n # find user name for recipe\n \n username = recipe.user.username;\n\n # get all ingredients from step ingredients ?\n ingredients = []\n\n recipe_steps = recipe.recipe_steps\n # one to one step ingredients to ingredients when coming from recipe-steps\n \n # recipe ingredients\n \n \n # Step \n step_ingredients = recipe_steps.map{ |rs| \n { \n step_num: rs.step_num,\n step_image: rs.image,\n instruction: rs.instruction,\n step_ingredients: rs.step_ingredients.map{ |si| \n {amount: si.amount, ingredient: {name: si.ingredient.name} }\n } \n \n }\n \n }\n\n \n step_ingredients.each do |si|\n \n ings = si[:step_ingredients]\n ings.each do |ing|\n if ing[:amount] \n ing_total = ing[:amount] + \" \" + ing[:ingredient][:name] \n if !ingredients.include?(ing_total)\n ingredients.push(ing_total) \n end\n else\n ing_total = ing[:ingredient][:name] \n if !ingredients.include?(ing_total)\n ingredients.push(ing_total) \n end\n end\n\n end\n end\n \n # fix time to string\n \n render json: {username: username, recipe: recipe, ingredients: ingredients, recipe_steps: step_ingredients }, status: :accepted\n\n end",
"def to_hash\n hash = {\n \"id\" => id,\n \"isbn\" => isbn,\n \"edition_group_id\" => edition_group_id,\n \"author\" => author,\n \"edition\" => edition,\n \"publisher\" => publisher,\n \"cover\" => cover,\n \"image\" => full_image_uri }\n end",
"def hash\n self.respond_to?(:id) && self.id ? self.id.to_i : self.to_hash.hash\n end",
"def hash\n object_id\n end",
"def recipe_finder(recipe_id)\n system 'clear'\n Recipe.all.select{|recipe| recipe.id == recipe_id}.each do |i|\n puts i.name.upcase\n puts \"Rating: #{i.rating}\"\n puts \"Cooking Time: #{i.time} hours\"\n puts \"Difficulty Level: #{i.difficulty}\"\n @recipe_ingredient = i.ingredient\n end\n prompt.select(\"What would you like to do?\") do |menu|\n menu.choice \"See ingredients\", -> {recipe_ingredients(recipe_id)}\n menu.choice \"Choose a different protein\", -> {choose_protein}\n menu.choice \"Exit\", -> {exit_helper}\n end\n end",
"def id\n Digest::SHA256.hexdigest(instance_variable_get(:@original_attributes).to_json)\n end",
"def id\n Digest::SHA256.hexdigest(instance_variable_get(:@original_attributes).to_json)\n end",
"def hash\n return @revision.hash if @revision\n return object_id\n end",
"def find_recipe_hash(missing)\n if self.user_ingredients.length == 0\n recipe_hash = {}\n Recipe.where(\"ingredient_count <= ?\", missing).pluck(:id).each do |id|\n recipe_hash[id] = 0\n end\n else\n pantry_names = self.pantry_names\n recipe_hash = Recipe.select(\"recipes.id\").joins(:ingredients).where(ingredients: {name: pantry_names}).group(\"recipes.id\").having('COUNT(*) >= recipes.ingredient_count - ?', missing).count\n end\n return recipe_hash\n end",
"def read_hash_for_id(id)\n Sidekiq.redis do |conn|\n conn.hgetall id\n end\n end",
"def hash\n [self.class, id].hash\n end",
"def get_hash(key, id)\t\t\n\t\t{ payload: { 'makes' => makes_dropdown, 'images' => images_array(key, id).compact.take(10), 'selected_key' => id}, success: true}\n\tend",
"def hash\n shasum.hash\n end",
"def hash\n shasum.hash\n end",
"def hash\n shasum.hash\n end",
"def modhash\n Reddit::Base.modhash\n end",
"def find_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def id\n Digest::SHA2.hexdigest @payload.to_json\n end",
"def hash\n \tcustom_unique_id.hash\n end",
"def find_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def scrap_recipe\n recipe = RecipeScraper::Recipe.new @marmiton_url\n # convert recipe object to hash and merge\n @recipe_hash.merge!(recipe.to_hash)\n # rename keys\n @recipe_hash[:servings] = @recipe_hash.delete :nb_of_persons\n @recipe_hash[:prep_time] = @recipe_hash.delete :preptime\n @recipe_hash[:cook_time] = @recipe_hash.delete :cooktime\n @recipe_hash[:image_url] = @recipe_hash.delete :image\n @recipe_hash[:ingredients_list] = @recipe_hash.delete :ingredients\n @recipe_hash[:marmiton_url] = @marmiton_url\n # format strings\n @recipe_hash[:ingredients_list].each { |ingredient| ingredient.gsub!(/\\d+/, ' \\0 ') }\n @recipe_hash[:title].delete!(\"\\n\").strip!\n end",
"def hash\n @hash ||= @client.get_hash(path)\n @hash\n end",
"def hash\n @hash ||= @client.get_hash(path)\n @hash\n end",
"def find(id)\n params = {\n 'sys.id': id\n }\n entry = fetch(params).first\n raise Exceptions::RecordNotFound if entry.blank?\n\n to_recipe(entry)\n end",
"def hash\n __record_id.hash\n end",
"def to_hash\n hash = {\n \"id\" => id,\n \"title\" => title }\n end",
"def node_hash(node_id)\n \n end",
"def to_hash\n hsh = {\n id: id,\n status: status.to_sym,\n connect: running? ? connect.to_h : nil,\n time: info.wallclock_time.to_i / 60 # only update every minute\n }\n Digest::SHA1.hexdigest(hsh.to_json)\n end",
"def hash\n [id, merchant_id, capacity, area_id, date_time, order_id, extra_info, promo_code, credit_card_vault_settings_id, recurring_card_detail_id, deals].hash\n end",
"def getHash(restid)\n # get all ordered items of users who ordered in restaurant \"restid\"\n userItems=OrderMng.getAllUsersItemsByRestID(restid)\n # userItems=Hash[userItems.map.with_index { |value, index| [index, value] }]\n return userItems\nend",
"def read_json\n recipes_json = File.read('JSON/recipes.json')\n recipe_hash = JSON.parse(recipes_json)\n return recipe_hash\nend",
"def hash # :nodoc:\n identifier.hash ^ requirement.hash\n end",
"def to_hash\n {\n :request_id => @request_id,\n :id => @id\n }\n end",
"def recipes\n @recipes.sort.collect {|id| $data_recipes[id] }\n end",
"def find_recipe\n \t\t@recipe = Recipe.friendly.find(params[:id])\n \tend",
"def hash() end",
"def hash() end",
"def hash() end",
"def hash() end",
"def hash() end",
"def hash() end",
"def hash() end",
"def by_ingredient\n # If ingredient exists, find recipes that use it\n if Ingredient.exists?(params[:id])\n ingredient = Ingredient.find(params[:id])\n recipes = Recipe.recipes_of_ingredient(params[:id])\n else\n recipes = Recipe.all\n end\n\n # Render json\n render json: {recipes: recipes}, status: 200 \n end",
"def hash\n [id, alternate_id, type, first_name, surname, date_of_brith, date_of_birth, shipping_address, mailing_address, home_phone, mobile_phone, email_address, mailing_address_active, accounts, classifications, member_photo, gender, receive_email, receive_sms, password].hash\n end",
"def hash\n node_id.hash\n end",
"def hash\n @hash || calculate_hash!\n end",
"def cart_hash\n end",
"def hash\n type.hash ^ (id.hash >> 1)\n end",
"def hasher\n Hashids.new(@hash_id_state[:salt], @hash_id_state[:length])\n end",
"def show\n recipe_id = params[:id].to_i\n @recipe = Recipe.find(recipe_id)\n end",
"def to_hash\n hash = {\n \"id\" => id,\n \"name\" => name,\n \"code\" => code }\n end",
"def to_hash\n hash = {\n \"id\" => id,\n \"title\" => title,\n \"code\" => code,\n \"section\" => section,\n \"department_id\" => department_id,\n \"instructor\" => instructor,\n \"term\" => term }\n end",
"def recipe_status_helper(recipe_id)\n system 'clear'\n Recipe.all.select{|recipe| recipe.id == recipe_id}.each do |i|\n puts i.name.upcase\n puts \"Rating: #{i.rating}\"\n puts \"Cooking Time: #{i.time} hours\"\n puts \"Difficulty Level: #{i.difficulty}\"\n end\n end",
"def hash\n @data[:asin].to_s.hash\n end",
"def to_h\n {\n id: @id\n }\n end",
"def hash\n data.hash\n end",
"def sha\n id.sha\n end",
"def hash\n [is_blueprint_copy, is_included, item_id, material_efficiency, quantity, record_id, runs, time_efficiency, type_id].hash\n end",
"def calculate_hash!\n entry_hash = to_hash\n entry_hash['description']=nil\n @hash = entry_hash.hash\n end",
"def generate_hash(id, raffle_number)\n Digest::SHA256.base64digest(id+ raffle_number)\nend",
"def hash\n @hash.hash\n end",
"def to_hash\n hash = {\n \"id\" => id,\n \"contactor_id\" => contactor_id,\n \"listing_id\" => listing_id,\n \"date\" => date }\n end",
"def add_recipe(recipe)\n raise \"[#{self}] duplicate recipe #{recipe.recipe_id} defined.\" if @recipes.has_key?(recipe.recipe_id)\n\n @recipes[recipe.recipe_id] = recipe\n end"
] |
[
"0.697261",
"0.66720676",
"0.66711473",
"0.66711473",
"0.66711473",
"0.66711473",
"0.66711473",
"0.66711473",
"0.66711473",
"0.66711473",
"0.66711473",
"0.6671053",
"0.6624796",
"0.6614309",
"0.65846837",
"0.65411645",
"0.65411645",
"0.6519106",
"0.64956707",
"0.645004",
"0.63700444",
"0.63503146",
"0.6303425",
"0.61859626",
"0.61644655",
"0.612193",
"0.6066957",
"0.60622543",
"0.605042",
"0.60431445",
"0.6037804",
"0.60293853",
"0.59679556",
"0.59404075",
"0.5913332",
"0.59069985",
"0.584469",
"0.58302546",
"0.58205676",
"0.5816831",
"0.5785686",
"0.57232124",
"0.56933033",
"0.56933033",
"0.5652634",
"0.5636776",
"0.5615692",
"0.56120527",
"0.5591386",
"0.55825114",
"0.55825114",
"0.55825114",
"0.55691695",
"0.55517715",
"0.55502397",
"0.5539593",
"0.5521026",
"0.55086476",
"0.54997563",
"0.54997563",
"0.5488467",
"0.5483727",
"0.5472892",
"0.54569125",
"0.5456373",
"0.5454822",
"0.5454165",
"0.5454004",
"0.5452591",
"0.5447364",
"0.5445297",
"0.5439783",
"0.54343736",
"0.54343736",
"0.54343736",
"0.54343736",
"0.54343736",
"0.54343736",
"0.54343736",
"0.54324615",
"0.5431052",
"0.5424742",
"0.541835",
"0.54126084",
"0.54104275",
"0.54062545",
"0.5399397",
"0.53855914",
"0.53841144",
"0.5382171",
"0.5372722",
"0.5370959",
"0.5362108",
"0.53604877",
"0.53600407",
"0.5357693",
"0.5354281",
"0.5345763",
"0.53454006",
"0.53342026"
] |
0.5676232
|
44
|
Add a new Recipe options Params for creating the recipe label label for the recipe description description for the recipe compatible_with recipe compatiblity (windows or unix) script_type specify script type for windows compatible (bat, vps, powershell) Returns a hash
|
def create(options = {})
optional = [:description,
:compatible_with,
:script_type
]
params.required(:label).accepts(optional).validate!(options)
response = request(:post, "/recipes.json", default_params(options))
response['recipe']
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def script_params\n params.require(:script).permit(:id, :name, :description, :definition, :long_text, :platform, :industry, :solution_type_id, :script_file, :pdf_file, :complexity, :status_id, requirements_attributes: [:id, :script_id, :requirement])\n end",
"def script_type\n case @script.type\n when :hash160\n 'pubkeyhash'\n when :pubkey\n 'pubkey'\n when :multisig\n 'multisig'\n when :p2sh\n 'scripthash'\n when :op_return\n 'nulldata'\n when :witness_v0_keyhash\n 'witness_v0_keyhash'\n when :witness_v0_scripthash\n 'witness_v0_scripthash'\n when :unknown\n 'nonstandard'\n else\n 'nonstandard'\n end\n end",
"def add_instance_type_option_types\n [\n {'fieldName' => 'name', 'fieldLabel' => 'Name', 'type' => 'text', 'required' => true, 'displayOrder' => 1},\n {'fieldName' => 'code', 'fieldLabel' => 'Code', 'type' => 'text', 'required' => true, 'displayOrder' => 2, 'description' => 'Useful shortcode for provisioning naming schemes and export reference.'},\n {'fieldName' => 'description', 'fieldLabel' => 'Description', 'type' => 'text', 'displayOrder' => 3},\n {'fieldName' => 'category', 'fieldLabel' => 'Category', 'type' => 'select', 'optionSource' => 'categories', 'required' => true, 'displayOrder' => 4},\n {'fieldName' => 'logo', 'fieldLabel' => 'Icon File', 'type' => 'text', 'displayOrder' => 5},\n {'fieldName' => 'visibility', 'fieldLabel' => 'Visibility', 'type' => 'select', 'selectOptions' => [{'name' => 'Private', 'value' => 'private'}, {'name' => 'Public', 'value' => 'public'}], 'defaultValue' => 'private', 'displayOrder' => 6},\n {'fieldName' => 'environmentPrefix', 'fieldLabel' => 'Environment Prefix', 'type' => 'text', 'displayOrder' => 7, 'description' => 'Used for exportable environment variables when tying instance types together in app contexts. If not specified a name will be generated.'},\n {'fieldName' => 'hasSettings', 'fieldLabel' => 'Enable Settings', 'type' => 'checkbox', 'displayOrder' => 8},\n {'fieldName' => 'hasAutoScale', 'fieldLabel' => 'Enable Scaling (Horizontal)', 'type' => 'checkbox', 'displayOrder' => 9},\n {'fieldName' => 'hasDeployment', 'fieldLabel' => 'Supports Deployments', 'type' => 'checkbox', 'displayOrder' => 10, 'description' => 'Requires a data volume be configured on each version. Files will be copied into this location.'}\n ]\n end",
"def create_additional_options\n type_dir = new_resource.send('config_dir_' + new_resource.type)\n new_resource.additional_options.each do |k, v|\n file \"#{new_resource.instance} :create #{type_dir})/#{k}\" do\n path \"#{type_dir}/#{k}\"\n content v\n end\n end\n end",
"def AddEditScript(scriptName, source, interpreter, type, chrooted, debug, feedback, network, feedback_type, location, notification)\n mod = false\n @merged = Builtins.maplist(@merged) do |script|\n # Edit\n if Ops.get_string(script, \"filename\", \"\") == scriptName\n oldScript = {}\n oldScript = Builtins.add(oldScript, \"filename\", scriptName)\n oldScript = Builtins.add(oldScript, \"source\", source)\n oldScript = Builtins.add(oldScript, \"interpreter\", interpreter)\n oldScript = Builtins.add(oldScript, \"type\", type)\n oldScript = Builtins.add(oldScript, \"chrooted\", chrooted)\n oldScript = Builtins.add(oldScript, \"debug\", debug)\n oldScript = Builtins.add(oldScript, \"feedback\", feedback)\n oldScript = Builtins.add(oldScript, \"network_needed\", network)\n oldScript = Builtins.add(oldScript, \"feedback_type\", feedback_type)\n oldScript = Builtins.add(oldScript, \"location\", location)\n oldScript = Builtins.add(oldScript, \"notification\", notification)\n\n mod = true\n next deep_copy(oldScript)\n else\n next deep_copy(script)\n end\n end\n\n if !mod\n script = {}\n script = Builtins.add(script, \"filename\", scriptName)\n script = Builtins.add(script, \"source\", source)\n script = Builtins.add(script, \"interpreter\", interpreter)\n script = Builtins.add(script, \"type\", type)\n script = Builtins.add(script, \"chrooted\", chrooted)\n script = Builtins.add(script, \"debug\", debug)\n script = Builtins.add(script, \"feedback\", feedback)\n script = Builtins.add(script, \"network_needed\", network)\n script = Builtins.add(script, \"feedback_type\", feedback_type)\n script = Builtins.add(script, \"location\", location)\n script = Builtins.add(script, \"notification\", notification)\n\n @merged = Builtins.add(@merged, script)\n end\n Builtins.y2debug(\"Merged scripts: %1\", @merged)\n nil\n end",
"def add_options(type, cmd, default_template: 'default')\n cmd_name = cmd.name.to_s\n action = case cmd_name\n when /again/\n 'Repeat'\n when /grep/\n 'Search'\n when /mark/\n 'Flag'\n when /(last|tags|view|on)/\n 'Show'\n else\n cmd_name.capitalize\n end\n\n case type\n when :output_template\n cmd.desc \"Output to export format (#{Doing::Plugins.plugin_names(type: :export)})\"\n cmd.arg_name 'FORMAT'\n cmd.flag %i[o output], type: ExportTemplate\n\n cmd.desc \"Output using a template from configuration\"\n cmd.arg_name 'TEMPLATE_KEY'\n cmd.flag [:config_template], type: TemplateName, default_value: default_template\n\n cmd.desc 'Override output format with a template string containing %placeholders'\n cmd.arg_name 'TEMPLATE_STRING'\n cmd.flag [:template]\n when :output_template_no_defaults\n cmd.desc \"Output to export format (#{Doing::Plugins.plugin_names(type: :export)})\"\n cmd.arg_name 'FORMAT'\n cmd.flag %i[o output]\n\n cmd.desc \"Output using a template from configuration\"\n cmd.arg_name 'TEMPLATE_KEY'\n cmd.flag [:config_template], type: TemplateName\n\n cmd.desc 'Override output format with a template string containing %placeholders'\n cmd.arg_name 'TEMPLATE_STRING'\n cmd.flag [:template]\n when :add_entry\n cmd.desc 'Exclude auto tags and default tags'\n cmd.switch %i[X noauto], default_value: false, negatable: false\n\n cmd.desc 'Include a note'\n cmd.arg_name 'TEXT'\n cmd.flag %i[n note]\n\n cmd.desc 'Prompt for note via multi-line input'\n cmd.switch %i[ask], negatable: false, default_value: false\n\n cmd.desc \"Edit entry with #{Doing::Util.default_editor}\"\n cmd.switch %i[e editor], negatable: false, default_value: false\n\n cmd.desc 'Backdate start date for new entry to date string [4pm|20m|2h|yesterday noon]'\n cmd.arg_name 'DATE_STRING'\n cmd.flag %i[b back started since], type: DateBeginString\n when :finish_entry\n cmd.desc %(Set finish date to specific date/time (natural langauge parsed, e.g. --at=1:30pm).\n Used with --took, backdates start date)\n cmd.arg_name 'DATE_STRING'\n cmd.flag %i[at finished], type: DateEndString\n\n cmd.desc %(\n Start and end times as a date/time range `doing done --from \"1am to 8am\"`.\n Overrides other date flags.\n )\n cmd.arg_name 'TIME_RANGE'\n cmd.flag [:from], must_match: REGEX_RANGE\n\n cmd.desc %(Set completion date to start date plus interval (XX[mhd] or HH:MM).\n If used without the --back option, the start date will be moved back to allow\n the completion date to be the current time.)\n cmd.arg_name 'INTERVAL'\n cmd.flag %i[t took for], type: DateIntervalString\n when :search\n cmd.desc 'Filter entries using a search query, surround with slashes for regex (e.g. \"/query.*/\"),\n start with single quote for exact match (\"\\'query\")'\n cmd.arg_name 'QUERY'\n cmd.flag [:search]\n\n cmd.desc 'Case sensitivity for search string matching [(c)ase-sensitive, (i)gnore, (s)mart]'\n cmd.arg_name 'TYPE'\n cmd.flag [:case], must_match: REGEX_CASE,\n default_value: Doing.settings.dig('search', 'case').normalize_case,\n type: CaseSymbol\n\n cmd.desc 'Force exact search string matching (case sensitive)'\n cmd.switch %i[x exact], default_value: Doing.config.exact_match?, negatable: Doing.config.exact_match?\n when :time_display\n cmd.desc 'Show time intervals on @done tasks'\n cmd.switch %i[t times], default_value: true, negatable: true\n\n cmd.desc 'Show elapsed time on entries without @done tag'\n cmd.switch [:duration]\n\n cmd.desc 'Show time totals at the end of output'\n cmd.switch [:totals], default_value: false, negatable: false\n\n cmd.desc 'Sort tags by (name|time)'\n default = Doing.setting('tag_sort').normalize_tag_sort || :name\n cmd.arg_name 'KEY'\n cmd.flag [:tag_sort], must_match: REGEX_TAG_SORT, default_value: default, type: TagSortSymbol\n\n cmd.desc 'Tag sort direction (asc|desc)'\n cmd.arg_name 'DIRECTION'\n cmd.flag [:tag_order], must_match: REGEX_SORT_ORDER, default_value: :asc, type: OrderSymbol\n\n cmd.desc 'Only show items with recorded time intervals'\n cmd.switch [:only_timed], default_value: false, negatable: false\n when :tag_filter\n cmd.desc 'Filter entries by tag. Combine multiple tags with a comma. Wildcards allowed (*, ?)'\n cmd.arg_name 'TAG'\n cmd.flag [:tag], type: TagArray\n\n cmd.desc 'Perform a tag value query (\"@done > two hours ago\" or \"@progress < 50\").\n May be used multiple times, combined with --bool'\n cmd.arg_name 'QUERY'\n cmd.flag [:val], multiple: true, must_match: REGEX_VALUE_QUERY\n\n cmd.desc \"#{action} items that *don't* match search/tag filters\"\n cmd.switch [:not], default_value: false, negatable: false\n\n cmd.desc 'Boolean used to combine multiple tags (AND|OR|NOT). Use PATTERN to parse + and - as booleans'\n cmd.arg_name 'BOOLEAN'\n cmd.flag [:bool], must_match: REGEX_BOOL,\n default_value: :pattern,\n type: BooleanSymbol\n when :tag_filter_no_defaults\n cmd.desc 'Filter entries by tag. Combine multiple tags with a comma. Wildcards allowed (*, ?)'\n cmd.arg_name 'TAG'\n cmd.flag [:tag], type: TagArray\n\n cmd.desc 'Perform a tag value query (\"@done > two hours ago\" or \"@progress < 50\").\n May be used multiple times, combined with --bool'\n cmd.arg_name 'QUERY'\n cmd.flag [:val], multiple: true, must_match: REGEX_VALUE_QUERY\n\n cmd.desc \"#{action} items that *don't* match search/tag filters\"\n cmd.switch [:not], negatable: false\n\n cmd.desc 'Boolean used to combine multiple tags. Use PATTERN to parse + and - as booleans'\n cmd.arg_name 'BOOLEAN'\n cmd.flag [:bool], must_match: REGEX_BOOL,\n type: BooleanSymbol\n when :time_filter\n cmd.desc 'View entries before specified time (e.g. 8am, 12:30pm, 15:00)'\n cmd.arg_name 'TIME_STRING'\n cmd.flag [:before], type: DateEndString\n\n cmd.desc 'View entries after specified time (e.g. 8am, 12:30pm, 15:00)'\n cmd.arg_name 'TIME_STRING'\n cmd.flag [:after], type: DateBeginString\n\n cmd.desc %(\n Time range to show `doing #{cmd.name} --from \"12pm to 4pm\"`\n )\n cmd.arg_name 'TIME_RANGE'\n cmd.flag [:from], type: DateRangeString, must_match: REGEX_TIME_RANGE\n when :date_filter\n if action =~ /Archive/\n cmd.desc 'Archive entries older than date (natural language).'\n else\n cmd.desc \"#{action} entries older than date (natural language). If this is only a time (8am, 1:30pm, 15:00), all\n dates will be included, but entries will be filtered by time of day\"\n end\n cmd.arg_name 'DATE_STRING'\n cmd.flag [:before], type: DateBeginString\n\n if action =~ /Archive/\n cmd.desc 'Archive entries newer than date (natural language).'\n else\n cmd.desc \"#{action} entries newer than date (natural language). If this is only a time (8am, 1:30pm, 15:00), all\n dates will be included, but entries will be filtered by time of day\"\n end\n cmd.arg_name 'DATE_STRING'\n cmd.flag [:after], type: DateEndString\n\n if action =~ /Archive/\n cmd.desc %(\n Date range (natural language) to archive: `doing archive --from \"1/1/21 to 12/31/21\"`.\n )\n else\n cmd.desc %(\n Date range (natural language) to #{action.downcase}, or a single day to filter on.\n To specify a range, use \"to\": `doing #{cmd_name} --from \"monday 8am to friday 5pm\"`.\n\n If values are only time(s) (6am to noon) all dates will be included, but entries will be filtered\n by time of day.\n )\n end\n cmd.arg_name 'DATE_OR_RANGE'\n cmd.flag [:from], type: DateRangeString\n when :save\n cmd.desc 'Save all current command line options as a new view'\n cmd.arg_name 'VIEW_NAME'\n cmd.flag %i[save], type: String\n\n cmd.desc 'Title string to be used for output formats that require it'\n cmd.arg_name 'TITLE'\n cmd.flag %i[title], type: String\n end\nend",
"def generate_flags overrides = {}\n { '-s' => 'dir',\n '-t' => 'rpm',\n '--name' => @spec.title,\n '--description' => @spec.description,\n '--url' => @spec.uri,\n '--category' => @spec.category,\n '--version' => @spec.version,\n '--epoch' => 1,\n '--license' => @spec.license,\n '-C' => @spec.dir_path,\n '--depends' => 'mono',\n '--rpm-digest' => 'sha256',\n '--package' => @out\n }.merge(overrides).reject { |_, v| v.nil? }\n end",
"def script\n attributes[:customization_script]\n end",
"def build_option_types(option_types)\n\n optiontype_vlist_map = {}\n\n option_types.each do |ostr|\n\n oname, value_str = ostr.split(name_value_delim)\n\n option_type = option_type_klass.where(:name => oname).first\n\n unless option_type\n option_type = option_type_klass.create(:name => oname, :presentation => oname.humanize)\n\n unless option_type\n logger.warm(\"WARNING: OptionType #{oname} NOT found and could not create - Not set Product\")\n next\n end\n logger.info \"Created missing OptionType #{option_type.inspect}\"\n end\n\n # OptionTypes must be specified first on Product to enable Variants to be created\n product_load_object.option_types << option_type unless product_load_object.option_types.include?(option_type)\n\n # Can be simply list of OptionTypes, some or all without values\n next unless(value_str)\n\n optiontype_vlist_map[option_type] ||= []\n\n # Now get the value(s) for the option e.g red,blue,green for OptType 'colour'\n optiontype_vlist_map[option_type] += value_str.split(',').flatten\n end\n\n\n # A single Variant can have MULTIPLE Option Types and the Syntax supports this combining\n #\n # So we need the LONGEST set of OptionValues - to use as the BASE for combining with the rest\n #\n # mime_type:png,PDF; print_type:colour\n #\n # This means create 2 Variants\n # 1 mime_type:png && print_type:colour\n # 1 mime_type:PDF && print_type:colour\n #\n # And we want to identify this \"mime_type:png,PDF\" as the longest to combine with the smaller print_type list\n\n sorted_map = optiontype_vlist_map.sort_by { |ot, ov| ov.size }.reverse\n\n sorted_map\n\n end",
"def script_params\n params.require(:script).permit(:name, :description, :status, :context, :version, :owningApp)\n end",
"def recipe_options\n \trecipes.map do |recipe| \n \t\t[recipe.name, recipe.id]\n \tend\n end",
"def initialize(key: nil,\n env_name: nil,\n description: nil,\n short_option: nil,\n default_value: nil,\n default_value_dynamic: false,\n verify_block: nil,\n is_string: true,\n type: nil,\n skip_type_validation: false,\n optional: nil,\n conflicting_options: nil,\n conflict_block: nil,\n deprecated: nil,\n sensitive: nil,\n code_gen_sensitive: false,\n code_gen_default_value: nil,\n display_in_shell: true)\n UI.user_error!(\"key must be a symbol\") unless key.kind_of?(Symbol)\n UI.user_error!(\"env_name must be a String\") unless (env_name || '').kind_of?(String)\n\n if short_option\n UI.user_error!(\"short_option for key :#{key} must of type String\") unless short_option.kind_of?(String)\n UI.user_error!(\"short_option for key :#{key} must be a string of length 1\") unless short_option.delete('-').length == 1\n end\n\n if description\n UI.user_error!(\"Do not let descriptions end with a '.', since it's used for user inputs as well for key :#{key}\") if description[-1] == '.'\n end\n\n if conflicting_options\n conflicting_options.each do |conflicting_option_key|\n UI.user_error!(\"Conflicting option key must be a symbol\") unless conflicting_option_key.kind_of?(Symbol)\n end\n end\n\n if deprecated\n # deprecated options are automatically optional\n optional = true if optional.nil?\n UI.crash!(\"Deprecated option must be optional\") unless optional\n\n # deprecated options are marked deprecated in their description\n description = deprecated_description(description, deprecated)\n end\n\n optional = false if optional.nil?\n sensitive = false if sensitive.nil?\n\n @key = key\n @env_name = env_name\n @description = description\n @short_option = short_option\n @default_value = default_value\n @default_value_dynamic = default_value_dynamic\n @verify_block = verify_block\n @is_string = is_string\n @data_type = type\n @data_type = String if type == :shell_string\n @optional = optional\n @conflicting_options = conflicting_options\n @conflict_block = conflict_block\n @deprecated = deprecated\n @sensitive = sensitive\n @code_gen_sensitive = code_gen_sensitive || sensitive\n @allow_shell_conversion = (type == :shell_string)\n @display_in_shell = display_in_shell\n @skip_type_validation = skip_type_validation # sometimes we allow multiple types which causes type validation failures, e.g.: export_options in gym\n\n @code_gen_default_value = code_gen_default_value\n\n update_code_gen_default_value_if_able!\n end",
"def chef_resource_params\n params.require(:chef_resource).permit(:resource_type, chef_properties_attributes: [ :id, :value, :value_type ])\n end",
"def bundler_options\n [].tap do |opts|\n if new_resource.binstubs\n opts << \"--binstubs\" + (new_resource.binstubs.is_a?(String) ? \"=#{new_resource.binstubs}\" : '')\n end\n if new_resource.vendor\n opts << \"--path=\" + (new_resource.vendor.is_a?(String) ? new_resource.vendor : 'vendor/bundle')\n end\n if new_resource.deployment\n opts << '--deployment'\n end\n if new_resource.jobs\n opts << \"--jobs=#{new_resource.jobs}\"\n end\n if new_resource.retry\n opts << \"--retry=#{new_resource.retry}\"\n end\n if new_resource.without\n opts << '--without'\n opts.insert(-1, *new_resource.without)\n end\n end\n end",
"def tool_attributes(overrides = {})\n {\n name: \"Pros and Cons\",\n description: \"Weighing up pros and cons can speed up the decision-making process,\n improve your understanding of the situation and help you avoid decision-making\n paralysis.\",\n price: 10.00\n }.merge(overrides)\nend",
"def generate_options(filename, code); end",
"def generate_options(filename, code); end",
"def manifest(type)\n type = type.downcase\n say \"Rendering #{type} manifest\", :green\n @values = parse_cloud_config\n @tf_output = parse_tf_state('terraform/terraform.tfstate') if options[:cloud] == 'aws'\n\n if options[:cloud] == 'aws'\n @private_subnet = IPAddr.new(@values['aws']['private_subnet']['network']).to_range.to_a\n @public_subnet = IPAddr.new(@values['aws']['public_subnet']['network']).to_range.to_a\n else\n @private_subnet = IPAddr.new(@values['gcp']['subnet_cidr']).to_range.to_a\n end\n\n @static_ip_vault = @private_subnet[11].to_s\n @static_ips_concourse = [@private_subnet[12]].map(&:to_s)\n @static_ip_prometheus_stack = @private_subnet[18].to_s\n\n case type\n when \"bosh\"\n directory(\"#{options[:cloud]}/deployments/bosh\", 'deployments/bosh')\n template(\"#{options[:cloud]}/bosh-vars.yml.erb\", 'config/bosh-vars.yml')\n copy_file(\"#{options[:cloud]}/docs/bosh.md\", \"docs/bosh.md\")\n template(\"#{options[:cloud]}/bin/bosh-install.sh.tt\", \"bin/bosh-install.sh\")\n chmod('bin/bosh-install.sh', 0755)\n\n when \"concourse\"\n directory(\"#{options[:cloud]}/deployments/concourse\", \"deployments/concourse\")\n copy_file(\"#{options[:cloud]}/docs/concourse.md\", \"docs/concourse.md\")\n template(\"#{options[:cloud]}/bin/concourse-deploy.sh.tt\", \"bin/concourse-deploy.sh\")\n chmod('bin/concourse-deploy.sh', 0755)\n ingress_add_entry(@values['concourse']['hostname'], @static_ips_concourse, port: 8080)\n\n when \"vault\"\n template(\"#{options[:cloud]}/deployments/vault/vault.yml.erb\", \"deployments/vault/vault.yml\")\n copy_file(\"#{options[:cloud]}/docs/vault.md\", \"docs/vault.md\")\n template(\"#{options[:cloud]}/bin/vault-deploy.sh.tt\", \"bin/vault-deploy.sh\")\n chmod('bin/vault-deploy.sh', 0755)\n ingress_add_entry(@values['vault']['hostname'], [@static_ip_vault], port: 8200)\n\n when \"ingress\"\n template(\"#{options[:cloud]}/deployments/ingress/ingress.yml.erb\", \"deployments/ingress/ingress.yml\")\n copy_file(\"#{options[:cloud]}/docs/ingress.md\", \"docs/ingress.md\")\n template(\"#{options[:cloud]}/bin/ingress-deploy.sh.tt\", \"bin/ingress-deploy.sh\")\n template(\"#{options[:cloud]}/bin/ingress-update.sh.tt\", \"bin/ingress-update.sh\")\n chmod('bin/ingress-deploy.sh', 0755)\n chmod('bin/ingress-update.sh', 0755)\n\n when \"prometheus\"\n directory(\"#{options[:cloud]}/deployments/prometheus\", \"deployments/prometheus\")\n copy_file(\"#{options[:cloud]}/docs/prometheus.md\", \"docs/prometheus.md\")\n template(\"#{options[:cloud]}/bin/prometheus-deploy.sh.tt\", \"bin/prometheus-deploy.sh\")\n chmod('bin/prometheus-deploy.sh', 0755)\n ingress_add_entry(@values['alertmanager']['hostname'], [@static_ip_prometheus_stack], port: 9093)\n ingress_add_entry(@values['grafana']['hostname'], [@static_ip_prometheus_stack], port: 3000)\n ingress_add_entry(@values['prometheus']['hostname'], [@static_ip_prometheus_stack], port: 9090)\n\n else\n say \"Manifest type not specified\"\n\n end\n end",
"def create_kubernetes_addon_definition_with_http_info(kubernetes_addon_definition, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: KubernetesApi.create_kubernetes_addon_definition ...'\n end\n # verify the required parameter 'kubernetes_addon_definition' is set\n if @api_client.config.client_side_validation && kubernetes_addon_definition.nil?\n fail ArgumentError, \"Missing the required parameter 'kubernetes_addon_definition' when calling KubernetesApi.create_kubernetes_addon_definition\"\n end\n # resource path\n local_var_path = '/api/v1/kubernetes/AddonDefinitions'\n\n # query parameters\n query_params = opts[:query_params] || {}\n\n # header parameters\n header_params = opts[:header_params] || {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n content_type = @api_client.select_header_content_type(['application/json'])\n if !content_type.nil?\n header_params['Content-Type'] = content_type\n end\n header_params[:'If-Match'] = opts[:'if_match'] if !opts[:'if_match'].nil?\n header_params[:'If-None-Match'] = opts[:'if_none_match'] if !opts[:'if_none_match'].nil?\n\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:debug_body] || @api_client.object_to_http_body(kubernetes_addon_definition)\n\n # return_type\n return_type = opts[:debug_return_type] || 'KubernetesAddonDefinition'\n\n # auth_names\n auth_names = opts[:debug_auth_names] || ['cookieAuth', 'http_signature', 'oAuth2', 'oAuth2']\n\n new_options = opts.merge(\n :operation => :\"KubernetesApi.create_kubernetes_addon_definition\",\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: KubernetesApi#create_kubernetes_addon_definition\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def with_version_constraints_strings\n map do |recipe_name|\n if @versions[recipe_name]\n \"#{recipe_name}@#{@versions[recipe_name]}\"\n else\n recipe_name\n end\n end\n end",
"def script_params\n params.require(:script).permit(:automatic_id, :script_type, :description, :param1, :param2, :script_order, :organ, :diagnostic, :pss_code, :who_code, :suggestion)\n end",
"def options\n [['--build32', 'Force a 32-bit build.']]\n end",
"def script_options(opts = {})\n opts = opts.to_h.compact.deep_symbolize_keys\n\n opts = {\n job_name: adapter.sanitize_job_name(job_name),\n workdir: staged_root,\n output_path: output_file,\n shell_path: shell_path\n }.merge opts\n end",
"def hash\n [key, name, description, kind, creation_date, include_in_snippet, temporary, maintainer_id, tags, variations, goal_ids, _version, custom_properties, _links, _maintainer, environments, archived_date, archived, client_side_availability, defaults].hash\n end",
"def initialize(type: nil, name: nil, created_at: nil, params: nil, run_context: nil, cookbook_name: nil, recipe_name: nil, enclosing_provider: nil)\nsuper if defined?(::Chef::ResourceBuilder)\n @type = type\n @name = name\n @created_at = created_at\n @params = params\n @run_context = run_context\n @cookbook_name = cookbook_name\n @recipe_name = recipe_name\n @enclosing_provider = enclosing_provider\n end",
"def help_option_params\n params.require(:help_option).permit(:descriptionvol, :descriptioncall)\n end",
"def fix_windows_manifest\n return manifest if manifest['windows'].nil?\n\n builds_32bit = {}\n builds_64bit = {}\n\n manifest['windows'].each do |platform_version, build_data|\n build_data.each do |architecture, builds|\n builds.each do |version, build|\n case architecture\n when 'x86_64'\n if %w{chef angrychef}.include?(project_name)\n # In the beginning (Chef 10) there was only 1 Chef package\n # architecture, and it was 32 bit. However, it was always stored\n # under the x86_64 manifest architecture and it was returned for\n # both x86_64 and i386 requests (1 package was used for both 32\n # and 64 bit Windows machines). This continued until Chef 12.4.2\n # - this was the first package to be stored under the i386\n # manifest architecture. There was still only 1 package and it\n # was 32 bit, but now it had the correct manifest architecture.\n # Starting with Chef 12.7 we started building 2 packages for Chef\n # - a 32 bit package for i386 architecture and a 64 bit package\n # for x86_64 architecture.\n #\n # Until Chef reaches version 12.9 we want to continue servering\n # all stable channel requests _only_ with the 32 bit package,\n # regardless of whether the user specifies x86_64 or i386\n # architecture. Once Chef 12.9 is released we will start returning\n # the correct package based upon requested architecture but only\n # for version 12.9+\n if Opscode::Version.parse(version) >= Opscode::Version.parse(\"12.7.0\")\n builds_64bit[version] = build\n else\n builds_32bit[version] ||= build\n end\n elsif project_name == 'chefdk'\n # ChefDK is still only built to produce a 32-bit package. But like Chef,\n # it works on both 32-bit systems and 64-bit systems. It also may\n # sometimes be tagged as x86_64 or i386. But we want to use each\n # package for all customer architectures.\n builds_32bit[version] = build\n builds_64bit[version] = build\n else\n builds_64bit[version] = build\n end\n when 'i386', 'i686'\n builds_32bit[version] = build\n if project_name == 'chefdk'\n builds_64bit[version] = build\n end\n else\n raise \"Unknown Windows architecture '#{architecture}'\"\n end\n end\n end\n end\n\n manifest['windows'] = {\n '2008r2' => {\n 'i386' => builds_32bit,\n 'x86_64' => builds_64bit\n }\n }\n\n manifest\n end",
"def app_spec_and_code\n shell_friendly_spec = {\n spec: @app.spec,\n assets: @app.ordered_assets,\n packages: @app.packages,\n }.to_json.shellescape\n\n shell_friendly_code = { code: @app.code }.to_json.shellescape\n\n cmds = []\n cmds << \"RUN \" + [\"/bin/bash\", \"-c\", \"echo -E #{shell_friendly_spec} > /spec.json\"].to_json\n cmds << \"RUN \" + [\"/bin/bash\", \"-c\", \"echo -E #{shell_friendly_code} | python -c 'import sys,json; print json.load(sys.stdin)[\\\"code\\\"]' > /script.sh\"].to_json\n\n <<~APP_SPEC\n # Write app spec and code to root folder\n #{cmds.join(\"\\n\")}\n APP_SPEC\n end",
"def build_script(hook_type)\n ERB.new(DEFAULT_TEMPLATE).result(binding)\n end",
"def build_opts(hash, *args)\n opts = args\n hash.each do |key, value|\n case key\n when :secure, :soft\n value == :yes && opts << '--%s' % key\n when :appname, :appversion\n when :name\n else\n opts << '--%s' % key << value\n end\n end\n opts << hash[:appname]\n opts << hash[:appversion]\n opts.compact\n end",
"def type_and_description(opts = {})\n { type: type, description: description(opts) }\n end",
"def build_dict(option_specs) #:nodoc:\n @dict = {}\n keys = []\n option_specs.each do |option_spec|\n # Parse the specification\n m, label, oper, cont, arg = *option_spec.match(/([^=:]+)(?:([=:])([@])?(\\w+))?/)\n raise ParseError.new(\"invalid option format for '#{option_spec}'\") unless m\n\n # Figure out the specification type\n is_bang_arg = label.gsub!(/!$/, '')\n is_increment = label.gsub!(/\\+$/, '')\n forms = label.split('|')\n key = forms.first\n\n # Create an instance of OptionDefinition to hold metat data\n od = OptionDefinition.new(key)\n od.option_type = :boolean if is_bang_arg\n od.option_type = :increment if is_increment\n if (arg)\n od.option_type = (oper == '=') ? :required_argument : :optional_argument\n od.container_type = case cont\n when '@'; :array\n else :scalar\n end\n od.argument_type = case arg\n when 'f', 'float' ; :float\n when 'i', 'integer'; :integer\n when 's', 'string' ; :string\n else raise ParseError.new(\"unknown argument type '#{arg}'\")\n end\n end\n\n # Process alternate key names\n forms.each do |k|\n @dict[k] = od.dup\n keys << k\n end\n\n # Only support negation on long option names\n if (is_bang_arg)\n @dict[\"no-#{key}\"] = od.dup\n end\n end\n\n # Allow abbreviated long options\n keys.abbrev.each do |ab,key|\n @dict[ab] = @dict[key].dup\n @dict[ab].abbreviated = true unless (ab == key)\n end\n end",
"def render_deployment_template(options)\n self_signed_cert_resource = nil\n if options[:operating_system] == \"Windows\" && options[:winrm_install_self_signed_cert]\n setup_winrm_powershell = VagrantPlugins::Azure::Util::TemplateRenderer.render(\"arm/setup-winrm.ps1\", options)\n encoded_setup_winrm_powershell = setup_winrm_powershell.\n gsub(\"'\", \"', variables('singleQuote'), '\").\n gsub(\"\\r\\n\", \"\\n\").\n gsub(\"\\n\", \"; \")\n self_signed_cert_resource = VagrantPlugins::Azure::Util::TemplateRenderer.render(\"arm/selfsignedcert.json\", options.merge({setup_winrm_powershell: encoded_setup_winrm_powershell}))\n end\n VagrantPlugins::Azure::Util::TemplateRenderer.render(\"arm/deployment.json\", options.merge({self_signed_cert_resource: self_signed_cert_resource}))\n end",
"def generate_id_yml(script)\n native_data = script.native\n native_data[:container][:supplemental_groups] = supplemental_groups(native_data[:container][:supplemental_groups])\n container = helper.container_from_native(native_data[:container], default_env)\n id = generate_id(container.name)\n configmap = helper.configmap_from_native(native_data, id, script.content)\n init_containers = helper.init_ctrs_from_native(native_data[:init_containers], container.env)\n spec = OodCore::Job::Adapters::Kubernetes::Resources::PodSpec.new(container, init_containers: init_containers)\n all_mounts = native_data[:mounts].nil? ? mounts : mounts + native_data[:mounts]\n node_selector = native_data[:node_selector].nil? ? {} : native_data[:node_selector]\n gpu_type = native_data[:gpu_type].nil? ? \"nvidia.com/gpu\" : native_data[:gpu_type]\n\n template = ERB.new(File.read(resource_file), nil, '-')\n\n [template.result(binding), id]\n end",
"def build_wrapper_script(os_platform, shebang, properties)\n msg = \"Environment variables from BRPM\"\n wrapper = \"srun_wrapper_#{@rpm.precision_timestamp}\"\n cmd = shebang[\"cmd\"]\n target = File.basename(@params[\"SS_script_file\"])\n cmd = cmd.gsub(\"%%\", target) if shebang[\"cmd\"].end_with?(\"%%\")\n cmd = \"#{cmd} #{target}\" unless shebang[\"cmd\"].end_with?(\"%%\")\n if os_platform =~ /win/\n properties[\"RPM_CHANNEL_ROOT\"] = @rpm.dos_path(properties[\"RPM_CHANNEL_ROOT\"])\n properties[\"VL_CHANNEL_ROOT\"] = properties[\"RPM_CHANNEL_ROOT\"]\n wrapper = \"#{wrapper}.bat\"\n script = \"@echo off\\r\\necho |hostname > junk.txt\\r\\nset /p HOST=<junk.txt\\r\\nrm junk.txt\\r\\n\"\n script += \"echo ============== HOSTNAME: %HOST% ==============\\r\\n\"\n script += \"echo #{msg} \\r\\n\"\n properties.each{|k,v| script += \"set #{k}=#{v}\\r\\n\" }\n script += \"echo Execute the file\\r\\n\"\n script += \"cd %RPM_CHANNEL_ROOT%\\r\\n\"\n script += \"#{cmd}\\r\\n\"\n script += \"timeout /T 500\\r\\necho y | del #{target}\\r\\n\"\n else\n wrapper = \"#{wrapper}.sh\"\n script = \"echo \\\"============== HOSTNAME: `hostname` ==============\\\"\\n\"\n script += \"echo #{msg} \\n\"\n properties.each{|k,v| script += \"export #{k}=\\\"#{v}\\\"\\n\" }\n script += \"echo Execute the file\\n\"\n script += \"cd $RPM_CHANNEL_ROOT\\n\"\n script += \"#{cmd}\\n\" \n script += \"sleep 2\\nrm -f #{target}\" \n end\n fil = File.open(File.join(@output_dir, wrapper),\"w+\")\n fil.puts script\n fil.flush\n fil.close\n File.join(@output_dir, wrapper)\nend",
"def option_type_config; end",
"def generate(input)\n runlist_json = JSON.pretty_generate((input[:attributes] || {}).merge({ run_list: input[:run_list] }))\n validation_key = get_cred(input[:validation_key])\n script = <<-SCRIPT\n#!/bin/bash\n# Download and install chef\ncurl -L https://www.chef.io/chef/install.sh | sudo bash\nmkdir -p /etc/chef\n\n# Prepare the runlist file\ncat <<'EOF' >/etc/chef/runlist.json\n#{runlist_json}\nEOF\n\n# Create the chef client configuration file\ncat <<'EOF' >/etc/chef/client.rb\nchef_server_url \"#{input[:chef_server_url]}\"\nvalidation_client_name \"#{input[:validation_client_name]}\"\nnode_name \"#{input[:node_name]}\"\nenvironment \"#{input[:chef_environment]}\"\nEOF\n\n# Create the validation key file\ncat <<'EOF' > /etc/chef/validation.pem\n#{validation_key}\nEOF\n\n# Converge\nchef-client -j /etc/chef/runlist.json\nSCRIPT\n script\n end",
"def build_cfn_options\n options = {\n stack_name: new_resource.stack_name,\n # make sure you call this after you save the file\n template_body: ::IO.read(@template_path),\n parameters: new_resource.parameters,\n disable_rollback: new_resource.disable_rollback,\n capabilities: [],\n }\n options[:stack_policy_body] = new_resource.stack_policy_body unless new_resource.stack_policy_body.nil?\n options[:capabilities] << 'CAPABILITY_IAM' if new_resource.iam_capability\n options[:capabilities] << 'CAPABILITY_NAMED_IAM' if new_resource.named_iam_capability\n options\n end",
"def params(package, type, data)\n package.name = \"mcollective-#{@package.metadata[:name].downcase}-#{type}\"\n package.maintainer = @package.metadata[:author]\n package.version = @package.metadata[:version]\n package.url = @package.metadata[:url]\n package.license = @package.metadata[:license]\n package.iteration = @package.iteration\n package.vendor = @package.vendor\n package.description = @package.metadata[:description] + \"\\n\\n#{data[:description]}\"\n package.dependencies = data[:dependencies]\n package.scripts[\"post-install\"] = @package.postinstall if @package.postinstall\n package.architecture = \"all\"\n end",
"def automation_type_options\n options = [[\"<#{_('No Entry Point')}>\", nil]]\n options + AUTOMATION_TYPES.values.map do |item|\n [item[:label], item[:key]]\n end\n end",
"def create_file(type, resource)\n Chef::Log.info(\"date : #{resource.date}\")\n\n date = ''\n temporary_filename = ''\n\n if platform_family?('windows')\n temporary_filename = \"C:/Windows/Temp/#{resource.reference}\"\n\n # Formatted date for the request\"\n ruby_block 'date-windows' do\n block do\n # Get date\n date = powershell_out('get-date -Format \"yyyy/%M/%d HHHH:mmmm:ssss\"').stdout.chop\n end\n action :create\n end\n\n else\n temporary_filename = \"/tmp/#{resource.reference}\"\n\n # Formatted date for the request\"\n ruby_block 'date-linux' do\n block do\n # Get date\n date = shell_out('date +\"%Y/%m/%d %T\"').stdout.chop\n end\n action :create\n end\n end\n\n Chef::Log.debug(\"temporary_filename : #{temporary_filename}\")\n\n template temporary_filename.to_s do\n source 'cyberark_request.erb'\n variables(\n version: resource.version,\n date: resource.date,\n type: type.to_s,\n reference: resource.reference,\n hostname: resource.hostname,\n ip: resource.ip,\n fqdn: resource.fqdn,\n platform: resource.platform,\n location: resource.location,\n geographic_code: resource.geographic_code,\n username: resource.username,\n password: resource.password\n )\n end\n\n ruby_block 'create-file' do\n block do\n if platform_family?('windows')\n hash = powershell_out(\"$(Get-FileHash #{temporary_filename} -Algorithm MD5).hash\").stdout.chop\n date_short = powershell_out('get-date -Format \"yyyyMMddHHmmss\"').stdout.chop\n else\n hash = shell_out(\"md5sum #{temporary_filename} | cut -f1 -d ' '\").stdout.chop\n date_short = shell_out('date +\"%Y%m%d%H%M\"').stdout.chop\n end\n\n filename = \"#{date_short}_#{type}_#{resource.reference}_#{hash}\"\n Chef::Log.debug(\"date_short : #{date_short}\")\n Chef::Log.debug(\"filename : #{filename}\")\n Chef::Log.debug(\"mv #{temporary_filename} /tmp/#{filename}.tmp\")\n node.default['cyberark']['filename'] = filename.to_s\n\n if platform_family?('windows')\n powershell_out(\"mv #{temporary_filename} C:/Windows/Temp/#{filename}.tmp\")\n else\n shell_out(\"mv #{temporary_filename} /opt/IBM/#{filename}.tmp\")\n end\n end\n action :create\n end\nend",
"def new_option_type_option_types\n [\n {'fieldName' => 'name', 'fieldLabel' => 'Name', 'type' => 'text', 'required' => true, 'displayOrder' => 1},\n {'fieldName' => 'description', 'fieldLabel' => 'Description', 'type' => 'text', 'displayOrder' => 2},\n {'shorthand' => '-l', 'fieldName' => 'labels', 'fieldLabel' => 'Labels', 'type' => 'text', 'required' => false, 'noPrompt' => true, 'processValue' => lambda {|val| parse_labels(val) }, 'displayOrder' => 3},\n {'fieldName' => 'fieldName', 'fieldLabel' => 'Field Name', 'type' => 'text', 'required' => true, 'description' => 'This is the input property that the value gets assigned to.', 'displayOrder' => 4},\n {'code' => 'optionType.type', 'fieldName' => 'type', 'fieldLabel' => 'Type', 'type' => 'select', 'selectOptions' => [{'name' => 'Text', 'value' => 'text'}, {'name' => 'Password', 'value' => 'password'}, {'name' => 'Number', 'value' => 'number'}, {'name' => 'Checkbox', 'value' => 'checkbox'}, {'name' => 'Select', 'value' => 'select'}, {'name' => 'Hidden', 'value' => 'hidden'}], 'defaultValue' => 'text', 'required' => true, 'displayOrder' => 5},\n {'fieldName' => 'optionList', 'fieldLabel' => 'Option List', 'type' => 'select', 'optionSource' => 'optionTypeLists', 'required' => true, 'dependsOnCode' => 'optionType.type:select', 'description' => \"The Option List to be the source of options when type is 'select'.\", 'displayOrder' => 6},\n {'fieldName' => 'fieldLabel', 'fieldLabel' => 'Field Label', 'type' => 'text', 'required' => true, 'description' => 'This is the input label that shows typically to the left of a custom option.', 'displayOrder' => 7},\n {'fieldName' => 'placeHolder', 'fieldLabel' => 'Placeholder', 'type' => 'text', 'displayOrder' => 8},\n {'fieldName' => 'helpBlock', 'fieldLabel' => 'Help Block', 'type' => 'text', 'description' => 'This is the explaination of the input that shows typically underneath the option.', 'displayOrder' => 9},\n {'fieldName' => 'defaultValue', 'fieldLabel' => 'Default Value', 'type' => 'text', 'displayOrder' => 10},\n {'fieldName' => 'required', 'fieldLabel' => 'Required', 'type' => 'checkbox', 'defaultValue' => false, 'displayOrder' => 11},\n {'fieldName' => 'exportMeta', 'fieldLabel' => 'Export As Tag', 'type' => 'checkbox', 'defaultValue' => false, 'description' => 'Export as Tag.', 'displayOrder' => 12},\n {'fieldName' => 'verifyPattern', 'fieldLabel' => 'Verify Pattern', 'type' => 'text', 'dependsOnCode' => 'optionType.type:text', 'description' => 'A regexp string that validates the input, use (?i) to make the matcher case insensitive', 'displayOrder' => 13},\n ]\n end",
"def platform_opts\n case platform\n when 'alpine'\n alpine\n when 'rhel', 'centos', 'fedora'\n rhel\n when 'debian', 'ubuntu'\n debian\n else\n raise \"Unknown platform for #{@name} using #{@image}\"\n end\n end",
"def <<(options)\n\t\t\t\toptions = [options] if !options.is_a?(Array)\n\n\t\t\t\toptions.each do |option|\n\t\t\t\t\t@console.fatal(msg: \"Every attribute must be an Hash.\", dots: false) if !option.is_a?(Hash)\n\n\t\t\t\t\t# Use symbols for names\n\t\t\t\t\toption[:name] = option[:name].to_sym\n\n\t\t\t\t\t# Add the default type, which is :string\n\t\t\t\t\toption[:type] ||= :string\n\n\t\t\t\t\t# Check if type is valid\n\t\t\t\t\t@console.fatal(msg: \"Invalid option type #{option[:type]} for option #{option[:name]}. Valid type are the following:\\n\\t#{@@valid_types.keys.join(\", \")}.\", dots: false) if !@@valid_types.keys.include?(option[:type])\n\n\t\t\t\t\t# Adjust the default value\n\t\t\t\t\tcase option[:type]\n\t\t\t\t\t\twhen :bool then\n\t\t\t\t\t\t\toption[:default] = false if !option.has_key?(:default)\n\t\t\t\t\t\twhen :action then\n\t\t\t\t\t\t\toption[:required] = false\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\toption[:default] = @@valid_types[option[:type]][1] if !option.has_key?(:default) || !option[:default].is_a?(@@valid_types[option[:type]][0])\n\t\t\t\t\tend\n\n\t\t\t\t\t# Adjust priority\n\t\t\t\t\toption[:priority] = option[:priority].to_s.to_i if !option[:priority].is_a?(Integer)\n\n\t\t\t\t\t# Prepend dashes\n\t\t\t\t\toption[:short] = \"-\" + option[:short] if !option[:short] =~ /^-/\n\t\t\t\t\twhile option[:long] !~ /^--/ do option[:long] = \"-\" + option[:long] end\n\t\t\t\t\t@console.fatal(msg: \"Invalid short form \\\"#{option[:short]}\\\".\", dots: false) if option[:short] !~ /^-[0-9a-z]$/i\n\t\t\t\t\t@console.fatal(msg: \"Invalid long form \\\"#{option[:long]}\\\".\", dots: false) if option[:long] !~ /^--([0-9a-z-]+)$/i\n\n\t\t\t\t\t# Check for choices if the type is choices\n\t\t\t\t\tif option[:type] == :choice then\n\t\t\t\t\t\tif option[:choices] == nil then\n\t\t\t\t\t\t\t@console.fatal(msg: \"Option \\\"#{option[:name]}\\\" of type choice requires a valid choices list (every element should be a regular expression).\")\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\toption[:choices].collect! { |choice| Regexp.new(choice) }\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\n\t\t\t\t\t# Check that action is a block if the type is action\n\t\t\t\t\t@console.fatal(\"Option \\\"#{option[:name]}\\\" of type action requires a action block.\") if option[:type] == :action && (option[:action] == nil || !option[:action].is_a?(Proc.class))\n\n\t\t\t\t\t# Check for uniqueness of option and its forms\n\t\t\t\t\t@console.fatal(\"An option with name \\\"#{option[:name]}\\\" already exists.\", dots: false) if @inserted[:name].include?(option[:name])\n\t\t\t\t\t@console.fatal(\"An option with short or long form \\\"#{option[:short]}\\\" already exists.\", dots: false) if @inserted[:short].include?(option[:short])\n\t\t\t\t\t@console.fatal(\"An option with short or long form \\\"#{option[:long]}\\\" already exists.\", dots: false) if @inserted[:long].include?(option[:long])\n\n\t\t\t\t\t# Save\n\t\t\t\t\t@options[option[:name]] = option\n\t\t\t\t\t@options_map[option[:long]] = option[:name]\n\t\t\t\t\t@inserted[:name].push(option[:name])\n\t\t\t\t\t@inserted[:short].push(option[:short])\n\t\t\t\t\t@inserted[:long].push(option[:long])\n\t\t\t\tend\n\t\t\tend",
"def tool_type_params\n params.require(:tool_type).permit(:name, :description)\n end",
"def scripts\n @scripts ||= @options[:scripts].try(:to_sym)\n end",
"def type_to_form_ready_hash\n {\n name: resource[:name],\n physicalPath: resource[:physicalpath],\n directoryType: resource[:directorytype],\n cleanupMode: resource[:cleanupmode],\n maxFileAge: resource[:maxfileage],\n description: resource[:description],\n }\n end",
"def handling_options_label\n $tracer.trace(__method__)\n #unit_test_no_generate: handling_options_label, section.id(\"handling_options\").find.h3\n return ToolTag.new(section.id(\"handling_options\").find.h3, __method__, self)\n end",
"def get_vars(instruction)\n dictionary = {\n 'definition' => ['os_type_id','iso_file','boot_cmd_sequence','postinstall_files'],\n 'kickstart' => ['reponame','pkgs'],\n 'preseed' => ['suite','pkgs'],\n 'autoinst' => ['pkgs']\n }\n # 'kickstart_file' option in definition.rb is deprecated\n # erb_vars = ['os_type_id','iso_file','boot_cmd_sequence','kickstart_file','postinstall_files']\n return dictionary[instruction]\n end",
"def attr_hash\n\t\t\thash = {:sourcetype => @type}\n\t\t\tcase @type\n\t\t\twhen 'random_string'\n\t\t\t\thash[:length] = @length\n\t\t\twhen 'random_number'\n\t\t\t\thash[:start] = @start\n\t\t\t\thash[:end] = @end\n\t\t\twhen 'eval'\n\t\t\t\thash[:code] = @code.chomp.to_sym\t\t\t# symbolize it in order to prevent it from being escaped\n\t\t\twhen 'file'\n\t\t\t\thash[:fileid] = @fileid\n\t\t\t\thash[:delimiter] = @delimiter\n\t\t\t\thash[:order] = @order\n\t\t\tend\n\t\t\thash\n\t\tend",
"def tool_params\n params.require(:tool).permit(:name, :language, :json_spec)\n end",
"def tool_params\n params.require(:tool).permit(\n :name,\n :slug,\n :type,\n :description,\n :source_url,\n :instructions,\n :up_for_adoption\n )\n end",
"def process_options\n img_string = @img.to_s\n options_erb = {}\n\n Params.each do |opt|\n name = opt[:name]\n value = @img[name]\n\n unless value.nil?\n options_erb[name] = \"#{name}: '#{value}'\"\n end\n end\n\n # extract data attributes\n while img_string.include? 'data-'\n removed_left_content = img_string.slice(img_string.index(\"data-\")..-1)\n data_attribute = (removed_left_content.slice(0..(removed_left_content.index('=')))).tr('=', '')\n data_value = @img[data_attribute]\n\n if data_attribute != 'data-pixel-density-2'\n options_erb[data_attribute] = \"'#{data_attribute}': '#{data_value}'\"\n end\n img_string.gsub!(data_attribute, \"\")\n end\n\n options_erb.empty? ? \"\" : \", \" + options_erb.values.join(\", \")\n end",
"def config_options\n {\n 'datacenter' => new_resource.datacenter,\n 'template_path' => new_resource.template_path,\n 'power_on' => true,\n 'datastore' => new_resource.datastore,\n 'wait' => true,\n 'hostname' => new_resource.hostname,\n 'name' => new_resource.name,\n 'customization_spec' => {\n 'domain' => new_resource.domain,\n 'ipsettings' => {\n 'ip' => new_resource.ip || node['vcac_vm']['ip'],\n 'gateway' => new_resource.gateway,\n 'subnetMask' => new_resource.subnet_mask,\n },\n }\n }\nend",
"def tools_setup(config)\n config[:tools].each_key do |name|\n tool = config[:tools][name]\n\n # populate name if not given\n tool[:name] = name.to_s if (tool[:name].nil?)\n\n # handle inline ruby string substitution in executable\n if (tool[:executable] =~ RUBY_STRING_REPLACEMENT_PATTERN)\n tool[:executable].replace(@system_wrapper.module_eval(tool[:executable]))\n end\n\n # populate stderr redirect option\n tool[:stderr_redirect] = StdErrRedirect::NONE if (tool[:stderr_redirect].nil?)\n\n # populate background execution option\n tool[:background_exec] = BackgroundExec::NONE if (tool[:background_exec].nil?)\n\n # populate optional option to control verification of executable in search paths\n tool[:optional] = false if (tool[:optional].nil?)\n end\n end",
"def deploy_commands(runtime)\n runtime.kubectl(\"create secret generic #{name} --from-literal=#{FIXED_FILE}=#{secret}\")\n end",
"def packer_config\n JSON.dump(JSON.parse(super).tap do |config|\n config['builders'] = [\n {\n \"type\" => \"vsphere\",\n \"vcenter_server\" => Stemcell::Builder::validate_env('VCENTER_SERVER'),\n \"username\" => Stemcell::Builder::validate_env('VCENTER_USERNAME'),\n \"password\" => Stemcell::Builder::validate_env('VCENTER_PASSWORD'),\n \"insecure_connection\" => true,\n\n \"template\" => Stemcell::Builder::validate_env('BASE_TEMPLATE'),\n \"folder\" => Stemcell::Builder::validate_env('VCENTER_VM_FOLDER'),\n \"vm_name\" => \"packer-vmx\",\n \"host\" => Stemcell::Builder::validate_env('VCENTER_HOST'),\n \"resource_pool\" => \"\",\n # \"ssh_username\" => 'Administrator',\n # \"ssh_password\" => Stemcell::Builder::validate_env('ADMINISTRATOR_PASSWORD'),\n 'communicator' => 'winrm',\n 'winrm_username' => 'Administrator',\n 'winrm_password' => Stemcell::Builder::validate_env('ADMINISTRATOR_PASSWORD'),\n 'winrm_timeout' => '3h',\n 'winrm_insecure' => true,\n \"CPUs\" => ENV.fetch('NUM_VCPUS', '4'),\n \"RAM\" => ENV.fetch('MEM_SIZE', '4096'),\n }\n ]\n end)\n end",
"def bc_install_layout_1_chef(bc, path, barclamp, options={})\n options = {:debug => false}.merge! options\n debug = options[:debug] or ENV['DEBUG'] === \"true\"\n \n log_path = File.join '/var', 'log', 'barclamps'\n FileUtils.mkdir log_path unless File.directory? log_path\n log = File.join log_path, \"#{bc}.log\"\n system \"date >> #{log}\"\n puts \"DEBUG: Capturing chef install logs to #{log}\" if debug\n chef = File.join path, 'chef'\n cookbooks = File.join chef, 'cookbooks'\n databags = File.join chef, 'data_bags'\n roles = File.join chef, 'roles'\n \n #upload the cookbooks\n if File.directory? cookbooks\n FileUtils.cd cookbooks\n knife_cookbook = \"knife cookbook upload -o . -a -V -k /etc/chef/webui.pem -u chef-webui\"\n unless system knife_cookbook + \" >> #{log} 2>&1\"\n puts \"\\t#{path} #{knife_cookbook} upload failed. Examine #{log} for more into\"\n exit 1\n end\n puts \"DEBUG: \\texecuted: #{path} #{knife_cookbook}\" if debug \n else\n puts \"DEBUG: \\tNOTE: could not find cookbooks #{cookbooks}\" if debug\n end\n \n #upload the databags\n if File.exists? databags\n Dir.entries(databags).each do |bag|\n next if bag == \".\" or bag == \"..\"\n bag_path = File.join databags, bag \n FileUtils.chmod 0755, bag_path\n chmod_dir 0644, bag_path\n FileUtils.cd bag_path\n knife_bag = \"knife data bag create #{bag} -V -k /etc/chef/webui.pem -u chef-webui\"\n unless system knife_bag + \" >> #{log} 2>&1\"\n puts \"\\t#{knife_bag} failed. Examine #{log} for more information.\"\n exit 1\n end\n puts \"\\texecuted: #{path} #{knife_bag}\" if debug\n \n json = Dir.entries(bag_path).find_all { |r| r.end_with?(\".json\") }\n json.each do |bag_file|\n knife_databag = \"knife data bag from file #{bag} #{bag_file} -V -k /etc/chef/webui.pem -u chef-webui\"\n unless system knife_databag + \" >> #{log} 2>&1\"\n puts \"\\t#{knife_databag} failed. Examine #{log} for more information.\"\n exit 1\n end\n puts \"DEBUG: \\texecuted: #{path} #{knife_databag}\" if debug\n end\n end\n else\n puts \"DEBUG: \\tNOTE: could not find databags #{databags}\" if debug\n end\n \n #upload the roles\n if File.directory? roles\n FileUtils.cd roles\n Dir.entries(roles).find_all { |r| r.end_with?(\".rb\") }.each do |role|\n knife_role = \"knife role from file #{role} -V -k /etc/chef/webui.pem -u chef-webui\"\n unless system knife_role + \" >> #{log} 2>&1\"\n puts \"\\t#{knife_role} failed. Examine #{log} for more information.\"\n exit 1\n end\n puts \"DEBUG: \\texecuted: #{path} #{knife_role}\" if debug\n end\n else\n puts \"DEBUG: \\tNOTE: could not find roles #{roles}\" if debug\n end\n \n puts \"Barclamp #{bc} (format v1) Chef Components Uploaded.\" \n \nend",
"def label_specification\n { 'LabelFormatType' => 'COMMON2D',\n 'ImageType' => 'PNG',\n 'LabelStockType' => 'PAPER_4X6',\n :order! => ['LabelFormatType', 'ImageType', 'LabelStockType'] }\n end",
"def app_script_text(bin_file_name)\n <<-TEXT\n#\n# This file was generated by RubyGems.\n#\n# The application '#{@spec.name}' is installed as part of a gem, and\n# this file is here to facilitate running it.\n#\n\nrequire 'rubygems'\n\nversion = \"#{Gem::Requirement.default}\"\n\nif ARGV.first =~ /^_(.*)_$/ and Gem::Version.correct? $1 then\n version = $1\n ARGV.shift\nend\n\ngem '#{@spec.name}', version\nload Gem.bin_path('#{@spec.name}', '#{bin_file_name}', version)\nTEXT\n end",
"def option_type(ns=[])\n a_template = (self =~ /template/) == 0\n a_service = self =~ /^[A-Z][a-zA-Z]*\\[[a-zA-Z0-9\\-\\.\\\"\\'_\\$\\{\\}\\/]*\\]/i\n a_function = self =~/(.)*\\((.)*\\)(.)*/\n if is_a?(PoolParty::Resources::Resource)\n self.to_s\n else\n (a_service || a_template || a_function) ? self : \"'#{self}'\"\n end \n end",
"def manifest() @opts.manifest; end",
"def patch_wrapper_script(prog)\n\t\twrapper_script_header = <<-WRAPPER_SCRIPT_HEADER\n#!/bin/bash\n\nexport LANG=en_US.UTF-8\nexport LANGUAGE=en_US.UTF-8\nexport LC_ALL=en_US.UTF-8\n\nCOMMONSDIR=\"#{HOMEBREW_PREFIX.join('opt', 'hets-commons')}\"\nPROGDIR=\"#{prefix}\"\nPROG=\"#{prog}\"\n\n[[ -z ${HETS_JNI_LIBS} ]] && \\\\\n\t\t HETS_JNI_LIBS=\"#{HOMEBREW_PREFIX.join('opt', 'factplusplus')}\"\nWRAPPER_SCRIPT_HEADER\n\n\t\t# Replace the header until (including) the line starting with PROG=\n\t\tinreplace(bin.join(prog), /\\A.*PROG=[^\\n]*$/m, wrapper_script_header)\n inreplace(bin.join(prog), 'BASEDIR', 'COMMONSDIR')\n inreplace(bin.join(prog), /PELLET_PATH=.*$/, \"PELLET_PATH=#{HOMEBREW_PREFIX.join('opt', 'pellet', 'bin')}\")\n inreplace(bin.join(prog), /^\\s*exec\\s+([\"']).*COMMONSDIR[^\\/]*/, 'exec \\1${PROGDIR}')\n end",
"def arguments(model = nil)\n args = OpenStudio::Measure::OSArgumentVector.new\n\n # Make an argument for the template\n template = OpenStudio::Measure::OSArgument.makeChoiceArgument('template', get_doe_templates(false), true)\n template.setDisplayName('Target ASHRAE Standard')\n template.setDescription('This used to set the target standard for most checks.')\n template.setDefaultValue('90.1-2013') # there is override variable in run method for this\n args << template\n\n # add arguments from possible_check_categories\n possible_check_categories.each do |hash|\n cat = hash[:cat]\n cat_input = \"\\'#{cat}\\'\"\n if hash[:standards]\n standards_input = \",\\'selected ASHRAE standard\\'\"\n else\n standards_input = ''\n end\n if hash[:data].nil?\n data_input = ''\n else\n data_input = \",#{hash[:data]}\"\n end\n if !hash[:tol_min]\n min = nil\n min_input = ''\n else\n min = hash[:tol_min]\n min_input = \",#{min}\"\n end\n if hash[:tol_max].is_a? Float\n max = hash[:tol_max]\n max_input = \",#{max}\"\n elsif !hash[:tol_max]\n max = nil\n max_input = ''\n else\n max = hash[:tol_min]\n max_input = \",#{max}\"\n end\n\n name_cat_desc = eval(\"#{hash[:method_name]}(#{cat_input}#{data_input}#{standards_input}#{min_input}#{max_input},true)\")\n arg = OpenStudio::Measure::OSArgument.makeBoolArgument(hash[:method_name], true)\n arg.setDisplayName(\"#{name_cat_desc[0]} (#{hash[:cat]})\")\n arg.setDescription(name_cat_desc[2])\n arg.setDefaultValue(true)\n args << arg\n if !min.nil?\n arg_tol = OpenStudio::Measure::OSArgument.makeDoubleArgument(\"#{hash[:method_name]}_tol\", true)\n arg_tol.setDisplayName(\"#{name_cat_desc[0]} Tolerance\")\n arg_tol.setDefaultValue(min)\n arg_tol.setUnits(hash[:units])\n args << arg_tol\n end\n if hash[:tol_max].is_a? Float\n arg_max_tol = OpenStudio::Measure::OSArgument.makeDoubleArgument(\"#{hash[:method_name]}_max_tol\", true)\n arg_max_tol.setDisplayName(\"#{name_cat_desc[0]} Max Tolerance\")\n arg_max_tol.setDefaultValue(max)\n arg_max_tol.setUnits(hash[:units])\n args << arg_max_tol\n end\n end\n\n # make an argument for use_upstream_args\n use_upstream_args = OpenStudio::Measure::OSArgument.makeBoolArgument('use_upstream_args', true)\n use_upstream_args.setDisplayName('Use Upstream Argument Values')\n use_upstream_args.setDescription('When true this will look for arguments or registerValues in upstream measures that match arguments from this measure, and will use the value from the upstream measure in place of what is entered for this measure.')\n use_upstream_args.setDefaultValue(true)\n args << use_upstream_args\n\n return args\n end",
"def create\n @option = \"Vger::Resources::#{params[:option][:option_type]}\".constantize.new(params[:option])\n respond_to do |format|\n if @option.save\n format.html { redirect_to suitability_factor_item_option_path(params[:factor_id],params[:item_id], @option), notice: 'Suitability Option was successfully created.' }\n format.js\n format.json { render json: @option, status: :created, location: @option }\n else\n format.html { render action: \"new\" }\n format.js\n format.json { render json: @option.errors, status: :unprocessable_entity }\n end\n end\n end",
"def post_app_generate(application_id, type, opts={})\n # \n # default_options = {\n # \"name\" => \"\",\n # \"author\" => \"\",\n # \"description\" => \"\",\n # \"guid\" => \"\",\n # \"datasets\" => \"\",\n # \"env\" => \"prod\",\n # \"image_url\" => \"http://appresource.s3.amazonaws.com/apiappimages/missing_icard.jpg\",\n # \"runtime\" => \"\"\n # }\n # options = default_options.merge(opts)\n return post_response(\"app/#{application_id}/generate/#{type}\", opts,:json)\n end",
"def configure options\n options.map do |key, value|\n types = {String => 'string', Fixnum => 'int', TrueClass => 'bool',\n FalseClass => 'bool', Float => 'float', Array => 'list --list-type=string'}\n type = types[value.class]\n raise 'Invalid type for configure' unless type\n value = value.to_json if value.is_a?(Array)\n value = %(\"#{value}\") if type == 'string'\n check = \"gconftool-2 --get \\\"#{key}\\\" | grep #{value} #{echo_result}\"\n Command.new(\"gconftool-2 --set \\\"#{key}\\\" --type #{type} #{value}\", check)\n end\n end",
"def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\n\n bldgType = OpenStudio::StringVector.new\n bldgType << 'Large Office Detailed'\n bldgType << 'Medium Office Detailed'\n bldgType << 'Retail Standalone'\n bldgType << 'Big Box Retail'\n buildingType = OpenStudio::Ruleset::OSArgument.makeChoiceArgument('buildingType', bldgType, true)\n buildingType.setDisplayName('Select the building type')\n buildingType.setDefaultValue('Retail Standalone')\n args << buildingType\n\n\n # make an argument for control_type\n vint = OpenStudio::StringVector.new\n vint << 'Post-1980'\n vint << '2010'\n vintage = OpenStudio::Ruleset::OSArgument.makeChoiceArgument('vintage', vint, true)\n vintage.setDisplayName('Select the vintage')\n vintage.setDefaultValue('2010')\n args << vintage\n\n # make an argument for control_type\n period = OpenStudio::StringVector.new\n period << 'All year'\n period << 'Summer'\n period << 'Winter'\n drPeriod = OpenStudio::Ruleset::OSArgument.makeChoiceArgument('drPeriod', period, true)\n drPeriod.setDisplayName('Select the period')\n drPeriod.setDefaultValue('All year')\n args << drPeriod\n\n\n # make an argument for control_type\n drtyp = OpenStudio::StringVector.new\n drtyp << 'Lighting'\n drtyp << 'Plug loads'\n drtyp << 'Summer GTA'\n drtyp << 'Pre-cool and Summer GTA'\n drtyp << 'Winter GTA'\n drtyp << 'Pre-heat and Winter GTA'\n drType = OpenStudio::Ruleset::OSArgument.makeChoiceArgument('drType', drtyp, true)\n drType.setDisplayName('Select the demand response type')\n drType.setDefaultValue('Lighting')\n args << drType\n\n # populate choice argument for schedules in the model\n sch_handles = OpenStudio::StringVector.new\n sch_display_names = OpenStudio::StringVector.new\n\n # putting schedule names into hash\n sch_hash = {}\n model.getSchedules.each do |sch|\n sch_hash[sch.name.to_s] = sch\n end\n\n # looping through sorted hash of schedules\n sch_hash.sort.map do |sch_name, sch|\n if !sch.scheduleTypeLimits.empty?\n unitType = sch.scheduleTypeLimits.get.unitType\n puts \"#{sch.name}, #{unitType}\"\n # if unitType == 'Temperature'\n sch_handles << sch.handle.to_s\n sch_display_names << sch_name\n # end\n end\n end\n\n # add empty handle to string vector with schedules\n sch_handles << OpenStudio.toUUID('').to_s\n sch_display_names << '*No Change*'\n\n # make an argument for cooling schedule\n schedule_old = OpenStudio::Measure::OSArgument.makeChoiceArgument('schedule_old', sch_handles, sch_display_names, true)\n schedule_old.setDisplayName('Choose a schedule to be replaced.')\n schedule_old.setDefaultValue('*No Change*') # if no change is chosen then cooling schedules will not be changed\n args << schedule_old\n\n usepredefined = OpenStudio::Measure::OSArgument.makeBoolArgument('usepredefined', true)\n usepredefined.setDisplayName('Use pre-defined schedule?')\n usepredefined.setDefaultValue(true)\n args << usepredefined\n\n\n return args\n end",
"def opts\n\n Map.new({\n :exe => @exe,\n :parameters => @parameters,\n :scripts => @scripts,\n :original_path => FileUtils.pwd\n })\n end",
"def recipe_type_params\n params.require(:recipe_type).permit(:name, :description)\n end",
"def typeString(type)\n if type == \"pre-scripts\"\n return _(\"Pre\")\n elsif type == \"post-scripts\"\n return _(\"Post\")\n elsif type == \"init-scripts\"\n return _(\"Init\")\n elsif type == \"chroot-scripts\"\n return _(\"Chroot\")\n elsif type == \"postpartitioning-scripts\"\n return _(\"Postpartitioning\")\n end\n _(\"Unknown\")\n end",
"def platform_merge ln\n flds = ln.split(' ')\n return if flds[0].to_i == 0\n # app-version-arch'\n fname = flds[2]\n #parts = fname.split('-')\n #return if parts[length] < 3\n #puts \"fname = #{fname}\"\n case ln\n when /32\\.exe$/\n @platforms['Win32'] = ln\n when /\\.tbz$/\n return # ignore \n when /\\.run$/\n return # short circuit - ignore .runs in 3.2.15+ \n when /osx\\-.*\\.tgz$/\n @platforms['OSX'] = ln\n when /armhf\\.run$/\n @platforms['Linux_Raspberry'] = ln\n when /i686\\.run$/\n @platforms['Linux_i686'] = ln\n when /x86_64\\.run$/ \n @platforms['Linux_x86_64'] = ln\n when /armhf\\.install$/\n @platforms['Linux_Raspberry'] = ln\n when /i686\\.install$/\n @platforms['Linux_i686'] = ln\n when /x86_64\\.install$/ \n @platforms['Linux_x86_64'] = ln\n when /tar\\.gz$/\n tarball = ln\n else\n #puts \"failed match #{ln}\"\n end\n return\n end",
"def add_opts!(type=:gen, *opts)\n opt_type = OpenBabel::OBConversion.const_get(type.to_s.upcase.<<(\"OPTIONS\"))\n hash = \n if opts.first.is_a?(Hash)\n opts.first\n else\n opts.inject({}) do |hsh,v| \n if v.is_a?(Array)\n hsh[v[0]] = v[1]\n else\n hsh[v] = true\n end\n hsh\n end\n end\n hash.each do |k,v|\n next if v == false\n args = [ (OUT_OPTS_SHORT[k] || k).to_s, opt_type ]\n if v && (v != true)\n args << v\n end\n self.add_option(*args)\n end\n self\n end",
"def update_answer_type_params\n scalar_params = [].tap do |result|\n result.push(:answer_text) # Text response answer\n end\n # Parameters that must be an array of permitted values\n array_params = {}.tap do |result|\n result[:option_ids] = [] # MRQ answer\n result[:files_attributes] = [:id, :_destroy, :filename, :content] # Programming answer\n end\n scalar_params.push(array_params)\n end",
"def add_options_variants\n # TODO smart column ordering to ensure always valid by time we get to associations\n begin\n save_if_new\n rescue => e\n raise ProductLoadError.new(\"Cannot add OptionTypes/Variants - Save failed on parent Product\")\n end\n # example : mime_type:jpeg;print_type:black_white|mime_type:jpeg|mime_type:png, PDF;print_type:colour\n\n variants = get_each_assoc\n\n logger.info \"add_options_variants #{variants.inspect}\"\n\n # example line becomes :\n # 1) mime_type:jpeg|print_type:black_white\n # 2) mime_type:jpeg\n # 3) mime_type:png, PDF|print_type:colour\n\n variants.each do |per_variant|\n option_types = per_variant.split(Delimiters::multi_facet_delim) # => [mime_type:jpeg, print_type:black_white]\n optiontype_vlist_map = {}\n\n option_types.each do |ostr|\n\n oname, value_str = ostr.split(Delimiters::name_value_delim)\n\n option_type = @@option_type_klass.where(:name => oname).first\n\n unless option_type\n option_type = @@option_type_klass.create( :name => oname, :presentation => oname.humanize)\n # TODO - dynamic creation should be an option\n\n unless option_type\n puts \"WARNING: OptionType #{oname} NOT found and could not create - Not set Product\"\n next\n end\n puts \"Created missing OptionType #{option_type.inspect}\"\n end\n\n # OptionTypes must be specified first on Product to enable Variants to be created\n # TODO - is include? very inefficient ??\n @product.option_types << option_type unless @product.option_types.include?(option_type)\n\n # Can be simply list of OptionTypes, some or all without values\n next unless(value_str)\n\n optiontype_vlist_map[option_type] = []\n\n # Now get the value(s) for the option e.g red,blue,green for OptType 'colour'\n optiontype_vlist_map[option_type] = value_str.split(',')\n end\n next if(optiontype_vlist_map.empty?) # only option types specified - no values\n # Now create set of Variants, some of which maybe composites\n # Find the longest set of OVs to use as base for combining with the rest\n sorted_map = optiontype_vlist_map.sort_by { |k,v| v.size }.reverse\n # [ [mime, ['pdf', 'jpeg', 'gif']], [print_type, ['black_white']] ]\n lead_option_type, lead_ovalues = sorted_map.shift\n lead_ovalues.each do |ovname|\n ov_list = []\n ovname.strip!\n ov = @@option_value_klass.find_or_create_by_name_and_option_type_id(ovname, lead_option_type.id, :presentation => ovname.humanize)\n ov_list << ov if ov\n\n # Process rest of array of types => values\n sorted_map.each do |ot, ovlist|\n ovlist.each do |for_composite|\n for_composite.strip!\n ov = @@option_value_klass.find_or_create_by_name_and_option_type_id(for_composite, ot.id, :presentation => for_composite.humanize)\n ov_list << ov if(ov)\n end\n end\n\n unless(ov_list.empty?)\n puts \"Creating Variant from OptionValue(s) #{ov_list.collect(&:name).inspect}\"\n i = @product.variants.size + 1\n variant = @product.variants.create sku: \"#{@product.sku}_#{i}\",\n price: @product.price,\n weight: @product.weight,\n height: @product.height,\n width: @product.width,\n depth: @product.depth\n variant.option_values << ov_list if variant\n puts \"Created #{variant.class} : #{variant.inspect}\" if verbose\n end\n end\n end\n end",
"def dummy_recipe(name, checksum)\n {\n \"name\" => \"#{name}.rb\",\n \"path\" => \"recipes/#{name}.rb\",\n \"checksum\" => checksum,\n \"specificity\" => \"default\",\n }\n end",
"def build_script\n raise NotImplementedError\n end",
"def compiler_options\n options = {}\n options['tmp_dir'] = @tmp_dir if @tmp_dir\n options['lib_dir'] = @lib_dir if @lib_dir\n options['config_script'] = @config_script if @config_script\n options['config_options'] = @config_options if @config_options\n #options['cross_config_options'] = @cross_config_options\n options\n end",
"def build_options(opts)\n options = []\n opts.each do |opt|\n val = new_resource.send(opt.to_sym)\n options << \"--#{opt}=\\\"#{val}\\\"\" unless val.nil?\n end\n options\n end",
"def create_button_config( action_title_i19n_sym, action_title_i19n_scope_sym, image_name = \"cog.png\" )\n action_text = I18n.t( action_title_i19n_sym.to_sym, {:scope => [action_title_i19n_scope_sym ? action_title_i19n_scope_sym.to_sym : nil]} )\n tooltip_text = I18n.t( \"#{action_title_i19n_sym}_tooltip\".to_sym, {:scope => [action_title_i19n_scope_sym ? action_title_i19n_scope_sym.to_sym : nil]} )\n {\n :xtype => 'button',\n :id => action_title_i19n_sym.to_s,\n :name => action_title_i19n_sym.to_s,\n :icon => \"/images/icons/#{ image_name }\",\n :text => \"#{ action_text }\",\n :tooltip => \"#{ tooltip_text }\",\n :margin => '0 3 3 3'\n }\n end",
"def checktype_params\n params.require(:checktype).permit(:name, :description, :timeout, :enabled, :options, :image, :assets => [], :required_vars => [])\n end",
"def knifeAddToRunList(rl_entry = nil, type=\"role\", ignore_missing: false, multiple: [])\n self.class.loadChefLib\n return if rl_entry.nil? and multiple.size == 0\n if multiple.size == 0\n multiple = [rl_entry]\n end\n multiple.map! { |entry|\n if !entry.match(/^role|recipe\\[/)\n \"#{type}[#{entry}]\"\n else\n entry\n end\n }\n\n if !ignore_missing\n role_list = nil\n recipe_list = nil\n missing = false\n multiple.each { |entry|\n # Rather than argue about whether to expect a bare entry name or\n # require entry[rolename], let's just accomodate.\n if entry.match(/^role\\[(.+?)\\]/)\n entry_name = Regexp.last_match(1)\n if role_list.nil?\n query=%Q{#{MU::Groomer::Chef.knife} role list};\n role_list = %x{#{query}}\n end\n if !role_list.match(/(^|\\n)#{entry_name}($|\\n)/)\n MU.log \"Attempting to add non-existent #{entry} to #{@server.mu_name}\", MU::WARN\n missing = true\n end\n elsif entry.match(/^recipe\\[(.+?)\\]/)\n entry_name = Regexp.last_match(1)\n if recipe_list.nil?\n query=%Q{#{MU::Groomer::Chef.knife} recipe list};\n recipe_list = %x{#{query}}\n end\n if !recipe_list.match(/(^|\\n)#{entry_name}($|\\n)/)\n MU.log \"Attempting to add non-existent #{entry} to #{@server.mu_name}\", MU::WARN\n missing = true\n end\n end\n\n if missing and !ignore_missing\n raise MuError, \"Can't continue with missing roles/recipes for #{@server.mu_name}\"\n end\n }\n end\n\n rl_string = multiple.join(\",\")\n begin\n query=%Q{#{MU::Groomer::Chef.knife} node run_list add #{@server.mu_name} \"#{rl_string}\"};\n MU.log(\"Adding #{rl_string} to Chef run_list of #{@server.mu_name}\")\n MU.log(\"Running #{query}\", MU::DEBUG)\n output=%x{#{query}}\n # XXX rescue StandardError is bad style\n rescue StandardError => e\n raise MuError, \"FAIL: #{MU::Groomer::Chef.knife} node run_list add #{@server.mu_name} \\\"#{rl_string}\\\": #{e.message} (output was #{output})\"\n end\n end",
"def methods_available_to_script\n [ 'program', 'version', 'updated, :maintainer',\n 'build_size', 'noarch', 'system_files',\n 'resource.categories', 'resource.dependencies', 'resource.conflicts',\n 'resource.compliment', 'resource.supplement' \n ].collect { |m| \"#{m}\" }\n end",
"def variable_define_flags\n flags = Hash.new\n flags['PuppetDescTag'] = describe 'downloads/puppet'\n flags['FacterDescTag'] = describe 'downloads/facter'\n\n # The regular expression with back reference groups for version string\n # parsing. We re-use this against either git-describe on Puppet or on\n # ENV['PE_VERSION_STRING'] which should match the same pattern. NOTE that we\n # can only use numbers in the product version and that product version\n # impacts major upgrades: ProductVersion Property is defined as\n # [0-255].[0-255].[0-65535] See:\n # http://stackoverflow.com/questions/9312221/msi-version-numbers\n # This regular expression focuses on the major numbers and discards things like \"rc1\" in the string\n version_regexps = [\n /(\\d+)[^.]*?\\.(\\d+)[^.]*?\\.(\\d+)[^.]*?-(\\d+)-(.*)/,\n /(\\d+)[^.]*?\\.(\\d+)[^.]*?\\.(\\d+)[^.]*?\\.(\\d+)/,\n /(\\d+)[^.]*?\\.(\\d+)[^.]*?\\.(\\d+)[^.]*?/,\n ]\n\n case ENV['BRANDING']\n when /enterprise/i\n flags['PackageBrand'] = \"enterprise\"\n msg = \"Could not parse PE_VERSION_STRING env variable. Set it with something like PE_VERSION_STRING=2.5.0\"\n # The Package Version components for FOSS\n match_data = nil\n version_regexps.find(lambda { raise ArgumentError, msg }) do |re|\n match_data = ENV['PE_VERSION_STRING'].match re\n end\n flags['MajorVersion'] = match_data[1]\n flags['MinorVersion'] = match_data[2]\n flags['BuildVersion'] = match_data[3]\n flags['Revision'] = match_data[4] || 0\n else\n flags['PackageBrand'] = \"foss\"\n msg = \"Could not parse git-describe annotated tag for Puppet\"\n # The Package Version components for FOSS\n match_data = nil\n version_regexps.find(lambda { raise ArgumentError, msg }) do |re|\n match_data = flags['PuppetDescTag'].match re\n end\n flags['MajorVersion'] = match_data[1]\n flags['MinorVersion'] = match_data[2]\n flags['BuildVersion'] = match_data[3]\n flags['Revision'] = match_data[4] || 0\n end\n\n # Return the string of flags suitable for candle\n flags.inject([]) { |a, (k,v)| a << \"-d#{k}=\\\"#{v}\\\"\" }.join \" \"\nend",
"def build_flags_cross\n # Unclear if we need config_site CONFIG_SITE=/etc/dpkg-cross/cross-config.i386\n [] << '-a' << cross_arch\n end",
"def pig_command_script_template_parameters(cmd, pig_version, pig_parameters)\n template_params = {}\n template_params['pig_params_file'] = make_pig_param_file(pig_parameters)\n template_params['pig_dir'] = pig_version.name\n template_params['pig_home'] = pig_directory(pig_version)\n template_params['pig_classpath'] = \"#{pig_directory(pig_version)}/lib-local/*:#{lib_directory}/lib-local/*:#{pig_directory(pig_version)}/lib-pig/*:#{pig_directory(pig_version)}/lib-cluster/*:#{lib_directory}/lib-pig/*:#{lib_directory}/lib-cluster/*:#{jython_directory}/jython.jar\"\n template_params['classpath'] = template_params_classpath\n template_params['log4j_conf'] = log4j_conf\n template_params['project_home'] = File.expand_path(\"..\", local_install_directory)\n template_params['local_install_dir'] = local_install_directory\n template_params['pig_sub_command'] = cmd\n template_params['pig_opts'] = pig_options\n template_params\n end",
"def build_command_line(tool_config, extra_params, *args)\n @tool_name = tool_config[:name]\n @executable = tool_config[:executable]\n\n command = {}\n\n # basic premise is to iterate top to bottom through arguments using '$' as\n # a string replacement indicator to expand globals or inline yaml arrays\n # into command line arguments via substitution strings\n # executable must be quoted if it includes spaces (common on windows)\n executable = @tool_executor_helper.osify_path_separators( expandify_element(@executable, *args) )\n executable = \"\\\"#{executable}\\\"\" if executable.include?(' ')\n command[:line] = [\n executable,\n extra_params.join(' ').strip,\n build_arguments(tool_config[:arguments], *args),\n ].reject{|s| s.nil? || s.empty?}.join(' ').strip\n\n command[:options] = {\n :stderr_redirect => @tool_executor_helper.stderr_redirection(tool_config, @configurator.project_logging),\n :background_exec => tool_config[:background_exec]\n }\n\n return command\n end",
"def recipe?(recipe)\n template_options[recipe.to_sym] = yes?((\"Install #{recipe.to_s}?\"))\n end",
"def custom_item_form options\n group_html = \"<li id='#{options[:id]}' class='p'>\"\n group_html += options[:label] ? \"<label for='#{options[:id]}'>#{options[:label]}</label>\" : \"\"\n group_html += \"<div class='wrap-custom-html'>#{options[:html]}</div>\"\n group_html += options[:hint] ? \"<p class='inline-hints'>#{options[:hint]}</p>\" : \"\"\n group_html += \"</li>\"\n group_html.html_safe\n end",
"def required_options\n %i[input output]\n end",
"def required_options\n %i[input output]\n end",
"def patch_kubernetes_addon_definition_with_http_info(moid, kubernetes_addon_definition, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: KubernetesApi.patch_kubernetes_addon_definition ...'\n end\n # verify the required parameter 'moid' is set\n if @api_client.config.client_side_validation && moid.nil?\n fail ArgumentError, \"Missing the required parameter 'moid' when calling KubernetesApi.patch_kubernetes_addon_definition\"\n end\n # verify the required parameter 'kubernetes_addon_definition' is set\n if @api_client.config.client_side_validation && kubernetes_addon_definition.nil?\n fail ArgumentError, \"Missing the required parameter 'kubernetes_addon_definition' when calling KubernetesApi.patch_kubernetes_addon_definition\"\n end\n # resource path\n local_var_path = '/api/v1/kubernetes/AddonDefinitions/{Moid}'.sub('{' + 'Moid' + '}', CGI.escape(moid.to_s))\n\n # query parameters\n query_params = opts[:query_params] || {}\n\n # header parameters\n header_params = opts[:header_params] || {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n content_type = @api_client.select_header_content_type(['application/json', 'application/json-patch+json'])\n if !content_type.nil?\n header_params['Content-Type'] = content_type\n end\n header_params[:'If-Match'] = opts[:'if_match'] if !opts[:'if_match'].nil?\n\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:debug_body] || @api_client.object_to_http_body(kubernetes_addon_definition)\n\n # return_type\n return_type = opts[:debug_return_type] || 'KubernetesAddonDefinition'\n\n # auth_names\n auth_names = opts[:debug_auth_names] || ['cookieAuth', 'http_signature', 'oAuth2', 'oAuth2']\n\n new_options = opts.merge(\n :operation => :\"KubernetesApi.patch_kubernetes_addon_definition\",\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:PATCH, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: KubernetesApi#patch_kubernetes_addon_definition\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def options_create opts, colors\n\t\t\t\t#todo create, switch\n\t\t\t\topts.separator \" *\".colorize(colors[:cyan]) + \" create, switch\".colorize(colors[:yellow]) + \n\t\t\t\t\" creates a new list or switches to an existing one\".colorize(colors[:magenta])\n\t\t\t\topts.separator \" usage: \".colorize(colors[:cyan]) + USAGE[:create].colorize(colors[:red])\n\t\t\tend",
"def update_resource_automation_parameters\n installed_component = InstalledComponent.find(params[:resource_installed_component_id]) if params[:resource_installed_component_id].present?\n old_installed_component_id = params[:resource_old_installed_component_id] || nil\n\n if params[:resource_step_id].present?\n step = Step.find(params[:resource_step_id])\n else\n # This means step object is a new record\n @request = Request.find(params[:resource_request_id]) if params[:resource_request_id].present?\n if @request.present?\n step = @request.steps.build\n step.component_id = params[:resource_component_id]\n step.installed_component_id = params[:resource_installed_component_id]\n step.script_id = params[:resource_script_id]\n step.script_type = params[:resource_script_type]\n step.owner = params[:resource_step_owner_type].constantize.find_by_id(params[:resource_step_owner_id]) unless params[:resource_step_owner_type].blank?\n end\n end\n script = Script.find(params[:resource_script_id])\n old_installed_component_hash = old_installed_component_id.nil? ? nil : {:old_installed_component_id => old_installed_component_id}\n argument_values = step.present? ? step.script_argument_values_display(old_installed_component_hash) : nil\n if request.xhr?\n arg_hsh = {}\n script.arguments.each do |argument|\n if argument.external_resource.present?\n new_argument_value = argument_values[argument.id][\"value\"] rescue nil\n ss = view_context.script_argument_value_input_display(step, argument, installed_component, new_argument_value, true)\n arg_hsh[argument.id] = ss\n end\n end\n render :json => arg_hsh.to_json\n end\n end",
"def initialize(script, timeout: -1)\n # This Powershell DLL source lives here: https://github.com/chef/chef-powershell-shim\n # Every merge into that repo triggers a Habitat build and verification process.\n # There is no mechanism to build a Windows gem file. It has to be done manually running manual_gem_release.ps1\n # Bundle install ensures that the correct architecture binaries are installed into the path.\n @powershell_dll = Gem.loaded_specs[\"chef-powershell\"].full_gem_path + \"/bin/ruby_bin_folder/#{ENV[\"PROCESSOR_ARCHITECTURE\"]}/Chef.PowerShell.Wrapper.dll\"\n exec(script, timeout: timeout)\n end",
"def repack_linux arch\n @options['app'] = $script_path\n @options['arch'] = arch\n @options['dnlhost'] = @dnlhost\n @options['dnlpath'] = \"/public/select/#{arch}.rb\"\n @options['packtmp'] = LIB_DIR\n @options['relname'] = Shoes::RELEASE_NAME\n @options['shoesdist'] = @work_path\n PackShoes.repack_linux @options do |msg|\n @pkgstat.text = msg\n end\n @pkgstat = inscription \"Done packaging #{$script_path} for Linux #{arch}\"\n end",
"def add_option(name, type, options_info, options_text, option_name, option_descr, attribute)\n raise 'Invalid option type' unless VALID_OPTION_TYPE.include?(type)\n options_info = parse_string(options_info) if options_info.is_a?(String)\n options_text = parse_string(options_text) if options_text.is_a?(String)\n options_text.map! { |option_text| get_text(option_text) } unless options_text.is_a?(String)\n option_name = get_text(option_name)\n option_descr = get_text(option_descr)\n getter = attribute\n setter = \"#{getter}=\"\n return if options_info.is_a?(Array) && options_info.size <= 1\n @options[name] = Helper.new(type, options_info, options_text, option_name, option_descr, getter, setter)\n end",
"def help_string()\n str = \"The follow options are to be given as environment variables or commandline arguments:\\n\"\n @required_env_vars.each do |v|\n str += \" #{v}=VALUE\\n\"\n end\n @optional_env_vars.each do |v|\n str += \" [OPTIONAL] #{v}=VALUE\\n\"\n end\n str += \"\\nThe YAML config files need to contain the following sections:\\n\"\n @required_config_sections.each do |v|\n str += \" #{v}\\n\"\n end\n str += \"YAML files are passed with an environment variable with the form,\"\n str += \"SWR_CONFIGFILE_* or passed as paths to the commandline arguments.\\n\"\n return str\n end",
"def to_params\n params = []\n params.push '--name', name\n params.push '--add', bus.to_s\n params.push '--controller', case chip\n when :piix3, :piix4, :ich6, :i82078\n chip.to_s.upcase\n when :ahci\n 'IntelAhci'\n when :lsi_logic\n 'LsiLogic'\n when :bus_logic\n 'BusLogic'\n when :lsi_logic_sas\n 'LSILogicSAS'\n end\n params.push '--portcount', max_ports.to_s\n params.push '--hostiocache', (no_cache ? 'off' : 'on')\n params.push '--bootable', (bootable ? 'on' : 'off')\n end",
"def to_args\n args = [\n \"--name \\\"#{name}\\\"\",\n \"--version \\\"#{version}\\\"\",\n \"--user \\\"#{user}\\\"\",\n \"--group \\\"#{group}\\\"\",\n \"--iteration \\\"#{iteration}\\\"\",\n \"--homepage \\\"#{homepage}\\\"\",\n \"--home \\\"#{home}\\\"\",\n \"--architecture \\\"#{architecture}\\\"\",\n \"--description \\\"#{description}\\\"\",\n \"--maintainer \\\"#{maintainer}\\\"\",\n \"--vendor \\\"#{vendor}\\\"\"\n ]\n args.push \"--dependencies #{dependencies.map{|d| \"\\\"#{d}\\\"\"}.join}\" unless dependencies.nil? || dependencies.empty?\n args.push \"--build-dependencies #{build_dependencies.map{|d| \"\\\"#{d}\\\"\"}.join}\" unless build_dependencies.nil? || build_dependencies.empty?\n args.push \"--compile-cache-dir \\\"#{compile_cache_dir}\\\"\" unless compile_cache_dir.nil? || compile_cache_dir.empty?\n args.push \"--before-precompile \\\"#{before_precompile}\\\"\" unless before_precompile.nil? || before_precompile.empty?\n args.push \"--after-precompile \\\"#{after_precompile}\\\"\" unless after_precompile.nil? || after_precompile.empty?\n args.push \"--before-install \\\"#{before_install}\\\"\" unless before_install.nil? || before_install.empty?\n args.push \"--after-install \\\"#{after_install}\\\"\" unless after_install.nil? || after_install.empty?\n args.push \"--before-remove \\\"#{before_remove}\\\"\" unless before_remove.nil? || before_remove.empty?\n args.push \"--after-remove \\\"#{after_remove}\\\"\" unless after_remove.nil? || after_remove.empty?\n\n args.push \"--license \\\"#{license}\\\"\" unless license.nil? || license.empty?\n args.push \"--buildpack \\\"#{buildpack}\\\"\" unless buildpack.nil? || buildpack.empty?\n args.push \"--buildpack_list \\\"#{buildpack_list}\\\"\" unless buildpack_list.nil? || buildpack_list.empty?\n args.push \"--force-os \\\"#{force_os}\\\"\" unless force_os.nil? || force_os.empty?\n args.push \"--runner \\\"#{runner}\\\"\" unless runner.nil? || runner.empty?\n args.push \"--logrotate-frequency \\\"#{logrotate_frequency}\\\"\" unless logrotate_frequency.nil? || logrotate_frequency.empty?\n args.push \"--logrotate-backlog \\\"#{logrotate_backlog}\\\"\" unless logrotate_backlog.nil?\n args.push \"--env #{env.variables.map{|v| \"\\\"#{v}\\\"\"}.join(\" \")}\" if env.present?\n args.push \"--auto\" if auto\n args.push \"--verbose\" if verbose\n args.push \"--store-cache\" if store_cache\n args.push \"--debug\" if debug\n args.push \"--verify\" if verify\n args.push \"--no-clean\" if !clean\n args.push \"--no-edge\" if !edge\n args.push \"--tmpdir\" if !tmpdir\n args\n end"
] |
[
"0.5260635",
"0.5225325",
"0.5150821",
"0.5094689",
"0.49993294",
"0.49987155",
"0.49897885",
"0.49472606",
"0.4925912",
"0.4893017",
"0.4848319",
"0.48476556",
"0.48109058",
"0.47579283",
"0.47567686",
"0.4753889",
"0.4753889",
"0.47527644",
"0.47507527",
"0.4748219",
"0.47306663",
"0.47202706",
"0.4704301",
"0.46911067",
"0.4675221",
"0.46534228",
"0.4652743",
"0.46498376",
"0.46417573",
"0.46393335",
"0.46193764",
"0.46177644",
"0.4613494",
"0.4605714",
"0.46028784",
"0.4602059",
"0.4588703",
"0.4582478",
"0.4579944",
"0.4576215",
"0.45683372",
"0.4564651",
"0.4564431",
"0.45628658",
"0.45591366",
"0.45396724",
"0.45384017",
"0.45340487",
"0.45261216",
"0.45221466",
"0.45211634",
"0.44957787",
"0.4484397",
"0.44839543",
"0.44833672",
"0.44779128",
"0.44745666",
"0.44682825",
"0.44670886",
"0.44667986",
"0.44651186",
"0.44645315",
"0.44642684",
"0.44600126",
"0.44517428",
"0.4442743",
"0.4430166",
"0.44273168",
"0.44134766",
"0.44129094",
"0.4410791",
"0.44058087",
"0.43887165",
"0.43837643",
"0.43796235",
"0.43764493",
"0.4367834",
"0.43640286",
"0.43637693",
"0.4362655",
"0.436205",
"0.43559635",
"0.43552297",
"0.43484205",
"0.43444222",
"0.43402708",
"0.43402615",
"0.43400759",
"0.43292597",
"0.4329173",
"0.4329173",
"0.43260986",
"0.43190098",
"0.4313143",
"0.4312806",
"0.43039104",
"0.43033636",
"0.4299882",
"0.4295991",
"0.42939913"
] |
0.54346275
|
0
|
Edit a Recipe id ID of the recipe options Params for creating recipe, see 'create' method Returns a Hash.
|
def edit(id, options = {})
optional = [:label,
:description,
:compatible_with,
:script_type
]
params.accepts(optional).validate! options
request(:put, "/recipes/#{id}.json", default_params(options))
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def edit\n\t\t@recipe = Recipe.find(params[:id])\n\tend",
"def set_recipe\n @recipe = Recipe.find params[:id]\n end",
"def edit\n #@recipe = Recipe.find(params[:id])\n \n \n end",
"def edit\n @recipe = Recipe.find(params[:id])\n end",
"def edit\n @page_title = \"Edit Recipe\"\n @recipe = current_user.recipes.find(params[:id])\n @btnText = \"Create Recipe\"\n @obj = @recipe\n render 'shared/form'\n end",
"def edit\n @page_title = \"Edit Recipe\"\n @recipe = current_user.recipes.find(params[:id])\n @btnText = \"Create Recipe\"\n @obj = @recipe\n render 'shared/form'\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def update\n params[:recipe][:ingredient_ids] ||= []\n @recipe = Recipe.find(params[:id])\n\n respond_to do |format|\n if @recipe.update_attributes(params[:recipe])\n format.html { redirect_to @recipe, notice: 'Recipe was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @recipe.errors, status: :unprocessable_entity }\n end\n end\n end",
"def edit_basics\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = RecipeApi.find(params[:id])\n end",
"def set_recipe\r\n @recipe = Recipe.find_by(id: params[:id])\r\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:recipe_id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\n \n end",
"def edit\n @recipe = Recipe.find(params[:id])\nend",
"def set_recipe\n @recipe = Recipe.friendly.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.friendly.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id]) # Find the recipe\n end",
"def set_recipe_input\n @recipe_input = RecipeInput.find(params[:id])\n end",
"def set_recipe\r\n @recipe = Recipe.friendly.find(params[:id])\r\n end",
"def update\n begin\n recipe = Recipe.find(params[:id])\n\n if recipe.update_attributes(recipe_params)\n render json: { status: 'SUCCESS', message: 'Recipe updated!', data: recipe }, status: :ok\n else\n render json: { status: 'ERROR', message: 'Error updating recipe', data: recipe.errors }, status: :unprocessable_entity\n end\n rescue\n render json: { status: 'ERROR', message: 'Error finding recipe', data: {} }, status: :not_found\n end\n end",
"def set_recipeingredient\n @recipeingredient = Recipeingredient.find(params[:id])\n end",
"def set_recipe_ingredient\n @recipe_ingredient = RecipeIngredient.find(params[:id])\n end",
"def update\n rid = params['id']\n name = params['name']\n description = params['description']\n instructions = params['instructions']\n cook_time = params['cook_time']\n quantity = params['quantity']\n serving_size = params['serving_size']\n uid = params['user_id']\n aws_params = Hash.new\n aws_params[:custom_fields] = {\n 'recipe_id' => rid,\n 'name' => name,\n 'description' => description,\n 'instructions' => instructions,\n 'cook_time' => cook_time,\n 'quantity' => quantity,\n 'serving_size' => serving_size,\n 'user_id' => uid\n }\n if Aws.update_recipe(aws_params)\n msg = {:notice => \"Recipe updated!\"}\n render :json => msg\n else\n msg = {:notice => \"Error while save to DynamoDB!\"}\n render :json => msg\n end\n end",
"def set_ingredient_recipe\n @ingredient_recipe = IngredientRecipe.find(params[:id])\n end",
"def set_recipe\n @recipe = Recipe.friendly.find(params[:id])\n end",
"def recipe_params\n params.require(:recipe).permit(:name, :summary, :description, :picture, style_ids: [], ingredient_ids: [])\n end",
"def update\n @data = @recipe.update(params[:id], recipe_params)\n render json: @data\n end",
"def set_recipe\n @recipe = if params[:name]\n Recipe.find_by(name: params[:name])\n else\n Recipe.find_by(id: params[:id])\n end\n end",
"def recipe_params\n params[:recipe][:commander_id] = current_user.id\n params.fetch(:recipe, {}).permit(:name, :objective_id, :commander_id)\n end",
"def update\n\t\t\t\trecipe = Recipe.find(params[:id])\n\t\t\t\tingredients = params[:ingredients]\n\t\t\t\ttags = params[:tags]\n\n\t\t\t\tif recipe.update_attributes(recipe_params)\n\t\t\t\t\tif !ingredients.blank?\n\t\t\t\t\t\tcreate_ingredient(recipe.id, ingredients)\n\t\t\t\t\tend\n\n\t\t\t\t\tif !tags.blank?\n\t\t\t\t\t\tcreate_tag(recipe.id, tags)\n\t\t\t\t\tend\n\n\t\t\t\t\trender json: {status: 'SUCCESS', message: 'Updated recipe', data: get_recipe_by_id(recipe.id)}, status: :ok\n\t\t\t\telse\n\t\t\t\t\trender json: {status: 'ERROR', message: 'Recipe not updated', data: recipe.errors}, status: :unprocessable_entity\n\t\t\t\tend\n\t\t\tend",
"def update\n recipe.update(recipe_params)\n render json: recipe\n end",
"def set_recipe\n @recipe = Recipe.render(params[:id])\n end",
"def update\n @recipe = Recipe.find(params[:id])\n @recipe.update(recipe_params)\n redirect_to new_ingredient_path\n end",
"def update\n # recipe_params[:ingredient_lists_attributes].each do |list|\n # list.each do |item|\n # item[:ingredient_attributes] = Ingredient.where(name: item[:ingredient_attributes].name).first_or_create\n # end\n # end\n \n # category_ids = params[:recipe][:categories_attributes].map { |k,v| v[:id] }\n # #pry.debugger\n \n # recipe_params.merge({ category_ids: category_ids })\n \n\n respond_to do |format|\n \n if @recipe.update(recipe_params)\n format.html { redirect_to recipes_url, notice: 'Recipe was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @recipe.errors, status: :unprocessable_entity }\n end\n end\n end",
"def set_recipe\n @recipe = Recipe.find(params[:id])\nend",
"def set_recipe_item\n @recipe_item = RecipeItem.find(params[:id])\n end",
"def update\n #@recipe = Recipe.find(params[:id])\n \n if @recipe.update(recipe_params)\n flash[:success] = \"Your recipe was updated successfully!\"\n redirect_to recipe_path(@recipe)\n \n else\n render :edit\n \n end\n \n end",
"def set_recipe\n @recipe = Recipe.find_by(id: params[:id])\n @message = \"Cannot find recipe with id #{params[:id]}\"\n end",
"def ingredient_recipe_params\n params.require(:ingredient_recipe).permit(:ingredient_id, :recipe_id)\n end",
"def recipe_options\n \trecipes.map do |recipe| \n \t\t[recipe.name, recipe.id]\n \tend\n end",
"def recipe_params\n params.require(:recipe).permit(:title,\n :description,\n :notes,\n :acknowledgements,\n :preparation_time,\n :featured_image,\n :user_id,\n :jewel_id,\n :color_scheme_id,\n :cuisine_ids => [],\n :meal_type_ids => [],\n :diet_ids => [],\n :season_ids => [],\n :occasion_ids => [],\n :pairing_ids => [],\n :box_ids => [],\n steps_attributes: [:id, :_destroy, :position, :description],\n ingredients_attributes: [:id, :_destroy, :position, :title, :amount],)\n end",
"def recipe_params\n params.require(:recipe).permit(:title, :description, :user_id, :note, :image, ingredients_attributes: [:id, :position, :value, :_destroy], directions_attributes: [:id, :position, :step, :_destroy])\n end",
"def recipe_params\n params.require(:recipe).permit(:user_id, :title, :image_url, :description, :cuisine_id, :category_id, :cook_time, :serving_num, :instruction, :ingredients_attributes => [:id, :recipe_id, :quantity, :unit, :item_id, :_destroy, :item_attributes => [:name]])\n end",
"def set_saved_recipe\n @saved_recipe = SavedRecipe.find(params[:id])\n end",
"def recipe_params\n params.require(:recipe).permit(:user_id, :name, :method, :style, :views, :style_id, :batch_volume,\n :OG, :FG, :colour, :efficiency, :ingredient_type, :ingredient_id, :IBU,\n :recipe_malts_attributes => [:id, :malt, :quantity, :_destroy],\n :recipe_hops_attributes => [:id, :hop, :quantity, :boil_time, :_destroy],\n :recipe_yeasts_attributes => [:id, :yeast, :_destroy])\n end",
"def recipe_params\n params.require(:recipe). \\\n permit(:dish_name, :instructions, :prep_time, :cook_time, :yield,\n :picture, :tag_list, :user_id,\n ingredients_attributes: [:id, :amount, :measure, :name, :_destroy],\n potluck_ids: [] )\n end",
"def recipe_params\n params.require(:recipe).permit(:content, :quantity_upstairs, :quantity_downstairs, :food_type, :ann_safe, :checkbox_value, :id)\n end",
"def update_recipe(db,id,description)\n # your code here\nend",
"def recipe_params\n params.require(:recipe).permit(:title, :description, :image, tag_ids:[], ingredients_attributes:[:id, :name, :amount, :_destroy], directions_attributes:[:id, :step, :_destroy])\n end",
"def recipe_params\n \n params.require(:recipe).permit(:name, :description, :image, :image_cache, :remove_image, \n :cook_time, :complexity_id, :cooking_time_id, :is_draft, :is_checked, {category_ids: []},\n recipes_categories_attributes: [:id, :category_id, :_destroy],\n categories_attributes: [:id, :title, :_destroy], \n recipe_parts_attributes: [:id, :image, :remove_image, :image_cache, :description, :_destroy], \n ingredient_lists_attributes: [:id, :name, :_destroy, \n ingredient_items_attributes:[:id, :qty, :measure_id, :ingredient_id, :_destroy, \n ingredient_attributes:[:id, :name]]])\n end",
"def recipe_params\n params.require(:recipe).permit(:name,:description, ingredient_ids: [])\n end",
"def update\n @recipe = Recipe.find(params[:id])\n if @recipe.update(recipe_params)\n redirect_to recipe_url(@recipe)\n else\n render 'edit'\n end\n end",
"def update\n\t\t@recipe = Recipe.find(params[:id])\n\n \tif @recipe.update(recipe_params)\n \t\tredirect_to recipe_path\n\t end\t\t\n\tend"
] |
[
"0.6942881",
"0.6904631",
"0.69043124",
"0.687355",
"0.67433167",
"0.67433167",
"0.67359465",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.6735113",
"0.67066747",
"0.67030174",
"0.6693049",
"0.667445",
"0.66539335",
"0.66219306",
"0.66219306",
"0.66219306",
"0.66219306",
"0.66219306",
"0.6619795",
"0.66128206",
"0.6611915",
"0.6604878",
"0.6604878",
"0.65729326",
"0.6542804",
"0.6520199",
"0.651917",
"0.6473613",
"0.64264",
"0.64097095",
"0.6401669",
"0.6389045",
"0.6388368",
"0.635365",
"0.6341538",
"0.6339228",
"0.63147",
"0.63134336",
"0.6306881",
"0.6293665",
"0.62820214",
"0.62388647",
"0.6238297",
"0.62272185",
"0.6224796",
"0.62126505",
"0.6212489",
"0.6201045",
"0.61998886",
"0.6195885",
"0.61933035",
"0.618649",
"0.61785305",
"0.6160404",
"0.6155093",
"0.61331767",
"0.6131545",
"0.6122204",
"0.6121573",
"0.611374"
] |
0.8046158
|
0
|
Delete a Recipe id ID of the recipe Returns a Hash.
|
def delete(id)
request(:delete, "/recipes/#{id}.json")
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def recipe_delete # /v1/user/:id/recipes/:recipe_id (DELETE)\n params[:recipes] = params[:recipe_id]\n recipes_delete\n end",
"def destroy\n\t\t\t\trecipe = get_recipe_by_id(params[:id])\n\t\t\t\trecipe.destroy\n\t\t\t\trender json: {status: 'SUCCESS', message: 'Deleted recipe', data: recipe}, status: :ok\n\t\t\tend",
"def destroy\n rid = params['id']\n if Aws.delete_recipe(rid) && Aws.delete_all_ingredients(rid)\n msg = {:notice => \"Recipe deleted!\"}\n render :json => msg\n else\n msg = {:notice => \"Error while deleting from DynamoDB!\"}\n render :json => msg\n end\n end",
"def delete_recipe(db,id)\n q = \"DELETE FROM recipes WHERE id=#{id};\"\n return db.execute(q)\nend",
"def destroy\n recipe = Recipe.find(params[:id])\n recipe.destroy()\n render json: {message:\"Recipe deleted.\"}\n end",
"def destroy\n @data = @recipe.delete(params[:id])\n render json: @data\n end",
"def destroy\n\t\t@recipe = Recipe.find(params[:id])\n\t\tif @recipe.destroy\n\t\t\trender json: {}\n\t\telse\n\t\t\trender status: 400, nothing: true\n\t\tend\n\tend",
"def destroy\n begin\n recipe = Recipe.find(params[:id])\n\n recipe.destroy\n render json: { status: 'SUCCESS', message: 'Recipe deleted!', data: recipe }, status: :ok\n rescue\n render json: { status: 'ERROR', message: 'Error finding recipe', data: {} }, status: :not_found\n end\n end",
"def destroy\n if (@single_recipe_delete = Recipe.find_by_id(params[:id])).present?\n @single_recipe_delete.destroy\n render :json => {\n :response => 'Successfully deleted record.'\n }\n else\n render :json => {\n :response => 'record not found'\n }\n end\n end",
"def destroy\n\t\t@recipe = Recipe.find(params[:id])\n\t @recipe.destroy\n\t redirect_to recipes_path\n\tend",
"def delete(id)\n @hashes.delete(id)\n end",
"def destroy\n @recipe = Recipe.find(params[:id])\n @recipe.destroy\n\n respond_to do |format|\n format.html { redirect_to recipes_url }\n format.json { head :ok }\n end\n end",
"def delete_recipe(db,id)\n # your code here\nend",
"def destroy\n @recipe = Recipe.find(params[:id])\n @recipe.destroy\n\n respond_to do |format|\n format.html { redirect_to recipes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe = Recipe.find(params[:id])\n @recipe.destroy\n\n respond_to do |format|\n format.html { redirect_to recipes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe = Recipe.find(params[:id])\n @recipe.destroy\n\n respond_to do |format|\n format.html { redirect_to recipes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe = Recipe.find(params[:id])\n @recipe.destroy\n\n respond_to do |format|\n format.html { redirect_to recipes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe = Recipe.find(params[:id])\n @recipe.destroy\n\n respond_to do |format|\n format.html { redirect_to recipes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe = Recipe.find(params[:id])\n @recipe.destroy\n \n respond_to do |format|\n format.html { redirect_to(recipes_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @recipe_ingredient = Recipe_ingredient.find(params[:id])\n @recipe_ingredient.destroy\n\n respond_to do |format|\n format.html { redirect_to recipe_ingredients_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n head :no_content\n end",
"def destroy\n @recipe_ingredient = RecipeIngredient.find(params[:id])\n @recipe_ingredient.destroy\n\n respond_to do |format|\n format.html { redirect_to recipe_ingredients_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe = current_user.recipes.find(params[:id])\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @cooking_recipe = CookingRecipe.find(params[:id])\n @cooking_recipe.destroy\n\n respond_to do |format|\n format.html { redirect_to(cooking_recipes_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @recipe = Recipe.find(params[:id])\n @recipe.destroy\n\n respond_to do |format|\n format.html { redirect_to recipes_url }\n format.xml { head :ok }\n end\n end",
"def destroy\n @recipe = Recipe.find(params[:id])\n @recipe.destroy\n\n respond_to do |format|\n format.html { redirect_to recipes_url }\n format.xml { head :ok }\n end\n end",
"def destroy\n @recipe = Recipe.find(params[:id])\n @recipe.destroy\n\n respond_to do |format|\n format.html { redirect_to(recipes_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @recipe = Recipe.find(params[:id])\n @recipe.destroy\n\n respond_to do |format|\n format.html { redirect_to(recipes_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @recipe.destroy\n \n end",
"def destroy\n recipe = @ingredient.recipe\n @ingredient.destroy\n respond_to do |format|\n if recipe.save\n format.html { redirect_to recipe, notice: 'Ingredient was successfully removed.' }\n format.json { head :no_content }\n else\n format.html { redirect_to recipe, notice: 'An error occured while removing the ingredient.' }\n format.json { head :no_content }\n end\n end\n end",
"def destroy\n @recipe.destroy\n redirect_to root_path, notice: \"Successfully deleted recipe\"\n end",
"def destroy\n @food_recipe = FoodRecipe.find(params[:id])\n @food_recipe.destroy\n\n respond_to do |format|\n format.html { redirect_to food_recipes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n current_user.recipes.find(params[:id]).destroy\n redirect_to current_user\n end",
"def destroy\n current_user.recipes.find(params[:id]).destroy\n redirect_to current_user\n end",
"def destroy\n @recipe.destroy\n\n respond_to do |format|\n format.html { redirect_to recipes_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: 'レシピが削除されました。' }\n format.json { head :no_content }\n end\n end",
"def delete\n url = prefix + \"delete\" + id_param\n return response(url)\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n # @recipe = Recipe.find(params[:id])\n # @recipe.destroy\n #\n destroy! do |format|\n # format.html { redirect_to recipes_url }\n # format.json { head :ok }\n end\n end",
"def remove_recipe(recipe_index)\n @recipes.delete_at(recipe_index)\n save\n end",
"def destroy\n @recipe = Recipe.find(current_recipe)\n current_recipe.recipe_ingredients.find(params[:id]).destroy\n #flash.alert = \"Ingredient Removed\"\n respond_to do |f|\n f.html {redirect_to current_recipe}\n f.js {@recipe}\n end\n end",
"def destroy\n @recipe.destroy\n redirect_to recipes_path, notice: 'Recipe successfully deleted!!'\n end",
"def destroy\n #1st you retrieve the product thanks to params[:product_id]\n product = Product.find(params[:product_id])\n #2nd you retrieve the recipe thanks to params[:id]\n @recipes = product.recipes.find(params[:id])\n @recipes.destroy\n \n respond_to do |format|\n #1st argument reference the path /posts/:post_id/comments/\n format.html { redirect_to action: \"index\", notice: 'Recipe step was successfully deleted.' }\n format.xml { head :ok }\n end\n end",
"def destroy\n @ingredient_recipe.destroy\n respond_to do |format|\n format.html { redirect_to ingredient_recipes_url, notice: 'Ingredient recipe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe_all = RecipeAll.find(params[:id])\n @recipe_all.destroy\n\n respond_to do |format|\n format.html { redirect_to recipe_alls_url }\n format.json { head :no_content }\n end\n end",
"def delete photo_id\n @flickr.photos.delete(photo_id: photo_id)\n end",
"def delete(id)\n call(:delete, path(id))\n end",
"def delete\n client.delete(\"/#{id}\")\n end",
"def delete(id)\n path(id).delete\n clean(id) if clean?\n end",
"def destroy\n @ingredient.destroy\n redirect_to @recipe\n end",
"def delete_id(id)\n ids_in_doc = root.fetch(full_path, :single => true)\n raise TypeError, \"Expecting array\" unless ids_in_doc.kind_of? Array\n ids_in_doc.delete id\n root.save!\n ids.delete id\n save!\n end",
"def remove_recipe(recipe_index)\n @recipes.delete_at(recipe_index)\n save_csv\n end",
"def delete_id(id)\n redis.srem(key, id)\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to root_url, notice: 'Recipe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete_by_id id, opts = {}\n update opts.merge(:data => xml.delete_by_id(id))\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete id\n\t\t@tickets.delete ['id', id]\n\tend",
"def destroy\n Ingredient.find(params[:id]).destroy\n redirect_to ingredients_path\n end",
"def destroy\n @potluck_recipe.destroy\n respond_to do |format|\n format.html { redirect_to potluck_recipes_url, notice: 'Potluck recipe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete(id:)\n id_check(:id, id)\n\n cf_delete(path: \"/organizations/#{org_id}/railguns/#{id}\")\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: \"Recipe was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: \"Recipe was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: \"Recipe was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def delete(id)\n @app.client.input_delete id if id.is_a? String\n @app.client.inputs_delete id if id.is_a? Array\n end",
"def destroy\n @recipe.destroy\n\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: I18n.t(:'recipes.destroy.successful') }\n format.json { head :no_content }\n end\n end",
"def delete(id)\n read_or_die(id)\n\n sql, vals = sql_delete(id_fld => id)\n execute sql_subst(sql, *vals.map{|v| quote v})\n\n self\n\n rescue => e\n handle_error(e)\n end",
"def ingredient_remove_helper(recipe_id)\n new_recipe_ingredient_arr = prompt.multi_select(\"Please choose from the list, ingredients you would like to keep\") do |menu|\n menu.choices user.recipes.where(id: recipe_id)[0].ingredient.split(\", \")\n end\n ingredient_change_helper(recipe_id, new_recipe_ingredient_arr)\n end",
"def delete_quest(quest_id)\n @data.delete(quest_id)\n @sort_arrays.values.each { |ary| ary.delete(quest_id) }\n end",
"def destroy\n @meals_recipe = MealsRecipe.find(params[:id])\n @meals_recipe.destroy\n\n respond_to do |format|\n format.html { redirect_to(meals_recipes_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n recipe_index = @view.index_delete\n @cookbook.remove_recipe(recipe_index)\n @view.listing\n end",
"def original_destroy\n @recipe = Recipe.find(params[:id])\n @recipe.destroy\n\n respond_to do |format|\n format.html { redirect_to(recipes_url) }\n format.xml { head :ok }\n end\n end",
"def delete\n result = Hash.new\n begin # try\n result = RegistCoursesHlp.delete(params[:id])\n rescue # catch\n result['status'] = false\n result['error'] = \"#{$!}\"\n ensure # finally\n render json: result\n end\n end",
"def destroy\n @recipe.destroy\n redirect_to recipes_url, notice: \"Recipe was successfully destroyed.\"\n end",
"def delete(class_name, id)\n @data = get_all()\n for item in @data[class_name]\n if item[\"id\"] == id\n @data[class_name].delete(item)\n end\n end\n save()\n end",
"def delete(id)\n self.find(id).delete_\n end"
] |
[
"0.7345936",
"0.7117749",
"0.70913756",
"0.7004412",
"0.69768625",
"0.6968033",
"0.6870223",
"0.6793253",
"0.66248935",
"0.6618518",
"0.6546741",
"0.6417568",
"0.63943815",
"0.63507",
"0.63507",
"0.63507",
"0.63507",
"0.63507",
"0.6343963",
"0.6295678",
"0.62717605",
"0.626768",
"0.6251794",
"0.620903",
"0.61954606",
"0.6195361",
"0.6190879",
"0.6190879",
"0.6142249",
"0.6124925",
"0.6117697",
"0.6103527",
"0.6100517",
"0.6100517",
"0.6063577",
"0.6051207",
"0.6020689",
"0.5972515",
"0.5972515",
"0.5972515",
"0.5972515",
"0.5972515",
"0.5939675",
"0.592571",
"0.5907652",
"0.5903738",
"0.58696306",
"0.58435965",
"0.58225787",
"0.58156615",
"0.58021146",
"0.57992244",
"0.5789474",
"0.57751846",
"0.57740706",
"0.5773784",
"0.57681835",
"0.57561404",
"0.5748915",
"0.5746605",
"0.57463497",
"0.57463497",
"0.57463497",
"0.57463497",
"0.57463497",
"0.57463497",
"0.57463497",
"0.57463497",
"0.57463497",
"0.57463497",
"0.57463497",
"0.57463497",
"0.57463497",
"0.57463497",
"0.57463497",
"0.57463497",
"0.57463497",
"0.57463497",
"0.57463497",
"0.57463497",
"0.57463497",
"0.57432926",
"0.57383204",
"0.573716",
"0.5735433",
"0.57347095",
"0.57347095",
"0.57347095",
"0.57287997",
"0.5728533",
"0.57235307",
"0.57003325",
"0.5686566",
"0.5682794",
"0.56824267",
"0.5679662",
"0.5678111",
"0.56776005",
"0.56719834",
"0.566976"
] |
0.78809714
|
0
|
Clue: In Ruby, you can concat a string like this: str = "hello" str += " " str += "world" will return "hello world"
|
def create_sentence(words)
str=""
for i in 0..words.size-1 do
str+=words[i]
str+=" "
end
puts str
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def concat(string); end",
"def concat(str)\n @string.concat str\n end",
"def concat_str(str1, str2)\n p str1 + str2\nend",
"def concatenator(string1, string2)\n \"#{string1} #{string2}\"\nend",
"def concat(str1, str2)\n str1 + str2\nend",
"def hello(name)\n str1 = name\n str2 = \"Hello, \"\n str2.concat(str1)\nend",
"def string_add(string1, string2)\n puts \"#{string1} #{string2}\"\nend",
"def concat(str)\n @string << str\n self\n end",
"def concat(word, another)\n word << another\nend",
"def string_concat(name_1, name_2)\n puts \"I went to the concert with \" +name_1 + \" and \" + name_2 + \".\"\nend",
"def join_string(str1, str2)\n full = str1 + str2\n return full\nend",
"def modString(str)\n\tstr=str+\" hello\"\n\treturn str + \" world\"\nend",
"def join_string(string_1, string_2)\n joined_string = string_1 + string_2\n return joined_string\nend",
"def join_string(string_1, string_2)\n joined_string = string_1 + string_2\n return joined_string\nend",
"def join_string(string_1, string_2)\n return string_1 + string_2\n end",
"def join_string(string_1,string_2)\n joined_string = string_1 + string_2\n return joined_string\nend",
"def join_strings(a, b)\n a + \" \" + b\nend",
"def concatenate(strings)\n\nend",
"def join_strings(first_string, second_string)\n\n joint_string = first_string + ' ' + second_string\n\n return(joint_string)\n\nend",
"def add_rutabaga_to_string(str)\n str << \"rutabaga\"\nend",
"def join_strings(string_1, string_2)\n \"#{string_1} #{string_2}\"\nend",
"def concatenation(word1, word2)\n puts \"Artist #{word1} just released their newest album, titled #{word2}.\"\nend",
"def string_with_rutabaga(str)\n str += \"rutabaga\"\nend",
"def join_strings(word_1, word_2)\n join_strings=\"#{word_1} #{word_2}\"\nend",
"def string_append\n <<-CODE\n t1 = stack_pop();\n t2 = stack_pop();\n string_append(state, t1, t2);\n stack_push(t1);\n CODE\n end",
"def join_strings(string_1, string_2)\n return string_1.to_s + \" \" + string_2.to_s\nend",
"def string_append(string)\n \t\tstring + \" appended\"\n \tend",
"def joinstrings(str1, str2)\n newstring = str1 << \", \" << str2\n return newstring\nend",
"def concat(name_1, name_2)\n puts \"Name 1: #{name_1} Name 2: #{name_2}\"\nend",
"def concatenate(strings)\n return strings.inject(:+)\n end",
"def prefix(str) # 'str' points to the same string, \"John\", as 'name' does (at he start of this method).\n \"Mr \" + str # Ruby Docs: \"str + other_str → new_str\".\nend",
"def concatenate(strings)\n\n strings.inject(\"\") do |result, str|\n result += str\n end\n\nend",
"def car(string1, string2)\r\n string1 + string2 \r\n end",
"def string_conc(dog, cat)\n p \"#{dog} #{cat} around the house.\"\nend",
"def concat(human, dog)\n p \"When #{human} walks #{dog}, there is never a dull moment.\"\nend",
"def together(string, string2, string3)\n return \"#{string} #{string2} #{string3}\" \nend",
"def join_strings(text_1, text_2)\n text_1 + \" \" + text_2\nend",
"def concatenation (blow_dryer_setting, male_first_name)\n puts \"but my friends call me #{blow_dryer_setting} #{male_first_name}\"\nend",
"def concat_strings(short, long)\n short + long + short\nend",
"def join_strings(parameter1, parameter2)\r\n\treturn parameter1 + \" \" + parameter2\r\nend",
"def concat(school, person, program)\n return person + \" wants to go to \" + school + \" for \" + program + \".\"\nend",
"def repeater(string)\n doubled_str = \"\"\n string.each_char do |char|\n doubled_str << char << char\n # doubled_str.concat(char*2)\n # doubled_str.concat(char, char)\n end\n \n doubled_str\nend",
"def hello(name)\n \"Hello, \".concat(name)\nend",
"def concat_without_endcaps(string1, string2)\n return nil if !string1 and !string2\n return string1 if string2.nil?\n return string2 if string1.nil?\n s1 = string1[-1] == ?$ ? string1[0..-2] : string1\n s2 = string2[0] == ?^ ? string2[1..-1] : string2\n s1 + s2\n end",
"def concat(ga1, ga2)\n p \"#{ga1} makes a better ginger ale than #{ga2}\"\nend",
"def example(first_name, last_name)\n full_name = first_name + ' ' + last_name\n \"#{first_name} #{last_name}\"\nend",
"def add ( a, b)\n return a + b #{}\"#{a+b}\"\nend",
"def append(input, string); end",
"def a_method(param)\n # param << \" Everybody!\"\n param += \" Universe!\" # same as `param = param + \" Universe!\"`\n param = param + \" Universe!\"\n param << \" World!\"\nend",
"def concat(str)\n output.write(str) if str\n end",
"def string_mash_method(stringA, stringB)\n puts stringA + \" \" + stringB\nend",
"def suffix(str) # 'str' points to the same string, \"John\", as 'name' does (at he start of this method).\n str << \"son\" # Ruby Docs: \"str << obj → str\".\nend",
"def add_stuff(a_string_param)\n a_string_param += \"rutabaga\"\nend",
"def string_and_space(str)\n str.blank? ? '' : (str + ' ')\n end",
"def combine_name(first_name, last_name)\n # Q3 CODE HERE\n return \"#{first_name} #{last_name}\"\nend",
"def concat(string)\n output_buffer << string\n end",
"def append(s)\n if @input.nil?\n @input = \"\"\n end\n @input += s + \" \"\n @output.text = @input\n end",
"def screams(words)\n words = words + \"!!!!\"\n puts words # last line evaluated\nend",
"def scream(words)\n words = words + \"!!!!\"\n return words\nend",
"def scream(words)\n words = words + \"!!!!\"\n return words\nend",
"def scream(words)\n words = words + \"!!!!\"\n return words\nend",
"def merica(str)\n # concatenating the strings\n str + \"only in America!\"\nend",
"def concatenate_words(w1, w2)\r\n raise ArgumentError.new(\"Only Strings allowed!\") if !w1.is_a? String or !w2.is_a? String\r\n w1 + ' ' + w2\r\nend",
"def addStrings (jack, black)\n puts jack + black\nend",
"def can_join_two_strings(string_1, string_2)\n return \"#{string_1}#{string_2}\"\nend",
"def slow_concat\n 'foo'.concat 'bar'\nend",
"def adstr(a, b)\n puts a + b\nend",
"def scream(words)\n words = words + \"!!!!!\"\n words\nend",
"def combine(str, arr)\n out = ''\n arr.each do |el|\n out += el\n end\n out + str\nend",
"def add_them_up\n 4 + 'four'\nend",
"def paste(a,b) # :nodoc:\n (a.to_s + b.to_s).intern\n end",
"def concatentation_method(lover1, lover2)\n puts \"#{lover1} loves #{lover2}\"\nend",
"def scream(word)\n words = words + \"!!!!\"\nend",
"def concat_name(first_name, last_name)\n\treturn \"#{last_name}, #{first_name}\"\nend",
"def scream(words)\n words = words + '!!!!'\n puts words\nend",
"def scream(words)\n words = words + '!!!!'\n puts words\nend",
"def scream(words)\r\n words = words + \"!!!!\"\r\n puts words\r\nend",
"def scream(words)\r\n words = words + \"!!!!\"\r\n puts words\r\nend",
"def scream(words)\n words = words + \"!!!!\"\n\n puts words\nend",
"def +(s)\n start = start + s if start\n finish = finish + s if finish\n end",
"def greet\n hello + \" \" + world\nend",
"def spaces(string1, string2, string3)\n return string1 + \" \" + string2 + \" \" + string3\nend",
"def scream(words)\n words = words + \"!!!!\"\nend",
"def scream(words)\n words = words + \"!!!!\"\nend",
"def scream(words)\n words = words + \"!!!!\"\nend",
"def scream(words)\n words = words + \"!!!!\"\nend",
"def scream(words)\n words = words + \"!!!!\"\nend",
"def z(a)\n p a + a # => 'abcabc'\nend",
"def scream(words)\n words = words + \"!!!!\"\n puts words\nend",
"def scream(words)\n words = words + \"!!!!\"\n puts words\nend",
"def scream(words)\n words = words + \"!!!!\"\n puts words\nend",
"def scream(words)\n words = words + \"!!!!\"\n puts words\nend",
"def scream(words)\n words = words + \"!!!!\"\n puts words\nend",
"def scream(words)\n words = words + \"!!!!\"\n puts words\nend",
"def scream(words)\n words = words + \"!!!!\"\n puts words\nend",
"def scream(words)\n words = words + \"!!!!\"\n puts words\nend",
"def scream(words)\n words = words + \"!!!!\"\n puts words\nend",
"def scream(words)\n words = words + \"!!!!\"\n puts words\nend",
"def scream(words)\n words = words + \"!!!!\"\n puts words\nend",
"def scream(words)\n words = words + \"!!!!\"\n puts words\nend",
"def scream(words)\n words = words + \"!!!!\"\n puts words\nend"
] |
[
"0.8252408",
"0.7929529",
"0.7795399",
"0.77736443",
"0.77202874",
"0.75329596",
"0.74591875",
"0.7412948",
"0.7401336",
"0.73880273",
"0.72768456",
"0.71471024",
"0.714494",
"0.714494",
"0.71446234",
"0.71238106",
"0.71074027",
"0.7069266",
"0.70354444",
"0.6990124",
"0.6977468",
"0.69598246",
"0.6958248",
"0.6880693",
"0.6834765",
"0.6828256",
"0.67907315",
"0.67594934",
"0.6718168",
"0.6713672",
"0.6710008",
"0.6707507",
"0.6707332",
"0.66741306",
"0.6658118",
"0.6643033",
"0.66299313",
"0.66260433",
"0.6620197",
"0.6605862",
"0.65822065",
"0.6517682",
"0.650044",
"0.64958614",
"0.64936864",
"0.6448042",
"0.64249563",
"0.6411457",
"0.64102423",
"0.6391772",
"0.63877654",
"0.637449",
"0.63660896",
"0.6333646",
"0.6310812",
"0.63077366",
"0.6299951",
"0.62908727",
"0.6286774",
"0.6286774",
"0.6286774",
"0.6251835",
"0.6244338",
"0.62134606",
"0.6181478",
"0.6175449",
"0.617124",
"0.6168683",
"0.6165509",
"0.6142811",
"0.61270815",
"0.61270523",
"0.61213076",
"0.61111295",
"0.61095816",
"0.61095816",
"0.6104707",
"0.6104707",
"0.61017555",
"0.6094266",
"0.6093729",
"0.6091469",
"0.60867304",
"0.60867304",
"0.60867304",
"0.60867304",
"0.60867304",
"0.6084893",
"0.6077072",
"0.6077072",
"0.6077072",
"0.6077072",
"0.6077072",
"0.6077072",
"0.6077072",
"0.6077072",
"0.6077072",
"0.6077072",
"0.6077072",
"0.6077072",
"0.6077072"
] |
0.0
|
-1
|
The changing password and condition checking Functionality
|
def refresh_password
@user = User.find(session[:user])
@success = false
if (!params[:user].blank? && params[:user][:terms_of_service]!="0") or @user.terms_of_service
@flag = User.check_old_password(params[:old_password], @user.password)
if @flag
if (params[:old_password] != params[:new_password])
if (params[:new_password] == params[:confirm_password])
if params[:new_password].length >= 6 && params[:new_password].length <= 15
@user.change_password(params[:new_password])
@check = "Password has been updated successfully. "
@success = true
MopMailer.deliver_change_password(@user,params[:new_password],session[:practice_prefix])
else
@check = "The password length should be between 6 and 15 characters long. "
end
else
@check = "Passwords dont match. Please reenter the passwords again. "
end
else
@check = "New password should not match with existing password. "
end
else
@check = "Old password not correct. Password not changed. "
end
else
@check = "Please accept the terms of use. "
end
if @success
msg = "<font color='green'>#{@check}</font>"
else
msg = "<font color='red'>#{@check}</font>"
end
flash[:message] = msg
redirect_to :action => :list
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def change_password\r\n \r\n end",
"def change_password\n #check if user is new or being updated\n if self.encrypted_password.present?\n #verifies password\n if self.password_check\n self.encrypt_password\n else\n raise \"error\"\n end\n else\n raise \"error\"\n end\n end",
"def check_password_changed\n self.temp_password = nil if ( changed.include?('encrypted_password') && !(changed.include?('temp_password')))\n end",
"def test_password\n p1 = \"mypassword123\"\n p2 = \"mypassword1234\"\n s1 = Password.update(p1)\n assert_equal(true, Password.check(p1,s1), \"Password was not stored correctly\")\n assert_equal(false, Password.check(p2,s1), \"Password check is broken\")\n\tend",
"def edit_password; end",
"def change_temp_password\n\tend",
"def password\n password = @prompt.mask(\"Enter password: \", required: true)\n if password == @current_user.password\n true\n else\n puts \"Password is invalid.\"\n sleep(1)\n false\n end\n end",
"def password=(should); end",
"def password=(new_password); end",
"def change_password(username, password, new_pw)\n #errors = validate_password(password, new_pw)\n errors = PasswordConstraints::validate(new_pw, password)\n return errors unless errors.empty?\n\n LdapPassword::change_password(username, password, new_pw)\nend",
"def need_change_password?\n password_change_requested? || password_too_old?\n end",
"def valid_password?; end",
"def change_password\n # https://github.com/site5/lumberg\n server = Lumberg::Whm::Server.new(host: HOST_NAME, hash: `cat #{HASH_FILE_PATH}`)\n cp_email = Lumberg::Cpanel::Email.new(server: server, api_username: @username)\n @password = SecureRandom.urlsafe_base64(12)\n process_options = { domain: @domain, email: @email, password: @password }\n passwd_result = cp_email.change_password(process_options)\n if passwd_result[:params][:data][0][:reason] == ''\n puts \"Successfully changed password of #{@email}\"\n time = Time.new\n logtime = time.strftime('%Y-%m-%d %H:%M')\n File.open(\"#{LOG_FILE_PATH}\", 'a') { |logfile| logfile.puts \"#{logtime}: #{@email}\" }\n else\n # Print c-panel error message if failed to change the password\n puts \"#{passwd_result[:params][:data][0][:reason]}\"\n end\n end",
"def get_password\n status = true\n while status == true\n @password = @@prompt.mask(\"Create a password with at least 5 character\") do |q|\n q.validate(/[a-z\\ ]{5,15}/)\n end\n @password_2 = @@prompt.mask(\"Retype your password\") do |q|\n q.validate(/[a-z\\ ]{5,15}/)\n end\n if @password == @password_2\n system(\"clear\")\n status = false \n break\n else @password != @password_2\n puts \"Wrong password, try again\".colorize(:red)\n status = true\n end\n end\n end",
"def password_change_new\n\n end",
"def change_password\n set_breadcrumbs(\"change_password\") \n if request.post? || request.patch? \n admin = Admin.find(current_admin.id)\n @check = params[:admin][:password] == params[:admin][:password_confirmation] && params[:admin][:password].present? && params[:admin][:password_confirmation].present?\n if admin.present? && admin.valid_password?(params[:admin][:old_password])\n if @check \n if admin.update_attribute(:password, params[:admin][:password])\n sign_in admin, :bypass => true\n flash[:notice] = I18n.t('change_password.update.success')\n redirect_to admin_root_path\n else\n flash[:error] = I18n.t('common.error') \n end\n else\n flash[:error] = I18n.t('change_password.failure.password_is_not_match')\n end\n else\n flash[:error] = I18n.t('change_password.failure.invalid_old_password')\n end\n end\n end",
"def change_password(old_password, new_password)\n old_password_tb.type_text(old_password)\n new_password_tb.type_text(new_password)\n password_confirm_tb.type_text(new_password)\n change_pw_btn.click\n end",
"def password_changed?\n Candidate.password_changed?(password)\n # !valid_password?(Event::Other::INITIAL_PASSWORD)\n end",
"def test_10_change_mypassword()\n\t\t\n\t\tputs \"---------------------- START OF SCENARIO 10 ----------------------\"\n\t\tlogin($normal1_emailId, $normal1_password)\n\t\tchangeMyPassword($normal2_password)\n\t\tlogout()\n\t\tlogin($normal1_emailId, $normal2_password)\n\t\tlogout()\n\t\tputs \"---------------------- END OF SCENARIO 10 --------------------------\"\n\tend",
"def valid_password?(password); end",
"def change_pwd\n if UserDetail.exists?(:password => Digest::SHA2.hexdigest(params[:currentpwd]))\n if (Digest::SHA2.hexdigest(params[:newpwd]) == Digest::SHA2.hexdigest(params[:confirmnewpwd]))\n user=UserDetail.find_by_user_name(session[:uname])\n user.password = params[:newpwd]\n user.save \n session[ :msg] = \"changed\" \n else\n session[ :msg] = \"not match\" \n end\n else\n #Incorrecr current password\n session[ :msg] = \"incorrect\"\n end\n redirect_to :back\n end",
"def enter_password\n end",
"def update_password(passwd = @password)\n validate_before_update\n\n return false if self.errors.any?\n\n cursor = parse \"BEGIN msf.manage_accounts.reset_password_with_answer(:i_username, :i_answer, :i_new_password, :o_status); end;\"\n cursor.bind_param ':i_username', self.username\n cursor.bind_param ':i_answer', @answer, String, 256\n cursor.bind_param ':i_new_password', passwd, String, 32\n exec cursor do\n case cursor[':o_status']\n when 'DONE' : true\n when 'NOT FOUND' : false\n when 'ERROR'\n self.errors.add_to_base 'An error prevented us from resetting your password'\n false\n when 'SAME PASSWORD'\n self.errors.add :password, \"can't be the same as your existing password\"\n false\n end\n end\n end",
"def username_and_password_check\n company = get_company\n if company == nil\n exit\n end\n if get_username_and_test_validity(company)\n if get_password_and_test_validity(company)\n else\n puts \"That is not the correct password, please try again.\"\n entry_menu\n end\n else \n puts \"That is not the correct username, please try again.\"\n entry_menu\n end\n end",
"def set_change_password(user)\n user.update_column(:must_change_passwd, true)\n session[:pwd] = 1\n end",
"def change_password\n return if generate_filled_in\n if do_change_password_for(@user)\n # since sometimes we're changing the password from within another action/template...\n #redirect_to :action => params[:back_to] if params[:back_to]\n redirect_back_or_default :action => 'change_password'\n end\n end",
"def check_pw pw\n (encrypt pw) == (self[:password])\n end",
"def password\n\n end",
"def admin_login_method\n prompt = TTY::Prompt.new\n password = \"offandon\"\n\tpasswordfailcount = 0\n\t# Password login loop\n while passwordfailcount < 3\n puts \"\"\n if prompt.mask(\"Welcome to the application. Please enter your password:\") != password\n passwordfailcount += 1\n puts \"Incorrect. Please try again. Attempt #{passwordfailcount} of 3.\"\n else\n main\n end\n end\nend",
"def password_request\n password_input = @prompt.mask(\"Please enter your password, or type quit.\")\n if password_input == @user.password\n puts \"Successful login!\"\n @user\n user_menu_runner\n #user can quit this process\n elsif password_input == \"quit\" || password_input == \"exit\"\n exit\n else\n #try again\n puts \"Sorry, incorrect password. Try again.\" # add esscape option\n password_request\n end\n end",
"def test_ID_25825_invalid_password\n login $user_1_email, $master_password\n go_to_change_password_page\n verify_text \"Change your Password\", \"Old password\" , \"New password\", \"Confirm password\"\n \n $profile_old_pass.when_present().set $master_password\n assert !($profile_save_changes.enabled?)\n $profile_new_pass.when_present().set \"newValidPass\"\n assert !($profile_save_changes.enabled?)\n $profile_confirm_pass.when_present().set \"unMatchedPass\"\n assert !($profile_save_changes.enabled?)\n \n $profile_old_pass.when_present().set $master_password\n $profile_new_pass.when_present().set \"newValidPass\"\n $profile_confirm_pass.when_present().set \"newValidPass\"\n assert $profile_save_changes.enabled?\n \n $profile_old_pass.when_present().set $master_password\n $profile_new_pass.when_present().set \"newValidPass\"\n $profile_confirm_pass.when_present().set \"unMatchedPass\"\n sleep 3\n assert $browser.text.include? \"Please make sure that your passwords match\"\n $profile_confirm_pass.when_present().set newValidPass\n sleep 3\n assert !($browser.text.include? \"Please make sure that your passwords match\")\n \n $profile_old_pass.when_present().set oldWrongPass\n $profile_new_pass.when_present().set \"pass11\"\n $profile_confirm_pass.when_present().set \"pass11\"\n $profile_save_changes.when_present().click\n sleep 3 \"pass11\"\n verify_text \"Password incorrect\"\n \n $profile_old_pass.when_present().clear\n $profile_old_pass.when_present().set \"oldPassword\"\n $profile_new_pass.when_present().clear\n $profile_new_pass.when_present().set \"pass\"\n $profile_confirm_pass.when_present().clear\n $profile_confirm_pass.when_present().set \"pass\"\n $profile_save_changes.when_present().click\n sleep 3 \n \n verify_text \"Please check for errors\", \"Must be at least 7 characters\"\n end",
"def change_password\n if request.post?\n @account = getAccount()\n pass = true\n err = \"\"\n old = params[:password][:old]\n new1 = params[:password][:new1]\n new2 = params[:password][:new2]\n if new1.length < 6 or new1.length > 18\n pass = false\n err = \"Length of password should be between 6 and 18.\"\n end\n \n if new1 != new2\n pass = false\n err = \"The retyped password doesn't match the new password.\"\n end\n \n if old != @account.password\n pass = false\n err = \"The password you entered doesn't match the password in our system.\"\n end\n \n if pass\n @account.update_attribute(\"password\", new1)\n flash[:notice] = \"Password updated.\"\n redirect_to :action=>'account', :controller=>'go'\n else\n flash[:notice] = err\n redirect_to :action=>'account', :controller=>'go'\n end \n \n else\n flash[:notice] = \"Please login.\"\n redirect_to :action=>'login', :controller=>'go'\n end\n \n if request.get?\n redirect_to(:action => \"index\", :controller =>\"go\")\n end \n end",
"def enter_password \n\nend",
"def call\n validate_equality\n user = context.user\n return if user.update(password: context.user_password_params[:password])\n\n context.fail!(message: user.errors.full_messages)\n end",
"def is_password_password(pass)\n if pass.downcase == 'password'\n 'Sorry, password cannot be password.'\n else\n 'Yay, password is not password.'\n end\nend",
"def password_changed?\n !password.blank?\n end",
"def password_changed?\n !@new_password.blank?\n end",
"def password_changed?\n !@new_password.blank?\n end",
"def password\n end",
"def password\n end",
"def update_password\n # check current password is valid\n if params[:account].present? and !@account.valid_password?(params[:account][:current_password])\n redirect_to gns_core.my_account_backend_accounts_path, flash: { error: \"Current password incorrectly.\" }\n return\n end\n\n if params[:account].present?\n params[:account].delete(:password) if params[:account][:password].blank?\n params[:account].delete(:password_confirmation) if params[:account][:password].blank? and params[:account][:password_confirmation].blank?\n\n if @account.update_with_password(account_params)\n bypass_sign_in(@account)\n redirect_to gns_core.my_account_backend_accounts_path, flash: { success: \"The new password has been successfully changed.\" }\n else\n if params[:account][:password].nil? or params[:account][:password].length < 6\n redirect_to gns_core.my_account_backend_accounts_path, flash: { error: \"New password must contain at least 6 characters.\" }\n else\n redirect_to gns_core.my_account_backend_accounts_path, flash: { error: \"Repeat password does not match.\" }\n end\n end\n end\n end",
"def edit_password(user, new_password)\n if @config.restrictions[:password_count_restriction]\n unless new_password >= @config.restrictions[:password_count_restriction].to_i\n return false\n end\n end\n user.password = user.hash_plaintext(new_password)\n user.save_data\n end",
"def new_password(data)\n data.strip!\n unless data =~ /^\\w{6,20}$/\n ask_password\n return\n end\n @display.echo_on\n @new_password = data\n ask_color\n end",
"def passwords_match?\n context.user.password == context.password\n end",
"def update_password\n @user = User.find_by_id(current_user.id)\n\n if User.authenticate(@user.username,pwd_params[:current_password])\n if(User.check_password_validity(pwd_params1[:password]))\n if @user.update(pwd_params1)\n flash[:notice] = \"Password was successfully changed.\"\n flash[:color]= \"valid\"\n redirect_to profile_index_path\n else\n render profile_change_password_path\n end\n else\n flash.now[:notice] = \"Password must be minimum of 6 characters.\"\n flash.now[:color]= \"invalid\"\n render profile_change_password_path\n end\n else\n flash.now[:notice] = \"Wrong Current Password.\"\n flash.now[:color]= \"invalid\"\n render profile_change_password_path\n end\n end",
"def password_required?; end",
"def update_password\n @user = User.find_by_id(session[:user_id])\n\n if (@user.password == params[:old_password]) and (params[:password] == params[:password_confirmation])\n\n @user.password = params[:password]\n if @user.save\n flash[:notice] = \"Password Updated Successfully\"\n redirect_to :action => \"home\"\n else\n flash[:notice] = \"Password not Updated Successfully\"\n end # if @user.save\n \n else\n flash[:notice] = \"Password doesn't match correctly\"\n redirect_to :action => \"change_password\"\n\n end #if (@user.password == params[:old_password])\n\n end",
"def need_change_password!\n return unless password_expiration_enabled?\n\n need_change_password\n save(validate: false)\n end",
"def validate_password\n puts \"Enter your User ID and Password here.\"\n user_id = gets.chomp\n password = gets.chomp\n\n same(user_id, password)\n long_enough(user_id)\n long_enough(password)\n does_not_contain_special(user_id)\n contains_special(password)\n is_password(password)\nend",
"def authen_action_chpass(session,new_body)\n authen_start = session.authen_start\n authen_cont = session.authen_cont\n\n # make sure this is an ascii or enable request\n if (!authen_start.body.authen_type_ascii? && !authen_start.body.service_enable?)\n new_body.status_fail!\n new_body.server_msg = \"Only ascii password change requests are supported.\"\n return(nil)\n end\n\n if (!session.reply.body) # no previous conversation has taken place\n if (authen_start.body.user_len == 0)\n # request username\n new_body.status_getuser!\n new_body.server_msg = @tacacs_daemon.login_prompt\n else\n # request old password\n session.getuser = authen_start.body.user\n new_body.status_getdata!\n new_body.flag_noecho!\n new_body.server_msg = @tacacs_daemon.password_prompt\n end\n\n else # make sure we got what we asked for in last reply\n if (session.reply.body.status_getuser?)\n if (authen_cont.body.user_msg_len != 0)\n # request old password\n session.getuser = authen_cont.body.user_msg\n new_body.status_getdata!\n new_body.flag_noecho!\n new_body.server_msg = @tacacs_daemon.password_prompt\n\n else\n # fail\n new_body.status_fail!\n new_body.server_msg = \"Username requested but none provided.\"\n end\n\n elsif (session.reply.body.status_getdata?)\n if (authen_cont.body.user_msg_len != 0)\n # determine pass/fail status\n username = session.getuser\n password = authen_cont.body.user_msg\n\n pass_fail = authenticate(username, password, session.authen_start)\n\n if (pass_fail[:pass])\n new_body.status_getpass!\n new_body.flag_noecho!\n new_body.server_msg = \"New Password: \"\n else\n new_body.status_fail!\n new_body.server_msg = pass_fail[:msg]\n end\n\n else\n # fail\n new_body.status_fail!\n new_ body.server_msg = \"Password requested but none provided.\"\n end\n\n elsif (session.reply.body.status_getpass?)\n if (authen_cont.body.user_msg_len != 0)\n # determine pass/fail status\n username = session.getuser\n password = authen_cont.body.user_msg\n\n if (!session.getpass)\n session.getpass = password\n new_body.status_getpass!\n new_body.flag_noecho!\n new_body.server_msg = \"Verify Password: \"\n else\n if (session.getpass == password)\n user = @tacacs_daemon.users(username) if (username)\n\n if (session.authen_start.body.service_enable?)\n user.enable_password = password\n else\n user.login_password = password\n end\n new_body.status_pass!\n new_body.server_msg = \"Password updated.\"\n @tacacs_daemon.log(:info, ['msg_type=Authentication', 'message=Password has been updated.', \"status=#{new_body.xlate_status}\"],authen_start,@peeraddr,username)\n else\n new_body.status_fail!\n new_body.server_msg = \"Passwords did not match.\"\n end\n\n end\n\n else\n # fail\n new_body.status_fail!\n new_ body.msg = \"Password requested but none provided.\"\n end\n\n else\n # all other statuses are in error, so some sort of internal error must have occured\n new_body.status_error!\n new_body.server_msg = \"Internal Server Error. Unexpected status for ASCII change \" +\n \"password request: #{session.reply.body.status}\"\n @tacacs_daemon.log(:error, ['msg_type=Authentication', \"message=#{new_body.server_msg}\",\"status=#{new_body.xlate_status}\"],authen_start,@peeraddr)\n end\n end\n\n return(nil)\n end",
"def password?\n password\n end",
"def update_password\n @user.password = @new_e_password\n if GlobalConstant::User.auto_blocked_status == @user.status\n # if we had blocked a user for more than a threshhold failed login attemps we set status to blocked\n # now we should reset it to active\n @user.status = GlobalConstant::User.active_status\n @user.failed_login_attempt_count = 0\n end\n @user.save!\n end",
"def password_changed_confirm\n pw_change_confirm.click\n end",
"def set_password_field(password)\n end",
"def test_change_password\n user = User.named(\"user\")\n assert(user.password_matches?(\"user\"))\n\n user.change_password(\"newpass\")\n assert(!user.password_matches?(\"user\"))\n assert(user.password_matches?(\"newpass\"))\n end",
"def change_password(new_password)\n update_password(new_password)\n @password = new_password\n puts 'Success! Your password has been changed.'.colorize(:light_green)\n @prompt.keypress('Press any key to continue..')\n menu = Menu.new(self)\n menu.account_details\n end",
"def old_password=(string)\n end",
"def password; end",
"def password; end",
"def password; end",
"def password; end",
"def password; end",
"def password; end",
"def correct_password?(params)\n self.current_password = params[:user][:current_password]\n self.password == self.current_password\n end",
"def change_password(username, password)\n perform_request({:action => \"client-updatepassword\", :username => username, :password => password})\n statusmsg.match /success/i\n end",
"def send_password_change_notification; end",
"def change_password(old_pass, new_pass, confirm_pass)\n if self.encrypted_password == encrypt(old_pass)\n p \"password_verified\"\n if new_pass = confirm_pass\n self.password = new_pass\n self.password_confirmation = confirm_pass\n if self.save\n p \"Sucess\"\n end\n else\n p \"Hey, your password doesn't match it's confirmation!\"\n end\n else\n p \"Hey, your Old password doesn't match!\"\n end\n end",
"def change_password (current_pass, new_pass, confirm_pass)\n return valid? unless @current_password = password?(current_pass)\n password_with_confirmation(new_pass, confirm_pass)\n valid?\n end",
"def password_changed?\n !@new_password.blank?\n end",
"def set_password\n @user = User.find(session[:user_id])\n if @user.password == params[:old_password]\n if @user.update_attributes(params[:user])\n redirect_to user_new_path\n else\n flash[:notice] = \"Please enter correct passwords\"\n render user_change_password_path\n end\n else\n flash[:notice] = \"Please enter your correct passwords\"\n redirect_to user_change_password_path\n end\n end",
"def match_password_basic(p)\n puts \"p: #{p}\"\n puts \"password: #{password}\"\n p == password\n end",
"def check\n # check passwd change priv\n res = send_request_cgi({\n 'uri' => normalize_uri(target_uri.path, \"password_change.cgi\"),\n 'headers' =>\n {\n 'Referer' => \"#{peer}/session_login.cgi\"\n },\n 'cookie' => \"redirect=1; testing=1; sid=x; sessiontest=1\"\n })\n\n if res && res.code == 200 && res.body =~ /Failed/\n res = send_request_cgi(\n {\n 'method' => 'POST',\n 'cookie' => \"redirect=1; testing=1; sid=x; sessiontest=1\",\n 'ctype' => 'application/x-www-form-urlencoded',\n 'uri' => normalize_uri(target_uri.path, 'password_change.cgi'),\n 'headers' =>\n {\n 'Referer' => \"#{peer}/session_login.cgi\"\n },\n 'data' => \"user=root&pam=&expired=2&old=AkkuS%7cdir%20&new1=akkuss&new2=akkuss\" \n })\n\n if res && res.code == 200 && res.body =~ /password_change.cgi/\n return CheckCode::Vulnerable\n else\n return CheckCode::Safe\n end\n else\n return CheckCode::Safe\n end\n end",
"def validate_password\n score = []\n score << repetitive_substring(@row[\"password\"])\n score << string_length(@row[\"password\"])\n score << upper_lower_case(@row[\"password\"])\n score << digit(@row[\"password\"])\n character_change = score.sum\n @row[\"status\"] = (character_change.zero? ? \"Strong\" : character_change)\n return @row\n end",
"def update_password(old_password, new_password, new_password_confirmation)\n if self.authenticated?(old_password)\n if new_password.blank?\n false\n elsif new_password == new_password_confirmation\n self.password = new_password\n self.password_confirmation = new_password_confirmation\n self.save\n else\n false\n end\n else\n false\n end\n end",
"def enter_password_shared\n end",
"def recruiter_password_change(current_password,new_password)\n current_password_field.set current_password\n\t new_password_field.set new_password\n confirm_password_field.set new_password\n\t change_button.click\n\t \n end",
"def change_password!(password)\n json = JSON.generate(:changePassword => { :adminPass => password })\n @compute.connection.req('POST', \"/servers/#{@id}/action\", :data => json)\n @adminPass = password\n end",
"def password_update?(new_pass)\n return false if current_resource.info['rep:password'].end_with?(\n hash_generator(new_pass)\n )\n true\n end",
"def change_password\n\t\t \tif params[:current_password]==current_user.password\n\t\t\t\tif params[:new_password]==params[:conform_password]\n\t\t\t\t\t current_user.password=params[:new_password]\n\t\t\t\t\t\tif current_user.save\t\n\t\t\t \t\t redirect_to take_password_path,:notice=>show_flash_message('Your Password is Successfully Changed.')\n\t\t\t \t\telse\n\t\t\t\t\t\t\tshow_flash_message('Your Password is not Changed.')\n\t\t\t \t\t \tredirect_to take_password_path\n\t \t\t\t\t\tend\n\t \t \telse\n\t\t\t\t \t\tredirect_to take_password_path,:notice=>show_flash_message('New Password and Conform password not matched.')\n\t\t\t\tend\n\t\t\telse\n\t\t\t\t \t\tredirect_to take_password_path ,:notice=>show_flash_message('Old Password is not correct.')\n\t\t\tend\n\t\tend",
"def change_password\n user_hash = params[:user]\n user = User.find(user_hash[:id])\n unless current_user.is_super_admin? || current_user.is_admin_of_any?(user.group_memberships)\n if user == current_user || current_user.is_super_admin? || current_user.is_admin_of_any?(user.group_memberships)\n if User.authenticate(user.login, user_hash[:current_password])\n if user_hash[:password] == user_hash[:password_confirmation]\n if user_hash[:password].length >= 4\n user.password = user_hash[:password]\n user.password_confirmation = user_hash[:password_confirmation]\n user.save!\n else\n @message = \"Password must be at least 4 characters\"\n end\n else\n @message = \"New Password must equal Confirm Password\"\n end \n else \n @message = \"Old Password must equal Current Password\"\n end\n end\n else\n # Wed Nov 3 04:40:07 IST 2010, ramonrails \n # TODO: why are we validating here? this should be done in model\n [:password, :password_confirmation].each {|e| user.send(\"#{e}=\", user_hash[e]) } # apply password\n #\n # save and collect errors for failures\n @message = user.errors.each_full(&:collect).join(', ') unless user.save\n #\n # old logic\n # if user_hash[:password] == user_hash[:password_confirmation]\n # if user_hash[:password].length >= 4\n # UtilityHelper.change_password_by_user_id(user.id, user_hash[:password])\n # else\n # @message = \"Password must be at least 4 characters\"\n # end\n # else\n # @message = \"New Password must equal Confirm Password\"\n # end\n end\n if @message.nil?\n @success_message = true\n #send email\n CriticalMailer.deliver_password_confirmation(user)\n end\n @user = user\n if request.xhr?\n \trender :partial => 'change_password_init'\n else\n \trender :action => 'change_password_init',:user_id => params[:user][:id]\n end\n end",
"def check_password_change_required?\n password_change_required || check_password_expired?\n end",
"def update_password\n @user = User.find_by_uuid(params[:id])\n if @user.update(user_params_with_password)\n if @user.send_password.present? && @user.send_password.to_i == 1\n @user.send_welcome_email\n end\n flash[:success] = t('messages.default_success')\n redirect_to users_path\n else\n flash[:error] = t('messages.default_error')\n render :edit_password\n end\n end",
"def change_password\n if current_doctor.present? && current_doctor.valid_password?(params[:password]) \n if (params[:new_password]) == (params[:confirm_password])\n current_doctor.update(password: params[:new_password])\n render json: {message: \"Password Changed Successfully \"}\n else\n render json: {message: \"New Password doesn't match Confirm Password\"}\n end\n else\n render json: {message: \"Current Password is invalid\"}\n end\n end",
"def has_password?(submitted_password)\n\tpassword == encrypt(submitted_password) \n end",
"def update_password password, password_confirmation, old_password\n if crypted_password.blank?\n self.password, self.password_confirmation = password, password_confirmation\n elsif authenticated_by_password? old_password\n self.password, self.password_confirmation = password, password_confirmation\n true\n else\n errors.add :base, t(:invalid_old_password)\n false\n end\n end",
"def update_password\n current_password = params[:current_password]\n correct_password = @account.password\n if current_password == correct_password\n @account.password = params[:account_password]\n flash.now[:message] = \"你的密码已成功修改\" if @account.save\n else\n flash.now[:error_msg] = \"你输入的当前密码不正确, 不能修改密码\"\n end\n \n render :action => \"edit\"\n end",
"def password\n if @user.update_with_password(password_params)\n render_update_success @user\n else\n render_failure @user\n end\n end",
"def do_change_password_for(user)\n# begin\n User.transaction(user) do\n user.change_password(params[:user][:password], params[:user][:password_confirmation])\n if user.save\n if LoginEngine.config(:use_email_notification)\n UserNotify.deliver_change_password(user, params[:user][:password])\n flash[:notice] = \"Updated password emailed to #{@user.email}\"\n else\n flash[:notice] = \"Password updated.\"\n end\n return true\n else\n flash[:warning] = 'There was a problem saving the password. Please retry.'\n return false\n end\n end\n# rescue\n# flash[:warning] = 'Password could not be changed at this time. Please retry.'\n# end\n end",
"def verify_password(*)\n false\n end",
"def set_Password(value)\n set_input(\"Password\", value)\n end",
"def set_Password(value)\n set_input(\"Password\", value)\n end",
"def set_Password(value)\n set_input(\"Password\", value)\n end",
"def set_Password(value)\n set_input(\"Password\", value)\n end",
"def set_Password(value)\n set_input(\"Password\", value)\n end",
"def set_Password(value)\n set_input(\"Password\", value)\n end",
"def set_Password(value)\n set_input(\"Password\", value)\n end",
"def set_Password(value)\n set_input(\"Password\", value)\n end",
"def set_Password(value)\n set_input(\"Password\", value)\n end",
"def set_Password(value)\n set_input(\"Password\", value)\n end",
"def set_Password(value)\n set_input(\"Password\", value)\n end"
] |
[
"0.79569876",
"0.7859544",
"0.7709374",
"0.75946057",
"0.757565",
"0.7538257",
"0.7515478",
"0.75051314",
"0.74864113",
"0.74533826",
"0.74109906",
"0.7392846",
"0.7386748",
"0.73720753",
"0.7349812",
"0.73483235",
"0.7314962",
"0.73023295",
"0.72956926",
"0.7286257",
"0.72813696",
"0.7267665",
"0.72669494",
"0.72597086",
"0.72327656",
"0.7201424",
"0.71912897",
"0.7184908",
"0.7175118",
"0.7126567",
"0.7126277",
"0.71197426",
"0.7113531",
"0.7112778",
"0.7094554",
"0.7093806",
"0.70897686",
"0.70897686",
"0.7083209",
"0.7083209",
"0.7078238",
"0.70414263",
"0.70368266",
"0.702398",
"0.70177615",
"0.70113325",
"0.700751",
"0.7005279",
"0.70043355",
"0.697846",
"0.6973499",
"0.6968531",
"0.69682163",
"0.6966638",
"0.69613796",
"0.69568425",
"0.69504726",
"0.69503176",
"0.69503176",
"0.69503176",
"0.69503176",
"0.69503176",
"0.69503176",
"0.6944339",
"0.69311273",
"0.6927373",
"0.6927257",
"0.6926884",
"0.6923935",
"0.69196767",
"0.69134563",
"0.6912022",
"0.6905783",
"0.69020194",
"0.6891772",
"0.6891212",
"0.68828046",
"0.6882751",
"0.6877697",
"0.68717736",
"0.68717295",
"0.6866793",
"0.6854662",
"0.685466",
"0.6852508",
"0.68305576",
"0.68080306",
"0.68008727",
"0.6796617",
"0.67896724",
"0.67896724",
"0.67896724",
"0.67896724",
"0.67896724",
"0.67896724",
"0.67896724",
"0.67896724",
"0.67896724",
"0.67896724",
"0.67896724"
] |
0.70792675
|
40
|
(This method is generated in Translator_defaultbuildImpl)
|
def get_id
return @m_id
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def translation_target\n super\n end",
"def build; end",
"def translations; end",
"def init_translations; end",
"def build=(_arg0); end",
"def build\r\n raise \"Not implemented\"\r\n end",
"def build\r\n end",
"def build\r\n end",
"def build\n end",
"def label_translation; end",
"def build!\n end",
"def create_translations\n end",
"def translatable\n self._translatable[base_name]\n end",
"def translate(settings); end",
"def translations_hash; end",
"def build\n end",
"def setup_mass_copy_translations\n end",
"def _lex_trans_keys=(_arg0); end",
"def _lex_trans_keys=(_arg0); end",
"def _lex_trans_keys=(_arg0); end",
"def _lex_trans_keys=(_arg0); end",
"def private; end",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translatable\n self._translatable[base_name] ||= []\n end",
"def build(params); end",
"def _lex_trans_keys; end",
"def _lex_trans_keys; end",
"def _lex_trans_keys; end",
"def _lex_trans_keys; end",
"def translate!( *args )\n super( *args )\n reset_positions_inside\n end",
"def _lex_trans_actions; end",
"def _lex_trans_actions; end",
"def _lex_trans_actions; end",
"def _lex_trans_actions; end",
"def build\n method_proxy(:build)\n\n true\n end",
"def create_translation(other)\n end",
"def definition_builder; end",
"def definition_builder; end",
"def build(**)\n raise NotImplementedError\n end",
"def lang=(_arg0); end",
"def lang=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def make; end",
"def translate q, target=@target_lang, source=@source_lang\n return \"[#{source}->#{target}]#{q.to_s}\"\n end",
"def build_script\n raise NotImplementedError\n end",
"def translator\n @translator ||= Translator.new\n end",
"def set_translation_target(opts)\n opts = check_params(opts,[:targets])\n super(opts)\n end",
"def build(*args)\n raise \"Method 'build' not implemented for #{self.class.name}\"\n end",
"def translate(eng_word) # here call to Max's ending code\n Multitran.translate(eng_word)\n end",
"def _lex_trans_targs; end",
"def _lex_trans_targs; end",
"def _lex_trans_targs; end",
"def _lex_trans_targs; end",
"def translate(*args, **opts); end",
"def build_html\n # the first one should not use a locale, for the default:\n generate_all_html_pages\n\n # now translate, if necessary:\n if translation.should_translate?\n translation.prepare\n translation.available_locales.each do |locale|\n translation.current_locale = locale\n generate_all_html_pages\n end\n end\n end",
"def builder; end",
"def builder; end",
"def builder; end",
"def build_gem; end",
"def _lex_trans_targs=(_arg0); end",
"def _lex_trans_targs=(_arg0); end",
"def _lex_trans_targs=(_arg0); end",
"def _lex_trans_targs=(_arg0); end",
"def create\n @user = current_user\n @project = Project.find(params[:project_id])\n @preferedlang = Language.find_by_id(@project.source_lang_id)\n @slanguages = Language.where(\"id != ?\", @preferedlang.id).order('iso_code asc') \n @slanguages.unshift(@preferedlang)\n #from railsrecipes recipe 22 - refactor\n # @user = current_user\n\n\n @mostpopulartarlang = Language.find_by_id(@project.translations.maximum(\"source_lang_id\"))\n if @mostpopulartarlang\n @tlanguages = Language.where(\"id != ?\", @mostpopulartarlang.id).order('iso_code asc')\n @tlanguages.unshift(@mostpopulartarlang)\n else\n @tlanguages = Language.order('iso_code desc')\n end\n\n\n @translation = @project.translations.build(params[:translation])\n @translation.owner_id = @user.id\n\n# @project = Project.find(params[:id])\n\n# @translation = Translation.new(params[:translation])\n# @translation.owner_id = current_user.id\n# @translation.project_id = Project.find_by_id(params[:project_id]).id\n # @user = User.find(params[:user_id])\n # @project = Project.find(params[:project_id])\n # @translation = Translation.new(params[:translation])\n # @project = current_user.projects.build\n # @translation = @project.translations.build\n # @user = current_user\n # @project = Project.find_by_user_id(@user)\n # @translation = @project.translations.build(params[:translation])\n @languages = Language.all(:order => 'iso_code')\n # #process information from checkbox\n\n if @translation.save\n flash[:notice] = \"Translation was successfully created\"\n # redirect_to user_project_translations_path(@user, @project)\n redirect_to user_project_path(current_user, @project)\n else\n render 'new'\n end\nend",
"def target_version=(_arg0); end",
"def translate(input_text, src_lang, target_lang)\n raise \"Not Implemented. Class #{self.class.name} doesn't implement translate\"\n end",
"def process_and_build_components \n end",
"def build_method\nend",
"def build_method\nend",
"def originalsourceform; end",
"def transforms; end",
"def rebuild\n build addl_cmake_bld_args: '--clean-first'\n end",
"def lang(orig); end",
"def initialize b\n @build = b\n end",
"def internal; end",
"def after_build\n cleanup_nontarget_files\n run_help_indexer\nend",
"def inject_translatable_block\n inject_into_class model_path, class_name, generate_translatable_block\n end",
"def target; end",
"def target; end",
"def inspect\n \"#<Translations (#{backend}) @names=#{names.join(\", \")}>\"\n end",
"def command_builder; end",
"def translate\n if self.products && self.products.first\n ContentTranslation.auto_translate(self, self.products.first.brand)\n end\n end",
"def check_starting(_lang_result)\n end",
"def build_with_lto(pass_manager, internalize = false, run_inliner = false)\n raise \"build_with_lto is not currently supported\"\n end",
"def mozart_german; end",
"def translated_msg(translate, message, src_lang, target_lang)\n return message unless translate \n use_src = nil \n if (src_lang.nil? || src_lang.empty?)\n # We don't need to infer again and again\n begin\n @inferred_src_lang ||= infer_languages.first\n rescue StandardError => e \n raise LangDetectionFailureException.new(\"Failed to infer language due to #{e.message}\")\n end\n use_src = @inferred_src_lang\n else\n use_src = src_lang\n end\n return message if use_src.eql?(target_lang)\n @translator.translate(message, use_src, target_lang)\n end",
"def make_dic_lists_class_from_ts_from_current_version(sFrTSFilePath, sEnTSFilePath, sJaTSFilePath, hQmFileBaseNamePath=Hash.new(), coTranslateSummaries=TranslateSummaries.new())\n#\t\tSTDOUT.puts \"Check1:#{sTSFilePath}\"\n\t\t#return false unless sFrTSFilePath =~ /_msg_(.+?)\\.ts$/\n\t\treturn false unless sFrTSFilePath =~ /_(\\w{2})\\.ts$/\n\t\tsLang = $1.to_s\n\t\tsTSFileBaseName_temp = File.basename(sFrTSFilePath).gsub(/\\.ts$/, \"\")\n\t\t#sTSFileBaseName = sTSFileBaseName_temp.gsub(/_msg_(en|ja)$/, \"_msg_fr\")\n\t\tsTSFileBaseName = sTSFileBaseName_temp.gsub(/_(en|ja)$/, \"_fr\")\n\t\t#return true if hQmFileBaseNamePath[sTSFileBaseName] == true\n\t\tsTargetTSFilePath = sFrTSFilePath.gsub(/\\.ts$/, \"\")\n\t\t#sTargetTSFilePath = sTargetTSFilePath.gsub(/_msg_(en|ja)$/, \"_msg_fr\")\n\t\tsTargetTSFilePath = sTargetTSFilePath.gsub(/_(en|ja)$/, \"_fr\")\n\t\t# modified by takeru on 2012.5.2\n\t\t# modified by takeru on 2012.5.12\n\t\tcoTranslateDicLists = coTranslateSummaries[sTSFileBaseName]\n\t\t#coTranslateDicLists = coTranslateSummaries[sTargetTSFilePath]\n\t\tif coTranslateDicLists == nil then\n\t\t\tcoTranslateDicLists = TranslateDicLists.new()\n\t\t\t#coTranslateDicLists.create_dic_lists(sTSFileBaseName, coTranslateSummaries) \n\t\t\tcoTranslateDicLists.create_dic_lists(sTSFileBaseName, coTranslateSummaries) \n\t\tend\n\n\t\t#PP.pp(coTranslateDicLists, STDERR)\n\t\t#STDERR.puts coTranslateDicLists\n\t\t# modified by takeru on 2012.5.2\n\t\t# modified by takeru on 2012.5.12\n\t\t#coTranslateDicLists.create_dic_lists(sTargetTSFilePath, coTranslateSummaries) \n\t\t\n\t\tdoc = nil\n\t\t#File.open(sTSFilePath) {|xmlfile|\n\t\t#\tdoc = REXML::Document.new(xmlfile)\n\t\t#}\n\t\t#nTotalCount = TranslateTsLIB.traverse_count_translate_tag(doc.root)\n\t\t#nCount = traverse_install_keyword(coTranslateDicLists, sLang, doc.root, nTotalCount, 0)\n\n\t\trexmlDocFr = nil\n\t\trexmlDocEn = nil\n\t\trexmlDocJa = nil\n#\t\tSTDOUT.puts \"Check2:#{sTSFilePath}\"\n\t\tif File.exist?(sFrTSFilePath) == true then\n\t\t\tFile.open(sFrTSFilePath) do |sXmlFile|\n\t\t\t\t#STDERR.puts sXmlFile\n\t\t\t\trexmlDocFr = REXML::Document.new(sXmlFile)\n\t\t\tend\n\t\telse\n\t\t\trexmlDocFr = REXML::Document.new(\"\")\n\t\tend\n\t\tif File.exist?(sEnTSFilePath) == true then\n\t\t\tFile.open(sEnTSFilePath) do |sXmlFile|\n\t\t\t\t#STDERR.puts sXmlFile\n\t\t\t\trexmlDocEn = REXML::Document.new(sXmlFile)\n\t\t\tend\n\t\telse\n\t\t\trexmlDocEn = REXML::Document.new(\"\")\n\t\tend\n\t\tif File.exist?(sJaTSFilePath) == true then\n\t\t\tFile.open(sJaTSFilePath) do |sXmlFile|\n\t\t\t\t#STDERR.puts sXmlFile\n\t\t\t\trexmlDocJa = REXML::Document.new(sXmlFile)\n\t\t\tend\n\t\telse\n\t\t\trexmlDocJa = REXML::Document.new(\"\")\n\t\tend\n\t\tTranslateTsLIB.make_dic_files_from_current_version(coTranslateDicLists, rexmlDocFr, rexmlDocEn, rexmlDocJa)\n\n\t\tPP.pp(coTranslateDicLists, STDERR)\n\t\t#STDERR.puts coTranslateDicListC\n\t\thQmFileBaseNamePath[sTSFileBaseName] = true\n\n\t\treturn true\n\n\tend",
"def transitive_tags=(_arg0); end",
"def project=(_arg0); end",
"def translator_for(t_key, template = nil, parameters = nil)\n o_translator = translators[t_key]\n if template\n translator = Translator.new(template,\n :parameters => parameters)\n if o_translator\n o_translator.flagged.each do |i|\n translator.flag_ref(i)\n end\n end\n translators[t_key] = translator\n o_translator = translator\n else\n unless o_translator\n o_translator = Translator.new({},\n :parameters => {})\n end\n end\n o_translator\n end",
"def build\n @values.fetch('ai.application.build') { \n @values['ai.application.build'] = nil\n }\n end"
] |
[
"0.6882901",
"0.653592",
"0.63217664",
"0.6284657",
"0.61551243",
"0.61091876",
"0.605949",
"0.605949",
"0.60470265",
"0.59335953",
"0.5844821",
"0.5795114",
"0.5761158",
"0.56754434",
"0.56447375",
"0.5643845",
"0.5639414",
"0.5635945",
"0.5635945",
"0.5635945",
"0.5635945",
"0.563406",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5539237",
"0.5517182",
"0.5505295",
"0.5505295",
"0.5505295",
"0.5505295",
"0.54820263",
"0.5475904",
"0.5475904",
"0.5475904",
"0.5475904",
"0.547027",
"0.5437076",
"0.54157394",
"0.54157394",
"0.5398866",
"0.5386972",
"0.5386972",
"0.53822404",
"0.53822404",
"0.53822404",
"0.53822404",
"0.5361637",
"0.5323374",
"0.5308725",
"0.52835053",
"0.5282656",
"0.52782214",
"0.5275988",
"0.5274997",
"0.5274997",
"0.5274997",
"0.5274997",
"0.5241623",
"0.52328515",
"0.52266777",
"0.52266777",
"0.52266777",
"0.52109337",
"0.5204789",
"0.5204789",
"0.5204789",
"0.5204789",
"0.5192355",
"0.5190386",
"0.51832217",
"0.5179127",
"0.51784027",
"0.51784027",
"0.5175266",
"0.5170668",
"0.51630884",
"0.5160946",
"0.5158187",
"0.51568115",
"0.51486707",
"0.51343715",
"0.51235247",
"0.51235247",
"0.5122161",
"0.51212776",
"0.5117833",
"0.5116379",
"0.50977826",
"0.5095889",
"0.50931627",
"0.5088532",
"0.5056332",
"0.50559413",
"0.5053341",
"0.5048526"
] |
0.0
|
-1
|
(This method is generated in Translator_defaultbuildImpl)
|
def get_name
return @m_name
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def translation_target\n super\n end",
"def build; end",
"def translations; end",
"def init_translations; end",
"def build=(_arg0); end",
"def build\r\n raise \"Not implemented\"\r\n end",
"def build\r\n end",
"def build\r\n end",
"def build\n end",
"def label_translation; end",
"def build!\n end",
"def create_translations\n end",
"def translatable\n self._translatable[base_name]\n end",
"def translate(settings); end",
"def translations_hash; end",
"def build\n end",
"def setup_mass_copy_translations\n end",
"def _lex_trans_keys=(_arg0); end",
"def _lex_trans_keys=(_arg0); end",
"def _lex_trans_keys=(_arg0); end",
"def _lex_trans_keys=(_arg0); end",
"def private; end",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translatable\n self._translatable[base_name] ||= []\n end",
"def build(params); end",
"def _lex_trans_keys; end",
"def _lex_trans_keys; end",
"def _lex_trans_keys; end",
"def _lex_trans_keys; end",
"def translate!( *args )\n super( *args )\n reset_positions_inside\n end",
"def _lex_trans_actions; end",
"def _lex_trans_actions; end",
"def _lex_trans_actions; end",
"def _lex_trans_actions; end",
"def build\n method_proxy(:build)\n\n true\n end",
"def create_translation(other)\n end",
"def definition_builder; end",
"def definition_builder; end",
"def build(**)\n raise NotImplementedError\n end",
"def lang=(_arg0); end",
"def lang=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def make; end",
"def translate q, target=@target_lang, source=@source_lang\n return \"[#{source}->#{target}]#{q.to_s}\"\n end",
"def build_script\n raise NotImplementedError\n end",
"def translator\n @translator ||= Translator.new\n end",
"def set_translation_target(opts)\n opts = check_params(opts,[:targets])\n super(opts)\n end",
"def _lex_trans_targs; end",
"def _lex_trans_targs; end",
"def _lex_trans_targs; end",
"def _lex_trans_targs; end",
"def translate(eng_word) # here call to Max's ending code\n Multitran.translate(eng_word)\n end",
"def build(*args)\n raise \"Method 'build' not implemented for #{self.class.name}\"\n end",
"def translate(*args, **opts); end",
"def build_html\n # the first one should not use a locale, for the default:\n generate_all_html_pages\n\n # now translate, if necessary:\n if translation.should_translate?\n translation.prepare\n translation.available_locales.each do |locale|\n translation.current_locale = locale\n generate_all_html_pages\n end\n end\n end",
"def builder; end",
"def builder; end",
"def builder; end",
"def build_gem; end",
"def _lex_trans_targs=(_arg0); end",
"def _lex_trans_targs=(_arg0); end",
"def _lex_trans_targs=(_arg0); end",
"def _lex_trans_targs=(_arg0); end",
"def create\n @user = current_user\n @project = Project.find(params[:project_id])\n @preferedlang = Language.find_by_id(@project.source_lang_id)\n @slanguages = Language.where(\"id != ?\", @preferedlang.id).order('iso_code asc') \n @slanguages.unshift(@preferedlang)\n #from railsrecipes recipe 22 - refactor\n # @user = current_user\n\n\n @mostpopulartarlang = Language.find_by_id(@project.translations.maximum(\"source_lang_id\"))\n if @mostpopulartarlang\n @tlanguages = Language.where(\"id != ?\", @mostpopulartarlang.id).order('iso_code asc')\n @tlanguages.unshift(@mostpopulartarlang)\n else\n @tlanguages = Language.order('iso_code desc')\n end\n\n\n @translation = @project.translations.build(params[:translation])\n @translation.owner_id = @user.id\n\n# @project = Project.find(params[:id])\n\n# @translation = Translation.new(params[:translation])\n# @translation.owner_id = current_user.id\n# @translation.project_id = Project.find_by_id(params[:project_id]).id\n # @user = User.find(params[:user_id])\n # @project = Project.find(params[:project_id])\n # @translation = Translation.new(params[:translation])\n # @project = current_user.projects.build\n # @translation = @project.translations.build\n # @user = current_user\n # @project = Project.find_by_user_id(@user)\n # @translation = @project.translations.build(params[:translation])\n @languages = Language.all(:order => 'iso_code')\n # #process information from checkbox\n\n if @translation.save\n flash[:notice] = \"Translation was successfully created\"\n # redirect_to user_project_translations_path(@user, @project)\n redirect_to user_project_path(current_user, @project)\n else\n render 'new'\n end\nend",
"def target_version=(_arg0); end",
"def translate(input_text, src_lang, target_lang)\n raise \"Not Implemented. Class #{self.class.name} doesn't implement translate\"\n end",
"def process_and_build_components \n end",
"def build_method\nend",
"def build_method\nend",
"def originalsourceform; end",
"def transforms; end",
"def rebuild\n build addl_cmake_bld_args: '--clean-first'\n end",
"def lang(orig); end",
"def initialize b\n @build = b\n end",
"def internal; end",
"def after_build\n cleanup_nontarget_files\n run_help_indexer\nend",
"def inject_translatable_block\n inject_into_class model_path, class_name, generate_translatable_block\n end",
"def inspect\n \"#<Translations (#{backend}) @names=#{names.join(\", \")}>\"\n end",
"def target; end",
"def target; end",
"def command_builder; end",
"def translate\n if self.products && self.products.first\n ContentTranslation.auto_translate(self, self.products.first.brand)\n end\n end",
"def check_starting(_lang_result)\n end",
"def build_with_lto(pass_manager, internalize = false, run_inliner = false)\n raise \"build_with_lto is not currently supported\"\n end",
"def mozart_german; end",
"def translated_msg(translate, message, src_lang, target_lang)\n return message unless translate \n use_src = nil \n if (src_lang.nil? || src_lang.empty?)\n # We don't need to infer again and again\n begin\n @inferred_src_lang ||= infer_languages.first\n rescue StandardError => e \n raise LangDetectionFailureException.new(\"Failed to infer language due to #{e.message}\")\n end\n use_src = @inferred_src_lang\n else\n use_src = src_lang\n end\n return message if use_src.eql?(target_lang)\n @translator.translate(message, use_src, target_lang)\n end",
"def make_dic_lists_class_from_ts_from_current_version(sFrTSFilePath, sEnTSFilePath, sJaTSFilePath, hQmFileBaseNamePath=Hash.new(), coTranslateSummaries=TranslateSummaries.new())\n#\t\tSTDOUT.puts \"Check1:#{sTSFilePath}\"\n\t\t#return false unless sFrTSFilePath =~ /_msg_(.+?)\\.ts$/\n\t\treturn false unless sFrTSFilePath =~ /_(\\w{2})\\.ts$/\n\t\tsLang = $1.to_s\n\t\tsTSFileBaseName_temp = File.basename(sFrTSFilePath).gsub(/\\.ts$/, \"\")\n\t\t#sTSFileBaseName = sTSFileBaseName_temp.gsub(/_msg_(en|ja)$/, \"_msg_fr\")\n\t\tsTSFileBaseName = sTSFileBaseName_temp.gsub(/_(en|ja)$/, \"_fr\")\n\t\t#return true if hQmFileBaseNamePath[sTSFileBaseName] == true\n\t\tsTargetTSFilePath = sFrTSFilePath.gsub(/\\.ts$/, \"\")\n\t\t#sTargetTSFilePath = sTargetTSFilePath.gsub(/_msg_(en|ja)$/, \"_msg_fr\")\n\t\tsTargetTSFilePath = sTargetTSFilePath.gsub(/_(en|ja)$/, \"_fr\")\n\t\t# modified by takeru on 2012.5.2\n\t\t# modified by takeru on 2012.5.12\n\t\tcoTranslateDicLists = coTranslateSummaries[sTSFileBaseName]\n\t\t#coTranslateDicLists = coTranslateSummaries[sTargetTSFilePath]\n\t\tif coTranslateDicLists == nil then\n\t\t\tcoTranslateDicLists = TranslateDicLists.new()\n\t\t\t#coTranslateDicLists.create_dic_lists(sTSFileBaseName, coTranslateSummaries) \n\t\t\tcoTranslateDicLists.create_dic_lists(sTSFileBaseName, coTranslateSummaries) \n\t\tend\n\n\t\t#PP.pp(coTranslateDicLists, STDERR)\n\t\t#STDERR.puts coTranslateDicLists\n\t\t# modified by takeru on 2012.5.2\n\t\t# modified by takeru on 2012.5.12\n\t\t#coTranslateDicLists.create_dic_lists(sTargetTSFilePath, coTranslateSummaries) \n\t\t\n\t\tdoc = nil\n\t\t#File.open(sTSFilePath) {|xmlfile|\n\t\t#\tdoc = REXML::Document.new(xmlfile)\n\t\t#}\n\t\t#nTotalCount = TranslateTsLIB.traverse_count_translate_tag(doc.root)\n\t\t#nCount = traverse_install_keyword(coTranslateDicLists, sLang, doc.root, nTotalCount, 0)\n\n\t\trexmlDocFr = nil\n\t\trexmlDocEn = nil\n\t\trexmlDocJa = nil\n#\t\tSTDOUT.puts \"Check2:#{sTSFilePath}\"\n\t\tif File.exist?(sFrTSFilePath) == true then\n\t\t\tFile.open(sFrTSFilePath) do |sXmlFile|\n\t\t\t\t#STDERR.puts sXmlFile\n\t\t\t\trexmlDocFr = REXML::Document.new(sXmlFile)\n\t\t\tend\n\t\telse\n\t\t\trexmlDocFr = REXML::Document.new(\"\")\n\t\tend\n\t\tif File.exist?(sEnTSFilePath) == true then\n\t\t\tFile.open(sEnTSFilePath) do |sXmlFile|\n\t\t\t\t#STDERR.puts sXmlFile\n\t\t\t\trexmlDocEn = REXML::Document.new(sXmlFile)\n\t\t\tend\n\t\telse\n\t\t\trexmlDocEn = REXML::Document.new(\"\")\n\t\tend\n\t\tif File.exist?(sJaTSFilePath) == true then\n\t\t\tFile.open(sJaTSFilePath) do |sXmlFile|\n\t\t\t\t#STDERR.puts sXmlFile\n\t\t\t\trexmlDocJa = REXML::Document.new(sXmlFile)\n\t\t\tend\n\t\telse\n\t\t\trexmlDocJa = REXML::Document.new(\"\")\n\t\tend\n\t\tTranslateTsLIB.make_dic_files_from_current_version(coTranslateDicLists, rexmlDocFr, rexmlDocEn, rexmlDocJa)\n\n\t\tPP.pp(coTranslateDicLists, STDERR)\n\t\t#STDERR.puts coTranslateDicListC\n\t\thQmFileBaseNamePath[sTSFileBaseName] = true\n\n\t\treturn true\n\n\tend",
"def project=(_arg0); end",
"def translator_for(t_key, template = nil, parameters = nil)\n o_translator = translators[t_key]\n if template\n translator = Translator.new(template,\n :parameters => parameters)\n if o_translator\n o_translator.flagged.each do |i|\n translator.flag_ref(i)\n end\n end\n translators[t_key] = translator\n o_translator = translator\n else\n unless o_translator\n o_translator = Translator.new({},\n :parameters => {})\n end\n end\n o_translator\n end",
"def transitive_tags=(_arg0); end",
"def build\n @values.fetch('ai.application.build') { \n @values['ai.application.build'] = nil\n }\n end"
] |
[
"0.6883647",
"0.6533848",
"0.63228124",
"0.6285692",
"0.61541957",
"0.6106972",
"0.60572135",
"0.60572135",
"0.6044818",
"0.5934256",
"0.58429533",
"0.57962584",
"0.57621515",
"0.56773853",
"0.56450874",
"0.5641148",
"0.56402266",
"0.56377953",
"0.56377953",
"0.56377953",
"0.56377953",
"0.563193",
"0.5603648",
"0.5603648",
"0.5603648",
"0.5603648",
"0.5603648",
"0.5603648",
"0.5603648",
"0.5603648",
"0.5539893",
"0.5515746",
"0.5506458",
"0.5506458",
"0.5506458",
"0.5506458",
"0.5483055",
"0.5478138",
"0.5478138",
"0.5478138",
"0.5478138",
"0.54689604",
"0.5438438",
"0.54147893",
"0.54147893",
"0.5396942",
"0.53882873",
"0.53882873",
"0.538508",
"0.538508",
"0.538508",
"0.538508",
"0.53616184",
"0.5325575",
"0.5307658",
"0.5285696",
"0.52836215",
"0.5277548",
"0.5277548",
"0.5277548",
"0.5277548",
"0.5277409",
"0.5276492",
"0.5244269",
"0.52338994",
"0.5225921",
"0.5225921",
"0.5225921",
"0.52102983",
"0.52075773",
"0.52075773",
"0.52075773",
"0.52075773",
"0.51929444",
"0.519034",
"0.51851165",
"0.5178272",
"0.5177214",
"0.5177214",
"0.5175146",
"0.5170643",
"0.51623094",
"0.51618916",
"0.5157075",
"0.51559997",
"0.51474744",
"0.5135601",
"0.512349",
"0.51233244",
"0.51233244",
"0.51216316",
"0.51184595",
"0.51173496",
"0.5098373",
"0.50958216",
"0.5095469",
"0.50897473",
"0.5055671",
"0.5055595",
"0.50555706",
"0.5046569"
] |
0.0
|
-1
|
(This method is generated in Translator_defaultbuildImpl)
|
def set_name(v)
Saklient::Util::validate_type(v, 'String')
@m_name = v
@n_name = true
return @m_name
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def translation_target\n super\n end",
"def build; end",
"def translations; end",
"def init_translations; end",
"def build=(_arg0); end",
"def build\r\n raise \"Not implemented\"\r\n end",
"def build\r\n end",
"def build\r\n end",
"def build\n end",
"def label_translation; end",
"def build!\n end",
"def create_translations\n end",
"def translatable\n self._translatable[base_name]\n end",
"def translate(settings); end",
"def translations_hash; end",
"def build\n end",
"def setup_mass_copy_translations\n end",
"def _lex_trans_keys=(_arg0); end",
"def _lex_trans_keys=(_arg0); end",
"def _lex_trans_keys=(_arg0); end",
"def _lex_trans_keys=(_arg0); end",
"def private; end",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translatable\n self._translatable[base_name] ||= []\n end",
"def build(params); end",
"def _lex_trans_keys; end",
"def _lex_trans_keys; end",
"def _lex_trans_keys; end",
"def _lex_trans_keys; end",
"def translate!( *args )\n super( *args )\n reset_positions_inside\n end",
"def _lex_trans_actions; end",
"def _lex_trans_actions; end",
"def _lex_trans_actions; end",
"def _lex_trans_actions; end",
"def build\n method_proxy(:build)\n\n true\n end",
"def create_translation(other)\n end",
"def definition_builder; end",
"def definition_builder; end",
"def build(**)\n raise NotImplementedError\n end",
"def lang=(_arg0); end",
"def lang=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def make; end",
"def translate q, target=@target_lang, source=@source_lang\n return \"[#{source}->#{target}]#{q.to_s}\"\n end",
"def build_script\n raise NotImplementedError\n end",
"def translator\n @translator ||= Translator.new\n end",
"def set_translation_target(opts)\n opts = check_params(opts,[:targets])\n super(opts)\n end",
"def build(*args)\n raise \"Method 'build' not implemented for #{self.class.name}\"\n end",
"def translate(eng_word) # here call to Max's ending code\n Multitran.translate(eng_word)\n end",
"def _lex_trans_targs; end",
"def _lex_trans_targs; end",
"def _lex_trans_targs; end",
"def _lex_trans_targs; end",
"def translate(*args, **opts); end",
"def build_html\n # the first one should not use a locale, for the default:\n generate_all_html_pages\n\n # now translate, if necessary:\n if translation.should_translate?\n translation.prepare\n translation.available_locales.each do |locale|\n translation.current_locale = locale\n generate_all_html_pages\n end\n end\n end",
"def builder; end",
"def builder; end",
"def builder; end",
"def build_gem; end",
"def _lex_trans_targs=(_arg0); end",
"def _lex_trans_targs=(_arg0); end",
"def _lex_trans_targs=(_arg0); end",
"def _lex_trans_targs=(_arg0); end",
"def create\n @user = current_user\n @project = Project.find(params[:project_id])\n @preferedlang = Language.find_by_id(@project.source_lang_id)\n @slanguages = Language.where(\"id != ?\", @preferedlang.id).order('iso_code asc') \n @slanguages.unshift(@preferedlang)\n #from railsrecipes recipe 22 - refactor\n # @user = current_user\n\n\n @mostpopulartarlang = Language.find_by_id(@project.translations.maximum(\"source_lang_id\"))\n if @mostpopulartarlang\n @tlanguages = Language.where(\"id != ?\", @mostpopulartarlang.id).order('iso_code asc')\n @tlanguages.unshift(@mostpopulartarlang)\n else\n @tlanguages = Language.order('iso_code desc')\n end\n\n\n @translation = @project.translations.build(params[:translation])\n @translation.owner_id = @user.id\n\n# @project = Project.find(params[:id])\n\n# @translation = Translation.new(params[:translation])\n# @translation.owner_id = current_user.id\n# @translation.project_id = Project.find_by_id(params[:project_id]).id\n # @user = User.find(params[:user_id])\n # @project = Project.find(params[:project_id])\n # @translation = Translation.new(params[:translation])\n # @project = current_user.projects.build\n # @translation = @project.translations.build\n # @user = current_user\n # @project = Project.find_by_user_id(@user)\n # @translation = @project.translations.build(params[:translation])\n @languages = Language.all(:order => 'iso_code')\n # #process information from checkbox\n\n if @translation.save\n flash[:notice] = \"Translation was successfully created\"\n # redirect_to user_project_translations_path(@user, @project)\n redirect_to user_project_path(current_user, @project)\n else\n render 'new'\n end\nend",
"def target_version=(_arg0); end",
"def translate(input_text, src_lang, target_lang)\n raise \"Not Implemented. Class #{self.class.name} doesn't implement translate\"\n end",
"def process_and_build_components \n end",
"def build_method\nend",
"def build_method\nend",
"def originalsourceform; end",
"def transforms; end",
"def rebuild\n build addl_cmake_bld_args: '--clean-first'\n end",
"def lang(orig); end",
"def initialize b\n @build = b\n end",
"def internal; end",
"def after_build\n cleanup_nontarget_files\n run_help_indexer\nend",
"def inject_translatable_block\n inject_into_class model_path, class_name, generate_translatable_block\n end",
"def target; end",
"def target; end",
"def inspect\n \"#<Translations (#{backend}) @names=#{names.join(\", \")}>\"\n end",
"def command_builder; end",
"def translate\n if self.products && self.products.first\n ContentTranslation.auto_translate(self, self.products.first.brand)\n end\n end",
"def check_starting(_lang_result)\n end",
"def build_with_lto(pass_manager, internalize = false, run_inliner = false)\n raise \"build_with_lto is not currently supported\"\n end",
"def mozart_german; end",
"def translated_msg(translate, message, src_lang, target_lang)\n return message unless translate \n use_src = nil \n if (src_lang.nil? || src_lang.empty?)\n # We don't need to infer again and again\n begin\n @inferred_src_lang ||= infer_languages.first\n rescue StandardError => e \n raise LangDetectionFailureException.new(\"Failed to infer language due to #{e.message}\")\n end\n use_src = @inferred_src_lang\n else\n use_src = src_lang\n end\n return message if use_src.eql?(target_lang)\n @translator.translate(message, use_src, target_lang)\n end",
"def make_dic_lists_class_from_ts_from_current_version(sFrTSFilePath, sEnTSFilePath, sJaTSFilePath, hQmFileBaseNamePath=Hash.new(), coTranslateSummaries=TranslateSummaries.new())\n#\t\tSTDOUT.puts \"Check1:#{sTSFilePath}\"\n\t\t#return false unless sFrTSFilePath =~ /_msg_(.+?)\\.ts$/\n\t\treturn false unless sFrTSFilePath =~ /_(\\w{2})\\.ts$/\n\t\tsLang = $1.to_s\n\t\tsTSFileBaseName_temp = File.basename(sFrTSFilePath).gsub(/\\.ts$/, \"\")\n\t\t#sTSFileBaseName = sTSFileBaseName_temp.gsub(/_msg_(en|ja)$/, \"_msg_fr\")\n\t\tsTSFileBaseName = sTSFileBaseName_temp.gsub(/_(en|ja)$/, \"_fr\")\n\t\t#return true if hQmFileBaseNamePath[sTSFileBaseName] == true\n\t\tsTargetTSFilePath = sFrTSFilePath.gsub(/\\.ts$/, \"\")\n\t\t#sTargetTSFilePath = sTargetTSFilePath.gsub(/_msg_(en|ja)$/, \"_msg_fr\")\n\t\tsTargetTSFilePath = sTargetTSFilePath.gsub(/_(en|ja)$/, \"_fr\")\n\t\t# modified by takeru on 2012.5.2\n\t\t# modified by takeru on 2012.5.12\n\t\tcoTranslateDicLists = coTranslateSummaries[sTSFileBaseName]\n\t\t#coTranslateDicLists = coTranslateSummaries[sTargetTSFilePath]\n\t\tif coTranslateDicLists == nil then\n\t\t\tcoTranslateDicLists = TranslateDicLists.new()\n\t\t\t#coTranslateDicLists.create_dic_lists(sTSFileBaseName, coTranslateSummaries) \n\t\t\tcoTranslateDicLists.create_dic_lists(sTSFileBaseName, coTranslateSummaries) \n\t\tend\n\n\t\t#PP.pp(coTranslateDicLists, STDERR)\n\t\t#STDERR.puts coTranslateDicLists\n\t\t# modified by takeru on 2012.5.2\n\t\t# modified by takeru on 2012.5.12\n\t\t#coTranslateDicLists.create_dic_lists(sTargetTSFilePath, coTranslateSummaries) \n\t\t\n\t\tdoc = nil\n\t\t#File.open(sTSFilePath) {|xmlfile|\n\t\t#\tdoc = REXML::Document.new(xmlfile)\n\t\t#}\n\t\t#nTotalCount = TranslateTsLIB.traverse_count_translate_tag(doc.root)\n\t\t#nCount = traverse_install_keyword(coTranslateDicLists, sLang, doc.root, nTotalCount, 0)\n\n\t\trexmlDocFr = nil\n\t\trexmlDocEn = nil\n\t\trexmlDocJa = nil\n#\t\tSTDOUT.puts \"Check2:#{sTSFilePath}\"\n\t\tif File.exist?(sFrTSFilePath) == true then\n\t\t\tFile.open(sFrTSFilePath) do |sXmlFile|\n\t\t\t\t#STDERR.puts sXmlFile\n\t\t\t\trexmlDocFr = REXML::Document.new(sXmlFile)\n\t\t\tend\n\t\telse\n\t\t\trexmlDocFr = REXML::Document.new(\"\")\n\t\tend\n\t\tif File.exist?(sEnTSFilePath) == true then\n\t\t\tFile.open(sEnTSFilePath) do |sXmlFile|\n\t\t\t\t#STDERR.puts sXmlFile\n\t\t\t\trexmlDocEn = REXML::Document.new(sXmlFile)\n\t\t\tend\n\t\telse\n\t\t\trexmlDocEn = REXML::Document.new(\"\")\n\t\tend\n\t\tif File.exist?(sJaTSFilePath) == true then\n\t\t\tFile.open(sJaTSFilePath) do |sXmlFile|\n\t\t\t\t#STDERR.puts sXmlFile\n\t\t\t\trexmlDocJa = REXML::Document.new(sXmlFile)\n\t\t\tend\n\t\telse\n\t\t\trexmlDocJa = REXML::Document.new(\"\")\n\t\tend\n\t\tTranslateTsLIB.make_dic_files_from_current_version(coTranslateDicLists, rexmlDocFr, rexmlDocEn, rexmlDocJa)\n\n\t\tPP.pp(coTranslateDicLists, STDERR)\n\t\t#STDERR.puts coTranslateDicListC\n\t\thQmFileBaseNamePath[sTSFileBaseName] = true\n\n\t\treturn true\n\n\tend",
"def transitive_tags=(_arg0); end",
"def project=(_arg0); end",
"def translator_for(t_key, template = nil, parameters = nil)\n o_translator = translators[t_key]\n if template\n translator = Translator.new(template,\n :parameters => parameters)\n if o_translator\n o_translator.flagged.each do |i|\n translator.flag_ref(i)\n end\n end\n translators[t_key] = translator\n o_translator = translator\n else\n unless o_translator\n o_translator = Translator.new({},\n :parameters => {})\n end\n end\n o_translator\n end",
"def build\n @values.fetch('ai.application.build') { \n @values['ai.application.build'] = nil\n }\n end"
] |
[
"0.6882901",
"0.653592",
"0.63217664",
"0.6284657",
"0.61551243",
"0.61091876",
"0.605949",
"0.605949",
"0.60470265",
"0.59335953",
"0.5844821",
"0.5795114",
"0.5761158",
"0.56754434",
"0.56447375",
"0.5643845",
"0.5639414",
"0.5635945",
"0.5635945",
"0.5635945",
"0.5635945",
"0.563406",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5539237",
"0.5517182",
"0.5505295",
"0.5505295",
"0.5505295",
"0.5505295",
"0.54820263",
"0.5475904",
"0.5475904",
"0.5475904",
"0.5475904",
"0.547027",
"0.5437076",
"0.54157394",
"0.54157394",
"0.5398866",
"0.5386972",
"0.5386972",
"0.53822404",
"0.53822404",
"0.53822404",
"0.53822404",
"0.5361637",
"0.5323374",
"0.5308725",
"0.52835053",
"0.5282656",
"0.52782214",
"0.5275988",
"0.5274997",
"0.5274997",
"0.5274997",
"0.5274997",
"0.5241623",
"0.52328515",
"0.52266777",
"0.52266777",
"0.52266777",
"0.52109337",
"0.5204789",
"0.5204789",
"0.5204789",
"0.5204789",
"0.5192355",
"0.5190386",
"0.51832217",
"0.5179127",
"0.51784027",
"0.51784027",
"0.5175266",
"0.5170668",
"0.51630884",
"0.5160946",
"0.5158187",
"0.51568115",
"0.51486707",
"0.51343715",
"0.51235247",
"0.51235247",
"0.5122161",
"0.51212776",
"0.5117833",
"0.5116379",
"0.50977826",
"0.5095889",
"0.50931627",
"0.5088532",
"0.5056332",
"0.50559413",
"0.5053341",
"0.5048526"
] |
0.0
|
-1
|
(This method is generated in Translator_defaultbuildImpl)
|
def get_description
return @m_description
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def translation_target\n super\n end",
"def build; end",
"def translations; end",
"def init_translations; end",
"def build=(_arg0); end",
"def build\r\n raise \"Not implemented\"\r\n end",
"def build\r\n end",
"def build\r\n end",
"def build\n end",
"def label_translation; end",
"def build!\n end",
"def create_translations\n end",
"def translatable\n self._translatable[base_name]\n end",
"def translate(settings); end",
"def translations_hash; end",
"def build\n end",
"def setup_mass_copy_translations\n end",
"def _lex_trans_keys=(_arg0); end",
"def _lex_trans_keys=(_arg0); end",
"def _lex_trans_keys=(_arg0); end",
"def _lex_trans_keys=(_arg0); end",
"def private; end",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translatable\n self._translatable[base_name] ||= []\n end",
"def build(params); end",
"def _lex_trans_keys; end",
"def _lex_trans_keys; end",
"def _lex_trans_keys; end",
"def _lex_trans_keys; end",
"def translate!( *args )\n super( *args )\n reset_positions_inside\n end",
"def _lex_trans_actions; end",
"def _lex_trans_actions; end",
"def _lex_trans_actions; end",
"def _lex_trans_actions; end",
"def build\n method_proxy(:build)\n\n true\n end",
"def create_translation(other)\n end",
"def definition_builder; end",
"def definition_builder; end",
"def build(**)\n raise NotImplementedError\n end",
"def lang=(_arg0); end",
"def lang=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def make; end",
"def translate q, target=@target_lang, source=@source_lang\n return \"[#{source}->#{target}]#{q.to_s}\"\n end",
"def build_script\n raise NotImplementedError\n end",
"def translator\n @translator ||= Translator.new\n end",
"def set_translation_target(opts)\n opts = check_params(opts,[:targets])\n super(opts)\n end",
"def build(*args)\n raise \"Method 'build' not implemented for #{self.class.name}\"\n end",
"def translate(eng_word) # here call to Max's ending code\n Multitran.translate(eng_word)\n end",
"def _lex_trans_targs; end",
"def _lex_trans_targs; end",
"def _lex_trans_targs; end",
"def _lex_trans_targs; end",
"def translate(*args, **opts); end",
"def build_html\n # the first one should not use a locale, for the default:\n generate_all_html_pages\n\n # now translate, if necessary:\n if translation.should_translate?\n translation.prepare\n translation.available_locales.each do |locale|\n translation.current_locale = locale\n generate_all_html_pages\n end\n end\n end",
"def builder; end",
"def builder; end",
"def builder; end",
"def build_gem; end",
"def _lex_trans_targs=(_arg0); end",
"def _lex_trans_targs=(_arg0); end",
"def _lex_trans_targs=(_arg0); end",
"def _lex_trans_targs=(_arg0); end",
"def create\n @user = current_user\n @project = Project.find(params[:project_id])\n @preferedlang = Language.find_by_id(@project.source_lang_id)\n @slanguages = Language.where(\"id != ?\", @preferedlang.id).order('iso_code asc') \n @slanguages.unshift(@preferedlang)\n #from railsrecipes recipe 22 - refactor\n # @user = current_user\n\n\n @mostpopulartarlang = Language.find_by_id(@project.translations.maximum(\"source_lang_id\"))\n if @mostpopulartarlang\n @tlanguages = Language.where(\"id != ?\", @mostpopulartarlang.id).order('iso_code asc')\n @tlanguages.unshift(@mostpopulartarlang)\n else\n @tlanguages = Language.order('iso_code desc')\n end\n\n\n @translation = @project.translations.build(params[:translation])\n @translation.owner_id = @user.id\n\n# @project = Project.find(params[:id])\n\n# @translation = Translation.new(params[:translation])\n# @translation.owner_id = current_user.id\n# @translation.project_id = Project.find_by_id(params[:project_id]).id\n # @user = User.find(params[:user_id])\n # @project = Project.find(params[:project_id])\n # @translation = Translation.new(params[:translation])\n # @project = current_user.projects.build\n # @translation = @project.translations.build\n # @user = current_user\n # @project = Project.find_by_user_id(@user)\n # @translation = @project.translations.build(params[:translation])\n @languages = Language.all(:order => 'iso_code')\n # #process information from checkbox\n\n if @translation.save\n flash[:notice] = \"Translation was successfully created\"\n # redirect_to user_project_translations_path(@user, @project)\n redirect_to user_project_path(current_user, @project)\n else\n render 'new'\n end\nend",
"def target_version=(_arg0); end",
"def translate(input_text, src_lang, target_lang)\n raise \"Not Implemented. Class #{self.class.name} doesn't implement translate\"\n end",
"def process_and_build_components \n end",
"def build_method\nend",
"def build_method\nend",
"def originalsourceform; end",
"def transforms; end",
"def rebuild\n build addl_cmake_bld_args: '--clean-first'\n end",
"def lang(orig); end",
"def initialize b\n @build = b\n end",
"def internal; end",
"def after_build\n cleanup_nontarget_files\n run_help_indexer\nend",
"def inject_translatable_block\n inject_into_class model_path, class_name, generate_translatable_block\n end",
"def target; end",
"def target; end",
"def inspect\n \"#<Translations (#{backend}) @names=#{names.join(\", \")}>\"\n end",
"def command_builder; end",
"def translate\n if self.products && self.products.first\n ContentTranslation.auto_translate(self, self.products.first.brand)\n end\n end",
"def check_starting(_lang_result)\n end",
"def build_with_lto(pass_manager, internalize = false, run_inliner = false)\n raise \"build_with_lto is not currently supported\"\n end",
"def mozart_german; end",
"def translated_msg(translate, message, src_lang, target_lang)\n return message unless translate \n use_src = nil \n if (src_lang.nil? || src_lang.empty?)\n # We don't need to infer again and again\n begin\n @inferred_src_lang ||= infer_languages.first\n rescue StandardError => e \n raise LangDetectionFailureException.new(\"Failed to infer language due to #{e.message}\")\n end\n use_src = @inferred_src_lang\n else\n use_src = src_lang\n end\n return message if use_src.eql?(target_lang)\n @translator.translate(message, use_src, target_lang)\n end",
"def make_dic_lists_class_from_ts_from_current_version(sFrTSFilePath, sEnTSFilePath, sJaTSFilePath, hQmFileBaseNamePath=Hash.new(), coTranslateSummaries=TranslateSummaries.new())\n#\t\tSTDOUT.puts \"Check1:#{sTSFilePath}\"\n\t\t#return false unless sFrTSFilePath =~ /_msg_(.+?)\\.ts$/\n\t\treturn false unless sFrTSFilePath =~ /_(\\w{2})\\.ts$/\n\t\tsLang = $1.to_s\n\t\tsTSFileBaseName_temp = File.basename(sFrTSFilePath).gsub(/\\.ts$/, \"\")\n\t\t#sTSFileBaseName = sTSFileBaseName_temp.gsub(/_msg_(en|ja)$/, \"_msg_fr\")\n\t\tsTSFileBaseName = sTSFileBaseName_temp.gsub(/_(en|ja)$/, \"_fr\")\n\t\t#return true if hQmFileBaseNamePath[sTSFileBaseName] == true\n\t\tsTargetTSFilePath = sFrTSFilePath.gsub(/\\.ts$/, \"\")\n\t\t#sTargetTSFilePath = sTargetTSFilePath.gsub(/_msg_(en|ja)$/, \"_msg_fr\")\n\t\tsTargetTSFilePath = sTargetTSFilePath.gsub(/_(en|ja)$/, \"_fr\")\n\t\t# modified by takeru on 2012.5.2\n\t\t# modified by takeru on 2012.5.12\n\t\tcoTranslateDicLists = coTranslateSummaries[sTSFileBaseName]\n\t\t#coTranslateDicLists = coTranslateSummaries[sTargetTSFilePath]\n\t\tif coTranslateDicLists == nil then\n\t\t\tcoTranslateDicLists = TranslateDicLists.new()\n\t\t\t#coTranslateDicLists.create_dic_lists(sTSFileBaseName, coTranslateSummaries) \n\t\t\tcoTranslateDicLists.create_dic_lists(sTSFileBaseName, coTranslateSummaries) \n\t\tend\n\n\t\t#PP.pp(coTranslateDicLists, STDERR)\n\t\t#STDERR.puts coTranslateDicLists\n\t\t# modified by takeru on 2012.5.2\n\t\t# modified by takeru on 2012.5.12\n\t\t#coTranslateDicLists.create_dic_lists(sTargetTSFilePath, coTranslateSummaries) \n\t\t\n\t\tdoc = nil\n\t\t#File.open(sTSFilePath) {|xmlfile|\n\t\t#\tdoc = REXML::Document.new(xmlfile)\n\t\t#}\n\t\t#nTotalCount = TranslateTsLIB.traverse_count_translate_tag(doc.root)\n\t\t#nCount = traverse_install_keyword(coTranslateDicLists, sLang, doc.root, nTotalCount, 0)\n\n\t\trexmlDocFr = nil\n\t\trexmlDocEn = nil\n\t\trexmlDocJa = nil\n#\t\tSTDOUT.puts \"Check2:#{sTSFilePath}\"\n\t\tif File.exist?(sFrTSFilePath) == true then\n\t\t\tFile.open(sFrTSFilePath) do |sXmlFile|\n\t\t\t\t#STDERR.puts sXmlFile\n\t\t\t\trexmlDocFr = REXML::Document.new(sXmlFile)\n\t\t\tend\n\t\telse\n\t\t\trexmlDocFr = REXML::Document.new(\"\")\n\t\tend\n\t\tif File.exist?(sEnTSFilePath) == true then\n\t\t\tFile.open(sEnTSFilePath) do |sXmlFile|\n\t\t\t\t#STDERR.puts sXmlFile\n\t\t\t\trexmlDocEn = REXML::Document.new(sXmlFile)\n\t\t\tend\n\t\telse\n\t\t\trexmlDocEn = REXML::Document.new(\"\")\n\t\tend\n\t\tif File.exist?(sJaTSFilePath) == true then\n\t\t\tFile.open(sJaTSFilePath) do |sXmlFile|\n\t\t\t\t#STDERR.puts sXmlFile\n\t\t\t\trexmlDocJa = REXML::Document.new(sXmlFile)\n\t\t\tend\n\t\telse\n\t\t\trexmlDocJa = REXML::Document.new(\"\")\n\t\tend\n\t\tTranslateTsLIB.make_dic_files_from_current_version(coTranslateDicLists, rexmlDocFr, rexmlDocEn, rexmlDocJa)\n\n\t\tPP.pp(coTranslateDicLists, STDERR)\n\t\t#STDERR.puts coTranslateDicListC\n\t\thQmFileBaseNamePath[sTSFileBaseName] = true\n\n\t\treturn true\n\n\tend",
"def transitive_tags=(_arg0); end",
"def project=(_arg0); end",
"def translator_for(t_key, template = nil, parameters = nil)\n o_translator = translators[t_key]\n if template\n translator = Translator.new(template,\n :parameters => parameters)\n if o_translator\n o_translator.flagged.each do |i|\n translator.flag_ref(i)\n end\n end\n translators[t_key] = translator\n o_translator = translator\n else\n unless o_translator\n o_translator = Translator.new({},\n :parameters => {})\n end\n end\n o_translator\n end",
"def build\n @values.fetch('ai.application.build') { \n @values['ai.application.build'] = nil\n }\n end"
] |
[
"0.6882901",
"0.653592",
"0.63217664",
"0.6284657",
"0.61551243",
"0.61091876",
"0.605949",
"0.605949",
"0.60470265",
"0.59335953",
"0.5844821",
"0.5795114",
"0.5761158",
"0.56754434",
"0.56447375",
"0.5643845",
"0.5639414",
"0.5635945",
"0.5635945",
"0.5635945",
"0.5635945",
"0.563406",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5539237",
"0.5517182",
"0.5505295",
"0.5505295",
"0.5505295",
"0.5505295",
"0.54820263",
"0.5475904",
"0.5475904",
"0.5475904",
"0.5475904",
"0.547027",
"0.5437076",
"0.54157394",
"0.54157394",
"0.5398866",
"0.5386972",
"0.5386972",
"0.53822404",
"0.53822404",
"0.53822404",
"0.53822404",
"0.5361637",
"0.5323374",
"0.5308725",
"0.52835053",
"0.5282656",
"0.52782214",
"0.5275988",
"0.5274997",
"0.5274997",
"0.5274997",
"0.5274997",
"0.5241623",
"0.52328515",
"0.52266777",
"0.52266777",
"0.52266777",
"0.52109337",
"0.5204789",
"0.5204789",
"0.5204789",
"0.5204789",
"0.5192355",
"0.5190386",
"0.51832217",
"0.5179127",
"0.51784027",
"0.51784027",
"0.5175266",
"0.5170668",
"0.51630884",
"0.5160946",
"0.5158187",
"0.51568115",
"0.51486707",
"0.51343715",
"0.51235247",
"0.51235247",
"0.5122161",
"0.51212776",
"0.5117833",
"0.5116379",
"0.50977826",
"0.5095889",
"0.50931627",
"0.5088532",
"0.5056332",
"0.50559413",
"0.5053341",
"0.5048526"
] |
0.0
|
-1
|
(This method is generated in Translator_defaultbuildImpl)
|
def set_description(v)
Saklient::Util::validate_type(v, 'String')
@m_description = v
@n_description = true
return @m_description
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def translation_target\n super\n end",
"def build; end",
"def translations; end",
"def init_translations; end",
"def build=(_arg0); end",
"def build\r\n raise \"Not implemented\"\r\n end",
"def build\r\n end",
"def build\r\n end",
"def build\n end",
"def label_translation; end",
"def build!\n end",
"def create_translations\n end",
"def translatable\n self._translatable[base_name]\n end",
"def translate(settings); end",
"def translations_hash; end",
"def build\n end",
"def setup_mass_copy_translations\n end",
"def _lex_trans_keys=(_arg0); end",
"def _lex_trans_keys=(_arg0); end",
"def _lex_trans_keys=(_arg0); end",
"def _lex_trans_keys=(_arg0); end",
"def private; end",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translatable\n self._translatable[base_name] ||= []\n end",
"def build(params); end",
"def _lex_trans_keys; end",
"def _lex_trans_keys; end",
"def _lex_trans_keys; end",
"def _lex_trans_keys; end",
"def translate!( *args )\n super( *args )\n reset_positions_inside\n end",
"def _lex_trans_actions; end",
"def _lex_trans_actions; end",
"def _lex_trans_actions; end",
"def _lex_trans_actions; end",
"def build\n method_proxy(:build)\n\n true\n end",
"def create_translation(other)\n end",
"def definition_builder; end",
"def definition_builder; end",
"def build(**)\n raise NotImplementedError\n end",
"def lang=(_arg0); end",
"def lang=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def make; end",
"def translate q, target=@target_lang, source=@source_lang\n return \"[#{source}->#{target}]#{q.to_s}\"\n end",
"def build_script\n raise NotImplementedError\n end",
"def translator\n @translator ||= Translator.new\n end",
"def set_translation_target(opts)\n opts = check_params(opts,[:targets])\n super(opts)\n end",
"def build(*args)\n raise \"Method 'build' not implemented for #{self.class.name}\"\n end",
"def translate(eng_word) # here call to Max's ending code\n Multitran.translate(eng_word)\n end",
"def _lex_trans_targs; end",
"def _lex_trans_targs; end",
"def _lex_trans_targs; end",
"def _lex_trans_targs; end",
"def translate(*args, **opts); end",
"def build_html\n # the first one should not use a locale, for the default:\n generate_all_html_pages\n\n # now translate, if necessary:\n if translation.should_translate?\n translation.prepare\n translation.available_locales.each do |locale|\n translation.current_locale = locale\n generate_all_html_pages\n end\n end\n end",
"def builder; end",
"def builder; end",
"def builder; end",
"def build_gem; end",
"def _lex_trans_targs=(_arg0); end",
"def _lex_trans_targs=(_arg0); end",
"def _lex_trans_targs=(_arg0); end",
"def _lex_trans_targs=(_arg0); end",
"def create\n @user = current_user\n @project = Project.find(params[:project_id])\n @preferedlang = Language.find_by_id(@project.source_lang_id)\n @slanguages = Language.where(\"id != ?\", @preferedlang.id).order('iso_code asc') \n @slanguages.unshift(@preferedlang)\n #from railsrecipes recipe 22 - refactor\n # @user = current_user\n\n\n @mostpopulartarlang = Language.find_by_id(@project.translations.maximum(\"source_lang_id\"))\n if @mostpopulartarlang\n @tlanguages = Language.where(\"id != ?\", @mostpopulartarlang.id).order('iso_code asc')\n @tlanguages.unshift(@mostpopulartarlang)\n else\n @tlanguages = Language.order('iso_code desc')\n end\n\n\n @translation = @project.translations.build(params[:translation])\n @translation.owner_id = @user.id\n\n# @project = Project.find(params[:id])\n\n# @translation = Translation.new(params[:translation])\n# @translation.owner_id = current_user.id\n# @translation.project_id = Project.find_by_id(params[:project_id]).id\n # @user = User.find(params[:user_id])\n # @project = Project.find(params[:project_id])\n # @translation = Translation.new(params[:translation])\n # @project = current_user.projects.build\n # @translation = @project.translations.build\n # @user = current_user\n # @project = Project.find_by_user_id(@user)\n # @translation = @project.translations.build(params[:translation])\n @languages = Language.all(:order => 'iso_code')\n # #process information from checkbox\n\n if @translation.save\n flash[:notice] = \"Translation was successfully created\"\n # redirect_to user_project_translations_path(@user, @project)\n redirect_to user_project_path(current_user, @project)\n else\n render 'new'\n end\nend",
"def target_version=(_arg0); end",
"def translate(input_text, src_lang, target_lang)\n raise \"Not Implemented. Class #{self.class.name} doesn't implement translate\"\n end",
"def process_and_build_components \n end",
"def build_method\nend",
"def build_method\nend",
"def originalsourceform; end",
"def transforms; end",
"def rebuild\n build addl_cmake_bld_args: '--clean-first'\n end",
"def lang(orig); end",
"def initialize b\n @build = b\n end",
"def internal; end",
"def after_build\n cleanup_nontarget_files\n run_help_indexer\nend",
"def inject_translatable_block\n inject_into_class model_path, class_name, generate_translatable_block\n end",
"def target; end",
"def target; end",
"def inspect\n \"#<Translations (#{backend}) @names=#{names.join(\", \")}>\"\n end",
"def command_builder; end",
"def translate\n if self.products && self.products.first\n ContentTranslation.auto_translate(self, self.products.first.brand)\n end\n end",
"def check_starting(_lang_result)\n end",
"def build_with_lto(pass_manager, internalize = false, run_inliner = false)\n raise \"build_with_lto is not currently supported\"\n end",
"def mozart_german; end",
"def translated_msg(translate, message, src_lang, target_lang)\n return message unless translate \n use_src = nil \n if (src_lang.nil? || src_lang.empty?)\n # We don't need to infer again and again\n begin\n @inferred_src_lang ||= infer_languages.first\n rescue StandardError => e \n raise LangDetectionFailureException.new(\"Failed to infer language due to #{e.message}\")\n end\n use_src = @inferred_src_lang\n else\n use_src = src_lang\n end\n return message if use_src.eql?(target_lang)\n @translator.translate(message, use_src, target_lang)\n end",
"def make_dic_lists_class_from_ts_from_current_version(sFrTSFilePath, sEnTSFilePath, sJaTSFilePath, hQmFileBaseNamePath=Hash.new(), coTranslateSummaries=TranslateSummaries.new())\n#\t\tSTDOUT.puts \"Check1:#{sTSFilePath}\"\n\t\t#return false unless sFrTSFilePath =~ /_msg_(.+?)\\.ts$/\n\t\treturn false unless sFrTSFilePath =~ /_(\\w{2})\\.ts$/\n\t\tsLang = $1.to_s\n\t\tsTSFileBaseName_temp = File.basename(sFrTSFilePath).gsub(/\\.ts$/, \"\")\n\t\t#sTSFileBaseName = sTSFileBaseName_temp.gsub(/_msg_(en|ja)$/, \"_msg_fr\")\n\t\tsTSFileBaseName = sTSFileBaseName_temp.gsub(/_(en|ja)$/, \"_fr\")\n\t\t#return true if hQmFileBaseNamePath[sTSFileBaseName] == true\n\t\tsTargetTSFilePath = sFrTSFilePath.gsub(/\\.ts$/, \"\")\n\t\t#sTargetTSFilePath = sTargetTSFilePath.gsub(/_msg_(en|ja)$/, \"_msg_fr\")\n\t\tsTargetTSFilePath = sTargetTSFilePath.gsub(/_(en|ja)$/, \"_fr\")\n\t\t# modified by takeru on 2012.5.2\n\t\t# modified by takeru on 2012.5.12\n\t\tcoTranslateDicLists = coTranslateSummaries[sTSFileBaseName]\n\t\t#coTranslateDicLists = coTranslateSummaries[sTargetTSFilePath]\n\t\tif coTranslateDicLists == nil then\n\t\t\tcoTranslateDicLists = TranslateDicLists.new()\n\t\t\t#coTranslateDicLists.create_dic_lists(sTSFileBaseName, coTranslateSummaries) \n\t\t\tcoTranslateDicLists.create_dic_lists(sTSFileBaseName, coTranslateSummaries) \n\t\tend\n\n\t\t#PP.pp(coTranslateDicLists, STDERR)\n\t\t#STDERR.puts coTranslateDicLists\n\t\t# modified by takeru on 2012.5.2\n\t\t# modified by takeru on 2012.5.12\n\t\t#coTranslateDicLists.create_dic_lists(sTargetTSFilePath, coTranslateSummaries) \n\t\t\n\t\tdoc = nil\n\t\t#File.open(sTSFilePath) {|xmlfile|\n\t\t#\tdoc = REXML::Document.new(xmlfile)\n\t\t#}\n\t\t#nTotalCount = TranslateTsLIB.traverse_count_translate_tag(doc.root)\n\t\t#nCount = traverse_install_keyword(coTranslateDicLists, sLang, doc.root, nTotalCount, 0)\n\n\t\trexmlDocFr = nil\n\t\trexmlDocEn = nil\n\t\trexmlDocJa = nil\n#\t\tSTDOUT.puts \"Check2:#{sTSFilePath}\"\n\t\tif File.exist?(sFrTSFilePath) == true then\n\t\t\tFile.open(sFrTSFilePath) do |sXmlFile|\n\t\t\t\t#STDERR.puts sXmlFile\n\t\t\t\trexmlDocFr = REXML::Document.new(sXmlFile)\n\t\t\tend\n\t\telse\n\t\t\trexmlDocFr = REXML::Document.new(\"\")\n\t\tend\n\t\tif File.exist?(sEnTSFilePath) == true then\n\t\t\tFile.open(sEnTSFilePath) do |sXmlFile|\n\t\t\t\t#STDERR.puts sXmlFile\n\t\t\t\trexmlDocEn = REXML::Document.new(sXmlFile)\n\t\t\tend\n\t\telse\n\t\t\trexmlDocEn = REXML::Document.new(\"\")\n\t\tend\n\t\tif File.exist?(sJaTSFilePath) == true then\n\t\t\tFile.open(sJaTSFilePath) do |sXmlFile|\n\t\t\t\t#STDERR.puts sXmlFile\n\t\t\t\trexmlDocJa = REXML::Document.new(sXmlFile)\n\t\t\tend\n\t\telse\n\t\t\trexmlDocJa = REXML::Document.new(\"\")\n\t\tend\n\t\tTranslateTsLIB.make_dic_files_from_current_version(coTranslateDicLists, rexmlDocFr, rexmlDocEn, rexmlDocJa)\n\n\t\tPP.pp(coTranslateDicLists, STDERR)\n\t\t#STDERR.puts coTranslateDicListC\n\t\thQmFileBaseNamePath[sTSFileBaseName] = true\n\n\t\treturn true\n\n\tend",
"def transitive_tags=(_arg0); end",
"def project=(_arg0); end",
"def translator_for(t_key, template = nil, parameters = nil)\n o_translator = translators[t_key]\n if template\n translator = Translator.new(template,\n :parameters => parameters)\n if o_translator\n o_translator.flagged.each do |i|\n translator.flag_ref(i)\n end\n end\n translators[t_key] = translator\n o_translator = translator\n else\n unless o_translator\n o_translator = Translator.new({},\n :parameters => {})\n end\n end\n o_translator\n end",
"def build\n @values.fetch('ai.application.build') { \n @values['ai.application.build'] = nil\n }\n end"
] |
[
"0.6882901",
"0.653592",
"0.63217664",
"0.6284657",
"0.61551243",
"0.61091876",
"0.605949",
"0.605949",
"0.60470265",
"0.59335953",
"0.5844821",
"0.5795114",
"0.5761158",
"0.56754434",
"0.56447375",
"0.5643845",
"0.5639414",
"0.5635945",
"0.5635945",
"0.5635945",
"0.5635945",
"0.563406",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5539237",
"0.5517182",
"0.5505295",
"0.5505295",
"0.5505295",
"0.5505295",
"0.54820263",
"0.5475904",
"0.5475904",
"0.5475904",
"0.5475904",
"0.547027",
"0.5437076",
"0.54157394",
"0.54157394",
"0.5398866",
"0.5386972",
"0.5386972",
"0.53822404",
"0.53822404",
"0.53822404",
"0.53822404",
"0.5361637",
"0.5323374",
"0.5308725",
"0.52835053",
"0.5282656",
"0.52782214",
"0.5275988",
"0.5274997",
"0.5274997",
"0.5274997",
"0.5274997",
"0.5241623",
"0.52328515",
"0.52266777",
"0.52266777",
"0.52266777",
"0.52109337",
"0.5204789",
"0.5204789",
"0.5204789",
"0.5204789",
"0.5192355",
"0.5190386",
"0.51832217",
"0.5179127",
"0.51784027",
"0.51784027",
"0.5175266",
"0.5170668",
"0.51630884",
"0.5160946",
"0.5158187",
"0.51568115",
"0.51486707",
"0.51343715",
"0.51235247",
"0.51235247",
"0.5122161",
"0.51212776",
"0.5117833",
"0.5116379",
"0.50977826",
"0.5095889",
"0.50931627",
"0.5088532",
"0.5056332",
"0.50559413",
"0.5053341",
"0.5048526"
] |
0.0
|
-1
|
(This method is generated in Translator_defaultbuildImpl)
|
def get_region
return @m_region
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def translation_target\n super\n end",
"def build; end",
"def translations; end",
"def init_translations; end",
"def build=(_arg0); end",
"def build\r\n raise \"Not implemented\"\r\n end",
"def build\r\n end",
"def build\r\n end",
"def build\n end",
"def label_translation; end",
"def build!\n end",
"def create_translations\n end",
"def translatable\n self._translatable[base_name]\n end",
"def translate(settings); end",
"def translations_hash; end",
"def build\n end",
"def setup_mass_copy_translations\n end",
"def _lex_trans_keys=(_arg0); end",
"def _lex_trans_keys=(_arg0); end",
"def _lex_trans_keys=(_arg0); end",
"def _lex_trans_keys=(_arg0); end",
"def private; end",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translatable\n self._translatable[base_name] ||= []\n end",
"def build(params); end",
"def _lex_trans_keys; end",
"def _lex_trans_keys; end",
"def _lex_trans_keys; end",
"def _lex_trans_keys; end",
"def translate!( *args )\n super( *args )\n reset_positions_inside\n end",
"def _lex_trans_actions; end",
"def _lex_trans_actions; end",
"def _lex_trans_actions; end",
"def _lex_trans_actions; end",
"def build\n method_proxy(:build)\n\n true\n end",
"def create_translation(other)\n end",
"def definition_builder; end",
"def definition_builder; end",
"def build(**)\n raise NotImplementedError\n end",
"def lang=(_arg0); end",
"def lang=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def make; end",
"def translate q, target=@target_lang, source=@source_lang\n return \"[#{source}->#{target}]#{q.to_s}\"\n end",
"def build_script\n raise NotImplementedError\n end",
"def translator\n @translator ||= Translator.new\n end",
"def set_translation_target(opts)\n opts = check_params(opts,[:targets])\n super(opts)\n end",
"def _lex_trans_targs; end",
"def _lex_trans_targs; end",
"def _lex_trans_targs; end",
"def _lex_trans_targs; end",
"def translate(eng_word) # here call to Max's ending code\n Multitran.translate(eng_word)\n end",
"def build(*args)\n raise \"Method 'build' not implemented for #{self.class.name}\"\n end",
"def translate(*args, **opts); end",
"def build_html\n # the first one should not use a locale, for the default:\n generate_all_html_pages\n\n # now translate, if necessary:\n if translation.should_translate?\n translation.prepare\n translation.available_locales.each do |locale|\n translation.current_locale = locale\n generate_all_html_pages\n end\n end\n end",
"def builder; end",
"def builder; end",
"def builder; end",
"def build_gem; end",
"def _lex_trans_targs=(_arg0); end",
"def _lex_trans_targs=(_arg0); end",
"def _lex_trans_targs=(_arg0); end",
"def _lex_trans_targs=(_arg0); end",
"def create\n @user = current_user\n @project = Project.find(params[:project_id])\n @preferedlang = Language.find_by_id(@project.source_lang_id)\n @slanguages = Language.where(\"id != ?\", @preferedlang.id).order('iso_code asc') \n @slanguages.unshift(@preferedlang)\n #from railsrecipes recipe 22 - refactor\n # @user = current_user\n\n\n @mostpopulartarlang = Language.find_by_id(@project.translations.maximum(\"source_lang_id\"))\n if @mostpopulartarlang\n @tlanguages = Language.where(\"id != ?\", @mostpopulartarlang.id).order('iso_code asc')\n @tlanguages.unshift(@mostpopulartarlang)\n else\n @tlanguages = Language.order('iso_code desc')\n end\n\n\n @translation = @project.translations.build(params[:translation])\n @translation.owner_id = @user.id\n\n# @project = Project.find(params[:id])\n\n# @translation = Translation.new(params[:translation])\n# @translation.owner_id = current_user.id\n# @translation.project_id = Project.find_by_id(params[:project_id]).id\n # @user = User.find(params[:user_id])\n # @project = Project.find(params[:project_id])\n # @translation = Translation.new(params[:translation])\n # @project = current_user.projects.build\n # @translation = @project.translations.build\n # @user = current_user\n # @project = Project.find_by_user_id(@user)\n # @translation = @project.translations.build(params[:translation])\n @languages = Language.all(:order => 'iso_code')\n # #process information from checkbox\n\n if @translation.save\n flash[:notice] = \"Translation was successfully created\"\n # redirect_to user_project_translations_path(@user, @project)\n redirect_to user_project_path(current_user, @project)\n else\n render 'new'\n end\nend",
"def target_version=(_arg0); end",
"def translate(input_text, src_lang, target_lang)\n raise \"Not Implemented. Class #{self.class.name} doesn't implement translate\"\n end",
"def process_and_build_components \n end",
"def build_method\nend",
"def build_method\nend",
"def originalsourceform; end",
"def transforms; end",
"def rebuild\n build addl_cmake_bld_args: '--clean-first'\n end",
"def lang(orig); end",
"def initialize b\n @build = b\n end",
"def internal; end",
"def after_build\n cleanup_nontarget_files\n run_help_indexer\nend",
"def inject_translatable_block\n inject_into_class model_path, class_name, generate_translatable_block\n end",
"def inspect\n \"#<Translations (#{backend}) @names=#{names.join(\", \")}>\"\n end",
"def target; end",
"def target; end",
"def command_builder; end",
"def translate\n if self.products && self.products.first\n ContentTranslation.auto_translate(self, self.products.first.brand)\n end\n end",
"def check_starting(_lang_result)\n end",
"def build_with_lto(pass_manager, internalize = false, run_inliner = false)\n raise \"build_with_lto is not currently supported\"\n end",
"def mozart_german; end",
"def translated_msg(translate, message, src_lang, target_lang)\n return message unless translate \n use_src = nil \n if (src_lang.nil? || src_lang.empty?)\n # We don't need to infer again and again\n begin\n @inferred_src_lang ||= infer_languages.first\n rescue StandardError => e \n raise LangDetectionFailureException.new(\"Failed to infer language due to #{e.message}\")\n end\n use_src = @inferred_src_lang\n else\n use_src = src_lang\n end\n return message if use_src.eql?(target_lang)\n @translator.translate(message, use_src, target_lang)\n end",
"def make_dic_lists_class_from_ts_from_current_version(sFrTSFilePath, sEnTSFilePath, sJaTSFilePath, hQmFileBaseNamePath=Hash.new(), coTranslateSummaries=TranslateSummaries.new())\n#\t\tSTDOUT.puts \"Check1:#{sTSFilePath}\"\n\t\t#return false unless sFrTSFilePath =~ /_msg_(.+?)\\.ts$/\n\t\treturn false unless sFrTSFilePath =~ /_(\\w{2})\\.ts$/\n\t\tsLang = $1.to_s\n\t\tsTSFileBaseName_temp = File.basename(sFrTSFilePath).gsub(/\\.ts$/, \"\")\n\t\t#sTSFileBaseName = sTSFileBaseName_temp.gsub(/_msg_(en|ja)$/, \"_msg_fr\")\n\t\tsTSFileBaseName = sTSFileBaseName_temp.gsub(/_(en|ja)$/, \"_fr\")\n\t\t#return true if hQmFileBaseNamePath[sTSFileBaseName] == true\n\t\tsTargetTSFilePath = sFrTSFilePath.gsub(/\\.ts$/, \"\")\n\t\t#sTargetTSFilePath = sTargetTSFilePath.gsub(/_msg_(en|ja)$/, \"_msg_fr\")\n\t\tsTargetTSFilePath = sTargetTSFilePath.gsub(/_(en|ja)$/, \"_fr\")\n\t\t# modified by takeru on 2012.5.2\n\t\t# modified by takeru on 2012.5.12\n\t\tcoTranslateDicLists = coTranslateSummaries[sTSFileBaseName]\n\t\t#coTranslateDicLists = coTranslateSummaries[sTargetTSFilePath]\n\t\tif coTranslateDicLists == nil then\n\t\t\tcoTranslateDicLists = TranslateDicLists.new()\n\t\t\t#coTranslateDicLists.create_dic_lists(sTSFileBaseName, coTranslateSummaries) \n\t\t\tcoTranslateDicLists.create_dic_lists(sTSFileBaseName, coTranslateSummaries) \n\t\tend\n\n\t\t#PP.pp(coTranslateDicLists, STDERR)\n\t\t#STDERR.puts coTranslateDicLists\n\t\t# modified by takeru on 2012.5.2\n\t\t# modified by takeru on 2012.5.12\n\t\t#coTranslateDicLists.create_dic_lists(sTargetTSFilePath, coTranslateSummaries) \n\t\t\n\t\tdoc = nil\n\t\t#File.open(sTSFilePath) {|xmlfile|\n\t\t#\tdoc = REXML::Document.new(xmlfile)\n\t\t#}\n\t\t#nTotalCount = TranslateTsLIB.traverse_count_translate_tag(doc.root)\n\t\t#nCount = traverse_install_keyword(coTranslateDicLists, sLang, doc.root, nTotalCount, 0)\n\n\t\trexmlDocFr = nil\n\t\trexmlDocEn = nil\n\t\trexmlDocJa = nil\n#\t\tSTDOUT.puts \"Check2:#{sTSFilePath}\"\n\t\tif File.exist?(sFrTSFilePath) == true then\n\t\t\tFile.open(sFrTSFilePath) do |sXmlFile|\n\t\t\t\t#STDERR.puts sXmlFile\n\t\t\t\trexmlDocFr = REXML::Document.new(sXmlFile)\n\t\t\tend\n\t\telse\n\t\t\trexmlDocFr = REXML::Document.new(\"\")\n\t\tend\n\t\tif File.exist?(sEnTSFilePath) == true then\n\t\t\tFile.open(sEnTSFilePath) do |sXmlFile|\n\t\t\t\t#STDERR.puts sXmlFile\n\t\t\t\trexmlDocEn = REXML::Document.new(sXmlFile)\n\t\t\tend\n\t\telse\n\t\t\trexmlDocEn = REXML::Document.new(\"\")\n\t\tend\n\t\tif File.exist?(sJaTSFilePath) == true then\n\t\t\tFile.open(sJaTSFilePath) do |sXmlFile|\n\t\t\t\t#STDERR.puts sXmlFile\n\t\t\t\trexmlDocJa = REXML::Document.new(sXmlFile)\n\t\t\tend\n\t\telse\n\t\t\trexmlDocJa = REXML::Document.new(\"\")\n\t\tend\n\t\tTranslateTsLIB.make_dic_files_from_current_version(coTranslateDicLists, rexmlDocFr, rexmlDocEn, rexmlDocJa)\n\n\t\tPP.pp(coTranslateDicLists, STDERR)\n\t\t#STDERR.puts coTranslateDicListC\n\t\thQmFileBaseNamePath[sTSFileBaseName] = true\n\n\t\treturn true\n\n\tend",
"def project=(_arg0); end",
"def translator_for(t_key, template = nil, parameters = nil)\n o_translator = translators[t_key]\n if template\n translator = Translator.new(template,\n :parameters => parameters)\n if o_translator\n o_translator.flagged.each do |i|\n translator.flag_ref(i)\n end\n end\n translators[t_key] = translator\n o_translator = translator\n else\n unless o_translator\n o_translator = Translator.new({},\n :parameters => {})\n end\n end\n o_translator\n end",
"def transitive_tags=(_arg0); end",
"def build\n @values.fetch('ai.application.build') { \n @values['ai.application.build'] = nil\n }\n end"
] |
[
"0.6883647",
"0.6533848",
"0.63228124",
"0.6285692",
"0.61541957",
"0.6106972",
"0.60572135",
"0.60572135",
"0.6044818",
"0.5934256",
"0.58429533",
"0.57962584",
"0.57621515",
"0.56773853",
"0.56450874",
"0.5641148",
"0.56402266",
"0.56377953",
"0.56377953",
"0.56377953",
"0.56377953",
"0.563193",
"0.5603648",
"0.5603648",
"0.5603648",
"0.5603648",
"0.5603648",
"0.5603648",
"0.5603648",
"0.5603648",
"0.5539893",
"0.5515746",
"0.5506458",
"0.5506458",
"0.5506458",
"0.5506458",
"0.5483055",
"0.5478138",
"0.5478138",
"0.5478138",
"0.5478138",
"0.54689604",
"0.5438438",
"0.54147893",
"0.54147893",
"0.5396942",
"0.53882873",
"0.53882873",
"0.538508",
"0.538508",
"0.538508",
"0.538508",
"0.53616184",
"0.5325575",
"0.5307658",
"0.5285696",
"0.52836215",
"0.5277548",
"0.5277548",
"0.5277548",
"0.5277548",
"0.5277409",
"0.5276492",
"0.5244269",
"0.52338994",
"0.5225921",
"0.5225921",
"0.5225921",
"0.52102983",
"0.52075773",
"0.52075773",
"0.52075773",
"0.52075773",
"0.51929444",
"0.519034",
"0.51851165",
"0.5178272",
"0.5177214",
"0.5177214",
"0.5175146",
"0.5170643",
"0.51623094",
"0.51618916",
"0.5157075",
"0.51559997",
"0.51474744",
"0.5135601",
"0.512349",
"0.51233244",
"0.51233244",
"0.51216316",
"0.51184595",
"0.51173496",
"0.5098373",
"0.50958216",
"0.5095469",
"0.50897473",
"0.5055671",
"0.5055595",
"0.50555706",
"0.5046569"
] |
0.0
|
-1
|
(This method is generated in Translator_defaultbuildImpl)
|
def set_region(v)
Saklient::Util::validate_type(v, 'Saklient::Cloud::Resources::Region')
raise Saklient::Errors::SaklientException.new('immutable_field', 'Immutable fields cannot be modified after the resource creation: ' + 'Saklient::Cloud::Resources::Bridge#region') if !@is_new
@m_region = v
@n_region = true
return @m_region
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def translation_target\n super\n end",
"def build; end",
"def translations; end",
"def init_translations; end",
"def build=(_arg0); end",
"def build\r\n raise \"Not implemented\"\r\n end",
"def build\r\n end",
"def build\r\n end",
"def build\n end",
"def label_translation; end",
"def build!\n end",
"def create_translations\n end",
"def translatable\n self._translatable[base_name]\n end",
"def translate(settings); end",
"def translations_hash; end",
"def build\n end",
"def setup_mass_copy_translations\n end",
"def _lex_trans_keys=(_arg0); end",
"def _lex_trans_keys=(_arg0); end",
"def _lex_trans_keys=(_arg0); end",
"def _lex_trans_keys=(_arg0); end",
"def private; end",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translatable\n self._translatable[base_name] ||= []\n end",
"def build(params); end",
"def _lex_trans_keys; end",
"def _lex_trans_keys; end",
"def _lex_trans_keys; end",
"def _lex_trans_keys; end",
"def translate!( *args )\n super( *args )\n reset_positions_inside\n end",
"def _lex_trans_actions; end",
"def _lex_trans_actions; end",
"def _lex_trans_actions; end",
"def _lex_trans_actions; end",
"def build\n method_proxy(:build)\n\n true\n end",
"def create_translation(other)\n end",
"def definition_builder; end",
"def definition_builder; end",
"def build(**)\n raise NotImplementedError\n end",
"def lang=(_arg0); end",
"def lang=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def make; end",
"def translate q, target=@target_lang, source=@source_lang\n return \"[#{source}->#{target}]#{q.to_s}\"\n end",
"def build_script\n raise NotImplementedError\n end",
"def translator\n @translator ||= Translator.new\n end",
"def set_translation_target(opts)\n opts = check_params(opts,[:targets])\n super(opts)\n end",
"def build(*args)\n raise \"Method 'build' not implemented for #{self.class.name}\"\n end",
"def translate(eng_word) # here call to Max's ending code\n Multitran.translate(eng_word)\n end",
"def _lex_trans_targs; end",
"def _lex_trans_targs; end",
"def _lex_trans_targs; end",
"def _lex_trans_targs; end",
"def translate(*args, **opts); end",
"def build_html\n # the first one should not use a locale, for the default:\n generate_all_html_pages\n\n # now translate, if necessary:\n if translation.should_translate?\n translation.prepare\n translation.available_locales.each do |locale|\n translation.current_locale = locale\n generate_all_html_pages\n end\n end\n end",
"def builder; end",
"def builder; end",
"def builder; end",
"def build_gem; end",
"def _lex_trans_targs=(_arg0); end",
"def _lex_trans_targs=(_arg0); end",
"def _lex_trans_targs=(_arg0); end",
"def _lex_trans_targs=(_arg0); end",
"def create\n @user = current_user\n @project = Project.find(params[:project_id])\n @preferedlang = Language.find_by_id(@project.source_lang_id)\n @slanguages = Language.where(\"id != ?\", @preferedlang.id).order('iso_code asc') \n @slanguages.unshift(@preferedlang)\n #from railsrecipes recipe 22 - refactor\n # @user = current_user\n\n\n @mostpopulartarlang = Language.find_by_id(@project.translations.maximum(\"source_lang_id\"))\n if @mostpopulartarlang\n @tlanguages = Language.where(\"id != ?\", @mostpopulartarlang.id).order('iso_code asc')\n @tlanguages.unshift(@mostpopulartarlang)\n else\n @tlanguages = Language.order('iso_code desc')\n end\n\n\n @translation = @project.translations.build(params[:translation])\n @translation.owner_id = @user.id\n\n# @project = Project.find(params[:id])\n\n# @translation = Translation.new(params[:translation])\n# @translation.owner_id = current_user.id\n# @translation.project_id = Project.find_by_id(params[:project_id]).id\n # @user = User.find(params[:user_id])\n # @project = Project.find(params[:project_id])\n # @translation = Translation.new(params[:translation])\n # @project = current_user.projects.build\n # @translation = @project.translations.build\n # @user = current_user\n # @project = Project.find_by_user_id(@user)\n # @translation = @project.translations.build(params[:translation])\n @languages = Language.all(:order => 'iso_code')\n # #process information from checkbox\n\n if @translation.save\n flash[:notice] = \"Translation was successfully created\"\n # redirect_to user_project_translations_path(@user, @project)\n redirect_to user_project_path(current_user, @project)\n else\n render 'new'\n end\nend",
"def target_version=(_arg0); end",
"def translate(input_text, src_lang, target_lang)\n raise \"Not Implemented. Class #{self.class.name} doesn't implement translate\"\n end",
"def process_and_build_components \n end",
"def build_method\nend",
"def build_method\nend",
"def originalsourceform; end",
"def transforms; end",
"def rebuild\n build addl_cmake_bld_args: '--clean-first'\n end",
"def lang(orig); end",
"def initialize b\n @build = b\n end",
"def internal; end",
"def after_build\n cleanup_nontarget_files\n run_help_indexer\nend",
"def inject_translatable_block\n inject_into_class model_path, class_name, generate_translatable_block\n end",
"def target; end",
"def target; end",
"def inspect\n \"#<Translations (#{backend}) @names=#{names.join(\", \")}>\"\n end",
"def command_builder; end",
"def translate\n if self.products && self.products.first\n ContentTranslation.auto_translate(self, self.products.first.brand)\n end\n end",
"def check_starting(_lang_result)\n end",
"def build_with_lto(pass_manager, internalize = false, run_inliner = false)\n raise \"build_with_lto is not currently supported\"\n end",
"def mozart_german; end",
"def translated_msg(translate, message, src_lang, target_lang)\n return message unless translate \n use_src = nil \n if (src_lang.nil? || src_lang.empty?)\n # We don't need to infer again and again\n begin\n @inferred_src_lang ||= infer_languages.first\n rescue StandardError => e \n raise LangDetectionFailureException.new(\"Failed to infer language due to #{e.message}\")\n end\n use_src = @inferred_src_lang\n else\n use_src = src_lang\n end\n return message if use_src.eql?(target_lang)\n @translator.translate(message, use_src, target_lang)\n end",
"def make_dic_lists_class_from_ts_from_current_version(sFrTSFilePath, sEnTSFilePath, sJaTSFilePath, hQmFileBaseNamePath=Hash.new(), coTranslateSummaries=TranslateSummaries.new())\n#\t\tSTDOUT.puts \"Check1:#{sTSFilePath}\"\n\t\t#return false unless sFrTSFilePath =~ /_msg_(.+?)\\.ts$/\n\t\treturn false unless sFrTSFilePath =~ /_(\\w{2})\\.ts$/\n\t\tsLang = $1.to_s\n\t\tsTSFileBaseName_temp = File.basename(sFrTSFilePath).gsub(/\\.ts$/, \"\")\n\t\t#sTSFileBaseName = sTSFileBaseName_temp.gsub(/_msg_(en|ja)$/, \"_msg_fr\")\n\t\tsTSFileBaseName = sTSFileBaseName_temp.gsub(/_(en|ja)$/, \"_fr\")\n\t\t#return true if hQmFileBaseNamePath[sTSFileBaseName] == true\n\t\tsTargetTSFilePath = sFrTSFilePath.gsub(/\\.ts$/, \"\")\n\t\t#sTargetTSFilePath = sTargetTSFilePath.gsub(/_msg_(en|ja)$/, \"_msg_fr\")\n\t\tsTargetTSFilePath = sTargetTSFilePath.gsub(/_(en|ja)$/, \"_fr\")\n\t\t# modified by takeru on 2012.5.2\n\t\t# modified by takeru on 2012.5.12\n\t\tcoTranslateDicLists = coTranslateSummaries[sTSFileBaseName]\n\t\t#coTranslateDicLists = coTranslateSummaries[sTargetTSFilePath]\n\t\tif coTranslateDicLists == nil then\n\t\t\tcoTranslateDicLists = TranslateDicLists.new()\n\t\t\t#coTranslateDicLists.create_dic_lists(sTSFileBaseName, coTranslateSummaries) \n\t\t\tcoTranslateDicLists.create_dic_lists(sTSFileBaseName, coTranslateSummaries) \n\t\tend\n\n\t\t#PP.pp(coTranslateDicLists, STDERR)\n\t\t#STDERR.puts coTranslateDicLists\n\t\t# modified by takeru on 2012.5.2\n\t\t# modified by takeru on 2012.5.12\n\t\t#coTranslateDicLists.create_dic_lists(sTargetTSFilePath, coTranslateSummaries) \n\t\t\n\t\tdoc = nil\n\t\t#File.open(sTSFilePath) {|xmlfile|\n\t\t#\tdoc = REXML::Document.new(xmlfile)\n\t\t#}\n\t\t#nTotalCount = TranslateTsLIB.traverse_count_translate_tag(doc.root)\n\t\t#nCount = traverse_install_keyword(coTranslateDicLists, sLang, doc.root, nTotalCount, 0)\n\n\t\trexmlDocFr = nil\n\t\trexmlDocEn = nil\n\t\trexmlDocJa = nil\n#\t\tSTDOUT.puts \"Check2:#{sTSFilePath}\"\n\t\tif File.exist?(sFrTSFilePath) == true then\n\t\t\tFile.open(sFrTSFilePath) do |sXmlFile|\n\t\t\t\t#STDERR.puts sXmlFile\n\t\t\t\trexmlDocFr = REXML::Document.new(sXmlFile)\n\t\t\tend\n\t\telse\n\t\t\trexmlDocFr = REXML::Document.new(\"\")\n\t\tend\n\t\tif File.exist?(sEnTSFilePath) == true then\n\t\t\tFile.open(sEnTSFilePath) do |sXmlFile|\n\t\t\t\t#STDERR.puts sXmlFile\n\t\t\t\trexmlDocEn = REXML::Document.new(sXmlFile)\n\t\t\tend\n\t\telse\n\t\t\trexmlDocEn = REXML::Document.new(\"\")\n\t\tend\n\t\tif File.exist?(sJaTSFilePath) == true then\n\t\t\tFile.open(sJaTSFilePath) do |sXmlFile|\n\t\t\t\t#STDERR.puts sXmlFile\n\t\t\t\trexmlDocJa = REXML::Document.new(sXmlFile)\n\t\t\tend\n\t\telse\n\t\t\trexmlDocJa = REXML::Document.new(\"\")\n\t\tend\n\t\tTranslateTsLIB.make_dic_files_from_current_version(coTranslateDicLists, rexmlDocFr, rexmlDocEn, rexmlDocJa)\n\n\t\tPP.pp(coTranslateDicLists, STDERR)\n\t\t#STDERR.puts coTranslateDicListC\n\t\thQmFileBaseNamePath[sTSFileBaseName] = true\n\n\t\treturn true\n\n\tend",
"def transitive_tags=(_arg0); end",
"def project=(_arg0); end",
"def translator_for(t_key, template = nil, parameters = nil)\n o_translator = translators[t_key]\n if template\n translator = Translator.new(template,\n :parameters => parameters)\n if o_translator\n o_translator.flagged.each do |i|\n translator.flag_ref(i)\n end\n end\n translators[t_key] = translator\n o_translator = translator\n else\n unless o_translator\n o_translator = Translator.new({},\n :parameters => {})\n end\n end\n o_translator\n end",
"def build\n @values.fetch('ai.application.build') { \n @values['ai.application.build'] = nil\n }\n end"
] |
[
"0.6882901",
"0.653592",
"0.63217664",
"0.6284657",
"0.61551243",
"0.61091876",
"0.605949",
"0.605949",
"0.60470265",
"0.59335953",
"0.5844821",
"0.5795114",
"0.5761158",
"0.56754434",
"0.56447375",
"0.5643845",
"0.5639414",
"0.5635945",
"0.5635945",
"0.5635945",
"0.5635945",
"0.563406",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5539237",
"0.5517182",
"0.5505295",
"0.5505295",
"0.5505295",
"0.5505295",
"0.54820263",
"0.5475904",
"0.5475904",
"0.5475904",
"0.5475904",
"0.547027",
"0.5437076",
"0.54157394",
"0.54157394",
"0.5398866",
"0.5386972",
"0.5386972",
"0.53822404",
"0.53822404",
"0.53822404",
"0.53822404",
"0.5361637",
"0.5323374",
"0.5308725",
"0.52835053",
"0.5282656",
"0.52782214",
"0.5275988",
"0.5274997",
"0.5274997",
"0.5274997",
"0.5274997",
"0.5241623",
"0.52328515",
"0.52266777",
"0.52266777",
"0.52266777",
"0.52109337",
"0.5204789",
"0.5204789",
"0.5204789",
"0.5204789",
"0.5192355",
"0.5190386",
"0.51832217",
"0.5179127",
"0.51784027",
"0.51784027",
"0.5175266",
"0.5170668",
"0.51630884",
"0.5160946",
"0.5158187",
"0.51568115",
"0.51486707",
"0.51343715",
"0.51235247",
"0.51235247",
"0.5122161",
"0.51212776",
"0.5117833",
"0.5116379",
"0.50977826",
"0.5095889",
"0.50931627",
"0.5088532",
"0.5056332",
"0.50559413",
"0.5053341",
"0.5048526"
] |
0.0
|
-1
|
(This method is generated in Translator_defaultbuildImpl)
|
def api_deserialize_impl(r)
@is_new = (r).nil?
r = {} if @is_new
@is_incomplete = false
if Saklient::Util::exists_path(r, 'ID')
@m_id = (Saklient::Util::get_by_path(r, 'ID')).nil? ? nil : Saklient::Util::get_by_path(r, 'ID').to_s
else
@m_id = nil
@is_incomplete = true
end
@n_id = false
if Saklient::Util::exists_path(r, 'Name')
@m_name = (Saklient::Util::get_by_path(r, 'Name')).nil? ? nil : Saklient::Util::get_by_path(r, 'Name').to_s
else
@m_name = nil
@is_incomplete = true
end
@n_name = false
if Saklient::Util::exists_path(r, 'Description')
@m_description = (Saklient::Util::get_by_path(r, 'Description')).nil? ? nil : Saklient::Util::get_by_path(r, 'Description').to_s
else
@m_description = nil
@is_incomplete = true
end
@n_description = false
if Saklient::Util::exists_path(r, 'Region')
@m_region = (Saklient::Util::get_by_path(r, 'Region')).nil? ? nil : Saklient::Cloud::Resources::Region.new(@_client, Saklient::Util::get_by_path(r, 'Region'))
else
@m_region = nil
@is_incomplete = true
end
@n_region = false
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def translation_target\n super\n end",
"def build; end",
"def translations; end",
"def init_translations; end",
"def build=(_arg0); end",
"def build\r\n raise \"Not implemented\"\r\n end",
"def build\r\n end",
"def build\r\n end",
"def build\n end",
"def label_translation; end",
"def build!\n end",
"def create_translations\n end",
"def translatable\n self._translatable[base_name]\n end",
"def translate(settings); end",
"def translations_hash; end",
"def build\n end",
"def setup_mass_copy_translations\n end",
"def _lex_trans_keys=(_arg0); end",
"def _lex_trans_keys=(_arg0); end",
"def _lex_trans_keys=(_arg0); end",
"def _lex_trans_keys=(_arg0); end",
"def private; end",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translate()\n\nend",
"def translatable\n self._translatable[base_name] ||= []\n end",
"def build(params); end",
"def _lex_trans_keys; end",
"def _lex_trans_keys; end",
"def _lex_trans_keys; end",
"def _lex_trans_keys; end",
"def translate!( *args )\n super( *args )\n reset_positions_inside\n end",
"def _lex_trans_actions; end",
"def _lex_trans_actions; end",
"def _lex_trans_actions; end",
"def _lex_trans_actions; end",
"def build\n method_proxy(:build)\n\n true\n end",
"def create_translation(other)\n end",
"def definition_builder; end",
"def definition_builder; end",
"def build(**)\n raise NotImplementedError\n end",
"def lang=(_arg0); end",
"def lang=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def _lex_trans_actions=(_arg0); end",
"def make; end",
"def translate q, target=@target_lang, source=@source_lang\n return \"[#{source}->#{target}]#{q.to_s}\"\n end",
"def build_script\n raise NotImplementedError\n end",
"def translator\n @translator ||= Translator.new\n end",
"def set_translation_target(opts)\n opts = check_params(opts,[:targets])\n super(opts)\n end",
"def build(*args)\n raise \"Method 'build' not implemented for #{self.class.name}\"\n end",
"def translate(eng_word) # here call to Max's ending code\n Multitran.translate(eng_word)\n end",
"def _lex_trans_targs; end",
"def _lex_trans_targs; end",
"def _lex_trans_targs; end",
"def _lex_trans_targs; end",
"def translate(*args, **opts); end",
"def build_html\n # the first one should not use a locale, for the default:\n generate_all_html_pages\n\n # now translate, if necessary:\n if translation.should_translate?\n translation.prepare\n translation.available_locales.each do |locale|\n translation.current_locale = locale\n generate_all_html_pages\n end\n end\n end",
"def builder; end",
"def builder; end",
"def builder; end",
"def build_gem; end",
"def _lex_trans_targs=(_arg0); end",
"def _lex_trans_targs=(_arg0); end",
"def _lex_trans_targs=(_arg0); end",
"def _lex_trans_targs=(_arg0); end",
"def create\n @user = current_user\n @project = Project.find(params[:project_id])\n @preferedlang = Language.find_by_id(@project.source_lang_id)\n @slanguages = Language.where(\"id != ?\", @preferedlang.id).order('iso_code asc') \n @slanguages.unshift(@preferedlang)\n #from railsrecipes recipe 22 - refactor\n # @user = current_user\n\n\n @mostpopulartarlang = Language.find_by_id(@project.translations.maximum(\"source_lang_id\"))\n if @mostpopulartarlang\n @tlanguages = Language.where(\"id != ?\", @mostpopulartarlang.id).order('iso_code asc')\n @tlanguages.unshift(@mostpopulartarlang)\n else\n @tlanguages = Language.order('iso_code desc')\n end\n\n\n @translation = @project.translations.build(params[:translation])\n @translation.owner_id = @user.id\n\n# @project = Project.find(params[:id])\n\n# @translation = Translation.new(params[:translation])\n# @translation.owner_id = current_user.id\n# @translation.project_id = Project.find_by_id(params[:project_id]).id\n # @user = User.find(params[:user_id])\n # @project = Project.find(params[:project_id])\n # @translation = Translation.new(params[:translation])\n # @project = current_user.projects.build\n # @translation = @project.translations.build\n # @user = current_user\n # @project = Project.find_by_user_id(@user)\n # @translation = @project.translations.build(params[:translation])\n @languages = Language.all(:order => 'iso_code')\n # #process information from checkbox\n\n if @translation.save\n flash[:notice] = \"Translation was successfully created\"\n # redirect_to user_project_translations_path(@user, @project)\n redirect_to user_project_path(current_user, @project)\n else\n render 'new'\n end\nend",
"def target_version=(_arg0); end",
"def translate(input_text, src_lang, target_lang)\n raise \"Not Implemented. Class #{self.class.name} doesn't implement translate\"\n end",
"def process_and_build_components \n end",
"def build_method\nend",
"def build_method\nend",
"def originalsourceform; end",
"def transforms; end",
"def rebuild\n build addl_cmake_bld_args: '--clean-first'\n end",
"def lang(orig); end",
"def initialize b\n @build = b\n end",
"def internal; end",
"def after_build\n cleanup_nontarget_files\n run_help_indexer\nend",
"def inject_translatable_block\n inject_into_class model_path, class_name, generate_translatable_block\n end",
"def target; end",
"def target; end",
"def inspect\n \"#<Translations (#{backend}) @names=#{names.join(\", \")}>\"\n end",
"def command_builder; end",
"def translate\n if self.products && self.products.first\n ContentTranslation.auto_translate(self, self.products.first.brand)\n end\n end",
"def check_starting(_lang_result)\n end",
"def build_with_lto(pass_manager, internalize = false, run_inliner = false)\n raise \"build_with_lto is not currently supported\"\n end",
"def mozart_german; end",
"def translated_msg(translate, message, src_lang, target_lang)\n return message unless translate \n use_src = nil \n if (src_lang.nil? || src_lang.empty?)\n # We don't need to infer again and again\n begin\n @inferred_src_lang ||= infer_languages.first\n rescue StandardError => e \n raise LangDetectionFailureException.new(\"Failed to infer language due to #{e.message}\")\n end\n use_src = @inferred_src_lang\n else\n use_src = src_lang\n end\n return message if use_src.eql?(target_lang)\n @translator.translate(message, use_src, target_lang)\n end",
"def make_dic_lists_class_from_ts_from_current_version(sFrTSFilePath, sEnTSFilePath, sJaTSFilePath, hQmFileBaseNamePath=Hash.new(), coTranslateSummaries=TranslateSummaries.new())\n#\t\tSTDOUT.puts \"Check1:#{sTSFilePath}\"\n\t\t#return false unless sFrTSFilePath =~ /_msg_(.+?)\\.ts$/\n\t\treturn false unless sFrTSFilePath =~ /_(\\w{2})\\.ts$/\n\t\tsLang = $1.to_s\n\t\tsTSFileBaseName_temp = File.basename(sFrTSFilePath).gsub(/\\.ts$/, \"\")\n\t\t#sTSFileBaseName = sTSFileBaseName_temp.gsub(/_msg_(en|ja)$/, \"_msg_fr\")\n\t\tsTSFileBaseName = sTSFileBaseName_temp.gsub(/_(en|ja)$/, \"_fr\")\n\t\t#return true if hQmFileBaseNamePath[sTSFileBaseName] == true\n\t\tsTargetTSFilePath = sFrTSFilePath.gsub(/\\.ts$/, \"\")\n\t\t#sTargetTSFilePath = sTargetTSFilePath.gsub(/_msg_(en|ja)$/, \"_msg_fr\")\n\t\tsTargetTSFilePath = sTargetTSFilePath.gsub(/_(en|ja)$/, \"_fr\")\n\t\t# modified by takeru on 2012.5.2\n\t\t# modified by takeru on 2012.5.12\n\t\tcoTranslateDicLists = coTranslateSummaries[sTSFileBaseName]\n\t\t#coTranslateDicLists = coTranslateSummaries[sTargetTSFilePath]\n\t\tif coTranslateDicLists == nil then\n\t\t\tcoTranslateDicLists = TranslateDicLists.new()\n\t\t\t#coTranslateDicLists.create_dic_lists(sTSFileBaseName, coTranslateSummaries) \n\t\t\tcoTranslateDicLists.create_dic_lists(sTSFileBaseName, coTranslateSummaries) \n\t\tend\n\n\t\t#PP.pp(coTranslateDicLists, STDERR)\n\t\t#STDERR.puts coTranslateDicLists\n\t\t# modified by takeru on 2012.5.2\n\t\t# modified by takeru on 2012.5.12\n\t\t#coTranslateDicLists.create_dic_lists(sTargetTSFilePath, coTranslateSummaries) \n\t\t\n\t\tdoc = nil\n\t\t#File.open(sTSFilePath) {|xmlfile|\n\t\t#\tdoc = REXML::Document.new(xmlfile)\n\t\t#}\n\t\t#nTotalCount = TranslateTsLIB.traverse_count_translate_tag(doc.root)\n\t\t#nCount = traverse_install_keyword(coTranslateDicLists, sLang, doc.root, nTotalCount, 0)\n\n\t\trexmlDocFr = nil\n\t\trexmlDocEn = nil\n\t\trexmlDocJa = nil\n#\t\tSTDOUT.puts \"Check2:#{sTSFilePath}\"\n\t\tif File.exist?(sFrTSFilePath) == true then\n\t\t\tFile.open(sFrTSFilePath) do |sXmlFile|\n\t\t\t\t#STDERR.puts sXmlFile\n\t\t\t\trexmlDocFr = REXML::Document.new(sXmlFile)\n\t\t\tend\n\t\telse\n\t\t\trexmlDocFr = REXML::Document.new(\"\")\n\t\tend\n\t\tif File.exist?(sEnTSFilePath) == true then\n\t\t\tFile.open(sEnTSFilePath) do |sXmlFile|\n\t\t\t\t#STDERR.puts sXmlFile\n\t\t\t\trexmlDocEn = REXML::Document.new(sXmlFile)\n\t\t\tend\n\t\telse\n\t\t\trexmlDocEn = REXML::Document.new(\"\")\n\t\tend\n\t\tif File.exist?(sJaTSFilePath) == true then\n\t\t\tFile.open(sJaTSFilePath) do |sXmlFile|\n\t\t\t\t#STDERR.puts sXmlFile\n\t\t\t\trexmlDocJa = REXML::Document.new(sXmlFile)\n\t\t\tend\n\t\telse\n\t\t\trexmlDocJa = REXML::Document.new(\"\")\n\t\tend\n\t\tTranslateTsLIB.make_dic_files_from_current_version(coTranslateDicLists, rexmlDocFr, rexmlDocEn, rexmlDocJa)\n\n\t\tPP.pp(coTranslateDicLists, STDERR)\n\t\t#STDERR.puts coTranslateDicListC\n\t\thQmFileBaseNamePath[sTSFileBaseName] = true\n\n\t\treturn true\n\n\tend",
"def transitive_tags=(_arg0); end",
"def project=(_arg0); end",
"def translator_for(t_key, template = nil, parameters = nil)\n o_translator = translators[t_key]\n if template\n translator = Translator.new(template,\n :parameters => parameters)\n if o_translator\n o_translator.flagged.each do |i|\n translator.flag_ref(i)\n end\n end\n translators[t_key] = translator\n o_translator = translator\n else\n unless o_translator\n o_translator = Translator.new({},\n :parameters => {})\n end\n end\n o_translator\n end",
"def build\n @values.fetch('ai.application.build') { \n @values['ai.application.build'] = nil\n }\n end"
] |
[
"0.6882901",
"0.653592",
"0.63217664",
"0.6284657",
"0.61551243",
"0.61091876",
"0.605949",
"0.605949",
"0.60470265",
"0.59335953",
"0.5844821",
"0.5795114",
"0.5761158",
"0.56754434",
"0.56447375",
"0.5643845",
"0.5639414",
"0.5635945",
"0.5635945",
"0.5635945",
"0.5635945",
"0.563406",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5602086",
"0.5539237",
"0.5517182",
"0.5505295",
"0.5505295",
"0.5505295",
"0.5505295",
"0.54820263",
"0.5475904",
"0.5475904",
"0.5475904",
"0.5475904",
"0.547027",
"0.5437076",
"0.54157394",
"0.54157394",
"0.5398866",
"0.5386972",
"0.5386972",
"0.53822404",
"0.53822404",
"0.53822404",
"0.53822404",
"0.5361637",
"0.5323374",
"0.5308725",
"0.52835053",
"0.5282656",
"0.52782214",
"0.5275988",
"0.5274997",
"0.5274997",
"0.5274997",
"0.5274997",
"0.5241623",
"0.52328515",
"0.52266777",
"0.52266777",
"0.52266777",
"0.52109337",
"0.5204789",
"0.5204789",
"0.5204789",
"0.5204789",
"0.5192355",
"0.5190386",
"0.51832217",
"0.5179127",
"0.51784027",
"0.51784027",
"0.5175266",
"0.5170668",
"0.51630884",
"0.5160946",
"0.5158187",
"0.51568115",
"0.51486707",
"0.51343715",
"0.51235247",
"0.51235247",
"0.5122161",
"0.51212776",
"0.5117833",
"0.5116379",
"0.50977826",
"0.5095889",
"0.50931627",
"0.5088532",
"0.5056332",
"0.50559413",
"0.5053341",
"0.5048526"
] |
0.0
|
-1
|
Consumes char and produces all valid states. What about free moves? We need to consume free moves
|
def follow_rules_for(state, char)
rules_for(state, char).map(&:follow)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def progress_input(ch)\n #puts \"At position #{@pos}\"\n success = @dfa[@state].success\n if !success.empty?\n @last_success = success\n @last_str = @str\n @last_pos = @pos\n end\n next_state = @dfa[@state].lookup[ch]\n if next_state.nil?\n if @last_success.nil?\n if @str.empty? && @pos == @size && @state == @start_state\n throw :done\n else\n #puts \"#{@str} #{@pos} #{@size} #{@state.inspect} #{@start_state.inspect}\"\n raise LexError.new(@pos, @size)\n end\n else\n @pos = @last_pos\n return success(@last_success, @last_str, @last_pos)\n end\n else\n @state = next_state\n @str += ch\n @pos += 1\n return nil\n end\n end",
"def get_next_state(char)\n @@scan_table[@state - 1].find(lambda {[0, 1]}) { |rule| char =~ rule[0] }[1]\n end",
"def process(cur_char, next_char)\n @cur_char = cur_char\n @next_char = next_char\n\n case @state\n when :DEFAULT; process_default\n when :IDENT; process_ident\n when :LIT_INT; process_lit_int\n when :LIT_FLOAT; process_lit_float\n when :STRING_SCOM; process_string_scom\n when :STRING_DCOM; process_string_dcom\n when :ESCAPE; process_escape\n when :SL_COMMENT; process_single_line_comment\n when :ML_COMMENT; process_multi_line_comment\n else; raise \"Unprocessed state #{@state}\"\n end\n end",
"def next_state(state, move)\n # Deep copy position (is this the easiest way?)\n position = Marshal.load(Marshal.dump(state[:position]))\n player = state[:player]\n opp = opponent(player)\n pieces = Marshal.load(Marshal.dump(state[:pieces]))\n from = move[0]\n to = move[1]\n force_analysis = false\n check = false\n moving_piece = pieces[player].find { |piece| piece.location == from }\n if !moving_piece\n puts \"ERROR--no piece to move!\"\n end\n # Check for capture\n if position[to[0]][to[1]] != \".\"\n # Remove enemy piece\n pieces[opp].delete_if { |piece| piece.location == to }\n # Force AI to continue analysis\n force_analysis = true\n end\n # Check for promotion\n if moving_piece.class == Pawn && to[0] == end_row(player)\n # Replace pawn with queen\n # (Underpromotion not yet implemented)\n pieces[player].delete(moving_piece)\n moving_piece = Queen.new(self, to, player)\n pieces[player] << moving_piece\n end\n # Move piece\n position[from[0]][from[1]] = \".\"\n position[to[0]][to[1]] = moving_piece.icon\n moving_piece.location = to\n # Complete castling by moving rook\n if moving_piece.class == ChessKing && (from[1] - to[1]).abs == 2\n rook_column = to[1] == 6 ? 7 : 0\n castling_rook = pieces[player].find { |piece| piece.location == [from[0], rook_column] }\n if castling_rook\n rook_dest = to[1] == 6 ? 5 : 3\n position[from[0]][rook_column] = \".\"\n position[to[0]][rook_dest] = castling_rook.icon\n castling_rook.location = [to[0], rook_dest]\n else\n puts \"Castling error -- can't find rook!\"\n end\n end\n # Switch active player\n next_player = opp\n # # Create new state for testing whether king is in check\n # new_position_state = {\n # :position => position,\n # :player => player,\n # :pieces => pieces,\n # :check => false,\n # :force_analysis => false\n # }\n # # Test whether opponent's king is now in check\n # check = check?(new_position_state)\n # force_analysis = true if check\n # Return new state\n {\n :position => position,\n :player => next_player,\n :pieces => pieces,\n :check => check,\n :force_analysis => force_analysis\n }\n end",
"def must_see(char)\n spaces\n if next_is char\n # All good, input as expected.\n char\n elsif input.eos?\n # Finally, the case we've been waiting for:\n # Input exhausted, but still elements to close.\n append char\n else\n append char\n # The magic trick:\n # We implicitly use the stack to count how many closing tags we have/need.\n # We pair with exception's `ensure` mechanism to actually write them out.\n if debug\n msg = \"Seen so far: %s\" % result.clone\n raise UnexpectedTokenError, msg\n else\n raise UnexpectedTokenError\n end\n end\n end",
"def process str\n str.each_char do |char|\n # route each character to its state handler\n send(@state, char)\n end\n end",
"def decide string\n @current_state = @start_state\n string.each_char do |c|\n if !@alphabet.include? c then\n return false\n end\n transition = false\n @transition_rules.each do |rule|\n if rule.input_char === c && rule.current_state === @current_state then\n transition = rule\n break\n end\n end\n if !transition then \n return false\n else\n @current_state = transition.end_state\n end\n end\n\n if @accept_states.include? @current_state then\n return true\n else\n return false\n end\n end",
"def consume_character\n unless @input.empty?\n success(advance(1))\n else\n failure(\"less than one character available\")\n end\n end",
"def one_to_win(char) # X or O\n moves = []\n\n state_wins.each_with_index do |e,i|\n if e.count(char) == 2 && e.count(E) == 1\n moves.push(POSITIONS[WINS[i][e.index(E)]])\n end\n end\n \n moves.uniq\nend",
"def is_move_valid(current_state, proposed_change)\n proposed_floor = current_state[:elevator] + proposed_change[:elevator]\n return false if proposed_change.length < 2 || proposed_change.length > 3\n return false if proposed_floor < 0 || proposed_floor > 3\n\n proposed_state = get_new_state(current_state, proposed_change)\n generators = []\n chips = []\n proposed_state[:floors][proposed_floor].each do |item|\n binding.pry if item == nil\n if item[0] == :gen\n generators << item[1]\n else\n chips << item[1]\n end\n end\n if generators.length > 0\n chips.each do |chip_type|\n return false if !generators.include?(chip_type)\n end\n end\n\n return false if @visited_states.include? proposed_state.to_s\n @visited_states << proposed_state.to_s\n # binding.pry\n proposed_state\nend",
"def pre_check_legal_moves(state)\n player = state[:player]\n piece_list = state[:pieces][player]\n move_list = []\n # Loop over pieces\n piece_list.each do |piece|\n move_list += piece.legal_moves(state)\n end\n move_list\n end",
"def make_move(valid)\n @move = \"\"\n until (valid.rules).has_key?(@move) \n puts \"#{@name}, pick your move: #{valid.rules.keys}\"\n @move = gets.chomp\n puts \"not a valid move\" if (valid.rules).include?(@move) == false\n end\n end",
"def make_moves\n if @moves != nil\n i = 0\n catch :invalid_command do\n @moves.each_char do |move|\n i += 1\n case move\n when \"L\"\n l_command\n when \"R\"\n r_command\n when \"M\"\n throw :invalid_command unless m_command(i)\n else \n puts \"Invalid move #{move} for rover ##{@number}\"\n throw :invalid_command\n end\n end\n end\n end\n end",
"def generate_possible_moves(state)\n end",
"def read characters\n forward characters\n end",
"def next_token\n @state = 1\n value = \"\"\n recovery_data = [0, 0]\n\n while !@stream.eof?\n char = @stream.read(1)\n next_state = get_next_state(char)\n\n # Move to the next state.\n if next_state\n if recognizable?\n recovery_data = [@state, 0]\n end\n\n value << char\n recovery_data[1] += 1\n @state = next_state\n else\n # Recognise the final token.\n if recognizable?\n @stream.seek(@stream.pos - 1)\n break\n else\n # Recoverable error.\n if recovery_data[0] > 0\n value = recover_from_error!(recovery_data, value)\n break\n # Fatal lexical error.\n else\n raise Bolverk::ASM::LexicalError, \"Disallowed token: #{char} on line #{@stream.line_number}\"\n end\n end\n end\n end\n\n build_token(value)\n end",
"def next_char_ignored\n state[:ignore] = true\n end",
"def legal_moves\n out = Set.new\n board = self.unrolled\n mark = next_turn_taker(board)\n \n board.each_with_index do |space, i|\n if space == @@MARKS[:empty]\n new_state = GameState.new(self.board_bits)\n new_state.mark_index i, mark\n out << new_state\n end\n end\n \n return out\n end",
"def move(input, color)\n aux = input\n\n letter_upgrade = nil\n piece_to_move = nil\n arr_pieces = nil\n dest = nil\n \n if aux == 'O-O'\n rook = color == 'black' ? board[0][7].piece : board[7][7].piece\n return unless short_castling?(rook)\n return move_castling(true, color)\n elsif aux == 'O-O-O'\n rook = color == 'black' ? board[0][0].piece : board[7][0].piece\n return unless long_castling?(rook)\n return move_castling(false, color)\n elsif aux.match?(/^[BRQNK][a-h][1-8]$/)\n first_letter = aux.slice!(0)\n arr_pieces = find_by_name(first_letter,color)\n dest = aux[-2..-1]\n elsif aux.match?(/^[BRQNK][a-h][a-h][1-8]$/)\n first_letter = aux.slice!(0)\n arr_pieces = aux[0].match?(/[a-h]/) ? get_column(aux[0],color) : get_row(aux[0],color)\n dest = aux[-2..-1]\n elsif aux.match?(/^[BRQNK][1-8][a-h][1-8]$/)\n first_letter = aux.slice!(0)\n arr_pieces = aux[0].match?(/[a-h]/) ? get_column(aux[0],color) : get_row(aux[0],color)\n dest = aux[-2..-1]\n elsif aux.match?(/^[BRQNK][a-h][1-8][a-h][1-8]$/)\n first_letter = aux.slice!(0)\n piece_to_move = get_by_notation(aux[0..1], color)\n return unless letter_match_piece?(first_letter, piece_to_move.piece)\n dest = aux[-2..-1]\n elsif aux.match?(/^[BRQNK][a-h][1-8][+#]$/)\n aux.slice!(-1)\n first_letter = aux.slice!(0)\n arr_pieces = find_by_name(first_letter,color)\n dest = aux[-2..-1]\n elsif aux.match?(/^[BRQNK][a-h][a-h][1-8][+#]$/)\n aux.slice!(-1)\n first_letter = aux.slice!(0)\n arr_pieces = aux[0].match?(/[a-h]/) ? get_column(aux[0],color) : get_row(aux[0],color)\n dest = aux[-2..-1]\n elsif aux.match?(/^[BRQNK][1-8][a-h][1-8][+#]$/)\n aux.slice!(-1)\n first_letter = aux.slice!(0)\n arr_pieces = aux[0].match?(/[a-h]/) ? get_column(aux[0],color) : get_row(aux[0],color)\n dest = aux[-2..-1]\n elsif aux.match?(/^[BRQNK][a-h][1-8][a-h][1-8][+#]$/)\n aux.slice!(-1)\n first_letter = aux.slice!(0)\n piece_to_move = get_by_notation(aux[0..1], color)\n return unless letter_match_piece?(first_letter, piece_to_move.piece)\n dest = aux[-2..-1]\n elsif aux.match?(/^[BRQNK]x[a-h][1-8][+#]$/)\n aux.slice!(-1)\n first_letter = aux.slice!(0)\n aux = aux.split('x')\n aux.reject!(&:empty?)\n arr_pieces = find_by_name(first_letter, color)\n dest = aux[0]\n elsif aux.match?(/^[BRQNK][a-h]x[a-h][1-8][+#]$/)\n aux.slice!(-1)\n first_letter = aux.slice!(0)\n aux = aux.split('x')\n aux.reject!(&:empty?)\n arr_pieces = get_column(aux[0],color)\n dest = aux[1]\n elsif aux.match?(/^[BRQNK][1-8]x[a-h][1-8][+#]$/)\n aux.slice!(-1)\n first_letter = aux.slice!(0)\n aux = aux.split('x')\n aux.reject!(&:empty?)\n arr_pieces = get_row(aux[0],color)\n dest = aux[1]\n elsif aux.match?(/^[BRQNK][a-h][1-8]x[a-h][1-8][+#]$/)\n aux.slice!(-1)\n first_letter = aux.slice!(0)\n aux = aux.split('x')\n aux.reject!(&:empty?)\n piece_to_move = get_by_notation(aux[0], color)\n return unless letter_match_piece?(first_letter, piece_to_move.piece)\n dest = aux[1]\n elsif aux.match?(/^[a-h][1-8][+#]$/)\n aux.slice!(-1)\n arr_pieces = find_by_name(color)\n dest = aux[-2..-1]\n elsif aux.match?(/^[a-h]x[a-h][1-8][+#]$/)\n first_letter = aux.slice!(0)\n aux.slice!(-1)\n aux = aux.split('x')\n aux.reject!(&:empty?)\n arr_pieces = get_column(first_letter,color)\n dest = aux[0]\n elsif aux.match?(/^[BRQNK]x[a-h][1-8]$/)\n first_letter = aux.slice!(0)\n aux = aux.split('x')\n aux.reject!(&:empty?)\n arr_pieces = find_by_name(first_letter, color)\n dest = aux[0]\n elsif aux.match?(/^[BRQNK][a-h]x[a-h][1-8]$/)\n first_letter = aux.slice!(0)\n aux = aux.split('x')\n aux.reject!(&:empty?)\n arr_pieces = get_column(aux[0],color)\n dest = aux[1]\n elsif aux.match?(/^[BRQNK][1-8]x[a-h][1-8]$/)\n first_letter = aux.slice!(0)\n aux = aux.split('x')\n aux.reject!(&:empty?)\n arr_pieces = get_row(aux[0],color)\n dest = aux[1]\n elsif aux.match?(/^[BRQNK][a-h][1-8]x[a-h][1-8]$/)\n first_letter = aux.slice!(0)\n aux = aux.split('x')\n aux.reject!(&:empty?)\n piece_to_move = get_by_notation(aux[0], color)\n return unless letter_match_piece?(first_letter, piece_to_move.piece)\n dest = aux[1]\n elsif aux.match?(/^[a-h][1-8]$/)\n arr_pieces = find_by_name(color)\n dest = aux[-2..-1]\n elsif aux.match?(/^[a-h][18][BRQN]$/)\n letter_upgrade = aux.slice!(-1)\n arr_pieces = find_by_name(color)\n dest = aux\n elsif aux.match?(/^[a-h][18]=[BRQN]$/)\n letter_upgrade = aux.slice!(-1)\n aux = aux.split('=')\n aux.reject!(&:empty?)\n arr_pieces = find_by_name(color)\n dest = aux[0]\n elsif aux.match?(/^[a-h]x[a-h][1-8]$/)\n first_letter = aux.slice!(0)\n aux = aux.split('x')\n aux.reject!(&:empty?)\n arr_pieces = get_column(first_letter,color)\n dest = aux[0]\n elsif aux.match?(/^[a-h]x[a-h][1-8]e.p.$/)\n \n first_letter = aux.slice!(0)\n aux = aux.split('x')\n aux.reject!(&:empty?)\n arr_pieces = get_column(first_letter,color)\n aux[0].delete!('e.p.')\n dest = aux[0]\n unless arr_pieces.nil?\n arr_pieces = delete_dif_by_name(arr_pieces, first_letter, color) unless first_letter.nil?\n\n arr_pieces.delete_if {|square| !square.piece.possible_movement?(get_indices(dest))}\n\n return if arr_pieces.size != 1\n piece_to_move = arr_pieces[0]\n end\n return move_en_passant(piece_to_move.NOTATION, dest)\n elsif aux.match?(/^[a-h]x[a-h][18][QRNB]$/)\n first_letter = aux.slice!(0)\n letter_upgrade = aux.slice!(-1)\n aux = aux.split('x')\n aux.reject!(&:empty?)\n arr_pieces = get_column(first_letter,color)\n dest = aux[0]\n elsif aux.match?(/^[a-h]x[a-h][18]=[BRQN]$/)\n first_letter = aux.slice!(0)\n letter_upgrade = aux.slice!(-1)\n aux = aux.split(/x|=/)\n aux.reject!(&:empty?)\n arr_pieces = get_column(first_letter,color)\n dest = aux[0]\n end\n # Delete any piece that no match the letter given in the notation and the name of the piece (pawn if there is no letter). Also, it delete any piece that cannot move to the destination position.\n # Return nil if there is more than 1 piece of the same type that can move to destination or there is none that can move to destination.\n unless arr_pieces.nil?\n arr_pieces = delete_dif_by_name(arr_pieces, first_letter, color) unless first_letter.nil?\n arr_pieces.delete_if {|square| !square.piece.possible_movement?(get_indices(dest))}\n return if arr_pieces.size != 1\n piece_to_move = arr_pieces[0]\n end\n \n return if piece_to_move.nil?\n \n unless letter_upgrade.nil?\n move_piece(piece_to_move.NOTATION, dest)\n upgrade(dest, letter_upgrade)\n else\n move_piece(piece_to_move.NOTATION, dest)\n end\n\n end",
"def valid_moves\n\n end",
"def get_full_move\n puts \"Action Types: E to explore a tile and F to toggle a flag\".white.bold\n puts \"Enter a row, column, and action type separated by spaces:\".white.bold\n input = gets.chomp.split\n pos, action = input[0..1].map { | num | num.to_i - 1 }, input[-1]\n until valid_pos?(pos) && valid_action?(action)\n system(\"clear\")\n @board.render\n puts \"Full moves need a row, column and action type\".light_red.bold\n puts \"Action Types: E to explore a tile and F to toggle a flag\".white.bold\n puts \"Enter a row, column, and action type separated by spaces:\".white.bold\n input = gets.chomp.split\n pos, action = input[0..1].map { | num | num.to_i - 1 }, input[-1]\n end\n input\n end",
"def prepare(char)\n # temporary variables\n x, y, ai = char.x, char.y, char.ai\n # if char was attacked\n if char.attacked > 0\n # set state\n ai.state = Knockback\n # stop if force moving knockback already\n return if char.moving?\n # if forced to move\n if char.move_type == 3\n # delete pending movement commands\n char.force_move = []\n # if not moving already\n elsif !char.moving?\n # add throw back moving commands\n char.force_move = [Cache::FDirs[10 - char.direction]]\n end\n # cancel action\n char.in_action = 0\n # decrease attacked counter\n char.attacked -= 1\n # if char in action\n elsif char.in_action > 0\n # set state\n ai.state = Abort\n # if defending\n if char.ai.act.defend?\n # decrease shock count\n char.in_action -= 1\n # set state\n ai.state = Defend\n # if not freeze action and no action sprite\n elsif !char.freeze_action && char.current_sprite == ''\n # decrease shock count\n char.in_action -= 1\n end\n # if char is moving or restricted to move\n elsif char.moving? || char.restriction == 4\n # set state\n ai.state = (char.ai.act.escape? ? Escape : Abort)\n # if char needs to move\n elsif char.force_move.size > 0\n # set state\n ai.state = (char.ai.act.escape? ? Escape : MoveOnly)\n # if target exists\n elsif ai.target != nil\n # set pre-state\n ai.state = Ready\n else\n # set pre-state\n ai.state = Return\n end\n end",
"def char!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 30 )\n\n\n\n type = CHAR\n channel = ANTLR3::DEFAULT_CHANNEL\n # - - - - label initialization - - - -\n\n\n # - - - - main rule block - - - -\n # at line 203:5: '\\\\'' . '\\\\''\n match( 0x27 )\n match_any\n match( 0x27 )\n\n\n @state.type = type\n @state.channel = channel\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 30 )\n\n\n end",
"def draw\n result = true\n BOARD.each do |x|\n if x == \"X\" || x == \"O\"\n next\n elsif x == ' '\n result = false\n break\n end\n end\n result\nend",
"def _SourceContents\n while true\n\n _save1 = self.pos\n while true # choice\n _save2 = self.pos\n\n _save3 = self.pos\n while true # sequence\n _save4 = self.pos\n _tmp = match_string(\"(\")\n _tmp = _tmp ? nil : true\n self.pos = _save4\n unless _tmp\n self.pos = _save3\n break\n end\n _save5 = self.pos\n _tmp = match_string(\")\")\n _tmp = _tmp ? nil : true\n self.pos = _save5\n unless _tmp\n self.pos = _save3\n break\n end\n _save6 = self.pos\n _tmp = match_string(\">\")\n _tmp = _tmp ? nil : true\n self.pos = _save6\n unless _tmp\n self.pos = _save3\n break\n end\n _tmp = apply(:_Nonspacechar)\n unless _tmp\n self.pos = _save3\n end\n break\n end # end sequence\n\n if _tmp\n while true\n\n _save7 = self.pos\n while true # sequence\n _save8 = self.pos\n _tmp = match_string(\"(\")\n _tmp = _tmp ? nil : true\n self.pos = _save8\n unless _tmp\n self.pos = _save7\n break\n end\n _save9 = self.pos\n _tmp = match_string(\")\")\n _tmp = _tmp ? nil : true\n self.pos = _save9\n unless _tmp\n self.pos = _save7\n break\n end\n _save10 = self.pos\n _tmp = match_string(\">\")\n _tmp = _tmp ? nil : true\n self.pos = _save10\n unless _tmp\n self.pos = _save7\n break\n end\n _tmp = apply(:_Nonspacechar)\n unless _tmp\n self.pos = _save7\n end\n break\n end # end sequence\n\n break unless _tmp\n end\n _tmp = true\n else\n self.pos = _save2\n end\n break if _tmp\n self.pos = _save1\n\n _save11 = self.pos\n while true # sequence\n _tmp = match_string(\"(\")\n unless _tmp\n self.pos = _save11\n break\n end\n _tmp = apply(:_SourceContents)\n unless _tmp\n self.pos = _save11\n break\n end\n _tmp = match_string(\")\")\n unless _tmp\n self.pos = _save11\n end\n break\n end # end sequence\n\n break if _tmp\n self.pos = _save1\n break\n end # end choice\n\n break unless _tmp\n end\n _tmp = true\n set_failed_rule :_SourceContents unless _tmp\n return _tmp\n end",
"def process_char(char)\n if @stringmode\n if char == '\"'\n @stringmode = false\n else\n @stack.push(char.ord)\n end\n else\n case char\n when ' '\n when '+'\n val1 = @stack.pop\n val2 = @stack.pop\n @stack.push(val2 + val1)\n when '-'\n val1 = @stack.pop\n val2 = @stack.pop\n @stack.push(val2 - val1)\n when '*'\n val1 = @stack.pop\n val2 = @stack.pop\n @stack.push(val2 * val1)\n when '/'\n val1 = @stack.pop\n val2 = @stack.pop\n if val1.zero?\n @io.print \"Attempting to divide #{val2} by zero. What should the result be? \"\n val1 = gets.to_i\n end\n @stack.push(val2 / val1)\n when '%'\n val1 = @stack.pop\n val2 = @stack.pop\n if val1.zero?\n @io.print \"Attempting to divide #{val2} by zero. What should the result be? \"\n val1 = gets.to_i\n end\n @stack.push(val2 % val1)\n when '!'\n val = @stack.pop\n @stack.push(val.nonzero? ? 0 : 1)\n when '`'\n val1 = @stack.pop\n val2 = @stack.pop\n @stack.push(val2 > val1 ? 1 : 0)\n when '^'\n @dir = UP\n when 'v'\n @dir = DOWN\n when '<'\n @dir = LEFT\n when '>'\n @dir = RIGHT\n when '?'\n @dir = rand(4)\n when '_'\n val = @stack.pop\n @dir = val.nonzero? ? LEFT : RIGHT\n when '|'\n val = @stack.pop\n @dir = val.nonzero? ? UP : DOWN\n when '\"'\n @stringmode = true\n when ':'\n @stack.duplicate\n when '\\\\'\n @stack.swap\n when '$'\n @stack.pop\n when '.'\n val = @stack.pop\n @io.print val\n when ','\n val = @stack.pop\n @io.print val.chr\n when '#'\n advance_pc\n when 'g'\n y = @stack.pop\n x = @stack.pop\n @stack.push(@field.get(x, y).ord)\n when 'p'\n y = @stack.pop\n x = @stack.pop\n val = @stack.pop\n @field.put(val.chr, x, y)\n when '&'\n val = @io.gets.chomp\n @stack.push(val.to_i)\n when '~'\n val = @io.gets\n @stack.push(val.chr.ord)\n when '@'\n @running = false\n when '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'\n @stack.push(char.to_i)\n end\n end\n end",
"def symbol! sym\ninitialize\ns0 = new_state\ns1 = new_state\nset_start(s0)\nset_final(s1, true)\nadd_transition(s0, s1, sym)\nif sym != \"\" && @alphabet.include?(\"#{sym}\") == false\n@alphabet.push(\"#{sym}\")\nend\nend",
"def apply_rules( state )\n\t\trules_hash = self.rules_as_hash\n\t\treturn state.each_char.with_object( String.new(encoding: 'utf-8') ) do |char, new_state|\n\t\t\tnew_state << rules_hash[ char ]\n\t\tend\n\tend",
"def forward characters\n @char += characters\n char || false\n end",
"def move(states, letter)\n result = []\n states.each{|state| \n if get_transition(state, letter) != nil\n get_transition(state, letter).each{|state2| \n if !result.include?(state2)\n result.push(state2)\n end\n }\n end\n }\n return result\n end",
"def clean\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 29 )\n clean_start_index = @input.index\n\n success = false # flag used for memoization\n\n begin\n # rule memoization\n if @state.backtracking > 0 and already_parsed_rule?( __method__ )\n success = true\n return \n end\n # at line 308:8: ( 'C' | 'c' ) ( 'L' | 'l' ) ( 'E' | 'e' ) ( 'A' | 'a' ) ( 'N' | 'n' )\n if @input.peek( 1 ).between?( T__46, T__47 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__22, T__23 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__28, T__29 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__48, T__49 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__34, T__35 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n\n success = true\n\n rescue ANTLR3::Error::RecognitionError => re\n report_error(re)\n recover(re)\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 29 )\n memoize( __method__, clean_start_index, success ) if @state.backtracking > 0\n\n end\n \n return \n end",
"def valid_input?(move)\n if move.length == 2\n return move.all? do |pos| \n if pos.length == 2 \n return (\"a\"..\"h\").include?(pos[0]) && (\"1\"..\"8\").include?(pos[1])\n end\n false\n end\n end\n false\n end",
"def input_other(ch)\n\n # move\n d = NETHACK_KEYS[ch] if NETHACK_KEYS.has_key? ch\n if DIRECTIONS.has_key? d\n return [:move, d]\n\n # rest\n elsif ch == ' '\n return [:rest]\n\n end\n\n # move screen\n if CONTROL_NETHACK_KEYS.has_key? ch\n fx,fy = DIRECTIONS[CONTROL_NETHACK_KEYS[ch]]\n @rx += fx\n @ry += fy\n end\n nil\n end",
"def char\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 59 )\n\n\n return_value = CharReturnValue.new\n\n # $rule.start = the first token seen before matching\n return_value.start = @input.look\n\n\n root_0 = nil\n\n __COMILLA321__ = nil\n set322 = nil\n __COMILLA323__ = nil\n\n\n tree_for_COMILLA321 = nil\n tree_for_set322 = nil\n tree_for_COMILLA323 = nil\n\n begin\n root_0 = @adaptor.create_flat_list\n\n\n # at line 569:10: COMILLA ( EscapeSequence |~ ( '\\\\'' | '\\\\\\\\' ) ) COMILLA\n __COMILLA321__ = match( COMILLA, TOKENS_FOLLOWING_COMILLA_IN_char_2781 )\n if @state.backtracking == 0\n tree_for_COMILLA321 = @adaptor.create_with_payload( __COMILLA321__ )\n @adaptor.add_child( root_0, tree_for_COMILLA321 )\n\n end\n\n\n set322 = @input.look\n\n if @input.peek( 1 ).between?( ASIGNACION, COMA ) || @input.peek( 1 ).between?( CORDER, WS ) || @input.peek( 1 ).between?( T__81, T__82 )\n @input.consume\n if @state.backtracking == 0\n @adaptor.add_child( root_0, @adaptor.create_with_payload( set322 ) )\n end\n\n @state.error_recovery = false\n\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n\n mse = MismatchedSet( nil )\n raise mse\n\n end\n\n\n __COMILLA323__ = match( COMILLA, TOKENS_FOLLOWING_COMILLA_IN_char_2798 )\n if @state.backtracking == 0\n tree_for_COMILLA323 = @adaptor.create_with_payload( __COMILLA323__ )\n @adaptor.add_child( root_0, tree_for_COMILLA323 )\n\n end\n\n\n # - - - - - - - rule clean up - - - - - - - -\n return_value.stop = @input.look( -1 )\n\n\n if @state.backtracking == 0\n return_value.tree = @adaptor.rule_post_processing( root_0 )\n @adaptor.set_token_boundaries( return_value.tree, return_value.start, return_value.stop )\n\n end\n\n rescue ANTLR3::Error::RecognitionError => re\n report_error(re)\n recover(re)\n return_value.tree = @adaptor.create_error_node( @input, return_value.start, @input.look(-1), re )\n\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 59 )\n\n\n end\n\n return return_value\n end",
"def space!\r\n # -> uncomment the next line to manually enable rule tracing\r\n # trace_in( __method__, 3 )\r\n\r\n type = SPACE\r\n channel = ANTLR3::DEFAULT_CHANNEL\r\n\r\n \r\n # - - - - main rule block - - - -\r\n # at line 12:9: ( ' ' )+\r\n # at file 12:9: ( ' ' )+\r\n match_count_2 = 0\r\n while true\r\n alt_2 = 2\r\n look_2_0 = @input.peek( 1 )\r\n\r\n if ( look_2_0 == 0x20 )\r\n alt_2 = 1\r\n\r\n end\r\n case alt_2\r\n when 1\r\n # at line 12:9: ' '\r\n match( 0x20 )\r\n\r\n else\r\n match_count_2 > 0 and break\r\n eee = EarlyExit(2)\r\n\r\n\r\n raise eee\r\n end\r\n match_count_2 += 1\r\n end\r\n\r\n # --> action\r\n channel = HIDDEN\r\n # <-- action\r\n\r\n \r\n @state.type = type\r\n @state.channel = channel\r\n\r\n ensure\r\n # -> uncomment the next line to manually enable rule tracing\r\n # trace_out( __method__, 3 )\r\n\r\n end",
"def two_to_win(char) # X or O\n moves = []\n \n state_wins.each_with_index do |row,i|\n if row.count(char) == 1 && row.count(E) == 2\n row.each do |space|\n if space == E\n moves.push(POSITIONS[WINS[i][row.index(E)]])\n end\n end\n end\n end\n \n moves.uniq\nend",
"def readchar() end",
"def readchar() end",
"def readchar() end",
"def parse( board )\n @state[X] = 0b000000000\n @state[O] = 0b000000000\n @pot = POT.dup\n b = board.gsub(' ','')\n b.length.times{ |i|\n case b[-i] \n when 'X'\n @state[X] = @state[X] & 2**i \n @pot.delete(2**i)\n when 'O'\n @state[O] = @state[O] & 2**i\n @pot.delete(2**i)\n end\n }\n end",
"def consume\n return nil if @s.eos?\n\n @s.mark\n\n # Consume comments.\n if comment_token = consume_comments\n if @options[:preserve_comments]\n return comment_token\n else\n return consume\n end\n end\n\n # Consume whitespace.\n return create_token(:whitespace) if @s.scan(RE_WHITESPACE)\n\n char = @s.consume\n\n case char.to_sym\n when :'\"'\n consume_string\n\n when :'#'\n if @s.peek =~ RE_NAME || valid_escape?(@s.peek(2))\n create_token(:hash,\n :type => start_identifier?(@s.peek(3)) ? :id : :unrestricted,\n :value => consume_name)\n else\n create_token(:delim, :value => char)\n end\n\n when :'$'\n if @s.peek == '='\n @s.consume\n create_token(:suffix_match)\n else\n create_token(:delim, :value => char)\n end\n\n when :\"'\"\n consume_string\n\n when :'('\n create_token(:'(')\n\n when :')'\n create_token(:')')\n\n when :*\n if @s.peek == '='\n @s.consume\n create_token(:substring_match)\n\n # Non-standard: Preserve the IE * hack.\n elsif @options[:preserve_hacks] && @s.peek =~ RE_NAME_START\n @s.reconsume\n consume_ident\n\n else\n create_token(:delim, :value => char)\n end\n\n when :+\n if start_number?\n @s.reconsume\n consume_numeric\n else\n create_token(:delim, :value => char)\n end\n\n when :','\n create_token(:comma)\n\n when :-\n nextTwoChars = @s.peek(2)\n nextThreeChars = char + nextTwoChars\n\n if start_number?(nextThreeChars)\n @s.reconsume\n consume_numeric\n elsif nextTwoChars == '->'\n @s.consume\n @s.consume\n create_token(:cdc)\n elsif start_identifier?(nextThreeChars)\n @s.reconsume\n consume_ident\n else\n create_token(:delim, :value => char)\n end\n\n when :'.'\n if start_number?\n @s.reconsume\n consume_numeric\n else\n create_token(:delim, :value => char)\n end\n\n when :':'\n create_token(:colon)\n\n when :';'\n create_token(:semicolon)\n\n when :<\n if @s.peek(3) == '!--'\n @s.consume\n @s.consume\n @s.consume\n\n create_token(:cdo)\n else\n create_token(:delim, :value => char)\n end\n\n when :'@'\n if start_identifier?(@s.peek(3))\n create_token(:at_keyword, :value => consume_name)\n else\n create_token(:delim, :value => char)\n end\n\n when :'['\n create_token(:'[')\n\n when :'\\\\'\n if valid_escape?\n @s.reconsume\n consume_ident\n else\n # Parse error.\n create_token(:delim,\n :error => true,\n :value => char)\n end\n\n when :']'\n create_token(:']')\n\n when :'^'\n if @s.peek == '='\n @s.consume\n create_token(:prefix_match)\n else\n create_token(:delim, :value => char)\n end\n\n when :'{'\n create_token(:'{')\n\n when :'}'\n create_token(:'}')\n\n when :U, :u\n if @s.peek(2) =~ RE_UNICODE_RANGE_START\n @s.consume\n consume_unicode_range\n else\n @s.reconsume\n consume_ident\n end\n\n when :|\n case @s.peek\n when '='\n @s.consume\n create_token(:dash_match)\n\n when '|'\n @s.consume\n create_token(:column)\n\n else\n create_token(:delim, :value => char)\n end\n\n when :~\n if @s.peek == '='\n @s.consume\n create_token(:include_match)\n else\n create_token(:delim, :value => char)\n end\n\n else\n case char\n when RE_DIGIT\n @s.reconsume\n consume_numeric\n\n when RE_NAME_START\n @s.reconsume\n consume_ident\n\n else\n create_token(:delim, :value => char)\n end\n end\n end",
"def state_string\n state.flatten.each_with_object([]) do |square, result|\n result << square_character(square)\n end\n end",
"def letter!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 56 )\n\n type = LETTER\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 355:9: ( 'a' .. 'z' | 'A' .. 'Z' )\n if @input.peek( 1 ).between?( 0x41, 0x5a ) || @input.peek( 1 ).between?( 0x61, 0x7a )\n @input.consume\n else\n mse = MismatchedSet( nil )\n recover mse\n raise mse\n end\n\n\n\n \n @state.type = type\n @state.channel = channel\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 56 )\n\n end",
"def parse ( c )\n @parserstate = 'wait'\n retval = true\n #\n # * Фиксированное состояние (определенное): -1.\n # * Не фиксированное состояние (неопределенное): -2.\n # * Переход (смена состояний): >0.\n # \n @buffer << c\n \n #\n # Проверка переходов в другие состояния.\n #\n r = classify( @chain.last )\n\n #\n # Переход (прыжок) в другое состояние.\n # <branch>:\n #\n if r >= 0 then\n\t@chain << @states[r]\n\t@chain.last.run_init( @buffer )\n\treset( )\n\t@parserstate = 'branch'\n #\n # Возврат из текущего состояния.\n # <back>:\n #\n elsif r == -1 then\n\t@chain.last.run_fini( @buffer )\n\t#\n\t# если это состояние не первое в цепочке\n\t# тогда откатываемся назад.\n\t#\n\tif @chain.size > 1 then\n\t @chain.delete_at( @chain.size - 1 )\n\tend\n\treset( )\n\t@parserstate = 'back'\n #\n # Нет совпадений.\n # <miss>:\n #\n elsif r == -3 then\n\t#\n\t# если в процессе состояния <wait>\n\t# мы попали в <miss>, то накопленный\n\t# буфер надо обработать.\n\t#\n\t@buffer.each do |ch|\n\t @parserstate = 'miss'\n\t tag = true\n\t if @chain.last.ignore.size > 0 then\n\t tag = false if @chain.last.ignore.include?(ch)\n\t end\n\t if tag == true then\n\t r = @chain.last.run_handler( ch )\n\t #\n\t # Анализ результата обработки состояния.\n\t #\n\t case r.class.to_s\n\t #\n\t # Fixnum - переход на любое состояние (индекс).\n\t when 'Fixnum'\n\t if( (r >= 0) && (r < @states.size) ) then\n\t\t@chain << @states[r]\n\t\treset( )\n\t\t@parserstate = 'hardset'\n\t else\n\t\traise TypeError, \"Method <#{@chain.last.statename}> return incorrectly index.\"\n\t end\n\t #\n\t # nil - ничего не возвращает.\n\t when 'NilClass'\n\t #\n\t # else - расценивается как ошибка обработки.\n\t # обработка ложится на плечи разработчика.\n\t #\n\t else\n\t @parserstate = 'error'\n\t retval = false\n\t break\n\t end\n\t end\n\tend\n\t@buffer = []\n end\n return retval\n end",
"def process_character(character)\n transition = get_next_transition(character)\n get_and_set_next_transition(character) if transition.initial?\n transition\n end",
"def input_move\n input = gets.chomp.downcase\n case input\n when /[a-h][1-8][a-h][1-8]/\n process_input(input)\n when '0-0-0'\n castle(false)\n when '0-0'\n castle(true)\n when /s/, /save/\n save_game\n when 'h', 'help'\n print_in_game_help\n when 'q', 'quit', 'exit'\n quit_game\n else\n puts \"I don't understand that. Please input a move in format [starting square][destination]\n I.e. to move the piece at A1 to D4, type A1D4\"\n input_move\n end\n end",
"def get_valid_moves\n # delta = color == :white ? 1 : -1\n pos = [position[0] + direction, position[1]]\n validated_moves = capture_spaces\n validated_moves << pos if valid_move?(pos)\n unless @moved || !validated_moves.include?(pos)\n\n pos = [position[0] + (2*direction), position[1]]\n validated_moves += valid_move?(pos) ? [pos] : []\n end\n\n validated_moves\n end",
"def valid_moves(pos)\n valid_moves = []\n long = [-2,2]\n short = [1,-1]\n valid_moves += valid_moves_helper(pos, long, short)\n valid_moves += valid_moves_helper(pos, short, long)\n end",
"def starting_chars\n if self.init\n if self.init.error.kind_of? State\n :everything\n else\n self.init.keys\n end\n else\n []\n end\t\n end",
"def expected_char_checked()\n self.expected_char_checked_stm_line()\n self.expected_char_checked_stm_token()\n end",
"def ws!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 103 )\n\n type = WS\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 928:5: ( '\\\\t' | '\\\\f' | ' ' | '\\\\u00A0' )+\n # at file 928:5: ( '\\\\t' | '\\\\f' | ' ' | '\\\\u00A0' )+\n match_count_32 = 0\n while true\n alt_32 = 2\n look_32_0 = @input.peek( 1 )\n\n if ( look_32_0 == 0x9 || look_32_0 == 0xc || look_32_0 == 0x20 || look_32_0 == 0xa0 )\n alt_32 = 1\n\n end\n case alt_32\n when 1\n # at line \n if @input.peek(1) == 0x9 || @input.peek(1) == 0xc || @input.peek(1) == 0x20 || @input.peek(1) == 0xa0\n @input.consume\n else\n mse = MismatchedSet( nil )\n recover mse\n raise mse\n end\n\n\n\n else\n match_count_32 > 0 and break\n eee = EarlyExit(32)\n\n\n raise eee\n end\n match_count_32 += 1\n end\n\n # --> action\n channel = HIDDEN \n # <-- action\n\n \n @state.type = type\n @state.channel = channel\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 103 )\n\n end",
"def accept?(str)\n raise(\"no final state\") if @final.nil?\n cursor = @initial\n str.each_char { |chr|\n transition = self.follow(cursor, chr)\n return false unless transition\n cursor = transition\n }\n cursor == @final\n end",
"def letter!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 40 )\n\n type = LETTER\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 139:9: ( 'a' .. 'z' | 'A' .. 'Z' )\n if @input.peek( 1 ).between?( 0x41, 0x5a ) || @input.peek( 1 ).between?( 0x61, 0x7a )\n @input.consume\n else\n mse = MismatchedSet( nil )\n recover mse\n raise mse\n end\n\n\n\n \n @state.type = type\n @state.channel = channel\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 40 )\n\n end",
"def get_transitions(state, char)\n transition = @transition_table[state][char]\n if transition\n return [transition]\n else\n return []\n end\n end",
"def ws!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 77 )\n\n\n\n type = WS\n channel = ANTLR3::DEFAULT_CHANNEL\n # - - - - label initialization - - - -\n\n\n # - - - - main rule block - - - -\n # at line 604:6: ( ' ' | '\\\\r' | '\\\\t' | '\\\\u000C' | '\\\\n' )\n if @input.peek( 1 ).between?( 0x9, 0xa ) || @input.peek( 1 ).between?( 0xc, 0xd ) || @input.peek(1) == 0x20\n @input.consume\n else\n mse = MismatchedSet( nil )\n recover mse\n raise mse\n\n end\n\n\n\n # --> action\n channel=HIDDEN;\n # <-- action\n\n\n\n @state.type = type\n @state.channel = channel\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 77 )\n\n\n end",
"def ws!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 38 )\n\n type = WS\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 137:5: ( ' ' | '\\\\t' )+\n # at file 137:5: ( ' ' | '\\\\t' )+\n match_count_1 = 0\n while true\n alt_1 = 2\n look_1_0 = @input.peek( 1 )\n\n if ( look_1_0 == 0x9 || look_1_0 == 0x20 )\n alt_1 = 1\n\n end\n case alt_1\n when 1\n # at line \n if @input.peek(1) == 0x9 || @input.peek(1) == 0x20\n @input.consume\n else\n mse = MismatchedSet( nil )\n recover mse\n raise mse\n end\n\n\n\n else\n match_count_1 > 0 and break\n eee = EarlyExit(1)\n\n\n raise eee\n end\n match_count_1 += 1\n end\n\n\n \n @state.type = type\n @state.channel = channel\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 38 )\n\n end",
"def ws!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 7 )\n\n type = WS\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 39:6: ( ' ' | '\\\\t' | '\\\\r' | '\\\\n' )+\n # at file 39:6: ( ' ' | '\\\\t' | '\\\\r' | '\\\\n' )+\n match_count_3 = 0\n while true\n alt_3 = 2\n look_3_0 = @input.peek( 1 )\n\n if ( look_3_0.between?( 0x9, 0xa ) || look_3_0 == 0xd || look_3_0 == 0x20 )\n alt_3 = 1\n\n end\n case alt_3\n when 1\n # at line \n if @input.peek( 1 ).between?( 0x9, 0xa ) || @input.peek(1) == 0xd || @input.peek(1) == 0x20\n @input.consume\n else\n mse = MismatchedSet( nil )\n recover mse\n raise mse\n end\n\n\n\n else\n match_count_3 > 0 and break\n eee = EarlyExit(3)\n\n\n raise eee\n end\n match_count_3 += 1\n end\n\n # --> action\n skip();\n # <-- action\n\n \n @state.type = type\n @state.channel = channel\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 7 )\n\n end",
"def accept?(s, current)\nif s == \"\"\nis_final?(current)\nelse\ndest = get_transition(current,s[0,1])\nif dest == nil || dest.size > 1\nfalse\nelse\naccept?(s[1..-1], dest[0])\nend\nend\nend",
"def is_valid(s)\n return false unless s\n\n mapping = {\n ')': 'C',\n '}': '{',\n ']': '['\n }\n\n stack = []\n\n s.each_char do |c|\n if !mapping[c.to_sym]\n stack << c\n elsif mapping[c.to_sym] != stack.pop\n return false\n end\n end\n\n stack.empty? ? true : false\nend",
"def parse(board, color, move_str)\n str = move_str.gsub(/[+\\#!]/, '')\n capture = str.delete!('x')\n\n # the promotion piece setting, e.g. h8=Q\n if str =~ /^.*(=.).*$/\n Pawn.set_promotion_piece(color, \n Board::PieceLetterMap.detect{|k,v| v.include?($1[1,1])}[0])\n str.gsub!($1, '')\n end\n \n case str.length\n when 2\n move_to = send(str)\n piece_pos = [move_to[0], move_to[1] - Piece.advance_direction(color)]\n piece = board.at(piece_pos)\n piece ||= board.at([piece_pos[0], \n piece_pos[1] - Piece.advance_direction(color)])\n \n mv = piece ? piece.moves.detect{|m| m.to == move_to} : nil\n \n when 3\n if str == 'O-O'\n mv = board.king(color).moves.detect{|m| m.to_s == 'O-O'}\n else\n c = str[0,1]\n move_to = send(str[1,2])\n \n if c == c.capitalize\n klass = Board::PieceLetterMap.detect{|k,v| v.include?(c)}[0]\n moves = board.pieces.select do |p|\n p.class == klass and p.color == color\n end.map(&:moves).flatten\n mv = moves.detect{|m| m.to == move_to}\n elsif capture\n x_diff = str[0,1] > str[1,1] ? 1 : -1\n \n pieces = board.pieces.select do |p| \n p.class == Pawn and p.color == color and \\\n p.x == move_to[0] + x_diff\n end\n \n mv = pieces.map{|p| p.moves}.flatten.detect{|m| [move_to, [move_to[0], move_to[1]+m.piece.advance_direction]].include?(m.to)}\n end\n end\n \n when 4\n c = str[0,1]\n move_to = send(str[2,2])\n \n if c == c.capitalize\n klass = Board::PieceLetterMap.detect{|k,v| v.include?(c)}[0]\n x_diff = nil\n y_pos = nil\n if str[1,1] <= '9'\n y_pos = str[1,1].to_i - 1\n else\n x_diff = str[1] - str[2]\n end\n piece = board.pieces.detect do |p|\n p.class == klass and p.color == color and \\\n (x_diff ? p.x == move_to[0] + x_diff : p.y == y_pos)\n end\n mv = piece ? piece.moves.detect{|m| m.to == move_to} : nil\n else\n move_from = send(str[0,2])\n piece = board.at(move_from)\n mv = piece ? piece.moves.detect{|m| m.to == move_to} : nil\n end\n \n when 5\n if str == 'O-O-O'\n mv = board.king(color).moves.detect{|m| m.to_s == 'O-O-O'}\n else\n move_from = send(str[1,2])\n move_to = send(str[3,2])\n piece = board.at(move_from)\n mv = piece ? piece.moves.detect{|m| m.to == move_to} : nil\n end\n end\n \n raise ParseError.new(\"Invalid move: #{move_str}\") if mv.nil?\n \n mv\n end",
"def next_token\n return process_string if lex_strterm\n self.cmd_state = self.command_start\n self.command_start = false\n self.space_seen = false # TODO: rename token_seen?\n self.last_state = lex_state\n\n token = nil\n\n until ss.eos? or token do\n token =\n case state\n when nil then\n case\n when ss.skip(/[\\ \\t\\r\\f\\v]/) then\n action { self.space_seen = true; next }\n when text = ss.scan(/\\n|\\#/) then\n process_newline_or_comment text\n when text = ss.scan(/[\\]\\)\\}]/) then\n process_brace_close text\n when ss.match?(/\\!/) then\n case\n when is_after_operator? && (ss.skip(/\\!\\@/)) then\n action { result EXPR_ARG, :tUBANG, \"!@\" }\n when text = ss.scan(/\\![=~]?/) then\n action { result :arg_state, TOKENS[text], text }\n end # group /\\!/\n when ss.match?(/\\./) then\n case\n when text = ss.scan(/\\.\\.\\.?/) then\n action { result EXPR_BEG, TOKENS[text], text }\n when ss.skip(/\\.\\d/) then\n action { rb_compile_error \"no .<digit> floating literal anymore put 0 before dot\" }\n when ss.skip(/\\./) then\n action { self.lex_state = EXPR_BEG; result EXPR_DOT, :tDOT, \".\" }\n end # group /\\./\n when text = ss.scan(/\\(/) then\n process_paren text\n when text = ss.scan(/\\,/) then\n action { result EXPR_PAR, TOKENS[text], text }\n when ss.match?(/=/) then\n case\n when text = ss.scan(/\\=\\=\\=|\\=\\=|\\=~|\\=>|\\=(?!begin\\b)/) then\n action { result arg_state, TOKENS[text], text }\n when bol? && (text = ss.scan(/\\=begin(?=\\s)/)) then\n process_begin text\n when text = ss.scan(/\\=(?=begin\\b)/) then\n action { result arg_state, TOKENS[text], text }\n end # group /=/\n when ruby22_label? && (text = ss.scan(/\\\"#{SIMPLE_STRING}\\\":/o)) then\n process_label text\n when text = ss.scan(/\\\"(#{SIMPLE_STRING})\\\"/o) then\n action { result EXPR_END, :tSTRING, text[1..-2].gsub(ESC) { unescape $1 } }\n when text = ss.scan(/\\\"/) then\n action { string STR_DQUOTE; result nil, :tSTRING_BEG, text }\n when text = ss.scan(/\\@\\@?\\d/) then\n action { rb_compile_error \"`#{text}` is not allowed as a variable name\" }\n when text = ss.scan(/\\@\\@?#{IDENT_CHAR}+/o) then\n process_ivar text\n when ss.match?(/:/) then\n case\n when not_end? && (text = ss.scan(/:([a-zA-Z_]#{IDENT_CHAR}*(?:[?]|[!](?!=)|=(?==>)|=(?![=>]))?)/o)) then\n process_symbol text\n when not_end? && (text = ss.scan(/\\:\\\"(#{SIMPLE_STRING})\\\"/o)) then\n process_symbol text\n when not_end? && (text = ss.scan(/\\:\\'(#{SSTRING})\\'/o)) then\n process_symbol text\n when text = ss.scan(/\\:\\:/) then\n process_colon2 text\n when text = ss.scan(/\\:/) then\n process_colon1 text\n end # group /:/\n when ss.skip(/->/) then\n action { result EXPR_ENDFN, :tLAMBDA, nil }\n when text = ss.scan(/[+-]/) then\n process_plus_minus text\n when ss.match?(/[+\\d]/) then\n case\n when ss.skip(/#{NUM_BAD}/o) then\n action { rb_compile_error \"Invalid numeric format\" }\n when ss.skip(/#{INT_DEC}/o) then\n action { int_with_base 10 }\n when ss.skip(/#{INT_HEX}/o) then\n action { int_with_base 16 }\n when ss.skip(/#{INT_BIN}/o) then\n action { int_with_base 2 }\n when ss.skip(/#{INT_OCT_BAD}/o) then\n action { rb_compile_error \"Illegal octal digit.\" }\n when ss.skip(/#{INT_OCT}/o) then\n action { int_with_base 8 }\n when ss.skip(/#{FLOAT_BAD}/o) then\n action { rb_compile_error \"Trailing '_' in number.\" }\n when text = ss.scan(/#{FLOAT}/o) then\n process_float text\n when ss.skip(/#{INT_DEC2}/o) then\n action { int_with_base 10 }\n when ss.skip(/[0-9]/) then\n action { rb_compile_error \"Bad number format\" }\n end # group /[+\\d]/\n when text = ss.scan(/\\[/) then\n process_square_bracket text\n when was_label? && (text = ss.scan(/\\'#{SSTRING}\\':?/o)) then\n process_label_or_string text\n when ss.match?(/\\|/) then\n case\n when ss.skip(/\\|\\|\\=/) then\n action { result EXPR_BEG, :tOP_ASGN, \"||\" }\n when ss.skip(/\\|\\|/) then\n action { result EXPR_BEG, :tOROP, \"||\" }\n when ss.skip(/\\|\\=/) then\n action { result EXPR_BEG, :tOP_ASGN, \"|\" }\n when ss.skip(/\\|/) then\n action { state = is_after_operator? ? EXPR_ARG : EXPR_PAR; result state, :tPIPE, \"|\" }\n end # group /\\|/\n when text = ss.scan(/\\{/) then\n process_brace_open text\n when ss.match?(/\\*/) then\n case\n when ss.skip(/\\*\\*=/) then\n action { result EXPR_BEG, :tOP_ASGN, \"**\" }\n when ss.skip(/\\*\\*/) then\n action { result(:arg_state, space_vs_beginning(:tDSTAR, :tDSTAR, :tPOW), \"**\") }\n when ss.skip(/\\*\\=/) then\n action { result(EXPR_BEG, :tOP_ASGN, \"*\") }\n when ss.skip(/\\*/) then\n action { result(:arg_state, space_vs_beginning(:tSTAR, :tSTAR, :tSTAR2), \"*\") }\n end # group /\\*/\n when ss.match?(/</) then\n case\n when ss.skip(/\\<\\=\\>/) then\n action { result :arg_state, :tCMP, \"<=>\" }\n when ss.skip(/\\<\\=/) then\n action { result :arg_state, :tLEQ, \"<=\" }\n when ss.skip(/\\<\\<\\=/) then\n action { result EXPR_BEG, :tOP_ASGN, \"<<\" }\n when text = ss.scan(/\\<\\</) then\n process_lchevron text\n when ss.skip(/\\</) then\n action { result :arg_state, :tLT, \"<\" }\n end # group /</\n when ss.match?(/>/) then\n case\n when ss.skip(/\\>\\=/) then\n action { result :arg_state, :tGEQ, \">=\" }\n when ss.skip(/\\>\\>=/) then\n action { result EXPR_BEG, :tOP_ASGN, \">>\" }\n when ss.skip(/\\>\\>/) then\n action { result :arg_state, :tRSHFT, \">>\" }\n when ss.skip(/\\>/) then\n action { result :arg_state, :tGT, \">\" }\n end # group />/\n when ss.match?(/\\`/) then\n case\n when expr_fname? && (ss.skip(/\\`/)) then\n action { result(EXPR_END, :tBACK_REF2, \"`\") }\n when expr_dot? && (ss.skip(/\\`/)) then\n action { result((cmd_state ? EXPR_CMDARG : EXPR_ARG), :tBACK_REF2, \"`\") }\n when ss.skip(/\\`/) then\n action { string STR_XQUOTE, '`'; result(nil, :tXSTRING_BEG, \"`\") }\n end # group /\\`/\n when text = ss.scan(/\\?/) then\n process_questionmark text\n when ss.match?(/&/) then\n case\n when ss.skip(/\\&\\&\\=/) then\n action { result(EXPR_BEG, :tOP_ASGN, \"&&\") }\n when ss.skip(/\\&\\&/) then\n action { result(EXPR_BEG, :tANDOP, \"&&\") }\n when ss.skip(/\\&\\=/) then\n action { result(EXPR_BEG, :tOP_ASGN, \"&\" ) }\n when ss.skip(/\\&\\./) then\n action { result(EXPR_DOT, :tLONELY, \"&.\") }\n when text = ss.scan(/\\&/) then\n process_amper text\n end # group /&/\n when text = ss.scan(/\\//) then\n process_slash text\n when ss.match?(/\\^/) then\n case\n when ss.skip(/\\^=/) then\n action { result(EXPR_BEG, :tOP_ASGN, \"^\") }\n when ss.skip(/\\^/) then\n action { result(:arg_state, :tCARET, \"^\") }\n end # group /\\^/\n when ss.skip(/\\;/) then\n action { self.command_start = true; result(EXPR_BEG, :tSEMI, \";\") }\n when ss.match?(/~/) then\n case\n when is_after_operator? && (ss.skip(/\\~@/)) then\n action { result(:arg_state, :tTILDE, \"~\") }\n when ss.skip(/\\~/) then\n action { result(:arg_state, :tTILDE, \"~\") }\n end # group /~/\n when ss.match?(/\\\\/) then\n case\n when ss.skip(/\\\\\\r?\\n/) then\n action { self.lineno += 1; self.space_seen = true; next }\n when ss.skip(/\\\\/) then\n action { rb_compile_error \"bare backslash only allowed before newline\" }\n end # group /\\\\/\n when text = ss.scan(/\\%/) then\n process_percent text\n when ss.match?(/\\$/) then\n case\n when text = ss.scan(/\\$_\\w+/) then\n process_gvar text\n when text = ss.scan(/\\$_/) then\n process_gvar text\n when text = ss.scan(/\\$[~*$?!@\\/\\\\;,.=:<>\\\"]|\\$-\\w?/) then\n process_gvar text\n when in_fname? && (text = ss.scan(/\\$([\\&\\`\\'\\+])/)) then\n process_gvar text\n when text = ss.scan(/\\$([\\&\\`\\'\\+])/) then\n process_backref text\n when in_fname? && (text = ss.scan(/\\$([1-9]\\d*)/)) then\n process_gvar text\n when text = ss.scan(/\\$([1-9]\\d*)/) then\n process_nthref text\n when text = ss.scan(/\\$0/) then\n process_gvar text\n when text = ss.scan(/\\$[^[:ascii:]]+/) then\n process_gvar text\n when text = ss.scan(/\\$\\W|\\$\\z/) then\n process_gvar_oddity text\n when text = ss.scan(/\\$\\w+/) then\n process_gvar text\n end # group /\\$/\n when text = ss.scan(/\\_/) then\n process_underscore text\n when text = ss.scan(/#{IDENT}/o) then\n process_token text\n when ss.skip(/\\004|\\032|\\000|\\Z/) then\n action { [RubyLexer::EOF, RubyLexer::EOF] }\n when text = ss.scan(/./) then\n action { rb_compile_error \"Invalid char #{text.inspect} in expression\" }\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n else\n raise ScanError, \"undefined state at #{location}: '#{state}'\"\n end # token = case state\n\n next unless token # allow functions to trigger redo w/ nil\n end # while\n\n raise LexerError, \"bad lexical result at #{location}: #{token.inspect}\" unless\n token.nil? || (Array === token && token.size >= 2)\n\n # auto-switch state\n self.state = token.last if token && token.first == :state\n\n token\n end",
"def _lex_from_state_actions; end",
"def _lex_from_state_actions; end",
"def _lex_from_state_actions; end",
"def _lex_from_state_actions; end",
"def st!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 49 )\n\n type = ST\n channel = ANTLR3::DEFAULT_CHANNEL\n # - - - - label initialization - - - -\n d = nil\n\n\n \n # - - - - main rule block - - - -\n # at line 348:5: d= ( ( DIGIT )* ) '1' ( 'S' | 's' ) ( 'T' | 't' )\n # at line 348:7: ( ( DIGIT )* )\n # at line 348:8: ( DIGIT )*\n # at line 348:8: ( DIGIT )*\n while true # decision 1\n alt_1 = 2\n look_1_0 = @input.peek( 1 )\n\n if ( look_1_0 == 0x31 )\n look_1_1 = @input.peek( 2 )\n\n if ( look_1_1.between?( 0x30, 0x39 ) )\n alt_1 = 1\n\n end\n elsif ( look_1_0 == 0x30 || look_1_0.between?( 0x32, 0x39 ) )\n alt_1 = 1\n\n end\n case alt_1\n when 1\n # at line 348:8: DIGIT\n digit!\n\n else\n break # out of loop for decision 1\n end\n end # loop for decision 1\n\n match( 0x31 )\n if @input.peek(1) == 0x53 || @input.peek(1) == 0x73\n @input.consume\n else\n mse = MismatchedSet( nil )\n recover mse\n raise mse\n end\n\n\n if @input.peek(1) == 0x54 || @input.peek(1) == 0x74\n @input.consume\n else\n mse = MismatchedSet( nil )\n recover mse\n raise mse\n end\n\n\n\n \n @state.type = type\n @state.channel = channel\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 49 )\n\n end",
"def valid(str)\n direction = Hash.new(0)\n str.each_char do |ch|\n direction[ch] += 1\n end\n if (direction['n'] == direction['s'] && direction['e'] == direction['w'])\n print true\n else\n print false\n end\n\n\nend",
"def move(arr, letter)\nresult = []\narr.each{|a|\nlist = get_transition(a, letter)\nif list != nil\nresult = result | list\nend\n}\nresult\nend",
"def parse_moves\n s0 = @scanner.pos\n s1 = parse_firstboard\n if s1 == :failed\n @scanner.pos = s0\n s0 = :failed\n else\n parse_split\n s2 = []\n s3 = parse_move\n while s3 != :failed\n s2 << s3\n s3 = parse_move\n end\n parse_result\n @reported_pos = s0\n s0 = s2.unshift(s1)\n end\n s0\n end",
"def possible_moves\r\n return [] if won?\r\n (0..8).select {|i| board.cells[i] == \" \"}\r\n end",
"def ws!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 36 )\n\n type = WS\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 353:9: ( ' ' | '\\\\t' | '\\\\r' | '\\\\n' )\n if @input.peek( 1 ).between?( 0x9, 0xa ) || @input.peek(1) == 0xd || @input.peek(1) == 0x20\n @input.consume\n else\n mse = MismatchedSet( nil )\n recover mse\n raise mse\n end\n\n\n # --> action\n channel=HIDDEN;\n # <-- action\n\n \n @state.type = type\n @state.channel = channel\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 36 )\n\n end",
"def letter!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 47 )\n\n \n # - - - - main rule block - - - -\n # at line \n if @input.peek( 1 ).between?( 0x41, 0x5a ) || @input.peek( 1 ).between?( 0x61, 0x7a )\n @input.consume\n else\n mse = MismatchedSet( nil )\n recover mse\n raise mse\n end\n\n\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 47 )\n\n end",
"def walk(_str, _index, _new_stack)\n\t#$ID += 1\n\tsmiley = false\n\tillegal = false\n\t_stack = Array.new(_new_stack)\n\t# puts \"[#{$ID}] \" + _str + \" + \" + _stack.join\n\tprev = ''\n\tlen = _str.length\n\n\t_str.each_char do |chr|\n\t\t# found illegal char\n\t\tif !$valid_chars.include? chr\n\t\t\t# balanced = NO\n\t\t\tillegal = true\n\t\t\tbreak\n\t\tend\n\n\t\t# watch for smiley at next interation\n\t\tif chr == ':'\n\t\t\tsmiley = true\n\t\t\tprev = chr\n\t\t\t_index += 1\n\t\t\tnext\n\t\tend\n\n\t\t# found possible smiley\n\t\tif (chr == '(' or chr == ')') and smiley == true\n\t\t\tif _index <= len\n\t\t\t\t#puts \"index: #{_index}\"\n\t\t\t\t_new_index = 0\n\t\t\t\t# puts \"[#{$ID}] \" + \"pass _stack: #{_stack.join}\"\n\t\t\t\twalk(_str[_index, len], _new_index, _stack)\n\t\t\tend\n\t\t\t# continue on this side with treating it as smiley\n\t\t\tsmiley = false\n\t\t\t_index += 1\n\t\t\tnext\n\t\t\t# end\n\t\tend\n\n\t\t# found regular ( paranthesis\n\t\tif chr == '('\n\t\t\t_stack.push(chr)\n\t\t\t# puts \"[#{$ID}] \" + \"push(#{_index})_stack: #{_stack.join}\"\n\t\t\t_index += 1\n\t\t\tnext\n\t\tend\n\n\t\t# found regular ) paranthesis\n\t\tif chr == ')'\n\t\t\t# if there is an ( paranthesis\n\t\t\tif _stack.size > 0\n\t\t\t\t_stack.pop\n\t\t\t\t# puts \"[#{$ID}] \" + \"pop(#{_index})_stack: #{_stack.join}\"\n\t\t\t\t_index += 1\n\t\t\t\tnext\n\t\t\telse\n\t\t\t\t# unbalanced paranthesis\n\t\t\t\tillegal = true\n\t\t\t\tbreak\n\t\t\tend\n\t\tend\n\n\t\t# other char after : -> reset smiley flag\n\t\tif smiley == true\n\t\t\tsmiley = false\n\t\t\t_index += 1\n\t\t\tnext\n\t\tend\n\n\t\t# any other char\n\t\t_index += 1\n\t\tnext\n\tend\n\n\t# check to see how we finished traversing the string\n\tif (_stack.size > 0 or illegal == true) and $balanced != YES\n\t\t$balanced = NO\n\telsif illegal == false\n\t\t$balanced = YES\n\tend\nend",
"def read_character\n unless @input.empty?\n result(@input.at(0), advance(1))\n else\n failure(\"less than one character available\")\n end\n end",
"def valid_moves\n moves.reject { |end_pos| move_into_check?(end_pos) }\n end",
"def parse_moves\n s0 = @scanner.pos\n s1 = parse_firstboard\n if s1 == :failed\n @scanner.pos = s0\n s0 = :failed\n else\n s2 = []\n s3 = parse_move\n while s3 != :failed\n s2 << s3\n s3 = parse_move\n end\n s3 = parse_result\n s3 = nil if s3 == :failed\n @reported_pos = s0\n s0 = -> (hd, tl, res) do\n tl.unshift(hd)\n tl << { 'special' => res } if res && !tl[tl.length - 1]['special']\n tl\n end.call(s1, s2, s3)\n end\n s0\n end",
"def ws!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 48 )\n\n type = WS\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 185:12: ( '\\\\t' | ' ' | '\\\\r' | '\\\\n' | '\\\\u000C' )+\n # at file 185:12: ( '\\\\t' | ' ' | '\\\\r' | '\\\\n' | '\\\\u000C' )+\n match_count_4 = 0\n while true\n alt_4 = 2\n look_4_0 = @input.peek( 1 )\n\n if ( look_4_0.between?( 0x9, 0xa ) || look_4_0.between?( 0xc, 0xd ) || look_4_0 == 0x20 )\n alt_4 = 1\n\n end\n case alt_4\n when 1\n # at line \n if @input.peek( 1 ).between?( 0x9, 0xa ) || @input.peek( 1 ).between?( 0xc, 0xd ) || @input.peek(1) == 0x20\n @input.consume\n else\n mse = MismatchedSet( nil )\n recover mse\n raise mse\n end\n\n\n\n else\n match_count_4 > 0 and break\n eee = EarlyExit(4)\n\n\n raise eee\n end\n match_count_4 += 1\n end\n\n\n \n @state.type = type\n @state.channel = channel\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 48 )\n\n end",
"def chars\n return to_enum :chars unless block_given?\n while c = getc\n yield c\n end\n end",
"def read( start_position )\n pos = start_position.adjusted_stream_position\n line_number = column_number = 0\n\n if @source.at_eof?(stream_position) then\n line_number = @source.eof_line_number\n column_number = @source.eof_column_number\n else\n line_number = @source.line_number(stream_position)\n column_number = @source.column_number(stream_position)\n end\n \n characters = []\n states = [ start_position.state ]\n\n forever do\n c = readc(pos)\n action = states[-1].action_for( c )\n \n case action\n \n #\n # Read a single character and prepare to move on.\n \n when Plan::Actions::Read\n characters << c\n states << action.to_state\n pos += 1\n \n \n #\n # Group several characters for further processing. Unlike in the Parser, we\n # perform the Shift here directly. We don't move the pos, because nothing was\n # used.\n \n when Plan::Actions::Group\n length = action.by_production.length\n group = characters.slice!(-length..-1)\n states.slice!(-length..-1)\n states << states[-1].action_for(action.by_production.name).to_state\n characters << group\n\n\n #\n # Tokenize ends the read() operation. We set our answer into the start_position\n # and return.\n \n when Plan::Actions::Tokenize\n length = action.by_production.length\n if characters.length == length then\n start_position.determinant = Nodes::Token.new( characters.flatten, action.by_production.name, start_position.adjusted_stream_position, line_number, column_number, @source )\n break\n else\n nyi( \"error handling for too short Tokenize\" )\n end\n \n \n #\n # For lexical stuff, all Attempt actions will be of the same type. For Group\n # actions, we want the longest match (always), so we need to try all branches\n # and find the longest Token produced. For Tokenize, we need to interact with\n # the Parser's BranchInfo system.\n \n when Plan::Actions::Attempt\n case action.actions[0]\n when Plan::Actions::Group\n nyi()\n when Plan::Actions::Tokenize\n nyi()\n else\n nyi( \"attempt support for #{action.actions[0].class.name}\" )\n end\n \n \n #\n # If there is no action, we've got an error.\n \n when NilClass\n nyi( \"error\" )\n \n else\n nyi( \"not supported\", action )\n end\n end\n end",
"def map_key_to_move\n c = read_char\n step = @step\n step ||= 1\n case c\n when ' '\n puts 'SPACE'\n park\n when \"\\t\"\n puts 'TAB'\n :stop\n when \"\\r\"\n puts 'RETURN'\n :stop\n when \"\\n\"\n puts 'LINE FEED'\n :stop\n when \"\\e\"\n puts 'ESCAPE'\n :stop\n when \"\\e[A\", 'w'\n up step\n when \"\\e[B\", 's'\n down step\n when \"\\e[C\", 'd'\n right step\n when \"\\e[D\", 'a'\n left step\n when '+', 'r'\n forward step\n when '-', 'f'\n back step\n when 'q'\n gripper_on\n when 'e'\n gripper_off\n when ','\n gripper_close(5)\n when '.'\n gripper_open(5)\n when 'j'\n wrist_left\n when 'l'\n wrist_right\n when 'i'\n wrist_up\n when 'k'\n wrist_down\n when \"\\177\"\n log 'BACKSPACE', true\n :stop\n when \"\\004\"\n log 'DELETE', true\n :stop\n when \"\\e[3~\"\n log 'ALTERNATE DELETE', true\n :stop\n when \"\\u0003\"\n log 'CONTROL-C', true\n :stop\n when /^.$/\n log \"SINGLE CHAR HIT: #{c.inspect}\"\n :stop\n else\n log \"SOMETHING ELSE: #{c.inspect}\"\n :stop\n end\n end",
"def parse(char = \" \")\n consumed = \"\"\n while c = consume\n break if c == char || c == \"\\n\"\n consumed += c\n end\n return consumed\nend",
"def feed(input)\n head = @start.to_s\n input.each_char { |symbol| head = @transitions[head][symbol] }\n accept = is_accept_state? head\n resp = {\n input: input,\n accept: accept,\n head: head \n }\n resp\n end",
"def ws!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 54 )\n\n type = WS\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 353:5: ( ' ' | '\\\\t' )+\n # at file 353:5: ( ' ' | '\\\\t' )+\n match_count_5 = 0\n while true\n alt_5 = 2\n look_5_0 = @input.peek( 1 )\n\n if ( look_5_0 == 0x9 || look_5_0 == 0x20 )\n alt_5 = 1\n\n end\n case alt_5\n when 1\n # at line \n if @input.peek(1) == 0x9 || @input.peek(1) == 0x20\n @input.consume\n else\n mse = MismatchedSet( nil )\n recover mse\n raise mse\n end\n\n\n\n else\n match_count_5 > 0 and break\n eee = EarlyExit(5)\n\n\n raise eee\n end\n match_count_5 += 1\n end\n\n\n \n @state.type = type\n @state.channel = channel\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 54 )\n\n end",
"def valid_input?(user_input)\n #regex for valid input\n proper_format = /^[a-zA-Z][1-8] [a-zA-Z][1-8]$/ #Example: A1 B2 or c3 G4\n if proper_format.match(user_input)\n move = user_input.split(\" \")\n if move[0] == move[1] #if start and end position are the same\n puts \"Not a valid move! The start and end positions are the same!\"\n puts\n return false\n else #else check other cases\n start_pos = [move[0][1].to_i - 1, @@file_num[move[0][0]]]\n end_pos = [move[1][1].to_i - 1, @@file_num[move[1][0]]]\n if !@board[start_pos] #if nothing at start position\n puts \"There is no piece at #{move[0]}!\"\n puts\n return false\n else #return the move if it passes all other cases\n puts\n return [start_pos, end_pos]\n end\n end\n else\n puts\n puts \"Not a valid input!\"\n puts\n return false\n end\n end",
"def ws!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 48 )\n\n\n\n type = WS\n channel = ANTLR3::DEFAULT_CHANNEL\n # - - - - label initialization - - - -\n\n\n # - - - - main rule block - - - -\n # at line 227:5: ( ' ' | '\\\\t' )+\n # at file 227:5: ( ' ' | '\\\\t' )+\n match_count_5 = 0\n while true\n alt_5 = 2\n look_5_0 = @input.peek( 1 )\n\n if ( look_5_0 == 0x9 || look_5_0 == 0x20 )\n alt_5 = 1\n\n end\n case alt_5\n when 1\n # at line \n if @input.peek(1) == 0x9 || @input.peek(1) == 0x20\n @input.consume\n else\n mse = MismatchedSet( nil )\n recover mse\n raise mse\n\n end\n\n\n\n else\n match_count_5 > 0 and break\n eee = EarlyExit(5)\n\n\n raise eee\n end\n match_count_5 += 1\n end\n\n\n\n # --> action\n channel = HIDDEN\n # <-- action\n\n\n\n @state.type = type\n @state.channel = channel\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 48 )\n\n\n end",
"def get_valid_moves(dictionary)\n #iterates through each letter of the alphabet and checks to see how many moves can be made after adding that letter\n #if the letter would make a word then we skip that letter\n #returns a hash where keys are the letters that don't make a word and values are how many possible moves can be made after using that letter\n #also removes any letters that don't have any possible moves after (those would be invalid moves)\n valid_moves = {}\n \n if @current_fragment == '' #if ROB is the first player return a hash with all letters with value 1\n ALPHABET.each do |letter|\n valid_moves[letter] = 1\n end\n return valid_moves\n end\n \n \n ALPHABET.each do |letter|\n valid_moves[letter] = 0\n end\n \n ALPHABET.each do |guess| \n test_string = @current_fragment+guess\n if !dictionary.include?(test_string)\n valid_moves[guess] = dictionary.count {|word| word[0...test_string.length].include?(test_string)}\n end\n end\n\n if valid_moves.values.uniq.length > 1\n return valid_moves.keep_if {|letter,count| count > 0}\n else\n valid_moves\n end\n end",
"def move(stage,level)\n\tcase read_char\n \twhen \"\\e[C\"\n \t\t#right character \n \t\tif canMoveRight(stage)\n \t\t\treturn moveRight(stage)\n \t\tend\n \twhen \"\\e[D\"\n \t\t#left character \n \t\tif canMoveLeft(stage)\n \t\t\treturn moveLeft(stage)\n \t\tend\n \twhen \"\\e[A\" \n\t\t#up character\n\t\tif canClimb(stage)\n\t\t\treturn climb(stage)\n\t\tend\n\twhen \"\\e[B\"\n \t\t#down character\n \t\tif blockPresent(stage)\n \t\t\treturn moveBlock(stage)\n \t\tend\n \twhen \"\\u0003\"\n \toverwrite($linePrinted, true)\n \texit 0\n when \"r\"\n \toverwrite($linePrinted, true)\n \t\tplayBlockMan(level)\n \twhen \"s\"\n \t\tnumber = read_char\n \t\toverwrite($linePrinted, true)\n \t\tplayBlockMan(number.to_i)\n \telse\n \t\t\n \tend\n \tmove(stage,level)\nend",
"def state_machine()\n parse_sucess = false\n if event_block && optional_reset_block()\n # if event_block() && optional_reset_block() &&\n # optional_command_block() && state_list()\n parse_sucess = true\n end\n parse_sucess\n end",
"def _lex_to_state_actions; end",
"def _lex_to_state_actions; end",
"def _lex_to_state_actions; end",
"def _lex_to_state_actions; end",
"def on(input)\n stack = Stack.new\n chars = input.chars.to_a\n\n chars.each do |char|\n if \"({[\".include?(char)\n stack.push(char)\n else\n opening = stack.pop\n\n return false unless valid_closing?(opening, char)\n end\n end\n\n stack.size == 0\n end",
"def execute\n state = current_state\n line.each_char do |character|\n state = current_state\n transition = process_character(character)\n log_initial_transition(transition, state)\n self.token += character\n end\n logger.log(state: state, character: token)\n end",
"def actions_for(state)\n actions = []\n\n state.free_cells.each_with_index do |free_cell, i|\n next if free_cell.nil?\n m = FreeToFoundationMove.new(state, free_cell, i)\n actions << m if m.valid?\n end\n\n # last card in column moves\n state.columns.each_with_index do |column, i|\n card = column.last\n next if card.nil?\n\n m1 = ColumnToFoundationMove.new(state, card, i)\n actions << m1 if m1.valid?\n\n m2 = ColumnToFreeMove.new(state, card, i)\n actions << m2 if m2.valid?\n end\n\n\n # column to column -- for each end card in each column...\n state.columns.each_with_index do |column, i|\n card = column.last\n idx = [i, column.index(card)]\n next if card.nil? # no need to try moving a blank...\n\n opts = { :state => state.clone, :card => card, :card_index => idx }\n state.columns.each_with_index do |target_col, j|\n next if i == j\n\n opts[:target_idx] = j\n m = ColumnToColumnMove.new(opts)\n actions << m if m.valid?\n end\n end\n\n # free to column\n opts = {:state => state}\n state.free_cells.each_with_index do |free_cell, i|\n next if free_cell.nil?\n opts.merge!({:card => free_cell, :card_index => i})\n state.columns.each_with_index do |target_col, target_idx|\n opts[:target_idx] = target_idx\n m = FreeToColumnMove.new(opts)\n actions << m if m.valid?\n end\n end\n\n actions\n end",
"def valid_white_rook(start,dest)\n x = start[0]; y = start[1]\n x1 = dest[0]; y1 = dest[1]\n\n xtrans = x\n ytrans = y\n\n return false if white_owned(x1,y1)\n\n #Getting the one space moves for the square around the rook\n if x1 == x+1 && y1 == y\n @black_piece.push(@b[x1][y1]) if black_owned(x1,y1)\n @b[x][y] = \" \"\n @wht_rook_left_move = true if x == 0 && y == 0\n @wht_rook_right_move = true if x == 7 && y == 0\n @b[x1][y1] = @WR\n return true\n elsif x1 == x-1 && y1 == y\n @black_piece.push(@b[x1][y1]) if black_owned(x1,y1)\n @b[x][y] = \" \"\n @wht_rook_left_move = true if x == 0 && y == 0\n @wht_rook_right_move = true if x == 7 && y == 0\n @b[x1][y1] = @WR\n return true\n elsif x1 == x && y1 == y+1\n @black_piece.push(@b[x1][y1]) if black_owned(x1,y1)\n @b[x][y] = \" \"\n @wht_rook_left_move = true if x == 0 && y == 0\n @wht_rook_right_move = true if x == 7 && y == 0\n @b[x1][y1] = @WR\n return true\n elsif x1 == x && y1 == y-1\n @black_piece.push(@b[x1][y1]) if black_owned(x1,y1)\n @b[x][y] = \" \"\n @wht_rook_left_move = true if x == 0 && y == 0\n @wht_rook_right_move = true if x == 7 && y == 0\n @b[x1][y1] = @WR\n return true\n end\n\n #The spaces that are +1 further away\n if x1 > x+1 && y1 == y\n while xtrans < x1-1 do\n xtrans += 1\n if @b[xtrans][ytrans] != \" \"\n return false #blockaded!\n end\n end\n @black_piece.push(@b[x1][y1]) if black_owned(x1,y1)\n @b[x][y] = \" \"\n @wht_rook_left_move = true if x == 0 && y == 0\n @wht_rook_right_move = true if x == 7 && y == 0\n @b[x1][y1] = @WR\n return true\n elsif x1 < x-1 && y1 == y\n while xtrans > x1+1 do\n xtrans -= 1\n if @b[xtrans][ytrans] != \" \"\n return false #blockaded!\n end\n end\n @black_piece.push(@b[x1][y1]) if black_owned(x1,y1)\n @b[x][y] = \" \"\n @wht_rook_left_move = true if x == 0 && y == 0\n @wht_rook_right_move = true if x == 7 && y == 0\n @b[x1][y1] = @WR\n return true\n elsif x1 == x && y1 > y+1\n while ytrans < y1-1 do\n ytrans += 1\n if @b[xtrans][ytrans] != \" \"\n return false #blockaded!\n end\n end\n @black_piece.push(@b[x1][y1]) if black_owned(x1,y1)\n @b[x][y] = \" \"\n @wht_rook_left_move = true if x == 0 && y == 0\n @wht_rook_right_move = true if x == 7 && y == 0\n @b[x1][y1] = @WR\n return true\n elsif x1 == x && y1 < y-1\n while ytrans > y1+1 do\n ytrans -= 1\n if @b[xtrans][ytrans] != \" \"\n return false #blockaded!\n end\n end\n @black_piece.push(@b[x1][y1]) if black_owned(x1,y1)\n @b[x][y] = \" \"\n @wht_rook_left_move = true if x == 0 && y == 0\n @wht_rook_right_move = true if x == 7 && y == 0\n @b[x1][y1] = @WR\n return true\n end\n return false\n end",
"def get_move(possibles)\n begin\n ch = STDIN.getch\n exit(1) if ch == \"\\u0003\"\n move = ch.to_i - 1\n end until possibles.include? move\n move\n end",
"def turn(board)\n puts \"Please enter 1-9:\"\n position = gets.strip()\n valid = false\n while valid == false\n if valid_move?(board, position)\n move(board, position, current_player(board))\n valid = true\n else\n puts \"Invalid Move. Please enter 1-9:\"\n position = gets.strip()\n end\n end\nend",
"def next_token\n\n token = nil\n\n until ss.eos? or token do\n token =\n case state\n when nil then\n case\n when text = ss.scan(/#{DIGIT}/) then\n action { [:DIGIT, text.to_i] }\n when text = ss.scan(/#{ADDITION}/) then\n action { [:ADDITION, text] }\n when text = ss.scan(/#{SUBSTRACTION}/) then\n action { [:SUBSTRACTION, text] }\n when text = ss.scan(/#{MULTIPLICATION}/) then\n action { [:MULTIPLICATION, text] }\n when text = ss.scan(/#{DIVISION}/) then\n action { [:DIVISION, text] }\n when text = ss.scan(/#{OPENING_PARANTHESIS}/) then\n action { [:OPENING_PARANTHESIS, text] }\n when text = ss.scan(/#{CLOSING_PARANTHESIS}/) then\n action { [:CLOSING_PARANTHESIS, text] }\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n else\n raise ScanError, \"undefined state at #{location}: '#{state}'\"\n end # token = case state\n\n next unless token # allow functions to trigger redo w/ nil\n end # while\n\n raise LexerError, \"bad lexical result at #{location}: #{token.inspect}\" unless\n token.nil? || (Array === token && token.size >= 2)\n\n # auto-switch state\n self.state = token.last if token && token.first == :state\n\n token\n end",
"def chunk_char!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 14 )\n\n \n # - - - - main rule block - - - -\n # at line 68:3: (~ ( '>' | '<' | '#' | '`' | '\\\"' | '\\\\'' | '|' | '(' | ')' | '$' | ';' | ' ' | '?' | '*' | '~' | '\\\\\\\\' | '\\\\t' | '{' | '}' | '\\\\n' | '\\\\r' ) | '\\\\\\\\' . )\n alt_23 = 2\n look_23_0 = @input.peek( 1 )\n\n if ( look_23_0.between?( 0x0, 0x8 ) || look_23_0.between?( 0xb, 0xc ) || look_23_0.between?( 0xe, 0x1f ) || look_23_0 == 0x21 || look_23_0.between?( 0x25, 0x26 ) || look_23_0.between?( 0x2b, 0x3a ) || look_23_0 == 0x3d || look_23_0.between?( 0x40, 0x5b ) || look_23_0.between?( 0x5d, 0x5f ) || look_23_0.between?( 0x61, 0x7a ) || look_23_0.between?( 0x7f, 0xffff ) )\n alt_23 = 1\n elsif ( look_23_0 == 0x5c )\n alt_23 = 2\n else\n raise NoViableAlternative( \"\", 23, 0 )\n end\n case alt_23\n when 1\n # at line 68:5: ~ ( '>' | '<' | '#' | '`' | '\\\"' | '\\\\'' | '|' | '(' | ')' | '$' | ';' | ' ' | '?' | '*' | '~' | '\\\\\\\\' | '\\\\t' | '{' | '}' | '\\\\n' | '\\\\r' )\n if @input.peek( 1 ).between?( 0x0, 0x8 ) || @input.peek( 1 ).between?( 0xb, 0xc ) || @input.peek( 1 ).between?( 0xe, 0x1f ) || @input.peek(1) == 0x21 || @input.peek( 1 ).between?( 0x25, 0x26 ) || @input.peek( 1 ).between?( 0x2b, 0x3a ) || @input.peek(1) == 0x3d || @input.peek( 1 ).between?( 0x40, 0x5b ) || @input.peek( 1 ).between?( 0x5d, 0x5f ) || @input.peek( 1 ).between?( 0x61, 0x7a ) || @input.peek( 1 ).between?( 0x7f, 0xff )\n @input.consume\n else\n mse = MismatchedSet( nil )\n recover mse\n raise mse\n end\n\n\n\n when 2\n # at line 70:5: '\\\\\\\\' .\n match( 0x5c )\n match_any\n\n end\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 14 )\n\n end",
"def valid_moves\n super\n end"
] |
[
"0.61441314",
"0.59424835",
"0.59123296",
"0.5880086",
"0.58797586",
"0.58199096",
"0.5812115",
"0.5761823",
"0.5670031",
"0.56590533",
"0.5644181",
"0.56257427",
"0.5615889",
"0.561159",
"0.55772066",
"0.55520207",
"0.55369925",
"0.55336136",
"0.5531898",
"0.5525613",
"0.5525609",
"0.55083656",
"0.5507555",
"0.5503147",
"0.54940856",
"0.5491945",
"0.5487671",
"0.54767275",
"0.54743063",
"0.5459559",
"0.5449603",
"0.54276353",
"0.5421692",
"0.54193664",
"0.54080737",
"0.54031885",
"0.5402063",
"0.5402063",
"0.5402063",
"0.53850406",
"0.53829414",
"0.53751665",
"0.5364476",
"0.536284",
"0.5360071",
"0.53576356",
"0.53565776",
"0.53542215",
"0.53408647",
"0.5334841",
"0.5319846",
"0.5318985",
"0.5316441",
"0.5312777",
"0.530162",
"0.53010505",
"0.529973",
"0.5298443",
"0.5297892",
"0.5297699",
"0.5293724",
"0.5290485",
"0.5290485",
"0.5290485",
"0.5290485",
"0.52850485",
"0.52837896",
"0.52731127",
"0.5272175",
"0.52691007",
"0.5268252",
"0.52639383",
"0.5259576",
"0.525772",
"0.5249849",
"0.5249287",
"0.52448684",
"0.5227618",
"0.5222851",
"0.5222727",
"0.5221508",
"0.5217763",
"0.52143013",
"0.52142537",
"0.52124274",
"0.52101666",
"0.5207807",
"0.520454",
"0.5201366",
"0.5201366",
"0.5201366",
"0.5201366",
"0.5196264",
"0.5190804",
"0.5189701",
"0.5185982",
"0.51834095",
"0.5173653",
"0.5169177",
"0.51661116",
"0.5164628"
] |
0.0
|
-1
|
Gets all rules that respond to a char in a given state.
|
def rules_for(state, char)
rules.select { |rule| rule.applies_to?(state, char) }
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def rule_for(state, character)\n self.rules.detect{ |rule| rule.applies_to?(state, character) } #detect == find\n end",
"def follow_rules_for(state, char)\n rules_for(state, char).map(&:follow)\n end",
"def rules_for(configuration, character)\n # note that it is select (filter), not detect (find)\n rules.select {|rule| rule.applies_to?(configuration, character)}\n end",
"def apply_rules( state )\n\t\trules_hash = self.rules_as_hash\n\t\treturn state.each_char.with_object( String.new(encoding: 'utf-8') ) do |char, new_state|\n\t\t\tnew_state << rules_hash[ char ]\n\t\tend\n\tend",
"def get_transitions(state, char)\n transition = @transition_table[state][char]\n if transition\n return [transition]\n else\n return []\n end\n end",
"def follow_rules_for(configuration, character)\n rules_for(configuration, character).map {|rule| rule.follow(configuration)}\n end",
"def rules\n return @rules unless @rules.nil?\n\n # this initialization code runs only once\n @rules = {}\n 7.downto(0).each do |rule_key|\n key = rule_key.to_s(2).rjust(3, '0') # convert to binary, pad left with 0\n @rules[key.to_sym] = RULE_NAME >> rule_key & 1 # just the one bit\n end\n\n @rules\n end",
"def translate_states_and_rules(states)\n # new rules, one state(set of states) to all character\n rules = states.flat_map { |state| rules_for state }\n # set of states that a state can reach(nfa.next_state)\n # treated as a new state\n more_states = rules.map(&:next_state).to_set\n # if true, then all states rule had been added to rules\n if more_states.subset? states\n [states, rules]\n else\n translate_states_and_rules(states + more_states)\n end\n end",
"def rules_as_hash\n\t\tunless @rules_as_hash\n\t\t\t@rules_as_hash = self.rules.each_with_object( {} ) do |rule, hash|\n\t\t\t\tpred, succ = self.parse_rule( rule )\n\t\t\t\thash[ pred ] = succ\n\t\t\tend\n\n\t\t\tself.alphabet.each do |char|\n\t\t\t\t@rules_as_hash[ char ] = char unless @rules_as_hash.key?( char )\n\t\t\tend\n\t\tend\n\n\t\treturn @rules_as_hash\n\tend",
"def rules_by_name; end",
"def get_next_state(char)\n @@scan_table[@state - 1].find(lambda {[0, 1]}) { |rule| char =~ rule[0] }[1]\n end",
"def all\n @rules\n end",
"def rules\n @rules.map{|r| [r.name, r.rule]}.to_h\n end",
"def rules\n return @rules\n end",
"def rules\n @rules ||= []\n end",
"def rules\n @rules ||= []\n end",
"def get_rules\r\n @rules\r\n end",
"def rules(event)\n @rules[event]\n end",
"def all\n @rules ||= raw.values.flatten.map { |rule| Accessibility::Rule.new(rule) }\n end",
"def result\n\n # start the matching of the ruleby engine if not yet called\n unless @engine_has_matched\n @engine.match\n @engine_has_matched = true\n end\n\n # return the result array\n @result_rules\n\n end",
"def rules_for(path)\n @rules.reverse.select do |rule| path.match(rule.pattern) end\n end",
"def get_rules\n rules = Array.new\n\n RULE_TYPES.each do |reg|\n ebtables_exit = `#{CONF[:ebtables]} -L FORWARD`\n\n rules << ebtables_exit.split(\"\\n\")[3..-1].collect do |l|\n line = l.strip\n m = line.match(reg)\n\n if m\n interface=m[1]\n {\n :interface => interface, \n :rule => line\n }\n else\n nil\n end\n end.compact\n end\n\n rules.flatten\nend",
"def rules\n return [] if @rules.empty?\n @rules.sort_by { |k| k['priority'] }.map { |h| h['rule_name'] }\n end",
"def chara_by_state\n return STATE_APPEARANCE_SUFFIX[@state || enter_in_walking_state]\n end",
"def rules\n @rules=get_endpoint('rule').keys\n end",
"def relevant_rules(action, subject)\n return [] unless @rules\n\n relevant = possible_relevant_rules(subject).select do |rule|\n rule.expanded_actions = expand_actions(rule.actions)\n rule.relevant? action, subject\n end\n relevant.reverse!.uniq!\n optimize_order! relevant\n relevant\n end",
"def process_rules(state)\n raise(\"No rules have been loaded into engine %s\" % self) if empty?\n\n rules_by_priority do |rule|\n state.mutable = !rule.concurrent?\n result = rule.process_state(state)\n state.mutable = true\n\n state.store_result(result) if result\n end\n\n state.results\n end",
"def rules\n @rules ||= {}\n end",
"def rules\n @rules ||= {}\n end",
"def rules\n @rules ||= {}\n end",
"def patterns\n #@rules.every.pattern\n @rules.map {|r| r.pattern }\n end",
"def get_bre_rules(opts = {})\n data, _status_code, _headers = get_bre_rules_with_http_info(opts)\n return data\n end",
"def known_rules\n @table.keys\n end",
"def to_list\n rules.map do |rule|\n object = { actions: rule.actions, subject: rule.subjects.map{ |s| s.is_a?(Symbol) ? s : s.name } }\n object[:conditions] = rule.conditions unless rule.conditions.blank?\n object[:inverted] = true unless rule.base_behavior\n object\n end\n end",
"def state_match\n states = %w(mn ak hi id mt wy ut nm tx ks \n ok nb sd nd ia ar la ms ab wi\n tn ky in oh pn wv md va nc sc\n ga de nj ct ri ma vt nh ma il\n ca co az nv fl mi ny or wa mo)\n eval states.map {|x| \"stri('#{x}')\"}.join(' | ')\n end",
"def to_a\n @rules.keys\n end",
"def rules; end",
"def rules; end",
"def rules; end",
"def rules; end",
"def rules; end",
"def rules; end",
"def rules; end",
"def get_candidates(rules)\n candidates = []\n rules.each { |rule| candidates << rule if rule.ever_matched? && rule.time_to_report? }\n candidates\n end",
"def relevant_rules(action, subject)\n rules.reverse.select do |rule|\n rule.expanded_actions = expand_actions(rule.actions)\n rule.relevant? action, subject\n end\n end",
"def list\n @driver.getRuleNames\n end",
"def rules\n @rules ||= {}\n end",
"def all\n rules = []\n\n raw.each do |type, details|\n # Add general rules\n Array(details['prefix']).each do |prefix|\n rules.push({\n prefix: prefix.to_s,\n length: details['length'],\n type: type\n })\n end\n\n # Process each country\n Array(details['countries']).each do |country, prefixes|\n # Add a rule for each prefix\n Array(prefixes).each do |prefix|\n rules.push({\n prefix: prefix.to_s,\n length: details['length'],\n type: type,\n country: country,\n })\n end\n end\n\n end\n\n # Sort by prefix length\n rules.sort { |x, y| y[:prefix].length <=> x[:prefix].length }\n end",
"def rule(regex, &action)\n states, reg_string = parse_rule(regex)\n states.each do |s|\n if s.nil?\n @open_states.each do |o|\n @state_rules[o][reg_string] = action\n end\n else\n @state_rules[s] = { reg_string => action }\n end\n end\n puts(\"Rule '#{regex}' defined\") if @verbose\n end",
"def rules\n self.class.rules\n end",
"def rules\n\t\tf = File.read(\"./rules.txt\")\n\t\tputs \"#{f}\"\n\t\tback_option = gets.chomp.to_i\n\t\trules_option(back_option)\n\tend",
"def valid_words(letters)\n center = letters[-1]\n out = []\n node = @dict.root\n queue = [node]\n next_queue = []\n until queue.empty?\n queue.each do |node|\n if node.terminal?\n word = node.full_state\n out.push(word) if word.include?(center)\n end\n letters.each do |char|\n child = node.walk(char)\n next_queue.push(child) unless child.nil?\n end\n end\n queue = next_queue\n next_queue = []\n end\n out\n end",
"def match_states(query); end",
"def characters\n Character.all.select{ |character| character.actor == self }\n end",
"def rules\n @rules ||= begin\n @rules = []\n resolve_permissions\n @rules\n end\n end",
"def consume_rules(flags = {})\n rules = []\n\n while token = @tokens.consume\n case token[:node]\n when :comment, :whitespace\n rules << token\n\n when :cdc, :cdo\n unless flags[:top_level]\n @tokens.reconsume\n rule = consume_qualified_rule\n rules << rule if rule\n end\n\n when :at_keyword\n @tokens.reconsume\n rule = consume_at_rule\n rules << rule if rule\n\n else\n @tokens.reconsume\n rule = consume_qualified_rule\n rules << rule if rule\n end\n end\n\n rules\n end",
"def k_accionsys!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 34 )\n\n\n\n type = K_ACCIONSYS\n channel = ANTLR3::DEFAULT_CHANNEL\n # - - - - label initialization - - - -\n\n\n # - - - - main rule block - - - -\n # at line 389:4: ( 'beep' | 'help' | 'exit' )\n # at line 389:4: ( 'beep' | 'help' | 'exit' )\n alt_9 = 3\n case look_9 = @input.peek( 1 )\n when 0x62 then alt_9 = 1\n when 0x68 then alt_9 = 2\n when 0x65 then alt_9 = 3\n else\n raise NoViableAlternative( \"\", 9, 0 )\n\n end\n case alt_9\n when 1\n # at line 389:5: 'beep'\n match( \"beep\" )\n\n\n when 2\n # at line 389:12: 'help'\n match( \"help\" )\n\n\n when 3\n # at line 389:19: 'exit'\n match( \"exit\" )\n\n\n end\n\n\n @state.type = type\n @state.channel = channel\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 34 )\n\n\n end",
"def characters\n Character.all.select {|character| character.actor == self }\n end",
"def get_actions_for_state(a_state)\r\n \tactions_list=Array.new\t\r\n \tself.adjacency_matrix[a_state].each do |a_transition|\r\n \t\tactions_list.push a_transition.action\t\r\n \tend # end each\r\n \t\r\n \treturn actions_list\t\r\n end",
"def find_possibilities\n (0..@field_count-1).reduce({}) do |acc, i|\n acc[i] = @rules\n .select do |rule|\n ticket_values_at(i).all? { |v| rule.valid?(v) }\n end\n .map(&:name)\n\n acc\n end\n end",
"def rule_names\n @rule_names ||= []\n end",
"def rule_names\n @rule_names ||= []\n end",
"def rules\n @rules.dup.freeze\n end",
"def rules(rule_name:, kind:)\n Rules::RuleSet.build_for(calendar: calendar, kind: kind).rules_with_name(rule_name)\n end",
"def to_rules\n Array.new.tap do |rules|\n new_rule = Rule.new(rule.chain)\n new_rule.description = \"#{rule.description} (#{self.description})\"\n new_rule.rule = rule.rule.gsub(/\\{\\{(\\w+)\\}\\}/) do\n if value = self.options[$1.to_sym]\n value\n else\n \"{{#{$1}}}\"\n end\n end\n new_rule.action = rule.action\n new_rule.conditions = rule.conditions | self.conditions\n if self.version\n new_rule.versions = [self.version]\n end\n\n if has_host_group?\n host_group = @rule.chain.table.base.host_groups[self.options[:ip]]\n host_group.hosts.each do |key, host|\n host.ips.each do |v, ip|\n hg_rule = new_rule.dup\n hg_rule.description += \" (#{host.name} via #{host_group.name})\"\n hg_rule.rule.gsub!(host_group.name.to_s, ip)\n hg_rule.versions = [v]\n rules << hg_rule\n end\n end\n else\n rules << new_rule\n end\n end\n end",
"def initialize\n @rules = [[\"r s\", \"s p\", \"p r\"], [\"s r\", \"p s\", \"r p\"], [\"r r\", \"s s\", \"p p\"]]\n @valid_moves = [\"r\", \"s\", \"p\"]\n end",
"def lex_rule start_state, regexp, action = nil\n rules << Rule.new(start_state, regexp, action)\n end",
"def terminals\n\t\treturn @production_rules.values.flatten.uniq.select { |x| /([a-z]+|\\$)/ =~ x and x != \"lambda\" }\n\tend",
"def Rules()\n puts \"┌─────────────────────────────┐\".center(CONSOLE_WIDTH)\n puts \"│ Rules │\".center(CONSOLE_WIDTH)\n puts \"└─────────────────────────────┘\".center(CONSOLE_WIDTH)\n puts \"\"\n puts \"A random five letter word has been chosen for you to decipher. This word can only\".center(CONSOLE_WIDTH)\n puts \"contain one occurence of any letter e.g alice is ok where allan is not. Each turn you will\".center(CONSOLE_WIDTH)\n puts \"guess five letters.\".center(CONSOLE_WIDTH)\n puts \"\"\n puts \"You will be told each letter was a:\".center(CONSOLE_WIDTH)\n puts \"Hit (right letter, right place)\".center(CONSOLE_WIDTH)\n puts \"Near (right letter, wrong place)\".center(CONSOLE_WIDTH)\n puts \"Miss (wrong letter, wrong place)\".center(CONSOLE_WIDTH)\n puts \"\"\n puts \"The game ends when you have run out of guesses or you uncover and correctly guess the word\".center(CONSOLE_WIDTH)\n puts \"Good luck\".center(CONSOLE_WIDTH)\n puts \"ENTER to continue\".center(CONSOLE_WIDTH)\n print \"\".center(CONSOLE_WIDTH / 2)\n STDIN.getc\n system \"clear\" or system \"cls\" # Clears the terminal screen so it doesn't look cluttered\nend",
"def state_consume(state, subject)\n term = state.next_term || \"\"\n if validate(term, subject)\n state.arg_hash.merge!({@name => term})\n state.unsatisfied_arguments.shift\n return [state]\n elsif existing_matcher = @completion_matchers[term]\n best = existing_matcher.found.max{|left, right| left.rating <=> right.rating}\n if validate(best.text, subject)\n state.arg_hash.merge!({@name => best.text})\n state.unsatisfied_arguments.shift\n return [state]\n end\n end\n return []\n end",
"def process str\n str.each_char do |char|\n # route each character to its state handler\n send(@state, char)\n end\n end",
"def letter!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 56 )\n\n type = LETTER\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 355:9: ( 'a' .. 'z' | 'A' .. 'Z' )\n if @input.peek( 1 ).between?( 0x41, 0x5a ) || @input.peek( 1 ).between?( 0x61, 0x7a )\n @input.consume\n else\n mse = MismatchedSet( nil )\n recover mse\n raise mse\n end\n\n\n\n \n @state.type = type\n @state.channel = channel\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 56 )\n\n end",
"def rules_by_name(rule_name, section_id = @one_section_id)\n rules = []\n return rules unless section_id\n\n all_rules = rules(section_id)\n return rules unless all_rules\n\n all_rules['results'].each do |rule|\n rules << rule if rule['display_name'] == rule_name\n end\n rules\n end",
"def bowl\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 40 )\n bowl_start_index = @input.index\n\n success = false # flag used for memoization\n\n begin\n # rule memoization\n if @state.backtracking > 0 and already_parsed_rule?( __method__ )\n success = true\n return \n end\n # at line 325:7: ( 'B' | 'b' ) ( 'O' | 'o' ) ( 'W' | 'w' ) ( 'L' | 'l' )\n if @input.peek( 1 ).between?( T__52, T__53 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__18, T__19 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__54, T__55 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__22, T__23 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n\n success = true\n\n rescue ANTLR3::Error::RecognitionError => re\n report_error(re)\n recover(re)\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 40 )\n memoize( __method__, bowl_start_index, success ) if @state.backtracking > 0\n\n end\n \n return \n end",
"def letter!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 40 )\n\n type = LETTER\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 139:9: ( 'a' .. 'z' | 'A' .. 'Z' )\n if @input.peek( 1 ).between?( 0x41, 0x5a ) || @input.peek( 1 ).between?( 0x61, 0x7a )\n @input.consume\n else\n mse = MismatchedSet( nil )\n recover mse\n raise mse\n end\n\n\n\n \n @state.type = type\n @state.channel = channel\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 40 )\n\n end",
"def get_relevant_rules\r\n @relevant_rules = Array.new\r\n @facts.each { |k,f| \r\n add_relevant_rules_for_fact f\r\n }\r\n sort_relevant_rules\r\n end",
"def decide string\n @current_state = @start_state\n string.each_char do |c|\n if !@alphabet.include? c then\n return false\n end\n transition = false\n @transition_rules.each do |rule|\n if rule.input_char === c && rule.current_state === @current_state then\n transition = rule\n break\n end\n end\n if !transition then \n return false\n else\n @current_state = transition.end_state\n end\n end\n\n if @accept_states.include? @current_state then\n return true\n else\n return false\n end\n end",
"def input\n lines = File.new('day12_input.txt').readlines()\n initial_state = lines[0].match('initial state:\\s*([^\\n]*)')[1]\n .chars\n .each_with_index\n .map { |x, i| [i, x] }\n rules = lines[2...lines.length].map { |item|\n item.strip.split(\" => \")\n }\n return initial_state, rules\nend",
"def chars\n return to_enum :chars unless block_given?\n while c = getc\n yield c\n end\n end",
"def available_rules\n\t\tif @rules.nil?\n\t\t\t@rules = []\n\t\t\tDir.glob(File.join(@rule_directory,\"**\",\"*.yar*\")).each do |yara_rule_file|\n\t\t\t\trule = YaraRule.new\n\t\t\t\trule.file_path = yara_rule_file.gsub(\"/\",\"\\\\\\\\\")\n\t\t\t\t@rules << rule\n\t\t\tend\n\t\tend\n\t\treturn @rules\n\tend",
"def get_modifying_rules(agent, opponent)\n modified_by = Hash.new { [[],[]] }\n track = lambda do |set, index|\n set.each_with_index do |rule, rule_i|\n rule.alternatives.each do |alt|\n alt.modifiers.each do |mod|\n arr = modified_by[mod.predicate]\n arr[index] << [rule_i, mod.type]\n modified_by[mod.predicate] = arr\n end\n end\n end\n end\n track.call(agent.actions, 0)\n track.call(opponent.rules, 1)\n return modified_by\n end",
"def generate_rules(grammar)\n rules = []\n action_index = 0\n rule_indices = grammar.rule_indices\n term_indices = grammar.terminal_indices\n\n grammar.rules.each_with_index do |rule, rule_index|\n rule.branches.each do |branch|\n row = [TYPES[:action], action_index]\n\n action_index += 1\n\n branch.steps.reverse_each do |step|\n if step.is_a?(LL::Terminal)\n row << TYPES[:terminal]\n row << term_indices[step] + 1\n\n elsif step.is_a?(LL::Rule)\n row << TYPES[:rule]\n row << rule_indices[step]\n\n elsif step.is_a?(LL::Epsilon)\n row << TYPES[:epsilon]\n row << 0\n end\n end\n\n rules << row\n end\n end\n\n return rules\n end",
"def defaultrule(&action)\n @open_states.each do |o|\n @state_rules[o][\".\\n\"] = action\n end\n end",
"def find_rules(dir)\n if File.directory?(dir)\n Dir.entries(dir).grep(/_rule.rb$/)\n else\n @logger.debug(\"The argument %s is not a directory while looking for rules\" % dir)\n []\n end\n end",
"def recommended_targets\n Character.all.select do |character|\n character.power <= (self.power + 2) && character != self\n end\n end",
"def state\n ret = self[:state] || {}\n if game.facts[:contraband] && game.facts[:contraband].include?(card_type)\n ret[:contraband] = true\n end\n return ret\n end",
"def get_cast\n get_characters.map {|char| char.actor}\n end",
"def readable\n \"Rules:\\n#{rules.collect {|r| r.readable }.join('\\n')}\\nFacts:\\n#{all_facts.collect {|f| f.readable }.join('\\n')}\"\n end",
"def when_rules\n @when_rules ||= []\n end",
"def namechar!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 45 )\n\n \n # - - - - main rule block - - - -\n # at line \n if @input.peek( 1 ).between?( 0x2d, 0x2e ) || @input.peek( 1 ).between?( 0x30, 0x3a ) || @input.peek( 1 ).between?( 0x41, 0x5a ) || @input.peek(1) == 0x5f || @input.peek( 1 ).between?( 0x61, 0x7a )\n @input.consume\n else\n mse = MismatchedSet( nil )\n recover mse\n raise mse\n end\n\n\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 45 )\n\n end",
"def rules\n \"Choose rock, paper, scissors, lizard, or spock.\"\n end",
"def cnf\n r = []\n @table.each {|inputs, output|\n return output.to_s if inputs.empty?\n next if output\n term = []\n each_input(inputs) {|name, input|\n if input\n term << \"!#{name}\"\n else\n term << name\n end\n }\n if term.length == 1\n r << term.join('|')\n else\n r << \"(#{term.join('|')})\"\n end\n }\n return \"true\" if r.empty?\n r.join(' & ')\n end",
"def rules_for(aNonTerm)\n rules.select { |a_rule| a_rule.lhs == aNonTerm }\n end",
"def starting_chars\n if self.init\n if self.init.error.kind_of? State\n :everything\n else\n self.init.keys\n end\n else\n []\n end\t\n end",
"def rules_ids\n @rules_registry.rules.map(&:id)\n end",
"def _lex_to_state_actions; end",
"def _lex_to_state_actions; end",
"def _lex_to_state_actions; end",
"def _lex_to_state_actions; end",
"def get_matching_chars(possible_word_chars, invalid_word_chars)\n matching_possible_word_chars = []\n possible_word_chars.each do |possible_char|\n if invalid_word_chars.include?(possible_char)\n matching_possible_word_chars << possible_char\n end\n end\n matching_possible_word_chars\n end"
] |
[
"0.7075871",
"0.6970317",
"0.6756823",
"0.6713443",
"0.59350425",
"0.57529193",
"0.55863184",
"0.55824673",
"0.5424139",
"0.5417562",
"0.5357804",
"0.53440744",
"0.5255588",
"0.52198327",
"0.51960623",
"0.51960623",
"0.5167096",
"0.51596755",
"0.5098893",
"0.5073545",
"0.50646293",
"0.50632644",
"0.50625926",
"0.50609",
"0.5021803",
"0.5010332",
"0.49862638",
"0.49534425",
"0.49534425",
"0.49534425",
"0.49508977",
"0.49380046",
"0.4918978",
"0.49160537",
"0.4915925",
"0.4900468",
"0.48934177",
"0.48934177",
"0.48934177",
"0.48934177",
"0.48934177",
"0.48934177",
"0.48934177",
"0.48729178",
"0.4867741",
"0.48608142",
"0.48525771",
"0.48484096",
"0.4835661",
"0.47836298",
"0.47607017",
"0.47211722",
"0.47208202",
"0.4675676",
"0.4671872",
"0.46671385",
"0.46480194",
"0.46420237",
"0.46418515",
"0.46395972",
"0.46250835",
"0.46250835",
"0.46015894",
"0.45927367",
"0.45902702",
"0.45867392",
"0.45712903",
"0.4561979",
"0.45612508",
"0.45591533",
"0.45374703",
"0.45331758",
"0.45299402",
"0.45279327",
"0.45184356",
"0.44979143",
"0.4492914",
"0.44893694",
"0.44716907",
"0.4464361",
"0.44617754",
"0.446098",
"0.44548514",
"0.44439864",
"0.44426817",
"0.44416726",
"0.4434723",
"0.44236875",
"0.44228372",
"0.44126037",
"0.4406837",
"0.44034156",
"0.4400378",
"0.43924803",
"0.43909723",
"0.4387106",
"0.4387106",
"0.4387106",
"0.4387106",
"0.43856758"
] |
0.8715351
|
0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.